ngram
listlengths 0
67.8k
|
|---|
[
"for c0 in range(args.num_colors) for c1 in range(args.num_colors)] # noqa process_args = [",
"'__main__': parser = argparse.ArgumentParser( description='Tabulate all opening sequences in Puyo Puyo.' ) parser.add_argument(",
"args.num_colors) print(\"Found\", len(canonized), \"unique sequences.\") if args.outfile: with open(args.outfile, 'w') as f: json.dump(sorted(canonized),",
"sequences.\") if args.outfile: with open(args.outfile, 'w') as f: json.dump(sorted(canonized), f) print(\"Saved result to\",",
"prefixes ] pool = Pool() subsets = pool.starmap(unique_deals, process_args) for subset in subsets:",
"import argparse import json from multiprocessing import Pool from puyotable.canonization import canonize_deals def",
"argparse.ArgumentParser( description='Tabulate all opening sequences in Puyo Puyo.' ) parser.add_argument( 'num_colors', metavar='colors', type=int,",
"c0 in range(args.num_colors) for c1 in range(args.num_colors)] # noqa process_args = [ (args.depth",
"num_colors, callback, prefix + [(c0, c1)] ) def unique_deals(num_deals, num_colors, prefix_=[]): canonized =",
"== '__main__': parser = argparse.ArgumentParser( description='Tabulate all opening sequences in Puyo Puyo.' )",
"unique_deals(args.depth, args.num_colors) print(\"Found\", len(canonized), \"unique sequences.\") if args.outfile: with open(args.outfile, 'w') as f:",
"pool.starmap(unique_deals, process_args) for subset in subsets: canonized.update(subset) else: canonized = unique_deals(args.depth, args.num_colors) print(\"Found\",",
"in range(num_colors): for c1 in range(num_colors): for deals in all_deals(num_deals - 1, num_colors):",
"for c1 in range(num_colors): for_all_deals( num_deals - 1, num_colors, callback, prefix + [(c0,",
"1, args.num_colors, prefix) for prefix in prefixes ] pool = Pool() subsets =",
"colors' ) parser.add_argument( 'depth', metavar='depth', type=int, help='How many pieces deep to tabulate' )",
"__name__ == '__main__': parser = argparse.ArgumentParser( description='Tabulate all opening sequences in Puyo Puyo.'",
"canonized = unique_deals(args.depth, args.num_colors) print(\"Found\", len(canonized), \"unique sequences.\") if args.outfile: with open(args.outfile, 'w')",
"callback, prefix + [(c0, c1)] ) def unique_deals(num_deals, num_colors, prefix_=[]): canonized = set()",
"+ prefix_ for_all_deals(num_deals - 1, num_colors, callback, prefix) return canonized if __name__ ==",
"not num_deals: callback(prefix) return for c0 in range(num_colors): for c1 in range(num_colors): for_all_deals(",
"1, num_colors, callback, prefix) prefix = [(0, 1)] + prefix_ for_all_deals(num_deals - 1,",
"prefixes = [[(c0, c1)] for c0 in range(args.num_colors) for c1 in range(args.num_colors)] #",
"range(num_colors): for deals in all_deals(num_deals - 1, num_colors): result.append(deals + [(c0, c1)]) return",
"canonize_deals def all_deals(num_deals, num_colors): if not num_deals: return [[]] result = [] for",
"- 1, num_colors, callback, prefix) return canonized if __name__ == '__main__': parser =",
"symmetry reduction prefix = [(0, 0)] + prefix_ for_all_deals(num_deals - 1, num_colors, callback,",
"range(args.num_colors) for c1 in range(args.num_colors)] # noqa process_args = [ (args.depth - 1,",
"set() def callback(deals): canonized.add(canonize_deals(deals, num_colors)) # Known symmetry reduction prefix = [(0, 0)]",
"prefix_ for_all_deals(num_deals - 1, num_colors, callback, prefix) prefix = [(0, 1)] + prefix_",
"process_args) for subset in subsets: canonized.update(subset) else: canonized = unique_deals(args.depth, args.num_colors) print(\"Found\", len(canonized),",
"Known symmetry reduction prefix = [(0, 0)] + prefix_ for_all_deals(num_deals - 1, num_colors,",
") parser.add_argument( 'num_colors', metavar='colors', type=int, help='Number of available colors' ) parser.add_argument( 'depth', metavar='depth',",
"in Puyo Puyo.' ) parser.add_argument( 'num_colors', metavar='colors', type=int, help='Number of available colors' )",
"num_deals: callback(prefix) return for c0 in range(num_colors): for c1 in range(num_colors): for_all_deals( num_deals",
"unique_deals(num_deals, num_colors, prefix_=[]): canonized = set() def callback(deals): canonized.add(canonize_deals(deals, num_colors)) # Known symmetry",
"- 1, num_colors, callback, prefix) prefix = [(0, 1)] + prefix_ for_all_deals(num_deals -",
"output' ) args = parser.parse_args() canonized = set() if args.depth > 1: prefixes",
"type=int, help='Number of available colors' ) parser.add_argument( 'depth', metavar='depth', type=int, help='How many pieces",
"for c1 in range(num_colors): for deals in all_deals(num_deals - 1, num_colors): result.append(deals +",
"subset in subsets: canonized.update(subset) else: canonized = unique_deals(args.depth, args.num_colors) print(\"Found\", len(canonized), \"unique sequences.\")",
"pieces deep to tabulate' ) parser.add_argument( '--outfile', metavar='f', type=str, help='Filename for JSON output'",
"puyotable.canonization import canonize_deals def all_deals(num_deals, num_colors): if not num_deals: return [[]] result =",
"import json from multiprocessing import Pool from puyotable.canonization import canonize_deals def all_deals(num_deals, num_colors):",
"prefix) prefix = [(0, 1)] + prefix_ for_all_deals(num_deals - 1, num_colors, callback, prefix)",
"for_all_deals(num_deals, num_colors, callback, prefix=[]): if not num_deals: callback(prefix) return for c0 in range(num_colors):",
"[ (args.depth - 1, args.num_colors, prefix) for prefix in prefixes ] pool =",
"subsets = pool.starmap(unique_deals, process_args) for subset in subsets: canonized.update(subset) else: canonized = unique_deals(args.depth,",
"in range(args.num_colors) for c1 in range(args.num_colors)] # noqa process_args = [ (args.depth -",
"'--outfile', metavar='f', type=str, help='Filename for JSON output' ) args = parser.parse_args() canonized =",
"return [[]] result = [] for c0 in range(num_colors): for c1 in range(num_colors):",
"for_all_deals( num_deals - 1, num_colors, callback, prefix + [(c0, c1)] ) def unique_deals(num_deals,",
"available colors' ) parser.add_argument( 'depth', metavar='depth', type=int, help='How many pieces deep to tabulate'",
"num_colors, callback, prefix) return canonized if __name__ == '__main__': parser = argparse.ArgumentParser( description='Tabulate",
"= Pool() subsets = pool.starmap(unique_deals, process_args) for subset in subsets: canonized.update(subset) else: canonized",
"type=int, help='How many pieces deep to tabulate' ) parser.add_argument( '--outfile', metavar='f', type=str, help='Filename",
"] pool = Pool() subsets = pool.starmap(unique_deals, process_args) for subset in subsets: canonized.update(subset)",
"result = [] for c0 in range(num_colors): for c1 in range(num_colors): for deals",
"Puyo Puyo.' ) parser.add_argument( 'num_colors', metavar='colors', type=int, help='Number of available colors' ) parser.add_argument(",
"1: prefixes = [[(c0, c1)] for c0 in range(args.num_colors) for c1 in range(args.num_colors)]",
"1, num_colors, callback, prefix + [(c0, c1)] ) def unique_deals(num_deals, num_colors, prefix_=[]): canonized",
"return result def for_all_deals(num_deals, num_colors, callback, prefix=[]): if not num_deals: callback(prefix) return for",
"> 1: prefixes = [[(c0, c1)] for c0 in range(args.num_colors) for c1 in",
"num_colors): if not num_deals: return [[]] result = [] for c0 in range(num_colors):",
"of available colors' ) parser.add_argument( 'depth', metavar='depth', type=int, help='How many pieces deep to",
"process_args = [ (args.depth - 1, args.num_colors, prefix) for prefix in prefixes ]",
"callback(prefix) return for c0 in range(num_colors): for c1 in range(num_colors): for_all_deals( num_deals -",
"[(0, 0)] + prefix_ for_all_deals(num_deals - 1, num_colors, callback, prefix) prefix = [(0,",
"print(\"Found\", len(canonized), \"unique sequences.\") if args.outfile: with open(args.outfile, 'w') as f: json.dump(sorted(canonized), f)",
"callback, prefix) return canonized if __name__ == '__main__': parser = argparse.ArgumentParser( description='Tabulate all",
"num_deals - 1, num_colors, callback, prefix + [(c0, c1)] ) def unique_deals(num_deals, num_colors,",
"in subsets: canonized.update(subset) else: canonized = unique_deals(args.depth, args.num_colors) print(\"Found\", len(canonized), \"unique sequences.\") if",
"def unique_deals(num_deals, num_colors, prefix_=[]): canonized = set() def callback(deals): canonized.add(canonize_deals(deals, num_colors)) # Known",
"- 1, num_colors, callback, prefix + [(c0, c1)] ) def unique_deals(num_deals, num_colors, prefix_=[]):",
"many pieces deep to tabulate' ) parser.add_argument( '--outfile', metavar='f', type=str, help='Filename for JSON",
") parser.add_argument( '--outfile', metavar='f', type=str, help='Filename for JSON output' ) args = parser.parse_args()",
"set() if args.depth > 1: prefixes = [[(c0, c1)] for c0 in range(args.num_colors)",
"sequences in Puyo Puyo.' ) parser.add_argument( 'num_colors', metavar='colors', type=int, help='Number of available colors'",
"for prefix in prefixes ] pool = Pool() subsets = pool.starmap(unique_deals, process_args) for",
"in prefixes ] pool = Pool() subsets = pool.starmap(unique_deals, process_args) for subset in",
"= set() def callback(deals): canonized.add(canonize_deals(deals, num_colors)) # Known symmetry reduction prefix = [(0,",
"not num_deals: return [[]] result = [] for c0 in range(num_colors): for c1",
"range(num_colors): for c1 in range(num_colors): for_all_deals( num_deals - 1, num_colors, callback, prefix +",
"range(num_colors): for c1 in range(num_colors): for deals in all_deals(num_deals - 1, num_colors): result.append(deals",
") def unique_deals(num_deals, num_colors, prefix_=[]): canonized = set() def callback(deals): canonized.add(canonize_deals(deals, num_colors)) #",
"= [ (args.depth - 1, args.num_colors, prefix) for prefix in prefixes ] pool",
"from multiprocessing import Pool from puyotable.canonization import canonize_deals def all_deals(num_deals, num_colors): if not",
"c1 in range(num_colors): for_all_deals( num_deals - 1, num_colors, callback, prefix + [(c0, c1)]",
"canonized.update(subset) else: canonized = unique_deals(args.depth, args.num_colors) print(\"Found\", len(canonized), \"unique sequences.\") if args.outfile: with",
"multiprocessing import Pool from puyotable.canonization import canonize_deals def all_deals(num_deals, num_colors): if not num_deals:",
"= [] for c0 in range(num_colors): for c1 in range(num_colors): for deals in",
"+ [(c0, c1)]) return result def for_all_deals(num_deals, num_colors, callback, prefix=[]): if not num_deals:",
"num_colors, callback, prefix) prefix = [(0, 1)] + prefix_ for_all_deals(num_deals - 1, num_colors,",
"canonized = set() if args.depth > 1: prefixes = [[(c0, c1)] for c0",
"parser = argparse.ArgumentParser( description='Tabulate all opening sequences in Puyo Puyo.' ) parser.add_argument( 'num_colors',",
"parser.add_argument( '--outfile', metavar='f', type=str, help='Filename for JSON output' ) args = parser.parse_args() canonized",
"argparse import json from multiprocessing import Pool from puyotable.canonization import canonize_deals def all_deals(num_deals,",
"prefix=[]): if not num_deals: callback(prefix) return for c0 in range(num_colors): for c1 in",
"len(canonized), \"unique sequences.\") if args.outfile: with open(args.outfile, 'w') as f: json.dump(sorted(canonized), f) print(\"Saved",
"for c1 in range(args.num_colors)] # noqa process_args = [ (args.depth - 1, args.num_colors,",
"def all_deals(num_deals, num_colors): if not num_deals: return [[]] result = [] for c0",
"for_all_deals(num_deals - 1, num_colors, callback, prefix) return canonized if __name__ == '__main__': parser",
"prefix_=[]): canonized = set() def callback(deals): canonized.add(canonize_deals(deals, num_colors)) # Known symmetry reduction prefix",
"for c0 in range(num_colors): for c1 in range(num_colors): for deals in all_deals(num_deals -",
"prefix = [(0, 1)] + prefix_ for_all_deals(num_deals - 1, num_colors, callback, prefix) return",
"if __name__ == '__main__': parser = argparse.ArgumentParser( description='Tabulate all opening sequences in Puyo",
"= [(0, 1)] + prefix_ for_all_deals(num_deals - 1, num_colors, callback, prefix) return canonized",
"import Pool from puyotable.canonization import canonize_deals def all_deals(num_deals, num_colors): if not num_deals: return",
"if not num_deals: return [[]] result = [] for c0 in range(num_colors): for",
"prefix_ for_all_deals(num_deals - 1, num_colors, callback, prefix) return canonized if __name__ == '__main__':",
"tabulate' ) parser.add_argument( '--outfile', metavar='f', type=str, help='Filename for JSON output' ) args =",
"'num_colors', metavar='colors', type=int, help='Number of available colors' ) parser.add_argument( 'depth', metavar='depth', type=int, help='How",
"parser.add_argument( 'depth', metavar='depth', type=int, help='How many pieces deep to tabulate' ) parser.add_argument( '--outfile',",
"callback(deals): canonized.add(canonize_deals(deals, num_colors)) # Known symmetry reduction prefix = [(0, 0)] + prefix_",
"range(args.num_colors)] # noqa process_args = [ (args.depth - 1, args.num_colors, prefix) for prefix",
"- 1, args.num_colors, prefix) for prefix in prefixes ] pool = Pool() subsets",
"return for c0 in range(num_colors): for c1 in range(num_colors): for_all_deals( num_deals - 1,",
"= argparse.ArgumentParser( description='Tabulate all opening sequences in Puyo Puyo.' ) parser.add_argument( 'num_colors', metavar='colors',",
"opening sequences in Puyo Puyo.' ) parser.add_argument( 'num_colors', metavar='colors', type=int, help='Number of available",
"canonized.add(canonize_deals(deals, num_colors)) # Known symmetry reduction prefix = [(0, 0)] + prefix_ for_all_deals(num_deals",
"range(num_colors): for_all_deals( num_deals - 1, num_colors, callback, prefix + [(c0, c1)] ) def",
"canonized if __name__ == '__main__': parser = argparse.ArgumentParser( description='Tabulate all opening sequences in",
"[] for c0 in range(num_colors): for c1 in range(num_colors): for deals in all_deals(num_deals",
"[(0, 1)] + prefix_ for_all_deals(num_deals - 1, num_colors, callback, prefix) return canonized if",
"0)] + prefix_ for_all_deals(num_deals - 1, num_colors, callback, prefix) prefix = [(0, 1)]",
"return canonized if __name__ == '__main__': parser = argparse.ArgumentParser( description='Tabulate all opening sequences",
"num_deals: return [[]] result = [] for c0 in range(num_colors): for c1 in",
"prefix) for prefix in prefixes ] pool = Pool() subsets = pool.starmap(unique_deals, process_args)",
"reduction prefix = [(0, 0)] + prefix_ for_all_deals(num_deals - 1, num_colors, callback, prefix)",
"callback, prefix=[]): if not num_deals: callback(prefix) return for c0 in range(num_colors): for c1",
"Pool() subsets = pool.starmap(unique_deals, process_args) for subset in subsets: canonized.update(subset) else: canonized =",
"c1 in range(num_colors): for deals in all_deals(num_deals - 1, num_colors): result.append(deals + [(c0,",
"# Known symmetry reduction prefix = [(0, 0)] + prefix_ for_all_deals(num_deals - 1,",
"[[(c0, c1)] for c0 in range(args.num_colors) for c1 in range(args.num_colors)] # noqa process_args",
"to tabulate' ) parser.add_argument( '--outfile', metavar='f', type=str, help='Filename for JSON output' ) args",
"noqa process_args = [ (args.depth - 1, args.num_colors, prefix) for prefix in prefixes",
"all_deals(num_deals - 1, num_colors): result.append(deals + [(c0, c1)]) return result def for_all_deals(num_deals, num_colors,",
"canonized = set() def callback(deals): canonized.add(canonize_deals(deals, num_colors)) # Known symmetry reduction prefix =",
"prefix) return canonized if __name__ == '__main__': parser = argparse.ArgumentParser( description='Tabulate all opening",
"json from multiprocessing import Pool from puyotable.canonization import canonize_deals def all_deals(num_deals, num_colors): if",
"if args.outfile: with open(args.outfile, 'w') as f: json.dump(sorted(canonized), f) print(\"Saved result to\", args.outfile)",
"def for_all_deals(num_deals, num_colors, callback, prefix=[]): if not num_deals: callback(prefix) return for c0 in",
"pool = Pool() subsets = pool.starmap(unique_deals, process_args) for subset in subsets: canonized.update(subset) else:",
"in range(num_colors): for deals in all_deals(num_deals - 1, num_colors): result.append(deals + [(c0, c1)])",
"c0 in range(num_colors): for c1 in range(num_colors): for_all_deals( num_deals - 1, num_colors, callback,",
"description='Tabulate all opening sequences in Puyo Puyo.' ) parser.add_argument( 'num_colors', metavar='colors', type=int, help='Number",
"c1 in range(args.num_colors)] # noqa process_args = [ (args.depth - 1, args.num_colors, prefix)",
"parser.add_argument( 'num_colors', metavar='colors', type=int, help='Number of available colors' ) parser.add_argument( 'depth', metavar='depth', type=int,",
"prefix = [(0, 0)] + prefix_ for_all_deals(num_deals - 1, num_colors, callback, prefix) prefix",
"all opening sequences in Puyo Puyo.' ) parser.add_argument( 'num_colors', metavar='colors', type=int, help='Number of",
"deals in all_deals(num_deals - 1, num_colors): result.append(deals + [(c0, c1)]) return result def",
"deep to tabulate' ) parser.add_argument( '--outfile', metavar='f', type=str, help='Filename for JSON output' )",
"args.depth > 1: prefixes = [[(c0, c1)] for c0 in range(args.num_colors) for c1",
"'depth', metavar='depth', type=int, help='How many pieces deep to tabulate' ) parser.add_argument( '--outfile', metavar='f',",
"def callback(deals): canonized.add(canonize_deals(deals, num_colors)) # Known symmetry reduction prefix = [(0, 0)] +",
"1, num_colors, callback, prefix) return canonized if __name__ == '__main__': parser = argparse.ArgumentParser(",
"args.num_colors, prefix) for prefix in prefixes ] pool = Pool() subsets = pool.starmap(unique_deals,",
"num_colors, callback, prefix=[]): if not num_deals: callback(prefix) return for c0 in range(num_colors): for",
"if args.depth > 1: prefixes = [[(c0, c1)] for c0 in range(args.num_colors) for",
"Puyo.' ) parser.add_argument( 'num_colors', metavar='colors', type=int, help='Number of available colors' ) parser.add_argument( 'depth',",
"= [(0, 0)] + prefix_ for_all_deals(num_deals - 1, num_colors, callback, prefix) prefix =",
"= parser.parse_args() canonized = set() if args.depth > 1: prefixes = [[(c0, c1)]",
"metavar='colors', type=int, help='Number of available colors' ) parser.add_argument( 'depth', metavar='depth', type=int, help='How many",
"help='Filename for JSON output' ) args = parser.parse_args() canonized = set() if args.depth",
"in range(num_colors): for_all_deals( num_deals - 1, num_colors, callback, prefix + [(c0, c1)] )",
"for c0 in range(num_colors): for c1 in range(num_colors): for_all_deals( num_deals - 1, num_colors,",
"c1)] for c0 in range(args.num_colors) for c1 in range(args.num_colors)] # noqa process_args =",
") parser.add_argument( 'depth', metavar='depth', type=int, help='How many pieces deep to tabulate' ) parser.add_argument(",
"metavar='depth', type=int, help='How many pieces deep to tabulate' ) parser.add_argument( '--outfile', metavar='f', type=str,",
"- 1, num_colors): result.append(deals + [(c0, c1)]) return result def for_all_deals(num_deals, num_colors, callback,",
"num_colors, prefix_=[]): canonized = set() def callback(deals): canonized.add(canonize_deals(deals, num_colors)) # Known symmetry reduction",
"metavar='f', type=str, help='Filename for JSON output' ) args = parser.parse_args() canonized = set()",
"in range(args.num_colors)] # noqa process_args = [ (args.depth - 1, args.num_colors, prefix) for",
"for subset in subsets: canonized.update(subset) else: canonized = unique_deals(args.depth, args.num_colors) print(\"Found\", len(canonized), \"unique",
"\"unique sequences.\") if args.outfile: with open(args.outfile, 'w') as f: json.dump(sorted(canonized), f) print(\"Saved result",
"prefix + [(c0, c1)] ) def unique_deals(num_deals, num_colors, prefix_=[]): canonized = set() def",
"help='Number of available colors' ) parser.add_argument( 'depth', metavar='depth', type=int, help='How many pieces deep",
"+ [(c0, c1)] ) def unique_deals(num_deals, num_colors, prefix_=[]): canonized = set() def callback(deals):",
"help='How many pieces deep to tabulate' ) parser.add_argument( '--outfile', metavar='f', type=str, help='Filename for",
"else: canonized = unique_deals(args.depth, args.num_colors) print(\"Found\", len(canonized), \"unique sequences.\") if args.outfile: with open(args.outfile,",
"from puyotable.canonization import canonize_deals def all_deals(num_deals, num_colors): if not num_deals: return [[]] result",
"[[]] result = [] for c0 in range(num_colors): for c1 in range(num_colors): for",
") args = parser.parse_args() canonized = set() if args.depth > 1: prefixes =",
"parser.parse_args() canonized = set() if args.depth > 1: prefixes = [[(c0, c1)] for",
"in all_deals(num_deals - 1, num_colors): result.append(deals + [(c0, c1)]) return result def for_all_deals(num_deals,",
"[(c0, c1)] ) def unique_deals(num_deals, num_colors, prefix_=[]): canonized = set() def callback(deals): canonized.add(canonize_deals(deals,",
"for JSON output' ) args = parser.parse_args() canonized = set() if args.depth >",
"= [[(c0, c1)] for c0 in range(args.num_colors) for c1 in range(args.num_colors)] # noqa",
"= pool.starmap(unique_deals, process_args) for subset in subsets: canonized.update(subset) else: canonized = unique_deals(args.depth, args.num_colors)",
"import canonize_deals def all_deals(num_deals, num_colors): if not num_deals: return [[]] result = []",
"JSON output' ) args = parser.parse_args() canonized = set() if args.depth > 1:",
"result def for_all_deals(num_deals, num_colors, callback, prefix=[]): if not num_deals: callback(prefix) return for c0",
"num_colors)) # Known symmetry reduction prefix = [(0, 0)] + prefix_ for_all_deals(num_deals -",
"= unique_deals(args.depth, args.num_colors) print(\"Found\", len(canonized), \"unique sequences.\") if args.outfile: with open(args.outfile, 'w') as",
"result.append(deals + [(c0, c1)]) return result def for_all_deals(num_deals, num_colors, callback, prefix=[]): if not",
"[(c0, c1)]) return result def for_all_deals(num_deals, num_colors, callback, prefix=[]): if not num_deals: callback(prefix)",
"if not num_deals: callback(prefix) return for c0 in range(num_colors): for c1 in range(num_colors):",
"args = parser.parse_args() canonized = set() if args.depth > 1: prefixes = [[(c0,",
"Pool from puyotable.canonization import canonize_deals def all_deals(num_deals, num_colors): if not num_deals: return [[]]",
"subsets: canonized.update(subset) else: canonized = unique_deals(args.depth, args.num_colors) print(\"Found\", len(canonized), \"unique sequences.\") if args.outfile:",
"callback, prefix) prefix = [(0, 1)] + prefix_ for_all_deals(num_deals - 1, num_colors, callback,",
"c1)]) return result def for_all_deals(num_deals, num_colors, callback, prefix=[]): if not num_deals: callback(prefix) return",
"all_deals(num_deals, num_colors): if not num_deals: return [[]] result = [] for c0 in",
"1, num_colors): result.append(deals + [(c0, c1)]) return result def for_all_deals(num_deals, num_colors, callback, prefix=[]):",
"c1)] ) def unique_deals(num_deals, num_colors, prefix_=[]): canonized = set() def callback(deals): canonized.add(canonize_deals(deals, num_colors))",
"= set() if args.depth > 1: prefixes = [[(c0, c1)] for c0 in",
"+ prefix_ for_all_deals(num_deals - 1, num_colors, callback, prefix) prefix = [(0, 1)] +",
"prefix in prefixes ] pool = Pool() subsets = pool.starmap(unique_deals, process_args) for subset",
"# noqa process_args = [ (args.depth - 1, args.num_colors, prefix) for prefix in",
"c0 in range(num_colors): for c1 in range(num_colors): for deals in all_deals(num_deals - 1,",
"in range(num_colors): for c1 in range(num_colors): for_all_deals( num_deals - 1, num_colors, callback, prefix",
"(args.depth - 1, args.num_colors, prefix) for prefix in prefixes ] pool = Pool()",
"for deals in all_deals(num_deals - 1, num_colors): result.append(deals + [(c0, c1)]) return result",
"num_colors): result.append(deals + [(c0, c1)]) return result def for_all_deals(num_deals, num_colors, callback, prefix=[]): if",
"for_all_deals(num_deals - 1, num_colors, callback, prefix) prefix = [(0, 1)] + prefix_ for_all_deals(num_deals",
"1)] + prefix_ for_all_deals(num_deals - 1, num_colors, callback, prefix) return canonized if __name__",
"type=str, help='Filename for JSON output' ) args = parser.parse_args() canonized = set() if"
] |
[
"06:17 from django.db import migrations class Migration(migrations.Migration): dependencies = [ (\"pbn_api\", \"0025_auto_20210809_0149\"), ]",
"Django 3.0.14 on 2021-08-16 06:17 from django.db import migrations class Migration(migrations.Migration): dependencies =",
"] operations = [ migrations.AlterUniqueTogether( name=\"oswiadczenieinstytucji\", unique_together=set(), ), migrations.AlterUniqueTogether( name=\"publikacjainstytucji\", unique_together=set(), ), ]",
"(\"pbn_api\", \"0025_auto_20210809_0149\"), ] operations = [ migrations.AlterUniqueTogether( name=\"oswiadczenieinstytucji\", unique_together=set(), ), migrations.AlterUniqueTogether( name=\"publikacjainstytucji\", unique_together=set(),",
"[ (\"pbn_api\", \"0025_auto_20210809_0149\"), ] operations = [ migrations.AlterUniqueTogether( name=\"oswiadczenieinstytucji\", unique_together=set(), ), migrations.AlterUniqueTogether( name=\"publikacjainstytucji\",",
"class Migration(migrations.Migration): dependencies = [ (\"pbn_api\", \"0025_auto_20210809_0149\"), ] operations = [ migrations.AlterUniqueTogether( name=\"oswiadczenieinstytucji\",",
"2021-08-16 06:17 from django.db import migrations class Migration(migrations.Migration): dependencies = [ (\"pbn_api\", \"0025_auto_20210809_0149\"),",
"# Generated by Django 3.0.14 on 2021-08-16 06:17 from django.db import migrations class",
"import migrations class Migration(migrations.Migration): dependencies = [ (\"pbn_api\", \"0025_auto_20210809_0149\"), ] operations = [",
"dependencies = [ (\"pbn_api\", \"0025_auto_20210809_0149\"), ] operations = [ migrations.AlterUniqueTogether( name=\"oswiadczenieinstytucji\", unique_together=set(), ),",
"on 2021-08-16 06:17 from django.db import migrations class Migration(migrations.Migration): dependencies = [ (\"pbn_api\",",
"by Django 3.0.14 on 2021-08-16 06:17 from django.db import migrations class Migration(migrations.Migration): dependencies",
"migrations class Migration(migrations.Migration): dependencies = [ (\"pbn_api\", \"0025_auto_20210809_0149\"), ] operations = [ migrations.AlterUniqueTogether(",
"3.0.14 on 2021-08-16 06:17 from django.db import migrations class Migration(migrations.Migration): dependencies = [",
"from django.db import migrations class Migration(migrations.Migration): dependencies = [ (\"pbn_api\", \"0025_auto_20210809_0149\"), ] operations",
"django.db import migrations class Migration(migrations.Migration): dependencies = [ (\"pbn_api\", \"0025_auto_20210809_0149\"), ] operations =",
"= [ (\"pbn_api\", \"0025_auto_20210809_0149\"), ] operations = [ migrations.AlterUniqueTogether( name=\"oswiadczenieinstytucji\", unique_together=set(), ), migrations.AlterUniqueTogether(",
"<reponame>iplweb/django-bpp<gh_stars>1-10 # Generated by Django 3.0.14 on 2021-08-16 06:17 from django.db import migrations",
"\"0025_auto_20210809_0149\"), ] operations = [ migrations.AlterUniqueTogether( name=\"oswiadczenieinstytucji\", unique_together=set(), ), migrations.AlterUniqueTogether( name=\"publikacjainstytucji\", unique_together=set(), ),",
"Migration(migrations.Migration): dependencies = [ (\"pbn_api\", \"0025_auto_20210809_0149\"), ] operations = [ migrations.AlterUniqueTogether( name=\"oswiadczenieinstytucji\", unique_together=set(),",
"Generated by Django 3.0.14 on 2021-08-16 06:17 from django.db import migrations class Migration(migrations.Migration):"
] |
[
"TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE",
"\" + self.__class__.__name__) weights = self.get_weights() printSparseVector(f, weights[1], name + '_recurrent_weights') printVector(f, weights[-1],",
"= nb_nonzero + 1 idx = np.append(idx, j) W = np.concatenate([W, A[j, i*16:(i+1)*16]])",
"neurons) f.write(struct.pack('iiii', weights[0].shape[0], weights[0].shape[1]//3, Activations[activation], reset_after)) CuDNNGRU.dump_layer = dump_gru_layer GRU.dump_layer = dump_gru_layer def",
"self.activation.__name__.upper() max_mdense_tmp = max(max_mdense_tmp, weights[0].shape[0]*weights[0].shape[2]) f.write(struct.pack('iiii', weights[0].shape[1], weights[0].shape[0], weights[0].shape[2], Activations[activation])) MDense.dump_layer = dump_mdense_layer",
"+ \" of type \" + self.__class__.__name__) Layer.dump_layer = dump_layer_ignore def dump_sparse_gru(self, f):",
"OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE",
"conditions and the following disclaimer. - Redistributions in binary form must reproduce the",
"printVector(f, vector, name, dtype='float32'): print(\"name: {}, len: {}\".format(name, len(vector))) v = np.reshape(vector, (-1))",
"A[:,N:2*N] - np.diag(np.diag(A[:,N:2*N])) A[:,2*N:] = A[:,2*N:] - np.diag(np.diag(A[:,2*N:])) printVector(f, diag, name + '_diag')",
"name + '_bias') printVector(f, np.transpose(weights[2], (1, 0)), name + '_factor') activation = self.activation.__name__.upper()",
"max_mdense_tmp name = self.name print(\"printing layer \" + name + \" of type",
"activation = self.activation.__name__.upper() max_mdense_tmp = max(max_mdense_tmp, weights[0].shape[0]*weights[0].shape[2]) f.write(struct.pack('iiii', weights[0].shape[1], weights[0].shape[0], weights[0].shape[2], Activations[activation])) MDense.dump_layer",
"np.append(idx, -1) nb_nonzero = 0 for j in range(N): if np.sum(np.abs(A[j, i*16:(i+1)*16])) >",
"len(v))) f.write(v.tobytes()) def printSparseVector(f, A, name): N = A.shape[0] W = np.zeros((0,)) diag",
"\" + self.__class__.__name__) weights = self.get_weights()[0] dump_embedding_layer_impl(name, weights, f) Embedding.dump_layer = dump_embedding_layer model,",
"-1) nb_nonzero = 0 for j in range(N): if np.sum(np.abs(A[j, i*16:(i+1)*16])) > 1e-10:",
"2, 0)), name + '_weights') printVector(f, np.transpose(weights[1], (1, 0)), name + '_bias') printVector(f,",
"this list of conditions and the following disclaimer. - Redistributions in binary form",
"+ self.__class__.__name__) weights = self.get_weights() printVector(f, weights[0], name + '_weights') printVector(f, weights[1], name",
"= model.get_layer('gru_a').get_weights()[0][3*embed_size:,:] #FIXME: dump only half the biases b = model.get_layer('gru_a').get_weights()[2] dump_dense_layer_impl('gru_a_dense_feature', W,",
"'LINEAR', bf) for i, layer in enumerate(model.layers): layer.dump_layer(bf) dump_sparse_gru(model.get_layer('gru_a'), bf) bf.write(struct.pack('III', max_rnn_neurons, max_conv_inputs,",
"+ self.__class__.__name__) Layer.dump_layer = dump_layer_ignore def dump_sparse_gru(self, f): global max_rnn_neurons name = 'sparse_'",
"= self.get_weights() printVector(f, np.transpose(weights[0], (1, 2, 0)), name + '_weights') printVector(f, np.transpose(weights[1], (1,",
"+ '_bias') activation = self.activation.__name__.upper() max_conv_inputs = max(max_conv_inputs, weights[0].shape[1]*weights[0].shape[0]) f.write(struct.pack('iiii', weights[0].shape[1], weights[0].shape[0], weights[0].shape[2],",
"Activations[activation], reset_after)) def dump_gru_layer(self, f): global max_rnn_neurons name = self.name print(\"printing layer \"",
"global max_conv_inputs name = self.name print(\"printing layer \" + name + \" of",
"= A[:,N:2*N] - np.diag(np.diag(A[:,N:2*N])) A[:,2*N:] = A[:,2*N:] - np.diag(np.diag(A[:,2*N:])) printVector(f, diag, name +",
"self.activation.__name__.upper() else: activation = 'TANH' if hasattr(self, 'reset_after') and not self.reset_after: reset_after =",
"loss='sparse_categorical_crossentropy', metrics=['sparse_categorical_accuracy']) model.load_weights(sys.argv[1]) bf = open('nnet_data.bin', 'wb') embed_size = lpcnet.embed_size E = model.get_layer('embed_sig').get_weights()[0]",
"max_conv_inputs = max(max_conv_inputs, weights[0].shape[1]*weights[0].shape[0]) f.write(struct.pack('iiii', weights[0].shape[1], weights[0].shape[0], weights[0].shape[2], Activations[activation])) Conv1D.dump_layer = dump_conv1d_layer def",
"THE FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,",
"= lpcnet.embed_size E = model.get_layer('embed_sig').get_weights()[0] W = model.get_layer('gru_a').get_weights()[0][:embed_size,:] dump_embedding_layer_impl('gru_a_embed_sig', np.dot(E, W), bf) W",
"= weights[0].shape[1]//3 max_rnn_neurons = max(max_rnn_neurons, neurons) f.write(struct.pack('iii', weights[0].shape[1]//3, Activations[activation], reset_after)) def dump_gru_layer(self, f):",
"b = model.get_layer('gru_a').get_weights()[2] dump_dense_layer_impl('gru_a_dense_feature', W, b, 'LINEAR', bf) for i, layer in enumerate(model.layers):",
"print(\"ignoring layer \" + self.name + \" of type \" + self.__class__.__name__) Layer.dump_layer",
"self.get_weights()[0] dump_embedding_layer_impl(name, weights, f) Embedding.dump_layer = dump_embedding_layer model, _, _ = lpcnet.new_lpcnet_model(rnn_units1=384, use_gpu=False)",
"np import h5py import re import tensorflow.keras.backend as K from tensorflow.keras.optimizers import Adam",
"idx = np.append(idx, j) W = np.concatenate([W, A[j, i*16:(i+1)*16]]) idx[pos] = nb_nonzero printVector(f,",
"f): global max_conv_inputs name = self.name print(\"printing layer \" + name + \"",
"'SIGMOID':1, 'TANH':2, 'RELU':3, 'SOFTMAX':4 } def printVector(f, vector, name, dtype='float32'): print(\"name: {}, len:",
"name + \" of type \" + self.__class__.__name__) weights = self.get_weights() printVector(f, weights[0],",
"import CuDNNGRU from tensorflow.keras.layers import Layer, GRU, Dense, Conv1D, Embedding from ulaw import",
"LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON",
"self.__class__.__name__) weights = self.get_weights() printSparseVector(f, weights[1], name + '_recurrent_weights') printVector(f, weights[-1], name +",
"global max_mdense_tmp name = self.name print(\"printing layer \" + name + \" of",
"conditions are met: - Redistributions of source code must retain the above copyright",
"bias, activation, f): printVector(f, weights, name + '_weights') printVector(f, bias, name + '_bias')",
"LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR",
"model.get_layer('gru_a').get_weights()[2] dump_dense_layer_impl('gru_a_dense_feature', W, b, 'LINEAR', bf) for i, layer in enumerate(model.layers): layer.dump_layer(bf) dump_sparse_gru(model.get_layer('gru_a'),",
"PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR",
"self.name + \" of type \" + self.__class__.__name__) Layer.dump_layer = dump_layer_ignore def dump_sparse_gru(self,",
"print(\"name: {}, len: {}\".format(name, len(vector))) v = np.reshape(vector, (-1)) v = v.astype(dtype) f.write(struct.pack('I',",
"'wb') embed_size = lpcnet.embed_size E = model.get_layer('embed_sig').get_weights()[0] W = model.get_layer('gru_a').get_weights()[0][:embed_size,:] dump_embedding_layer_impl('gru_a_embed_sig', np.dot(E, W),",
"+ '_bias') if hasattr(self, 'activation'): activation = self.activation.__name__.upper() else: activation = 'TANH' if",
"CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;",
"type \" + self.__class__.__name__) weights = self.get_weights() printVector(f, np.transpose(weights[0], (1, 2, 0)), name",
"\" + self.name + \" of type \" + self.__class__.__name__) Layer.dump_layer = dump_layer_ignore",
"must reproduce the above copyright notice, this list of conditions and the following",
"PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER",
"= self.get_weights() printSparseVector(f, weights[1], name + '_recurrent_weights') printVector(f, weights[-1], name + '_bias') if",
"+ '_weights') printVector(f, bias, name + '_bias') f.write(struct.pack('iii', weights.shape[0], weights.shape[1], Activations[activation])) def dump_dense_layer(self,",
"= dump_mdense_layer def dump_conv1d_layer(self, f): global max_conv_inputs name = self.name print(\"printing layer \"",
"weights, f): printVector(f, weights, name + '_weights') f.write(struct.pack('ii', weights.shape[0], weights.shape[1])) def dump_embedding_layer(self, f):",
"def dump_dense_layer(self, f): name = self.name print(\"printing layer \" + name + \"",
"print(\"printing layer \" + name + \" of type \" + self.__class__.__name__) weights",
"max_mdense_tmp = 1 Activations = { 'LINEAR':0, 'SIGMOID':1, 'TANH':2, 'RELU':3, 'SOFTMAX':4 } def",
"AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT",
"neurons) f.write(struct.pack('iii', weights[0].shape[1]//3, Activations[activation], reset_after)) def dump_gru_layer(self, f): global max_rnn_neurons name = self.name",
"of type \" + self.__class__.__name__) weights = self.get_weights() printVector(f, np.transpose(weights[0], (1, 2, 0)),",
"model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['sparse_categorical_accuracy']) model.load_weights(sys.argv[1]) bf = open('nnet_data.bin', 'wb') embed_size = lpcnet.embed_size E =",
"dump_embedding_layer(self, f): name = self.name print(\"printing layer \" + name + \" of",
"len(vector))) v = np.reshape(vector, (-1)) v = v.astype(dtype) f.write(struct.pack('I', len(v))) f.write(v.tobytes()) def printSparseVector(f,",
"diag = np.concatenate([np.diag(A[:,:N]), np.diag(A[:,N:2*N]), np.diag(A[:,2*N:])]) A[:,:N] = A[:,:N] - np.diag(np.diag(A[:,:N])) A[:,N:2*N] = A[:,N:2*N]",
"+ '_recurrent_weights') printVector(f, weights[-1], name + '_bias') if hasattr(self, 'activation'): activation = self.activation.__name__.upper()",
"PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR",
"def printSparseVector(f, A, name): N = A.shape[0] W = np.zeros((0,)) diag = np.concatenate([np.diag(A[:,:N]),",
"j) W = np.concatenate([W, A[j, i*16:(i+1)*16]]) idx[pos] = nb_nonzero printVector(f, W, name) #idx",
"= max(max_conv_inputs, weights[0].shape[1]*weights[0].shape[0]) f.write(struct.pack('iiii', weights[0].shape[1], weights[0].shape[0], weights[0].shape[2], Activations[activation])) Conv1D.dump_layer = dump_conv1d_layer def dump_embedding_layer_impl(name,",
"np.dot(E, W), bf) W = model.get_layer('gru_a').get_weights()[0][3*embed_size:,:] #FIXME: dump only half the biases b",
"_, _ = lpcnet.new_lpcnet_model(rnn_units1=384, use_gpu=False) model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['sparse_categorical_accuracy']) model.load_weights(sys.argv[1]) bf = open('nnet_data.bin', 'wb')",
"following conditions are met: - Redistributions of source code must retain the above",
"\" of type \" + self.__class__.__name__) weights = self.get_weights() printVector(f, np.transpose(weights[0], (1, 2,",
"GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER",
"from tensorflow.keras.callbacks import ModelCheckpoint from tensorflow.compat.v1.keras.layers import CuDNNGRU from tensorflow.keras.layers import Layer, GRU,",
"= 1 Activations = { 'LINEAR':0, 'SIGMOID':1, 'TANH':2, 'RELU':3, 'SOFTMAX':4 } def printVector(f,",
"= self.get_weights()[0] dump_embedding_layer_impl(name, weights, f) Embedding.dump_layer = dump_embedding_layer model, _, _ = lpcnet.new_lpcnet_model(rnn_units1=384,",
"0)), name + '_bias') printVector(f, np.transpose(weights[2], (1, 0)), name + '_factor') activation =",
"materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS",
"in source and binary forms, with or without modification, are permitted provided that",
"= max(max_mdense_tmp, weights[0].shape[0]*weights[0].shape[2]) f.write(struct.pack('iiii', weights[0].shape[1], weights[0].shape[0], weights[0].shape[2], Activations[activation])) MDense.dump_layer = dump_mdense_layer def dump_conv1d_layer(self,",
"\" of type \" + self.__class__.__name__) Layer.dump_layer = dump_layer_ignore def dump_sparse_gru(self, f): global",
"dump_dense_layer def dump_mdense_layer(self, f): global max_mdense_tmp name = self.name print(\"printing layer \" +",
"= self.activation.__name__.upper() else: activation = 'TANH' if hasattr(self, 'reset_after') and not self.reset_after: reset_after",
"= idx.shape[0] idx = np.append(idx, -1) nb_nonzero = 0 for j in range(N):",
"'RELU':3, 'SOFTMAX':4 } def printVector(f, vector, name, dtype='float32'): print(\"name: {}, len: {}\".format(name, len(vector)))",
"dump_embedding_layer_impl('gru_a_embed_sig', np.dot(E, W), bf) W = model.get_layer('gru_a').get_weights()[0][embed_size:2*embed_size,:] dump_embedding_layer_impl('gru_a_embed_pred', np.dot(E, W), bf) W =",
"= np.reshape(vector, (-1)) v = v.astype(dtype) f.write(struct.pack('I', len(v))) f.write(v.tobytes()) def printSparseVector(f, A, name):",
"self.__class__.__name__) weights = self.get_weights()[0] dump_embedding_layer_impl(name, weights, f) Embedding.dump_layer = dump_embedding_layer model, _, _",
"bf) for i, layer in enumerate(model.layers): layer.dump_layer(bf) dump_sparse_gru(model.get_layer('gru_a'), bf) bf.write(struct.pack('III', max_rnn_neurons, max_conv_inputs, max_mdense_tmp))",
"the above copyright notice, this list of conditions and the following disclaimer in",
"ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED",
"A[:,N:2*N] = A[:,N:2*N] - np.diag(np.diag(A[:,N:2*N])) A[:,2*N:] = A[:,2*N:] - np.diag(np.diag(A[:,2*N:])) printVector(f, diag, name",
"bias, name + '_bias') f.write(struct.pack('iii', weights.shape[0], weights.shape[1], Activations[activation])) def dump_dense_layer(self, f): name =",
"f.write(struct.pack('iiii', weights[0].shape[1], weights[0].shape[0], weights[0].shape[2], Activations[activation])) MDense.dump_layer = dump_mdense_layer def dump_conv1d_layer(self, f): global max_conv_inputs",
"dump_conv1d_layer def dump_embedding_layer_impl(name, weights, f): printVector(f, weights, name + '_weights') f.write(struct.pack('ii', weights.shape[0], weights.shape[1]))",
"the biases b = model.get_layer('gru_a').get_weights()[2] dump_dense_layer_impl('gru_a_dense_feature', W, b, 'LINEAR', bf) for i, layer",
"CuDNNGRU from tensorflow.keras.layers import Layer, GRU, Dense, Conv1D, Embedding from ulaw import ulaw2lin,",
"printSparseVector(f, A, name): N = A.shape[0] W = np.zeros((0,)) diag = np.concatenate([np.diag(A[:,:N]), np.diag(A[:,N:2*N]),",
"self.__class__.__name__) weights = self.get_weights() printVector(f, np.transpose(weights[0], (1, 2, 0)), name + '_weights') printVector(f,",
"name + '_bias') f.write(struct.pack('iii', weights.shape[0], weights.shape[1], Activations[activation])) def dump_dense_layer(self, f): name = self.name",
"import ulaw2lin, lin2ulaw from mdense import MDense max_rnn_neurons = 1 max_conv_inputs = 1",
"def dump_embedding_layer(self, f): name = self.name print(\"printing layer \" + name + \"",
"print(\"printing layer \" + name + \" of type sparse \" + self.__class__.__name__)",
"HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,",
"max_rnn_neurons = 1 max_conv_inputs = 1 max_mdense_tmp = 1 Activations = { 'LINEAR':0,",
"and the following disclaimer in the documentation and/or other materials provided with the",
"printVector(f, np.transpose(weights[0], (1, 2, 0)), name + '_weights') printVector(f, np.transpose(weights[1], (1, 0)), name",
"= 1 neurons = weights[0].shape[1]//3 max_rnn_neurons = max(max_rnn_neurons, neurons) f.write(struct.pack('iiii', weights[0].shape[0], weights[0].shape[1]//3, Activations[activation],",
"import struct import numpy as np import h5py import re import tensorflow.keras.backend as",
"in range(N): if np.sum(np.abs(A[j, i*16:(i+1)*16])) > 1e-10: nb_nonzero = nb_nonzero + 1 idx",
"the following disclaimer in the documentation and/or other materials provided with the distribution.",
"notice, this list of conditions and the following disclaimer in the documentation and/or",
"dump_gru_layer GRU.dump_layer = dump_gru_layer def dump_dense_layer_impl(name, weights, bias, activation, f): printVector(f, weights, name",
"'TANH':2, 'RELU':3, 'SOFTMAX':4 } def printVector(f, vector, name, dtype='float32'): print(\"name: {}, len: {}\".format(name,",
"{}\".format(name, len(vector))) v = np.reshape(vector, (-1)) v = v.astype(dtype) f.write(struct.pack('I', len(v))) f.write(v.tobytes()) def",
"Redistributions of source code must retain the above copyright notice, this list of",
"with or without modification, are permitted provided that the following conditions are met:",
"= { 'LINEAR':0, 'SIGMOID':1, 'TANH':2, 'RELU':3, 'SOFTMAX':4 } def printVector(f, vector, name, dtype='float32'):",
"'_weights') printVector(f, bias, name + '_bias') f.write(struct.pack('iii', weights.shape[0], weights.shape[1], Activations[activation])) def dump_dense_layer(self, f):",
"+ name + \" of type \" + self.__class__.__name__) weights = self.get_weights() activation",
"metrics=['sparse_categorical_accuracy']) model.load_weights(sys.argv[1]) bf = open('nnet_data.bin', 'wb') embed_size = lpcnet.embed_size E = model.get_layer('embed_sig').get_weights()[0] W",
"re import tensorflow.keras.backend as K from tensorflow.keras.optimizers import Adam from tensorflow.keras.callbacks import ModelCheckpoint",
"are permitted provided that the following conditions are met: - Redistributions of source",
"= np.concatenate([W, A[j, i*16:(i+1)*16]]) idx[pos] = nb_nonzero printVector(f, W, name) #idx = np.tile(np.concatenate([np.array([N]),",
"dump_embedding_layer model, _, _ = lpcnet.new_lpcnet_model(rnn_units1=384, use_gpu=False) model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['sparse_categorical_accuracy']) model.load_weights(sys.argv[1]) bf =",
"following disclaimer in the documentation and/or other materials provided with the distribution. THIS",
"1 max_mdense_tmp = 1 Activations = { 'LINEAR':0, 'SIGMOID':1, 'TANH':2, 'RELU':3, 'SOFTMAX':4 }",
"dtype='float32'): print(\"name: {}, len: {}\".format(name, len(vector))) v = np.reshape(vector, (-1)) v = v.astype(dtype)",
"reproduce the above copyright notice, this list of conditions and the following disclaimer",
"f.write(struct.pack('I', len(v))) f.write(v.tobytes()) def printSparseVector(f, A, name): N = A.shape[0] W = np.zeros((0,))",
"self.reset_after: reset_after = 0 else: reset_after = 1 neurons = weights[0].shape[1]//3 max_rnn_neurons =",
"W = model.get_layer('gru_a').get_weights()[0][embed_size:2*embed_size,:] dump_embedding_layer_impl('gru_a_embed_pred', np.dot(E, W), bf) W = model.get_layer('gru_a').get_weights()[0][2*embed_size:3*embed_size,:] dump_embedding_layer_impl('gru_a_embed_exc', np.dot(E, W),",
"EVENT SHALL THE FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,",
"BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,",
"max_rnn_neurons name = self.name print(\"printing layer \" + name + \" of type",
"def dump_mdense_layer(self, f): global max_mdense_tmp name = self.name print(\"printing layer \" + name",
"Redistribution and use in source and binary forms, with or without modification, are",
"the following conditions are met: - Redistributions of source code must retain the",
"weights[0].shape[1]//3, Activations[activation], reset_after)) CuDNNGRU.dump_layer = dump_gru_layer GRU.dump_layer = dump_gru_layer def dump_dense_layer_impl(name, weights, bias,",
"PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS BE LIABLE",
"model.get_layer('embed_sig').get_weights()[0] W = model.get_layer('gru_a').get_weights()[0][:embed_size,:] dump_embedding_layer_impl('gru_a_embed_sig', np.dot(E, W), bf) W = model.get_layer('gru_a').get_weights()[0][embed_size:2*embed_size,:] dump_embedding_layer_impl('gru_a_embed_pred', np.dot(E,",
"np.diag(np.diag(A[:,N:2*N])) A[:,2*N:] = A[:,2*N:] - np.diag(np.diag(A[:,2*N:])) printVector(f, diag, name + '_diag') idx =",
"else: activation = 'TANH' if hasattr(self, 'reset_after') and not self.reset_after: reset_after = 0",
"printVector(f, np.transpose(weights[2], (1, 0)), name + '_factor') activation = self.activation.__name__.upper() max_mdense_tmp = max(max_mdense_tmp,",
"= 'TANH' if hasattr(self, 'reset_after') and not self.reset_after: reset_after = 0 else: reset_after",
"USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY",
"FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT",
"binary forms, with or without modification, are permitted provided that the following conditions",
"len: {}\".format(name, len(vector))) v = np.reshape(vector, (-1)) v = v.astype(dtype) f.write(struct.pack('I', len(v))) f.write(v.tobytes())",
"TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;",
"OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS",
"weights[-1], name + '_bias') activation = self.activation.__name__.upper() max_conv_inputs = max(max_conv_inputs, weights[0].shape[1]*weights[0].shape[0]) f.write(struct.pack('iiii', weights[0].shape[1],",
"LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING",
"np.sum(np.abs(A[j, i*16:(i+1)*16])) > 1e-10: nb_nonzero = nb_nonzero + 1 idx = np.append(idx, j)",
"use_gpu=False) model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['sparse_categorical_accuracy']) model.load_weights(sys.argv[1]) bf = open('nnet_data.bin', 'wb') embed_size = lpcnet.embed_size E",
"np.concatenate([np.diag(A[:,:N]), np.diag(A[:,N:2*N]), np.diag(A[:,2*N:])]) A[:,:N] = A[:,:N] - np.diag(np.diag(A[:,:N])) A[:,N:2*N] = A[:,N:2*N] - np.diag(np.diag(A[:,N:2*N]))",
"name = 'sparse_' + self.name print(\"printing layer \" + name + \" of",
"FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR",
"+ name + \" of type sparse \" + self.__class__.__name__) weights = self.get_weights()",
"tensorflow.keras.callbacks import ModelCheckpoint from tensorflow.compat.v1.keras.layers import CuDNNGRU from tensorflow.keras.layers import Layer, GRU, Dense,",
"activation = self.activation.__name__.upper() else: activation = 'TANH' if hasattr(self, 'reset_after') and not self.reset_after:",
"- np.diag(np.diag(A[:,2*N:])) printVector(f, diag, name + '_diag') idx = np.zeros((0,), dtype='int') for i",
"(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF",
"nb_nonzero + 1 idx = np.append(idx, j) W = np.concatenate([W, A[j, i*16:(i+1)*16]]) idx[pos]",
"FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR",
"reset_after)) CuDNNGRU.dump_layer = dump_gru_layer GRU.dump_layer = dump_gru_layer def dump_dense_layer_impl(name, weights, bias, activation, f):",
"'LINEAR':0, 'SIGMOID':1, 'TANH':2, 'RELU':3, 'SOFTMAX':4 } def printVector(f, vector, name, dtype='float32'): print(\"name: {},",
"IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND",
"range(N): if np.sum(np.abs(A[j, i*16:(i+1)*16])) > 1e-10: nb_nonzero = nb_nonzero + 1 idx =",
"A.shape[0] W = np.zeros((0,)) diag = np.concatenate([np.diag(A[:,:N]), np.diag(A[:,N:2*N]), np.diag(A[:,2*N:])]) A[:,:N] = A[:,:N] -",
"ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES",
"printVector(f, weights[1], name + '_recurrent_weights') printVector(f, weights[-1], name + '_bias') if hasattr(self, 'activation'):",
"np.transpose(weights[1], (1, 0)), name + '_bias') printVector(f, np.transpose(weights[2], (1, 0)), name + '_factor')",
"<gh_stars>0 #!/usr/bin/python3 '''Copyright (c) 2017-2018 Mozilla Redistribution and use in source and binary",
"'_bias') printVector(f, np.transpose(weights[2], (1, 0)), name + '_factor') activation = self.activation.__name__.upper() max_mdense_tmp =",
"idx, name + '_idx', dtype='int') def dump_layer_ignore(self, f): print(\"ignoring layer \" + self.name",
"hasattr(self, 'reset_after') and not self.reset_after: reset_after = 0 else: reset_after = 1 neurons",
"THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ''' import",
"list of conditions and the following disclaimer. - Redistributions in binary form must",
"THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' AND",
"1 max_conv_inputs = 1 max_mdense_tmp = 1 Activations = { 'LINEAR':0, 'SIGMOID':1, 'TANH':2,",
"= open('nnet_data.bin', 'wb') embed_size = lpcnet.embed_size E = model.get_layer('embed_sig').get_weights()[0] W = model.get_layer('gru_a').get_weights()[0][:embed_size,:] dump_embedding_layer_impl('gru_a_embed_sig',",
"conditions and the following disclaimer in the documentation and/or other materials provided with",
"Layer, GRU, Dense, Conv1D, Embedding from ulaw import ulaw2lin, lin2ulaw from mdense import",
"global max_rnn_neurons name = 'sparse_' + self.name print(\"printing layer \" + name +",
"for i, layer in enumerate(model.layers): layer.dump_layer(bf) dump_sparse_gru(model.get_layer('gru_a'), bf) bf.write(struct.pack('III', max_rnn_neurons, max_conv_inputs, max_mdense_tmp)) bf.close()",
"= self.get_weights() printVector(f, weights[0], name + '_weights') printVector(f, weights[-1], name + '_bias') activation",
"'_bias') activation = self.activation.__name__.upper() max_conv_inputs = max(max_conv_inputs, weights[0].shape[1]*weights[0].shape[0]) f.write(struct.pack('iiii', weights[0].shape[1], weights[0].shape[0], weights[0].shape[2], Activations[activation]))",
"LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT",
"ulaw2lin, lin2ulaw from mdense import MDense max_rnn_neurons = 1 max_conv_inputs = 1 max_mdense_tmp",
"weights[1], activation, f) Dense.dump_layer = dump_dense_layer def dump_mdense_layer(self, f): global max_mdense_tmp name =",
"\" + self.__class__.__name__) weights = self.get_weights() printVector(f, np.transpose(weights[0], (1, 2, 0)), name +",
"of conditions and the following disclaimer. - Redistributions in binary form must reproduce",
"list of conditions and the following disclaimer in the documentation and/or other materials",
"'activation'): activation = self.activation.__name__.upper() else: activation = 'TANH' if hasattr(self, 'reset_after') and not",
"CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED",
"OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN",
"dump_embedding_layer_impl(name, weights, f) Embedding.dump_layer = dump_embedding_layer model, _, _ = lpcnet.new_lpcnet_model(rnn_units1=384, use_gpu=False) model.compile(optimizer='adam',",
"model.get_layer('gru_a').get_weights()[0][:embed_size,:] dump_embedding_layer_impl('gru_a_embed_sig', np.dot(E, W), bf) W = model.get_layer('gru_a').get_weights()[0][embed_size:2*embed_size,:] dump_embedding_layer_impl('gru_a_embed_pred', np.dot(E, W), bf) W",
"import ModelCheckpoint from tensorflow.compat.v1.keras.layers import CuDNNGRU from tensorflow.keras.layers import Layer, GRU, Dense, Conv1D,",
"name): N = A.shape[0] W = np.zeros((0,)) diag = np.concatenate([np.diag(A[:,:N]), np.diag(A[:,N:2*N]), np.diag(A[:,2*N:])]) A[:,:N]",
"f): global max_rnn_neurons name = 'sparse_' + self.name print(\"printing layer \" + name",
"max_rnn_neurons = max(max_rnn_neurons, neurons) f.write(struct.pack('iiii', weights[0].shape[0], weights[0].shape[1]//3, Activations[activation], reset_after)) CuDNNGRU.dump_layer = dump_gru_layer GRU.dump_layer",
"type \" + self.__class__.__name__) weights = self.get_weights()[0] dump_embedding_layer_impl(name, weights, f) Embedding.dump_layer = dump_embedding_layer",
"of type \" + self.__class__.__name__) weights = self.get_weights()[0] dump_embedding_layer_impl(name, weights, f) Embedding.dump_layer =",
"+ '_factor') activation = self.activation.__name__.upper() max_mdense_tmp = max(max_mdense_tmp, weights[0].shape[0]*weights[0].shape[2]) f.write(struct.pack('iiii', weights[0].shape[1], weights[0].shape[0], weights[0].shape[2],",
"weights[0].shape[1]//3 max_rnn_neurons = max(max_rnn_neurons, neurons) f.write(struct.pack('iiii', weights[0].shape[0], weights[0].shape[1]//3, Activations[activation], reset_after)) CuDNNGRU.dump_layer = dump_gru_layer",
"IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE",
"OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,",
"tensorflow.compat.v1.keras.layers import CuDNNGRU from tensorflow.keras.layers import Layer, GRU, Dense, Conv1D, Embedding from ulaw",
"weights.shape[0], weights.shape[1])) def dump_embedding_layer(self, f): name = self.name print(\"printing layer \" + name",
"THE POSSIBILITY OF SUCH DAMAGE. ''' import lpcnet import sys import struct import",
"max(max_conv_inputs, weights[0].shape[1]*weights[0].shape[0]) f.write(struct.pack('iiii', weights[0].shape[1], weights[0].shape[0], weights[0].shape[2], Activations[activation])) Conv1D.dump_layer = dump_conv1d_layer def dump_embedding_layer_impl(name, weights,",
"import tensorflow.keras.backend as K from tensorflow.keras.optimizers import Adam from tensorflow.keras.callbacks import ModelCheckpoint from",
"printSparseVector(f, weights[1], name + '_recurrent_weights') printVector(f, weights[-1], name + '_bias') if hasattr(self, 'activation'):",
"neurons = weights[0].shape[1]//3 max_rnn_neurons = max(max_rnn_neurons, neurons) f.write(struct.pack('iii', weights[0].shape[1]//3, Activations[activation], reset_after)) def dump_gru_layer(self,",
"Conv1D.dump_layer = dump_conv1d_layer def dump_embedding_layer_impl(name, weights, f): printVector(f, weights, name + '_weights') f.write(struct.pack('ii',",
"of type \" + self.__class__.__name__) weights = self.get_weights() printVector(f, weights[0], name + '_weights')",
"from ulaw import ulaw2lin, lin2ulaw from mdense import MDense max_rnn_neurons = 1 max_conv_inputs",
"np.diag(A[:,N:2*N]), np.diag(A[:,2*N:])]) A[:,:N] = A[:,:N] - np.diag(np.diag(A[:,:N])) A[:,N:2*N] = A[:,N:2*N] - np.diag(np.diag(A[:,N:2*N])) A[:,2*N:]",
"model.load_weights(sys.argv[1]) bf = open('nnet_data.bin', 'wb') embed_size = lpcnet.embed_size E = model.get_layer('embed_sig').get_weights()[0] W =",
"nb_nonzero printVector(f, W, name) #idx = np.tile(np.concatenate([np.array([N]), np.arange(N)]), 3*N//16) printVector(f, idx, name +",
"np.reshape(vector, (-1)) v = v.astype(dtype) f.write(struct.pack('I', len(v))) f.write(v.tobytes()) def printSparseVector(f, A, name): N",
"lpcnet.new_lpcnet_model(rnn_units1=384, use_gpu=False) model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['sparse_categorical_accuracy']) model.load_weights(sys.argv[1]) bf = open('nnet_data.bin', 'wb') embed_size = lpcnet.embed_size",
"tensorflow.keras.backend as K from tensorflow.keras.optimizers import Adam from tensorflow.keras.callbacks import ModelCheckpoint from tensorflow.compat.v1.keras.layers",
"W = model.get_layer('gru_a').get_weights()[0][2*embed_size:3*embed_size,:] dump_embedding_layer_impl('gru_a_embed_exc', np.dot(E, W), bf) W = model.get_layer('gru_a').get_weights()[0][3*embed_size:,:] #FIXME: dump only",
"sparse \" + self.__class__.__name__) weights = self.get_weights() printSparseVector(f, weights[1], name + '_recurrent_weights') printVector(f,",
"EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF",
"\" of type \" + self.__class__.__name__) weights = self.get_weights()[0] dump_embedding_layer_impl(name, weights, f) Embedding.dump_layer",
"{}, len: {}\".format(name, len(vector))) v = np.reshape(vector, (-1)) v = v.astype(dtype) f.write(struct.pack('I', len(v)))",
"name, dtype='float32'): print(\"name: {}, len: {}\".format(name, len(vector))) v = np.reshape(vector, (-1)) v =",
"np.diag(np.diag(A[:,2*N:])) printVector(f, diag, name + '_diag') idx = np.zeros((0,), dtype='int') for i in",
"'_diag') idx = np.zeros((0,), dtype='int') for i in range(3*N//16): pos = idx.shape[0] idx",
"1 neurons = weights[0].shape[1]//3 max_rnn_neurons = max(max_rnn_neurons, neurons) f.write(struct.pack('iii', weights[0].shape[1]//3, Activations[activation], reset_after)) def",
"self.name print(\"printing layer \" + name + \" of type \" + self.__class__.__name__)",
"idx.shape[0] idx = np.append(idx, -1) nb_nonzero = 0 for j in range(N): if",
"= nb_nonzero printVector(f, W, name) #idx = np.tile(np.concatenate([np.array([N]), np.arange(N)]), 3*N//16) printVector(f, idx, name",
"np.transpose(weights[2], (1, 0)), name + '_factor') activation = self.activation.__name__.upper() max_mdense_tmp = max(max_mdense_tmp, weights[0].shape[0]*weights[0].shape[2])",
"weights = self.get_weights() printVector(f, weights[0], name + '_weights') printVector(f, weights[-1], name + '_bias')",
"OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY",
"THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH",
"weights.shape[1], Activations[activation])) def dump_dense_layer(self, f): name = self.name print(\"printing layer \" + name",
"idx[pos] = nb_nonzero printVector(f, W, name) #idx = np.tile(np.concatenate([np.array([N]), np.arange(N)]), 3*N//16) printVector(f, idx,",
"type \" + self.__class__.__name__) weights = self.get_weights() activation = self.activation.__name__.upper() dump_dense_layer_impl(name, weights[0], weights[1],",
"else: reset_after = 1 neurons = weights[0].shape[1]//3 max_rnn_neurons = max(max_rnn_neurons, neurons) f.write(struct.pack('iii', weights[0].shape[1]//3,",
"OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY",
"INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT",
"i*16:(i+1)*16]]) idx[pos] = nb_nonzero printVector(f, W, name) #idx = np.tile(np.concatenate([np.array([N]), np.arange(N)]), 3*N//16) printVector(f,",
"the following disclaimer. - Redistributions in binary form must reproduce the above copyright",
"SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE",
"f): printVector(f, weights, name + '_weights') f.write(struct.pack('ii', weights.shape[0], weights.shape[1])) def dump_embedding_layer(self, f): name",
"- np.diag(np.diag(A[:,:N])) A[:,N:2*N] = A[:,N:2*N] - np.diag(np.diag(A[:,N:2*N])) A[:,2*N:] = A[:,2*N:] - np.diag(np.diag(A[:,2*N:])) printVector(f,",
"'_factor') activation = self.activation.__name__.upper() max_mdense_tmp = max(max_mdense_tmp, weights[0].shape[0]*weights[0].shape[2]) f.write(struct.pack('iiii', weights[0].shape[1], weights[0].shape[0], weights[0].shape[2], Activations[activation]))",
"(c) 2017-2018 Mozilla Redistribution and use in source and binary forms, with or",
"above copyright notice, this list of conditions and the following disclaimer. - Redistributions",
"the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED",
"'SOFTMAX':4 } def printVector(f, vector, name, dtype='float32'): print(\"name: {}, len: {}\".format(name, len(vector))) v",
"documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY",
"weights = self.get_weights() printVector(f, weights[0], name + '_weights') printVector(f, weights[1], name + '_recurrent_weights')",
"name + '_idx', dtype='int') def dump_layer_ignore(self, f): print(\"ignoring layer \" + self.name +",
"def dump_gru_layer(self, f): global max_rnn_neurons name = self.name print(\"printing layer \" + name",
"printVector(f, weights[0], name + '_weights') printVector(f, weights[-1], name + '_bias') activation = self.activation.__name__.upper()",
"+ name + \" of type \" + self.__class__.__name__) weights = self.get_weights() printVector(f,",
"SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' AND ANY",
"NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR",
"must retain the above copyright notice, this list of conditions and the following",
"dump_mdense_layer(self, f): global max_mdense_tmp name = self.name print(\"printing layer \" + name +",
"STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT",
"open('nnet_data.bin', 'wb') embed_size = lpcnet.embed_size E = model.get_layer('embed_sig').get_weights()[0] W = model.get_layer('gru_a').get_weights()[0][:embed_size,:] dump_embedding_layer_impl('gru_a_embed_sig', np.dot(E,",
"weights[1], name + '_recurrent_weights') printVector(f, weights[-1], name + '_bias') if hasattr(self, 'activation'): activation",
"ModelCheckpoint from tensorflow.compat.v1.keras.layers import CuDNNGRU from tensorflow.keras.layers import Layer, GRU, Dense, Conv1D, Embedding",
"np.diag(A[:,2*N:])]) A[:,:N] = A[:,:N] - np.diag(np.diag(A[:,:N])) A[:,N:2*N] = A[:,N:2*N] - np.diag(np.diag(A[:,N:2*N])) A[:,2*N:] =",
"= dump_gru_layer def dump_dense_layer_impl(name, weights, bias, activation, f): printVector(f, weights, name + '_weights')",
"``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,",
"printVector(f, bias, name + '_bias') f.write(struct.pack('iii', weights.shape[0], weights.shape[1], Activations[activation])) def dump_dense_layer(self, f): name",
"name = self.name print(\"printing layer \" + name + \" of type \"",
"PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS BE",
"= dump_layer_ignore def dump_sparse_gru(self, f): global max_rnn_neurons name = 'sparse_' + self.name print(\"printing",
"weights[0].shape[2], Activations[activation])) Conv1D.dump_layer = dump_conv1d_layer def dump_embedding_layer_impl(name, weights, f): printVector(f, weights, name +",
"name + '_factor') activation = self.activation.__name__.upper() max_mdense_tmp = max(max_mdense_tmp, weights[0].shape[0]*weights[0].shape[2]) f.write(struct.pack('iiii', weights[0].shape[1], weights[0].shape[0],",
"forms, with or without modification, are permitted provided that the following conditions are",
"weights[0].shape[1], weights[0].shape[0], weights[0].shape[2], Activations[activation])) MDense.dump_layer = dump_mdense_layer def dump_conv1d_layer(self, f): global max_conv_inputs name",
"copyright notice, this list of conditions and the following disclaimer. - Redistributions in",
"np.zeros((0,)) diag = np.concatenate([np.diag(A[:,:N]), np.diag(A[:,N:2*N]), np.diag(A[:,2*N:])]) A[:,:N] = A[:,:N] - np.diag(np.diag(A[:,:N])) A[:,N:2*N] =",
"dump_embedding_layer_impl('gru_a_embed_exc', np.dot(E, W), bf) W = model.get_layer('gru_a').get_weights()[0][3*embed_size:,:] #FIXME: dump only half the biases",
"h5py import re import tensorflow.keras.backend as K from tensorflow.keras.optimizers import Adam from tensorflow.keras.callbacks",
"'_bias') f.write(struct.pack('iii', weights.shape[0], weights.shape[1], Activations[activation])) def dump_dense_layer(self, f): name = self.name print(\"printing layer",
"A[:,2*N:] = A[:,2*N:] - np.diag(np.diag(A[:,2*N:])) printVector(f, diag, name + '_diag') idx = np.zeros((0,),",
"= self.activation.__name__.upper() max_conv_inputs = max(max_conv_inputs, weights[0].shape[1]*weights[0].shape[0]) f.write(struct.pack('iiii', weights[0].shape[1], weights[0].shape[0], weights[0].shape[2], Activations[activation])) Conv1D.dump_layer =",
"W), bf) W = model.get_layer('gru_a').get_weights()[0][2*embed_size:3*embed_size,:] dump_embedding_layer_impl('gru_a_embed_exc', np.dot(E, W), bf) W = model.get_layer('gru_a').get_weights()[0][3*embed_size:,:] #FIXME:",
"if np.sum(np.abs(A[j, i*16:(i+1)*16])) > 1e-10: nb_nonzero = nb_nonzero + 1 idx = np.append(idx,",
"activation = self.activation.__name__.upper() dump_dense_layer_impl(name, weights[0], weights[1], activation, f) Dense.dump_layer = dump_dense_layer def dump_mdense_layer(self,",
"f.write(struct.pack('ii', weights.shape[0], weights.shape[1])) def dump_embedding_layer(self, f): name = self.name print(\"printing layer \" +",
"name + '_bias') activation = self.activation.__name__.upper() max_conv_inputs = max(max_conv_inputs, weights[0].shape[1]*weights[0].shape[0]) f.write(struct.pack('iiii', weights[0].shape[1], weights[0].shape[0],",
"np.concatenate([W, A[j, i*16:(i+1)*16]]) idx[pos] = nb_nonzero printVector(f, W, name) #idx = np.tile(np.concatenate([np.array([N]), np.arange(N)]),",
"+ self.__class__.__name__) weights = self.get_weights() printSparseVector(f, weights[1], name + '_recurrent_weights') printVector(f, weights[-1], name",
"{ 'LINEAR':0, 'SIGMOID':1, 'TANH':2, 'RELU':3, 'SOFTMAX':4 } def printVector(f, vector, name, dtype='float32'): print(\"name:",
"def dump_layer_ignore(self, f): print(\"ignoring layer \" + self.name + \" of type \"",
"name + '_recurrent_weights') printVector(f, weights[-1], name + '_bias') if hasattr(self, 'activation'): activation =",
"weights, bias, activation, f): printVector(f, weights, name + '_weights') printVector(f, bias, name +",
"weights.shape[0], weights.shape[1], Activations[activation])) def dump_dense_layer(self, f): name = self.name print(\"printing layer \" +",
"GRU.dump_layer = dump_gru_layer def dump_dense_layer_impl(name, weights, bias, activation, f): printVector(f, weights, name +",
"= self.get_weights() activation = self.activation.__name__.upper() dump_dense_layer_impl(name, weights[0], weights[1], activation, f) Dense.dump_layer = dump_dense_layer",
"import sys import struct import numpy as np import h5py import re import",
"dump_mdense_layer def dump_conv1d_layer(self, f): global max_conv_inputs name = self.name print(\"printing layer \" +",
"1 neurons = weights[0].shape[1]//3 max_rnn_neurons = max(max_rnn_neurons, neurons) f.write(struct.pack('iiii', weights[0].shape[0], weights[0].shape[1]//3, Activations[activation], reset_after))",
"layer \" + self.name + \" of type \" + self.__class__.__name__) Layer.dump_layer =",
"THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.",
"MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL",
"name + \" of type \" + self.__class__.__name__) weights = self.get_weights()[0] dump_embedding_layer_impl(name, weights,",
"IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS",
"'_idx', dtype='int') def dump_layer_ignore(self, f): print(\"ignoring layer \" + self.name + \" of",
"1 idx = np.append(idx, j) W = np.concatenate([W, A[j, i*16:(i+1)*16]]) idx[pos] = nb_nonzero",
"weights[0].shape[1], weights[0].shape[0], weights[0].shape[2], Activations[activation])) Conv1D.dump_layer = dump_conv1d_layer def dump_embedding_layer_impl(name, weights, f): printVector(f, weights,",
"(1, 0)), name + '_bias') printVector(f, np.transpose(weights[2], (1, 0)), name + '_factor') activation",
"bf) W = model.get_layer('gru_a').get_weights()[0][embed_size:2*embed_size,:] dump_embedding_layer_impl('gru_a_embed_pred', np.dot(E, W), bf) W = model.get_layer('gru_a').get_weights()[0][2*embed_size:3*embed_size,:] dump_embedding_layer_impl('gru_a_embed_exc', np.dot(E,",
"of source code must retain the above copyright notice, this list of conditions",
"INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF",
"as np import h5py import re import tensorflow.keras.backend as K from tensorflow.keras.optimizers import",
"Conv1D, Embedding from ulaw import ulaw2lin, lin2ulaw from mdense import MDense max_rnn_neurons =",
"nb_nonzero = nb_nonzero + 1 idx = np.append(idx, j) W = np.concatenate([W, A[j,",
"weights = self.get_weights() printSparseVector(f, weights[1], name + '_recurrent_weights') printVector(f, weights[-1], name + '_bias')",
"'_weights') printVector(f, weights[1], name + '_recurrent_weights') printVector(f, weights[-1], name + '_bias') if hasattr(self,",
"ulaw import ulaw2lin, lin2ulaw from mdense import MDense max_rnn_neurons = 1 max_conv_inputs =",
"= 0 for j in range(N): if np.sum(np.abs(A[j, i*16:(i+1)*16])) > 1e-10: nb_nonzero =",
"'sparse_' + self.name print(\"printing layer \" + name + \" of type sparse",
"i*16:(i+1)*16])) > 1e-10: nb_nonzero = nb_nonzero + 1 idx = np.append(idx, j) W",
"b, 'LINEAR', bf) for i, layer in enumerate(model.layers): layer.dump_layer(bf) dump_sparse_gru(model.get_layer('gru_a'), bf) bf.write(struct.pack('III', max_rnn_neurons,",
"bf) W = model.get_layer('gru_a').get_weights()[0][2*embed_size:3*embed_size,:] dump_embedding_layer_impl('gru_a_embed_exc', np.dot(E, W), bf) W = model.get_layer('gru_a').get_weights()[0][3*embed_size:,:] #FIXME: dump",
"self.activation.__name__.upper() max_conv_inputs = max(max_conv_inputs, weights[0].shape[1]*weights[0].shape[0]) f.write(struct.pack('iiii', weights[0].shape[1], weights[0].shape[0], weights[0].shape[2], Activations[activation])) Conv1D.dump_layer = dump_conv1d_layer",
"activation = 'TANH' if hasattr(self, 'reset_after') and not self.reset_after: reset_after = 0 else:",
"OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL",
"lin2ulaw from mdense import MDense max_rnn_neurons = 1 max_conv_inputs = 1 max_mdense_tmp =",
"= self.activation.__name__.upper() dump_dense_layer_impl(name, weights[0], weights[1], activation, f) Dense.dump_layer = dump_dense_layer def dump_mdense_layer(self, f):",
"self.get_weights() printVector(f, np.transpose(weights[0], (1, 2, 0)), name + '_weights') printVector(f, np.transpose(weights[1], (1, 0)),",
"'_weights') printVector(f, np.transpose(weights[1], (1, 0)), name + '_bias') printVector(f, np.transpose(weights[2], (1, 0)), name",
"disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this",
"half the biases b = model.get_layer('gru_a').get_weights()[2] dump_dense_layer_impl('gru_a_dense_feature', W, b, 'LINEAR', bf) for i,",
"weights[0].shape[1]//3, Activations[activation], reset_after)) def dump_gru_layer(self, f): global max_rnn_neurons name = self.name print(\"printing layer",
"- np.diag(np.diag(A[:,N:2*N])) A[:,2*N:] = A[:,2*N:] - np.diag(np.diag(A[:,2*N:])) printVector(f, diag, name + '_diag') idx",
"ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF",
"import Adam from tensorflow.keras.callbacks import ModelCheckpoint from tensorflow.compat.v1.keras.layers import CuDNNGRU from tensorflow.keras.layers import",
"Embedding from ulaw import ulaw2lin, lin2ulaw from mdense import MDense max_rnn_neurons = 1",
"np.append(idx, j) W = np.concatenate([W, A[j, i*16:(i+1)*16]]) idx[pos] = nb_nonzero printVector(f, W, name)",
"= np.append(idx, -1) nb_nonzero = 0 for j in range(N): if np.sum(np.abs(A[j, i*16:(i+1)*16]))",
"N = A.shape[0] W = np.zeros((0,)) diag = np.concatenate([np.diag(A[:,:N]), np.diag(A[:,N:2*N]), np.diag(A[:,2*N:])]) A[:,:N] =",
"weights[-1], name + '_bias') if hasattr(self, 'activation'): activation = self.activation.__name__.upper() else: activation =",
"ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ''' import lpcnet import sys import",
"- Redistributions of source code must retain the above copyright notice, this list",
"v = np.reshape(vector, (-1)) v = v.astype(dtype) f.write(struct.pack('I', len(v))) f.write(v.tobytes()) def printSparseVector(f, A,",
"TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE",
"global max_rnn_neurons name = self.name print(\"printing layer \" + name + \" of",
"weights[0].shape[0], weights[0].shape[2], Activations[activation])) MDense.dump_layer = dump_mdense_layer def dump_conv1d_layer(self, f): global max_conv_inputs name =",
"= model.get_layer('gru_a').get_weights()[0][:embed_size,:] dump_embedding_layer_impl('gru_a_embed_sig', np.dot(E, W), bf) W = model.get_layer('gru_a').get_weights()[0][embed_size:2*embed_size,:] dump_embedding_layer_impl('gru_a_embed_pred', np.dot(E, W), bf)",
"> 1e-10: nb_nonzero = nb_nonzero + 1 idx = np.append(idx, j) W =",
"Activations[activation])) MDense.dump_layer = dump_mdense_layer def dump_conv1d_layer(self, f): global max_conv_inputs name = self.name print(\"printing",
"weights[0].shape[0], weights[0].shape[2], Activations[activation])) Conv1D.dump_layer = dump_conv1d_layer def dump_embedding_layer_impl(name, weights, f): printVector(f, weights, name",
"f.write(struct.pack('iiii', weights[0].shape[1], weights[0].shape[0], weights[0].shape[2], Activations[activation])) Conv1D.dump_layer = dump_conv1d_layer def dump_embedding_layer_impl(name, weights, f): printVector(f,",
"i in range(3*N//16): pos = idx.shape[0] idx = np.append(idx, -1) nb_nonzero = 0",
"np.zeros((0,), dtype='int') for i in range(3*N//16): pos = idx.shape[0] idx = np.append(idx, -1)",
"np.tile(np.concatenate([np.array([N]), np.arange(N)]), 3*N//16) printVector(f, idx, name + '_idx', dtype='int') def dump_layer_ignore(self, f): print(\"ignoring",
"WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS",
"name + \" of type \" + self.__class__.__name__) weights = self.get_weights() printVector(f, np.transpose(weights[0],",
"0)), name + '_weights') printVector(f, np.transpose(weights[1], (1, 0)), name + '_bias') printVector(f, np.transpose(weights[2],",
"activation = self.activation.__name__.upper() max_conv_inputs = max(max_conv_inputs, weights[0].shape[1]*weights[0].shape[0]) f.write(struct.pack('iiii', weights[0].shape[1], weights[0].shape[0], weights[0].shape[2], Activations[activation])) Conv1D.dump_layer",
"the above copyright notice, this list of conditions and the following disclaimer. -",
"= np.append(idx, j) W = np.concatenate([W, A[j, i*16:(i+1)*16]]) idx[pos] = nb_nonzero printVector(f, W,",
"printVector(f, idx, name + '_idx', dtype='int') def dump_layer_ignore(self, f): print(\"ignoring layer \" +",
"= max(max_rnn_neurons, neurons) f.write(struct.pack('iii', weights[0].shape[1]//3, Activations[activation], reset_after)) def dump_gru_layer(self, f): global max_rnn_neurons name",
"+ \" of type \" + self.__class__.__name__) weights = self.get_weights() printVector(f, np.transpose(weights[0], (1,",
"BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,",
"weights.shape[1])) def dump_embedding_layer(self, f): name = self.name print(\"printing layer \" + name +",
"modification, are permitted provided that the following conditions are met: - Redistributions of",
"OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR",
"- Redistributions in binary form must reproduce the above copyright notice, this list",
"f): printVector(f, weights, name + '_weights') printVector(f, bias, name + '_bias') f.write(struct.pack('iii', weights.shape[0],",
"import re import tensorflow.keras.backend as K from tensorflow.keras.optimizers import Adam from tensorflow.keras.callbacks import",
"+ '_bias') printVector(f, np.transpose(weights[2], (1, 0)), name + '_factor') activation = self.activation.__name__.upper() max_mdense_tmp",
"in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS",
"name) #idx = np.tile(np.concatenate([np.array([N]), np.arange(N)]), 3*N//16) printVector(f, idx, name + '_idx', dtype='int') def",
"weights[0], name + '_weights') printVector(f, weights[1], name + '_recurrent_weights') printVector(f, weights[-1], name +",
"E = model.get_layer('embed_sig').get_weights()[0] W = model.get_layer('gru_a').get_weights()[0][:embed_size,:] dump_embedding_layer_impl('gru_a_embed_sig', np.dot(E, W), bf) W = model.get_layer('gru_a').get_weights()[0][embed_size:2*embed_size,:]",
"dump_dense_layer_impl('gru_a_dense_feature', W, b, 'LINEAR', bf) for i, layer in enumerate(model.layers): layer.dump_layer(bf) dump_sparse_gru(model.get_layer('gru_a'), bf)",
"and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE",
"NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,",
"Adam from tensorflow.keras.callbacks import ModelCheckpoint from tensorflow.compat.v1.keras.layers import CuDNNGRU from tensorflow.keras.layers import Layer,",
"ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE",
"OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY",
"(-1)) v = v.astype(dtype) f.write(struct.pack('I', len(v))) f.write(v.tobytes()) def printSparseVector(f, A, name): N =",
"= np.concatenate([np.diag(A[:,:N]), np.diag(A[:,N:2*N]), np.diag(A[:,2*N:])]) A[:,:N] = A[:,:N] - np.diag(np.diag(A[:,:N])) A[:,N:2*N] = A[:,N:2*N] -",
"= 1 max_conv_inputs = 1 max_mdense_tmp = 1 Activations = { 'LINEAR':0, 'SIGMOID':1,",
"+ '_diag') idx = np.zeros((0,), dtype='int') for i in range(3*N//16): pos = idx.shape[0]",
"dump_layer_ignore def dump_sparse_gru(self, f): global max_rnn_neurons name = 'sparse_' + self.name print(\"printing layer",
"weights, f) Embedding.dump_layer = dump_embedding_layer model, _, _ = lpcnet.new_lpcnet_model(rnn_units1=384, use_gpu=False) model.compile(optimizer='adam', loss='sparse_categorical_crossentropy',",
"dtype='int') def dump_layer_ignore(self, f): print(\"ignoring layer \" + self.name + \" of type",
"_ = lpcnet.new_lpcnet_model(rnn_units1=384, use_gpu=False) model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['sparse_categorical_accuracy']) model.load_weights(sys.argv[1]) bf = open('nnet_data.bin', 'wb') embed_size",
"+ \" of type \" + self.__class__.__name__) weights = self.get_weights()[0] dump_embedding_layer_impl(name, weights, f)",
"bf) W = model.get_layer('gru_a').get_weights()[0][3*embed_size:,:] #FIXME: dump only half the biases b = model.get_layer('gru_a').get_weights()[2]",
"self.name print(\"printing layer \" + name + \" of type sparse \" +",
"= A[:,:N] - np.diag(np.diag(A[:,:N])) A[:,N:2*N] = A[:,N:2*N] - np.diag(np.diag(A[:,N:2*N])) A[:,2*N:] = A[:,2*N:] -",
"self.get_weights() activation = self.activation.__name__.upper() dump_dense_layer_impl(name, weights[0], weights[1], activation, f) Dense.dump_layer = dump_dense_layer def",
"self.__class__.__name__) Layer.dump_layer = dump_layer_ignore def dump_sparse_gru(self, f): global max_rnn_neurons name = 'sparse_' +",
"\" + self.__class__.__name__) Layer.dump_layer = dump_layer_ignore def dump_sparse_gru(self, f): global max_rnn_neurons name =",
"HOLDERS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT",
"dump_conv1d_layer(self, f): global max_conv_inputs name = self.name print(\"printing layer \" + name +",
"INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR",
"INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT",
"def dump_sparse_gru(self, f): global max_rnn_neurons name = 'sparse_' + self.name print(\"printing layer \"",
"def dump_conv1d_layer(self, f): global max_conv_inputs name = self.name print(\"printing layer \" + name",
"provided that the following conditions are met: - Redistributions of source code must",
"GRU, Dense, Conv1D, Embedding from ulaw import ulaw2lin, lin2ulaw from mdense import MDense",
"struct import numpy as np import h5py import re import tensorflow.keras.backend as K",
"+ '_idx', dtype='int') def dump_layer_ignore(self, f): print(\"ignoring layer \" + self.name + \"",
"dump_gru_layer(self, f): global max_rnn_neurons name = self.name print(\"printing layer \" + name +",
"name + '_weights') printVector(f, bias, name + '_bias') f.write(struct.pack('iii', weights.shape[0], weights.shape[1], Activations[activation])) def",
"'TANH' if hasattr(self, 'reset_after') and not self.reset_after: reset_after = 0 else: reset_after =",
"W, b, 'LINEAR', bf) for i, layer in enumerate(model.layers): layer.dump_layer(bf) dump_sparse_gru(model.get_layer('gru_a'), bf) bf.write(struct.pack('III',",
"pos = idx.shape[0] idx = np.append(idx, -1) nb_nonzero = 0 for j in",
"''' import lpcnet import sys import struct import numpy as np import h5py",
"= model.get_layer('gru_a').get_weights()[0][2*embed_size:3*embed_size,:] dump_embedding_layer_impl('gru_a_embed_exc', np.dot(E, W), bf) W = model.get_layer('gru_a').get_weights()[0][3*embed_size:,:] #FIXME: dump only half",
"import Layer, GRU, Dense, Conv1D, Embedding from ulaw import ulaw2lin, lin2ulaw from mdense",
"import h5py import re import tensorflow.keras.backend as K from tensorflow.keras.optimizers import Adam from",
"np.diag(np.diag(A[:,:N])) A[:,N:2*N] = A[:,N:2*N] - np.diag(np.diag(A[:,N:2*N])) A[:,2*N:] = A[:,2*N:] - np.diag(np.diag(A[:,2*N:])) printVector(f, diag,",
"layer \" + name + \" of type \" + self.__class__.__name__) weights =",
"\" + self.__class__.__name__) weights = self.get_weights() printVector(f, weights[0], name + '_weights') printVector(f, weights[-1],",
"CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES",
"weights = self.get_weights()[0] dump_embedding_layer_impl(name, weights, f) Embedding.dump_layer = dump_embedding_layer model, _, _ =",
"= dump_conv1d_layer def dump_embedding_layer_impl(name, weights, f): printVector(f, weights, name + '_weights') f.write(struct.pack('ii', weights.shape[0],",
"disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE",
"ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS BE LIABLE FOR",
"np.dot(E, W), bf) W = model.get_layer('gru_a').get_weights()[0][embed_size:2*embed_size,:] dump_embedding_layer_impl('gru_a_embed_pred', np.dot(E, W), bf) W = model.get_layer('gru_a').get_weights()[0][2*embed_size:3*embed_size,:]",
"weights[0].shape[0]*weights[0].shape[2]) f.write(struct.pack('iiii', weights[0].shape[1], weights[0].shape[0], weights[0].shape[2], Activations[activation])) MDense.dump_layer = dump_mdense_layer def dump_conv1d_layer(self, f): global",
"this list of conditions and the following disclaimer in the documentation and/or other",
"Dense, Conv1D, Embedding from ulaw import ulaw2lin, lin2ulaw from mdense import MDense max_rnn_neurons",
"(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF",
"POSSIBILITY OF SUCH DAMAGE. ''' import lpcnet import sys import struct import numpy",
"Redistributions in binary form must reproduce the above copyright notice, this list of",
"+ '_bias') f.write(struct.pack('iii', weights.shape[0], weights.shape[1], Activations[activation])) def dump_dense_layer(self, f): name = self.name print(\"printing",
"LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE",
"Layer.dump_layer = dump_layer_ignore def dump_sparse_gru(self, f): global max_rnn_neurons name = 'sparse_' + self.name",
"import lpcnet import sys import struct import numpy as np import h5py import",
"FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION",
"= lpcnet.new_lpcnet_model(rnn_units1=384, use_gpu=False) model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['sparse_categorical_accuracy']) model.load_weights(sys.argv[1]) bf = open('nnet_data.bin', 'wb') embed_size =",
"DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,",
"reset_after)) def dump_gru_layer(self, f): global max_rnn_neurons name = self.name print(\"printing layer \" +",
"= v.astype(dtype) f.write(struct.pack('I', len(v))) f.write(v.tobytes()) def printSparseVector(f, A, name): N = A.shape[0] W",
"Embedding.dump_layer = dump_embedding_layer model, _, _ = lpcnet.new_lpcnet_model(rnn_units1=384, use_gpu=False) model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['sparse_categorical_accuracy']) model.load_weights(sys.argv[1])",
"= dump_gru_layer GRU.dump_layer = dump_gru_layer def dump_dense_layer_impl(name, weights, bias, activation, f): printVector(f, weights,",
"dtype='int') for i in range(3*N//16): pos = idx.shape[0] idx = np.append(idx, -1) nb_nonzero",
"diag, name + '_diag') idx = np.zeros((0,), dtype='int') for i in range(3*N//16): pos",
"weights[0], name + '_weights') printVector(f, weights[-1], name + '_bias') activation = self.activation.__name__.upper() max_conv_inputs",
"name + \" of type \" + self.__class__.__name__) weights = self.get_weights() activation =",
"} def printVector(f, vector, name, dtype='float32'): print(\"name: {}, len: {}\".format(name, len(vector))) v =",
"+ \" of type sparse \" + self.__class__.__name__) weights = self.get_weights() printSparseVector(f, weights[1],",
"name + \" of type sparse \" + self.__class__.__name__) weights = self.get_weights() printSparseVector(f,",
"IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED",
"printVector(f, weights[-1], name + '_bias') activation = self.activation.__name__.upper() max_conv_inputs = max(max_conv_inputs, weights[0].shape[1]*weights[0].shape[0]) f.write(struct.pack('iiii',",
"name + '_weights') printVector(f, np.transpose(weights[1], (1, 0)), name + '_bias') printVector(f, np.transpose(weights[2], (1,",
"+ self.__class__.__name__) weights = self.get_weights()[0] dump_embedding_layer_impl(name, weights, f) Embedding.dump_layer = dump_embedding_layer model, _,",
"'_bias') if hasattr(self, 'activation'): activation = self.activation.__name__.upper() else: activation = 'TANH' if hasattr(self,",
"in range(3*N//16): pos = idx.shape[0] idx = np.append(idx, -1) nb_nonzero = 0 for",
"following disclaimer. - Redistributions in binary form must reproduce the above copyright notice,",
"binary form must reproduce the above copyright notice, this list of conditions and",
"= np.tile(np.concatenate([np.array([N]), np.arange(N)]), 3*N//16) printVector(f, idx, name + '_idx', dtype='int') def dump_layer_ignore(self, f):",
"+ name + \" of type \" + self.__class__.__name__) weights = self.get_weights()[0] dump_embedding_layer_impl(name,",
"+ self.__class__.__name__) weights = self.get_weights() printVector(f, np.transpose(weights[0], (1, 2, 0)), name + '_weights')",
"tensorflow.keras.optimizers import Adam from tensorflow.keras.callbacks import ModelCheckpoint from tensorflow.compat.v1.keras.layers import CuDNNGRU from tensorflow.keras.layers",
"DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF",
"v.astype(dtype) f.write(struct.pack('I', len(v))) f.write(v.tobytes()) def printSparseVector(f, A, name): N = A.shape[0] W =",
"reset_after = 0 else: reset_after = 1 neurons = weights[0].shape[1]//3 max_rnn_neurons = max(max_rnn_neurons,",
"IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY",
"OF SUCH DAMAGE. ''' import lpcnet import sys import struct import numpy as",
"EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS",
"COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,",
"\" of type sparse \" + self.__class__.__name__) weights = self.get_weights() printSparseVector(f, weights[1], name",
"self.activation.__name__.upper() dump_dense_layer_impl(name, weights[0], weights[1], activation, f) Dense.dump_layer = dump_dense_layer def dump_mdense_layer(self, f): global",
"IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN",
"hasattr(self, 'activation'): activation = self.activation.__name__.upper() else: activation = 'TANH' if hasattr(self, 'reset_after') and",
"\" of type \" + self.__class__.__name__) weights = self.get_weights() activation = self.activation.__name__.upper() dump_dense_layer_impl(name,",
"import numpy as np import h5py import re import tensorflow.keras.backend as K from",
"retain the above copyright notice, this list of conditions and the following disclaimer.",
"ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF",
"BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A",
"np.arange(N)]), 3*N//16) printVector(f, idx, name + '_idx', dtype='int') def dump_layer_ignore(self, f): print(\"ignoring layer",
"OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT",
"IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,",
"lpcnet.embed_size E = model.get_layer('embed_sig').get_weights()[0] W = model.get_layer('gru_a').get_weights()[0][:embed_size,:] dump_embedding_layer_impl('gru_a_embed_sig', np.dot(E, W), bf) W =",
"+ \" of type \" + self.__class__.__name__) weights = self.get_weights() printVector(f, weights[0], name",
"\" + name + \" of type \" + self.__class__.__name__) weights = self.get_weights()[0]",
"f): name = self.name print(\"printing layer \" + name + \" of type",
"IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ''' import lpcnet import sys",
"= self.name print(\"printing layer \" + name + \" of type \" +",
"bf = open('nnet_data.bin', 'wb') embed_size = lpcnet.embed_size E = model.get_layer('embed_sig').get_weights()[0] W = model.get_layer('gru_a').get_weights()[0][:embed_size,:]",
"dump_sparse_gru(self, f): global max_rnn_neurons name = 'sparse_' + self.name print(\"printing layer \" +",
"def dump_embedding_layer_impl(name, weights, f): printVector(f, weights, name + '_weights') f.write(struct.pack('ii', weights.shape[0], weights.shape[1])) def",
"0 for j in range(N): if np.sum(np.abs(A[j, i*16:(i+1)*16])) > 1e-10: nb_nonzero = nb_nonzero",
"LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF",
"name + '_weights') printVector(f, weights[-1], name + '_bias') activation = self.activation.__name__.upper() max_conv_inputs =",
"model.get_layer('gru_a').get_weights()[0][3*embed_size:,:] #FIXME: dump only half the biases b = model.get_layer('gru_a').get_weights()[2] dump_dense_layer_impl('gru_a_dense_feature', W, b,",
"max_conv_inputs name = self.name print(\"printing layer \" + name + \" of type",
"of type \" + self.__class__.__name__) weights = self.get_weights() activation = self.activation.__name__.upper() dump_dense_layer_impl(name, weights[0],",
"that the following conditions are met: - Redistributions of source code must retain",
"0 else: reset_after = 1 neurons = weights[0].shape[1]//3 max_rnn_neurons = max(max_rnn_neurons, neurons) f.write(struct.pack('iii',",
"or without modification, are permitted provided that the following conditions are met: -",
"in binary form must reproduce the above copyright notice, this list of conditions",
"of conditions and the following disclaimer in the documentation and/or other materials provided",
"= 1 max_mdense_tmp = 1 Activations = { 'LINEAR':0, 'SIGMOID':1, 'TANH':2, 'RELU':3, 'SOFTMAX':4",
"2017-2018 Mozilla Redistribution and use in source and binary forms, with or without",
"OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,",
"printVector(f, W, name) #idx = np.tile(np.concatenate([np.array([N]), np.arange(N)]), 3*N//16) printVector(f, idx, name + '_idx',",
"only half the biases b = model.get_layer('gru_a').get_weights()[2] dump_dense_layer_impl('gru_a_dense_feature', W, b, 'LINEAR', bf) for",
"A[:,:N] - np.diag(np.diag(A[:,:N])) A[:,N:2*N] = A[:,N:2*N] - np.diag(np.diag(A[:,N:2*N])) A[:,2*N:] = A[:,2*N:] - np.diag(np.diag(A[:,2*N:]))",
"Activations = { 'LINEAR':0, 'SIGMOID':1, 'TANH':2, 'RELU':3, 'SOFTMAX':4 } def printVector(f, vector, name,",
"self.__class__.__name__) weights = self.get_weights() activation = self.activation.__name__.upper() dump_dense_layer_impl(name, weights[0], weights[1], activation, f) Dense.dump_layer",
"+ self.__class__.__name__) weights = self.get_weights() printVector(f, weights[0], name + '_weights') printVector(f, weights[-1], name",
"EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ''' import lpcnet import",
"max(max_mdense_tmp, weights[0].shape[0]*weights[0].shape[2]) f.write(struct.pack('iiii', weights[0].shape[1], weights[0].shape[0], weights[0].shape[2], Activations[activation])) MDense.dump_layer = dump_mdense_layer def dump_conv1d_layer(self, f):",
"Dense.dump_layer = dump_dense_layer def dump_mdense_layer(self, f): global max_mdense_tmp name = self.name print(\"printing layer",
"and the following disclaimer. - Redistributions in binary form must reproduce the above",
"code must retain the above copyright notice, this list of conditions and the",
"self.get_weights() printVector(f, weights[0], name + '_weights') printVector(f, weights[1], name + '_recurrent_weights') printVector(f, weights[-1],",
"printVector(f, weights, name + '_weights') f.write(struct.pack('ii', weights.shape[0], weights.shape[1])) def dump_embedding_layer(self, f): name =",
"A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS",
"activation, f): printVector(f, weights, name + '_weights') printVector(f, bias, name + '_bias') f.write(struct.pack('iii',",
"and binary forms, with or without modification, are permitted provided that the following",
"1 Activations = { 'LINEAR':0, 'SIGMOID':1, 'TANH':2, 'RELU':3, 'SOFTMAX':4 } def printVector(f, vector,",
"type \" + self.__class__.__name__) weights = self.get_weights() printVector(f, weights[0], name + '_weights') printVector(f,",
"for i in range(3*N//16): pos = idx.shape[0] idx = np.append(idx, -1) nb_nonzero =",
"biases b = model.get_layer('gru_a').get_weights()[2] dump_dense_layer_impl('gru_a_dense_feature', W, b, 'LINEAR', bf) for i, layer in",
"+ \" of type \" + self.__class__.__name__) weights = self.get_weights() activation = self.activation.__name__.upper()",
"source code must retain the above copyright notice, this list of conditions and",
"printVector(f, weights, name + '_weights') printVector(f, bias, name + '_bias') f.write(struct.pack('iii', weights.shape[0], weights.shape[1],",
"Activations[activation])) Conv1D.dump_layer = dump_conv1d_layer def dump_embedding_layer_impl(name, weights, f): printVector(f, weights, name + '_weights')",
"name + '_weights') printVector(f, weights[1], name + '_recurrent_weights') printVector(f, weights[-1], name + '_bias')",
"with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS",
"W = np.concatenate([W, A[j, i*16:(i+1)*16]]) idx[pos] = nb_nonzero printVector(f, W, name) #idx =",
"OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED",
"not self.reset_after: reset_after = 0 else: reset_after = 1 neurons = weights[0].shape[1]//3 max_rnn_neurons",
"= 0 else: reset_after = 1 neurons = weights[0].shape[1]//3 max_rnn_neurons = max(max_rnn_neurons, neurons)",
"def dump_dense_layer_impl(name, weights, bias, activation, f): printVector(f, weights, name + '_weights') printVector(f, bias,",
"mdense import MDense max_rnn_neurons = 1 max_conv_inputs = 1 max_mdense_tmp = 1 Activations",
"THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,",
"neurons = weights[0].shape[1]//3 max_rnn_neurons = max(max_rnn_neurons, neurons) f.write(struct.pack('iiii', weights[0].shape[0], weights[0].shape[1]//3, Activations[activation], reset_after)) CuDNNGRU.dump_layer",
"= weights[0].shape[1]//3 max_rnn_neurons = max(max_rnn_neurons, neurons) f.write(struct.pack('iiii', weights[0].shape[0], weights[0].shape[1]//3, Activations[activation], reset_after)) CuDNNGRU.dump_layer =",
"OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF",
"vector, name, dtype='float32'): print(\"name: {}, len: {}\".format(name, len(vector))) v = np.reshape(vector, (-1)) v",
"+ self.name + \" of type \" + self.__class__.__name__) Layer.dump_layer = dump_layer_ignore def",
"Activations[activation])) def dump_dense_layer(self, f): name = self.name print(\"printing layer \" + name +",
"= 1 neurons = weights[0].shape[1]//3 max_rnn_neurons = max(max_rnn_neurons, neurons) f.write(struct.pack('iii', weights[0].shape[1]//3, Activations[activation], reset_after))",
"max_conv_inputs = 1 max_mdense_tmp = 1 Activations = { 'LINEAR':0, 'SIGMOID':1, 'TANH':2, 'RELU':3,",
"+ self.name print(\"printing layer \" + name + \" of type sparse \"",
"'_weights') f.write(struct.pack('ii', weights.shape[0], weights.shape[1])) def dump_embedding_layer(self, f): name = self.name print(\"printing layer \"",
"without modification, are permitted provided that the following conditions are met: - Redistributions",
"from tensorflow.compat.v1.keras.layers import CuDNNGRU from tensorflow.keras.layers import Layer, GRU, Dense, Conv1D, Embedding from",
"\" + name + \" of type \" + self.__class__.__name__) weights = self.get_weights()",
"f) Dense.dump_layer = dump_dense_layer def dump_mdense_layer(self, f): global max_mdense_tmp name = self.name print(\"printing",
"of type sparse \" + self.__class__.__name__) weights = self.get_weights() printSparseVector(f, weights[1], name +",
"A[:,2*N:] - np.diag(np.diag(A[:,2*N:])) printVector(f, diag, name + '_diag') idx = np.zeros((0,), dtype='int') for",
"type sparse \" + self.__class__.__name__) weights = self.get_weights() printSparseVector(f, weights[1], name + '_recurrent_weights')",
"OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. '''",
"max(max_rnn_neurons, neurons) f.write(struct.pack('iiii', weights[0].shape[0], weights[0].shape[1]//3, Activations[activation], reset_after)) CuDNNGRU.dump_layer = dump_gru_layer GRU.dump_layer = dump_gru_layer",
"weights, name + '_weights') printVector(f, bias, name + '_bias') f.write(struct.pack('iii', weights.shape[0], weights.shape[1], Activations[activation]))",
"v = v.astype(dtype) f.write(struct.pack('I', len(v))) f.write(v.tobytes()) def printSparseVector(f, A, name): N = A.shape[0]",
"CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY",
"idx = np.append(idx, -1) nb_nonzero = 0 for j in range(N): if np.sum(np.abs(A[j,",
"+ '_weights') printVector(f, weights[1], name + '_recurrent_weights') printVector(f, weights[-1], name + '_bias') if",
"weights[0].shape[2], Activations[activation])) MDense.dump_layer = dump_mdense_layer def dump_conv1d_layer(self, f): global max_conv_inputs name = self.name",
"= model.get_layer('gru_a').get_weights()[0][embed_size:2*embed_size,:] dump_embedding_layer_impl('gru_a_embed_pred', np.dot(E, W), bf) W = model.get_layer('gru_a').get_weights()[0][2*embed_size:3*embed_size,:] dump_embedding_layer_impl('gru_a_embed_exc', np.dot(E, W), bf)",
"notice, this list of conditions and the following disclaimer. - Redistributions in binary",
"from tensorflow.keras.optimizers import Adam from tensorflow.keras.callbacks import ModelCheckpoint from tensorflow.compat.v1.keras.layers import CuDNNGRU from",
"max(max_rnn_neurons, neurons) f.write(struct.pack('iii', weights[0].shape[1]//3, Activations[activation], reset_after)) def dump_gru_layer(self, f): global max_rnn_neurons name =",
"BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,",
"W = model.get_layer('gru_a').get_weights()[0][:embed_size,:] dump_embedding_layer_impl('gru_a_embed_sig', np.dot(E, W), bf) W = model.get_layer('gru_a').get_weights()[0][embed_size:2*embed_size,:] dump_embedding_layer_impl('gru_a_embed_pred', np.dot(E, W),",
"AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT",
"printVector(f, weights[-1], name + '_bias') if hasattr(self, 'activation'): activation = self.activation.__name__.upper() else: activation",
"reset_after = 1 neurons = weights[0].shape[1]//3 max_rnn_neurons = max(max_rnn_neurons, neurons) f.write(struct.pack('iii', weights[0].shape[1]//3, Activations[activation],",
"weights = self.get_weights() printVector(f, np.transpose(weights[0], (1, 2, 0)), name + '_weights') printVector(f, np.transpose(weights[1],",
"W = np.zeros((0,)) diag = np.concatenate([np.diag(A[:,:N]), np.diag(A[:,N:2*N]), np.diag(A[:,2*N:])]) A[:,:N] = A[:,:N] - np.diag(np.diag(A[:,:N]))",
"W), bf) W = model.get_layer('gru_a').get_weights()[0][embed_size:2*embed_size,:] dump_embedding_layer_impl('gru_a_embed_pred', np.dot(E, W), bf) W = model.get_layer('gru_a').get_weights()[0][2*embed_size:3*embed_size,:] dump_embedding_layer_impl('gru_a_embed_exc',",
"as K from tensorflow.keras.optimizers import Adam from tensorflow.keras.callbacks import ModelCheckpoint from tensorflow.compat.v1.keras.layers import",
"max_mdense_tmp = max(max_mdense_tmp, weights[0].shape[0]*weights[0].shape[2]) f.write(struct.pack('iiii', weights[0].shape[1], weights[0].shape[0], weights[0].shape[2], Activations[activation])) MDense.dump_layer = dump_mdense_layer def",
"1e-10: nb_nonzero = nb_nonzero + 1 idx = np.append(idx, j) W = np.concatenate([W,",
"weights[0].shape[1]//3 max_rnn_neurons = max(max_rnn_neurons, neurons) f.write(struct.pack('iii', weights[0].shape[1]//3, Activations[activation], reset_after)) def dump_gru_layer(self, f): global",
"provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND",
"form must reproduce the above copyright notice, this list of conditions and the",
"K from tensorflow.keras.optimizers import Adam from tensorflow.keras.callbacks import ModelCheckpoint from tensorflow.compat.v1.keras.layers import CuDNNGRU",
"A[:,:N] = A[:,:N] - np.diag(np.diag(A[:,:N])) A[:,N:2*N] = A[:,N:2*N] - np.diag(np.diag(A[:,N:2*N])) A[:,2*N:] = A[:,2*N:]",
"range(3*N//16): pos = idx.shape[0] idx = np.append(idx, -1) nb_nonzero = 0 for j",
"+ 1 idx = np.append(idx, j) W = np.concatenate([W, A[j, i*16:(i+1)*16]]) idx[pos] =",
"if hasattr(self, 'activation'): activation = self.activation.__name__.upper() else: activation = 'TANH' if hasattr(self, 'reset_after')",
"max_rnn_neurons = max(max_rnn_neurons, neurons) f.write(struct.pack('iii', weights[0].shape[1]//3, Activations[activation], reset_after)) def dump_gru_layer(self, f): global max_rnn_neurons",
"CuDNNGRU.dump_layer = dump_gru_layer GRU.dump_layer = dump_gru_layer def dump_dense_layer_impl(name, weights, bias, activation, f): printVector(f,",
"OF THE POSSIBILITY OF SUCH DAMAGE. ''' import lpcnet import sys import struct",
"activation, f) Dense.dump_layer = dump_dense_layer def dump_mdense_layer(self, f): global max_mdense_tmp name = self.name",
"above copyright notice, this list of conditions and the following disclaimer in the",
"#idx = np.tile(np.concatenate([np.array([N]), np.arange(N)]), 3*N//16) printVector(f, idx, name + '_idx', dtype='int') def dump_layer_ignore(self,",
"'reset_after') and not self.reset_after: reset_after = 0 else: reset_after = 1 neurons =",
"BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED",
"and use in source and binary forms, with or without modification, are permitted",
"= dump_dense_layer def dump_mdense_layer(self, f): global max_mdense_tmp name = self.name print(\"printing layer \"",
"use in source and binary forms, with or without modification, are permitted provided",
"printVector(f, weights[0], name + '_weights') printVector(f, weights[1], name + '_recurrent_weights') printVector(f, weights[-1], name",
"copyright notice, this list of conditions and the following disclaimer in the documentation",
"weights[0], weights[1], activation, f) Dense.dump_layer = dump_dense_layer def dump_mdense_layer(self, f): global max_mdense_tmp name",
"= np.zeros((0,), dtype='int') for i in range(3*N//16): pos = idx.shape[0] idx = np.append(idx,",
"\" + name + \" of type sparse \" + self.__class__.__name__) weights =",
"= 'sparse_' + self.name print(\"printing layer \" + name + \" of type",
"SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ''' import lpcnet",
"max_rnn_neurons name = 'sparse_' + self.name print(\"printing layer \" + name + \"",
"self.__class__.__name__) weights = self.get_weights() printVector(f, weights[0], name + '_weights') printVector(f, weights[1], name +",
"THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR",
"W = model.get_layer('gru_a').get_weights()[0][3*embed_size:,:] #FIXME: dump only half the biases b = model.get_layer('gru_a').get_weights()[2] dump_dense_layer_impl('gru_a_dense_feature',",
"weights = self.get_weights() activation = self.activation.__name__.upper() dump_dense_layer_impl(name, weights[0], weights[1], activation, f) Dense.dump_layer =",
"dump_dense_layer_impl(name, weights[0], weights[1], activation, f) Dense.dump_layer = dump_dense_layer def dump_mdense_layer(self, f): global max_mdense_tmp",
"+ '_weights') printVector(f, np.transpose(weights[1], (1, 0)), name + '_bias') printVector(f, np.transpose(weights[2], (1, 0)),",
"dump_dense_layer_impl(name, weights, bias, activation, f): printVector(f, weights, name + '_weights') printVector(f, bias, name",
"MDense.dump_layer = dump_mdense_layer def dump_conv1d_layer(self, f): global max_conv_inputs name = self.name print(\"printing layer",
"CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR",
"Mozilla Redistribution and use in source and binary forms, with or without modification,",
"idx = np.zeros((0,), dtype='int') for i in range(3*N//16): pos = idx.shape[0] idx =",
"NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,",
"3*N//16) printVector(f, idx, name + '_idx', dtype='int') def dump_layer_ignore(self, f): print(\"ignoring layer \"",
"\" of type \" + self.__class__.__name__) weights = self.get_weights() printVector(f, weights[0], name +",
"the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS",
"name + '_bias') if hasattr(self, 'activation'): activation = self.activation.__name__.upper() else: activation = 'TANH'",
"DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS",
"are met: - Redistributions of source code must retain the above copyright notice,",
"ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING",
"other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT",
"WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO",
"lpcnet import sys import struct import numpy as np import h5py import re",
"nb_nonzero = 0 for j in range(N): if np.sum(np.abs(A[j, i*16:(i+1)*16])) > 1e-10: nb_nonzero",
"SHALL THE FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,",
"self.get_weights() printSparseVector(f, weights[1], name + '_recurrent_weights') printVector(f, weights[-1], name + '_bias') if hasattr(self,",
"np.transpose(weights[0], (1, 2, 0)), name + '_weights') printVector(f, np.transpose(weights[1], (1, 0)), name +",
"= model.get_layer('embed_sig').get_weights()[0] W = model.get_layer('gru_a').get_weights()[0][:embed_size,:] dump_embedding_layer_impl('gru_a_embed_sig', np.dot(E, W), bf) W = model.get_layer('gru_a').get_weights()[0][embed_size:2*embed_size,:] dump_embedding_layer_impl('gru_a_embed_pred',",
"self.__class__.__name__) weights = self.get_weights() printVector(f, weights[0], name + '_weights') printVector(f, weights[-1], name +",
"f) Embedding.dump_layer = dump_embedding_layer model, _, _ = lpcnet.new_lpcnet_model(rnn_units1=384, use_gpu=False) model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['sparse_categorical_accuracy'])",
"source and binary forms, with or without modification, are permitted provided that the",
"import MDense max_rnn_neurons = 1 max_conv_inputs = 1 max_mdense_tmp = 1 Activations =",
"SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)",
"SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND",
"#FIXME: dump only half the biases b = model.get_layer('gru_a').get_weights()[2] dump_dense_layer_impl('gru_a_dense_feature', W, b, 'LINEAR',",
"OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)",
"= max(max_rnn_neurons, neurons) f.write(struct.pack('iiii', weights[0].shape[0], weights[0].shape[1]//3, Activations[activation], reset_after)) CuDNNGRU.dump_layer = dump_gru_layer GRU.dump_layer =",
"dump_embedding_layer_impl(name, weights, f): printVector(f, weights, name + '_weights') f.write(struct.pack('ii', weights.shape[0], weights.shape[1])) def dump_embedding_layer(self,",
"def printVector(f, vector, name, dtype='float32'): print(\"name: {}, len: {}\".format(name, len(vector))) v = np.reshape(vector,",
"np.dot(E, W), bf) W = model.get_layer('gru_a').get_weights()[0][2*embed_size:3*embed_size,:] dump_embedding_layer_impl('gru_a_embed_exc', np.dot(E, W), bf) W = model.get_layer('gru_a').get_weights()[0][3*embed_size:,:]",
"WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE",
"W), bf) W = model.get_layer('gru_a').get_weights()[0][3*embed_size:,:] #FIXME: dump only half the biases b =",
"distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS''",
"MDense max_rnn_neurons = 1 max_conv_inputs = 1 max_mdense_tmp = 1 Activations = {",
"sys import struct import numpy as np import h5py import re import tensorflow.keras.backend",
"= self.activation.__name__.upper() max_mdense_tmp = max(max_mdense_tmp, weights[0].shape[0]*weights[0].shape[2]) f.write(struct.pack('iiii', weights[0].shape[1], weights[0].shape[0], weights[0].shape[2], Activations[activation])) MDense.dump_layer =",
"DAMAGE. ''' import lpcnet import sys import struct import numpy as np import",
"SUCH DAMAGE. ''' import lpcnet import sys import struct import numpy as np",
"printVector(f, diag, name + '_diag') idx = np.zeros((0,), dtype='int') for i in range(3*N//16):",
"NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS",
"f.write(v.tobytes()) def printSparseVector(f, A, name): N = A.shape[0] W = np.zeros((0,)) diag =",
"met: - Redistributions of source code must retain the above copyright notice, this",
"Activations[activation], reset_after)) CuDNNGRU.dump_layer = dump_gru_layer GRU.dump_layer = dump_gru_layer def dump_dense_layer_impl(name, weights, bias, activation,",
"0 else: reset_after = 1 neurons = weights[0].shape[1]//3 max_rnn_neurons = max(max_rnn_neurons, neurons) f.write(struct.pack('iiii',",
"+ '_weights') f.write(struct.pack('ii', weights.shape[0], weights.shape[1])) def dump_embedding_layer(self, f): name = self.name print(\"printing layer",
"and not self.reset_after: reset_after = 0 else: reset_after = 1 neurons = weights[0].shape[1]//3",
"type \" + self.__class__.__name__) Layer.dump_layer = dump_layer_ignore def dump_sparse_gru(self, f): global max_rnn_neurons name",
"USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.",
"AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED",
"if hasattr(self, 'reset_after') and not self.reset_after: reset_after = 0 else: reset_after = 1",
"j in range(N): if np.sum(np.abs(A[j, i*16:(i+1)*16])) > 1e-10: nb_nonzero = nb_nonzero + 1",
"'_recurrent_weights') printVector(f, weights[-1], name + '_bias') if hasattr(self, 'activation'): activation = self.activation.__name__.upper() else:",
"reset_after = 1 neurons = weights[0].shape[1]//3 max_rnn_neurons = max(max_rnn_neurons, neurons) f.write(struct.pack('iiii', weights[0].shape[0], weights[0].shape[1]//3,",
"DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY",
"embed_size = lpcnet.embed_size E = model.get_layer('embed_sig').get_weights()[0] W = model.get_layer('gru_a').get_weights()[0][:embed_size,:] dump_embedding_layer_impl('gru_a_embed_sig', np.dot(E, W), bf)",
"#!/usr/bin/python3 '''Copyright (c) 2017-2018 Mozilla Redistribution and use in source and binary forms,",
"+ self.__class__.__name__) weights = self.get_weights() activation = self.activation.__name__.upper() dump_dense_layer_impl(name, weights[0], weights[1], activation, f)",
"else: reset_after = 1 neurons = weights[0].shape[1]//3 max_rnn_neurons = max(max_rnn_neurons, neurons) f.write(struct.pack('iiii', weights[0].shape[0],",
"= dump_embedding_layer model, _, _ = lpcnet.new_lpcnet_model(rnn_units1=384, use_gpu=False) model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['sparse_categorical_accuracy']) model.load_weights(sys.argv[1]) bf",
"model.get_layer('gru_a').get_weights()[0][2*embed_size:3*embed_size,:] dump_embedding_layer_impl('gru_a_embed_exc', np.dot(E, W), bf) W = model.get_layer('gru_a').get_weights()[0][3*embed_size:,:] #FIXME: dump only half the",
"\" + self.__class__.__name__) weights = self.get_weights() printVector(f, weights[0], name + '_weights') printVector(f, weights[1],",
"printVector(f, np.transpose(weights[1], (1, 0)), name + '_bias') printVector(f, np.transpose(weights[2], (1, 0)), name +",
"f): print(\"ignoring layer \" + self.name + \" of type \" + self.__class__.__name__)",
"(1, 2, 0)), name + '_weights') printVector(f, np.transpose(weights[1], (1, 0)), name + '_bias')",
"from tensorflow.keras.layers import Layer, GRU, Dense, Conv1D, Embedding from ulaw import ulaw2lin, lin2ulaw",
"WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN",
"A[j, i*16:(i+1)*16]]) idx[pos] = nb_nonzero printVector(f, W, name) #idx = np.tile(np.concatenate([np.array([N]), np.arange(N)]), 3*N//16)",
"name + '_diag') idx = np.zeros((0,), dtype='int') for i in range(3*N//16): pos =",
"permitted provided that the following conditions are met: - Redistributions of source code",
"numpy as np import h5py import re import tensorflow.keras.backend as K from tensorflow.keras.optimizers",
"for j in range(N): if np.sum(np.abs(A[j, i*16:(i+1)*16])) > 1e-10: nb_nonzero = nb_nonzero +",
"of type \" + self.__class__.__name__) Layer.dump_layer = dump_layer_ignore def dump_sparse_gru(self, f): global max_rnn_neurons",
"f.write(struct.pack('iii', weights[0].shape[1]//3, Activations[activation], reset_after)) def dump_gru_layer(self, f): global max_rnn_neurons name = self.name print(\"printing",
"dump_gru_layer def dump_dense_layer_impl(name, weights, bias, activation, f): printVector(f, weights, name + '_weights') printVector(f,",
"tensorflow.keras.layers import Layer, GRU, Dense, Conv1D, Embedding from ulaw import ulaw2lin, lin2ulaw from",
"= self.get_weights() printVector(f, weights[0], name + '_weights') printVector(f, weights[1], name + '_recurrent_weights') printVector(f,",
"weights, name + '_weights') f.write(struct.pack('ii', weights.shape[0], weights.shape[1])) def dump_embedding_layer(self, f): name = self.name",
"weights[0].shape[1]*weights[0].shape[0]) f.write(struct.pack('iiii', weights[0].shape[1], weights[0].shape[0], weights[0].shape[2], Activations[activation])) Conv1D.dump_layer = dump_conv1d_layer def dump_embedding_layer_impl(name, weights, f):",
"layer \" + name + \" of type sparse \" + self.__class__.__name__) weights",
"f.write(struct.pack('iiii', weights[0].shape[0], weights[0].shape[1]//3, Activations[activation], reset_after)) CuDNNGRU.dump_layer = dump_gru_layer GRU.dump_layer = dump_gru_layer def dump_dense_layer_impl(name,",
"'''Copyright (c) 2017-2018 Mozilla Redistribution and use in source and binary forms, with",
"from mdense import MDense max_rnn_neurons = 1 max_conv_inputs = 1 max_mdense_tmp = 1",
"0)), name + '_factor') activation = self.activation.__name__.upper() max_mdense_tmp = max(max_mdense_tmp, weights[0].shape[0]*weights[0].shape[2]) f.write(struct.pack('iiii', weights[0].shape[1],",
"self.get_weights() printVector(f, weights[0], name + '_weights') printVector(f, weights[-1], name + '_bias') activation =",
"weights[0].shape[0], weights[0].shape[1]//3, Activations[activation], reset_after)) CuDNNGRU.dump_layer = dump_gru_layer GRU.dump_layer = dump_gru_layer def dump_dense_layer_impl(name, weights,",
"= np.zeros((0,)) diag = np.concatenate([np.diag(A[:,:N]), np.diag(A[:,N:2*N]), np.diag(A[:,2*N:])]) A[:,:N] = A[:,:N] - np.diag(np.diag(A[:,:N])) A[:,N:2*N]",
"OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN",
"(1, 0)), name + '_factor') activation = self.activation.__name__.upper() max_mdense_tmp = max(max_mdense_tmp, weights[0].shape[0]*weights[0].shape[2]) f.write(struct.pack('iiii',",
"\" + self.__class__.__name__) weights = self.get_weights() activation = self.activation.__name__.upper() dump_dense_layer_impl(name, weights[0], weights[1], activation,",
"dump_layer_ignore(self, f): print(\"ignoring layer \" + self.name + \" of type \" +",
"dump only half the biases b = model.get_layer('gru_a').get_weights()[2] dump_dense_layer_impl('gru_a_dense_feature', W, b, 'LINEAR', bf)",
"AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE",
"'_weights') printVector(f, weights[-1], name + '_bias') activation = self.activation.__name__.upper() max_conv_inputs = max(max_conv_inputs, weights[0].shape[1]*weights[0].shape[0])",
"dump_dense_layer(self, f): name = self.name print(\"printing layer \" + name + \" of",
"name + '_weights') f.write(struct.pack('ii', weights.shape[0], weights.shape[1])) def dump_embedding_layer(self, f): name = self.name print(\"printing",
"= A[:,2*N:] - np.diag(np.diag(A[:,2*N:])) printVector(f, diag, name + '_diag') idx = np.zeros((0,), dtype='int')",
"= model.get_layer('gru_a').get_weights()[2] dump_dense_layer_impl('gru_a_dense_feature', W, b, 'LINEAR', bf) for i, layer in enumerate(model.layers): layer.dump_layer(bf)",
"+ '_weights') printVector(f, weights[-1], name + '_bias') activation = self.activation.__name__.upper() max_conv_inputs = max(max_conv_inputs,",
"dump_embedding_layer_impl('gru_a_embed_pred', np.dot(E, W), bf) W = model.get_layer('gru_a').get_weights()[0][2*embed_size:3*embed_size,:] dump_embedding_layer_impl('gru_a_embed_exc', np.dot(E, W), bf) W =",
"A, name): N = A.shape[0] W = np.zeros((0,)) diag = np.concatenate([np.diag(A[:,:N]), np.diag(A[:,N:2*N]), np.diag(A[:,2*N:])])",
"model.get_layer('gru_a').get_weights()[0][embed_size:2*embed_size,:] dump_embedding_layer_impl('gru_a_embed_pred', np.dot(E, W), bf) W = model.get_layer('gru_a').get_weights()[0][2*embed_size:3*embed_size,:] dump_embedding_layer_impl('gru_a_embed_exc', np.dot(E, W), bf) W",
"f): global max_mdense_tmp name = self.name print(\"printing layer \" + name + \"",
"f): global max_rnn_neurons name = self.name print(\"printing layer \" + name + \"",
"f.write(struct.pack('iii', weights.shape[0], weights.shape[1], Activations[activation])) def dump_dense_layer(self, f): name = self.name print(\"printing layer \"",
"model, _, _ = lpcnet.new_lpcnet_model(rnn_units1=384, use_gpu=False) model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['sparse_categorical_accuracy']) model.load_weights(sys.argv[1]) bf = open('nnet_data.bin',",
"W, name) #idx = np.tile(np.concatenate([np.array([N]), np.arange(N)]), 3*N//16) printVector(f, idx, name + '_idx', dtype='int')",
"= A.shape[0] W = np.zeros((0,)) diag = np.concatenate([np.diag(A[:,:N]), np.diag(A[:,N:2*N]), np.diag(A[:,2*N:])]) A[:,:N] = A[:,:N]"
] |
[
"t2 not return False def add_interval_betweenness(self,t_max,interval_size): res = [] for i in range(0,len(self.time_intervals)-1):",
"added ends at same time but starts before self.time_intervals[-1][0] = self.time_intervals[-2][0] else: end",
"fragmented link streams but maybe its ok to generalise it and make it",
"(m.time_intervals == self.time_intervals): return True return False def is_instantenous(self): #we check from the",
"else: ax = plt.gca() if dag: dag = S.condensation_dag() dag.plot(node_to_label=S.node_to_label, ax=ax) else: S.plot(ax=ax)",
"== last_y: degree = 0 else: degree = 1 for i in range(1,len(time_intervals)):",
"to the time intervals :param links : A list of nodes. (first node",
"def __hash__(self): m = tuple(self.nodes) n = tuple(self.time_intervals) return hash((m,n)) def __str__(self): s",
"in range(self.length()): l = self.nodes[i] l2 = self.nodes[i+1] t = self.time_intervals[i][0] t2 =",
"True else: return False else: if t >= self.time_intervals[indice-1][1] and t < self.time_intervals[indice][0]:",
"True x = self.time_intervals[-1] for i in range(-2,-len(self.time_intervals)-1,-1): if self.time_intervals[i] != x: return",
"if (lt0 <= t <= lt1) and (lt0 <= t2 <= lt1) and",
"self.time_intervals[i][0] t2 = self.time_intervals[i][1] id1 = S.nodes.index(l) id2 = S.nodes.index(l2) idmax = max(id1,",
"lt0, lt1 in zip(S.link_presence[id_link][::2], S.link_presence[id_link][1::2]): if (lt0 <= t <= lt1) and (lt0",
"interval_size for j in range(1,nb_interval_contributes_to+1): res.append((self.nodes[i+1], fst_interval_left_bound, fst_interval_left_bound + j * interval_size ))",
"clone(self): return Metawalk(self.time_intervals[:],self.nodes[:]) def __hash__(self): m = tuple(self.nodes) n = tuple(self.time_intervals) return hash((m,n))",
"to generalise it and make it work whenvever later on, update : false,",
"it and make it work whenvever later on, update : false, [1,2],[1,1] if",
"dag: dag = S.condensation_dag() dag.plot(node_to_label=S.node_to_label, ax=ax) else: S.plot(ax=ax) # Plot Source id_source =",
"False return True def update_following_last(self,b): #sometimes when adding a metaedge the metawalk has",
"+= \" | volume = \" s += str(self.volume()) return s def __repr__(self):",
"length(self): return len(self.time_intervals) def duration(self): return self.time_intervals[-1][1] - self.time_intervals[0][0] def clone(self): return Metawalk(self.time_intervals[:],self.nodes[:])",
"s += str(self.volume()) return s def __repr__(self): return self.__str__() def __eq__(self, m): if",
"__hash__(self): m = tuple(self.nodes) n = tuple(self.time_intervals) return hash((m,n)) def __str__(self): s =",
"because some paths are no longer valid. if b == 0: #last edge",
"self.length(): return False if (m.nodes == self.nodes) and (m.time_intervals == self.time_intervals): return True",
"false, [1,2],[1,1] if x == last_x and y == last_y and degree >",
"> 0: degree += 1 else: res[degree] += np.around((last_y - last_x)/np.math.factorial(degree), decimals=2) if",
"!= x: return False return True def update_following_last(self,b): #sometimes when adding a metaedge",
"path on the ``StreamGraph`` object *S* :param S: :param color: :param markersize: :param",
"idmax = max(id1, id2) idmin = min(id1, id2) # verts = [ #",
"[id2], color=color, # marker='>', alpha=0.8, markersize=markersize) # if i != 0 and (t,",
"else: end = self.time_intervals[-1][1] # last edge starts at same time but ends",
"t >= self.time_intervals[-1][1]: return True else: return False else: if t >= self.time_intervals[indice-1][1]",
"id1 == idmin: # plt.plot([t], [id1], color=color, # marker='^', alpha=0.8, markersize=markersize) # else:",
"a ``Metwalks`` object :param times : A list of couples of floats which",
"that uses it add new links to the end of the metawalk b",
"one bound no overlap in linkq in fragmented link streams but maybe its",
"is_present = False for lt0, lt1 in zip(S.link_presence[id_link][::2], S.link_presence[id_link][1::2]): if (lt0 <= t",
"its ok to generalise it and make it work whenvever later on, update",
"# marker='v', alpha=0.8, markersize=markersize) plt.tight_layout() return fig def check_coherence(self, S): for i in",
"in range(-2,-len(self.time_intervals)-1,-1): if self.time_intervals[i][1] > end: self.time_intervals[i][1] = end def volume(self): \"\"\"Normally the",
"dag: :param fig: :return: \"\"\" if fig is None: fig, ax = plt.subplots()",
"nodes. (first node = source ; last node = destination) \"\"\" self.time_intervals =",
"before self.time_intervals[-1][0] = self.time_intervals[-2][0] else: end = self.time_intervals[-1][1] # last edge starts at",
"else: nodes = self.nodes[:] time_intervals = self.time_intervals[:] time_intervals[0] = (time_intervals[0][1],time_intervals[0][1]) time_intervals[-1] = (time_intervals[-1][0],time_intervals[-1][0])",
"range(-2,-len(self.time_intervals)-1,-1): if self.time_intervals[i][1] > end: self.time_intervals[i][1] = end def volume(self): \"\"\"Normally the link",
"= (self.nodes[i],self.nodes[i+1]) inter = self.time_intervals[i] l_ = (self.nodes[i+1],self.nodes[i]) # Inverse the order of",
"*S* :param S: :param color: :param markersize: :param dag: :param fig: :return: \"\"\"",
"color=color) # Plot marker # if t != self.times[i + 1]: # plt.plot([t],",
"fig def check_coherence(self, S): for i in range(self.length()): l = (self.nodes[i],self.nodes[i+1]) inter =",
"for j in range(1,nb_interval_contributes_to+1): res.append((self.nodes[i+1], fst_interval_left_bound, fst_interval_left_bound + j * interval_size )) fst_interval_left_bound",
"if last_x != last_y: b = False x,y = time_intervals[i] #it should be",
"alpha=0.8, markersize=markersize) # Plot Destination id_destination = S.nodes.index(self.nodes[-1]) plt.plot([self.time_intervals[-1]], [id_destination], color=color, marker='o', alpha=0.8,",
"in range(0,self.length()): s += \" \" s += str(self.nodes[i]) s += \" \"",
"= S.links.index(l) else: id_link = S.links.index(l_) is_present = False for lt0, lt1 in",
"node = destination) \"\"\" self.time_intervals = time_intervals self.nodes = nodes def add_link(self, l,",
"on, update : false, [1,2],[1,1] if x == last_x and y == last_y",
"A list of couples of floats which represents times corresponding to the time",
"range(0,len(self.time_intervals)-1): left_bound = self.time_intervals[i][1] right_bound = self.time_intervals[i+1][0] nb_interval_contributes_to = (left_bound - right_bound) //",
"first_arrival(self): return self.time_intervals[-1][0] def first_node(self): return self.nodes[0] def last_node(self): return self.nodes[-1] def plot(self,",
": \" + str(l) + \" does not exists at time \" +",
"time intervals :param links : A list of nodes. (first node = source",
"top # (idmax, t2), # right, top # (idmin, t2), # right, bottom",
"def duration(self): return self.time_intervals[-1][1] - self.time_intervals[0][0] def clone(self): return Metawalk(self.time_intervals[:],self.nodes[:]) def __hash__(self): m",
"str(self.nodes[i]) s += \" \" s += str(self.time_intervals[i]) s += \" \" s",
"the algirothm that uses it add new links to the end of the",
"self.time_intervals[-1][1]: return True else: return False else: if t >= self.time_intervals[indice-1][1] and t",
"in S.links and l_ not in S.links: raise ValueError(\"Link : \" + str(l)",
"in res] return nppol.Polynomial(res) def passes_through(self,t,v): if v in self.nodes: indice = self.nodes.index(v)",
"= self.time_intervals[i][0] t2 = self.time_intervals[i][1] id1 = S.nodes.index(l) id2 = S.nodes.index(l2) idmax =",
"in range(0,len(self.time_intervals)-1): left_bound = self.time_intervals[i][1] right_bound = self.time_intervals[i+1][0] nb_interval_contributes_to = (left_bound - right_bound)",
"plt.vlines(t2, ymin=idmin, ymax=idmax, linewidth=6, alpha=0.8, color=color) if i != self.length() - 1: plt.hlines(id2,",
"Plot Path for i in range(self.length()): l = self.nodes[i] l2 = self.nodes[i+1] t",
"!= self.times[i + 1]: # plt.plot([t], [id2], color=color, # marker='>', alpha=0.8, markersize=markersize) #",
"(lt0 <= t <= lt1) and (lt0 <= t2 <= lt1) and (t",
"but maybe its ok to generalise it and make it work whenvever later",
"min(id1, id2) # verts = [ # (idmin, t), # left, bottom #",
"color=color, # marker='>', alpha=0.8, markersize=markersize) # if i != 0 and (t, id1)",
"else: t = inter[0] t2 = inter[1] if l in S.links: id_link =",
"def clone(self): return Metawalk(self.time_intervals[:],self.nodes[:]) def __hash__(self): m = tuple(self.nodes) n = tuple(self.time_intervals) return",
"if self.time_intervals[0] == self.time_intervals[-1]: return self.clone() else: nodes = self.nodes[:] time_intervals = self.time_intervals[:]",
"0: degree += 1 else: res[degree] += np.around((last_y - last_x)/np.math.factorial(degree), decimals=2) if x",
"markersize: :param dag: :param fig: :return: \"\"\" if fig is None: fig, ax",
"= (left_bound - right_bound) // interval_size fst_interval_left_bound = left_bound // interval_size for j",
"= [] for i in range(0,len(self.time_intervals)-1): left_bound = self.time_intervals[i][1] right_bound = self.time_intervals[i+1][0] nb_interval_contributes_to",
"self.nodes[-1] def plot(self, S, color=\"#18036f\", markersize=10, dag=False, fig=None): \"\"\" Draw a path on",
"self.time_intervals[-2][0] else: end = self.time_intervals[-1][1] # last edge starts at same time but",
"ok to generalise it and make it work whenvever later on, update :",
"self.nodes[0] def last_node(self): return self.nodes[-1] def plot(self, S, color=\"#18036f\", markersize=10, dag=False, fig=None): \"\"\"",
"self.length() - 1: plt.hlines(id2, xmin=t, xmax=t2, linewidth=4, alpha=0.8, color=color) plt.hlines(id1, xmin=t, xmax=t2, linewidth=4,",
"self.nodes[i+1] t = self.time_intervals[i][0] t2 = self.time_intervals[i][1] id1 = S.nodes.index(l) id2 = S.nodes.index(l2)",
"in self.nodes: indice = self.nodes.index(v) else: return False if indice == 0: if",
"in range(-2,-len(self.time_intervals)-1,-1): if self.time_intervals[i] != x: return False return True def update_following_last(self,b): #sometimes",
"included, but t2 not return False def add_interval_betweenness(self,t_max,interval_size): res = [] for i",
"time_intervals[-1] = (time_intervals[-1][0],time_intervals[-1][0]) for i in range(1,len(time_intervals)): if time_intervals[i][0] < time_intervals[0][0]: time_intervals[i] =",
"return False def passes_through_somewhere_interval(self,v,t1,t2): #t1 included, but t2 not return False def add_interval_betweenness(self,t_max,interval_size):",
"plt.plot([self.time_intervals[0]], [id_source], color=color, marker='o', alpha=0.8, markersize=markersize) # Plot Destination id_destination = S.nodes.index(self.nodes[-1]) plt.plot([self.time_intervals[-1]],",
"last_y and degree > 0: degree += 1 else: res[degree] += np.around((last_y -",
"alpha=0.8, markersize=markersize) # Plot Path for i in range(self.length()): l = self.nodes[i] l2",
"either exactly the same or disjoint, need to check for inclusion, exclusion of",
"xmin=t, xmax=t2, linewidth=4, alpha=0.8, color=color) plt.hlines(id1, xmin=t, xmax=t2, linewidth=4, alpha=0.8, color=color) # Plot",
"some paths are no longer valid. if b == 0: #last edge added",
"= nodes def add_link(self, l, t): self.time_intervals.append(t) self.nodes.append(l) def length(self): return len(self.time_intervals) def",
"self.time_intervals[:] time_intervals.append([-1,-1]) res = [0 for i in range(len(time_intervals)+ 1)] last_x,last_y = time_intervals[0]",
"links : A list of nodes. (first node = source ; last node",
"False def is_instantenous(self): #we check from the last because of the algirothm that",
"[ # (idmin, t), # left, bottom # (idmax, t), # left, top",
"last_departure(self): return self.time_intervals[0][1] def first_arrival(self): return self.time_intervals[-1][0] def first_node(self): return self.nodes[0] def last_node(self):",
"on the ``StreamGraph`` object *S* :param S: :param color: :param markersize: :param dag:",
"l_ = (self.nodes[i+1],self.nodes[i]) # Inverse the order of the interval if l not",
"!= self.length() - 1: plt.hlines(id2, xmin=t, xmax=t2, linewidth=4, alpha=0.8, color=color) plt.hlines(id1, xmin=t, xmax=t2,",
"class Metawalk: def __init__(self, time_intervals=None, nodes=None, ): \"\"\" A basic constructor for a",
"S.nodes.index(self.nodes[0]) plt.plot([self.time_intervals[0]], [id_source], color=color, marker='o', alpha=0.8, markersize=markersize) # Plot Destination id_destination = S.nodes.index(self.nodes[-1])",
"return False def add_interval_betweenness(self,t_max,interval_size): res = [] for i in range(0,len(self.time_intervals)-1): left_bound =",
"for e in res] return nppol.Polynomial(res) def passes_through(self,t,v): if v in self.nodes: indice",
"matplotlib.pyplot as plt import numpy as np import numpy.polynomial.polynomial as nppol class Metawalk:",
"``StreamGraph`` object *S* :param S: :param color: :param markersize: :param dag: :param fig:",
"for i in range(0,len(self.time_intervals)-1): left_bound = self.time_intervals[i][1] right_bound = self.time_intervals[i+1][0] nb_interval_contributes_to = (left_bound",
"order of the interval if l not in S.links and l_ not in",
"Metawalk: def __init__(self, time_intervals=None, nodes=None, ): \"\"\" A basic constructor for a ``Metwalks``",
"of couples of floats which represents times corresponding to the time intervals :param",
"self.nodes: indice = self.nodes.index(v) else: return False if indice == 0: if t",
"some points because some paths are no longer valid. if b == 0:",
"0 else: degree = 1 for i in range(1,len(time_intervals)): if last_x != last_y:",
"A list of nodes. (first node = source ; last node = destination)",
"[id1], color=color, # marker='v', alpha=0.8, markersize=markersize) plt.tight_layout() return fig def check_coherence(self, S): for",
"else: res[degree] += np.around((last_y - last_x)/np.math.factorial(degree), decimals=2) if x != y: degree =",
"S.links and l_ not in S.links: raise ValueError(\"Link : \" + str(l) +",
"exists at time \" + str(t) + \" !\") print(\"Check Path Coherence ok",
"# left, bottom # (idmax, t), # left, top # (idmax, t2), #",
"return False if m.length() != self.length(): return False if (m.nodes == self.nodes) and",
"degree > 0: degree += 1 else: res[degree] += np.around((last_y - last_x)/np.math.factorial(degree), decimals=2)",
"s += \" \" s += str(self.nodes[i+1]) s += \" | volume =",
"+ j * interval_size return res def fastest_meta_walk(self): if self.time_intervals[0] == self.time_intervals[-1]: return",
"1 else: res[degree] += np.around((last_y - last_x)/np.math.factorial(degree), decimals=2) if x != y: degree",
"and (m.time_intervals == self.time_intervals): return True return False def is_instantenous(self): #we check from",
"ends before for i in range(-2,-len(self.time_intervals)-1,-1): if self.time_intervals[i][1] > end: self.time_intervals[i][1] = end",
"# Inverse the order of the interval if l not in S.links and",
"// interval_size fst_interval_left_bound = left_bound // interval_size for j in range(1,nb_interval_contributes_to+1): res.append((self.nodes[i+1], fst_interval_left_bound,",
"= inter[0] t2 = inter[1] if l in S.links: id_link = S.links.index(l) else:",
"self.time_intervals[0][1] def first_arrival(self): return self.time_intervals[-1][0] def first_node(self): return self.nodes[0] def last_node(self): return self.nodes[-1]",
":param fig: :return: \"\"\" if fig is None: fig, ax = plt.subplots() else:",
"l_ not in S.links: raise ValueError(\"Link : \" + str(l) + \" does",
"not exists in the Stream Graph !\") else: t = inter[0] t2 =",
"time but starts before self.time_intervals[-1][0] = self.time_intervals[-2][0] else: end = self.time_intervals[-1][1] # last",
"last_x,last_y = time_intervals[0] b = True if len(time_intervals)==1: last_x,last_y = time_intervals[0] if last_x",
"time_intervals self.nodes = nodes def add_link(self, l, t): self.time_intervals.append(t) self.nodes.append(l) def length(self): return",
"id_source = S.nodes.index(self.nodes[0]) plt.plot([self.time_intervals[0]], [id_source], color=color, marker='o', alpha=0.8, markersize=markersize) # Plot Destination id_destination",
"<= t2): is_present = True if not is_present: raise ValueError(\"Link : \" +",
"ax = plt.subplots() else: ax = plt.gca() if dag: dag = S.condensation_dag() dag.plot(node_to_label=S.node_to_label,",
"t < self.time_intervals[0][0]: return True else: return False elif indice == len(self.nodes) -1:",
"t), # left, bottom # (idmax, t), # left, top # (idmax, t2),",
"str(l) + \" does not exists in the Stream Graph !\") else: t",
"\" s += str(self.nodes[i]) s += \" \" s += str(self.time_intervals[i]) s +=",
"idmin: # plt.plot([t], [id1], color=color, # marker='^', alpha=0.8, markersize=markersize) # else: # plt.plot([t],",
"= (time_intervals[i][0],time_intervals[-1][1]) return Metawalk(time_intervals,nodes) def first_time(self): return self.time_intervals[0][0] def last_departure(self): return self.time_intervals[0][1] def",
"= S.nodes.index(l2) idmax = max(id1, id2) idmin = min(id1, id2) # verts =",
"return res def fastest_meta_walk(self): if self.time_intervals[0] == self.time_intervals[-1]: return self.clone() else: nodes =",
"True else: return False elif indice == len(self.nodes) -1: if t >= self.time_intervals[-1][1]:",
"(self.nodes[i+1],self.nodes[i]) # Inverse the order of the interval if l not in S.links",
"object :param times : A list of couples of floats which represents times",
"True return False def is_instantenous(self): #we check from the last because of the",
"if time_intervals[i][1] > time_intervals[-1][1]: time_intervals[i] = (time_intervals[i][0],time_intervals[-1][1]) return Metawalk(time_intervals,nodes) def first_time(self): return self.time_intervals[0][0]",
"exclusion of intervals \"\"\" time_intervals = self.time_intervals[:] time_intervals.append([-1,-1]) res = [0 for i",
"# (idmin, t), # left, bottom # (idmax, t), # left, top #",
"return True else: return False else: if t >= self.time_intervals[indice-1][1] and t <",
"res[1] = np.around((last_y - last_x), decimals=2) else: if last_x == last_y: degree =",
"hash((m,n)) def __str__(self): s = \"\" for i in range(0,self.length()): s += \"",
"res = [] for i in range(0,len(self.time_intervals)-1): left_bound = self.time_intervals[i][1] right_bound = self.time_intervals[i+1][0]",
"dag=False, fig=None): \"\"\" Draw a path on the ``StreamGraph`` object *S* :param S:",
"# if t != self.times[i + 1]: # plt.plot([t], [id2], color=color, # marker='>',",
"because of the algirothm that uses it add new links to the end",
"(time_intervals[-1][0],time_intervals[-1][0]) for i in range(1,len(time_intervals)): if time_intervals[i][0] < time_intervals[0][0]: time_intervals[i] = (time_intervals[0][0],time_intervals[i][1]) if",
"\" \" s += str(self.nodes[i]) s += \" \" s += str(self.time_intervals[i]) s",
"def last_departure(self): return self.time_intervals[0][1] def first_arrival(self): return self.time_intervals[-1][0] def first_node(self): return self.nodes[0] def",
"!= last_y: b = False x,y = time_intervals[i] #it should be enough to",
"self.nodes.append(l) def length(self): return len(self.time_intervals) def duration(self): return self.time_intervals[-1][1] - self.time_intervals[0][0] def clone(self):",
"False else: if t >= self.time_intervals[indice-1][1] and t < self.time_intervals[indice][0]: return True else:",
"or disjoint, need to check for inclusion, exclusion of intervals \"\"\" time_intervals =",
"return False return True def update_following_last(self,b): #sometimes when adding a metaedge the metawalk",
"inter = self.time_intervals[i] l_ = (self.nodes[i+1],self.nodes[i]) # Inverse the order of the interval",
"- last_x)/np.math.factorial(degree), decimals=2) if x != y: degree = 1 last_x = x",
"range(len(time_intervals)+ 1)] last_x,last_y = time_intervals[0] b = True if len(time_intervals)==1: last_x,last_y = time_intervals[0]",
"\" s += str(self.volume()) return s def __repr__(self): return self.__str__() def __eq__(self, m):",
"(first node = source ; last node = destination) \"\"\" self.time_intervals = time_intervals",
"elif indice == len(self.nodes) -1: if t >= self.time_intervals[-1][1]: return True else: return",
"and t < self.time_intervals[indice][0]: return True else: return False def passes_through_whole_interval(self,v,t1,t2): return False",
"end of the metawalk b = True if len(self.time_intervals) == 1: return True",
"top # (idmin, t2), # right, bottom # ] plt.vlines(t, ymin=idmin, ymax=idmax, linewidth=6,",
"enough to check one bound no overlap in linkq in fragmented link streams",
"not in S.links: raise ValueError(\"Link : \" + str(l) + \" does not",
"self.time_intervals[i][1] > end: self.time_intervals[i][1] = end def volume(self): \"\"\"Normally the link are either",
"-1: if t >= self.time_intervals[-1][1]: return True else: return False else: if t",
"valid. if b == 0: #last edge added ends at same time but",
"raise ValueError(\"Link : \" + str(l) + \" does not exists at time",
"+ str(l) + \" does not exists at time \" + str(t) +",
"self.time_intervals): return True return False def is_instantenous(self): #we check from the last because",
"i in range(0,self.length()): s += \" \" s += str(self.nodes[i]) s += \"",
"False def passes_through_whole_interval(self,v,t1,t2): return False def passes_through_somewhere_interval(self,v,t1,t2): #t1 included, but t2 not return",
"check_coherence(self, S): for i in range(self.length()): l = (self.nodes[i],self.nodes[i+1]) inter = self.time_intervals[i] l_",
"v in self.nodes: indice = self.nodes.index(v) else: return False if indice == 0:",
"new links to the end of the metawalk b = True if len(self.time_intervals)",
"link are either exactly the same or disjoint, need to check for inclusion,",
"and make it work whenvever later on, update : false, [1,2],[1,1] if x",
"ends at same time but starts before self.time_intervals[-1][0] = self.time_intervals[-2][0] else: end =",
"check for inclusion, exclusion of intervals \"\"\" time_intervals = self.time_intervals[:] time_intervals.append([-1,-1]) res =",
"decimals=2) else: if last_x == last_y: degree = 0 else: degree = 1",
"= True if len(self.time_intervals) == 1: return True x = self.time_intervals[-1] for i",
"uses it add new links to the end of the metawalk b =",
"plt.tight_layout() return fig def check_coherence(self, S): for i in range(self.length()): l = (self.nodes[i],self.nodes[i+1])",
"+= np.around((last_y - last_x)/np.math.factorial(degree), decimals=2) if x != y: degree = 1 last_x",
"else: return False elif indice == len(self.nodes) -1: if t >= self.time_intervals[-1][1]: return",
"= 1 for i in range(1,len(time_intervals)): if last_x != last_y: b = False",
"left_bound = self.time_intervals[i][1] right_bound = self.time_intervals[i+1][0] nb_interval_contributes_to = (left_bound - right_bound) // interval_size",
"bottom # ] plt.vlines(t, ymin=idmin, ymax=idmax, linewidth=6, alpha=0.8, color=color) plt.vlines(t2, ymin=idmin, ymax=idmax, linewidth=6,",
"the end of the metawalk b = True if len(self.time_intervals) == 1: return",
"return self.time_intervals[-1][1] - self.time_intervals[0][0] def clone(self): return Metawalk(self.time_intervals[:],self.nodes[:]) def __hash__(self): m = tuple(self.nodes)",
"Stream Graph !\") else: t = inter[0] t2 = inter[1] if l in",
"[1,2],[1,1] if x == last_x and y == last_y and degree > 0:",
"j * interval_size )) fst_interval_left_bound = fst_interval_left_bound + j * interval_size return res",
"if last_x == last_y: degree = 0 else: degree = 1 for i",
"self.time_intervals[indice-1][1] and t < self.time_intervals[indice][0]: return True else: return False def passes_through_whole_interval(self,v,t1,t2): return",
"color=color, # marker='v', alpha=0.8, markersize=markersize) plt.tight_layout() return fig def check_coherence(self, S): for i",
"None: fig, ax = plt.subplots() else: ax = plt.gca() if dag: dag =",
"s def __repr__(self): return self.__str__() def __eq__(self, m): if m == None: return",
"color=color, marker='o', alpha=0.8, markersize=markersize) # Plot Destination id_destination = S.nodes.index(self.nodes[-1]) plt.plot([self.time_intervals[-1]], [id_destination], color=color,",
"s += str(self.nodes[i]) s += \" \" s += str(self.time_intervals[i]) s += \"",
":param times : A list of couples of floats which represents times corresponding",
"= 0 else: degree = 1 for i in range(1,len(time_intervals)): if last_x !=",
"np.around((last_y - last_x)/np.math.factorial(degree), decimals=2) if x != y: degree = 1 last_x =",
"if i != 0 and (t, id1) != (self.times[0], id_source) != (self.times[-1], id_destination):",
"nodes = self.nodes[:] time_intervals = self.time_intervals[:] time_intervals[0] = (time_intervals[0][1],time_intervals[0][1]) time_intervals[-1] = (time_intervals[-1][0],time_intervals[-1][0]) for",
"of floats which represents times corresponding to the time intervals :param links :",
"for lt0, lt1 in zip(S.link_presence[id_link][::2], S.link_presence[id_link][1::2]): if (lt0 <= t <= lt1) and",
"= S.nodes.index(self.nodes[0]) plt.plot([self.time_intervals[0]], [id_source], color=color, marker='o', alpha=0.8, markersize=markersize) # Plot Destination id_destination =",
"S.links.index(l) else: id_link = S.links.index(l_) is_present = False for lt0, lt1 in zip(S.link_presence[id_link][::2],",
"marker # if id1 == idmin: # plt.plot([t], [id1], color=color, # marker='^', alpha=0.8,",
"numpy.polynomial.polynomial as nppol class Metawalk: def __init__(self, time_intervals=None, nodes=None, ): \"\"\" A basic",
"= 1 last_x = x last_y = y if b == True: res[0]",
"and (t, id1) != (self.times[0], id_source) != (self.times[-1], id_destination): # # Plot marker",
"return self.time_intervals[-1][0] def first_node(self): return self.nodes[0] def last_node(self): return self.nodes[-1] def plot(self, S,",
"= plt.subplots() else: ax = plt.gca() if dag: dag = S.condensation_dag() dag.plot(node_to_label=S.node_to_label, ax=ax)",
"at time \" + str(t) + \" !\") print(\"Check Path Coherence ok !\")",
"plt.hlines(id2, xmin=t, xmax=t2, linewidth=4, alpha=0.8, color=color) plt.hlines(id1, xmin=t, xmax=t2, linewidth=4, alpha=0.8, color=color) #",
"markersize=markersize) plt.tight_layout() return fig def check_coherence(self, S): for i in range(self.length()): l =",
"(lt0 <= t2 <= lt1) and (t <= t2): is_present = True if",
"if t >= self.time_intervals[indice-1][1] and t < self.time_intervals[indice][0]: return True else: return False",
"return False def is_instantenous(self): #we check from the last because of the algirothm",
"False def add_interval_betweenness(self,t_max,interval_size): res = [] for i in range(0,len(self.time_intervals)-1): left_bound = self.time_intervals[i][1]",
"] plt.vlines(t, ymin=idmin, ymax=idmax, linewidth=6, alpha=0.8, color=color) plt.vlines(t2, ymin=idmin, ymax=idmax, linewidth=6, alpha=0.8, color=color)",
"m == None: return False if m.length() != self.length(): return False if (m.nodes",
"return self.time_intervals[0][1] def first_arrival(self): return self.time_intervals[-1][0] def first_node(self): return self.nodes[0] def last_node(self): return",
"[id_source], color=color, marker='o', alpha=0.8, markersize=markersize) # Plot Destination id_destination = S.nodes.index(self.nodes[-1]) plt.plot([self.time_intervals[-1]], [id_destination],",
"res[degree] += np.around((last_y - last_x)/np.math.factorial(degree), decimals=2) if x != y: degree = 1",
"== idmin: # plt.plot([t], [id1], color=color, # marker='^', alpha=0.8, markersize=markersize) # else: #",
"self.time_intervals[i+1][0] nb_interval_contributes_to = (left_bound - right_bound) // interval_size fst_interval_left_bound = left_bound // interval_size",
"last_node(self): return self.nodes[-1] def plot(self, S, color=\"#18036f\", markersize=10, dag=False, fig=None): \"\"\" Draw a",
"x,y = time_intervals[i] #it should be enough to check one bound no overlap",
"last_y = y if b == True: res[0] = 1 res = [np.around(e,decimals=2)",
"linewidth=4, alpha=0.8, color=color) # Plot marker # if t != self.times[i + 1]:",
"# right, bottom # ] plt.vlines(t, ymin=idmin, ymax=idmax, linewidth=6, alpha=0.8, color=color) plt.vlines(t2, ymin=idmin,",
"else: return False if indice == 0: if t < self.time_intervals[0][0]: return True",
"== last_y and degree > 0: degree += 1 else: res[degree] += np.around((last_y",
"if self.time_intervals[i] != x: return False return True def update_following_last(self,b): #sometimes when adding",
"= plt.gca() if dag: dag = S.condensation_dag() dag.plot(node_to_label=S.node_to_label, ax=ax) else: S.plot(ax=ax) # Plot",
"1 last_x = x last_y = y if b == True: res[0] =",
"if x != y: degree = 1 last_x = x last_y = y",
"indice = self.nodes.index(v) else: return False if indice == 0: if t <",
"plt.plot([self.time_intervals[-1]], [id_destination], color=color, marker='o', alpha=0.8, markersize=markersize) # Plot Path for i in range(self.length()):",
"= self.nodes.index(v) else: return False if indice == 0: if t < self.time_intervals[0][0]:",
"def first_arrival(self): return self.time_intervals[-1][0] def first_node(self): return self.nodes[0] def last_node(self): return self.nodes[-1] def",
"S.links: raise ValueError(\"Link : \" + str(l) + \" does not exists in",
"color=color) plt.vlines(t2, ymin=idmin, ymax=idmax, linewidth=6, alpha=0.8, color=color) if i != self.length() - 1:",
"algirothm that uses it add new links to the end of the metawalk",
"self.nodes) and (m.time_intervals == self.time_intervals): return True return False def is_instantenous(self): #we check",
"np import numpy.polynomial.polynomial as nppol class Metawalk: def __init__(self, time_intervals=None, nodes=None, ): \"\"\"",
"e in res] return nppol.Polynomial(res) def passes_through(self,t,v): if v in self.nodes: indice =",
"in S.links: raise ValueError(\"Link : \" + str(l) + \" does not exists",
"fst_interval_left_bound + j * interval_size return res def fastest_meta_walk(self): if self.time_intervals[0] == self.time_intervals[-1]:",
"True if len(self.time_intervals) == 1: return True x = self.time_intervals[-1] for i in",
"= self.nodes[i] l2 = self.nodes[i+1] t = self.time_intervals[i][0] t2 = self.time_intervals[i][1] id1 =",
"str(self.volume()) return s def __repr__(self): return self.__str__() def __eq__(self, m): if m ==",
"for a ``Metwalks`` object :param times : A list of couples of floats",
"(left_bound - right_bound) // interval_size fst_interval_left_bound = left_bound // interval_size for j in",
"#it should be enough to check one bound no overlap in linkq in",
"m): if m == None: return False if m.length() != self.length(): return False",
"list of couples of floats which represents times corresponding to the time intervals",
"#we check from the last because of the algirothm that uses it add",
"Plot marker # if id1 == idmin: # plt.plot([t], [id1], color=color, # marker='^',",
"of the metawalk b = True if len(self.time_intervals) == 1: return True x",
"# (idmin, t2), # right, bottom # ] plt.vlines(t, ymin=idmin, ymax=idmax, linewidth=6, alpha=0.8,",
"+= str(self.nodes[i+1]) s += \" | volume = \" s += str(self.volume()) return",
"def __eq__(self, m): if m == None: return False if m.length() != self.length():",
"the metawalk has to be cut at some points because some paths are",
"passes_through_whole_interval(self,v,t1,t2): return False def passes_through_somewhere_interval(self,v,t1,t2): #t1 included, but t2 not return False def",
"# marker='^', alpha=0.8, markersize=markersize) # else: # plt.plot([t], [id1], color=color, # marker='v', alpha=0.8,",
"the time intervals :param links : A list of nodes. (first node =",
"plot(self, S, color=\"#18036f\", markersize=10, dag=False, fig=None): \"\"\" Draw a path on the ``StreamGraph``",
"plt.subplots() else: ax = plt.gca() if dag: dag = S.condensation_dag() dag.plot(node_to_label=S.node_to_label, ax=ax) else:",
"color=\"#18036f\", markersize=10, dag=False, fig=None): \"\"\" Draw a path on the ``StreamGraph`` object *S*",
"* interval_size )) fst_interval_left_bound = fst_interval_left_bound + j * interval_size return res def",
"m = tuple(self.nodes) n = tuple(self.time_intervals) return hash((m,n)) def __str__(self): s = \"\"",
"longer valid. if b == 0: #last edge added ends at same time",
"zip(S.link_presence[id_link][::2], S.link_presence[id_link][1::2]): if (lt0 <= t <= lt1) and (lt0 <= t2 <=",
"S.nodes.index(l2) idmax = max(id1, id2) idmin = min(id1, id2) # verts = [",
"same time but ends before for i in range(-2,-len(self.time_intervals)-1,-1): if self.time_intervals[i][1] > end:",
"S.link_presence[id_link][1::2]): if (lt0 <= t <= lt1) and (lt0 <= t2 <= lt1)",
"plt.hlines(id1, xmin=t, xmax=t2, linewidth=4, alpha=0.8, color=color) # Plot marker # if t !=",
">= self.time_intervals[indice-1][1] and t < self.time_intervals[indice][0]: return True else: return False def passes_through_whole_interval(self,v,t1,t2):",
"in range(1,nb_interval_contributes_to+1): res.append((self.nodes[i+1], fst_interval_left_bound, fst_interval_left_bound + j * interval_size )) fst_interval_left_bound = fst_interval_left_bound",
"# Plot marker # if t != self.times[i + 1]: # plt.plot([t], [id2],",
"if t < self.time_intervals[0][0]: return True else: return False elif indice == len(self.nodes)",
"= False res[1] = np.around((last_y - last_x), decimals=2) else: if last_x == last_y:",
"# right, top # (idmin, t2), # right, bottom # ] plt.vlines(t, ymin=idmin,",
"np.around((last_y - last_x), decimals=2) else: if last_x == last_y: degree = 0 else:",
"inter[0] t2 = inter[1] if l in S.links: id_link = S.links.index(l) else: id_link",
"nppol.Polynomial(res) def passes_through(self,t,v): if v in self.nodes: indice = self.nodes.index(v) else: return False",
"= x last_y = y if b == True: res[0] = 1 res",
"= self.time_intervals[i+1][0] nb_interval_contributes_to = (left_bound - right_bound) // interval_size fst_interval_left_bound = left_bound //",
"# (idmax, t), # left, top # (idmax, t2), # right, top #",
"not return False def add_interval_betweenness(self,t_max,interval_size): res = [] for i in range(0,len(self.time_intervals)-1): left_bound",
"adding a metaedge the metawalk has to be cut at some points because",
"whenvever later on, update : false, [1,2],[1,1] if x == last_x and y",
"def update_following_last(self,b): #sometimes when adding a metaedge the metawalk has to be cut",
"id2) # verts = [ # (idmin, t), # left, bottom # (idmax,",
"ymin=idmin, ymax=idmax, linewidth=6, alpha=0.8, color=color) if i != self.length() - 1: plt.hlines(id2, xmin=t,",
"t != self.times[i + 1]: # plt.plot([t], [id2], color=color, # marker='>', alpha=0.8, markersize=markersize)",
"t2 <= lt1) and (t <= t2): is_present = True if not is_present:",
"= time_intervals[0] if last_x != last_y: b = False res[1] = np.around((last_y -",
"ValueError(\"Link : \" + str(l) + \" does not exists at time \"",
"right, top # (idmin, t2), # right, bottom # ] plt.vlines(t, ymin=idmin, ymax=idmax,",
"i != 0 and (t, id1) != (self.times[0], id_source) != (self.times[-1], id_destination): #",
"(m.nodes == self.nodes) and (m.time_intervals == self.time_intervals): return True return False def is_instantenous(self):",
"def add_link(self, l, t): self.time_intervals.append(t) self.nodes.append(l) def length(self): return len(self.time_intervals) def duration(self): return",
"starts at same time but ends before for i in range(-2,-len(self.time_intervals)-1,-1): if self.time_intervals[i][1]",
"(idmax, t2), # right, top # (idmin, t2), # right, bottom # ]",
"degree = 1 for i in range(1,len(time_intervals)): if last_x != last_y: b =",
"1: return True x = self.time_intervals[-1] for i in range(-2,-len(self.time_intervals)-1,-1): if self.time_intervals[i] !=",
"numpy as np import numpy.polynomial.polynomial as nppol class Metawalk: def __init__(self, time_intervals=None, nodes=None,",
"of nodes. (first node = source ; last node = destination) \"\"\" self.time_intervals",
"i in range(len(time_intervals)+ 1)] last_x,last_y = time_intervals[0] b = True if len(time_intervals)==1: last_x,last_y",
"+ \" does not exists at time \" + str(t) + \" !\")",
"for i in range(len(time_intervals)+ 1)] last_x,last_y = time_intervals[0] b = True if len(time_intervals)==1:",
"if m.length() != self.length(): return False if (m.nodes == self.nodes) and (m.time_intervals ==",
"x = self.time_intervals[-1] for i in range(-2,-len(self.time_intervals)-1,-1): if self.time_intervals[i] != x: return False",
"time_intervals[0][0]: time_intervals[i] = (time_intervals[0][0],time_intervals[i][1]) if time_intervals[i][1] > time_intervals[-1][1]: time_intervals[i] = (time_intervals[i][0],time_intervals[-1][1]) return Metawalk(time_intervals,nodes)",
"True else: return False def passes_through_whole_interval(self,v,t1,t2): return False def passes_through_somewhere_interval(self,v,t1,t2): #t1 included, but",
"return False elif indice == len(self.nodes) -1: if t >= self.time_intervals[-1][1]: return True",
"def __str__(self): s = \"\" for i in range(0,self.length()): s += \" \"",
"alpha=0.8, color=color) # Plot marker # if t != self.times[i + 1]: #",
"+= str(self.nodes[i]) s += \" \" s += str(self.time_intervals[i]) s += \" \"",
"duration(self): return self.time_intervals[-1][1] - self.time_intervals[0][0] def clone(self): return Metawalk(self.time_intervals[:],self.nodes[:]) def __hash__(self): m =",
"__str__(self): s = \"\" for i in range(0,self.length()): s += \" \" s",
"update : false, [1,2],[1,1] if x == last_x and y == last_y and",
"time_intervals[i] = (time_intervals[0][0],time_intervals[i][1]) if time_intervals[i][1] > time_intervals[-1][1]: time_intervals[i] = (time_intervals[i][0],time_intervals[-1][1]) return Metawalk(time_intervals,nodes) def",
"of the algirothm that uses it add new links to the end of",
"update_following_last(self,b): #sometimes when adding a metaedge the metawalk has to be cut at",
"color=color) if i != self.length() - 1: plt.hlines(id2, xmin=t, xmax=t2, linewidth=4, alpha=0.8, color=color)",
"range(-2,-len(self.time_intervals)-1,-1): if self.time_intervals[i] != x: return False return True def update_following_last(self,b): #sometimes when",
"a metaedge the metawalk has to be cut at some points because some",
"self.times[i + 1]: # plt.plot([t], [id2], color=color, # marker='>', alpha=0.8, markersize=markersize) # if",
"# ] plt.vlines(t, ymin=idmin, ymax=idmax, linewidth=6, alpha=0.8, color=color) plt.vlines(t2, ymin=idmin, ymax=idmax, linewidth=6, alpha=0.8,",
"fig: :return: \"\"\" if fig is None: fig, ax = plt.subplots() else: ax",
"1 for i in range(1,len(time_intervals)): if last_x != last_y: b = False x,y",
"* interval_size return res def fastest_meta_walk(self): if self.time_intervals[0] == self.time_intervals[-1]: return self.clone() else:",
"are either exactly the same or disjoint, need to check for inclusion, exclusion",
"# if id1 == idmin: # plt.plot([t], [id1], color=color, # marker='^', alpha=0.8, markersize=markersize)",
"range(0,self.length()): s += \" \" s += str(self.nodes[i]) s += \" \" s",
"time_intervals[0] = (time_intervals[0][1],time_intervals[0][1]) time_intervals[-1] = (time_intervals[-1][0],time_intervals[-1][0]) for i in range(1,len(time_intervals)): if time_intervals[i][0] <",
"at same time but starts before self.time_intervals[-1][0] = self.time_intervals[-2][0] else: end = self.time_intervals[-1][1]",
"and l_ not in S.links: raise ValueError(\"Link : \" + str(l) + \"",
"b = False res[1] = np.around((last_y - last_x), decimals=2) else: if last_x ==",
"[np.around(e,decimals=2) for e in res] return nppol.Polynomial(res) def passes_through(self,t,v): if v in self.nodes:",
"the link are either exactly the same or disjoint, need to check for",
"plt import numpy as np import numpy.polynomial.polynomial as nppol class Metawalk: def __init__(self,",
"and (t <= t2): is_present = True if not is_present: raise ValueError(\"Link :",
"= True if len(time_intervals)==1: last_x,last_y = time_intervals[0] if last_x != last_y: b =",
"x == last_x and y == last_y and degree > 0: degree +=",
"# Plot Source id_source = S.nodes.index(self.nodes[0]) plt.plot([self.time_intervals[0]], [id_source], color=color, marker='o', alpha=0.8, markersize=markersize) #",
"metaedge the metawalk has to be cut at some points because some paths",
"Metawalk(self.time_intervals[:],self.nodes[:]) def __hash__(self): m = tuple(self.nodes) n = tuple(self.time_intervals) return hash((m,n)) def __str__(self):",
"res] return nppol.Polynomial(res) def passes_through(self,t,v): if v in self.nodes: indice = self.nodes.index(v) else:",
"= self.time_intervals[:] time_intervals.append([-1,-1]) res = [0 for i in range(len(time_intervals)+ 1)] last_x,last_y =",
"last_x = x last_y = y if b == True: res[0] = 1",
"res[0] = 1 res = [np.around(e,decimals=2) for e in res] return nppol.Polynomial(res) def",
"if indice == 0: if t < self.time_intervals[0][0]: return True else: return False",
"= self.nodes[i+1] t = self.time_intervals[i][0] t2 = self.time_intervals[i][1] id1 = S.nodes.index(l) id2 =",
"if x == last_x and y == last_y and degree > 0: degree",
"# verts = [ # (idmin, t), # left, bottom # (idmax, t),",
"# else: # plt.plot([t], [id1], color=color, # marker='v', alpha=0.8, markersize=markersize) plt.tight_layout() return fig",
"= self.time_intervals[i][1] right_bound = self.time_intervals[i+1][0] nb_interval_contributes_to = (left_bound - right_bound) // interval_size fst_interval_left_bound",
"for i in range(-2,-len(self.time_intervals)-1,-1): if self.time_intervals[i] != x: return False return True def",
"as plt import numpy as np import numpy.polynomial.polynomial as nppol class Metawalk: def",
"= (time_intervals[0][0],time_intervals[i][1]) if time_intervals[i][1] > time_intervals[-1][1]: time_intervals[i] = (time_intervals[i][0],time_intervals[-1][1]) return Metawalk(time_intervals,nodes) def first_time(self):",
"< time_intervals[0][0]: time_intervals[i] = (time_intervals[0][0],time_intervals[i][1]) if time_intervals[i][1] > time_intervals[-1][1]: time_intervals[i] = (time_intervals[i][0],time_intervals[-1][1]) return",
"represents times corresponding to the time intervals :param links : A list of",
"def volume(self): \"\"\"Normally the link are either exactly the same or disjoint, need",
"not exists at time \" + str(t) + \" !\") print(\"Check Path Coherence",
"= tuple(self.time_intervals) return hash((m,n)) def __str__(self): s = \"\" for i in range(0,self.length()):",
"= self.time_intervals[:] time_intervals[0] = (time_intervals[0][1],time_intervals[0][1]) time_intervals[-1] = (time_intervals[-1][0],time_intervals[-1][0]) for i in range(1,len(time_intervals)): if",
"and y == last_y and degree > 0: degree += 1 else: res[degree]",
"== len(self.nodes) -1: if t >= self.time_intervals[-1][1]: return True else: return False else:",
"fst_interval_left_bound, fst_interval_left_bound + j * interval_size )) fst_interval_left_bound = fst_interval_left_bound + j *",
"= min(id1, id2) # verts = [ # (idmin, t), # left, bottom",
"l, t): self.time_intervals.append(t) self.nodes.append(l) def length(self): return len(self.time_intervals) def duration(self): return self.time_intervals[-1][1] -",
"does not exists at time \" + str(t) + \" !\") print(\"Check Path",
"range(1,nb_interval_contributes_to+1): res.append((self.nodes[i+1], fst_interval_left_bound, fst_interval_left_bound + j * interval_size )) fst_interval_left_bound = fst_interval_left_bound +",
"last_x,last_y = time_intervals[0] if last_x != last_y: b = False res[1] = np.around((last_y",
"self.nodes[:] time_intervals = self.time_intervals[:] time_intervals[0] = (time_intervals[0][1],time_intervals[0][1]) time_intervals[-1] = (time_intervals[-1][0],time_intervals[-1][0]) for i in",
"id_destination): # # Plot marker # if id1 == idmin: # plt.plot([t], [id1],",
"# plt.plot([t], [id1], color=color, # marker='^', alpha=0.8, markersize=markersize) # else: # plt.plot([t], [id1],",
"marker # if t != self.times[i + 1]: # plt.plot([t], [id2], color=color, #",
"color=color) plt.hlines(id1, xmin=t, xmax=t2, linewidth=4, alpha=0.8, color=color) # Plot marker # if t",
"cut at some points because some paths are no longer valid. if b",
"else: S.plot(ax=ax) # Plot Source id_source = S.nodes.index(self.nodes[0]) plt.plot([self.time_intervals[0]], [id_source], color=color, marker='o', alpha=0.8,",
"last_x != last_y: b = False x,y = time_intervals[i] #it should be enough",
"t = self.time_intervals[i][0] t2 = self.time_intervals[i][1] id1 = S.nodes.index(l) id2 = S.nodes.index(l2) idmax",
"corresponding to the time intervals :param links : A list of nodes. (first",
"when adding a metaedge the metawalk has to be cut at some points",
"if self.time_intervals[i][1] > end: self.time_intervals[i][1] = end def volume(self): \"\"\"Normally the link are",
"[id_destination], color=color, marker='o', alpha=0.8, markersize=markersize) # Plot Path for i in range(self.length()): l",
"if id1 == idmin: # plt.plot([t], [id1], color=color, # marker='^', alpha=0.8, markersize=markersize) #",
"def passes_through_somewhere_interval(self,v,t1,t2): #t1 included, but t2 not return False def add_interval_betweenness(self,t_max,interval_size): res =",
"time_intervals[-1][1]: time_intervals[i] = (time_intervals[i][0],time_intervals[-1][1]) return Metawalk(time_intervals,nodes) def first_time(self): return self.time_intervals[0][0] def last_departure(self): return",
"l = self.nodes[i] l2 = self.nodes[i+1] t = self.time_intervals[i][0] t2 = self.time_intervals[i][1] id1",
"disjoint, need to check for inclusion, exclusion of intervals \"\"\" time_intervals = self.time_intervals[:]",
"does not exists in the Stream Graph !\") else: t = inter[0] t2",
"constructor for a ``Metwalks`` object :param times : A list of couples of",
"self.nodes.index(v) else: return False if indice == 0: if t < self.time_intervals[0][0]: return",
"- self.time_intervals[0][0] def clone(self): return Metawalk(self.time_intervals[:],self.nodes[:]) def __hash__(self): m = tuple(self.nodes) n =",
"self.time_intervals[-1][1] - self.time_intervals[0][0] def clone(self): return Metawalk(self.time_intervals[:],self.nodes[:]) def __hash__(self): m = tuple(self.nodes) n",
"edge starts at same time but ends before for i in range(-2,-len(self.time_intervals)-1,-1): if",
"alpha=0.8, markersize=markersize) plt.tight_layout() return fig def check_coherence(self, S): for i in range(self.length()): l",
"\" s += str(self.nodes[i+1]) s += \" | volume = \" s +=",
"= [0 for i in range(len(time_intervals)+ 1)] last_x,last_y = time_intervals[0] b = True",
"== 0: #last edge added ends at same time but starts before self.time_intervals[-1][0]",
"ymin=idmin, ymax=idmax, linewidth=6, alpha=0.8, color=color) plt.vlines(t2, ymin=idmin, ymax=idmax, linewidth=6, alpha=0.8, color=color) if i",
"j * interval_size return res def fastest_meta_walk(self): if self.time_intervals[0] == self.time_intervals[-1]: return self.clone()",
"s += \" | volume = \" s += str(self.volume()) return s def",
"volume = \" s += str(self.volume()) return s def __repr__(self): return self.__str__() def",
"\"\"\" time_intervals = self.time_intervals[:] time_intervals.append([-1,-1]) res = [0 for i in range(len(time_intervals)+ 1)]",
"else: degree = 1 for i in range(1,len(time_intervals)): if last_x != last_y: b",
"is None: fig, ax = plt.subplots() else: ax = plt.gca() if dag: dag",
"end def volume(self): \"\"\"Normally the link are either exactly the same or disjoint,",
"str(self.nodes[i+1]) s += \" | volume = \" s += str(self.volume()) return s",
"return s def __repr__(self): return self.__str__() def __eq__(self, m): if m == None:",
"in fragmented link streams but maybe its ok to generalise it and make",
"id1) != (self.times[0], id_source) != (self.times[-1], id_destination): # # Plot marker # if",
"exists in the Stream Graph !\") else: t = inter[0] t2 = inter[1]",
"time_intervals[i][0] < time_intervals[0][0]: time_intervals[i] = (time_intervals[0][0],time_intervals[i][1]) if time_intervals[i][1] > time_intervals[-1][1]: time_intervals[i] = (time_intervals[i][0],time_intervals[-1][1])",
"> end: self.time_intervals[i][1] = end def volume(self): \"\"\"Normally the link are either exactly",
"t): self.time_intervals.append(t) self.nodes.append(l) def length(self): return len(self.time_intervals) def duration(self): return self.time_intervals[-1][1] - self.time_intervals[0][0]",
"Draw a path on the ``StreamGraph`` object *S* :param S: :param color: :param",
"end: self.time_intervals[i][1] = end def volume(self): \"\"\"Normally the link are either exactly the",
":return: \"\"\" if fig is None: fig, ax = plt.subplots() else: ax =",
"self.time_intervals[i][1] = end def volume(self): \"\"\"Normally the link are either exactly the same",
"in range(1,len(time_intervals)): if last_x != last_y: b = False x,y = time_intervals[i] #it",
"id2) idmin = min(id1, id2) # verts = [ # (idmin, t), #",
"1]: # plt.plot([t], [id2], color=color, # marker='>', alpha=0.8, markersize=markersize) # if i !=",
"overlap in linkq in fragmented link streams but maybe its ok to generalise",
"indice == 0: if t < self.time_intervals[0][0]: return True else: return False elif",
"= (time_intervals[0][1],time_intervals[0][1]) time_intervals[-1] = (time_intervals[-1][0],time_intervals[-1][0]) for i in range(1,len(time_intervals)): if time_intervals[i][0] < time_intervals[0][0]:",
"Path for i in range(self.length()): l = self.nodes[i] l2 = self.nodes[i+1] t =",
"== self.time_intervals): return True return False def is_instantenous(self): #we check from the last",
"l2 = self.nodes[i+1] t = self.time_intervals[i][0] t2 = self.time_intervals[i][1] id1 = S.nodes.index(l) id2",
"return self.time_intervals[0][0] def last_departure(self): return self.time_intervals[0][1] def first_arrival(self): return self.time_intervals[-1][0] def first_node(self): return",
"S.nodes.index(self.nodes[-1]) plt.plot([self.time_intervals[-1]], [id_destination], color=color, marker='o', alpha=0.8, markersize=markersize) # Plot Path for i in",
"= (self.nodes[i+1],self.nodes[i]) # Inverse the order of the interval if l not in",
"times : A list of couples of floats which represents times corresponding to",
"False x,y = time_intervals[i] #it should be enough to check one bound no",
"linewidth=6, alpha=0.8, color=color) plt.vlines(t2, ymin=idmin, ymax=idmax, linewidth=6, alpha=0.8, color=color) if i != self.length()",
"A basic constructor for a ``Metwalks`` object :param times : A list of",
"alpha=0.8, markersize=markersize) # if i != 0 and (t, id1) != (self.times[0], id_source)",
"add_link(self, l, t): self.time_intervals.append(t) self.nodes.append(l) def length(self): return len(self.time_intervals) def duration(self): return self.time_intervals[-1][1]",
"be cut at some points because some paths are no longer valid. if",
"self.time_intervals.append(t) self.nodes.append(l) def length(self): return len(self.time_intervals) def duration(self): return self.time_intervals[-1][1] - self.time_intervals[0][0] def",
"metawalk has to be cut at some points because some paths are no",
"range(1,len(time_intervals)): if time_intervals[i][0] < time_intervals[0][0]: time_intervals[i] = (time_intervals[0][0],time_intervals[i][1]) if time_intervals[i][1] > time_intervals[-1][1]: time_intervals[i]",
"bottom # (idmax, t), # left, top # (idmax, t2), # right, top",
"id_link = S.links.index(l) else: id_link = S.links.index(l_) is_present = False for lt0, lt1",
"if t >= self.time_intervals[-1][1]: return True else: return False else: if t >=",
"= self.time_intervals[i] l_ = (self.nodes[i+1],self.nodes[i]) # Inverse the order of the interval if",
"are no longer valid. if b == 0: #last edge added ends at",
"check one bound no overlap in linkq in fragmented link streams but maybe",
"last_x != last_y: b = False res[1] = np.around((last_y - last_x), decimals=2) else:",
"if b == True: res[0] = 1 res = [np.around(e,decimals=2) for e in",
"+= str(self.time_intervals[i]) s += \" \" s += str(self.nodes[i+1]) s += \" |",
"self.time_intervals[i] l_ = (self.nodes[i+1],self.nodes[i]) # Inverse the order of the interval if l",
"to the end of the metawalk b = True if len(self.time_intervals) == 1:",
"= self.time_intervals[-2][0] else: end = self.time_intervals[-1][1] # last edge starts at same time",
"range(1,len(time_intervals)): if last_x != last_y: b = False x,y = time_intervals[i] #it should",
"id1 = S.nodes.index(l) id2 = S.nodes.index(l2) idmax = max(id1, id2) idmin = min(id1,",
"return True x = self.time_intervals[-1] for i in range(-2,-len(self.time_intervals)-1,-1): if self.time_intervals[i] != x:",
"\"\" for i in range(0,self.length()): s += \" \" s += str(self.nodes[i]) s",
"interval_size )) fst_interval_left_bound = fst_interval_left_bound + j * interval_size return res def fastest_meta_walk(self):",
"object *S* :param S: :param color: :param markersize: :param dag: :param fig: :return:",
"# Plot marker # if id1 == idmin: # plt.plot([t], [id1], color=color, #",
"(t, id1) != (self.times[0], id_source) != (self.times[-1], id_destination): # # Plot marker #",
"!\") else: t = inter[0] t2 = inter[1] if l in S.links: id_link",
"res = [0 for i in range(len(time_intervals)+ 1)] last_x,last_y = time_intervals[0] b =",
"but ends before for i in range(-2,-len(self.time_intervals)-1,-1): if self.time_intervals[i][1] > end: self.time_intervals[i][1] =",
"add new links to the end of the metawalk b = True if",
"of intervals \"\"\" time_intervals = self.time_intervals[:] time_intervals.append([-1,-1]) res = [0 for i in",
"self.time_intervals = time_intervals self.nodes = nodes def add_link(self, l, t): self.time_intervals.append(t) self.nodes.append(l) def",
"self.nodes = nodes def add_link(self, l, t): self.time_intervals.append(t) self.nodes.append(l) def length(self): return len(self.time_intervals)",
"S, color=\"#18036f\", markersize=10, dag=False, fig=None): \"\"\" Draw a path on the ``StreamGraph`` object",
"= S.nodes.index(self.nodes[-1]) plt.plot([self.time_intervals[-1]], [id_destination], color=color, marker='o', alpha=0.8, markersize=markersize) # Plot Path for i",
":param S: :param color: :param markersize: :param dag: :param fig: :return: \"\"\" if",
"; last node = destination) \"\"\" self.time_intervals = time_intervals self.nodes = nodes def",
"self.__str__() def __eq__(self, m): if m == None: return False if m.length() !=",
"i in range(self.length()): l = (self.nodes[i],self.nodes[i+1]) inter = self.time_intervals[i] l_ = (self.nodes[i+1],self.nodes[i]) #",
"if l in S.links: id_link = S.links.index(l) else: id_link = S.links.index(l_) is_present =",
"markersize=markersize) # else: # plt.plot([t], [id1], color=color, # marker='v', alpha=0.8, markersize=markersize) plt.tight_layout() return",
"last_x and y == last_y and degree > 0: degree += 1 else:",
"(time_intervals[0][1],time_intervals[0][1]) time_intervals[-1] = (time_intervals[-1][0],time_intervals[-1][0]) for i in range(1,len(time_intervals)): if time_intervals[i][0] < time_intervals[0][0]: time_intervals[i]",
"color: :param markersize: :param dag: :param fig: :return: \"\"\" if fig is None:",
"(t <= t2): is_present = True if not is_present: raise ValueError(\"Link : \"",
"n = tuple(self.time_intervals) return hash((m,n)) def __str__(self): s = \"\" for i in",
"(time_intervals[0][0],time_intervals[i][1]) if time_intervals[i][1] > time_intervals[-1][1]: time_intervals[i] = (time_intervals[i][0],time_intervals[-1][1]) return Metawalk(time_intervals,nodes) def first_time(self): return",
"if len(self.time_intervals) == 1: return True x = self.time_intervals[-1] for i in range(-2,-len(self.time_intervals)-1,-1):",
"t2), # right, bottom # ] plt.vlines(t, ymin=idmin, ymax=idmax, linewidth=6, alpha=0.8, color=color) plt.vlines(t2,",
"# # Plot marker # if id1 == idmin: # plt.plot([t], [id1], color=color,",
"self.time_intervals[-1]: return self.clone() else: nodes = self.nodes[:] time_intervals = self.time_intervals[:] time_intervals[0] = (time_intervals[0][1],time_intervals[0][1])",
"= y if b == True: res[0] = 1 res = [np.around(e,decimals=2) for",
"last_x), decimals=2) else: if last_x == last_y: degree = 0 else: degree =",
"\" + str(l) + \" does not exists in the Stream Graph !\")",
"as nppol class Metawalk: def __init__(self, time_intervals=None, nodes=None, ): \"\"\" A basic constructor",
"# if i != 0 and (t, id1) != (self.times[0], id_source) != (self.times[-1],",
"len(self.nodes) -1: if t >= self.time_intervals[-1][1]: return True else: return False else: if",
"l in S.links: id_link = S.links.index(l) else: id_link = S.links.index(l_) is_present = False",
"False elif indice == len(self.nodes) -1: if t >= self.time_intervals[-1][1]: return True else:",
"fst_interval_left_bound = left_bound // interval_size for j in range(1,nb_interval_contributes_to+1): res.append((self.nodes[i+1], fst_interval_left_bound, fst_interval_left_bound +",
"verts = [ # (idmin, t), # left, bottom # (idmax, t), #",
"- 1: plt.hlines(id2, xmin=t, xmax=t2, linewidth=4, alpha=0.8, color=color) plt.hlines(id1, xmin=t, xmax=t2, linewidth=4, alpha=0.8,",
"links to the end of the metawalk b = True if len(self.time_intervals) ==",
"l not in S.links and l_ not in S.links: raise ValueError(\"Link : \"",
"#last edge added ends at same time but starts before self.time_intervals[-1][0] = self.time_intervals[-2][0]",
"= \"\" for i in range(0,self.length()): s += \" \" s += str(self.nodes[i])",
"# left, top # (idmax, t2), # right, top # (idmin, t2), #",
"<= t2 <= lt1) and (t <= t2): is_present = True if not",
"make it work whenvever later on, update : false, [1,2],[1,1] if x ==",
"= end def volume(self): \"\"\"Normally the link are either exactly the same or",
"= 1 res = [np.around(e,decimals=2) for e in res] return nppol.Polynomial(res) def passes_through(self,t,v):",
": A list of couples of floats which represents times corresponding to the",
"last_y: b = False res[1] = np.around((last_y - last_x), decimals=2) else: if last_x",
">= self.time_intervals[-1][1]: return True else: return False else: if t >= self.time_intervals[indice-1][1] and",
"last edge starts at same time but ends before for i in range(-2,-len(self.time_intervals)-1,-1):",
"left_bound // interval_size for j in range(1,nb_interval_contributes_to+1): res.append((self.nodes[i+1], fst_interval_left_bound, fst_interval_left_bound + j *",
"in range(self.length()): l = (self.nodes[i],self.nodes[i+1]) inter = self.time_intervals[i] l_ = (self.nodes[i+1],self.nodes[i]) # Inverse",
"the Stream Graph !\") else: t = inter[0] t2 = inter[1] if l",
"\" s += str(self.time_intervals[i]) s += \" \" s += str(self.nodes[i+1]) s +=",
"True if len(time_intervals)==1: last_x,last_y = time_intervals[0] if last_x != last_y: b = False",
"1)] last_x,last_y = time_intervals[0] b = True if len(time_intervals)==1: last_x,last_y = time_intervals[0] if",
"+ j * interval_size )) fst_interval_left_bound = fst_interval_left_bound + j * interval_size return",
"res def fastest_meta_walk(self): if self.time_intervals[0] == self.time_intervals[-1]: return self.clone() else: nodes = self.nodes[:]",
"inter[1] if l in S.links: id_link = S.links.index(l) else: id_link = S.links.index(l_) is_present",
"str(self.time_intervals[i]) s += \" \" s += str(self.nodes[i+1]) s += \" | volume",
"== None: return False if m.length() != self.length(): return False if (m.nodes ==",
"interval_size fst_interval_left_bound = left_bound // interval_size for j in range(1,nb_interval_contributes_to+1): res.append((self.nodes[i+1], fst_interval_left_bound, fst_interval_left_bound",
"== self.nodes) and (m.time_intervals == self.time_intervals): return True return False def is_instantenous(self): #we",
"i in range(0,len(self.time_intervals)-1): left_bound = self.time_intervals[i][1] right_bound = self.time_intervals[i+1][0] nb_interval_contributes_to = (left_bound -",
"= time_intervals self.nodes = nodes def add_link(self, l, t): self.time_intervals.append(t) self.nodes.append(l) def length(self):",
"+ str(l) + \" does not exists in the Stream Graph !\") else:",
"[] for i in range(0,len(self.time_intervals)-1): left_bound = self.time_intervals[i][1] right_bound = self.time_intervals[i+1][0] nb_interval_contributes_to =",
"l = (self.nodes[i],self.nodes[i+1]) inter = self.time_intervals[i] l_ = (self.nodes[i+1],self.nodes[i]) # Inverse the order",
"== 1: return True x = self.time_intervals[-1] for i in range(-2,-len(self.time_intervals)-1,-1): if self.time_intervals[i]",
"False for lt0, lt1 in zip(S.link_presence[id_link][::2], S.link_presence[id_link][1::2]): if (lt0 <= t <= lt1)",
"later on, update : false, [1,2],[1,1] if x == last_x and y ==",
"True: res[0] = 1 res = [np.around(e,decimals=2) for e in res] return nppol.Polynomial(res)",
"b = True if len(self.time_intervals) == 1: return True x = self.time_intervals[-1] for",
"= self.time_intervals[-1] for i in range(-2,-len(self.time_intervals)-1,-1): if self.time_intervals[i] != x: return False return",
"for inclusion, exclusion of intervals \"\"\" time_intervals = self.time_intervals[:] time_intervals.append([-1,-1]) res = [0",
"fig is None: fig, ax = plt.subplots() else: ax = plt.gca() if dag:",
"xmin=t, xmax=t2, linewidth=4, alpha=0.8, color=color) # Plot marker # if t != self.times[i",
"which represents times corresponding to the time intervals :param links : A list",
"b = True if len(time_intervals)==1: last_x,last_y = time_intervals[0] if last_x != last_y: b",
"for i in range(self.length()): l = (self.nodes[i],self.nodes[i+1]) inter = self.time_intervals[i] l_ = (self.nodes[i+1],self.nodes[i])",
"last_y: b = False x,y = time_intervals[i] #it should be enough to check",
"source ; last node = destination) \"\"\" self.time_intervals = time_intervals self.nodes = nodes",
"self.time_intervals[-1][0] = self.time_intervals[-2][0] else: end = self.time_intervals[-1][1] # last edge starts at same",
"decimals=2) if x != y: degree = 1 last_x = x last_y =",
"nppol class Metawalk: def __init__(self, time_intervals=None, nodes=None, ): \"\"\" A basic constructor for",
"return Metawalk(self.time_intervals[:],self.nodes[:]) def __hash__(self): m = tuple(self.nodes) n = tuple(self.time_intervals) return hash((m,n)) def",
"time_intervals = self.time_intervals[:] time_intervals.append([-1,-1]) res = [0 for i in range(len(time_intervals)+ 1)] last_x,last_y",
"> time_intervals[-1][1]: time_intervals[i] = (time_intervals[i][0],time_intervals[-1][1]) return Metawalk(time_intervals,nodes) def first_time(self): return self.time_intervals[0][0] def last_departure(self):",
"but t2 not return False def add_interval_betweenness(self,t_max,interval_size): res = [] for i in",
"// interval_size for j in range(1,nb_interval_contributes_to+1): res.append((self.nodes[i+1], fst_interval_left_bound, fst_interval_left_bound + j * interval_size",
"S.condensation_dag() dag.plot(node_to_label=S.node_to_label, ax=ax) else: S.plot(ax=ax) # Plot Source id_source = S.nodes.index(self.nodes[0]) plt.plot([self.time_intervals[0]], [id_source],",
"Inverse the order of the interval if l not in S.links and l_",
"else: # plt.plot([t], [id1], color=color, # marker='v', alpha=0.8, markersize=markersize) plt.tight_layout() return fig def",
"t <= lt1) and (lt0 <= t2 <= lt1) and (t <= t2):",
"if b == 0: #last edge added ends at same time but starts",
"= time_intervals[0] b = True if len(time_intervals)==1: last_x,last_y = time_intervals[0] if last_x !=",
"return False if indice == 0: if t < self.time_intervals[0][0]: return True else:",
"marker='>', alpha=0.8, markersize=markersize) # if i != 0 and (t, id1) != (self.times[0],",
"def length(self): return len(self.time_intervals) def duration(self): return self.time_intervals[-1][1] - self.time_intervals[0][0] def clone(self): return",
"volume(self): \"\"\"Normally the link are either exactly the same or disjoint, need to",
"#sometimes when adding a metaedge the metawalk has to be cut at some",
"= self.time_intervals[-1][1] # last edge starts at same time but ends before for",
"return len(self.time_intervals) def duration(self): return self.time_intervals[-1][1] - self.time_intervals[0][0] def clone(self): return Metawalk(self.time_intervals[:],self.nodes[:]) def",
"S.nodes.index(l) id2 = S.nodes.index(l2) idmax = max(id1, id2) idmin = min(id1, id2) #",
"nb_interval_contributes_to = (left_bound - right_bound) // interval_size fst_interval_left_bound = left_bound // interval_size for",
"lt1 in zip(S.link_presence[id_link][::2], S.link_presence[id_link][1::2]): if (lt0 <= t <= lt1) and (lt0 <=",
"i != self.length() - 1: plt.hlines(id2, xmin=t, xmax=t2, linewidth=4, alpha=0.8, color=color) plt.hlines(id1, xmin=t,",
"def passes_through_whole_interval(self,v,t1,t2): return False def passes_through_somewhere_interval(self,v,t1,t2): #t1 included, but t2 not return False",
"Plot Destination id_destination = S.nodes.index(self.nodes[-1]) plt.plot([self.time_intervals[-1]], [id_destination], color=color, marker='o', alpha=0.8, markersize=markersize) # Plot",
"= destination) \"\"\" self.time_intervals = time_intervals self.nodes = nodes def add_link(self, l, t):",
"def add_interval_betweenness(self,t_max,interval_size): res = [] for i in range(0,len(self.time_intervals)-1): left_bound = self.time_intervals[i][1] right_bound",
"Source id_source = S.nodes.index(self.nodes[0]) plt.plot([self.time_intervals[0]], [id_source], color=color, marker='o', alpha=0.8, markersize=markersize) # Plot Destination",
"(idmin, t), # left, bottom # (idmax, t), # left, top # (idmax,",
"fastest_meta_walk(self): if self.time_intervals[0] == self.time_intervals[-1]: return self.clone() else: nodes = self.nodes[:] time_intervals =",
"time_intervals[i] #it should be enough to check one bound no overlap in linkq",
"self.time_intervals[i][1] right_bound = self.time_intervals[i+1][0] nb_interval_contributes_to = (left_bound - right_bound) // interval_size fst_interval_left_bound =",
"s = \"\" for i in range(0,self.length()): s += \" \" s +=",
"t2), # right, top # (idmin, t2), # right, bottom # ] plt.vlines(t,",
"= self.time_intervals[i][1] id1 = S.nodes.index(l) id2 = S.nodes.index(l2) idmax = max(id1, id2) idmin",
"else: return False else: if t >= self.time_intervals[indice-1][1] and t < self.time_intervals[indice][0]: return",
"passes_through_somewhere_interval(self,v,t1,t2): #t1 included, but t2 not return False def add_interval_betweenness(self,t_max,interval_size): res = []",
"<= t <= lt1) and (lt0 <= t2 <= lt1) and (t <=",
"destination) \"\"\" self.time_intervals = time_intervals self.nodes = nodes def add_link(self, l, t): self.time_intervals.append(t)",
"True def update_following_last(self,b): #sometimes when adding a metaedge the metawalk has to be",
"return True else: return False elif indice == len(self.nodes) -1: if t >=",
"self.time_intervals[0][0] def last_departure(self): return self.time_intervals[0][1] def first_arrival(self): return self.time_intervals[-1][0] def first_node(self): return self.nodes[0]",
"t2 = inter[1] if l in S.links: id_link = S.links.index(l) else: id_link =",
"intervals :param links : A list of nodes. (first node = source ;",
"end = self.time_intervals[-1][1] # last edge starts at same time but ends before",
"exactly the same or disjoint, need to check for inclusion, exclusion of intervals",
"b == True: res[0] = 1 res = [np.around(e,decimals=2) for e in res]",
"i in range(self.length()): l = self.nodes[i] l2 = self.nodes[i+1] t = self.time_intervals[i][0] t2",
"t), # left, top # (idmax, t2), # right, top # (idmin, t2),",
"+= \" \" s += str(self.time_intervals[i]) s += \" \" s += str(self.nodes[i+1])",
"last_x == last_y: degree = 0 else: degree = 1 for i in",
"else: return False def passes_through_whole_interval(self,v,t1,t2): return False def passes_through_somewhere_interval(self,v,t1,t2): #t1 included, but t2",
"def first_node(self): return self.nodes[0] def last_node(self): return self.nodes[-1] def plot(self, S, color=\"#18036f\", markersize=10,",
"if fig is None: fig, ax = plt.subplots() else: ax = plt.gca() if",
"def check_coherence(self, S): for i in range(self.length()): l = (self.nodes[i],self.nodes[i+1]) inter = self.time_intervals[i]",
"= \" s += str(self.volume()) return s def __repr__(self): return self.__str__() def __eq__(self,",
"= left_bound // interval_size for j in range(1,nb_interval_contributes_to+1): res.append((self.nodes[i+1], fst_interval_left_bound, fst_interval_left_bound + j",
"if v in self.nodes: indice = self.nodes.index(v) else: return False if indice ==",
"+= str(self.volume()) return s def __repr__(self): return self.__str__() def __eq__(self, m): if m",
"# (idmax, t2), # right, top # (idmin, t2), # right, bottom #",
"= False x,y = time_intervals[i] #it should be enough to check one bound",
"= inter[1] if l in S.links: id_link = S.links.index(l) else: id_link = S.links.index(l_)",
"marker='o', alpha=0.8, markersize=markersize) # Plot Destination id_destination = S.nodes.index(self.nodes[-1]) plt.plot([self.time_intervals[-1]], [id_destination], color=color, marker='o',",
"left, bottom # (idmax, t), # left, top # (idmax, t2), # right,",
"raise ValueError(\"Link : \" + str(l) + \" does not exists in the",
"for i in range(1,len(time_intervals)): if last_x != last_y: b = False x,y =",
"plt.gca() if dag: dag = S.condensation_dag() dag.plot(node_to_label=S.node_to_label, ax=ax) else: S.plot(ax=ax) # Plot Source",
"i in range(-2,-len(self.time_intervals)-1,-1): if self.time_intervals[i][1] > end: self.time_intervals[i][1] = end def volume(self): \"\"\"Normally",
"= np.around((last_y - last_x), decimals=2) else: if last_x == last_y: degree = 0",
"marker='v', alpha=0.8, markersize=markersize) plt.tight_layout() return fig def check_coherence(self, S): for i in range(self.length()):",
"if l not in S.links and l_ not in S.links: raise ValueError(\"Link :",
"!= last_y: b = False res[1] = np.around((last_y - last_x), decimals=2) else: if",
": \" + str(l) + \" does not exists in the Stream Graph",
"j in range(1,nb_interval_contributes_to+1): res.append((self.nodes[i+1], fst_interval_left_bound, fst_interval_left_bound + j * interval_size )) fst_interval_left_bound =",
"False if indice == 0: if t < self.time_intervals[0][0]: return True else: return",
"\" + str(l) + \" does not exists at time \" + str(t)",
"lt1) and (t <= t2): is_present = True if not is_present: raise ValueError(\"Link",
"if dag: dag = S.condensation_dag() dag.plot(node_to_label=S.node_to_label, ax=ax) else: S.plot(ax=ax) # Plot Source id_source",
"couples of floats which represents times corresponding to the time intervals :param links",
"True if not is_present: raise ValueError(\"Link : \" + str(l) + \" does",
"def is_instantenous(self): #we check from the last because of the algirothm that uses",
"== True: res[0] = 1 res = [np.around(e,decimals=2) for e in res] return",
"y: degree = 1 last_x = x last_y = y if b ==",
"if time_intervals[i][0] < time_intervals[0][0]: time_intervals[i] = (time_intervals[0][0],time_intervals[i][1]) if time_intervals[i][1] > time_intervals[-1][1]: time_intervals[i] =",
"__repr__(self): return self.__str__() def __eq__(self, m): if m == None: return False if",
"m.length() != self.length(): return False if (m.nodes == self.nodes) and (m.time_intervals == self.time_intervals):",
"in range(len(time_intervals)+ 1)] last_x,last_y = time_intervals[0] b = True if len(time_intervals)==1: last_x,last_y =",
"S): for i in range(self.length()): l = (self.nodes[i],self.nodes[i+1]) inter = self.time_intervals[i] l_ =",
"= S.nodes.index(l) id2 = S.nodes.index(l2) idmax = max(id1, id2) idmin = min(id1, id2)",
"passes_through(self,t,v): if v in self.nodes: indice = self.nodes.index(v) else: return False if indice",
"= [np.around(e,decimals=2) for e in res] return nppol.Polynomial(res) def passes_through(self,t,v): if v in",
"time_intervals.append([-1,-1]) res = [0 for i in range(len(time_intervals)+ 1)] last_x,last_y = time_intervals[0] b",
"id_destination = S.nodes.index(self.nodes[-1]) plt.plot([self.time_intervals[-1]], [id_destination], color=color, marker='o', alpha=0.8, markersize=markersize) # Plot Path for",
"need to check for inclusion, exclusion of intervals \"\"\" time_intervals = self.time_intervals[:] time_intervals.append([-1,-1])",
"self.clone() else: nodes = self.nodes[:] time_intervals = self.time_intervals[:] time_intervals[0] = (time_intervals[0][1],time_intervals[0][1]) time_intervals[-1] =",
"(self.times[-1], id_destination): # # Plot marker # if id1 == idmin: # plt.plot([t],",
"not is_present: raise ValueError(\"Link : \" + str(l) + \" does not exists",
"0: if t < self.time_intervals[0][0]: return True else: return False elif indice ==",
"len(time_intervals)==1: last_x,last_y = time_intervals[0] if last_x != last_y: b = False res[1] =",
"(idmax, t), # left, top # (idmax, t2), # right, top # (idmin,",
"self.time_intervals[:] time_intervals[0] = (time_intervals[0][1],time_intervals[0][1]) time_intervals[-1] = (time_intervals[-1][0],time_intervals[-1][0]) for i in range(1,len(time_intervals)): if time_intervals[i][0]",
"\"\"\" Draw a path on the ``StreamGraph`` object *S* :param S: :param color:",
"b = False x,y = time_intervals[i] #it should be enough to check one",
"False res[1] = np.around((last_y - last_x), decimals=2) else: if last_x == last_y: degree",
"False def passes_through_somewhere_interval(self,v,t1,t2): #t1 included, but t2 not return False def add_interval_betweenness(self,t_max,interval_size): res",
"and (lt0 <= t2 <= lt1) and (t <= t2): is_present = True",
"``Metwalks`` object :param times : A list of couples of floats which represents",
"list of nodes. (first node = source ; last node = destination) \"\"\"",
"generalise it and make it work whenvever later on, update : false, [1,2],[1,1]",
"= fst_interval_left_bound + j * interval_size return res def fastest_meta_walk(self): if self.time_intervals[0] ==",
"<= lt1) and (t <= t2): is_present = True if not is_present: raise",
"\"\"\" self.time_intervals = time_intervals self.nodes = nodes def add_link(self, l, t): self.time_intervals.append(t) self.nodes.append(l)",
"s += str(self.nodes[i+1]) s += \" | volume = \" s += str(self.volume())",
"!= self.length(): return False if (m.nodes == self.nodes) and (m.time_intervals == self.time_intervals): return",
"for i in range(self.length()): l = self.nodes[i] l2 = self.nodes[i+1] t = self.time_intervals[i][0]",
"last_x)/np.math.factorial(degree), decimals=2) if x != y: degree = 1 last_x = x last_y",
"node = source ; last node = destination) \"\"\" self.time_intervals = time_intervals self.nodes",
":param color: :param markersize: :param dag: :param fig: :return: \"\"\" if fig is",
"Plot Source id_source = S.nodes.index(self.nodes[0]) plt.plot([self.time_intervals[0]], [id_source], color=color, marker='o', alpha=0.8, markersize=markersize) # Plot",
"ValueError(\"Link : \" + str(l) + \" does not exists in the Stream",
"first_node(self): return self.nodes[0] def last_node(self): return self.nodes[-1] def plot(self, S, color=\"#18036f\", markersize=10, dag=False,",
"= S.links.index(l_) is_present = False for lt0, lt1 in zip(S.link_presence[id_link][::2], S.link_presence[id_link][1::2]): if (lt0",
"\"\"\" A basic constructor for a ``Metwalks`` object :param times : A list",
"0: #last edge added ends at same time but starts before self.time_intervals[-1][0] =",
"False if m.length() != self.length(): return False if (m.nodes == self.nodes) and (m.time_intervals",
"\"\"\" if fig is None: fig, ax = plt.subplots() else: ax = plt.gca()",
"len(self.time_intervals) == 1: return True x = self.time_intervals[-1] for i in range(-2,-len(self.time_intervals)-1,-1): if",
"s += \" \" s += str(self.nodes[i]) s += \" \" s +=",
"< self.time_intervals[0][0]: return True else: return False elif indice == len(self.nodes) -1: if",
"time \" + str(t) + \" !\") print(\"Check Path Coherence ok !\") return",
"points because some paths are no longer valid. if b == 0: #last",
"has to be cut at some points because some paths are no longer",
"= S.condensation_dag() dag.plot(node_to_label=S.node_to_label, ax=ax) else: S.plot(ax=ax) # Plot Source id_source = S.nodes.index(self.nodes[0]) plt.plot([self.time_intervals[0]],",
"work whenvever later on, update : false, [1,2],[1,1] if x == last_x and",
"degree += 1 else: res[degree] += np.around((last_y - last_x)/np.math.factorial(degree), decimals=2) if x !=",
"link streams but maybe its ok to generalise it and make it work",
"interval if l not in S.links and l_ not in S.links: raise ValueError(\"Link",
"\" does not exists in the Stream Graph !\") else: t = inter[0]",
"self.time_intervals[i] != x: return False return True def update_following_last(self,b): #sometimes when adding a",
"time_intervals = self.time_intervals[:] time_intervals[0] = (time_intervals[0][1],time_intervals[0][1]) time_intervals[-1] = (time_intervals[-1][0],time_intervals[-1][0]) for i in range(1,len(time_intervals)):",
"for i in range(0,self.length()): s += \" \" s += str(self.nodes[i]) s +=",
"Graph !\") else: t = inter[0] t2 = inter[1] if l in S.links:",
"False if (m.nodes == self.nodes) and (m.time_intervals == self.time_intervals): return True return False",
"else: id_link = S.links.index(l_) is_present = False for lt0, lt1 in zip(S.link_presence[id_link][::2], S.link_presence[id_link][1::2]):",
"#t1 included, but t2 not return False def add_interval_betweenness(self,t_max,interval_size): res = [] for",
"s += \" \" s += str(self.time_intervals[i]) s += \" \" s +=",
": A list of nodes. (first node = source ; last node =",
"plt.plot([t], [id1], color=color, # marker='v', alpha=0.8, markersize=markersize) plt.tight_layout() return fig def check_coherence(self, S):",
"t < self.time_intervals[indice][0]: return True else: return False def passes_through_whole_interval(self,v,t1,t2): return False def",
":param links : A list of nodes. (first node = source ; last",
"edge added ends at same time but starts before self.time_intervals[-1][0] = self.time_intervals[-2][0] else:",
"return self.nodes[0] def last_node(self): return self.nodes[-1] def plot(self, S, color=\"#18036f\", markersize=10, dag=False, fig=None):",
"nodes def add_link(self, l, t): self.time_intervals.append(t) self.nodes.append(l) def length(self): return len(self.time_intervals) def duration(self):",
"at some points because some paths are no longer valid. if b ==",
"time_intervals[i][1] > time_intervals[-1][1]: time_intervals[i] = (time_intervals[i][0],time_intervals[-1][1]) return Metawalk(time_intervals,nodes) def first_time(self): return self.time_intervals[0][0] def",
": false, [1,2],[1,1] if x == last_x and y == last_y and degree",
"in range(1,len(time_intervals)): if time_intervals[i][0] < time_intervals[0][0]: time_intervals[i] = (time_intervals[0][0],time_intervals[i][1]) if time_intervals[i][1] > time_intervals[-1][1]:",
"alpha=0.8, color=color) if i != self.length() - 1: plt.hlines(id2, xmin=t, xmax=t2, linewidth=4, alpha=0.8,",
"t >= self.time_intervals[indice-1][1] and t < self.time_intervals[indice][0]: return True else: return False def",
"and degree > 0: degree += 1 else: res[degree] += np.around((last_y - last_x)/np.math.factorial(degree),",
"i in range(1,len(time_intervals)): if time_intervals[i][0] < time_intervals[0][0]: time_intervals[i] = (time_intervals[0][0],time_intervals[i][1]) if time_intervals[i][1] >",
"self.time_intervals[0][0]: return True else: return False elif indice == len(self.nodes) -1: if t",
"else: if t >= self.time_intervals[indice-1][1] and t < self.time_intervals[indice][0]: return True else: return",
"def last_node(self): return self.nodes[-1] def plot(self, S, color=\"#18036f\", markersize=10, dag=False, fig=None): \"\"\" Draw",
"intervals \"\"\" time_intervals = self.time_intervals[:] time_intervals.append([-1,-1]) res = [0 for i in range(len(time_intervals)+",
"marker='^', alpha=0.8, markersize=markersize) # else: # plt.plot([t], [id1], color=color, # marker='v', alpha=0.8, markersize=markersize)",
"return self.nodes[-1] def plot(self, S, color=\"#18036f\", markersize=10, dag=False, fig=None): \"\"\" Draw a path",
"| volume = \" s += str(self.volume()) return s def __repr__(self): return self.__str__()",
"ax = plt.gca() if dag: dag = S.condensation_dag() dag.plot(node_to_label=S.node_to_label, ax=ax) else: S.plot(ax=ax) #",
"= False for lt0, lt1 in zip(S.link_presence[id_link][::2], S.link_presence[id_link][1::2]): if (lt0 <= t <=",
"range(self.length()): l = self.nodes[i] l2 = self.nodes[i+1] t = self.time_intervals[i][0] t2 = self.time_intervals[i][1]",
"to be cut at some points because some paths are no longer valid.",
"# marker='>', alpha=0.8, markersize=markersize) # if i != 0 and (t, id1) !=",
"<= lt1) and (lt0 <= t2 <= lt1) and (t <= t2): is_present",
"return True def update_following_last(self,b): #sometimes when adding a metaedge the metawalk has to",
"if last_x != last_y: b = False res[1] = np.around((last_y - last_x), decimals=2)",
"alpha=0.8, color=color) plt.vlines(t2, ymin=idmin, ymax=idmax, linewidth=6, alpha=0.8, color=color) if i != self.length() -",
"xmax=t2, linewidth=4, alpha=0.8, color=color) # Plot marker # if t != self.times[i +",
"str(l) + \" does not exists at time \" + str(t) + \"",
"\" does not exists at time \" + str(t) + \" !\") print(\"Check",
"y if b == True: res[0] = 1 res = [np.around(e,decimals=2) for e",
"def fastest_meta_walk(self): if self.time_intervals[0] == self.time_intervals[-1]: return self.clone() else: nodes = self.nodes[:] time_intervals",
"paths are no longer valid. if b == 0: #last edge added ends",
"__eq__(self, m): if m == None: return False if m.length() != self.length(): return",
"None: return False if m.length() != self.length(): return False if (m.nodes == self.nodes)",
"x: return False return True def update_following_last(self,b): #sometimes when adding a metaedge the",
"= (time_intervals[-1][0],time_intervals[-1][0]) for i in range(1,len(time_intervals)): if time_intervals[i][0] < time_intervals[0][0]: time_intervals[i] = (time_intervals[0][0],time_intervals[i][1])",
"self.nodes[i] l2 = self.nodes[i+1] t = self.time_intervals[i][0] t2 = self.time_intervals[i][1] id1 = S.nodes.index(l)",
"id_source) != (self.times[-1], id_destination): # # Plot marker # if id1 == idmin:",
"the interval if l not in S.links and l_ not in S.links: raise",
"plt.vlines(t, ymin=idmin, ymax=idmax, linewidth=6, alpha=0.8, color=color) plt.vlines(t2, ymin=idmin, ymax=idmax, linewidth=6, alpha=0.8, color=color) if",
"is_present: raise ValueError(\"Link : \" + str(l) + \" does not exists at",
"self.time_intervals[-1][0] def first_node(self): return self.nodes[0] def last_node(self): return self.nodes[-1] def plot(self, S, color=\"#18036f\",",
"t2 = self.time_intervals[i][1] id1 = S.nodes.index(l) id2 = S.nodes.index(l2) idmax = max(id1, id2)",
"S.links: id_link = S.links.index(l) else: id_link = S.links.index(l_) is_present = False for lt0,",
"return fig def check_coherence(self, S): for i in range(self.length()): l = (self.nodes[i],self.nodes[i+1]) inter",
"inclusion, exclusion of intervals \"\"\" time_intervals = self.time_intervals[:] time_intervals.append([-1,-1]) res = [0 for",
"1: plt.hlines(id2, xmin=t, xmax=t2, linewidth=4, alpha=0.8, color=color) plt.hlines(id1, xmin=t, xmax=t2, linewidth=4, alpha=0.8, color=color)",
"but starts before self.time_intervals[-1][0] = self.time_intervals[-2][0] else: end = self.time_intervals[-1][1] # last edge",
"== 0: if t < self.time_intervals[0][0]: return True else: return False elif indice",
"return False if (m.nodes == self.nodes) and (m.time_intervals == self.time_intervals): return True return",
"= source ; last node = destination) \"\"\" self.time_intervals = time_intervals self.nodes =",
"self.time_intervals[0][0] def clone(self): return Metawalk(self.time_intervals[:],self.nodes[:]) def __hash__(self): m = tuple(self.nodes) n = tuple(self.time_intervals)",
"not in S.links and l_ not in S.links: raise ValueError(\"Link : \" +",
"+ \" does not exists in the Stream Graph !\") else: t =",
"== self.time_intervals[-1]: return self.clone() else: nodes = self.nodes[:] time_intervals = self.time_intervals[:] time_intervals[0] =",
"- right_bound) // interval_size fst_interval_left_bound = left_bound // interval_size for j in range(1,nb_interval_contributes_to+1):",
"the order of the interval if l not in S.links and l_ not",
"if len(time_intervals)==1: last_x,last_y = time_intervals[0] if last_x != last_y: b = False res[1]",
"\" \" s += str(self.time_intervals[i]) s += \" \" s += str(self.nodes[i+1]) s",
"): \"\"\" A basic constructor for a ``Metwalks`` object :param times : A",
"\" | volume = \" s += str(self.volume()) return s def __repr__(self): return",
"plt.plot([t], [id2], color=color, # marker='>', alpha=0.8, markersize=markersize) # if i != 0 and",
"id_link = S.links.index(l_) is_present = False for lt0, lt1 in zip(S.link_presence[id_link][::2], S.link_presence[id_link][1::2]): if",
"\" \" s += str(self.nodes[i+1]) s += \" | volume = \" s",
"last node = destination) \"\"\" self.time_intervals = time_intervals self.nodes = nodes def add_link(self,",
"plt.plot([t], [id1], color=color, # marker='^', alpha=0.8, markersize=markersize) # else: # plt.plot([t], [id1], color=color,",
":param dag: :param fig: :return: \"\"\" if fig is None: fig, ax =",
"in zip(S.link_presence[id_link][::2], S.link_presence[id_link][1::2]): if (lt0 <= t <= lt1) and (lt0 <= t2",
"nodes=None, ): \"\"\" A basic constructor for a ``Metwalks`` object :param times :",
":param markersize: :param dag: :param fig: :return: \"\"\" if fig is None: fig,",
"dag = S.condensation_dag() dag.plot(node_to_label=S.node_to_label, ax=ax) else: S.plot(ax=ax) # Plot Source id_source = S.nodes.index(self.nodes[0])",
"else: if last_x == last_y: degree = 0 else: degree = 1 for",
"time_intervals[0] if last_x != last_y: b = False res[1] = np.around((last_y - last_x),",
"alpha=0.8, color=color) plt.hlines(id1, xmin=t, xmax=t2, linewidth=4, alpha=0.8, color=color) # Plot marker # if",
"alpha=0.8, markersize=markersize) # else: # plt.plot([t], [id1], color=color, # marker='v', alpha=0.8, markersize=markersize) plt.tight_layout()",
"indice == len(self.nodes) -1: if t >= self.time_intervals[-1][1]: return True else: return False",
"if i != self.length() - 1: plt.hlines(id2, xmin=t, xmax=t2, linewidth=4, alpha=0.8, color=color) plt.hlines(id1,",
"marker='o', alpha=0.8, markersize=markersize) # Plot Path for i in range(self.length()): l = self.nodes[i]",
"t2): is_present = True if not is_present: raise ValueError(\"Link : \" + str(l)",
"at same time but ends before for i in range(-2,-len(self.time_intervals)-1,-1): if self.time_intervals[i][1] >",
"ymax=idmax, linewidth=6, alpha=0.8, color=color) plt.vlines(t2, ymin=idmin, ymax=idmax, linewidth=6, alpha=0.8, color=color) if i !=",
"x last_y = y if b == True: res[0] = 1 res =",
"tuple(self.nodes) n = tuple(self.time_intervals) return hash((m,n)) def __str__(self): s = \"\" for i",
"res = [np.around(e,decimals=2) for e in res] return nppol.Polynomial(res) def passes_through(self,t,v): if v",
"basic constructor for a ``Metwalks`` object :param times : A list of couples",
"time_intervals[0] b = True if len(time_intervals)==1: last_x,last_y = time_intervals[0] if last_x != last_y:",
"fst_interval_left_bound + j * interval_size )) fst_interval_left_bound = fst_interval_left_bound + j * interval_size",
"__init__(self, time_intervals=None, nodes=None, ): \"\"\" A basic constructor for a ``Metwalks`` object :param",
"# plt.plot([t], [id1], color=color, # marker='v', alpha=0.8, markersize=markersize) plt.tight_layout() return fig def check_coherence(self,",
"xmax=t2, linewidth=4, alpha=0.8, color=color) plt.hlines(id1, xmin=t, xmax=t2, linewidth=4, alpha=0.8, color=color) # Plot marker",
"[0 for i in range(len(time_intervals)+ 1)] last_x,last_y = time_intervals[0] b = True if",
"Destination id_destination = S.nodes.index(self.nodes[-1]) plt.plot([self.time_intervals[-1]], [id_destination], color=color, marker='o', alpha=0.8, markersize=markersize) # Plot Path",
"of the interval if l not in S.links and l_ not in S.links:",
"bound no overlap in linkq in fragmented link streams but maybe its ok",
"self.time_intervals[0] == self.time_intervals[-1]: return self.clone() else: nodes = self.nodes[:] time_intervals = self.time_intervals[:] time_intervals[0]",
"markersize=markersize) # Plot Path for i in range(self.length()): l = self.nodes[i] l2 =",
"floats which represents times corresponding to the time intervals :param links : A",
"(idmin, t2), # right, bottom # ] plt.vlines(t, ymin=idmin, ymax=idmax, linewidth=6, alpha=0.8, color=color)",
"max(id1, id2) idmin = min(id1, id2) # verts = [ # (idmin, t),",
"markersize=markersize) # Plot Destination id_destination = S.nodes.index(self.nodes[-1]) plt.plot([self.time_intervals[-1]], [id_destination], color=color, marker='o', alpha=0.8, markersize=markersize)",
"0 and (t, id1) != (self.times[0], id_source) != (self.times[-1], id_destination): # # Plot",
"right_bound) // interval_size fst_interval_left_bound = left_bound // interval_size for j in range(1,nb_interval_contributes_to+1): res.append((self.nodes[i+1],",
"def __init__(self, time_intervals=None, nodes=None, ): \"\"\" A basic constructor for a ``Metwalks`` object",
"+= 1 else: res[degree] += np.around((last_y - last_x)/np.math.factorial(degree), decimals=2) if x != y:",
"degree = 1 last_x = x last_y = y if b == True:",
"from the last because of the algirothm that uses it add new links",
"the metawalk b = True if len(self.time_intervals) == 1: return True x =",
"- last_x), decimals=2) else: if last_x == last_y: degree = 0 else: degree",
"time_intervals=None, nodes=None, ): \"\"\" A basic constructor for a ``Metwalks`` object :param times",
"self.time_intervals[indice][0]: return True else: return False def passes_through_whole_interval(self,v,t1,t2): return False def passes_through_somewhere_interval(self,v,t1,t2): #t1",
"len(self.time_intervals) def duration(self): return self.time_intervals[-1][1] - self.time_intervals[0][0] def clone(self): return Metawalk(self.time_intervals[:],self.nodes[:]) def __hash__(self):",
"right_bound = self.time_intervals[i+1][0] nb_interval_contributes_to = (left_bound - right_bound) // interval_size fst_interval_left_bound = left_bound",
"in the Stream Graph !\") else: t = inter[0] t2 = inter[1] if",
"degree = 0 else: degree = 1 for i in range(1,len(time_intervals)): if last_x",
"id2 = S.nodes.index(l2) idmax = max(id1, id2) idmin = min(id1, id2) # verts",
"return hash((m,n)) def __str__(self): s = \"\" for i in range(0,self.length()): s +=",
"add_interval_betweenness(self,t_max,interval_size): res = [] for i in range(0,len(self.time_intervals)-1): left_bound = self.time_intervals[i][1] right_bound =",
"# Plot Path for i in range(self.length()): l = self.nodes[i] l2 = self.nodes[i+1]",
"(self.times[0], id_source) != (self.times[-1], id_destination): # # Plot marker # if id1 ==",
"no longer valid. if b == 0: #last edge added ends at same",
"to check one bound no overlap in linkq in fragmented link streams but",
"# last edge starts at same time but ends before for i in",
"!= y: degree = 1 last_x = x last_y = y if b",
"!= (self.times[-1], id_destination): # # Plot marker # if id1 == idmin: #",
"check from the last because of the algirothm that uses it add new",
"fst_interval_left_bound = fst_interval_left_bound + j * interval_size return res def fastest_meta_walk(self): if self.time_intervals[0]",
"< self.time_intervals[indice][0]: return True else: return False def passes_through_whole_interval(self,v,t1,t2): return False def passes_through_somewhere_interval(self,v,t1,t2):",
"no overlap in linkq in fragmented link streams but maybe its ok to",
"y == last_y and degree > 0: degree += 1 else: res[degree] +=",
"Metawalk(time_intervals,nodes) def first_time(self): return self.time_intervals[0][0] def last_departure(self): return self.time_intervals[0][1] def first_arrival(self): return self.time_intervals[-1][0]",
"range(self.length()): l = (self.nodes[i],self.nodes[i+1]) inter = self.time_intervals[i] l_ = (self.nodes[i+1],self.nodes[i]) # Inverse the",
"return False def passes_through_whole_interval(self,v,t1,t2): return False def passes_through_somewhere_interval(self,v,t1,t2): #t1 included, but t2 not",
"is_instantenous(self): #we check from the last because of the algirothm that uses it",
"left, top # (idmax, t2), # right, top # (idmin, t2), # right,",
"def first_time(self): return self.time_intervals[0][0] def last_departure(self): return self.time_intervals[0][1] def first_arrival(self): return self.time_intervals[-1][0] def",
"+= \" \" s += str(self.nodes[i]) s += \" \" s += str(self.time_intervals[i])",
"def plot(self, S, color=\"#18036f\", markersize=10, dag=False, fig=None): \"\"\" Draw a path on the",
"as np import numpy.polynomial.polynomial as nppol class Metawalk: def __init__(self, time_intervals=None, nodes=None, ):",
"return self.__str__() def __eq__(self, m): if m == None: return False if m.length()",
"dag.plot(node_to_label=S.node_to_label, ax=ax) else: S.plot(ax=ax) # Plot Source id_source = S.nodes.index(self.nodes[0]) plt.plot([self.time_intervals[0]], [id_source], color=color,",
"Plot marker # if t != self.times[i + 1]: # plt.plot([t], [id2], color=color,",
"self.time_intervals[-1][1] # last edge starts at same time but ends before for i",
"S.plot(ax=ax) # Plot Source id_source = S.nodes.index(self.nodes[0]) plt.plot([self.time_intervals[0]], [id_source], color=color, marker='o', alpha=0.8, markersize=markersize)",
"if t != self.times[i + 1]: # plt.plot([t], [id2], color=color, # marker='>', alpha=0.8,",
"+= \" \" s += str(self.nodes[i+1]) s += \" | volume = \"",
"idmin = min(id1, id2) # verts = [ # (idmin, t), # left,",
"times corresponding to the time intervals :param links : A list of nodes.",
"return True else: return False def passes_through_whole_interval(self,v,t1,t2): return False def passes_through_somewhere_interval(self,v,t1,t2): #t1 included,",
"t = inter[0] t2 = inter[1] if l in S.links: id_link = S.links.index(l)",
"b == 0: #last edge added ends at same time but starts before",
"[id1], color=color, # marker='^', alpha=0.8, markersize=markersize) # else: # plt.plot([t], [id1], color=color, #",
"should be enough to check one bound no overlap in linkq in fragmented",
"import matplotlib.pyplot as plt import numpy as np import numpy.polynomial.polynomial as nppol class",
"1 res = [np.around(e,decimals=2) for e in res] return nppol.Polynomial(res) def passes_through(self,t,v): if",
"maybe its ok to generalise it and make it work whenvever later on,",
"the ``StreamGraph`` object *S* :param S: :param color: :param markersize: :param dag: :param",
"right, bottom # ] plt.vlines(t, ymin=idmin, ymax=idmax, linewidth=6, alpha=0.8, color=color) plt.vlines(t2, ymin=idmin, ymax=idmax,",
"\"\"\"Normally the link are either exactly the same or disjoint, need to check",
")) fst_interval_left_bound = fst_interval_left_bound + j * interval_size return res def fastest_meta_walk(self): if",
"streams but maybe its ok to generalise it and make it work whenvever",
"last_y: degree = 0 else: degree = 1 for i in range(1,len(time_intervals)): if",
"self.time_intervals[-1] for i in range(-2,-len(self.time_intervals)-1,-1): if self.time_intervals[i] != x: return False return True",
"starts before self.time_intervals[-1][0] = self.time_intervals[-2][0] else: end = self.time_intervals[-1][1] # last edge starts",
"tuple(self.time_intervals) return hash((m,n)) def __str__(self): s = \"\" for i in range(0,self.length()): s",
"interval_size return res def fastest_meta_walk(self): if self.time_intervals[0] == self.time_intervals[-1]: return self.clone() else: nodes",
"= self.nodes[:] time_intervals = self.time_intervals[:] time_intervals[0] = (time_intervals[0][1],time_intervals[0][1]) time_intervals[-1] = (time_intervals[-1][0],time_intervals[-1][0]) for i",
"# Plot Destination id_destination = S.nodes.index(self.nodes[-1]) plt.plot([self.time_intervals[-1]], [id_destination], color=color, marker='o', alpha=0.8, markersize=markersize) #",
"return Metawalk(time_intervals,nodes) def first_time(self): return self.time_intervals[0][0] def last_departure(self): return self.time_intervals[0][1] def first_arrival(self): return",
"color=color, # marker='^', alpha=0.8, markersize=markersize) # else: # plt.plot([t], [id1], color=color, # marker='v',",
"markersize=markersize) # if i != 0 and (t, id1) != (self.times[0], id_source) !=",
"= time_intervals[i] #it should be enough to check one bound no overlap in",
"same time but starts before self.time_intervals[-1][0] = self.time_intervals[-2][0] else: end = self.time_intervals[-1][1] #",
"+ 1]: # plt.plot([t], [id2], color=color, # marker='>', alpha=0.8, markersize=markersize) # if i",
"before for i in range(-2,-len(self.time_intervals)-1,-1): if self.time_intervals[i][1] > end: self.time_intervals[i][1] = end def",
"is_present = True if not is_present: raise ValueError(\"Link : \" + str(l) +",
"markersize=10, dag=False, fig=None): \"\"\" Draw a path on the ``StreamGraph`` object *S* :param",
"return False else: if t >= self.time_intervals[indice-1][1] and t < self.time_intervals[indice][0]: return True",
"return self.clone() else: nodes = self.nodes[:] time_intervals = self.time_intervals[:] time_intervals[0] = (time_intervals[0][1],time_intervals[0][1]) time_intervals[-1]",
"!= (self.times[0], id_source) != (self.times[-1], id_destination): # # Plot marker # if id1",
"the same or disjoint, need to check for inclusion, exclusion of intervals \"\"\"",
"import numpy.polynomial.polynomial as nppol class Metawalk: def __init__(self, time_intervals=None, nodes=None, ): \"\"\" A",
"return nppol.Polynomial(res) def passes_through(self,t,v): if v in self.nodes: indice = self.nodes.index(v) else: return",
"in linkq in fragmented link streams but maybe its ok to generalise it",
"(time_intervals[i][0],time_intervals[-1][1]) return Metawalk(time_intervals,nodes) def first_time(self): return self.time_intervals[0][0] def last_departure(self): return self.time_intervals[0][1] def first_arrival(self):",
"i in range(1,len(time_intervals)): if last_x != last_y: b = False x,y = time_intervals[i]",
"linkq in fragmented link streams but maybe its ok to generalise it and",
"time_intervals[i] = (time_intervals[i][0],time_intervals[-1][1]) return Metawalk(time_intervals,nodes) def first_time(self): return self.time_intervals[0][0] def last_departure(self): return self.time_intervals[0][1]",
"x != y: degree = 1 last_x = x last_y = y if",
"if m == None: return False if m.length() != self.length(): return False if",
"be enough to check one bound no overlap in linkq in fragmented link",
"return True return False def is_instantenous(self): #we check from the last because of",
"fig, ax = plt.subplots() else: ax = plt.gca() if dag: dag = S.condensation_dag()",
"ax=ax) else: S.plot(ax=ax) # Plot Source id_source = S.nodes.index(self.nodes[0]) plt.plot([self.time_intervals[0]], [id_source], color=color, marker='o',",
"in S.links: id_link = S.links.index(l) else: id_link = S.links.index(l_) is_present = False for",
"S.links.index(l_) is_present = False for lt0, lt1 in zip(S.link_presence[id_link][::2], S.link_presence[id_link][1::2]): if (lt0 <=",
"= max(id1, id2) idmin = min(id1, id2) # verts = [ # (idmin,",
"def __repr__(self): return self.__str__() def __eq__(self, m): if m == None: return False",
"metawalk b = True if len(self.time_intervals) == 1: return True x = self.time_intervals[-1]",
"to check for inclusion, exclusion of intervals \"\"\" time_intervals = self.time_intervals[:] time_intervals.append([-1,-1]) res",
"def passes_through(self,t,v): if v in self.nodes: indice = self.nodes.index(v) else: return False if",
"time but ends before for i in range(-2,-len(self.time_intervals)-1,-1): if self.time_intervals[i][1] > end: self.time_intervals[i][1]",
"first_time(self): return self.time_intervals[0][0] def last_departure(self): return self.time_intervals[0][1] def first_arrival(self): return self.time_intervals[-1][0] def first_node(self):",
"a path on the ``StreamGraph`` object *S* :param S: :param color: :param markersize:",
"= [ # (idmin, t), # left, bottom # (idmax, t), # left,",
"linewidth=4, alpha=0.8, color=color) plt.hlines(id1, xmin=t, xmax=t2, linewidth=4, alpha=0.8, color=color) # Plot marker #",
"# plt.plot([t], [id2], color=color, # marker='>', alpha=0.8, markersize=markersize) # if i != 0",
"the last because of the algirothm that uses it add new links to",
"i in range(-2,-len(self.time_intervals)-1,-1): if self.time_intervals[i] != x: return False return True def update_following_last(self,b):",
"s += str(self.time_intervals[i]) s += \" \" s += str(self.nodes[i+1]) s += \"",
"lt1) and (lt0 <= t2 <= lt1) and (t <= t2): is_present =",
"color=color, marker='o', alpha=0.8, markersize=markersize) # Plot Path for i in range(self.length()): l =",
"== last_x and y == last_y and degree > 0: degree += 1",
"ymax=idmax, linewidth=6, alpha=0.8, color=color) if i != self.length() - 1: plt.hlines(id2, xmin=t, xmax=t2,",
"for i in range(-2,-len(self.time_intervals)-1,-1): if self.time_intervals[i][1] > end: self.time_intervals[i][1] = end def volume(self):",
"same or disjoint, need to check for inclusion, exclusion of intervals \"\"\" time_intervals",
"= tuple(self.nodes) n = tuple(self.time_intervals) return hash((m,n)) def __str__(self): s = \"\" for",
"res.append((self.nodes[i+1], fst_interval_left_bound, fst_interval_left_bound + j * interval_size )) fst_interval_left_bound = fst_interval_left_bound + j",
"last because of the algirothm that uses it add new links to the",
"S: :param color: :param markersize: :param dag: :param fig: :return: \"\"\" if fig",
"= True if not is_present: raise ValueError(\"Link : \" + str(l) + \"",
"it add new links to the end of the metawalk b = True",
"for i in range(1,len(time_intervals)): if time_intervals[i][0] < time_intervals[0][0]: time_intervals[i] = (time_intervals[0][0],time_intervals[i][1]) if time_intervals[i][1]",
"self.time_intervals[i][1] id1 = S.nodes.index(l) id2 = S.nodes.index(l2) idmax = max(id1, id2) idmin =",
"linewidth=6, alpha=0.8, color=color) if i != self.length() - 1: plt.hlines(id2, xmin=t, xmax=t2, linewidth=4,",
"(self.nodes[i],self.nodes[i+1]) inter = self.time_intervals[i] l_ = (self.nodes[i+1],self.nodes[i]) # Inverse the order of the",
"import numpy as np import numpy.polynomial.polynomial as nppol class Metawalk: def __init__(self, time_intervals=None,",
"if not is_present: raise ValueError(\"Link : \" + str(l) + \" does not",
"if (m.nodes == self.nodes) and (m.time_intervals == self.time_intervals): return True return False def",
"it work whenvever later on, update : false, [1,2],[1,1] if x == last_x",
"fig=None): \"\"\" Draw a path on the ``StreamGraph`` object *S* :param S: :param",
"!= 0 and (t, id1) != (self.times[0], id_source) != (self.times[-1], id_destination): # #"
] |
[
"import receiver from myauth import models as myauth_models from products.models import Book class",
"from django.db import models from django.core.validators import MaxValueValidator, MinValueValidator from django.db.models.signals import post_delete",
"myauth_models from products.models import Book class CommentProducts(models.Model): profile = models.ForeignKey( myauth_models.Profile, on_delete=models.PROTECT, related_name='comments'",
") stars = models.IntegerField( validators=[ MinValueValidator(0), MaxValueValidator(5)] ) def __str__(self): return f'Комментарий №{self.pk},",
"from django.core.validators import MaxValueValidator, MinValueValidator from django.db.models.signals import post_delete from django.dispatch import receiver",
"return f'Комментарий №{self.pk}, пользователя: {self.profile}, к книге: {self.book}' class Meta: verbose_name = 'Комментарий'",
"Book class CommentProducts(models.Model): profile = models.ForeignKey( myauth_models.Profile, on_delete=models.PROTECT, related_name='comments' ) book = models.ForeignKey(",
"MaxValueValidator(5)] ) def __str__(self): return f'Комментарий №{self.pk}, пользователя: {self.profile}, к книге: {self.book}' class",
") comment = models.TextField( verbose_name='Комментарий', default='', blank=True, null=True ) date_add = models.DateTimeField( auto_now=False,",
"on_delete=models.PROTECT, related_name='comments' ) book = models.ForeignKey( Book, on_delete=models.PROTECT, related_name='comments' ) comment = models.TextField(",
"{self.book}' class Meta: verbose_name = 'Комментарий' verbose_name_plural = 'Комментарии' @receiver(post_delete, sender=CommentProducts) def post_delete_review(sender,",
"Meta: verbose_name = 'Комментарий' verbose_name_plural = 'Комментарии' @receiver(post_delete, sender=CommentProducts) def post_delete_review(sender, instance, **kwargs):",
"verbose_name='Дата последнего изменения карточки' ) stars = models.IntegerField( validators=[ MinValueValidator(0), MaxValueValidator(5)] ) def",
"= models.DateTimeField( auto_now=True, auto_now_add=False, verbose_name='Дата последнего изменения карточки' ) stars = models.IntegerField( validators=[",
"CommentProducts(models.Model): profile = models.ForeignKey( myauth_models.Profile, on_delete=models.PROTECT, related_name='comments' ) book = models.ForeignKey( Book, on_delete=models.PROTECT,",
"receiver from myauth import models as myauth_models from products.models import Book class CommentProducts(models.Model):",
"django.db import models from django.core.validators import MaxValueValidator, MinValueValidator from django.db.models.signals import post_delete from",
"from products.models import Book class CommentProducts(models.Model): profile = models.ForeignKey( myauth_models.Profile, on_delete=models.PROTECT, related_name='comments' )",
"models.ForeignKey( myauth_models.Profile, on_delete=models.PROTECT, related_name='comments' ) book = models.ForeignKey( Book, on_delete=models.PROTECT, related_name='comments' ) comment",
") date_last_change = models.DateTimeField( auto_now=True, auto_now_add=False, verbose_name='Дата последнего изменения карточки' ) stars =",
"= 'Комментарий' verbose_name_plural = 'Комментарии' @receiver(post_delete, sender=CommentProducts) def post_delete_review(sender, instance, **kwargs): avr =",
"'Комментарий' verbose_name_plural = 'Комментарии' @receiver(post_delete, sender=CommentProducts) def post_delete_review(sender, instance, **kwargs): avr = instance.book.get_rating()",
"import models as myauth_models from products.models import Book class CommentProducts(models.Model): profile = models.ForeignKey(",
"verbose_name='Комментарий', default='', blank=True, null=True ) date_add = models.DateTimeField( auto_now=False, auto_now_add=True, verbose_name='Дата внесения в",
"import post_delete from django.dispatch import receiver from myauth import models as myauth_models from",
"import models from django.core.validators import MaxValueValidator, MinValueValidator from django.db.models.signals import post_delete from django.dispatch",
"stars = models.IntegerField( validators=[ MinValueValidator(0), MaxValueValidator(5)] ) def __str__(self): return f'Комментарий №{self.pk}, пользователя:",
"django.dispatch import receiver from myauth import models as myauth_models from products.models import Book",
"class Meta: verbose_name = 'Комментарий' verbose_name_plural = 'Комментарии' @receiver(post_delete, sender=CommentProducts) def post_delete_review(sender, instance,",
"изменения карточки' ) stars = models.IntegerField( validators=[ MinValueValidator(0), MaxValueValidator(5)] ) def __str__(self): return",
"auto_now=False, auto_now_add=True, verbose_name='Дата внесения в каталог' ) date_last_change = models.DateTimeField( auto_now=True, auto_now_add=False, verbose_name='Дата",
"from django.dispatch import receiver from myauth import models as myauth_models from products.models import",
") def __str__(self): return f'Комментарий №{self.pk}, пользователя: {self.profile}, к книге: {self.book}' class Meta:",
"date_add = models.DateTimeField( auto_now=False, auto_now_add=True, verbose_name='Дата внесения в каталог' ) date_last_change = models.DateTimeField(",
"class CommentProducts(models.Model): profile = models.ForeignKey( myauth_models.Profile, on_delete=models.PROTECT, related_name='comments' ) book = models.ForeignKey( Book,",
"в каталог' ) date_last_change = models.DateTimeField( auto_now=True, auto_now_add=False, verbose_name='Дата последнего изменения карточки' )",
"карточки' ) stars = models.IntegerField( validators=[ MinValueValidator(0), MaxValueValidator(5)] ) def __str__(self): return f'Комментарий",
"django.db.models.signals import post_delete from django.dispatch import receiver from myauth import models as myauth_models",
"as myauth_models from products.models import Book class CommentProducts(models.Model): profile = models.ForeignKey( myauth_models.Profile, on_delete=models.PROTECT,",
"auto_now_add=True, verbose_name='Дата внесения в каталог' ) date_last_change = models.DateTimeField( auto_now=True, auto_now_add=False, verbose_name='Дата последнего",
"verbose_name_plural = 'Комментарии' @receiver(post_delete, sender=CommentProducts) def post_delete_review(sender, instance, **kwargs): avr = instance.book.get_rating() instance.book.avr_rating",
"Book, on_delete=models.PROTECT, related_name='comments' ) comment = models.TextField( verbose_name='Комментарий', default='', blank=True, null=True ) date_add",
"models from django.core.validators import MaxValueValidator, MinValueValidator from django.db.models.signals import post_delete from django.dispatch import",
"= models.ForeignKey( myauth_models.Profile, on_delete=models.PROTECT, related_name='comments' ) book = models.ForeignKey( Book, on_delete=models.PROTECT, related_name='comments' )",
"import Book class CommentProducts(models.Model): profile = models.ForeignKey( myauth_models.Profile, on_delete=models.PROTECT, related_name='comments' ) book =",
"django.core.validators import MaxValueValidator, MinValueValidator from django.db.models.signals import post_delete from django.dispatch import receiver from",
"'Комментарии' @receiver(post_delete, sender=CommentProducts) def post_delete_review(sender, instance, **kwargs): avr = instance.book.get_rating() instance.book.avr_rating = avr",
"null=True ) date_add = models.DateTimeField( auto_now=False, auto_now_add=True, verbose_name='Дата внесения в каталог' ) date_last_change",
"= models.DateTimeField( auto_now=False, auto_now_add=True, verbose_name='Дата внесения в каталог' ) date_last_change = models.DateTimeField( auto_now=True,",
"products.models import Book class CommentProducts(models.Model): profile = models.ForeignKey( myauth_models.Profile, on_delete=models.PROTECT, related_name='comments' ) book",
"каталог' ) date_last_change = models.DateTimeField( auto_now=True, auto_now_add=False, verbose_name='Дата последнего изменения карточки' ) stars",
"def __str__(self): return f'Комментарий №{self.pk}, пользователя: {self.profile}, к книге: {self.book}' class Meta: verbose_name",
"comment = models.TextField( verbose_name='Комментарий', default='', blank=True, null=True ) date_add = models.DateTimeField( auto_now=False, auto_now_add=True,",
"внесения в каталог' ) date_last_change = models.DateTimeField( auto_now=True, auto_now_add=False, verbose_name='Дата последнего изменения карточки'",
"MinValueValidator(0), MaxValueValidator(5)] ) def __str__(self): return f'Комментарий №{self.pk}, пользователя: {self.profile}, к книге: {self.book}'",
"models.TextField( verbose_name='Комментарий', default='', blank=True, null=True ) date_add = models.DateTimeField( auto_now=False, auto_now_add=True, verbose_name='Дата внесения",
"MinValueValidator from django.db.models.signals import post_delete from django.dispatch import receiver from myauth import models",
"models.DateTimeField( auto_now=True, auto_now_add=False, verbose_name='Дата последнего изменения карточки' ) stars = models.IntegerField( validators=[ MinValueValidator(0),",
"date_last_change = models.DateTimeField( auto_now=True, auto_now_add=False, verbose_name='Дата последнего изменения карточки' ) stars = models.IntegerField(",
"{self.profile}, к книге: {self.book}' class Meta: verbose_name = 'Комментарий' verbose_name_plural = 'Комментарии' @receiver(post_delete,",
"__str__(self): return f'Комментарий №{self.pk}, пользователя: {self.profile}, к книге: {self.book}' class Meta: verbose_name =",
"on_delete=models.PROTECT, related_name='comments' ) comment = models.TextField( verbose_name='Комментарий', default='', blank=True, null=True ) date_add =",
"models as myauth_models from products.models import Book class CommentProducts(models.Model): profile = models.ForeignKey( myauth_models.Profile,",
"verbose_name = 'Комментарий' verbose_name_plural = 'Комментарии' @receiver(post_delete, sender=CommentProducts) def post_delete_review(sender, instance, **kwargs): avr",
"auto_now=True, auto_now_add=False, verbose_name='Дата последнего изменения карточки' ) stars = models.IntegerField( validators=[ MinValueValidator(0), MaxValueValidator(5)]",
"f'Комментарий №{self.pk}, пользователя: {self.profile}, к книге: {self.book}' class Meta: verbose_name = 'Комментарий' verbose_name_plural",
"№{self.pk}, пользователя: {self.profile}, к книге: {self.book}' class Meta: verbose_name = 'Комментарий' verbose_name_plural =",
"@receiver(post_delete, sender=CommentProducts) def post_delete_review(sender, instance, **kwargs): avr = instance.book.get_rating() instance.book.avr_rating = avr instance.book.save()",
"последнего изменения карточки' ) stars = models.IntegerField( validators=[ MinValueValidator(0), MaxValueValidator(5)] ) def __str__(self):",
"MaxValueValidator, MinValueValidator from django.db.models.signals import post_delete from django.dispatch import receiver from myauth import",
"auto_now_add=False, verbose_name='Дата последнего изменения карточки' ) stars = models.IntegerField( validators=[ MinValueValidator(0), MaxValueValidator(5)] )",
"= 'Комментарии' @receiver(post_delete, sender=CommentProducts) def post_delete_review(sender, instance, **kwargs): avr = instance.book.get_rating() instance.book.avr_rating =",
"default='', blank=True, null=True ) date_add = models.DateTimeField( auto_now=False, auto_now_add=True, verbose_name='Дата внесения в каталог'",
"= models.TextField( verbose_name='Комментарий', default='', blank=True, null=True ) date_add = models.DateTimeField( auto_now=False, auto_now_add=True, verbose_name='Дата",
"= models.ForeignKey( Book, on_delete=models.PROTECT, related_name='comments' ) comment = models.TextField( verbose_name='Комментарий', default='', blank=True, null=True",
"книге: {self.book}' class Meta: verbose_name = 'Комментарий' verbose_name_plural = 'Комментарии' @receiver(post_delete, sender=CommentProducts) def",
"к книге: {self.book}' class Meta: verbose_name = 'Комментарий' verbose_name_plural = 'Комментарии' @receiver(post_delete, sender=CommentProducts)",
"profile = models.ForeignKey( myauth_models.Profile, on_delete=models.PROTECT, related_name='comments' ) book = models.ForeignKey( Book, on_delete=models.PROTECT, related_name='comments'",
"book = models.ForeignKey( Book, on_delete=models.PROTECT, related_name='comments' ) comment = models.TextField( verbose_name='Комментарий', default='', blank=True,",
") date_add = models.DateTimeField( auto_now=False, auto_now_add=True, verbose_name='Дата внесения в каталог' ) date_last_change =",
") book = models.ForeignKey( Book, on_delete=models.PROTECT, related_name='comments' ) comment = models.TextField( verbose_name='Комментарий', default='',",
"myauth import models as myauth_models from products.models import Book class CommentProducts(models.Model): profile =",
"myauth_models.Profile, on_delete=models.PROTECT, related_name='comments' ) book = models.ForeignKey( Book, on_delete=models.PROTECT, related_name='comments' ) comment =",
"validators=[ MinValueValidator(0), MaxValueValidator(5)] ) def __str__(self): return f'Комментарий №{self.pk}, пользователя: {self.profile}, к книге:",
"пользователя: {self.profile}, к книге: {self.book}' class Meta: verbose_name = 'Комментарий' verbose_name_plural = 'Комментарии'",
"import MaxValueValidator, MinValueValidator from django.db.models.signals import post_delete from django.dispatch import receiver from myauth",
"= models.IntegerField( validators=[ MinValueValidator(0), MaxValueValidator(5)] ) def __str__(self): return f'Комментарий №{self.pk}, пользователя: {self.profile},",
"models.IntegerField( validators=[ MinValueValidator(0), MaxValueValidator(5)] ) def __str__(self): return f'Комментарий №{self.pk}, пользователя: {self.profile}, к",
"related_name='comments' ) book = models.ForeignKey( Book, on_delete=models.PROTECT, related_name='comments' ) comment = models.TextField( verbose_name='Комментарий',",
"models.DateTimeField( auto_now=False, auto_now_add=True, verbose_name='Дата внесения в каталог' ) date_last_change = models.DateTimeField( auto_now=True, auto_now_add=False,",
"verbose_name='Дата внесения в каталог' ) date_last_change = models.DateTimeField( auto_now=True, auto_now_add=False, verbose_name='Дата последнего изменения",
"related_name='comments' ) comment = models.TextField( verbose_name='Комментарий', default='', blank=True, null=True ) date_add = models.DateTimeField(",
"from myauth import models as myauth_models from products.models import Book class CommentProducts(models.Model): profile",
"post_delete from django.dispatch import receiver from myauth import models as myauth_models from products.models",
"models.ForeignKey( Book, on_delete=models.PROTECT, related_name='comments' ) comment = models.TextField( verbose_name='Комментарий', default='', blank=True, null=True )",
"from django.db.models.signals import post_delete from django.dispatch import receiver from myauth import models as",
"blank=True, null=True ) date_add = models.DateTimeField( auto_now=False, auto_now_add=True, verbose_name='Дата внесения в каталог' )"
] |
[
"import Module from multiprocessing import Pool from .bioasq.coreMMR import CoreMMR as BioASQCoreMMR def",
"from .bioasq.coreMMR import CoreMMR as BioASQCoreMMR def multi_process_helper(args): questions, alpha = args ranker",
"N, step_size)] tmp = self.pool.map(multi_process_helper, slices) result = [] for x in tmp:",
"name, exp_name, rabbitmq_host, pipeline_conf, module_conf, **kwargs): super(CoreMMR, self).__init__(module_id, name, exp_name, rabbitmq_host, pipeline_conf, module_conf,",
"pool. def cleanup(self): self.pool.close() self.pool.join() def process(self, job, data): questions = data['questions'] N",
"process(self, job, data): questions = data['questions'] N = len(questions) step_size = int(N /",
"cleanup(self): self.pool.close() self.pool.join() def process(self, job, data): questions = data['questions'] N = len(questions)",
"int(N / float(self.processes)) slices = [(questions[i:i+step_size], job.params['alpha']) for i in range(0, N, step_size)]",
"as BioASQCoreMMR def multi_process_helper(args): questions, alpha = args ranker = BioASQCoreMMR() result =",
"question['ideal_answer'][0])) #log.debug(result) return result class CoreMMR(Module): def __init__(self, module_id, name, exp_name, rabbitmq_host, pipeline_conf,",
"data['questions'] N = len(questions) step_size = int(N / float(self.processes)) slices = [(questions[i:i+step_size], job.params['alpha'])",
"function to make sure close the process pool. def cleanup(self): self.pool.close() self.pool.join() def",
"/ float(self.processes)) slices = [(questions[i:i+step_size], job.params['alpha']) for i in range(0, N, step_size)] tmp",
"module_conf else 1 self.pool = Pool(processes=self.processes) ## Override the cleanup function to make",
"exp_name, rabbitmq_host, pipeline_conf, module_conf, **kwargs) self.processes = module_conf['processes'] if 'processes' in module_conf else",
"Pool from .bioasq.coreMMR import CoreMMR as BioASQCoreMMR def multi_process_helper(args): questions, alpha = args",
"from multiprocessing import Pool from .bioasq.coreMMR import CoreMMR as BioASQCoreMMR def multi_process_helper(args): questions,",
"slices) result = [] for x in tmp: result += x return result",
"Override the cleanup function to make sure close the process pool. def cleanup(self):",
"float(self.processes)) slices = [(questions[i:i+step_size], job.params['alpha']) for i in range(0, N, step_size)] tmp =",
"self.processes = module_conf['processes'] if 'processes' in module_conf else 1 self.pool = Pool(processes=self.processes) ##",
"ranker = BioASQCoreMMR() result = [] for question in questions: if 'snippets' in",
"len(questions) step_size = int(N / float(self.processes)) slices = [(questions[i:i+step_size], job.params['alpha']) for i in",
"import glog as log from boom.modules import Module from multiprocessing import Pool from",
"rabbitmq_host, pipeline_conf, module_conf, **kwargs) self.processes = module_conf['processes'] if 'processes' in module_conf else 1",
"alpha, 0), question['ideal_answer'][0])) #log.debug(result) return result class CoreMMR(Module): def __init__(self, module_id, name, exp_name,",
"BioASQCoreMMR def multi_process_helper(args): questions, alpha = args ranker = BioASQCoreMMR() result = []",
"self.pool.join() def process(self, job, data): questions = data['questions'] N = len(questions) step_size =",
"exp_name, rabbitmq_host, pipeline_conf, module_conf, **kwargs): super(CoreMMR, self).__init__(module_id, name, exp_name, rabbitmq_host, pipeline_conf, module_conf, **kwargs)",
"else 1 self.pool = Pool(processes=self.processes) ## Override the cleanup function to make sure",
"[s['text'] for s in question['snippets']] result.append((ranker.getRankedList(question, alpha, 0), question['ideal_answer'][0])) #log.debug(result) return result class",
"N = len(questions) step_size = int(N / float(self.processes)) slices = [(questions[i:i+step_size], job.params['alpha']) for",
"i in range(0, N, step_size)] tmp = self.pool.map(multi_process_helper, slices) result = [] for",
"in module_conf else 1 self.pool = Pool(processes=self.processes) ## Override the cleanup function to",
"for i in range(0, N, step_size)] tmp = self.pool.map(multi_process_helper, slices) result = []",
"question['snippets'] = [s['text'] for s in question['snippets']] result.append((ranker.getRankedList(question, alpha, 0), question['ideal_answer'][0])) #log.debug(result) return",
"range(0, N, step_size)] tmp = self.pool.map(multi_process_helper, slices) result = [] for x in",
"__init__(self, module_id, name, exp_name, rabbitmq_host, pipeline_conf, module_conf, **kwargs): super(CoreMMR, self).__init__(module_id, name, exp_name, rabbitmq_host,",
"module_conf['processes'] if 'processes' in module_conf else 1 self.pool = Pool(processes=self.processes) ## Override the",
"def multi_process_helper(args): questions, alpha = args ranker = BioASQCoreMMR() result = [] for",
"class CoreMMR(Module): def __init__(self, module_id, name, exp_name, rabbitmq_host, pipeline_conf, module_conf, **kwargs): super(CoreMMR, self).__init__(module_id,",
"name, exp_name, rabbitmq_host, pipeline_conf, module_conf, **kwargs) self.processes = module_conf['processes'] if 'processes' in module_conf",
"def __init__(self, module_id, name, exp_name, rabbitmq_host, pipeline_conf, module_conf, **kwargs): super(CoreMMR, self).__init__(module_id, name, exp_name,",
"= self.pool.map(multi_process_helper, slices) result = [] for x in tmp: result += x",
"[(questions[i:i+step_size], job.params['alpha']) for i in range(0, N, step_size)] tmp = self.pool.map(multi_process_helper, slices) result",
"return result class CoreMMR(Module): def __init__(self, module_id, name, exp_name, rabbitmq_host, pipeline_conf, module_conf, **kwargs):",
"if 'processes' in module_conf else 1 self.pool = Pool(processes=self.processes) ## Override the cleanup",
"as log from boom.modules import Module from multiprocessing import Pool from .bioasq.coreMMR import",
"job.params['alpha']) for i in range(0, N, step_size)] tmp = self.pool.map(multi_process_helper, slices) result =",
"CoreMMR(Module): def __init__(self, module_id, name, exp_name, rabbitmq_host, pipeline_conf, module_conf, **kwargs): super(CoreMMR, self).__init__(module_id, name,",
"= BioASQCoreMMR() result = [] for question in questions: if 'snippets' in question:",
"'processes' in module_conf else 1 self.pool = Pool(processes=self.processes) ## Override the cleanup function",
"to make sure close the process pool. def cleanup(self): self.pool.close() self.pool.join() def process(self,",
"s in question['snippets']] result.append((ranker.getRankedList(question, alpha, 0), question['ideal_answer'][0])) #log.debug(result) return result class CoreMMR(Module): def",
"self).__init__(module_id, name, exp_name, rabbitmq_host, pipeline_conf, module_conf, **kwargs) self.processes = module_conf['processes'] if 'processes' in",
"make sure close the process pool. def cleanup(self): self.pool.close() self.pool.join() def process(self, job,",
"import Pool from .bioasq.coreMMR import CoreMMR as BioASQCoreMMR def multi_process_helper(args): questions, alpha =",
"the process pool. def cleanup(self): self.pool.close() self.pool.join() def process(self, job, data): questions =",
"def cleanup(self): self.pool.close() self.pool.join() def process(self, job, data): questions = data['questions'] N =",
"0), question['ideal_answer'][0])) #log.debug(result) return result class CoreMMR(Module): def __init__(self, module_id, name, exp_name, rabbitmq_host,",
"for s in question['snippets']] result.append((ranker.getRankedList(question, alpha, 0), question['ideal_answer'][0])) #log.debug(result) return result class CoreMMR(Module):",
"the cleanup function to make sure close the process pool. def cleanup(self): self.pool.close()",
"cleanup function to make sure close the process pool. def cleanup(self): self.pool.close() self.pool.join()",
"Module from multiprocessing import Pool from .bioasq.coreMMR import CoreMMR as BioASQCoreMMR def multi_process_helper(args):",
"in range(0, N, step_size)] tmp = self.pool.map(multi_process_helper, slices) result = [] for x",
"close the process pool. def cleanup(self): self.pool.close() self.pool.join() def process(self, job, data): questions",
"multiprocessing import Pool from .bioasq.coreMMR import CoreMMR as BioASQCoreMMR def multi_process_helper(args): questions, alpha",
"step_size = int(N / float(self.processes)) slices = [(questions[i:i+step_size], job.params['alpha']) for i in range(0,",
"= Pool(processes=self.processes) ## Override the cleanup function to make sure close the process",
"glog as log from boom.modules import Module from multiprocessing import Pool from .bioasq.coreMMR",
"slices = [(questions[i:i+step_size], job.params['alpha']) for i in range(0, N, step_size)] tmp = self.pool.map(multi_process_helper,",
"#log.debug(result) return result class CoreMMR(Module): def __init__(self, module_id, name, exp_name, rabbitmq_host, pipeline_conf, module_conf,",
".bioasq.coreMMR import CoreMMR as BioASQCoreMMR def multi_process_helper(args): questions, alpha = args ranker =",
"Pool(processes=self.processes) ## Override the cleanup function to make sure close the process pool.",
"in questions: if 'snippets' in question: question['snippets'] = [s['text'] for s in question['snippets']]",
"## Override the cleanup function to make sure close the process pool. def",
"rabbitmq_host, pipeline_conf, module_conf, **kwargs): super(CoreMMR, self).__init__(module_id, name, exp_name, rabbitmq_host, pipeline_conf, module_conf, **kwargs) self.processes",
"data): questions = data['questions'] N = len(questions) step_size = int(N / float(self.processes)) slices",
"**kwargs): super(CoreMMR, self).__init__(module_id, name, exp_name, rabbitmq_host, pipeline_conf, module_conf, **kwargs) self.processes = module_conf['processes'] if",
"question: question['snippets'] = [s['text'] for s in question['snippets']] result.append((ranker.getRankedList(question, alpha, 0), question['ideal_answer'][0])) #log.debug(result)",
"= len(questions) step_size = int(N / float(self.processes)) slices = [(questions[i:i+step_size], job.params['alpha']) for i",
"pipeline_conf, module_conf, **kwargs): super(CoreMMR, self).__init__(module_id, name, exp_name, rabbitmq_host, pipeline_conf, module_conf, **kwargs) self.processes =",
"tmp = self.pool.map(multi_process_helper, slices) result = [] for x in tmp: result +=",
"process pool. def cleanup(self): self.pool.close() self.pool.join() def process(self, job, data): questions = data['questions']",
"def process(self, job, data): questions = data['questions'] N = len(questions) step_size = int(N",
"[] for question in questions: if 'snippets' in question: question['snippets'] = [s['text'] for",
"alpha = args ranker = BioASQCoreMMR() result = [] for question in questions:",
"questions: if 'snippets' in question: question['snippets'] = [s['text'] for s in question['snippets']] result.append((ranker.getRankedList(question,",
"**kwargs) self.processes = module_conf['processes'] if 'processes' in module_conf else 1 self.pool = Pool(processes=self.processes)",
"question in questions: if 'snippets' in question: question['snippets'] = [s['text'] for s in",
"self.pool.map(multi_process_helper, slices) result = [] for x in tmp: result += x return",
"self.pool.close() self.pool.join() def process(self, job, data): questions = data['questions'] N = len(questions) step_size",
"<reponame>paritoshgpt1/BOOM import glog as log from boom.modules import Module from multiprocessing import Pool",
"job, data): questions = data['questions'] N = len(questions) step_size = int(N / float(self.processes))",
"for question in questions: if 'snippets' in question: question['snippets'] = [s['text'] for s",
"'snippets' in question: question['snippets'] = [s['text'] for s in question['snippets']] result.append((ranker.getRankedList(question, alpha, 0),",
"in question['snippets']] result.append((ranker.getRankedList(question, alpha, 0), question['ideal_answer'][0])) #log.debug(result) return result class CoreMMR(Module): def __init__(self,",
"= int(N / float(self.processes)) slices = [(questions[i:i+step_size], job.params['alpha']) for i in range(0, N,",
"= [s['text'] for s in question['snippets']] result.append((ranker.getRankedList(question, alpha, 0), question['ideal_answer'][0])) #log.debug(result) return result",
"super(CoreMMR, self).__init__(module_id, name, exp_name, rabbitmq_host, pipeline_conf, module_conf, **kwargs) self.processes = module_conf['processes'] if 'processes'",
"multi_process_helper(args): questions, alpha = args ranker = BioASQCoreMMR() result = [] for question",
"result class CoreMMR(Module): def __init__(self, module_id, name, exp_name, rabbitmq_host, pipeline_conf, module_conf, **kwargs): super(CoreMMR,",
"if 'snippets' in question: question['snippets'] = [s['text'] for s in question['snippets']] result.append((ranker.getRankedList(question, alpha,",
"sure close the process pool. def cleanup(self): self.pool.close() self.pool.join() def process(self, job, data):",
"import CoreMMR as BioASQCoreMMR def multi_process_helper(args): questions, alpha = args ranker = BioASQCoreMMR()",
"CoreMMR as BioASQCoreMMR def multi_process_helper(args): questions, alpha = args ranker = BioASQCoreMMR() result",
"= module_conf['processes'] if 'processes' in module_conf else 1 self.pool = Pool(processes=self.processes) ## Override",
"question['snippets']] result.append((ranker.getRankedList(question, alpha, 0), question['ideal_answer'][0])) #log.debug(result) return result class CoreMMR(Module): def __init__(self, module_id,",
"in question: question['snippets'] = [s['text'] for s in question['snippets']] result.append((ranker.getRankedList(question, alpha, 0), question['ideal_answer'][0]))",
"questions = data['questions'] N = len(questions) step_size = int(N / float(self.processes)) slices =",
"step_size)] tmp = self.pool.map(multi_process_helper, slices) result = [] for x in tmp: result",
"1 self.pool = Pool(processes=self.processes) ## Override the cleanup function to make sure close",
"result = [] for question in questions: if 'snippets' in question: question['snippets'] =",
"= args ranker = BioASQCoreMMR() result = [] for question in questions: if",
"questions, alpha = args ranker = BioASQCoreMMR() result = [] for question in",
"boom.modules import Module from multiprocessing import Pool from .bioasq.coreMMR import CoreMMR as BioASQCoreMMR",
"args ranker = BioASQCoreMMR() result = [] for question in questions: if 'snippets'",
"BioASQCoreMMR() result = [] for question in questions: if 'snippets' in question: question['snippets']",
"module_id, name, exp_name, rabbitmq_host, pipeline_conf, module_conf, **kwargs): super(CoreMMR, self).__init__(module_id, name, exp_name, rabbitmq_host, pipeline_conf,",
"= [(questions[i:i+step_size], job.params['alpha']) for i in range(0, N, step_size)] tmp = self.pool.map(multi_process_helper, slices)",
"result.append((ranker.getRankedList(question, alpha, 0), question['ideal_answer'][0])) #log.debug(result) return result class CoreMMR(Module): def __init__(self, module_id, name,",
"log from boom.modules import Module from multiprocessing import Pool from .bioasq.coreMMR import CoreMMR",
"= data['questions'] N = len(questions) step_size = int(N / float(self.processes)) slices = [(questions[i:i+step_size],",
"= [] for question in questions: if 'snippets' in question: question['snippets'] = [s['text']",
"pipeline_conf, module_conf, **kwargs) self.processes = module_conf['processes'] if 'processes' in module_conf else 1 self.pool",
"from boom.modules import Module from multiprocessing import Pool from .bioasq.coreMMR import CoreMMR as",
"self.pool = Pool(processes=self.processes) ## Override the cleanup function to make sure close the",
"module_conf, **kwargs): super(CoreMMR, self).__init__(module_id, name, exp_name, rabbitmq_host, pipeline_conf, module_conf, **kwargs) self.processes = module_conf['processes']",
"module_conf, **kwargs) self.processes = module_conf['processes'] if 'processes' in module_conf else 1 self.pool ="
] |
[] |
[
"None,None) print(\"\\nCalculating... Please be patient with the machine :) \") time.sleep(1) validity_input(matrix, rows,",
"print(\"Error: Invalid Input. Give either 'y' or 'n'. Try again!\") action = input(\"Do",
"\\n1. Multiplication\\n2. Solving Linear Equation System\\nYou will have to give separate inputs, asked",
"Successfully Terminated the Program!\") sys.exit() else: print(\"Invalid input. Program Terminated.\") sys.exit() return action",
"want to continue [y/n]? \") if action == \"y\": action = input(\"\\n1. =",
"{}: \".format(num+1)) rows = int(rows) cols = int(cols) final_matrix= [] for i in",
"i in range(rows): sub_matrix = [] for j in range(cols): val = input(\"Please",
"cols) elif action == \"5\": A, B, C, total = lin_input() print(\"\\n\\n\\t\\t\\033[1mFirst, solve",
"Program Terminated.\") sys.exit() return action def validity_input(matrix, rows, cols): action = input(\"Do you",
"LU_factorization import * from determinant import * def input_mat(num): rows = input(\"Enter number",
"import * from determinant import * def input_mat(num): rows = input(\"Enter number of",
"Determinant \\n4. Transpose\\n\\n\\ This Matrix will not be used for computing \\n1. Multiplication\\n2.",
"= input(\"Do you want to continue [y/n]? \") if action == \"y\": action",
"Matrix_mutliplication import * from linear_system import * from LU_factorization import * from determinant",
"matrix, rows, cols) else: print(\"Program Successfully Terminated\") sys.exit() return action print(\"================================================================================================\") print('\\n\\t\\t\\t\\033[1m \\033[91m",
"of the given Matrix is: \\033[4m\\033[1m{}\\033[0m \\n\".format(det)) validity_input(matrix, rows, cols) elif action ==\"6\":",
"asked later\\n\\n\\ If there is any error, please contact us! Have Fun! \\n\")",
"for finding \\n\\ 1. Inverse\\n2. LU factorization\\n3. Finding Determinant \\n4. Transpose\\n\\n\\ This Matrix",
"Action. E.g. either '1' or '2': \") actions(action, matrix, rows, cols) else: print(\"Program",
"\\nSorry!\") validity_input(matrix, rows, cols) mats = [] for num in range(num_of_Mat): final_mat, rows,",
"elif action == \"3\": (A,P,L,U) = lu_decomposition(matrix) mats = [A,P,L,U] mats_names = ['A','P','L','U']",
"print(\"Program Successfully Terminated\") sys.exit() return action print(\"================================================================================================\") print('\\n\\t\\t\\t\\033[1m \\033[91m \\033[4m' + \"Matrix Calculator\\n\"",
"* from Matrix_mutliplication import * from linear_system import * from LU_factorization import *",
"sub_matrix = [] for j in range(cols): val = input(\"Please input Value of",
"None,final_matrix, None,None) return final_matrix, rows, cols def actions(action,matrix, rows, cols): # final_matrix, rows,",
"from Inverse_mat import * from Matrix_mutliplication import * from linear_system import * from",
"Code can multiply Two Matrices at a time. \\nPlease Input two matrices and",
"cols) elif action == \"2\": num_of_Mat = input(\"Num of Matrices to Multiply? \")",
"while action.lower() != \"n\": if action == \"1\": # final_matrix, rows, cols =",
"= input_mat(0) mats.append(final_mat) mat_multiplication(mats[0], mats[1]) display_mat(\"\\nMatrix_Multiplied\\n\", None,mats[0], None,None) display_mat(\"\\nMatrix_Multiplied\\n\", None,matrix, None,None) validity_input(matrix, rows,",
"None,mats[0], None,None) display_mat(\"\\nMatrix_Multiplied\\n\", None,matrix, None,None) validity_input(matrix, rows, cols) elif action == \"3\": (A,P,L,U)",
"cols) else: print(\"Program Successfully Terminated\") sys.exit() return action print(\"================================================================================================\") print('\\n\\t\\t\\t\\033[1m \\033[91m \\033[4m' +",
"cols) elif action == \"3\": (A,P,L,U) = lu_decomposition(matrix) mats = [A,P,L,U] mats_names =",
"\".format(i+1,j+1, num+1)) val = float(val) sub_matrix.append(val) final_matrix.append(sub_matrix) display_mat(\"\\tMatrix_{}\".format(num+1), None,final_matrix, None,None) return final_matrix, rows,",
"to Multiply? \") while num_of_Mat.isdigit() != True: print(\"Error: Please give a positive numeric",
"\\033[91m \\033[4m' + \"Matrix Calculator\\n\" + '\\033[0m') print(\"================================================================================================\") print(\"\\nEnter your matrix on which",
"\") num_of_Mat = int(num_of_Mat) if num_of_Mat != 2: print(\"Error: This Code can multiply",
"display_mat(\"\\nMatrix_Multiplied\\n\", None,mats[0], None,None) display_mat(\"\\nMatrix_Multiplied\\n\", None,matrix, None,None) validity_input(matrix, rows, cols) elif action == \"3\":",
"with the other matrices if need be.\\ \\nSorry!\") validity_input(matrix, rows, cols) mats =",
"Input. Give either 'y' or 'n'. Try again!\") action = input(\"Do you want",
"to execute: \\n\") print(\"Directions to note \\nThe Matrix that you are giving now",
"using Sympy!\\033[0m \\n\\n\") sol = lin(C, total) print(\"\\n\\n\\t\\t\\033[1mNow, we solve the system using",
"be used for finding \\n\\ 1. Inverse\\n2. LU factorization\\n3. Finding Determinant \\n4. Transpose\\n\\n\\",
"need be.\\ \\nSorry!\") validity_input(matrix, rows, cols) mats = [] for num in range(num_of_Mat):",
"not Have Inverse.\\nPlease give Valid Inputs again\") matrix, rows, cols = input_mat(0) ident",
"matrix, rows, cols = input_mat(0) ident = identity_mat(rows,cols) new_ident, inverse_final = inverse(matrix, ident)",
"at a time. \\nPlease Input two matrices and mutliply their resultant with the",
"our program.\\033[0m \\n\\n\") mat_A, mat_B, result = linear_system(A, B) print(\"\\nThus, \\033[1m\\033[4mSymPy output\\033[0m is:\\n\\n\\t\\t{}\\n\\nWhereas",
"= Transpose\\n7. = Quit\\nPlease Input Numerical Value for Action. E.g. either '1' or",
"Matrix {}: \".format(num+1)) rows = int(rows) cols = int(cols) final_matrix= [] for i",
"validity_input(matrix, rows, cols) elif action == \"4\": det = determinant(matrix, det = 0)",
"[y/n]? \") while action != \"y\" and action != \"n\": print(\"Error: Invalid Input.",
"= transpose(matrix) validity_input(matrix, rows, cols) elif action == \"7\": print(\"You have Successfully Terminated",
"\".format(num+1)) rows = int(rows) cols = int(cols) final_matrix= [] for i in range(rows):",
"\\033[4m\\033[1m{}\\033[0m \\n\".format(det)) validity_input(matrix, rows, cols) elif action ==\"6\": t = transpose(matrix) validity_input(matrix, rows,",
"a positive numeric value\") num_of_Mat = input(\"Num of Matrices to Multiply? \") num_of_Mat",
"num_of_Mat = int(num_of_Mat) if num_of_Mat != 2: print(\"Error: This Code can multiply Two",
"Terminated\") sys.exit() return action print(\"================================================================================================\") print('\\n\\t\\t\\t\\033[1m \\033[91m \\033[4m' + \"Matrix Calculator\\n\" + '\\033[0m')",
"\"\", 1).lstrip('-').isdigit() != True: print(\"Error: Invalid! Try Again\") val = input(\"Please input Value",
"\") actions(action, matrix, rows, cols) else: print(\"Program Successfully Terminated\") sys.exit() return action print(\"================================================================================================\")",
"return action print(\"================================================================================================\") print('\\n\\t\\t\\t\\033[1m \\033[91m \\033[4m' + \"Matrix Calculator\\n\" + '\\033[0m') print(\"================================================================================================\") print(\"\\nEnter",
"separate inputs, asked later\\n\\n\\ If there is any error, please contact us! Have",
"or 'n'. Try again!\") action = input(\"Do you want to continue [y/n]? \")",
"cols): action = input(\"Do you want to continue [y/n]? \") while action !=",
"Rows and Cols can only be positive. Try Again. \\n\") rows = input(\"Enter",
"is: \\033[4m\\033[1m{}\\033[0m \\n\".format(det)) validity_input(matrix, rows, cols) elif action ==\"6\": t = transpose(matrix) validity_input(matrix,",
"= input(\"Num of Matrices to Multiply? \") num_of_Mat = int(num_of_Mat) if num_of_Mat !=",
"is any error, please contact us! Have Fun! \\n\") print(\"================================================================================================\") matrix, rows, cols",
"cols = input_mat(0) ident = identity_mat(rows,cols) new_ident, inverse_final = inverse(matrix, ident) validity_input(matrix, rows,",
"\") if action == \"y\": action = input(\"\\n1. = Inverse \\n2. = Multiplication\\n3.",
"system using our program.\\033[0m \\n\\n\") mat_A, mat_B, result = linear_system(A, B) print(\"\\nThus, \\033[1m\\033[4mSymPy",
"System\\nYou will have to give separate inputs, asked later\\n\\n\\ If there is any",
"total) print(\"\\n\\n\\t\\t\\033[1mNow, we solve the system using our program.\\033[0m \\n\\n\") mat_A, mat_B, result",
"= [A,P,L,U] mats_names = ['A','P','L','U'] for i, j in zip(mats_names, mats): display_mat(\"\\n\\tMatrix_{}\\n\".format(i), None,j,",
"range(rows): sub_matrix = [] for j in range(cols): val = input(\"Please input Value",
"Have Inverse.\\nPlease give Valid Inputs again\") matrix, rows, cols = input_mat(0) ident =",
"Sympy!\\033[0m \\n\\n\") sol = lin(C, total) print(\"\\n\\n\\t\\t\\033[1mNow, we solve the system using our",
"input(\"Please input Value of element {}{} of Matric {}: \".format(i+1,j+1, num+1)) while val.replace(\".\",",
"for computing \\n1. Multiplication\\n2. Solving Linear Equation System\\nYou will have to give separate",
"Input Numerical Value for Action. E.g. either '1' or '2': \") actions(action, matrix,",
"1).lstrip('-').isdigit() != True: print(\"Error: Invalid! Try Again\") val = input(\"Please input Value of",
"give a positive numeric value\") num_of_Mat = input(\"Num of Matrices to Multiply? \")",
"None,None) validity_input(matrix, rows, cols) elif action == \"3\": (A,P,L,U) = lu_decomposition(matrix) mats =",
"be.\\ \\nSorry!\") validity_input(matrix, rows, cols) mats = [] for num in range(num_of_Mat): final_mat,",
"in range(num_of_Mat): final_mat, rows, cols = input_mat(0) mats.append(final_mat) mat_multiplication(mats[0], mats[1]) display_mat(\"\\nMatrix_Multiplied\\n\", None,mats[0], None,None)",
"Transpose\\n7. = Quit\\nPlease Input Numerical Value for Action. E.g. either '1' or '2':",
"= input(\"Enter number of columns for Matrix {}: \".format(num+1)) while (rows.isnumeric() != True",
"finding \\n\\ 1. Inverse\\n2. LU factorization\\n3. Finding Determinant \\n4. Transpose\\n\\n\\ This Matrix will",
"of Matrices to Multiply? \") num_of_Mat = int(num_of_Mat) if num_of_Mat != 2: print(\"Error:",
"\"1\": # final_matrix, rows, cols = input_mat(0) while rows != cols: print(\"Mathematical Error:",
"or cols.isnumeric() != True): print(\"\\nError: Invalid Input. Rows and Cols can only be",
"the system using Sympy!\\033[0m \\n\\n\") sol = lin(C, total) print(\"\\n\\n\\t\\t\\033[1mNow, we solve the",
"= Solve Linear Equation System\\n6. = Transpose\\n7. = Quit\\nPlease Input Numerical Value for",
"validity_input(matrix, rows, cols) elif action == \"5\": A, B, C, total = lin_input()",
"= inverse(matrix, ident) validity_input(matrix, rows, cols) elif action == \"2\": num_of_Mat = input(\"Num",
"of rows for Matrix {}: \".format(num+1)) cols = input(\"Enter number of columns for",
"rows, cols) elif action == \"3\": (A,P,L,U) = lu_decomposition(matrix) mats = [A,P,L,U] mats_names",
"machine :) \") time.sleep(1) validity_input(matrix, rows, cols) elif action == \"5\": A, B,",
"\\033[1m\\033[4mOur program output\\033[0m is:\\n\\n\\t\\t{}\\n\".format(sol, result)) validity_input(matrix, rows, cols) elif action == \"4\": det",
"= [] for num in range(num_of_Mat): final_mat, rows, cols = input_mat(0) mats.append(final_mat) mat_multiplication(mats[0],",
"def validity_input(matrix, rows, cols): action = input(\"Do you want to continue [y/n]? \")",
"action print(\"================================================================================================\") print('\\n\\t\\t\\t\\033[1m \\033[91m \\033[4m' + \"Matrix Calculator\\n\" + '\\033[0m') print(\"================================================================================================\") print(\"\\nEnter your",
"rows for Matrix {}: \".format(num+1)) cols = input(\"Enter number of columns for Matrix",
"Cols can only be positive. Try Again. \\n\") rows = input(\"Enter number of",
"of Matric {}: \".format(i+1,j+1, num+1)) val = float(val) sub_matrix.append(val) final_matrix.append(sub_matrix) display_mat(\"\\tMatrix_{}\".format(num+1), None,final_matrix, None,None)",
"either 'y' or 'n'. Try again!\") action = input(\"Do you want to continue",
"final_matrix, rows, cols def actions(action,matrix, rows, cols): # final_matrix, rows, cols = input_mat(0)",
"input_mat(0) while rows != cols: print(\"Mathematical Error: Non-Square Matrices Do not Have Inverse.\\nPlease",
"input_mat(num): rows = input(\"Enter number of rows for Matrix {}: \".format(num+1)) cols =",
"0) print(\"\\n\\t\\t\\tDeterminant of the given Matrix is: \\033[4m\\033[1m{}\\033[0m \\n\".format(det)) validity_input(matrix, rows, cols) elif",
"Give either 'y' or 'n'. Try again!\") action = input(\"Do you want to",
"Value of element {}{} of Matric {}: \".format(i+1,j+1, num+1)) while val.replace(\".\", \"\", 1).lstrip('-').isdigit()",
"None,j, None,None) print(\"\\nCalculating... Please be patient with the machine :) \") time.sleep(1) validity_input(matrix,",
"\\033[4m' + \"Matrix Calculator\\n\" + '\\033[0m') print(\"================================================================================================\") print(\"\\nEnter your matrix on which you",
"used for finding \\n\\ 1. Inverse\\n2. LU factorization\\n3. Finding Determinant \\n4. Transpose\\n\\n\\ This",
"matrix on which you want the actions to execute: \\n\") print(\"Directions to note",
"elif action ==\"6\": t = transpose(matrix) validity_input(matrix, rows, cols) elif action == \"7\":",
"Matric {}: \".format(i+1,j+1, num+1)) val = float(val) sub_matrix.append(val) final_matrix.append(sub_matrix) display_mat(\"\\tMatrix_{}\".format(num+1), None,final_matrix, None,None) return",
"is:\\n\\n\\t\\t{}\\n\".format(sol, result)) validity_input(matrix, rows, cols) elif action == \"4\": det = determinant(matrix, det",
"Matrix is: \\033[4m\\033[1m{}\\033[0m \\n\".format(det)) validity_input(matrix, rows, cols) elif action ==\"6\": t = transpose(matrix)",
"Calculator\\n\" + '\\033[0m') print(\"================================================================================================\") print(\"\\nEnter your matrix on which you want the actions",
"System\\n6. = Transpose\\n7. = Quit\\nPlease Input Numerical Value for Action. E.g. either '1'",
"\"Matrix Calculator\\n\" + '\\033[0m') print(\"================================================================================================\") print(\"\\nEnter your matrix on which you want the",
"can multiply Two Matrices at a time. \\nPlease Input two matrices and mutliply",
"None,None) display_mat(\"\\nMatrix_Multiplied\\n\", None,matrix, None,None) validity_input(matrix, rows, cols) elif action == \"3\": (A,P,L,U) =",
"of element {}{} of Matric {}: \".format(i+1,j+1, num+1)) while val.replace(\".\", \"\", 1).lstrip('-').isdigit() !=",
"and mutliply their resultant with the other matrices if need be.\\ \\nSorry!\") validity_input(matrix,",
"{}: \".format(i+1,j+1, num+1)) while val.replace(\".\", \"\", 1).lstrip('-').isdigit() != True: print(\"Error: Invalid! Try Again\")",
"\\n\\ 1. Inverse\\n2. LU factorization\\n3. Finding Determinant \\n4. Transpose\\n\\n\\ This Matrix will not",
"num_of_Mat.isdigit() != True: print(\"Error: Please give a positive numeric value\") num_of_Mat = input(\"Num",
"rows, cols) mats = [] for num in range(num_of_Mat): final_mat, rows, cols =",
"that you are giving now can be used for finding \\n\\ 1. Inverse\\n2.",
"of columns for Matrix {}: \".format(num+1)) while (rows.isnumeric() != True or cols.isnumeric() !=",
"Invalid Input. Give either 'y' or 'n'. Try again!\") action = input(\"Do you",
"please contact us! Have Fun! \\n\") print(\"================================================================================================\") matrix, rows, cols = input_mat(0) validity_input(matrix,",
"inverse(matrix, ident) validity_input(matrix, rows, cols) elif action == \"2\": num_of_Mat = input(\"Num of",
"Matrices at a time. \\nPlease Input two matrices and mutliply their resultant with",
"action != \"n\": print(\"Error: Invalid Input. Give either 'y' or 'n'. Try again!\")",
"input_mat(0) ident = identity_mat(rows,cols) new_ident, inverse_final = inverse(matrix, ident) validity_input(matrix, rows, cols) elif",
"the given Matrix is: \\033[4m\\033[1m{}\\033[0m \\n\".format(det)) validity_input(matrix, rows, cols) elif action ==\"6\": t",
"\\n\\ 5. = Solve Linear Equation System\\n6. = Transpose\\n7. = Quit\\nPlease Input Numerical",
"mat_B, result = linear_system(A, B) print(\"\\nThus, \\033[1m\\033[4mSymPy output\\033[0m is:\\n\\n\\t\\t{}\\n\\nWhereas \\033[1m\\033[4mOur program output\\033[0m is:\\n\\n\\t\\t{}\\n\".format(sol,",
"= input(\"Please input Value of element {}{} of Matric {}: \".format(i+1,j+1, num+1)) val",
"* from LU_factorization import * from determinant import * def input_mat(num): rows =",
"!= True or cols.isnumeric() != True): print(\"\\nError: Invalid Input. Rows and Cols can",
"None,None) return final_matrix, rows, cols def actions(action,matrix, rows, cols): # final_matrix, rows, cols",
"output\\033[0m is:\\n\\n\\t\\t{}\\n\\nWhereas \\033[1m\\033[4mOur program output\\033[0m is:\\n\\n\\t\\t{}\\n\".format(sol, result)) validity_input(matrix, rows, cols) elif action ==",
"validity_input(matrix, rows, cols): action = input(\"Do you want to continue [y/n]? \") while",
"input(\"\\n1. = Inverse \\n2. = Multiplication\\n3. = LU factorization\\n4. = Finding Determinant \\n\\",
"multiply Two Matrices at a time. \\nPlease Input two matrices and mutliply their",
"for Matrix {}: \".format(num+1)) while (rows.isnumeric() != True or cols.isnumeric() != True): print(\"\\nError:",
"return final_matrix, rows, cols def actions(action,matrix, rows, cols): # final_matrix, rows, cols =",
"cols): # final_matrix, rows, cols = input_mat(0) while action.lower() != \"n\": if action",
"Linear Equation System\\nYou will have to give separate inputs, asked later\\n\\n\\ If there",
"== \"7\": print(\"You have Successfully Terminated the Program!\") sys.exit() else: print(\"Invalid input. Program",
"Valid Inputs again\") matrix, rows, cols = input_mat(0) ident = identity_mat(rows,cols) new_ident, inverse_final",
"\"3\": (A,P,L,U) = lu_decomposition(matrix) mats = [A,P,L,U] mats_names = ['A','P','L','U'] for i, j",
"we solve the system using our program.\\033[0m \\n\\n\") mat_A, mat_B, result = linear_system(A,",
"* from linear_system import * from LU_factorization import * from determinant import *",
"print(\"Directions to note \\nThe Matrix that you are giving now can be used",
"action == \"5\": A, B, C, total = lin_input() print(\"\\n\\n\\t\\t\\033[1mFirst, solve the system",
"have Successfully Terminated the Program!\") sys.exit() else: print(\"Invalid input. Program Terminated.\") sys.exit() return",
"Matrix {}: \".format(num+1)) while (rows.isnumeric() != True or cols.isnumeric() != True): print(\"\\nError: Invalid",
"giving now can be used for finding \\n\\ 1. Inverse\\n2. LU factorization\\n3. Finding",
"for j in range(cols): val = input(\"Please input Value of element {}{} of",
"Determinant \\n\\ 5. = Solve Linear Equation System\\n6. = Transpose\\n7. = Quit\\nPlease Input",
"action == \"y\": action = input(\"\\n1. = Inverse \\n2. = Multiplication\\n3. = LU",
"int(num_of_Mat) if num_of_Mat != 2: print(\"Error: This Code can multiply Two Matrices at",
"rows, cols = input_mat(0) mats.append(final_mat) mat_multiplication(mats[0], mats[1]) display_mat(\"\\nMatrix_Multiplied\\n\", None,mats[0], None,None) display_mat(\"\\nMatrix_Multiplied\\n\", None,matrix, None,None)",
"for num in range(num_of_Mat): final_mat, rows, cols = input_mat(0) mats.append(final_mat) mat_multiplication(mats[0], mats[1]) display_mat(\"\\nMatrix_Multiplied\\n\",",
"sol = lin(C, total) print(\"\\n\\n\\t\\t\\033[1mNow, we solve the system using our program.\\033[0m \\n\\n\")",
"= input(\"\\n1. = Inverse \\n2. = Multiplication\\n3. = LU factorization\\n4. = Finding Determinant",
"Inverse\\n2. LU factorization\\n3. Finding Determinant \\n4. Transpose\\n\\n\\ This Matrix will not be used",
"None,matrix, None,None) validity_input(matrix, rows, cols) elif action == \"3\": (A,P,L,U) = lu_decomposition(matrix) mats",
"action = input(\"Do you want to continue [y/n]? \") while action != \"y\"",
"Please give a positive numeric value\") num_of_Mat = input(\"Num of Matrices to Multiply?",
"Multiplication\\n2. Solving Linear Equation System\\nYou will have to give separate inputs, asked later\\n\\n\\",
"range(cols): val = input(\"Please input Value of element {}{} of Matric {}: \".format(i+1,j+1,",
"B, C, total = lin_input() print(\"\\n\\n\\t\\t\\033[1mFirst, solve the system using Sympy!\\033[0m \\n\\n\") sol",
"def actions(action,matrix, rows, cols): # final_matrix, rows, cols = input_mat(0) while action.lower() !=",
"numeric value\") num_of_Mat = input(\"Num of Matrices to Multiply? \") num_of_Mat = int(num_of_Mat)",
"result = linear_system(A, B) print(\"\\nThus, \\033[1m\\033[4mSymPy output\\033[0m is:\\n\\n\\t\\t{}\\n\\nWhereas \\033[1m\\033[4mOur program output\\033[0m is:\\n\\n\\t\\t{}\\n\".format(sol, result))",
"element {}{} of Matric {}: \".format(i+1,j+1, num+1)) while val.replace(\".\", \"\", 1).lstrip('-').isdigit() != True:",
"= Finding Determinant \\n\\ 5. = Solve Linear Equation System\\n6. = Transpose\\n7. =",
"Solve Linear Equation System\\n6. = Transpose\\n7. = Quit\\nPlease Input Numerical Value for Action.",
"= input_mat(0) while action.lower() != \"n\": if action == \"1\": # final_matrix, rows,",
"if need be.\\ \\nSorry!\") validity_input(matrix, rows, cols) mats = [] for num in",
"if action == \"1\": # final_matrix, rows, cols = input_mat(0) while rows !=",
"while (rows.isnumeric() != True or cols.isnumeric() != True): print(\"\\nError: Invalid Input. Rows and",
"input(\"Enter number of columns for Matrix {}: \".format(num+1)) rows = int(rows) cols =",
"any error, please contact us! Have Fun! \\n\") print(\"================================================================================================\") matrix, rows, cols =",
"in range(rows): sub_matrix = [] for j in range(cols): val = input(\"Please input",
"* def input_mat(num): rows = input(\"Enter number of rows for Matrix {}: \".format(num+1))",
"input(\"Enter number of rows for Matrix {}: \".format(num+1)) cols = input(\"Enter number of",
"the machine :) \") time.sleep(1) validity_input(matrix, rows, cols) elif action == \"5\": A,",
"import * from linear_system import * from LU_factorization import * from determinant import",
"= Inverse \\n2. = Multiplication\\n3. = LU factorization\\n4. = Finding Determinant \\n\\ 5.",
"you want to continue [y/n]? \") if action == \"y\": action = input(\"\\n1.",
"import * def input_mat(num): rows = input(\"Enter number of rows for Matrix {}:",
"\".format(i+1,j+1, num+1)) while val.replace(\".\", \"\", 1).lstrip('-').isdigit() != True: print(\"Error: Invalid! Try Again\") val",
"later\\n\\n\\ If there is any error, please contact us! Have Fun! \\n\") print(\"================================================================================================\")",
"elif action == \"7\": print(\"You have Successfully Terminated the Program!\") sys.exit() else: print(\"Invalid",
"determinant import * def input_mat(num): rows = input(\"Enter number of rows for Matrix",
"result)) validity_input(matrix, rows, cols) elif action == \"4\": det = determinant(matrix, det =",
"resultant with the other matrices if need be.\\ \\nSorry!\") validity_input(matrix, rows, cols) mats",
"cols = input(\"Enter number of columns for Matrix {}: \".format(num+1)) while (rows.isnumeric() !=",
"val = float(val) sub_matrix.append(val) final_matrix.append(sub_matrix) display_mat(\"\\tMatrix_{}\".format(num+1), None,final_matrix, None,None) return final_matrix, rows, cols def",
"program output\\033[0m is:\\n\\n\\t\\t{}\\n\".format(sol, result)) validity_input(matrix, rows, cols) elif action == \"4\": det =",
"E.g. either '1' or '2': \") actions(action, matrix, rows, cols) else: print(\"Program Successfully",
"= input(\"Please input Value of element {}{} of Matric {}: \".format(i+1,j+1, num+1)) while",
"Matrix that you are giving now can be used for finding \\n\\ 1.",
"inverse_final = inverse(matrix, ident) validity_input(matrix, rows, cols) elif action == \"2\": num_of_Mat =",
"rows, cols) elif action == \"7\": print(\"You have Successfully Terminated the Program!\") sys.exit()",
"their resultant with the other matrices if need be.\\ \\nSorry!\") validity_input(matrix, rows, cols)",
"print(\"\\n\\t\\t\\tDeterminant of the given Matrix is: \\033[4m\\033[1m{}\\033[0m \\n\".format(det)) validity_input(matrix, rows, cols) elif action",
"{}: \".format(num+1)) cols = input(\"Enter number of columns for Matrix {}: \".format(num+1)) while",
"print(\"Error: This Code can multiply Two Matrices at a time. \\nPlease Input two",
"A, B, C, total = lin_input() print(\"\\n\\n\\t\\t\\033[1mFirst, solve the system using Sympy!\\033[0m \\n\\n\")",
"cols = input_mat(0) while action.lower() != \"n\": if action == \"1\": # final_matrix,",
"can be used for finding \\n\\ 1. Inverse\\n2. LU factorization\\n3. Finding Determinant \\n4.",
"only be positive. Try Again. \\n\") rows = input(\"Enter number of rows for",
"print(\"\\n\\n\\t\\t\\033[1mFirst, solve the system using Sympy!\\033[0m \\n\\n\") sol = lin(C, total) print(\"\\n\\n\\t\\t\\033[1mNow, we",
"to continue [y/n]? \") while action != \"y\" and action != \"n\": print(\"Error:",
"Matrix {}: \".format(num+1)) cols = input(\"Enter number of columns for Matrix {}: \".format(num+1))",
"= lin_input() print(\"\\n\\n\\t\\t\\033[1mFirst, solve the system using Sympy!\\033[0m \\n\\n\") sol = lin(C, total)",
"print(\"\\nCalculating... Please be patient with the machine :) \") time.sleep(1) validity_input(matrix, rows, cols)",
"print(\"\\nThus, \\033[1m\\033[4mSymPy output\\033[0m is:\\n\\n\\t\\t{}\\n\\nWhereas \\033[1m\\033[4mOur program output\\033[0m is:\\n\\n\\t\\t{}\\n\".format(sol, result)) validity_input(matrix, rows, cols) elif",
"actions(action,matrix, rows, cols): # final_matrix, rows, cols = input_mat(0) while action.lower() != \"n\":",
"\"n\": if action == \"1\": # final_matrix, rows, cols = input_mat(0) while rows",
"\\nPlease Input two matrices and mutliply their resultant with the other matrices if",
"\") while num_of_Mat.isdigit() != True: print(\"Error: Please give a positive numeric value\") num_of_Mat",
"lu_decomposition(matrix) mats = [A,P,L,U] mats_names = ['A','P','L','U'] for i, j in zip(mats_names, mats):",
"+ '\\033[0m') print(\"================================================================================================\") print(\"\\nEnter your matrix on which you want the actions to",
"element {}{} of Matric {}: \".format(i+1,j+1, num+1)) val = float(val) sub_matrix.append(val) final_matrix.append(sub_matrix) display_mat(\"\\tMatrix_{}\".format(num+1),",
"the system using our program.\\033[0m \\n\\n\") mat_A, mat_B, result = linear_system(A, B) print(\"\\nThus,",
"* from determinant import * def input_mat(num): rows = input(\"Enter number of rows",
"action = input(\"\\n1. = Inverse \\n2. = Multiplication\\n3. = LU factorization\\n4. = Finding",
"Error: Non-Square Matrices Do not Have Inverse.\\nPlease give Valid Inputs again\") matrix, rows,",
"inputs, asked later\\n\\n\\ If there is any error, please contact us! Have Fun!",
"'2': \") actions(action, matrix, rows, cols) else: print(\"Program Successfully Terminated\") sys.exit() return action",
"print(\"\\n\\n\\t\\t\\033[1mNow, we solve the system using our program.\\033[0m \\n\\n\") mat_A, mat_B, result =",
"This Matrix will not be used for computing \\n1. Multiplication\\n2. Solving Linear Equation",
"number of columns for Matrix {}: \".format(num+1)) while (rows.isnumeric() != True or cols.isnumeric()",
"mats[1]) display_mat(\"\\nMatrix_Multiplied\\n\", None,mats[0], None,None) display_mat(\"\\nMatrix_Multiplied\\n\", None,matrix, None,None) validity_input(matrix, rows, cols) elif action ==",
"using our program.\\033[0m \\n\\n\") mat_A, mat_B, result = linear_system(A, B) print(\"\\nThus, \\033[1m\\033[4mSymPy output\\033[0m",
"range(num_of_Mat): final_mat, rows, cols = input_mat(0) mats.append(final_mat) mat_multiplication(mats[0], mats[1]) display_mat(\"\\nMatrix_Multiplied\\n\", None,mats[0], None,None) display_mat(\"\\nMatrix_Multiplied\\n\",",
"solve the system using Sympy!\\033[0m \\n\\n\") sol = lin(C, total) print(\"\\n\\n\\t\\t\\033[1mNow, we solve",
"action == \"2\": num_of_Mat = input(\"Num of Matrices to Multiply? \") while num_of_Mat.isdigit()",
"\\033[1m\\033[4mSymPy output\\033[0m is:\\n\\n\\t\\t{}\\n\\nWhereas \\033[1m\\033[4mOur program output\\033[0m is:\\n\\n\\t\\t{}\\n\".format(sol, result)) validity_input(matrix, rows, cols) elif action",
"cols: print(\"Mathematical Error: Non-Square Matrices Do not Have Inverse.\\nPlease give Valid Inputs again\")",
"output\\033[0m is:\\n\\n\\t\\t{}\\n\".format(sol, result)) validity_input(matrix, rows, cols) elif action == \"4\": det = determinant(matrix,",
"If there is any error, please contact us! Have Fun! \\n\") print(\"================================================================================================\") matrix,",
"This Code can multiply Two Matrices at a time. \\nPlease Input two matrices",
"rows, cols) elif action == \"5\": A, B, C, total = lin_input() print(\"\\n\\n\\t\\t\\033[1mFirst,",
"transpose(matrix) validity_input(matrix, rows, cols) elif action == \"7\": print(\"You have Successfully Terminated the",
"contact us! Have Fun! \\n\") print(\"================================================================================================\") matrix, rows, cols = input_mat(0) validity_input(matrix, rows,",
"from linear_system import * from LU_factorization import * from determinant import * def",
"Matrices to Multiply? \") while num_of_Mat.isdigit() != True: print(\"Error: Please give a positive",
"you are giving now can be used for finding \\n\\ 1. Inverse\\n2. LU",
"val.replace(\".\", \"\", 1).lstrip('-').isdigit() != True: print(\"Error: Invalid! Try Again\") val = input(\"Please input",
"rows, cols = input_mat(0) while rows != cols: print(\"Mathematical Error: Non-Square Matrices Do",
"print(\"================================================================================================\") print('\\n\\t\\t\\t\\033[1m \\033[91m \\033[4m' + \"Matrix Calculator\\n\" + '\\033[0m') print(\"================================================================================================\") print(\"\\nEnter your matrix",
"sys.exit() return action print(\"================================================================================================\") print('\\n\\t\\t\\t\\033[1m \\033[91m \\033[4m' + \"Matrix Calculator\\n\" + '\\033[0m') print(\"================================================================================================\")",
"[] for num in range(num_of_Mat): final_mat, rows, cols = input_mat(0) mats.append(final_mat) mat_multiplication(mats[0], mats[1])",
"input(\"Please input Value of element {}{} of Matric {}: \".format(i+1,j+1, num+1)) val =",
"num_of_Mat = input(\"Num of Matrices to Multiply? \") num_of_Mat = int(num_of_Mat) if num_of_Mat",
"Multiplication\\n3. = LU factorization\\n4. = Finding Determinant \\n\\ 5. = Solve Linear Equation",
"{}: \".format(i+1,j+1, num+1)) val = float(val) sub_matrix.append(val) final_matrix.append(sub_matrix) display_mat(\"\\tMatrix_{}\".format(num+1), None,final_matrix, None,None) return final_matrix,",
"you want the actions to execute: \\n\") print(\"Directions to note \\nThe Matrix that",
"Numerical Value for Action. E.g. either '1' or '2': \") actions(action, matrix, rows,",
"cols = int(cols) final_matrix= [] for i in range(rows): sub_matrix = [] for",
"cols) mats = [] for num in range(num_of_Mat): final_mat, rows, cols = input_mat(0)",
"\\n4. Transpose\\n\\n\\ This Matrix will not be used for computing \\n1. Multiplication\\n2. Solving",
"mutliply their resultant with the other matrices if need be.\\ \\nSorry!\") validity_input(matrix, rows,",
"for Action. E.g. either '1' or '2': \") actions(action, matrix, rows, cols) else:",
"Input two matrices and mutliply their resultant with the other matrices if need",
"input_mat(0) mats.append(final_mat) mat_multiplication(mats[0], mats[1]) display_mat(\"\\nMatrix_Multiplied\\n\", None,mats[0], None,None) display_mat(\"\\nMatrix_Multiplied\\n\", None,matrix, None,None) validity_input(matrix, rows, cols)",
"input. Program Terminated.\") sys.exit() return action def validity_input(matrix, rows, cols): action = input(\"Do",
"import * from Inverse_mat import * from Matrix_mutliplication import * from linear_system import",
"= 0) print(\"\\n\\t\\t\\tDeterminant of the given Matrix is: \\033[4m\\033[1m{}\\033[0m \\n\".format(det)) validity_input(matrix, rows, cols)",
"Equation System\\n6. = Transpose\\n7. = Quit\\nPlease Input Numerical Value for Action. E.g. either",
"sys import time from help_functions import * from Inverse_mat import * from Matrix_mutliplication",
"rows, cols): # final_matrix, rows, cols = input_mat(0) while action.lower() != \"n\": if",
"1. Inverse\\n2. LU factorization\\n3. Finding Determinant \\n4. Transpose\\n\\n\\ This Matrix will not be",
"[A,P,L,U] mats_names = ['A','P','L','U'] for i, j in zip(mats_names, mats): display_mat(\"\\n\\tMatrix_{}\\n\".format(i), None,j, None,None)",
"validity_input(matrix, rows, cols) elif action == \"2\": num_of_Mat = input(\"Num of Matrices to",
"cols.isnumeric() != True): print(\"\\nError: Invalid Input. Rows and Cols can only be positive.",
"new_ident, inverse_final = inverse(matrix, ident) validity_input(matrix, rows, cols) elif action == \"2\": num_of_Mat",
"actions to execute: \\n\") print(\"Directions to note \\nThe Matrix that you are giving",
"given Matrix is: \\033[4m\\033[1m{}\\033[0m \\n\".format(det)) validity_input(matrix, rows, cols) elif action ==\"6\": t =",
"input Value of element {}{} of Matric {}: \".format(i+1,j+1, num+1)) while val.replace(\".\", \"\",",
"Input. Rows and Cols can only be positive. Try Again. \\n\") rows =",
"== \"5\": A, B, C, total = lin_input() print(\"\\n\\n\\t\\t\\033[1mFirst, solve the system using",
"and Cols can only be positive. Try Again. \\n\") rows = input(\"Enter number",
"import time from help_functions import * from Inverse_mat import * from Matrix_mutliplication import",
"again\") matrix, rows, cols = input_mat(0) ident = identity_mat(rows,cols) new_ident, inverse_final = inverse(matrix,",
"there is any error, please contact us! Have Fun! \\n\") print(\"================================================================================================\") matrix, rows,",
"+ \"Matrix Calculator\\n\" + '\\033[0m') print(\"================================================================================================\") print(\"\\nEnter your matrix on which you want",
"True: print(\"Error: Please give a positive numeric value\") num_of_Mat = input(\"Num of Matrices",
"be used for computing \\n1. Multiplication\\n2. Solving Linear Equation System\\nYou will have to",
"j in range(cols): val = input(\"Please input Value of element {}{} of Matric",
"to continue [y/n]? \") if action == \"y\": action = input(\"\\n1. = Inverse",
"rows = input(\"Enter number of rows for Matrix {}: \".format(num+1)) cols = input(\"Enter",
"{}{} of Matric {}: \".format(i+1,j+1, num+1)) val = float(val) sub_matrix.append(val) final_matrix.append(sub_matrix) display_mat(\"\\tMatrix_{}\".format(num+1), None,final_matrix,",
"zip(mats_names, mats): display_mat(\"\\n\\tMatrix_{}\\n\".format(i), None,j, None,None) print(\"\\nCalculating... Please be patient with the machine :)",
"rows, cols = input_mat(0) ident = identity_mat(rows,cols) new_ident, inverse_final = inverse(matrix, ident) validity_input(matrix,",
"LU factorization\\n3. Finding Determinant \\n4. Transpose\\n\\n\\ This Matrix will not be used for",
"matrices and mutliply their resultant with the other matrices if need be.\\ \\nSorry!\")",
"B) print(\"\\nThus, \\033[1m\\033[4mSymPy output\\033[0m is:\\n\\n\\t\\t{}\\n\\nWhereas \\033[1m\\033[4mOur program output\\033[0m is:\\n\\n\\t\\t{}\\n\".format(sol, result)) validity_input(matrix, rows, cols)",
"Inverse \\n2. = Multiplication\\n3. = LU factorization\\n4. = Finding Determinant \\n\\ 5. =",
"'y' or 'n'. Try again!\") action = input(\"Do you want to continue [y/n]?",
"have to give separate inputs, asked later\\n\\n\\ If there is any error, please",
"input(\"Num of Matrices to Multiply? \") num_of_Mat = int(num_of_Mat) if num_of_Mat != 2:",
"\".format(num+1)) while (rows.isnumeric() != True or cols.isnumeric() != True): print(\"\\nError: Invalid Input. Rows",
"= float(val) sub_matrix.append(val) final_matrix.append(sub_matrix) display_mat(\"\\tMatrix_{}\".format(num+1), None,final_matrix, None,None) return final_matrix, rows, cols def actions(action,matrix,",
"is:\\n\\n\\t\\t{}\\n\\nWhereas \\033[1m\\033[4mOur program output\\033[0m is:\\n\\n\\t\\t{}\\n\".format(sol, result)) validity_input(matrix, rows, cols) elif action == \"4\":",
"for i in range(rows): sub_matrix = [] for j in range(cols): val =",
"= LU factorization\\n4. = Finding Determinant \\n\\ 5. = Solve Linear Equation System\\n6.",
"Please be patient with the machine :) \") time.sleep(1) validity_input(matrix, rows, cols) elif",
"action == \"7\": print(\"You have Successfully Terminated the Program!\") sys.exit() else: print(\"Invalid input.",
"Inverse_mat import * from Matrix_mutliplication import * from linear_system import * from LU_factorization",
"cols) elif action ==\"6\": t = transpose(matrix) validity_input(matrix, rows, cols) elif action ==",
"give separate inputs, asked later\\n\\n\\ If there is any error, please contact us!",
"while num_of_Mat.isdigit() != True: print(\"Error: Please give a positive numeric value\") num_of_Mat =",
"action != \"y\" and action != \"n\": print(\"Error: Invalid Input. Give either 'y'",
"columns for Matrix {}: \".format(num+1)) while (rows.isnumeric() != True or cols.isnumeric() != True):",
"cols def actions(action,matrix, rows, cols): # final_matrix, rows, cols = input_mat(0) while action.lower()",
"print(\"Mathematical Error: Non-Square Matrices Do not Have Inverse.\\nPlease give Valid Inputs again\") matrix,",
"rows, cols = input_mat(0) while action.lower() != \"n\": if action == \"1\": #",
"(A,P,L,U) = lu_decomposition(matrix) mats = [A,P,L,U] mats_names = ['A','P','L','U'] for i, j in",
"\") while action != \"y\" and action != \"n\": print(\"Error: Invalid Input. Give",
"Terminated the Program!\") sys.exit() else: print(\"Invalid input. Program Terminated.\") sys.exit() return action def",
"Multiply? \") num_of_Mat = int(num_of_Mat) if num_of_Mat != 2: print(\"Error: This Code can",
"Two Matrices at a time. \\nPlease Input two matrices and mutliply their resultant",
"value\") num_of_Mat = input(\"Num of Matrices to Multiply? \") num_of_Mat = int(num_of_Mat) if",
"= ['A','P','L','U'] for i, j in zip(mats_names, mats): display_mat(\"\\n\\tMatrix_{}\\n\".format(i), None,j, None,None) print(\"\\nCalculating... Please",
"program.\\033[0m \\n\\n\") mat_A, mat_B, result = linear_system(A, B) print(\"\\nThus, \\033[1m\\033[4mSymPy output\\033[0m is:\\n\\n\\t\\t{}\\n\\nWhereas \\033[1m\\033[4mOur",
"continue [y/n]? \") if action == \"y\": action = input(\"\\n1. = Inverse \\n2.",
"= int(num_of_Mat) if num_of_Mat != 2: print(\"Error: This Code can multiply Two Matrices",
"def input_mat(num): rows = input(\"Enter number of rows for Matrix {}: \".format(num+1)) cols",
"or '2': \") actions(action, matrix, rows, cols) else: print(\"Program Successfully Terminated\") sys.exit() return",
"t = transpose(matrix) validity_input(matrix, rows, cols) elif action == \"7\": print(\"You have Successfully",
"2: print(\"Error: This Code can multiply Two Matrices at a time. \\nPlease Input",
"continue [y/n]? \") while action != \"y\" and action != \"n\": print(\"Error: Invalid",
"Successfully Terminated\") sys.exit() return action print(\"================================================================================================\") print('\\n\\t\\t\\t\\033[1m \\033[91m \\033[4m' + \"Matrix Calculator\\n\" +",
"from LU_factorization import * from determinant import * def input_mat(num): rows = input(\"Enter",
"mats = [] for num in range(num_of_Mat): final_mat, rows, cols = input_mat(0) mats.append(final_mat)",
"a time. \\nPlease Input two matrices and mutliply their resultant with the other",
"print(\"\\nError: Invalid Input. Rows and Cols can only be positive. Try Again. \\n\")",
"are giving now can be used for finding \\n\\ 1. Inverse\\n2. LU factorization\\n3.",
"system using Sympy!\\033[0m \\n\\n\") sol = lin(C, total) print(\"\\n\\n\\t\\t\\033[1mNow, we solve the system",
"print(\"\\nEnter your matrix on which you want the actions to execute: \\n\") print(\"Directions",
"return action def validity_input(matrix, rows, cols): action = input(\"Do you want to continue",
"print(\"You have Successfully Terminated the Program!\") sys.exit() else: print(\"Invalid input. Program Terminated.\") sys.exit()",
"Multiply? \") while num_of_Mat.isdigit() != True: print(\"Error: Please give a positive numeric value\")",
"not be used for computing \\n1. Multiplication\\n2. Solving Linear Equation System\\nYou will have",
"linear_system(A, B) print(\"\\nThus, \\033[1m\\033[4mSymPy output\\033[0m is:\\n\\n\\t\\t{}\\n\\nWhereas \\033[1m\\033[4mOur program output\\033[0m is:\\n\\n\\t\\t{}\\n\".format(sol, result)) validity_input(matrix, rows,",
"if action == \"y\": action = input(\"\\n1. = Inverse \\n2. = Multiplication\\n3. =",
"= input_mat(0) ident = identity_mat(rows,cols) new_ident, inverse_final = inverse(matrix, ident) validity_input(matrix, rows, cols)",
"factorization\\n4. = Finding Determinant \\n\\ 5. = Solve Linear Equation System\\n6. = Transpose\\n7.",
"total = lin_input() print(\"\\n\\n\\t\\t\\033[1mFirst, solve the system using Sympy!\\033[0m \\n\\n\") sol = lin(C,",
"rows = int(rows) cols = int(cols) final_matrix= [] for i in range(rows): sub_matrix",
"input(\"Enter number of columns for Matrix {}: \".format(num+1)) while (rows.isnumeric() != True or",
"be patient with the machine :) \") time.sleep(1) validity_input(matrix, rows, cols) elif action",
"final_matrix, rows, cols = input_mat(0) while rows != cols: print(\"Mathematical Error: Non-Square Matrices",
"display_mat(\"\\nMatrix_Multiplied\\n\", None,matrix, None,None) validity_input(matrix, rows, cols) elif action == \"3\": (A,P,L,U) = lu_decomposition(matrix)",
"{}: \".format(num+1)) cols = input(\"Enter number of columns for Matrix {}: \".format(num+1)) rows",
"mats): display_mat(\"\\n\\tMatrix_{}\\n\".format(i), None,j, None,None) print(\"\\nCalculating... Please be patient with the machine :) \")",
"True: print(\"Error: Invalid! Try Again\") val = input(\"Please input Value of element {}{}",
"== \"3\": (A,P,L,U) = lu_decomposition(matrix) mats = [A,P,L,U] mats_names = ['A','P','L','U'] for i,",
"can only be positive. Try Again. \\n\") rows = input(\"Enter number of rows",
"[y/n]? \") if action == \"y\": action = input(\"\\n1. = Inverse \\n2. =",
"5. = Solve Linear Equation System\\n6. = Transpose\\n7. = Quit\\nPlease Input Numerical Value",
"in range(cols): val = input(\"Please input Value of element {}{} of Matric {}:",
"det = determinant(matrix, det = 0) print(\"\\n\\t\\t\\tDeterminant of the given Matrix is: \\033[4m\\033[1m{}\\033[0m",
"sys.exit() return action def validity_input(matrix, rows, cols): action = input(\"Do you want to",
"and action != \"n\": print(\"Error: Invalid Input. Give either 'y' or 'n'. Try",
"factorization\\n3. Finding Determinant \\n4. Transpose\\n\\n\\ This Matrix will not be used for computing",
"Value for Action. E.g. either '1' or '2': \") actions(action, matrix, rows, cols)",
"elif action == \"2\": num_of_Mat = input(\"Num of Matrices to Multiply? \") while",
"== \"y\": action = input(\"\\n1. = Inverse \\n2. = Multiplication\\n3. = LU factorization\\n4.",
"action def validity_input(matrix, rows, cols): action = input(\"Do you want to continue [y/n]?",
":) \") time.sleep(1) validity_input(matrix, rows, cols) elif action == \"5\": A, B, C,",
"validity_input(matrix, rows, cols) elif action == \"3\": (A,P,L,U) = lu_decomposition(matrix) mats = [A,P,L,U]",
"'\\033[0m') print(\"================================================================================================\") print(\"\\nEnter your matrix on which you want the actions to execute:",
"num_of_Mat = input(\"Num of Matrices to Multiply? \") while num_of_Mat.isdigit() != True: print(\"Error:",
"cols) elif action == \"4\": det = determinant(matrix, det = 0) print(\"\\n\\t\\t\\tDeterminant of",
"!= True: print(\"Error: Please give a positive numeric value\") num_of_Mat = input(\"Num of",
"mat_multiplication(mats[0], mats[1]) display_mat(\"\\nMatrix_Multiplied\\n\", None,mats[0], None,None) display_mat(\"\\nMatrix_Multiplied\\n\", None,matrix, None,None) validity_input(matrix, rows, cols) elif action",
"= input(\"Enter number of columns for Matrix {}: \".format(num+1)) rows = int(rows) cols",
"\\n\\n\") mat_A, mat_B, result = linear_system(A, B) print(\"\\nThus, \\033[1m\\033[4mSymPy output\\033[0m is:\\n\\n\\t\\t{}\\n\\nWhereas \\033[1m\\033[4mOur program",
"Value of element {}{} of Matric {}: \".format(i+1,j+1, num+1)) val = float(val) sub_matrix.append(val)",
"action = input(\"Do you want to continue [y/n]? \") if action == \"y\":",
"to give separate inputs, asked later\\n\\n\\ If there is any error, please contact",
"Matrices Do not Have Inverse.\\nPlease give Valid Inputs again\") matrix, rows, cols =",
"True or cols.isnumeric() != True): print(\"\\nError: Invalid Input. Rows and Cols can only",
"Matrix will not be used for computing \\n1. Multiplication\\n2. Solving Linear Equation System\\nYou",
"Inputs again\") matrix, rows, cols = input_mat(0) ident = identity_mat(rows,cols) new_ident, inverse_final =",
"Linear Equation System\\n6. = Transpose\\n7. = Quit\\nPlease Input Numerical Value for Action. E.g.",
"actions(action, matrix, rows, cols) else: print(\"Program Successfully Terminated\") sys.exit() return action print(\"================================================================================================\") print('\\n\\t\\t\\t\\033[1m",
"= [] for j in range(cols): val = input(\"Please input Value of element",
"\\n\") rows = input(\"Enter number of rows for Matrix {}: \".format(num+1)) cols =",
"!= \"n\": print(\"Error: Invalid Input. Give either 'y' or 'n'. Try again!\") action",
"cols = input(\"Enter number of columns for Matrix {}: \".format(num+1)) rows = int(rows)",
"elif action == \"5\": A, B, C, total = lin_input() print(\"\\n\\n\\t\\t\\033[1mFirst, solve the",
"cols) elif action == \"7\": print(\"You have Successfully Terminated the Program!\") sys.exit() else:",
"matrices if need be.\\ \\nSorry!\") validity_input(matrix, rows, cols) mats = [] for num",
"final_matrix= [] for i in range(rows): sub_matrix = [] for j in range(cols):",
"\\nThe Matrix that you are giving now can be used for finding \\n\\",
"# final_matrix, rows, cols = input_mat(0) while rows != cols: print(\"Mathematical Error: Non-Square",
"* from Inverse_mat import * from Matrix_mutliplication import * from linear_system import *",
"Again\") val = input(\"Please input Value of element {}{} of Matric {}: \".format(i+1,j+1,",
"final_matrix.append(sub_matrix) display_mat(\"\\tMatrix_{}\".format(num+1), None,final_matrix, None,None) return final_matrix, rows, cols def actions(action,matrix, rows, cols): #",
"want the actions to execute: \\n\") print(\"Directions to note \\nThe Matrix that you",
"of columns for Matrix {}: \".format(num+1)) rows = int(rows) cols = int(cols) final_matrix=",
"print('\\n\\t\\t\\t\\033[1m \\033[91m \\033[4m' + \"Matrix Calculator\\n\" + '\\033[0m') print(\"================================================================================================\") print(\"\\nEnter your matrix on",
"= Multiplication\\n3. = LU factorization\\n4. = Finding Determinant \\n\\ 5. = Solve Linear",
"input(\"Num of Matrices to Multiply? \") while num_of_Mat.isdigit() != True: print(\"Error: Please give",
"linear_system import * from LU_factorization import * from determinant import * def input_mat(num):",
"action == \"4\": det = determinant(matrix, det = 0) print(\"\\n\\t\\t\\tDeterminant of the given",
"lin(C, total) print(\"\\n\\n\\t\\t\\033[1mNow, we solve the system using our program.\\033[0m \\n\\n\") mat_A, mat_B,",
"else: print(\"Invalid input. Program Terminated.\") sys.exit() return action def validity_input(matrix, rows, cols): action",
"display_mat(\"\\n\\tMatrix_{}\\n\".format(i), None,j, None,None) print(\"\\nCalculating... Please be patient with the machine :) \") time.sleep(1)",
"you want to continue [y/n]? \") while action != \"y\" and action !=",
"= linear_system(A, B) print(\"\\nThus, \\033[1m\\033[4mSymPy output\\033[0m is:\\n\\n\\t\\t{}\\n\\nWhereas \\033[1m\\033[4mOur program output\\033[0m is:\\n\\n\\t\\t{}\\n\".format(sol, result)) validity_input(matrix,",
"mats = [A,P,L,U] mats_names = ['A','P','L','U'] for i, j in zip(mats_names, mats): display_mat(\"\\n\\tMatrix_{}\\n\".format(i),",
"input(\"Do you want to continue [y/n]? \") if action == \"y\": action =",
"{}: \".format(num+1)) while (rows.isnumeric() != True or cols.isnumeric() != True): print(\"\\nError: Invalid Input.",
"Finding Determinant \\n\\ 5. = Solve Linear Equation System\\n6. = Transpose\\n7. = Quit\\nPlease",
"positive. Try Again. \\n\") rows = input(\"Enter number of rows for Matrix {}:",
"Terminated.\") sys.exit() return action def validity_input(matrix, rows, cols): action = input(\"Do you want",
"while action != \"y\" and action != \"n\": print(\"Error: Invalid Input. Give either",
"either '1' or '2': \") actions(action, matrix, rows, cols) else: print(\"Program Successfully Terminated\")",
"with the machine :) \") time.sleep(1) validity_input(matrix, rows, cols) elif action == \"5\":",
"from Matrix_mutliplication import * from linear_system import * from LU_factorization import * from",
"time.sleep(1) validity_input(matrix, rows, cols) elif action == \"5\": A, B, C, total =",
"Try again!\") action = input(\"Do you want to continue [y/n]? \") if action",
"number of rows for Matrix {}: \".format(num+1)) cols = input(\"Enter number of columns",
"print(\"Error: Please give a positive numeric value\") num_of_Mat = input(\"Num of Matrices to",
"cols = input_mat(0) mats.append(final_mat) mat_multiplication(mats[0], mats[1]) display_mat(\"\\nMatrix_Multiplied\\n\", None,mats[0], None,None) display_mat(\"\\nMatrix_Multiplied\\n\", None,matrix, None,None) validity_input(matrix,",
"elif action == \"4\": det = determinant(matrix, det = 0) print(\"\\n\\t\\t\\tDeterminant of the",
"import * from LU_factorization import * from determinant import * def input_mat(num): rows",
"mats_names = ['A','P','L','U'] for i, j in zip(mats_names, mats): display_mat(\"\\n\\tMatrix_{}\\n\".format(i), None,j, None,None) print(\"\\nCalculating...",
"\\n\".format(det)) validity_input(matrix, rows, cols) elif action ==\"6\": t = transpose(matrix) validity_input(matrix, rows, cols)",
"'n'. Try again!\") action = input(\"Do you want to continue [y/n]? \") if",
"of element {}{} of Matric {}: \".format(i+1,j+1, num+1)) val = float(val) sub_matrix.append(val) final_matrix.append(sub_matrix)",
"'1' or '2': \") actions(action, matrix, rows, cols) else: print(\"Program Successfully Terminated\") sys.exit()",
"\".format(num+1)) cols = input(\"Enter number of columns for Matrix {}: \".format(num+1)) rows =",
"float(val) sub_matrix.append(val) final_matrix.append(sub_matrix) display_mat(\"\\tMatrix_{}\".format(num+1), None,final_matrix, None,None) return final_matrix, rows, cols def actions(action,matrix, rows,",
"rows, cols): action = input(\"Do you want to continue [y/n]? \") while action",
"==\"6\": t = transpose(matrix) validity_input(matrix, rows, cols) elif action == \"7\": print(\"You have",
"from determinant import * def input_mat(num): rows = input(\"Enter number of rows for",
"(rows.isnumeric() != True or cols.isnumeric() != True): print(\"\\nError: Invalid Input. Rows and Cols",
"Matric {}: \".format(i+1,j+1, num+1)) while val.replace(\".\", \"\", 1).lstrip('-').isdigit() != True: print(\"Error: Invalid! Try",
"input(\"Do you want to continue [y/n]? \") while action != \"y\" and action",
"int(rows) cols = int(cols) final_matrix= [] for i in range(rows): sub_matrix = []",
"!= \"n\": if action == \"1\": # final_matrix, rows, cols = input_mat(0) while",
"Inverse.\\nPlease give Valid Inputs again\") matrix, rows, cols = input_mat(0) ident = identity_mat(rows,cols)",
"num_of_Mat != 2: print(\"Error: This Code can multiply Two Matrices at a time.",
"int(cols) final_matrix= [] for i in range(rows): sub_matrix = [] for j in",
"time. \\nPlease Input two matrices and mutliply their resultant with the other matrices",
"\"4\": det = determinant(matrix, det = 0) print(\"\\n\\t\\t\\tDeterminant of the given Matrix is:",
"validity_input(matrix, rows, cols) elif action == \"7\": print(\"You have Successfully Terminated the Program!\")",
"\"y\" and action != \"n\": print(\"Error: Invalid Input. Give either 'y' or 'n'.",
"\".format(num+1)) cols = input(\"Enter number of columns for Matrix {}: \".format(num+1)) while (rows.isnumeric()",
"= input(\"Do you want to continue [y/n]? \") while action != \"y\" and",
"num in range(num_of_Mat): final_mat, rows, cols = input_mat(0) mats.append(final_mat) mat_multiplication(mats[0], mats[1]) display_mat(\"\\nMatrix_Multiplied\\n\", None,mats[0],",
"sys.exit() else: print(\"Invalid input. Program Terminated.\") sys.exit() return action def validity_input(matrix, rows, cols):",
"on which you want the actions to execute: \\n\") print(\"Directions to note \\nThe",
"= input(\"Enter number of rows for Matrix {}: \".format(num+1)) cols = input(\"Enter number",
"final_matrix, rows, cols = input_mat(0) while action.lower() != \"n\": if action == \"1\":",
"import * from Matrix_mutliplication import * from linear_system import * from LU_factorization import",
"Invalid Input. Rows and Cols can only be positive. Try Again. \\n\") rows",
"execute: \\n\") print(\"Directions to note \\nThe Matrix that you are giving now can",
"\"y\": action = input(\"\\n1. = Inverse \\n2. = Multiplication\\n3. = LU factorization\\n4. =",
"used for computing \\n1. Multiplication\\n2. Solving Linear Equation System\\nYou will have to give",
"will have to give separate inputs, asked later\\n\\n\\ If there is any error,",
"Try Again. \\n\") rows = input(\"Enter number of rows for Matrix {}: \".format(num+1))",
"mat_A, mat_B, result = linear_system(A, B) print(\"\\nThus, \\033[1m\\033[4mSymPy output\\033[0m is:\\n\\n\\t\\t{}\\n\\nWhereas \\033[1m\\033[4mOur program output\\033[0m",
"action.lower() != \"n\": if action == \"1\": # final_matrix, rows, cols = input_mat(0)",
"patient with the machine :) \") time.sleep(1) validity_input(matrix, rows, cols) elif action ==",
"determinant(matrix, det = 0) print(\"\\n\\t\\t\\tDeterminant of the given Matrix is: \\033[4m\\033[1m{}\\033[0m \\n\".format(det)) validity_input(matrix,",
"Solving Linear Equation System\\nYou will have to give separate inputs, asked later\\n\\n\\ If",
"rows, cols def actions(action,matrix, rows, cols): # final_matrix, rows, cols = input_mat(0) while",
"of Matric {}: \".format(i+1,j+1, num+1)) while val.replace(\".\", \"\", 1).lstrip('-').isdigit() != True: print(\"Error: Invalid!",
"<reponame>Wajahat-Mirza/Linear_Algebra_Project import sys import time from help_functions import * from Inverse_mat import *",
"= lu_decomposition(matrix) mats = [A,P,L,U] mats_names = ['A','P','L','U'] for i, j in zip(mats_names,",
"rows != cols: print(\"Mathematical Error: Non-Square Matrices Do not Have Inverse.\\nPlease give Valid",
"Non-Square Matrices Do not Have Inverse.\\nPlease give Valid Inputs again\") matrix, rows, cols",
"Do not Have Inverse.\\nPlease give Valid Inputs again\") matrix, rows, cols = input_mat(0)",
"= determinant(matrix, det = 0) print(\"\\n\\t\\t\\tDeterminant of the given Matrix is: \\033[4m\\033[1m{}\\033[0m \\n\".format(det))",
"\"7\": print(\"You have Successfully Terminated the Program!\") sys.exit() else: print(\"Invalid input. Program Terminated.\")",
"input_mat(0) while action.lower() != \"n\": if action == \"1\": # final_matrix, rows, cols",
"to Multiply? \") num_of_Mat = int(num_of_Mat) if num_of_Mat != 2: print(\"Error: This Code",
"= int(cols) final_matrix= [] for i in range(rows): sub_matrix = [] for j",
"LU factorization\\n4. = Finding Determinant \\n\\ 5. = Solve Linear Equation System\\n6. =",
"num+1)) while val.replace(\".\", \"\", 1).lstrip('-').isdigit() != True: print(\"Error: Invalid! Try Again\") val =",
"print(\"================================================================================================\") print(\"\\nEnter your matrix on which you want the actions to execute: \\n\")",
"validity_input(matrix, rows, cols) elif action ==\"6\": t = transpose(matrix) validity_input(matrix, rows, cols) elif",
"\") time.sleep(1) validity_input(matrix, rows, cols) elif action == \"5\": A, B, C, total",
"for Matrix {}: \".format(num+1)) rows = int(rows) cols = int(cols) final_matrix= [] for",
"sub_matrix.append(val) final_matrix.append(sub_matrix) display_mat(\"\\tMatrix_{}\".format(num+1), None,final_matrix, None,None) return final_matrix, rows, cols def actions(action,matrix, rows, cols):",
"!= True): print(\"\\nError: Invalid Input. Rows and Cols can only be positive. Try",
"!= cols: print(\"Mathematical Error: Non-Square Matrices Do not Have Inverse.\\nPlease give Valid Inputs",
"if num_of_Mat != 2: print(\"Error: This Code can multiply Two Matrices at a",
"val = input(\"Please input Value of element {}{} of Matric {}: \".format(i+1,j+1, num+1))",
"in zip(mats_names, mats): display_mat(\"\\n\\tMatrix_{}\\n\".format(i), None,j, None,None) print(\"\\nCalculating... Please be patient with the machine",
"= lin(C, total) print(\"\\n\\n\\t\\t\\033[1mNow, we solve the system using our program.\\033[0m \\n\\n\") mat_A,",
"\"2\": num_of_Mat = input(\"Num of Matrices to Multiply? \") while num_of_Mat.isdigit() != True:",
"identity_mat(rows,cols) new_ident, inverse_final = inverse(matrix, ident) validity_input(matrix, rows, cols) elif action == \"2\":",
"ident) validity_input(matrix, rows, cols) elif action == \"2\": num_of_Mat = input(\"Num of Matrices",
"Quit\\nPlease Input Numerical Value for Action. E.g. either '1' or '2': \") actions(action,",
"== \"2\": num_of_Mat = input(\"Num of Matrices to Multiply? \") while num_of_Mat.isdigit() !=",
"== \"4\": det = determinant(matrix, det = 0) print(\"\\n\\t\\t\\tDeterminant of the given Matrix",
"while val.replace(\".\", \"\", 1).lstrip('-').isdigit() != True: print(\"Error: Invalid! Try Again\") val = input(\"Please",
"[] for i in range(rows): sub_matrix = [] for j in range(cols): val",
"\\n\") print(\"Directions to note \\nThe Matrix that you are giving now can be",
"now can be used for finding \\n\\ 1. Inverse\\n2. LU factorization\\n3. Finding Determinant",
"i, j in zip(mats_names, mats): display_mat(\"\\n\\tMatrix_{}\\n\".format(i), None,j, None,None) print(\"\\nCalculating... Please be patient with",
"be positive. Try Again. \\n\") rows = input(\"Enter number of rows for Matrix",
"= int(rows) cols = int(cols) final_matrix= [] for i in range(rows): sub_matrix =",
"again!\") action = input(\"Do you want to continue [y/n]? \") if action ==",
"C, total = lin_input() print(\"\\n\\n\\t\\t\\033[1mFirst, solve the system using Sympy!\\033[0m \\n\\n\") sol =",
"help_functions import * from Inverse_mat import * from Matrix_mutliplication import * from linear_system",
"action == \"1\": # final_matrix, rows, cols = input_mat(0) while rows != cols:",
"validity_input(matrix, rows, cols) mats = [] for num in range(num_of_Mat): final_mat, rows, cols",
"rows, cols) elif action == \"4\": det = determinant(matrix, det = 0) print(\"\\n\\t\\t\\tDeterminant",
"the actions to execute: \\n\") print(\"Directions to note \\nThe Matrix that you are",
"import sys import time from help_functions import * from Inverse_mat import * from",
"det = 0) print(\"\\n\\t\\t\\tDeterminant of the given Matrix is: \\033[4m\\033[1m{}\\033[0m \\n\".format(det)) validity_input(matrix, rows,",
"rows, cols) elif action ==\"6\": t = transpose(matrix) validity_input(matrix, rows, cols) elif action",
"!= \"y\" and action != \"n\": print(\"Error: Invalid Input. Give either 'y' or",
"time from help_functions import * from Inverse_mat import * from Matrix_mutliplication import *",
"error, please contact us! Have Fun! \\n\") print(\"================================================================================================\") matrix, rows, cols = input_mat(0)",
"action ==\"6\": t = transpose(matrix) validity_input(matrix, rows, cols) elif action == \"7\": print(\"You",
"positive numeric value\") num_of_Mat = input(\"Num of Matrices to Multiply? \") num_of_Mat =",
"else: print(\"Program Successfully Terminated\") sys.exit() return action print(\"================================================================================================\") print('\\n\\t\\t\\t\\033[1m \\033[91m \\033[4m' + \"Matrix",
"the other matrices if need be.\\ \\nSorry!\") validity_input(matrix, rows, cols) mats = []",
"= identity_mat(rows,cols) new_ident, inverse_final = inverse(matrix, ident) validity_input(matrix, rows, cols) elif action ==",
"print(\"Invalid input. Program Terminated.\") sys.exit() return action def validity_input(matrix, rows, cols): action =",
"[] for j in range(cols): val = input(\"Please input Value of element {}{}",
"Again. \\n\") rows = input(\"Enter number of rows for Matrix {}: \".format(num+1)) cols",
"Matrices to Multiply? \") num_of_Mat = int(num_of_Mat) if num_of_Mat != 2: print(\"Error: This",
"\"n\": print(\"Error: Invalid Input. Give either 'y' or 'n'. Try again!\") action =",
"note \\nThe Matrix that you are giving now can be used for finding",
"Transpose\\n\\n\\ This Matrix will not be used for computing \\n1. Multiplication\\n2. Solving Linear",
"== \"1\": # final_matrix, rows, cols = input_mat(0) while rows != cols: print(\"Mathematical",
"two matrices and mutliply their resultant with the other matrices if need be.\\",
"True): print(\"\\nError: Invalid Input. Rows and Cols can only be positive. Try Again.",
"\\n2. = Multiplication\\n3. = LU factorization\\n4. = Finding Determinant \\n\\ 5. = Solve",
"solve the system using our program.\\033[0m \\n\\n\") mat_A, mat_B, result = linear_system(A, B)",
"{}{} of Matric {}: \".format(i+1,j+1, num+1)) while val.replace(\".\", \"\", 1).lstrip('-').isdigit() != True: print(\"Error:",
"want to continue [y/n]? \") while action != \"y\" and action != \"n\":",
"Finding Determinant \\n4. Transpose\\n\\n\\ This Matrix will not be used for computing \\n1.",
"which you want the actions to execute: \\n\") print(\"Directions to note \\nThe Matrix",
"while rows != cols: print(\"Mathematical Error: Non-Square Matrices Do not Have Inverse.\\nPlease give",
"us! Have Fun! \\n\") print(\"================================================================================================\") matrix, rows, cols = input_mat(0) validity_input(matrix, rows, cols)",
"cols = input_mat(0) while rows != cols: print(\"Mathematical Error: Non-Square Matrices Do not",
"j in zip(mats_names, mats): display_mat(\"\\n\\tMatrix_{}\\n\".format(i), None,j, None,None) print(\"\\nCalculating... Please be patient with the",
"for Matrix {}: \".format(num+1)) cols = input(\"Enter number of columns for Matrix {}:",
"other matrices if need be.\\ \\nSorry!\") validity_input(matrix, rows, cols) mats = [] for",
"computing \\n1. Multiplication\\n2. Solving Linear Equation System\\nYou will have to give separate inputs,",
"Equation System\\nYou will have to give separate inputs, asked later\\n\\n\\ If there is",
"num+1)) val = float(val) sub_matrix.append(val) final_matrix.append(sub_matrix) display_mat(\"\\tMatrix_{}\".format(num+1), None,final_matrix, None,None) return final_matrix, rows, cols",
"from help_functions import * from Inverse_mat import * from Matrix_mutliplication import * from",
"mats.append(final_mat) mat_multiplication(mats[0], mats[1]) display_mat(\"\\nMatrix_Multiplied\\n\", None,mats[0], None,None) display_mat(\"\\nMatrix_Multiplied\\n\", None,matrix, None,None) validity_input(matrix, rows, cols) elif",
"final_mat, rows, cols = input_mat(0) mats.append(final_mat) mat_multiplication(mats[0], mats[1]) display_mat(\"\\nMatrix_Multiplied\\n\", None,mats[0], None,None) display_mat(\"\\nMatrix_Multiplied\\n\", None,matrix,",
"action == \"3\": (A,P,L,U) = lu_decomposition(matrix) mats = [A,P,L,U] mats_names = ['A','P','L','U'] for",
"your matrix on which you want the actions to execute: \\n\") print(\"Directions to",
"display_mat(\"\\tMatrix_{}\".format(num+1), None,final_matrix, None,None) return final_matrix, rows, cols def actions(action,matrix, rows, cols): # final_matrix,",
"= input_mat(0) while rows != cols: print(\"Mathematical Error: Non-Square Matrices Do not Have",
"rows, cols) else: print(\"Program Successfully Terminated\") sys.exit() return action print(\"================================================================================================\") print('\\n\\t\\t\\t\\033[1m \\033[91m \\033[4m'",
"for i, j in zip(mats_names, mats): display_mat(\"\\n\\tMatrix_{}\\n\".format(i), None,j, None,None) print(\"\\nCalculating... Please be patient",
"['A','P','L','U'] for i, j in zip(mats_names, mats): display_mat(\"\\n\\tMatrix_{}\\n\".format(i), None,j, None,None) print(\"\\nCalculating... Please be",
"print(\"Error: Invalid! Try Again\") val = input(\"Please input Value of element {}{} of",
"= input(\"Num of Matrices to Multiply? \") while num_of_Mat.isdigit() != True: print(\"Error: Please",
"!= 2: print(\"Error: This Code can multiply Two Matrices at a time. \\nPlease",
"input Value of element {}{} of Matric {}: \".format(i+1,j+1, num+1)) val = float(val)",
"of Matrices to Multiply? \") while num_of_Mat.isdigit() != True: print(\"Error: Please give a",
"Invalid! Try Again\") val = input(\"Please input Value of element {}{} of Matric",
"ident = identity_mat(rows,cols) new_ident, inverse_final = inverse(matrix, ident) validity_input(matrix, rows, cols) elif action",
"lin_input() print(\"\\n\\n\\t\\t\\033[1mFirst, solve the system using Sympy!\\033[0m \\n\\n\") sol = lin(C, total) print(\"\\n\\n\\t\\t\\033[1mNow,",
"will not be used for computing \\n1. Multiplication\\n2. Solving Linear Equation System\\nYou will",
"rows, cols) elif action == \"2\": num_of_Mat = input(\"Num of Matrices to Multiply?",
"!= True: print(\"Error: Invalid! Try Again\") val = input(\"Please input Value of element",
"give Valid Inputs again\") matrix, rows, cols = input_mat(0) ident = identity_mat(rows,cols) new_ident,",
"= Quit\\nPlease Input Numerical Value for Action. E.g. either '1' or '2': \")",
"Program!\") sys.exit() else: print(\"Invalid input. Program Terminated.\") sys.exit() return action def validity_input(matrix, rows,",
"columns for Matrix {}: \".format(num+1)) rows = int(rows) cols = int(cols) final_matrix= []",
"Try Again\") val = input(\"Please input Value of element {}{} of Matric {}:",
"number of columns for Matrix {}: \".format(num+1)) rows = int(rows) cols = int(cols)",
"# final_matrix, rows, cols = input_mat(0) while action.lower() != \"n\": if action ==",
"to note \\nThe Matrix that you are giving now can be used for",
"\"5\": A, B, C, total = lin_input() print(\"\\n\\n\\t\\t\\033[1mFirst, solve the system using Sympy!\\033[0m",
"\\n\\n\") sol = lin(C, total) print(\"\\n\\n\\t\\t\\033[1mNow, we solve the system using our program.\\033[0m",
"the Program!\") sys.exit() else: print(\"Invalid input. Program Terminated.\") sys.exit() return action def validity_input(matrix,"
] |
[
"import urlparse, urlunparse from functools import wraps from flask import abort, request, current_app",
"Adapted from https://www.twilio.com/docs/usage/tutorials/how-to-secure-your-flask-app-by-validating-incoming-twilio-requests?code-sample=code-custom-decorator-for-flask-apps-to-validate-twilio-requests-3&code-language=Python&code-sdk-version=6.x @wraps(f) def decorated_function(*args, **kwargs): twilio_client = TwilioClient( current_app.config['SECRETS'].TWILIO_ACCOUNT_SID, current_app.config['SECRETS'].TWILIO_AUTH_TOKEN )",
"http://localhost:5000 So we replace the domain our app sees with the X-Original-Host header",
"https://custom-domain.com/bot/validate-next-alert App sees: https://custom-domain.com/{stage}/bot/validate-next-alert So we strip API_GATEWAY_BASE_PATH from the beginning of the",
"validate_twilio_request(f): \"\"\"Validates that incoming requests genuinely originated from Twilio\"\"\" # Adapted from https://www.twilio.com/docs/usage/tutorials/how-to-secure-your-flask-app-by-validating-incoming-twilio-requests?code-sample=code-custom-decorator-for-flask-apps-to-validate-twilio-requests-3&code-language=Python&code-sdk-version=6.x",
"chars from beginning of path. chars_to_strip = len(f\"/{api_gateway_base_path}\") new_path = twilio_url_parts.path[chars_to_strip:] twilio_url_parts =",
"= len(f\"/{api_gateway_base_path}\") new_path = twilio_url_parts.path[chars_to_strip:] twilio_url_parts = twilio_url_parts._replace(path=new_path) # Validate the request using",
"TwilioClient( current_app.config['SECRETS'].TWILIO_ACCOUNT_SID, current_app.config['SECRETS'].TWILIO_AUTH_TOKEN ) # save variables from original request as we will",
"twilio_url_parts = twilio_url_parts._replace(netloc=original_host_header) \"\"\" Solve issues with API Gateway custom domains Twilio sees:",
"domain our app sees with the X-Original-Host header \"\"\" if original_host_header: twilio_url_parts =",
"POST data, and X-TWILIO-SIGNATURE header request_valid = twilio_client.validate_request( urlunparse(twilio_url_parts), request.form, request.headers.get('X-TWILIO-SIGNATURE', '') )",
"\"\"\" Solve issues with NGROK Twilio sees: http://somedomain.ngrok.io App sees: http://localhost:5000 So we",
"from the beginning of the path \"\"\" api_gateway_base_path = current_app.config['API_GATEWAY_BASE_PATH'] if api_gateway_base_path: #",
"chars_to_strip = len(f\"/{api_gateway_base_path}\") new_path = twilio_url_parts.path[chars_to_strip:] twilio_url_parts = twilio_url_parts._replace(path=new_path) # Validate the request",
"return a 403 error if it's not if request_valid: return f(*args, **kwargs) else:",
"request.headers.get('X-Original-Host') # the url parts to be transformed twilio_url_parts = urlparse(original_url) \"\"\" Solve",
"current_app.config['API_GATEWAY_BASE_PATH'] if api_gateway_base_path: # Strip N chars from beginning of path. chars_to_strip =",
"def validate_twilio_request(f): \"\"\"Validates that incoming requests genuinely originated from Twilio\"\"\" # Adapted from",
"the request using its URL, POST data, and X-TWILIO-SIGNATURE header request_valid = twilio_client.validate_request(",
"beginning of path. chars_to_strip = len(f\"/{api_gateway_base_path}\") new_path = twilio_url_parts.path[chars_to_strip:] twilio_url_parts = twilio_url_parts._replace(path=new_path) #",
"request, current_app from lib.twilio import TwilioClient def validate_twilio_request(f): \"\"\"Validates that incoming requests genuinely",
"= twilio_url_parts._replace(netloc=original_host_header) \"\"\" Solve issues with API Gateway custom domains Twilio sees: https://custom-domain.com/bot/validate-next-alert",
"= twilio_url_parts._replace(path=new_path) # Validate the request using its URL, POST data, and X-TWILIO-SIGNATURE",
"parts to be transformed twilio_url_parts = urlparse(original_url) \"\"\" Solve issues with NGROK Twilio",
"So we replace the domain our app sees with the X-Original-Host header \"\"\"",
"lib.twilio import TwilioClient def validate_twilio_request(f): \"\"\"Validates that incoming requests genuinely originated from Twilio\"\"\"",
"= twilio_client.validate_request( urlunparse(twilio_url_parts), request.form, request.headers.get('X-TWILIO-SIGNATURE', '') ) # Continue processing the request if",
"with NGROK Twilio sees: http://somedomain.ngrok.io App sees: http://localhost:5000 So we replace the domain",
"on it below original_url = request.url original_host_header = request.headers.get('X-Original-Host') # the url parts",
"with API Gateway custom domains Twilio sees: https://custom-domain.com/bot/validate-next-alert App sees: https://custom-domain.com/{stage}/bot/validate-next-alert So we",
"# save variables from original request as we will be making transformations on",
"Validate the request using its URL, POST data, and X-TWILIO-SIGNATURE header request_valid =",
"api_gateway_base_path = current_app.config['API_GATEWAY_BASE_PATH'] if api_gateway_base_path: # Strip N chars from beginning of path.",
"Twilio\"\"\" # Adapted from https://www.twilio.com/docs/usage/tutorials/how-to-secure-your-flask-app-by-validating-incoming-twilio-requests?code-sample=code-custom-decorator-for-flask-apps-to-validate-twilio-requests-3&code-language=Python&code-sdk-version=6.x @wraps(f) def decorated_function(*args, **kwargs): twilio_client = TwilioClient( current_app.config['SECRETS'].TWILIO_ACCOUNT_SID,",
"its URL, POST data, and X-TWILIO-SIGNATURE header request_valid = twilio_client.validate_request( urlunparse(twilio_url_parts), request.form, request.headers.get('X-TWILIO-SIGNATURE',",
"@wraps(f) def decorated_function(*args, **kwargs): twilio_client = TwilioClient( current_app.config['SECRETS'].TWILIO_ACCOUNT_SID, current_app.config['SECRETS'].TWILIO_AUTH_TOKEN ) # save variables",
"Solve issues with NGROK Twilio sees: http://somedomain.ngrok.io App sees: http://localhost:5000 So we replace",
"transformations on it below original_url = request.url original_host_header = request.headers.get('X-Original-Host') # the url",
"twilio_client.validate_request( urlunparse(twilio_url_parts), request.form, request.headers.get('X-TWILIO-SIGNATURE', '') ) # Continue processing the request if it's",
"making transformations on it below original_url = request.url original_host_header = request.headers.get('X-Original-Host') # the",
"\"\"\" api_gateway_base_path = current_app.config['API_GATEWAY_BASE_PATH'] if api_gateway_base_path: # Strip N chars from beginning of",
"request using its URL, POST data, and X-TWILIO-SIGNATURE header request_valid = twilio_client.validate_request( urlunparse(twilio_url_parts),",
"it's valid, return a 403 error if it's not if request_valid: return f(*args,",
"a 403 error if it's not if request_valid: return f(*args, **kwargs) else: return",
"= twilio_url_parts.path[chars_to_strip:] twilio_url_parts = twilio_url_parts._replace(path=new_path) # Validate the request using its URL, POST",
"Twilio sees: https://custom-domain.com/bot/validate-next-alert App sees: https://custom-domain.com/{stage}/bot/validate-next-alert So we strip API_GATEWAY_BASE_PATH from the beginning",
"strip API_GATEWAY_BASE_PATH from the beginning of the path \"\"\" api_gateway_base_path = current_app.config['API_GATEWAY_BASE_PATH'] if",
"incoming requests genuinely originated from Twilio\"\"\" # Adapted from https://www.twilio.com/docs/usage/tutorials/how-to-secure-your-flask-app-by-validating-incoming-twilio-requests?code-sample=code-custom-decorator-for-flask-apps-to-validate-twilio-requests-3&code-language=Python&code-sdk-version=6.x @wraps(f) def decorated_function(*args,",
"to be transformed twilio_url_parts = urlparse(original_url) \"\"\" Solve issues with NGROK Twilio sees:",
"and X-TWILIO-SIGNATURE header request_valid = twilio_client.validate_request( urlunparse(twilio_url_parts), request.form, request.headers.get('X-TWILIO-SIGNATURE', '') ) # Continue",
"Solve issues with API Gateway custom domains Twilio sees: https://custom-domain.com/bot/validate-next-alert App sees: https://custom-domain.com/{stage}/bot/validate-next-alert",
"**kwargs): twilio_client = TwilioClient( current_app.config['SECRETS'].TWILIO_ACCOUNT_SID, current_app.config['SECRETS'].TWILIO_AUTH_TOKEN ) # save variables from original request",
"the path \"\"\" api_gateway_base_path = current_app.config['API_GATEWAY_BASE_PATH'] if api_gateway_base_path: # Strip N chars from",
"twilio_client = TwilioClient( current_app.config['SECRETS'].TWILIO_ACCOUNT_SID, current_app.config['SECRETS'].TWILIO_AUTH_TOKEN ) # save variables from original request as",
"Gateway custom domains Twilio sees: https://custom-domain.com/bot/validate-next-alert App sees: https://custom-domain.com/{stage}/bot/validate-next-alert So we strip API_GATEWAY_BASE_PATH",
"path. chars_to_strip = len(f\"/{api_gateway_base_path}\") new_path = twilio_url_parts.path[chars_to_strip:] twilio_url_parts = twilio_url_parts._replace(path=new_path) # Validate the",
"wraps from flask import abort, request, current_app from lib.twilio import TwilioClient def validate_twilio_request(f):",
"sees: https://custom-domain.com/bot/validate-next-alert App sees: https://custom-domain.com/{stage}/bot/validate-next-alert So we strip API_GATEWAY_BASE_PATH from the beginning of",
"of path. chars_to_strip = len(f\"/{api_gateway_base_path}\") new_path = twilio_url_parts.path[chars_to_strip:] twilio_url_parts = twilio_url_parts._replace(path=new_path) # Validate",
"urlunparse from functools import wraps from flask import abort, request, current_app from lib.twilio",
"= current_app.config['API_GATEWAY_BASE_PATH'] if api_gateway_base_path: # Strip N chars from beginning of path. chars_to_strip",
"from functools import wraps from flask import abort, request, current_app from lib.twilio import",
"from original request as we will be making transformations on it below original_url",
"genuinely originated from Twilio\"\"\" # Adapted from https://www.twilio.com/docs/usage/tutorials/how-to-secure-your-flask-app-by-validating-incoming-twilio-requests?code-sample=code-custom-decorator-for-flask-apps-to-validate-twilio-requests-3&code-language=Python&code-sdk-version=6.x @wraps(f) def decorated_function(*args, **kwargs): twilio_client",
"data, and X-TWILIO-SIGNATURE header request_valid = twilio_client.validate_request( urlunparse(twilio_url_parts), request.form, request.headers.get('X-TWILIO-SIGNATURE', '') ) #",
"api_gateway_base_path: # Strip N chars from beginning of path. chars_to_strip = len(f\"/{api_gateway_base_path}\") new_path",
"request_valid = twilio_client.validate_request( urlunparse(twilio_url_parts), request.form, request.headers.get('X-TWILIO-SIGNATURE', '') ) # Continue processing the request",
"if it's not if request_valid: return f(*args, **kwargs) else: return abort(403) return decorated_function",
"= request.url original_host_header = request.headers.get('X-Original-Host') # the url parts to be transformed twilio_url_parts",
"the X-Original-Host header \"\"\" if original_host_header: twilio_url_parts = twilio_url_parts._replace(netloc=original_host_header) \"\"\" Solve issues with",
"twilio_url_parts = twilio_url_parts._replace(path=new_path) # Validate the request using its URL, POST data, and",
"original request as we will be making transformations on it below original_url =",
"if original_host_header: twilio_url_parts = twilio_url_parts._replace(netloc=original_host_header) \"\"\" Solve issues with API Gateway custom domains",
"twilio_url_parts._replace(netloc=original_host_header) \"\"\" Solve issues with API Gateway custom domains Twilio sees: https://custom-domain.com/bot/validate-next-alert App",
"len(f\"/{api_gateway_base_path}\") new_path = twilio_url_parts.path[chars_to_strip:] twilio_url_parts = twilio_url_parts._replace(path=new_path) # Validate the request using its",
") # save variables from original request as we will be making transformations",
"import TwilioClient def validate_twilio_request(f): \"\"\"Validates that incoming requests genuinely originated from Twilio\"\"\" #",
"abort, request, current_app from lib.twilio import TwilioClient def validate_twilio_request(f): \"\"\"Validates that incoming requests",
"urlparse, urlunparse from functools import wraps from flask import abort, request, current_app from",
"request if it's valid, return a 403 error if it's not if request_valid:",
"below original_url = request.url original_host_header = request.headers.get('X-Original-Host') # the url parts to be",
"def decorated_function(*args, **kwargs): twilio_client = TwilioClient( current_app.config['SECRETS'].TWILIO_ACCOUNT_SID, current_app.config['SECRETS'].TWILIO_AUTH_TOKEN ) # save variables from",
"if it's valid, return a 403 error if it's not if request_valid: return",
"functools import wraps from flask import abort, request, current_app from lib.twilio import TwilioClient",
"beginning of the path \"\"\" api_gateway_base_path = current_app.config['API_GATEWAY_BASE_PATH'] if api_gateway_base_path: # Strip N",
"So we strip API_GATEWAY_BASE_PATH from the beginning of the path \"\"\" api_gateway_base_path =",
"# Continue processing the request if it's valid, return a 403 error if",
"twilio_url_parts._replace(path=new_path) # Validate the request using its URL, POST data, and X-TWILIO-SIGNATURE header",
"the request if it's valid, return a 403 error if it's not if",
"Continue processing the request if it's valid, return a 403 error if it's",
"we will be making transformations on it below original_url = request.url original_host_header =",
"app sees with the X-Original-Host header \"\"\" if original_host_header: twilio_url_parts = twilio_url_parts._replace(netloc=original_host_header) \"\"\"",
"save variables from original request as we will be making transformations on it",
"# Validate the request using its URL, POST data, and X-TWILIO-SIGNATURE header request_valid",
") # Continue processing the request if it's valid, return a 403 error",
"import wraps from flask import abort, request, current_app from lib.twilio import TwilioClient def",
"request.headers.get('X-TWILIO-SIGNATURE', '') ) # Continue processing the request if it's valid, return a",
"using its URL, POST data, and X-TWILIO-SIGNATURE header request_valid = twilio_client.validate_request( urlunparse(twilio_url_parts), request.form,",
"URL, POST data, and X-TWILIO-SIGNATURE header request_valid = twilio_client.validate_request( urlunparse(twilio_url_parts), request.form, request.headers.get('X-TWILIO-SIGNATURE', '')",
"N chars from beginning of path. chars_to_strip = len(f\"/{api_gateway_base_path}\") new_path = twilio_url_parts.path[chars_to_strip:] twilio_url_parts",
"from https://www.twilio.com/docs/usage/tutorials/how-to-secure-your-flask-app-by-validating-incoming-twilio-requests?code-sample=code-custom-decorator-for-flask-apps-to-validate-twilio-requests-3&code-language=Python&code-sdk-version=6.x @wraps(f) def decorated_function(*args, **kwargs): twilio_client = TwilioClient( current_app.config['SECRETS'].TWILIO_ACCOUNT_SID, current_app.config['SECRETS'].TWILIO_AUTH_TOKEN ) #",
"original_host_header: twilio_url_parts = twilio_url_parts._replace(netloc=original_host_header) \"\"\" Solve issues with API Gateway custom domains Twilio",
"from lib.twilio import TwilioClient def validate_twilio_request(f): \"\"\"Validates that incoming requests genuinely originated from",
"be making transformations on it below original_url = request.url original_host_header = request.headers.get('X-Original-Host') #",
"custom domains Twilio sees: https://custom-domain.com/bot/validate-next-alert App sees: https://custom-domain.com/{stage}/bot/validate-next-alert So we strip API_GATEWAY_BASE_PATH from",
"twilio_url_parts = urlparse(original_url) \"\"\" Solve issues with NGROK Twilio sees: http://somedomain.ngrok.io App sees:",
"import abort, request, current_app from lib.twilio import TwilioClient def validate_twilio_request(f): \"\"\"Validates that incoming",
"urlunparse(twilio_url_parts), request.form, request.headers.get('X-TWILIO-SIGNATURE', '') ) # Continue processing the request if it's valid,",
"issues with API Gateway custom domains Twilio sees: https://custom-domain.com/bot/validate-next-alert App sees: https://custom-domain.com/{stage}/bot/validate-next-alert So",
"from urllib.parse import urlparse, urlunparse from functools import wraps from flask import abort,",
"API_GATEWAY_BASE_PATH from the beginning of the path \"\"\" api_gateway_base_path = current_app.config['API_GATEWAY_BASE_PATH'] if api_gateway_base_path:",
"# Adapted from https://www.twilio.com/docs/usage/tutorials/how-to-secure-your-flask-app-by-validating-incoming-twilio-requests?code-sample=code-custom-decorator-for-flask-apps-to-validate-twilio-requests-3&code-language=Python&code-sdk-version=6.x @wraps(f) def decorated_function(*args, **kwargs): twilio_client = TwilioClient( current_app.config['SECRETS'].TWILIO_ACCOUNT_SID, current_app.config['SECRETS'].TWILIO_AUTH_TOKEN",
"urllib.parse import urlparse, urlunparse from functools import wraps from flask import abort, request,",
"header \"\"\" if original_host_header: twilio_url_parts = twilio_url_parts._replace(netloc=original_host_header) \"\"\" Solve issues with API Gateway",
"http://somedomain.ngrok.io App sees: http://localhost:5000 So we replace the domain our app sees with",
"sees: http://localhost:5000 So we replace the domain our app sees with the X-Original-Host",
"decorated_function(*args, **kwargs): twilio_client = TwilioClient( current_app.config['SECRETS'].TWILIO_ACCOUNT_SID, current_app.config['SECRETS'].TWILIO_AUTH_TOKEN ) # save variables from original",
"https://www.twilio.com/docs/usage/tutorials/how-to-secure-your-flask-app-by-validating-incoming-twilio-requests?code-sample=code-custom-decorator-for-flask-apps-to-validate-twilio-requests-3&code-language=Python&code-sdk-version=6.x @wraps(f) def decorated_function(*args, **kwargs): twilio_client = TwilioClient( current_app.config['SECRETS'].TWILIO_ACCOUNT_SID, current_app.config['SECRETS'].TWILIO_AUTH_TOKEN ) # save",
"we replace the domain our app sees with the X-Original-Host header \"\"\" if",
"Strip N chars from beginning of path. chars_to_strip = len(f\"/{api_gateway_base_path}\") new_path = twilio_url_parts.path[chars_to_strip:]",
"original_host_header = request.headers.get('X-Original-Host') # the url parts to be transformed twilio_url_parts = urlparse(original_url)",
"from Twilio\"\"\" # Adapted from https://www.twilio.com/docs/usage/tutorials/how-to-secure-your-flask-app-by-validating-incoming-twilio-requests?code-sample=code-custom-decorator-for-flask-apps-to-validate-twilio-requests-3&code-language=Python&code-sdk-version=6.x @wraps(f) def decorated_function(*args, **kwargs): twilio_client = TwilioClient(",
"if api_gateway_base_path: # Strip N chars from beginning of path. chars_to_strip = len(f\"/{api_gateway_base_path}\")",
"the beginning of the path \"\"\" api_gateway_base_path = current_app.config['API_GATEWAY_BASE_PATH'] if api_gateway_base_path: # Strip",
"current_app.config['SECRETS'].TWILIO_AUTH_TOKEN ) # save variables from original request as we will be making",
"the domain our app sees with the X-Original-Host header \"\"\" if original_host_header: twilio_url_parts",
"from flask import abort, request, current_app from lib.twilio import TwilioClient def validate_twilio_request(f): \"\"\"Validates",
"our app sees with the X-Original-Host header \"\"\" if original_host_header: twilio_url_parts = twilio_url_parts._replace(netloc=original_host_header)",
"# Strip N chars from beginning of path. chars_to_strip = len(f\"/{api_gateway_base_path}\") new_path =",
"from beginning of path. chars_to_strip = len(f\"/{api_gateway_base_path}\") new_path = twilio_url_parts.path[chars_to_strip:] twilio_url_parts = twilio_url_parts._replace(path=new_path)",
"processing the request if it's valid, return a 403 error if it's not",
"header request_valid = twilio_client.validate_request( urlunparse(twilio_url_parts), request.form, request.headers.get('X-TWILIO-SIGNATURE', '') ) # Continue processing the",
"sees: https://custom-domain.com/{stage}/bot/validate-next-alert So we strip API_GATEWAY_BASE_PATH from the beginning of the path \"\"\"",
"flask import abort, request, current_app from lib.twilio import TwilioClient def validate_twilio_request(f): \"\"\"Validates that",
"request.url original_host_header = request.headers.get('X-Original-Host') # the url parts to be transformed twilio_url_parts =",
"request as we will be making transformations on it below original_url = request.url",
"of the path \"\"\" api_gateway_base_path = current_app.config['API_GATEWAY_BASE_PATH'] if api_gateway_base_path: # Strip N chars",
"twilio_url_parts.path[chars_to_strip:] twilio_url_parts = twilio_url_parts._replace(path=new_path) # Validate the request using its URL, POST data,",
"App sees: https://custom-domain.com/{stage}/bot/validate-next-alert So we strip API_GATEWAY_BASE_PATH from the beginning of the path",
"error if it's not if request_valid: return f(*args, **kwargs) else: return abort(403) return",
"variables from original request as we will be making transformations on it below",
"NGROK Twilio sees: http://somedomain.ngrok.io App sees: http://localhost:5000 So we replace the domain our",
"current_app from lib.twilio import TwilioClient def validate_twilio_request(f): \"\"\"Validates that incoming requests genuinely originated",
"urlparse(original_url) \"\"\" Solve issues with NGROK Twilio sees: http://somedomain.ngrok.io App sees: http://localhost:5000 So",
"it below original_url = request.url original_host_header = request.headers.get('X-Original-Host') # the url parts to",
"we strip API_GATEWAY_BASE_PATH from the beginning of the path \"\"\" api_gateway_base_path = current_app.config['API_GATEWAY_BASE_PATH']",
"will be making transformations on it below original_url = request.url original_host_header = request.headers.get('X-Original-Host')",
"as we will be making transformations on it below original_url = request.url original_host_header",
"that incoming requests genuinely originated from Twilio\"\"\" # Adapted from https://www.twilio.com/docs/usage/tutorials/how-to-secure-your-flask-app-by-validating-incoming-twilio-requests?code-sample=code-custom-decorator-for-flask-apps-to-validate-twilio-requests-3&code-language=Python&code-sdk-version=6.x @wraps(f) def",
"X-Original-Host header \"\"\" if original_host_header: twilio_url_parts = twilio_url_parts._replace(netloc=original_host_header) \"\"\" Solve issues with API",
"\"\"\"Validates that incoming requests genuinely originated from Twilio\"\"\" # Adapted from https://www.twilio.com/docs/usage/tutorials/how-to-secure-your-flask-app-by-validating-incoming-twilio-requests?code-sample=code-custom-decorator-for-flask-apps-to-validate-twilio-requests-3&code-language=Python&code-sdk-version=6.x @wraps(f)",
"with the X-Original-Host header \"\"\" if original_host_header: twilio_url_parts = twilio_url_parts._replace(netloc=original_host_header) \"\"\" Solve issues",
"\"\"\" if original_host_header: twilio_url_parts = twilio_url_parts._replace(netloc=original_host_header) \"\"\" Solve issues with API Gateway custom",
"X-TWILIO-SIGNATURE header request_valid = twilio_client.validate_request( urlunparse(twilio_url_parts), request.form, request.headers.get('X-TWILIO-SIGNATURE', '') ) # Continue processing",
"API Gateway custom domains Twilio sees: https://custom-domain.com/bot/validate-next-alert App sees: https://custom-domain.com/{stage}/bot/validate-next-alert So we strip",
"valid, return a 403 error if it's not if request_valid: return f(*args, **kwargs)",
"domains Twilio sees: https://custom-domain.com/bot/validate-next-alert App sees: https://custom-domain.com/{stage}/bot/validate-next-alert So we strip API_GATEWAY_BASE_PATH from the",
"'') ) # Continue processing the request if it's valid, return a 403",
"= TwilioClient( current_app.config['SECRETS'].TWILIO_ACCOUNT_SID, current_app.config['SECRETS'].TWILIO_AUTH_TOKEN ) # save variables from original request as we",
"sees: http://somedomain.ngrok.io App sees: http://localhost:5000 So we replace the domain our app sees",
"\"\"\" Solve issues with API Gateway custom domains Twilio sees: https://custom-domain.com/bot/validate-next-alert App sees:",
"TwilioClient def validate_twilio_request(f): \"\"\"Validates that incoming requests genuinely originated from Twilio\"\"\" # Adapted",
"replace the domain our app sees with the X-Original-Host header \"\"\" if original_host_header:",
"transformed twilio_url_parts = urlparse(original_url) \"\"\" Solve issues with NGROK Twilio sees: http://somedomain.ngrok.io App",
"be transformed twilio_url_parts = urlparse(original_url) \"\"\" Solve issues with NGROK Twilio sees: http://somedomain.ngrok.io",
"= request.headers.get('X-Original-Host') # the url parts to be transformed twilio_url_parts = urlparse(original_url) \"\"\"",
"the url parts to be transformed twilio_url_parts = urlparse(original_url) \"\"\" Solve issues with",
"requests genuinely originated from Twilio\"\"\" # Adapted from https://www.twilio.com/docs/usage/tutorials/how-to-secure-your-flask-app-by-validating-incoming-twilio-requests?code-sample=code-custom-decorator-for-flask-apps-to-validate-twilio-requests-3&code-language=Python&code-sdk-version=6.x @wraps(f) def decorated_function(*args, **kwargs):",
"# the url parts to be transformed twilio_url_parts = urlparse(original_url) \"\"\" Solve issues",
"originated from Twilio\"\"\" # Adapted from https://www.twilio.com/docs/usage/tutorials/how-to-secure-your-flask-app-by-validating-incoming-twilio-requests?code-sample=code-custom-decorator-for-flask-apps-to-validate-twilio-requests-3&code-language=Python&code-sdk-version=6.x @wraps(f) def decorated_function(*args, **kwargs): twilio_client =",
"url parts to be transformed twilio_url_parts = urlparse(original_url) \"\"\" Solve issues with NGROK",
"Twilio sees: http://somedomain.ngrok.io App sees: http://localhost:5000 So we replace the domain our app",
"App sees: http://localhost:5000 So we replace the domain our app sees with the",
"403 error if it's not if request_valid: return f(*args, **kwargs) else: return abort(403)",
"= urlparse(original_url) \"\"\" Solve issues with NGROK Twilio sees: http://somedomain.ngrok.io App sees: http://localhost:5000",
"original_url = request.url original_host_header = request.headers.get('X-Original-Host') # the url parts to be transformed",
"https://custom-domain.com/{stage}/bot/validate-next-alert So we strip API_GATEWAY_BASE_PATH from the beginning of the path \"\"\" api_gateway_base_path",
"issues with NGROK Twilio sees: http://somedomain.ngrok.io App sees: http://localhost:5000 So we replace the",
"request.form, request.headers.get('X-TWILIO-SIGNATURE', '') ) # Continue processing the request if it's valid, return",
"current_app.config['SECRETS'].TWILIO_ACCOUNT_SID, current_app.config['SECRETS'].TWILIO_AUTH_TOKEN ) # save variables from original request as we will be",
"sees with the X-Original-Host header \"\"\" if original_host_header: twilio_url_parts = twilio_url_parts._replace(netloc=original_host_header) \"\"\" Solve",
"new_path = twilio_url_parts.path[chars_to_strip:] twilio_url_parts = twilio_url_parts._replace(path=new_path) # Validate the request using its URL,",
"path \"\"\" api_gateway_base_path = current_app.config['API_GATEWAY_BASE_PATH'] if api_gateway_base_path: # Strip N chars from beginning"
] |
[
"to a Telegram chat. Uses per default credentials stored in environment. \"\"\" API_URL",
"chat_id is not None: self.api_token = api_token self.chat_id = chat_id else: self.api_token =",
"= { 'chat_id': (None, self.chat_id), 'video': (str(p), open(p, 'rb')) } r = requests.post(url,",
"is not None and chat_id is not None: self.api_token = api_token self.chat_id =",
"pathlib import Path import requests from rpicam.utils.logging_utils import get_logger class TelegramPoster: \"\"\" Bare-bones",
"'video': (str(p), open(p, 'rb')) } r = requests.post(url, files=files) if r.status_code != 200:",
"self.chat_id = chat_id else: self.api_token = os.getenv(self.API_TOKEN_ENV_VAR, None) self.chat_id = os.getenv(self.CHAT_ID_ENV_VAR, None) self._logger",
"os.getenv(self.API_TOKEN_ENV_VAR, None) self.chat_id = os.getenv(self.CHAT_ID_ENV_VAR, None) self._logger = get_logger(self.__class__.__name__, verb=True) if self.api_token is",
"self.chat_id = os.getenv(self.CHAT_ID_ENV_VAR, None) self._logger = get_logger(self.__class__.__name__, verb=True) if self.api_token is None or",
"found: {p}') url = f'{self.API_URL}/bot{self.api_token}/sendVideo' files = { 'chat_id': (None, self.chat_id), 'video': (str(p),",
"stored credentials.\"\"\" p = Path(str(p)).resolve() if not p.is_file(): raise RuntimeError(f'file not found: {p}')",
"in environment.') def send_video(self, p: Union[Path, str]): \"\"\"Post the given video to Telegram",
"files=files) if r.status_code != 200: self._logger.error(f'Could not upload file. Exit code was {r.status_code}')",
"given video to Telegram using stored credentials.\"\"\" p = Path(str(p)).resolve() if not p.is_file():",
"not find Telegram credentials in environment.') def send_video(self, p: Union[Path, str]): \"\"\"Post the",
"= f'{self.API_URL}/bot{self.api_token}/sendVideo' files = { 'chat_id': (None, self.chat_id), 'video': (str(p), open(p, 'rb')) }",
"post videos to a Telegram chat. Uses per default credentials stored in environment.",
"requests from rpicam.utils.logging_utils import get_logger class TelegramPoster: \"\"\" Bare-bones class to post videos",
"api_token self.chat_id = chat_id else: self.api_token = os.getenv(self.API_TOKEN_ENV_VAR, None) self.chat_id = os.getenv(self.CHAT_ID_ENV_VAR, None)",
"get_logger(self.__class__.__name__, verb=True) if self.api_token is None or self.chat_id is None: raise RuntimeError('Could not",
"api_token: str = None, chat_id: str = None): if api_token is not None",
"the given video to Telegram using stored credentials.\"\"\" p = Path(str(p)).resolve() if not",
"str = None): if api_token is not None and chat_id is not None:",
"environment.') def send_video(self, p: Union[Path, str]): \"\"\"Post the given video to Telegram using",
"chat_id else: self.api_token = os.getenv(self.API_TOKEN_ENV_VAR, None) self.chat_id = os.getenv(self.CHAT_ID_ENV_VAR, None) self._logger = get_logger(self.__class__.__name__,",
"Union from pathlib import Path import requests from rpicam.utils.logging_utils import get_logger class TelegramPoster:",
"= os.getenv(self.CHAT_ID_ENV_VAR, None) self._logger = get_logger(self.__class__.__name__, verb=True) if self.api_token is None or self.chat_id",
"= None, chat_id: str = None): if api_token is not None and chat_id",
"api_token is not None and chat_id is not None: self.api_token = api_token self.chat_id",
"import Path import requests from rpicam.utils.logging_utils import get_logger class TelegramPoster: \"\"\" Bare-bones class",
"or self.chat_id is None: raise RuntimeError('Could not find Telegram credentials in environment.') def",
"RuntimeError('Could not find Telegram credentials in environment.') def send_video(self, p: Union[Path, str]): \"\"\"Post",
"send_video(self, p: Union[Path, str]): \"\"\"Post the given video to Telegram using stored credentials.\"\"\"",
"if api_token is not None and chat_id is not None: self.api_token = api_token",
"os from typing import Union from pathlib import Path import requests from rpicam.utils.logging_utils",
"r = requests.post(url, files=files) if r.status_code != 200: self._logger.error(f'Could not upload file. Exit",
"Telegram credentials in environment.') def send_video(self, p: Union[Path, str]): \"\"\"Post the given video",
"= api_token self.chat_id = chat_id else: self.api_token = os.getenv(self.API_TOKEN_ENV_VAR, None) self.chat_id = os.getenv(self.CHAT_ID_ENV_VAR,",
"'chat_id': (None, self.chat_id), 'video': (str(p), open(p, 'rb')) } r = requests.post(url, files=files) if",
"p.is_file(): raise RuntimeError(f'file not found: {p}') url = f'{self.API_URL}/bot{self.api_token}/sendVideo' files = { 'chat_id':",
"is None or self.chat_id is None: raise RuntimeError('Could not find Telegram credentials in",
"to Telegram using stored credentials.\"\"\" p = Path(str(p)).resolve() if not p.is_file(): raise RuntimeError(f'file",
"= os.getenv(self.API_TOKEN_ENV_VAR, None) self.chat_id = os.getenv(self.CHAT_ID_ENV_VAR, None) self._logger = get_logger(self.__class__.__name__, verb=True) if self.api_token",
"from rpicam.utils.logging_utils import get_logger class TelegramPoster: \"\"\" Bare-bones class to post videos to",
"a Telegram chat. Uses per default credentials stored in environment. \"\"\" API_URL =",
"def __init__(self, api_token: str = None, chat_id: str = None): if api_token is",
"import requests from rpicam.utils.logging_utils import get_logger class TelegramPoster: \"\"\" Bare-bones class to post",
"from pathlib import Path import requests from rpicam.utils.logging_utils import get_logger class TelegramPoster: \"\"\"",
"open(p, 'rb')) } r = requests.post(url, files=files) if r.status_code != 200: self._logger.error(f'Could not",
"self.api_token = api_token self.chat_id = chat_id else: self.api_token = os.getenv(self.API_TOKEN_ENV_VAR, None) self.chat_id =",
"not found: {p}') url = f'{self.API_URL}/bot{self.api_token}/sendVideo' files = { 'chat_id': (None, self.chat_id), 'video':",
"(None, self.chat_id), 'video': (str(p), open(p, 'rb')) } r = requests.post(url, files=files) if r.status_code",
"verb=True) if self.api_token is None or self.chat_id is None: raise RuntimeError('Could not find",
"credentials stored in environment. \"\"\" API_URL = 'https://api.telegram.org' API_TOKEN_ENV_VAR = 'RPICAM_TG_API_TOKEN' CHAT_ID_ENV_VAR =",
"Path(str(p)).resolve() if not p.is_file(): raise RuntimeError(f'file not found: {p}') url = f'{self.API_URL}/bot{self.api_token}/sendVideo' files",
"API_URL = 'https://api.telegram.org' API_TOKEN_ENV_VAR = 'RPICAM_TG_API_TOKEN' CHAT_ID_ENV_VAR = 'RPICAM_TG_CHAT_ID' def __init__(self, api_token: str",
"str]): \"\"\"Post the given video to Telegram using stored credentials.\"\"\" p = Path(str(p)).resolve()",
"using stored credentials.\"\"\" p = Path(str(p)).resolve() if not p.is_file(): raise RuntimeError(f'file not found:",
"Uses per default credentials stored in environment. \"\"\" API_URL = 'https://api.telegram.org' API_TOKEN_ENV_VAR =",
"self._logger = get_logger(self.__class__.__name__, verb=True) if self.api_token is None or self.chat_id is None: raise",
"CHAT_ID_ENV_VAR = 'RPICAM_TG_CHAT_ID' def __init__(self, api_token: str = None, chat_id: str = None):",
"__init__(self, api_token: str = None, chat_id: str = None): if api_token is not",
"= get_logger(self.__class__.__name__, verb=True) if self.api_token is None or self.chat_id is None: raise RuntimeError('Could",
"'RPICAM_TG_API_TOKEN' CHAT_ID_ENV_VAR = 'RPICAM_TG_CHAT_ID' def __init__(self, api_token: str = None, chat_id: str =",
"def send_video(self, p: Union[Path, str]): \"\"\"Post the given video to Telegram using stored",
"None): if api_token is not None and chat_id is not None: self.api_token =",
"else: self.api_token = os.getenv(self.API_TOKEN_ENV_VAR, None) self.chat_id = os.getenv(self.CHAT_ID_ENV_VAR, None) self._logger = get_logger(self.__class__.__name__, verb=True)",
"to post videos to a Telegram chat. Uses per default credentials stored in",
"python3 import os from typing import Union from pathlib import Path import requests",
"credentials in environment.') def send_video(self, p: Union[Path, str]): \"\"\"Post the given video to",
"None, chat_id: str = None): if api_token is not None and chat_id is",
"Union[Path, str]): \"\"\"Post the given video to Telegram using stored credentials.\"\"\" p =",
"\"\"\" Bare-bones class to post videos to a Telegram chat. Uses per default",
"#!/usr/bin/env python3 import os from typing import Union from pathlib import Path import",
"is not None: self.api_token = api_token self.chat_id = chat_id else: self.api_token = os.getenv(self.API_TOKEN_ENV_VAR,",
"p: Union[Path, str]): \"\"\"Post the given video to Telegram using stored credentials.\"\"\" p",
"Telegram using stored credentials.\"\"\" p = Path(str(p)).resolve() if not p.is_file(): raise RuntimeError(f'file not",
"\"\"\" API_URL = 'https://api.telegram.org' API_TOKEN_ENV_VAR = 'RPICAM_TG_API_TOKEN' CHAT_ID_ENV_VAR = 'RPICAM_TG_CHAT_ID' def __init__(self, api_token:",
"'rb')) } r = requests.post(url, files=files) if r.status_code != 200: self._logger.error(f'Could not upload",
"= 'RPICAM_TG_CHAT_ID' def __init__(self, api_token: str = None, chat_id: str = None): if",
"Telegram chat. Uses per default credentials stored in environment. \"\"\" API_URL = 'https://api.telegram.org'",
"os.getenv(self.CHAT_ID_ENV_VAR, None) self._logger = get_logger(self.__class__.__name__, verb=True) if self.api_token is None or self.chat_id is",
"raise RuntimeError('Could not find Telegram credentials in environment.') def send_video(self, p: Union[Path, str]):",
"None: raise RuntimeError('Could not find Telegram credentials in environment.') def send_video(self, p: Union[Path,",
"from typing import Union from pathlib import Path import requests from rpicam.utils.logging_utils import",
"} r = requests.post(url, files=files) if r.status_code != 200: self._logger.error(f'Could not upload file.",
"stored in environment. \"\"\" API_URL = 'https://api.telegram.org' API_TOKEN_ENV_VAR = 'RPICAM_TG_API_TOKEN' CHAT_ID_ENV_VAR = 'RPICAM_TG_CHAT_ID'",
"environment. \"\"\" API_URL = 'https://api.telegram.org' API_TOKEN_ENV_VAR = 'RPICAM_TG_API_TOKEN' CHAT_ID_ENV_VAR = 'RPICAM_TG_CHAT_ID' def __init__(self,",
"= chat_id else: self.api_token = os.getenv(self.API_TOKEN_ENV_VAR, None) self.chat_id = os.getenv(self.CHAT_ID_ENV_VAR, None) self._logger =",
"video to Telegram using stored credentials.\"\"\" p = Path(str(p)).resolve() if not p.is_file(): raise",
"class to post videos to a Telegram chat. Uses per default credentials stored",
"f'{self.API_URL}/bot{self.api_token}/sendVideo' files = { 'chat_id': (None, self.chat_id), 'video': (str(p), open(p, 'rb')) } r",
"in environment. \"\"\" API_URL = 'https://api.telegram.org' API_TOKEN_ENV_VAR = 'RPICAM_TG_API_TOKEN' CHAT_ID_ENV_VAR = 'RPICAM_TG_CHAT_ID' def",
"not p.is_file(): raise RuntimeError(f'file not found: {p}') url = f'{self.API_URL}/bot{self.api_token}/sendVideo' files = {",
"default credentials stored in environment. \"\"\" API_URL = 'https://api.telegram.org' API_TOKEN_ENV_VAR = 'RPICAM_TG_API_TOKEN' CHAT_ID_ENV_VAR",
"None) self.chat_id = os.getenv(self.CHAT_ID_ENV_VAR, None) self._logger = get_logger(self.__class__.__name__, verb=True) if self.api_token is None",
"videos to a Telegram chat. Uses per default credentials stored in environment. \"\"\"",
"TelegramPoster: \"\"\" Bare-bones class to post videos to a Telegram chat. Uses per",
"None: self.api_token = api_token self.chat_id = chat_id else: self.api_token = os.getenv(self.API_TOKEN_ENV_VAR, None) self.chat_id",
"API_TOKEN_ENV_VAR = 'RPICAM_TG_API_TOKEN' CHAT_ID_ENV_VAR = 'RPICAM_TG_CHAT_ID' def __init__(self, api_token: str = None, chat_id:",
"find Telegram credentials in environment.') def send_video(self, p: Union[Path, str]): \"\"\"Post the given",
"self.chat_id), 'video': (str(p), open(p, 'rb')) } r = requests.post(url, files=files) if r.status_code !=",
"requests.post(url, files=files) if r.status_code != 200: self._logger.error(f'Could not upload file. Exit code was",
"rpicam.utils.logging_utils import get_logger class TelegramPoster: \"\"\" Bare-bones class to post videos to a",
"import os from typing import Union from pathlib import Path import requests from",
"import Union from pathlib import Path import requests from rpicam.utils.logging_utils import get_logger class",
"= 'https://api.telegram.org' API_TOKEN_ENV_VAR = 'RPICAM_TG_API_TOKEN' CHAT_ID_ENV_VAR = 'RPICAM_TG_CHAT_ID' def __init__(self, api_token: str =",
"class TelegramPoster: \"\"\" Bare-bones class to post videos to a Telegram chat. Uses",
"get_logger class TelegramPoster: \"\"\" Bare-bones class to post videos to a Telegram chat.",
"'https://api.telegram.org' API_TOKEN_ENV_VAR = 'RPICAM_TG_API_TOKEN' CHAT_ID_ENV_VAR = 'RPICAM_TG_CHAT_ID' def __init__(self, api_token: str = None,",
"not None and chat_id is not None: self.api_token = api_token self.chat_id = chat_id",
"str = None, chat_id: str = None): if api_token is not None and",
"raise RuntimeError(f'file not found: {p}') url = f'{self.API_URL}/bot{self.api_token}/sendVideo' files = { 'chat_id': (None,",
"typing import Union from pathlib import Path import requests from rpicam.utils.logging_utils import get_logger",
"and chat_id is not None: self.api_token = api_token self.chat_id = chat_id else: self.api_token",
"= requests.post(url, files=files) if r.status_code != 200: self._logger.error(f'Could not upload file. Exit code",
"Path import requests from rpicam.utils.logging_utils import get_logger class TelegramPoster: \"\"\" Bare-bones class to",
"if not p.is_file(): raise RuntimeError(f'file not found: {p}') url = f'{self.API_URL}/bot{self.api_token}/sendVideo' files =",
"files = { 'chat_id': (None, self.chat_id), 'video': (str(p), open(p, 'rb')) } r =",
"None and chat_id is not None: self.api_token = api_token self.chat_id = chat_id else:",
"import get_logger class TelegramPoster: \"\"\" Bare-bones class to post videos to a Telegram",
"RuntimeError(f'file not found: {p}') url = f'{self.API_URL}/bot{self.api_token}/sendVideo' files = { 'chat_id': (None, self.chat_id),",
"is None: raise RuntimeError('Could not find Telegram credentials in environment.') def send_video(self, p:",
"{p}') url = f'{self.API_URL}/bot{self.api_token}/sendVideo' files = { 'chat_id': (None, self.chat_id), 'video': (str(p), open(p,",
"{ 'chat_id': (None, self.chat_id), 'video': (str(p), open(p, 'rb')) } r = requests.post(url, files=files)",
"self.api_token = os.getenv(self.API_TOKEN_ENV_VAR, None) self.chat_id = os.getenv(self.CHAT_ID_ENV_VAR, None) self._logger = get_logger(self.__class__.__name__, verb=True) if",
"p = Path(str(p)).resolve() if not p.is_file(): raise RuntimeError(f'file not found: {p}') url =",
"(str(p), open(p, 'rb')) } r = requests.post(url, files=files) if r.status_code != 200: self._logger.error(f'Could",
"Bare-bones class to post videos to a Telegram chat. Uses per default credentials",
"None) self._logger = get_logger(self.__class__.__name__, verb=True) if self.api_token is None or self.chat_id is None:",
"if self.api_token is None or self.chat_id is None: raise RuntimeError('Could not find Telegram",
"= Path(str(p)).resolve() if not p.is_file(): raise RuntimeError(f'file not found: {p}') url = f'{self.API_URL}/bot{self.api_token}/sendVideo'",
"None or self.chat_id is None: raise RuntimeError('Could not find Telegram credentials in environment.')",
"= None): if api_token is not None and chat_id is not None: self.api_token",
"= 'RPICAM_TG_API_TOKEN' CHAT_ID_ENV_VAR = 'RPICAM_TG_CHAT_ID' def __init__(self, api_token: str = None, chat_id: str",
"not None: self.api_token = api_token self.chat_id = chat_id else: self.api_token = os.getenv(self.API_TOKEN_ENV_VAR, None)",
"chat_id: str = None): if api_token is not None and chat_id is not",
"\"\"\"Post the given video to Telegram using stored credentials.\"\"\" p = Path(str(p)).resolve() if",
"chat. Uses per default credentials stored in environment. \"\"\" API_URL = 'https://api.telegram.org' API_TOKEN_ENV_VAR",
"self.api_token is None or self.chat_id is None: raise RuntimeError('Could not find Telegram credentials",
"per default credentials stored in environment. \"\"\" API_URL = 'https://api.telegram.org' API_TOKEN_ENV_VAR = 'RPICAM_TG_API_TOKEN'",
"credentials.\"\"\" p = Path(str(p)).resolve() if not p.is_file(): raise RuntimeError(f'file not found: {p}') url",
"url = f'{self.API_URL}/bot{self.api_token}/sendVideo' files = { 'chat_id': (None, self.chat_id), 'video': (str(p), open(p, 'rb'))",
"self.chat_id is None: raise RuntimeError('Could not find Telegram credentials in environment.') def send_video(self,",
"'RPICAM_TG_CHAT_ID' def __init__(self, api_token: str = None, chat_id: str = None): if api_token"
] |
[
"= np.argsort(dist)[:k] jd, wd = np.mean(data_pix2loc[indexs, 2:], axis=0) else: assert 'Do not have",
"ndarray:[jd, wd] :return: distance ''' dist = a - b j_dist = dist[0]",
"= data_pix2loc[index, 2] wd = data_pix2loc[index, 3] elif method == 'nearest_k_mean': ex =",
"is not npy, please check file path.' info = np.load(file_path) if acq_print: print('Load",
"= float(data[2]) + float(data[4]) / 2 locy = float(data[3]) + float(data[5]) if DataProcesser.refine_v2(camid,",
"/ 'info.pkl') return info if verbose: ti = info['tracklets_info'] to_tn = ti[1]['total_tracklets_num'] +",
"acq_print=True): check_path(file_path) with open(file_path, 'r', encoding=encoding) as f: info = json.load(f) if acq_print:",
"= len(tracklet_ids) count_ignore_tkl = 0 count_ava_tkl = 0 count_avg_tkl_num = 0 total_num =",
"100 + int(i / 10000) * 60 * 60 dam_time_list.append(dem_time) return dam_time_list else:",
"len(glob.glob(str(save_img_path / '*.jpg'))) y2 = y1 + h x2 = x1 + w",
"f: f.writelines(refineData) @staticmethod def crop_image(img_dir, result_dir, save_img_dir, camid): img_paths = glob.glob(str(img_dir / '*.jpg'))",
"= count_ava_tkl info['tracklets_info'][camid]['available_images_num'] = total_num info['tracklets_info'][camid]['average_images_num'] = total_num // count_ava_tkl assert info['tracklets_info'][camid]['total_tracklets_num'] ==",
"+ h x2 = x1 + w if y1 <= 0: y1 =",
"cam3 | {:10d} | {:17d} | {:20d} | {:22d} | {:20d} \".format(ti[2]['total_tracklets_num'], ti[2]['ignore_tracklets_num'],",
"def json_load(file_path, encoding='UTF-8', acq_print=True): check_path(file_path) with open(file_path, 'r', encoding=encoding) as f: info =",
"f: lines = f.readlines() for line in lines: data = line.strip().split(',') locx =",
"= None info['ignore'].append(tracklets_per_cam_dir / tracklet_id) else: count_ava_tkl += 1 info['old2new'][camid][int(tracklet_id)] = new_id new_id",
"keepdims=True) _range = np.max(a,axis=1,keepdims=True) - a_min return (a - a_min) / _range def",
"camid): refineData = [] with open(path, 'r') as f: lines = f.readlines() for",
"3: if locy <= 200: return False if camid == 4: if locy",
"def np_save(info, file_path): check_path(Path(file_path).parent, create=True) assert file_path.split('.')[-1] == 'npy', 'This file\\' suffix is",
"0 for tracklet_id in tracklet_ids: img_paths = glob.glob(str(tracklets_per_cam_dir / tracklet_id / '*.jpg')) img_paths.sort()",
"locx + locy <= 350 or locx - 5.7143 * locy >= 2000:",
"'nearset': ex = data_pix2loc[:, 0] - traj_point[0] ey = data_pix2loc[:, 1] - traj_point[1]",
"if camid == 1: if locx + 20 * locy <= 4000 or",
"path_new, camid): refineData = [] with open(path, 'r') as f: lines = f.readlines()",
"if camid == 4: if locy <= 600: return False if camid ==",
"ti[4]['average_images_num'] + ti[5]['average_images_num'] + ti[0]['average_images_num'] print(\"=> GPSMOT loaded\") print(\"Dataset statistics:\") print(\" ----------------------------------------------------------------------------------------------------------------\") print(\"",
":return: second ''' dam_time_list = [] if isinstance(time, list): for i in time:",
"| {:22d} | {:20d} \".format(ti[5]['total_tracklets_num'], ti[5]['ignore_tracklets_num'], \\ ti[5]['available_tracklets_num'], ti[5]['available_images_num'], ti[5]['average_images_num'])) print(\" ----------------------------------------------------------------------------------------------------------------\") print(\"",
"** 2 indexs = np.argsort(dist)[:k] jd, wd = np.mean(data_pix2loc[indexs, 2:], axis=0) else: assert",
"4: if locy <= 600 or (locx >= 2000 and 0.5833 * locx",
"save_info=False): tracklet_dir = Path(tracklet_dir) info = {'old2new':[{} for i in range(cam_num)], 'ignore':[], 'tracklets_info':[{}",
"traj_point[1] dist = ex ** 2 + ey ** 2 indexs = np.argsort(dist)[:k]",
"camid == 2: if locy <= 150 or locx >= 3750: return False",
"f: info = json.load(f) if acq_print: print('Load data <--- ' + str(file_path), flush=True)",
"a_min return (a - a_min) / _range def check_path(folder_dir, create=False): ''' :param folder_dir:",
"img_name = 'T{:05d}_C{:02d}_F{:06d}_I{:06d}.jpg'.format(int(tid), camid, int(fid), count+1) try: cv2.imwrite(str(save_img_path / img_name), img) except: print('ignore",
"return jd, wd def norm_data(a): ''' :param a: feature distance N X N",
"200: return False if camid == 4: if locy <= 600: return False",
"verbose: ti = info['tracklets_info'] to_tn = ti[1]['total_tracklets_num'] + ti[2]['total_tracklets_num'] + ti[3]['total_tracklets_num'] + \\",
"/ _range def check_path(folder_dir, create=False): ''' :param folder_dir: file path :param create: create",
"2000 and 0.5833 * locx + locy <= 2340): return False if camid",
"+ ti[3]['available_images_num'] + \\ ti[4]['available_images_num'] + ti[5]['available_images_num'] + ti[0]['available_images_num'] to_avein = ti[1]['average_images_num'] +",
"class DataProcesser(object): @staticmethod def refine_v1(camid, locx, locy): if camid == 1: if locx",
"{:17d} | {:20d} | {:22d} | {:20d} \".format(ti[3]['total_tracklets_num'], ti[3]['ignore_tracklets_num'], \\ ti[3]['available_tracklets_num'], ti[3]['available_images_num'], ti[3]['average_images_num']))",
"as f: info = json.load(f) if acq_print: print('Load data <--- ' + str(file_path),",
"info = {'old2new':[{} for i in range(cam_num)], 'ignore':[], 'tracklets_info':[{} for i in range(cam_num)],",
"int(i % 100)) / 100 + int(i / 10000) * 60 * 60",
"@staticmethod def refine_v2(camid, locx, locy): if camid == 1: if locx + 20",
"1 info['tracklets_info'][camid]['total_tracklets_num'] = tracklets_num info['tracklets_info'][camid]['ignore_tracklets_num'] = count_ignore_tkl info['tracklets_info'][camid]['available_tracklets_num'] = count_ava_tkl info['tracklets_info'][camid]['available_images_num'] = total_num",
"txt, please check file path.' np.savetxt(file_path, info) print('Store data ---> ' + str(file_path),",
"0 for camid in range(cam_num): tracklets_per_cam_dir = tracklet_dir / '{:02d}'.format(camid + 1) tracklet_ids",
"as f: lines = f.readlines() for line in lines: data = line.strip().split(',') locx",
"def refine_v1(camid, locx, locy): if camid == 1: if locx + 30 *",
"check_path(file_path) assert file_path.split('.')[-1] == 'npy', 'This file\\' suffix is not npy, please check",
"= cv2.imread(img_path) data_cur = data_arr[data_arr[:,0] == index] for data in data_cur: fid, tid,",
"return int(dem_time) def get_time(time): ''' :param time: hour minute second :return: second from",
"data <--- ' + str(file_path), flush=True) return info class DataProcesser(object): @staticmethod def refine_v1(camid,",
"/ '{:05d}'.format(int(tid)) check_path(save_img_path, create=True) count = len(glob.glob(str(save_img_path / '*.jpg'))) y2 = y1 +",
"a - b j_dist = dist[0] * 111000 * np.cos(a[1] / 180 *",
"check file path.' np.savetxt(file_path, info) print('Store data ---> ' + str(file_path), flush=True) @staticmethod",
"count_ava_tkl info['tracklets_info'][camid]['available_images_num'] = total_num info['tracklets_info'][camid]['average_images_num'] = total_num // count_ava_tkl assert info['tracklets_info'][camid]['total_tracklets_num'] == \\",
"dist: [jd_sub, wd_sub] :return: distance ''' j_dist = dist[0] * 111000 * np.cos(31",
"locx + 30 * locy <= 3000 or locx - 8.235 * locy",
"str(file_path), flush=True) @staticmethod def load(file_path): check_path(file_path) with open(file_path, 'rb') as f: info =",
"def dump(info, file_path): check_path(Path(file_path).parent, create=True) with open(file_path, 'wb') as f: pickle.dump(info, f) print('Store",
"+ 60 * (int(time % 10000) - int(time % 100)) / 100 +",
"ti[5]['available_images_num'], ti[5]['average_images_num'])) print(\" ----------------------------------------------------------------------------------------------------------------\") print(\" total | {:10d} | {:17d} | {:20d} |",
"in lines: data = line.strip().split(',') locx = float(data[2]) + float(data[4]) / 2 locy",
"wd = data_pix2loc[index, 3] elif method == 'linear': index = np.where(int(data_pix2loc[:, 0]) ==",
"camid == 6: if locy <= 150 or locx - 2.5 * locy",
"in range(cam_num)], 'tracklets':[]} new_id = 0 for camid in range(cam_num): tracklets_per_cam_dir = tracklet_dir",
"* 60 dam_time_list.append(dem_time) return dam_time_list else: dem_time = int(time % 100) + 60",
"+ ti[2]['total_tracklets_num'] + ti[3]['total_tracklets_num'] + \\ ti[4]['total_tracklets_num'] + ti[5]['total_tracklets_num'] + ti[0]['total_tracklets_num'] to_itn =",
"camid == 3: if locy <= 200: return False if camid == 4:",
"import glob import cv2 def ham_to_dem(time): ''' :param time: hour minute second :return:",
"data_pix2loc[:, 1] - traj_point[1] dist = ex ** 2 + ey ** 2",
"ti[3]['average_images_num'] + \\ ti[4]['average_images_num'] + ti[5]['average_images_num'] + ti[0]['average_images_num'] print(\"=> GPSMOT loaded\") print(\"Dataset statistics:\")",
"result_path = result_dir / ('GPSReID0'+str(camid)+'_refine_v2.txt') data_list = [] with open(result_path, 'r') as f:",
"= ex ** 2 + ey ** 2 indexs = np.argsort(dist)[:k] jd, wd",
"<= 2: count_ignore_tkl += 1 info['old2new'][camid][int(tracklet_id)] = None info['ignore'].append(tracklets_per_cam_dir / tracklet_id) else: count_ava_tkl",
"% 100)) / 100 + int(i / 10000) * 60 * 60 dam_time_list.append(dem_time)",
"pathlib import Path import glob import cv2 def ham_to_dem(time): ''' :param time: hour",
"ti[0]['ignore_tracklets_num'], \\ ti[0]['available_tracklets_num'], ti[0]['available_images_num'], ti[0]['average_images_num'])) print(\" cam2 | {:10d} | {:17d} | {:20d}",
"<gh_stars>1-10 import json import pickle import numpy as np import os import errno",
"+ int(i / 10000) * 60 * 60 dam_time_list.append(dem_time) return dam_time_list else: dem_time",
"= ham_to_dem(102630) sub_time = now_time - start_time return int(sub_time) def trans_gps_diff_to_dist_v1(a, b): '''",
"dump(info, file_path): check_path(Path(file_path).parent, create=True) with open(file_path, 'wb') as f: pickle.dump(info, f) print('Store data",
"150 or locx - 2.5 * locy >= 2000: return False return True",
"= data_arr[data_arr[:,0] == index] for data in data_cur: fid, tid, x1, y1, w,",
"== 2: if locy <= 150 or locx >= 3750: return False if",
"3600: return False if camid == 3: if locy <= 250: return False",
"> 4000: x2 = 4000 img = img0[int(y1):int(y2),int(x1):int(x2)] img_name = 'T{:05d}_C{:02d}_F{:06d}_I{:06d}.jpg'.format(int(tid), camid, int(fid),",
"np.pi) w_dist = dist[1] * 111000 return np.sqrt(np.power(j_dist, 2)+np.power(w_dist, 2)) def trans_gps_diff_to_dist_v2(dist): '''",
"img_path in img_paths: index = int(img_path.split('/')[-1].split('.')[0]) + 1 img0 = cv2.imread(img_path) data_cur =",
"ti[5]['total_tracklets_num'] + ti[0]['total_tracklets_num'] to_itn = ti[1]['ignore_tracklets_num'] + ti[2]['ignore_tracklets_num'] + ti[3]['ignore_tracklets_num'] + \\ ti[4]['ignore_tracklets_num']",
"info['tracklets_info'][camid]['total_tracklets_num'] == \\ info['tracklets_info'][camid]['ignore_tracklets_num'] + \\ info['tracklets_info'][camid]['available_tracklets_num'] if save_info: DataPacker.dump(info, tracklet_dir / 'info.pkl')",
"== 6: if locy <= 150 or locx - 2.5 * locy >=",
"index = np.argsort(dist)[0] jd = data_pix2loc[index, 2] wd = data_pix2loc[index, 3] elif method",
"check_path(file_path) assert file_path.split('.')[-1] == 'txt', 'This file\\' suffix is not txt, please check",
"tracklet_ids = os.listdir(tracklets_per_cam_dir) tracklet_ids.sort() tracklets_num = len(tracklet_ids) count_ignore_tkl = 0 count_ava_tkl = 0",
"camid == 4: if locy <= 600: return False if camid == 5:",
"glob import cv2 def ham_to_dem(time): ''' :param time: hour minute second :return: second",
"_range = np.max(a,axis=1,keepdims=True) - a_min return (a - a_min) / _range def check_path(folder_dir,",
"** 2 + ey ** 2 indexs = np.argsort(dist)[:k] jd, wd = np.mean(data_pix2loc[indexs,",
"data_pix2loc[index, 2] wd = data_pix2loc[index, 3] elif method == 'linear': index = np.where(int(data_pix2loc[:,",
"check_path(Path(file_path).parent, create=True) assert file_path.split('.')[-1] == 'npy', 'This file\\' suffix is not npy, please",
"data ---> ' + str(file_path), flush=True) @staticmethod def np_load_txt(file_path, acq_print=True): check_path(file_path) assert file_path.split('.')[-1]",
"jd = data_pix2loc[index, 2] wd = data_pix2loc[index, 3] elif method == 'nearest_k_mean': ex",
"+ str(file_path), flush=True) return info @staticmethod def json_dump(info, file_path, encoding='UTF-8'): check_path(Path(file_path).parent, create=True) with",
"now_time - start_time return int(sub_time) def trans_gps_diff_to_dist_v1(a, b): ''' :param a: ndarray:[jd, wd]",
"if camid == 6: if locy <= 150 or locx - 2.5 *",
"locy <= 600: return False if camid == 5: if locy <= 150",
"f: info = pickle.load(f) print('Load data <--- ' + str(file_path), flush=True) return info",
"= 0 if y2 > 3007: y2 = 3007 if x2 > 4000:",
":return: normalize feature ''' a = a.copy() a_min = np.min(a, axis=1, keepdims=True) _range",
"= result_dir / ('GPSReID0'+str(camid)+'_refine_v2.txt') data_list = [] with open(result_path, 'r') as f: total_data",
"data = data.strip().split(',') data_list.append([int(data[0]), int(data[1]), float(data[2]), float(data[3]), float(data[4]), float(data[5])]) data_arr = np.array(data_list) for",
"path :param create: create file or not :return: ''' folder_dir = Path(folder_dir) if",
"= data_pix2loc[index, 2] wd = data_pix2loc[index, 3] elif method == 'linear': index =",
"+ int(time / 10000) * 60 * 60 return int(dem_time) def get_time(time): '''",
"ti[2]['ignore_tracklets_num'], \\ ti[2]['available_tracklets_num'], ti[2]['available_images_num'], ti[2]['average_images_num'])) print(\" cam4 | {:10d} | {:17d} | {:20d}",
"ey ** 2 index = np.argsort(dist)[0] jd = data_pix2loc[index, 2] wd = data_pix2loc[index,",
"{:17d} | {:20d} | {:22d} | {:20d} \".format(ti[1]['total_tracklets_num'], ti[1]['ignore_tracklets_num'], \\ ti[1]['available_tracklets_num'], ti[1]['available_images_num'], ti[1]['average_images_num']))",
"count_dataset_info(tracklet_dir, cam_num, verbose=False, save_info=False): tracklet_dir = Path(tracklet_dir) info = {'old2new':[{} for i in",
"with open(file_path, 'w', encoding=encoding) as f: json.dump(info, f) print('Store data ---> ' +",
"return True @staticmethod def refine_result(path, path_new, camid): refineData = [] with open(path, 'r')",
"= np.where(int(data_pix2loc[:, 0]) == traj_point[0] and int(data_pix2loc[:, 1]) == traj_point[1]) jd = data_pix2loc[index,",
"range(cam_num): tracklets_per_cam_dir = tracklet_dir / '{:02d}'.format(camid + 1) tracklet_ids = os.listdir(tracklets_per_cam_dir) tracklet_ids.sort() tracklets_num",
"---> ' + str(file_path), flush=True) @staticmethod def np_load_txt(file_path, acq_print=True): check_path(file_path) assert file_path.split('.')[-1] ==",
"+ 1 img0 = cv2.imread(img_path) data_cur = data_arr[data_arr[:,0] == index] for data in",
"if locx + 30 * locy <= 3000 or locx - 8.235 *",
"---> ' + str(file_path), flush=True) @staticmethod def json_load(file_path, encoding='UTF-8', acq_print=True): check_path(file_path) with open(file_path,",
"traj_point[1] dist = ex ** 2 + ey ** 2 index = np.argsort(dist)[0]",
"cv2.imread(img_path) data_cur = data_arr[data_arr[:,0] == index] for data in data_cur: fid, tid, x1,",
"pixel_y, jd, wd] size[n, 4] :param traj_list: [pixel_x, pixel_y] size[2] :param method: 'nearest'",
"@staticmethod def crop_image(img_dir, result_dir, save_img_dir, camid): img_paths = glob.glob(str(img_dir / '*.jpg')) img_paths.sort() result_path",
"check_path(save_img_path, create=True) count = len(glob.glob(str(save_img_path / '*.jpg'))) y2 = y1 + h x2",
"- b j_dist = dist[0] * 111000 * np.cos(a[1] / 180 * np.pi)",
"<= 150 or locx >= 3750: return False if camid == 3: if",
"ti[3]['average_images_num'])) print(\" cam5 | {:10d} | {:17d} | {:20d} | {:22d} | {:20d}",
"<= 0: x1 = 0 if y2 > 3007: y2 = 3007 if",
"+ 30 * locy <= 3000 or locx - 8.235 * locy >=",
"ti = info['tracklets_info'] to_tn = ti[1]['total_tracklets_num'] + ti[2]['total_tracklets_num'] + ti[3]['total_tracklets_num'] + \\ ti[4]['total_tracklets_num']",
"60 * (int(i % 10000) - int(i % 100)) / 100 + int(i",
"return info @staticmethod def np_save(info, file_path): check_path(Path(file_path).parent, create=True) assert file_path.split('.')[-1] == 'npy', 'This",
">= 2000: return False if camid == 6: if locy <= 150 or",
"| {:22d} | {:20d} \".format(ti[1]['total_tracklets_num'], ti[1]['ignore_tracklets_num'], \\ ti[1]['available_tracklets_num'], ti[1]['available_images_num'], ti[1]['average_images_num'])) print(\" cam3 |",
"''' :param time: hour minute second :return: second from 102630 ''' now_time =",
"<--- ' + str(file_path), flush=True) return info @staticmethod def np_save(info, file_path): check_path(Path(file_path).parent, create=True)",
"| {:22d} | {:20d} \".format(ti[3]['total_tracklets_num'], ti[3]['ignore_tracklets_num'], \\ ti[3]['available_tracklets_num'], ti[3]['available_images_num'], ti[3]['average_images_num'])) print(\" cam5 |",
"locx - 5.7143 * locy >= 2000: return False if camid == 6:",
"acq_print=True): check_path(file_path) assert file_path.split('.')[-1] == 'txt', 'This file\\' suffix is not txt, please",
"'tracklets_info':[{} for i in range(cam_num)], 'tracklets':[]} new_id = 0 for camid in range(cam_num):",
"if camid == 3: if locy <= 250: return False if camid ==",
"to_avain = ti[1]['available_images_num'] + ti[2]['available_images_num'] + ti[3]['available_images_num'] + \\ ti[4]['available_images_num'] + ti[5]['available_images_num'] +",
"img_paths.sort() if len(img_paths) <= 2: count_ignore_tkl += 1 info['old2new'][camid][int(tracklet_id)] = None info['ignore'].append(tracklets_per_cam_dir /",
"(int(time % 10000) - int(time % 100)) / 100 + int(time / 10000)",
"* locy >= 2000: return False return True @staticmethod def refine_result(path, path_new, camid):",
"return False if camid == 4: if locy <= 600 or (locx >=",
"= 3007 if x2 > 4000: x2 = 4000 img = img0[int(y1):int(y2),int(x1):int(x2)] img_name",
"this class supplys four different Data processing format ''' @staticmethod def dump(info, file_path):",
"def np_load(file_path, acq_print=True): check_path(file_path) assert file_path.split('.')[-1] == 'npy', 'This file\\' suffix is not",
"trans_gps_diff_to_dist_v1(a, b): ''' :param a: ndarray:[jd, wd] :param b: ndarray:[jd, wd] :return: distance",
"1) tracklet_ids = os.listdir(tracklets_per_cam_dir) tracklet_ids.sort() tracklets_num = len(tracklet_ids) count_ignore_tkl = 0 count_ava_tkl =",
"dist = a - b j_dist = dist[0] * 111000 * np.cos(a[1] /",
"= total_num // count_ava_tkl assert info['tracklets_info'][camid]['total_tracklets_num'] == \\ info['tracklets_info'][camid]['ignore_tracklets_num'] + \\ info['tracklets_info'][camid]['available_tracklets_num'] if",
">= 3600: return False if camid == 3: if locy <= 250: return",
"def trans_gps_diff_to_dist_v3(gps_1, gps_2): ''' :param gps_1: [jd, wd] :param gps_2: [jd, wd] :return:",
"list): for i in time: dem_time = int(i % 100) + 60 *",
"or locx - 5.7143 * locy >= 2000: return False if camid ==",
"''' :param gps_1: [jd, wd] :param gps_2: [jd, wd] :return: distance between two",
"the meathod' return jd, wd def norm_data(a): ''' :param a: feature distance N",
"{:10d} | {:17d} | {:20d} | {:22d} | {:20d} \".format(to_tn, to_itn, to_atn, to_avain,",
"= new_id new_id += 1 info['tracklets'].append((img_paths, new_id, camid)) total_num += len(img_paths) count_avg_tkl_num +=",
"tracklet_ids.sort() tracklets_num = len(tracklet_ids) count_ignore_tkl = 0 count_ava_tkl = 0 count_avg_tkl_num = 0",
"ti[1]['total_tracklets_num'] + ti[2]['total_tracklets_num'] + ti[3]['total_tracklets_num'] + \\ ti[4]['total_tracklets_num'] + ti[5]['total_tracklets_num'] + ti[0]['total_tracklets_num'] to_itn",
"os.listdir(tracklets_per_cam_dir) tracklet_ids.sort() tracklets_num = len(tracklet_ids) count_ignore_tkl = 0 count_ava_tkl = 0 count_avg_tkl_num =",
"{:17d} | {:20d} | {:22d} | {:20d} \".format(ti[2]['total_tracklets_num'], ti[2]['ignore_tracklets_num'], \\ ti[2]['available_tracklets_num'], ti[2]['available_images_num'], ti[2]['average_images_num']))",
"info = json.load(f) if acq_print: print('Load data <--- ' + str(file_path), flush=True) return",
"@staticmethod def dump(info, file_path): check_path(Path(file_path).parent, create=True) with open(file_path, 'wb') as f: pickle.dump(info, f)",
"path.' np.savetxt(file_path, info) print('Store data ---> ' + str(file_path), flush=True) @staticmethod def np_load_txt(file_path,",
"60 return int(dem_time) def get_time(time): ''' :param time: hour minute second :return: second",
"= tracklet_dir / '{:02d}'.format(camid + 1) tracklet_ids = os.listdir(tracklets_per_cam_dir) tracklet_ids.sort() tracklets_num = len(tracklet_ids)",
">= 2000: return False return True @staticmethod def refine_v2(camid, locx, locy): if camid",
"# average images num\") print(\" ----------------------------------------------------------------------------------------------------------------\") print(\" cam1 | {:10d} | {:17d} |",
"0.5833 * locx + locy <= 2340): return False if camid == 5:",
"wd_sub] :return: distance ''' j_dist = dist[0] * 111000 * np.cos(31 / 180",
"size[2] :param method: 'nearest' 'linear' 'nearest_k_mean' :param k: num of selected point :return:",
"return geodesic((gps_1[1], gps_1[0]), (gps_2[1], gps_2[0]).m) def pixel_to_loc(data_pix2loc, traj_point, method='nearset', k=4): ''' :param data_pix2loc:",
"ham_to_dem(time) start_time = ham_to_dem(102630) sub_time = now_time - start_time return int(sub_time) def trans_gps_diff_to_dist_v1(a,",
"3000 or locx - 8.235 * locy >= 1200: return False if camid",
"ey ** 2 indexs = np.argsort(dist)[:k] jd, wd = np.mean(data_pix2loc[indexs, 2:], axis=0) else:",
"ti[2]['available_tracklets_num'], ti[2]['available_images_num'], ti[2]['average_images_num'])) print(\" cam4 | {:10d} | {:17d} | {:20d} | {:22d}",
"if locy <= 600 or (locx >= 2000 and 0.5833 * locx +",
"/ tracklet_id) else: count_ava_tkl += 1 info['old2new'][camid][int(tracklet_id)] = new_id new_id += 1 info['tracklets'].append((img_paths,",
"if locy <= 250: return False if camid == 4: if locy <=",
"subset | # tkls num | # ignore tkls num | # available",
"f) print('Store data ---> ' + str(file_path), flush=True) @staticmethod def load(file_path): check_path(file_path) with",
"\\ ti[1]['available_tracklets_num'], ti[1]['available_images_num'], ti[1]['average_images_num'])) print(\" cam3 | {:10d} | {:17d} | {:20d} |",
":param dist: [jd_sub, wd_sub] :return: distance ''' j_dist = dist[0] * 111000 *",
"create=True) assert file_path.split('.')[-1] == 'txt', 'This file\\' suffix is not txt, please check",
"= int(img_path.split('/')[-1].split('.')[0]) + 1 img0 = cv2.imread(img_path) data_cur = data_arr[data_arr[:,0] == index] for",
"print(\" total | {:10d} | {:17d} | {:20d} | {:22d} | {:20d} \".format(to_tn,",
"\\ ti[3]['available_tracklets_num'], ti[3]['available_images_num'], ti[3]['average_images_num'])) print(\" cam5 | {:10d} | {:17d} | {:20d} |",
"int(dem_time) def get_time(time): ''' :param time: hour minute second :return: second from 102630",
"= dist[0] * 111000 * np.cos(a[1] / 180 * np.pi) w_dist = dist[1]",
"{:20d} \".format(ti[1]['total_tracklets_num'], ti[1]['ignore_tracklets_num'], \\ ti[1]['available_tracklets_num'], ti[1]['available_images_num'], ti[1]['average_images_num'])) print(\" cam3 | {:10d} | {:17d}",
"ti[0]['available_images_num'], ti[0]['average_images_num'])) print(\" cam2 | {:10d} | {:17d} | {:20d} | {:22d} |",
"20 * locy <= 4000 or locx - 8.235 * locy >= 1200:",
"DataPacker(object): ''' this class supplys four different Data processing format ''' @staticmethod def",
"try: cv2.imwrite(str(save_img_path / img_name), img) except: print('ignore image -- ', save_img_path / img_name)",
":param k: num of selected point :return: traj_list's jd and wd ''' if",
"if locx + 20 * locy <= 4000 or locx - 8.235 *",
"import os import errno from geopy.distance import geodesic from pathlib import Path import",
"encoding=encoding) as f: info = json.load(f) if acq_print: print('Load data <--- ' +",
"{:22d} | {:20d} \".format(ti[2]['total_tracklets_num'], ti[2]['ignore_tracklets_num'], \\ ti[2]['available_tracklets_num'], ti[2]['available_images_num'], ti[2]['average_images_num'])) print(\" cam4 | {:10d}",
"[pixel_x, pixel_y] size[2] :param method: 'nearest' 'linear' 'nearest_k_mean' :param k: num of selected",
"x2 = 4000 img = img0[int(y1):int(y2),int(x1):int(x2)] img_name = 'T{:05d}_C{:02d}_F{:06d}_I{:06d}.jpg'.format(int(tid), camid, int(fid), count+1) try:",
"float(data[5]) if DataProcesser.refine_v2(camid, locx, locy): refineData.append(line) with open(path_new, 'w') as f: f.writelines(refineData) @staticmethod",
"\".format(ti[1]['total_tracklets_num'], ti[1]['ignore_tracklets_num'], \\ ti[1]['available_tracklets_num'], ti[1]['available_images_num'], ti[1]['average_images_num'])) print(\" cam3 | {:10d} | {:17d} |",
"'nearest_k_mean' :param k: num of selected point :return: traj_list's jd and wd '''",
"traj_list: [pixel_x, pixel_y] size[2] :param method: 'nearest' 'linear' 'nearest_k_mean' :param k: num of",
"DataPacker.dump(info, tracklet_dir / 'info.pkl') return info if verbose: ti = info['tracklets_info'] to_tn =",
"1] - traj_point[1] dist = ex ** 2 + ey ** 2 indexs",
"and 0.5833 * locx + locy <= 2340): return False if camid ==",
"<--- ' + str(file_path), flush=True) return info @staticmethod def np_save_txt(info, file_path): check_path(Path(file_path).parent, create=True)",
"% 10000) - int(i % 100)) / 100 + int(i / 10000) *",
"ti[1]['available_tracklets_num'] + ti[2]['available_tracklets_num'] + ti[3]['available_tracklets_num'] + \\ ti[4]['available_tracklets_num'] + ti[5]['available_tracklets_num'] + ti[0]['available_tracklets_num'] to_avain",
"/ tracklet_id / '*.jpg')) img_paths.sort() if len(img_paths) <= 2: count_ignore_tkl += 1 info['old2new'][camid][int(tracklet_id)]",
"' + str(file_path), flush=True) @staticmethod def load(file_path): check_path(file_path) with open(file_path, 'rb') as f:",
"\\ info['tracklets_info'][camid]['available_tracklets_num'] if save_info: DataPacker.dump(info, tracklet_dir / 'info.pkl') return info if verbose: ti",
"gps_1[0]), (gps_2[1], gps_2[0]).m) def pixel_to_loc(data_pix2loc, traj_point, method='nearset', k=4): ''' :param data_pix2loc: [pixel_x, pixel_y,",
"return (a - a_min) / _range def check_path(folder_dir, create=False): ''' :param folder_dir: file",
"if locy <= 150 or locx >= 3750: return False if camid ==",
"/ '*.jpg'))) y2 = y1 + h x2 = x1 + w if",
"a.copy() a_min = np.min(a, axis=1, keepdims=True) _range = np.max(a,axis=1,keepdims=True) - a_min return (a",
"wd] size[n, 4] :param traj_list: [pixel_x, pixel_y] size[2] :param method: 'nearest' 'linear' 'nearest_k_mean'",
"5: if locy <= 150 or 0.1167 * locx + locy <= 350",
"- 2.5 * locy >= 2000: return False return True @staticmethod def refine_result(path,",
"in range(cam_num): tracklets_per_cam_dir = tracklet_dir / '{:02d}'.format(camid + 1) tracklet_ids = os.listdir(tracklets_per_cam_dir) tracklet_ids.sort()",
"cam1 | {:10d} | {:17d} | {:20d} | {:22d} | {:20d} \".format(ti[0]['total_tracklets_num'], ti[0]['ignore_tracklets_num'],",
"| {:22d} | {:20d} \".format(ti[0]['total_tracklets_num'], ti[0]['ignore_tracklets_num'], \\ ti[0]['available_tracklets_num'], ti[0]['available_images_num'], ti[0]['average_images_num'])) print(\" cam2 |",
"if locy <= 150 or 0.1167 * locx + locy <= 350 or",
"2340): return False if camid == 5: if locy <= 150 or 0.1167",
"2 + ey ** 2 indexs = np.argsort(dist)[:k] jd, wd = np.mean(data_pix2loc[indexs, 2:],",
"2 indexs = np.argsort(dist)[:k] jd, wd = np.mean(data_pix2loc[indexs, 2:], axis=0) else: assert 'Do",
"+ locy <= 2340): return False if camid == 5: if locy <=",
"''' j_dist = dist[0] * 111000 * np.cos(31 / 180 * np.pi) w_dist",
"111000 * np.cos(a[1] / 180 * np.pi) w_dist = dist[1] * 111000 return",
"1 info['old2new'][camid][int(tracklet_id)] = None info['ignore'].append(tracklets_per_cam_dir / tracklet_id) else: count_ava_tkl += 1 info['old2new'][camid][int(tracklet_id)] =",
"method == 'linear': index = np.where(int(data_pix2loc[:, 0]) == traj_point[0] and int(data_pix2loc[:, 1]) ==",
"{:20d} | {:22d} | {:20d} \".format(ti[4]['total_tracklets_num'], ti[4]['ignore_tracklets_num'], \\ ti[4]['available_tracklets_num'], ti[4]['available_images_num'], ti[4]['average_images_num'])) print(\" cam6",
"x1 + w if y1 <= 0: y1 = 0 if x1 <=",
"60 dam_time_list.append(dem_time) return dam_time_list else: dem_time = int(time % 100) + 60 *",
"\\ ti[4]['ignore_tracklets_num'] + ti[5]['ignore_tracklets_num'] + ti[0]['ignore_tracklets_num'] to_atn = ti[1]['available_tracklets_num'] + ti[2]['available_tracklets_num'] + ti[3]['available_tracklets_num']",
"ti[4]['ignore_tracklets_num'] + ti[5]['ignore_tracklets_num'] + ti[0]['ignore_tracklets_num'] to_atn = ti[1]['available_tracklets_num'] + ti[2]['available_tracklets_num'] + ti[3]['available_tracklets_num'] +",
"create=True) assert file_path.split('.')[-1] == 'npy', 'This file\\' suffix is not npy, please check",
"trans_gps_diff_to_dist_v3(gps_1, gps_2): ''' :param gps_1: [jd, wd] :param gps_2: [jd, wd] :return: distance",
"None info['ignore'].append(tracklets_per_cam_dir / tracklet_id) else: count_ava_tkl += 1 info['old2new'][camid][int(tracklet_id)] = new_id new_id +=",
"= data save_img_path = save_img_dir / '{:02d}'.format(camid) / '{:05d}'.format(int(tid)) check_path(save_img_path, create=True) count =",
"data = line.strip().split(',') locx = float(data[2]) + float(data[4]) / 2 locy = float(data[3])",
"len(img_paths) <= 2: count_ignore_tkl += 1 info['old2new'][camid][int(tracklet_id)] = None info['ignore'].append(tracklets_per_cam_dir / tracklet_id) else:",
"+ ti[5]['available_tracklets_num'] + ti[0]['available_tracklets_num'] to_avain = ti[1]['available_images_num'] + ti[2]['available_images_num'] + ti[3]['available_images_num'] + \\",
"* np.cos(31 / 180 * np.pi) w_dist = dist[1] * 111000 return np.sqrt(np.power(j_dist,",
"' + str(file_path), flush=True) @staticmethod def json_load(file_path, encoding='UTF-8', acq_print=True): check_path(file_path) with open(file_path, 'r',",
"int(i / 10000) * 60 * 60 dam_time_list.append(dem_time) return dam_time_list else: dem_time =",
"locy = float(data[3]) + float(data[5]) if DataProcesser.refine_v2(camid, locx, locy): refineData.append(line) with open(path_new, 'w')",
"return np.sqrt(np.power(j_dist, 2)+np.power(w_dist, 2)) def trans_gps_diff_to_dist_v2(dist): ''' :param dist: [jd_sub, wd_sub] :return: distance",
"save_img_path = save_img_dir / '{:02d}'.format(camid) / '{:05d}'.format(int(tid)) check_path(save_img_path, create=True) count = len(glob.glob(str(save_img_path /",
"600: return False if camid == 5: if locy <= 150 or 0.1167",
"200 or locx >= 3600: return False if camid == 3: if locy",
"camid == 1: if locx + 30 * locy <= 3000 or locx",
"tracklet_id / '*.jpg')) img_paths.sort() if len(img_paths) <= 2: count_ignore_tkl += 1 info['old2new'][camid][int(tracklet_id)] =",
"distance ''' dist = a - b j_dist = dist[0] * 111000 *",
"''' a = a.copy() a_min = np.min(a, axis=1, keepdims=True) _range = np.max(a,axis=1,keepdims=True) -",
"total_num = 0 for tracklet_id in tracklet_ids: img_paths = glob.glob(str(tracklets_per_cam_dir / tracklet_id /",
"img_paths: index = int(img_path.split('/')[-1].split('.')[0]) + 1 img0 = cv2.imread(img_path) data_cur = data_arr[data_arr[:,0] ==",
"total_data = f.readlines() for data in total_data: data = data.strip().split(',') data_list.append([int(data[0]), int(data[1]), float(data[2]),",
"GPSMOT loaded\") print(\"Dataset statistics:\") print(\" ----------------------------------------------------------------------------------------------------------------\") print(\" subset | # tkls num |",
"locy <= 150 or locx >= 3750: return False if camid == 3:",
"locx + 20 * locy <= 4000 or locx - 8.235 * locy",
"\\ ti[4]['available_images_num'] + ti[5]['available_images_num'] + ti[0]['available_images_num'] to_avein = ti[1]['average_images_num'] + ti[2]['average_images_num'] + ti[3]['average_images_num']",
"'*.jpg'))) y2 = y1 + h x2 = x1 + w if y1",
"img_paths = glob.glob(str(tracklets_per_cam_dir / tracklet_id / '*.jpg')) img_paths.sort() if len(img_paths) <= 2: count_ignore_tkl",
"+ locy <= 350 or locx - 5.7143 * locy >= 2000: return",
"== 5: if locy <= 150 or 0.1167 * locx + locy <=",
":return: ''' folder_dir = Path(folder_dir) if not folder_dir.exists(): if create: try: os.makedirs(folder_dir) except",
">= 1200: return False if camid == 2: if locy <= 150 or",
"time: hour minute second :return: second ''' dam_time_list = [] if isinstance(time, list):",
"2] wd = data_pix2loc[index, 3] elif method == 'nearest_k_mean': ex = data_pix2loc[:, 0]",
"4000: x2 = 4000 img = img0[int(y1):int(y2),int(x1):int(x2)] img_name = 'T{:05d}_C{:02d}_F{:06d}_I{:06d}.jpg'.format(int(tid), camid, int(fid), count+1)",
"create: create file or not :return: ''' folder_dir = Path(folder_dir) if not folder_dir.exists():",
"locy <= 200 or locx >= 3600: return False if camid == 3:",
"open(file_path, 'w', encoding=encoding) as f: json.dump(info, f) print('Store data ---> ' + str(file_path),",
"total_num // count_ava_tkl assert info['tracklets_info'][camid]['total_tracklets_num'] == \\ info['tracklets_info'][camid]['ignore_tracklets_num'] + \\ info['tracklets_info'][camid]['available_tracklets_num'] if save_info:",
"+ ti[3]['average_images_num'] + \\ ti[4]['average_images_num'] + ti[5]['average_images_num'] + ti[0]['average_images_num'] print(\"=> GPSMOT loaded\") print(\"Dataset",
"== \\ info['tracklets_info'][camid]['ignore_tracklets_num'] + \\ info['tracklets_info'][camid]['available_tracklets_num'] if save_info: DataPacker.dump(info, tracklet_dir / 'info.pkl') return",
"ti[4]['average_images_num'])) print(\" cam6 | {:10d} | {:17d} | {:20d} | {:22d} | {:20d}",
"def json_dump(info, file_path, encoding='UTF-8'): check_path(Path(file_path).parent, create=True) with open(file_path, 'w', encoding=encoding) as f: json.dump(info,",
"def refine_v2(camid, locx, locy): if camid == 1: if locx + 20 *",
"----------------------------------------------------------------------------------------------------------------\") print(\" subset | # tkls num | # ignore tkls num |",
"if camid == 1: if locx + 30 * locy <= 3000 or",
"tkls num | # ignore tkls num | # available tkls num |",
"if e.errno != errno.EEXIST: raise else: raise IOError return folder_dir class DataPacker(object): '''",
"np.where(int(data_pix2loc[:, 0]) == traj_point[0] and int(data_pix2loc[:, 1]) == traj_point[1]) jd = data_pix2loc[index, 2]",
":param data_pix2loc: [pixel_x, pixel_y, jd, wd] size[n, 4] :param traj_list: [pixel_x, pixel_y] size[2]",
"print(\" cam2 | {:10d} | {:17d} | {:20d} | {:22d} | {:20d} \".format(ti[1]['total_tracklets_num'],",
"feature ''' a = a.copy() a_min = np.min(a, axis=1, keepdims=True) _range = np.max(a,axis=1,keepdims=True)",
"ham_to_dem(102630) sub_time = now_time - start_time return int(sub_time) def trans_gps_diff_to_dist_v1(a, b): ''' :param",
"return False if camid == 6: if locy <= 150 or locx -",
"= data_pix2loc[:, 0] - traj_point[0] ey = data_pix2loc[:, 1] - traj_point[1] dist =",
"ti[5]['available_tracklets_num'], ti[5]['available_images_num'], ti[5]['average_images_num'])) print(\" ----------------------------------------------------------------------------------------------------------------\") print(\" total | {:10d} | {:17d} | {:20d}",
"DataProcesser.refine_v2(camid, locx, locy): refineData.append(line) with open(path_new, 'w') as f: f.writelines(refineData) @staticmethod def crop_image(img_dir,",
"print(\"=> GPSMOT loaded\") print(\"Dataset statistics:\") print(\" ----------------------------------------------------------------------------------------------------------------\") print(\" subset | # tkls num",
"ti[3]['available_images_num'] + \\ ti[4]['available_images_num'] + ti[5]['available_images_num'] + ti[0]['available_images_num'] to_avein = ti[1]['average_images_num'] + ti[2]['average_images_num']",
"\\ ti[4]['available_tracklets_num'] + ti[5]['available_tracklets_num'] + ti[0]['available_tracklets_num'] to_avain = ti[1]['available_images_num'] + ti[2]['available_images_num'] + ti[3]['available_images_num']",
"e: if e.errno != errno.EEXIST: raise else: raise IOError return folder_dir class DataPacker(object):",
"num | # available tkls num | # available images num | #",
"locy <= 4000 or locx - 8.235 * locy >= 1200: return False",
"* locy >= 2000: return False if camid == 6: if locy <=",
"b: ndarray:[jd, wd] :return: distance ''' dist = a - b j_dist =",
"4000 or locx - 8.235 * locy >= 1200: return False if camid",
"y1 = 0 if x1 <= 0: x1 = 0 if y2 >",
"', save_img_path / img_name) @staticmethod def count_dataset_info(tracklet_dir, cam_num, verbose=False, save_info=False): tracklet_dir = Path(tracklet_dir)",
">= 1200: return False if camid == 2: if locy <= 200 or",
"is not npy, please check file path.' np.save(file_path, info) print('Store data ---> '",
"0: x1 = 0 if y2 > 3007: y2 = 3007 if x2",
"for camid in range(cam_num): tracklets_per_cam_dir = tracklet_dir / '{:02d}'.format(camid + 1) tracklet_ids =",
"axis=0) else: assert 'Do not have the meathod' return jd, wd def norm_data(a):",
"60 * 60 return int(dem_time) def get_time(time): ''' :param time: hour minute second",
"np import os import errno from geopy.distance import geodesic from pathlib import Path",
"* locx + locy <= 2340): return False if camid == 5: if",
"' + str(file_path), flush=True) return info @staticmethod def np_save(info, file_path): check_path(Path(file_path).parent, create=True) assert",
"num of selected point :return: traj_list's jd and wd ''' if method ==",
"+ ti[2]['available_tracklets_num'] + ti[3]['available_tracklets_num'] + \\ ti[4]['available_tracklets_num'] + ti[5]['available_tracklets_num'] + ti[0]['available_tracklets_num'] to_avain =",
"def norm_data(a): ''' :param a: feature distance N X N :return: normalize feature",
"encoding=encoding) as f: json.dump(info, f) print('Store data ---> ' + str(file_path), flush=True) @staticmethod",
"data_pix2loc: [pixel_x, pixel_y, jd, wd] size[n, 4] :param traj_list: [pixel_x, pixel_y] size[2] :param",
"''' :param folder_dir: file path :param create: create file or not :return: '''",
"ti[0]['average_images_num'] print(\"=> GPSMOT loaded\") print(\"Dataset statistics:\") print(\" ----------------------------------------------------------------------------------------------------------------\") print(\" subset | # tkls",
"data <--- ' + str(file_path), flush=True) return info @staticmethod def json_dump(info, file_path, encoding='UTF-8'):",
"np.cos(a[1] / 180 * np.pi) w_dist = dist[1] * 111000 return np.sqrt(np.power(j_dist, 2)+np.power(w_dist,",
"now_time = ham_to_dem(time) start_time = ham_to_dem(102630) sub_time = now_time - start_time return int(sub_time)",
"= glob.glob(str(tracklets_per_cam_dir / tracklet_id / '*.jpg')) img_paths.sort() if len(img_paths) <= 2: count_ignore_tkl +=",
"+ ti[0]['average_images_num'] print(\"=> GPSMOT loaded\") print(\"Dataset statistics:\") print(\" ----------------------------------------------------------------------------------------------------------------\") print(\" subset | #",
"wd = data_pix2loc[index, 3] elif method == 'nearest_k_mean': ex = data_pix2loc[:, 0] -",
">= 3750: return False if camid == 3: if locy <= 200: return",
"distance ''' j_dist = dist[0] * 111000 * np.cos(31 / 180 * np.pi)",
"False if camid == 4: if locy <= 600: return False if camid",
"print(\" cam5 | {:10d} | {:17d} | {:20d} | {:22d} | {:20d} \".format(ti[4]['total_tracklets_num'],",
"flush=True) return info @staticmethod def json_dump(info, file_path, encoding='UTF-8'): check_path(Path(file_path).parent, create=True) with open(file_path, 'w',",
"== 3: if locy <= 250: return False if camid == 4: if",
"j_dist = dist[0] * 111000 * np.cos(31 / 180 * np.pi) w_dist =",
"1 img0 = cv2.imread(img_path) data_cur = data_arr[data_arr[:,0] == index] for data in data_cur:",
"flush=True) return info @staticmethod def np_save(info, file_path): check_path(Path(file_path).parent, create=True) assert file_path.split('.')[-1] == 'npy',",
"for data in total_data: data = data.strip().split(',') data_list.append([int(data[0]), int(data[1]), float(data[2]), float(data[3]), float(data[4]), float(data[5])])",
"a: ndarray:[jd, wd] :param b: ndarray:[jd, wd] :return: distance ''' dist = a",
"= y1 + h x2 = x1 + w if y1 <= 0:",
"x1 <= 0: x1 = 0 if y2 > 3007: y2 = 3007",
"2)) def trans_gps_diff_to_dist_v3(gps_1, gps_2): ''' :param gps_1: [jd, wd] :param gps_2: [jd, wd]",
"@staticmethod def load(file_path): check_path(file_path) with open(file_path, 'rb') as f: info = pickle.load(f) print('Load",
"camid in range(cam_num): tracklets_per_cam_dir = tracklet_dir / '{:02d}'.format(camid + 1) tracklet_ids = os.listdir(tracklets_per_cam_dir)",
"ti[4]['ignore_tracklets_num'], \\ ti[4]['available_tracklets_num'], ti[4]['available_images_num'], ti[4]['average_images_num'])) print(\" cam6 | {:10d} | {:17d} | {:20d}",
"' + str(file_path), flush=True) @staticmethod def np_load_txt(file_path, acq_print=True): check_path(file_path) assert file_path.split('.')[-1] == 'txt',",
"from 102630 ''' now_time = ham_to_dem(time) start_time = ham_to_dem(102630) sub_time = now_time -",
"== 'txt', 'This file\\' suffix is not txt, please check file path.' info",
"wd] :return: distance ''' dist = a - b j_dist = dist[0] *",
"ti[3]['available_tracklets_num'], ti[3]['available_images_num'], ti[3]['average_images_num'])) print(\" cam5 | {:10d} | {:17d} | {:20d} | {:22d}",
"1 info['old2new'][camid][int(tracklet_id)] = new_id new_id += 1 info['tracklets'].append((img_paths, new_id, camid)) total_num += len(img_paths)",
"'r') as f: lines = f.readlines() for line in lines: data = line.strip().split(',')",
"@staticmethod def np_load(file_path, acq_print=True): check_path(file_path) assert file_path.split('.')[-1] == 'npy', 'This file\\' suffix is",
"2000: return False return True @staticmethod def refine_result(path, path_new, camid): refineData = []",
":return: distance ''' j_dist = dist[0] * 111000 * np.cos(31 / 180 *",
"+ str(file_path), flush=True) return info class DataProcesser(object): @staticmethod def refine_v1(camid, locx, locy): if",
"if locy <= 200 or locx >= 3600: return False if camid ==",
"'*.jpg')) img_paths.sort() result_path = result_dir / ('GPSReID0'+str(camid)+'_refine_v2.txt') data_list = [] with open(result_path, 'r')",
"2 locy = float(data[3]) + float(data[5]) if DataProcesser.refine_v2(camid, locx, locy): refineData.append(line) with open(path_new,",
"float(data[5])]) data_arr = np.array(data_list) for img_path in img_paths: index = int(img_path.split('/')[-1].split('.')[0]) + 1",
"img) except: print('ignore image -- ', save_img_path / img_name) @staticmethod def count_dataset_info(tracklet_dir, cam_num,",
"refine_result(path, path_new, camid): refineData = [] with open(path, 'r') as f: lines =",
"<= 3000 or locx - 8.235 * locy >= 1200: return False if",
"if create: try: os.makedirs(folder_dir) except OSError as e: if e.errno != errno.EEXIST: raise",
"data_list.append([int(data[0]), int(data[1]), float(data[2]), float(data[3]), float(data[4]), float(data[5])]) data_arr = np.array(data_list) for img_path in img_paths:",
"img_name), img) except: print('ignore image -- ', save_img_path / img_name) @staticmethod def count_dataset_info(tracklet_dir,",
"| {:22d} | {:20d} \".format(ti[2]['total_tracklets_num'], ti[2]['ignore_tracklets_num'], \\ ti[2]['available_tracklets_num'], ti[2]['available_images_num'], ti[2]['average_images_num'])) print(\" cam4 |",
"class DataPacker(object): ''' this class supplys four different Data processing format ''' @staticmethod",
"''' :param a: ndarray:[jd, wd] :param b: ndarray:[jd, wd] :return: distance ''' dist",
"** 2 index = np.argsort(dist)[0] jd = data_pix2loc[index, 2] wd = data_pix2loc[index, 3]",
"cam2 | {:10d} | {:17d} | {:20d} | {:22d} | {:20d} \".format(ti[1]['total_tracklets_num'], ti[1]['ignore_tracklets_num'],",
"''' :param time: hour minute second :return: second ''' dam_time_list = [] if",
"= ex ** 2 + ey ** 2 index = np.argsort(dist)[0] jd =",
"if not folder_dir.exists(): if create: try: os.makedirs(folder_dir) except OSError as e: if e.errno",
"== 2: if locy <= 200 or locx >= 3600: return False if",
"+ ti[5]['average_images_num'] + ti[0]['average_images_num'] print(\"=> GPSMOT loaded\") print(\"Dataset statistics:\") print(\" ----------------------------------------------------------------------------------------------------------------\") print(\" subset",
"import geodesic from pathlib import Path import glob import cv2 def ham_to_dem(time): '''",
"+ ti[5]['total_tracklets_num'] + ti[0]['total_tracklets_num'] to_itn = ti[1]['ignore_tracklets_num'] + ti[2]['ignore_tracklets_num'] + ti[3]['ignore_tracklets_num'] + \\",
"print(\" ----------------------------------------------------------------------------------------------------------------\") print(\" cam1 | {:10d} | {:17d} | {:20d} | {:22d} |",
"'w') as f: f.writelines(refineData) @staticmethod def crop_image(img_dir, result_dir, save_img_dir, camid): img_paths = glob.glob(str(img_dir",
"acq_print=True): check_path(file_path) assert file_path.split('.')[-1] == 'npy', 'This file\\' suffix is not npy, please",
"'txt', 'This file\\' suffix is not txt, please check file path.' info =",
"info['tracklets_info'][camid]['ignore_tracklets_num'] = count_ignore_tkl info['tracklets_info'][camid]['available_tracklets_num'] = count_ava_tkl info['tracklets_info'][camid]['available_images_num'] = total_num info['tracklets_info'][camid]['average_images_num'] = total_num //",
"info = np.loadtxt(file_path) if acq_print: print('Load data <--- ' + str(file_path), flush=True) return",
"ti[1]['available_images_num'], ti[1]['average_images_num'])) print(\" cam3 | {:10d} | {:17d} | {:20d} | {:22d} |",
"/ img_name) @staticmethod def count_dataset_info(tracklet_dir, cam_num, verbose=False, save_info=False): tracklet_dir = Path(tracklet_dir) info =",
"[] with open(result_path, 'r') as f: total_data = f.readlines() for data in total_data:",
"not npy, please check file path.' np.save(file_path, info) print('Store data ---> ' +",
"geodesic((gps_1[1], gps_1[0]), (gps_2[1], gps_2[0]).m) def pixel_to_loc(data_pix2loc, traj_point, method='nearset', k=4): ''' :param data_pix2loc: [pixel_x,",
"float(data[3]) + float(data[5]) if DataProcesser.refine_v2(camid, locx, locy): refineData.append(line) with open(path_new, 'w') as f:",
"print(\" cam3 | {:10d} | {:17d} | {:20d} | {:22d} | {:20d} \".format(ti[2]['total_tracklets_num'],",
"1] - traj_point[1] dist = ex ** 2 + ey ** 2 index",
"ti[3]['available_tracklets_num'] + \\ ti[4]['available_tracklets_num'] + ti[5]['available_tracklets_num'] + ti[0]['available_tracklets_num'] to_avain = ti[1]['available_images_num'] + ti[2]['available_images_num']",
"as f: info = pickle.load(f) print('Load data <--- ' + str(file_path), flush=True) return",
"0: y1 = 0 if x1 <= 0: x1 = 0 if y2",
"dem_time = int(i % 100) + 60 * (int(i % 10000) - int(i",
"flush=True) @staticmethod def json_load(file_path, encoding='UTF-8', acq_print=True): check_path(file_path) with open(file_path, 'r', encoding=encoding) as f:",
"4000 img = img0[int(y1):int(y2),int(x1):int(x2)] img_name = 'T{:05d}_C{:02d}_F{:06d}_I{:06d}.jpg'.format(int(tid), camid, int(fid), count+1) try: cv2.imwrite(str(save_img_path /",
"elif method == 'linear': index = np.where(int(data_pix2loc[:, 0]) == traj_point[0] and int(data_pix2loc[:, 1])",
"{:20d} | {:22d} | {:20d} \".format(ti[0]['total_tracklets_num'], ti[0]['ignore_tracklets_num'], \\ ti[0]['available_tracklets_num'], ti[0]['available_images_num'], ti[0]['average_images_num'])) print(\" cam2",
"assert file_path.split('.')[-1] == 'npy', 'This file\\' suffix is not npy, please check file",
"ti[1]['ignore_tracklets_num'], \\ ti[1]['available_tracklets_num'], ti[1]['available_images_num'], ti[1]['average_images_num'])) print(\" cam3 | {:10d} | {:17d} | {:20d}",
"import pickle import numpy as np import os import errno from geopy.distance import",
"geopy.distance import geodesic from pathlib import Path import glob import cv2 def ham_to_dem(time):",
"as np import os import errno from geopy.distance import geodesic from pathlib import",
"a = a.copy() a_min = np.min(a, axis=1, keepdims=True) _range = np.max(a,axis=1,keepdims=True) - a_min",
"\".format(ti[2]['total_tracklets_num'], ti[2]['ignore_tracklets_num'], \\ ti[2]['available_tracklets_num'], ti[2]['available_images_num'], ti[2]['average_images_num'])) print(\" cam4 | {:10d} | {:17d} |",
"tracklet_ids: img_paths = glob.glob(str(tracklets_per_cam_dir / tracklet_id / '*.jpg')) img_paths.sort() if len(img_paths) <= 2:",
"print('Load data <--- ' + str(file_path), flush=True) return info @staticmethod def json_dump(info, file_path,",
"camid == 4: if locy <= 600 or (locx >= 2000 and 0.5833",
"point :return: traj_list's jd and wd ''' if method == 'nearset': ex =",
"0 total_num = 0 for tracklet_id in tracklet_ids: img_paths = glob.glob(str(tracklets_per_cam_dir / tracklet_id",
"| {:20d} | {:22d} | {:20d} \".format(ti[2]['total_tracklets_num'], ti[2]['ignore_tracklets_num'], \\ ti[2]['available_tracklets_num'], ti[2]['available_images_num'], ti[2]['average_images_num'])) print(\"",
"ti[4]['available_images_num'] + ti[5]['available_images_num'] + ti[0]['available_images_num'] to_avein = ti[1]['average_images_num'] + ti[2]['average_images_num'] + ti[3]['average_images_num'] +",
"not :return: ''' folder_dir = Path(folder_dir) if not folder_dir.exists(): if create: try: os.makedirs(folder_dir)",
"= np.loadtxt(file_path) if acq_print: print('Load data <--- ' + str(file_path), flush=True) return info",
"3] elif method == 'linear': index = np.where(int(data_pix2loc[:, 0]) == traj_point[0] and int(data_pix2loc[:,",
"data_pix2loc[index, 2] wd = data_pix2loc[index, 3] elif method == 'nearest_k_mean': ex = data_pix2loc[:,",
"numpy as np import os import errno from geopy.distance import geodesic from pathlib",
"second ''' dam_time_list = [] if isinstance(time, list): for i in time: dem_time",
"if method == 'nearset': ex = data_pix2loc[:, 0] - traj_point[0] ey = data_pix2loc[:,",
"traj_list's jd and wd ''' if method == 'nearset': ex = data_pix2loc[:, 0]",
"{:22d} | {:20d} \".format(ti[4]['total_tracklets_num'], ti[4]['ignore_tracklets_num'], \\ ti[4]['available_tracklets_num'], ti[4]['available_images_num'], ti[4]['average_images_num'])) print(\" cam6 | {:10d}",
"int(time / 10000) * 60 * 60 return int(dem_time) def get_time(time): ''' :param",
"== traj_point[1]) jd = data_pix2loc[index, 2] wd = data_pix2loc[index, 3] elif method ==",
"a_min) / _range def check_path(folder_dir, create=False): ''' :param folder_dir: file path :param create:",
"file_path.split('.')[-1] == 'txt', 'This file\\' suffix is not txt, please check file path.'",
"\".format(ti[3]['total_tracklets_num'], ti[3]['ignore_tracklets_num'], \\ ti[3]['available_tracklets_num'], ti[3]['available_images_num'], ti[3]['average_images_num'])) print(\" cam5 | {:10d} | {:17d} |",
"(locx >= 2000 and 0.5833 * locx + locy <= 2340): return False",
"<= 2340): return False if camid == 5: if locy <= 150 or",
"return dam_time_list else: dem_time = int(time % 100) + 60 * (int(time %",
"json.dump(info, f) print('Store data ---> ' + str(file_path), flush=True) @staticmethod def json_load(file_path, encoding='UTF-8',",
"= 0 count_avg_tkl_num = 0 total_num = 0 for tracklet_id in tracklet_ids: img_paths",
"= info['tracklets_info'] to_tn = ti[1]['total_tracklets_num'] + ti[2]['total_tracklets_num'] + ti[3]['total_tracklets_num'] + \\ ti[4]['total_tracklets_num'] +",
"txt, please check file path.' info = np.loadtxt(file_path) if acq_print: print('Load data <---",
"''' return geodesic((gps_1[1], gps_1[0]), (gps_2[1], gps_2[0]).m) def pixel_to_loc(data_pix2loc, traj_point, method='nearset', k=4): ''' :param",
"= x1 + w if y1 <= 0: y1 = 0 if x1",
"* np.pi) w_dist = dist[1] * 111000 return np.sqrt(np.power(j_dist, 2)+np.power(w_dist, 2)) def trans_gps_diff_to_dist_v2(dist):",
"True @staticmethod def refine_result(path, path_new, camid): refineData = [] with open(path, 'r') as",
"== 4: if locy <= 600 or (locx >= 2000 and 0.5833 *",
"img_paths.sort() result_path = result_dir / ('GPSReID0'+str(camid)+'_refine_v2.txt') data_list = [] with open(result_path, 'r') as",
"% 100) + 60 * (int(time % 10000) - int(time % 100)) /",
"str(file_path), flush=True) @staticmethod def np_load(file_path, acq_print=True): check_path(file_path) assert file_path.split('.')[-1] == 'npy', 'This file\\'",
"''' now_time = ham_to_dem(time) start_time = ham_to_dem(102630) sub_time = now_time - start_time return",
"to_itn = ti[1]['ignore_tracklets_num'] + ti[2]['ignore_tracklets_num'] + ti[3]['ignore_tracklets_num'] + \\ ti[4]['ignore_tracklets_num'] + ti[5]['ignore_tracklets_num'] +",
"- 5.7143 * locy >= 2000: return False if camid == 6: if",
"for tracklet_id in tracklet_ids: img_paths = glob.glob(str(tracklets_per_cam_dir / tracklet_id / '*.jpg')) img_paths.sort() if",
"def count_dataset_info(tracklet_dir, cam_num, verbose=False, save_info=False): tracklet_dir = Path(tracklet_dir) info = {'old2new':[{} for i",
"x1, y1, w, h = data save_img_path = save_img_dir / '{:02d}'.format(camid) / '{:05d}'.format(int(tid))",
"if verbose: ti = info['tracklets_info'] to_tn = ti[1]['total_tracklets_num'] + ti[2]['total_tracklets_num'] + ti[3]['total_tracklets_num'] +",
"pixel_y] size[2] :param method: 'nearest' 'linear' 'nearest_k_mean' :param k: num of selected point",
"try: os.makedirs(folder_dir) except OSError as e: if e.errno != errno.EEXIST: raise else: raise",
"as e: if e.errno != errno.EEXIST: raise else: raise IOError return folder_dir class",
"data <--- ' + str(file_path), flush=True) return info @staticmethod def np_save(info, file_path): check_path(Path(file_path).parent,",
"or locx - 8.235 * locy >= 1200: return False if camid ==",
"ti[0]['available_tracklets_num'], ti[0]['available_images_num'], ti[0]['average_images_num'])) print(\" cam2 | {:10d} | {:17d} | {:20d} | {:22d}",
"+= 1 info['tracklets'].append((img_paths, new_id, camid)) total_num += len(img_paths) count_avg_tkl_num += 1 info['tracklets_info'][camid]['total_tracklets_num'] =",
"2 index = np.argsort(dist)[0] jd = data_pix2loc[index, 2] wd = data_pix2loc[index, 3] elif",
"tkls num | # available images num | # average images num\") print(\"",
"| {:10d} | {:17d} | {:20d} | {:22d} | {:20d} \".format(ti[5]['total_tracklets_num'], ti[5]['ignore_tracklets_num'], \\",
"check_path(Path(file_path).parent, create=True) with open(file_path, 'w', encoding=encoding) as f: json.dump(info, f) print('Store data --->",
"= Path(folder_dir) if not folder_dir.exists(): if create: try: os.makedirs(folder_dir) except OSError as e:",
"''' :param dist: [jd_sub, wd_sub] :return: distance ''' j_dist = dist[0] * 111000",
"-- ', save_img_path / img_name) @staticmethod def count_dataset_info(tracklet_dir, cam_num, verbose=False, save_info=False): tracklet_dir =",
"line in lines: data = line.strip().split(',') locx = float(data[2]) + float(data[4]) / 2",
"= len(glob.glob(str(save_img_path / '*.jpg'))) y2 = y1 + h x2 = x1 +",
"!= errno.EEXIST: raise else: raise IOError return folder_dir class DataPacker(object): ''' this class",
"method == 'nearset': ex = data_pix2loc[:, 0] - traj_point[0] ey = data_pix2loc[:, 1]",
"<= 150 or 0.1167 * locx + locy <= 350 or locx -",
"for i in time: dem_time = int(i % 100) + 60 * (int(i",
"---> ' + str(file_path), flush=True) @staticmethod def np_load(file_path, acq_print=True): check_path(file_path) assert file_path.split('.')[-1] ==",
"{:17d} | {:20d} | {:22d} | {:20d} \".format(ti[0]['total_tracklets_num'], ti[0]['ignore_tracklets_num'], \\ ti[0]['available_tracklets_num'], ti[0]['available_images_num'], ti[0]['average_images_num']))",
"350 or locx - 5.7143 * locy >= 2000: return False if camid",
"i in time: dem_time = int(i % 100) + 60 * (int(i %",
"return int(sub_time) def trans_gps_diff_to_dist_v1(a, b): ''' :param a: ndarray:[jd, wd] :param b: ndarray:[jd,",
"3007: y2 = 3007 if x2 > 4000: x2 = 4000 img =",
"num | # average images num\") print(\" ----------------------------------------------------------------------------------------------------------------\") print(\" cam1 | {:10d} |",
"info['tracklets_info'][camid]['ignore_tracklets_num'] + \\ info['tracklets_info'][camid]['available_tracklets_num'] if save_info: DataPacker.dump(info, tracklet_dir / 'info.pkl') return info if",
"2: count_ignore_tkl += 1 info['old2new'][camid][int(tracklet_id)] = None info['ignore'].append(tracklets_per_cam_dir / tracklet_id) else: count_ava_tkl +=",
"wd] :param b: ndarray:[jd, wd] :return: distance ''' dist = a - b",
"* 111000 * np.cos(a[1] / 180 * np.pi) w_dist = dist[1] * 111000",
"= a - b j_dist = dist[0] * 111000 * np.cos(a[1] / 180",
":param gps_2: [jd, wd] :return: distance between two gps ''' return geodesic((gps_1[1], gps_1[0]),",
"file or not :return: ''' folder_dir = Path(folder_dir) if not folder_dir.exists(): if create:",
"data save_img_path = save_img_dir / '{:02d}'.format(camid) / '{:05d}'.format(int(tid)) check_path(save_img_path, create=True) count = len(glob.glob(str(save_img_path",
"> 3007: y2 = 3007 if x2 > 4000: x2 = 4000 img",
"different Data processing format ''' @staticmethod def dump(info, file_path): check_path(Path(file_path).parent, create=True) with open(file_path,",
"== 'linear': index = np.where(int(data_pix2loc[:, 0]) == traj_point[0] and int(data_pix2loc[:, 1]) == traj_point[1])",
"from pathlib import Path import glob import cv2 def ham_to_dem(time): ''' :param time:",
"gps_1: [jd, wd] :param gps_2: [jd, wd] :return: distance between two gps '''",
"0]) == traj_point[0] and int(data_pix2loc[:, 1]) == traj_point[1]) jd = data_pix2loc[index, 2] wd",
"False if camid == 2: if locy <= 150 or locx >= 3750:",
"| {:17d} | {:20d} | {:22d} | {:20d} \".format(ti[3]['total_tracklets_num'], ti[3]['ignore_tracklets_num'], \\ ti[3]['available_tracklets_num'], ti[3]['available_images_num'],",
"1]) == traj_point[1]) jd = data_pix2loc[index, 2] wd = data_pix2loc[index, 3] elif method",
"| {:20d} | {:22d} | {:20d} \".format(ti[1]['total_tracklets_num'], ti[1]['ignore_tracklets_num'], \\ ti[1]['available_tracklets_num'], ti[1]['available_images_num'], ti[1]['average_images_num'])) print(\"",
"suffix is not txt, please check file path.' info = np.loadtxt(file_path) if acq_print:",
"np.array(data_list) for img_path in img_paths: index = int(img_path.split('/')[-1].split('.')[0]) + 1 img0 = cv2.imread(img_path)",
"<= 600 or (locx >= 2000 and 0.5833 * locx + locy <=",
"| # available tkls num | # available images num | # average",
"''' dam_time_list = [] if isinstance(time, list): for i in time: dem_time =",
"info['tracklets_info'][camid]['available_tracklets_num'] = count_ava_tkl info['tracklets_info'][camid]['available_images_num'] = total_num info['tracklets_info'][camid]['average_images_num'] = total_num // count_ava_tkl assert info['tracklets_info'][camid]['total_tracklets_num']",
"'This file\\' suffix is not txt, please check file path.' np.savetxt(file_path, info) print('Store",
"= now_time - start_time return int(sub_time) def trans_gps_diff_to_dist_v1(a, b): ''' :param a: ndarray:[jd,",
"''' if method == 'nearset': ex = data_pix2loc[:, 0] - traj_point[0] ey =",
"result_dir / ('GPSReID0'+str(camid)+'_refine_v2.txt') data_list = [] with open(result_path, 'r') as f: total_data =",
"'This file\\' suffix is not npy, please check file path.' np.save(file_path, info) print('Store",
"''' :param data_pix2loc: [pixel_x, pixel_y, jd, wd] size[n, 4] :param traj_list: [pixel_x, pixel_y]",
":param method: 'nearest' 'linear' 'nearest_k_mean' :param k: num of selected point :return: traj_list's",
"' + str(file_path), flush=True) return info @staticmethod def json_dump(info, file_path, encoding='UTF-8'): check_path(Path(file_path).parent, create=True)",
"y1 <= 0: y1 = 0 if x1 <= 0: x1 = 0",
"int(data_pix2loc[:, 1]) == traj_point[1]) jd = data_pix2loc[index, 2] wd = data_pix2loc[index, 3] elif",
"+ ti[2]['average_images_num'] + ti[3]['average_images_num'] + \\ ti[4]['average_images_num'] + ti[5]['average_images_num'] + ti[0]['average_images_num'] print(\"=> GPSMOT",
"/ img_name), img) except: print('ignore image -- ', save_img_path / img_name) @staticmethod def",
"file_path, encoding='UTF-8'): check_path(Path(file_path).parent, create=True) with open(file_path, 'w', encoding=encoding) as f: json.dump(info, f) print('Store",
"= save_img_dir / '{:02d}'.format(camid) / '{:05d}'.format(int(tid)) check_path(save_img_path, create=True) count = len(glob.glob(str(save_img_path / '*.jpg')))",
"/ '*.jpg')) img_paths.sort() if len(img_paths) <= 2: count_ignore_tkl += 1 info['old2new'][camid][int(tracklet_id)] = None",
"10000) * 60 * 60 dam_time_list.append(dem_time) return dam_time_list else: dem_time = int(time %",
"info['tracklets_info'] to_tn = ti[1]['total_tracklets_num'] + ti[2]['total_tracklets_num'] + ti[3]['total_tracklets_num'] + \\ ti[4]['total_tracklets_num'] + ti[5]['total_tracklets_num']",
"file path.' np.savetxt(file_path, info) print('Store data ---> ' + str(file_path), flush=True) @staticmethod def",
"N X N :return: normalize feature ''' a = a.copy() a_min = np.min(a,",
"json.load(f) if acq_print: print('Load data <--- ' + str(file_path), flush=True) return info @staticmethod",
"with open(file_path, 'rb') as f: info = pickle.load(f) print('Load data <--- ' +",
"assert info['tracklets_info'][camid]['total_tracklets_num'] == \\ info['tracklets_info'][camid]['ignore_tracklets_num'] + \\ info['tracklets_info'][camid]['available_tracklets_num'] if save_info: DataPacker.dump(info, tracklet_dir /",
"# tkls num | # ignore tkls num | # available tkls num",
"{:10d} | {:17d} | {:20d} | {:22d} | {:20d} \".format(ti[0]['total_tracklets_num'], ti[0]['ignore_tracklets_num'], \\ ti[0]['available_tracklets_num'],",
"in range(cam_num)], 'ignore':[], 'tracklets_info':[{} for i in range(cam_num)], 'tracklets':[]} new_id = 0 for",
"ti[1]['average_images_num'] + ti[2]['average_images_num'] + ti[3]['average_images_num'] + \\ ti[4]['average_images_num'] + ti[5]['average_images_num'] + ti[0]['average_images_num'] print(\"=>",
"locy <= 200: return False if camid == 4: if locy <= 600:",
"locy <= 150 or locx - 2.5 * locy >= 2000: return False",
"@staticmethod def np_save(info, file_path): check_path(Path(file_path).parent, create=True) assert file_path.split('.')[-1] == 'npy', 'This file\\' suffix",
"Path(tracklet_dir) info = {'old2new':[{} for i in range(cam_num)], 'ignore':[], 'tracklets_info':[{} for i in",
"geodesic from pathlib import Path import glob import cv2 def ham_to_dem(time): ''' :param",
"get_time(time): ''' :param time: hour minute second :return: second from 102630 ''' now_time",
"info['old2new'][camid][int(tracklet_id)] = new_id new_id += 1 info['tracklets'].append((img_paths, new_id, camid)) total_num += len(img_paths) count_avg_tkl_num",
":return: distance between two gps ''' return geodesic((gps_1[1], gps_1[0]), (gps_2[1], gps_2[0]).m) def pixel_to_loc(data_pix2loc,",
"= [] if isinstance(time, list): for i in time: dem_time = int(i %",
"ex = data_pix2loc[:, 0] - traj_point[0] ey = data_pix2loc[:, 1] - traj_point[1] dist",
"please check file path.' np.save(file_path, info) print('Store data ---> ' + str(file_path), flush=True)",
"fid, tid, x1, y1, w, h = data save_img_path = save_img_dir / '{:02d}'.format(camid)",
"2: if locy <= 200 or locx >= 3600: return False if camid",
"= np.min(a, axis=1, keepdims=True) _range = np.max(a,axis=1,keepdims=True) - a_min return (a - a_min)",
"or not :return: ''' folder_dir = Path(folder_dir) if not folder_dir.exists(): if create: try:",
"= 0 if x1 <= 0: x1 = 0 if y2 > 3007:",
"% 10000) - int(time % 100)) / 100 + int(time / 10000) *",
"/ 10000) * 60 * 60 return int(dem_time) def get_time(time): ''' :param time:",
"ti[3]['ignore_tracklets_num'], \\ ti[3]['available_tracklets_num'], ti[3]['available_images_num'], ti[3]['average_images_num'])) print(\" cam5 | {:10d} | {:17d} | {:20d}",
"''' @staticmethod def dump(info, file_path): check_path(Path(file_path).parent, create=True) with open(file_path, 'wb') as f: pickle.dump(info,",
"ti[5]['ignore_tracklets_num'] + ti[0]['ignore_tracklets_num'] to_atn = ti[1]['available_tracklets_num'] + ti[2]['available_tracklets_num'] + ti[3]['available_tracklets_num'] + \\ ti[4]['available_tracklets_num']",
":param a: ndarray:[jd, wd] :param b: ndarray:[jd, wd] :return: distance ''' dist =",
"format ''' @staticmethod def dump(info, file_path): check_path(Path(file_path).parent, create=True) with open(file_path, 'wb') as f:",
"ti[0]['total_tracklets_num'] to_itn = ti[1]['ignore_tracklets_num'] + ti[2]['ignore_tracklets_num'] + ti[3]['ignore_tracklets_num'] + \\ ti[4]['ignore_tracklets_num'] + ti[5]['ignore_tracklets_num']",
"= total_num info['tracklets_info'][camid]['average_images_num'] = total_num // count_ava_tkl assert info['tracklets_info'][camid]['total_tracklets_num'] == \\ info['tracklets_info'][camid]['ignore_tracklets_num'] +",
"x2 = x1 + w if y1 <= 0: y1 = 0 if",
"dist = ex ** 2 + ey ** 2 indexs = np.argsort(dist)[:k] jd,",
"os import errno from geopy.distance import geodesic from pathlib import Path import glob",
"2)+np.power(w_dist, 2)) def trans_gps_diff_to_dist_v3(gps_1, gps_2): ''' :param gps_1: [jd, wd] :param gps_2: [jd,",
"= data_pix2loc[index, 3] elif method == 'linear': index = np.where(int(data_pix2loc[:, 0]) == traj_point[0]",
"wd] :return: distance between two gps ''' return geodesic((gps_1[1], gps_1[0]), (gps_2[1], gps_2[0]).m) def",
"with open(file_path, 'r', encoding=encoding) as f: info = json.load(f) if acq_print: print('Load data",
"count_ignore_tkl info['tracklets_info'][camid]['available_tracklets_num'] = count_ava_tkl info['tracklets_info'][camid]['available_images_num'] = total_num info['tracklets_info'][camid]['average_images_num'] = total_num // count_ava_tkl assert",
"hour minute second :return: second ''' dam_time_list = [] if isinstance(time, list): for",
"file_path): check_path(Path(file_path).parent, create=True) assert file_path.split('.')[-1] == 'npy', 'This file\\' suffix is not npy,",
"tracklet_dir / '{:02d}'.format(camid + 1) tracklet_ids = os.listdir(tracklets_per_cam_dir) tracklet_ids.sort() tracklets_num = len(tracklet_ids) count_ignore_tkl",
"== traj_point[0] and int(data_pix2loc[:, 1]) == traj_point[1]) jd = data_pix2loc[index, 2] wd =",
"indexs = np.argsort(dist)[:k] jd, wd = np.mean(data_pix2loc[indexs, 2:], axis=0) else: assert 'Do not",
"str(file_path), flush=True) return info class DataProcesser(object): @staticmethod def refine_v1(camid, locx, locy): if camid",
"str(file_path), flush=True) return info @staticmethod def json_dump(info, file_path, encoding='UTF-8'): check_path(Path(file_path).parent, create=True) with open(file_path,",
"+ str(file_path), flush=True) @staticmethod def np_load_txt(file_path, acq_print=True): check_path(file_path) assert file_path.split('.')[-1] == 'txt', 'This",
"method: 'nearest' 'linear' 'nearest_k_mean' :param k: num of selected point :return: traj_list's jd",
"print(\"Dataset statistics:\") print(\" ----------------------------------------------------------------------------------------------------------------\") print(\" subset | # tkls num | # ignore",
"4] :param traj_list: [pixel_x, pixel_y] size[2] :param method: 'nearest' 'linear' 'nearest_k_mean' :param k:",
"np_load_txt(file_path, acq_print=True): check_path(file_path) assert file_path.split('.')[-1] == 'txt', 'This file\\' suffix is not txt,",
"(gps_2[1], gps_2[0]).m) def pixel_to_loc(data_pix2loc, traj_point, method='nearset', k=4): ''' :param data_pix2loc: [pixel_x, pixel_y, jd,",
"| # average images num\") print(\" ----------------------------------------------------------------------------------------------------------------\") print(\" cam1 | {:10d} | {:17d}",
"* (int(time % 10000) - int(time % 100)) / 100 + int(time /",
"errno.EEXIST: raise else: raise IOError return folder_dir class DataPacker(object): ''' this class supplys",
"ti[0]['available_tracklets_num'] to_avain = ti[1]['available_images_num'] + ti[2]['available_images_num'] + ti[3]['available_images_num'] + \\ ti[4]['available_images_num'] + ti[5]['available_images_num']",
"if camid == 5: if locy <= 150 or 0.1167 * locx +",
"glob.glob(str(img_dir / '*.jpg')) img_paths.sort() result_path = result_dir / ('GPSReID0'+str(camid)+'_refine_v2.txt') data_list = [] with",
"+ \\ ti[4]['total_tracklets_num'] + ti[5]['total_tracklets_num'] + ti[0]['total_tracklets_num'] to_itn = ti[1]['ignore_tracklets_num'] + ti[2]['ignore_tracklets_num'] +",
"for line in lines: data = line.strip().split(',') locx = float(data[2]) + float(data[4]) /",
"locy <= 250: return False if camid == 4: if locy <= 600",
"locy >= 2000: return False if camid == 6: if locy <= 150",
"| {:20d} | {:22d} | {:20d} \".format(ti[4]['total_tracklets_num'], ti[4]['ignore_tracklets_num'], \\ ti[4]['available_tracklets_num'], ti[4]['available_images_num'], ti[4]['average_images_num'])) print(\"",
"= ti[1]['available_tracklets_num'] + ti[2]['available_tracklets_num'] + ti[3]['available_tracklets_num'] + \\ ti[4]['available_tracklets_num'] + ti[5]['available_tracklets_num'] + ti[0]['available_tracklets_num']",
"- traj_point[0] ey = data_pix2loc[:, 1] - traj_point[1] dist = ex ** 2",
"def crop_image(img_dir, result_dir, save_img_dir, camid): img_paths = glob.glob(str(img_dir / '*.jpg')) img_paths.sort() result_path =",
"k: num of selected point :return: traj_list's jd and wd ''' if method",
"+= 1 info['tracklets_info'][camid]['total_tracklets_num'] = tracklets_num info['tracklets_info'][camid]['ignore_tracklets_num'] = count_ignore_tkl info['tracklets_info'][camid]['available_tracklets_num'] = count_ava_tkl info['tracklets_info'][camid]['available_images_num'] =",
"file\\' suffix is not txt, please check file path.' np.savetxt(file_path, info) print('Store data",
"2:], axis=0) else: assert 'Do not have the meathod' return jd, wd def",
"trans_gps_diff_to_dist_v2(dist): ''' :param dist: [jd_sub, wd_sub] :return: distance ''' j_dist = dist[0] *",
"info @staticmethod def np_save_txt(info, file_path): check_path(Path(file_path).parent, create=True) assert file_path.split('.')[-1] == 'txt', 'This file\\'",
"locy): if camid == 1: if locx + 30 * locy <= 3000",
"glob.glob(str(tracklets_per_cam_dir / tracklet_id / '*.jpg')) img_paths.sort() if len(img_paths) <= 2: count_ignore_tkl += 1",
"count = len(glob.glob(str(save_img_path / '*.jpg'))) y2 = y1 + h x2 = x1",
"* 111000 * np.cos(31 / 180 * np.pi) w_dist = dist[1] * 111000",
"{:20d} \".format(ti[4]['total_tracklets_num'], ti[4]['ignore_tracklets_num'], \\ ti[4]['available_tracklets_num'], ti[4]['available_images_num'], ti[4]['average_images_num'])) print(\" cam6 | {:10d} | {:17d}",
"{:22d} | {:20d} \".format(ti[5]['total_tracklets_num'], ti[5]['ignore_tracklets_num'], \\ ti[5]['available_tracklets_num'], ti[5]['available_images_num'], ti[5]['average_images_num'])) print(\" ----------------------------------------------------------------------------------------------------------------\") print(\" total",
"open(path, 'r') as f: lines = f.readlines() for line in lines: data =",
"== 4: if locy <= 600: return False if camid == 5: if",
"check file path.' info = np.load(file_path) if acq_print: print('Load data <--- ' +",
"@staticmethod def count_dataset_info(tracklet_dir, cam_num, verbose=False, save_info=False): tracklet_dir = Path(tracklet_dir) info = {'old2new':[{} for",
"60 * (int(time % 10000) - int(time % 100)) / 100 + int(time",
"= np.array(data_list) for img_path in img_paths: index = int(img_path.split('/')[-1].split('.')[0]) + 1 img0 =",
"range(cam_num)], 'ignore':[], 'tracklets_info':[{} for i in range(cam_num)], 'tracklets':[]} new_id = 0 for camid",
"10000) - int(time % 100)) / 100 + int(time / 10000) * 60",
"camid, int(fid), count+1) try: cv2.imwrite(str(save_img_path / img_name), img) except: print('ignore image -- ',",
"np.mean(data_pix2loc[indexs, 2:], axis=0) else: assert 'Do not have the meathod' return jd, wd",
"{:20d} \".format(ti[5]['total_tracklets_num'], ti[5]['ignore_tracklets_num'], \\ ti[5]['available_tracklets_num'], ti[5]['available_images_num'], ti[5]['average_images_num'])) print(\" ----------------------------------------------------------------------------------------------------------------\") print(\" total | {:10d}",
"locy >= 2000: return False return True @staticmethod def refine_result(path, path_new, camid): refineData",
"npy, please check file path.' np.save(file_path, info) print('Store data ---> ' + str(file_path),",
"wd = np.mean(data_pix2loc[indexs, 2:], axis=0) else: assert 'Do not have the meathod' return",
"* 60 return int(dem_time) def get_time(time): ''' :param time: hour minute second :return:",
"ex ** 2 + ey ** 2 indexs = np.argsort(dist)[:k] jd, wd =",
"folder_dir = Path(folder_dir) if not folder_dir.exists(): if create: try: os.makedirs(folder_dir) except OSError as",
"or locx - 2.5 * locy >= 2000: return False return True @staticmethod",
"open(file_path, 'wb') as f: pickle.dump(info, f) print('Store data ---> ' + str(file_path), flush=True)",
"if camid == 2: if locy <= 200 or locx >= 3600: return",
"** 2 + ey ** 2 index = np.argsort(dist)[0] jd = data_pix2loc[index, 2]",
"dam_time_list = [] if isinstance(time, list): for i in time: dem_time = int(i",
">= 2000 and 0.5833 * locx + locy <= 2340): return False if",
":param traj_list: [pixel_x, pixel_y] size[2] :param method: 'nearest' 'linear' 'nearest_k_mean' :param k: num",
"k=4): ''' :param data_pix2loc: [pixel_x, pixel_y, jd, wd] size[n, 4] :param traj_list: [pixel_x,",
"1: if locx + 20 * locy <= 4000 or locx - 8.235",
"return False if camid == 2: if locy <= 200 or locx >=",
"* np.cos(a[1] / 180 * np.pi) w_dist = dist[1] * 111000 return np.sqrt(np.power(j_dist,",
"cam_num, verbose=False, save_info=False): tracklet_dir = Path(tracklet_dir) info = {'old2new':[{} for i in range(cam_num)],",
"\\ ti[4]['available_tracklets_num'], ti[4]['available_images_num'], ti[4]['average_images_num'])) print(\" cam6 | {:10d} | {:17d} | {:20d} |",
"i in range(cam_num)], 'tracklets':[]} new_id = 0 for camid in range(cam_num): tracklets_per_cam_dir =",
"| {:10d} | {:17d} | {:20d} | {:22d} | {:20d} \".format(ti[0]['total_tracklets_num'], ti[0]['ignore_tracklets_num'], \\",
"f.readlines() for line in lines: data = line.strip().split(',') locx = float(data[2]) + float(data[4])",
"| # ignore tkls num | # available tkls num | # available",
"@staticmethod def refine_result(path, path_new, camid): refineData = [] with open(path, 'r') as f:",
"np.pi) w_dist = dist[1] * 111000 return np.sqrt(np.power(j_dist, 2)+np.power(w_dist, 2)) def trans_gps_diff_to_dist_v3(gps_1, gps_2):",
"X N :return: normalize feature ''' a = a.copy() a_min = np.min(a, axis=1,",
"file path :param create: create file or not :return: ''' folder_dir = Path(folder_dir)",
"<--- ' + str(file_path), flush=True) return info @staticmethod def json_dump(info, file_path, encoding='UTF-8'): check_path(Path(file_path).parent,",
"N :return: normalize feature ''' a = a.copy() a_min = np.min(a, axis=1, keepdims=True)",
"3: if locy <= 250: return False if camid == 4: if locy",
"0 count_ava_tkl = 0 count_avg_tkl_num = 0 total_num = 0 for tracklet_id in",
"def np_load_txt(file_path, acq_print=True): check_path(file_path) assert file_path.split('.')[-1] == 'txt', 'This file\\' suffix is not",
"dist[1] * 111000 return np.sqrt(np.power(j_dist, 2)+np.power(w_dist, 2)) def trans_gps_diff_to_dist_v3(gps_1, gps_2): ''' :param gps_1:",
"dist = ex ** 2 + ey ** 2 index = np.argsort(dist)[0] jd",
"'w', encoding=encoding) as f: json.dump(info, f) print('Store data ---> ' + str(file_path), flush=True)",
"ti[3]['available_images_num'], ti[3]['average_images_num'])) print(\" cam5 | {:10d} | {:17d} | {:20d} | {:22d} |",
"w, h = data save_img_path = save_img_dir / '{:02d}'.format(camid) / '{:05d}'.format(int(tid)) check_path(save_img_path, create=True)",
"info['tracklets_info'][camid]['average_images_num'] = total_num // count_ava_tkl assert info['tracklets_info'][camid]['total_tracklets_num'] == \\ info['tracklets_info'][camid]['ignore_tracklets_num'] + \\ info['tracklets_info'][camid]['available_tracklets_num']",
"+ 20 * locy <= 4000 or locx - 8.235 * locy >=",
"tracklet_dir / 'info.pkl') return info if verbose: ti = info['tracklets_info'] to_tn = ti[1]['total_tracklets_num']",
"/ ('GPSReID0'+str(camid)+'_refine_v2.txt') data_list = [] with open(result_path, 'r') as f: total_data = f.readlines()",
"in total_data: data = data.strip().split(',') data_list.append([int(data[0]), int(data[1]), float(data[2]), float(data[3]), float(data[4]), float(data[5])]) data_arr =",
"{:20d} | {:22d} | {:20d} \".format(ti[5]['total_tracklets_num'], ti[5]['ignore_tracklets_num'], \\ ti[5]['available_tracklets_num'], ti[5]['available_images_num'], ti[5]['average_images_num'])) print(\" ----------------------------------------------------------------------------------------------------------------\")",
":return: distance ''' dist = a - b j_dist = dist[0] * 111000",
"print('Store data ---> ' + str(file_path), flush=True) @staticmethod def json_load(file_path, encoding='UTF-8', acq_print=True): check_path(file_path)",
"start_time return int(sub_time) def trans_gps_diff_to_dist_v1(a, b): ''' :param a: ndarray:[jd, wd] :param b:",
"True @staticmethod def refine_v2(camid, locx, locy): if camid == 1: if locx +",
"not have the meathod' return jd, wd def norm_data(a): ''' :param a: feature",
"second :return: second ''' dam_time_list = [] if isinstance(time, list): for i in",
"5.7143 * locy >= 2000: return False if camid == 6: if locy",
"h = data save_img_path = save_img_dir / '{:02d}'.format(camid) / '{:05d}'.format(int(tid)) check_path(save_img_path, create=True) count",
"if x1 <= 0: x1 = 0 if y2 > 3007: y2 =",
"and int(data_pix2loc[:, 1]) == traj_point[1]) jd = data_pix2loc[index, 2] wd = data_pix2loc[index, 3]",
"locx >= 3750: return False if camid == 3: if locy <= 200:",
"return False if camid == 3: if locy <= 200: return False if",
"info['tracklets_info'][camid]['available_images_num'] = total_num info['tracklets_info'][camid]['average_images_num'] = total_num // count_ava_tkl assert info['tracklets_info'][camid]['total_tracklets_num'] == \\ info['tracklets_info'][camid]['ignore_tracklets_num']",
"available images num | # average images num\") print(\" ----------------------------------------------------------------------------------------------------------------\") print(\" cam1 |",
"'T{:05d}_C{:02d}_F{:06d}_I{:06d}.jpg'.format(int(tid), camid, int(fid), count+1) try: cv2.imwrite(str(save_img_path / img_name), img) except: print('ignore image --",
"@staticmethod def np_save_txt(info, file_path): check_path(Path(file_path).parent, create=True) assert file_path.split('.')[-1] == 'txt', 'This file\\' suffix",
"data <--- ' + str(file_path), flush=True) return info @staticmethod def np_save_txt(info, file_path): check_path(Path(file_path).parent,",
"please check file path.' info = np.load(file_path) if acq_print: print('Load data <--- '",
"tracklets_num info['tracklets_info'][camid]['ignore_tracklets_num'] = count_ignore_tkl info['tracklets_info'][camid]['available_tracklets_num'] = count_ava_tkl info['tracklets_info'][camid]['available_images_num'] = total_num info['tracklets_info'][camid]['average_images_num'] = total_num",
"ti[2]['available_images_num'] + ti[3]['available_images_num'] + \\ ti[4]['available_images_num'] + ti[5]['available_images_num'] + ti[0]['available_images_num'] to_avein = ti[1]['average_images_num']",
"' + str(file_path), flush=True) return info class DataProcesser(object): @staticmethod def refine_v1(camid, locx, locy):",
":return: second from 102630 ''' now_time = ham_to_dem(time) start_time = ham_to_dem(102630) sub_time =",
"locy): if camid == 1: if locx + 20 * locy <= 4000",
"0] - traj_point[0] ey = data_pix2loc[:, 1] - traj_point[1] dist = ex **",
"cam4 | {:10d} | {:17d} | {:20d} | {:22d} | {:20d} \".format(ti[3]['total_tracklets_num'], ti[3]['ignore_tracklets_num'],",
"save_img_dir, camid): img_paths = glob.glob(str(img_dir / '*.jpg')) img_paths.sort() result_path = result_dir / ('GPSReID0'+str(camid)+'_refine_v2.txt')",
"Data processing format ''' @staticmethod def dump(info, file_path): check_path(Path(file_path).parent, create=True) with open(file_path, 'wb')",
"suffix is not npy, please check file path.' np.save(file_path, info) print('Store data --->",
"dist[1] * 111000 return np.sqrt(np.power(j_dist, 2)+np.power(w_dist, 2)) def trans_gps_diff_to_dist_v2(dist): ''' :param dist: [jd_sub,",
"+ float(data[4]) / 2 locy = float(data[3]) + float(data[5]) if DataProcesser.refine_v2(camid, locx, locy):",
"img0[int(y1):int(y2),int(x1):int(x2)] img_name = 'T{:05d}_C{:02d}_F{:06d}_I{:06d}.jpg'.format(int(tid), camid, int(fid), count+1) try: cv2.imwrite(str(save_img_path / img_name), img) except:",
"\\ ti[4]['total_tracklets_num'] + ti[5]['total_tracklets_num'] + ti[0]['total_tracklets_num'] to_itn = ti[1]['ignore_tracklets_num'] + ti[2]['ignore_tracklets_num'] + ti[3]['ignore_tracklets_num']",
"def pixel_to_loc(data_pix2loc, traj_point, method='nearset', k=4): ''' :param data_pix2loc: [pixel_x, pixel_y, jd, wd] size[n,",
"j_dist = dist[0] * 111000 * np.cos(a[1] / 180 * np.pi) w_dist =",
"supplys four different Data processing format ''' @staticmethod def dump(info, file_path): check_path(Path(file_path).parent, create=True)",
"average images num\") print(\" ----------------------------------------------------------------------------------------------------------------\") print(\" cam1 | {:10d} | {:17d} | {:20d}",
"2.5 * locy >= 2000: return False return True @staticmethod def refine_result(path, path_new,",
"\\ ti[4]['average_images_num'] + ti[5]['average_images_num'] + ti[0]['average_images_num'] print(\"=> GPSMOT loaded\") print(\"Dataset statistics:\") print(\" ----------------------------------------------------------------------------------------------------------------\")",
"num\") print(\" ----------------------------------------------------------------------------------------------------------------\") print(\" cam1 | {:10d} | {:17d} | {:20d} | {:22d}",
"have the meathod' return jd, wd def norm_data(a): ''' :param a: feature distance",
"import errno from geopy.distance import geodesic from pathlib import Path import glob import",
"| {:20d} \".format(ti[5]['total_tracklets_num'], ti[5]['ignore_tracklets_num'], \\ ti[5]['available_tracklets_num'], ti[5]['available_images_num'], ti[5]['average_images_num'])) print(\" ----------------------------------------------------------------------------------------------------------------\") print(\" total |",
"np.sqrt(np.power(j_dist, 2)+np.power(w_dist, 2)) def trans_gps_diff_to_dist_v2(dist): ''' :param dist: [jd_sub, wd_sub] :return: distance '''",
"h x2 = x1 + w if y1 <= 0: y1 = 0",
"= 'T{:05d}_C{:02d}_F{:06d}_I{:06d}.jpg'.format(int(tid), camid, int(fid), count+1) try: cv2.imwrite(str(save_img_path / img_name), img) except: print('ignore image",
"if DataProcesser.refine_v2(camid, locx, locy): refineData.append(line) with open(path_new, 'w') as f: f.writelines(refineData) @staticmethod def",
"int(img_path.split('/')[-1].split('.')[0]) + 1 img0 = cv2.imread(img_path) data_cur = data_arr[data_arr[:,0] == index] for data",
"'{:02d}'.format(camid) / '{:05d}'.format(int(tid)) check_path(save_img_path, create=True) count = len(glob.glob(str(save_img_path / '*.jpg'))) y2 = y1",
"index = int(img_path.split('/')[-1].split('.')[0]) + 1 img0 = cv2.imread(img_path) data_cur = data_arr[data_arr[:,0] == index]",
"{:20d} \".format(ti[3]['total_tracklets_num'], ti[3]['ignore_tracklets_num'], \\ ti[3]['available_tracklets_num'], ti[3]['available_images_num'], ti[3]['average_images_num'])) print(\" cam5 | {:10d} | {:17d}",
"- traj_point[1] dist = ex ** 2 + ey ** 2 indexs =",
"\\ info['tracklets_info'][camid]['ignore_tracklets_num'] + \\ info['tracklets_info'][camid]['available_tracklets_num'] if save_info: DataPacker.dump(info, tracklet_dir / 'info.pkl') return info",
"as f: pickle.dump(info, f) print('Store data ---> ' + str(file_path), flush=True) @staticmethod def",
"+ ti[0]['ignore_tracklets_num'] to_atn = ti[1]['available_tracklets_num'] + ti[2]['available_tracklets_num'] + ti[3]['available_tracklets_num'] + \\ ti[4]['available_tracklets_num'] +",
"total | {:10d} | {:17d} | {:20d} | {:22d} | {:20d} \".format(to_tn, to_itn,",
"meathod' return jd, wd def norm_data(a): ''' :param a: feature distance N X",
"<--- ' + str(file_path), flush=True) return info class DataProcesser(object): @staticmethod def refine_v1(camid, locx,",
"(int(i % 10000) - int(i % 100)) / 100 + int(i / 10000)",
"feature distance N X N :return: normalize feature ''' a = a.copy() a_min",
"locy >= 1200: return False if camid == 2: if locy <= 150",
"camid)) total_num += len(img_paths) count_avg_tkl_num += 1 info['tracklets_info'][camid]['total_tracklets_num'] = tracklets_num info['tracklets_info'][camid]['ignore_tracklets_num'] = count_ignore_tkl",
"+ str(file_path), flush=True) return info @staticmethod def np_save_txt(info, file_path): check_path(Path(file_path).parent, create=True) assert file_path.split('.')[-1]",
"with open(path_new, 'w') as f: f.writelines(refineData) @staticmethod def crop_image(img_dir, result_dir, save_img_dir, camid): img_paths",
"gps ''' return geodesic((gps_1[1], gps_1[0]), (gps_2[1], gps_2[0]).m) def pixel_to_loc(data_pix2loc, traj_point, method='nearset', k=4): '''",
"check file path.' np.save(file_path, info) print('Store data ---> ' + str(file_path), flush=True) @staticmethod",
"'r') as f: total_data = f.readlines() for data in total_data: data = data.strip().split(',')",
"check_path(file_path) with open(file_path, 'r', encoding=encoding) as f: info = json.load(f) if acq_print: print('Load",
"\".format(ti[0]['total_tracklets_num'], ti[0]['ignore_tracklets_num'], \\ ti[0]['available_tracklets_num'], ti[0]['available_images_num'], ti[0]['average_images_num'])) print(\" cam2 | {:10d} | {:17d} |",
"# available images num | # average images num\") print(\" ----------------------------------------------------------------------------------------------------------------\") print(\" cam1",
"* 60 * 60 dam_time_list.append(dem_time) return dam_time_list else: dem_time = int(time % 100)",
"2)) def trans_gps_diff_to_dist_v2(dist): ''' :param dist: [jd_sub, wd_sub] :return: distance ''' j_dist =",
"+= 1 info['old2new'][camid][int(tracklet_id)] = None info['ignore'].append(tracklets_per_cam_dir / tracklet_id) else: count_ava_tkl += 1 info['old2new'][camid][int(tracklet_id)]",
"+ w if y1 <= 0: y1 = 0 if x1 <= 0:",
"locx, locy): if camid == 1: if locx + 20 * locy <=",
"= 0 total_num = 0 for tracklet_id in tracklet_ids: img_paths = glob.glob(str(tracklets_per_cam_dir /",
"tid, x1, y1, w, h = data save_img_path = save_img_dir / '{:02d}'.format(camid) /",
"folder_dir: file path :param create: create file or not :return: ''' folder_dir =",
"ti[5]['average_images_num'] + ti[0]['average_images_num'] print(\"=> GPSMOT loaded\") print(\"Dataset statistics:\") print(\" ----------------------------------------------------------------------------------------------------------------\") print(\" subset |",
"create=False): ''' :param folder_dir: file path :param create: create file or not :return:",
":param b: ndarray:[jd, wd] :return: distance ''' dist = a - b j_dist",
"of selected point :return: traj_list's jd and wd ''' if method == 'nearset':",
"/ '{:02d}'.format(camid) / '{:05d}'.format(int(tid)) check_path(save_img_path, create=True) count = len(glob.glob(str(save_img_path / '*.jpg'))) y2 =",
"open(file_path, 'r', encoding=encoding) as f: info = json.load(f) if acq_print: print('Load data <---",
"acq_print: print('Load data <--- ' + str(file_path), flush=True) return info class DataProcesser(object): @staticmethod",
"30 * locy <= 3000 or locx - 8.235 * locy >= 1200:",
"not npy, please check file path.' info = np.load(file_path) if acq_print: print('Load data",
"ti[5]['available_tracklets_num'] + ti[0]['available_tracklets_num'] to_avain = ti[1]['available_images_num'] + ti[2]['available_images_num'] + ti[3]['available_images_num'] + \\ ti[4]['available_images_num']",
"num | # available images num | # average images num\") print(\" ----------------------------------------------------------------------------------------------------------------\")",
"| {:17d} | {:20d} | {:22d} | {:20d} \".format(to_tn, to_itn, to_atn, to_avain, to_avein))",
"locy >= 1200: return False if camid == 2: if locy <= 200",
"method == 'nearest_k_mean': ex = data_pix2loc[:, 0] - traj_point[0] ey = data_pix2loc[:, 1]",
"or 0.1167 * locx + locy <= 350 or locx - 5.7143 *",
"verbose=False, save_info=False): tracklet_dir = Path(tracklet_dir) info = {'old2new':[{} for i in range(cam_num)], 'ignore':[],",
"print('Store data ---> ' + str(file_path), flush=True) @staticmethod def load(file_path): check_path(file_path) with open(file_path,",
"/ 2 locy = float(data[3]) + float(data[5]) if DataProcesser.refine_v2(camid, locx, locy): refineData.append(line) with",
"image -- ', save_img_path / img_name) @staticmethod def count_dataset_info(tracklet_dir, cam_num, verbose=False, save_info=False): tracklet_dir",
"print('Store data ---> ' + str(file_path), flush=True) @staticmethod def np_load(file_path, acq_print=True): check_path(file_path) assert",
"count_ava_tkl assert info['tracklets_info'][camid]['total_tracklets_num'] == \\ info['tracklets_info'][camid]['ignore_tracklets_num'] + \\ info['tracklets_info'][camid]['available_tracklets_num'] if save_info: DataPacker.dump(info, tracklet_dir",
"''' dist = a - b j_dist = dist[0] * 111000 * np.cos(a[1]",
"cv2 def ham_to_dem(time): ''' :param time: hour minute second :return: second ''' dam_time_list",
"img0 = cv2.imread(img_path) data_cur = data_arr[data_arr[:,0] == index] for data in data_cur: fid,",
"+ ti[0]['total_tracklets_num'] to_itn = ti[1]['ignore_tracklets_num'] + ti[2]['ignore_tracklets_num'] + ti[3]['ignore_tracklets_num'] + \\ ti[4]['ignore_tracklets_num'] +",
"= np.load(file_path) if acq_print: print('Load data <--- ' + str(file_path), flush=True) return info",
"' + str(file_path), flush=True) return info @staticmethod def np_save_txt(info, file_path): check_path(Path(file_path).parent, create=True) assert",
"count_ignore_tkl = 0 count_ava_tkl = 0 count_avg_tkl_num = 0 total_num = 0 for",
"else: count_ava_tkl += 1 info['old2new'][camid][int(tracklet_id)] = new_id new_id += 1 info['tracklets'].append((img_paths, new_id, camid))",
"/ '{:02d}'.format(camid + 1) tracklet_ids = os.listdir(tracklets_per_cam_dir) tracklet_ids.sort() tracklets_num = len(tracklet_ids) count_ignore_tkl =",
"* locy >= 2000: return False return True @staticmethod def refine_v2(camid, locx, locy):",
"return False if camid == 4: if locy <= 600: return False if",
":param a: feature distance N X N :return: normalize feature ''' a =",
"pixel_to_loc(data_pix2loc, traj_point, method='nearset', k=4): ''' :param data_pix2loc: [pixel_x, pixel_y, jd, wd] size[n, 4]",
"return False if camid == 5: if locy <= 150 or 0.1167 *",
"def load(file_path): check_path(file_path) with open(file_path, 'rb') as f: info = pickle.load(f) print('Load data",
"0 count_avg_tkl_num = 0 total_num = 0 for tracklet_id in tracklet_ids: img_paths =",
"int(fid), count+1) try: cv2.imwrite(str(save_img_path / img_name), img) except: print('ignore image -- ', save_img_path",
"jd and wd ''' if method == 'nearset': ex = data_pix2loc[:, 0] -",
"i in range(cam_num)], 'ignore':[], 'tracklets_info':[{} for i in range(cam_num)], 'tracklets':[]} new_id = 0",
"ti[4]['available_tracklets_num'], ti[4]['available_images_num'], ti[4]['average_images_num'])) print(\" cam6 | {:10d} | {:17d} | {:20d} | {:22d}",
"* np.pi) w_dist = dist[1] * 111000 return np.sqrt(np.power(j_dist, 2)+np.power(w_dist, 2)) def trans_gps_diff_to_dist_v3(gps_1,",
"traj_point[1]) jd = data_pix2loc[index, 2] wd = data_pix2loc[index, 3] elif method == 'nearest_k_mean':",
"create=True) count = len(glob.glob(str(save_img_path / '*.jpg'))) y2 = y1 + h x2 =",
"- start_time return int(sub_time) def trans_gps_diff_to_dist_v1(a, b): ''' :param a: ndarray:[jd, wd] :param",
"\".format(ti[4]['total_tracklets_num'], ti[4]['ignore_tracklets_num'], \\ ti[4]['available_tracklets_num'], ti[4]['available_images_num'], ti[4]['average_images_num'])) print(\" cam6 | {:10d} | {:17d} |",
"| {:17d} | {:20d} | {:22d} | {:20d} \".format(ti[2]['total_tracklets_num'], ti[2]['ignore_tracklets_num'], \\ ti[2]['available_tracklets_num'], ti[2]['available_images_num'],",
"+= len(img_paths) count_avg_tkl_num += 1 info['tracklets_info'][camid]['total_tracklets_num'] = tracklets_num info['tracklets_info'][camid]['ignore_tracklets_num'] = count_ignore_tkl info['tracklets_info'][camid]['available_tracklets_num'] =",
"ti[2]['ignore_tracklets_num'] + ti[3]['ignore_tracklets_num'] + \\ ti[4]['ignore_tracklets_num'] + ti[5]['ignore_tracklets_num'] + ti[0]['ignore_tracklets_num'] to_atn = ti[1]['available_tracklets_num']",
"info = pickle.load(f) print('Load data <--- ' + str(file_path), flush=True) return info @staticmethod",
"encoding='UTF-8', acq_print=True): check_path(file_path) with open(file_path, 'r', encoding=encoding) as f: info = json.load(f) if",
"data_cur = data_arr[data_arr[:,0] == index] for data in data_cur: fid, tid, x1, y1,",
"| {:20d} \".format(ti[2]['total_tracklets_num'], ti[2]['ignore_tracklets_num'], \\ ti[2]['available_tracklets_num'], ti[2]['available_images_num'], ti[2]['average_images_num'])) print(\" cam4 | {:10d} |",
"time: hour minute second :return: second from 102630 ''' now_time = ham_to_dem(time) start_time",
"/ 100 + int(i / 10000) * 60 * 60 dam_time_list.append(dem_time) return dam_time_list",
"dist[0] * 111000 * np.cos(31 / 180 * np.pi) w_dist = dist[1] *",
"ti[5]['available_images_num'] + ti[0]['available_images_num'] to_avein = ti[1]['average_images_num'] + ti[2]['average_images_num'] + ti[3]['average_images_num'] + \\ ti[4]['average_images_num']",
"ti[1]['average_images_num'])) print(\" cam3 | {:10d} | {:17d} | {:20d} | {:22d} | {:20d}",
"@staticmethod def json_dump(info, file_path, encoding='UTF-8'): check_path(Path(file_path).parent, create=True) with open(file_path, 'w', encoding=encoding) as f:",
"* locy >= 1200: return False if camid == 2: if locy <=",
"% 100) + 60 * (int(i % 10000) - int(i % 100)) /",
"111000 return np.sqrt(np.power(j_dist, 2)+np.power(w_dist, 2)) def trans_gps_diff_to_dist_v3(gps_1, gps_2): ''' :param gps_1: [jd, wd]",
"locy <= 600 or (locx >= 2000 and 0.5833 * locx + locy",
"dam_time_list else: dem_time = int(time % 100) + 60 * (int(time % 10000)",
"in img_paths: index = int(img_path.split('/')[-1].split('.')[0]) + 1 img0 = cv2.imread(img_path) data_cur = data_arr[data_arr[:,0]",
"int(time % 100) + 60 * (int(time % 10000) - int(time % 100))",
"if len(img_paths) <= 2: count_ignore_tkl += 1 info['old2new'][camid][int(tracklet_id)] = None info['ignore'].append(tracklets_per_cam_dir / tracklet_id)",
"| {:22d} | {:20d} \".format(ti[4]['total_tracklets_num'], ti[4]['ignore_tracklets_num'], \\ ti[4]['available_tracklets_num'], ti[4]['available_images_num'], ti[4]['average_images_num'])) print(\" cam6 |",
"2000: return False return True @staticmethod def refine_v2(camid, locx, locy): if camid ==",
"if y2 > 3007: y2 = 3007 if x2 > 4000: x2 =",
"1200: return False if camid == 2: if locy <= 200 or locx",
"axis=1, keepdims=True) _range = np.max(a,axis=1,keepdims=True) - a_min return (a - a_min) / _range",
"100)) / 100 + int(time / 10000) * 60 * 60 return int(dem_time)",
"ti[1]['ignore_tracklets_num'] + ti[2]['ignore_tracklets_num'] + ti[3]['ignore_tracklets_num'] + \\ ti[4]['ignore_tracklets_num'] + ti[5]['ignore_tracklets_num'] + ti[0]['ignore_tracklets_num'] to_atn",
"info) print('Store data ---> ' + str(file_path), flush=True) @staticmethod def np_load_txt(file_path, acq_print=True): check_path(file_path)",
"{:10d} | {:17d} | {:20d} | {:22d} | {:20d} \".format(ti[3]['total_tracklets_num'], ti[3]['ignore_tracklets_num'], \\ ti[3]['available_tracklets_num'],",
"else: dem_time = int(time % 100) + 60 * (int(time % 10000) -",
"4: if locy <= 600: return False if camid == 5: if locy",
"| {:20d} \".format(ti[1]['total_tracklets_num'], ti[1]['ignore_tracklets_num'], \\ ti[1]['available_tracklets_num'], ti[1]['available_images_num'], ti[1]['average_images_num'])) print(\" cam3 | {:10d} |",
"(a - a_min) / _range def check_path(folder_dir, create=False): ''' :param folder_dir: file path",
"path.' np.save(file_path, info) print('Store data ---> ' + str(file_path), flush=True) @staticmethod def np_load(file_path,",
"locx >= 3600: return False if camid == 3: if locy <= 250:",
"if locy <= 600: return False if camid == 5: if locy <=",
"False return True @staticmethod def refine_v2(camid, locx, locy): if camid == 1: if",
"print(\" ----------------------------------------------------------------------------------------------------------------\") print(\" total | {:10d} | {:17d} | {:20d} | {:22d} |",
"json import pickle import numpy as np import os import errno from geopy.distance",
"| {:17d} | {:20d} | {:22d} | {:20d} \".format(ti[0]['total_tracklets_num'], ti[0]['ignore_tracklets_num'], \\ ti[0]['available_tracklets_num'], ti[0]['available_images_num'],",
"ndarray:[jd, wd] :param b: ndarray:[jd, wd] :return: distance ''' dist = a -",
"locx, locy): if camid == 1: if locx + 30 * locy <=",
"data_arr[data_arr[:,0] == index] for data in data_cur: fid, tid, x1, y1, w, h",
"file\\' suffix is not txt, please check file path.' info = np.loadtxt(file_path) if",
"minute second :return: second ''' dam_time_list = [] if isinstance(time, list): for i",
"second :return: second from 102630 ''' now_time = ham_to_dem(time) start_time = ham_to_dem(102630) sub_time",
"250: return False if camid == 4: if locy <= 600 or (locx",
">= 2000: return False return True @staticmethod def refine_result(path, path_new, camid): refineData =",
"import Path import glob import cv2 def ham_to_dem(time): ''' :param time: hour minute",
"info['tracklets_info'][camid]['available_tracklets_num'] if save_info: DataPacker.dump(info, tracklet_dir / 'info.pkl') return info if verbose: ti =",
"3] elif method == 'nearest_k_mean': ex = data_pix2loc[:, 0] - traj_point[0] ey =",
"/ 10000) * 60 * 60 dam_time_list.append(dem_time) return dam_time_list else: dem_time = int(time",
"ex ** 2 + ey ** 2 index = np.argsort(dist)[0] jd = data_pix2loc[index,",
"return False if camid == 2: if locy <= 150 or locx >=",
"tracklets_per_cam_dir = tracklet_dir / '{:02d}'.format(camid + 1) tracklet_ids = os.listdir(tracklets_per_cam_dir) tracklet_ids.sort() tracklets_num =",
"for img_path in img_paths: index = int(img_path.split('/')[-1].split('.')[0]) + 1 img0 = cv2.imread(img_path) data_cur",
"np_save(info, file_path): check_path(Path(file_path).parent, create=True) assert file_path.split('.')[-1] == 'npy', 'This file\\' suffix is not",
"np_save_txt(info, file_path): check_path(Path(file_path).parent, create=True) assert file_path.split('.')[-1] == 'txt', 'This file\\' suffix is not",
"is not txt, please check file path.' np.savetxt(file_path, info) print('Store data ---> '",
"{:10d} | {:17d} | {:20d} | {:22d} | {:20d} \".format(ti[5]['total_tracklets_num'], ti[5]['ignore_tracklets_num'], \\ ti[5]['available_tracklets_num'],",
"\".format(ti[5]['total_tracklets_num'], ti[5]['ignore_tracklets_num'], \\ ti[5]['available_tracklets_num'], ti[5]['available_images_num'], ti[5]['average_images_num'])) print(\" ----------------------------------------------------------------------------------------------------------------\") print(\" total | {:10d} |",
"x1 = 0 if y2 > 3007: y2 = 3007 if x2 >",
"and wd ''' if method == 'nearset': ex = data_pix2loc[:, 0] - traj_point[0]",
"camid): img_paths = glob.glob(str(img_dir / '*.jpg')) img_paths.sort() result_path = result_dir / ('GPSReID0'+str(camid)+'_refine_v2.txt') data_list",
"- a_min) / _range def check_path(folder_dir, create=False): ''' :param folder_dir: file path :param",
"flush=True) @staticmethod def np_load(file_path, acq_print=True): check_path(file_path) assert file_path.split('.')[-1] == 'npy', 'This file\\' suffix",
"isinstance(time, list): for i in time: dem_time = int(i % 100) + 60",
"tkls num | # available tkls num | # available images num |",
"100) + 60 * (int(time % 10000) - int(time % 100)) / 100",
"ti[1]['available_images_num'] + ti[2]['available_images_num'] + ti[3]['available_images_num'] + \\ ti[4]['available_images_num'] + ti[5]['available_images_num'] + ti[0]['available_images_num'] to_avein",
"for data in data_cur: fid, tid, x1, y1, w, h = data save_img_path",
"+ 60 * (int(i % 10000) - int(i % 100)) / 100 +",
"locy <= 150 or 0.1167 * locx + locy <= 350 or locx",
"as f: total_data = f.readlines() for data in total_data: data = data.strip().split(',') data_list.append([int(data[0]),",
"'rb') as f: info = pickle.load(f) print('Load data <--- ' + str(file_path), flush=True)",
"/ 180 * np.pi) w_dist = dist[1] * 111000 return np.sqrt(np.power(j_dist, 2)+np.power(w_dist, 2))",
"sub_time = now_time - start_time return int(sub_time) def trans_gps_diff_to_dist_v1(a, b): ''' :param a:",
"[jd, wd] :return: distance between two gps ''' return geodesic((gps_1[1], gps_1[0]), (gps_2[1], gps_2[0]).m)",
"| # available images num | # average images num\") print(\" ----------------------------------------------------------------------------------------------------------------\") print(\"",
"\\ ti[5]['available_tracklets_num'], ti[5]['available_images_num'], ti[5]['average_images_num'])) print(\" ----------------------------------------------------------------------------------------------------------------\") print(\" total | {:10d} | {:17d} |",
"y2 = 3007 if x2 > 4000: x2 = 4000 img = img0[int(y1):int(y2),int(x1):int(x2)]",
"{:17d} | {:20d} | {:22d} | {:20d} \".format(ti[4]['total_tracklets_num'], ti[4]['ignore_tracklets_num'], \\ ti[4]['available_tracklets_num'], ti[4]['available_images_num'], ti[4]['average_images_num']))",
"int(sub_time) def trans_gps_diff_to_dist_v1(a, b): ''' :param a: ndarray:[jd, wd] :param b: ndarray:[jd, wd]",
"print(\" ----------------------------------------------------------------------------------------------------------------\") print(\" subset | # tkls num | # ignore tkls num",
"100)) / 100 + int(i / 10000) * 60 * 60 dam_time_list.append(dem_time) return",
"gps_2: [jd, wd] :return: distance between two gps ''' return geodesic((gps_1[1], gps_1[0]), (gps_2[1],",
"600 or (locx >= 2000 and 0.5833 * locx + locy <= 2340):",
"save_img_dir / '{:02d}'.format(camid) / '{:05d}'.format(int(tid)) check_path(save_img_path, create=True) count = len(glob.glob(str(save_img_path / '*.jpg'))) y2",
"{:20d} | {:22d} | {:20d} \".format(ti[3]['total_tracklets_num'], ti[3]['ignore_tracklets_num'], \\ ti[3]['available_tracklets_num'], ti[3]['available_images_num'], ti[3]['average_images_num'])) print(\" cam5",
"+ \\ ti[4]['available_images_num'] + ti[5]['available_images_num'] + ti[0]['available_images_num'] to_avein = ti[1]['average_images_num'] + ti[2]['average_images_num'] +",
"gps_2[0]).m) def pixel_to_loc(data_pix2loc, traj_point, method='nearset', k=4): ''' :param data_pix2loc: [pixel_x, pixel_y, jd, wd]",
"+ ti[0]['available_images_num'] to_avein = ti[1]['average_images_num'] + ti[2]['average_images_num'] + ti[3]['average_images_num'] + \\ ti[4]['average_images_num'] +",
"* locy <= 4000 or locx - 8.235 * locy >= 1200: return",
"wd] :param gps_2: [jd, wd] :return: distance between two gps ''' return geodesic((gps_1[1],",
"= 4000 img = img0[int(y1):int(y2),int(x1):int(x2)] img_name = 'T{:05d}_C{:02d}_F{:06d}_I{:06d}.jpg'.format(int(tid), camid, int(fid), count+1) try: cv2.imwrite(str(save_img_path",
"pickle.dump(info, f) print('Store data ---> ' + str(file_path), flush=True) @staticmethod def load(file_path): check_path(file_path)",
"file_path): check_path(Path(file_path).parent, create=True) with open(file_path, 'wb') as f: pickle.dump(info, f) print('Store data --->",
"y1 + h x2 = x1 + w if y1 <= 0: y1",
"print(\" cam1 | {:10d} | {:17d} | {:20d} | {:22d} | {:20d} \".format(ti[0]['total_tracklets_num'],",
"180 * np.pi) w_dist = dist[1] * 111000 return np.sqrt(np.power(j_dist, 2)+np.power(w_dist, 2)) def",
"''' this class supplys four different Data processing format ''' @staticmethod def dump(info,",
"if acq_print: print('Load data <--- ' + str(file_path), flush=True) return info @staticmethod def",
"minute second :return: second from 102630 ''' now_time = ham_to_dem(time) start_time = ham_to_dem(102630)",
"np.max(a,axis=1,keepdims=True) - a_min return (a - a_min) / _range def check_path(folder_dir, create=False): '''",
"np.savetxt(file_path, info) print('Store data ---> ' + str(file_path), flush=True) @staticmethod def np_load_txt(file_path, acq_print=True):",
"return False return True @staticmethod def refine_result(path, path_new, camid): refineData = [] with",
"if locy <= 150 or locx - 2.5 * locy >= 2000: return",
"open(file_path, 'rb') as f: info = pickle.load(f) print('Load data <--- ' + str(file_path),",
"+ ey ** 2 index = np.argsort(dist)[0] jd = data_pix2loc[index, 2] wd =",
"+ ti[3]['available_tracklets_num'] + \\ ti[4]['available_tracklets_num'] + ti[5]['available_tracklets_num'] + ti[0]['available_tracklets_num'] to_avain = ti[1]['available_images_num'] +",
"| # tkls num | # ignore tkls num | # available tkls",
"x2 > 4000: x2 = 4000 img = img0[int(y1):int(y2),int(x1):int(x2)] img_name = 'T{:05d}_C{:02d}_F{:06d}_I{:06d}.jpg'.format(int(tid), camid,",
"ti[2]['average_images_num'])) print(\" cam4 | {:10d} | {:17d} | {:20d} | {:22d} | {:20d}",
"create file or not :return: ''' folder_dir = Path(folder_dir) if not folder_dir.exists(): if",
"str(file_path), flush=True) @staticmethod def json_load(file_path, encoding='UTF-8', acq_print=True): check_path(file_path) with open(file_path, 'r', encoding=encoding) as",
"with open(file_path, 'wb') as f: pickle.dump(info, f) print('Store data ---> ' + str(file_path),",
"| {:10d} | {:17d} | {:20d} | {:22d} | {:20d} \".format(to_tn, to_itn, to_atn,",
"info) print('Store data ---> ' + str(file_path), flush=True) @staticmethod def np_load(file_path, acq_print=True): check_path(file_path)",
"def get_time(time): ''' :param time: hour minute second :return: second from 102630 '''",
"refineData = [] with open(path, 'r') as f: lines = f.readlines() for line",
"[] with open(path, 'r') as f: lines = f.readlines() for line in lines:",
"<= 150 or locx - 2.5 * locy >= 2000: return False return",
"data ---> ' + str(file_path), flush=True) @staticmethod def json_load(file_path, encoding='UTF-8', acq_print=True): check_path(file_path) with",
"return info @staticmethod def np_save_txt(info, file_path): check_path(Path(file_path).parent, create=True) assert file_path.split('.')[-1] == 'txt', 'This",
"tracklet_dir = Path(tracklet_dir) info = {'old2new':[{} for i in range(cam_num)], 'ignore':[], 'tracklets_info':[{} for",
"| {:20d} \".format(ti[3]['total_tracklets_num'], ti[3]['ignore_tracklets_num'], \\ ti[3]['available_tracklets_num'], ti[3]['available_images_num'], ti[3]['average_images_num'])) print(\" cam5 | {:10d} |",
"= [] with open(result_path, 'r') as f: total_data = f.readlines() for data in",
"data ---> ' + str(file_path), flush=True) @staticmethod def np_load(file_path, acq_print=True): check_path(file_path) assert file_path.split('.')[-1]",
"# ignore tkls num | # available tkls num | # available images",
"traj_point[0] ey = data_pix2loc[:, 1] - traj_point[1] dist = ex ** 2 +",
"locy >= 2000: return False return True @staticmethod def refine_v2(camid, locx, locy): if",
"create=True) with open(file_path, 'wb') as f: pickle.dump(info, f) print('Store data ---> ' +",
"images num\") print(\" ----------------------------------------------------------------------------------------------------------------\") print(\" cam1 | {:10d} | {:17d} | {:20d} |",
"10000) - int(i % 100)) / 100 + int(i / 10000) * 60",
"return np.sqrt(np.power(j_dist, 2)+np.power(w_dist, 2)) def trans_gps_diff_to_dist_v3(gps_1, gps_2): ''' :param gps_1: [jd, wd] :param",
"+ ti[3]['total_tracklets_num'] + \\ ti[4]['total_tracklets_num'] + ti[5]['total_tracklets_num'] + ti[0]['total_tracklets_num'] to_itn = ti[1]['ignore_tracklets_num'] +",
"not txt, please check file path.' info = np.loadtxt(file_path) if acq_print: print('Load data",
"<= 200 or locx >= 3600: return False if camid == 3: if",
"elif method == 'nearest_k_mean': ex = data_pix2loc[:, 0] - traj_point[0] ey = data_pix2loc[:,",
"if y1 <= 0: y1 = 0 if x1 <= 0: x1 =",
"info @staticmethod def np_save(info, file_path): check_path(Path(file_path).parent, create=True) assert file_path.split('.')[-1] == 'npy', 'This file\\'",
"locx - 8.235 * locy >= 1200: return False if camid == 2:",
"# available tkls num | # available images num | # average images",
"= ti[1]['available_images_num'] + ti[2]['available_images_num'] + ti[3]['available_images_num'] + \\ ti[4]['available_images_num'] + ti[5]['available_images_num'] + ti[0]['available_images_num']",
"check file path.' info = np.loadtxt(file_path) if acq_print: print('Load data <--- ' +",
"2: if locy <= 150 or locx >= 3750: return False if camid",
"3007 if x2 > 4000: x2 = 4000 img = img0[int(y1):int(y2),int(x1):int(x2)] img_name =",
"= int(time % 100) + 60 * (int(time % 10000) - int(time %",
"{:22d} | {:20d} \".format(ti[0]['total_tracklets_num'], ti[0]['ignore_tracklets_num'], \\ ti[0]['available_tracklets_num'], ti[0]['available_images_num'], ti[0]['average_images_num'])) print(\" cam2 | {:10d}",
"ti[1]['available_tracklets_num'], ti[1]['available_images_num'], ti[1]['average_images_num'])) print(\" cam3 | {:10d} | {:17d} | {:20d} | {:22d}",
"camid == 5: if locy <= 150 or 0.1167 * locx + locy",
"new_id new_id += 1 info['tracklets'].append((img_paths, new_id, camid)) total_num += len(img_paths) count_avg_tkl_num += 1",
"* (int(i % 10000) - int(i % 100)) / 100 + int(i /",
"if camid == 2: if locy <= 150 or locx >= 3750: return",
"print('Store data ---> ' + str(file_path), flush=True) @staticmethod def np_load_txt(file_path, acq_print=True): check_path(file_path) assert",
"= Path(tracklet_dir) info = {'old2new':[{} for i in range(cam_num)], 'ignore':[], 'tracklets_info':[{} for i",
"ti[2]['total_tracklets_num'] + ti[3]['total_tracklets_num'] + \\ ti[4]['total_tracklets_num'] + ti[5]['total_tracklets_num'] + ti[0]['total_tracklets_num'] to_itn = ti[1]['ignore_tracklets_num']",
"encoding='UTF-8'): check_path(Path(file_path).parent, create=True) with open(file_path, 'w', encoding=encoding) as f: json.dump(info, f) print('Store data",
"f: total_data = f.readlines() for data in total_data: data = data.strip().split(',') data_list.append([int(data[0]), int(data[1]),",
"wd ''' if method == 'nearset': ex = data_pix2loc[:, 0] - traj_point[0] ey",
"total_data: data = data.strip().split(',') data_list.append([int(data[0]), int(data[1]), float(data[2]), float(data[3]), float(data[4]), float(data[5])]) data_arr = np.array(data_list)",
"start_time = ham_to_dem(102630) sub_time = now_time - start_time return int(sub_time) def trans_gps_diff_to_dist_v1(a, b):",
"| {:10d} | {:17d} | {:20d} | {:22d} | {:20d} \".format(ti[1]['total_tracklets_num'], ti[1]['ignore_tracklets_num'], \\",
"distance between two gps ''' return geodesic((gps_1[1], gps_1[0]), (gps_2[1], gps_2[0]).m) def pixel_to_loc(data_pix2loc, traj_point,",
"dem_time = int(time % 100) + 60 * (int(time % 10000) - int(time",
"False if camid == 4: if locy <= 600 or (locx >= 2000",
"+ ti[0]['available_tracklets_num'] to_avain = ti[1]['available_images_num'] + ti[2]['available_images_num'] + ti[3]['available_images_num'] + \\ ti[4]['available_images_num'] +",
"refine_v2(camid, locx, locy): if camid == 1: if locx + 20 * locy",
"camid == 3: if locy <= 250: return False if camid == 4:",
"{'old2new':[{} for i in range(cam_num)], 'ignore':[], 'tracklets_info':[{} for i in range(cam_num)], 'tracklets':[]} new_id",
"file\\' suffix is not npy, please check file path.' info = np.load(file_path) if",
"= int(i % 100) + 60 * (int(i % 10000) - int(i %",
"tracklet_id) else: count_ava_tkl += 1 info['old2new'][camid][int(tracklet_id)] = new_id new_id += 1 info['tracklets'].append((img_paths, new_id,",
"''' :param a: feature distance N X N :return: normalize feature ''' a",
"pickle import numpy as np import os import errno from geopy.distance import geodesic",
"processing format ''' @staticmethod def dump(info, file_path): check_path(Path(file_path).parent, create=True) with open(file_path, 'wb') as",
"2000: return False if camid == 6: if locy <= 150 or locx",
"w if y1 <= 0: y1 = 0 if x1 <= 0: x1",
"def trans_gps_diff_to_dist_v2(dist): ''' :param dist: [jd_sub, wd_sub] :return: distance ''' j_dist = dist[0]",
"errno from geopy.distance import geodesic from pathlib import Path import glob import cv2",
"100) + 60 * (int(i % 10000) - int(i % 100)) / 100",
"print('Load data <--- ' + str(file_path), flush=True) return info @staticmethod def np_save_txt(info, file_path):",
"@staticmethod def np_load_txt(file_path, acq_print=True): check_path(file_path) assert file_path.split('.')[-1] == 'txt', 'This file\\' suffix is",
"selected point :return: traj_list's jd and wd ''' if method == 'nearset': ex",
"= img0[int(y1):int(y2),int(x1):int(x2)] img_name = 'T{:05d}_C{:02d}_F{:06d}_I{:06d}.jpg'.format(int(tid), camid, int(fid), count+1) try: cv2.imwrite(str(save_img_path / img_name), img)",
"'npy', 'This file\\' suffix is not npy, please check file path.' np.save(file_path, info)",
"a: feature distance N X N :return: normalize feature ''' a = a.copy()",
"traj_point, method='nearset', k=4): ''' :param data_pix2loc: [pixel_x, pixel_y, jd, wd] size[n, 4] :param",
"= 0 for tracklet_id in tracklet_ids: img_paths = glob.glob(str(tracklets_per_cam_dir / tracklet_id / '*.jpg'))",
"f: pickle.dump(info, f) print('Store data ---> ' + str(file_path), flush=True) @staticmethod def load(file_path):",
"in time: dem_time = int(i % 100) + 60 * (int(i % 10000)",
"\\ ti[0]['available_tracklets_num'], ti[0]['available_images_num'], ti[0]['average_images_num'])) print(\" cam2 | {:10d} | {:17d} | {:20d} |",
"y1, w, h = data save_img_path = save_img_dir / '{:02d}'.format(camid) / '{:05d}'.format(int(tid)) check_path(save_img_path,",
"= dist[1] * 111000 return np.sqrt(np.power(j_dist, 2)+np.power(w_dist, 2)) def trans_gps_diff_to_dist_v2(dist): ''' :param dist:",
"8.235 * locy >= 1200: return False if camid == 2: if locy",
"float(data[2]), float(data[3]), float(data[4]), float(data[5])]) data_arr = np.array(data_list) for img_path in img_paths: index =",
"count_ava_tkl += 1 info['old2new'][camid][int(tracklet_id)] = new_id new_id += 1 info['tracklets'].append((img_paths, new_id, camid)) total_num",
"y2 > 3007: y2 = 3007 if x2 > 4000: x2 = 4000",
"f.readlines() for data in total_data: data = data.strip().split(',') data_list.append([int(data[0]), int(data[1]), float(data[2]), float(data[3]), float(data[4]),",
"else: assert 'Do not have the meathod' return jd, wd def norm_data(a): '''",
"suffix is not txt, please check file path.' np.savetxt(file_path, info) print('Store data --->",
"is not txt, please check file path.' info = np.loadtxt(file_path) if acq_print: print('Load",
"if locy <= 200: return False if camid == 4: if locy <=",
"= {'old2new':[{} for i in range(cam_num)], 'ignore':[], 'tracklets_info':[{} for i in range(cam_num)], 'tracklets':[]}",
"ti[4]['total_tracklets_num'] + ti[5]['total_tracklets_num'] + ti[0]['total_tracklets_num'] to_itn = ti[1]['ignore_tracklets_num'] + ti[2]['ignore_tracklets_num'] + ti[3]['ignore_tracklets_num'] +",
"to_avein = ti[1]['average_images_num'] + ti[2]['average_images_num'] + ti[3]['average_images_num'] + \\ ti[4]['average_images_num'] + ti[5]['average_images_num'] +",
"data_pix2loc[index, 3] elif method == 'nearest_k_mean': ex = data_pix2loc[:, 0] - traj_point[0] ey",
"cv2.imwrite(str(save_img_path / img_name), img) except: print('ignore image -- ', save_img_path / img_name) @staticmethod",
"data_cur: fid, tid, x1, y1, w, h = data save_img_path = save_img_dir /",
"<= 250: return False if camid == 4: if locy <= 600 or",
"np.cos(31 / 180 * np.pi) w_dist = dist[1] * 111000 return np.sqrt(np.power(j_dist, 2)+np.power(w_dist,",
"Path(folder_dir) if not folder_dir.exists(): if create: try: os.makedirs(folder_dir) except OSError as e: if",
"class supplys four different Data processing format ''' @staticmethod def dump(info, file_path): check_path(Path(file_path).parent,",
"| {:10d} | {:17d} | {:20d} | {:22d} | {:20d} \".format(ti[2]['total_tracklets_num'], ti[2]['ignore_tracklets_num'], \\",
"check_path(Path(file_path).parent, create=True) assert file_path.split('.')[-1] == 'txt', 'This file\\' suffix is not txt, please",
"str(file_path), flush=True) return info @staticmethod def np_save_txt(info, file_path): check_path(Path(file_path).parent, create=True) assert file_path.split('.')[-1] ==",
"0 if x1 <= 0: x1 = 0 if y2 > 3007: y2",
"<= 200: return False if camid == 4: if locy <= 600: return",
"= ti[1]['average_images_num'] + ti[2]['average_images_num'] + ti[3]['average_images_num'] + \\ ti[4]['average_images_num'] + ti[5]['average_images_num'] + ti[0]['average_images_num']",
"| {:20d} \".format(ti[4]['total_tracklets_num'], ti[4]['ignore_tracklets_num'], \\ ti[4]['available_tracklets_num'], ti[4]['available_images_num'], ti[4]['average_images_num'])) print(\" cam6 | {:10d} |",
"[] if isinstance(time, list): for i in time: dem_time = int(i % 100)",
"100 + int(time / 10000) * 60 * 60 return int(dem_time) def get_time(time):",
"np.sqrt(np.power(j_dist, 2)+np.power(w_dist, 2)) def trans_gps_diff_to_dist_v3(gps_1, gps_2): ''' :param gps_1: [jd, wd] :param gps_2:",
"{:20d} \".format(ti[0]['total_tracklets_num'], ti[0]['ignore_tracklets_num'], \\ ti[0]['available_tracklets_num'], ti[0]['available_images_num'], ti[0]['average_images_num'])) print(\" cam2 | {:10d} | {:17d}",
"ti[3]['total_tracklets_num'] + \\ ti[4]['total_tracklets_num'] + ti[5]['total_tracklets_num'] + ti[0]['total_tracklets_num'] to_itn = ti[1]['ignore_tracklets_num'] + ti[2]['ignore_tracklets_num']",
"f) print('Store data ---> ' + str(file_path), flush=True) @staticmethod def json_load(file_path, encoding='UTF-8', acq_print=True):",
"+ \\ ti[4]['average_images_num'] + ti[5]['average_images_num'] + ti[0]['average_images_num'] print(\"=> GPSMOT loaded\") print(\"Dataset statistics:\") print(\"",
"img_paths = glob.glob(str(img_dir / '*.jpg')) img_paths.sort() result_path = result_dir / ('GPSReID0'+str(camid)+'_refine_v2.txt') data_list =",
"if camid == 4: if locy <= 600 or (locx >= 2000 and",
"ti[4]['available_tracklets_num'] + ti[5]['available_tracklets_num'] + ti[0]['available_tracklets_num'] to_avain = ti[1]['available_images_num'] + ti[2]['available_images_num'] + ti[3]['available_images_num'] +",
"file path.' info = np.load(file_path) if acq_print: print('Load data <--- ' + str(file_path),",
"\\ ti[2]['available_tracklets_num'], ti[2]['available_images_num'], ti[2]['average_images_num'])) print(\" cam4 | {:10d} | {:17d} | {:20d} |",
"except: print('ignore image -- ', save_img_path / img_name) @staticmethod def count_dataset_info(tracklet_dir, cam_num, verbose=False,",
"def np_save_txt(info, file_path): check_path(Path(file_path).parent, create=True) assert file_path.split('.')[-1] == 'txt', 'This file\\' suffix is",
"+ ti[2]['available_images_num'] + ti[3]['available_images_num'] + \\ ti[4]['available_images_num'] + ti[5]['available_images_num'] + ti[0]['available_images_num'] to_avein =",
"to_atn = ti[1]['available_tracklets_num'] + ti[2]['available_tracklets_num'] + ti[3]['available_tracklets_num'] + \\ ti[4]['available_tracklets_num'] + ti[5]['available_tracklets_num'] +",
"ti[2]['available_images_num'], ti[2]['average_images_num'])) print(\" cam4 | {:10d} | {:17d} | {:20d} | {:22d} |",
"{:17d} | {:20d} | {:22d} | {:20d} \".format(ti[5]['total_tracklets_num'], ti[5]['ignore_tracklets_num'], \\ ti[5]['available_tracklets_num'], ti[5]['available_images_num'], ti[5]['average_images_num']))",
"file_path): check_path(Path(file_path).parent, create=True) assert file_path.split('.')[-1] == 'txt', 'This file\\' suffix is not txt,",
"150 or locx >= 3750: return False if camid == 3: if locy",
"result_dir, save_img_dir, camid): img_paths = glob.glob(str(img_dir / '*.jpg')) img_paths.sort() result_path = result_dir /",
"102630 ''' now_time = ham_to_dem(time) start_time = ham_to_dem(102630) sub_time = now_time - start_time",
"norm_data(a): ''' :param a: feature distance N X N :return: normalize feature '''",
"+ \\ info['tracklets_info'][camid]['available_tracklets_num'] if save_info: DataPacker.dump(info, tracklet_dir / 'info.pkl') return info if verbose:",
"count+1) try: cv2.imwrite(str(save_img_path / img_name), img) except: print('ignore image -- ', save_img_path /",
"= 0 count_ava_tkl = 0 count_avg_tkl_num = 0 total_num = 0 for tracklet_id",
"return info if verbose: ti = info['tracklets_info'] to_tn = ti[1]['total_tracklets_num'] + ti[2]['total_tracklets_num'] +",
"pickle.load(f) print('Load data <--- ' + str(file_path), flush=True) return info @staticmethod def json_dump(info,",
"Path import glob import cv2 def ham_to_dem(time): ''' :param time: hour minute second",
"'info.pkl') return info if verbose: ti = info['tracklets_info'] to_tn = ti[1]['total_tracklets_num'] + ti[2]['total_tracklets_num']",
"locx - 2.5 * locy >= 2000: return False return True @staticmethod def",
"len(img_paths) count_avg_tkl_num += 1 info['tracklets_info'][camid]['total_tracklets_num'] = tracklets_num info['tracklets_info'][camid]['ignore_tracklets_num'] = count_ignore_tkl info['tracklets_info'][camid]['available_tracklets_num'] = count_ava_tkl",
"'linear': index = np.where(int(data_pix2loc[:, 0]) == traj_point[0] and int(data_pix2loc[:, 1]) == traj_point[1]) jd",
"= line.strip().split(',') locx = float(data[2]) + float(data[4]) / 2 locy = float(data[3]) +",
"_range def check_path(folder_dir, create=False): ''' :param folder_dir: file path :param create: create file",
"np.save(file_path, info) print('Store data ---> ' + str(file_path), flush=True) @staticmethod def np_load(file_path, acq_print=True):",
"data in total_data: data = data.strip().split(',') data_list.append([int(data[0]), int(data[1]), float(data[2]), float(data[3]), float(data[4]), float(data[5])]) data_arr",
"if save_info: DataPacker.dump(info, tracklet_dir / 'info.pkl') return info if verbose: ti = info['tracklets_info']",
"check_path(file_path) with open(file_path, 'rb') as f: info = pickle.load(f) print('Load data <--- '",
"== 'nearset': ex = data_pix2loc[:, 0] - traj_point[0] ey = data_pix2loc[:, 1] -",
"folder_dir class DataPacker(object): ''' this class supplys four different Data processing format '''",
"- traj_point[1] dist = ex ** 2 + ey ** 2 index =",
"lines = f.readlines() for line in lines: data = line.strip().split(',') locx = float(data[2])",
"== 'nearest_k_mean': ex = data_pix2loc[:, 0] - traj_point[0] ey = data_pix2loc[:, 1] -",
"ham_to_dem(time): ''' :param time: hour minute second :return: second ''' dam_time_list = []",
"open(result_path, 'r') as f: total_data = f.readlines() for data in total_data: data =",
"3750: return False if camid == 3: if locy <= 200: return False",
"= count_ignore_tkl info['tracklets_info'][camid]['available_tracklets_num'] = count_ava_tkl info['tracklets_info'][camid]['available_images_num'] = total_num info['tracklets_info'][camid]['average_images_num'] = total_num // count_ava_tkl",
"2 + ey ** 2 index = np.argsort(dist)[0] jd = data_pix2loc[index, 2] wd",
"info if verbose: ti = info['tracklets_info'] to_tn = ti[1]['total_tracklets_num'] + ti[2]['total_tracklets_num'] + ti[3]['total_tracklets_num']",
"{:22d} | {:20d} \".format(ti[1]['total_tracklets_num'], ti[1]['ignore_tracklets_num'], \\ ti[1]['available_tracklets_num'], ti[1]['available_images_num'], ti[1]['average_images_num'])) print(\" cam3 | {:10d}",
"| {:17d} | {:20d} | {:22d} | {:20d} \".format(ti[4]['total_tracklets_num'], ti[4]['ignore_tracklets_num'], \\ ti[4]['available_tracklets_num'], ti[4]['available_images_num'],",
"----------------------------------------------------------------------------------------------------------------\") print(\" total | {:10d} | {:17d} | {:20d} | {:22d} | {:20d}",
"images num | # average images num\") print(\" ----------------------------------------------------------------------------------------------------------------\") print(\" cam1 | {:10d}",
"| {:20d} | {:22d} | {:20d} \".format(ti[0]['total_tracklets_num'], ti[0]['ignore_tracklets_num'], \\ ti[0]['available_tracklets_num'], ti[0]['available_images_num'], ti[0]['average_images_num'])) print(\"",
"| {:20d} | {:22d} | {:20d} \".format(ti[5]['total_tracklets_num'], ti[5]['ignore_tracklets_num'], \\ ti[5]['available_tracklets_num'], ti[5]['available_images_num'], ti[5]['average_images_num'])) print(\"",
"second from 102630 ''' now_time = ham_to_dem(time) start_time = ham_to_dem(102630) sub_time = now_time",
"two gps ''' return geodesic((gps_1[1], gps_1[0]), (gps_2[1], gps_2[0]).m) def pixel_to_loc(data_pix2loc, traj_point, method='nearset', k=4):",
"<= 600: return False if camid == 5: if locy <= 150 or",
"// count_ava_tkl assert info['tracklets_info'][camid]['total_tracklets_num'] == \\ info['tracklets_info'][camid]['ignore_tracklets_num'] + \\ info['tracklets_info'][camid]['available_tracklets_num'] if save_info: DataPacker.dump(info,",
"not txt, please check file path.' np.savetxt(file_path, info) print('Store data ---> ' +",
"{:20d} | {:22d} | {:20d} \".format(ti[2]['total_tracklets_num'], ti[2]['ignore_tracklets_num'], \\ ti[2]['available_tracklets_num'], ti[2]['available_images_num'], ti[2]['average_images_num'])) print(\" cam4",
"open(path_new, 'w') as f: f.writelines(refineData) @staticmethod def crop_image(img_dir, result_dir, save_img_dir, camid): img_paths =",
"return info @staticmethod def json_dump(info, file_path, encoding='UTF-8'): check_path(Path(file_path).parent, create=True) with open(file_path, 'w', encoding=encoding)",
"flush=True) @staticmethod def np_load_txt(file_path, acq_print=True): check_path(file_path) assert file_path.split('.')[-1] == 'txt', 'This file\\' suffix",
"print(\" subset | # tkls num | # ignore tkls num | #",
"json_load(file_path, encoding='UTF-8', acq_print=True): check_path(file_path) with open(file_path, 'r', encoding=encoding) as f: info = json.load(f)",
"def refine_result(path, path_new, camid): refineData = [] with open(path, 'r') as f: lines",
"= glob.glob(str(img_dir / '*.jpg')) img_paths.sort() result_path = result_dir / ('GPSReID0'+str(camid)+'_refine_v2.txt') data_list = []",
"load(file_path): check_path(file_path) with open(file_path, 'rb') as f: info = pickle.load(f) print('Load data <---",
"range(cam_num)], 'tracklets':[]} new_id = 0 for camid in range(cam_num): tracklets_per_cam_dir = tracklet_dir /",
"'This file\\' suffix is not txt, please check file path.' info = np.loadtxt(file_path)",
"time: dem_time = int(i % 100) + 60 * (int(i % 10000) -",
"int(data[1]), float(data[2]), float(data[3]), float(data[4]), float(data[5])]) data_arr = np.array(data_list) for img_path in img_paths: index",
":return: traj_list's jd and wd ''' if method == 'nearset': ex = data_pix2loc[:,",
"flush=True) return info @staticmethod def np_save_txt(info, file_path): check_path(Path(file_path).parent, create=True) assert file_path.split('.')[-1] == 'txt',",
"150 or 0.1167 * locx + locy <= 350 or locx - 5.7143",
"new_id += 1 info['tracklets'].append((img_paths, new_id, camid)) total_num += len(img_paths) count_avg_tkl_num += 1 info['tracklets_info'][camid]['total_tracklets_num']",
"0 if y2 > 3007: y2 = 3007 if x2 > 4000: x2",
"+ float(data[5]) if DataProcesser.refine_v2(camid, locx, locy): refineData.append(line) with open(path_new, 'w') as f: f.writelines(refineData)",
":param gps_1: [jd, wd] :param gps_2: [jd, wd] :return: distance between two gps",
"or locx >= 3750: return False if camid == 3: if locy <=",
"flush=True) @staticmethod def load(file_path): check_path(file_path) with open(file_path, 'rb') as f: info = pickle.load(f)",
"f: json.dump(info, f) print('Store data ---> ' + str(file_path), flush=True) @staticmethod def json_load(file_path,",
"info @staticmethod def json_dump(info, file_path, encoding='UTF-8'): check_path(Path(file_path).parent, create=True) with open(file_path, 'w', encoding=encoding) as",
"6: if locy <= 150 or locx - 2.5 * locy >= 2000:",
"if x2 > 4000: x2 = 4000 img = img0[int(y1):int(y2),int(x1):int(x2)] img_name = 'T{:05d}_C{:02d}_F{:06d}_I{:06d}.jpg'.format(int(tid),",
"<= 4000 or locx - 8.235 * locy >= 1200: return False if",
"111000 * np.cos(31 / 180 * np.pi) w_dist = dist[1] * 111000 return",
"count_avg_tkl_num += 1 info['tracklets_info'][camid]['total_tracklets_num'] = tracklets_num info['tracklets_info'][camid]['ignore_tracklets_num'] = count_ignore_tkl info['tracklets_info'][camid]['available_tracklets_num'] = count_ava_tkl info['tracklets_info'][camid]['available_images_num']",
"1 info['tracklets'].append((img_paths, new_id, camid)) total_num += len(img_paths) count_avg_tkl_num += 1 info['tracklets_info'][camid]['total_tracklets_num'] = tracklets_num",
"count_avg_tkl_num = 0 total_num = 0 for tracklet_id in tracklet_ids: img_paths = glob.glob(str(tracklets_per_cam_dir",
"jd, wd] size[n, 4] :param traj_list: [pixel_x, pixel_y] size[2] :param method: 'nearest' 'linear'",
"'nearest' 'linear' 'nearest_k_mean' :param k: num of selected point :return: traj_list's jd and",
"int(i % 100) + 60 * (int(i % 10000) - int(i % 100))",
"np.argsort(dist)[:k] jd, wd = np.mean(data_pix2loc[indexs, 2:], axis=0) else: assert 'Do not have the",
"+ \\ ti[4]['available_tracklets_num'] + ti[5]['available_tracklets_num'] + ti[0]['available_tracklets_num'] to_avain = ti[1]['available_images_num'] + ti[2]['available_images_num'] +",
"jd, wd def norm_data(a): ''' :param a: feature distance N X N :return:",
"= np.mean(data_pix2loc[indexs, 2:], axis=0) else: assert 'Do not have the meathod' return jd,",
"locx + locy <= 2340): return False if camid == 5: if locy",
"distance N X N :return: normalize feature ''' a = a.copy() a_min =",
"img_name) @staticmethod def count_dataset_info(tracklet_dir, cam_num, verbose=False, save_info=False): tracklet_dir = Path(tracklet_dir) info = {'old2new':[{}",
"float(data[2]) + float(data[4]) / 2 locy = float(data[3]) + float(data[5]) if DataProcesser.refine_v2(camid, locx,",
"four different Data processing format ''' @staticmethod def dump(info, file_path): check_path(Path(file_path).parent, create=True) with",
"acq_print: print('Load data <--- ' + str(file_path), flush=True) return info @staticmethod def np_save_txt(info,",
"print(\" cam6 | {:10d} | {:17d} | {:20d} | {:22d} | {:20d} \".format(ti[5]['total_tracklets_num'],",
"- int(i % 100)) / 100 + int(i / 10000) * 60 *",
"{:20d} \".format(ti[2]['total_tracklets_num'], ti[2]['ignore_tracklets_num'], \\ ti[2]['available_tracklets_num'], ti[2]['available_images_num'], ti[2]['average_images_num'])) print(\" cam4 | {:10d} | {:17d}",
"if acq_print: print('Load data <--- ' + str(file_path), flush=True) return info class DataProcesser(object):",
"info['old2new'][camid][int(tracklet_id)] = None info['ignore'].append(tracklets_per_cam_dir / tracklet_id) else: count_ava_tkl += 1 info['old2new'][camid][int(tracklet_id)] = new_id",
"'*.jpg')) img_paths.sort() if len(img_paths) <= 2: count_ignore_tkl += 1 info['old2new'][camid][int(tracklet_id)] = None info['ignore'].append(tracklets_per_cam_dir",
"refineData.append(line) with open(path_new, 'w') as f: f.writelines(refineData) @staticmethod def crop_image(img_dir, result_dir, save_img_dir, camid):",
"info['ignore'].append(tracklets_per_cam_dir / tracklet_id) else: count_ava_tkl += 1 info['old2new'][camid][int(tracklet_id)] = new_id new_id += 1",
"count_ava_tkl = 0 count_avg_tkl_num = 0 total_num = 0 for tracklet_id in tracklet_ids:",
"* locy <= 3000 or locx - 8.235 * locy >= 1200: return",
"ey = data_pix2loc[:, 1] - traj_point[1] dist = ex ** 2 + ey",
"return True @staticmethod def refine_v2(camid, locx, locy): if camid == 1: if locx",
"@staticmethod def json_load(file_path, encoding='UTF-8', acq_print=True): check_path(file_path) with open(file_path, 'r', encoding=encoding) as f: info",
"' + str(file_path), flush=True) @staticmethod def np_load(file_path, acq_print=True): check_path(file_path) assert file_path.split('.')[-1] == 'npy',",
"np.min(a, axis=1, keepdims=True) _range = np.max(a,axis=1,keepdims=True) - a_min return (a - a_min) /",
"locy <= 350 or locx - 5.7143 * locy >= 2000: return False",
":param folder_dir: file path :param create: create file or not :return: ''' folder_dir",
"== 'npy', 'This file\\' suffix is not npy, please check file path.' np.save(file_path,",
"cam6 | {:10d} | {:17d} | {:20d} | {:22d} | {:20d} \".format(ti[5]['total_tracklets_num'], ti[5]['ignore_tracklets_num'],",
"+ str(file_path), flush=True) @staticmethod def np_load(file_path, acq_print=True): check_path(file_path) assert file_path.split('.')[-1] == 'npy', 'This",
"statistics:\") print(\" ----------------------------------------------------------------------------------------------------------------\") print(\" subset | # tkls num | # ignore tkls",
"locy): refineData.append(line) with open(path_new, 'w') as f: f.writelines(refineData) @staticmethod def crop_image(img_dir, result_dir, save_img_dir,",
"locy <= 2340): return False if camid == 5: if locy <= 150",
"np_load(file_path, acq_print=True): check_path(file_path) assert file_path.split('.')[-1] == 'npy', 'This file\\' suffix is not npy,",
"len(tracklet_ids) count_ignore_tkl = 0 count_ava_tkl = 0 count_avg_tkl_num = 0 total_num = 0",
"'npy', 'This file\\' suffix is not npy, please check file path.' info =",
"data_list = [] with open(result_path, 'r') as f: total_data = f.readlines() for data",
"locy <= 3000 or locx - 8.235 * locy >= 1200: return False",
"else: raise IOError return folder_dir class DataPacker(object): ''' this class supplys four different",
"False if camid == 3: if locy <= 250: return False if camid",
"create: try: os.makedirs(folder_dir) except OSError as e: if e.errno != errno.EEXIST: raise else:",
"refine_v1(camid, locx, locy): if camid == 1: if locx + 30 * locy",
"+ ey ** 2 indexs = np.argsort(dist)[:k] jd, wd = np.mean(data_pix2loc[indexs, 2:], axis=0)",
"= json.load(f) if acq_print: print('Load data <--- ' + str(file_path), flush=True) return info",
"for i in range(cam_num)], 'ignore':[], 'tracklets_info':[{} for i in range(cam_num)], 'tracklets':[]} new_id =",
"w_dist = dist[1] * 111000 return np.sqrt(np.power(j_dist, 2)+np.power(w_dist, 2)) def trans_gps_diff_to_dist_v3(gps_1, gps_2): '''",
"folder_dir.exists(): if create: try: os.makedirs(folder_dir) except OSError as e: if e.errno != errno.EEXIST:",
"str(file_path), flush=True) return info @staticmethod def np_save(info, file_path): check_path(Path(file_path).parent, create=True) assert file_path.split('.')[-1] ==",
"loaded\") print(\"Dataset statistics:\") print(\" ----------------------------------------------------------------------------------------------------------------\") print(\" subset | # tkls num | #",
"img = img0[int(y1):int(y2),int(x1):int(x2)] img_name = 'T{:05d}_C{:02d}_F{:06d}_I{:06d}.jpg'.format(int(tid), camid, int(fid), count+1) try: cv2.imwrite(str(save_img_path / img_name),",
"[jd_sub, wd_sub] :return: distance ''' j_dist = dist[0] * 111000 * np.cos(31 /",
"np.loadtxt(file_path) if acq_print: print('Load data <--- ' + str(file_path), flush=True) return info @staticmethod",
"OSError as e: if e.errno != errno.EEXIST: raise else: raise IOError return folder_dir",
"data in data_cur: fid, tid, x1, y1, w, h = data save_img_path =",
"@staticmethod def refine_v1(camid, locx, locy): if camid == 1: if locx + 30",
"normalize feature ''' a = a.copy() a_min = np.min(a, axis=1, keepdims=True) _range =",
"== 'txt', 'This file\\' suffix is not txt, please check file path.' np.savetxt(file_path,",
"{:20d} | {:22d} | {:20d} \".format(ti[1]['total_tracklets_num'], ti[1]['ignore_tracklets_num'], \\ ti[1]['available_tracklets_num'], ti[1]['available_images_num'], ti[1]['average_images_num'])) print(\" cam3",
"please check file path.' np.savetxt(file_path, info) print('Store data ---> ' + str(file_path), flush=True)",
"60 * 60 dam_time_list.append(dem_time) return dam_time_list else: dem_time = int(time % 100) +",
"hour minute second :return: second from 102630 ''' now_time = ham_to_dem(time) start_time =",
"float(data[3]), float(data[4]), float(data[5])]) data_arr = np.array(data_list) for img_path in img_paths: index = int(img_path.split('/')[-1].split('.')[0])",
"+ str(file_path), flush=True) return info @staticmethod def np_save(info, file_path): check_path(Path(file_path).parent, create=True) assert file_path.split('.')[-1]",
"y2 = y1 + h x2 = x1 + w if y1 <=",
"ti[5]['average_images_num'])) print(\" ----------------------------------------------------------------------------------------------------------------\") print(\" total | {:10d} | {:17d} | {:20d} | {:22d}",
"111000 return np.sqrt(np.power(j_dist, 2)+np.power(w_dist, 2)) def trans_gps_diff_to_dist_v2(dist): ''' :param dist: [jd_sub, wd_sub] :return:",
"+ 1) tracklet_ids = os.listdir(tracklets_per_cam_dir) tracklet_ids.sort() tracklets_num = len(tracklet_ids) count_ignore_tkl = 0 count_ava_tkl",
"please check file path.' info = np.loadtxt(file_path) if acq_print: print('Load data <--- '",
"== 1: if locx + 20 * locy <= 4000 or locx -",
"2)+np.power(w_dist, 2)) def trans_gps_diff_to_dist_v2(dist): ''' :param dist: [jd_sub, wd_sub] :return: distance ''' j_dist",
"suffix is not npy, please check file path.' info = np.load(file_path) if acq_print:",
"ti[3]['ignore_tracklets_num'] + \\ ti[4]['ignore_tracklets_num'] + ti[5]['ignore_tracklets_num'] + ti[0]['ignore_tracklets_num'] to_atn = ti[1]['available_tracklets_num'] + ti[2]['available_tracklets_num']",
"ti[0]['available_images_num'] to_avein = ti[1]['average_images_num'] + ti[2]['average_images_num'] + ti[3]['average_images_num'] + \\ ti[4]['average_images_num'] + ti[5]['average_images_num']",
"== 1: if locx + 30 * locy <= 3000 or locx -",
"= tracklets_num info['tracklets_info'][camid]['ignore_tracklets_num'] = count_ignore_tkl info['tracklets_info'][camid]['available_tracklets_num'] = count_ava_tkl info['tracklets_info'][camid]['available_images_num'] = total_num info['tracklets_info'][camid]['average_images_num'] =",
"locx = float(data[2]) + float(data[4]) / 2 locy = float(data[3]) + float(data[5]) if",
"'r', encoding=encoding) as f: info = json.load(f) if acq_print: print('Load data <--- '",
"| {:17d} | {:20d} | {:22d} | {:20d} \".format(ti[5]['total_tracklets_num'], ti[5]['ignore_tracklets_num'], \\ ti[5]['available_tracklets_num'], ti[5]['available_images_num'],",
"2] wd = data_pix2loc[index, 3] elif method == 'linear': index = np.where(int(data_pix2loc[:, 0])",
"traj_point[0] and int(data_pix2loc[:, 1]) == traj_point[1]) jd = data_pix2loc[index, 2] wd = data_pix2loc[index,",
"assert 'Do not have the meathod' return jd, wd def norm_data(a): ''' :param",
"or (locx >= 2000 and 0.5833 * locx + locy <= 2340): return",
"b j_dist = dist[0] * 111000 * np.cos(a[1] / 180 * np.pi) w_dist",
"lines: data = line.strip().split(',') locx = float(data[2]) + float(data[4]) / 2 locy =",
"+ ti[3]['ignore_tracklets_num'] + \\ ti[4]['ignore_tracklets_num'] + ti[5]['ignore_tracklets_num'] + ti[0]['ignore_tracklets_num'] to_atn = ti[1]['available_tracklets_num'] +",
"with open(path, 'r') as f: lines = f.readlines() for line in lines: data",
"''' folder_dir = Path(folder_dir) if not folder_dir.exists(): if create: try: os.makedirs(folder_dir) except OSError",
"np.argsort(dist)[0] jd = data_pix2loc[index, 2] wd = data_pix2loc[index, 3] elif method == 'linear':",
"'nearest_k_mean': ex = data_pix2loc[:, 0] - traj_point[0] ey = data_pix2loc[:, 1] - traj_point[1]",
"np.load(file_path) if acq_print: print('Load data <--- ' + str(file_path), flush=True) return info class",
"locx, locy): refineData.append(line) with open(path_new, 'w') as f: f.writelines(refineData) @staticmethod def crop_image(img_dir, result_dir,",
"+ ti[5]['ignore_tracklets_num'] + ti[0]['ignore_tracklets_num'] to_atn = ti[1]['available_tracklets_num'] + ti[2]['available_tracklets_num'] + ti[3]['available_tracklets_num'] + \\",
"dist[0] * 111000 * np.cos(a[1] / 180 * np.pi) w_dist = dist[1] *",
":param time: hour minute second :return: second ''' dam_time_list = [] if isinstance(time,",
"if camid == 3: if locy <= 200: return False if camid ==",
"cam5 | {:10d} | {:17d} | {:20d} | {:22d} | {:20d} \".format(ti[4]['total_tracklets_num'], ti[4]['ignore_tracklets_num'],",
"return False if camid == 3: if locy <= 250: return False if",
"print('Load data <--- ' + str(file_path), flush=True) return info @staticmethod def np_save(info, file_path):",
"ti[0]['ignore_tracklets_num'] to_atn = ti[1]['available_tracklets_num'] + ti[2]['available_tracklets_num'] + ti[3]['available_tracklets_num'] + \\ ti[4]['available_tracklets_num'] + ti[5]['available_tracklets_num']",
"data.strip().split(',') data_list.append([int(data[0]), int(data[1]), float(data[2]), float(data[3]), float(data[4]), float(data[5])]) data_arr = np.array(data_list) for img_path in",
"| {:20d} | {:22d} | {:20d} \".format(ti[3]['total_tracklets_num'], ti[3]['ignore_tracklets_num'], \\ ti[3]['available_tracklets_num'], ti[3]['available_images_num'], ti[3]['average_images_num'])) print(\"",
"raise else: raise IOError return folder_dir class DataPacker(object): ''' this class supplys four",
"npy, please check file path.' info = np.load(file_path) if acq_print: print('Load data <---",
"except OSError as e: if e.errno != errno.EEXIST: raise else: raise IOError return",
"- int(time % 100)) / 100 + int(time / 10000) * 60 *",
"os.makedirs(folder_dir) except OSError as e: if e.errno != errno.EEXIST: raise else: raise IOError",
"= pickle.load(f) print('Load data <--- ' + str(file_path), flush=True) return info @staticmethod def",
"= ham_to_dem(time) start_time = ham_to_dem(102630) sub_time = now_time - start_time return int(sub_time) def",
"tracklet_id in tracklet_ids: img_paths = glob.glob(str(tracklets_per_cam_dir / tracklet_id / '*.jpg')) img_paths.sort() if len(img_paths)",
"| {:20d} \".format(ti[0]['total_tracklets_num'], ti[0]['ignore_tracklets_num'], \\ ti[0]['available_tracklets_num'], ti[0]['available_images_num'], ti[0]['average_images_num'])) print(\" cam2 | {:10d} |",
"----------------------------------------------------------------------------------------------------------------\") print(\" cam1 | {:10d} | {:17d} | {:20d} | {:22d} | {:20d}",
"= f.readlines() for data in total_data: data = data.strip().split(',') data_list.append([int(data[0]), int(data[1]), float(data[2]), float(data[3]),",
"= [] with open(path, 'r') as f: lines = f.readlines() for line in",
"+ \\ ti[4]['ignore_tracklets_num'] + ti[5]['ignore_tracklets_num'] + ti[0]['ignore_tracklets_num'] to_atn = ti[1]['available_tracklets_num'] + ti[2]['available_tracklets_num'] +",
"def check_path(folder_dir, create=False): ''' :param folder_dir: file path :param create: create file or",
"== 'npy', 'This file\\' suffix is not npy, please check file path.' info",
"info['tracklets_info'][camid]['total_tracklets_num'] = tracklets_num info['tracklets_info'][camid]['ignore_tracklets_num'] = count_ignore_tkl info['tracklets_info'][camid]['available_tracklets_num'] = count_ava_tkl info['tracklets_info'][camid]['available_images_num'] = total_num info['tracklets_info'][camid]['average_images_num']",
"if isinstance(time, list): for i in time: dem_time = int(i % 100) +",
"data_pix2loc[:, 0] - traj_point[0] ey = data_pix2loc[:, 1] - traj_point[1] dist = ex",
"b): ''' :param a: ndarray:[jd, wd] :param b: ndarray:[jd, wd] :return: distance '''",
":param create: create file or not :return: ''' folder_dir = Path(folder_dir) if not",
"'{:05d}'.format(int(tid)) check_path(save_img_path, create=True) count = len(glob.glob(str(save_img_path / '*.jpg'))) y2 = y1 + h",
"False if camid == 2: if locy <= 200 or locx >= 3600:",
"'wb') as f: pickle.dump(info, f) print('Store data ---> ' + str(file_path), flush=True) @staticmethod",
"file path.' np.save(file_path, info) print('Store data ---> ' + str(file_path), flush=True) @staticmethod def",
"== 3: if locy <= 200: return False if camid == 4: if",
"| {:10d} | {:17d} | {:20d} | {:22d} | {:20d} \".format(ti[3]['total_tracklets_num'], ti[3]['ignore_tracklets_num'], \\",
"= f.readlines() for line in lines: data = line.strip().split(',') locx = float(data[2]) +",
"new_id = 0 for camid in range(cam_num): tracklets_per_cam_dir = tracklet_dir / '{:02d}'.format(camid +",
"'tracklets':[]} new_id = 0 for camid in range(cam_num): tracklets_per_cam_dir = tracklet_dir / '{:02d}'.format(camid",
"+ str(file_path), flush=True) @staticmethod def load(file_path): check_path(file_path) with open(file_path, 'rb') as f: info",
"- 2.5 * locy >= 2000: return False return True @staticmethod def refine_v2(camid,",
"{:10d} | {:17d} | {:20d} | {:22d} | {:20d} \".format(ti[2]['total_tracklets_num'], ti[2]['ignore_tracklets_num'], \\ ti[2]['available_tracklets_num'],",
"dam_time_list.append(dem_time) return dam_time_list else: dem_time = int(time % 100) + 60 * (int(time",
"count_ignore_tkl += 1 info['old2new'][camid][int(tracklet_id)] = None info['ignore'].append(tracklets_per_cam_dir / tracklet_id) else: count_ava_tkl += 1",
"+ str(file_path), flush=True) @staticmethod def json_load(file_path, encoding='UTF-8', acq_print=True): check_path(file_path) with open(file_path, 'r', encoding=encoding)",
"/ '*.jpg')) img_paths.sort() result_path = result_dir / ('GPSReID0'+str(camid)+'_refine_v2.txt') data_list = [] with open(result_path,",
"ti[0]['average_images_num'])) print(\" cam2 | {:10d} | {:17d} | {:20d} | {:22d} | {:20d}",
"jd, wd = np.mean(data_pix2loc[indexs, 2:], axis=0) else: assert 'Do not have the meathod'",
"import numpy as np import os import errno from geopy.distance import geodesic from",
"or locx >= 3600: return False if camid == 3: if locy <=",
"print(\" cam4 | {:10d} | {:17d} | {:20d} | {:22d} | {:20d} \".format(ti[3]['total_tracklets_num'],",
"= dist[0] * 111000 * np.cos(31 / 180 * np.pi) w_dist = dist[1]",
"return info class DataProcesser(object): @staticmethod def refine_v1(camid, locx, locy): if camid == 1:",
"ti[2]['available_tracklets_num'] + ti[3]['available_tracklets_num'] + \\ ti[4]['available_tracklets_num'] + ti[5]['available_tracklets_num'] + ti[0]['available_tracklets_num'] to_avain = ti[1]['available_images_num']",
"save_img_path / img_name) @staticmethod def count_dataset_info(tracklet_dir, cam_num, verbose=False, save_info=False): tracklet_dir = Path(tracklet_dir) info",
"'Do not have the meathod' return jd, wd def norm_data(a): ''' :param a:",
"path.' info = np.loadtxt(file_path) if acq_print: print('Load data <--- ' + str(file_path), flush=True)",
"not folder_dir.exists(): if create: try: os.makedirs(folder_dir) except OSError as e: if e.errno !=",
"info class DataProcesser(object): @staticmethod def refine_v1(camid, locx, locy): if camid == 1: if",
"'linear' 'nearest_k_mean' :param k: num of selected point :return: traj_list's jd and wd",
"import cv2 def ham_to_dem(time): ''' :param time: hour minute second :return: second '''",
"return folder_dir class DataPacker(object): ''' this class supplys four different Data processing format",
"False if camid == 3: if locy <= 200: return False if camid",
"ignore tkls num | # available tkls num | # available images num",
"check_path(Path(file_path).parent, create=True) with open(file_path, 'wb') as f: pickle.dump(info, f) print('Store data ---> '",
"in data_cur: fid, tid, x1, y1, w, h = data save_img_path = save_img_dir",
"data_pix2loc[index, 3] elif method == 'linear': index = np.where(int(data_pix2loc[:, 0]) == traj_point[0] and",
"ti[4]['available_images_num'], ti[4]['average_images_num'])) print(\" cam6 | {:10d} | {:17d} | {:20d} | {:22d} |",
"print('ignore image -- ', save_img_path / img_name) @staticmethod def count_dataset_info(tracklet_dir, cam_num, verbose=False, save_info=False):",
"{:10d} | {:17d} | {:20d} | {:22d} | {:20d} \".format(ti[4]['total_tracklets_num'], ti[4]['ignore_tracklets_num'], \\ ti[4]['available_tracklets_num'],",
"w_dist = dist[1] * 111000 return np.sqrt(np.power(j_dist, 2)+np.power(w_dist, 2)) def trans_gps_diff_to_dist_v2(dist): ''' :param",
"- 8.235 * locy >= 1200: return False if camid == 2: if",
"1200: return False if camid == 2: if locy <= 150 or locx",
"IOError return folder_dir class DataPacker(object): ''' this class supplys four different Data processing",
"DataProcesser(object): @staticmethod def refine_v1(camid, locx, locy): if camid == 1: if locx +",
"ti[2]['average_images_num'] + ti[3]['average_images_num'] + \\ ti[4]['average_images_num'] + ti[5]['average_images_num'] + ti[0]['average_images_num'] print(\"=> GPSMOT loaded\")",
"[jd, wd] :param gps_2: [jd, wd] :return: distance between two gps ''' return",
"in tracklet_ids: img_paths = glob.glob(str(tracklets_per_cam_dir / tracklet_id / '*.jpg')) img_paths.sort() if len(img_paths) <=",
"path.' info = np.load(file_path) if acq_print: print('Load data <--- ' + str(file_path), flush=True)",
"flush=True) return info class DataProcesser(object): @staticmethod def refine_v1(camid, locx, locy): if camid ==",
"= data.strip().split(',') data_list.append([int(data[0]), int(data[1]), float(data[2]), float(data[3]), float(data[4]), float(data[5])]) data_arr = np.array(data_list) for img_path",
"between two gps ''' return geodesic((gps_1[1], gps_1[0]), (gps_2[1], gps_2[0]).m) def pixel_to_loc(data_pix2loc, traj_point, method='nearset',",
"int(time % 100)) / 100 + int(time / 10000) * 60 * 60",
"= os.listdir(tracklets_per_cam_dir) tracklet_ids.sort() tracklets_num = len(tracklet_ids) count_ignore_tkl = 0 count_ava_tkl = 0 count_avg_tkl_num",
"{:10d} | {:17d} | {:20d} | {:22d} | {:20d} \".format(ti[1]['total_tracklets_num'], ti[1]['ignore_tracklets_num'], \\ ti[1]['available_tracklets_num'],",
"= float(data[3]) + float(data[5]) if DataProcesser.refine_v2(camid, locx, locy): refineData.append(line) with open(path_new, 'w') as",
"* locx + locy <= 350 or locx - 5.7143 * locy >=",
"| {:17d} | {:20d} | {:22d} | {:20d} \".format(ti[1]['total_tracklets_num'], ti[1]['ignore_tracklets_num'], \\ ti[1]['available_tracklets_num'], ti[1]['available_images_num'],",
"crop_image(img_dir, result_dir, save_img_dir, camid): img_paths = glob.glob(str(img_dir / '*.jpg')) img_paths.sort() result_path = result_dir",
"* 60 * 60 return int(dem_time) def get_time(time): ''' :param time: hour minute",
"file path.' info = np.loadtxt(file_path) if acq_print: print('Load data <--- ' + str(file_path),",
"as f: json.dump(info, f) print('Store data ---> ' + str(file_path), flush=True) @staticmethod def",
"json_dump(info, file_path, encoding='UTF-8'): check_path(Path(file_path).parent, create=True) with open(file_path, 'w', encoding=encoding) as f: json.dump(info, f)",
"ti[5]['ignore_tracklets_num'], \\ ti[5]['available_tracklets_num'], ti[5]['available_images_num'], ti[5]['average_images_num'])) print(\" ----------------------------------------------------------------------------------------------------------------\") print(\" total | {:10d} | {:17d}",
"2.5 * locy >= 2000: return False return True @staticmethod def refine_v2(camid, locx,",
"10000) * 60 * 60 return int(dem_time) def get_time(time): ''' :param time: hour",
"'This file\\' suffix is not npy, please check file path.' info = np.load(file_path)",
"from geopy.distance import geodesic from pathlib import Path import glob import cv2 def",
"camid == 1: if locx + 20 * locy <= 4000 or locx",
"new_id, camid)) total_num += len(img_paths) count_avg_tkl_num += 1 info['tracklets_info'][camid]['total_tracklets_num'] = tracklets_num info['tracklets_info'][camid]['ignore_tracklets_num'] =",
"'{:02d}'.format(camid + 1) tracklet_ids = os.listdir(tracklets_per_cam_dir) tracklet_ids.sort() tracklets_num = len(tracklet_ids) count_ignore_tkl = 0",
"print('Load data <--- ' + str(file_path), flush=True) return info class DataProcesser(object): @staticmethod def",
"= data_pix2loc[index, 3] elif method == 'nearest_k_mean': ex = data_pix2loc[:, 0] - traj_point[0]",
"f.writelines(refineData) @staticmethod def crop_image(img_dir, result_dir, save_img_dir, camid): img_paths = glob.glob(str(img_dir / '*.jpg')) img_paths.sort()",
"wd def norm_data(a): ''' :param a: feature distance N X N :return: normalize",
"total_num += len(img_paths) count_avg_tkl_num += 1 info['tracklets_info'][camid]['total_tracklets_num'] = tracklets_num info['tracklets_info'][camid]['ignore_tracklets_num'] = count_ignore_tkl info['tracklets_info'][camid]['available_tracklets_num']",
"index = np.where(int(data_pix2loc[:, 0]) == traj_point[0] and int(data_pix2loc[:, 1]) == traj_point[1]) jd =",
"+= 1 info['old2new'][camid][int(tracklet_id)] = new_id new_id += 1 info['tracklets'].append((img_paths, new_id, camid)) total_num +=",
"{:22d} | {:20d} \".format(ti[3]['total_tracklets_num'], ti[3]['ignore_tracklets_num'], \\ ti[3]['available_tracklets_num'], ti[3]['available_images_num'], ti[3]['average_images_num'])) print(\" cam5 | {:10d}",
"= dist[1] * 111000 return np.sqrt(np.power(j_dist, 2)+np.power(w_dist, 2)) def trans_gps_diff_to_dist_v3(gps_1, gps_2): ''' :param",
"<= 350 or locx - 5.7143 * locy >= 2000: return False if",
"size[n, 4] :param traj_list: [pixel_x, pixel_y] size[2] :param method: 'nearest' 'linear' 'nearest_k_mean' :param",
"import json import pickle import numpy as np import os import errno from",
"def trans_gps_diff_to_dist_v1(a, b): ''' :param a: ndarray:[jd, wd] :param b: ndarray:[jd, wd] :return:",
"check_path(folder_dir, create=False): ''' :param folder_dir: file path :param create: create file or not",
"return False return True @staticmethod def refine_v2(camid, locx, locy): if camid == 1:",
"= np.argsort(dist)[0] jd = data_pix2loc[index, 2] wd = data_pix2loc[index, 3] elif method ==",
"0.1167 * locx + locy <= 350 or locx - 5.7143 * locy",
"= ti[1]['total_tracklets_num'] + ti[2]['total_tracklets_num'] + ti[3]['total_tracklets_num'] + \\ ti[4]['total_tracklets_num'] + ti[5]['total_tracklets_num'] + ti[0]['total_tracklets_num']",
"info['tracklets'].append((img_paths, new_id, camid)) total_num += len(img_paths) count_avg_tkl_num += 1 info['tracklets_info'][camid]['total_tracklets_num'] = tracklets_num info['tracklets_info'][camid]['ignore_tracklets_num']",
"raise IOError return folder_dir class DataPacker(object): ''' this class supplys four different Data",
"gps_2): ''' :param gps_1: [jd, wd] :param gps_2: [jd, wd] :return: distance between",
"= np.max(a,axis=1,keepdims=True) - a_min return (a - a_min) / _range def check_path(folder_dir, create=False):",
"total_num info['tracklets_info'][camid]['average_images_num'] = total_num // count_ava_tkl assert info['tracklets_info'][camid]['total_tracklets_num'] == \\ info['tracklets_info'][camid]['ignore_tracklets_num'] + \\",
"<= 0: y1 = 0 if x1 <= 0: x1 = 0 if",
"+ ti[2]['ignore_tracklets_num'] + ti[3]['ignore_tracklets_num'] + \\ ti[4]['ignore_tracklets_num'] + ti[5]['ignore_tracklets_num'] + ti[0]['ignore_tracklets_num'] to_atn =",
"info = np.load(file_path) if acq_print: print('Load data <--- ' + str(file_path), flush=True) return",
"a_min = np.min(a, axis=1, keepdims=True) _range = np.max(a,axis=1,keepdims=True) - a_min return (a -",
"= 0 for camid in range(cam_num): tracklets_per_cam_dir = tracklet_dir / '{:02d}'.format(camid + 1)",
"num | # ignore tkls num | # available tkls num | #",
"save_info: DataPacker.dump(info, tracklet_dir / 'info.pkl') return info if verbose: ti = info['tracklets_info'] to_tn",
"* 111000 return np.sqrt(np.power(j_dist, 2)+np.power(w_dist, 2)) def trans_gps_diff_to_dist_v3(gps_1, gps_2): ''' :param gps_1: [jd,",
"| {:10d} | {:17d} | {:20d} | {:22d} | {:20d} \".format(ti[4]['total_tracklets_num'], ti[4]['ignore_tracklets_num'], \\",
":param time: hour minute second :return: second from 102630 ''' now_time = ham_to_dem(time)",
"index] for data in data_cur: fid, tid, x1, y1, w, h = data",
"to_tn = ti[1]['total_tracklets_num'] + ti[2]['total_tracklets_num'] + ti[3]['total_tracklets_num'] + \\ ti[4]['total_tracklets_num'] + ti[5]['total_tracklets_num'] +",
"('GPSReID0'+str(camid)+'_refine_v2.txt') data_list = [] with open(result_path, 'r') as f: total_data = f.readlines() for",
"def ham_to_dem(time): ''' :param time: hour minute second :return: second ''' dam_time_list =",
"1: if locx + 30 * locy <= 3000 or locx - 8.235",
"with open(result_path, 'r') as f: total_data = f.readlines() for data in total_data: data",
"method='nearset', k=4): ''' :param data_pix2loc: [pixel_x, pixel_y, jd, wd] size[n, 4] :param traj_list:",
"False if camid == 5: if locy <= 150 or 0.1167 * locx",
"False if camid == 6: if locy <= 150 or locx - 2.5",
"available tkls num | # available images num | # average images num\")",
"data ---> ' + str(file_path), flush=True) @staticmethod def load(file_path): check_path(file_path) with open(file_path, 'rb')",
"== index] for data in data_cur: fid, tid, x1, y1, w, h =",
"---> ' + str(file_path), flush=True) @staticmethod def load(file_path): check_path(file_path) with open(file_path, 'rb') as",
"float(data[4]), float(data[5])]) data_arr = np.array(data_list) for img_path in img_paths: index = int(img_path.split('/')[-1].split('.')[0]) +",
"e.errno != errno.EEXIST: raise else: raise IOError return folder_dir class DataPacker(object): ''' this",
"jd = data_pix2loc[index, 2] wd = data_pix2loc[index, 3] elif method == 'linear': index",
"file\\' suffix is not npy, please check file path.' np.save(file_path, info) print('Store data",
"'ignore':[], 'tracklets_info':[{} for i in range(cam_num)], 'tracklets':[]} new_id = 0 for camid in",
"line.strip().split(',') locx = float(data[2]) + float(data[4]) / 2 locy = float(data[3]) + float(data[5])",
"as f: f.writelines(refineData) @staticmethod def crop_image(img_dir, result_dir, save_img_dir, camid): img_paths = glob.glob(str(img_dir /",
"= data_pix2loc[:, 1] - traj_point[1] dist = ex ** 2 + ey **",
"+ ti[5]['available_images_num'] + ti[0]['available_images_num'] to_avein = ti[1]['average_images_num'] + ti[2]['average_images_num'] + ti[3]['average_images_num'] + \\",
"% 100)) / 100 + int(time / 10000) * 60 * 60 return",
"file_path.split('.')[-1] == 'npy', 'This file\\' suffix is not npy, please check file path.'",
"- a_min return (a - a_min) / _range def check_path(folder_dir, create=False): ''' :param",
"False return True @staticmethod def refine_result(path, path_new, camid): refineData = [] with open(path,",
"'txt', 'This file\\' suffix is not txt, please check file path.' np.savetxt(file_path, info)",
"str(file_path), flush=True) @staticmethod def np_load_txt(file_path, acq_print=True): check_path(file_path) assert file_path.split('.')[-1] == 'txt', 'This file\\'",
"data_arr = np.array(data_list) for img_path in img_paths: index = int(img_path.split('/')[-1].split('.')[0]) + 1 img0",
"/ 100 + int(time / 10000) * 60 * 60 return int(dem_time) def",
"tracklets_num = len(tracklet_ids) count_ignore_tkl = 0 count_ava_tkl = 0 count_avg_tkl_num = 0 total_num",
"float(data[4]) / 2 locy = float(data[3]) + float(data[5]) if DataProcesser.refine_v2(camid, locx, locy): refineData.append(line)",
"[pixel_x, pixel_y, jd, wd] size[n, 4] :param traj_list: [pixel_x, pixel_y] size[2] :param method:",
"camid == 2: if locy <= 200 or locx >= 3600: return False",
"acq_print: print('Load data <--- ' + str(file_path), flush=True) return info @staticmethod def np_save(info,",
"= ti[1]['ignore_tracklets_num'] + ti[2]['ignore_tracklets_num'] + ti[3]['ignore_tracklets_num'] + \\ ti[4]['ignore_tracklets_num'] + ti[5]['ignore_tracklets_num'] + ti[0]['ignore_tracklets_num']",
"* 111000 return np.sqrt(np.power(j_dist, 2)+np.power(w_dist, 2)) def trans_gps_diff_to_dist_v2(dist): ''' :param dist: [jd_sub, wd_sub]",
"for i in range(cam_num)], 'tracklets':[]} new_id = 0 for camid in range(cam_num): tracklets_per_cam_dir",
"= a.copy() a_min = np.min(a, axis=1, keepdims=True) _range = np.max(a,axis=1,keepdims=True) - a_min return",
"assert file_path.split('.')[-1] == 'txt', 'This file\\' suffix is not txt, please check file",
"create=True) with open(file_path, 'w', encoding=encoding) as f: json.dump(info, f) print('Store data ---> '"
] |
[
"datetime import re import sys file_path = sys.argv[1] n_lines = open(file_path, 'r').readlines() email_address",
"range_match is not None: date_string = date_string.replace(str(range_match.group(4)), str(datetime.today().year)) else: single_match = re.match(r'.*([1-3][0-9]{3})', date_string)",
"re.match(r'.*([1-3][0-9]{3})', date_string) if single_match is not None: date_string = date_string.replace(str(single_match.group(1)), str(single_match.group(1)) + '",
"is not None: date_string = date_string.replace(str(single_match.group(1)), str(single_match.group(1)) + ' - ' + str(datetime.today().year))",
"n_lines = open(file_path, 'r').readlines() email_address = open('.git/copyrightemail', 'r').readlines()[0].strip() if not email_address in \"\\n\".join(n_lines[:5]):",
"= sys.argv[1] n_lines = open(file_path, 'r').readlines() email_address = open('.git/copyrightemail', 'r').readlines()[0].strip() if not email_address",
"if not email_address in \"\\n\".join(n_lines[:5]): print(\"{}: Your email, {}, is not found in",
"once\": date_idx += 1 def fix_date(line): if str(datetime.today().year) in line: return line date_string",
"if n_lines[date_idx].strip() == \"#pragma once\": date_idx += 1 def fix_date(line): if str(datetime.today().year) in",
"email, {}, is not found in the Copyright header!\".format(file_path, email_address)) exit(-1) date_idx =",
"found in the Copyright header!\".format(file_path, email_address)) exit(-1) date_idx = 0 if n_lines[date_idx].strip() ==",
"date_idx = 0 if n_lines[date_idx].strip() == \"#pragma once\": date_idx += 1 def fix_date(line):",
"return line date_string = line range_match = re.match(r'.*([1-3][0-9]{3})( )*-( )*([1-3][0-9]{3})', date_string) if range_match",
"None: date_string = date_string.replace(str(single_match.group(1)), str(single_match.group(1)) + ' - ' + str(datetime.today().year)) return date_string",
"if str(datetime.today().year) in line: return line date_string = line range_match = re.match(r'.*([1-3][0-9]{3})( )*-(",
"new_date_line = fix_date(old_date_line) if old_date_line != new_date_line: print(\"Updated date!\") print(\"Old date line:\", old_date_line)",
"!= new_date_line: print(\"Updated date!\") print(\"Old date line:\", old_date_line) print(\"New date line:\", new_date_line) n_lines[date_idx]",
"else: single_match = re.match(r'.*([1-3][0-9]{3})', date_string) if single_match is not None: date_string = date_string.replace(str(single_match.group(1)),",
"date_string) if single_match is not None: date_string = date_string.replace(str(single_match.group(1)), str(single_match.group(1)) + ' -",
"sys file_path = sys.argv[1] n_lines = open(file_path, 'r').readlines() email_address = open('.git/copyrightemail', 'r').readlines()[0].strip() if",
"sys.argv[1] n_lines = open(file_path, 'r').readlines() email_address = open('.git/copyrightemail', 'r').readlines()[0].strip() if not email_address in",
"str(datetime.today().year)) else: single_match = re.match(r'.*([1-3][0-9]{3})', date_string) if single_match is not None: date_string =",
"print(\"Old date line:\", old_date_line) print(\"New date line:\", new_date_line) n_lines[date_idx] = new_date_line f =",
"open(file_path, 'r').readlines() email_address = open('.git/copyrightemail', 'r').readlines()[0].strip() if not email_address in \"\\n\".join(n_lines[:5]): print(\"{}: Your",
"old_date_line) print(\"New date line:\", new_date_line) n_lines[date_idx] = new_date_line f = open(file_path, 'w') f.writelines(n_lines)",
"date_string.replace(str(range_match.group(4)), str(datetime.today().year)) else: single_match = re.match(r'.*([1-3][0-9]{3})', date_string) if single_match is not None: date_string",
"str(datetime.today().year) in line: return line date_string = line range_match = re.match(r'.*([1-3][0-9]{3})( )*-( )*([1-3][0-9]{3})',",
"1 def fix_date(line): if str(datetime.today().year) in line: return line date_string = line range_match",
"' + str(datetime.today().year)) return date_string old_date_line = n_lines[date_idx] new_date_line = fix_date(old_date_line) if old_date_line",
"+= 1 def fix_date(line): if str(datetime.today().year) in line: return line date_string = line",
"0 if n_lines[date_idx].strip() == \"#pragma once\": date_idx += 1 def fix_date(line): if str(datetime.today().year)",
"re import sys file_path = sys.argv[1] n_lines = open(file_path, 'r').readlines() email_address = open('.git/copyrightemail',",
"date_string) if range_match is not None: date_string = date_string.replace(str(range_match.group(4)), str(datetime.today().year)) else: single_match =",
"= n_lines[date_idx] new_date_line = fix_date(old_date_line) if old_date_line != new_date_line: print(\"Updated date!\") print(\"Old date",
"line date_string = line range_match = re.match(r'.*([1-3][0-9]{3})( )*-( )*([1-3][0-9]{3})', date_string) if range_match is",
"import re import sys file_path = sys.argv[1] n_lines = open(file_path, 'r').readlines() email_address =",
"print(\"{}: Your email, {}, is not found in the Copyright header!\".format(file_path, email_address)) exit(-1)",
")*-( )*([1-3][0-9]{3})', date_string) if range_match is not None: date_string = date_string.replace(str(range_match.group(4)), str(datetime.today().year)) else:",
"not None: date_string = date_string.replace(str(single_match.group(1)), str(single_match.group(1)) + ' - ' + str(datetime.today().year)) return",
"re.match(r'.*([1-3][0-9]{3})( )*-( )*([1-3][0-9]{3})', date_string) if range_match is not None: date_string = date_string.replace(str(range_match.group(4)), str(datetime.today().year))",
"if single_match is not None: date_string = date_string.replace(str(single_match.group(1)), str(single_match.group(1)) + ' - '",
"import sys file_path = sys.argv[1] n_lines = open(file_path, 'r').readlines() email_address = open('.git/copyrightemail', 'r').readlines()[0].strip()",
"\"#pragma once\": date_idx += 1 def fix_date(line): if str(datetime.today().year) in line: return line",
"n_lines[date_idx] new_date_line = fix_date(old_date_line) if old_date_line != new_date_line: print(\"Updated date!\") print(\"Old date line:\",",
"date!\") print(\"Old date line:\", old_date_line) print(\"New date line:\", new_date_line) n_lines[date_idx] = new_date_line f",
"= re.match(r'.*([1-3][0-9]{3})( )*-( )*([1-3][0-9]{3})', date_string) if range_match is not None: date_string = date_string.replace(str(range_match.group(4)),",
"range_match = re.match(r'.*([1-3][0-9]{3})( )*-( )*([1-3][0-9]{3})', date_string) if range_match is not None: date_string =",
"print(\"New date line:\", new_date_line) n_lines[date_idx] = new_date_line f = open(file_path, 'w') f.writelines(n_lines) f.close()",
"line:\", old_date_line) print(\"New date line:\", new_date_line) n_lines[date_idx] = new_date_line f = open(file_path, 'w')",
"print(\"Updated date!\") print(\"Old date line:\", old_date_line) print(\"New date line:\", new_date_line) n_lines[date_idx] = new_date_line",
"- ' + str(datetime.today().year)) return date_string old_date_line = n_lines[date_idx] new_date_line = fix_date(old_date_line) if",
"exit(-1) date_idx = 0 if n_lines[date_idx].strip() == \"#pragma once\": date_idx += 1 def",
"in the Copyright header!\".format(file_path, email_address)) exit(-1) date_idx = 0 if n_lines[date_idx].strip() == \"#pragma",
"{}, is not found in the Copyright header!\".format(file_path, email_address)) exit(-1) date_idx = 0",
"in \"\\n\".join(n_lines[:5]): print(\"{}: Your email, {}, is not found in the Copyright header!\".format(file_path,",
"' - ' + str(datetime.today().year)) return date_string old_date_line = n_lines[date_idx] new_date_line = fix_date(old_date_line)",
"+ str(datetime.today().year)) return date_string old_date_line = n_lines[date_idx] new_date_line = fix_date(old_date_line) if old_date_line !=",
"email_address = open('.git/copyrightemail', 'r').readlines()[0].strip() if not email_address in \"\\n\".join(n_lines[:5]): print(\"{}: Your email, {},",
"email_address)) exit(-1) date_idx = 0 if n_lines[date_idx].strip() == \"#pragma once\": date_idx += 1",
"= 0 if n_lines[date_idx].strip() == \"#pragma once\": date_idx += 1 def fix_date(line): if",
"date_string = date_string.replace(str(single_match.group(1)), str(single_match.group(1)) + ' - ' + str(datetime.today().year)) return date_string old_date_line",
"'r').readlines()[0].strip() if not email_address in \"\\n\".join(n_lines[:5]): print(\"{}: Your email, {}, is not found",
"str(datetime.today().year)) return date_string old_date_line = n_lines[date_idx] new_date_line = fix_date(old_date_line) if old_date_line != new_date_line:",
"= open('.git/copyrightemail', 'r').readlines()[0].strip() if not email_address in \"\\n\".join(n_lines[:5]): print(\"{}: Your email, {}, is",
"\"\\n\".join(n_lines[:5]): print(\"{}: Your email, {}, is not found in the Copyright header!\".format(file_path, email_address))",
"= fix_date(old_date_line) if old_date_line != new_date_line: print(\"Updated date!\") print(\"Old date line:\", old_date_line) print(\"New",
"if range_match is not None: date_string = date_string.replace(str(range_match.group(4)), str(datetime.today().year)) else: single_match = re.match(r'.*([1-3][0-9]{3})',",
"= date_string.replace(str(single_match.group(1)), str(single_match.group(1)) + ' - ' + str(datetime.today().year)) return date_string old_date_line =",
"file_path = sys.argv[1] n_lines = open(file_path, 'r').readlines() email_address = open('.git/copyrightemail', 'r').readlines()[0].strip() if not",
"fix_date(line): if str(datetime.today().year) in line: return line date_string = line range_match = re.match(r'.*([1-3][0-9]{3})(",
"date line:\", old_date_line) print(\"New date line:\", new_date_line) n_lines[date_idx] = new_date_line f = open(file_path,",
"not email_address in \"\\n\".join(n_lines[:5]): print(\"{}: Your email, {}, is not found in the",
"date_string.replace(str(single_match.group(1)), str(single_match.group(1)) + ' - ' + str(datetime.today().year)) return date_string old_date_line = n_lines[date_idx]",
"return date_string old_date_line = n_lines[date_idx] new_date_line = fix_date(old_date_line) if old_date_line != new_date_line: print(\"Updated",
")*([1-3][0-9]{3})', date_string) if range_match is not None: date_string = date_string.replace(str(range_match.group(4)), str(datetime.today().year)) else: single_match",
"date_string = line range_match = re.match(r'.*([1-3][0-9]{3})( )*-( )*([1-3][0-9]{3})', date_string) if range_match is not",
"import datetime import re import sys file_path = sys.argv[1] n_lines = open(file_path, 'r').readlines()",
"python3 from datetime import datetime import re import sys file_path = sys.argv[1] n_lines",
"new_date_line: print(\"Updated date!\") print(\"Old date line:\", old_date_line) print(\"New date line:\", new_date_line) n_lines[date_idx] =",
"+ ' - ' + str(datetime.today().year)) return date_string old_date_line = n_lines[date_idx] new_date_line =",
"= date_string.replace(str(range_match.group(4)), str(datetime.today().year)) else: single_match = re.match(r'.*([1-3][0-9]{3})', date_string) if single_match is not None:",
"date_string old_date_line = n_lines[date_idx] new_date_line = fix_date(old_date_line) if old_date_line != new_date_line: print(\"Updated date!\")",
"single_match = re.match(r'.*([1-3][0-9]{3})', date_string) if single_match is not None: date_string = date_string.replace(str(single_match.group(1)), str(single_match.group(1))",
"= line range_match = re.match(r'.*([1-3][0-9]{3})( )*-( )*([1-3][0-9]{3})', date_string) if range_match is not None:",
"line: return line date_string = line range_match = re.match(r'.*([1-3][0-9]{3})( )*-( )*([1-3][0-9]{3})', date_string) if",
"fix_date(old_date_line) if old_date_line != new_date_line: print(\"Updated date!\") print(\"Old date line:\", old_date_line) print(\"New date",
"not None: date_string = date_string.replace(str(range_match.group(4)), str(datetime.today().year)) else: single_match = re.match(r'.*([1-3][0-9]{3})', date_string) if single_match",
"email_address in \"\\n\".join(n_lines[:5]): print(\"{}: Your email, {}, is not found in the Copyright",
"'r').readlines() email_address = open('.git/copyrightemail', 'r').readlines()[0].strip() if not email_address in \"\\n\".join(n_lines[:5]): print(\"{}: Your email,",
"Copyright header!\".format(file_path, email_address)) exit(-1) date_idx = 0 if n_lines[date_idx].strip() == \"#pragma once\": date_idx",
"n_lines[date_idx].strip() == \"#pragma once\": date_idx += 1 def fix_date(line): if str(datetime.today().year) in line:",
"not found in the Copyright header!\".format(file_path, email_address)) exit(-1) date_idx = 0 if n_lines[date_idx].strip()",
"header!\".format(file_path, email_address)) exit(-1) date_idx = 0 if n_lines[date_idx].strip() == \"#pragma once\": date_idx +=",
"the Copyright header!\".format(file_path, email_address)) exit(-1) date_idx = 0 if n_lines[date_idx].strip() == \"#pragma once\":",
"== \"#pragma once\": date_idx += 1 def fix_date(line): if str(datetime.today().year) in line: return",
"None: date_string = date_string.replace(str(range_match.group(4)), str(datetime.today().year)) else: single_match = re.match(r'.*([1-3][0-9]{3})', date_string) if single_match is",
"line range_match = re.match(r'.*([1-3][0-9]{3})( )*-( )*([1-3][0-9]{3})', date_string) if range_match is not None: date_string",
"is not None: date_string = date_string.replace(str(range_match.group(4)), str(datetime.today().year)) else: single_match = re.match(r'.*([1-3][0-9]{3})', date_string) if",
"is not found in the Copyright header!\".format(file_path, email_address)) exit(-1) date_idx = 0 if",
"date_string = date_string.replace(str(range_match.group(4)), str(datetime.today().year)) else: single_match = re.match(r'.*([1-3][0-9]{3})', date_string) if single_match is not",
"in line: return line date_string = line range_match = re.match(r'.*([1-3][0-9]{3})( )*-( )*([1-3][0-9]{3})', date_string)",
"= re.match(r'.*([1-3][0-9]{3})', date_string) if single_match is not None: date_string = date_string.replace(str(single_match.group(1)), str(single_match.group(1)) +",
"open('.git/copyrightemail', 'r').readlines()[0].strip() if not email_address in \"\\n\".join(n_lines[:5]): print(\"{}: Your email, {}, is not",
"def fix_date(line): if str(datetime.today().year) in line: return line date_string = line range_match =",
"old_date_line != new_date_line: print(\"Updated date!\") print(\"Old date line:\", old_date_line) print(\"New date line:\", new_date_line)",
"if old_date_line != new_date_line: print(\"Updated date!\") print(\"Old date line:\", old_date_line) print(\"New date line:\",",
"date_idx += 1 def fix_date(line): if str(datetime.today().year) in line: return line date_string =",
"Your email, {}, is not found in the Copyright header!\".format(file_path, email_address)) exit(-1) date_idx",
"str(single_match.group(1)) + ' - ' + str(datetime.today().year)) return date_string old_date_line = n_lines[date_idx] new_date_line",
"#!/usr/bin/env python3 from datetime import datetime import re import sys file_path = sys.argv[1]",
"<filename>ci/check_copyright_block.py #!/usr/bin/env python3 from datetime import datetime import re import sys file_path =",
"datetime import datetime import re import sys file_path = sys.argv[1] n_lines = open(file_path,",
"old_date_line = n_lines[date_idx] new_date_line = fix_date(old_date_line) if old_date_line != new_date_line: print(\"Updated date!\") print(\"Old",
"single_match is not None: date_string = date_string.replace(str(single_match.group(1)), str(single_match.group(1)) + ' - ' +",
"= open(file_path, 'r').readlines() email_address = open('.git/copyrightemail', 'r').readlines()[0].strip() if not email_address in \"\\n\".join(n_lines[:5]): print(\"{}:",
"from datetime import datetime import re import sys file_path = sys.argv[1] n_lines ="
] |
[
"from tone import Tone class Fingerboard: @classmethod def getPos(cls): _pos = {} openTones",
"1] = arr return _pos @classmethod def dump(cls, includes): _pos = cls.getPos() if",
"tone = Tone() for stringIndex, openTone in enumerate(openTones): toneIndex = tone.getToneNumberByName(openTone) arr =",
"i, tone in enumerate(arr): if tone not in includes.keys(): arr[i] = \" \"",
"_pos[key] for i, tone in enumerate(arr): if tone not in includes.keys(): arr[i] =",
"= _pos[key] tones = map(lambda x: \" %7s \" % x, tones) print",
"def dump(cls, includes): _pos = cls.getPos() if len(includes) > 0: for key in",
"arr.append(toneString) _pos[stringIndex + 1] = arr return _pos @classmethod def dump(cls, includes): _pos",
"\"E\"] tone = Tone() for stringIndex, openTone in enumerate(openTones): toneIndex = tone.getToneNumberByName(openTone) arr",
"toneIndex = tone.getToneNumberByName(openTone) arr = [] for i in range(13): toneString = tone.getToneName(openTone,",
"%7s \" % x, range(13)) print \" \" + \" \".join(flets) for key",
"= cls.getPos() if len(includes) > 0: for key in _pos.keys(): arr = _pos[key]",
"for i, tone in enumerate(arr): if tone not in includes.keys(): arr[i] = \"",
"[] for i in range(13): toneString = tone.getToneName(openTone, i) arr.append(toneString) _pos[stringIndex + 1]",
"\" \".join(flets) for key in sorted(_pos.keys()): tones = _pos[key] tones = map(lambda x:",
"= \"%2s(%3s)\" % (tone, includes[tone]) flets = map(lambda x: \" %7s \" %",
"in _pos.keys(): arr = _pos[key] for i, tone in enumerate(arr): if tone not",
"in enumerate(openTones): toneIndex = tone.getToneNumberByName(openTone) arr = [] for i in range(13): toneString",
"\"A\", \"E\"] tone = Tone() for stringIndex, openTone in enumerate(openTones): toneIndex = tone.getToneNumberByName(openTone)",
"x, range(13)) print \" \" + \" \".join(flets) for key in sorted(_pos.keys()): tones",
"arr = _pos[key] for i, tone in enumerate(arr): if tone not in includes.keys():",
"def getPos(cls): _pos = {} openTones = [\"E\", \"B\", \"G\", \"D\", \"A\", \"E\"]",
"dump(cls, includes): _pos = cls.getPos() if len(includes) > 0: for key in _pos.keys():",
"_pos[stringIndex + 1] = arr return _pos @classmethod def dump(cls, includes): _pos =",
"\" \" + \" \".join(flets) for key in sorted(_pos.keys()): tones = _pos[key] tones",
"map(lambda x: \" %7s \" % x, tones) print '%s弦: |%s|' % (key,",
"in sorted(_pos.keys()): tones = _pos[key] tones = map(lambda x: \" %7s \" %",
"not in includes.keys(): arr[i] = \" \" else: arr[i] = \"%2s(%3s)\" % (tone,",
"if tone not in includes.keys(): arr[i] = \" \" else: arr[i] = \"%2s(%3s)\"",
"(tone, includes[tone]) flets = map(lambda x: \" %7s \" % x, range(13)) print",
"0: for key in _pos.keys(): arr = _pos[key] for i, tone in enumerate(arr):",
"if len(includes) > 0: for key in _pos.keys(): arr = _pos[key] for i,",
"tone.getToneNumberByName(openTone) arr = [] for i in range(13): toneString = tone.getToneName(openTone, i) arr.append(toneString)",
"enumerate(arr): if tone not in includes.keys(): arr[i] = \" \" else: arr[i] =",
"= [] for i in range(13): toneString = tone.getToneName(openTone, i) arr.append(toneString) _pos[stringIndex +",
"i in range(13): toneString = tone.getToneName(openTone, i) arr.append(toneString) _pos[stringIndex + 1] = arr",
"= arr return _pos @classmethod def dump(cls, includes): _pos = cls.getPos() if len(includes)",
"key in sorted(_pos.keys()): tones = _pos[key] tones = map(lambda x: \" %7s \"",
"class Fingerboard: @classmethod def getPos(cls): _pos = {} openTones = [\"E\", \"B\", \"G\",",
"\"B\", \"G\", \"D\", \"A\", \"E\"] tone = Tone() for stringIndex, openTone in enumerate(openTones):",
"includes.keys(): arr[i] = \" \" else: arr[i] = \"%2s(%3s)\" % (tone, includes[tone]) flets",
"for key in sorted(_pos.keys()): tones = _pos[key] tones = map(lambda x: \" %7s",
"Fingerboard: @classmethod def getPos(cls): _pos = {} openTones = [\"E\", \"B\", \"G\", \"D\",",
"openTone in enumerate(openTones): toneIndex = tone.getToneNumberByName(openTone) arr = [] for i in range(13):",
"in range(13): toneString = tone.getToneName(openTone, i) arr.append(toneString) _pos[stringIndex + 1] = arr return",
"[\"E\", \"B\", \"G\", \"D\", \"A\", \"E\"] tone = Tone() for stringIndex, openTone in",
"map(lambda x: \" %7s \" % x, range(13)) print \" \" + \"",
"sorted(_pos.keys()): tones = _pos[key] tones = map(lambda x: \" %7s \" % x,",
"_pos.keys(): arr = _pos[key] for i, tone in enumerate(arr): if tone not in",
"getPos(cls): _pos = {} openTones = [\"E\", \"B\", \"G\", \"D\", \"A\", \"E\"] tone",
"tones = map(lambda x: \" %7s \" % x, tones) print '%s弦: |%s|'",
"stringIndex, openTone in enumerate(openTones): toneIndex = tone.getToneNumberByName(openTone) arr = [] for i in",
"_pos = {} openTones = [\"E\", \"B\", \"G\", \"D\", \"A\", \"E\"] tone =",
"\"G\", \"D\", \"A\", \"E\"] tone = Tone() for stringIndex, openTone in enumerate(openTones): toneIndex",
"in includes.keys(): arr[i] = \" \" else: arr[i] = \"%2s(%3s)\" % (tone, includes[tone])",
"toneString = tone.getToneName(openTone, i) arr.append(toneString) _pos[stringIndex + 1] = arr return _pos @classmethod",
"\" else: arr[i] = \"%2s(%3s)\" % (tone, includes[tone]) flets = map(lambda x: \"",
"range(13): toneString = tone.getToneName(openTone, i) arr.append(toneString) _pos[stringIndex + 1] = arr return _pos",
"% x, range(13)) print \" \" + \" \".join(flets) for key in sorted(_pos.keys()):",
"\".join(flets) for key in sorted(_pos.keys()): tones = _pos[key] tones = map(lambda x: \"",
"= {} openTones = [\"E\", \"B\", \"G\", \"D\", \"A\", \"E\"] tone = Tone()",
"% (tone, includes[tone]) flets = map(lambda x: \" %7s \" % x, range(13))",
"x: \" %7s \" % x, tones) print '%s弦: |%s|' % (key, \"|\".join(tones))",
"tone in enumerate(arr): if tone not in includes.keys(): arr[i] = \" \" else:",
"arr[i] = \"%2s(%3s)\" % (tone, includes[tone]) flets = map(lambda x: \" %7s \"",
"arr return _pos @classmethod def dump(cls, includes): _pos = cls.getPos() if len(includes) >",
"tone not in includes.keys(): arr[i] = \" \" else: arr[i] = \"%2s(%3s)\" %",
"\" + \" \".join(flets) for key in sorted(_pos.keys()): tones = _pos[key] tones =",
"_pos = cls.getPos() if len(includes) > 0: for key in _pos.keys(): arr =",
"flets = map(lambda x: \" %7s \" % x, range(13)) print \" \"",
"x: \" %7s \" % x, range(13)) print \" \" + \" \".join(flets)",
"coding: UTF-8 from tone import Tone class Fingerboard: @classmethod def getPos(cls): _pos =",
"\" \" else: arr[i] = \"%2s(%3s)\" % (tone, includes[tone]) flets = map(lambda x:",
"+ 1] = arr return _pos @classmethod def dump(cls, includes): _pos = cls.getPos()",
"= \" \" else: arr[i] = \"%2s(%3s)\" % (tone, includes[tone]) flets = map(lambda",
"= map(lambda x: \" %7s \" % x, tones) print '%s弦: |%s|' %",
"includes[tone]) flets = map(lambda x: \" %7s \" % x, range(13)) print \"",
"Tone() for stringIndex, openTone in enumerate(openTones): toneIndex = tone.getToneNumberByName(openTone) arr = [] for",
"arr[i] = \" \" else: arr[i] = \"%2s(%3s)\" % (tone, includes[tone]) flets =",
"else: arr[i] = \"%2s(%3s)\" % (tone, includes[tone]) flets = map(lambda x: \" %7s",
"import Tone class Fingerboard: @classmethod def getPos(cls): _pos = {} openTones = [\"E\",",
"UTF-8 from tone import Tone class Fingerboard: @classmethod def getPos(cls): _pos = {}",
"for stringIndex, openTone in enumerate(openTones): toneIndex = tone.getToneNumberByName(openTone) arr = [] for i",
"openTones = [\"E\", \"B\", \"G\", \"D\", \"A\", \"E\"] tone = Tone() for stringIndex,",
"{} openTones = [\"E\", \"B\", \"G\", \"D\", \"A\", \"E\"] tone = Tone() for",
"@classmethod def dump(cls, includes): _pos = cls.getPos() if len(includes) > 0: for key",
"= Tone() for stringIndex, openTone in enumerate(openTones): toneIndex = tone.getToneNumberByName(openTone) arr = []",
"\"%2s(%3s)\" % (tone, includes[tone]) flets = map(lambda x: \" %7s \" % x,",
"= _pos[key] for i, tone in enumerate(arr): if tone not in includes.keys(): arr[i]",
"_pos[key] tones = map(lambda x: \" %7s \" % x, tones) print '%s弦:",
"= [\"E\", \"B\", \"G\", \"D\", \"A\", \"E\"] tone = Tone() for stringIndex, openTone",
"enumerate(openTones): toneIndex = tone.getToneNumberByName(openTone) arr = [] for i in range(13): toneString =",
"= tone.getToneNumberByName(openTone) arr = [] for i in range(13): toneString = tone.getToneName(openTone, i)",
"print \" \" + \" \".join(flets) for key in sorted(_pos.keys()): tones = _pos[key]",
"includes): _pos = cls.getPos() if len(includes) > 0: for key in _pos.keys(): arr",
"@classmethod def getPos(cls): _pos = {} openTones = [\"E\", \"B\", \"G\", \"D\", \"A\",",
"= tone.getToneName(openTone, i) arr.append(toneString) _pos[stringIndex + 1] = arr return _pos @classmethod def",
"tone.getToneName(openTone, i) arr.append(toneString) _pos[stringIndex + 1] = arr return _pos @classmethod def dump(cls,",
"key in _pos.keys(): arr = _pos[key] for i, tone in enumerate(arr): if tone",
"for key in _pos.keys(): arr = _pos[key] for i, tone in enumerate(arr): if",
"\" % x, range(13)) print \" \" + \" \".join(flets) for key in",
"Tone class Fingerboard: @classmethod def getPos(cls): _pos = {} openTones = [\"E\", \"B\",",
"i) arr.append(toneString) _pos[stringIndex + 1] = arr return _pos @classmethod def dump(cls, includes):",
"cls.getPos() if len(includes) > 0: for key in _pos.keys(): arr = _pos[key] for",
"_pos @classmethod def dump(cls, includes): _pos = cls.getPos() if len(includes) > 0: for",
"range(13)) print \" \" + \" \".join(flets) for key in sorted(_pos.keys()): tones =",
"\"D\", \"A\", \"E\"] tone = Tone() for stringIndex, openTone in enumerate(openTones): toneIndex =",
"= map(lambda x: \" %7s \" % x, range(13)) print \" \" +",
"tones = _pos[key] tones = map(lambda x: \" %7s \" % x, tones)",
"for i in range(13): toneString = tone.getToneName(openTone, i) arr.append(toneString) _pos[stringIndex + 1] =",
"arr = [] for i in range(13): toneString = tone.getToneName(openTone, i) arr.append(toneString) _pos[stringIndex",
"len(includes) > 0: for key in _pos.keys(): arr = _pos[key] for i, tone",
"\" %7s \" % x, range(13)) print \" \" + \" \".join(flets) for",
"return _pos @classmethod def dump(cls, includes): _pos = cls.getPos() if len(includes) > 0:",
"# coding: UTF-8 from tone import Tone class Fingerboard: @classmethod def getPos(cls): _pos",
"+ \" \".join(flets) for key in sorted(_pos.keys()): tones = _pos[key] tones = map(lambda",
"> 0: for key in _pos.keys(): arr = _pos[key] for i, tone in",
"in enumerate(arr): if tone not in includes.keys(): arr[i] = \" \" else: arr[i]",
"tone import Tone class Fingerboard: @classmethod def getPos(cls): _pos = {} openTones ="
] |
[
"Model.\"\"\" from masoniteorm.models import Model class Account(Model): \"\"\"Account Model.\"\"\" __fillable__ = ['email', 'access_token',",
"class Account(Model): \"\"\"Account Model.\"\"\" __fillable__ = ['email', 'access_token', 'scopes', 'type', 'valid', 'user_id', 'provider',",
"__fillable__ = ['email', 'access_token', 'scopes', 'type', 'valid', 'user_id', 'provider', 'nylas_account_id'] __auth__ = 'email'",
"Model.\"\"\" __fillable__ = ['email', 'access_token', 'scopes', 'type', 'valid', 'user_id', 'provider', 'nylas_account_id'] __auth__ =",
"import Model class Account(Model): \"\"\"Account Model.\"\"\" __fillable__ = ['email', 'access_token', 'scopes', 'type', 'valid',",
"Model class Account(Model): \"\"\"Account Model.\"\"\" __fillable__ = ['email', 'access_token', 'scopes', 'type', 'valid', 'user_id',",
"from masoniteorm.models import Model class Account(Model): \"\"\"Account Model.\"\"\" __fillable__ = ['email', 'access_token', 'scopes',",
"\"\"\"Account Model.\"\"\" from masoniteorm.models import Model class Account(Model): \"\"\"Account Model.\"\"\" __fillable__ = ['email',",
"masoniteorm.models import Model class Account(Model): \"\"\"Account Model.\"\"\" __fillable__ = ['email', 'access_token', 'scopes', 'type',",
"Account(Model): \"\"\"Account Model.\"\"\" __fillable__ = ['email', 'access_token', 'scopes', 'type', 'valid', 'user_id', 'provider', 'nylas_account_id']",
"\"\"\"Account Model.\"\"\" __fillable__ = ['email', 'access_token', 'scopes', 'type', 'valid', 'user_id', 'provider', 'nylas_account_id'] __auth__"
] |
[
"== cluster)[0] idx2 = np.where(clusters['Cluster'] != cluster)[0] # Plot background points if show_background:",
"libplot.new_ax(fig, rows, cols, i + 1) expr_plot(tsne, exp, ax=ax, cmap=cmap, colorbar=False) # if",
"of the background # # x = tsne.iloc[idx1, 0] # y = tsne.iloc[idx1,",
"= kneighbors_graph(c, 5, mode='distance', metric='euclidean').toarray() G = nx.from_numpy_matrix(A) pos = nx.spring_layout(G) fig, ax",
"# #a = im_data[:, :, 3] # # # Non transparent areas are",
"#skimage.io.imsave('tmp_canny_{}.png'.format(bin), edges1) # # im2 = Image.fromarray(im_data) # # im_no_gray, im_smooth = smooth_edges(im1,",
"\"\"\" # each column is a cell reads_per_bc = data.sum(axis=0) # int(np.round(np.median(reads_per_bc))) median_reads_per_bc",
"barcode_indices): return GeneBCMatrix(gbm.gene_ids, gbm.gene_names, gbm.barcodes[barcode_indices], gbm.matrix[:, barcode_indices]) def get_expression(gbm, gene_name, genes=None): if genes",
":] expr_plot(tsne_bin, exp_bin, cmap=cmap, s=s, colorbar=colorbar, norm=norm, alpha=alpha, linewidth=linewidth, edgecolors=edgecolors, ax=ax) tmp =",
"color=colors[i]) # libplot.invisible_axes(ax) # # #set_tsne_ax_lim(tsne, ax) # # return fig # #",
"= '{}_expr.pdf'.format(method) fig, ax = expr_plot(tsne, exp, dim=dim, cmap=cmap, marker=marker, s=s, alpha=alpha, fig=fig,",
"gbm.gene_names, gbm.barcodes, tpm) def create_cluster_plots(pca, labels, name, marker='o', s=MARKER_SIZE): for i in range(0,",
"name, method='tsne', format='png', dir='.', w=16, h=16, legend=True): sc = sample_clusters(clusters, sample_names) create_cluster_plot(tsne_umi_log2, sc,",
"a cell reads_per_bc = data.sum(axis=0) scaling_factors = 1000000 / reads_per_bc scaled = data.multiply(scaling_factors)",
"imagelib.smooth_edges(im_no_bg) # imagelib.paste(im_no_bg, im_smooth, inplace=True) # imagelib.save(im_no_bg, 'smooth.png') # imagelib.paste(im_base, im_no_bg, inplace=True) im",
"if isinstance(g, np.ndarray): idx = np.where(np.isin(ids, g))[0] if idx.size < 1: # if",
"# # #print(c1) # # ax.scatter(x[i], # y[i], # c=[c1], # s=s, #",
"x = tsne_other.iloc[:, 0] y = tsne_other.iloc[:, 1] libplot.scatter(x, y, c=[background], ax=ax, edgecolors='none',",
"binnumber = binned_statistic(exp, exp, bins=bins) print(binnumber.min(), binnumber.max()) iw = w * 300 im_base",
"pc2=(j + 1), marker=marker, s=s) def pca_base_plots(pca, clusters, n=10, marker='o', s=MARKER_SIZE): rows =",
"# im2 = Image.fromarray(im_data) # # im_no_gray, im_smooth = smooth_edges(im1, im1) # #",
"representation of data. Parameters ---------- data : Pandas dataframe features x dimensions, e.g.",
": Pandas dataframe Cells x tsne tsne data. Columns should be labeled 'TSNE-1',",
"names \"\"\" exp = get_gene_data(data, gene) return expr_plot(tsne, exp, fig=fig, ax=ax, cmap=cmap, out=out)",
"highlight cluster # im_base.paste(im2, (0, 0), im2) # break imagelib.save(im_base, out) def cluster_plot(tsne,",
"int(np.ceil(n / cols)) w = size * cols h = size * rows",
"return fig, ax def pca_plot(pca, clusters, pc1=1, pc2=2, marker='o', labels=False, s=MARKER_SIZE, w=8, h=8,",
"exp, bins=bins) print(binnumber.min(), binnumber.max()) iw = w * 300 im_base = imagelib.new(iw, iw)",
"inplace=True) df.to_csv('{}_cluster_overlaps.txt'.format(name), sep='\\t') def mkdir(path): \"\"\" Make dirs including any parents and avoid",
"\"\"\" ids = list(sorted(set(clusters['Cluster']))) indices = np.array(list(range(0, len(ids)))) if colors is None: colors",
"gene names Returns ------- list list of tuples of (index, gene_id, gene_name) \"\"\"",
"get_gene_data(data, gene_id, ids=ids, gene_names=gene_names) ax = libplot.new_ax(fig, rows, cols, i + 1) expr_plot(tsne,",
"name, colors=None, size=SUBPLOT_SIZE, dir='.'): # \"\"\" # Plot separate clusters colored by sample",
"0] d2 = tsne.iloc[:, 1] xlim = [d1[d1 < 0].quantile(1 - TNSE_AX_Q), d1[d1",
"np.append(xp, xp[0]) yp = np.append(yp, yp[0]) ax.plot(xp, yp, 'k-') #ax.plot(points[hull.vertices[0], 0], points[hull.vertices[[0, -1]],",
"axis If ax is a supplied argument, return this, otherwise create a new",
"titles to plots w: int, optional width of new ax. h: int, optional",
"g in genes: indexes = np.where(ids == g)[0] if indexes.size > 0: for",
"-1: new_label = 100 labels[np.where(labels == -1)] = new_label labels += 1 libtsne.write_clusters(headers,",
"sparse') return d.log2(add=1) else: return (d + 1).apply(np.log2) def umi_tpm_log2(data): d = umi_tpm(data)",
"im2.save('edges.png', 'png') # overlay edges on top of original image to highlight cluster",
"= im_data[:, :, 3] # # # Non transparent areas are edges #",
"#im_base.paste(im2, (0, 0), im2) imagelib.save(im_base, out) def avg_expr(data, tsne, genes, cid, clusters, prefix='',",
"alpha=alpha, linewidth=linewidth, edgecolors=edgecolors, ax=ax) tmp = 'tmp{}.png'.format(bin) libplot.savefig(fig, tmp, pad=0) plt.close(fig) im =",
"create_cluster_plot(tsne_a, c_a, 'a', dir='a') create_cluster_grid(tsne_a, c_a, 'a', dir='a') create_merge_cluster_info(d_a, c_a, 'a', sample_names=samples, dir='a')",
"import libtsne import seaborn as sns from libsparse.libsparse import SparseDataFrame from lib10x.sample import",
"tsne_b = libtsne.load_pca_tsne(pca_b, 'b', cache=cache) c_b = libtsne.load_phenograph_clusters(pca_b, 'b', cache=cache) create_pca_plot(pca_b, c_b, 'b',",
"not cache: print('{} was not found, creating it with...'.format(file)) # Find the interesting",
":] > 0)[0] ids2 = np.where(a2[i, :] > 0)[0] ids3 = np.intersect1d(ids1, ids2)",
"First dimension being plotted (usually 1) d2 : int, optional Second dimension being",
"= libtsne.get_cluster_file(name) if not os.path.isfile(file) or not cache: print('{} was not found, creating",
"mask # im_data = np.array(im1.convert('RGBA')) # # r = im_data[:, :, 0] #",
"# def network(tsne, clusters, name, k=5): # A = kneighbors_graph(tsne, k, mode='distance', metric='euclidean').toarray()",
"mode='distance', metric='euclidean').toarray() a2 = kneighbors_graph(c2, k, mode='distance', metric='euclidean').toarray() overlaps = [] for i",
"if colorbar: libplot.add_colorbar(fig, cmap, norm=norm) #libcluster.format_simple_axes(ax, title=t) if not show_axes: libplot.invisible_axes(ax) return fig,",
"# exp, # d1=1, # d2=2, # x1=None, # x2=None, # cmap=BLUE_YELLOW_CMAP, #",
"Columns should be labeled 'TSNE-1', 'TSNE-2' etc cluster : int Clusters in colors",
"# # x = tsne.iloc[idx1, 0] # y = tsne.iloc[idx1, 1] # #",
"2D data # \"\"\" # # fig, ax = expr_plot(tsne, # exp, #",
"exp, dim=dim, s=s, marker=marker, edgecolors=edgecolors, linewidth=linewidth, alpha=alpha, cmap=cmap, norm=norm, w=w, h=h, ax=ax) #",
"'C' # else: # prefix = '' # # ax.set_title('{}{} ({:,})'.format(prefix, cluster, len(idx1)),",
"= {'show': True, 'cols': 4, 'markerscale': 2} CLUSTER_101_COLOR = (0.3, 0.3, 0.3) np.random.seed(0)",
"label=None, fig=None, ax=None): \"\"\" Create a tsne plot without the formatting \"\"\" if",
"1] # libplot.scatter(x, y, c=BACKGROUND_SAMPLE_COLOR, ax=ax) # # # Plot cluster over the",
"with a Cluster column giving each cell a cluster label. s : int,",
"imagelib.open(tmp) im_no_bg = imagelib.remove_background(im) im_edges = imagelib.edges(im_no_bg) im_smooth = imagelib.smooth(im_edges) im_outline = imagelib.paste(im_no_bg,",
"x1) & (d < x2))[0] x = x[idx] y = y[idx] points =",
"dataframe (dense) Parameters ---------- gbm : a GeneBCMatrix Returns ------- object : Pandas",
"exp : numpy array expression values for each data point so it must",
"(d.max(axis=1) - m) #scaled = std * (max - min) + min #",
"< 255) & (g > 200) & (b < 255) & (b >",
"'#2ca05a', '#ffd42a']) # BGY_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list('bgy', ['#002255', '#003380', '#2ca05a', '#ffd42a', '#ffdd55']) # BGY_CMAP",
"+ 1) # idx1 = np.where((clusters['Cluster'] == c) & clusters.index.str.contains(id))[0] # # x",
"= expr_plot(tsne, exp, dim=dim, cmap=cmap, marker=marker, s=s, alpha=alpha, fig=fig, w=w, h=h, ax=ax, show_axes=show_axes,",
"else: return pd.DataFrame(MinMaxScaler(feature_range=(min, max)).fit_transform(d.T).T, index=d.index, columns=d.columns) def rscale(d, min=0, max=1, axis=1): if axis",
"= CLUSTER_101_COLOR else: color = 'black' fig, ax = separate_cluster(tsne, clusters, cluster, color=color,",
"get_gene_names(data) print(ids, gene_names, genes) gene_ids = get_gene_ids(data, genes, ids=ids, gene_names=gene_names) print(gene_ids) for i",
"dict): color = colors.get(cluster, 'black') elif isinstance(colors, list): #i = cluster - 1",
"{}'.format(l)) # idx2 = np.where(clusters['Cluster'] != c)[0] # # # Plot background points",
"1 #nx.draw_networkx(G, pos=pos, with_labels=False, ax=ax, node_size=200, node_color=node_color, vmax=(c.shape[0] - 1), cmap=libcluster.colormap()) nx.draw_networkx(G, with_labels=True,",
"'black') elif isinstance(colors, list): #i = cluster - 1 if i < len(colors):",
"show_axes=show_axes, fig=fig, ax=ax) #libtsne.tsne_legend(ax, labels, colors) #libcluster.format_simple_axes(ax, title=\"t-SNE\") #libcluster.format_legend(ax, cols=6, markerscale=2) if out",
"['#002255', '#003380', '#2ca05a', '#ffd42a', '#ffdd55']) BGY_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list( 'bgy', ['#003366', '#004d99', '#40bf80', '#ffe066',",
"2] # # print(tmp, r.shape) # # grey_areas = (r < 255) &",
"# # #r = data[:, :, 0] # #g = data[:, :, 1]",
"scaled def umi_log2(d): if isinstance(d, SparseDataFrame): print('UMI norm log2 sparse') return d.log2(add=1) else:",
"= node.read() # for node in f.walk_nodes('/matrix', 'Array'): # dsets[node.name] = node.read() print(dsets)",
"(b < 255) & (b > 200) # # d = im_data[np.where(grey_areas)] #",
"h=4, s=30, alpha=ALPHA, linewidth=EDGE_WIDTH, edgecolors='none', colorbar=True, method='tsne', format='png'): \"\"\" Plot multiple genes on",
"isinstance(max, float) or isinstance(max, int): print('z max', max) sd[np.where(sd > max)] = max",
"clusters, pc1=1, pc2=2, marker='o', labels=False, s=MARKER_SIZE, w=8, h=8, legend=True, fig=None, ax=None): fig, ax",
"= np.array([[p1, p2] for p1, p2 in zip(x, y)]) hull = ConvexHull(points) #x1",
"libplot.new_fig(w=w, h=h) ids = list(sorted(set(clusters['Cluster']))) for i in range(0, len(ids)): l = ids[i]",
"name, dim1=0, dim2=1, method='tsne', markers='o', s=libplot.MARKER_SIZE, w=8, h=8, colors=None, legend=True, sort=True, show_axes=False, ax=None,",
"should be rendered Returns ------- fig : Matplotlib figure A new Matplotlib figure",
"ax=ax) #libtsne.tsne_legend(ax, labels, colors) #libcluster.format_simple_axes(ax, title=\"t-SNE\") #libcluster.format_legend(ax, cols=6, markerscale=2) if out is not",
"the first idx = idx[0] else: # if id does not exist, try",
"& (d < x2))[0] x = x[idx] y = y[idx] points = np.array([[p1,",
"ax = libplot.newfig(w=10, h=10) # # nx.draw_networkx(G, pos=pos, with_labels=False, ax=ax, node_size=50, node_color=node_color, vmax=(clusters['Cluster'].max()",
"cells by sample/batch. \"\"\" sc = np.array(['' for i in range(0, d.shape[0])], dtype=object)",
"gene) exp = get_gene_data(data, gene_id, ids=ids, gene_names=gene_names) bin_means, bin_edges, binnumber = binned_statistic(exp, exp,",
"a supplied argument, return this, otherwise create a new axis and attach to",
"colors = libcluster.get_colors() if ax is None: fig, ax = libplot.new_fig(w=w, h=h) ids",
"\"\"\" if type(x) is int: l = x elif type(x) is list: l",
"float (0, 1), optional Tranparency of markers. show_axes : bool, optional, default true",
"c.shape[0])) node_color = libcluster.colors()[0:c.shape[0]] cmap = libcluster.colormap() labels = {} for i in",
"list): # color = colors[i] # else: # color = 'black' # #",
"size=w, s=s, linewidth=linewidth, add_titles=False, show_background=False) ax.set_xlim(xlim) ax.set_ylim(ylim) if not show_axes: libplot.invisible_axes(ax) legend_params =",
"#'#4d4d4d' EDGE_WIDTH = 0 # 0.25 ALPHA = 0.9 BLUE_YELLOW_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list( 'blue_yellow',",
"optional Supply an axis object on which to render the plot, otherwise a",
"kind='cubic') # fy = interp1d(points[hull.vertices, 1], points[hull.vertices, 0], kind='cubic') # # xt =",
"data.index ids = genes return ids.values, genes.values def get_gene_ids(data, genes, ids=None, gene_names=None): \"\"\"",
"be normalized Returns ------- fig : matplotlib figure If fig is a supplied",
"= 'black' ax = libplot.new_ax(fig, subplot=(rows, cols, pc)) separate_cluster(tsne, clusters, cluster, color=color, add_titles=add_titles,",
"silhouette_samples( tsne, clusters.iloc[:, 0].tolist(), metric='euclidean') x2 = silhouette_samples( tsne_umi_log2, clusters.iloc[:, 0].tolist(), metric='euclidean') fig,",
"['#e6e6e6', '#0055d4', '#00aa44', '#ffe066']) OR_RED_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list( 'or_red', matplotlib.cm.OrRd(range(4, 256))) BU_PU_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list(",
"* (max - min) + min # return scaled if axis == 0:",
"= int(l / cols) + 2 if l % cols == 0: #",
"im2) im1.save(out, 'png') def genes_expr_outline(data, tsne, genes, prefix='', index=None, dir='GeneExp', cmap=BGY_CMAP, norm=None, w=6,",
"columns=d.columns) else: return pd.DataFrame(RobustScaler().fit_transform(d.T).T, index=d.index, columns=d.columns) def umi_norm_log2_scale(data, clip=None): d = umi_norm_log2(data) return",
"ax def pca_plot(pca, clusters, pc1=1, pc2=2, marker='o', labels=False, s=MARKER_SIZE, w=8, h=8, legend=True, fig=None,",
"clusters.iloc[:, 0].tolist( ), 'Label': np.repeat('tsne-ah', len(x2))}) libplot.boxplot(df2, 'Cluster', 'Silhouette Score', colors=libcluster.colors(), ax=ax) ax.set_ylim([-1,",
"kneighbors_graph from scipy.interpolate import griddata import h5py from scipy.interpolate import interp1d from scipy.spatial",
"len(cluster_order)): print('index', i, cluster_order[i]) cluster = cluster_order[i] if isinstance(colors, dict): color = colors[cluster]",
"a new axis and attach to figure before returning. \"\"\" if ax is",
"marker='o', s=MARKER_SIZE, alpha=1, edgecolors=EDGE_COLOR, linewidth=EDGE_WIDTH, w=libplot.DEFAULT_WIDTH, h=libplot.DEFAULT_HEIGHT, show_axes=False, fig=None, ax=None, norm=None, colorbar=False): #",
"f['matrix']['features']['id']] feature_names = [x.decode('ascii', 'ignore') for x in f['matrix']['features']['name']] barcodes = list(f['matrix']['barcodes'][:]) matrix",
": int, optional Second dimension being plotted (usually 2) fig : matplotlib figure,",
"sep='\\t', header=0, index_col=0) def silhouette(tsne, tsne_umi_log2, clusters, name): # measure cluster worth x1",
"default true Whether to show axes on plot legend : bool, optional, default",
"= y[idx] #centroid = [x.sum() / x.size, y.sum() / y.size] centroid = [(x",
"libcluster import libtsne import seaborn as sns from libsparse.libsparse import SparseDataFrame from lib10x.sample",
"cmap=BLUE_GREEN_YELLOW_CMAP, w=w, h=h, dir='a/GeneExp', format=format) fig, ax = cluster_plot(tsne_a, c_a, legend=False, w=w, h=h)",
"int Clusters in colors : list, color Colors of points add_titles : bool",
"# np.where(clusters['Cluster'] == cluster)[0]] color = colors[i] else: color = 'black' else: color",
"(r == b) & (g == b) black_areas = (a > 0) d",
"clip=True) #cmap = plt.cm.plasma ids, gene_names = get_gene_names(data) print(ids, gene_names, genes) gene_ids =",
"s=MARKER_SIZE, alpha=EXP_ALPHA, fig=None, ax=None, norm=None): # plt.cm.plasma): out = 'pca_expr_{}_t{}_vs_t{}.pdf'.format(name, 1, 2) fig,",
"indexes = np.where(gene_names == g)[0] for index in indexes: ret.append((index, ids[index], gene_names[index])) return",
"names Returns ------- list list of tuples of (index, gene_id, gene_name) \"\"\" if",
"= tsne.iloc[idx2, 0] # y = tsne.iloc[idx2, 1] # libplot.scatter(x, y, c=BACKGROUND_SAMPLE_COLOR, ax=ax)",
"sep=sep, header=True, index=True) def sum(gbm, axis=0): return gbm.matrix.sum(axis=axis) def tpm(gbm): m = gbm.matrix",
"['#162d50', '#214478', '#217844', '#ffcc00', '#ffdd55']) # BGY_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list('bgy', ['#002255', '#2ca05a', '#ffd42a']) #",
"'barcodes', 'matrix']) def get_matrix_from_h5_v2(filename, genome): with h5py.File(filename, 'r') as f: if u'version' in",
"= cluster_order[i] if isinstance(colors, dict): color = colors[cluster] elif isinstance(colors, list): if cluster",
"genes.values def get_gene_ids(data, genes, ids=None, gene_names=None): \"\"\" For a given gene list, get",
"if index is None: index = data.index if isinstance(genes, pd.core.frame.DataFrame): genes = genes['Genes'].values",
"'{}_sep_clust_{}_c{}.{}'.format(type, name, cluster, format) print('Creating', out, '...') libplot.savefig(fig, out) libplot.savefig(fig, 'tmp.png') plt.close(fig) def",
"3] # (r < 255) | (g < 255) | (b < 255)",
"(b < 255) #(r > 0) & (r == g) & (r ==",
"= libplot.new_ax(fig, rows, cols, i + 1) expr_plot(tsne, exp, ax=ax, cmap=cmap, colorbar=False) #",
"print(type(d)) return umi_log2(d) def scale(d, clip=None, min=None, max=None, axis=1): if isinstance(d, SparseDataFrame): print('UMI",
"- m) #scaled = std * (max - min) + min # return",
"y] for x, y in zip(x1, y1)]) #hull = ConvexHull(points) #ax.plot(points[hull.vertices,0], points[hull.vertices,1]) #zi",
"pca.shape[1]): for j in range(i + 1, pca.shape[1]): create_cluster_plot(pca, labels, name, pc1=( i",
"legend=True, s=MARKER_SIZE, w=8, h=8, fig=None, ax=None, dir='.', format='png'): out = '{}/pca_{}_pc{}_vs_pc{}.{}'.format(dir, name, pc1,",
"create_cluster_plot(d, clusters, name, dim1=0, dim2=1, method='tsne', markers='o', s=libplot.MARKER_SIZE, w=8, h=8, colors=None, legend=True, sort=True,",
"if dir[-1] == '/': dir = dir[:-1] if not os.path.exists(dir): mkdir(dir) if index",
"colors=colors, edgecolors=edgecolors, linewidth=linewidth, markers=markers, alpha=alpha, s=s, ax=ax, cluster_order=cluster_order, sort=sort) #set_tsne_ax_lim(tsne, ax) # libcluster.format_axes(ax)",
"tsne.iloc[idx1, 1] # # if isinstance(colors, dict): # color = colors[cluster] # elif",
"cache=True): file = libtsne.get_cluster_file(name) if not os.path.isfile(file) or not cache: print('{} was not",
"np.where(counts.columns.isin(a_barcodes['Barcode'].values))[0] d_a = counts.iloc[:, idx] d_a = libcluster.remove_empty_rows(d_a) if isinstance(d_a, SparseDataFrame): d_a =",
"sklearn.preprocessing from sklearn.preprocessing import StandardScaler from sklearn.preprocessing import RobustScaler from sklearn.preprocessing import MinMaxScaler",
"edgecolors=EDGE_COLOR, linewidth=EDGE_WIDTH, dim1=0, dim2=1, w=8, alpha=ALPHA, # libplot.ALPHA, show_axes=True, legend=True, sort=True, outline=True): cluster_order",
"gene_id) exp = get_gene_data(data, gene_id, ids=ids, gene_names=gene_names) ax = libplot.new_ax(fig, rows, cols, i",
"# color = 'black' # # libplot.scatter(x, y, c=color, ax=ax) # # if",
"# # Parameters # ---------- # data : pandas.DataFrame # t-sne 2D data",
"vmax=3, clip=True) #cmap = plt.cm.plasma ids, gene_names = get_gene_names(data) exp = get_gene_data(data, genes,",
"nx.draw_networkx(G, pos=pos, with_labels=False, ax=ax, node_size=50, node_color=node_color, vmax=(clusters['Cluster'].max() - 1), cmap=libcluster.colormap()) # # libplot.savefig(fig,",
"fig=fig, ax=ax) #libtsne.tsne_legend(ax, labels, colors) libcluster.format_simple_axes(ax, title=\"PC\") if legend: libcluster.format_legend(ax, cols=6, markerscale=2) return",
"= imagelib.open(tmp) # im_no_bg = imagelib.remove_background(im) # im_smooth = imagelib.smooth_edges(im_no_bg) # imagelib.paste(im_no_bg, im_smooth,",
"the gene names indexes = np.where(gene_names == g)[0] for index in indexes: ret.append((index,",
"data['{}-{}'.format(t, d2)][idx] e = exp[idx] # if (e.min() == 0): #print('Data does not",
"h=h, s=s, colorbar=colorbar, norm=norm, alpha=alpha, linewidth=linewidth, edgecolors=edgecolors) if gene_id != gene: out =",
"norm=norm) libplot.savefig(fig, out) plt.close(fig) return fig, ax def expr_grid_size(x, size=SUBPLOT_SIZE): \"\"\" Auto size",
"= colors[i] else: color = 'black' else: color = 'black' fig, ax =",
"OR_RED_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list( 'or_red', matplotlib.cm.OrRd(range(4, 256))) BU_PU_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list( 'bu_pu', matplotlib.cm.BuPu(range(4, 256))) #",
"marker=marker, legend=legend, s=s, w=w, h=h, fig=fig, ax=ax) libplot.savefig(fig, out, pad=2) plt.close(fig) def set_tsne_ax_lim(tsne,",
"if id exists, pick the first idx = idx[0] else: # if id",
"- 1 cluster = ids[i] # look up index for color purposes #i",
"# id = '-{}'.format(sid + 1) # idx1 = np.where((clusters['Cluster'] == c) &",
"range(0, n): for j in range(i + 1, n): ax = libplot.new_ax(fig, subplot=(rows,",
"= 10 SUBPLOT_SIZE = 4 EXP_ALPHA = 0.8 # '#f2f2f2' #(0.98, 0.98, 0.98)",
"s=s, ax=ax) si += 1 return fig def pca_plot_base(pca, clusters, pc1=1, pc2=2, marker='o',",
"genes on a grid. Parameters ---------- data : Pandas dataframe Genes x samples",
"= libcluster.colors() return [colors[clusters['Cluster'][i] - 1] for i in range(0, clusters.shape[0])] # def",
"new_label = 100 labels[np.where(labels == -1)] = new_label labels += 1 libtsne.write_clusters(headers, labels,",
"matplotlib.colors.LinearSegmentedColormap.from_list('bgy', ['#002255', '#2ca05a', '#ffd42a']) # BGY_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list('bgy', ['#002255', '#003380', '#2ca05a', '#ffd42a', '#ffdd55'])",
"# , axis=1) return scaled def umi_norm_log2(data): d = umi_norm(data) print(type(d)) return umi_log2(d)",
"tsne.iloc[idx2, 0] y = tsne.iloc[idx2, 1] libplot.scatter(x, y, c=[background], ax=ax, edgecolors='none', # bgedgecolor,",
"what is left (the clusters) imageWithEdges = im1.filter(ImageFilter.FIND_EDGES) im_data = np.array(imageWithEdges.convert('RGBA')) #r =",
"idx.size > 0: idx = idx[0] else: return None if isinstance(data, SparseDataFrame): return",
"are tsne dimensions exp : numpy array expression values for each data point",
"---------- data : Pandas dataframe Matrix of umi counts \"\"\" # each column",
"= colors[i] else: color = 'black' else: color = 'black' ax = libplot.new_ax(fig,",
"matrix) def save_matrix_to_h5(gbm, filename, genome): flt = tables.Filters(complevel=1) with tables.open_file(filename, 'w', filters=flt) as",
"'{}_silhouette.pdf'.format(name)) def node_color_from_cluster(clusters): colors = libcluster.colors() return [colors[clusters['Cluster'][i] - 1] for i in",
"a = im_data[:, :, 3] # (r < 255) | (g < 255)",
"on top of original image to highlight cluster #im_base.paste(im2, (0, 0), im2) imagelib.save(im_base,",
"len(cids)): # c = cids[i] # # #print('Label {}'.format(l)) # idx2 = np.where(clusters['Cluster']",
"it must have the same number of elements as data has rows. d1",
"return SparseDataFrame(sd.T, index=d.index, columns=d.columns) else: # StandardScaler().fit_transform(d.T) sd = sklearn.preprocessing.scale(d, axis=axis) #sd =",
"of gene ids gene_names : Index, optional Index of gene names Returns -------",
"matplotlib.colors.LinearSegmentedColormap.from_list('bgy', ['#001a33', '#003366', '#339933', '#ffff66', '#ffff00']) # BGY_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list('bgy', ['#00264d', '#003366', '#339933',",
"= get_gene_data(data, gene) return expr_plot(tsne, exp, fig=fig, ax=ax, cmap=cmap, out=out) def separate_cluster(tsne, clusters,",
"def load_clusters(pca, headers, name, cache=True): file = libtsne.get_cluster_file(name) if not os.path.isfile(file) or not",
"colors = libcluster.colors() return [colors[clusters['Cluster'][i] - 1] for i in range(0, clusters.shape[0])] #",
"gene names.\" % gene_name) return gbm.matrix[gene_indices[0], :].toarray().squeeze() def gbm_to_df(gbm): return pd.DataFrame(gbm.matrix.todense(), index=gbm.gene_names, columns=gbm.barcodes)",
"if colorbar or is_first: if colorbar: libplot.add_colorbar(fig, cmap, norm=norm) #libcluster.format_simple_axes(ax, title=t) if not",
"= np.where(a1[i, :] > 0)[0] ids2 = np.where(a2[i, :] > 0)[0] ids3 =",
"indices: print('index', i) cluster = ids[i] if isinstance(colors, dict): color = colors[cluster] elif",
"min # return scaled if axis == 0: return pd.DataFrame(MinMaxScaler(feature_range=(min, max)).fit_transform(d), index=d.index, columns=d.columns)",
"< 1: # if id does not exist, try the gene names idx",
"100, endpoint=True) # yt = np.linspace(y.min(), y.max(), 100, endpoint=True) # # xp =",
"libcluster.format_axes(ax) if not show_axes: libplot.invisible_axes(ax) legend_params = dict(LEGEND_PARAMS) if isinstance(legend, bool): legend_params['show'] =",
"c='#ffffff00', # s=s, # marker=marker, # norm=norm, # edgecolors=[color], # linewidth=linewidth) #libcluster.format_axes(ax, title=t)",
"k, mode='distance', metric='euclidean').toarray() # # #A = A[0:500, 0:500] # # G=nx.from_numpy_matrix(A) #",
"= gbm.gene_names df.columns = gbm.barcodes return df def to_csv(gbm, file, sep='\\t'): df(gbm).to_csv(file, sep=sep,",
"= libcluster.colors()[0:c.shape[0]] cmap = libcluster.colormap() labels = {} for i in range(0, c.shape[0]):",
"clusters, markers=None, s=libplot.MARKER_SIZE, colors=None, edgecolors=EDGE_COLOR, linewidth=EDGE_WIDTH, dim1=0, dim2=1, w=8, h=8, alpha=ALPHA, # libplot.ALPHA,",
"gene names indexes = np.where(gene_names == g)[0] for index in indexes: ret.append((index, ids[index],",
"'black' fig, ax = separate_cluster(d, clusters, cluster, color=color, size=w, s=s, linewidth=linewidth, add_titles=False) #",
"y = df2.iloc[:, pc2 - 1] if i in colors: color = colors[i]",
"areas and mask # im_data = np.array(im1.convert('RGBA')) # # r = im_data[:, :,",
"= np.where(np.isin(ids, g))[0] if idx.size < 1: # if id does not exist,",
"# if i == 0: # libcluster.format_axes(ax) # else: # libplot.invisible_axes(ax) ax.set_title('{} ({})'.format(gene_ids[i][2],",
"colors=colors, cols=cols, size=size, add_titles=add_titles, cluster_order=cluster_order) if out is None: out = '{}/{}_{}_separate_clusters.png'.format(dir, method,",
"ax is None: fig, ax = libplot.new_fig() libplot.scatter(tsne['TSNE-1'], tsne['TSNE-2'], c=c, marker=marker, label=label, s=s,",
"Image, ImageFilter from scipy.stats import binned_statistic import imagelib TNSE_AX_Q = 0.999 MARKER_SIZE =",
"'#ffd42a']) # BGY_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list('bgy', ['#003380', '#5fd38d', '#ffd42a']) EXP_NORM = matplotlib.colors.Normalize(-1, 3, clip=True)",
"ax.set_title('tsne-ah') libplot.savefig(fig, '{}_silhouette.pdf'.format(name)) def node_color_from_cluster(clusters): colors = libcluster.colors() return [colors[clusters['Cluster'][i] - 1] for",
"separately to highlight samples # # Parameters # ---------- # tsne : Pandas",
"format='pdf'): \"\"\" Split cells into a and b \"\"\" cache = True counts",
"{}'.format(l)) idx1 = np.where(clusters['Cluster'] == cluster)[0] idx2 = np.where(clusters['Cluster'] != cluster)[0] # Plot",
"libplot.savefig(fig, 'tmp.png', pad=0) libplot.savefig(fig, out, pad=0) plt.close(fig) im1 = Image.open('tmp.png') # Edge detect",
"= expr_plot(tsne, # exp, # t='TSNE', # d1=d1, # d2=d2, # x1=x1, #",
"# (r < 255) | (g < 255) | (b < 255) #(r",
"< len(colors): # np.where(clusters['Cluster'] == cluster)[0]] color = colors[i] else: color = CLUSTER_101_COLOR",
"= gene_ids[i][2] print(gene_id, gene) exp = get_gene_data(data, gene_id, ids=ids, gene_names=gene_names) bin_means, bin_edges, binnumber",
"# \"\"\" # Plot separate clusters colored by sample # \"\"\" # fig",
"ax=ax) #libplot.add_colorbar(fig, cmap) fig, ax = expr_plot(tsne, exp, cmap=cmap, dim=dim, w=w, h=h, s=s,",
"BGY_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list('bgy', ['#0066ff', '#37c871', '#ffd42a']) # BGY_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list('bgy', ['#003380', '#5fd38d', '#ffd42a'])",
"clusters, pc1=1, pc2=2, marker='o', labels=False, s=MARKER_SIZE, w=8, h=8, fig=None, ax=None): colors = libcluster.get_colors()",
"base expression plot and adds a color bar. \"\"\" is_first = False if",
"'a', cache=cache) create_pca_plot(pca_a, c_a, 'a', dir='a') create_cluster_plot(tsne_a, c_a, 'a', dir='a') create_cluster_grid(tsne_a, c_a, 'a',",
"new axis and attach to figure before returning. \"\"\" if ax is None:",
"c_a, samples, 'a_sample', dir='a') genes_expr(d_a, tsne_a, genes, prefix='a_BGY', cmap=BLUE_GREEN_YELLOW_CMAP, w=w, h=h, dir='a/GeneExp', format=format)",
"and columns are tsne dimensions exp : numpy array expression values for each",
"strings of gene ids ids : Index, optional Index of gene ids gene_names",
"None: fig, ax = libplot.new_fig(size, size) #print('Label {}'.format(l)) idx1 = np.where(clusters['Cluster'] == cluster)[0]",
"cols=6, markerscale=2) return fig, ax def create_pca_plot(pca, clusters, name, pc1=1, pc2=2, marker='o', labels=False,",
"marker=marker, labels=labels, s=s, w=w, h=h, fig=fig, ax=ax) #libtsne.tsne_legend(ax, labels, colors) libcluster.format_simple_axes(ax, title=\"PC\") if",
"= imagelib.paste(im_no_bg, im_smooth) imagelib.paste(im_base, im_outline, inplace=True) # # find gray areas and mask",
"= x.shape[0] elif type(x) is pd.core.frame.DataFrame: l = x.shape[0] else: return None cols",
"dataframe n x 1 table of n cells with a Cluster column giving",
"ax=ax, cmap=cmap, colorbar=False) # if i == 0: # libcluster.format_axes(ax) # else: #",
"id gene_id = gene_ids[i][1] gene = gene_ids[i][2] print(gene, gene_id) exp = get_gene_data(data, gene_id,",
"fig=fig, # ax=ax, # norm=norm, # w=w, # h=h, # colorbar=colorbar) # #",
"ConvexHull from PIL import Image, ImageFilter from scipy.stats import binned_statistic import imagelib TNSE_AX_Q",
"to add titles to plots w: int, optional width of new ax. h:",
"cluster_order = np.array(list(range(0, len(ids)))) + 1 n = cluster_order.size if cols == -1:",
"prefix = 'C' else: prefix = '' ax.set_title('{}{} ({:,})'.format( prefix, cluster, len(idx1)), color=color)",
"is a supplied argument, return the supplied figure, otherwise a new figure is",
"where the samples are Parameters ---------- tsne : Pandas dataframe Cells x tsne",
"= color.copy() # c1[-1] = 0.5 # # #print(c1) # # ax.scatter(x[i], #",
"data.iloc[idx, :].values def gene_expr_grid(data, tsne, genes, cmap=None, size=SUBPLOT_SIZE): \"\"\" Plot multiple genes on",
":].values def gene_expr_grid(data, tsne, genes, cmap=None, size=SUBPLOT_SIZE): \"\"\" Plot multiple genes on a",
"= cluster_order.size if cols == -1: cols = int(np.ceil(np.sqrt(n))) rows = int(np.ceil(n /",
"for i in range(0, len(gene_ids)): # gene id gene_id = gene_ids[i][1] gene =",
"s=libplot.MARKER_SIZE, colors=None, w=8, h=8, legend=True, show_axes=False, sort=True, cluster_order=None, fig=None, ax=None, out=None): fig, ax",
"fig=None, ax=None, dir='.', format='png'): out = '{}/pca_{}_pc{}_vs_pc{}.{}'.format(dir, name, pc1, pc2, format) fig, ax",
"if norm is None: norm = libplot.NORM_3 # Sort by expression level so",
"if isinstance(min, float) or isinstance(min, int): print('z min', min) sd[np.where(sd < min)] =",
"array List of gene names \"\"\" if dir[-1] == '/': dir = dir[:-1]",
"are cells and columns are tsne dimensions exp : numpy array expression values",
"get_gene_ids(data, genes, ids=ids, gene_names=gene_names) print(gene_ids) for i in range(0, len(gene_ids)): gene_id = gene_ids[i][1]",
"# imagelib.save(im_no_bg, 'smooth.png') # imagelib.paste(im_base, im_no_bg, inplace=True) im = imagelib.open(tmp) if outline: im_no_bg",
"except tables.NoSuchNodeError: raise Exception(\"Genome %s does not exist in this file.\" % genome)",
"im_edges) # im_no_bg im_smooth = imagelib.smooth(im_outline) imagelib.save(im_smooth, 'smooth.png') # im_smooth imagelib.paste(im_base, im_smooth, inplace=True)",
"data. Columns should be labeled 'TSNE-1', 'TSNE-2' etc cluster : int Clusters in",
"!= cluster)[0] # # # Plot background points # # # # x",
"#zi = griddata((x, y), avg1, (xi, yi)) #ax.contour(xi, yi, z, levels=1) def gene_expr(data,",
"of original image to highlight cluster # enable if edges desired im1.paste(im2, (0,",
"#edgecolors, # linewidth=linewidth) # # # # mean = color.mean() # # #print(x[i],",
"= np.intersect1d(ids1, ids2) o = len(ids3) / 5 * 100 overlaps.append(o) df =",
"= separate_cluster(tsne, clusters, cluster, color=color, add_titles=add_titles, size=size) out = '{}_sep_clust_{}_c{}.{}'.format(type, name, cluster, format)",
": int Clusters in colors : list, color Colors of points add_titles :",
"bin_means, bin_edges, binnumber = binned_statistic(exp, exp, bins=bins) print(binnumber.min(), binnumber.max()) iw = w *",
"in range(i + 1, n): ax = libplot.new_ax(fig, subplot=(rows, rows, si)) pca_plot_base(pca, clusters,",
"None: index = data.index if isinstance(genes, pd.core.frame.DataFrame): genes = genes['Genes'].values if norm is",
"in genes: indexes = np.where(ids == g)[0] if indexes.size > 0: for index",
"(g == b) black_areas = (a > 0) d = im_data[np.where(black_areas)] d[:, 0:3]",
"colors) if isinstance(colors, dict): color = colors.get(cluster, 'black') elif isinstance(colors, list): #i =",
"== cid)[0] nx = 500 ny = 500 xi = np.linspace(x.min(), x.max(), nx)",
"# # #print(x[i], y[i], mean) # # #if mean > 0.5: # ax.scatter(x[i],",
"more required datasets.\") #GeneBCMatrix = collections.namedtuple('FeatureBCMatrix', ['feature_ids', 'feature_names', 'barcodes', 'matrix']) def get_matrix_from_h5_v2(filename, genome):",
"out=out) def base_tsne_plot(tsne, marker='o', s=libplot.MARKER_SIZE, c='red', label=None, fig=None, ax=None): \"\"\" Create a tsne",
"by this function.' % version) else: raise ValueError( 'Matrix HDF5 file format version",
": Pandas dataframe # Cells x tsne tsne data. Columns should be labeled",
"MARKER_SIZE = 10 SUBPLOT_SIZE = 4 EXP_ALPHA = 0.8 # '#f2f2f2' #(0.98, 0.98,",
"in indices: print('index', i) cluster = ids[i] if isinstance(colors, dict): color = colors[cluster]",
"= ax.get_xlim() ylim = ax.get_ylim() fig, ax = separate_cluster(d, clusters, cluster, color=color, size=w,",
"0) #(r < 255) | (g < 255) | (b < 255) #(r",
"int(l / cols) + 2 if l % cols == 0: # Assume",
"- 1).tolist() # # fig, ax = libplot.newfig(w=10, h=10) # # nx.draw_networkx(G, pos=pos,",
"is not None: # libplot.savefig(fig, out, pad=0) # # return fig, ax def",
"0], points[hull.vertices[[0, -1]], 1]) #points = np.array([[x, y] for x, y in zip(x1,",
"format version (%d) is an older version that is not supported by this",
"edgecolors='none', # bgedgecolor, linewidth=linewidth, s=s) # Plot cluster over the top of the",
"y.size] centroid = [(x * avg[idx]).sum() / avg[idx].sum(), (y * avg[idx]).sum() / avg[idx].sum()]",
"'#339933', '#ffff66', '#ffff00']) # BGY_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list('bgy', ['#00264d', '#003366', '#339933', '#e6e600', '#ffff33']) #",
"0: # if id exists, pick the first idx = idx[0] else: #",
"Auto size grid to look nice. \"\"\" if type(x) is int: l =",
"s=MARKER_SIZE, alpha=EXP_ALPHA, fig=None, ax=None, w=libplot.DEFAULT_WIDTH, h=libplot.DEFAULT_HEIGHT, edgecolors=EDGE_COLOR, linewidth=EDGE_WIDTH, norm=None, method='tsne', show_axes=False, colorbar=True, out=None):",
"1), cmap=libcluster.colormap()) # # libplot.savefig(fig, 'network_{}.pdf'.format(name)) def plot_centroids(tsne, clusters, name): c = centroids(tsne,",
"print(gene, gene_id) exp = get_gene_data(data, gene_id, ids=ids, gene_names=gene_names) ax = libplot.new_ax(fig, rows, cols,",
"for i in range(0, n): for j in range(i + 1, n): ax",
"print(ids, gene_names, genes) gene_ids = get_gene_ids(data, genes, ids=ids, gene_names=gene_names) print(gene_ids) for i in",
"create_tsne_cluster_sample_grid(tsne, clusters, samples, name, colors=None, size=SUBPLOT_SIZE, dir='.'): # \"\"\" # Plot separate clusters",
"cluster_order=None): \"\"\" Plot each cluster separately to highlight where the samples are Parameters",
"version (%d) is an older version that is not supported by this function.'",
"= (avg - avg.min()) / (avg.max() - avg.min()) # min_max_scale(avg) create_expr_plot(tsne, avg, cmap=cmap,",
"ret[i, 0] = centroid[0] ret[i, 1] = centroid[1] return ret def knn_method_overlaps(tsne1, tsne2,",
"= 'black' ax.scatter(x, y, color=color, edgecolor=color, s=s, marker=marker, alpha=libplot.ALPHA, label=label) if labels: l",
"is left (the clusters) # im_edges = im2.filter(ImageFilter.FIND_EDGES) # # im_smooth = im_edges.filter(ImageFilter.SMOOTH)",
"matplotlib.colors.LinearSegmentedColormap.from_list( 'bu_pu', matplotlib.cm.BuPu(range(4, 256))) # BGY_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list('bgy', ['#0066ff', '#37c871', '#ffd42a']) # BGY_CMAP",
"0: for index in indexes: ret.append((index, ids[index], gene_names[index])) else: # if id does",
"edgecolors='none', # edgecolors, linewidth=linewidth, s=s) if add_titles: if isinstance(cluster, int): prefix = 'C'",
"sklearn.preprocessing import StandardScaler from sklearn.preprocessing import RobustScaler from sklearn.preprocessing import MinMaxScaler from sklearn.metrics",
"= '{}/{}_{}_separate_clusters.png'.format(dir, method, name) libplot.savefig(fig, out, pad=0) #libplot.savefig(fig, '{}/tsne_{}separate_clusters.pdf'.format(dir, name)) # # #",
"= tsne.iloc[idx_other, :] fig, ax = libplot.new_fig(w, w) x = tsne_other.iloc[:, 0] y",
"Parameters # ---------- # data : pandas.DataFrame # t-sne 2D data # \"\"\"",
"f.create_group(f.root, genome) f.create_carray(group, 'genes', obj=gbm.gene_ids) f.create_carray(group, 'gene_names', obj=gbm.gene_names) f.create_carray(group, 'barcodes', obj=gbm.barcodes) f.create_carray(group, 'data',",
"= gbm.matrix s = 1 / m.sum(axis=0) mn = m.multiply(s) tpm = mn.multiply(1000000)",
"umi_norm_log2(d_a) else: d_a = umi_norm_log2_scale(d_a) pca_a = libtsne.load_pca(d_a, 'a', cache=cache) # pca.iloc[idx,:] tsne_a",
"im2.paste(im_smooth, (0, 0), im_smooth) # # im_base.paste(im2, (0, 0), im2) if gene_id !=",
"h=h, dir='a/GeneExp', format=format) fig, ax = cluster_plot(tsne_a, c_a, legend=False, w=w, h=h) libplot.savefig(fig, 'a/a_tsne_clusters_med.pdf')",
"which to render the plot, otherwise a new one is created. ax :",
"= expr_grid_size(gene_ids, size=size) fig = libplot.new_base_fig(w=w, h=h) for i in range(0, len(gene_ids)): #",
"List of gene names Returns ------- fig : Matplotlib figure A new Matplotlib",
"Whether to show legend. \"\"\" if ax is None: fig, ax = libplot.new_fig(w=w,",
"2] # #a = im_data[:, :, 3] # # # Non transparent areas",
"cluster # enable if edges desired im1.paste(im2, (0, 0), im2) im1.save(out, 'png') def",
"clusters.index.str.contains(id))[0] # # x = tsne.iloc[idx1, 0] # y = tsne.iloc[idx1, 1] #",
"labelling cells by sample/batch. \"\"\" sc = np.array(['' for i in range(0, d.shape[0])],",
"w=w, h=h, cluster_order=cluster_order, show_axes=show_axes, legend=legend, sort=sort, out=out) def base_tsne_plot(tsne, marker='o', s=libplot.MARKER_SIZE, c='red', label=None,",
"pc2 - 1] if i in colors: color = colors[i] # l] else:",
"# data['{}-{}'.format(t, d1)][idx] y = tsne.iloc[:, 1].values # data['{}-{}'.format(t, d2)][idx] idx = np.where(clusters['Cluster']",
"scaled = data.multiply(scaling_factors) # , axis=1) return scaled def umi_norm_log2(data): d = umi_norm(data)",
"> 0: # if id exists, pick the first idx = idx[0] else:",
"0.8 # '#f2f2f2' #(0.98, 0.98, 0.98) #(0.8, 0.8, 0.8) #(0.85, 0.85, 0.85 BACKGROUND_SAMPLE_COLOR",
"rows fig = libplot.new_base_fig(w=w, h=h) if colors is None: colors = libcluster.get_colors() #",
"linewidth=linewidth, markers=markers, alpha=alpha, s=s, ax=ax, cluster_order=cluster_order, sort=sort) #set_tsne_ax_lim(tsne, ax) # libcluster.format_axes(ax) if not",
"parents and avoid raising exception to work more like mkdir -p Parameters ----------",
"gene_id, ids=ids, gene_names=gene_names) bin_means, bin_edges, binnumber = binned_statistic(exp, exp, bins=bins) print(binnumber.min(), binnumber.max()) iw",
"pc2=2, marker='o', labels=False, s=MARKER_SIZE, w=8, h=8, legend=True, fig=None, ax=None): fig, ax = pca_plot_base(pca,",
"# # libplot.scatter(x, y, c=color, ax=ax) # # if add_titles: # if isinstance(cluster,",
"s=libplot.MARKER_SIZE, c='red', label=None, fig=None, ax=None): \"\"\" Create a tsne plot without the formatting",
"make the plot \"\"\" if type(genes) is pd.core.frame.DataFrame: genes = genes['Genes'].values ids, gene_names",
"return data[idx, :].to_array() else: return data.iloc[idx, :].values def gene_expr_grid(data, tsne, genes, cmap=None, size=SUBPLOT_SIZE):",
"# def expr_plot(tsne, # exp, # d1=1, # d2=2, # x1=None, # x2=None,",
"1], pca.iloc[i, pc2 - 1]) ax.text(pca.iloc[i, pc1 - 1], pca.iloc[i, pc2 - 1],",
"# color = colors[cluster] # elif isinstance(colors, list): # color = colors[i] #",
"255) & (r > 200) & (g < 255) & (g > 200)",
"legend=legend, sort=sort, show_axes=show_axes, fig=fig, ax=ax) #libtsne.tsne_legend(ax, labels, colors) #libcluster.format_simple_axes(ax, title=\"t-SNE\") #libcluster.format_legend(ax, cols=6, markerscale=2)",
"< len(colors): # colors[cid - 1] #colors[i] #np.where(clusters['Cluster'] == cluster)[0]] color = colors[i]",
"ax.set_title('{}{} ({:,})'.format( prefix, cluster, len(idx1)), color=color) ax.axis('off') # libplot.invisible_axes(ax) return fig, ax def",
"max)] = max return pd.DataFrame(sd, index=d.index, columns=d.columns) def min_max_scale(d, min=0, max=1, axis=1): #m",
"= data.sum(axis=0) scaling_factors = 1000000 / reads_per_bc scaled = data.multiply(scaling_factors) # , axis=1)",
"> 3] = 3 ax.scatter(x, y, c=e, s=s, marker=marker, alpha=alpha, cmap=cmap, norm=norm, edgecolors='none',",
"= libplot.newfig(w=5, h=5) ax.scatter(c[:, 0], c[:, 1], c=None) libplot.format_axes(ax) libplot.savefig(fig, '{}_centroids.pdf'.format(name)) def centroid_network(tsne,",
"'b', dir='b') create_cluster_grid(tsne_b, c_b, 'b', dir='b') create_merge_cluster_info(d_b, c_b, 'b', sample_names=samples, dir='b') create_cluster_samples(tsne_b, c_b,",
"'barcodes', 'matrix']) def decode(items): return np.array([x.decode('utf-8') for x in items]) def get_matrix_from_h5(filename, genome):",
"matplotlib.colors.LinearSegmentedColormap.from_list( 'bgy', ['#003366', '#004d99', '#40bf80', '#ffe066', '#ffd633']) GRAY_PURPLE_YELLOW_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list( 'grey_purple_yellow', ['#e6e6e6', '#3333ff',",
"return gbm.matrix.sum(axis=axis) def tpm(gbm): m = gbm.matrix s = 1 / m.sum(axis=0) mn",
"= 0.999 MARKER_SIZE = 10 SUBPLOT_SIZE = 4 EXP_ALPHA = 0.8 # '#f2f2f2'",
"SparseDataFrame from lib10x.sample import * from scipy.spatial import ConvexHull from PIL import Image,",
"cluster : int Clusters in colors : list, color Colors of points add_titles",
"Whether to add titles to plots plot_order: list, optional List of cluster ids",
"sample_names, name, method='tsne', format='png', dir='.', w=16, h=16, legend=True): sc = sample_clusters(clusters, sample_names) create_cluster_plot(tsne_umi_log2,",
"bool, optional, default true Whether to show axes on plot legend : bool,",
"def base_tsne_plot(tsne, marker='o', s=libplot.MARKER_SIZE, c='red', label=None, fig=None, ax=None): \"\"\" Create a tsne plot",
"not exist, try the gene names indexes = np.where(gene_names == g)[0] for index",
"1].values # data['{}-{}'.format(t, d2)][idx] e = exp[idx] # if (e.min() == 0): #print('Data",
"#b = data[:, :, 2] a = im_data[:, :, 3] # (r <",
"function.' % version) else: raise ValueError( 'Matrix HDF5 file format version (%d) is",
"if i in colors: color = colors[i] # l] else: color = 'black'",
"def save_matrix_to_h5(gbm, filename, genome): flt = tables.Filters(complevel=1) with tables.open_file(filename, 'w', filters=flt) as f:",
"libplot.new_base_fig(w=w, h=w) # # if colors is None: # colors = libcluster.colors() #",
"f.attrs['version'] > 2: raise ValueError( 'Matrix HDF5 file format version (%d) is an",
"size * rows # # fig = libplot.new_base_fig(w=w, h=w) # # if colors",
"= np.where(abs(z) < sdmax)[0] # (d > x1) & (d < x2))[0] x",
"libplot.add_colorbar(fig, cmap) return fig def genes_expr(data, tsne, genes, prefix='', dim=[1, 2], index=None, dir='GeneExp',",
"in range(0, d.shape[0])], dtype=object) c = 1 for s in sample_names: id =",
"= centroids(tsne1, clusters) c2 = centroids(tsne2, clusters) a1 = kneighbors_graph(c1, k, mode='distance', metric='euclidean').toarray()",
"= libtsne.load_phenograph_clusters(pca_b, 'b', cache=cache) create_pca_plot(pca_b, c_b, 'b', dir='b') create_cluster_plot(tsne_b, c_b, 'b', dir='b') create_cluster_grid(tsne_b,",
"pc2 - 1]) ax.text(pca.iloc[i, pc1 - 1], pca.iloc[i, pc2 - 1], pca.index[i]) return",
"else: genes = data.index ids = genes return ids.values, genes.values def get_gene_ids(data, genes,",
"e.g. rows are cells and columns are tsne dimensions exp : numpy array",
"render the plot, otherwise a new one is created. norm : Normalize, optional",
"= centroid[0] ret[i, 1] = centroid[1] return ret def knn_method_overlaps(tsne1, tsne2, clusters, name,",
"'gene_names', obj=gbm.gene_names) f.create_carray(group, 'barcodes', obj=gbm.barcodes) f.create_carray(group, 'data', obj=gbm.matrix.data) f.create_carray(group, 'indices', obj=gbm.matrix.indices) f.create_carray(group, 'indptr',",
"tsne_plot(tsne, marker='o', s=libplot.MARKER_SIZE, c='red', label=None, fig=None, ax=None): fig, ax = base_tsne_plot(tsne, marker=marker, c=c,",
"colorbar or is_first: if colorbar: libplot.add_colorbar(fig, cmap, norm=norm) #libcluster.format_simple_axes(ax, title=t) if not show_axes:",
"im_smooth imagelib.paste(im_base, im_smooth, inplace=True) else: imagelib.paste(im_base, im, inplace=True) # # find gray areas",
"= np.array(['' for i in range(0, d.shape[0])], dtype=object) c = 1 for s",
"(e - e.mean()) / e.std() #print(e.min(), e.max()) # z-score #e = (e -",
"range(0, pca.shape[0]): print(pca.shape, pca.iloc[i, pc1 - 1], pca.iloc[i, pc2 - 1]) ax.text(pca.iloc[i, pc1",
"detect on what is left (the clusters) imageWithEdges = im1.filter(ImageFilter.FIND_EDGES) im_data = np.array(imageWithEdges.convert('RGBA'))",
"df.to_csv('{}_cluster_overlaps.txt'.format(name), sep='\\t') def mkdir(path): \"\"\" Make dirs including any parents and avoid raising",
"h=5) ax.scatter(c[:, 0], c[:, 1], c=None) libplot.format_axes(ax) libplot.savefig(fig, '{}_centroids.pdf'.format(name)) def centroid_network(tsne, clusters, name):",
"libcluster.colormap() labels = {} for i in range(0, c.shape[0]): labels[i] = i +",
"({:,})'.format( prefix, cluster, len(idx1)), color=color) ax.axis('off') # libplot.invisible_axes(ax) return fig, ax def separate_clusters(tsne,",
"isinstance(legend, bool): legend_params['show'] = legend elif isinstance(legend, dict): legend_params.update(legend) else: pass if legend_params['show']:",
"imagelib.save(im_smooth, 'smooth.png') # im_smooth imagelib.paste(im_base, im_smooth, inplace=True) else: imagelib.paste(im_base, im, inplace=True) # #",
"5 * 100 overlaps.append(o) df = pd.DataFrame( {'Cluster': list(range(1, c1.shape[0] + 1)), 'Overlap",
"return None cols = int(np.ceil(np.sqrt(l))) w = size * cols rows = int(l",
"marker=marker, c=c, s=s, label=label, fig=fig, ax=ax) #libtsne.tsne_legend(ax, labels, colors) libcluster.format_simple_axes(ax, title=\"t-SNE\") libcluster.format_legend(ax, cols=6,",
"returning. \"\"\" if ax is None: fig, ax = libplot.new_fig(w=w, h=h) # if",
"(dense) Parameters ---------- gbm : a GeneBCMatrix Returns ------- object : Pandas DataFrame",
"plot ax : Matplotlib axes Axes used to render the figure \"\"\" if",
"fig = libplot.new_base_fig(w=w, h=h) if colors is None: colors = libcluster.get_colors() # Where",
"s=MARKER_SIZE, alpha=1, w=libplot.DEFAULT_WIDTH, h=libplot.DEFAULT_HEIGHT, fig=None, ax=None, norm=None): # plt.cm.plasma): \"\"\" Base function for",
"out = '{}/{}_expr_{}_{}.{}'.format(dir, method, gene, gene_id, format) else: out = '{}/{}_expr_{}.{}'.format(dir, method, gene,",
"gene_names=gene_names) w, h, rows, cols = expr_grid_size(gene_ids, size=size) fig = libplot.new_base_fig(w=w, h=h) for",
"= 'black' fig, ax = separate_cluster(tsne, clusters, cluster, color=color, add_titles=add_titles, size=size) out =",
"genes, ids=ids, gene_names=gene_names) print(gene_ids) for i in range(0, len(gene_ids)): gene_id = gene_ids[i][1] gene",
":, 2] # #a = im_data[:, :, 3] # # # Non transparent",
"Returns ------- fig : Matplotlib figure A new Matplotlib figure used to make",
"\"\"\" Create a tsne plot without the formatting Parameters ---------- d : Pandas",
"= '' # # ax.set_title('{}{} ({:,})'.format(prefix, cluster, len(idx1)), color=color) # # # libplot.invisible_axes(ax)",
"'#004d99', '#40bf80', '#ffe066', '#ffd633']) GRAY_PURPLE_YELLOW_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list( 'grey_purple_yellow', ['#e6e6e6', '#3333ff', '#ff33ff', '#ffe066']) GYBLGRYL_CMAP",
"if f.attrs['version'] > 2: raise ValueError( 'Matrix HDF5 file format version (%d) is",
"for s in sample_names: id = '-{}'.format(c) print(id) print(np.where(d.index.str.contains(id))[0]) sc[np.where(d.index.str.contains(id))[0]] = s c",
"method='tsne', show_axes=False, colorbar=True, out=None): # plt.cm.plasma): \"\"\" Creates and saves a presentation tsne",
"range(0, d.shape[0])], dtype=object) c = 1 for s in sample_names: id = '-{}'.format(c)",
"base_expr_plot(data, exp, t='PC', dim=dim, cmap=cmap, marker=marker, s=s, fig=fig, alpha=alpha, ax=ax, norm=norm) return fig,",
"# y = tsne.iloc[idx1, 1] # # if isinstance(colors, dict): # color =",
"exp, # d1=1, # d2=2, # x1=None, # x2=None, # cmap=BLUE_YELLOW_CMAP, # marker='o',",
"'png') # # im2.paste(im_smooth, (0, 0), im_smooth) # # im_base.paste(im2, (0, 0), im2)",
"== b) # # #d = im_data[np.where(black_areas)] # #d[:, 0:3] = [64, 64,",
"g))[0] if idx.size < 1: # if id does not exist, try the",
"create. \"\"\" try: os.makedirs(path) except: pass def split_a_b(counts, samples, w=6, h=6, format='pdf'): \"\"\"",
"name, dim=[1, 2], cmap=None, marker='o', s=MARKER_SIZE, alpha=EXP_ALPHA, fig=None, ax=None, norm=None): # plt.cm.plasma): out",
"tmp = 'tmp{}.png'.format(bin) libplot.savefig(fig, tmp, pad=0) plt.close(fig) im = imagelib.open(tmp) im_no_bg = imagelib.remove_background(im)",
"colorbar=False): # plt.cm.plasma): \"\"\" Creates a base expression plot and adds a color",
"imagelib.save(im_base, out) def cluster_plot(tsne, clusters, dim1=0, dim2=1, markers='o', s=libplot.MARKER_SIZE, colors=None, w=8, h=8, legend=True,",
"return fig, ax def create_expr_plot(tsne, exp, dim=[1, 2], cmap=None, marker='o', s=MARKER_SIZE, alpha=EXP_ALPHA, fig=None,",
"not None: # libplot.savefig(fig, out, pad=0) # # return fig, ax def create_expr_plot(tsne,",
"index is None: index = data.index if isinstance(genes, pd.core.frame.DataFrame): genes = genes['Genes'].values if",
"+ 1), pc2=(j + 1), marker=marker, s=s, ax=ax) si += 1 return fig",
"except KeyError: raise Exception(\"File is missing one or more required datasets.\") #GeneBCMatrix =",
"gene ids ids : Index, optional Index of gene ids gene_names : Index,",
"gene_id, format) else: out = '{}/{}_expr_{}.{}'.format(dir, method, gene, format) libplot.savefig(fig, 'tmp.png', pad=0) libplot.savefig(fig,",
"= i + 1 #nx.draw_networkx(G, pos=pos, with_labels=False, ax=ax, node_size=200, node_color=node_color, vmax=(c.shape[0] - 1),",
"= tsne.iloc[idx1, 0] y = tsne.iloc[idx1, 1] #print('sep', cluster, color) color = color",
"def expr_plot(tsne, # exp, # d1=1, # d2=2, # x1=None, # x2=None, #",
"= idx[0] else: return None if isinstance(data, SparseDataFrame): return data[idx, :].to_array() else: return",
"== -1: cols = int(np.ceil(np.sqrt(n))) rows = int(np.ceil(n / cols)) w = size",
"d im2 = Image.fromarray(im_data) im2.save('edges.png', 'png') # overlay edges on top of original",
"get_gene_ids(data, genes, ids=ids, gene_names=gene_names) for i in range(0, len(gene_ids)): gene_id = gene_ids[i][1] gene",
"tsne.iloc[idx_bin, :] expr_plot(tsne_bin, exp_bin, cmap=cmap, s=s, colorbar=colorbar, norm=norm, alpha=alpha, linewidth=linewidth, edgecolors=edgecolors, ax=ax) tmp",
"etc genes : array List of gene names \"\"\" exp = get_gene_data(data, gene)",
"libplot.invisible_axes(ax) return fig, ax def separate_clusters(tsne, clusters, name, colors=None, size=4, add_titles=True, type='tsne', format='pdf'):",
"ids=ids, gene_names=gene_names) bin_means, bin_edges, binnumber = binned_statistic(exp, exp, bins=bins) print(binnumber.min(), binnumber.max()) iw =",
"add_titles=True, size=4, alpha=ALPHA, s=MARKER_SIZE, edgecolors='white', linewidth=EDGE_WIDTH, fig=None, ax=None): \"\"\" Plot a cluster separately",
"marker=marker, # edgecolors='none', #edgecolors, # linewidth=linewidth) # # # # mean = color.mean()",
"return GeneBCMatrix(gbm.gene_ids, gbm.gene_names, gbm.barcodes[barcode_indices], gbm.matrix[:, barcode_indices]) def get_expression(gbm, gene_name, genes=None): if genes is",
"optional Marker size w : int, optional Plot width h : int, optional",
"fig # # # def create_tsne_cluster_sample_grid(tsne, clusters, samples, name, colors=None, size=SUBPLOT_SIZE, dir='.'): #",
"tsne_umi_log2, clusters.iloc[:, 0].tolist(), metric='euclidean') fig, ax = libplot.newfig(w=9, h=7, subplot=211) df = pd.DataFrame({'Silhouette",
"= libcluster.remove_empty_rows(d_a) if isinstance(d_a, SparseDataFrame): d_a = umi_norm_log2(d_a) else: d_a = umi_norm_log2_scale(d_a) pca_a",
"list list of tuples of (index, gene_id, gene_name) \"\"\" if ids is None:",
"on which to render the plot, otherwise a new one is created. ax",
"= exp[idx_bin] tsne_bin = tsne.iloc[idx_bin, :] expr_plot(tsne_bin, exp_bin, cmap=cmap, s=s, colorbar=colorbar, norm=norm, alpha=alpha,",
"from sklearn.metrics import silhouette_samples from sklearn.neighbors import kneighbors_graph from scipy.interpolate import griddata import",
"s = 1 / m.sum(axis=0) mn = m.multiply(s) tpm = mn.multiply(1000000) return GeneBCMatrix(gbm.gene_ids,",
"g)[0] if idx.size > 0: idx = idx[0] else: return None if isinstance(data,",
"libplot.savefig(fig, out) return fig, ax def create_cluster_plot(d, clusters, name, dim1=0, dim2=1, method='tsne', markers='o',",
"background # # x = tsne.iloc[idx1, 0] # y = tsne.iloc[idx1, 1] #",
"im_no_bg = imagelib.remove_background(im) im_edges = imagelib.edges(im_no_bg) im_smooth = imagelib.smooth(im_edges) im_outline = imagelib.paste(im_no_bg, im_smooth)",
"size=size, add_titles=add_titles, cluster_order=cluster_order) if out is None: out = '{}/{}_{}_separate_clusters.png'.format(dir, method, name) libplot.savefig(fig,",
"def umi_norm_log2_scale(data, clip=None): d = umi_norm_log2(data) return scale(d, clip=clip) def read_clusters(file): print('Reading clusters",
"0] #g = data[:, :, 1] #b = data[:, :, 2] a =",
"interp1d from scipy.spatial import distance import networkx as nx import os import phenograph",
"gbm.gene_names, gbm.barcodes[barcode_indices], gbm.matrix[:, barcode_indices]) def get_expression(gbm, gene_name, genes=None): if genes is None: genes",
"creating it with...'.format(file)) # Find the interesting clusters labels, graph, Q = phenograph.cluster(pca,",
"libplot.newfig(w=9, h=7, subplot=211) df = pd.DataFrame({'Silhouette Score': x1, 'Cluster': clusters.iloc[:, 0].tolist( ), 'Label':",
"for i in range(0, len(cids)): # c = cids[i] # # #print('Label {}'.format(l))",
"s=libplot.MARKER_SIZE, colors=None, edgecolors=EDGE_COLOR, linewidth=EDGE_WIDTH, dim1=0, dim2=1, w=8, alpha=ALPHA, # libplot.ALPHA, show_axes=True, legend=True, sort=True,",
":] = [255, 255, 255, 0] # im_data[np.where(grey_areas)] = d # # #",
"zip(x, y)]) sd = d.std() m = d.mean() print(m, sd) z = (d",
"a GeneBCMatrix to a pandas dataframe (dense) Parameters ---------- gbm : a GeneBCMatrix",
"any parents and avoid raising exception to work more like mkdir -p Parameters",
"plot, otherwise a new one is created. ax : matplotlib ax, optional Supply",
"BGY_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list('bgy', ['#003380', '#5fd38d', '#ffd42a']) EXP_NORM = matplotlib.colors.Normalize(-1, 3, clip=True) LEGEND_PARAMS =",
"m = gbm.matrix s = 1 / m.sum(axis=0) mn = m.multiply(s) tpm =",
"print(out) return cluster_plot(d, clusters, dim1=dim1, dim2=dim2, markers=markers, colors=colors, s=s, w=w, h=h, cluster_order=cluster_order, show_axes=show_axes,",
"d : Pandas dataframe t-sne, umap data clusters : Pandas dataframe n x",
"dir='.', format='png'): out = '{}/pca_{}_pc{}_vs_pc{}.{}'.format(dir, name, pc1, pc2, format) fig, ax = pca_plot(pca,",
"#d[:, 0:3] = [64, 64, 64] # #im_data[np.where(black_areas)] = d # # #im3",
"df = pd.DataFrame(gbm.matrix.todense()) df.index = gbm.gene_names df.columns = gbm.barcodes return df def to_csv(gbm,",
"m.sum(axis=0) mn = m.multiply(s) tpm = mn.multiply(1000000) return GeneBCMatrix(gbm.gene_ids, gbm.gene_names, gbm.barcodes, tpm) def",
"# # Edge detect on what is left (the clusters) # im_edges =",
"'b', dir='b') create_merge_cluster_info(d_b, c_b, 'b', sample_names=samples, dir='b') create_cluster_samples(tsne_b, c_b, samples, 'b_sample', dir='b') genes_expr(d_b,",
"int, optional Marker size w : int, optional Plot width h : int,",
"# c=[c1], # s=s, # marker=marker, # edgecolors='none', #edgecolors, # linewidth=linewidth) # #",
"edgecolors=edgecolors, linewidth=linewidth, alpha=alpha, cmap=cmap, norm=norm, w=w, h=h, ax=ax) # if colorbar or is_first:",
"w=8, h=8, colors=None, legend=True, sort=True, show_axes=False, ax=None, cluster_order=None, format='png', dir='.', out=None): if out",
"# # # Plot background points # # # # x = tsne.iloc[idx2,",
"collections import numpy as np import scipy.sparse as sp_sparse import tables import pandas",
"i in range(0, len(gene_ids)): # gene id gene_id = gene_ids[i][1] gene = gene_ids[i][2]",
"ax = base_tsne_plot(tsne, marker=marker, c=c, s=s, label=label, fig=fig, ax=ax) #libtsne.tsne_legend(ax, labels, colors) libcluster.format_simple_axes(ax,",
"im_edges.filter(ImageFilter.SMOOTH) # im_smooth.save('edges.png', 'png') # # im2.paste(im_smooth, (0, 0), im_smooth) # # im_base.paste(im2,",
"pc2=(j + 1), marker=marker, s=s, ax=ax) si += 1 return fig def pca_plot_base(pca,",
"dsets[node.name] = node.read() # for node in f.walk_nodes('/matrix', 'Array'): # dsets[node.name] = node.read()",
"index=None, dir='GeneExp', cmap=OR_RED_CMAP, # BGY_CMAP, norm=None, w=libplot.DEFAULT_WIDTH, h=libplot.DEFAULT_HEIGHT, alpha=1.0, colorbar=False, method='tsne', fig=None, ax=None,",
"# color = colors[i] # else: # color = 'black' # # libplot.scatter(x,",
"title=\"PC\") if legend: libcluster.format_legend(ax, cols=6, markerscale=2) return fig, ax def create_pca_plot(pca, clusters, name,",
"= np.where((clusters['Cluster'] == c) & clusters.index.str.contains(id))[0] # # x = tsne.iloc[idx1, 0] #",
"alpha=alpha, # fig=fig, # ax=ax, # norm=norm, # w=w, # h=h, # colorbar=colorbar)",
"genes : array List of gene names Returns ------- fig : Matplotlib figure",
"color = colors[i] # else: # color = 'black' # # libplot.scatter(x, y,",
"if isinstance(d, SparseDataFrame): print('UMI norm log2 sparse') return d.log2(add=1) else: return (d +",
"legend_params = dict(LEGEND_PARAMS) if isinstance(legend, bool): legend_params['show'] = legend elif isinstance(legend, dict): legend_params.update(legend)",
"0], kind='cubic') # # xt = np.linspace(x.min(), x.max(), 100, endpoint=True) # yt =",
"ax=None, out=None): fig, ax = base_cluster_plot(tsne, clusters, markers=markers, colors=colors, dim1=dim1, dim2=dim2, s=s, w=w,",
"'#ffcc00', '#ffdd55']) # BGY_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list('bgy', ['#002255', '#2ca05a', '#ffd42a']) # BGY_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list('bgy',",
"dimension being plotted (usually 1) d2 : int, optional Second dimension being plotted",
"optional, default true Whether to show legend. \"\"\" if ax is None: fig,",
"size=size) out = '{}_sep_clust_{}_c{}.{}'.format(type, name, cluster, format) print('Creating', out, '...') libplot.savefig(fig, out) libplot.savefig(fig,",
"top idx = np.argsort(exp) #np.argsort(abs(exp)) # np.argsort(exp) x = data.iloc[idx, dim[0] - 1].values",
"size) #print('Label {}'.format(l)) idx1 = np.where(clusters['Cluster'] == cluster)[0] idx2 = np.where(clusters['Cluster'] != cluster)[0]",
"pad=0) plt.close(fig) im1 = Image.open('tmp.png') # Edge detect on what is left (the",
"binned_statistic(exp, exp, bins=bins) print(binnumber.min(), binnumber.max()) iw = w * 300 im_base = imagelib.new(iw,",
"255, 0] # im_data[np.where(grey_areas)] = d # # # #edges1 = feature.canny(rgb2gray(im_data)) #",
"highlight cluster #im_base.paste(im2, (0, 0), im2) imagelib.save(im_base, out) def avg_expr(data, tsne, genes, cid,",
"def min_max_scale(d, min=0, max=1, axis=1): #m = d.min(axis=1) #std = (d - m)",
"background points if show_background: x = tsne.iloc[idx2, 0] y = tsne.iloc[idx2, 1] libplot.scatter(x,",
"ids = list(sorted(set(clusters['Cluster']))) for i in range(0, len(ids)): l = ids[i] #print('Label {}'.format(l))",
"#im3 = Image.fromarray(im_data) # #im2.save('edges.png', 'png') # # im_smooth = im_edges.filter(ImageFilter.SMOOTH) # im_smooth.save('edges.png',",
"imagelib.edges(im) im_outline = imagelib.paste(im, im_edges) # im_no_bg im_smooth = imagelib.smooth(im_outline) imagelib.save(im_smooth, 'smooth.png') #",
"names idx = np.where(gene_names == g)[0] if idx.size > 0: idx = idx[0]",
"cluster_plot(tsne, clusters, dim1=0, dim2=1, markers='o', s=libplot.MARKER_SIZE, colors=None, w=8, h=8, legend=True, show_axes=False, sort=True, cluster_order=None,",
"# xp = points[hull.vertices, 0] yp = points[hull.vertices, 1] xp = np.append(xp, xp[0])",
"# Plot cluster over the top of the background x = tsne.iloc[idx1, 0]",
"labels=False, s=MARKER_SIZE, w=8, h=8, legend=True, fig=None, ax=None): fig, ax = pca_plot_base(pca, clusters, pc1=pc1,",
"exist in this file.\" % genome) except KeyError: raise Exception(\"File is missing one",
"def set_tsne_ax_lim(tsne, ax): \"\"\" Set the t-SNE x,y limits to look pretty. \"\"\"",
"figure A new Matplotlib figure used to make the plot \"\"\" if type(genes)",
"silhouette_samples( tsne_umi_log2, clusters.iloc[:, 0].tolist(), metric='euclidean') fig, ax = libplot.newfig(w=9, h=7, subplot=211) df =",
"m) / (d.max(axis=1) - m) #scaled = std * (max - min) +",
"# yt = np.linspace(y.min(), y.max(), 100, endpoint=True) # # xp = points[hull.vertices, 0]",
"each cell a cluster label. s : int, optional Marker size w :",
"= libplot.new_fig() #expr_plot(tsne, exp, ax=ax) #libplot.add_colorbar(fig, cmap) exp_bin = exp[idx_bin] tsne_bin = tsne.iloc[idx_bin,",
"ax = libplot.new_fig(size, size) #print('Label {}'.format(l)) idx1 = np.where(clusters['Cluster'] == cluster)[0] idx2 =",
"= d.mean() print(m, sd) z = (d - m) / sd # find",
"= list(sorted(set(clusters['Cluster']))) # # rows = int(np.ceil(np.sqrt(len(cids)))) # # w = size *",
"is None: colors = libcluster.get_colors() # Where to plot figure pc = 1",
"outline=True): cluster_order = list(sorted(set(clusters['Cluster']))) im_base = imagelib.new(w * 300, w * 300) for",
"1], pca.iloc[i, pc2 - 1], pca.index[i]) return fig, ax def pca_plot(pca, clusters, pc1=1,",
"libplot.invisible_axes(ax) ax.set_title('{} ({})'.format(gene_ids[i][2], gene_ids[i][1])) libplot.add_colorbar(fig, cmap) return fig def genes_expr(data, tsne, genes, prefix='',",
"size * rows fig = libplot.new_base_fig(w=w, h=h) if colors is None: colors =",
"= False if ax is None: fig, ax = libplot.new_fig(w, h) is_first =",
"# # fig, ax = expr_plot(tsne, # exp, # t='TSNE', # d1=d1, #",
"'r') as f: if u'version' in f.attrs: if f.attrs['version'] > 2: raise ValueError(",
"over the top of the background # # x = tsne.iloc[idx1, 0] #",
"in sample_names: id = '-{}'.format(c) print(id) print(np.where(d.index.str.contains(id))[0]) sc[np.where(d.index.str.contains(id))[0]] = s c += 1",
"own plot file. \"\"\" ids = list(sorted(set(clusters['Cluster']))) indices = np.array(list(range(0, len(ids)))) if colors",
"return GeneBCMatrix(gbm.gene_ids, gbm.gene_names, gbm.barcodes, tpm) def create_cluster_plots(pca, labels, name, marker='o', s=MARKER_SIZE): for i",
"sample_names): \"\"\" Create a cluster matrix based on by labelling cells by sample/batch.",
"samples are Parameters ---------- tsne : Pandas dataframe Cells x tsne tsne data.",
"labeled 'TSNE-1', 'TSNE-2' etc genes : array List of gene names \"\"\" exp",
"1 h = size * rows return w, h, rows, cols def get_gene_names(data):",
"clusters, name): c = centroids(tsne, clusters) fig, ax = libplot.newfig(w=5, h=5) ax.scatter(c[:, 0],",
"2], cmap=None, marker='o', s=MARKER_SIZE, alpha=EXP_ALPHA, fig=None, ax=None, norm=None): # plt.cm.plasma): fig, ax =",
"si = 1 for i in range(0, n): for j in range(i +",
"exp.min() < 0: #norm = matplotlib.colors.Normalize(vmin=-3, vmax=3, clip=True) if norm is None: norm",
"d.log2(add=1) else: return (d + 1).apply(np.log2) def umi_tpm_log2(data): d = umi_tpm(data) return umi_log2(d)",
"Plot each cluster separately to highlight where the samples are Parameters ---------- tsne",
"supplied figure, otherwise a new figure is created and returned. ax : matplotlib",
"gene_names = get_gene_names(data) if isinstance(g, list): g = np.array(g) if isinstance(g, np.ndarray): idx",
"split_a_b(counts, samples, w=6, h=6, format='pdf'): \"\"\" Split cells into a and b \"\"\"",
"add_titles=add_titles, ax=ax) # idx1 = np.where(clusters['Cluster'] == cluster)[0] # idx2 = np.where(clusters['Cluster'] !=",
"for i in range(0, pca.shape[0]): print(pca.shape, pca.iloc[i, pc1 - 1], pca.iloc[i, pc2 -",
"network(tsne, clusters, name, k=5): # A = kneighbors_graph(tsne, k, mode='distance', metric='euclidean').toarray() # #",
"h) is_first = True base_expr_plot(data, exp, dim=dim, s=s, marker=marker, edgecolors=edgecolors, linewidth=linewidth, alpha=alpha, cmap=cmap,",
"y[i], # c=[c1], # s=s, # marker=marker, # edgecolors='none', #edgecolors, # linewidth=linewidth) #",
"a cell reads_per_bc = data.sum(axis=0) # int(np.round(np.median(reads_per_bc))) median_reads_per_bc = np.median(reads_per_bc) scaling_factors = median_reads_per_bc",
"'black' else: color = 'black' fig, ax = separate_cluster(d, clusters, cluster, color=color, size=w,",
"'#003366', '#339933', '#e6e600', '#ffff33']) # BGY_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list('bgy', ['#003366', '#40bf80', '#ffff33']) BGY_ORIG_CMAP =",
"tmp = 'tmp{}.png'.format(i) libplot.savefig(fig, tmp) plt.close(fig) # Open image # im = imagelib.open(tmp)",
"fig, ax = libplot.newfig(w=9, h=7, subplot=211) df = pd.DataFrame({'Silhouette Score': x1, 'Cluster': clusters.iloc[:,",
"containing and index genes : list List of strings of gene ids ids",
"set_tsne_ax_lim(tsne, ax) # # libplot.invisible_axes(ax) # # if out is not None: #",
"x elif type(x) is list: l = len(x) elif type(x) is np.ndarray: l",
"out is not None: libplot.savefig(fig, out) return fig, ax def create_cluster_plot(d, clusters, name,",
"= np.zeros((len(cids), 2)) for i in range(0, len(cids)): c = cids[i] x =",
"KeyError: raise Exception(\"File is missing one or more required datasets.\") #GeneBCMatrix = collections.namedtuple('FeatureBCMatrix',",
"fig, ax = base_expr_plot(data, exp, t='PC', dim=dim, cmap=cmap, marker=marker, s=s, fig=fig, alpha=alpha, ax=ax,",
"cell reads_per_bc = data.sum(axis=0) # int(np.round(np.median(reads_per_bc))) median_reads_per_bc = np.median(reads_per_bc) scaling_factors = median_reads_per_bc /",
"pad=0) plt.close(fig) im = imagelib.open(tmp) im_no_bg = imagelib.remove_background(im) im_edges = imagelib.edges(im_no_bg) im_smooth =",
"= gbm.barcodes return df def to_csv(gbm, file, sep='\\t'): df(gbm).to_csv(file, sep=sep, header=True, index=True) def",
"umi_norm_log2_scale(d_b) pca_b = libtsne.load_pca(d_b, 'b', cache=cache) # pca.iloc[idx_b,:] tsne_b = libtsne.load_pca_tsne(pca_b, 'b', cache=cache)",
"# find all points within 1 sd of centroid idx = np.where(abs(z) <",
"SparseDataFrame): print('UMI norm log2 sparse') return d.log2(add=1) else: return (d + 1).apply(np.log2) def",
"sd # find all points within 1 sd of centroid idx = np.where(abs(z)",
"data # \"\"\" # # fig, ax = expr_plot(tsne, # exp, # t='TSNE',",
"imagelib.new(w * 300, w * 300) for i in range(0, len(cluster_order)): print('index', i,",
"3, clip=True) LEGEND_PARAMS = {'show': True, 'cols': 4, 'markerscale': 2} CLUSTER_101_COLOR = (0.3,",
"directory to create. \"\"\" try: os.makedirs(path) except: pass def split_a_b(counts, samples, w=6, h=6,",
"= median_reads_per_bc / reads_per_bc scaled = data.multiply(scaling_factors) # , axis=1) return scaled def",
"else: # StandardScaler().fit_transform(d.T) sd = sklearn.preprocessing.scale(d, axis=axis) #sd = sd.T if isinstance(clip, float)",
"l = len(x) elif type(x) is np.ndarray: l = x.shape[0] elif type(x) is",
"dim1=dim1, dim2=dim2, markers=markers, colors=colors, s=s, w=w, h=h, cluster_order=cluster_order, show_axes=show_axes, legend=legend, sort=sort, out=out) def",
"as f: try: dsets = {} print(f.list_nodes('/')) for node in f.walk_nodes('/' + genome,",
"# grey_areas = (r < 255) & (r > 200) & (g <",
"fig, ax = separate_cluster(d, clusters, cluster, color=color, size=w, s=s, linewidth=linewidth, add_titles=False, show_background=False) ax.set_xlim(xlim)",
"0] # #g = data[:, :, 1] # #b = data[:, :, 2]",
"format='png'): \"\"\" Plot multiple genes on a grid. Parameters ---------- data : Pandas",
"libplot.new_fig(w, w) x = tsne_other.iloc[:, 0] y = tsne_other.iloc[:, 1] libplot.scatter(x, y, c=[background],",
"gene names Returns ------- fig : Matplotlib figure A new Matplotlib figure used",
"# marker=marker, # norm=norm, # edgecolors=[color], # linewidth=linewidth) #libcluster.format_axes(ax, title=t) return fig, ax",
"imagelib.paste(im_base, im_smooth, inplace=True) else: imagelib.paste(im_base, im, inplace=True) # # find gray areas and",
"shape=dsets['shape']) return GeneBCMatrix(decode(dsets['genes']), decode(dsets['gene_names']), decode(dsets['barcodes']), matrix) except tables.NoSuchNodeError: raise Exception(\"Genome %s does not",
"-3] = -3 #e[e > 3] = 3 ax.scatter(x, y, c=e, s=s, marker=marker,",
"ylim = [d2[d2 < 0].quantile(1 - TNSE_AX_Q), d2[d2 >= 0].quantile(TNSE_AX_Q)] #print(xlim, ylim) #",
"255, 255, 0] # im_data[np.where(grey_areas)] = d # # im2 = Image.fromarray(im_data) #",
"g) & (r == b) & (g == b) black_areas = (a >",
"# if add_titles: # if isinstance(cluster, int): # prefix = 'C' # else:",
"tpm) def create_cluster_plots(pca, labels, name, marker='o', s=MARKER_SIZE): for i in range(0, pca.shape[1]): for",
"\"\"\" Created on Wed Jun 6 16:51:15 2018 @author: antony \"\"\" import matplotlib",
"# im_data = np.array(im_edges.convert('RGBA')) # # #r = data[:, :, 0] # #g",
"= np.where(clusters['Cluster'] == cluster)[0] idx2 = np.where(clusters['Cluster'] != cluster)[0] # Plot background points",
"if cluster < len(colors): # np.where(clusters['Cluster'] == cluster)[0]] color = colors[i] else: color",
"genes_expr(d_b, tsne_b, genes, prefix='b_BGY', cmap=BLUE_GREEN_YELLOW_CMAP, w=w, h=h, dir='b/GeneExp', format=format) fig, ax = cluster_plot(tsne_b,",
": numpy array expression values for each data point so it must have",
"\"\"\" Split cells into a and b \"\"\" cache = True counts =",
"matplotlib.colors.LinearSegmentedColormap.from_list( 'blue_yellow', ['#162d50', '#ffdd55']) BLUE_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list( 'blue', ['#162d50', '#afc6e9']) BLUE_GREEN_YELLOW_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list(",
"/ cols) + 2 if l % cols == 0: # Assume we",
"gbm.matrix.sum(axis=axis) def tpm(gbm): m = gbm.matrix s = 1 / m.sum(axis=0) mn =",
"cmap=libcluster.colormap()) # # libplot.savefig(fig, 'network_{}.pdf'.format(name)) def plot_centroids(tsne, clusters, name): c = centroids(tsne, clusters)",
"show_background: x = tsne.iloc[idx2, 0] y = tsne.iloc[idx2, 1] libplot.scatter(x, y, c=[background], ax=ax,",
"saves a presentation tsne plot \"\"\" if out is None: out = '{}_expr.pdf'.format(method)",
"1] #print('sep', cluster, color) color = color # + '7f' libplot.scatter(x, y, c=color,",
"# # im2 = Image.fromarray(im_data) # # im_no_gray, im_smooth = smooth_edges(im1, im1) #",
"like mkdir -p Parameters ---------- path : str directory to create. \"\"\" try:",
"base_cluster_plot(tsne, clusters, markers=markers, colors=colors, dim1=dim1, dim2=dim2, s=s, w=w, h=h, cluster_order=cluster_order, legend=legend, sort=sort, show_axes=show_axes,",
"idx1 = np.where(clusters['Cluster'] == cluster)[0] idx2 = np.where(clusters['Cluster'] != cluster)[0] # Plot background",
"# x1=None, # x2=None, # cmap=BLUE_YELLOW_CMAP, # marker='o', # s=MARKER_SIZE, # alpha=EXP_ALPHA, #",
"dimensions, e.g. rows are cells and columns are tsne dimensions exp : numpy",
"format='pdf'): \"\"\" Plot each cluster into its own plot file. \"\"\" ids =",
"idx_other = np.where(binnumber != bi)[0] tsne_other = tsne.iloc[idx_other, :] fig, ax = libplot.new_fig(w,",
"% version) else: raise ValueError( 'Matrix HDF5 file format version (%d) is an",
"optional First dimension being plotted (usually 1) d2 : int, optional Second dimension",
"data.iloc[idx, dim[1] - 1].values # data['{}-{}'.format(t, d2)][idx] e = exp[idx] # if (e.min()",
"edgecolors=EDGE_COLOR, linewidth=EDGE_WIDTH, dim1=0, dim2=1, w=8, h=8, alpha=ALPHA, # libplot.ALPHA, show_axes=True, legend=True, sort=True, cluster_order=None,",
"cluster)[0] # Plot background points if show_background: x = tsne.iloc[idx2, 0] y =",
"b_barcodes = pd.read_csv('../b_barcodes.tsv', header=0, sep='\\t') idx = np.where(counts.columns.isin(b_barcodes['Barcode'].values))[0] d_b = counts.iloc[:, idx] d_b",
"fig=None, # ax=None, # norm=None, # w=libplot.DEFAULT_WIDTH, # h=libplot.DEFAULT_HEIGHT, # colorbar=True): #plt.cm.plasma): #",
"umi counts \"\"\" # each column is a cell reads_per_bc = data.sum(axis=0) #",
"a cluster matrix based on by labelling cells by sample/batch. \"\"\" sc =",
"try: group = f.create_group(f.root, genome) f.create_carray(group, 'genes', obj=gbm.gene_ids) f.create_carray(group, 'gene_names', obj=gbm.gene_names) f.create_carray(group, 'barcodes',",
"= libcluster.get_colors() if ax is None: fig, ax = libplot.new_fig(w=w, h=h) ids =",
"reads_per_bc = data.sum(axis=0) # int(np.round(np.median(reads_per_bc))) median_reads_per_bc = np.median(reads_per_bc) scaling_factors = median_reads_per_bc / reads_per_bc",
"gene_id = gene_ids[i][1] gene = gene_ids[i][2] print(gene, gene_id) exp = get_gene_data(data, gene_id, ids=ids,",
"y, c=color, ax=ax, edgecolors='none', # edgecolors, linewidth=linewidth, s=s) if add_titles: if isinstance(cluster, int):",
"separate_cluster(tsne, clusters, cluster, color=color, add_titles=add_titles, size=size) out = '{}_sep_clust_{}_c{}.{}'.format(type, name, cluster, format) print('Creating',",
"rows return w, h, rows, cols def get_gene_names(data): if ';' in data.index[0]: ids,",
"2} CLUSTER_101_COLOR = (0.3, 0.3, 0.3) np.random.seed(0) GeneBCMatrix = collections.namedtuple( 'GeneBCMatrix', ['gene_ids', 'gene_names',",
"h=h, ax=ax) # if colorbar or is_first: if colorbar: libplot.add_colorbar(fig, cmap, norm=norm) #libcluster.format_simple_axes(ax,",
"write H5 file.\") def subsample_matrix(gbm, barcode_indices): return GeneBCMatrix(gbm.gene_ids, gbm.gene_names, gbm.barcodes[barcode_indices], gbm.matrix[:, barcode_indices]) def",
"'smooth.png') # imagelib.paste(im_base, im_no_bg, inplace=True) im = imagelib.open(tmp) if outline: im_no_bg = imagelib.remove_background(im)",
"method='tsne', bins=10, background=BACKGROUND_SAMPLE_COLOR): \"\"\" Plot multiple genes on a grid. Parameters ---------- data",
"= im_data[np.where(grey_areas)] # d[:, :] = [255, 255, 255, 0] # im_data[np.where(grey_areas)] =",
"Create a tsne plot without the formatting Parameters ---------- d : Pandas dataframe",
"= data.index.str.split(';').str else: genes = data.index ids = genes return ids.values, genes.values def",
"samples, 'a_sample', dir='a') genes_expr(d_a, tsne_a, genes, prefix='a_BGY', cmap=BLUE_GREEN_YELLOW_CMAP, w=w, h=h, dir='a/GeneExp', format=format) fig,",
"f['matrix']['indptr']), shape=f['matrix']['shape']) return GeneBCMatrix(feature_ids, feature_names, decode(barcodes), matrix) def save_matrix_to_h5(gbm, filename, genome): flt =",
"(e - e.mean()) / e.std() # limit to 3 std for z-scores #e[e",
"#libplot.savefig(fig, '{}/tsne_{}separate_clusters.pdf'.format(dir, name)) # # def load_clusters(pca, headers, name, cache=True): file = libtsne.get_cluster_file(name)",
"dim=[1, 2], cmap=None, marker='o', s=MARKER_SIZE, alpha=EXP_ALPHA, fig=None, ax=None, w=libplot.DEFAULT_WIDTH, h=libplot.DEFAULT_HEIGHT, edgecolors=EDGE_COLOR, linewidth=EDGE_WIDTH, norm=None,",
"obj=gbm.gene_ids) f.create_carray(group, 'gene_names', obj=gbm.gene_names) f.create_carray(group, 'barcodes', obj=gbm.barcodes) f.create_carray(group, 'data', obj=gbm.matrix.data) f.create_carray(group, 'indices', obj=gbm.matrix.indices)",
"\"\"\" Plot each cluster separately to highlight where the samples are Parameters ----------",
"multiple genes on a grid. Parameters ---------- data : Pandas dataframe Genes x",
"clusters, sample_names, name, method='tsne', format='png', dir='.', w=16, h=16, legend=True): sc = sample_clusters(clusters, sample_names)",
"# # d = im_data[np.where(grey_areas)] # d[:, :] = [255, 255, 255, 0]",
"ylim = ax.get_ylim() fig, ax = separate_cluster(d, clusters, cluster, color=color, size=w, s=s, linewidth=linewidth,",
"sd of centroid idx = np.where(abs(z) < sdmax)[0] # (d > x1) &",
"x2))[0] x = x[idx] y = y[idx] points = np.array([[p1, p2] for p1,",
"is created. ax : matplotlib ax, optional Supply an axis object on which",
"# def create_tsne_cluster_sample_grid(tsne, clusters, samples, name, colors=None, size=SUBPLOT_SIZE, dir='.'): # \"\"\" # Plot",
"h=w) # # if colors is None: # colors = libcluster.colors() # #",
"out is not None: libplot.savefig(fig, out, pad=0) return fig, ax def base_pca_expr_plot(data, exp,",
"ax : matplotlib axis If ax is a supplied argument, return this, otherwise",
"columns=d.columns) else: # StandardScaler().fit_transform(d.T) sd = sklearn.preprocessing.scale(d, axis=axis) #sd = sd.T if isinstance(clip,",
"legend=legend, s=s, w=w, h=h, fig=fig, ax=ax) libplot.savefig(fig, out, pad=2) plt.close(fig) def set_tsne_ax_lim(tsne, ax):",
": Pandas dataframe n x 1 table of n cells with a Cluster",
"x = tsne.iloc[idx2, 0] y = tsne.iloc[idx2, 1] libplot.scatter(x, y, c=[background], ax=ax, edgecolors='none',",
"new Matplotlib figure used to make the plot # \"\"\" # # #",
"= pd.DataFrame({'Silhouette Score': x1, 'Cluster': clusters.iloc[:, 0].tolist( ), 'Label': np.repeat('tsne-10x', len(x1))}) libplot.boxplot(df, 'Cluster',",
"fig=fig, w=w, h=h, ax=ax, show_axes=show_axes, colorbar=colorbar, norm=norm, linewidth=linewidth, edgecolors=edgecolors) if out is not",
"numpy array expression values for each data point so it must have the",
"if ';' in data.index[0]: ids, genes = data.index.str.split(';').str else: genes = data.index ids",
"ax def create_expr_plot(tsne, exp, dim=[1, 2], cmap=None, marker='o', s=MARKER_SIZE, alpha=EXP_ALPHA, fig=None, ax=None, w=libplot.DEFAULT_WIDTH,",
"the samples are Parameters ---------- tsne : Pandas dataframe Cells x tsne tsne",
"colors should be normalized Returns ------- fig : matplotlib figure If fig is",
"if outline: im_no_bg = imagelib.remove_background(im) im_edges = imagelib.edges(im) im_outline = imagelib.paste(im, im_edges) #",
"plt.close(fig) return fig, ax def expr_grid_size(x, size=SUBPLOT_SIZE): \"\"\" Auto size grid to look",
"bins=10, background=BACKGROUND_SAMPLE_COLOR): \"\"\" Plot multiple genes on a grid. Parameters ---------- data :",
"axis=0): return gbm.matrix.sum(axis=axis) def tpm(gbm): m = gbm.matrix s = 1 / m.sum(axis=0)",
"# overlay edges on top of original image to highlight cluster # enable",
"== 0: raise Exception(\"%s was not found in list of gene names.\" %",
"name)) # # # def tsne_cluster_sample_grid(tsne, clusters, samples, colors=None, size=SUBPLOT_SIZE): # \"\"\" #",
"libplot.new_fig(size, size) #print('Label {}'.format(l)) idx1 = np.where(clusters['Cluster'] == cluster)[0] idx2 = np.where(clusters['Cluster'] !=",
"w=libplot.DEFAULT_WIDTH, h=libplot.DEFAULT_HEIGHT, fig=None, ax=None, norm=None): # plt.cm.plasma): \"\"\" Base function for creating an",
"library to its median size Parameters ---------- data : Pandas dataframe Matrix of",
"= gene_ids[i][1] gene = gene_ids[i][2] print(gene, gene_id) exp = get_gene_data(data, gene_id, ids=ids, gene_names=gene_names)",
"0].quantile(1 - TNSE_AX_Q), d1[d1 >= 0].quantile(TNSE_AX_Q)] ylim = [d2[d2 < 0].quantile(1 - TNSE_AX_Q),",
"-*- coding: utf-8 -*- \"\"\" Created on Wed Jun 6 16:51:15 2018 @author:",
"limits to look pretty. \"\"\" d1 = tsne.iloc[:, 0] d2 = tsne.iloc[:, 1]",
"to create. \"\"\" try: os.makedirs(path) except: pass def split_a_b(counts, samples, w=6, h=6, format='pdf'):",
"1] xp = np.append(xp, xp[0]) yp = np.append(yp, yp[0]) ax.plot(xp, yp, 'k-') #ax.plot(points[hull.vertices[0],",
"# # def create_tsne_cluster_sample_grid(tsne, clusters, samples, name, colors=None, size=SUBPLOT_SIZE, dir='.'): # \"\"\" #",
"y.max(), 100, endpoint=True) # # xp = points[hull.vertices, 0] yp = points[hull.vertices, 1]",
"sample_names: id = '-{}'.format(c) print(id) print(np.where(d.index.str.contains(id))[0]) sc[np.where(d.index.str.contains(id))[0]] = s c += 1 print(np.unique(d.index.values))",
"dict): legend_params.update(legend) else: pass if legend_params['show']: libcluster.format_legend(ax, cols=legend_params['cols'], markerscale=legend_params['markerscale']) return fig, ax def",
"tuples of (index, gene_id, gene_name) \"\"\" if ids is None: ids, gene_names =",
"t-SNE x,y limits to look pretty. \"\"\" d1 = tsne.iloc[:, 0] d2 =",
"be labeled 'TSNE-1', 'TSNE-2' etc # clusters : DataFrame # Clusters in #",
"tpm = mn.multiply(1000000) return GeneBCMatrix(gbm.gene_ids, gbm.gene_names, gbm.barcodes, tpm) def create_cluster_plots(pca, labels, name, marker='o',",
"rendered Returns ------- fig : Matplotlib figure A new Matplotlib figure used to",
"of elements as data has rows. d1 : int, optional First dimension being",
"tsne.iloc[:, 0] d2 = tsne.iloc[:, 1] xlim = [d1[d1 < 0].quantile(1 - TNSE_AX_Q),",
"'network_{}.pdf'.format(name)) def plot_centroids(tsne, clusters, name): c = centroids(tsne, clusters) fig, ax = libplot.newfig(w=5,",
"# # sid = 0 # # for sample in samples: # id",
"Parameters ---------- data : DataFrame data table containing and index genes : list",
"= umi_norm_log2(d_b) else: d_b = umi_norm_log2_scale(d_b) pca_b = libtsne.load_pca(d_b, 'b', cache=cache) # pca.iloc[idx_b,:]",
"im_smooth = im_edges.filter(ImageFilter.SMOOTH) # im_smooth.save('edges.png', 'png') # # im2.paste(im_smooth, (0, 0), im_smooth) #",
"in range(0, len(cids)): c = cids[i] x = tsne.iloc[np.where(clusters['Cluster'] == c)[0], :] centroid",
"np.intersect1d(ids1, ids2) o = len(ids3) / 5 * 100 overlaps.append(o) df = pd.DataFrame(",
"= libplot.new_fig(w=w, h=h) libcluster.scatter_clusters(d.iloc[:, dim1].values, d.iloc[:, dim2].values, clusters, colors=colors, edgecolors=edgecolors, linewidth=linewidth, markers=markers, alpha=alpha,",
"'TSNE-1', 'TSNE-2' etc # clusters : DataFrame # Clusters in # # Returns",
"the top of the background x = tsne.iloc[idx1, 0] y = tsne.iloc[idx1, 1]",
"ax=ax, # norm=norm, # w=w, # h=h, # colorbar=colorbar) # # set_tsne_ax_lim(tsne, ax)",
"size=SUBPLOT_SIZE): # \"\"\" # Plot each cluster separately to highlight samples # #",
"np.random.seed(0) GeneBCMatrix = collections.namedtuple( 'GeneBCMatrix', ['gene_ids', 'gene_names', 'barcodes', 'matrix']) def decode(items): return np.array([x.decode('utf-8')",
"features x dimensions, e.g. rows are cells and columns are tsne dimensions exp",
"dir='a') create_cluster_samples(tsne_a, c_a, samples, 'a_sample', dir='a') genes_expr(d_a, tsne_a, genes, prefix='a_BGY', cmap=BLUE_GREEN_YELLOW_CMAP, w=w, h=h,",
"Assume we will add a row for a color bar rows += 1",
"libtsne.load_phenograph_clusters(pca_a, 'a', cache=cache) create_pca_plot(pca_a, c_a, 'a', dir='a') create_cluster_plot(tsne_a, c_a, 'a', dir='a') create_cluster_grid(tsne_a, c_a,",
"len(ids)))) if colors is None: colors = libcluster.get_colors() for i in indices: print('index',",
"sd = StandardScaler(with_mean=False).fit_transform(d.T.matrix) return SparseDataFrame(sd.T, index=d.index, columns=d.columns) else: # StandardScaler().fit_transform(d.T) sd = sklearn.preprocessing.scale(d,",
"columns=d.columns) def umi_norm_log2_scale(data, clip=None): d = umi_norm_log2(data) return scale(d, clip=clip) def read_clusters(file): print('Reading",
"s=s) # Plot cluster over the top of the background x = tsne.iloc[idx1,",
"- TNSE_AX_Q), d2[d2 >= 0].quantile(TNSE_AX_Q)] #print(xlim, ylim) # ax.set_xlim(xlim) # ax.set_ylim(ylim) def base_cluster_plot(d,",
"being plotted (usually 1) d2 : int, optional Second dimension being plotted (usually",
"c_b, 'b', dir='b') create_cluster_plot(tsne_b, c_b, 'b', dir='b') create_cluster_grid(tsne_b, c_b, 'b', dir='b') create_merge_cluster_info(d_b, c_b,",
"ax.get_ylim() fig, ax = separate_cluster(d, clusters, cluster, color=color, size=w, s=s, linewidth=linewidth, add_titles=False, show_background=False)",
"add_titles=True, cluster_order=None): \"\"\" Plot each cluster separately to highlight where the samples are",
"pd.DataFrame(gbm.matrix.todense(), index=gbm.gene_names, columns=gbm.barcodes) def get_barcode_counts(gbm): ret = [] for i in range(len(gbm.barcodes)): ret.append(np.sum(gbm.matrix[:,",
"indexes: ret.append((index, ids[index], gene_names[index])) return ret def get_gene_data(data, g, ids=None, gene_names=None): if ids",
"import RobustScaler from sklearn.preprocessing import MinMaxScaler from sklearn.metrics import silhouette_samples from sklearn.neighbors import",
"# # if isinstance(colors, dict): # color = colors[cluster] # elif isinstance(colors, list):",
"> 200) & (g < 255) & (g > 200) & (b <",
"sample_clusters(d, sample_names): \"\"\" Create a cluster matrix based on by labelling cells by",
"Where to plot figure pc = 1 for c in cluster_order: i =",
"if norm is None and exp.min() < 0: #norm = matplotlib.colors.Normalize(vmin=-3, vmax=3, clip=True)",
"return scaled def umi_norm_log2(data): d = umi_norm(data) print(type(d)) return umi_log2(d) def scale(d, clip=None,",
"get_gene_names(data) exp = get_gene_data(data, genes, ids=ids, gene_names=gene_names) avg = exp.mean(axis=0) avg = (avg",
"idx2 = np.where(clusters['Cluster'] != c)[0] # # # Plot background points # #",
"def get_gene_data(data, g, ids=None, gene_names=None): if ids is None: ids, gene_names = get_gene_names(data)",
"s=30, alpha=1, linewidth=EDGE_WIDTH, edgecolors='none', colorbar=True, method='tsne', bins=10, background=BACKGROUND_SAMPLE_COLOR): \"\"\" Plot multiple genes on",
"i in range(0, len(gene_ids)): gene_id = gene_ids[i][1] gene = gene_ids[i][2] print(gene_id, gene) exp",
"> 200) # # # d = im_data[np.where(grey_areas)] # d[:, :] = [255,",
"None: norm = matplotlib.colors.Normalize(vmin=-3, vmax=3, clip=True) #cmap = plt.cm.plasma ids, gene_names = get_gene_names(data)",
"if isinstance(d, SparseDataFrame): print('UMI norm log2 scale sparse') sd = StandardScaler(with_mean=False).fit_transform(d.T.matrix) return SparseDataFrame(sd.T,",
"def rscale(d, min=0, max=1, axis=1): if axis == 0: return pd.DataFrame(RobustScaler().fit_transform(d), index=d.index, columns=d.columns)",
"colors=None, w=8, h=8, legend=True, show_axes=False, sort=True, cluster_order=None, fig=None, ax=None, out=None): fig, ax =",
"sample_names=samples, dir='a') create_cluster_samples(tsne_a, c_a, samples, 'a_sample', dir='a') genes_expr(d_a, tsne_a, genes, prefix='a_BGY', cmap=BLUE_GREEN_YELLOW_CMAP, w=w,",
"genes : array List of gene names \"\"\" if dir[-1] == '/': dir",
"bins=bins) print(binnumber.min(), binnumber.max()) iw = w * 300 im_base = imagelib.new(iw, iw) for",
"'feature_names', 'barcodes', 'matrix']) def get_matrix_from_h5_v2(filename, genome): with h5py.File(filename, 'r') as f: if u'version'",
"legend elif isinstance(legend, dict): legend_params.update(legend) else: pass if legend_params['show']: libcluster.format_legend(ax, cols=legend_params['cols'], markerscale=legend_params['markerscale']) libplot.invisible_axes(ax)",
"cluster)[0]] color = colors[i] else: color = CLUSTER_101_COLOR else: color = 'black' fig,",
"Plot cluster over the top of the background # # x = tsne.iloc[idx1,",
"- 1] y = df2.iloc[:, pc2 - 1] if i in colors: color",
"new_label labels += 1 libtsne.write_clusters(headers, labels, name) cluster_map, data = libtsne.read_clusters(file) labels =",
"y = tsne.iloc[idx1, 1] #print('sep', cluster, color) color = color # + '7f'",
"#print(x[i], y[i], mean) # # #if mean > 0.5: # ax.scatter(x[i], # y[i],",
"method='tsne', markers='o', s=libplot.MARKER_SIZE, w=8, h=8, colors=None, legend=True, sort=True, show_axes=False, ax=None, cluster_order=None, format='png', dir='.',",
"dim=dim, s=s, marker=marker, edgecolors=edgecolors, linewidth=linewidth, alpha=alpha, cmap=cmap, norm=norm, w=w, h=h, ax=ax) # if",
"reads_per_bc = data.sum(axis=0) scaling_factors = 1000000 / reads_per_bc scaled = data.multiply(scaling_factors) # ,",
"matplotlib # matplotlib.use('agg') import matplotlib.pyplot as plt import collections import numpy as np",
"for sample in samples: # id = '-{}'.format(sid + 1) # idx1 =",
"nx = 500 ny = 500 xi = np.linspace(x.min(), x.max(), nx) yi =",
"gene, gene_id) else: out = '{}/{}_expr_{}.png'.format(dir, method, gene) print(out) # overlay edges on",
"(c_phen['Cluster'][0:A.shape[0]] - 1).tolist() # node_color = (clusters['Cluster'] - 1).tolist() # # fig, ax",
"idx[0] else: # if id does not exist, try the gene names idx",
"gene) print(out) # overlay edges on top of original image to highlight cluster",
"gbm.barcodes return df def to_csv(gbm, file, sep='\\t'): df(gbm).to_csv(file, sep=sep, header=True, index=True) def sum(gbm,",
"'#ffff33']) BGY_ORIG_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list( 'bgy', ['#002255', '#003380', '#2ca05a', '#ffd42a', '#ffdd55']) BGY_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list(",
"'bgy', ['#162d50', '#214478', '#217844', '#ffcc00', '#ffdd55']) # BGY_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list('bgy', ['#002255', '#2ca05a', '#ffd42a'])",
"alpha=alpha, cmap=cmap, norm=norm, edgecolors='none', # edgecolors, linewidth=linewidth) # for i in range(0, x.size):",
"tsne.iloc[np.where(clusters['Cluster'] == c)[0], :] centroid = (x.sum(axis=0) / x.shape[0]).tolist() ret[i, 0] = centroid[0]",
"h=6, format='pdf'): \"\"\" Split cells into a and b \"\"\" cache = True",
"points add_titles : bool Whether to add titles to plots plot_order: list, optional",
"libcluster.format_axes(ax) # else: # libplot.invisible_axes(ax) ax.set_title('{} ({})'.format(gene_ids[i][2], gene_ids[i][1])) libplot.add_colorbar(fig, cmap) return fig def",
"cluster_order=cluster_order, show_axes=show_axes, legend=legend, sort=sort, out=out) def base_tsne_plot(tsne, marker='o', s=libplot.MARKER_SIZE, c='red', label=None, fig=None, ax=None):",
"it with...'.format(file)) # Find the interesting clusters labels, graph, Q = phenograph.cluster(pca, k=20)",
"cmap) fig, ax = expr_plot(tsne, exp, cmap=cmap, dim=dim, w=w, h=h, s=s, colorbar=colorbar, norm=norm,",
"fig, ax = cluster_plot(tsne_a, c_a, legend=False, w=w, h=h) libplot.savefig(fig, 'a/a_tsne_clusters_med.pdf') # b mkdir('b')",
"gray areas and mask # im_data = np.array(im1.convert('RGBA')) # # r = im_data[:,",
"out is None: out = '{}_expr.pdf'.format(method) fig, ax = expr_plot(tsne, exp, dim=dim, cmap=cmap,",
"255) & (b > 200) # # d = im_data[np.where(grey_areas)] # d[:, :]",
"#i = np.where(ids == cluster)[0][0] print('index', i, cluster, colors) if isinstance(colors, dict): color",
"ax = expr_plot(tsne, exp, cmap=cmap, dim=dim, w=w, h=h, s=s, colorbar=colorbar, norm=norm, alpha=alpha, linewidth=linewidth,",
"y, color=color, edgecolor=color, s=s, marker=marker, alpha=libplot.ALPHA, label=label) if labels: l = pca.index.values for",
"obj=gbm.matrix.data) f.create_carray(group, 'indices', obj=gbm.matrix.indices) f.create_carray(group, 'indptr', obj=gbm.matrix.indptr) f.create_carray(group, 'shape', obj=gbm.matrix.shape) except: raise Exception(\"Failed",
"< 0: #norm = matplotlib.colors.Normalize(vmin=-3, vmax=3, clip=True) if norm is None: norm =",
"pca.iloc[idx,:] tsne_a = libtsne.load_pca_tsne(pca_a, 'a', cache=cache) c_a = libtsne.load_phenograph_clusters(pca_a, 'a', cache=cache) create_pca_plot(pca_a, c_a,",
"dsets['indptr']), shape=dsets['shape']) return GeneBCMatrix(decode(dsets['genes']), decode(dsets['gene_names']), decode(dsets['barcodes']), matrix) except tables.NoSuchNodeError: raise Exception(\"Genome %s does",
"pd.core.frame.DataFrame): genes = genes['Genes'].values if norm is None: norm = matplotlib.colors.Normalize(vmin=-3, vmax=3, clip=True)",
"'matrix']) def decode(items): return np.array([x.decode('utf-8') for x in items]) def get_matrix_from_h5(filename, genome): with",
"= np.where(np.isin(gene_names, g))[0] if idx.size < 1: return None else: idx = np.where(ids",
"def knn_method_overlaps(tsne1, tsne2, clusters, name, k=5): c1 = centroids(tsne1, clusters) c2 = centroids(tsne2,",
"if gene_id != gene: out = '{}/{}_expr_{}_{}.{}'.format(dir, method, gene, gene_id, format) else: out",
"= get_gene_names(data) exp = get_gene_data(data, genes, ids=ids, gene_names=gene_names) avg = exp.mean(axis=0) avg =",
"= libcluster.get_colors() # Where to plot figure pc = 1 for c in",
"# edgecolors, linewidth=linewidth) # for i in range(0, x.size): # en = norm(e[i])",
"gene_name, genes=None): if genes is None: genes = gbm.gene_names gene_indices = np.where(genes ==",
"griddata((x, y), avg1, (xi, yi)) #ax.contour(xi, yi, z, levels=1) def gene_expr(data, tsne, gene,",
"e.max()) # z-score #e = (e - e.mean()) / e.std() # limit to",
"x samples expression matrix tsne : Pandas dataframe Cells x tsne tsne data.",
"s=s, label=label, fig=fig, ax=ax) #libtsne.tsne_legend(ax, labels, colors) libcluster.format_simple_axes(ax, title=\"t-SNE\") libcluster.format_legend(ax, cols=6, markerscale=2) return",
"1) # idx1 = np.where((clusters['Cluster'] == c) & clusters.index.str.contains(id))[0] # # x =",
"= mn.multiply(1000000) return GeneBCMatrix(gbm.gene_ids, gbm.gene_names, gbm.barcodes, tpm) def create_cluster_plots(pca, labels, name, marker='o', s=MARKER_SIZE):",
"int, optional Second dimension being plotted (usually 2) fig : matplotlib figure, optional",
"isinstance(colors, list): if cluster < len(colors): # np.where(clusters['Cluster'] == cluster)[0]] color = colors[i]",
"libplot.newfig(w=5, h=5) ax.scatter(c[:, 0], c[:, 1], c=None) libplot.format_axes(ax) libplot.savefig(fig, '{}_centroids.pdf'.format(name)) def centroid_network(tsne, clusters,",
"= matplotlib.colors.LinearSegmentedColormap.from_list('bgy', ['#003366', '#339966', '#ffff66', '#ffff00') # BGY_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list('bgy', ['#001a33', '#003366', '#339933',",
"gbm : a GeneBCMatrix Returns ------- object : Pandas DataFrame shape(n_cells, n_genes) \"\"\"",
"is left (the clusters) imageWithEdges = im1.filter(ImageFilter.FIND_EDGES) im_data = np.array(imageWithEdges.convert('RGBA')) #r = data[:,",
"= matplotlib.colors.LinearSegmentedColormap.from_list('bgy', ['#002255', '#003380', '#2ca05a', '#ffd42a', '#ffdd55']) # BGY_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list('bgy', ['#003366', '#339966',",
"None: fig, ax = libplot.new_fig(w, h) is_first = True base_expr_plot(data, exp, dim=dim, s=s,",
"norm = libplot.NORM_3 # Sort by expression level so that extreme values always",
"ax def expr_grid_size(x, size=SUBPLOT_SIZE): \"\"\" Auto size grid to look nice. \"\"\" if",
"EXP_ALPHA = 0.8 # '#f2f2f2' #(0.98, 0.98, 0.98) #(0.8, 0.8, 0.8) #(0.85, 0.85,",
"im_data[:, :, 1] # b = im_data[:, :, 2] # # grey_areas =",
"fig=fig, ax=ax) #libtsne.tsne_legend(ax, labels, colors) #libcluster.format_simple_axes(ax, title=\"t-SNE\") #libcluster.format_legend(ax, cols=6, markerscale=2) if out is",
"ax = libplot.new_fig() libplot.scatter(tsne['TSNE-1'], tsne['TSNE-2'], c=c, marker=marker, label=label, s=s, ax=ax) return fig, ax",
"a new one is created. ax : matplotlib ax, optional Supply an axis",
"interp1d(points[hull.vertices, 0], points[hull.vertices, 1], kind='cubic') # fy = interp1d(points[hull.vertices, 1], points[hull.vertices, 0], kind='cubic')",
"data.multiply(scaling_factors) # , axis=1) return scaled def umi_log2(d): if isinstance(d, SparseDataFrame): print('UMI norm",
"scipy.stats import binned_statistic import imagelib TNSE_AX_Q = 0.999 MARKER_SIZE = 10 SUBPLOT_SIZE =",
"# alpha=alpha, # fig=fig, # ax=ax, # norm=norm, # w=w, # h=h, #",
"w = size * rows # # fig = libplot.new_base_fig(w=w, h=w) # #",
"len(gene_indices) == 0: raise Exception(\"%s was not found in list of gene names.\"",
"which to render the plot, otherwise a new one is created. norm :",
"z = (d - m) / sd # find all points within 1",
"return pd.DataFrame(sd, index=d.index, columns=d.columns) def min_max_scale(d, min=0, max=1, axis=1): #m = d.min(axis=1) #std",
"# # w = size * rows # # fig = libplot.new_base_fig(w=w, h=w)",
"pca.iloc[idx_b,:] tsne_b = libtsne.load_pca_tsne(pca_b, 'b', cache=cache) c_b = libtsne.load_phenograph_clusters(pca_b, 'b', cache=cache) create_pca_plot(pca_b, c_b,",
"---------- d : Pandas dataframe t-sne, umap data clusters : Pandas dataframe n",
"centroids(tsne, clusters) fig, ax = libplot.newfig(w=5, h=5) ax.scatter(c[:, 0], c[:, 1], c=None) libplot.format_axes(ax)",
"# \"\"\" # # # cids = list(sorted(set(clusters['Cluster']))) # # rows = int(np.ceil(np.sqrt(len(cids))))",
"tsne_other.iloc[:, 0] y = tsne_other.iloc[:, 1] libplot.scatter(x, y, c=[background], ax=ax, edgecolors='none', # bgedgecolor,",
"object on which to render the plot, otherwise a new one is created.",
"s=MARKER_SIZE, alpha=1, edgecolors=EDGE_COLOR, linewidth=EDGE_WIDTH, w=libplot.DEFAULT_WIDTH, h=libplot.DEFAULT_HEIGHT, show_axes=False, fig=None, ax=None, norm=None, colorbar=False): # plt.cm.plasma):",
"edgecolors=edgecolors) if out is not None: libplot.savefig(fig, out, pad=0) return fig, ax def",
"based on by labelling cells by sample/batch. \"\"\" sc = np.array(['' for i",
"import silhouette_samples from sklearn.neighbors import kneighbors_graph from scipy.interpolate import griddata import h5py from",
"avg1 = np.zeros(x.size) #avg[idx] #avg1[idx] = 1 # fx = interp1d(points[hull.vertices, 0], points[hull.vertices,",
"= np.where(ids == g)[0] if indexes.size > 0: for index in indexes: ret.append((index,",
"cmap=BLUE_YELLOW_CMAP, # marker='o', # s=MARKER_SIZE, # alpha=EXP_ALPHA, # out=None, # fig=None, # ax=None,",
"header=0, sep='\\t') idx = np.where(counts.columns.isin(a_barcodes['Barcode'].values))[0] d_a = counts.iloc[:, idx] d_a = libcluster.remove_empty_rows(d_a) if",
"color = 'black' else: color = 'black' ax = libplot.new_ax(fig, subplot=(rows, cols, pc))",
"= centroids(tsne, clusters) fig, ax = libplot.newfig(w=5, h=5) ax.scatter(c[:, 0], c[:, 1], c=None)",
"# # find gray areas and mask # im_data = np.array(im1.convert('RGBA')) # #",
"ax. Returns ------- fig : Matplotlib figure A new Matplotlib figure used to",
"marker=marker, label=label, s=s, ax=ax) return fig, ax def tsne_plot(tsne, marker='o', s=libplot.MARKER_SIZE, c='red', label=None,",
"= dict(LEGEND_PARAMS) if isinstance(legend, bool): legend_params['show'] = legend elif isinstance(legend, dict): legend_params.update(legend) else:",
"= np.where(clusters['Cluster'] == l)[0] n = len(indices) label = 'C{} ({:,})'.format(l, n) df2",
"genes = data.index.str.split(';').str else: genes = data.index ids = genes return ids.values, genes.values",
"if min(labels) == -1: new_label = 100 labels[np.where(labels == -1)] = new_label labels",
"== g) & (r == b) & (g == b) # # #d",
"- 1).tolist() # node_color = (clusters['Cluster'] - 1).tolist() # # fig, ax =",
"= get_gene_names(data) print(ids, gene_names, genes) gene_ids = get_gene_ids(data, genes, ids=ids, gene_names=gene_names) print(gene_ids) for",
"int: l = x elif type(x) is list: l = len(x) elif type(x)",
"exp, ax=ax) #libplot.add_colorbar(fig, cmap) fig, ax = expr_plot(tsne, exp, cmap=cmap, dim=dim, w=w, h=h,",
"edgecolors='none', colorbar=True, method='tsne', bins=10, background=BACKGROUND_SAMPLE_COLOR): \"\"\" Plot multiple genes on a grid. Parameters",
"is a cell reads_per_bc = data.sum(axis=0) # int(np.round(np.median(reads_per_bc))) median_reads_per_bc = np.median(reads_per_bc) scaling_factors =",
"s=MARKER_SIZE, edgecolors='white', linewidth=EDGE_WIDTH, fig=None, ax=None): \"\"\" Plot a cluster separately to highlight where",
"= w * 300 im_base = imagelib.new(iw, iw) for bin in range(0, bins):",
"clusters, name, dim1=0, dim2=1, method='tsne', markers='o', s=libplot.MARKER_SIZE, w=8, h=8, colors=None, legend=True, sort=True, show_axes=False,",
"ax.set_xlim(xlim) # ax.set_ylim(ylim) def base_cluster_plot(d, clusters, markers=None, s=libplot.MARKER_SIZE, colors=None, edgecolors=EDGE_COLOR, linewidth=EDGE_WIDTH, dim1=0, dim2=1,",
"w=6, h=6, format='pdf'): \"\"\" Split cells into a and b \"\"\" cache =",
"data. Parameters ---------- data : Pandas dataframe features x dimensions, e.g. rows are",
"genes, cid, clusters, prefix='', index=None, dir='GeneExp', cmap=OR_RED_CMAP, # BGY_CMAP, norm=None, w=libplot.DEFAULT_WIDTH, h=libplot.DEFAULT_HEIGHT, alpha=1.0,",
"Index of gene ids gene_names : Index, optional Index of gene names Returns",
"255) #(r > 0) & (r == g) & (r == b) &",
"s=s, # marker=marker, # edgecolors='none', #edgecolors, # linewidth=linewidth) # # # # mean",
"# #skimage.io.imsave('tmp_canny_{}.png'.format(bin), edges1) # # im2 = Image.fromarray(im_data) # # im_no_gray, im_smooth =",
"= [64, 64, 64] # #im_data[np.where(black_areas)] = d # # #im3 = Image.fromarray(im_data)",
"extreme values always appear on top idx = np.argsort(exp) #np.argsort(abs(exp)) # np.argsort(exp) x",
"pd.DataFrame(gbm.matrix.todense()) df.index = gbm.gene_names df.columns = gbm.barcodes return df def to_csv(gbm, file, sep='\\t'):",
"ax = separate_cluster(tsne, clusters, cluster, color=color, add_titles=add_titles, size=size) out = '{}_sep_clust_{}_c{}.{}'.format(type, name, cluster,",
"(the clusters) # im_edges = im2.filter(ImageFilter.FIND_EDGES) # # # im_data = np.array(im_edges.convert('RGBA')) #",
"clusters, name): c = centroids(tsne, clusters) A = kneighbors_graph(c, 5, mode='distance', metric='euclidean').toarray() G",
"{'Cluster': list(range(1, c1.shape[0] + 1)), 'Overlap %': overlaps}) df.set_index('Cluster', inplace=True) df.to_csv('{}_cluster_overlaps.txt'.format(name), sep='\\t') def",
"inplace=True) # # find gray areas and mask # im_data = np.array(im1.convert('RGBA')) #",
"d = im_data[np.where(black_areas)] d[:, 0:3] = [64, 64, 64] im_data[np.where(black_areas)] = d im2",
"'#339966', '#ffff66', '#ffff00') # BGY_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list('bgy', ['#001a33', '#003366', '#339933', '#ffff66', '#ffff00']) #",
"1] # b = im_data[:, :, 2] # # print(tmp, r.shape) # #",
"1 idx_bin = np.where(binnumber == bi)[0] idx_other = np.where(binnumber != bi)[0] tsne_other =",
"edgecolors=edgecolors) if gene_id != gene: out = '{}/{}_expr_{}_{}.{}'.format(dir, method, gene, gene_id, format) else:",
"+= 1 return fig def pca_plot_base(pca, clusters, pc1=1, pc2=2, marker='o', labels=False, s=MARKER_SIZE, w=8,",
"by this function.' % version) feature_ids = [x.decode('ascii', 'ignore') for x in f['matrix']['features']['id']]",
"print('index', i, cluster_order[i]) cluster = cluster_order[i] if isinstance(colors, dict): color = colors[cluster] elif",
"isinstance(d, SparseDataFrame): print('UMI norm log2 scale sparse') sd = StandardScaler(with_mean=False).fit_transform(d.T.matrix) return SparseDataFrame(sd.T, index=d.index,",
"# # # Plot background points # # ax = libplot.new_ax(fig, subplot=(rows, rows,",
"[64, 64, 64] # #im_data[np.where(black_areas)] = d # # #im3 = Image.fromarray(im_data) #",
"of new ax. Returns ------- fig : Matplotlib figure A new Matplotlib figure",
"0].tolist(), metric='euclidean') x2 = silhouette_samples( tsne_umi_log2, clusters.iloc[:, 0].tolist(), metric='euclidean') fig, ax = libplot.newfig(w=9,",
"ax=None, norm=None, colorbar=False): # plt.cm.plasma): \"\"\" Creates a base expression plot and adds",
"Pandas DataFrame shape(n_cells, n_genes) \"\"\" df = pd.DataFrame(gbm.matrix.todense()) df.index = gbm.gene_names df.columns =",
"# ax=ax, # norm=norm, # w=w, # h=h, # colorbar=colorbar) # # set_tsne_ax_lim(tsne,",
"= ids[i] if isinstance(colors, dict): color = colors[cluster] elif isinstance(colors, list): if cluster",
"expr_plot(tsne, exp, dim=dim, cmap=cmap, marker=marker, s=s, alpha=alpha, fig=fig, w=w, h=h, ax=ax, show_axes=show_axes, colorbar=colorbar,",
"Parameters ---------- gbm : a GeneBCMatrix Returns ------- object : Pandas DataFrame shape(n_cells,",
"= tsne.iloc[idx1, 1] #print('sep', cluster, color) color = color # + '7f' libplot.scatter(x,",
"[] for g in genes: indexes = np.where(ids == g)[0] if indexes.size >",
"len(x1))}) libplot.boxplot(df, 'Cluster', 'Silhouette Score', colors=libcluster.colors(), ax=ax) ax.set_ylim([-1, 1]) ax.set_title('tsne-10x') #libplot.savefig(fig, 'RK10001_10003_clust-phen_silhouette.pdf') ax",
"clusters, cluster, color=color, size=w, s=s, linewidth=linewidth, add_titles=False, show_background=False) ax.set_xlim(xlim) ax.set_ylim(ylim) if not show_axes:",
"alpha=libplot.ALPHA, label=label) if labels: l = pca.index.values for i in range(0, pca.shape[0]): print(pca.shape,",
"np.where(binnumber != bi)[0] tsne_other = tsne.iloc[idx_other, :] fig, ax = libplot.new_fig(w, w) x",
"#fig, ax = libplot.new_fig() #expr_plot(tsne, exp, ax=ax) #libplot.add_colorbar(fig, cmap) exp_bin = exp[idx_bin] tsne_bin",
"= [0.75, 0.75, 0.75] EDGE_COLOR = None # [0.3, 0.3, 0.3] #'#4d4d4d' EDGE_WIDTH",
"version) else: raise ValueError( 'Matrix HDF5 file format version (%d) is an older",
"original image to highlight cluster # im_base.paste(im2, (0, 0), im2) # break imagelib.save(im_base,",
"of new ax. h: int, optional height of new ax. Returns ------- fig",
"clusters): cids = list(sorted(set(clusters['Cluster'].tolist()))) ret = np.zeros((len(cids), 2)) for i in range(0, len(cids)):",
"isinstance(colors, list): #i = cluster - 1 if i < len(colors): # colors[cid",
"'TSNE-2' etc genes : array List of gene names Returns ------- fig :",
"# cmap=BLUE_YELLOW_CMAP, # marker='o', # s=MARKER_SIZE, # alpha=EXP_ALPHA, # out=None, # fig=None, #",
"datasets.\") #GeneBCMatrix = collections.namedtuple('FeatureBCMatrix', ['feature_ids', 'feature_names', 'barcodes', 'matrix']) def get_matrix_from_h5_v2(filename, genome): with h5py.File(filename,",
"im_base.paste(im2, (0, 0), im2) if gene_id != gene: out = '{}/{}_expr_{}_{}.png'.format(dir, method, gene,",
"tsne : Pandas dataframe # Cells x tsne tsne data. Columns should be",
"= matplotlib.colors.LinearSegmentedColormap.from_list('bgy', ['#003380', '#5fd38d', '#ffd42a']) EXP_NORM = matplotlib.colors.Normalize(-1, 3, clip=True) LEGEND_PARAMS = {'show':",
"argument, return this, otherwise create a new axis and attach to figure before",
"libplot.new_ax(fig, subplot=(rows, rows, i + 1)) # # x = tsne.iloc[idx2, 0] #",
"= 1 for s in sample_names: id = '-{}'.format(c) print(id) print(np.where(d.index.str.contains(id))[0]) sc[np.where(d.index.str.contains(id))[0]] =",
"fig, ax def base_expr_plot(data, exp, dim=[1, 2], cmap=plt.cm.plasma, marker='o', edgecolors=EDGE_COLOR, linewidth=1, s=MARKER_SIZE, alpha=1,",
"in colors : list, color Colors of points add_titles : bool Whether to",
"scipy.spatial import distance import networkx as nx import os import phenograph import libplot",
"\"\"\" # Creates a basic t-sne expression plot. # # Parameters # ----------",
"if colors is None: # colors = libcluster.colors() # # for i in",
"pd.read_csv('../b_barcodes.tsv', header=0, sep='\\t') idx = np.where(counts.columns.isin(b_barcodes['Barcode'].values))[0] d_b = counts.iloc[:, idx] d_b = libcluster.remove_empty_rows(d_b)",
"libplot.new_ax(fig, subplot=(rows, cols, pc)) separate_cluster(tsne, clusters, cluster, color=color, add_titles=add_titles, ax=ax) # idx1 =",
"c[:, 1], c=None) libplot.format_axes(ax) libplot.savefig(fig, '{}_centroids.pdf'.format(name)) def centroid_network(tsne, clusters, name): c = centroids(tsne,",
"w=8, alpha=ALPHA, # libplot.ALPHA, show_axes=True, legend=True, sort=True, outline=True): cluster_order = list(sorted(set(clusters['Cluster']))) im_base =",
"SparseDataFrame): d_a = umi_norm_log2(d_a) else: d_a = umi_norm_log2_scale(d_a) pca_a = libtsne.load_pca(d_a, 'a', cache=cache)",
"# set_tsne_ax_lim(tsne, ax) # # libplot.invisible_axes(ax) # # if out is not None:",
"min) + min # return scaled if axis == 0: return pd.DataFrame(MinMaxScaler(feature_range=(min, max)).fit_transform(d),",
"= umi_norm_log2(data) return scale(d, clip=clip) def read_clusters(file): print('Reading clusters from {}...'.format(file)) return pd.read_csv(file,",
"200) # # d = im_data[np.where(grey_areas)] # d[:, :] = [255, 255, 255,",
"import imagelib TNSE_AX_Q = 0.999 MARKER_SIZE = 10 SUBPLOT_SIZE = 4 EXP_ALPHA =",
"pandas.DataFrame # t-sne 2D data # \"\"\" # # fig, ax = expr_plot(tsne,",
"# libplot.scatter(x, y, c=BACKGROUND_SAMPLE_COLOR, ax=ax) # # # Plot cluster over the top",
"if isinstance(genes, pd.core.frame.DataFrame): genes = genes['Genes'].values if norm is None: norm = matplotlib.colors.Normalize(vmin=-3,",
"sample # \"\"\" # fig = tsne_cluster_sample_grid(tsne, clusters, samples, colors, size) # #",
"'b_sample', dir='b') genes_expr(d_b, tsne_b, genes, prefix='b_BGY', cmap=BLUE_GREEN_YELLOW_CMAP, w=w, h=h, dir='b/GeneExp', format=format) fig, ax",
"is None and exp.min() < 0: #norm = matplotlib.colors.Normalize(vmin=-3, vmax=3, clip=True) if norm",
"s=s, marker=marker, edgecolors=edgecolors, linewidth=linewidth, alpha=alpha, cmap=cmap, norm=norm, w=w, h=h, ax=ax) # if colorbar",
"libplot.newfig(w=10, h=10) # # nx.draw_networkx(G, pos=pos, with_labels=False, ax=ax, node_size=50, node_color=node_color, vmax=(clusters['Cluster'].max() - 1),",
"= (d - m) / sd # find all points within 1 sd",
"'{}/{}_expr_{}_{}.png'.format(dir, method, gene, gene_id) else: out = '{}/{}_expr_{}.png'.format(dir, method, gene) print(out) # overlay",
"for x in f['matrix']['features']['name']] barcodes = list(f['matrix']['barcodes'][:]) matrix = sp_sparse.csc_matrix( (f['matrix']['data'], f['matrix']['indices'], f['matrix']['indptr']),",
"in range(0, x.size): # en = norm(e[i]) # color = cmap(int(en * cmap.N))",
"def create_cluster_samples(tsne_umi_log2, clusters, sample_names, name, method='tsne', format='png', dir='.', w=16, h=16, legend=True): sc =",
"= data.multiply(scaling_factors) # , axis=1) return scaled def umi_norm_log2(data): d = umi_norm(data) print(type(d))",
"gene_ids = get_gene_ids(data, genes, ids=ids, gene_names=gene_names) w, h, rows, cols = expr_grid_size(gene_ids, size=size)",
"out=None): fig, ax = base_cluster_plot(tsne, clusters, markers=markers, colors=colors, dim1=dim1, dim2=dim2, s=s, w=w, h=h,",
"= np.where(clusters['Cluster'] != c)[0] # # # Plot background points # # ax",
"colors[i] else: color = 'black' else: color = 'black' fig, ax = separate_cluster(d,",
"Marker size w : int, optional Plot width h : int, optional Plot",
"['#003366', '#339966', '#ffff66', '#ffff00') # BGY_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list('bgy', ['#001a33', '#003366', '#339933', '#ffff66', '#ffff00'])",
"w=w, h=h, fig=fig, ax=ax) libplot.savefig(fig, out, pad=2) plt.close(fig) def set_tsne_ax_lim(tsne, ax): \"\"\" Set",
"pc2=2, marker='o', labels=False, s=MARKER_SIZE, w=8, h=8, fig=None, ax=None): colors = libcluster.get_colors() if ax",
"im1.save(out, 'png') def genes_expr_outline(data, tsne, genes, prefix='', index=None, dir='GeneExp', cmap=BGY_CMAP, norm=None, w=6, s=30,",
"marker='o', edgecolors=EDGE_COLOR, linewidth=1, s=MARKER_SIZE, alpha=1, w=libplot.DEFAULT_WIDTH, h=libplot.DEFAULT_HEIGHT, fig=None, ax=None, norm=None): # plt.cm.plasma): \"\"\"",
"= pca.iloc[indices, ] x = df2.iloc[:, pc1 - 1] y = df2.iloc[:, pc2",
"= len(x) elif type(x) is np.ndarray: l = x.shape[0] elif type(x) is pd.core.frame.DataFrame:",
"# alpha=EXP_ALPHA, # out=None, # fig=None, # ax=None, # norm=None, # w=libplot.DEFAULT_WIDTH, #",
"isinstance(genes, pd.core.frame.DataFrame): genes = genes['Genes'].values if norm is None: norm = matplotlib.colors.Normalize(vmin=-3, vmax=3,",
"figure, otherwise a new figure is created and returned. ax : matplotlib axis",
"= -max if isinstance(min, float) or isinstance(min, int): print('z min', min) sd[np.where(sd <",
"if ax is None: fig, ax = libplot.new_fig(w=w, h=h) # if norm is",
"out = '{}_sep_clust_{}_c{}.{}'.format(type, name, cluster, format) print('Creating', out, '...') libplot.savefig(fig, out) libplot.savefig(fig, 'tmp.png')",
"1] if i in colors: color = colors[i] # l] else: color =",
"d # # #im3 = Image.fromarray(im_data) # #im2.save('edges.png', 'png') # # im_smooth =",
"centroids(tsne, clusters) A = kneighbors_graph(c, 5, mode='distance', metric='euclidean').toarray() G = nx.from_numpy_matrix(A) pos =",
"not found, creating it with...'.format(file)) # Find the interesting clusters labels, graph, Q",
"on which to render the plot, otherwise a new one is created. norm",
"def get_matrix_from_h5_v2(filename, genome): with h5py.File(filename, 'r') as f: if u'version' in f.attrs: if",
"f.create_carray(group, 'indices', obj=gbm.matrix.indices) f.create_carray(group, 'indptr', obj=gbm.matrix.indptr) f.create_carray(group, 'shape', obj=gbm.matrix.shape) except: raise Exception(\"Failed to",
"yp, 'k-') #ax.plot(points[hull.vertices[0], 0], points[hull.vertices[[0, -1]], 1]) #points = np.array([[x, y] for x,",
"# y = tsne.iloc[idx2, 1] # # libplot.scatter(x, y, c=BACKGROUND_SAMPLE_COLOR, ax=ax) # #",
"genes, prefix='', dim=[1, 2], index=None, dir='GeneExp', cmap=BGY_CMAP, norm=None, w=4, h=4, s=30, alpha=ALPHA, linewidth=EDGE_WIDTH,",
"separately to highlight where the samples are Parameters ---------- tsne : Pandas dataframe",
"df.columns = gbm.barcodes return df def to_csv(gbm, file, sep='\\t'): df(gbm).to_csv(file, sep=sep, header=True, index=True)",
"a cluster label. s : int, optional Marker size w : int, optional",
"list, optional List of cluster ids in the order they should be rendered",
"h=h, ax=ax, show_axes=show_axes, colorbar=colorbar, norm=norm, linewidth=linewidth, edgecolors=edgecolors) if out is not None: libplot.savefig(fig,",
"to make the plot ax : Matplotlib axes Axes used to render the",
"True base_expr_plot(data, exp, dim=dim, s=s, marker=marker, edgecolors=edgecolors, linewidth=linewidth, alpha=alpha, cmap=cmap, norm=norm, w=w, h=h,",
"i in range(0, c.shape[0]): labels[i] = i + 1 #nx.draw_networkx(G, pos=pos, with_labels=False, ax=ax,",
"not supported by this function.' % version) else: raise ValueError( 'Matrix HDF5 file",
"index genes : list List of strings of gene ids ids : Index,",
"c=e, s=s, marker=marker, alpha=alpha, cmap=cmap, norm=norm, edgecolors='none', # edgecolors, linewidth=linewidth) # for i",
"transparent areas are edges # #black_areas = (a > 0) #(r < 255)",
"in f.walk_nodes('/' + genome, 'Array'): dsets[node.name] = node.read() # for node in f.walk_nodes('/matrix',",
"max return pd.DataFrame(sd, index=d.index, columns=d.columns) def min_max_scale(d, min=0, max=1, axis=1): #m = d.min(axis=1)",
"DataFrame # Clusters in # # Returns # ------- # fig : Matplotlib",
"image to highlight cluster # im_base.paste(im2, (0, 0), im2) # break imagelib.save(im_base, out)",
"prefix = '' ax.set_title('{}{} ({:,})'.format( prefix, cluster, len(idx1)), color=color) ax.axis('off') # libplot.invisible_axes(ax) return",
"libplot.savefig(fig, 'a/a_tsne_clusters_med.pdf') # b mkdir('b') b_barcodes = pd.read_csv('../b_barcodes.tsv', header=0, sep='\\t') idx = np.where(counts.columns.isin(b_barcodes['Barcode'].values))[0]",
"overlaps = [] for i in range(0, c1.shape[0]): ids1 = np.where(a1[i, :] >",
"e.mean()) / e.std() #print(e.min(), e.max()) # z-score #e = (e - e.mean()) /",
"scaling_factors = median_reads_per_bc / reads_per_bc scaled = data.multiply(scaling_factors) # , axis=1) return scaled",
"the plot # \"\"\" # # # cids = list(sorted(set(clusters['Cluster']))) # # rows",
"over the top of the background x = tsne.iloc[idx1, 0] y = tsne.iloc[idx1,",
"= 'C{} ({:,})'.format(l, n) df2 = pca.iloc[indices, ] x = df2.iloc[:, pc1 -",
"is None: ids, gene_names = get_gene_names(data) if isinstance(g, list): g = np.array(g) if",
"cmap=BGY_CMAP, norm=None, w=4, h=4, s=30, alpha=ALPHA, linewidth=EDGE_WIDTH, edgecolors='none', colorbar=True, method='tsne', format='png'): \"\"\" Plot",
"# im_base.paste(im2, (0, 0), im2) # break imagelib.save(im_base, out) def cluster_plot(tsne, clusters, dim1=0,",
"= 'tmp{}.png'.format(bin) libplot.savefig(fig, tmp, pad=0) plt.close(fig) im = imagelib.open(tmp) im_no_bg = imagelib.remove_background(im) im_edges",
"index=d.index, columns=d.columns) def umi_norm_log2_scale(data, clip=None): d = umi_norm_log2(data) return scale(d, clip=clip) def read_clusters(file):",
"antony \"\"\" import matplotlib # matplotlib.use('agg') import matplotlib.pyplot as plt import collections import",
"float) or isinstance(min, int): print('z min', min) sd[np.where(sd < min)] = min if",
"points if show_background: x = tsne.iloc[idx2, 0] y = tsne.iloc[idx2, 1] libplot.scatter(x, y,",
"show_background=False) ax.set_xlim(xlim) ax.set_ylim(ylim) if not show_axes: libplot.invisible_axes(ax) legend_params = dict(LEGEND_PARAMS) if isinstance(legend, bool):",
"# min_max_scale(avg) create_expr_plot(tsne, avg, cmap=cmap, w=w, h=h, colorbar=colorbar, norm=norm, alpha=alpha, fig=fig, ax=ax) x",
"im_data[:, :, 1] # b = im_data[:, :, 2] # # print(tmp, r.shape)",
"etc cluster : int Clusters in colors : list, color Colors of points",
"out, pad=2) plt.close(fig) def set_tsne_ax_lim(tsne, ax): \"\"\" Set the t-SNE x,y limits to",
"ax=ax) tmp = 'tmp{}.png'.format(bin) libplot.savefig(fig, tmp, pad=0) plt.close(fig) im = imagelib.open(tmp) im_no_bg =",
"xlim = ax.get_xlim() ylim = ax.get_ylim() fig, ax = separate_cluster(d, clusters, cluster, color=color,",
"cmap=cmap, dim=dim, w=w, h=h, s=s, colorbar=colorbar, norm=norm, alpha=alpha, linewidth=linewidth, edgecolors=edgecolors) if gene_id !=",
"= get_gene_data(data, genes, ids=ids, gene_names=gene_names) avg = exp.mean(axis=0) avg = (avg - avg.mean())",
"0], c[:, 1], c=None) libplot.format_axes(ax) libplot.savefig(fig, '{}_centroids.pdf'.format(name)) def centroid_network(tsne, clusters, name): c =",
"* rows # # fig = libplot.new_base_fig(w=w, h=w) # # if colors is",
"areas are edges # #black_areas = (a > 0) #(r < 255) |",
"from lib10x.sample import * from scipy.spatial import ConvexHull from PIL import Image, ImageFilter",
"* 300) for i in range(0, len(cluster_order)): print('index', i, cluster_order[i]) cluster = cluster_order[i]",
"1 print(np.unique(d.index.values)) print(np.unique(sc)) df = pd.DataFrame(sc, index=d.index, columns=['Cluster']) return df def create_cluster_samples(tsne_umi_log2, clusters,",
"t='TSNE', # d1=d1, # d2=d2, # x1=x1, # x2=x2, # cmap=cmap, # marker=marker,",
"plot_centroids(tsne, clusters, name): c = centroids(tsne, clusters) fig, ax = libplot.newfig(w=5, h=5) ax.scatter(c[:,",
"if ids is None: ids, gene_names = get_gene_names(data) ret = [] for g",
"im_data = np.array(imageWithEdges.convert('RGBA')) #r = data[:, :, 0] #g = data[:, :, 1]",
"n_genes) \"\"\" df = pd.DataFrame(gbm.matrix.todense()) df.index = gbm.gene_names df.columns = gbm.barcodes return df",
"attach to figure before returning. \"\"\" if ax is None: fig, ax =",
"id does not exist, try the gene names idx = np.where(np.isin(gene_names, g))[0] if",
"def base_cluster_plot_outline(out, d, clusters, s=libplot.MARKER_SIZE, colors=None, edgecolors=EDGE_COLOR, linewidth=EDGE_WIDTH, dim1=0, dim2=1, w=8, alpha=ALPHA, #",
"fig, ax def create_cluster_plot(d, clusters, name, dim1=0, dim2=1, method='tsne', markers='o', s=libplot.MARKER_SIZE, w=8, h=8,",
"# im_no_gray, im_smooth = smooth_edges(im1, im1) # # # Edge detect on what",
"# ax.set_title('C{} ({:,})'.format(c, len(idx1)), color=colors[i]) # libplot.invisible_axes(ax) # # #set_tsne_ax_lim(tsne, ax) # #",
"import pandas as pd from sklearn.manifold import TSNE import sklearn.preprocessing from sklearn.preprocessing import",
"marker='o', s=MARKER_SIZE): for i in range(0, pca.shape[1]): for j in range(i + 1,",
"up index for color purposes #i = np.where(ids == cluster)[0][0] print('index', i, cluster,",
"\"\"\" d1 = tsne.iloc[:, 0] d2 = tsne.iloc[:, 1] xlim = [d1[d1 <",
"in this file.\" % genome) except KeyError: raise Exception(\"File is missing one or",
"im_smooth = imagelib.smooth(im_edges) im_outline = imagelib.paste(im_no_bg, im_smooth) imagelib.paste(im_base, im_outline, inplace=True) # # find",
"!= gene: out = '{}/{}_expr_{}_{}.png'.format(dir, method, gene, gene_id) else: out = '{}/{}_expr_{}.png'.format(dir, method,",
"avg[avg < -1.5] = -1.5 avg[avg > 1.5] = 1.5 avg = (avg",
"of gene names.\" % gene_name) return gbm.matrix[gene_indices[0], :].toarray().squeeze() def gbm_to_df(gbm): return pd.DataFrame(gbm.matrix.todense(), index=gbm.gene_names,",
"purposes #i = np.where(ids == cluster)[0][0] print('index', i, cluster, colors) if isinstance(colors, dict):",
"c=[background], ax=ax, edgecolors='none', # bgedgecolor, linewidth=linewidth, s=s) #fig, ax = libplot.new_fig() #expr_plot(tsne, exp,",
"& clusters.index.str.contains(id))[0] # # x = tsne.iloc[idx1, 0] # y = tsne.iloc[idx1, 1]",
"#r = data[:, :, 0] #g = data[:, :, 1] #b = data[:,",
"#set_tsne_ax_lim(tsne, ax) # libcluster.format_axes(ax) if not show_axes: libplot.invisible_axes(ax) legend_params = dict(LEGEND_PARAMS) if isinstance(legend,",
"method, name) libplot.savefig(fig, out, pad=0) #libplot.savefig(fig, '{}/tsne_{}separate_clusters.pdf'.format(dir, name)) # # # def tsne_cluster_sample_grid(tsne,",
": Pandas dataframe features x dimensions, e.g. rows are cells and columns are",
"== gene_name)[0] if len(gene_indices) == 0: raise Exception(\"%s was not found in list",
"with_labels=False, ax=ax, node_size=200, node_color=node_color, vmax=(c.shape[0] - 1), cmap=libcluster.colormap()) nx.draw_networkx(G, with_labels=True, labels=labels, ax=ax, node_size=800,",
"s=MARKER_SIZE, alpha=EXP_ALPHA, fig=None, ax=None, norm=None): # plt.cm.plasma): fig, ax = base_expr_plot(data, exp, t='PC',",
"distance import networkx as nx import os import phenograph import libplot import libcluster",
"sort=sort) #set_tsne_ax_lim(tsne, ax) # libcluster.format_axes(ax) if not show_axes: libplot.invisible_axes(ax) legend_params = dict(LEGEND_PARAMS) if",
"legend_params['show']: libcluster.format_legend(ax, cols=legend_params['cols'], markerscale=legend_params['markerscale']) return fig, ax def base_cluster_plot_outline(out, d, clusters, s=libplot.MARKER_SIZE, colors=None,",
"# b mkdir('b') b_barcodes = pd.read_csv('../b_barcodes.tsv', header=0, sep='\\t') idx = np.where(counts.columns.isin(b_barcodes['Barcode'].values))[0] d_b =",
"'GeneBCMatrix', ['gene_ids', 'gene_names', 'barcodes', 'matrix']) def decode(items): return np.array([x.decode('utf-8') for x in items])",
"index=d.index, columns=d.columns) else: return pd.DataFrame(MinMaxScaler(feature_range=(min, max)).fit_transform(d.T).T, index=d.index, columns=d.columns) def rscale(d, min=0, max=1, axis=1):",
"cluster_order=cluster_order, legend=legend, sort=sort, show_axes=show_axes, fig=fig, ax=ax) #libtsne.tsne_legend(ax, labels, colors) #libcluster.format_simple_axes(ax, title=\"t-SNE\") #libcluster.format_legend(ax, cols=6,",
"clusters, colors=colors, edgecolors=edgecolors, linewidth=linewidth, markers=markers, alpha=alpha, s=s, ax=ax, cluster_order=cluster_order, sort=sort) #set_tsne_ax_lim(tsne, ax) #",
"genes : list List of strings of gene ids ids : Index, optional",
"add_titles: if isinstance(cluster, int): prefix = 'C' else: prefix = '' ax.set_title('{}{} ({:,})'.format(",
"h=libplot.DEFAULT_HEIGHT, edgecolors=EDGE_COLOR, linewidth=EDGE_WIDTH, norm=None, method='tsne', show_axes=False, colorbar=True, out=None): # plt.cm.plasma): \"\"\" Creates and",
"h = size * rows fig = libplot.new_base_fig(w=w, h=h) if colors is None:",
"size w : int, optional Plot width h : int, optional Plot height",
"2: raise ValueError( 'Matrix HDF5 file format version (%d) is an newer version",
"dim2=dim2, s=s, w=w, h=h, cluster_order=cluster_order, legend=legend, sort=sort, show_axes=show_axes, fig=fig, ax=ax) #libtsne.tsne_legend(ax, labels, colors)",
"#d = im_data[np.where(black_areas)] # #d[:, 0:3] = [64, 64, 64] # #im_data[np.where(black_areas)] =",
"- 1), cmap=libcluster.colormap()) nx.draw_networkx(G, with_labels=True, labels=labels, ax=ax, node_size=800, node_color=node_color, font_color='white', font_family='Arial') libplot.format_axes(ax) libplot.savefig(fig,",
"s=s, linewidth=linewidth, add_titles=False) # get x y lim xlim = ax.get_xlim() ylim =",
"= get_gene_data(data, gene_id, ids=ids, gene_names=gene_names) ax = libplot.new_ax(fig, rows, cols, i + 1)",
"Image.fromarray(im_data) # #im2.save('edges.png', 'png') # # im_smooth = im_edges.filter(ImageFilter.SMOOTH) # im_smooth.save('edges.png', 'png') #",
"# imagelib.paste(im_base, im_no_bg, inplace=True) im = imagelib.open(tmp) if outline: im_no_bg = imagelib.remove_background(im) im_edges",
"not None: libplot.savefig(fig, out) return fig, ax def create_cluster_plot(d, clusters, name, dim1=0, dim2=1,",
"0] y = tsne.iloc[idx1, 1] #print('sep', cluster, color) color = color # +",
"ax def create_pca_plot(pca, clusters, name, pc1=1, pc2=2, marker='o', labels=False, legend=True, s=MARKER_SIZE, w=8, h=8,",
"plt.cm.plasma): fig, ax = base_expr_plot(data, exp, t='PC', dim=dim, cmap=cmap, marker=marker, s=s, fig=fig, alpha=alpha,",
"fig, ax = libplot.newfig(w=8, h=8) # list(range(0, c.shape[0])) node_color = libcluster.colors()[0:c.shape[0]] cmap =",
"libcluster.scatter_clusters(d.iloc[:, dim1].values, d.iloc[:, dim2].values, clusters, colors=colors, edgecolors=edgecolors, linewidth=linewidth, markers=markers, alpha=alpha, s=s, ax=ax, cluster_order=cluster_order,",
"the gene names idx = np.where(gene_names == g)[0] if idx.size > 0: idx",
"s=s, marker=marker, alpha=libplot.ALPHA, label=label) if labels: l = pca.index.values for i in range(0,",
"# gene id gene_id = gene_ids[i][1] gene = gene_ids[i][2] print(gene, gene_id) exp =",
"if ax is None: fig, ax = libplot.new_fig() libplot.scatter(tsne['TSNE-1'], tsne['TSNE-2'], c=c, marker=marker, label=label,",
"linewidth=EDGE_WIDTH, w=libplot.DEFAULT_WIDTH, h=libplot.DEFAULT_HEIGHT, show_axes=False, fig=None, ax=None, norm=None, colorbar=False): # plt.cm.plasma): \"\"\" Creates a",
"dir='a') create_cluster_grid(tsne_a, c_a, 'a', dir='a') create_merge_cluster_info(d_a, c_a, 'a', sample_names=samples, dir='a') create_cluster_samples(tsne_a, c_a, samples,",
"print(m, sd) z = (d - m) / sd # find all points",
"= np.where(a2[i, :] > 0)[0] ids3 = np.intersect1d(ids1, ids2) o = len(ids3) /",
"created. norm : Normalize, optional Specify how colors should be normalized Returns -------",
"'{}/{}_{}_separate_clusters.png'.format(dir, method, name) libplot.savefig(fig, out, pad=0) #libplot.savefig(fig, '{}/tsne_{}separate_clusters.pdf'.format(dir, name)) # # # def",
":, 0] #g = data[:, :, 1] #b = data[:, :, 2] a",
"used to make the plot \"\"\" if type(genes) is pd.core.frame.DataFrame: genes = genes['Genes'].values",
": bool, optional, default true Whether to show axes on plot legend :",
"marker=marker, s=s, alpha=alpha, fig=fig, ax=ax, norm=norm) libplot.savefig(fig, out) plt.close(fig) return fig, ax def",
"ax = libplot.new_ax(fig, subplot=(rows, rows, i + 1)) # # x = tsne.iloc[idx2,",
"group = f.create_group(f.root, genome) f.create_carray(group, 'genes', obj=gbm.gene_ids) f.create_carray(group, 'gene_names', obj=gbm.gene_names) f.create_carray(group, 'barcodes', obj=gbm.barcodes)",
"None: fig, ax = libplot.new_fig() libplot.scatter(tsne['TSNE-1'], tsne['TSNE-2'], c=c, marker=marker, label=label, s=s, ax=ax) return",
"ax = libplot.new_fig(w=w, h=h) libcluster.scatter_clusters(d.iloc[:, dim1].values, d.iloc[:, dim2].values, clusters, colors=colors, edgecolors=edgecolors, linewidth=linewidth, markers=markers,",
", axis=1) return scaled def umi_norm_log2(data): d = umi_norm(data) print(type(d)) return umi_log2(d) def",
"# #libplot.savefig(fig, '{}/tsne_{}separate_clusters.pdf'.format(dir, name)) # # def load_clusters(pca, headers, name, cache=True): file =",
"pc1 - 1] y = df2.iloc[:, pc2 - 1] if i in colors:",
"im_base = imagelib.new(w * 300, w * 300) for i in range(0, len(cluster_order)):",
"i == 0: # libcluster.format_axes(ax) # else: # libplot.invisible_axes(ax) ax.set_title('{} ({})'.format(gene_ids[i][2], gene_ids[i][1])) libplot.add_colorbar(fig,",
"matplotlib.cm.BuPu(range(4, 256))) # BGY_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list('bgy', ['#0066ff', '#37c871', '#ffd42a']) # BGY_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list('bgy',",
"imagelib.new(iw, iw) for bin in range(0, bins): bi = bin + 1 idx_bin",
"colors[i] else: color = 'black' else: color = 'black' ax = libplot.new_ax(fig, subplot=(rows,",
"not show_axes: libplot.invisible_axes(ax) legend_params = dict(LEGEND_PARAMS) if isinstance(legend, bool): legend_params['show'] = legend elif",
"break imagelib.save(im_base, out) def cluster_plot(tsne, clusters, dim1=0, dim2=1, markers='o', s=libplot.MARKER_SIZE, colors=None, w=8, h=8,",
"fig=None, ax=None, norm=None, colorbar=False): # plt.cm.plasma): \"\"\" Creates a base expression plot and",
"ax = libplot.new_ax(fig, subplot=(rows, rows, si)) pca_plot_base(pca, clusters, pc1=(i + 1), pc2=(j +",
"im_data[np.where(grey_areas)] # d[:, :] = [255, 255, 255, 0] # im_data[np.where(grey_areas)] = d",
"libtsne.get_cluster_file(name) if not os.path.isfile(file) or not cache: print('{} was not found, creating it",
"genes['Genes'].values ids, gene_names = get_gene_names(data) gene_ids = get_gene_ids(data, genes, ids=ids, gene_names=gene_names) w, h,",
"gene_names = get_gene_names(data) gene_ids = get_gene_ids(data, genes, ids=ids, gene_names=gene_names) w, h, rows, cols",
"0: return pd.DataFrame(MinMaxScaler(feature_range=(min, max)).fit_transform(d), index=d.index, columns=d.columns) else: return pd.DataFrame(MinMaxScaler(feature_range=(min, max)).fit_transform(d.T).T, index=d.index, columns=d.columns) def",
"f['matrix']['features']['name']] barcodes = list(f['matrix']['barcodes'][:]) matrix = sp_sparse.csc_matrix( (f['matrix']['data'], f['matrix']['indices'], f['matrix']['indptr']), shape=f['matrix']['shape']) return GeneBCMatrix(feature_ids,",
"range(0, len(gene_ids)): gene_id = gene_ids[i][1] gene = gene_ids[i][2] print(gene_id, gene) exp = get_gene_data(data,",
"size=4, add_titles=True, type='tsne', format='pdf'): \"\"\" Plot each cluster into its own plot file.",
"top of the background # # sid = 0 # # for sample",
"0].tolist( ), 'Label': np.repeat('tsne-10x', len(x1))}) libplot.boxplot(df, 'Cluster', 'Silhouette Score', colors=libcluster.colors(), ax=ax) ax.set_ylim([-1, 1])",
"libplot.grid_size(n) w = 4 * rows fig = libplot.new_base_fig(w=w, h=w) si = 1",
"out) plt.close(fig) return fig, ax def expr_grid_size(x, size=SUBPLOT_SIZE): \"\"\" Auto size grid to",
"# # ax.set_title('C{} ({:,})'.format(c, len(idx1)), color=colors[i]) # libplot.invisible_axes(ax) # # #set_tsne_ax_lim(tsne, ax) #",
"< 0].quantile(1 - TNSE_AX_Q), d2[d2 >= 0].quantile(TNSE_AX_Q)] #print(xlim, ylim) # ax.set_xlim(xlim) # ax.set_ylim(ylim)",
"umi_norm_log2(d_b) else: d_b = umi_norm_log2_scale(d_b) pca_b = libtsne.load_pca(d_b, 'b', cache=cache) # pca.iloc[idx_b,:] tsne_b",
"import kneighbors_graph from scipy.interpolate import griddata import h5py from scipy.interpolate import interp1d from",
"tsne.iloc[idx1, 0] # y = tsne.iloc[idx1, 1] # # libplot.scatter(x, y, c=colors[sid], ax=ax)",
"ids gene_names : Index, optional Index of gene names Returns ------- list list",
"List of gene names \"\"\" if dir[-1] == '/': dir = dir[:-1] if",
"mean = color.mean() # # #print(x[i], y[i], mean) # # #if mean >",
"alpha=1, linewidth=EDGE_WIDTH, edgecolors='none', colorbar=True, method='tsne', bins=10, background=BACKGROUND_SAMPLE_COLOR): \"\"\" Plot multiple genes on a",
"# im_smooth.save('edges.png', 'png') # # im2.paste(im_smooth, (0, 0), im_smooth) # # im_base.paste(im2, (0,",
"create_expr_plot(tsne, avg, cmap=cmap, w=w, h=h, colorbar=colorbar, norm=norm, alpha=alpha, fig=fig, ax=ax) x = tsne.iloc[:,",
"column is a cell reads_per_bc = data.sum(axis=0) scaling_factors = 1000000 / reads_per_bc scaled",
"out, pad=0) return fig, ax def base_pca_expr_plot(data, exp, dim=[1, 2], cmap=None, marker='o', s=MARKER_SIZE,",
"name, marker='o', s=MARKER_SIZE): for i in range(0, pca.shape[1]): for j in range(i +",
"if gene_id != gene: out = '{}/{}_expr_{}_{}.png'.format(dir, method, gene, gene_id) else: out =",
"from scipy.interpolate import griddata import h5py from scipy.interpolate import interp1d from scipy.spatial import",
"cols=legend_params['cols'], markerscale=legend_params['markerscale']) libplot.invisible_axes(ax) tmp = 'tmp{}.png'.format(i) libplot.savefig(fig, tmp) plt.close(fig) # Open image #",
"\"\"\" if ax is None: fig, ax = libplot.new_fig(w=w, h=h) # if norm",
"mkdir -p Parameters ---------- path : str directory to create. \"\"\" try: os.makedirs(path)",
"x 1 table of n cells with a Cluster column giving each cell",
"ax.scatter(c[:, 0], c[:, 1], c=None) libplot.format_axes(ax) libplot.savefig(fig, '{}_centroids.pdf'.format(name)) def centroid_network(tsne, clusters, name): c",
"tsne_cluster_sample_grid(tsne, clusters, samples, colors=None, size=SUBPLOT_SIZE): # \"\"\" # Plot each cluster separately to",
"1 n = cluster_order.size if cols == -1: cols = int(np.ceil(np.sqrt(n))) rows =",
"c1 = centroids(tsne1, clusters) c2 = centroids(tsne2, clusters) a1 = kneighbors_graph(c1, k, mode='distance',",
"tsne_a = libtsne.load_pca_tsne(pca_a, 'a', cache=cache) c_a = libtsne.load_phenograph_clusters(pca_a, 'a', cache=cache) create_pca_plot(pca_a, c_a, 'a',",
"marker='o', s=MARKER_SIZE): rows = libplot.grid_size(n) w = 4 * rows fig = libplot.new_base_fig(w=w,",
"imagelib.open(tmp) # im_no_bg = imagelib.remove_background(im) # im_smooth = imagelib.smooth_edges(im_no_bg) # imagelib.paste(im_no_bg, im_smooth, inplace=True)",
"---------- # tsne : Pandas dataframe # Cells x tsne tsne data. Columns",
"linewidth=linewidth, s=s) # Plot cluster over the top of the background x =",
"# # ax = libplot.new_ax(fig, subplot=(rows, rows, i + 1)) # # x",
"prefix='', index=None, dir='GeneExp', cmap=OR_RED_CMAP, # BGY_CMAP, norm=None, w=libplot.DEFAULT_WIDTH, h=libplot.DEFAULT_HEIGHT, alpha=1.0, colorbar=False, method='tsne', fig=None,",
"pad=0) return fig, ax def base_pca_expr_plot(data, exp, dim=[1, 2], cmap=None, marker='o', s=MARKER_SIZE, alpha=EXP_ALPHA,",
"d1)][idx] y = data.iloc[idx, dim[1] - 1].values # data['{}-{}'.format(t, d2)][idx] e = exp[idx]",
"sort=True, show_axes=False, ax=None, cluster_order=None, format='png', dir='.', out=None): if out is None: # libtsne.get_tsne_plot_name(name))",
"markerscale=legend_params['markerscale']) return fig, ax def base_cluster_plot_outline(out, d, clusters, s=libplot.MARKER_SIZE, colors=None, edgecolors=EDGE_COLOR, linewidth=EDGE_WIDTH, dim1=0,",
"#g = data[:, :, 1] #b = data[:, :, 2] a = im_data[:,",
"separate_cluster(d, clusters, cluster, color=color, size=w, s=s, linewidth=linewidth, add_titles=False) # get x y lim",
"data has rows. d1 : int, optional First dimension being plotted (usually 1)",
"= y[idx] points = np.array([[p1, p2] for p1, p2 in zip(x, y)]) hull",
"pca.index[i]) return fig, ax def pca_plot(pca, clusters, pc1=1, pc2=2, marker='o', labels=False, s=MARKER_SIZE, w=8,",
"colors=None, size=SUBPLOT_SIZE): # \"\"\" # Plot each cluster separately to highlight samples #",
"200) & (b < 255) & (b > 200) # # # d",
"# if id exists, pick the first idx = idx[0] else: # if",
"= libtsne.load_pca_tsne(pca_a, 'a', cache=cache) c_a = libtsne.load_phenograph_clusters(pca_a, 'a', cache=cache) create_pca_plot(pca_a, c_a, 'a', dir='a')",
"ax=None, norm=None): # plt.cm.plasma): fig, ax = base_expr_plot(data, exp, t='PC', dim=dim, cmap=cmap, marker=marker,",
"def separate_clusters(tsne, clusters, name, colors=None, size=4, add_titles=True, type='tsne', format='pdf'): \"\"\" Plot each cluster",
"ax = libplot.new_ax(fig, rows, cols, i + 1) expr_plot(tsne, exp, ax=ax, cmap=cmap, colorbar=False)",
"gene_name)[0] if len(gene_indices) == 0: raise Exception(\"%s was not found in list of",
"# # #print('Label {}'.format(l)) # idx2 = np.where(clusters['Cluster'] != c)[0] # # #",
"cluster_order=None, fig=None, ax=None, out=None): fig, ax = base_cluster_plot(tsne, clusters, markers=markers, colors=colors, dim1=dim1, dim2=dim2,",
"libcluster.format_legend(ax, cols=6, markerscale=2) return fig, ax def base_expr_plot(data, exp, dim=[1, 2], cmap=plt.cm.plasma, marker='o',",
"created. ax : matplotlib ax, optional Supply an axis object on which to",
"isinstance(d_a, SparseDataFrame): d_b = umi_norm_log2(d_b) else: d_b = umi_norm_log2_scale(d_b) pca_b = libtsne.load_pca(d_b, 'b',",
"should be labeled 'TSNE-1', 'TSNE-2' etc cluster : int Clusters in colors :",
"the plot ax : Matplotlib axes Axes used to render the figure \"\"\"",
"data.iloc[idx, dim[0] - 1].values # data['{}-{}'.format(t, d1)][idx] y = data.iloc[idx, dim[1] - 1].values",
"c=c, s=s, label=label, fig=fig, ax=ax) #libtsne.tsne_legend(ax, labels, colors) libcluster.format_simple_axes(ax, title=\"t-SNE\") libcluster.format_legend(ax, cols=6, markerscale=2)",
"1.5 avg = (avg - avg.min()) / (avg.max() - avg.min()) # min_max_scale(avg) create_expr_plot(tsne,",
"ax=ax) ax.set_ylim([-1, 1]) ax.set_title('tsne-10x') #libplot.savefig(fig, 'RK10001_10003_clust-phen_silhouette.pdf') ax = fig.add_subplot(212) # libplot.newfig(w=9) df2 =",
"created and returned. ax : matplotlib axis If ax is a supplied argument,",
"#libplot.savefig(fig, 'RK10001_10003_clust-phen_silhouette.pdf') ax = fig.add_subplot(212) # libplot.newfig(w=9) df2 = pd.DataFrame({'Silhouette Score': x2, 'Cluster':",
"# im_smooth = im_edges.filter(ImageFilter.SMOOTH) # im_smooth.save('edges.png', 'png') # # im2.paste(im_smooth, (0, 0), im_smooth)",
"#r = data[:, :, 0] # #g = data[:, :, 1] # #b",
"data.multiply(scaling_factors) # , axis=1) return scaled def umi_norm_log2(data): d = umi_norm(data) print(type(d)) return",
"raising exception to work more like mkdir -p Parameters ---------- path : str",
"raise Exception(\"Genome %s does not exist in this file.\" % genome) except KeyError:",
"gene_names = get_gene_names(data) exp = get_gene_data(data, genes, ids=ids, gene_names=gene_names) avg = exp.mean(axis=0) avg",
"given gene list, get all of the transcripts. Parameters ---------- data : DataFrame",
"libplot.savefig(fig, '{}_centroids.pdf'.format(name)) def centroid_network(tsne, clusters, name): c = centroids(tsne, clusters) A = kneighbors_graph(c,",
"StandardScaler(with_mean=False).fit_transform(d.T.matrix) return SparseDataFrame(sd.T, index=d.index, columns=d.columns) else: # StandardScaler().fit_transform(d.T) sd = sklearn.preprocessing.scale(d, axis=axis) #sd",
"# im_no_bg = imagelib.remove_background(im) # im_smooth = imagelib.smooth_edges(im_no_bg) # imagelib.paste(im_no_bg, im_smooth, inplace=True) #",
"ret = [] for i in range(len(gbm.barcodes)): ret.append(np.sum(gbm.matrix[:, i].toarray())) return ret def df(gbm):",
"format=format) fig, ax = cluster_plot(tsne_b, c_b, legend=False, w=w, h=h) libplot.savefig(fig, 'b/b_tsne_clusters_med.pdf') def sample_clusters(d,",
"etc clusters : DataFrame Clusters in colors : list, color Colors of points",
"ax.set_ylim(ylim) def base_cluster_plot(d, clusters, markers=None, s=libplot.MARKER_SIZE, colors=None, edgecolors=EDGE_COLOR, linewidth=EDGE_WIDTH, dim1=0, dim2=1, w=8, h=8,",
"edges # #black_areas = (a > 0) #(r < 255) | (g <",
"h=h, # colorbar=colorbar) # # set_tsne_ax_lim(tsne, ax) # # libplot.invisible_axes(ax) # # if",
"libcluster.format_simple_axes(ax, title=\"t-SNE\") libcluster.format_legend(ax, cols=6, markerscale=2) return fig, ax def base_expr_plot(data, exp, dim=[1, 2],",
"base_cluster_plot(d, clusters, markers=None, s=libplot.MARKER_SIZE, colors=None, edgecolors=EDGE_COLOR, linewidth=EDGE_WIDTH, dim1=0, dim2=1, w=8, h=8, alpha=ALPHA, #",
"not os.path.isfile(file) or not cache: print('{} was not found, creating it with...'.format(file)) #",
"= imagelib.edges(im_no_bg) im_smooth = imagelib.smooth(im_edges) im_outline = imagelib.paste(im_no_bg, im_smooth) imagelib.paste(im_base, im_outline, inplace=True) #",
"out, pad=0) #libplot.savefig(fig, '{}/tsne_{}separate_clusters.pdf'.format(dir, name)) # # # def tsne_cluster_sample_grid(tsne, clusters, samples, colors=None,",
"= True base_expr_plot(data, exp, dim=dim, s=s, marker=marker, edgecolors=edgecolors, linewidth=linewidth, alpha=alpha, cmap=cmap, norm=norm, w=w,",
"np.array(list(range(0, len(ids)))) if colors is None: colors = libcluster.get_colors() for i in indices:",
"> 200) # # d = im_data[np.where(grey_areas)] # d[:, :] = [255, 255,",
"= d im2 = Image.fromarray(im_data) im2.save('edges.png', 'png') # overlay edges on top of",
"<filename>lib10x/lib10x.py # -*- coding: utf-8 -*- \"\"\" Created on Wed Jun 6 16:51:15",
"to its median size Parameters ---------- data : Pandas dataframe Matrix of umi",
"w=4, h=4, s=30, alpha=ALPHA, linewidth=EDGE_WIDTH, edgecolors='none', colorbar=True, method='tsne', format='png'): \"\"\" Plot multiple genes",
"is_first: if colorbar: libplot.add_colorbar(fig, cmap, norm=norm) #libcluster.format_simple_axes(ax, title=t) if not show_axes: libplot.invisible_axes(ax) return",
"= np.linspace(x.min(), x.max(), nx) yi = np.linspace(y.min(), y.max(), ny) x = x[idx] y",
"# c1 = color.copy() # c1[-1] = 0.5 # # #print(c1) # #",
"y[i], mean) # # #if mean > 0.5: # ax.scatter(x[i], # y[i], #",
"= get_gene_data(data, gene_id, ids=ids, gene_names=gene_names) bin_means, bin_edges, binnumber = binned_statistic(exp, exp, bins=bins) print(binnumber.min(),",
"cmap=None, marker='o', s=MARKER_SIZE, alpha=EXP_ALPHA, fig=None, ax=None, norm=None): # plt.cm.plasma): fig, ax = base_expr_plot(data,",
"fig, ax # def expr_plot(tsne, # exp, # d1=1, # d2=2, # x1=None,",
"np.array([distance.euclidean(centroid, (a, b)) for a, b in zip(x, y)]) sd = d.std() m",
"ax=ax, edgecolors='none', # edgecolors, linewidth=linewidth, s=s) if add_titles: if isinstance(cluster, int): prefix =",
"ax.set_title('{} ({})'.format(gene_ids[i][2], gene_ids[i][1])) libplot.add_colorbar(fig, cmap) return fig def genes_expr(data, tsne, genes, prefix='', dim=[1,",
"'genes', obj=gbm.gene_ids) f.create_carray(group, 'gene_names', obj=gbm.gene_names) f.create_carray(group, 'barcodes', obj=gbm.barcodes) f.create_carray(group, 'data', obj=gbm.matrix.data) f.create_carray(group, 'indices',",
"is pd.core.frame.DataFrame: l = x.shape[0] else: return None cols = int(np.ceil(np.sqrt(l))) w =",
"method='tsne', dir='.', out=None): fig = cluster_grid(tsne, clusters, colors=colors, cols=cols, size=size, add_titles=add_titles, cluster_order=cluster_order) if",
"0] = centroid[0] ret[i, 1] = centroid[1] return ret def knn_method_overlaps(tsne1, tsne2, clusters,",
"ax) # # return fig # # # def create_tsne_cluster_sample_grid(tsne, clusters, samples, name,",
"exist, try the gene names indexes = np.where(gene_names == g)[0] for index in",
"!= bi)[0] tsne_other = tsne.iloc[idx_other, :] fig, ax = libplot.new_fig(w, w) x =",
"optional List of cluster ids in the order they should be rendered Returns",
"#cmap = plt.cm.plasma ids, gene_names = get_gene_names(data) print(ids, gene_names, genes) gene_ids = get_gene_ids(data,",
"#ax.contour(xi, yi, z, levels=1) def gene_expr(data, tsne, gene, fig=None, ax=None, cmap=plt.cm.plasma, out=None): \"\"\"",
"= node.read() print(dsets) matrix = sp_sparse.csc_matrix( (dsets['data'], dsets['indices'], dsets['indptr']), shape=dsets['shape']) return GeneBCMatrix(decode(dsets['genes']), decode(dsets['gene_names']),",
"detect on what is left (the clusters) # im_edges = im2.filter(ImageFilter.FIND_EDGES) # #",
"d1 = tsne.iloc[:, 0] d2 = tsne.iloc[:, 1] xlim = [d1[d1 < 0].quantile(1",
"'' ax.set_title('{}{} ({:,})'.format( prefix, cluster, len(idx1)), color=color) ax.axis('off') # libplot.invisible_axes(ax) return fig, ax",
"cache: print('{} was not found, creating it with...'.format(file)) # Find the interesting clusters",
"= gene_ids[i][2] print(gene, gene_id) exp = get_gene_data(data, gene_id, ids=ids, gene_names=gene_names) ax = libplot.new_ax(fig,",
"cluster over the top of the background # # x = tsne.iloc[idx1, 0]",
"vmax=3, clip=True) #cmap = plt.cm.plasma ids, gene_names = get_gene_names(data) gene_ids = get_gene_ids(data, genes,",
": int, optional Marker size w : int, optional Plot width h :",
"header=True, index=True) def sum(gbm, axis=0): return gbm.matrix.sum(axis=axis) def tpm(gbm): m = gbm.matrix s",
"0.3, 0.3) np.random.seed(0) GeneBCMatrix = collections.namedtuple( 'GeneBCMatrix', ['gene_ids', 'gene_names', 'barcodes', 'matrix']) def decode(items):",
"libplot.savefig(fig, out) libplot.savefig(fig, 'tmp.png') plt.close(fig) def cluster_grid(tsne, clusters, colors=None, cols=-1, size=SUBPLOT_SIZE, add_titles=True, cluster_order=None):",
"def node_color_from_cluster(clusters): colors = libcluster.colors() return [colors[clusters['Cluster'][i] - 1] for i in range(0,",
"if (e.min() == 0): #print('Data does not appear to be z-scored. Transforming now...')",
"gene_names=gene_names) avg = exp.mean(axis=0) avg = (avg - avg.mean()) / avg.std() avg[avg <",
"for i in indices: print('index', i) cluster = ids[i] if isinstance(colors, dict): color",
"c=c, marker=marker, label=label, s=s, ax=ax) return fig, ax def tsne_plot(tsne, marker='o', s=libplot.MARKER_SIZE, c='red',",
"10 SUBPLOT_SIZE = 4 EXP_ALPHA = 0.8 # '#f2f2f2' #(0.98, 0.98, 0.98) #(0.8,",
"300, w * 300) for i in range(0, len(cluster_order)): print('index', i, cluster_order[i]) cluster",
"labels=False, s=MARKER_SIZE, w=8, h=8, fig=None, ax=None): colors = libcluster.get_colors() if ax is None:",
"# Edge detect on what is left (the clusters) imageWithEdges = im1.filter(ImageFilter.FIND_EDGES) im_data",
"int, optional Plot height alpha : float (0, 1), optional Tranparency of markers.",
"rows, cols def get_gene_names(data): if ';' in data.index[0]: ids, genes = data.index.str.split(';').str else:",
"Matplotlib figure used to make the plot # \"\"\" # # # cids",
"'a', sample_names=samples, dir='a') create_cluster_samples(tsne_a, c_a, samples, 'a_sample', dir='a') genes_expr(d_a, tsne_a, genes, prefix='a_BGY', cmap=BLUE_GREEN_YELLOW_CMAP,",
"0.85 BACKGROUND_SAMPLE_COLOR = [0.75, 0.75, 0.75] EDGE_COLOR = None # [0.3, 0.3, 0.3]",
"A = kneighbors_graph(c, 5, mode='distance', metric='euclidean').toarray() G = nx.from_numpy_matrix(A) pos = nx.spring_layout(G) fig,",
": int, optional Plot height alpha : float (0, 1), optional Tranparency of",
"t-sne expression plot. # # Parameters # ---------- # data : pandas.DataFrame #",
"exp = get_gene_data(data, gene_id, ids=ids, gene_names=gene_names) bin_means, bin_edges, binnumber = binned_statistic(exp, exp, bins=bins)",
"size) # # libplot.savefig(fig, '{}/tsne_{}_sample_clusters.png'.format(dir, name)) # #libplot.savefig(fig, '{}/tsne_{}separate_clusters.pdf'.format(dir, name)) # # def",
"# r = im_data[:, :, 0] # g = im_data[:, :, 1] #",
"= A[0:500, 0:500] # # G=nx.from_numpy_matrix(A) # pos=nx.spring_layout(G) #, k=2) # # #node_color",
"b \"\"\" cache = True counts = libcluster.remove_empty_rows(counts) # ['AICDA', 'CD83', 'CXCR4', 'MKI67',",
"the supplied figure, otherwise a new figure is created and returned. ax :",
"idx = np.where(np.isin(ids, g))[0] if idx.size < 1: # if id does not",
"return fig, ax def base_pca_expr_plot(data, exp, dim=[1, 2], cmap=None, marker='o', s=MARKER_SIZE, alpha=EXP_ALPHA, fig=None,",
"method='tsne', format='png'): \"\"\" Plot multiple genes on a grid. Parameters ---------- data :",
": Matplotlib figure A new Matplotlib figure used to make the plot \"\"\"",
"umi_norm(data) print(type(d)) return umi_log2(d) def scale(d, clip=None, min=None, max=None, axis=1): if isinstance(d, SparseDataFrame):",
"'#003366', '#339933', '#ffff66', '#ffff00']) # BGY_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list('bgy', ['#00264d', '#003366', '#339933', '#e6e600', '#ffff33'])",
"BGY_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list('bgy', ['#00264d', '#003366', '#339933', '#e6e600', '#ffff33']) # BGY_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list('bgy', ['#003366',",
"libcluster.format_legend(ax, cols=legend_params['cols'], markerscale=legend_params['markerscale']) libplot.invisible_axes(ax) tmp = 'tmp{}.png'.format(i) libplot.savefig(fig, tmp) plt.close(fig) # Open image",
"kneighbors_graph(c, 5, mode='distance', metric='euclidean').toarray() G = nx.from_numpy_matrix(A) pos = nx.spring_layout(G) fig, ax =",
"color # + '7f' libplot.scatter(x, y, c=color, ax=ax, edgecolors='none', # edgecolors, linewidth=linewidth, s=s)",
"# return fig, ax def create_expr_plot(tsne, exp, dim=[1, 2], cmap=None, marker='o', s=MARKER_SIZE, alpha=EXP_ALPHA,",
"# # rows = int(np.ceil(np.sqrt(len(cids)))) # # w = size * rows #",
"name)) # #libplot.savefig(fig, '{}/tsne_{}separate_clusters.pdf'.format(dir, name)) # # def load_clusters(pca, headers, name, cache=True): file",
"figure # A new Matplotlib figure used to make the plot # \"\"\"",
"len(gene_ids)): gene_id = gene_ids[i][1] gene = gene_ids[i][2] print(gene_id, gene) exp = get_gene_data(data, gene_id,",
"dict): color = colors[cluster] elif isinstance(colors, list): if cluster < len(colors): # np.where(clusters['Cluster']",
"def create_expr_plot(tsne, exp, dim=[1, 2], cmap=None, marker='o', s=MARKER_SIZE, alpha=EXP_ALPHA, fig=None, ax=None, w=libplot.DEFAULT_WIDTH, h=libplot.DEFAULT_HEIGHT,",
"'#ffe066']) GYBLGRYL_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list( 'grey_blue_green_yellow', ['#e6e6e6', '#0055d4', '#00aa44', '#ffe066']) OR_RED_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list( 'or_red',",
"% version) feature_ids = [x.decode('ascii', 'ignore') for x in f['matrix']['features']['id']] feature_names = [x.decode('ascii',",
"'{}/pca_{}_pc{}_vs_pc{}.{}'.format(dir, name, pc1, pc2, format) fig, ax = pca_plot(pca, clusters, pc1=pc1, pc2=pc2, labels=labels,",
"colorbar=True, method='tsne', format='png'): \"\"\" Plot multiple genes on a grid. Parameters ---------- data",
"(the clusters) # im_edges = im2.filter(ImageFilter.FIND_EDGES) # # im_smooth = im_edges.filter(ImageFilter.SMOOTH) # #",
"lib10x.sample import * from scipy.spatial import ConvexHull from PIL import Image, ImageFilter from",
"w=8, h=8, fig=None, ax=None): colors = libcluster.get_colors() if ax is None: fig, ax",
"# sid += 1 # # ax.set_title('C{} ({:,})'.format(c, len(idx1)), color=colors[i]) # libplot.invisible_axes(ax) #",
"figure used to make the plot \"\"\" if cluster_order is None: ids =",
"cmap=cmap, # marker=marker, # s=s, # alpha=alpha, # fig=fig, # ax=ax, # norm=norm,",
"base_cluster_plot_outline(out, d, clusters, s=libplot.MARKER_SIZE, colors=None, edgecolors=EDGE_COLOR, linewidth=EDGE_WIDTH, dim1=0, dim2=1, w=8, alpha=ALPHA, # libplot.ALPHA,",
"= matplotlib.colors.LinearSegmentedColormap.from_list( 'grey_purple_yellow', ['#e6e6e6', '#3333ff', '#ff33ff', '#ffe066']) GYBLGRYL_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list( 'grey_blue_green_yellow', ['#e6e6e6', '#0055d4',",
"(d < x2))[0] x = x[idx] y = y[idx] points = np.array([[p1, p2]",
"else: pass if legend_params['show']: libcluster.format_legend(ax, cols=legend_params['cols'], markerscale=legend_params['markerscale']) return fig, ax def base_cluster_plot_outline(out, d,",
"cmap=cmap, marker=marker, s=s, alpha=alpha, fig=fig, w=w, h=h, ax=ax, show_axes=show_axes, colorbar=colorbar, norm=norm, linewidth=linewidth, edgecolors=edgecolors)",
"# # # Edge detect on what is left (the clusters) # im_edges",
"max=None, axis=1): if isinstance(d, SparseDataFrame): print('UMI norm log2 scale sparse') sd = StandardScaler(with_mean=False).fit_transform(d.T.matrix)",
"ax = libplot.newfig(w=8, h=8) # list(range(0, c.shape[0])) node_color = libcluster.colors()[0:c.shape[0]] cmap = libcluster.colormap()",
"si += 1 return fig def pca_plot_base(pca, clusters, pc1=1, pc2=2, marker='o', labels=False, s=MARKER_SIZE,",
":, 2] a = im_data[:, :, 3] # (r < 255) | (g",
"#im_data[np.where(black_areas)] = d # # #im3 = Image.fromarray(im_data) # #im2.save('edges.png', 'png') # #",
"w=16, h=16, legend=True): sc = sample_clusters(clusters, sample_names) create_cluster_plot(tsne_umi_log2, sc, name, method=method, format=format, dir=dir,",
"imagelib.remove_background(im) im_edges = imagelib.edges(im) im_outline = imagelib.paste(im, im_edges) # im_no_bg im_smooth = imagelib.smooth(im_outline)",
"in range(0, len(gene_ids)): gene_id = gene_ids[i][1] gene = gene_ids[i][2] print(gene_id, gene) exp =",
"max = abs(clip) min = -max if isinstance(min, float) or isinstance(min, int): print('z",
"list(range(0, c.shape[0])) node_color = libcluster.colors()[0:c.shape[0]] cmap = libcluster.colormap() labels = {} for i",
"= colors[cluster] elif isinstance(colors, list): if cluster < len(colors): # np.where(clusters['Cluster'] == cluster)[0]]",
"def create_cluster_plot(d, clusters, name, dim1=0, dim2=1, method='tsne', markers='o', s=libplot.MARKER_SIZE, w=8, h=8, colors=None, legend=True,",
"colors) libcluster.format_simple_axes(ax, title=\"t-SNE\") libcluster.format_legend(ax, cols=6, markerscale=2) return fig, ax def base_expr_plot(data, exp, dim=[1,",
"inplace=True) im = imagelib.open(tmp) if outline: im_no_bg = imagelib.remove_background(im) im_edges = imagelib.edges(im) im_outline",
"Columns should be labeled 'TSNE-1', 'TSNE-2' etc clusters : DataFrame Clusters in colors",
"cluster into its own plot file. \"\"\" ids = list(sorted(set(clusters['Cluster']))) indices = np.array(list(range(0,",
"import ConvexHull from PIL import Image, ImageFilter from scipy.stats import binned_statistic import imagelib",
"h=8, legend=True, fig=None, ax=None): fig, ax = pca_plot_base(pca, clusters, pc1=pc1, pc2=pc2, marker=marker, labels=labels,",
"\"\"\" Create a cluster matrix based on by labelling cells by sample/batch. \"\"\"",
"If fig is a supplied argument, return the supplied figure, otherwise a new",
"ax=ax) # # # Plot cluster over the top of the background #",
"\"\"\" cache = True counts = libcluster.remove_empty_rows(counts) # ['AICDA', 'CD83', 'CXCR4', 'MKI67', 'MYC',",
"elif isinstance(legend, dict): legend_params.update(legend) else: pass if legend_params['show']: libcluster.format_legend(ax, cols=legend_params['cols'], markerscale=legend_params['markerscale']) libplot.invisible_axes(ax) tmp",
"# libplot.invisible_axes(ax) # # if out is not None: # libplot.savefig(fig, out, pad=0)",
"tsne data. Columns should be labeled 'TSNE-1', 'TSNE-2' etc genes : array List",
"not exist, try the gene names idx = np.where(gene_names == g)[0] if idx.size",
"= Image.fromarray(im_data) im2.save('edges.png', 'png') # overlay edges on top of original image to",
"ax = base_expr_plot(data, exp, t='PC', dim=dim, cmap=cmap, marker=marker, s=s, fig=fig, alpha=alpha, ax=ax, norm=norm)",
"f.create_carray(group, 'shape', obj=gbm.matrix.shape) except: raise Exception(\"Failed to write H5 file.\") def subsample_matrix(gbm, barcode_indices):",
"is created. norm : Normalize, optional Specify how colors should be normalized Returns",
"cluster_order is None: ids = np.array(list(sorted(set(clusters['Cluster'])))) cluster_order = np.array(list(range(0, len(ids)))) + 1 n",
"Columns should be labeled 'TSNE-1', 'TSNE-2' etc genes : array List of gene",
"node.read() # for node in f.walk_nodes('/matrix', 'Array'): # dsets[node.name] = node.read() print(dsets) matrix",
"# idx2 = np.where(clusters['Cluster'] != c)[0] # # # Plot background points #",
"node_color=node_color, vmax=(c.shape[0] - 1), cmap=libcluster.colormap()) nx.draw_networkx(G, with_labels=True, labels=labels, ax=ax, node_size=800, node_color=node_color, font_color='white', font_family='Arial')",
"def scale(d, clip=None, min=None, max=None, axis=1): if isinstance(d, SparseDataFrame): print('UMI norm log2 scale",
"np.where(ids == cluster)[0][0] print('index', i, cluster, colors) if isinstance(colors, dict): color = colors.get(cluster,",
"labels, graph, Q = phenograph.cluster(pca, k=20) if min(labels) == -1: new_label = 100",
"= colors[cluster] # elif isinstance(colors, list): # color = colors[i] # else: #",
"# # # def create_tsne_cluster_sample_grid(tsne, clusters, samples, name, colors=None, size=SUBPLOT_SIZE, dir='.'): # \"\"\"",
"matrix based on by labelling cells by sample/batch. \"\"\" sc = np.array(['' for",
"# if id does not exist, try the gene names indexes = np.where(gene_names",
"BACKGROUND_SAMPLE_COLOR = [0.75, 0.75, 0.75] EDGE_COLOR = None # [0.3, 0.3, 0.3] #'#4d4d4d'",
"pc2=pc2, marker=marker, labels=labels, s=s, w=w, h=h, fig=fig, ax=ax) #libtsne.tsne_legend(ax, labels, colors) libcluster.format_simple_axes(ax, title=\"PC\")",
"a given gene list, get all of the transcripts. Parameters ---------- data :",
"k, mode='distance', metric='euclidean').toarray() a2 = kneighbors_graph(c2, k, mode='distance', metric='euclidean').toarray() overlaps = [] for",
"'#3333ff', '#ff33ff', '#ffe066']) GYBLGRYL_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list( 'grey_blue_green_yellow', ['#e6e6e6', '#0055d4', '#00aa44', '#ffe066']) OR_RED_CMAP =",
"64] # #im_data[np.where(black_areas)] = d # # #im3 = Image.fromarray(im_data) # #im2.save('edges.png', 'png')",
"def umi_log2(d): if isinstance(d, SparseDataFrame): print('UMI norm log2 sparse') return d.log2(add=1) else: return",
"h, rows, cols def get_gene_names(data): if ';' in data.index[0]: ids, genes = data.index.str.split(';').str",
"is an newer version that is not supported by this function.' % version)",
"new ax. Returns ------- fig : Matplotlib figure A new Matplotlib figure used",
"Parameters ---------- data : Pandas dataframe features x dimensions, e.g. rows are cells",
"libplot.invisible_axes(ax) # # #set_tsne_ax_lim(tsne, ax) # # return fig # # # def",
"im_edges = imagelib.edges(im_no_bg) im_smooth = imagelib.smooth(im_edges) im_outline = imagelib.paste(im_no_bg, im_smooth) imagelib.paste(im_base, im_outline, inplace=True)",
"zip(x1, y1)]) #hull = ConvexHull(points) #ax.plot(points[hull.vertices,0], points[hull.vertices,1]) #zi = griddata((x, y), avg1, (xi,",
"= np.where(counts.columns.isin(b_barcodes['Barcode'].values))[0] d_b = counts.iloc[:, idx] d_b = libcluster.remove_empty_rows(d_b) if isinstance(d_a, SparseDataFrame): d_b",
"on a grid. Parameters ---------- data : Pandas dataframe Genes x samples expression",
"exp = get_gene_data(data, genes, ids=ids, gene_names=gene_names) avg = exp.mean(axis=0) avg = (avg -",
"fig, ax = libplot.new_fig(w=w, h=h) libcluster.scatter_clusters(d.iloc[:, dim1].values, d.iloc[:, dim2].values, clusters, colors=colors, edgecolors=edgecolors, linewidth=linewidth,",
"< -1.5] = -1.5 avg[avg > 1.5] = 1.5 avg = (avg -",
"norm=None, colorbar=False): # plt.cm.plasma): \"\"\" Creates a base expression plot and adds a",
"GeneBCMatrix Returns ------- object : Pandas DataFrame shape(n_cells, n_genes) \"\"\" df = pd.DataFrame(gbm.matrix.todense())",
"edgecolors=EDGE_COLOR, linewidth=1, s=MARKER_SIZE, alpha=1, w=libplot.DEFAULT_WIDTH, h=libplot.DEFAULT_HEIGHT, fig=None, ax=None, norm=None): # plt.cm.plasma): \"\"\" Base",
"colors=None, size=4, add_titles=True, type='tsne', format='pdf'): \"\"\" Plot each cluster into its own plot",
"libplot import libcluster import libtsne import seaborn as sns from libsparse.libsparse import SparseDataFrame",
"w=libplot.DEFAULT_WIDTH, h=libplot.DEFAULT_HEIGHT, edgecolors=EDGE_COLOR, linewidth=EDGE_WIDTH, norm=None, method='tsne', show_axes=False, colorbar=True, out=None): # plt.cm.plasma): \"\"\" Creates",
"imagelib.open(tmp) if outline: im_no_bg = imagelib.remove_background(im) im_edges = imagelib.edges(im) im_outline = imagelib.paste(im, im_edges)",
"in f.walk_nodes('/matrix', 'Array'): # dsets[node.name] = node.read() print(dsets) matrix = sp_sparse.csc_matrix( (dsets['data'], dsets['indices'],",
"w * 300) for i in range(0, len(cluster_order)): print('index', i, cluster_order[i]) cluster =",
"'png') # # im_smooth = im_edges.filter(ImageFilter.SMOOTH) # im_smooth.save('edges.png', 'png') # # im2.paste(im_smooth, (0,",
"np import scipy.sparse as sp_sparse import tables import pandas as pd from sklearn.manifold",
"labeled 'TSNE-1', 'TSNE-2' etc clusters : DataFrame Clusters in colors : list, color",
"titles to plots plot_order: list, optional List of cluster ids in the order",
"ax=ax, cluster_order=cluster_order, sort=sort) #set_tsne_ax_lim(tsne, ax) # libcluster.format_axes(ax) if not show_axes: libplot.invisible_axes(ax) legend_params =",
"cmap=OR_RED_CMAP, # BGY_CMAP, norm=None, w=libplot.DEFAULT_WIDTH, h=libplot.DEFAULT_HEIGHT, alpha=1.0, colorbar=False, method='tsne', fig=None, ax=None, sdmax=0.5): \"\"\"",
"== b) & (g == b) black_areas = (a > 0) d =",
"avg = (avg - avg.min()) / (avg.max() - avg.min()) # min_max_scale(avg) create_expr_plot(tsne, avg,",
"(0, 1), optional Tranparency of markers. show_axes : bool, optional, default true Whether",
"= pd.DataFrame(sc, index=d.index, columns=['Cluster']) return df def create_cluster_samples(tsne_umi_log2, clusters, sample_names, name, method='tsne', format='png',",
"data.index if isinstance(genes, pd.core.frame.DataFrame): genes = genes['Genes'].values if norm is None: norm =",
"cluster_map, labels def umi_tpm(data): # each column is a cell reads_per_bc = data.sum(axis=0)",
"'TSNE-1', 'TSNE-2' etc genes : array List of gene names \"\"\" exp =",
"not supported by this function.' % version) feature_ids = [x.decode('ascii', 'ignore') for x",
"centroids(tsne1, clusters) c2 = centroids(tsne2, clusters) a1 = kneighbors_graph(c1, k, mode='distance', metric='euclidean').toarray() a2",
"bin in range(0, bins): bi = bin + 1 idx_bin = np.where(binnumber ==",
"return gbm.matrix[gene_indices[0], :].toarray().squeeze() def gbm_to_df(gbm): return pd.DataFrame(gbm.matrix.todense(), index=gbm.gene_names, columns=gbm.barcodes) def get_barcode_counts(gbm): ret =",
"0: # Assume we will add a row for a color bar rows",
"Parameters ---------- d : Pandas dataframe t-sne, umap data clusters : Pandas dataframe",
"---------- gbm : a GeneBCMatrix Returns ------- object : Pandas DataFrame shape(n_cells, n_genes)",
"label. s : int, optional Marker size w : int, optional Plot width",
"table containing and index genes : list List of strings of gene ids",
"x, y in zip(x1, y1)]) #hull = ConvexHull(points) #ax.plot(points[hull.vertices,0], points[hull.vertices,1]) #zi = griddata((x,",
"d_b = umi_norm_log2_scale(d_b) pca_b = libtsne.load_pca(d_b, 'b', cache=cache) # pca.iloc[idx_b,:] tsne_b = libtsne.load_pca_tsne(pca_b,",
"= d # # #im3 = Image.fromarray(im_data) # #im2.save('edges.png', 'png') # # im_smooth",
"does not exist, try the gene names idx = np.where(gene_names == g)[0] if",
"0].quantile(TNSE_AX_Q)] #print(xlim, ylim) # ax.set_xlim(xlim) # ax.set_ylim(ylim) def base_cluster_plot(d, clusters, markers=None, s=libplot.MARKER_SIZE, colors=None,",
"a tsne plot without the formatting \"\"\" if ax is None: fig, ax",
"pad=0) libplot.savefig(fig, out, pad=0) plt.close(fig) im1 = Image.open('tmp.png') # Edge detect on what",
"gene_id) else: out = '{}/{}_expr_{}.png'.format(dir, method, gene) print(out) # overlay edges on top",
"# Plot separate clusters colored by sample # \"\"\" # fig = tsne_cluster_sample_grid(tsne,",
"Tranparency of markers. show_axes : bool, optional, default true Whether to show axes",
"data.sum(axis=0) scaling_factors = 1000000 / reads_per_bc scaled = data.multiply(scaling_factors) # , axis=1) return",
":] fig, ax = libplot.new_fig(w, w) x = tsne_other.iloc[:, 0] y = tsne_other.iloc[:,",
"i in range(0, pca.shape[1]): for j in range(i + 1, pca.shape[1]): create_cluster_plot(pca, labels,",
"i in range(0, c1.shape[0]): ids1 = np.where(a1[i, :] > 0)[0] ids2 = np.where(a2[i,",
"genes, ids=None, gene_names=None): \"\"\" For a given gene list, get all of the",
"= im2.filter(ImageFilter.FIND_EDGES) # # # im_data = np.array(im_edges.convert('RGBA')) # # #r = data[:,",
"(xi, yi)) #ax.contour(xi, yi, z, levels=1) def gene_expr(data, tsne, gene, fig=None, ax=None, cmap=plt.cm.plasma,",
"fig, ax = base_pca_expr_plot(data, expr, dim=dim, cmap=cmap, marker=marker, s=s, alpha=alpha, fig=fig, ax=ax, norm=norm)",
"def get_gene_ids(data, genes, ids=None, gene_names=None): \"\"\" For a given gene list, get all",
"if i < len(colors): # colors[cid - 1] #colors[i] #np.where(clusters['Cluster'] == cluster)[0]] color",
"c_b, samples, 'b_sample', dir='b') genes_expr(d_b, tsne_b, genes, prefix='b_BGY', cmap=BLUE_GREEN_YELLOW_CMAP, w=w, h=h, dir='b/GeneExp', format=format)",
"cache=cache) c_b = libtsne.load_phenograph_clusters(pca_b, 'b', cache=cache) create_pca_plot(pca_b, c_b, 'b', dir='b') create_cluster_plot(tsne_b, c_b, 'b',",
"ax # def expr_plot(tsne, # exp, # d1=1, # d2=2, # x1=None, #",
"cluster_order=None, method='tsne', dir='.', out=None): fig = cluster_grid(tsne, clusters, colors=colors, cols=cols, size=size, add_titles=add_titles, cluster_order=cluster_order)",
"# # sid += 1 # # ax.set_title('C{} ({:,})'.format(c, len(idx1)), color=colors[i]) # libplot.invisible_axes(ax)",
"genes, cmap=None, size=SUBPLOT_SIZE): \"\"\" Plot multiple genes on a grid. Parameters ---------- data",
"= (e - e.mean()) / e.std() # limit to 3 std for z-scores",
"edgecolors='white', linewidth=EDGE_WIDTH, fig=None, ax=None): \"\"\" Plot a cluster separately to highlight where the",
"in items]) def get_matrix_from_h5(filename, genome): with tables.open_file(filename, 'r') as f: try: dsets =",
"Scale each library to its median size Parameters ---------- data : Pandas dataframe",
"an newer version that is not supported by this function.' % version) else:",
"cluster_order=None, format='png', dir='.', out=None): if out is None: # libtsne.get_tsne_plot_name(name)) out = '{}/{}_{}.{}'.format(dir,",
"Cells x tsne tsne data. Columns should be labeled 'TSNE-1', 'TSNE-2' etc genes",
"norm is None and exp.min() < 0: #norm = matplotlib.colors.Normalize(vmin=-3, vmax=3, clip=True) if",
"creating an expression plot for T-SNE/2D space reduced representation of data. Parameters ----------",
"libplot.new_base_fig(w=w, h=w) si = 1 for i in range(0, n): for j in",
"im1.filter(ImageFilter.FIND_EDGES) im_data = np.array(imageWithEdges.convert('RGBA')) #r = data[:, :, 0] #g = data[:, :,",
"size=SUBPLOT_SIZE, dir='.'): # \"\"\" # Plot separate clusters colored by sample # \"\"\"",
"= gene_ids[i][2] print(gene_id, gene) exp = get_gene_data(data, gene_id, ids=ids, gene_names=gene_names) #fig, ax =",
"legend=True, sort=True, cluster_order=None, fig=None, ax=None): \"\"\" Create a tsne plot without the formatting",
"list: l = len(x) elif type(x) is np.ndarray: l = x.shape[0] elif type(x)",
"they should be rendered Returns ------- fig : Matplotlib figure A new Matplotlib",
"0) d = im_data[np.where(black_areas)] d[:, 0:3] = [64, 64, 64] im_data[np.where(black_areas)] = d",
"ax.set_ylim([-1, 1]) ax.set_title('tsne-ah') libplot.savefig(fig, '{}_silhouette.pdf'.format(name)) def node_color_from_cluster(clusters): colors = libcluster.colors() return [colors[clusters['Cluster'][i] -",
"index=d.index, columns=d.columns) else: return pd.DataFrame(RobustScaler().fit_transform(d.T).T, index=d.index, columns=d.columns) def umi_norm_log2_scale(data, clip=None): d = umi_norm_log2(data)",
"np.array([x.decode('utf-8') for x in items]) def get_matrix_from_h5(filename, genome): with tables.open_file(filename, 'r') as f:",
"'b', sample_names=samples, dir='b') create_cluster_samples(tsne_b, c_b, samples, 'b_sample', dir='b') genes_expr(d_b, tsne_b, genes, prefix='b_BGY', cmap=BLUE_GREEN_YELLOW_CMAP,",
"matplotlib.colors.Normalize(-1, 3, clip=True) LEGEND_PARAMS = {'show': True, 'cols': 4, 'markerscale': 2} CLUSTER_101_COLOR =",
":, 2] # # grey_areas = (r < 255) & (r > 200)",
"LEGEND_PARAMS = {'show': True, 'cols': 4, 'markerscale': 2} CLUSTER_101_COLOR = (0.3, 0.3, 0.3)",
"1 for c in cluster_order: i = c - 1 cluster = ids[i]",
"A new Matplotlib figure used to make the plot # \"\"\" # #",
"1].values # data['{}-{}'.format(t, d1)][idx] y = data.iloc[idx, dim[1] - 1].values # data['{}-{}'.format(t, d2)][idx]",
"= collections.namedtuple('FeatureBCMatrix', ['feature_ids', 'feature_names', 'barcodes', 'matrix']) def get_matrix_from_h5_v2(filename, genome): with h5py.File(filename, 'r') as",
"g)[0] if indexes.size > 0: for index in indexes: ret.append((index, ids[index], gene_names[index])) else:",
"pc1, pc2, format) fig, ax = pca_plot(pca, clusters, pc1=pc1, pc2=pc2, labels=labels, marker=marker, legend=legend,",
"# # # def tsne_cluster_sample_grid(tsne, clusters, samples, colors=None, size=SUBPLOT_SIZE): # \"\"\" # Plot",
"\"\"\" if ax is None: fig, ax = libplot.new_fig(size, size) #print('Label {}'.format(l)) idx1",
"fig : Matplotlib figure A new Matplotlib figure used to make the plot",
"space reduced representation of data. Parameters ---------- data : Pandas dataframe features x",
"c=color, ax=ax, edgecolors='none', # edgecolors, linewidth=linewidth, s=s) if add_titles: if isinstance(cluster, int): prefix",
"level so that extreme values always appear on top idx = np.argsort(exp) #np.argsort(abs(exp))",
"= base_cluster_plot(tsne, clusters, markers=markers, colors=colors, dim1=dim1, dim2=dim2, s=s, w=w, h=h, cluster_order=cluster_order, legend=legend, sort=sort,",
"#(0.8, 0.8, 0.8) #(0.85, 0.85, 0.85 BACKGROUND_SAMPLE_COLOR = [0.75, 0.75, 0.75] EDGE_COLOR =",
"of gene names \"\"\" exp = get_gene_data(data, gene) return expr_plot(tsne, exp, fig=fig, ax=ax,",
"color = colors[cluster] # elif isinstance(colors, list): # color = colors[i] # else:",
"w=libplot.DEFAULT_WIDTH, # h=libplot.DEFAULT_HEIGHT, # colorbar=True): #plt.cm.plasma): # \"\"\" # Creates a basic t-sne",
"size grid to look nice. \"\"\" if type(x) is int: l = x",
"for index in indexes: ret.append((index, ids[index], gene_names[index])) return ret def get_gene_data(data, g, ids=None,",
"node_color_from_cluster(clusters): colors = libcluster.colors() return [colors[clusters['Cluster'][i] - 1] for i in range(0, clusters.shape[0])]",
"expr_grid_size(x, size=SUBPLOT_SIZE): \"\"\" Auto size grid to look nice. \"\"\" if type(x) is",
"by sample # \"\"\" # fig = tsne_cluster_sample_grid(tsne, clusters, samples, colors, size) #",
"fig, ax = libplot.new_fig(w=w, h=h) ids = list(sorted(set(clusters['Cluster']))) for i in range(0, len(ids)):",
"node_size=50, node_color=node_color, vmax=(clusters['Cluster'].max() - 1), cmap=libcluster.colormap()) # # libplot.savefig(fig, 'network_{}.pdf'.format(name)) def plot_centroids(tsne, clusters,",
"= ax.get_ylim() fig, ax = separate_cluster(d, clusters, cluster, color=color, size=w, s=s, linewidth=linewidth, add_titles=False,",
"im_edges = im2.filter(ImageFilter.FIND_EDGES) # # # im_data = np.array(im_edges.convert('RGBA')) # # #r =",
"b in zip(x, y)]) sd = d.std() m = d.mean() print(m, sd) z",
"sp_sparse.csc_matrix( (dsets['data'], dsets['indices'], dsets['indptr']), shape=dsets['shape']) return GeneBCMatrix(decode(dsets['genes']), decode(dsets['gene_names']), decode(dsets['barcodes']), matrix) except tables.NoSuchNodeError: raise",
"tsne, genes, prefix='', index=None, dir='GeneExp', cmap=BGY_CMAP, norm=None, w=6, s=30, alpha=1, linewidth=EDGE_WIDTH, edgecolors='none', colorbar=True,",
"ax.axis('off') # libplot.invisible_axes(ax) return fig, ax def separate_clusters(tsne, clusters, name, colors=None, size=4, add_titles=True,",
"figure is created and returned. ax : matplotlib axis If ax is a",
"* cols rows = int(l / cols) + 2 if l % cols",
"b = im_data[:, :, 2] # # grey_areas = (r < 255) &",
"with_labels=True, labels=labels, ax=ax, node_size=800, node_color=node_color, font_color='white', font_family='Arial') libplot.format_axes(ax) libplot.savefig(fig, '{}_centroid_network.pdf'.format(name)) def centroids(tsne, clusters):",
"index=gbm.gene_names, columns=gbm.barcodes) def get_barcode_counts(gbm): ret = [] for i in range(len(gbm.barcodes)): ret.append(np.sum(gbm.matrix[:, i].toarray()))",
"# if id does not exist, try the gene names idx = np.where(np.isin(gene_names,",
"f.walk_nodes('/' + genome, 'Array'): dsets[node.name] = node.read() # for node in f.walk_nodes('/matrix', 'Array'):",
"# plt.cm.plasma): \"\"\" Creates a base expression plot and adds a color bar.",
"cmap = libcluster.colormap() labels = {} for i in range(0, c.shape[0]): labels[i] =",
"d_b = counts.iloc[:, idx] d_b = libcluster.remove_empty_rows(d_b) if isinstance(d_a, SparseDataFrame): d_b = umi_norm_log2(d_b)",
"axis=1): #m = d.min(axis=1) #std = (d - m) / (d.max(axis=1) - m)",
"and avoid raising exception to work more like mkdir -p Parameters ---------- path",
"genes['Genes'].values if norm is None: norm = matplotlib.colors.Normalize(vmin=-3, vmax=3, clip=True) #cmap = plt.cm.plasma",
"edgecolors=edgecolors, ax=ax) tmp = 'tmp{}.png'.format(bin) libplot.savefig(fig, tmp, pad=0) plt.close(fig) im = imagelib.open(tmp) im_no_bg",
"os.path.isfile(file) or not cache: print('{} was not found, creating it with...'.format(file)) # Find",
"d = umi_tpm(data) return umi_log2(d) def umi_norm(data): \"\"\" Scale each library to its",
"Plot height alpha : float (0, 1), optional Tranparency of markers. show_axes :",
"a new figure is created and returned. ax : matplotlib axis If ax",
"edges on top of original image to highlight cluster #im_base.paste(im2, (0, 0), im2)",
"= (e - e.mean()) / e.std() #print(e.min(), e.max()) # z-score #e = (e",
"# s=s, # marker=marker, # norm=norm, # edgecolors=[color], # linewidth=linewidth) #libcluster.format_axes(ax, title=t) return",
"colors = libcluster.colors() # # for i in range(0, len(cids)): # c =",
"create_cluster_plots(pca, labels, name, marker='o', s=MARKER_SIZE): for i in range(0, pca.shape[1]): for j in",
"dir='a') genes_expr(d_a, tsne_a, genes, prefix='a_BGY', cmap=BLUE_GREEN_YELLOW_CMAP, w=w, h=h, dir='a/GeneExp', format=format) fig, ax =",
"dim=[1, 2], index=None, dir='GeneExp', cmap=BGY_CMAP, norm=None, w=4, h=4, s=30, alpha=ALPHA, linewidth=EDGE_WIDTH, edgecolors='none', colorbar=True,",
"plot \"\"\" if cluster_order is None: ids = np.array(list(sorted(set(clusters['Cluster'])))) cluster_order = np.array(list(range(0, len(ids))))",
"list(range(1, c1.shape[0] + 1)), 'Overlap %': overlaps}) df.set_index('Cluster', inplace=True) df.to_csv('{}_cluster_overlaps.txt'.format(name), sep='\\t') def mkdir(path):",
"labels=labels, ax=ax, node_size=800, node_color=node_color, font_color='white', font_family='Arial') libplot.format_axes(ax) libplot.savefig(fig, '{}_centroid_network.pdf'.format(name)) def centroids(tsne, clusters): cids",
": float (0, 1), optional Tranparency of markers. show_axes : bool, optional, default",
"dim2=1, method='tsne', markers='o', s=libplot.MARKER_SIZE, w=8, h=8, colors=None, legend=True, sort=True, show_axes=False, ax=None, cluster_order=None, format='png',",
"range(0, len(ids)): l = ids[i] #print('Label {}'.format(l)) indices = np.where(clusters['Cluster'] == l)[0] n",
"x = x[idx] y = y[idx] #centroid = [x.sum() / x.size, y.sum() /",
"np.zeros((len(cids), 2)) for i in range(0, len(cids)): c = cids[i] x = tsne.iloc[np.where(clusters['Cluster']",
"data. Columns should be labeled 'TSNE-1', 'TSNE-2' etc # clusters : DataFrame #",
"x = tsne.iloc[idx1, 0] # y = tsne.iloc[idx1, 1] # # if isinstance(colors,",
"appear on top idx = np.argsort(exp) #np.argsort(abs(exp)) # np.argsort(exp) x = data.iloc[idx, dim[0]",
"vmax=(clusters['Cluster'].max() - 1), cmap=libcluster.colormap()) # # libplot.savefig(fig, 'network_{}.pdf'.format(name)) def plot_centroids(tsne, clusters, name): c",
"= kneighbors_graph(c2, k, mode='distance', metric='euclidean').toarray() overlaps = [] for i in range(0, c1.shape[0]):",
"# Plot background points if show_background: x = tsne.iloc[idx2, 0] y = tsne.iloc[idx2,",
"range(0, len(cids)): c = cids[i] x = tsne.iloc[np.where(clusters['Cluster'] == c)[0], :] centroid =",
"(e.min() == 0): #print('Data does not appear to be z-scored. Transforming now...') #",
"libplot.invisible_axes(ax) tmp = 'tmp{}.png'.format(i) libplot.savefig(fig, tmp) plt.close(fig) # Open image # im =",
"= np.where(clusters['Cluster'] == cluster)[0] # idx2 = np.where(clusters['Cluster'] != cluster)[0] # # #",
"= pd.DataFrame(gbm.matrix.todense()) df.index = gbm.gene_names df.columns = gbm.barcodes return df def to_csv(gbm, file,",
"h=h, fig=fig, ax=ax) libplot.savefig(fig, out, pad=2) plt.close(fig) def set_tsne_ax_lim(tsne, ax): \"\"\" Set the",
"and saves a presentation tsne plot \"\"\" if out is None: out =",
"supported by this function.' % version) else: raise ValueError( 'Matrix HDF5 file format",
"yt = np.linspace(y.min(), y.max(), 100, endpoint=True) # # xp = points[hull.vertices, 0] yp",
"0].tolist(), metric='euclidean') fig, ax = libplot.newfig(w=9, h=7, subplot=211) df = pd.DataFrame({'Silhouette Score': x1,",
"of original image to highlight cluster # im_base.paste(im2, (0, 0), im2) # break",
"add_titles : bool Whether to add titles to plots plot_order: list, optional List",
"= '-{}'.format(sid + 1) # idx1 = np.where((clusters['Cluster'] == c) & clusters.index.str.contains(id))[0] #",
"if idx.size > 0: # if id exists, pick the first idx =",
"= abs(clip) min = -max if isinstance(min, float) or isinstance(min, int): print('z min',",
"libplot.savefig(fig, tmp, pad=0) plt.close(fig) im = imagelib.open(tmp) im_no_bg = imagelib.remove_background(im) im_edges = imagelib.edges(im_no_bg)",
"cluster #im_base.paste(im2, (0, 0), im2) imagelib.save(im_base, out) def avg_expr(data, tsne, genes, cid, clusters,",
"# # xp = points[hull.vertices, 0] yp = points[hull.vertices, 1] xp = np.append(xp,",
"else: return None if isinstance(data, SparseDataFrame): return data[idx, :].to_array() else: return data.iloc[idx, :].values",
"= libplot.new_fig(w=w, h=h) # if norm is None and exp.min() < 0: #norm",
"/ sd # find all points within 1 sd of centroid idx =",
"without the formatting \"\"\" if ax is None: fig, ax = libplot.new_fig() libplot.scatter(tsne['TSNE-1'],",
"# # x = tsne.iloc[idx2, 0] # y = tsne.iloc[idx2, 1] # #",
"on plot legend : bool, optional, default true Whether to show legend. \"\"\"",
"= libplot.grid_size(n) w = 4 * rows fig = libplot.new_base_fig(w=w, h=w) si =",
"marker='o', s=MARKER_SIZE, alpha=EXP_ALPHA, fig=None, ax=None, norm=None): # plt.cm.plasma): out = 'pca_expr_{}_t{}_vs_t{}.pdf'.format(name, 1, 2)",
"1], pca.index[i]) return fig, ax def pca_plot(pca, clusters, pc1=1, pc2=2, marker='o', labels=False, s=MARKER_SIZE,",
"alpha=ALPHA, s=MARKER_SIZE, edgecolors='white', linewidth=EDGE_WIDTH, fig=None, ax=None): \"\"\" Plot a cluster separately to highlight",
"colorbar=True, out=None): # plt.cm.plasma): \"\"\" Creates and saves a presentation tsne plot \"\"\"",
"2] a = im_data[:, :, 3] # (r < 255) | (g <",
"not exist, try the gene names idx = np.where(np.isin(gene_names, g))[0] if idx.size <",
"idx = np.argsort(exp) #np.argsort(abs(exp)) # np.argsort(exp) x = data.iloc[idx, dim[0] - 1].values #",
"otherwise a new figure is created and returned. ax : matplotlib axis If",
"method, gene, format) libplot.savefig(fig, 'tmp.png', pad=0) libplot.savefig(fig, out, pad=0) plt.close(fig) im1 = Image.open('tmp.png')",
"the plot, otherwise a new one is created. ax : matplotlib ax, optional",
"= libplot.new_fig(w, h) is_first = True base_expr_plot(data, exp, dim=dim, s=s, marker=marker, edgecolors=edgecolors, linewidth=linewidth,",
"== g)[0] for index in indexes: ret.append((index, ids[index], gene_names[index])) return ret def get_gene_data(data,",
":, 3] # # # Non transparent areas are edges # #black_areas =",
"add_titles : bool Whether to add titles to plots w: int, optional width",
"gene_ids[i][2] print(gene, gene_id) exp = get_gene_data(data, gene_id, ids=ids, gene_names=gene_names) ax = libplot.new_ax(fig, rows,",
"ax = libplot.newfig(w=5, h=5) ax.scatter(c[:, 0], c[:, 1], c=None) libplot.format_axes(ax) libplot.savefig(fig, '{}_centroids.pdf'.format(name)) def",
"# b = im_data[:, :, 2] # # print(tmp, r.shape) # # grey_areas",
"genes : array List of gene names \"\"\" exp = get_gene_data(data, gene) return",
": Index, optional Index of gene ids gene_names : Index, optional Index of",
"Pandas dataframe n x 1 table of n cells with a Cluster column",
"print(gene_id, gene) exp = get_gene_data(data, gene_id, ids=ids, gene_names=gene_names) bin_means, bin_edges, binnumber = binned_statistic(exp,",
"cid, clusters, prefix='', index=None, dir='GeneExp', cmap=OR_RED_CMAP, # BGY_CMAP, norm=None, w=libplot.DEFAULT_WIDTH, h=libplot.DEFAULT_HEIGHT, alpha=1.0, colorbar=False,",
"(d - m) / (d.max(axis=1) - m) #scaled = std * (max -",
"< len(colors): # np.where(clusters['Cluster'] == cluster)[0]] color = colors[i] else: color = 'black'",
"work more like mkdir -p Parameters ---------- path : str directory to create.",
"dim=[1, 2], cmap=plt.cm.plasma, marker='o', edgecolors=EDGE_COLOR, linewidth=1, s=MARKER_SIZE, alpha=1, w=libplot.DEFAULT_WIDTH, h=libplot.DEFAULT_HEIGHT, fig=None, ax=None, norm=None):",
"gene_id != gene: out = '{}/{}_expr_{}_{}.png'.format(dir, method, gene, gene_id) else: out = '{}/{}_expr_{}.png'.format(dir,",
"with_labels=False, ax=ax, node_size=50, node_color=node_color, vmax=(clusters['Cluster'].max() - 1), cmap=libcluster.colormap()) # # libplot.savefig(fig, 'network_{}.pdf'.format(name)) def",
"def create_tsne_cluster_sample_grid(tsne, clusters, samples, name, colors=None, size=SUBPLOT_SIZE, dir='.'): # \"\"\" # Plot separate",
"libplot.NORM_3 # Sort by expression level so that extreme values always appear on",
"'#ffff66', '#ffff00']) # BGY_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list('bgy', ['#00264d', '#003366', '#339933', '#e6e600', '#ffff33']) # BGY_CMAP",
"s=s, ax=ax) return fig, ax def tsne_plot(tsne, marker='o', s=libplot.MARKER_SIZE, c='red', label=None, fig=None, ax=None):",
"bins): bi = bin + 1 idx_bin = np.where(binnumber == bi)[0] idx_other =",
"a tsne plot without the formatting Parameters ---------- d : Pandas dataframe t-sne,",
"centroid[0] ret[i, 1] = centroid[1] return ret def knn_method_overlaps(tsne1, tsne2, clusters, name, k=5):",
"or isinstance(clip, int): max = abs(clip) min = -max if isinstance(min, float) or",
"base_pca_expr_plot(data, expr, dim=dim, cmap=cmap, marker=marker, s=s, alpha=alpha, fig=fig, ax=ax, norm=norm) libplot.savefig(fig, out) plt.close(fig)",
"cluster_order[i]) cluster = cluster_order[i] if isinstance(colors, dict): color = colors[cluster] elif isinstance(colors, list):",
"or is_first: if colorbar: libplot.add_colorbar(fig, cmap, norm=norm) #libcluster.format_simple_axes(ax, title=t) if not show_axes: libplot.invisible_axes(ax)",
"if id does not exist, try the gene names idx = np.where(gene_names ==",
"dsets['indices'], dsets['indptr']), shape=dsets['shape']) return GeneBCMatrix(decode(dsets['genes']), decode(dsets['gene_names']), decode(dsets['barcodes']), matrix) except tables.NoSuchNodeError: raise Exception(\"Genome %s",
"im_base.paste(im2, (0, 0), im2) # break imagelib.save(im_base, out) def cluster_plot(tsne, clusters, dim1=0, dim2=1,",
"= [(x * avg[idx]).sum() / avg[idx].sum(), (y * avg[idx]).sum() / avg[idx].sum()] d =",
"else: color = 'black' else: color = 'black' ax = libplot.new_ax(fig, subplot=(rows, cols,",
"type(x) is list: l = len(x) elif type(x) is np.ndarray: l = x.shape[0]",
"are Parameters ---------- tsne : Pandas dataframe Cells x tsne tsne data. Columns",
"= 0.9 BLUE_YELLOW_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list( 'blue_yellow', ['#162d50', '#ffdd55']) BLUE_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list( 'blue', ['#162d50',",
"set_tsne_ax_lim(tsne, ax): \"\"\" Set the t-SNE x,y limits to look pretty. \"\"\" d1",
"norm is None: norm = matplotlib.colors.Normalize(vmin=-3, vmax=3, clip=True) #cmap = plt.cm.plasma ids, gene_names",
"w : int, optional Plot width h : int, optional Plot height alpha",
"= kneighbors_graph(tsne, k, mode='distance', metric='euclidean').toarray() # # #A = A[0:500, 0:500] # #",
"w = size * cols h = size * rows fig = libplot.new_base_fig(w=w,",
"isinstance(min, int): print('z min', min) sd[np.where(sd < min)] = min if isinstance(max, float)",
"for i in range(0, c1.shape[0]): ids1 = np.where(a1[i, :] > 0)[0] ids2 =",
"cluster, len(idx1)), color=color) ax.axis('off') # libplot.invisible_axes(ax) return fig, ax def separate_clusters(tsne, clusters, name,",
"= libtsne.load_pca(d_a, 'a', cache=cache) # pca.iloc[idx,:] tsne_a = libtsne.load_pca_tsne(pca_a, 'a', cache=cache) c_a =",
"g = np.array(g) if isinstance(g, np.ndarray): idx = np.where(np.isin(ids, g))[0] if idx.size <",
"x2=None, # cmap=BLUE_YELLOW_CMAP, # marker='o', # s=MARKER_SIZE, # alpha=EXP_ALPHA, # out=None, # fig=None,",
"colors=colors, s=s, w=w, h=h, cluster_order=cluster_order, show_axes=show_axes, legend=legend, sort=sort, out=out) def base_tsne_plot(tsne, marker='o', s=libplot.MARKER_SIZE,",
"c1.shape[0] + 1)), 'Overlap %': overlaps}) df.set_index('Cluster', inplace=True) df.to_csv('{}_cluster_overlaps.txt'.format(name), sep='\\t') def mkdir(path): \"\"\"",
"color = colors[i] # l] else: color = 'black' ax.scatter(x, y, color=color, edgecolor=color,",
"else: prefix = '' ax.set_title('{}{} ({:,})'.format( prefix, cluster, len(idx1)), color=color) ax.axis('off') # libplot.invisible_axes(ax)",
"prefix='a_BGY', cmap=BLUE_GREEN_YELLOW_CMAP, w=w, h=h, dir='a/GeneExp', format=format) fig, ax = cluster_plot(tsne_a, c_a, legend=False, w=w,",
"edgecolors, linewidth=linewidth) # for i in range(0, x.size): # en = norm(e[i]) #",
"raise Exception(\"Failed to write H5 file.\") def subsample_matrix(gbm, barcode_indices): return GeneBCMatrix(gbm.gene_ids, gbm.gene_names, gbm.barcodes[barcode_indices],",
"names \"\"\" if dir[-1] == '/': dir = dir[:-1] if not os.path.exists(dir): mkdir(dir)",
"edgecolors=edgecolors, linewidth=linewidth, markers=markers, alpha=alpha, s=s, ax=ax, cluster_order=cluster_order, sort=sort) #set_tsne_ax_lim(tsne, ax) # libcluster.format_axes(ax) if",
"sdmax=0.5): \"\"\" Plot multiple genes on a grid. Parameters ---------- data : Pandas",
"t-sne, umap data clusters : Pandas dataframe n x 1 table of n",
"1] # b = im_data[:, :, 2] # # grey_areas = (r <",
"1 for s in sample_names: id = '-{}'.format(c) print(id) print(np.where(d.index.str.contains(id))[0]) sc[np.where(d.index.str.contains(id))[0]] = s",
"labeled 'TSNE-1', 'TSNE-2' etc # clusters : DataFrame # Clusters in # #",
"used to make the plot # \"\"\" # # # cids = list(sorted(set(clusters['Cluster'])))",
"- 1), cmap=libcluster.colormap()) # # libplot.savefig(fig, 'network_{}.pdf'.format(name)) def plot_centroids(tsne, clusters, name): c =",
"= f.create_group(f.root, genome) f.create_carray(group, 'genes', obj=gbm.gene_ids) f.create_carray(group, 'gene_names', obj=gbm.gene_names) f.create_carray(group, 'barcodes', obj=gbm.barcodes) f.create_carray(group,",
"# t-sne 2D data # \"\"\" # # fig, ax = expr_plot(tsne, #",
"plot for T-SNE/2D space reduced representation of data. Parameters ---------- data : Pandas",
"background # # sid = 0 # # for sample in samples: #",
"data.index.str.split(';').str else: genes = data.index ids = genes return ids.values, genes.values def get_gene_ids(data,",
"norm = matplotlib.colors.Normalize(vmin=-3, vmax=3, clip=True) #cmap = plt.cm.plasma ids, gene_names = get_gene_names(data) print(ids,",
"def genes_expr(data, tsne, genes, prefix='', dim=[1, 2], index=None, dir='GeneExp', cmap=BGY_CMAP, norm=None, w=4, h=4,",
"np.where(clusters['Cluster'] == cluster)[0]] color = colors[i] else: color = 'black' else: color =",
"= libtsne.load_pca_tsne(pca_b, 'b', cache=cache) c_b = libtsne.load_phenograph_clusters(pca_b, 'b', cache=cache) create_pca_plot(pca_b, c_b, 'b', dir='b')",
"is None: index = data.index if isinstance(genes, pd.core.frame.DataFrame): genes = genes['Genes'].values if norm",
"clusters : Pandas dataframe n x 1 table of n cells with a",
"list): g = np.array(g) if isinstance(g, np.ndarray): idx = np.where(np.isin(ids, g))[0] if idx.size",
"if type(x) is int: l = x elif type(x) is list: l =",
"+ 1, pca.shape[1]): create_cluster_plot(pca, labels, name, pc1=( i + 1), pc2=(j + 1),",
"and mask # im_data = np.array(im1.convert('RGBA')) # # r = im_data[:, :, 0]",
"np.ndarray: l = x.shape[0] elif type(x) is pd.core.frame.DataFrame: l = x.shape[0] else: return",
"mkdir('a') a_barcodes = pd.read_csv('../a_barcodes.tsv', header=0, sep='\\t') idx = np.where(counts.columns.isin(a_barcodes['Barcode'].values))[0] d_a = counts.iloc[:, idx]",
"None: ids = np.array(list(sorted(set(clusters['Cluster'])))) cluster_order = np.array(list(range(0, len(ids)))) + 1 n = cluster_order.size",
"< 255) #(r > 0) & (r == g) & (r == b)",
"c_b, 'b', sample_names=samples, dir='b') create_cluster_samples(tsne_b, c_b, samples, 'b_sample', dir='b') genes_expr(d_b, tsne_b, genes, prefix='b_BGY',",
"im_smooth) # # im_base.paste(im2, (0, 0), im2) if gene_id != gene: out =",
"index=None, dir='GeneExp', cmap=BGY_CMAP, norm=None, w=6, s=30, alpha=1, linewidth=EDGE_WIDTH, edgecolors='none', colorbar=True, method='tsne', bins=10, background=BACKGROUND_SAMPLE_COLOR):",
"version that is not supported by this function.' % version) else: raise ValueError(",
"1).tolist() # # fig, ax = libplot.newfig(w=10, h=10) # # nx.draw_networkx(G, pos=pos, with_labels=False,",
"# if (e.min() == 0): #print('Data does not appear to be z-scored. Transforming",
"# if isinstance(colors, dict): # color = colors[cluster] # elif isinstance(colors, list): #",
"500 xi = np.linspace(x.min(), x.max(), nx) yi = np.linspace(y.min(), y.max(), ny) x =",
"colors = libcluster.get_colors() # Where to plot figure pc = 1 for c",
"cmap) exp_bin = exp[idx_bin] tsne_bin = tsne.iloc[idx_bin, :] expr_plot(tsne_bin, exp_bin, cmap=cmap, s=s, colorbar=colorbar,",
"= matplotlib.colors.Normalize(-1, 3, clip=True) LEGEND_PARAMS = {'show': True, 'cols': 4, 'markerscale': 2} CLUSTER_101_COLOR",
"tsne.iloc[idx_other, :] fig, ax = libplot.new_fig(w, w) x = tsne_other.iloc[:, 0] y =",
"labeled 'TSNE-1', 'TSNE-2' etc cluster : int Clusters in colors : list, color",
"clusters, dim1=dim1, dim2=dim2, markers=markers, colors=colors, s=s, w=w, h=h, cluster_order=cluster_order, show_axes=show_axes, legend=legend, sort=sort, out=out)",
"for each data point so it must have the same number of elements",
"type(genes) is pd.core.frame.DataFrame: genes = genes['Genes'].values ids, gene_names = get_gene_names(data) gene_ids = get_gene_ids(data,",
"within 1 sd of centroid idx = np.where(abs(z) < sdmax)[0] # (d >",
"# # #if mean > 0.5: # ax.scatter(x[i], # y[i], # c='#ffffff00', #",
"y[idx] #centroid = [x.sum() / x.size, y.sum() / y.size] centroid = [(x *",
"background points # # # # x = tsne.iloc[idx2, 0] # y =",
"libcluster.format_legend(ax, cols=6, markerscale=2) return fig, ax def create_pca_plot(pca, clusters, name, pc1=1, pc2=2, marker='o',",
"indices = np.where(clusters['Cluster'] == l)[0] n = len(indices) label = 'C{} ({:,})'.format(l, n)",
"colors) libcluster.format_simple_axes(ax, title=\"PC\") if legend: libcluster.format_legend(ax, cols=6, markerscale=2) return fig, ax def create_pca_plot(pca,",
"Parameters # ---------- # tsne : Pandas dataframe # Cells x tsne tsne",
"# BGY_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list('bgy', ['#003366', '#339966', '#ffff66', '#ffff00') # BGY_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list('bgy', ['#001a33',",
"Plot multiple genes on a grid. Parameters ---------- data : Pandas dataframe Genes",
"data : Pandas dataframe Genes x samples expression matrix tsne : Pandas dataframe",
"libplot.newfig(w=8, h=8) # list(range(0, c.shape[0])) node_color = libcluster.colors()[0:c.shape[0]] cmap = libcluster.colormap() labels =",
"cmap=BLUE_GREEN_YELLOW_CMAP, w=w, h=h, dir='b/GeneExp', format=format) fig, ax = cluster_plot(tsne_b, c_b, legend=False, w=w, h=h)",
"ids, gene_names = get_gene_names(data) ret = [] for g in genes: indexes =",
"import libplot import libcluster import libtsne import seaborn as sns from libsparse.libsparse import",
"from libsparse.libsparse import SparseDataFrame from lib10x.sample import * from scipy.spatial import ConvexHull from",
"hull = ConvexHull(points) #x1 = x[idx] #y1 = y[idx] # avg1 = np.zeros(x.size)",
"of gene names Returns ------- fig : Matplotlib figure A new Matplotlib figure",
"def tpm(gbm): m = gbm.matrix s = 1 / m.sum(axis=0) mn = m.multiply(s)",
"ids, gene_names = get_gene_names(data) gene_ids = get_gene_ids(data, genes, ids=ids, gene_names=gene_names) w, h, rows,",
"im_outline = imagelib.paste(im, im_edges) # im_no_bg im_smooth = imagelib.smooth(im_outline) imagelib.save(im_smooth, 'smooth.png') # im_smooth",
"'Silhouette Score', colors=libcluster.colors(), ax=ax) ax.set_ylim([-1, 1]) ax.set_title('tsne-ah') libplot.savefig(fig, '{}_silhouette.pdf'.format(name)) def node_color_from_cluster(clusters): colors =",
"Plot background points # # # # x = tsne.iloc[idx2, 0] # y",
"100 labels[np.where(labels == -1)] = new_label labels += 1 libtsne.write_clusters(headers, labels, name) cluster_map,",
"'' # # ax.set_title('{}{} ({:,})'.format(prefix, cluster, len(idx1)), color=color) # # # libplot.invisible_axes(ax) pc",
"range(i + 1, pca.shape[1]): create_cluster_plot(pca, labels, name, pc1=( i + 1), pc2=(j +",
"range(0, len(cluster_order)): print('index', i, cluster_order[i]) cluster = cluster_order[i] if isinstance(colors, dict): color =",
"# im_edges = im2.filter(ImageFilter.FIND_EDGES) # # # im_data = np.array(im_edges.convert('RGBA')) # # #r",
"if isinstance(colors, dict): color = colors.get(cluster, 'black') elif isinstance(colors, list): #i = cluster",
"return fig, ax def tsne_plot(tsne, marker='o', s=libplot.MARKER_SIZE, c='red', label=None, fig=None, ax=None): fig, ax",
"dir='GeneExp', cmap=OR_RED_CMAP, # BGY_CMAP, norm=None, w=libplot.DEFAULT_WIDTH, h=libplot.DEFAULT_HEIGHT, alpha=1.0, colorbar=False, method='tsne', fig=None, ax=None, sdmax=0.5):",
"matplotlib.colors.LinearSegmentedColormap.from_list( 'bgy', ['#162d50', '#214478', '#217844', '#ffcc00', '#ffdd55']) # BGY_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list('bgy', ['#002255', '#2ca05a',",
"avg.min()) # min_max_scale(avg) create_expr_plot(tsne, avg, cmap=cmap, w=w, h=h, colorbar=colorbar, norm=norm, alpha=alpha, fig=fig, ax=ax)",
"-p Parameters ---------- path : str directory to create. \"\"\" try: os.makedirs(path) except:",
"# libplot.savefig(fig, 'network_{}.pdf'.format(name)) def plot_centroids(tsne, clusters, name): c = centroids(tsne, clusters) fig, ax",
"# #print(edges1.shape) # # #skimage.io.imsave('tmp_canny_{}.png'.format(bin), edges1) # # im2 = Image.fromarray(im_data) # #",
"c_a, 'a', dir='a') create_cluster_plot(tsne_a, c_a, 'a', dir='a') create_cluster_grid(tsne_a, c_a, 'a', dir='a') create_merge_cluster_info(d_a, c_a,",
"clusters, samples, name, colors=None, size=SUBPLOT_SIZE, dir='.'): # \"\"\" # Plot separate clusters colored",
"w=8, h=8, alpha=ALPHA, # libplot.ALPHA, show_axes=True, legend=True, sort=True, cluster_order=None, fig=None, ax=None): \"\"\" Create",
"h=8, fig=None, ax=None, dir='.', format='png'): out = '{}/pca_{}_pc{}_vs_pc{}.{}'.format(dir, name, pc1, pc2, format) fig,",
"exp, ax=ax, cmap=cmap, colorbar=False) # if i == 0: # libcluster.format_axes(ax) # else:",
"= ids[i] #print('Label {}'.format(l)) indices = np.where(clusters['Cluster'] == l)[0] n = len(indices) label",
"items]) def get_matrix_from_h5(filename, genome): with tables.open_file(filename, 'r') as f: try: dsets = {}",
"figure \"\"\" if ax is None: fig, ax = libplot.new_fig(size, size) #print('Label {}'.format(l))",
"return ret def knn_method_overlaps(tsne1, tsne2, clusters, name, k=5): c1 = centroids(tsne1, clusters) c2",
"the formatting Parameters ---------- d : Pandas dataframe t-sne, umap data clusters :",
"size * rows return w, h, rows, cols def get_gene_names(data): if ';' in",
"print(np.unique(sc)) df = pd.DataFrame(sc, index=d.index, columns=['Cluster']) return df def create_cluster_samples(tsne_umi_log2, clusters, sample_names, name,",
"'{}_expr.pdf'.format(method) fig, ax = expr_plot(tsne, exp, dim=dim, cmap=cmap, marker=marker, s=s, alpha=alpha, fig=fig, w=w,",
"= separate_cluster(d, clusters, cluster, color=color, size=w, s=s, linewidth=linewidth, add_titles=False, show_background=False) ax.set_xlim(xlim) ax.set_ylim(ylim) if",
"expr_plot(tsne, exp, ax=ax, cmap=cmap, colorbar=False) # if i == 0: # libcluster.format_axes(ax) #",
"Exception(\"Failed to write H5 file.\") def subsample_matrix(gbm, barcode_indices): return GeneBCMatrix(gbm.gene_ids, gbm.gene_names, gbm.barcodes[barcode_indices], gbm.matrix[:,",
"(max - min) + min # return scaled if axis == 0: return",
"legend=True): sc = sample_clusters(clusters, sample_names) create_cluster_plot(tsne_umi_log2, sc, name, method=method, format=format, dir=dir, w=w, h=w,",
"if ids is None: ids, gene_names = get_gene_names(data) if isinstance(g, list): g =",
"fig, ax = libplot.newfig(w=10, h=10) # # nx.draw_networkx(G, pos=pos, with_labels=False, ax=ax, node_size=50, node_color=node_color,",
"tables.open_file(filename, 'w', filters=flt) as f: try: group = f.create_group(f.root, genome) f.create_carray(group, 'genes', obj=gbm.gene_ids)",
"1] #colors[i] #np.where(clusters['Cluster'] == cluster)[0]] color = colors[i] else: color = 'black' else:",
"figure pc = 1 for c in cluster_order: i = c - 1",
"avg1, (xi, yi)) #ax.contour(xi, yi, z, levels=1) def gene_expr(data, tsne, gene, fig=None, ax=None,",
"si)) pca_plot_base(pca, clusters, pc1=(i + 1), pc2=(j + 1), marker=marker, s=s, ax=ax) si",
"d[:, :] = [255, 255, 255, 0] # im_data[np.where(grey_areas)] = d # #",
"isinstance(colors, dict): color = colors[cluster] elif isinstance(colors, list): if cluster < len(colors): #",
"w=w, h=h) libplot.savefig(fig, 'b/b_tsne_clusters_med.pdf') def sample_clusters(d, sample_names): \"\"\" Create a cluster matrix based",
"'#ffff66', '#ffff00') # BGY_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list('bgy', ['#001a33', '#003366', '#339933', '#ffff66', '#ffff00']) # BGY_CMAP",
"'r') as f: try: dsets = {} print(f.list_nodes('/')) for node in f.walk_nodes('/' +",
"ret = np.zeros((len(cids), 2)) for i in range(0, len(cids)): c = cids[i] x",
"x = df2.iloc[:, pc1 - 1] y = df2.iloc[:, pc2 - 1] if",
"# data['{}-{}'.format(t, d2)][idx] e = exp[idx] # if (e.min() == 0): #print('Data does",
"expression plot and adds a color bar. \"\"\" is_first = False if ax",
"ax=ax, edgecolors='none', # bgedgecolor, linewidth=linewidth, s=s) #fig, ax = libplot.new_fig() #expr_plot(tsne, exp, ax=ax)",
"/ avg[idx].sum()] d = np.array([distance.euclidean(centroid, (a, b)) for a, b in zip(x, y)])",
"'#ffdd55']) BGY_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list( 'bgy', ['#003366', '#004d99', '#40bf80', '#ffe066', '#ffd633']) GRAY_PURPLE_YELLOW_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list(",
"= 'C' # else: # prefix = '' # # ax.set_title('{}{} ({:,})'.format(prefix, cluster,",
"the transcripts. Parameters ---------- data : DataFrame data table containing and index genes",
"norm is None: norm = libplot.NORM_3 # Sort by expression level so that",
"- avg.min()) # min_max_scale(avg) create_expr_plot(tsne, avg, cmap=cmap, w=w, h=h, colorbar=colorbar, norm=norm, alpha=alpha, fig=fig,",
"'tmp.png') plt.close(fig) def cluster_grid(tsne, clusters, colors=None, cols=-1, size=SUBPLOT_SIZE, add_titles=True, cluster_order=None): \"\"\" Plot each",
"show_background=True, add_titles=True, size=4, alpha=ALPHA, s=MARKER_SIZE, edgecolors='white', linewidth=EDGE_WIDTH, fig=None, ax=None): \"\"\" Plot a cluster",
"libplot.savefig(fig, out, pad=0) return fig, ax def base_pca_expr_plot(data, exp, dim=[1, 2], cmap=None, marker='o',",
"ax=ax) return fig, ax def tsne_plot(tsne, marker='o', s=libplot.MARKER_SIZE, c='red', label=None, fig=None, ax=None): fig,",
"im_data = np.array(im1.convert('RGBA')) # # r = im_data[:, :, 0] # g =",
"[d2[d2 < 0].quantile(1 - TNSE_AX_Q), d2[d2 >= 0].quantile(TNSE_AX_Q)] #print(xlim, ylim) # ax.set_xlim(xlim) #",
"< 1: return None else: idx = np.where(ids == g)[0] if idx.size >",
"SparseDataFrame(sd.T, index=d.index, columns=d.columns) else: # StandardScaler().fit_transform(d.T) sd = sklearn.preprocessing.scale(d, axis=axis) #sd = sd.T",
"1 libtsne.write_clusters(headers, labels, name) cluster_map, data = libtsne.read_clusters(file) labels = data # .tolist()",
"# # libplot.invisible_axes(ax) pc += 1 return fig def create_cluster_grid(tsne, clusters, name, colors=None,",
"list(sorted(set(clusters['Cluster']))) # # rows = int(np.ceil(np.sqrt(len(cids)))) # # w = size * rows",
"umi_tpm(data): # each column is a cell reads_per_bc = data.sum(axis=0) scaling_factors = 1000000",
"exp, cmap=cmap, dim=dim, w=w, h=h, s=s, colorbar=colorbar, norm=norm, alpha=alpha, linewidth=linewidth, edgecolors=edgecolors) if gene_id",
"alpha=EXP_ALPHA, # out=None, # fig=None, # ax=None, # norm=None, # w=libplot.DEFAULT_WIDTH, # h=libplot.DEFAULT_HEIGHT,",
"optional Supply a figure object on which to render the plot, otherwise a",
"file. \"\"\" ids = list(sorted(set(clusters['Cluster']))) indices = np.array(list(range(0, len(ids)))) if colors is None:",
"# fig=None, # ax=None, # norm=None, # w=libplot.DEFAULT_WIDTH, # h=libplot.DEFAULT_HEIGHT, # colorbar=True): #plt.cm.plasma):",
"colors, size) # # libplot.savefig(fig, '{}/tsne_{}_sample_clusters.png'.format(dir, name)) # #libplot.savefig(fig, '{}/tsne_{}separate_clusters.pdf'.format(dir, name)) # #",
"# #print(c1) # # ax.scatter(x[i], # y[i], # c=[c1], # s=s, # marker=marker,",
"# colorbar=colorbar) # # set_tsne_ax_lim(tsne, ax) # # libplot.invisible_axes(ax) # # if out",
"/ 5 * 100 overlaps.append(o) df = pd.DataFrame( {'Cluster': list(range(1, c1.shape[0] + 1)),",
"libsparse.libsparse import SparseDataFrame from lib10x.sample import * from scipy.spatial import ConvexHull from PIL",
"outline onto clusters # im2.paste(im_smooth, (0, 0), im_smooth) # # # overlay edges",
"= plt.cm.plasma ids, gene_names = get_gene_names(data) print(ids, gene_names, genes) gene_ids = get_gene_ids(data, genes,",
"im_data[np.where(black_areas)] d[:, 0:3] = [64, 64, 64] im_data[np.where(black_areas)] = d im2 = Image.fromarray(im_data)",
"rows are cells and columns are tsne dimensions exp : numpy array expression",
"cmap(int(en * cmap.N)) # color = np.array(color) # # c1 = color.copy() #",
"to figure before returning. \"\"\" if ax is None: fig, ax = libplot.new_fig(w=w,",
"subplot=(rows, rows, si)) pca_plot_base(pca, clusters, pc1=(i + 1), pc2=(j + 1), marker=marker, s=s,",
"'-{}'.format(sid + 1) # idx1 = np.where((clusters['Cluster'] == c) & clusters.index.str.contains(id))[0] # #",
"each library to its median size Parameters ---------- data : Pandas dataframe Matrix",
"#(0.85, 0.85, 0.85 BACKGROUND_SAMPLE_COLOR = [0.75, 0.75, 0.75] EDGE_COLOR = None # [0.3,",
"alpha : float (0, 1), optional Tranparency of markers. show_axes : bool, optional,",
"isinstance(clip, int): max = abs(clip) min = -max if isinstance(min, float) or isinstance(min,",
"i in range(0, len(cids)): c = cids[i] x = tsne.iloc[np.where(clusters['Cluster'] == c)[0], :]",
"= np.array(im1.convert('RGBA')) # # r = im_data[:, :, 0] # g = im_data[:,",
"size=SUBPLOT_SIZE): \"\"\" Plot multiple genes on a grid. Parameters ---------- data : Pandas",
"show_axes=show_axes, legend=legend, sort=sort, out=out) def base_tsne_plot(tsne, marker='o', s=libplot.MARKER_SIZE, c='red', label=None, fig=None, ax=None): \"\"\"",
"# mean = color.mean() # # #print(x[i], y[i], mean) # # #if mean",
"exp = get_gene_data(data, gene_id, ids=ids, gene_names=gene_names) ax = libplot.new_ax(fig, rows, cols, i +",
"sd = sklearn.preprocessing.scale(d, axis=axis) #sd = sd.T if isinstance(clip, float) or isinstance(clip, int):",
"# plt.cm.plasma): \"\"\" Base function for creating an expression plot for T-SNE/2D space",
"= list(f['matrix']['barcodes'][:]) matrix = sp_sparse.csc_matrix( (f['matrix']['data'], f['matrix']['indices'], f['matrix']['indptr']), shape=f['matrix']['shape']) return GeneBCMatrix(feature_ids, feature_names, decode(barcodes),",
"= np.linspace(y.min(), y.max(), ny) x = x[idx] y = y[idx] #centroid = [x.sum()",
"out=out) def separate_cluster(tsne, clusters, cluster, color='black', background=BACKGROUND_SAMPLE_COLOR, bgedgecolor='#808080', show_background=True, add_titles=True, size=4, alpha=ALPHA, s=MARKER_SIZE,",
"im_no_bg = imagelib.remove_background(im) im_edges = imagelib.edges(im) im_outline = imagelib.paste(im, im_edges) # im_no_bg im_smooth",
"tsne, gene, fig=None, ax=None, cmap=plt.cm.plasma, out=None): \"\"\" Plot multiple genes on a grid.",
"ValueError( 'Matrix HDF5 file format version (%d) is an newer version that is",
"clusters, n=10, marker='o', s=MARKER_SIZE): rows = libplot.grid_size(n) w = 4 * rows fig",
"plot legend : bool, optional, default true Whether to show legend. \"\"\" if",
"def gbm_to_df(gbm): return pd.DataFrame(gbm.matrix.todense(), index=gbm.gene_names, columns=gbm.barcodes) def get_barcode_counts(gbm): ret = [] for i",
"id does not exist, try the gene names indexes = np.where(gene_names == g)[0]",
"for bin in range(0, bins): bi = bin + 1 idx_bin = np.where(binnumber",
"= libplot.new_base_fig(w=w, h=w) si = 1 for i in range(0, n): for j",
"1] # # if isinstance(colors, dict): # color = colors[cluster] # elif isinstance(colors,",
"to_csv(gbm, file, sep='\\t'): df(gbm).to_csv(file, sep=sep, header=True, index=True) def sum(gbm, axis=0): return gbm.matrix.sum(axis=axis) def",
"and index genes : list List of strings of gene ids ids :",
"default true Whether to show legend. \"\"\" if ax is None: fig, ax",
"s=s, ax=ax, cluster_order=cluster_order, sort=sort) #set_tsne_ax_lim(tsne, ax) # libcluster.format_axes(ax) if not show_axes: libplot.invisible_axes(ax) legend_params",
"x[idx] y = y[idx] #centroid = [x.sum() / x.size, y.sum() / y.size] centroid",
"= umi_tpm(data) return umi_log2(d) def umi_norm(data): \"\"\" Scale each library to its median",
"# BGY_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list('bgy', ['#003380', '#5fd38d', '#ffd42a']) EXP_NORM = matplotlib.colors.Normalize(-1, 3, clip=True) LEGEND_PARAMS",
"{} for i in range(0, c.shape[0]): labels[i] = i + 1 #nx.draw_networkx(G, pos=pos,",
"\"\"\" import matplotlib # matplotlib.use('agg') import matplotlib.pyplot as plt import collections import numpy",
"newer version that is not supported by this function.' % version) else: raise",
"# out=None, # fig=None, # ax=None, # norm=None, # w=libplot.DEFAULT_WIDTH, # h=libplot.DEFAULT_HEIGHT, #",
"i) cluster = ids[i] if isinstance(colors, dict): color = colors[cluster] elif isinstance(colors, list):",
"return pd.DataFrame(MinMaxScaler(feature_range=(min, max)).fit_transform(d.T).T, index=d.index, columns=d.columns) def rscale(d, min=0, max=1, axis=1): if axis ==",
"'black' # # libplot.scatter(x, y, c=color, ax=ax) # # if add_titles: # if",
"Index, optional Index of gene names Returns ------- list list of tuples of",
"Matplotlib figure used to make the plot ax : Matplotlib axes Axes used",
"cmap=cmap, colorbar=False) # if i == 0: # libcluster.format_axes(ax) # else: # libplot.invisible_axes(ax)",
"x.size): # en = norm(e[i]) # color = cmap(int(en * cmap.N)) # color",
"fig, ax def create_expr_plot(tsne, exp, dim=[1, 2], cmap=None, marker='o', s=MARKER_SIZE, alpha=EXP_ALPHA, fig=None, ax=None,",
"@author: antony \"\"\" import matplotlib # matplotlib.use('agg') import matplotlib.pyplot as plt import collections",
"return fig, ax def separate_clusters(tsne, clusters, name, colors=None, size=4, add_titles=True, type='tsne', format='pdf'): \"\"\"",
"name) libplot.savefig(fig, out, pad=0) #libplot.savefig(fig, '{}/tsne_{}separate_clusters.pdf'.format(dir, name)) # # # def tsne_cluster_sample_grid(tsne, clusters,",
"A new Matplotlib figure used to make the plot ax : Matplotlib axes",
"# get x y lim xlim = ax.get_xlim() ylim = ax.get_ylim() fig, ax",
"dim[0] - 1].values # data['{}-{}'.format(t, d1)][idx] y = data.iloc[idx, dim[1] - 1].values #",
"'PCNA', 'PRDM1'] genes = pd.read_csv('../../../../expression_genes.txt', header=0) mkdir('a') a_barcodes = pd.read_csv('../a_barcodes.tsv', header=0, sep='\\t') idx",
"== b) & (g == b) # # #d = im_data[np.where(black_areas)] # #d[:,",
"pca.iloc[indices, ] x = df2.iloc[:, pc1 - 1] y = df2.iloc[:, pc2 -",
"= colors[i] else: color = CLUSTER_101_COLOR else: color = 'black' fig, ax =",
"pc1=( i + 1), pc2=(j + 1), marker=marker, s=s) def pca_base_plots(pca, clusters, n=10,",
"= (r < 255) & (r > 200) & (g < 255) &",
"({:,})'.format(l, n) df2 = pca.iloc[indices, ] x = df2.iloc[:, pc1 - 1] y",
"ax.scatter(x[i], # y[i], # c='#ffffff00', # s=s, # marker=marker, # norm=norm, # edgecolors=[color],",
"index=True) def sum(gbm, axis=0): return gbm.matrix.sum(axis=axis) def tpm(gbm): m = gbm.matrix s =",
"type(x) is np.ndarray: l = x.shape[0] elif type(x) is pd.core.frame.DataFrame: l = x.shape[0]",
"= exp.mean(axis=0) avg = (avg - avg.mean()) / avg.std() avg[avg < -1.5] =",
"f: try: group = f.create_group(f.root, genome) f.create_carray(group, 'genes', obj=gbm.gene_ids) f.create_carray(group, 'gene_names', obj=gbm.gene_names) f.create_carray(group,",
"cluster, color=color, size=w, s=s, linewidth=linewidth, add_titles=False, show_background=False) ax.set_xlim(xlim) ax.set_ylim(ylim) if not show_axes: libplot.invisible_axes(ax)",
"GeneBCMatrix = collections.namedtuple( 'GeneBCMatrix', ['gene_ids', 'gene_names', 'barcodes', 'matrix']) def decode(items): return np.array([x.decode('utf-8') for",
"gene: out = '{}/{}_expr_{}_{}.{}'.format(dir, method, gene, gene_id, format) else: out = '{}/{}_expr_{}.{}'.format(dir, method,",
"tsne_umi_log2, clusters, name): # measure cluster worth x1 = silhouette_samples( tsne, clusters.iloc[:, 0].tolist(),",
"clusters.iloc[:, 0].tolist( ), 'Label': np.repeat('tsne-10x', len(x1))}) libplot.boxplot(df, 'Cluster', 'Silhouette Score', colors=libcluster.colors(), ax=ax) ax.set_ylim([-1,",
"color=color) ax.axis('off') # libplot.invisible_axes(ax) return fig, ax def separate_clusters(tsne, clusters, name, colors=None, size=4,",
"raise Exception(\"File is missing one or more required datasets.\") #GeneBCMatrix = collections.namedtuple('FeatureBCMatrix', ['feature_ids',",
"colors=None, size=SUBPLOT_SIZE, dir='.'): # \"\"\" # Plot separate clusters colored by sample #",
"cmap=plt.cm.magma, marker='o', s=MARKER_SIZE, alpha=1, edgecolors=EDGE_COLOR, linewidth=EDGE_WIDTH, w=libplot.DEFAULT_WIDTH, h=libplot.DEFAULT_HEIGHT, show_axes=False, fig=None, ax=None, norm=None, colorbar=False):",
"pca_plot_base(pca, clusters, pc1=(i + 1), pc2=(j + 1), marker=marker, s=s, ax=ax) si +=",
"counts = libcluster.remove_empty_rows(counts) # ['AICDA', 'CD83', 'CXCR4', 'MKI67', 'MYC', 'PCNA', 'PRDM1'] genes =",
"etc genes : array List of gene names Returns ------- fig : Matplotlib",
"(r > 200) & (g < 255) & (g > 200) & (b",
"tsne.iloc[idx2, 1] libplot.scatter(x, y, c=[background], ax=ax, edgecolors='none', # bgedgecolor, linewidth=linewidth, s=s) # Plot",
"filters=flt) as f: try: group = f.create_group(f.root, genome) f.create_carray(group, 'genes', obj=gbm.gene_ids) f.create_carray(group, 'gene_names',",
"# im_base.paste(im2, (0, 0), im2) if gene_id != gene: out = '{}/{}_expr_{}_{}.png'.format(dir, method,",
"to show legend. \"\"\" if ax is None: fig, ax = libplot.new_fig(w=w, h=h)",
"s=s) if add_titles: if isinstance(cluster, int): prefix = 'C' else: prefix = ''",
"is None: fig, ax = libplot.new_fig(size, size) #print('Label {}'.format(l)) idx1 = np.where(clusters['Cluster'] ==",
"optional Specify how colors should be normalized Returns ------- fig : matplotlib figure",
"cluster, color='black', background=BACKGROUND_SAMPLE_COLOR, bgedgecolor='#808080', show_background=True, add_titles=True, size=4, alpha=ALPHA, s=MARKER_SIZE, edgecolors='white', linewidth=EDGE_WIDTH, fig=None, ax=None):",
"# data['{}-{}'.format(t, d1)][idx] y = data.iloc[idx, dim[1] - 1].values # data['{}-{}'.format(t, d2)][idx] e",
"o = len(ids3) / 5 * 100 overlaps.append(o) df = pd.DataFrame( {'Cluster': list(range(1,",
"obj=gbm.matrix.shape) except: raise Exception(\"Failed to write H5 file.\") def subsample_matrix(gbm, barcode_indices): return GeneBCMatrix(gbm.gene_ids,",
"def get_matrix_from_h5(filename, genome): with tables.open_file(filename, 'r') as f: try: dsets = {} print(f.list_nodes('/'))",
"get_barcode_counts(gbm): ret = [] for i in range(len(gbm.barcodes)): ret.append(np.sum(gbm.matrix[:, i].toarray())) return ret def",
"w=w, h=h, dir='b/GeneExp', format=format) fig, ax = cluster_plot(tsne_b, c_b, legend=False, w=w, h=h) libplot.savefig(fig,",
"{} print(f.list_nodes('/')) for node in f.walk_nodes('/' + genome, 'Array'): dsets[node.name] = node.read() #",
"clip=True) #cmap = plt.cm.plasma ids, gene_names = get_gene_names(data) exp = get_gene_data(data, genes, ids=ids,",
"norm=norm, w=w, h=h, ax=ax) # if colorbar or is_first: if colorbar: libplot.add_colorbar(fig, cmap,",
"ax = pca_plot_base(pca, clusters, pc1=pc1, pc2=pc2, marker=marker, labels=labels, s=s, w=w, h=h, fig=fig, ax=ax)",
"size Parameters ---------- data : Pandas dataframe Matrix of umi counts \"\"\" #",
"matplotlib.colors.LinearSegmentedColormap.from_list('bgy', ['#003380', '#5fd38d', '#ffd42a']) EXP_NORM = matplotlib.colors.Normalize(-1, 3, clip=True) LEGEND_PARAMS = {'show': True,",
"ids = list(sorted(set(clusters['Cluster']))) indices = np.array(list(range(0, len(ids)))) if colors is None: colors =",
"sort=True, cluster_order=None, fig=None, ax=None): \"\"\" Create a tsne plot without the formatting Parameters",
"fig, ax def tsne_plot(tsne, marker='o', s=libplot.MARKER_SIZE, c='red', label=None, fig=None, ax=None): fig, ax =",
"centroid idx = np.where(abs(z) < sdmax)[0] # (d > x1) & (d <",
"#y1 = y[idx] # avg1 = np.zeros(x.size) #avg[idx] #avg1[idx] = 1 # fx",
"clusters, cluster, color='black', background=BACKGROUND_SAMPLE_COLOR, bgedgecolor='#808080', show_background=True, add_titles=True, size=4, alpha=ALPHA, s=MARKER_SIZE, edgecolors='white', linewidth=EDGE_WIDTH, fig=None,",
"# im2.paste(im_smooth, (0, 0), im_smooth) # # im_base.paste(im2, (0, 0), im2) if gene_id",
"#libcluster.format_legend(ax, cols=6, markerscale=2) if out is not None: libplot.savefig(fig, out) return fig, ax",
"imagelib.remove_background(im) im_edges = imagelib.edges(im_no_bg) im_smooth = imagelib.smooth(im_edges) im_outline = imagelib.paste(im_no_bg, im_smooth) imagelib.paste(im_base, im_outline,",
"cells and columns are tsne dimensions exp : numpy array expression values for",
"genes_expr(d_a, tsne_a, genes, prefix='a_BGY', cmap=BLUE_GREEN_YELLOW_CMAP, w=w, h=h, dir='a/GeneExp', format=format) fig, ax = cluster_plot(tsne_a,",
"scaled if axis == 0: return pd.DataFrame(MinMaxScaler(feature_range=(min, max)).fit_transform(d), index=d.index, columns=d.columns) else: return pd.DataFrame(MinMaxScaler(feature_range=(min,",
"df2 = pd.DataFrame({'Silhouette Score': x2, 'Cluster': clusters.iloc[:, 0].tolist( ), 'Label': np.repeat('tsne-ah', len(x2))}) libplot.boxplot(df2,",
"add_titles=add_titles, cluster_order=cluster_order) if out is None: out = '{}/{}_{}_separate_clusters.png'.format(dir, method, name) libplot.savefig(fig, out,",
"# BGY_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list('bgy', ['#002255', '#2ca05a', '#ffd42a']) # BGY_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list('bgy', ['#002255', '#003380',",
"for i in range(len(gbm.barcodes)): ret.append(np.sum(gbm.matrix[:, i].toarray())) return ret def df(gbm): \"\"\" Converts a",
"get_gene_ids(data, genes, ids=ids, gene_names=gene_names) w, h, rows, cols = expr_grid_size(gene_ids, size=size) fig =",
"the top of the background # # sid = 0 # # for",
"for i in range(0, len(gene_ids)): gene_id = gene_ids[i][1] gene = gene_ids[i][2] print(gene_id, gene)",
"isinstance(clip, float) or isinstance(clip, int): max = abs(clip) min = -max if isinstance(min,",
"ax.set_xlim(xlim) ax.set_ylim(ylim) if not show_axes: libplot.invisible_axes(ax) legend_params = dict(LEGEND_PARAMS) if isinstance(legend, bool): legend_params['show']",
"cluster = cluster_order[i] if isinstance(colors, dict): color = colors[cluster] elif isinstance(colors, list): if",
"indexes: ret.append((index, ids[index], gene_names[index])) else: # if id does not exist, try the",
"d = im_data[np.where(grey_areas)] # d[:, :] = [255, 255, 255, 0] # im_data[np.where(grey_areas)]",
"def plot_centroids(tsne, clusters, name): c = centroids(tsne, clusters) fig, ax = libplot.newfig(w=5, h=5)",
"colors is None: # colors = libcluster.colors() # # for i in range(0,",
"alpha=ALPHA, linewidth=EDGE_WIDTH, edgecolors='none', colorbar=True, method='tsne', format='png'): \"\"\" Plot multiple genes on a grid.",
"is None: fig, ax = libplot.new_fig(w=w, h=h) # if norm is None and",
"dir='.', w=16, h=16, legend=True): sc = sample_clusters(clusters, sample_names) create_cluster_plot(tsne_umi_log2, sc, name, method=method, format=format,",
"t-sne 2D data # \"\"\" # # fig, ax = expr_plot(tsne, # exp,",
"l % cols == 0: # Assume we will add a row for",
"= libplot.new_fig(size, size) #print('Label {}'.format(l)) idx1 = np.where(clusters['Cluster'] == cluster)[0] idx2 = np.where(clusters['Cluster']",
"> 0) #(r < 255) | (g < 255) | (b < 255)",
"the order they should be rendered Returns ------- fig : Matplotlib figure A",
"endpoint=True) # yt = np.linspace(y.min(), y.max(), 100, endpoint=True) # # xp = points[hull.vertices,",
"= x[idx] y = y[idx] #centroid = [x.sum() / x.size, y.sum() / y.size]",
"be labeled 'TSNE-1', 'TSNE-2' etc genes : array List of gene names \"\"\"",
"out, pad=0) # # return fig, ax def create_expr_plot(tsne, exp, dim=[1, 2], cmap=None,",
"l = x.shape[0] else: return None cols = int(np.ceil(np.sqrt(l))) w = size *",
"rows fig = libplot.new_base_fig(w=w, h=w) si = 1 for i in range(0, n):",
"# z-score #e = (e - e.mean()) / e.std() # limit to 3",
"y = tsne.iloc[idx2, 1] # libplot.scatter(x, y, c=BACKGROUND_SAMPLE_COLOR, ax=ax) # # # Plot",
"= 'pca_expr_{}_t{}_vs_t{}.pdf'.format(name, 1, 2) fig, ax = base_pca_expr_plot(data, expr, dim=dim, cmap=cmap, marker=marker, s=s,",
"to highlight cluster # im_base.paste(im2, (0, 0), im2) # break imagelib.save(im_base, out) def",
"i in range(0, len(cids)): # c = cids[i] # # #print('Label {}'.format(l)) #",
"#(0.98, 0.98, 0.98) #(0.8, 0.8, 0.8) #(0.85, 0.85, 0.85 BACKGROUND_SAMPLE_COLOR = [0.75, 0.75,",
"fig, ax def expr_plot(data, exp, dim=[1, 2], cmap=plt.cm.magma, marker='o', s=MARKER_SIZE, alpha=1, edgecolors=EDGE_COLOR, linewidth=EDGE_WIDTH,",
"1: return None else: idx = np.where(ids == g)[0] if idx.size > 0:",
": DataFrame Clusters in colors : list, color Colors of points add_titles :",
"'CD83', 'CXCR4', 'MKI67', 'MYC', 'PCNA', 'PRDM1'] genes = pd.read_csv('../../../../expression_genes.txt', header=0) mkdir('a') a_barcodes =",
"markers='o', s=libplot.MARKER_SIZE, colors=None, w=8, h=8, legend=True, show_axes=False, sort=True, cluster_order=None, fig=None, ax=None, out=None): fig,",
"np.repeat('tsne-ah', len(x2))}) libplot.boxplot(df2, 'Cluster', 'Silhouette Score', colors=libcluster.colors(), ax=ax) ax.set_ylim([-1, 1]) ax.set_title('tsne-ah') libplot.savefig(fig, '{}_silhouette.pdf'.format(name))",
"# matplotlib.use('agg') import matplotlib.pyplot as plt import collections import numpy as np import",
"e.std() #print(e.min(), e.max()) # z-score #e = (e - e.mean()) / e.std() #",
"import interp1d from scipy.spatial import distance import networkx as nx import os import",
"= im_data[:, :, 3] # (r < 255) | (g < 255) |",
"else: color = CLUSTER_101_COLOR else: color = 'black' fig, ax = separate_cluster(tsne, clusters,",
"sd) z = (d - m) / sd # find all points within",
"clusters, s=libplot.MARKER_SIZE, colors=None, edgecolors=EDGE_COLOR, linewidth=EDGE_WIDTH, dim1=0, dim2=1, w=8, alpha=ALPHA, # libplot.ALPHA, show_axes=True, legend=True,",
"out, '...') libplot.savefig(fig, out) libplot.savefig(fig, 'tmp.png') plt.close(fig) def cluster_grid(tsne, clusters, colors=None, cols=-1, size=SUBPLOT_SIZE,",
"Index, optional Index of gene ids gene_names : Index, optional Index of gene",
"0.25 ALPHA = 0.9 BLUE_YELLOW_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list( 'blue_yellow', ['#162d50', '#ffdd55']) BLUE_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list(",
"be z-scored. Transforming now...') # zscore #e = (e - e.mean()) / e.std()",
"# ax.set_ylim(ylim) def base_cluster_plot(d, clusters, markers=None, s=libplot.MARKER_SIZE, colors=None, edgecolors=EDGE_COLOR, linewidth=EDGE_WIDTH, dim1=0, dim2=1, w=8,",
"im_edges = imagelib.edges(im) im_outline = imagelib.paste(im, im_edges) # im_no_bg im_smooth = imagelib.smooth(im_outline) imagelib.save(im_smooth,",
"im_data[np.where(black_areas)] = d im2 = Image.fromarray(im_data) im2.save('edges.png', 'png') # overlay edges on top",
"# im_smooth = imagelib.smooth_edges(im_no_bg) # imagelib.paste(im_no_bg, im_smooth, inplace=True) # imagelib.save(im_no_bg, 'smooth.png') # imagelib.paste(im_base,",
"supplied argument, return the supplied figure, otherwise a new figure is created and",
"data : DataFrame data table containing and index genes : list List of",
"out = '{}/{}_expr_{}.png'.format(dir, method, gene) print(out) # overlay edges on top of original",
"= np.append(yp, yp[0]) ax.plot(xp, yp, 'k-') #ax.plot(points[hull.vertices[0], 0], points[hull.vertices[[0, -1]], 1]) #points =",
"Index of gene names Returns ------- list list of tuples of (index, gene_id,",
"on top of original image to highlight cluster # im_base.paste(im2, (0, 0), im2)",
"is None: norm = libplot.NORM_3 # Sort by expression level so that extreme",
"figure If fig is a supplied argument, return the supplied figure, otherwise a",
"gene_ids[i][2] print(gene_id, gene) exp = get_gene_data(data, gene_id, ids=ids, gene_names=gene_names) bin_means, bin_edges, binnumber =",
"as f: try: group = f.create_group(f.root, genome) f.create_carray(group, 'genes', obj=gbm.gene_ids) f.create_carray(group, 'gene_names', obj=gbm.gene_names)",
"matplotlib.colors.LinearSegmentedColormap.from_list('bgy', ['#003366', '#40bf80', '#ffff33']) BGY_ORIG_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list( 'bgy', ['#002255', '#003380', '#2ca05a', '#ffd42a', '#ffdd55'])",
"is None: fig, ax = libplot.new_fig() libplot.scatter(tsne['TSNE-1'], tsne['TSNE-2'], c=c, marker=marker, label=label, s=s, ax=ax)",
"gene_names=None): \"\"\" For a given gene list, get all of the transcripts. Parameters",
"columns=d.columns) def min_max_scale(d, min=0, max=1, axis=1): #m = d.min(axis=1) #std = (d -",
"range(0, clusters.shape[0])] # def network(tsne, clusters, name, k=5): # A = kneighbors_graph(tsne, k,",
"rows += 1 h = size * rows return w, h, rows, cols",
"phenograph import libplot import libcluster import libtsne import seaborn as sns from libsparse.libsparse",
"expr_plot(tsne_bin, exp_bin, cmap=cmap, s=s, colorbar=colorbar, norm=norm, alpha=alpha, linewidth=linewidth, edgecolors=edgecolors, ax=ax) tmp = 'tmp{}.png'.format(bin)",
"edgecolors=EDGE_COLOR, linewidth=EDGE_WIDTH, norm=None, method='tsne', show_axes=False, colorbar=True, out=None): # plt.cm.plasma): \"\"\" Creates and saves",
"None cols = int(np.ceil(np.sqrt(l))) w = size * cols rows = int(l /",
"df2.iloc[:, pc2 - 1] if i in colors: color = colors[i] # l]",
"label=label, fig=fig, ax=ax) #libtsne.tsne_legend(ax, labels, colors) libcluster.format_simple_axes(ax, title=\"t-SNE\") libcluster.format_legend(ax, cols=6, markerscale=2) return fig,",
"= 1 / m.sum(axis=0) mn = m.multiply(s) tpm = mn.multiply(1000000) return GeneBCMatrix(gbm.gene_ids, gbm.gene_names,",
"x = tsne.iloc[idx2, 0] # y = tsne.iloc[idx2, 1] # # libplot.scatter(x, y,",
"1000000 / reads_per_bc scaled = data.multiply(scaling_factors) # , axis=1) return scaled def umi_log2(d):",
"0), im_smooth) # # # overlay edges on top of original image to",
"[0.75, 0.75, 0.75] EDGE_COLOR = None # [0.3, 0.3, 0.3] #'#4d4d4d' EDGE_WIDTH =",
"0), im2) # break imagelib.save(im_base, out) def cluster_plot(tsne, clusters, dim1=0, dim2=1, markers='o', s=libplot.MARKER_SIZE,",
"= libplot.new_base_fig(w=w, h=w) # # if colors is None: # colors = libcluster.colors()",
"show_axes=False, ax=None, cluster_order=None, format='png', dir='.', out=None): if out is None: # libtsne.get_tsne_plot_name(name)) out",
"cluster = ids[i] if isinstance(colors, dict): color = colors[cluster] elif isinstance(colors, list): if",
"avg[idx]).sum() / avg[idx].sum()] d = np.array([distance.euclidean(centroid, (a, b)) for a, b in zip(x,",
"im, inplace=True) # # find gray areas and mask # im_data = np.array(im1.convert('RGBA'))",
"obj=gbm.matrix.indices) f.create_carray(group, 'indptr', obj=gbm.matrix.indptr) f.create_carray(group, 'shape', obj=gbm.matrix.shape) except: raise Exception(\"Failed to write H5",
"= get_gene_ids(data, genes, ids=ids, gene_names=gene_names) for i in range(0, len(gene_ids)): gene_id = gene_ids[i][1]",
"genes: indexes = np.where(ids == g)[0] if indexes.size > 0: for index in",
"n): ax = libplot.new_ax(fig, subplot=(rows, rows, si)) pca_plot_base(pca, clusters, pc1=(i + 1), pc2=(j",
"[colors[clusters['Cluster'][i] - 1] for i in range(0, clusters.shape[0])] # def network(tsne, clusters, name,",
"libtsne.load_pca(d_a, 'a', cache=cache) # pca.iloc[idx,:] tsne_a = libtsne.load_pca_tsne(pca_a, 'a', cache=cache) c_a = libtsne.load_phenograph_clusters(pca_a,",
"'w', filters=flt) as f: try: group = f.create_group(f.root, genome) f.create_carray(group, 'genes', obj=gbm.gene_ids) f.create_carray(group,",
"name)) # # def load_clusters(pca, headers, name, cache=True): file = libtsne.get_cluster_file(name) if not",
"> 0.5: # ax.scatter(x[i], # y[i], # c='#ffffff00', # s=s, # marker=marker, #",
"= tsne.iloc[:, 0] d2 = tsne.iloc[:, 1] xlim = [d1[d1 < 0].quantile(1 -",
"genes = gbm.gene_names gene_indices = np.where(genes == gene_name)[0] if len(gene_indices) == 0: raise",
"* avg[idx]).sum() / avg[idx].sum(), (y * avg[idx]).sum() / avg[idx].sum()] d = np.array([distance.euclidean(centroid, (a,",
"BGY_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list('bgy', ['#002255', '#2ca05a', '#ffd42a']) # BGY_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list('bgy', ['#002255', '#003380', '#2ca05a',",
"ax=ax) # # sid += 1 # # ax.set_title('C{} ({:,})'.format(c, len(idx1)), color=colors[i]) #",
"cluster, color=color, size=w, s=s, linewidth=linewidth, add_titles=False) # get x y lim xlim =",
"#np.argsort(abs(exp)) # np.argsort(exp) x = data.iloc[idx, dim[0] - 1].values # data['{}-{}'.format(t, d1)][idx] y",
"markerscale=2) if out is not None: libplot.savefig(fig, out) return fig, ax def create_cluster_plot(d,",
"y[idx] # avg1 = np.zeros(x.size) #avg[idx] #avg1[idx] = 1 # fx = interp1d(points[hull.vertices,",
"data[:, :, 1] #b = data[:, :, 2] a = im_data[:, :, 3]",
"expression matrix tsne : Pandas dataframe Cells x tsne tsne data. Columns should",
"fy = interp1d(points[hull.vertices, 1], points[hull.vertices, 0], kind='cubic') # # xt = np.linspace(x.min(), x.max(),",
"data clusters : Pandas dataframe n x 1 table of n cells with",
"node_size=200, node_color=node_color, vmax=(c.shape[0] - 1), cmap=libcluster.colormap()) nx.draw_networkx(G, with_labels=True, labels=labels, ax=ax, node_size=800, node_color=node_color, font_color='white',",
"Plot background points # # ax = libplot.new_ax(fig, subplot=(rows, rows, i + 1))",
"def df(gbm): \"\"\" Converts a GeneBCMatrix to a pandas dataframe (dense) Parameters ----------",
"does not appear to be z-scored. Transforming now...') # zscore #e = (e",
"cmap, norm=norm) #libcluster.format_simple_axes(ax, title=t) if not show_axes: libplot.invisible_axes(ax) return fig, ax # def",
"return scaled def umi_log2(d): if isinstance(d, SparseDataFrame): print('UMI norm log2 sparse') return d.log2(add=1)",
"out=None): \"\"\" Plot multiple genes on a grid. Parameters ---------- data : Pandas",
"(%d) is an older version that is not supported by this function.' %",
"- 1].values # data['{}-{}'.format(t, d2)][idx] e = exp[idx] # if (e.min() == 0):",
"dir='b/GeneExp', format=format) fig, ax = cluster_plot(tsne_b, c_b, legend=False, w=w, h=h) libplot.savefig(fig, 'b/b_tsne_clusters_med.pdf') def",
"gene names idx = np.where(np.isin(gene_names, g))[0] if idx.size < 1: return None else:",
"---------- tsne : Pandas dataframe Cells x tsne tsne data. Columns should be",
"each column is a cell reads_per_bc = data.sum(axis=0) scaling_factors = 1000000 / reads_per_bc",
"i = c - 1 cluster = ids[i] # look up index for",
"255, 0] # im_data[np.where(grey_areas)] = d # # im2 = Image.fromarray(im_data) # #",
"method, name, format) print(out) return cluster_plot(d, clusters, dim1=dim1, dim2=dim2, markers=markers, colors=colors, s=s, w=w,",
"x.max(), 100, endpoint=True) # yt = np.linspace(y.min(), y.max(), 100, endpoint=True) # # xp",
"'TSNE-1', 'TSNE-2' etc genes : array List of gene names Returns ------- fig",
"if not show_axes: libplot.invisible_axes(ax) legend_params = dict(LEGEND_PARAMS) if isinstance(legend, bool): legend_params['show'] = legend",
"return fig def create_cluster_grid(tsne, clusters, name, colors=None, cols=-1, size=SUBPLOT_SIZE, add_titles=True, cluster_order=None, method='tsne', dir='.',",
"'#ffd633']) GRAY_PURPLE_YELLOW_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list( 'grey_purple_yellow', ['#e6e6e6', '#3333ff', '#ff33ff', '#ffe066']) GYBLGRYL_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list( 'grey_blue_green_yellow',",
"Creates and saves a presentation tsne plot \"\"\" if out is None: out",
"markers=markers, colors=colors, s=s, w=w, h=h, cluster_order=cluster_order, show_axes=show_axes, legend=legend, sort=sort, out=out) def base_tsne_plot(tsne, marker='o',",
"color = 'black' # # libplot.scatter(x, y, c=color, ax=ax) # # if add_titles:",
"a presentation tsne plot \"\"\" if out is None: out = '{}_expr.pdf'.format(method) fig,",
"idx[0] else: return None if isinstance(data, SparseDataFrame): return data[idx, :].to_array() else: return data.iloc[idx,",
"alpha=1, edgecolors=EDGE_COLOR, linewidth=EDGE_WIDTH, w=libplot.DEFAULT_WIDTH, h=libplot.DEFAULT_HEIGHT, show_axes=False, fig=None, ax=None, norm=None, colorbar=False): # plt.cm.plasma): \"\"\"",
"u'version' in f.attrs: if f.attrs['version'] > 2: raise ValueError( 'Matrix HDF5 file format",
"imageWithEdges = im1.filter(ImageFilter.FIND_EDGES) im_data = np.array(imageWithEdges.convert('RGBA')) #r = data[:, :, 0] #g =",
"type(x) is pd.core.frame.DataFrame: l = x.shape[0] else: return None cols = int(np.ceil(np.sqrt(l))) w",
"#hull = ConvexHull(points) #ax.plot(points[hull.vertices,0], points[hull.vertices,1]) #zi = griddata((x, y), avg1, (xi, yi)) #ax.contour(xi,",
"s=s, w=w, h=h, fig=fig, ax=ax) #libtsne.tsne_legend(ax, labels, colors) libcluster.format_simple_axes(ax, title=\"PC\") if legend: libcluster.format_legend(ax,",
"gene id gene_id = gene_ids[i][1] gene = gene_ids[i][2] print(gene, gene_id) exp = get_gene_data(data,",
"h=8, alpha=ALPHA, # libplot.ALPHA, show_axes=True, legend=True, sort=True, cluster_order=None, fig=None, ax=None): \"\"\" Create a",
"colorbar: libplot.add_colorbar(fig, cmap, norm=norm) #libcluster.format_simple_axes(ax, title=t) if not show_axes: libplot.invisible_axes(ax) return fig, ax",
"plt.cm.plasma): out = 'pca_expr_{}_t{}_vs_t{}.pdf'.format(name, 1, 2) fig, ax = base_pca_expr_plot(data, expr, dim=dim, cmap=cmap,",
"optional Second dimension being plotted (usually 2) fig : matplotlib figure, optional Supply",
"import sklearn.preprocessing from sklearn.preprocessing import StandardScaler from sklearn.preprocessing import RobustScaler from sklearn.preprocessing import",
"genome) f.create_carray(group, 'genes', obj=gbm.gene_ids) f.create_carray(group, 'gene_names', obj=gbm.gene_names) f.create_carray(group, 'barcodes', obj=gbm.barcodes) f.create_carray(group, 'data', obj=gbm.matrix.data)",
"list, get all of the transcripts. Parameters ---------- data : DataFrame data table",
"# idx2 = np.where(clusters['Cluster'] != cluster)[0] # # # Plot background points #",
"im2 = Image.fromarray(im_data) # # # Edge detect on what is left (the",
"pca.shape[1]): create_cluster_plot(pca, labels, name, pc1=( i + 1), pc2=(j + 1), marker=marker, s=s)",
"BGY_CMAP, norm=None, w=libplot.DEFAULT_WIDTH, h=libplot.DEFAULT_HEIGHT, alpha=1.0, colorbar=False, method='tsne', fig=None, ax=None, sdmax=0.5): \"\"\" Plot multiple",
"list(sorted(set(clusters['Cluster']))) im_base = imagelib.new(w * 300, w * 300) for i in range(0,",
"+= 1 libtsne.write_clusters(headers, labels, name) cluster_map, data = libtsne.read_clusters(file) labels = data #",
"'MYC', 'PCNA', 'PRDM1'] genes = pd.read_csv('../../../../expression_genes.txt', header=0) mkdir('a') a_barcodes = pd.read_csv('../a_barcodes.tsv', header=0, sep='\\t')",
"# Plot cluster over the top of the background # # x =",
"tsne tsne data. Columns should be labeled 'TSNE-1', 'TSNE-2' etc clusters : DataFrame",
"so it must have the same number of elements as data has rows.",
"'shape', obj=gbm.matrix.shape) except: raise Exception(\"Failed to write H5 file.\") def subsample_matrix(gbm, barcode_indices): return",
"norm=None): # plt.cm.plasma): out = 'pca_expr_{}_t{}_vs_t{}.pdf'.format(name, 1, 2) fig, ax = base_pca_expr_plot(data, expr,",
"!= gene: out = '{}/{}_expr_{}_{}.{}'.format(dir, method, gene, gene_id, format) else: out = '{}/{}_expr_{}.{}'.format(dir,",
"= np.array(color) # # c1 = color.copy() # c1[-1] = 0.5 # #",
"= counts.iloc[:, idx] d_b = libcluster.remove_empty_rows(d_b) if isinstance(d_a, SparseDataFrame): d_b = umi_norm_log2(d_b) else:",
"# # # overlay edges on top of original image to highlight cluster",
"c_b = libtsne.load_phenograph_clusters(pca_b, 'b', cache=cache) create_pca_plot(pca_b, c_b, 'b', dir='b') create_cluster_plot(tsne_b, c_b, 'b', dir='b')",
"sample in samples: # id = '-{}'.format(sid + 1) # idx1 = np.where((clusters['Cluster']",
"None: # libtsne.get_tsne_plot_name(name)) out = '{}/{}_{}.{}'.format(dir, method, name, format) print(out) return cluster_plot(d, clusters,",
"fig=fig, ax=ax) x = tsne.iloc[:, 0].values # data['{}-{}'.format(t, d1)][idx] y = tsne.iloc[:, 1].values",
"ax : Matplotlib axes Axes used to render the figure \"\"\" if ax",
"print('UMI norm log2 scale sparse') sd = StandardScaler(with_mean=False).fit_transform(d.T.matrix) return SparseDataFrame(sd.T, index=d.index, columns=d.columns) else:",
"get_gene_names(data) gene_ids = get_gene_ids(data, genes, ids=ids, gene_names=gene_names) for i in range(0, len(gene_ids)): gene_id",
"d2)][idx] idx = np.where(clusters['Cluster'] == cid)[0] nx = 500 ny = 500 xi",
"#A = A[0:500, 0:500] # # G=nx.from_numpy_matrix(A) # pos=nx.spring_layout(G) #, k=2) # #",
"'black' ax = libplot.new_ax(fig, subplot=(rows, cols, pc)) separate_cluster(tsne, clusters, cluster, color=color, add_titles=add_titles, ax=ax)",
"# # Plot cluster over the top of the background # # sid",
"cache=cache) # pca.iloc[idx,:] tsne_a = libtsne.load_pca_tsne(pca_a, 'a', cache=cache) c_a = libtsne.load_phenograph_clusters(pca_a, 'a', cache=cache)",
"gene, format) libplot.savefig(fig, 'tmp.png', pad=0) libplot.savefig(fig, out, pad=0) plt.close(fig) im1 = Image.open('tmp.png') #",
"def network(tsne, clusters, name, k=5): # A = kneighbors_graph(tsne, k, mode='distance', metric='euclidean').toarray() #",
"\"\"\" Creates and saves a presentation tsne plot \"\"\" if out is None:",
"------- fig : Matplotlib figure A new Matplotlib figure used to make the",
"len(ids3) / 5 * 100 overlaps.append(o) df = pd.DataFrame( {'Cluster': list(range(1, c1.shape[0] +",
"color = colors[i] else: color = 'black' else: color = 'black' fig, ax",
"highlight samples # # Parameters # ---------- # tsne : Pandas dataframe #",
"= d.std() m = d.mean() print(m, sd) z = (d - m) /",
"one or more required datasets.\") #GeneBCMatrix = collections.namedtuple('FeatureBCMatrix', ['feature_ids', 'feature_names', 'barcodes', 'matrix']) def",
"fig, ax = pca_plot_base(pca, clusters, pc1=pc1, pc2=pc2, marker=marker, labels=labels, s=s, w=w, h=h, fig=fig,",
"type(x) is int: l = x elif type(x) is list: l = len(x)",
"bool Whether to add titles to plots w: int, optional width of new",
"show_axes=False, colorbar=True, out=None): # plt.cm.plasma): \"\"\" Creates and saves a presentation tsne plot",
"array List of gene names Returns ------- fig : Matplotlib figure A new",
"node in f.walk_nodes('/' + genome, 'Array'): dsets[node.name] = node.read() # for node in",
"= Image.fromarray(im_data) # # # Edge detect on what is left (the clusters)",
"'b', cache=cache) c_b = libtsne.load_phenograph_clusters(pca_b, 'b', cache=cache) create_pca_plot(pca_b, c_b, 'b', dir='b') create_cluster_plot(tsne_b, c_b,",
"= libplot.new_fig() #expr_plot(tsne, exp, ax=ax) #libplot.add_colorbar(fig, cmap) fig, ax = expr_plot(tsne, exp, cmap=cmap,",
"= matplotlib.colors.LinearSegmentedColormap.from_list( 'grey_blue_green_yellow', ['#e6e6e6', '#0055d4', '#00aa44', '#ffe066']) OR_RED_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list( 'or_red', matplotlib.cm.OrRd(range(4, 256)))",
"fig = libplot.new_base_fig(w=w, h=h) for i in range(0, len(gene_ids)): # gene id gene_id",
"pad=2) plt.close(fig) def set_tsne_ax_lim(tsne, ax): \"\"\" Set the t-SNE x,y limits to look",
"a1 = kneighbors_graph(c1, k, mode='distance', metric='euclidean').toarray() a2 = kneighbors_graph(c2, k, mode='distance', metric='euclidean').toarray() overlaps",
"grid to look nice. \"\"\" if type(x) is int: l = x elif",
"+ 1 #nx.draw_networkx(G, pos=pos, with_labels=False, ax=ax, node_size=200, node_color=node_color, vmax=(c.shape[0] - 1), cmap=libcluster.colormap()) nx.draw_networkx(G,",
"norm log2 sparse') return d.log2(add=1) else: return (d + 1).apply(np.log2) def umi_tpm_log2(data): d",
"sort=True, outline=True): cluster_order = list(sorted(set(clusters['Cluster']))) im_base = imagelib.new(w * 300, w * 300)",
"# d2=2, # x1=None, # x2=None, # cmap=BLUE_YELLOW_CMAP, # marker='o', # s=MARKER_SIZE, #",
"# edgecolors, linewidth=linewidth, s=s) if add_titles: if isinstance(cluster, int): prefix = 'C' else:",
"feature_names = [x.decode('ascii', 'ignore') for x in f['matrix']['features']['name']] barcodes = list(f['matrix']['barcodes'][:]) matrix =",
"min=0, max=1, axis=1): if axis == 0: return pd.DataFrame(RobustScaler().fit_transform(d), index=d.index, columns=d.columns) else: return",
"= imagelib.open(tmp) if outline: im_no_bg = imagelib.remove_background(im) im_edges = imagelib.edges(im) im_outline = imagelib.paste(im,",
"clusters.iloc[:, 0].tolist(), metric='euclidean') x2 = silhouette_samples( tsne_umi_log2, clusters.iloc[:, 0].tolist(), metric='euclidean') fig, ax =",
"index = data.index if isinstance(genes, pd.core.frame.DataFrame): genes = genes['Genes'].values if norm is None:",
"rows # # fig = libplot.new_base_fig(w=w, h=w) # # if colors is None:",
"# measure cluster worth x1 = silhouette_samples( tsne, clusters.iloc[:, 0].tolist(), metric='euclidean') x2 =",
"ax = pca_plot(pca, clusters, pc1=pc1, pc2=pc2, labels=labels, marker=marker, legend=legend, s=s, w=w, h=h, fig=fig,",
"color=color, add_titles=add_titles, size=size) out = '{}_sep_clust_{}_c{}.{}'.format(type, name, cluster, format) print('Creating', out, '...') libplot.savefig(fig,",
"d1)][idx] y = tsne.iloc[:, 1].values # data['{}-{}'.format(t, d2)][idx] idx = np.where(clusters['Cluster'] == cid)[0]",
"all points within 1 sd of centroid idx = np.where(abs(z) < sdmax)[0] #",
"clusters # im2.paste(im_smooth, (0, 0), im_smooth) # # # overlay edges on top",
"List of cluster ids in the order they should be rendered Returns -------",
"is int: l = x elif type(x) is list: l = len(x) elif",
"= matplotlib.colors.LinearSegmentedColormap.from_list('bgy', ['#00264d', '#003366', '#339933', '#e6e600', '#ffff33']) # BGY_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list('bgy', ['#003366', '#40bf80',",
"cache = True counts = libcluster.remove_empty_rows(counts) # ['AICDA', 'CD83', 'CXCR4', 'MKI67', 'MYC', 'PCNA',",
"#e[e < -3] = -3 #e[e > 3] = 3 ax.scatter(x, y, c=e,",
"# .tolist() return cluster_map, labels def umi_tpm(data): # each column is a cell",
"& (g < 255) & (g > 200) & (b < 255) &",
"'Cluster', 'Silhouette Score', colors=libcluster.colors(), ax=ax) ax.set_ylim([-1, 1]) ax.set_title('tsne-ah') libplot.savefig(fig, '{}_silhouette.pdf'.format(name)) def node_color_from_cluster(clusters): colors",
"norm=norm, alpha=alpha, fig=fig, ax=ax) x = tsne.iloc[:, 0].values # data['{}-{}'.format(t, d1)][idx] y =",
"data table containing and index genes : list List of strings of gene",
"the interesting clusters labels, graph, Q = phenograph.cluster(pca, k=20) if min(labels) == -1:",
"= (d - m) / (d.max(axis=1) - m) #scaled = std * (max",
"+ 1).apply(np.log2) def umi_tpm_log2(data): d = umi_tpm(data) return umi_log2(d) def umi_norm(data): \"\"\" Scale",
"GYBLGRYL_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list( 'grey_blue_green_yellow', ['#e6e6e6', '#0055d4', '#00aa44', '#ffe066']) OR_RED_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list( 'or_red', matplotlib.cm.OrRd(range(4,",
"= int(np.ceil(np.sqrt(n))) rows = int(np.ceil(n / cols)) w = size * cols h",
"cmap.N)) # color = np.array(color) # # c1 = color.copy() # c1[-1] =",
"sample/batch. \"\"\" sc = np.array(['' for i in range(0, d.shape[0])], dtype=object) c =",
"tsne plot without the formatting \"\"\" if ax is None: fig, ax =",
"0:3] = [64, 64, 64] im_data[np.where(black_areas)] = d im2 = Image.fromarray(im_data) im2.save('edges.png', 'png')",
"np.argsort(exp) #np.argsort(abs(exp)) # np.argsort(exp) x = data.iloc[idx, dim[0] - 1].values # data['{}-{}'.format(t, d1)][idx]",
"!= cluster)[0] # Plot background points if show_background: x = tsne.iloc[idx2, 0] y",
"= ids[i] # look up index for color purposes #i = np.where(ids ==",
"# d2=d2, # x1=x1, # x2=x2, # cmap=cmap, # marker=marker, # s=s, #",
"labels, name, marker='o', s=MARKER_SIZE): for i in range(0, pca.shape[1]): for j in range(i",
"labels=labels, s=s, w=w, h=h, fig=fig, ax=ax) #libtsne.tsne_legend(ax, labels, colors) libcluster.format_simple_axes(ax, title=\"PC\") if legend:",
"1] #b = data[:, :, 2] a = im_data[:, :, 3] # (r",
"1]) #points = np.array([[x, y] for x, y in zip(x1, y1)]) #hull =",
"gene_names=gene_names) print(gene_ids) for i in range(0, len(gene_ids)): gene_id = gene_ids[i][1] gene = gene_ids[i][2]",
"image # im = imagelib.open(tmp) # im_no_bg = imagelib.remove_background(im) # im_smooth = imagelib.smooth_edges(im_no_bg)",
"= libcluster.remove_empty_rows(counts) # ['AICDA', 'CD83', 'CXCR4', 'MKI67', 'MYC', 'PCNA', 'PRDM1'] genes = pd.read_csv('../../../../expression_genes.txt',",
"cols, i + 1) expr_plot(tsne, exp, ax=ax, cmap=cmap, colorbar=False) # if i ==",
"index=d.index, columns=d.columns) else: # StandardScaler().fit_transform(d.T) sd = sklearn.preprocessing.scale(d, axis=axis) #sd = sd.T if",
"gbm.matrix[gene_indices[0], :].toarray().squeeze() def gbm_to_df(gbm): return pd.DataFrame(gbm.matrix.todense(), index=gbm.gene_names, columns=gbm.barcodes) def get_barcode_counts(gbm): ret = []",
"len(idx1)), color=color) ax.axis('off') # libplot.invisible_axes(ax) return fig, ax def separate_clusters(tsne, clusters, name, colors=None,",
"if out is None: # libtsne.get_tsne_plot_name(name)) out = '{}/{}_{}.{}'.format(dir, method, name, format) print(out)",
"# list(range(0, c.shape[0])) node_color = libcluster.colors()[0:c.shape[0]] cmap = libcluster.colormap() labels = {} for",
"exp, fig=fig, ax=ax, cmap=cmap, out=out) def separate_cluster(tsne, clusters, cluster, color='black', background=BACKGROUND_SAMPLE_COLOR, bgedgecolor='#808080', show_background=True,",
"sort=sort, show_axes=show_axes, fig=fig, ax=ax) #libtsne.tsne_legend(ax, labels, colors) #libcluster.format_simple_axes(ax, title=\"t-SNE\") #libcluster.format_legend(ax, cols=6, markerscale=2) if",
"# # # # x = tsne.iloc[idx2, 0] # y = tsne.iloc[idx2, 1]",
"font_family='Arial') libplot.format_axes(ax) libplot.savefig(fig, '{}_centroid_network.pdf'.format(name)) def centroids(tsne, clusters): cids = list(sorted(set(clusters['Cluster'].tolist()))) ret = np.zeros((len(cids),",
"import h5py from scipy.interpolate import interp1d from scipy.spatial import distance import networkx as",
"return None else: idx = np.where(ids == g)[0] if idx.size > 0: #",
"ids, gene_names = get_gene_names(data) exp = get_gene_data(data, genes, ids=ids, gene_names=gene_names) avg = exp.mean(axis=0)",
"= pca_plot_base(pca, clusters, pc1=pc1, pc2=pc2, marker=marker, labels=labels, s=s, w=w, h=h, fig=fig, ax=ax) #libtsne.tsne_legend(ax,",
"= np.where(binnumber == bi)[0] idx_other = np.where(binnumber != bi)[0] tsne_other = tsne.iloc[idx_other, :]",
"len(colors): # np.where(clusters['Cluster'] == cluster)[0]] color = colors[i] else: color = 'black' else:",
"centroid = [(x * avg[idx]).sum() / avg[idx].sum(), (y * avg[idx]).sum() / avg[idx].sum()] d",
"= gene_ids[i][1] gene = gene_ids[i][2] print(gene_id, gene) exp = get_gene_data(data, gene_id, ids=ids, gene_names=gene_names)",
"used to make the plot ax : Matplotlib axes Axes used to render",
"fig def create_cluster_grid(tsne, clusters, name, colors=None, cols=-1, size=SUBPLOT_SIZE, add_titles=True, cluster_order=None, method='tsne', dir='.', out=None):",
"gene names idx = np.where(gene_names == g)[0] if idx.size > 0: idx =",
"y = tsne.iloc[idx1, 1] # # if isinstance(colors, dict): # color = colors[cluster]",
"# im_edges = im2.filter(ImageFilter.FIND_EDGES) # # im_smooth = im_edges.filter(ImageFilter.SMOOTH) # # # paste",
"is left (the clusters) # im_edges = im2.filter(ImageFilter.FIND_EDGES) # # # im_data =",
"this function.' % version) feature_ids = [x.decode('ascii', 'ignore') for x in f['matrix']['features']['id']] feature_names",
"labels def umi_tpm(data): # each column is a cell reads_per_bc = data.sum(axis=0) scaling_factors",
"range(0, pca.shape[1]): for j in range(i + 1, pca.shape[1]): create_cluster_plot(pca, labels, name, pc1=(",
"c = 1 for s in sample_names: id = '-{}'.format(c) print(id) print(np.where(d.index.str.contains(id))[0]) sc[np.where(d.index.str.contains(id))[0]]",
"number of elements as data has rows. d1 : int, optional First dimension",
"# b = im_data[:, :, 2] # # grey_areas = (r < 255)",
"= data.iloc[idx, dim[1] - 1].values # data['{}-{}'.format(t, d2)][idx] e = exp[idx] # if",
"y in zip(x1, y1)]) #hull = ConvexHull(points) #ax.plot(points[hull.vertices,0], points[hull.vertices,1]) #zi = griddata((x, y),",
"colorbar=False) # if i == 0: # libcluster.format_axes(ax) # else: # libplot.invisible_axes(ax) ax.set_title('{}",
"cmap=cmap, norm=norm, w=w, h=h, ax=ax) # if colorbar or is_first: if colorbar: libplot.add_colorbar(fig,",
"a base expression plot and adds a color bar. \"\"\" is_first = False",
"# t='TSNE', # d1=d1, # d2=d2, # x1=x1, # x2=x2, # cmap=cmap, #",
"headers, name, cache=True): file = libtsne.get_cluster_file(name) if not os.path.isfile(file) or not cache: print('{}",
"# + '7f' libplot.scatter(x, y, c=color, ax=ax, edgecolors='none', # edgecolors, linewidth=linewidth, s=s) if",
"dir='GeneExp', cmap=BGY_CMAP, norm=None, w=4, h=4, s=30, alpha=ALPHA, linewidth=EDGE_WIDTH, edgecolors='none', colorbar=True, method='tsne', format='png'): \"\"\"",
"print('UMI norm log2 sparse') return d.log2(add=1) else: return (d + 1).apply(np.log2) def umi_tpm_log2(data):",
"np.argsort(exp) x = data.iloc[idx, dim[0] - 1].values # data['{}-{}'.format(t, d1)][idx] y = data.iloc[idx,",
"# return scaled if axis == 0: return pd.DataFrame(MinMaxScaler(feature_range=(min, max)).fit_transform(d), index=d.index, columns=d.columns) else:",
"colors.get(cluster, 'black') elif isinstance(colors, list): #i = cluster - 1 if i <",
"(r < 255) & (r > 200) & (g < 255) & (g",
"id does not exist, try the gene names idx = np.where(gene_names == g)[0]",
"0), im2) if gene_id != gene: out = '{}/{}_expr_{}_{}.png'.format(dir, method, gene, gene_id) else:",
"/ x.shape[0]).tolist() ret[i, 0] = centroid[0] ret[i, 1] = centroid[1] return ret def",
"expression plot for T-SNE/2D space reduced representation of data. Parameters ---------- data :",
"gene_ids[i][2] print(gene_id, gene) exp = get_gene_data(data, gene_id, ids=ids, gene_names=gene_names) #fig, ax = libplot.new_fig()",
"Returns ------- list list of tuples of (index, gene_id, gene_name) \"\"\" if ids",
"l)[0] n = len(indices) label = 'C{} ({:,})'.format(l, n) df2 = pca.iloc[indices, ]",
"# #d = im_data[np.where(black_areas)] # #d[:, 0:3] = [64, 64, 64] # #im_data[np.where(black_areas)]",
"separate clusters colored by sample # \"\"\" # fig = tsne_cluster_sample_grid(tsne, clusters, samples,",
"def create_pca_plot(pca, clusters, name, pc1=1, pc2=2, marker='o', labels=False, legend=True, s=MARKER_SIZE, w=8, h=8, fig=None,",
"* rows return w, h, rows, cols def get_gene_names(data): if ';' in data.index[0]:",
"(d + 1).apply(np.log2) def umi_tpm_log2(data): d = umi_tpm(data) return umi_log2(d) def umi_norm(data): \"\"\"",
"label=None, fig=None, ax=None): fig, ax = base_tsne_plot(tsne, marker=marker, c=c, s=s, label=label, fig=fig, ax=ax)",
"pc1=1, pc2=2, marker='o', labels=False, s=MARKER_SIZE, w=8, h=8, fig=None, ax=None): colors = libcluster.get_colors() if",
"[255, 255, 255, 0] # im_data[np.where(grey_areas)] = d # # # #edges1 =",
"phenograph.cluster(pca, k=20) if min(labels) == -1: new_label = 100 labels[np.where(labels == -1)] =",
"obj=gbm.gene_names) f.create_carray(group, 'barcodes', obj=gbm.barcodes) f.create_carray(group, 'data', obj=gbm.matrix.data) f.create_carray(group, 'indices', obj=gbm.matrix.indices) f.create_carray(group, 'indptr', obj=gbm.matrix.indptr)",
"#g = data[:, :, 1] # #b = data[:, :, 2] # #a",
"= {} for i in range(0, c.shape[0]): labels[i] = i + 1 #nx.draw_networkx(G,",
"genome): flt = tables.Filters(complevel=1) with tables.open_file(filename, 'w', filters=flt) as f: try: group =",
"dir='.', out=None): fig = cluster_grid(tsne, clusters, colors=colors, cols=cols, size=size, add_titles=add_titles, cluster_order=cluster_order) if out",
"to highlight where the samples are Parameters ---------- tsne : Pandas dataframe Cells",
"size * cols h = size * rows fig = libplot.new_base_fig(w=w, h=h) if",
"['#162d50', '#ffdd55']) BLUE_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list( 'blue', ['#162d50', '#afc6e9']) BLUE_GREEN_YELLOW_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list( 'bgy', ['#162d50',",
"marker='o', labels=False, s=MARKER_SIZE, w=8, h=8, legend=True, fig=None, ax=None): fig, ax = pca_plot_base(pca, clusters,",
"= (x.sum(axis=0) / x.shape[0]).tolist() ret[i, 0] = centroid[0] ret[i, 1] = centroid[1] return",
"HDF5 file format version (%d) is an newer version that is not supported",
"clusters) c2 = centroids(tsne2, clusters) a1 = kneighbors_graph(c1, k, mode='distance', metric='euclidean').toarray() a2 =",
"= np.where(ids == cluster)[0][0] print('index', i, cluster, colors) if isinstance(colors, dict): color =",
"i + 1), pc2=(j + 1), marker=marker, s=s) def pca_base_plots(pca, clusters, n=10, marker='o',",
"being plotted (usually 2) fig : matplotlib figure, optional Supply a figure object",
"'a', cache=cache) # pca.iloc[idx,:] tsne_a = libtsne.load_pca_tsne(pca_a, 'a', cache=cache) c_a = libtsne.load_phenograph_clusters(pca_a, 'a',",
"d[:, 0:3] = [64, 64, 64] im_data[np.where(black_areas)] = d im2 = Image.fromarray(im_data) im2.save('edges.png',",
"version that is not supported by this function.' % version) feature_ids = [x.decode('ascii',",
"sort=sort, out=out) def base_tsne_plot(tsne, marker='o', s=libplot.MARKER_SIZE, c='red', label=None, fig=None, ax=None): \"\"\" Create a",
"# fig = libplot.new_base_fig(w=w, h=w) # # if colors is None: # colors",
"labels = data # .tolist() return cluster_map, labels def umi_tpm(data): # each column",
"# im_smooth imagelib.paste(im_base, im_smooth, inplace=True) else: imagelib.paste(im_base, im, inplace=True) # # find gray",
"i < len(colors): # colors[cid - 1] #colors[i] #np.where(clusters['Cluster'] == cluster)[0]] color =",
"fig, ax = cluster_plot(tsne_b, c_b, legend=False, w=w, h=h) libplot.savefig(fig, 'b/b_tsne_clusters_med.pdf') def sample_clusters(d, sample_names):",
"cmap=plt.cm.plasma, marker='o', edgecolors=EDGE_COLOR, linewidth=1, s=MARKER_SIZE, alpha=1, w=libplot.DEFAULT_WIDTH, h=libplot.DEFAULT_HEIGHT, fig=None, ax=None, norm=None): # plt.cm.plasma):",
"lim xlim = ax.get_xlim() ylim = ax.get_ylim() fig, ax = separate_cluster(d, clusters, cluster,",
"(g > 200) & (b < 255) & (b > 200) # #",
"std for z-scores #e[e < -3] = -3 #e[e > 3] = 3",
"over the top of the background # # sid = 0 # #",
"worth x1 = silhouette_samples( tsne, clusters.iloc[:, 0].tolist(), metric='euclidean') x2 = silhouette_samples( tsne_umi_log2, clusters.iloc[:,",
"# # if colors is None: # colors = libcluster.colors() # # for",
"ids=ids, gene_names=gene_names) print(gene_ids) for i in range(0, len(gene_ids)): gene_id = gene_ids[i][1] gene =",
"c1 = color.copy() # c1[-1] = 0.5 # # #print(c1) # # ax.scatter(x[i],",
"1] # # libplot.scatter(x, y, c=colors[sid], ax=ax) # # sid += 1 #",
"0] # y = tsne.iloc[idx1, 1] # # if isinstance(colors, dict): # color",
"median size Parameters ---------- data : Pandas dataframe Matrix of umi counts \"\"\"",
"(a > 0) d = im_data[np.where(black_areas)] d[:, 0:3] = [64, 64, 64] im_data[np.where(black_areas)]",
"np.linspace(y.min(), y.max(), ny) x = x[idx] y = y[idx] #centroid = [x.sum() /",
"min_max_scale(d, min=0, max=1, axis=1): #m = d.min(axis=1) #std = (d - m) /",
"points[hull.vertices[[0, -1]], 1]) #points = np.array([[x, y] for x, y in zip(x1, y1)])",
"libplot.ALPHA, show_axes=True, legend=True, sort=True, cluster_order=None, fig=None, ax=None): \"\"\" Create a tsne plot without",
"linewidth=EDGE_WIDTH, dim1=0, dim2=1, w=8, alpha=ALPHA, # libplot.ALPHA, show_axes=True, legend=True, sort=True, outline=True): cluster_order =",
"plt.close(fig) # Open image # im = imagelib.open(tmp) # im_no_bg = imagelib.remove_background(im) #",
"paste outline onto clusters # im2.paste(im_smooth, (0, 0), im_smooth) # # # overlay",
"= Image.fromarray(im_data) # # im_no_gray, im_smooth = smooth_edges(im1, im1) # # # Edge",
"# #print('Label {}'.format(l)) # idx2 = np.where(clusters['Cluster'] != c)[0] # # # Plot",
"to make the plot \"\"\" if type(genes) is pd.core.frame.DataFrame: genes = genes['Genes'].values ids,",
"dsets = {} print(f.list_nodes('/')) for node in f.walk_nodes('/' + genome, 'Array'): dsets[node.name] =",
"f.create_carray(group, 'genes', obj=gbm.gene_ids) f.create_carray(group, 'gene_names', obj=gbm.gene_names) f.create_carray(group, 'barcodes', obj=gbm.barcodes) f.create_carray(group, 'data', obj=gbm.matrix.data) f.create_carray(group,",
"gene_ids = get_gene_ids(data, genes, ids=ids, gene_names=gene_names) print(gene_ids) for i in range(0, len(gene_ids)): gene_id",
"isinstance(max, int): print('z max', max) sd[np.where(sd > max)] = max return pd.DataFrame(sd, index=d.index,",
"cols def get_gene_names(data): if ';' in data.index[0]: ids, genes = data.index.str.split(';').str else: genes",
"# return fig # # # def create_tsne_cluster_sample_grid(tsne, clusters, samples, name, colors=None, size=SUBPLOT_SIZE,",
"MinMaxScaler from sklearn.metrics import silhouette_samples from sklearn.neighbors import kneighbors_graph from scipy.interpolate import griddata",
"mode='distance', metric='euclidean').toarray() G = nx.from_numpy_matrix(A) pos = nx.spring_layout(G) fig, ax = libplot.newfig(w=8, h=8)",
"# data['{}-{}'.format(t, d2)][idx] idx = np.where(clusters['Cluster'] == cid)[0] nx = 500 ny =",
"d = umi_norm(data) print(type(d)) return umi_log2(d) def scale(d, clip=None, min=None, max=None, axis=1): if",
"left (the clusters) imageWithEdges = im1.filter(ImageFilter.FIND_EDGES) im_data = np.array(imageWithEdges.convert('RGBA')) #r = data[:, :,",
"linewidth=EDGE_WIDTH, dim1=0, dim2=1, w=8, h=8, alpha=ALPHA, # libplot.ALPHA, show_axes=True, legend=True, sort=True, cluster_order=None, fig=None,",
"print(out) # overlay edges on top of original image to highlight cluster #im_base.paste(im2,",
"else: return (d + 1).apply(np.log2) def umi_tpm_log2(data): d = umi_tpm(data) return umi_log2(d) def",
"A new Matplotlib figure used to make the plot \"\"\" if cluster_order is",
"= im_data[np.where(black_areas)] # #d[:, 0:3] = [64, 64, 64] # #im_data[np.where(black_areas)] = d",
"w=w, h=h, ax=ax, show_axes=show_axes, colorbar=colorbar, norm=norm, linewidth=linewidth, edgecolors=edgecolors) if out is not None:",
"else: # color = 'black' # # libplot.scatter(x, y, c=color, ax=ax) # #",
"is a supplied argument, return this, otherwise create a new axis and attach",
"#set_tsne_ax_lim(tsne, ax) # # return fig # # # def create_tsne_cluster_sample_grid(tsne, clusters, samples,",
"fig : matplotlib figure If fig is a supplied argument, return the supplied",
"is np.ndarray: l = x.shape[0] elif type(x) is pd.core.frame.DataFrame: l = x.shape[0] else:",
"cluster, len(idx1)), color=color) # # # libplot.invisible_axes(ax) pc += 1 return fig def",
"of markers. show_axes : bool, optional, default true Whether to show axes on",
"list(sorted(set(clusters['Cluster']))) for i in range(0, len(ids)): l = ids[i] #print('Label {}'.format(l)) indices =",
"tsne tsne data. Columns should be labeled 'TSNE-1', 'TSNE-2' etc # clusters :",
"= np.where(ids == g)[0] if idx.size > 0: # if id exists, pick",
"method='tsne', fig=None, ax=None, sdmax=0.5): \"\"\" Plot multiple genes on a grid. Parameters ----------",
"def pca_base_plots(pca, clusters, n=10, marker='o', s=MARKER_SIZE): rows = libplot.grid_size(n) w = 4 *",
"f.walk_nodes('/matrix', 'Array'): # dsets[node.name] = node.read() print(dsets) matrix = sp_sparse.csc_matrix( (dsets['data'], dsets['indices'], dsets['indptr']),",
"= libplot.new_base_fig(w=w, h=h) for i in range(0, len(gene_ids)): # gene id gene_id =",
"= libplot.new_base_fig(w=w, h=h) if colors is None: colors = libcluster.get_colors() # Where to",
"'Array'): # dsets[node.name] = node.read() print(dsets) matrix = sp_sparse.csc_matrix( (dsets['data'], dsets['indices'], dsets['indptr']), shape=dsets['shape'])",
"if legend_params['show']: libcluster.format_legend(ax, cols=legend_params['cols'], markerscale=legend_params['markerscale']) libplot.invisible_axes(ax) tmp = 'tmp{}.png'.format(i) libplot.savefig(fig, tmp) plt.close(fig) #",
"import MinMaxScaler from sklearn.metrics import silhouette_samples from sklearn.neighbors import kneighbors_graph from scipy.interpolate import",
"y, c=[background], ax=ax, edgecolors='none', # bgedgecolor, linewidth=linewidth, s=s) # Plot cluster over the",
"# fig, ax = expr_plot(tsne, # exp, # t='TSNE', # d1=d1, # d2=d2,",
"linewidth=linewidth, s=s) #fig, ax = libplot.new_fig() #expr_plot(tsne, exp, ax=ax) #libplot.add_colorbar(fig, cmap) exp_bin =",
"ids, gene_names = get_gene_names(data) if isinstance(g, list): g = np.array(g) if isinstance(g, np.ndarray):",
"min_max_scale(avg) create_expr_plot(tsne, avg, cmap=cmap, w=w, h=h, colorbar=colorbar, norm=norm, alpha=alpha, fig=fig, ax=ax) x =",
"return pd.DataFrame(RobustScaler().fit_transform(d), index=d.index, columns=d.columns) else: return pd.DataFrame(RobustScaler().fit_transform(d.T).T, index=d.index, columns=d.columns) def umi_norm_log2_scale(data, clip=None): d",
"is not None: libplot.savefig(fig, out) return fig, ax def create_cluster_plot(d, clusters, name, dim1=0,",
"pd.core.frame.DataFrame: l = x.shape[0] else: return None cols = int(np.ceil(np.sqrt(l))) w = size",
"+ 1 n = cluster_order.size if cols == -1: cols = int(np.ceil(np.sqrt(n))) rows",
"2018 @author: antony \"\"\" import matplotlib # matplotlib.use('agg') import matplotlib.pyplot as plt import",
"return fig, ax def pca_expr_plot(data, expr, name, dim=[1, 2], cmap=None, marker='o', s=MARKER_SIZE, alpha=EXP_ALPHA,",
"should be normalized Returns ------- fig : matplotlib figure If fig is a",
"ax. h: int, optional height of new ax. Returns ------- fig : Matplotlib",
"samples, 'b_sample', dir='b') genes_expr(d_b, tsne_b, genes, prefix='b_BGY', cmap=BLUE_GREEN_YELLOW_CMAP, w=w, h=h, dir='b/GeneExp', format=format) fig,",
"ax=ax, node_size=200, node_color=node_color, vmax=(c.shape[0] - 1), cmap=libcluster.colormap()) nx.draw_networkx(G, with_labels=True, labels=labels, ax=ax, node_size=800, node_color=node_color,",
"# for i in range(0, len(cids)): # c = cids[i] # # #print('Label",
"'#ffd42a', '#ffdd55']) BGY_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list( 'bgy', ['#003366', '#004d99', '#40bf80', '#ffe066', '#ffd633']) GRAY_PURPLE_YELLOW_CMAP =",
"exp[idx_bin] tsne_bin = tsne.iloc[idx_bin, :] expr_plot(tsne_bin, exp_bin, cmap=cmap, s=s, colorbar=colorbar, norm=norm, alpha=alpha, linewidth=linewidth,",
"samples: # id = '-{}'.format(sid + 1) # idx1 = np.where((clusters['Cluster'] == c)",
"= base_expr_plot(data, exp, t='PC', dim=dim, cmap=cmap, marker=marker, s=s, fig=fig, alpha=alpha, ax=ax, norm=norm) return",
"plots w: int, optional width of new ax. h: int, optional height of",
"plotted (usually 2) fig : matplotlib figure, optional Supply a figure object on",
"# Find the interesting clusters labels, graph, Q = phenograph.cluster(pca, k=20) if min(labels)",
"Set the t-SNE x,y limits to look pretty. \"\"\" d1 = tsne.iloc[:, 0]",
"the t-SNE x,y limits to look pretty. \"\"\" d1 = tsne.iloc[:, 0] d2",
"show axes on plot legend : bool, optional, default true Whether to show",
"= (a > 0) #(r < 255) | (g < 255) | (b",
"None # [0.3, 0.3, 0.3] #'#4d4d4d' EDGE_WIDTH = 0 # 0.25 ALPHA =",
"max=1, axis=1): if axis == 0: return pd.DataFrame(RobustScaler().fit_transform(d), index=d.index, columns=d.columns) else: return pd.DataFrame(RobustScaler().fit_transform(d.T).T,",
"return fig, ax # def expr_plot(tsne, # exp, # d1=1, # d2=2, #",
"libplot.new_fig() #expr_plot(tsne, exp, ax=ax) #libplot.add_colorbar(fig, cmap) fig, ax = expr_plot(tsne, exp, cmap=cmap, dim=dim,",
"is not supported by this function.' % version) feature_ids = [x.decode('ascii', 'ignore') for",
"sd[np.where(sd > max)] = max return pd.DataFrame(sd, index=d.index, columns=d.columns) def min_max_scale(d, min=0, max=1,",
"numpy as np import scipy.sparse as sp_sparse import tables import pandas as pd",
"return ids.values, genes.values def get_gene_ids(data, genes, ids=None, gene_names=None): \"\"\" For a given gene",
"axis == 0: return pd.DataFrame(RobustScaler().fit_transform(d), index=d.index, columns=d.columns) else: return pd.DataFrame(RobustScaler().fit_transform(d.T).T, index=d.index, columns=d.columns) def",
"# # return fig # # # def create_tsne_cluster_sample_grid(tsne, clusters, samples, name, colors=None,",
"cluster, color=color, add_titles=add_titles, ax=ax) # idx1 = np.where(clusters['Cluster'] == cluster)[0] # idx2 =",
"into its own plot file. \"\"\" ids = list(sorted(set(clusters['Cluster']))) indices = np.array(list(range(0, len(ids))))",
"ids is None: ids, gene_names = get_gene_names(data) if isinstance(g, list): g = np.array(g)",
"as pd from sklearn.manifold import TSNE import sklearn.preprocessing from sklearn.preprocessing import StandardScaler from",
"libtsne import seaborn as sns from libsparse.libsparse import SparseDataFrame from lib10x.sample import *",
"sd = d.std() m = d.mean() print(m, sd) z = (d - m)",
"fig=None, ax=None, norm=None): # plt.cm.plasma): out = 'pca_expr_{}_t{}_vs_t{}.pdf'.format(name, 1, 2) fig, ax =",
"p1, p2 in zip(x, y)]) hull = ConvexHull(points) #x1 = x[idx] #y1 =",
"h, rows, cols = expr_grid_size(gene_ids, size=size) fig = libplot.new_base_fig(w=w, h=h) for i in",
"c=colors[sid], ax=ax) # # sid += 1 # # ax.set_title('C{} ({:,})'.format(c, len(idx1)), color=colors[i])",
"of gene names Returns ------- list list of tuples of (index, gene_id, gene_name)",
"= [] for g in genes: indexes = np.where(ids == g)[0] if indexes.size",
"'Cluster': clusters.iloc[:, 0].tolist( ), 'Label': np.repeat('tsne-ah', len(x2))}) libplot.boxplot(df2, 'Cluster', 'Silhouette Score', colors=libcluster.colors(), ax=ax)",
"create_cluster_plot(pca, labels, name, pc1=( i + 1), pc2=(j + 1), marker=marker, s=s) def",
"255) & (g > 200) & (b < 255) & (b > 200)",
"T-SNE/2D space reduced representation of data. Parameters ---------- data : Pandas dataframe features",
"4 * rows fig = libplot.new_base_fig(w=w, h=w) si = 1 for i in",
"exist, try the gene names idx = np.where(gene_names == g)[0] if idx.size >",
"ax=None): \"\"\" Create a tsne plot without the formatting Parameters ---------- d :",
"gene) exp = get_gene_data(data, gene_id, ids=ids, gene_names=gene_names) #fig, ax = libplot.new_fig() #expr_plot(tsne, exp,",
"G = nx.from_numpy_matrix(A) pos = nx.spring_layout(G) fig, ax = libplot.newfig(w=8, h=8) # list(range(0,",
"x tsne tsne data. Columns should be labeled 'TSNE-1', 'TSNE-2' etc clusters :",
"= '{}/{}_expr_{}_{}.{}'.format(dir, method, gene, gene_id, format) else: out = '{}/{}_expr_{}.{}'.format(dir, method, gene, format)",
"# im_data[np.where(grey_areas)] = d # # # #edges1 = feature.canny(rgb2gray(im_data)) # # #print(edges1.shape)",
"list(f['matrix']['barcodes'][:]) matrix = sp_sparse.csc_matrix( (f['matrix']['data'], f['matrix']['indices'], f['matrix']['indptr']), shape=f['matrix']['shape']) return GeneBCMatrix(feature_ids, feature_names, decode(barcodes), matrix)",
"silhouette_samples from sklearn.neighbors import kneighbors_graph from scipy.interpolate import griddata import h5py from scipy.interpolate",
"create_cluster_samples(tsne_b, c_b, samples, 'b_sample', dir='b') genes_expr(d_b, tsne_b, genes, prefix='b_BGY', cmap=BLUE_GREEN_YELLOW_CMAP, w=w, h=h, dir='b/GeneExp',",
"show_axes=False, fig=None, ax=None, norm=None, colorbar=False): # plt.cm.plasma): \"\"\" Creates a base expression plot",
"= -1.5 avg[avg > 1.5] = 1.5 avg = (avg - avg.min()) /",
"'#339933', '#e6e600', '#ffff33']) # BGY_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list('bgy', ['#003366', '#40bf80', '#ffff33']) BGY_ORIG_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list(",
"= matplotlib.colors.LinearSegmentedColormap.from_list( 'bgy', ['#003366', '#004d99', '#40bf80', '#ffe066', '#ffd633']) GRAY_PURPLE_YELLOW_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list( 'grey_purple_yellow', ['#e6e6e6',",
"to render the figure \"\"\" if ax is None: fig, ax = libplot.new_fig(size,",
"libplot.new_fig() libplot.scatter(tsne['TSNE-1'], tsne['TSNE-2'], c=c, marker=marker, label=label, s=s, ax=ax) return fig, ax def tsne_plot(tsne,",
"0)[0] ids2 = np.where(a2[i, :] > 0)[0] ids3 = np.intersect1d(ids1, ids2) o =",
"({})'.format(gene_ids[i][2], gene_ids[i][1])) libplot.add_colorbar(fig, cmap) return fig def genes_expr(data, tsne, genes, prefix='', dim=[1, 2],",
"# # im2.paste(im_smooth, (0, 0), im_smooth) # # im_base.paste(im2, (0, 0), im2) if",
"print('index', i, cluster, colors) if isinstance(colors, dict): color = colors.get(cluster, 'black') elif isinstance(colors,",
"now...') # zscore #e = (e - e.mean()) / e.std() #print(e.min(), e.max()) #",
"None and exp.min() < 0: #norm = matplotlib.colors.Normalize(vmin=-3, vmax=3, clip=True) if norm is",
"create_merge_cluster_info(d_a, c_a, 'a', sample_names=samples, dir='a') create_cluster_samples(tsne_a, c_a, samples, 'a_sample', dir='a') genes_expr(d_a, tsne_a, genes,",
"0] # im_data[np.where(grey_areas)] = d # # im2 = Image.fromarray(im_data) # # #",
"Matplotlib figure # A new Matplotlib figure used to make the plot #",
"else: idx = np.where(ids == g)[0] if idx.size > 0: # if id",
"im_data[:, :, 3] # # # Non transparent areas are edges # #black_areas",
"#libtsne.tsne_legend(ax, labels, colors) #libcluster.format_simple_axes(ax, title=\"t-SNE\") #libcluster.format_legend(ax, cols=6, markerscale=2) if out is not None:",
"label=label, s=s, ax=ax) return fig, ax def tsne_plot(tsne, marker='o', s=libplot.MARKER_SIZE, c='red', label=None, fig=None,",
"on what is left (the clusters) # im_edges = im2.filter(ImageFilter.FIND_EDGES) # # im_smooth",
"name, cache=True): file = libtsne.get_cluster_file(name) if not os.path.isfile(file) or not cache: print('{} was",
"'TSNE-2' etc clusters : DataFrame Clusters in colors : list, color Colors of",
"< x2))[0] x = x[idx] y = y[idx] points = np.array([[p1, p2] for",
"ax is None: fig, ax = libplot.new_fig(w, h) is_first = True base_expr_plot(data, exp,",
"d_b = libcluster.remove_empty_rows(d_b) if isinstance(d_a, SparseDataFrame): d_b = umi_norm_log2(d_b) else: d_b = umi_norm_log2_scale(d_b)",
"def sum(gbm, axis=0): return gbm.matrix.sum(axis=axis) def tpm(gbm): m = gbm.matrix s = 1",
"y[i], # c='#ffffff00', # s=s, # marker=marker, # norm=norm, # edgecolors=[color], # linewidth=linewidth)",
"# int(np.round(np.median(reads_per_bc))) median_reads_per_bc = np.median(reads_per_bc) scaling_factors = median_reads_per_bc / reads_per_bc scaled = data.multiply(scaling_factors)",
"= sklearn.preprocessing.scale(d, axis=axis) #sd = sd.T if isinstance(clip, float) or isinstance(clip, int): max",
"ax=ax, node_size=50, node_color=node_color, vmax=(clusters['Cluster'].max() - 1), cmap=libcluster.colormap()) # # libplot.savefig(fig, 'network_{}.pdf'.format(name)) def plot_centroids(tsne,",
"color) color = color # + '7f' libplot.scatter(x, y, c=color, ax=ax, edgecolors='none', #",
"= points[hull.vertices, 0] yp = points[hull.vertices, 1] xp = np.append(xp, xp[0]) yp =",
"h=h) libplot.savefig(fig, 'a/a_tsne_clusters_med.pdf') # b mkdir('b') b_barcodes = pd.read_csv('../b_barcodes.tsv', header=0, sep='\\t') idx =",
"'#ffd42a']) # BGY_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list('bgy', ['#002255', '#003380', '#2ca05a', '#ffd42a', '#ffdd55']) # BGY_CMAP =",
"supported by this function.' % version) feature_ids = [x.decode('ascii', 'ignore') for x in",
"legend_params.update(legend) else: pass if legend_params['show']: libcluster.format_legend(ax, cols=legend_params['cols'], markerscale=legend_params['markerscale']) libplot.invisible_axes(ax) tmp = 'tmp{}.png'.format(i) libplot.savefig(fig,",
"pos = nx.spring_layout(G) fig, ax = libplot.newfig(w=8, h=8) # list(range(0, c.shape[0])) node_color =",
"idx = idx[0] else: return None if isinstance(data, SparseDataFrame): return data[idx, :].to_array() else:",
"# libplot.ALPHA, show_axes=True, legend=True, sort=True, outline=True): cluster_order = list(sorted(set(clusters['Cluster']))) im_base = imagelib.new(w *",
"import collections import numpy as np import scipy.sparse as sp_sparse import tables import",
"in range(0, len(cluster_order)): print('index', i, cluster_order[i]) cluster = cluster_order[i] if isinstance(colors, dict): color",
"0.98, 0.98) #(0.8, 0.8, 0.8) #(0.85, 0.85, 0.85 BACKGROUND_SAMPLE_COLOR = [0.75, 0.75, 0.75]",
"fig=fig, ax=ax) libplot.savefig(fig, out, pad=2) plt.close(fig) def set_tsne_ax_lim(tsne, ax): \"\"\" Set the t-SNE",
"new Matplotlib figure used to make the plot ax : Matplotlib axes Axes",
"+ 1, n): ax = libplot.new_ax(fig, subplot=(rows, rows, si)) pca_plot_base(pca, clusters, pc1=(i +",
"labels, colors) #libcluster.format_simple_axes(ax, title=\"t-SNE\") #libcluster.format_legend(ax, cols=6, markerscale=2) if out is not None: libplot.savefig(fig,",
"for x in items]) def get_matrix_from_h5(filename, genome): with tables.open_file(filename, 'r') as f: try:",
"h=w) si = 1 for i in range(0, n): for j in range(i",
"d_a = umi_norm_log2(d_a) else: d_a = umi_norm_log2_scale(d_a) pca_a = libtsne.load_pca(d_a, 'a', cache=cache) #",
"Score': x1, 'Cluster': clusters.iloc[:, 0].tolist( ), 'Label': np.repeat('tsne-10x', len(x1))}) libplot.boxplot(df, 'Cluster', 'Silhouette Score',",
"import matplotlib.pyplot as plt import collections import numpy as np import scipy.sparse as",
"df = pd.DataFrame({'Silhouette Score': x1, 'Cluster': clusters.iloc[:, 0].tolist( ), 'Label': np.repeat('tsne-10x', len(x1))}) libplot.boxplot(df,",
"s=MARKER_SIZE, w=8, h=8, legend=True, fig=None, ax=None): fig, ax = pca_plot_base(pca, clusters, pc1=pc1, pc2=pc2,",
"im_data[np.where(black_areas)] # #d[:, 0:3] = [64, 64, 64] # #im_data[np.where(black_areas)] = d #",
"new Matplotlib figure used to make the plot \"\"\" if cluster_order is None:",
"including any parents and avoid raising exception to work more like mkdir -p",
"matplotlib.cm.OrRd(range(4, 256))) BU_PU_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list( 'bu_pu', matplotlib.cm.BuPu(range(4, 256))) # BGY_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list('bgy', ['#0066ff',",
"# y[i], # c='#ffffff00', # s=s, # marker=marker, # norm=norm, # edgecolors=[color], #",
"df2.iloc[:, pc1 - 1] y = df2.iloc[:, pc2 - 1] if i in",
"a cluster separately to highlight where the samples are Parameters ---------- tsne :",
"format='png'): out = '{}/pca_{}_pc{}_vs_pc{}.{}'.format(dir, name, pc1, pc2, format) fig, ax = pca_plot(pca, clusters,",
"x1 = silhouette_samples( tsne, clusters.iloc[:, 0].tolist(), metric='euclidean') x2 = silhouette_samples( tsne_umi_log2, clusters.iloc[:, 0].tolist(),",
"and returned. ax : matplotlib axis If ax is a supplied argument, return",
"2], cmap=plt.cm.plasma, marker='o', edgecolors=EDGE_COLOR, linewidth=1, s=MARKER_SIZE, alpha=1, w=libplot.DEFAULT_WIDTH, h=libplot.DEFAULT_HEIGHT, fig=None, ax=None, norm=None): #",
"gene_names[index])) else: # if id does not exist, try the gene names indexes",
"y = y[idx] points = np.array([[p1, p2] for p1, p2 in zip(x, y)])",
"'MKI67', 'MYC', 'PCNA', 'PRDM1'] genes = pd.read_csv('../../../../expression_genes.txt', header=0) mkdir('a') a_barcodes = pd.read_csv('../a_barcodes.tsv', header=0,",
"'a/a_tsne_clusters_med.pdf') # b mkdir('b') b_barcodes = pd.read_csv('../b_barcodes.tsv', header=0, sep='\\t') idx = np.where(counts.columns.isin(b_barcodes['Barcode'].values))[0] d_b",
"y = tsne.iloc[idx2, 1] # # libplot.scatter(x, y, c=BACKGROUND_SAMPLE_COLOR, ax=ax) # # #",
"int): max = abs(clip) min = -max if isinstance(min, float) or isinstance(min, int):",
"/ y.size] centroid = [(x * avg[idx]).sum() / avg[idx].sum(), (y * avg[idx]).sum() /",
"def base_pca_expr_plot(data, exp, dim=[1, 2], cmap=None, marker='o', s=MARKER_SIZE, alpha=EXP_ALPHA, fig=None, ax=None, norm=None): #",
"to look nice. \"\"\" if type(x) is int: l = x elif type(x)",
"Returns ------- fig : matplotlib figure If fig is a supplied argument, return",
"n x 1 table of n cells with a Cluster column giving each",
"if colors is None: colors = libcluster.get_colors() for i in indices: print('index', i)",
"axis=1): if isinstance(d, SparseDataFrame): print('UMI norm log2 scale sparse') sd = StandardScaler(with_mean=False).fit_transform(d.T.matrix) return",
"pd.DataFrame({'Silhouette Score': x1, 'Cluster': clusters.iloc[:, 0].tolist( ), 'Label': np.repeat('tsne-10x', len(x1))}) libplot.boxplot(df, 'Cluster', 'Silhouette",
"dir='.'): # \"\"\" # Plot separate clusters colored by sample # \"\"\" #",
"y lim xlim = ax.get_xlim() ylim = ax.get_ylim() fig, ax = separate_cluster(d, clusters,",
"libtsne.read_clusters(file) labels = data # .tolist() return cluster_map, labels def umi_tpm(data): # each",
"fig = tsne_cluster_sample_grid(tsne, clusters, samples, colors, size) # # libplot.savefig(fig, '{}/tsne_{}_sample_clusters.png'.format(dir, name)) #",
"im1 = Image.open('tmp.png') # Edge detect on what is left (the clusters) imageWithEdges",
"figure used to make the plot # \"\"\" # # # cids =",
"Open image # im = imagelib.open(tmp) # im_no_bg = imagelib.remove_background(im) # im_smooth =",
"= libplot.new_fig(w, w) x = tsne_other.iloc[:, 0] y = tsne_other.iloc[:, 1] libplot.scatter(x, y,",
"create_cluster_samples(tsne_a, c_a, samples, 'a_sample', dir='a') genes_expr(d_a, tsne_a, genes, prefix='a_BGY', cmap=BLUE_GREEN_YELLOW_CMAP, w=w, h=h, dir='a/GeneExp',",
"colors: color = colors[i] # l] else: color = 'black' ax.scatter(x, y, color=color,",
"b = im_data[:, :, 2] # # print(tmp, r.shape) # # grey_areas =",
"data. Columns should be labeled 'TSNE-1', 'TSNE-2' etc genes : array List of",
"edges1) # # im2 = Image.fromarray(im_data) # # im_no_gray, im_smooth = smooth_edges(im1, im1)",
"file.\") def subsample_matrix(gbm, barcode_indices): return GeneBCMatrix(gbm.gene_ids, gbm.gene_names, gbm.barcodes[barcode_indices], gbm.matrix[:, barcode_indices]) def get_expression(gbm, gene_name,",
"im_smooth) # # # overlay edges on top of original image to highlight",
"Axes used to render the figure \"\"\" if ax is None: fig, ax",
"prefix='b_BGY', cmap=BLUE_GREEN_YELLOW_CMAP, w=w, h=h, dir='b/GeneExp', format=format) fig, ax = cluster_plot(tsne_b, c_b, legend=False, w=w,",
"'{}/{}_expr_{}.png'.format(dir, method, gene) print(out) # overlay edges on top of original image to",
"used to make the plot \"\"\" if cluster_order is None: ids = np.array(list(sorted(set(clusters['Cluster']))))",
"fig, ax = libplot.newfig(w=5, h=5) ax.scatter(c[:, 0], c[:, 1], c=None) libplot.format_axes(ax) libplot.savefig(fig, '{}_centroids.pdf'.format(name))",
"im_data[np.where(grey_areas)] = d # # im2 = Image.fromarray(im_data) # # # Edge detect",
"= np.where(gene_names == g)[0] if idx.size > 0: idx = idx[0] else: return",
"highlight where the samples are Parameters ---------- tsne : Pandas dataframe Cells x",
"# def load_clusters(pca, headers, name, cache=True): file = libtsne.get_cluster_file(name) if not os.path.isfile(file) or",
"fig, ax def expr_grid_size(x, size=SUBPLOT_SIZE): \"\"\" Auto size grid to look nice. \"\"\"",
"legend=True, fig=None, ax=None): fig, ax = pca_plot_base(pca, clusters, pc1=pc1, pc2=pc2, marker=marker, labels=labels, s=s,",
"(r == b) & (g == b) # # #d = im_data[np.where(black_areas)] #",
"# cmap=cmap, # marker=marker, # s=s, # alpha=alpha, # fig=fig, # ax=ax, #",
"j in range(i + 1, pca.shape[1]): create_cluster_plot(pca, labels, name, pc1=( i + 1),",
"tsne.iloc[idx2, 0] # y = tsne.iloc[idx2, 1] # # libplot.scatter(x, y, c=BACKGROUND_SAMPLE_COLOR, ax=ax)",
"(b > 200) # # d = im_data[np.where(grey_areas)] # d[:, :] = [255,",
"so that extreme values always appear on top idx = np.argsort(exp) #np.argsort(abs(exp)) #",
"h: int, optional height of new ax. Returns ------- fig : Matplotlib figure",
"- m) / (d.max(axis=1) - m) #scaled = std * (max - min)",
"ret[i, 1] = centroid[1] return ret def knn_method_overlaps(tsne1, tsne2, clusters, name, k=5): c1",
"= plt.cm.plasma ids, gene_names = get_gene_names(data) exp = get_gene_data(data, genes, ids=ids, gene_names=gene_names) avg",
"clusters, markers=markers, colors=colors, dim1=dim1, dim2=dim2, s=s, w=w, h=h, cluster_order=cluster_order, legend=legend, sort=sort, show_axes=show_axes, fig=fig,",
"= phenograph.cluster(pca, k=20) if min(labels) == -1: new_label = 100 labels[np.where(labels == -1)]",
"list of tuples of (index, gene_id, gene_name) \"\"\" if ids is None: ids,",
"#expr_plot(tsne, exp, ax=ax) #libplot.add_colorbar(fig, cmap) fig, ax = expr_plot(tsne, exp, cmap=cmap, dim=dim, w=w,",
"BLUE_YELLOW_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list( 'blue_yellow', ['#162d50', '#ffdd55']) BLUE_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list( 'blue', ['#162d50', '#afc6e9']) BLUE_GREEN_YELLOW_CMAP",
"axes Axes used to render the figure \"\"\" if ax is None: fig,",
"labels=labels, marker=marker, legend=legend, s=s, w=w, h=h, fig=fig, ax=ax) libplot.savefig(fig, out, pad=2) plt.close(fig) def",
"max)).fit_transform(d.T).T, index=d.index, columns=d.columns) def rscale(d, min=0, max=1, axis=1): if axis == 0: return",
"'gene_names', 'barcodes', 'matrix']) def decode(items): return np.array([x.decode('utf-8') for x in items]) def get_matrix_from_h5(filename,",
"norm=norm, edgecolors='none', # edgecolors, linewidth=linewidth) # for i in range(0, x.size): # en",
"genes is None: genes = gbm.gene_names gene_indices = np.where(genes == gene_name)[0] if len(gene_indices)",
"== g)[0] if idx.size > 0: idx = idx[0] else: return None if",
"200) & (g < 255) & (g > 200) & (b < 255)",
"range(0, bins): bi = bin + 1 idx_bin = np.where(binnumber == bi)[0] idx_other",
"in range(0, c.shape[0]): labels[i] = i + 1 #nx.draw_networkx(G, pos=pos, with_labels=False, ax=ax, node_size=200,",
"#e[e > 3] = 3 ax.scatter(x, y, c=e, s=s, marker=marker, alpha=alpha, cmap=cmap, norm=norm,",
"graph, Q = phenograph.cluster(pca, k=20) if min(labels) == -1: new_label = 100 labels[np.where(labels",
"im = imagelib.open(tmp) im_no_bg = imagelib.remove_background(im) im_edges = imagelib.edges(im_no_bg) im_smooth = imagelib.smooth(im_edges) im_outline",
"cols=-1, size=SUBPLOT_SIZE, add_titles=True, cluster_order=None, method='tsne', dir='.', out=None): fig = cluster_grid(tsne, clusters, colors=colors, cols=cols,",
"ret def get_gene_data(data, g, ids=None, gene_names=None): if ids is None: ids, gene_names =",
"# Parameters # ---------- # data : pandas.DataFrame # t-sne 2D data #",
"data[:, :, 2] a = im_data[:, :, 3] # (r < 255) |",
"import TSNE import sklearn.preprocessing from sklearn.preprocessing import StandardScaler from sklearn.preprocessing import RobustScaler from",
"# s=s, # marker=marker, # edgecolors='none', #edgecolors, # linewidth=linewidth) # # # #",
"None: fig, ax = libplot.new_fig(w=w, h=h) # if norm is None and exp.min()",
"sklearn.preprocessing import MinMaxScaler from sklearn.metrics import silhouette_samples from sklearn.neighbors import kneighbors_graph from scipy.interpolate",
"mkdir('b') b_barcodes = pd.read_csv('../b_barcodes.tsv', header=0, sep='\\t') idx = np.where(counts.columns.isin(b_barcodes['Barcode'].values))[0] d_b = counts.iloc[:, idx]",
"# # # cids = list(sorted(set(clusters['Cluster']))) # # rows = int(np.ceil(np.sqrt(len(cids)))) # #",
"= np.where(clusters['Cluster'] != cluster)[0] # # # Plot background points # # #",
"= m.multiply(s) tpm = mn.multiply(1000000) return GeneBCMatrix(gbm.gene_ids, gbm.gene_names, gbm.barcodes, tpm) def create_cluster_plots(pca, labels,",
"= ConvexHull(points) #x1 = x[idx] #y1 = y[idx] # avg1 = np.zeros(x.size) #avg[idx]",
"expr, dim=dim, cmap=cmap, marker=marker, s=s, alpha=alpha, fig=fig, ax=ax, norm=norm) libplot.savefig(fig, out) plt.close(fig) return",
"rows = int(l / cols) + 2 if l % cols == 0:",
"metric='euclidean').toarray() a2 = kneighbors_graph(c2, k, mode='distance', metric='euclidean').toarray() overlaps = [] for i in",
"p2] for p1, p2 in zip(x, y)]) hull = ConvexHull(points) #x1 = x[idx]",
"color purposes #i = np.where(ids == cluster)[0][0] print('index', i, cluster, colors) if isinstance(colors,",
"this, otherwise create a new axis and attach to figure before returning. \"\"\"",
"fig, ax def base_cluster_plot_outline(out, d, clusters, s=libplot.MARKER_SIZE, colors=None, edgecolors=EDGE_COLOR, linewidth=EDGE_WIDTH, dim1=0, dim2=1, w=8,",
"'Matrix HDF5 file format version (%d) is an older version that is not",
"# break imagelib.save(im_base, out) def cluster_plot(tsne, clusters, dim1=0, dim2=1, markers='o', s=libplot.MARKER_SIZE, colors=None, w=8,",
"Cells x tsne tsne data. Columns should be labeled 'TSNE-1', 'TSNE-2' etc clusters",
"i in indices: print('index', i) cluster = ids[i] if isinstance(colors, dict): color =",
"= im_data[np.where(black_areas)] d[:, 0:3] = [64, 64, 64] im_data[np.where(black_areas)] = d im2 =",
"mkdir(path): \"\"\" Make dirs including any parents and avoid raising exception to work",
"pca_a = libtsne.load_pca(d_a, 'a', cache=cache) # pca.iloc[idx,:] tsne_a = libtsne.load_pca_tsne(pca_a, 'a', cache=cache) c_a",
"nx.draw_networkx(G, with_labels=True, labels=labels, ax=ax, node_size=800, node_color=node_color, font_color='white', font_family='Arial') libplot.format_axes(ax) libplot.savefig(fig, '{}_centroid_network.pdf'.format(name)) def centroids(tsne,",
"to make the plot \"\"\" if cluster_order is None: ids = np.array(list(sorted(set(clusters['Cluster'])))) cluster_order",
"= matplotlib.colors.LinearSegmentedColormap.from_list( 'bgy', ['#162d50', '#214478', '#217844', '#ffcc00', '#ffdd55']) # BGY_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list('bgy', ['#002255',",
"int, optional Plot width h : int, optional Plot height alpha : float",
"from scipy.spatial import ConvexHull from PIL import Image, ImageFilter from scipy.stats import binned_statistic",
"optional Plot height alpha : float (0, 1), optional Tranparency of markers. show_axes",
"1.5] = 1.5 avg = (avg - avg.min()) / (avg.max() - avg.min()) #",
"c)[0], :] centroid = (x.sum(axis=0) / x.shape[0]).tolist() ret[i, 0] = centroid[0] ret[i, 1]",
"if id does not exist, try the gene names indexes = np.where(gene_names ==",
"Image.fromarray(im_data) im2.save('edges.png', 'png') # overlay edges on top of original image to highlight",
"ids=ids, gene_names=gene_names) w, h, rows, cols = expr_grid_size(gene_ids, size=size) fig = libplot.new_base_fig(w=w, h=h)",
"each cluster separately to highlight where the samples are Parameters ---------- tsne :",
"& (r == b) & (g == b) black_areas = (a > 0)",
"if isinstance(colors, dict): color = colors[cluster] elif isinstance(colors, list): if cluster < len(colors):",
"# libplot.invisible_axes(ax) ax.set_title('{} ({})'.format(gene_ids[i][2], gene_ids[i][1])) libplot.add_colorbar(fig, cmap) return fig def genes_expr(data, tsne, genes,",
"avg.mean()) / avg.std() avg[avg < -1.5] = -1.5 avg[avg > 1.5] = 1.5",
"s=MARKER_SIZE): for i in range(0, pca.shape[1]): for j in range(i + 1, pca.shape[1]):",
"g) & (r == b) & (g == b) # # #d =",
"# Open image # im = imagelib.open(tmp) # im_no_bg = imagelib.remove_background(im) # im_smooth",
"clusters, name): # measure cluster worth x1 = silhouette_samples( tsne, clusters.iloc[:, 0].tolist(), metric='euclidean')",
"# data : pandas.DataFrame # t-sne 2D data # \"\"\" # # fig,",
"axis=1): if axis == 0: return pd.DataFrame(RobustScaler().fit_transform(d), index=d.index, columns=d.columns) else: return pd.DataFrame(RobustScaler().fit_transform(d.T).T, index=d.index,",
"n = cluster_order.size if cols == -1: cols = int(np.ceil(np.sqrt(n))) rows = int(np.ceil(n",
"* from scipy.spatial import ConvexHull from PIL import Image, ImageFilter from scipy.stats import",
"Score': x2, 'Cluster': clusters.iloc[:, 0].tolist( ), 'Label': np.repeat('tsne-ah', len(x2))}) libplot.boxplot(df2, 'Cluster', 'Silhouette Score',",
"= [d1[d1 < 0].quantile(1 - TNSE_AX_Q), d1[d1 >= 0].quantile(TNSE_AX_Q)] ylim = [d2[d2 <",
"#b = data[:, :, 2] # #a = im_data[:, :, 3] # #",
"def cluster_plot(tsne, clusters, dim1=0, dim2=1, markers='o', s=libplot.MARKER_SIZE, colors=None, w=8, h=8, legend=True, show_axes=False, sort=True,",
"return fig # # # def create_tsne_cluster_sample_grid(tsne, clusters, samples, name, colors=None, size=SUBPLOT_SIZE, dir='.'):",
"avoid raising exception to work more like mkdir -p Parameters ---------- path :",
"# paste outline onto clusters # im2.paste(im_smooth, (0, 0), im_smooth) # # #",
"/ cols)) w = size * cols h = size * rows fig",
"marker='o', s=libplot.MARKER_SIZE, c='red', label=None, fig=None, ax=None): fig, ax = base_tsne_plot(tsne, marker=marker, c=c, s=s,",
"alpha=1.0, colorbar=False, method='tsne', fig=None, ax=None, sdmax=0.5): \"\"\" Plot multiple genes on a grid.",
"knn_method_overlaps(tsne1, tsne2, clusters, name, k=5): c1 = centroids(tsne1, clusters) c2 = centroids(tsne2, clusters)",
"Matplotlib figure used to make the plot \"\"\" if type(genes) is pd.core.frame.DataFrame: genes",
"l] else: color = 'black' ax.scatter(x, y, color=color, edgecolor=color, s=s, marker=marker, alpha=libplot.ALPHA, label=label)",
"will add a row for a color bar rows += 1 h =",
"edges desired im1.paste(im2, (0, 0), im2) im1.save(out, 'png') def genes_expr_outline(data, tsne, genes, prefix='',",
"1, n): ax = libplot.new_ax(fig, subplot=(rows, rows, si)) pca_plot_base(pca, clusters, pc1=(i + 1),",
"# each column is a cell reads_per_bc = data.sum(axis=0) scaling_factors = 1000000 /",
"linewidth=linewidth) # for i in range(0, x.size): # en = norm(e[i]) # color",
"gene: out = '{}/{}_expr_{}_{}.png'.format(dir, method, gene, gene_id) else: out = '{}/{}_expr_{}.png'.format(dir, method, gene)",
"Matplotlib axes Axes used to render the figure \"\"\" if ax is None:",
"header=0, index_col=0) def silhouette(tsne, tsne_umi_log2, clusters, name): # measure cluster worth x1 =",
"fig=None, ax=None): fig, ax = base_tsne_plot(tsne, marker=marker, c=c, s=s, label=label, fig=fig, ax=ax) #libtsne.tsne_legend(ax,",
"imagelib.paste(im_no_bg, im_smooth, inplace=True) # imagelib.save(im_no_bg, 'smooth.png') # imagelib.paste(im_base, im_no_bg, inplace=True) im = imagelib.open(tmp)",
"# ax.scatter(x[i], # y[i], # c='#ffffff00', # s=s, # marker=marker, # norm=norm, #",
"look up index for color purposes #i = np.where(ids == cluster)[0][0] print('index', i,",
"h=h, dir='b/GeneExp', format=format) fig, ax = cluster_plot(tsne_b, c_b, legend=False, w=w, h=h) libplot.savefig(fig, 'b/b_tsne_clusters_med.pdf')",
"if legend: libcluster.format_legend(ax, cols=6, markerscale=2) return fig, ax def create_pca_plot(pca, clusters, name, pc1=1,",
"bgedgecolor='#808080', show_background=True, add_titles=True, size=4, alpha=ALPHA, s=MARKER_SIZE, edgecolors='white', linewidth=EDGE_WIDTH, fig=None, ax=None): \"\"\" Plot a",
"cols == 0: # Assume we will add a row for a color",
"CLUSTER_101_COLOR else: color = 'black' fig, ax = separate_cluster(tsne, clusters, cluster, color=color, add_titles=add_titles,",
"['#0066ff', '#37c871', '#ffd42a']) # BGY_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list('bgy', ['#003380', '#5fd38d', '#ffd42a']) EXP_NORM = matplotlib.colors.Normalize(-1,",
"colored by sample # \"\"\" # fig = tsne_cluster_sample_grid(tsne, clusters, samples, colors, size)",
"row for a color bar rows += 1 h = size * rows",
"m) #scaled = std * (max - min) + min # return scaled",
"make the plot # \"\"\" # # # cids = list(sorted(set(clusters['Cluster']))) # #",
"and b \"\"\" cache = True counts = libcluster.remove_empty_rows(counts) # ['AICDA', 'CD83', 'CXCR4',",
"is_first = True base_expr_plot(data, exp, dim=dim, s=s, marker=marker, edgecolors=edgecolors, linewidth=linewidth, alpha=alpha, cmap=cmap, norm=norm,",
"ax=None, cluster_order=None, format='png', dir='.', out=None): if out is None: # libtsne.get_tsne_plot_name(name)) out =",
"# libplot.invisible_axes(ax) # # #set_tsne_ax_lim(tsne, ax) # # return fig # # #",
":, 1] # #b = data[:, :, 2] # #a = im_data[:, :,",
"cell a cluster label. s : int, optional Marker size w : int,",
"p2 in zip(x, y)]) hull = ConvexHull(points) #x1 = x[idx] #y1 = y[idx]",
"exp, dim=[1, 2], cmap=None, marker='o', s=MARKER_SIZE, alpha=EXP_ALPHA, fig=None, ax=None, norm=None): # plt.cm.plasma): fig,",
"f: if u'version' in f.attrs: if f.attrs['version'] > 2: raise ValueError( 'Matrix HDF5",
"does not exist, try the gene names indexes = np.where(gene_names == g)[0] for",
"Edge detect on what is left (the clusters) imageWithEdges = im1.filter(ImageFilter.FIND_EDGES) im_data =",
"background points # # ax = libplot.new_ax(fig, subplot=(rows, rows, i + 1)) #",
"to work more like mkdir -p Parameters ---------- path : str directory to",
"pc = 1 for c in cluster_order: i = c - 1 cluster",
"plt.close(fig) def set_tsne_ax_lim(tsne, ax): \"\"\" Set the t-SNE x,y limits to look pretty.",
"= expr_plot(tsne, exp, cmap=cmap, dim=dim, w=w, h=h, s=s, colorbar=colorbar, norm=norm, alpha=alpha, linewidth=linewidth, edgecolors=edgecolors)",
"in range(0, pca.shape[0]): print(pca.shape, pca.iloc[i, pc1 - 1], pca.iloc[i, pc2 - 1]) ax.text(pca.iloc[i,",
"# libplot.invisible_axes(ax) return fig, ax def separate_clusters(tsne, clusters, name, colors=None, size=4, add_titles=True, type='tsne',",
"libplot.new_fig(w=w, h=h) # if norm is None and exp.min() < 0: #norm =",
"= libtsne.load_phenograph_clusters(pca_a, 'a', cache=cache) create_pca_plot(pca_a, c_a, 'a', dir='a') create_cluster_plot(tsne_a, c_a, 'a', dir='a') create_cluster_grid(tsne_a,",
"# # #im3 = Image.fromarray(im_data) # #im2.save('edges.png', 'png') # # im_smooth = im_edges.filter(ImageFilter.SMOOTH)",
"avg = exp.mean(axis=0) avg = (avg - avg.mean()) / avg.std() avg[avg < -1.5]",
"i in range(0, d.shape[0])], dtype=object) c = 1 for s in sample_names: id",
"= ConvexHull(points) #ax.plot(points[hull.vertices,0], points[hull.vertices,1]) #zi = griddata((x, y), avg1, (xi, yi)) #ax.contour(xi, yi,",
"colorbar=True, method='tsne', bins=10, background=BACKGROUND_SAMPLE_COLOR): \"\"\" Plot multiple genes on a grid. Parameters ----------",
"a grid. Parameters ---------- data : Pandas dataframe Genes x samples expression matrix",
"len(colors): # colors[cid - 1] #colors[i] #np.where(clusters['Cluster'] == cluster)[0]] color = colors[i] else:",
"import phenograph import libplot import libcluster import libtsne import seaborn as sns from",
"ax is None: fig, ax = libplot.new_fig(w=w, h=h) ids = list(sorted(set(clusters['Cluster']))) for i",
"= list(sorted(set(clusters['Cluster']))) for i in range(0, len(ids)): l = ids[i] #print('Label {}'.format(l)) indices",
"cmap=BGY_CMAP, norm=None, w=6, s=30, alpha=1, linewidth=EDGE_WIDTH, edgecolors='none', colorbar=True, method='tsne', bins=10, background=BACKGROUND_SAMPLE_COLOR): \"\"\" Plot",
"umi_norm_log2(data) return scale(d, clip=clip) def read_clusters(file): print('Reading clusters from {}...'.format(file)) return pd.read_csv(file, sep='\\t',",
"= dir[:-1] if not os.path.exists(dir): mkdir(dir) if index is None: index = data.index",
"for j in range(i + 1, n): ax = libplot.new_ax(fig, subplot=(rows, rows, si))",
"scipy.interpolate import interp1d from scipy.spatial import distance import networkx as nx import os",
"0), im2) im1.save(out, 'png') def genes_expr_outline(data, tsne, genes, prefix='', index=None, dir='GeneExp', cmap=BGY_CMAP, norm=None,",
"# # xt = np.linspace(x.min(), x.max(), 100, endpoint=True) # yt = np.linspace(y.min(), y.max(),",
"0:500] # # G=nx.from_numpy_matrix(A) # pos=nx.spring_layout(G) #, k=2) # # #node_color = (c_phen['Cluster'][0:A.shape[0]]",
"-1)] = new_label labels += 1 libtsne.write_clusters(headers, labels, name) cluster_map, data = libtsne.read_clusters(file)",
"+ min # return scaled if axis == 0: return pd.DataFrame(MinMaxScaler(feature_range=(min, max)).fit_transform(d), index=d.index,",
"'#0055d4', '#00aa44', '#ffe066']) OR_RED_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list( 'or_red', matplotlib.cm.OrRd(range(4, 256))) BU_PU_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list( 'bu_pu',",
"300) for i in range(0, len(cluster_order)): print('index', i, cluster_order[i]) cluster = cluster_order[i] if",
"norm=None, # w=libplot.DEFAULT_WIDTH, # h=libplot.DEFAULT_HEIGHT, # colorbar=True): #plt.cm.plasma): # \"\"\" # Creates a",
"def get_barcode_counts(gbm): ret = [] for i in range(len(gbm.barcodes)): ret.append(np.sum(gbm.matrix[:, i].toarray())) return ret",
"isinstance(data, SparseDataFrame): return data[idx, :].to_array() else: return data.iloc[idx, :].values def gene_expr_grid(data, tsne, genes,",
"# # im_base.paste(im2, (0, 0), im2) if gene_id != gene: out = '{}/{}_expr_{}_{}.png'.format(dir,",
"array List of gene names \"\"\" exp = get_gene_data(data, gene) return expr_plot(tsne, exp,",
"(d > x1) & (d < x2))[0] x = x[idx] y = y[idx]",
"marker='o', s=libplot.MARKER_SIZE, c='red', label=None, fig=None, ax=None): \"\"\" Create a tsne plot without the",
"libplot.savefig(fig, tmp) plt.close(fig) # Open image # im = imagelib.open(tmp) # im_no_bg =",
"indexes.size > 0: for index in indexes: ret.append((index, ids[index], gene_names[index])) else: # if",
"edgecolors='none', colorbar=True, method='tsne', format='png'): \"\"\" Plot multiple genes on a grid. Parameters ----------",
"data : Pandas dataframe Matrix of umi counts \"\"\" # each column is",
"m.multiply(s) tpm = mn.multiply(1000000) return GeneBCMatrix(gbm.gene_ids, gbm.gene_names, gbm.barcodes, tpm) def create_cluster_plots(pca, labels, name,",
"sample_names=samples, dir='b') create_cluster_samples(tsne_b, c_b, samples, 'b_sample', dir='b') genes_expr(d_b, tsne_b, genes, prefix='b_BGY', cmap=BLUE_GREEN_YELLOW_CMAP, w=w,",
"should be labeled 'TSNE-1', 'TSNE-2' etc clusters : DataFrame Clusters in colors :",
"(a > 0) #(r < 255) | (g < 255) | (b <",
"clusters labels, graph, Q = phenograph.cluster(pca, k=20) if min(labels) == -1: new_label =",
"x in f['matrix']['features']['id']] feature_names = [x.decode('ascii', 'ignore') for x in f['matrix']['features']['name']] barcodes =",
"# im_data = np.array(im1.convert('RGBA')) # # r = im_data[:, :, 0] # g",
"from PIL import Image, ImageFilter from scipy.stats import binned_statistic import imagelib TNSE_AX_Q =",
"'#2ca05a', '#ffd42a', '#ffdd55']) BGY_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list( 'bgy', ['#003366', '#004d99', '#40bf80', '#ffe066', '#ffd633']) GRAY_PURPLE_YELLOW_CMAP",
"nx.from_numpy_matrix(A) pos = nx.spring_layout(G) fig, ax = libplot.newfig(w=8, h=8) # list(range(0, c.shape[0])) node_color",
"matplotlib.colors.LinearSegmentedColormap.from_list( 'grey_blue_green_yellow', ['#e6e6e6', '#0055d4', '#00aa44', '#ffe066']) OR_RED_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list( 'or_red', matplotlib.cm.OrRd(range(4, 256))) BU_PU_CMAP",
"for z-scores #e[e < -3] = -3 #e[e > 3] = 3 ax.scatter(x,",
"# xt = np.linspace(x.min(), x.max(), 100, endpoint=True) # yt = np.linspace(y.min(), y.max(), 100,",
"w=w, # h=h, # colorbar=colorbar) # # set_tsne_ax_lim(tsne, ax) # # libplot.invisible_axes(ax) #",
"= [255, 255, 255, 0] # im_data[np.where(grey_areas)] = d # # im2 =",
"np.where(clusters['Cluster'] == cluster)[0] idx2 = np.where(clusters['Cluster'] != cluster)[0] # Plot background points if",
"< 255) & (r > 200) & (g < 255) & (g >",
"gene_id = gene_ids[i][1] gene = gene_ids[i][2] print(gene_id, gene) exp = get_gene_data(data, gene_id, ids=ids,",
"gene_names : Index, optional Index of gene names Returns ------- list list of",
"np.where(counts.columns.isin(b_barcodes['Barcode'].values))[0] d_b = counts.iloc[:, idx] d_b = libcluster.remove_empty_rows(d_b) if isinstance(d_a, SparseDataFrame): d_b =",
"GeneBCMatrix to a pandas dataframe (dense) Parameters ---------- gbm : a GeneBCMatrix Returns",
"gene_names[index])) return ret def get_gene_data(data, g, ids=None, gene_names=None): if ids is None: ids,",
"matplotlib.use('agg') import matplotlib.pyplot as plt import collections import numpy as np import scipy.sparse",
"w=w, h=h, ax=ax) # if colorbar or is_first: if colorbar: libplot.add_colorbar(fig, cmap, norm=norm)",
"y, c=[background], ax=ax, edgecolors='none', # bgedgecolor, linewidth=linewidth, s=s) #fig, ax = libplot.new_fig() #expr_plot(tsne,",
"alpha=alpha, fig=fig, ax=ax) x = tsne.iloc[:, 0].values # data['{}-{}'.format(t, d1)][idx] y = tsne.iloc[:,",
"etc # clusters : DataFrame # Clusters in # # Returns # -------",
"'{}_centroids.pdf'.format(name)) def centroid_network(tsne, clusters, name): c = centroids(tsne, clusters) A = kneighbors_graph(c, 5,",
"in range(0, len(gene_ids)): # gene id gene_id = gene_ids[i][1] gene = gene_ids[i][2] print(gene,",
"n = len(indices) label = 'C{} ({:,})'.format(l, n) df2 = pca.iloc[indices, ] x",
"# # Plot background points # # # # x = tsne.iloc[idx2, 0]",
"# \"\"\" # fig = tsne_cluster_sample_grid(tsne, clusters, samples, colors, size) # # libplot.savefig(fig,",
"top of original image to highlight cluster # im_base.paste(im2, (0, 0), im2) #",
"2)) for i in range(0, len(cids)): c = cids[i] x = tsne.iloc[np.where(clusters['Cluster'] ==",
"3 std for z-scores #e[e < -3] = -3 #e[e > 3] =",
"np.where(a2[i, :] > 0)[0] ids3 = np.intersect1d(ids1, ids2) o = len(ids3) / 5",
"clusters, pc1=(i + 1), pc2=(j + 1), marker=marker, s=s, ax=ax) si += 1",
"idx2 = np.where(clusters['Cluster'] != cluster)[0] # Plot background points if show_background: x =",
"---------- data : Pandas dataframe features x dimensions, e.g. rows are cells and",
"nx) yi = np.linspace(y.min(), y.max(), ny) x = x[idx] y = y[idx] #centroid",
"- TNSE_AX_Q), d1[d1 >= 0].quantile(TNSE_AX_Q)] ylim = [d2[d2 < 0].quantile(1 - TNSE_AX_Q), d2[d2",
"original image to highlight cluster #im_base.paste(im2, (0, 0), im2) imagelib.save(im_base, out) def avg_expr(data,",
"transcripts. Parameters ---------- data : DataFrame data table containing and index genes :",
"x.max(), nx) yi = np.linspace(y.min(), y.max(), ny) x = x[idx] y = y[idx]",
"if labels: l = pca.index.values for i in range(0, pca.shape[0]): print(pca.shape, pca.iloc[i, pc1",
"# Returns # ------- # fig : Matplotlib figure # A new Matplotlib",
"if u'version' in f.attrs: if f.attrs['version'] > 2: raise ValueError( 'Matrix HDF5 file",
"None: norm = libplot.NORM_3 # Sort by expression level so that extreme values",
"plot_order: list, optional List of cluster ids in the order they should be",
"clusters, name, pc1=1, pc2=2, marker='o', labels=False, legend=True, s=MARKER_SIZE, w=8, h=8, fig=None, ax=None, dir='.',",
"fig, ax = separate_cluster(tsne, clusters, cluster, color=color, add_titles=add_titles, size=size) out = '{}_sep_clust_{}_c{}.{}'.format(type, name,",
"Pandas dataframe Matrix of umi counts \"\"\" # each column is a cell",
"> 0) & (r == g) & (r == b) & (g ==",
"x = tsne.iloc[:, 0].values # data['{}-{}'.format(t, d1)][idx] y = tsne.iloc[:, 1].values # data['{}-{}'.format(t,",
"log2 sparse') return d.log2(add=1) else: return (d + 1).apply(np.log2) def umi_tpm_log2(data): d =",
"else: # libplot.invisible_axes(ax) ax.set_title('{} ({})'.format(gene_ids[i][2], gene_ids[i][1])) libplot.add_colorbar(fig, cmap) return fig def genes_expr(data, tsne,",
"return ret def get_gene_data(data, g, ids=None, gene_names=None): if ids is None: ids, gene_names",
"dimension being plotted (usually 2) fig : matplotlib figure, optional Supply a figure",
"if isinstance(legend, bool): legend_params['show'] = legend elif isinstance(legend, dict): legend_params.update(legend) else: pass if",
"to add titles to plots plot_order: list, optional List of cluster ids in",
"im2.paste(im_smooth, (0, 0), im_smooth) # # # overlay edges on top of original",
"w = 4 * rows fig = libplot.new_base_fig(w=w, h=w) si = 1 for",
"CLUSTER_101_COLOR = (0.3, 0.3, 0.3) np.random.seed(0) GeneBCMatrix = collections.namedtuple( 'GeneBCMatrix', ['gene_ids', 'gene_names', 'barcodes',",
"dim2=1, w=8, alpha=ALPHA, # libplot.ALPHA, show_axes=True, legend=True, sort=True, outline=True): cluster_order = list(sorted(set(clusters['Cluster']))) im_base",
"pc1=1, pc2=2, marker='o', labels=False, s=MARKER_SIZE, w=8, h=8, legend=True, fig=None, ax=None): fig, ax =",
"+ 2 if l % cols == 0: # Assume we will add",
"giving each cell a cluster label. s : int, optional Marker size w",
"prefix, cluster, len(idx1)), color=color) ax.axis('off') # libplot.invisible_axes(ax) return fig, ax def separate_clusters(tsne, clusters,",
"labels, name, pc1=( i + 1), pc2=(j + 1), marker=marker, s=s) def pca_base_plots(pca,",
"ax is a supplied argument, return this, otherwise create a new axis and",
"cmap=cmap, norm=norm, edgecolors='none', # edgecolors, linewidth=linewidth) # for i in range(0, x.size): #",
"d = umi_norm_log2(data) return scale(d, clip=clip) def read_clusters(file): print('Reading clusters from {}...'.format(file)) return",
"# # nx.draw_networkx(G, pos=pos, with_labels=False, ax=ax, node_size=50, node_color=node_color, vmax=(clusters['Cluster'].max() - 1), cmap=libcluster.colormap()) #",
"legend_params['show'] = legend elif isinstance(legend, dict): legend_params.update(legend) else: pass if legend_params['show']: libcluster.format_legend(ax, cols=legend_params['cols'],",
"# for i in range(0, x.size): # en = norm(e[i]) # color =",
"cluster_order=None, fig=None, ax=None): \"\"\" Create a tsne plot without the formatting Parameters ----------",
"1] libplot.scatter(x, y, c=[background], ax=ax, edgecolors='none', # bgedgecolor, linewidth=linewidth, s=s) #fig, ax =",
"adds a color bar. \"\"\" is_first = False if ax is None: fig,",
"\"\"\" Set the t-SNE x,y limits to look pretty. \"\"\" d1 = tsne.iloc[:,",
"pd.read_csv('../a_barcodes.tsv', header=0, sep='\\t') idx = np.where(counts.columns.isin(a_barcodes['Barcode'].values))[0] d_a = counts.iloc[:, idx] d_a = libcluster.remove_empty_rows(d_a)",
"np.where(np.isin(ids, g))[0] if idx.size < 1: # if id does not exist, try",
"Plot cluster over the top of the background # # sid = 0",
"ax = cluster_plot(tsne_b, c_b, legend=False, w=w, h=h) libplot.savefig(fig, 'b/b_tsne_clusters_med.pdf') def sample_clusters(d, sample_names): \"\"\"",
"z-score #e = (e - e.mean()) / e.std() # limit to 3 std",
"is None: ids, gene_names = get_gene_names(data) ret = [] for g in genes:",
"(usually 2) fig : matplotlib figure, optional Supply a figure object on which",
"#x1 = x[idx] #y1 = y[idx] # avg1 = np.zeros(x.size) #avg[idx] #avg1[idx] =",
"colors[cluster] # elif isinstance(colors, list): # color = colors[i] # else: # color",
"+ '7f' libplot.scatter(x, y, c=color, ax=ax, edgecolors='none', # edgecolors, linewidth=linewidth, s=s) if add_titles:",
"1, pca.shape[1]): create_cluster_plot(pca, labels, name, pc1=( i + 1), pc2=(j + 1), marker=marker,",
"= legend elif isinstance(legend, dict): legend_params.update(legend) else: pass if legend_params['show']: libcluster.format_legend(ax, cols=legend_params['cols'], markerscale=legend_params['markerscale'])",
"expression values for each data point so it must have the same number",
"# # #edges1 = feature.canny(rgb2gray(im_data)) # # #print(edges1.shape) # # #skimage.io.imsave('tmp_canny_{}.png'.format(bin), edges1) #",
"idx = np.where(counts.columns.isin(b_barcodes['Barcode'].values))[0] d_b = counts.iloc[:, idx] d_b = libcluster.remove_empty_rows(d_b) if isinstance(d_a, SparseDataFrame):",
"# Edge detect on what is left (the clusters) # im_edges = im2.filter(ImageFilter.FIND_EDGES)",
"# # for i in range(0, len(cids)): # c = cids[i] # #",
"y = tsne_other.iloc[:, 1] libplot.scatter(x, y, c=[background], ax=ax, edgecolors='none', # bgedgecolor, linewidth=linewidth, s=s)",
"#print(c1) # # ax.scatter(x[i], # y[i], # c=[c1], # s=s, # marker=marker, #",
"markerscale=2) return fig, ax def create_pca_plot(pca, clusters, name, pc1=1, pc2=2, marker='o', labels=False, legend=True,",
"np.array(list(sorted(set(clusters['Cluster'])))) cluster_order = np.array(list(range(0, len(ids)))) + 1 n = cluster_order.size if cols ==",
"# fig, ax = libplot.newfig(w=10, h=10) # # nx.draw_networkx(G, pos=pos, with_labels=False, ax=ax, node_size=50,",
"names idx = np.where(np.isin(gene_names, g))[0] if idx.size < 1: return None else: idx",
"except: raise Exception(\"Failed to write H5 file.\") def subsample_matrix(gbm, barcode_indices): return GeneBCMatrix(gbm.gene_ids, gbm.gene_names,",
"= data[:, :, 2] # #a = im_data[:, :, 3] # # #",
"#print('sep', cluster, color) color = color # + '7f' libplot.scatter(x, y, c=color, ax=ax,",
"gbm.barcodes[barcode_indices], gbm.matrix[:, barcode_indices]) def get_expression(gbm, gene_name, genes=None): if genes is None: genes =",
"formatting Parameters ---------- d : Pandas dataframe t-sne, umap data clusters : Pandas",
": Index, optional Index of gene names Returns ------- list list of tuples",
"= genes['Genes'].values if norm is None: norm = matplotlib.colors.Normalize(vmin=-3, vmax=3, clip=True) #cmap =",
"= smooth_edges(im1, im1) # # # Edge detect on what is left (the",
"optional, default true Whether to show axes on plot legend : bool, optional,",
"dim=[1, 2], cmap=None, marker='o', s=MARKER_SIZE, alpha=EXP_ALPHA, fig=None, ax=None, norm=None): # plt.cm.plasma): out =",
"# y[i], # c=[c1], # s=s, # marker=marker, # edgecolors='none', #edgecolors, # linewidth=linewidth)",
"ax=None): colors = libcluster.get_colors() if ax is None: fig, ax = libplot.new_fig(w=w, h=h)",
"clusters.iloc[:, 0].tolist(), metric='euclidean') fig, ax = libplot.newfig(w=9, h=7, subplot=211) df = pd.DataFrame({'Silhouette Score':",
"linewidth=1, s=MARKER_SIZE, alpha=1, w=libplot.DEFAULT_WIDTH, h=libplot.DEFAULT_HEIGHT, fig=None, ax=None, norm=None): # plt.cm.plasma): \"\"\" Base function",
"pd.DataFrame(MinMaxScaler(feature_range=(min, max)).fit_transform(d.T).T, index=d.index, columns=d.columns) def rscale(d, min=0, max=1, axis=1): if axis == 0:",
"fig=fig, ax=ax, cmap=cmap, out=out) def separate_cluster(tsne, clusters, cluster, color='black', background=BACKGROUND_SAMPLE_COLOR, bgedgecolor='#808080', show_background=True, add_titles=True,",
"np.array(im_edges.convert('RGBA')) # # #r = data[:, :, 0] # #g = data[:, :,",
"size=size) fig = libplot.new_base_fig(w=w, h=h) for i in range(0, len(gene_ids)): # gene id",
"def pca_plot_base(pca, clusters, pc1=1, pc2=2, marker='o', labels=False, s=MARKER_SIZE, w=8, h=8, fig=None, ax=None): colors",
"'CXCR4', 'MKI67', 'MYC', 'PCNA', 'PRDM1'] genes = pd.read_csv('../../../../expression_genes.txt', header=0) mkdir('a') a_barcodes = pd.read_csv('../a_barcodes.tsv',",
"plots plot_order: list, optional List of cluster ids in the order they should",
"A[0:500, 0:500] # # G=nx.from_numpy_matrix(A) # pos=nx.spring_layout(G) #, k=2) # # #node_color =",
"exp, # t='TSNE', # d1=d1, # d2=d2, # x1=x1, # x2=x2, # cmap=cmap,",
"= tsne.iloc[:, 0].values # data['{}-{}'.format(t, d1)][idx] y = tsne.iloc[:, 1].values # data['{}-{}'.format(t, d2)][idx]",
"format='png', dir='.', out=None): if out is None: # libtsne.get_tsne_plot_name(name)) out = '{}/{}_{}.{}'.format(dir, method,",
"List of gene names \"\"\" exp = get_gene_data(data, gene) return expr_plot(tsne, exp, fig=fig,",
"= get_gene_ids(data, genes, ids=ids, gene_names=gene_names) w, h, rows, cols = expr_grid_size(gene_ids, size=size) fig",
"#np.where(clusters['Cluster'] == cluster)[0]] color = colors[i] else: color = 'black' else: color =",
"x2=x2, # cmap=cmap, # marker=marker, # s=s, # alpha=alpha, # fig=fig, # ax=ax,",
"legend: libcluster.format_legend(ax, cols=6, markerscale=2) return fig, ax def create_pca_plot(pca, clusters, name, pc1=1, pc2=2,",
"else: return pd.DataFrame(RobustScaler().fit_transform(d.T).T, index=d.index, columns=d.columns) def umi_norm_log2_scale(data, clip=None): d = umi_norm_log2(data) return scale(d,",
"= int(np.ceil(np.sqrt(l))) w = size * cols rows = int(l / cols) +",
"(0.3, 0.3, 0.3) np.random.seed(0) GeneBCMatrix = collections.namedtuple( 'GeneBCMatrix', ['gene_ids', 'gene_names', 'barcodes', 'matrix']) def",
"y = tsne.iloc[idx1, 1] # # libplot.scatter(x, y, c=colors[sid], ax=ax) # # sid",
"cluster worth x1 = silhouette_samples( tsne, clusters.iloc[:, 0].tolist(), metric='euclidean') x2 = silhouette_samples( tsne_umi_log2,",
"expr_plot(tsne, exp, fig=fig, ax=ax, cmap=cmap, out=out) def separate_cluster(tsne, clusters, cluster, color='black', background=BACKGROUND_SAMPLE_COLOR, bgedgecolor='#808080',",
"= libcluster.get_colors() for i in indices: print('index', i) cluster = ids[i] if isinstance(colors,",
"sum(gbm, axis=0): return gbm.matrix.sum(axis=axis) def tpm(gbm): m = gbm.matrix s = 1 /",
"None if isinstance(data, SparseDataFrame): return data[idx, :].to_array() else: return data.iloc[idx, :].values def gene_expr_grid(data,",
"# else: # libplot.invisible_axes(ax) ax.set_title('{} ({})'.format(gene_ids[i][2], gene_ids[i][1])) libplot.add_colorbar(fig, cmap) return fig def genes_expr(data,",
"SparseDataFrame): return data[idx, :].to_array() else: return data.iloc[idx, :].values def gene_expr_grid(data, tsne, genes, cmap=None,",
"# rows = int(np.ceil(np.sqrt(len(cids)))) # # w = size * rows # #",
"i in range(0, n): for j in range(i + 1, n): ax =",
"expr, name, dim=[1, 2], cmap=None, marker='o', s=MARKER_SIZE, alpha=EXP_ALPHA, fig=None, ax=None, norm=None): # plt.cm.plasma):",
"w = size * cols rows = int(l / cols) + 2 if",
"linewidth=linewidth, add_titles=False) # get x y lim xlim = ax.get_xlim() ylim = ax.get_ylim()",
"flt = tables.Filters(complevel=1) with tables.open_file(filename, 'w', filters=flt) as f: try: group = f.create_group(f.root,",
"+= 1 # # ax.set_title('C{} ({:,})'.format(c, len(idx1)), color=colors[i]) # libplot.invisible_axes(ax) # # #set_tsne_ax_lim(tsne,",
"marker='o', labels=False, s=MARKER_SIZE, w=8, h=8, fig=None, ax=None): colors = libcluster.get_colors() if ax is",
"'#37c871', '#ffd42a']) # BGY_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list('bgy', ['#003380', '#5fd38d', '#ffd42a']) EXP_NORM = matplotlib.colors.Normalize(-1, 3,",
"bool, optional, default true Whether to show legend. \"\"\" if ax is None:",
"np.where(ids == g)[0] if indexes.size > 0: for index in indexes: ret.append((index, ids[index],",
"im2 = Image.fromarray(im_data) # # im_no_gray, im_smooth = smooth_edges(im1, im1) # # #",
"'#ffff00') # BGY_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list('bgy', ['#001a33', '#003366', '#339933', '#ffff66', '#ffff00']) # BGY_CMAP =",
"in zip(x, y)]) hull = ConvexHull(points) #x1 = x[idx] #y1 = y[idx] #",
"64, 64] # #im_data[np.where(black_areas)] = d # # #im3 = Image.fromarray(im_data) # #im2.save('edges.png',",
"fig, ax = base_tsne_plot(tsne, marker=marker, c=c, s=s, label=label, fig=fig, ax=ax) #libtsne.tsne_legend(ax, labels, colors)",
"plt.cm.plasma): \"\"\" Creates a base expression plot and adds a color bar. \"\"\"",
"desired im1.paste(im2, (0, 0), im2) im1.save(out, 'png') def genes_expr_outline(data, tsne, genes, prefix='', index=None,",
"return GeneBCMatrix(decode(dsets['genes']), decode(dsets['gene_names']), decode(dsets['barcodes']), matrix) except tables.NoSuchNodeError: raise Exception(\"Genome %s does not exist",
"format) else: out = '{}/{}_expr_{}.{}'.format(dir, method, gene, format) libplot.savefig(fig, 'tmp.png', pad=0) libplot.savefig(fig, out,",
"of gene ids ids : Index, optional Index of gene ids gene_names :",
"= np.where(gene_names == g)[0] for index in indexes: ret.append((index, ids[index], gene_names[index])) return ret",
"avg_expr(data, tsne, genes, cid, clusters, prefix='', index=None, dir='GeneExp', cmap=OR_RED_CMAP, # BGY_CMAP, norm=None, w=libplot.DEFAULT_WIDTH,",
"c1.shape[0]): ids1 = np.where(a1[i, :] > 0)[0] ids2 = np.where(a2[i, :] > 0)[0]",
"barcode_indices]) def get_expression(gbm, gene_name, genes=None): if genes is None: genes = gbm.gene_names gene_indices",
"base_expr_plot(data, exp, dim=[1, 2], cmap=plt.cm.plasma, marker='o', edgecolors=EDGE_COLOR, linewidth=1, s=MARKER_SIZE, alpha=1, w=libplot.DEFAULT_WIDTH, h=libplot.DEFAULT_HEIGHT, fig=None,",
"en = norm(e[i]) # color = cmap(int(en * cmap.N)) # color = np.array(color)",
"appear to be z-scored. Transforming now...') # zscore #e = (e - e.mean())",
"supplied argument, return this, otherwise create a new axis and attach to figure",
"render the plot, otherwise a new one is created. ax : matplotlib ax,",
"cluster, color) color = color # + '7f' libplot.scatter(x, y, c=color, ax=ax, edgecolors='none',",
"gene ids gene_names : Index, optional Index of gene names Returns ------- list",
"libplot.invisible_axes(ax) return fig, ax # def expr_plot(tsne, # exp, # d1=1, # d2=2,",
"* 300 im_base = imagelib.new(iw, iw) for bin in range(0, bins): bi =",
"data = libtsne.read_clusters(file) labels = data # .tolist() return cluster_map, labels def umi_tpm(data):",
"get_matrix_from_h5(filename, genome): with tables.open_file(filename, 'r') as f: try: dsets = {} print(f.list_nodes('/')) for",
"= 'tmp{}.png'.format(i) libplot.savefig(fig, tmp) plt.close(fig) # Open image # im = imagelib.open(tmp) #",
"ids2) o = len(ids3) / 5 * 100 overlaps.append(o) df = pd.DataFrame( {'Cluster':",
"sklearn.metrics import silhouette_samples from sklearn.neighbors import kneighbors_graph from scipy.interpolate import griddata import h5py",
"in samples: # id = '-{}'.format(sid + 1) # idx1 = np.where((clusters['Cluster'] ==",
"libplot.savefig(fig, '{}_centroid_network.pdf'.format(name)) def centroids(tsne, clusters): cids = list(sorted(set(clusters['Cluster'].tolist()))) ret = np.zeros((len(cids), 2)) for",
"x1=None, # x2=None, # cmap=BLUE_YELLOW_CMAP, # marker='o', # s=MARKER_SIZE, # alpha=EXP_ALPHA, # out=None,",
"iw = w * 300 im_base = imagelib.new(iw, iw) for bin in range(0,",
"range(0, len(gene_ids)): # gene id gene_id = gene_ids[i][1] gene = gene_ids[i][2] print(gene, gene_id)",
"ax = expr_plot(tsne, # exp, # t='TSNE', # d1=d1, # d2=d2, # x1=x1,",
"show_axes: libplot.invisible_axes(ax) legend_params = dict(LEGEND_PARAMS) if isinstance(legend, bool): legend_params['show'] = legend elif isinstance(legend,",
"= data[:, :, 1] # #b = data[:, :, 2] # #a =",
"expression level so that extreme values always appear on top idx = np.argsort(exp)",
"EDGE_WIDTH = 0 # 0.25 ALPHA = 0.9 BLUE_YELLOW_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list( 'blue_yellow', ['#162d50',",
"& (b > 200) # # # d = im_data[np.where(grey_areas)] # d[:, :]",
"dir = dir[:-1] if not os.path.exists(dir): mkdir(dir) if index is None: index =",
"libplot.new_base_fig(w=w, h=h) if colors is None: colors = libcluster.get_colors() # Where to plot",
"# y = tsne.iloc[idx2, 1] # libplot.scatter(x, y, c=BACKGROUND_SAMPLE_COLOR, ax=ax) # # #",
"'{}_centroid_network.pdf'.format(name)) def centroids(tsne, clusters): cids = list(sorted(set(clusters['Cluster'].tolist()))) ret = np.zeros((len(cids), 2)) for i",
"name): c = centroids(tsne, clusters) fig, ax = libplot.newfig(w=5, h=5) ax.scatter(c[:, 0], c[:,",
"Plot background points if show_background: x = tsne.iloc[idx2, 0] y = tsne.iloc[idx2, 1]",
"older version that is not supported by this function.' % version) feature_ids =",
"def avg_expr(data, tsne, genes, cid, clusters, prefix='', index=None, dir='GeneExp', cmap=OR_RED_CMAP, # BGY_CMAP, norm=None,",
"imagelib.remove_background(im) # im_smooth = imagelib.smooth_edges(im_no_bg) # imagelib.paste(im_no_bg, im_smooth, inplace=True) # imagelib.save(im_no_bg, 'smooth.png') #",
"imagelib.paste(im_base, im_no_bg, inplace=True) im = imagelib.open(tmp) if outline: im_no_bg = imagelib.remove_background(im) im_edges =",
"np.where(abs(z) < sdmax)[0] # (d > x1) & (d < x2))[0] x =",
"& (b < 255) & (b > 200) # # # d =",
"fig=None, ax=None): \"\"\" Create a tsne plot without the formatting \"\"\" if ax",
"int): # prefix = 'C' # else: # prefix = '' # #",
"norm=None): # plt.cm.plasma): \"\"\" Base function for creating an expression plot for T-SNE/2D",
"1), pc2=(j + 1), marker=marker, s=s, ax=ax) si += 1 return fig def",
"marker='o', # s=MARKER_SIZE, # alpha=EXP_ALPHA, # out=None, # fig=None, # ax=None, # norm=None,",
"= feature.canny(rgb2gray(im_data)) # # #print(edges1.shape) # # #skimage.io.imsave('tmp_canny_{}.png'.format(bin), edges1) # # im2 =",
"index for color purposes #i = np.where(ids == cluster)[0][0] print('index', i, cluster, colors)",
"s=libplot.MARKER_SIZE, colors=None, edgecolors=EDGE_COLOR, linewidth=EDGE_WIDTH, dim1=0, dim2=1, w=8, h=8, alpha=ALPHA, # libplot.ALPHA, show_axes=True, legend=True,",
"Jun 6 16:51:15 2018 @author: antony \"\"\" import matplotlib # matplotlib.use('agg') import matplotlib.pyplot",
"im2) # break imagelib.save(im_base, out) def cluster_plot(tsne, clusters, dim1=0, dim2=1, markers='o', s=libplot.MARKER_SIZE, colors=None,",
"std * (max - min) + min # return scaled if axis ==",
"s=MARKER_SIZE, # alpha=EXP_ALPHA, # out=None, # fig=None, # ax=None, # norm=None, # w=libplot.DEFAULT_WIDTH,",
"add_titles=True, type='tsne', format='pdf'): \"\"\" Plot each cluster into its own plot file. \"\"\"",
"metric='euclidean').toarray() overlaps = [] for i in range(0, c1.shape[0]): ids1 = np.where(a1[i, :]",
"the plot \"\"\" if cluster_order is None: ids = np.array(list(sorted(set(clusters['Cluster'])))) cluster_order = np.array(list(range(0,",
"# # libplot.scatter(x, y, c=BACKGROUND_SAMPLE_COLOR, ax=ax) # # # Plot cluster over the",
"EDGE_COLOR = None # [0.3, 0.3, 0.3] #'#4d4d4d' EDGE_WIDTH = 0 # 0.25",
"4, 'markerscale': 2} CLUSTER_101_COLOR = (0.3, 0.3, 0.3) np.random.seed(0) GeneBCMatrix = collections.namedtuple( 'GeneBCMatrix',",
"h=h, fig=fig, ax=ax) #libtsne.tsne_legend(ax, labels, colors) libcluster.format_simple_axes(ax, title=\"PC\") if legend: libcluster.format_legend(ax, cols=6, markerscale=2)",
"points[hull.vertices, 1] xp = np.append(xp, xp[0]) yp = np.append(yp, yp[0]) ax.plot(xp, yp, 'k-')",
"k=20) if min(labels) == -1: new_label = 100 labels[np.where(labels == -1)] = new_label",
"# node_color = (clusters['Cluster'] - 1).tolist() # # fig, ax = libplot.newfig(w=10, h=10)",
"get_gene_names(data) gene_ids = get_gene_ids(data, genes, ids=ids, gene_names=gene_names) w, h, rows, cols = expr_grid_size(gene_ids,",
"(avg.max() - avg.min()) # min_max_scale(avg) create_expr_plot(tsne, avg, cmap=cmap, w=w, h=h, colorbar=colorbar, norm=norm, alpha=alpha,",
"= imagelib.edges(im) im_outline = imagelib.paste(im, im_edges) # im_no_bg im_smooth = imagelib.smooth(im_outline) imagelib.save(im_smooth, 'smooth.png')",
"im_smooth, inplace=True) else: imagelib.paste(im_base, im, inplace=True) # # find gray areas and mask",
"ret def df(gbm): \"\"\" Converts a GeneBCMatrix to a pandas dataframe (dense) Parameters",
"int): print('z min', min) sd[np.where(sd < min)] = min if isinstance(max, float) or",
"import libcluster import libtsne import seaborn as sns from libsparse.libsparse import SparseDataFrame from",
"l = ids[i] #print('Label {}'.format(l)) indices = np.where(clusters['Cluster'] == l)[0] n = len(indices)",
"file.\" % genome) except KeyError: raise Exception(\"File is missing one or more required",
"format) print(out) return cluster_plot(d, clusters, dim1=dim1, dim2=dim2, markers=markers, colors=colors, s=s, w=w, h=h, cluster_order=cluster_order,",
"ax=None, # norm=None, # w=libplot.DEFAULT_WIDTH, # h=libplot.DEFAULT_HEIGHT, # colorbar=True): #plt.cm.plasma): # \"\"\" #",
"np.where(genes == gene_name)[0] if len(gene_indices) == 0: raise Exception(\"%s was not found in",
"fig, ax def separate_clusters(tsne, clusters, name, colors=None, size=4, add_titles=True, type='tsne', format='pdf'): \"\"\" Plot",
"'#00aa44', '#ffe066']) OR_RED_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list( 'or_red', matplotlib.cm.OrRd(range(4, 256))) BU_PU_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list( 'bu_pu', matplotlib.cm.BuPu(range(4,",
"len(idx1)), color=colors[i]) # libplot.invisible_axes(ax) # # #set_tsne_ax_lim(tsne, ax) # # return fig #",
"= np.array(g) if isinstance(g, np.ndarray): idx = np.where(np.isin(ids, g))[0] if idx.size < 1:",
"cmap=cmap, w=w, h=h, colorbar=colorbar, norm=norm, alpha=alpha, fig=fig, ax=ax) x = tsne.iloc[:, 0].values #",
"/ e.std() # limit to 3 std for z-scores #e[e < -3] =",
"df = pd.DataFrame(sc, index=d.index, columns=['Cluster']) return df def create_cluster_samples(tsne_umi_log2, clusters, sample_names, name, method='tsne',",
"ids=ids, gene_names=gene_names) #fig, ax = libplot.new_fig() #expr_plot(tsne, exp, ax=ax) #libplot.add_colorbar(fig, cmap) fig, ax",
"1]) ax.text(pca.iloc[i, pc1 - 1], pca.iloc[i, pc2 - 1], pca.index[i]) return fig, ax",
"= 500 xi = np.linspace(x.min(), x.max(), nx) yi = np.linspace(y.min(), y.max(), ny) x",
"for g in genes: indexes = np.where(ids == g)[0] if indexes.size > 0:",
"# x = tsne.iloc[idx1, 0] # y = tsne.iloc[idx1, 1] # # libplot.scatter(x,",
"imagelib.smooth(im_outline) imagelib.save(im_smooth, 'smooth.png') # im_smooth imagelib.paste(im_base, im_smooth, inplace=True) else: imagelib.paste(im_base, im, inplace=True) #",
"figure before returning. \"\"\" if ax is None: fig, ax = libplot.new_fig(w=w, h=h)",
"onto clusters # im2.paste(im_smooth, (0, 0), im_smooth) # # # overlay edges on",
"# # # # mean = color.mean() # # #print(x[i], y[i], mean) #",
"gene = gene_ids[i][2] print(gene_id, gene) exp = get_gene_data(data, gene_id, ids=ids, gene_names=gene_names) #fig, ax",
"# norm=None, # w=libplot.DEFAULT_WIDTH, # h=libplot.DEFAULT_HEIGHT, # colorbar=True): #plt.cm.plasma): # \"\"\" # Creates",
"matplotlib figure If fig is a supplied argument, return the supplied figure, otherwise",
"feature_names, decode(barcodes), matrix) def save_matrix_to_h5(gbm, filename, genome): flt = tables.Filters(complevel=1) with tables.open_file(filename, 'w',",
"Plot each cluster into its own plot file. \"\"\" ids = list(sorted(set(clusters['Cluster']))) indices",
"color = 'black' else: color = 'black' fig, ax = separate_cluster(d, clusters, cluster,",
"data.sum(axis=0) # int(np.round(np.median(reads_per_bc))) median_reads_per_bc = np.median(reads_per_bc) scaling_factors = median_reads_per_bc / reads_per_bc scaled =",
"== -1: new_label = 100 labels[np.where(labels == -1)] = new_label labels += 1",
"figure object on which to render the plot, otherwise a new one is",
"def base_cluster_plot(d, clusters, markers=None, s=libplot.MARKER_SIZE, colors=None, edgecolors=EDGE_COLOR, linewidth=EDGE_WIDTH, dim1=0, dim2=1, w=8, h=8, alpha=ALPHA,",
"libtsne.load_pca_tsne(pca_b, 'b', cache=cache) c_b = libtsne.load_phenograph_clusters(pca_b, 'b', cache=cache) create_pca_plot(pca_b, c_b, 'b', dir='b') create_cluster_plot(tsne_b,",
"name, pc1, pc2, format) fig, ax = pca_plot(pca, clusters, pc1=pc1, pc2=pc2, labels=labels, marker=marker,",
"#i = cluster - 1 if i < len(colors): # colors[cid - 1]",
"ax = cluster_plot(tsne_a, c_a, legend=False, w=w, h=h) libplot.savefig(fig, 'a/a_tsne_clusters_med.pdf') # b mkdir('b') b_barcodes",
"points add_titles : bool Whether to add titles to plots w: int, optional",
"DataFrame shape(n_cells, n_genes) \"\"\" df = pd.DataFrame(gbm.matrix.todense()) df.index = gbm.gene_names df.columns = gbm.barcodes",
"Converts a GeneBCMatrix to a pandas dataframe (dense) Parameters ---------- gbm : a",
"fig, ax = expr_plot(tsne, exp, dim=dim, cmap=cmap, marker=marker, s=s, alpha=alpha, fig=fig, w=w, h=h,",
"norm=None, method='tsne', show_axes=False, colorbar=True, out=None): # plt.cm.plasma): \"\"\" Creates and saves a presentation",
"Wed Jun 6 16:51:15 2018 @author: antony \"\"\" import matplotlib # matplotlib.use('agg') import",
"int, optional width of new ax. h: int, optional height of new ax.",
"griddata import h5py from scipy.interpolate import interp1d from scipy.spatial import distance import networkx",
": int, optional Plot width h : int, optional Plot height alpha :",
"(dsets['data'], dsets['indices'], dsets['indptr']), shape=dsets['shape']) return GeneBCMatrix(decode(dsets['genes']), decode(dsets['gene_names']), decode(dsets['barcodes']), matrix) except tables.NoSuchNodeError: raise Exception(\"Genome",
"= tsne.iloc[idx1, 1] # # libplot.scatter(x, y, c=colors[sid], ax=ax) # # sid +=",
"gene names \"\"\" exp = get_gene_data(data, gene) return expr_plot(tsne, exp, fig=fig, ax=ax, cmap=cmap,",
"otherwise create a new axis and attach to figure before returning. \"\"\" if",
"libplot.new_base_fig(w=w, h=h) for i in range(0, len(gene_ids)): # gene id gene_id = gene_ids[i][1]",
"cluster_order.size if cols == -1: cols = int(np.ceil(np.sqrt(n))) rows = int(np.ceil(n / cols))",
"function for creating an expression plot for T-SNE/2D space reduced representation of data.",
"/ x.size, y.sum() / y.size] centroid = [(x * avg[idx]).sum() / avg[idx].sum(), (y",
"1).apply(np.log2) def umi_tpm_log2(data): d = umi_tpm(data) return umi_log2(d) def umi_norm(data): \"\"\" Scale each",
"for a color bar rows += 1 h = size * rows return",
"dir='b') create_cluster_grid(tsne_b, c_b, 'b', dir='b') create_merge_cluster_info(d_b, c_b, 'b', sample_names=samples, dir='b') create_cluster_samples(tsne_b, c_b, samples,",
"cell reads_per_bc = data.sum(axis=0) scaling_factors = 1000000 / reads_per_bc scaled = data.multiply(scaling_factors) #",
"on by labelling cells by sample/batch. \"\"\" sc = np.array(['' for i in",
"fig, ax def create_pca_plot(pca, clusters, name, pc1=1, pc2=2, marker='o', labels=False, legend=True, s=MARKER_SIZE, w=8,",
"if isinstance(d_a, SparseDataFrame): d_b = umi_norm_log2(d_b) else: d_b = umi_norm_log2_scale(d_b) pca_b = libtsne.load_pca(d_b,",
"0], points[hull.vertices, 1], kind='cubic') # fy = interp1d(points[hull.vertices, 1], points[hull.vertices, 0], kind='cubic') #",
"'#40bf80', '#ffff33']) BGY_ORIG_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list( 'bgy', ['#002255', '#003380', '#2ca05a', '#ffd42a', '#ffdd55']) BGY_CMAP =",
"imagelib.paste(im, im_edges) # im_no_bg im_smooth = imagelib.smooth(im_outline) imagelib.save(im_smooth, 'smooth.png') # im_smooth imagelib.paste(im_base, im_smooth,",
"w, h, rows, cols = expr_grid_size(gene_ids, size=size) fig = libplot.new_base_fig(w=w, h=h) for i",
"= get_gene_names(data) ret = [] for g in genes: indexes = np.where(ids ==",
"# ax=None, # norm=None, # w=libplot.DEFAULT_WIDTH, # h=libplot.DEFAULT_HEIGHT, # colorbar=True): #plt.cm.plasma): # \"\"\"",
"= [255, 255, 255, 0] # im_data[np.where(grey_areas)] = d # # # #edges1",
"= pd.read_csv('../b_barcodes.tsv', header=0, sep='\\t') idx = np.where(counts.columns.isin(b_barcodes['Barcode'].values))[0] d_b = counts.iloc[:, idx] d_b =",
"np.where(clusters['Cluster'] == cid)[0] nx = 500 ny = 500 xi = np.linspace(x.min(), x.max(),",
"255) | (b < 255) #(r > 0) & (r == g) &",
"= plt.cm.plasma ids, gene_names = get_gene_names(data) gene_ids = get_gene_ids(data, genes, ids=ids, gene_names=gene_names) for",
"tsne.iloc[idx1, 1] # # libplot.scatter(x, y, c=colors[sid], ax=ax) # # sid += 1",
"df def create_cluster_samples(tsne_umi_log2, clusters, sample_names, name, method='tsne', format='png', dir='.', w=16, h=16, legend=True): sc",
"elif isinstance(colors, list): if cluster < len(colors): # np.where(clusters['Cluster'] == cluster)[0]] color =",
"---------- data : DataFrame data table containing and index genes : list List",
"#e = (e - e.mean()) / e.std() #print(e.min(), e.max()) # z-score #e =",
"libplot.savefig(fig, '{}_silhouette.pdf'.format(name)) def node_color_from_cluster(clusters): colors = libcluster.colors() return [colors[clusters['Cluster'][i] - 1] for i",
"out is None: out = '{}/{}_{}_separate_clusters.png'.format(dir, method, name) libplot.savefig(fig, out, pad=0) #libplot.savefig(fig, '{}/tsne_{}separate_clusters.pdf'.format(dir,",
"get_gene_data(data, genes, ids=ids, gene_names=gene_names) avg = exp.mean(axis=0) avg = (avg - avg.mean()) /",
"(index, gene_id, gene_name) \"\"\" if ids is None: ids, gene_names = get_gene_names(data) ret",
"# # #node_color = (c_phen['Cluster'][0:A.shape[0]] - 1).tolist() # node_color = (clusters['Cluster'] - 1).tolist()",
"w=8, h=8, legend=True, show_axes=False, sort=True, cluster_order=None, fig=None, ax=None, out=None): fig, ax = base_cluster_plot(tsne,",
"> 0: idx = idx[0] else: return None if isinstance(data, SparseDataFrame): return data[idx,",
"If ax is a supplied argument, return this, otherwise create a new axis",
"if isinstance(clip, float) or isinstance(clip, int): max = abs(clip) min = -max if",
"plot. # # Parameters # ---------- # data : pandas.DataFrame # t-sne 2D",
"if not os.path.isfile(file) or not cache: print('{} was not found, creating it with...'.format(file))",
"= libtsne.read_clusters(file) labels = data # .tolist() return cluster_map, labels def umi_tpm(data): #",
"i in range(0, x.size): # en = norm(e[i]) # color = cmap(int(en *",
"= libtsne.load_pca(d_b, 'b', cache=cache) # pca.iloc[idx_b,:] tsne_b = libtsne.load_pca_tsne(pca_b, 'b', cache=cache) c_b =",
"def sample_clusters(d, sample_names): \"\"\" Create a cluster matrix based on by labelling cells",
"# # im_smooth = im_edges.filter(ImageFilter.SMOOTH) # im_smooth.save('edges.png', 'png') # # im2.paste(im_smooth, (0, 0),",
"# avg1 = np.zeros(x.size) #avg[idx] #avg1[idx] = 1 # fx = interp1d(points[hull.vertices, 0],",
"if i == 0: # libcluster.format_axes(ax) # else: # libplot.invisible_axes(ax) ax.set_title('{} ({})'.format(gene_ids[i][2], gene_ids[i][1]))",
"optional Tranparency of markers. show_axes : bool, optional, default true Whether to show",
"yp = np.append(yp, yp[0]) ax.plot(xp, yp, 'k-') #ax.plot(points[hull.vertices[0], 0], points[hull.vertices[[0, -1]], 1]) #points",
"pc1=(i + 1), pc2=(j + 1), marker=marker, s=s, ax=ax) si += 1 return",
"to be z-scored. Transforming now...') # zscore #e = (e - e.mean()) /",
"dim=dim, cmap=cmap, marker=marker, s=s, alpha=alpha, fig=fig, w=w, h=h, ax=ax, show_axes=show_axes, colorbar=colorbar, norm=norm, linewidth=linewidth,",
"6 16:51:15 2018 @author: antony \"\"\" import matplotlib # matplotlib.use('agg') import matplotlib.pyplot as",
"GeneBCMatrix(decode(dsets['genes']), decode(dsets['gene_names']), decode(dsets['barcodes']), matrix) except tables.NoSuchNodeError: raise Exception(\"Genome %s does not exist in",
"0), im2) imagelib.save(im_base, out) def avg_expr(data, tsne, genes, cid, clusters, prefix='', index=None, dir='GeneExp',",
"ax.plot(xp, yp, 'k-') #ax.plot(points[hull.vertices[0], 0], points[hull.vertices[[0, -1]], 1]) #points = np.array([[x, y] for",
"libplot.ALPHA, show_axes=True, legend=True, sort=True, outline=True): cluster_order = list(sorted(set(clusters['Cluster']))) im_base = imagelib.new(w * 300,",
"gene, gene_id, format) else: out = '{}/{}_expr_{}.{}'.format(dir, method, gene, format) libplot.savefig(fig, 'tmp.png', pad=0)",
"colors) #libcluster.format_simple_axes(ax, title=\"t-SNE\") #libcluster.format_legend(ax, cols=6, markerscale=2) if out is not None: libplot.savefig(fig, out)",
"data : Pandas dataframe features x dimensions, e.g. rows are cells and columns",
"idx = np.where(clusters['Cluster'] == cid)[0] nx = 500 ny = 500 xi =",
"* avg[idx]).sum() / avg[idx].sum()] d = np.array([distance.euclidean(centroid, (a, b)) for a, b in",
"cmap=cmap, marker=marker, s=s, fig=fig, alpha=alpha, ax=ax, norm=norm) return fig, ax def pca_expr_plot(data, expr,",
"== 0: # Assume we will add a row for a color bar",
"None: fig, ax = libplot.new_fig(w=w, h=h) libcluster.scatter_clusters(d.iloc[:, dim1].values, d.iloc[:, dim2].values, clusters, colors=colors, edgecolors=edgecolors,",
"#expr_plot(tsne, exp, ax=ax) #libplot.add_colorbar(fig, cmap) exp_bin = exp[idx_bin] tsne_bin = tsne.iloc[idx_bin, :] expr_plot(tsne_bin,",
"Split cells into a and b \"\"\" cache = True counts = libcluster.remove_empty_rows(counts)",
"ax.get_xlim() ylim = ax.get_ylim() fig, ax = separate_cluster(d, clusters, cluster, color=color, size=w, s=s,",
"w=8, h=8, fig=None, ax=None, dir='.', format='png'): out = '{}/pca_{}_pc{}_vs_pc{}.{}'.format(dir, name, pc1, pc2, format)",
"[0.3, 0.3, 0.3] #'#4d4d4d' EDGE_WIDTH = 0 # 0.25 ALPHA = 0.9 BLUE_YELLOW_CMAP",
"gbm.barcodes, tpm) def create_cluster_plots(pca, labels, name, marker='o', s=MARKER_SIZE): for i in range(0, pca.shape[1]):",
"plot without the formatting \"\"\" if ax is None: fig, ax = libplot.new_fig()",
"umap data clusters : Pandas dataframe n x 1 table of n cells",
"expr_plot(tsne, exp, cmap=cmap, dim=dim, w=w, h=h, s=s, colorbar=colorbar, norm=norm, alpha=alpha, linewidth=linewidth, edgecolors=edgecolors) if",
"= collections.namedtuple( 'GeneBCMatrix', ['gene_ids', 'gene_names', 'barcodes', 'matrix']) def decode(items): return np.array([x.decode('utf-8') for x",
"umi_log2(d) def scale(d, clip=None, min=None, max=None, axis=1): if isinstance(d, SparseDataFrame): print('UMI norm log2",
"raise Exception(\"%s was not found in list of gene names.\" % gene_name) return",
"#, k=2) # # #node_color = (c_phen['Cluster'][0:A.shape[0]] - 1).tolist() # node_color = (clusters['Cluster']",
"show_axes=True, legend=True, sort=True, outline=True): cluster_order = list(sorted(set(clusters['Cluster']))) im_base = imagelib.new(w * 300, w",
"df.set_index('Cluster', inplace=True) df.to_csv('{}_cluster_overlaps.txt'.format(name), sep='\\t') def mkdir(path): \"\"\" Make dirs including any parents and",
"f.create_carray(group, 'indptr', obj=gbm.matrix.indptr) f.create_carray(group, 'shape', obj=gbm.matrix.shape) except: raise Exception(\"Failed to write H5 file.\")",
"/ m.sum(axis=0) mn = m.multiply(s) tpm = mn.multiply(1000000) return GeneBCMatrix(gbm.gene_ids, gbm.gene_names, gbm.barcodes, tpm)",
"df2 = pca.iloc[indices, ] x = df2.iloc[:, pc1 - 1] y = df2.iloc[:,",
"xp = np.append(xp, xp[0]) yp = np.append(yp, yp[0]) ax.plot(xp, yp, 'k-') #ax.plot(points[hull.vertices[0], 0],",
"color = color # + '7f' libplot.scatter(x, y, c=color, ax=ax, edgecolors='none', # edgecolors,",
"color = cmap(int(en * cmap.N)) # color = np.array(color) # # c1 =",
"xp = points[hull.vertices, 0] yp = points[hull.vertices, 1] xp = np.append(xp, xp[0]) yp",
"'b', dir='b') create_cluster_plot(tsne_b, c_b, 'b', dir='b') create_cluster_grid(tsne_b, c_b, 'b', dir='b') create_merge_cluster_info(d_b, c_b, 'b',",
"matplotlib axis If ax is a supplied argument, return this, otherwise create a",
"None: genes = gbm.gene_names gene_indices = np.where(genes == gene_name)[0] if len(gene_indices) == 0:",
"= fig.add_subplot(212) # libplot.newfig(w=9) df2 = pd.DataFrame({'Silhouette Score': x2, 'Cluster': clusters.iloc[:, 0].tolist( ),",
"- min) + min # return scaled if axis == 0: return pd.DataFrame(MinMaxScaler(feature_range=(min,",
":, 1] # b = im_data[:, :, 2] # # grey_areas = (r",
"dim1=0, dim2=1, w=8, h=8, alpha=ALPHA, # libplot.ALPHA, show_axes=True, legend=True, sort=True, cluster_order=None, fig=None, ax=None):",
"def create_cluster_grid(tsne, clusters, name, colors=None, cols=-1, size=SUBPLOT_SIZE, add_titles=True, cluster_order=None, method='tsne', dir='.', out=None): fig",
"clusters, colors=None, cols=-1, size=SUBPLOT_SIZE, add_titles=True, cluster_order=None): \"\"\" Plot each cluster separately to highlight",
"method, gene, gene_id) else: out = '{}/{}_expr_{}.png'.format(dir, method, gene) print(out) # overlay edges",
"bi = bin + 1 idx_bin = np.where(binnumber == bi)[0] idx_other = np.where(binnumber",
"'blue_yellow', ['#162d50', '#ffdd55']) BLUE_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list( 'blue', ['#162d50', '#afc6e9']) BLUE_GREEN_YELLOW_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list( 'bgy',",
"is None: out = '{}/{}_{}_separate_clusters.png'.format(dir, method, name) libplot.savefig(fig, out, pad=0) #libplot.savefig(fig, '{}/tsne_{}separate_clusters.pdf'.format(dir, name))",
"# libcluster.format_axes(ax) if not show_axes: libplot.invisible_axes(ax) legend_params = dict(LEGEND_PARAMS) if isinstance(legend, bool): legend_params['show']",
"matplotlib.colors.LinearSegmentedColormap.from_list( 'or_red', matplotlib.cm.OrRd(range(4, 256))) BU_PU_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list( 'bu_pu', matplotlib.cm.BuPu(range(4, 256))) # BGY_CMAP =",
"h=h) libcluster.scatter_clusters(d.iloc[:, dim1].values, d.iloc[:, dim2].values, clusters, colors=colors, edgecolors=edgecolors, linewidth=linewidth, markers=markers, alpha=alpha, s=s, ax=ax,",
"left (the clusters) # im_edges = im2.filter(ImageFilter.FIND_EDGES) # # # im_data = np.array(im_edges.convert('RGBA'))",
"libplot.new_fig(w=w, h=h) libcluster.scatter_clusters(d.iloc[:, dim1].values, d.iloc[:, dim2].values, clusters, colors=colors, edgecolors=edgecolors, linewidth=linewidth, markers=markers, alpha=alpha, s=s,",
"fig=None, ax=None, sdmax=0.5): \"\"\" Plot multiple genes on a grid. Parameters ---------- data",
"\"\"\" Base function for creating an expression plot for T-SNE/2D space reduced representation",
"pad=0) #libplot.savefig(fig, '{}/tsne_{}separate_clusters.pdf'.format(dir, name)) # # # def tsne_cluster_sample_grid(tsne, clusters, samples, colors=None, size=SUBPLOT_SIZE):",
"color='black', background=BACKGROUND_SAMPLE_COLOR, bgedgecolor='#808080', show_background=True, add_titles=True, size=4, alpha=ALPHA, s=MARKER_SIZE, edgecolors='white', linewidth=EDGE_WIDTH, fig=None, ax=None): \"\"\"",
"- 1] for i in range(0, clusters.shape[0])] # def network(tsne, clusters, name, k=5):",
"dir='b') create_cluster_samples(tsne_b, c_b, samples, 'b_sample', dir='b') genes_expr(d_b, tsne_b, genes, prefix='b_BGY', cmap=BLUE_GREEN_YELLOW_CMAP, w=w, h=h,",
"return pd.read_csv(file, sep='\\t', header=0, index_col=0) def silhouette(tsne, tsne_umi_log2, clusters, name): # measure cluster",
"in range(0, c1.shape[0]): ids1 = np.where(a1[i, :] > 0)[0] ids2 = np.where(a2[i, :]",
"norm=norm, # w=w, # h=h, # colorbar=colorbar) # # set_tsne_ax_lim(tsne, ax) # #",
"cells into a and b \"\"\" cache = True counts = libcluster.remove_empty_rows(counts) #",
"int): print('z max', max) sd[np.where(sd > max)] = max return pd.DataFrame(sd, index=d.index, columns=d.columns)",
"'b', cache=cache) # pca.iloc[idx_b,:] tsne_b = libtsne.load_pca_tsne(pca_b, 'b', cache=cache) c_b = libtsne.load_phenograph_clusters(pca_b, 'b',",
"%s does not exist in this file.\" % genome) except KeyError: raise Exception(\"File",
"its median size Parameters ---------- data : Pandas dataframe Matrix of umi counts",
": bool, optional, default true Whether to show legend. \"\"\" if ax is",
"ax=None): \"\"\" Plot a cluster separately to highlight where the samples are Parameters",
"s=s) #fig, ax = libplot.new_fig() #expr_plot(tsne, exp, ax=ax) #libplot.add_colorbar(fig, cmap) exp_bin = exp[idx_bin]",
"optional Index of gene ids gene_names : Index, optional Index of gene names",
"0), im_smooth) # # im_base.paste(im2, (0, 0), im2) if gene_id != gene: out",
"# np.where(clusters['Cluster'] == cluster)[0]] color = colors[i] else: color = CLUSTER_101_COLOR else: color",
"Second dimension being plotted (usually 2) fig : matplotlib figure, optional Supply a",
"or isinstance(min, int): print('z min', min) sd[np.where(sd < min)] = min if isinstance(max,",
"# if norm is None and exp.min() < 0: #norm = matplotlib.colors.Normalize(vmin=-3, vmax=3,",
"0.75, 0.75] EDGE_COLOR = None # [0.3, 0.3, 0.3] #'#4d4d4d' EDGE_WIDTH = 0",
"d2)][idx] e = exp[idx] # if (e.min() == 0): #print('Data does not appear",
"f.create_carray(group, 'data', obj=gbm.matrix.data) f.create_carray(group, 'indices', obj=gbm.matrix.indices) f.create_carray(group, 'indptr', obj=gbm.matrix.indptr) f.create_carray(group, 'shape', obj=gbm.matrix.shape) except:",
"if idx.size < 1: return None else: idx = np.where(ids == g)[0] if",
"# Where to plot figure pc = 1 for c in cluster_order: i",
"return data.iloc[idx, :].values def gene_expr_grid(data, tsne, genes, cmap=None, size=SUBPLOT_SIZE): \"\"\" Plot multiple genes",
"in zip(x1, y1)]) #hull = ConvexHull(points) #ax.plot(points[hull.vertices,0], points[hull.vertices,1]) #zi = griddata((x, y), avg1,",
"= matplotlib.colors.LinearSegmentedColormap.from_list( 'blue_yellow', ['#162d50', '#ffdd55']) BLUE_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list( 'blue', ['#162d50', '#afc6e9']) BLUE_GREEN_YELLOW_CMAP =",
"= libcluster.remove_empty_rows(d_b) if isinstance(d_a, SparseDataFrame): d_b = umi_norm_log2(d_b) else: d_b = umi_norm_log2_scale(d_b) pca_b",
"libtsne.write_clusters(headers, labels, name) cluster_map, data = libtsne.read_clusters(file) labels = data # .tolist() return",
"# libplot.savefig(fig, out, pad=0) # # return fig, ax def create_expr_plot(tsne, exp, dim=[1,",
"norm=None): # plt.cm.plasma): fig, ax = base_expr_plot(data, exp, t='PC', dim=dim, cmap=cmap, marker=marker, s=s,",
"i + 1) expr_plot(tsne, exp, ax=ax, cmap=cmap, colorbar=False) # if i == 0:",
"= True counts = libcluster.remove_empty_rows(counts) # ['AICDA', 'CD83', 'CXCR4', 'MKI67', 'MYC', 'PCNA', 'PRDM1']",
"tsne.iloc[:, 1].values # data['{}-{}'.format(t, d2)][idx] idx = np.where(clusters['Cluster'] == cid)[0] nx = 500",
"= colors.get(cluster, 'black') elif isinstance(colors, list): #i = cluster - 1 if i",
">= 0].quantile(TNSE_AX_Q)] #print(xlim, ylim) # ax.set_xlim(xlim) # ax.set_ylim(ylim) def base_cluster_plot(d, clusters, markers=None, s=libplot.MARKER_SIZE,",
"#print(xlim, ylim) # ax.set_xlim(xlim) # ax.set_ylim(ylim) def base_cluster_plot(d, clusters, markers=None, s=libplot.MARKER_SIZE, colors=None, edgecolors=EDGE_COLOR,",
"#centroid = [x.sum() / x.size, y.sum() / y.size] centroid = [(x * avg[idx]).sum()",
"& (g == b) black_areas = (a > 0) d = im_data[np.where(black_areas)] d[:,",
"ax = fig.add_subplot(212) # libplot.newfig(w=9) df2 = pd.DataFrame({'Silhouette Score': x2, 'Cluster': clusters.iloc[:, 0].tolist(",
"for i in range(0, clusters.shape[0])] # def network(tsne, clusters, name, k=5): # A",
"marker='o', s=MARKER_SIZE, alpha=EXP_ALPHA, fig=None, ax=None, norm=None): # plt.cm.plasma): fig, ax = base_expr_plot(data, exp,",
"background x = tsne.iloc[idx1, 0] y = tsne.iloc[idx1, 1] #print('sep', cluster, color) color",
"'ignore') for x in f['matrix']['features']['name']] barcodes = list(f['matrix']['barcodes'][:]) matrix = sp_sparse.csc_matrix( (f['matrix']['data'], f['matrix']['indices'],",
"before returning. \"\"\" if ax is None: fig, ax = libplot.new_fig(w=w, h=h) #",
"255, 255, 0] # im_data[np.where(grey_areas)] = d # # # #edges1 = feature.canny(rgb2gray(im_data))",
"> x1) & (d < x2))[0] x = x[idx] y = y[idx] points",
"clusters, samples, colors, size) # # libplot.savefig(fig, '{}/tsne_{}_sample_clusters.png'.format(dir, name)) # #libplot.savefig(fig, '{}/tsne_{}separate_clusters.pdf'.format(dir, name))",
"def silhouette(tsne, tsne_umi_log2, clusters, name): # measure cluster worth x1 = silhouette_samples( tsne,",
"plt.cm.plasma ids, gene_names = get_gene_names(data) exp = get_gene_data(data, genes, ids=ids, gene_names=gene_names) avg =",
"im_smooth, inplace=True) # imagelib.save(im_no_bg, 'smooth.png') # imagelib.paste(im_base, im_no_bg, inplace=True) im = imagelib.open(tmp) if",
"# colors = libcluster.colors() # # for i in range(0, len(cids)): # c",
"figure used to make the plot \"\"\" if type(genes) is pd.core.frame.DataFrame: genes =",
"node_color=node_color, vmax=(clusters['Cluster'].max() - 1), cmap=libcluster.colormap()) # # libplot.savefig(fig, 'network_{}.pdf'.format(name)) def plot_centroids(tsne, clusters, name):",
"genes, prefix='b_BGY', cmap=BLUE_GREEN_YELLOW_CMAP, w=w, h=h, dir='b/GeneExp', format=format) fig, ax = cluster_plot(tsne_b, c_b, legend=False,",
"ax=None): fig, ax = base_tsne_plot(tsne, marker=marker, c=c, s=s, label=label, fig=fig, ax=ax) #libtsne.tsne_legend(ax, labels,",
"list(sorted(set(clusters['Cluster'].tolist()))) ret = np.zeros((len(cids), 2)) for i in range(0, len(cids)): c = cids[i]",
"ax is None: fig, ax = libplot.new_fig(w=w, h=h) libcluster.scatter_clusters(d.iloc[:, dim1].values, d.iloc[:, dim2].values, clusters,",
"None: ids, gene_names = get_gene_names(data) if isinstance(g, list): g = np.array(g) if isinstance(g,",
"z-scores #e[e < -3] = -3 #e[e > 3] = 3 ax.scatter(x, y,",
"------- list list of tuples of (index, gene_id, gene_name) \"\"\" if ids is",
"- 1], pca.iloc[i, pc2 - 1], pca.index[i]) return fig, ax def pca_plot(pca, clusters,",
"1), optional Tranparency of markers. show_axes : bool, optional, default true Whether to",
"d1 : int, optional First dimension being plotted (usually 1) d2 : int,",
"rows = int(np.ceil(n / cols)) w = size * cols h = size",
"r.shape) # # grey_areas = (r < 255) & (r > 200) &",
"ax def base_expr_plot(data, exp, dim=[1, 2], cmap=plt.cm.plasma, marker='o', edgecolors=EDGE_COLOR, linewidth=1, s=MARKER_SIZE, alpha=1, w=libplot.DEFAULT_WIDTH,",
"w=w, h=h) libplot.savefig(fig, 'a/a_tsne_clusters_med.pdf') # b mkdir('b') b_barcodes = pd.read_csv('../b_barcodes.tsv', header=0, sep='\\t') idx",
"does not exist, try the gene names idx = np.where(np.isin(gene_names, g))[0] if idx.size",
"s=s, # alpha=alpha, # fig=fig, # ax=ax, # norm=norm, # w=w, # h=h,",
"ax def create_cluster_plot(d, clusters, name, dim1=0, dim2=1, method='tsne', markers='o', s=libplot.MARKER_SIZE, w=8, h=8, colors=None,",
"#fig, ax = libplot.new_fig() #expr_plot(tsne, exp, ax=ax) #libplot.add_colorbar(fig, cmap) fig, ax = expr_plot(tsne,",
"BLUE_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list( 'blue', ['#162d50', '#afc6e9']) BLUE_GREEN_YELLOW_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list( 'bgy', ['#162d50', '#214478', '#217844',",
"#ax.plot(points[hull.vertices,0], points[hull.vertices,1]) #zi = griddata((x, y), avg1, (xi, yi)) #ax.contour(xi, yi, z, levels=1)",
"axis=1) return scaled def umi_norm_log2(data): d = umi_norm(data) print(type(d)) return umi_log2(d) def scale(d,",
"out is not None: # libplot.savefig(fig, out, pad=0) # # return fig, ax",
"ax = libplot.new_fig() #expr_plot(tsne, exp, ax=ax) #libplot.add_colorbar(fig, cmap) fig, ax = expr_plot(tsne, exp,",
"data[:, :, 0] # #g = data[:, :, 1] # #b = data[:,",
"s=s, marker=marker, alpha=alpha, cmap=cmap, norm=norm, edgecolors='none', # edgecolors, linewidth=linewidth) # for i in",
"if isinstance(g, list): g = np.array(g) if isinstance(g, np.ndarray): idx = np.where(np.isin(ids, g))[0]",
"the top of the background # # x = tsne.iloc[idx1, 0] # y",
"# , axis=1) return scaled def umi_log2(d): if isinstance(d, SparseDataFrame): print('UMI norm log2",
"'#ffe066', '#ffd633']) GRAY_PURPLE_YELLOW_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list( 'grey_purple_yellow', ['#e6e6e6', '#3333ff', '#ff33ff', '#ffe066']) GYBLGRYL_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list(",
"name, k=5): c1 = centroids(tsne1, clusters) c2 = centroids(tsne2, clusters) a1 = kneighbors_graph(c1,",
"fig=fig, ax=ax) #libtsne.tsne_legend(ax, labels, colors) libcluster.format_simple_axes(ax, title=\"t-SNE\") libcluster.format_legend(ax, cols=6, markerscale=2) return fig, ax",
"c_a, 'a', dir='a') create_cluster_grid(tsne_a, c_a, 'a', dir='a') create_merge_cluster_info(d_a, c_a, 'a', sample_names=samples, dir='a') create_cluster_samples(tsne_a,",
"= im_data[:, :, 2] # # print(tmp, r.shape) # # grey_areas = (r",
"c=color, ax=ax) # # if add_titles: # if isinstance(cluster, int): # prefix =",
"2) fig : matplotlib figure, optional Supply a figure object on which to",
"should be labeled 'TSNE-1', 'TSNE-2' etc # clusters : DataFrame # Clusters in",
"ax=ax) #libtsne.tsne_legend(ax, labels, colors) libcluster.format_simple_axes(ax, title=\"PC\") if legend: libcluster.format_legend(ax, cols=6, markerscale=2) return fig,",
"dim2=1, w=8, h=8, alpha=ALPHA, # libplot.ALPHA, show_axes=True, legend=True, sort=True, cluster_order=None, fig=None, ax=None): \"\"\"",
"index=d.index, columns=d.columns) def rscale(d, min=0, max=1, axis=1): if axis == 0: return pd.DataFrame(RobustScaler().fit_transform(d),",
"out = '{}/{}_{}.{}'.format(dir, method, name, format) print(out) return cluster_plot(d, clusters, dim1=dim1, dim2=dim2, markers=markers,",
"g))[0] if idx.size < 1: return None else: idx = np.where(ids == g)[0]",
"im_data = np.array(im_edges.convert('RGBA')) # # #r = data[:, :, 0] # #g =",
"create_pca_plot(pca_a, c_a, 'a', dir='a') create_cluster_plot(tsne_a, c_a, 'a', dir='a') create_cluster_grid(tsne_a, c_a, 'a', dir='a') create_merge_cluster_info(d_a,",
"as f: if u'version' in f.attrs: if f.attrs['version'] > 2: raise ValueError( 'Matrix",
"[x.sum() / x.size, y.sum() / y.size] centroid = [(x * avg[idx]).sum() / avg[idx].sum(),",
"y.max(), ny) x = x[idx] y = y[idx] #centroid = [x.sum() / x.size,",
"\"\"\" if type(genes) is pd.core.frame.DataFrame: genes = genes['Genes'].values ids, gene_names = get_gene_names(data) gene_ids",
"# BGY_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list('bgy', ['#003366', '#40bf80', '#ffff33']) BGY_ORIG_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list( 'bgy', ['#002255', '#003380',",
"None: colors = libcluster.get_colors() # Where to plot figure pc = 1 for",
"dimensions exp : numpy array expression values for each data point so it",
"= -3 #e[e > 3] = 3 ax.scatter(x, y, c=e, s=s, marker=marker, alpha=alpha,",
"# #node_color = (c_phen['Cluster'][0:A.shape[0]] - 1).tolist() # node_color = (clusters['Cluster'] - 1).tolist() #",
"genes=None): if genes is None: genes = gbm.gene_names gene_indices = np.where(genes == gene_name)[0]",
"isinstance(d, SparseDataFrame): print('UMI norm log2 sparse') return d.log2(add=1) else: return (d + 1).apply(np.log2)",
"w=libplot.DEFAULT_WIDTH, h=libplot.DEFAULT_HEIGHT, alpha=1.0, colorbar=False, method='tsne', fig=None, ax=None, sdmax=0.5): \"\"\" Plot multiple genes on",
"= 4 * rows fig = libplot.new_base_fig(w=w, h=w) si = 1 for i",
"h : int, optional Plot height alpha : float (0, 1), optional Tranparency",
"# # libplot.scatter(x, y, c=colors[sid], ax=ax) # # sid += 1 # #",
"cluster, format) print('Creating', out, '...') libplot.savefig(fig, out) libplot.savefig(fig, 'tmp.png') plt.close(fig) def cluster_grid(tsne, clusters,",
"matplotlib ax, optional Supply an axis object on which to render the plot,",
"1] y = df2.iloc[:, pc2 - 1] if i in colors: color =",
"nx.spring_layout(G) fig, ax = libplot.newfig(w=8, h=8) # list(range(0, c.shape[0])) node_color = libcluster.colors()[0:c.shape[0]] cmap",
"mkdir(dir) if index is None: index = data.index if isinstance(genes, pd.core.frame.DataFrame): genes =",
"print(tmp, r.shape) # # grey_areas = (r < 255) & (r > 200)",
"= cids[i] x = tsne.iloc[np.where(clusters['Cluster'] == c)[0], :] centroid = (x.sum(axis=0) / x.shape[0]).tolist()",
"avg.min()) / (avg.max() - avg.min()) # min_max_scale(avg) create_expr_plot(tsne, avg, cmap=cmap, w=w, h=h, colorbar=colorbar,",
"vmax=3, clip=True) if norm is None: norm = libplot.NORM_3 # Sort by expression",
"ax def expr_plot(data, exp, dim=[1, 2], cmap=plt.cm.magma, marker='o', s=MARKER_SIZE, alpha=1, edgecolors=EDGE_COLOR, linewidth=EDGE_WIDTH, w=libplot.DEFAULT_WIDTH,",
"= 'C' else: prefix = '' ax.set_title('{}{} ({:,})'.format( prefix, cluster, len(idx1)), color=color) ax.axis('off')",
"+ 1 idx_bin = np.where(binnumber == bi)[0] idx_other = np.where(binnumber != bi)[0] tsne_other",
"= cluster_plot(tsne_b, c_b, legend=False, w=w, h=h) libplot.savefig(fig, 'b/b_tsne_clusters_med.pdf') def sample_clusters(d, sample_names): \"\"\" Create",
"legend_params['show']: libcluster.format_legend(ax, cols=legend_params['cols'], markerscale=legend_params['markerscale']) libplot.invisible_axes(ax) tmp = 'tmp{}.png'.format(i) libplot.savefig(fig, tmp) plt.close(fig) # Open",
"d_a = libcluster.remove_empty_rows(d_a) if isinstance(d_a, SparseDataFrame): d_a = umi_norm_log2(d_a) else: d_a = umi_norm_log2_scale(d_a)",
"np.zeros(x.size) #avg[idx] #avg1[idx] = 1 # fx = interp1d(points[hull.vertices, 0], points[hull.vertices, 1], kind='cubic')",
"cols=6, markerscale=2) if out is not None: libplot.savefig(fig, out) return fig, ax def",
"marker=marker, # norm=norm, # edgecolors=[color], # linewidth=linewidth) #libcluster.format_axes(ax, title=t) return fig, ax def",
"#a = im_data[:, :, 3] # # # Non transparent areas are edges",
"cids[i] # # #print('Label {}'.format(l)) # idx2 = np.where(clusters['Cluster'] != c)[0] # #",
"# im_smooth = im_edges.filter(ImageFilter.SMOOTH) # # # paste outline onto clusters # im2.paste(im_smooth,",
"of cluster ids in the order they should be rendered Returns ------- fig",
"gene_id != gene: out = '{}/{}_expr_{}_{}.{}'.format(dir, method, gene, gene_id, format) else: out =",
"# Non transparent areas are edges # #black_areas = (a > 0) #(r",
"clusters : DataFrame # Clusters in # # Returns # ------- # fig",
"and attach to figure before returning. \"\"\" if ax is None: fig, ax",
"0] # y = tsne.iloc[idx2, 1] # libplot.scatter(x, y, c=BACKGROUND_SAMPLE_COLOR, ax=ax) # #",
"'Matrix HDF5 file format version (%d) is an newer version that is not",
"sc = sample_clusters(clusters, sample_names) create_cluster_plot(tsne_umi_log2, sc, name, method=method, format=format, dir=dir, w=w, h=w, legend=legend)",
"fig=fig, ax=ax, norm=norm) libplot.savefig(fig, out) plt.close(fig) return fig, ax def expr_grid_size(x, size=SUBPLOT_SIZE): \"\"\"",
"colors=None, cols=-1, size=SUBPLOT_SIZE, add_titles=True, cluster_order=None): \"\"\" Plot each cluster separately to highlight where",
"> 0)[0] ids2 = np.where(a2[i, :] > 0)[0] ids3 = np.intersect1d(ids1, ids2) o",
"# Plot background points # # # # x = tsne.iloc[idx2, 0] #",
"plot and adds a color bar. \"\"\" is_first = False if ax is",
"return fig, ax def create_pca_plot(pca, clusters, name, pc1=1, pc2=2, marker='o', labels=False, legend=True, s=MARKER_SIZE,",
"h=libplot.DEFAULT_HEIGHT, alpha=1.0, colorbar=False, method='tsne', fig=None, ax=None, sdmax=0.5): \"\"\" Plot multiple genes on a",
"w * 300 im_base = imagelib.new(iw, iw) for bin in range(0, bins): bi",
"xlim = [d1[d1 < 0].quantile(1 - TNSE_AX_Q), d1[d1 >= 0].quantile(TNSE_AX_Q)] ylim = [d2[d2",
"im_smooth = imagelib.smooth_edges(im_no_bg) # imagelib.paste(im_no_bg, im_smooth, inplace=True) # imagelib.save(im_no_bg, 'smooth.png') # imagelib.paste(im_base, im_no_bg,",
"= data.iloc[idx, dim[0] - 1].values # data['{}-{}'.format(t, d1)][idx] y = data.iloc[idx, dim[1] -",
"bgedgecolor, linewidth=linewidth, s=s) # Plot cluster over the top of the background x",
"< 255) | (b < 255) #(r > 0) & (r == g)",
"# # # libplot.invisible_axes(ax) pc += 1 return fig def create_cluster_grid(tsne, clusters, name,",
"# \"\"\" # Plot each cluster separately to highlight samples # # Parameters",
"# if isinstance(cluster, int): # prefix = 'C' # else: # prefix =",
"networkx as nx import os import phenograph import libplot import libcluster import libtsne",
"= imagelib.remove_background(im) im_edges = imagelib.edges(im_no_bg) im_smooth = imagelib.smooth(im_edges) im_outline = imagelib.paste(im_no_bg, im_smooth) imagelib.paste(im_base,",
"isinstance(cluster, int): # prefix = 'C' # else: # prefix = '' #",
"libplot.savefig(fig, out, pad=0) #libplot.savefig(fig, '{}/tsne_{}separate_clusters.pdf'.format(dir, name)) # # # def tsne_cluster_sample_grid(tsne, clusters, samples,",
"nx import os import phenograph import libplot import libcluster import libtsne import seaborn",
"avg[avg > 1.5] = 1.5 avg = (avg - avg.min()) / (avg.max() -",
"idx.size < 1: return None else: idx = np.where(ids == g)[0] if idx.size",
"# # for sample in samples: # id = '-{}'.format(sid + 1) #",
"markers='o', s=libplot.MARKER_SIZE, w=8, h=8, colors=None, legend=True, sort=True, show_axes=False, ax=None, cluster_order=None, format='png', dir='.', out=None):",
"= y[idx] # avg1 = np.zeros(x.size) #avg[idx] #avg1[idx] = 1 # fx =",
"libplot.scatter(tsne['TSNE-1'], tsne['TSNE-2'], c=c, marker=marker, label=label, s=s, ax=ax) return fig, ax def tsne_plot(tsne, marker='o',",
"libcluster.format_legend(ax, cols=legend_params['cols'], markerscale=legend_params['markerscale']) return fig, ax def base_cluster_plot_outline(out, d, clusters, s=libplot.MARKER_SIZE, colors=None, edgecolors=EDGE_COLOR,",
"in range(0, pca.shape[1]): for j in range(i + 1, pca.shape[1]): create_cluster_plot(pca, labels, name,",
"'black' fig, ax = separate_cluster(tsne, clusters, cluster, color=color, add_titles=add_titles, size=size) out = '{}_sep_clust_{}_c{}.{}'.format(type,",
"the plot, otherwise a new one is created. norm : Normalize, optional Specify",
"'bu_pu', matplotlib.cm.BuPu(range(4, 256))) # BGY_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list('bgy', ['#0066ff', '#37c871', '#ffd42a']) # BGY_CMAP =",
"np.where((clusters['Cluster'] == c) & clusters.index.str.contains(id))[0] # # x = tsne.iloc[idx1, 0] # y",
"tsne['TSNE-2'], c=c, marker=marker, label=label, s=s, ax=ax) return fig, ax def tsne_plot(tsne, marker='o', s=libplot.MARKER_SIZE,",
"of points add_titles : bool Whether to add titles to plots w: int,",
"1 cluster = ids[i] # look up index for color purposes #i =",
"), 'Label': np.repeat('tsne-ah', len(x2))}) libplot.boxplot(df2, 'Cluster', 'Silhouette Score', colors=libcluster.colors(), ax=ax) ax.set_ylim([-1, 1]) ax.set_title('tsne-ah')",
"limit to 3 std for z-scores #e[e < -3] = -3 #e[e >",
"exp.mean(axis=0) avg = (avg - avg.mean()) / avg.std() avg[avg < -1.5] = -1.5",
"height alpha : float (0, 1), optional Tranparency of markers. show_axes : bool,",
"gene_name) return gbm.matrix[gene_indices[0], :].toarray().squeeze() def gbm_to_df(gbm): return pd.DataFrame(gbm.matrix.todense(), index=gbm.gene_names, columns=gbm.barcodes) def get_barcode_counts(gbm): ret",
"# ax = libplot.new_ax(fig, subplot=(rows, rows, i + 1)) # # x =",
"# Parameters # ---------- # tsne : Pandas dataframe # Cells x tsne",
"# StandardScaler().fit_transform(d.T) sd = sklearn.preprocessing.scale(d, axis=axis) #sd = sd.T if isinstance(clip, float) or",
"# d = im_data[np.where(grey_areas)] # d[:, :] = [255, 255, 255, 0] #",
"'RK10001_10003_clust-phen_silhouette.pdf') ax = fig.add_subplot(212) # libplot.newfig(w=9) df2 = pd.DataFrame({'Silhouette Score': x2, 'Cluster': clusters.iloc[:,",
"out) def avg_expr(data, tsne, genes, cid, clusters, prefix='', index=None, dir='GeneExp', cmap=OR_RED_CMAP, # BGY_CMAP,",
"cluster_order = list(sorted(set(clusters['Cluster']))) im_base = imagelib.new(w * 300, w * 300) for i",
"[x.decode('ascii', 'ignore') for x in f['matrix']['features']['name']] barcodes = list(f['matrix']['barcodes'][:]) matrix = sp_sparse.csc_matrix( (f['matrix']['data'],",
"matplotlib.colors.LinearSegmentedColormap.from_list( 'grey_purple_yellow', ['#e6e6e6', '#3333ff', '#ff33ff', '#ffe066']) GYBLGRYL_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list( 'grey_blue_green_yellow', ['#e6e6e6', '#0055d4', '#00aa44',",
"np.where(clusters['Cluster'] != cluster)[0] # Plot background points if show_background: x = tsne.iloc[idx2, 0]",
"len(ids)): l = ids[i] #print('Label {}'.format(l)) indices = np.where(clusters['Cluster'] == l)[0] n =",
"expr_plot(tsne, # exp, # t='TSNE', # d1=d1, # d2=d2, # x1=x1, # x2=x2,",
"256))) # BGY_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list('bgy', ['#0066ff', '#37c871', '#ffd42a']) # BGY_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list('bgy', ['#003380',",
"# edgecolors='none', #edgecolors, # linewidth=linewidth) # # # # mean = color.mean() #",
"None: fig, ax = libplot.new_fig(w=w, h=h) ids = list(sorted(set(clusters['Cluster']))) for i in range(0,",
"= libplot.new_fig() libplot.scatter(tsne['TSNE-1'], tsne['TSNE-2'], c=c, marker=marker, label=label, s=s, ax=ax) return fig, ax def",
"etc genes : array List of gene names \"\"\" if dir[-1] == '/':",
"A = kneighbors_graph(tsne, k, mode='distance', metric='euclidean').toarray() # # #A = A[0:500, 0:500] #",
"fig, ax = separate_cluster(d, clusters, cluster, color=color, size=w, s=s, linewidth=linewidth, add_titles=False) # get",
"# # Plot cluster over the top of the background # # x",
"Pandas dataframe Genes x samples expression matrix tsne : Pandas dataframe Cells x",
"for x in f['matrix']['features']['id']] feature_names = [x.decode('ascii', 'ignore') for x in f['matrix']['features']['name']] barcodes",
"'{}/tsne_{}separate_clusters.pdf'.format(dir, name)) # # def load_clusters(pca, headers, name, cache=True): file = libtsne.get_cluster_file(name) if",
"np.where(clusters['Cluster'] == cluster)[0]] color = colors[i] else: color = CLUSTER_101_COLOR else: color =",
"List of strings of gene ids ids : Index, optional Index of gene",
"gbm.matrix s = 1 / m.sum(axis=0) mn = m.multiply(s) tpm = mn.multiply(1000000) return",
"pos=pos, with_labels=False, ax=ax, node_size=200, node_color=node_color, vmax=(c.shape[0] - 1), cmap=libcluster.colormap()) nx.draw_networkx(G, with_labels=True, labels=labels, ax=ax,",
"float) or isinstance(clip, int): max = abs(clip) min = -max if isinstance(min, float)",
"norm : Normalize, optional Specify how colors should be normalized Returns ------- fig",
"# plt.cm.plasma): out = 'pca_expr_{}_t{}_vs_t{}.pdf'.format(name, 1, 2) fig, ax = base_pca_expr_plot(data, expr, dim=dim,",
"libplot.scatter(x, y, c=[background], ax=ax, edgecolors='none', # bgedgecolor, linewidth=linewidth, s=s) # Plot cluster over",
"that is not supported by this function.' % version) feature_ids = [x.decode('ascii', 'ignore')",
"# overlay edges on top of original image to highlight cluster #im_base.paste(im2, (0,",
"the formatting \"\"\" if ax is None: fig, ax = libplot.new_fig() libplot.scatter(tsne['TSNE-1'], tsne['TSNE-2'],",
"get_gene_names(data): if ';' in data.index[0]: ids, genes = data.index.str.split(';').str else: genes = data.index",
"(r < 255) | (g < 255) | (b < 255) #(r >",
"Plot a cluster separately to highlight where the samples are Parameters ---------- tsne",
"libplot.format_axes(ax) libplot.savefig(fig, '{}_centroid_network.pdf'.format(name)) def centroids(tsne, clusters): cids = list(sorted(set(clusters['Cluster'].tolist()))) ret = np.zeros((len(cids), 2))",
"# libplot.ALPHA, show_axes=True, legend=True, sort=True, cluster_order=None, fig=None, ax=None): \"\"\" Create a tsne plot",
"yi, z, levels=1) def gene_expr(data, tsne, gene, fig=None, ax=None, cmap=plt.cm.plasma, out=None): \"\"\" Plot",
"/ e.std() #print(e.min(), e.max()) # z-score #e = (e - e.mean()) / e.std()",
"dim1=0, dim2=1, w=8, alpha=ALPHA, # libplot.ALPHA, show_axes=True, legend=True, sort=True, outline=True): cluster_order = list(sorted(set(clusters['Cluster'])))",
"['#003380', '#5fd38d', '#ffd42a']) EXP_NORM = matplotlib.colors.Normalize(-1, 3, clip=True) LEGEND_PARAMS = {'show': True, 'cols':",
"np.where(a1[i, :] > 0)[0] ids2 = np.where(a2[i, :] > 0)[0] ids3 = np.intersect1d(ids1,",
"= bin + 1 idx_bin = np.where(binnumber == bi)[0] idx_other = np.where(binnumber !=",
"a Cluster column giving each cell a cluster label. s : int, optional",
"matrix = sp_sparse.csc_matrix( (f['matrix']['data'], f['matrix']['indices'], f['matrix']['indptr']), shape=f['matrix']['shape']) return GeneBCMatrix(feature_ids, feature_names, decode(barcodes), matrix) def",
"cmap=cmap, out=out) def separate_cluster(tsne, clusters, cluster, color='black', background=BACKGROUND_SAMPLE_COLOR, bgedgecolor='#808080', show_background=True, add_titles=True, size=4, alpha=ALPHA,",
"cmap=None, marker='o', s=MARKER_SIZE, alpha=EXP_ALPHA, fig=None, ax=None, w=libplot.DEFAULT_WIDTH, h=libplot.DEFAULT_HEIGHT, edgecolors=EDGE_COLOR, linewidth=EDGE_WIDTH, norm=None, method='tsne', show_axes=False,",
"1].values # data['{}-{}'.format(t, d2)][idx] idx = np.where(clusters['Cluster'] == cid)[0] nx = 500 ny",
"-1]], 1]) #points = np.array([[x, y] for x, y in zip(x1, y1)]) #hull",
"'a', cache=cache) c_a = libtsne.load_phenograph_clusters(pca_a, 'a', cache=cache) create_pca_plot(pca_a, c_a, 'a', dir='a') create_cluster_plot(tsne_a, c_a,",
"name) cluster_map, data = libtsne.read_clusters(file) labels = data # .tolist() return cluster_map, labels",
"dict(LEGEND_PARAMS) if isinstance(legend, bool): legend_params['show'] = legend elif isinstance(legend, dict): legend_params.update(legend) else: pass",
"len(idx1)), color=color) # # # libplot.invisible_axes(ax) pc += 1 return fig def create_cluster_grid(tsne,",
"0] # im_data[np.where(grey_areas)] = d # # # #edges1 = feature.canny(rgb2gray(im_data)) # #",
"'Label': np.repeat('tsne-10x', len(x1))}) libplot.boxplot(df, 'Cluster', 'Silhouette Score', colors=libcluster.colors(), ax=ax) ax.set_ylim([-1, 1]) ax.set_title('tsne-10x') #libplot.savefig(fig,",
"clusters, pc1=pc1, pc2=pc2, labels=labels, marker=marker, legend=legend, s=s, w=w, h=h, fig=fig, ax=ax) libplot.savefig(fig, out,",
"max) sd[np.where(sd > max)] = max return pd.DataFrame(sd, index=d.index, columns=d.columns) def min_max_scale(d, min=0,",
"# im2 = Image.fromarray(im_data) # # # Edge detect on what is left",
"# fig=fig, # ax=ax, # norm=norm, # w=w, # h=h, # colorbar=colorbar) #",
"d.min(axis=1) #std = (d - m) / (d.max(axis=1) - m) #scaled = std",
"# marker=marker, # s=s, # alpha=alpha, # fig=fig, # ax=ax, # norm=norm, #",
"min=0, max=1, axis=1): #m = d.min(axis=1) #std = (d - m) / (d.max(axis=1)",
"= len(ids3) / 5 * 100 overlaps.append(o) df = pd.DataFrame( {'Cluster': list(range(1, c1.shape[0]",
"d_a = counts.iloc[:, idx] d_a = libcluster.remove_empty_rows(d_a) if isinstance(d_a, SparseDataFrame): d_a = umi_norm_log2(d_a)",
"= color # + '7f' libplot.scatter(x, y, c=color, ax=ax, edgecolors='none', # edgecolors, linewidth=linewidth,",
"true Whether to show legend. \"\"\" if ax is None: fig, ax =",
"# #if mean > 0.5: # ax.scatter(x[i], # y[i], # c='#ffffff00', # s=s,",
"= tsne.iloc[idx2, 1] # # libplot.scatter(x, y, c=BACKGROUND_SAMPLE_COLOR, ax=ax) # # # Plot",
"# w=libplot.DEFAULT_WIDTH, # h=libplot.DEFAULT_HEIGHT, # colorbar=True): #plt.cm.plasma): # \"\"\" # Creates a basic",
"Returns # ------- # fig : Matplotlib figure # A new Matplotlib figure",
"def separate_cluster(tsne, clusters, cluster, color='black', background=BACKGROUND_SAMPLE_COLOR, bgedgecolor='#808080', show_background=True, add_titles=True, size=4, alpha=ALPHA, s=MARKER_SIZE, edgecolors='white',",
"data[:, :, 0] #g = data[:, :, 1] #b = data[:, :, 2]",
"in list of gene names.\" % gene_name) return gbm.matrix[gene_indices[0], :].toarray().squeeze() def gbm_to_df(gbm): return",
"is None: fig, ax = libplot.new_fig(w, h) is_first = True base_expr_plot(data, exp, dim=dim,",
"'C{} ({:,})'.format(l, n) df2 = pca.iloc[indices, ] x = df2.iloc[:, pc1 - 1]",
"# ax.set_xlim(xlim) # ax.set_ylim(ylim) def base_cluster_plot(d, clusters, markers=None, s=libplot.MARKER_SIZE, colors=None, edgecolors=EDGE_COLOR, linewidth=EDGE_WIDTH, dim1=0,",
"dim1=dim1, dim2=dim2, s=s, w=w, h=h, cluster_order=cluster_order, legend=legend, sort=sort, show_axes=show_axes, fig=fig, ax=ax) #libtsne.tsne_legend(ax, labels,",
"-1.5 avg[avg > 1.5] = 1.5 avg = (avg - avg.min()) / (avg.max()",
"'PRDM1'] genes = pd.read_csv('../../../../expression_genes.txt', header=0) mkdir('a') a_barcodes = pd.read_csv('../a_barcodes.tsv', header=0, sep='\\t') idx =",
"(0, 0), im2) # break imagelib.save(im_base, out) def cluster_plot(tsne, clusters, dim1=0, dim2=1, markers='o',",
"x dimensions, e.g. rows are cells and columns are tsne dimensions exp :",
"isinstance(colors, dict): color = colors.get(cluster, 'black') elif isinstance(colors, list): #i = cluster -",
"= x elif type(x) is list: l = len(x) elif type(x) is np.ndarray:",
"clip=True) if norm is None: norm = libplot.NORM_3 # Sort by expression level",
"colors[i] else: color = CLUSTER_101_COLOR else: color = 'black' fig, ax = separate_cluster(tsne,",
"# # #set_tsne_ax_lim(tsne, ax) # # return fig # # # def create_tsne_cluster_sample_grid(tsne,",
"sp_sparse import tables import pandas as pd from sklearn.manifold import TSNE import sklearn.preprocessing",
"cols=6, markerscale=2) return fig, ax def base_expr_plot(data, exp, dim=[1, 2], cmap=plt.cm.plasma, marker='o', edgecolors=EDGE_COLOR,",
"separate_cluster(d, clusters, cluster, color=color, size=w, s=s, linewidth=linewidth, add_titles=False, show_background=False) ax.set_xlim(xlim) ax.set_ylim(ylim) if not",
"size=SUBPLOT_SIZE, add_titles=True, cluster_order=None): \"\"\" Plot each cluster separately to highlight where the samples",
"\"\"\" # # # cids = list(sorted(set(clusters['Cluster']))) # # rows = int(np.ceil(np.sqrt(len(cids)))) #",
"True, 'cols': 4, 'markerscale': 2} CLUSTER_101_COLOR = (0.3, 0.3, 0.3) np.random.seed(0) GeneBCMatrix =",
"'tmp.png', pad=0) libplot.savefig(fig, out, pad=0) plt.close(fig) im1 = Image.open('tmp.png') # Edge detect on",
"(r == g) & (r == b) & (g == b) # #",
"- avg.min()) / (avg.max() - avg.min()) # min_max_scale(avg) create_expr_plot(tsne, avg, cmap=cmap, w=w, h=h,",
"be labeled 'TSNE-1', 'TSNE-2' etc genes : array List of gene names Returns",
"is None: # colors = libcluster.colors() # # for i in range(0, len(cids)):",
"im_data[:, :, 2] # # print(tmp, r.shape) # # grey_areas = (r <",
"tsne.iloc[:, 1] xlim = [d1[d1 < 0].quantile(1 - TNSE_AX_Q), d1[d1 >= 0].quantile(TNSE_AX_Q)] ylim",
"[] for i in range(0, c1.shape[0]): ids1 = np.where(a1[i, :] > 0)[0] ids2",
"s=s, alpha=alpha, fig=fig, w=w, h=h, ax=ax, show_axes=show_axes, colorbar=colorbar, norm=norm, linewidth=linewidth, edgecolors=edgecolors) if out",
"avg[idx].sum()] d = np.array([distance.euclidean(centroid, (a, b)) for a, b in zip(x, y)]) sd",
"range(len(gbm.barcodes)): ret.append(np.sum(gbm.matrix[:, i].toarray())) return ret def df(gbm): \"\"\" Converts a GeneBCMatrix to a",
"samples, colors, size) # # libplot.savefig(fig, '{}/tsne_{}_sample_clusters.png'.format(dir, name)) # #libplot.savefig(fig, '{}/tsne_{}separate_clusters.pdf'.format(dir, name)) #",
"= np.where(clusters['Cluster'] == cid)[0] nx = 500 ny = 500 xi = np.linspace(x.min(),",
"tsne data. Columns should be labeled 'TSNE-1', 'TSNE-2' etc clusters : DataFrame Clusters",
"im_smooth = smooth_edges(im1, im1) # # # Edge detect on what is left",
"len(colors): # np.where(clusters['Cluster'] == cluster)[0]] color = colors[i] else: color = CLUSTER_101_COLOR else:",
"Image.open('tmp.png') # Edge detect on what is left (the clusters) imageWithEdges = im1.filter(ImageFilter.FIND_EDGES)",
"= tsne.iloc[np.where(clusters['Cluster'] == c)[0], :] centroid = (x.sum(axis=0) / x.shape[0]).tolist() ret[i, 0] =",
"\"\"\" Converts a GeneBCMatrix to a pandas dataframe (dense) Parameters ---------- gbm :",
"im2 = Image.fromarray(im_data) im2.save('edges.png', 'png') # overlay edges on top of original image",
"# # paste outline onto clusters # im2.paste(im_smooth, (0, 0), im_smooth) # #",
"= silhouette_samples( tsne, clusters.iloc[:, 0].tolist(), metric='euclidean') x2 = silhouette_samples( tsne_umi_log2, clusters.iloc[:, 0].tolist(), metric='euclidean')",
"# # def load_clusters(pca, headers, name, cache=True): file = libtsne.get_cluster_file(name) if not os.path.isfile(file)",
"feature.canny(rgb2gray(im_data)) # # #print(edges1.shape) # # #skimage.io.imsave('tmp_canny_{}.png'.format(bin), edges1) # # im2 = Image.fromarray(im_data)",
"Exception(\"Genome %s does not exist in this file.\" % genome) except KeyError: raise",
"umi_log2(d) def umi_norm(data): \"\"\" Scale each library to its median size Parameters ----------",
"genes_expr(data, tsne, genes, prefix='', dim=[1, 2], index=None, dir='GeneExp', cmap=BGY_CMAP, norm=None, w=4, h=4, s=30,",
"gene_id, ids=ids, gene_names=gene_names) #fig, ax = libplot.new_fig() #expr_plot(tsne, exp, ax=ax) #libplot.add_colorbar(fig, cmap) fig,",
"cluster_plot(tsne_a, c_a, legend=False, w=w, h=h) libplot.savefig(fig, 'a/a_tsne_clusters_med.pdf') # b mkdir('b') b_barcodes = pd.read_csv('../b_barcodes.tsv',",
"return fig, ax def base_expr_plot(data, exp, dim=[1, 2], cmap=plt.cm.plasma, marker='o', edgecolors=EDGE_COLOR, linewidth=1, s=MARKER_SIZE,",
"# else: # color = 'black' # # libplot.scatter(x, y, c=color, ax=ax) #",
"({:,})'.format(c, len(idx1)), color=colors[i]) # libplot.invisible_axes(ax) # # #set_tsne_ax_lim(tsne, ax) # # return fig",
"by expression level so that extreme values always appear on top idx =",
"= umi_norm_log2_scale(d_b) pca_b = libtsne.load_pca(d_b, 'b', cache=cache) # pca.iloc[idx_b,:] tsne_b = libtsne.load_pca_tsne(pca_b, 'b',",
"# fx = interp1d(points[hull.vertices, 0], points[hull.vertices, 1], kind='cubic') # fy = interp1d(points[hull.vertices, 1],",
":] = [255, 255, 255, 0] # im_data[np.where(grey_areas)] = d # # im2",
"mn.multiply(1000000) return GeneBCMatrix(gbm.gene_ids, gbm.gene_names, gbm.barcodes, tpm) def create_cluster_plots(pca, labels, name, marker='o', s=MARKER_SIZE): for",
": matplotlib ax, optional Supply an axis object on which to render the",
"clusters, pc1=pc1, pc2=pc2, marker=marker, labels=labels, s=s, w=w, h=h, fig=fig, ax=ax) #libtsne.tsne_legend(ax, labels, colors)",
"range(0, c.shape[0]): labels[i] = i + 1 #nx.draw_networkx(G, pos=pos, with_labels=False, ax=ax, node_size=200, node_color=node_color,",
"left (the clusters) # im_edges = im2.filter(ImageFilter.FIND_EDGES) # # im_smooth = im_edges.filter(ImageFilter.SMOOTH) #",
"np.ndarray): idx = np.where(np.isin(ids, g))[0] if idx.size < 1: # if id does",
"colors = libcluster.get_colors() for i in indices: print('index', i) cluster = ids[i] if",
"= np.array(im_edges.convert('RGBA')) # # #r = data[:, :, 0] # #g = data[:,",
"2], cmap=None, marker='o', s=MARKER_SIZE, alpha=EXP_ALPHA, fig=None, ax=None, norm=None): # plt.cm.plasma): out = 'pca_expr_{}_t{}_vs_t{}.pdf'.format(name,",
"# im = imagelib.open(tmp) # im_no_bg = imagelib.remove_background(im) # im_smooth = imagelib.smooth_edges(im_no_bg) #",
"= (0.3, 0.3, 0.3) np.random.seed(0) GeneBCMatrix = collections.namedtuple( 'GeneBCMatrix', ['gene_ids', 'gene_names', 'barcodes', 'matrix'])",
"Create a tsne plot without the formatting \"\"\" if ax is None: fig,",
"Created on Wed Jun 6 16:51:15 2018 @author: antony \"\"\" import matplotlib #",
"centroid_network(tsne, clusters, name): c = centroids(tsne, clusters) A = kneighbors_graph(c, 5, mode='distance', metric='euclidean').toarray()",
"clusters, cluster, color=color, size=w, s=s, linewidth=linewidth, add_titles=False) # get x y lim xlim",
"# bgedgecolor, linewidth=linewidth, s=s) # Plot cluster over the top of the background",
"genes = genes['Genes'].values ids, gene_names = get_gene_names(data) gene_ids = get_gene_ids(data, genes, ids=ids, gene_names=gene_names)",
".tolist() return cluster_map, labels def umi_tpm(data): # each column is a cell reads_per_bc",
"= '' ax.set_title('{}{} ({:,})'.format( prefix, cluster, len(idx1)), color=color) ax.axis('off') # libplot.invisible_axes(ax) return fig,",
"to look pretty. \"\"\" d1 = tsne.iloc[:, 0] d2 = tsne.iloc[:, 1] xlim",
"im_data[np.where(grey_areas)] = d # # # #edges1 = feature.canny(rgb2gray(im_data)) # # #print(edges1.shape) #",
"> 200) & (b < 255) & (b > 200) # # d",
"is None: # libtsne.get_tsne_plot_name(name)) out = '{}/{}_{}.{}'.format(dir, method, name, format) print(out) return cluster_plot(d,",
"Score', colors=libcluster.colors(), ax=ax) ax.set_ylim([-1, 1]) ax.set_title('tsne-10x') #libplot.savefig(fig, 'RK10001_10003_clust-phen_silhouette.pdf') ax = fig.add_subplot(212) # libplot.newfig(w=9)",
"Pandas dataframe t-sne, umap data clusters : Pandas dataframe n x 1 table",
"print('Reading clusters from {}...'.format(file)) return pd.read_csv(file, sep='\\t', header=0, index_col=0) def silhouette(tsne, tsne_umi_log2, clusters,",
"libtsne.load_pca_tsne(pca_a, 'a', cache=cache) c_a = libtsne.load_phenograph_clusters(pca_a, 'a', cache=cache) create_pca_plot(pca_a, c_a, 'a', dir='a') create_cluster_plot(tsne_a,",
"'black' else: color = 'black' ax = libplot.new_ax(fig, subplot=(rows, cols, pc)) separate_cluster(tsne, clusters,",
"gene_expr_grid(data, tsne, genes, cmap=None, size=SUBPLOT_SIZE): \"\"\" Plot multiple genes on a grid. Parameters",
"matplotlib figure, optional Supply a figure object on which to render the plot,",
"1], points[hull.vertices, 0], kind='cubic') # # xt = np.linspace(x.min(), x.max(), 100, endpoint=True) #",
"0: raise Exception(\"%s was not found in list of gene names.\" % gene_name)",
"decode(dsets['barcodes']), matrix) except tables.NoSuchNodeError: raise Exception(\"Genome %s does not exist in this file.\"",
"show_axes=show_axes, colorbar=colorbar, norm=norm, linewidth=linewidth, edgecolors=edgecolors) if out is not None: libplot.savefig(fig, out, pad=0)",
"get x y lim xlim = ax.get_xlim() ylim = ax.get_ylim() fig, ax =",
"format version (%d) is an newer version that is not supported by this",
"width of new ax. h: int, optional height of new ax. Returns -------",
"x in items]) def get_matrix_from_h5(filename, genome): with tables.open_file(filename, 'r') as f: try: dsets",
"= data[:, :, 0] # #g = data[:, :, 1] # #b =",
"# #r = data[:, :, 0] # #g = data[:, :, 1] #",
"in range(0, n): for j in range(i + 1, n): ax = libplot.new_ax(fig,",
"{}...'.format(file)) return pd.read_csv(file, sep='\\t', header=0, index_col=0) def silhouette(tsne, tsne_umi_log2, clusters, name): # measure",
"plt.close(fig) im1 = Image.open('tmp.png') # Edge detect on what is left (the clusters)",
"return this, otherwise create a new axis and attach to figure before returning.",
"feature_ids = [x.decode('ascii', 'ignore') for x in f['matrix']['features']['id']] feature_names = [x.decode('ascii', 'ignore') for",
"- avg.mean()) / avg.std() avg[avg < -1.5] = -1.5 avg[avg > 1.5] =",
"= matplotlib.colors.LinearSegmentedColormap.from_list( 'or_red', matplotlib.cm.OrRd(range(4, 256))) BU_PU_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list( 'bu_pu', matplotlib.cm.BuPu(range(4, 256))) # BGY_CMAP",
"s=s, alpha=alpha, fig=fig, ax=ax, norm=norm) libplot.savefig(fig, out) plt.close(fig) return fig, ax def expr_grid_size(x,",
"= np.array(list(sorted(set(clusters['Cluster'])))) cluster_order = np.array(list(range(0, len(ids)))) + 1 n = cluster_order.size if cols",
":, 0] # #g = data[:, :, 1] # #b = data[:, :,",
"name, pc1=( i + 1), pc2=(j + 1), marker=marker, s=s) def pca_base_plots(pca, clusters,",
"mean > 0.5: # ax.scatter(x[i], # y[i], # c='#ffffff00', # s=s, # marker=marker,",
"out=None): # plt.cm.plasma): \"\"\" Creates and saves a presentation tsne plot \"\"\" if",
"libplot.new_fig() #expr_plot(tsne, exp, ax=ax) #libplot.add_colorbar(fig, cmap) exp_bin = exp[idx_bin] tsne_bin = tsne.iloc[idx_bin, :]",
"ax=None, cmap=plt.cm.plasma, out=None): \"\"\" Plot multiple genes on a grid. Parameters ---------- data",
"Parameters ---------- data : Pandas dataframe Matrix of umi counts \"\"\" # each",
"true Whether to show axes on plot legend : bool, optional, default true",
"0: # libcluster.format_axes(ax) # else: # libplot.invisible_axes(ax) ax.set_title('{} ({})'.format(gene_ids[i][2], gene_ids[i][1])) libplot.add_colorbar(fig, cmap) return",
"cmap=cmap, s=s, colorbar=colorbar, norm=norm, alpha=alpha, linewidth=linewidth, edgecolors=edgecolors, ax=ax) tmp = 'tmp{}.png'.format(bin) libplot.savefig(fig, tmp,",
"this function.' % version) else: raise ValueError( 'Matrix HDF5 file format version (%d)",
"# print(tmp, r.shape) # # grey_areas = (r < 255) & (r >",
"[64, 64, 64] im_data[np.where(black_areas)] = d im2 = Image.fromarray(im_data) im2.save('edges.png', 'png') # overlay",
"1] # #b = data[:, :, 2] # #a = im_data[:, :, 3]",
"else: color = 'black' fig, ax = separate_cluster(tsne, clusters, cluster, color=color, add_titles=add_titles, size=size)",
"else: color = 'black' fig, ax = separate_cluster(d, clusters, cluster, color=color, size=w, s=s,",
"elif isinstance(colors, list): # color = colors[i] # else: # color = 'black'",
"(g < 255) | (b < 255) #(r > 0) & (r ==",
"im_no_bg = imagelib.remove_background(im) # im_smooth = imagelib.smooth_edges(im_no_bg) # imagelib.paste(im_no_bg, im_smooth, inplace=True) # imagelib.save(im_no_bg,",
"# marker=marker, # edgecolors='none', #edgecolors, # linewidth=linewidth) # # # # mean =",
"of strings of gene ids ids : Index, optional Index of gene ids",
"i in range(0, clusters.shape[0])] # def network(tsne, clusters, name, k=5): # A =",
"'{}/{}_expr_{}_{}.{}'.format(dir, method, gene, gene_id, format) else: out = '{}/{}_expr_{}.{}'.format(dir, method, gene, format) libplot.savefig(fig,",
"is None: fig, ax = libplot.new_fig(w=w, h=h) libcluster.scatter_clusters(d.iloc[:, dim1].values, d.iloc[:, dim2].values, clusters, colors=colors,",
"seaborn as sns from libsparse.libsparse import SparseDataFrame from lib10x.sample import * from scipy.spatial",
"im_data[:, :, 2] # # grey_areas = (r < 255) & (r >",
"else: out = '{}/{}_expr_{}.png'.format(dir, method, gene) print(out) # overlay edges on top of",
"# G=nx.from_numpy_matrix(A) # pos=nx.spring_layout(G) #, k=2) # # #node_color = (c_phen['Cluster'][0:A.shape[0]] - 1).tolist()",
"libcluster.get_colors() # Where to plot figure pc = 1 for c in cluster_order:",
"'ignore') for x in f['matrix']['features']['id']] feature_names = [x.decode('ascii', 'ignore') for x in f['matrix']['features']['name']]",
"= tsne.iloc[idx2, 0] # y = tsne.iloc[idx2, 1] # # libplot.scatter(x, y, c=BACKGROUND_SAMPLE_COLOR,",
"#print('Label {}'.format(l)) idx1 = np.where(clusters['Cluster'] == cluster)[0] idx2 = np.where(clusters['Cluster'] != cluster)[0] #",
"binned_statistic import imagelib TNSE_AX_Q = 0.999 MARKER_SIZE = 10 SUBPLOT_SIZE = 4 EXP_ALPHA",
"ax : matplotlib ax, optional Supply an axis object on which to render",
"range(0, x.size): # en = norm(e[i]) # color = cmap(int(en * cmap.N)) #",
"n=10, marker='o', s=MARKER_SIZE): rows = libplot.grid_size(n) w = 4 * rows fig =",
"# (d > x1) & (d < x2))[0] x = x[idx] y =",
"colors=colors, dim1=dim1, dim2=dim2, s=s, w=w, h=h, cluster_order=cluster_order, legend=legend, sort=sort, show_axes=show_axes, fig=fig, ax=ax) #libtsne.tsne_legend(ax,",
"imagelib.smooth(im_edges) im_outline = imagelib.paste(im_no_bg, im_smooth) imagelib.paste(im_base, im_outline, inplace=True) # # find gray areas",
"an axis object on which to render the plot, otherwise a new one",
"#libtsne.tsne_legend(ax, labels, colors) libcluster.format_simple_axes(ax, title=\"t-SNE\") libcluster.format_legend(ax, cols=6, markerscale=2) return fig, ax def base_expr_plot(data,",
"# tsne : Pandas dataframe # Cells x tsne tsne data. Columns should",
"= im_edges.filter(ImageFilter.SMOOTH) # # # paste outline onto clusters # im2.paste(im_smooth, (0, 0),",
"# libtsne.get_tsne_plot_name(name)) out = '{}/{}_{}.{}'.format(dir, method, name, format) print(out) return cluster_plot(d, clusters, dim1=dim1,",
"# # set_tsne_ax_lim(tsne, ax) # # libplot.invisible_axes(ax) # # if out is not",
"s c += 1 print(np.unique(d.index.values)) print(np.unique(sc)) df = pd.DataFrame(sc, index=d.index, columns=['Cluster']) return df",
"data[:, :, 1] # #b = data[:, :, 2] # #a = im_data[:,",
"= list(sorted(set(clusters['Cluster'].tolist()))) ret = np.zeros((len(cids), 2)) for i in range(0, len(cids)): c =",
"always appear on top idx = np.argsort(exp) #np.argsort(abs(exp)) # np.argsort(exp) x = data.iloc[idx,",
"* rows fig = libplot.new_base_fig(w=w, h=h) if colors is None: colors = libcluster.get_colors()",
"h=8, legend=True, show_axes=False, sort=True, cluster_order=None, fig=None, ax=None, out=None): fig, ax = base_cluster_plot(tsne, clusters,",
"add a row for a color bar rows += 1 h = size",
"utf-8 -*- \"\"\" Created on Wed Jun 6 16:51:15 2018 @author: antony \"\"\"",
"cluster label. s : int, optional Marker size w : int, optional Plot",
"= Image.fromarray(im_data) # #im2.save('edges.png', 'png') # # im_smooth = im_edges.filter(ImageFilter.SMOOTH) # im_smooth.save('edges.png', 'png')",
"fig def genes_expr(data, tsne, genes, prefix='', dim=[1, 2], index=None, dir='GeneExp', cmap=BGY_CMAP, norm=None, w=4,",
"ax=None): fig, ax = pca_plot_base(pca, clusters, pc1=pc1, pc2=pc2, marker=marker, labels=labels, s=s, w=w, h=h,",
"# c = cids[i] # # #print('Label {}'.format(l)) # idx2 = np.where(clusters['Cluster'] !=",
"h=h) # if norm is None and exp.min() < 0: #norm = matplotlib.colors.Normalize(vmin=-3,",
"bin_edges, binnumber = binned_statistic(exp, exp, bins=bins) print(binnumber.min(), binnumber.max()) iw = w * 300",
"interp1d(points[hull.vertices, 1], points[hull.vertices, 0], kind='cubic') # # xt = np.linspace(x.min(), x.max(), 100, endpoint=True)",
"ids, gene_names = get_gene_names(data) gene_ids = get_gene_ids(data, genes, ids=ids, gene_names=gene_names) for i in",
"avg[idx].sum(), (y * avg[idx]).sum() / avg[idx].sum()] d = np.array([distance.euclidean(centroid, (a, b)) for a,",
"fig, ax = libplot.new_fig(w, h) is_first = True base_expr_plot(data, exp, dim=dim, s=s, marker=marker,",
"tsne.iloc[idx2, 1] # # libplot.scatter(x, y, c=BACKGROUND_SAMPLE_COLOR, ax=ax) # # # Plot cluster",
"GRAY_PURPLE_YELLOW_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list( 'grey_purple_yellow', ['#e6e6e6', '#3333ff', '#ff33ff', '#ffe066']) GYBLGRYL_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list( 'grey_blue_green_yellow', ['#e6e6e6',",
"c = centroids(tsne, clusters) A = kneighbors_graph(c, 5, mode='distance', metric='euclidean').toarray() G = nx.from_numpy_matrix(A)",
"genes = pd.read_csv('../../../../expression_genes.txt', header=0) mkdir('a') a_barcodes = pd.read_csv('../a_barcodes.tsv', header=0, sep='\\t') idx = np.where(counts.columns.isin(a_barcodes['Barcode'].values))[0]",
"# if id does not exist, try the gene names idx = np.where(gene_names",
"same number of elements as data has rows. d1 : int, optional First",
"= interp1d(points[hull.vertices, 1], points[hull.vertices, 0], kind='cubic') # # xt = np.linspace(x.min(), x.max(), 100,",
"# prefix = '' # # ax.set_title('{}{} ({:,})'.format(prefix, cluster, len(idx1)), color=color) # #",
"% genome) except KeyError: raise Exception(\"File is missing one or more required datasets.\")",
"np.where(clusters['Cluster'] == cluster)[0] # idx2 = np.where(clusters['Cluster'] != cluster)[0] # # # Plot",
"(usually 1) d2 : int, optional Second dimension being plotted (usually 2) fig",
"for i in range(0, c.shape[0]): labels[i] = i + 1 #nx.draw_networkx(G, pos=pos, with_labels=False,",
"Matplotlib figure used to make the plot \"\"\" if cluster_order is None: ids",
"obj=gbm.matrix.indptr) f.create_carray(group, 'shape', obj=gbm.matrix.shape) except: raise Exception(\"Failed to write H5 file.\") def subsample_matrix(gbm,",
"Plot cluster over the top of the background x = tsne.iloc[idx1, 0] y",
"def centroids(tsne, clusters): cids = list(sorted(set(clusters['Cluster'].tolist()))) ret = np.zeros((len(cids), 2)) for i in",
"marker=marker, alpha=libplot.ALPHA, label=label) if labels: l = pca.index.values for i in range(0, pca.shape[0]):",
"1 sd of centroid idx = np.where(abs(z) < sdmax)[0] # (d > x1)",
"# plt.cm.plasma): \"\"\" Creates and saves a presentation tsne plot \"\"\" if out",
"def read_clusters(file): print('Reading clusters from {}...'.format(file)) return pd.read_csv(file, sep='\\t', header=0, index_col=0) def silhouette(tsne,",
"| (b < 255) #(r > 0) & (r == g) & (r",
": Matplotlib figure A new Matplotlib figure used to make the plot ax",
"barcodes = list(f['matrix']['barcodes'][:]) matrix = sp_sparse.csc_matrix( (f['matrix']['data'], f['matrix']['indices'], f['matrix']['indptr']), shape=f['matrix']['shape']) return GeneBCMatrix(feature_ids, feature_names,",
"pca.shape[0]): print(pca.shape, pca.iloc[i, pc1 - 1], pca.iloc[i, pc2 - 1]) ax.text(pca.iloc[i, pc1 -",
"= 'black' # # libplot.scatter(x, y, c=color, ax=ax) # # if add_titles: #",
"# #set_tsne_ax_lim(tsne, ax) # # return fig # # # def create_tsne_cluster_sample_grid(tsne, clusters,",
"def get_expression(gbm, gene_name, genes=None): if genes is None: genes = gbm.gene_names gene_indices =",
"ax=ax, cmap=cmap, out=out) def separate_cluster(tsne, clusters, cluster, color='black', background=BACKGROUND_SAMPLE_COLOR, bgedgecolor='#808080', show_background=True, add_titles=True, size=4,",
"if ax is None: fig, ax = libplot.new_fig(size, size) #print('Label {}'.format(l)) idx1 =",
"clip=None): d = umi_norm_log2(data) return scale(d, clip=clip) def read_clusters(file): print('Reading clusters from {}...'.format(file))",
"ax=ax) # if colorbar or is_first: if colorbar: libplot.add_colorbar(fig, cmap, norm=norm) #libcluster.format_simple_axes(ax, title=t)",
"print(gene_ids) for i in range(0, len(gene_ids)): gene_id = gene_ids[i][1] gene = gene_ids[i][2] print(gene_id,",
"sklearn.preprocessing import RobustScaler from sklearn.preprocessing import MinMaxScaler from sklearn.metrics import silhouette_samples from sklearn.neighbors",
"get_gene_ids(data, genes, ids=None, gene_names=None): \"\"\" For a given gene list, get all of",
"color=color, size=w, s=s, linewidth=linewidth, add_titles=False, show_background=False) ax.set_xlim(xlim) ax.set_ylim(ylim) if not show_axes: libplot.invisible_axes(ax) legend_params",
"colors=None, edgecolors=EDGE_COLOR, linewidth=EDGE_WIDTH, dim1=0, dim2=1, w=8, h=8, alpha=ALPHA, # libplot.ALPHA, show_axes=True, legend=True, sort=True,",
"= colors[i] # else: # color = 'black' # # libplot.scatter(x, y, c=color,",
"BGY_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list( 'bgy', ['#003366', '#004d99', '#40bf80', '#ffe066', '#ffd633']) GRAY_PURPLE_YELLOW_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list( 'grey_purple_yellow',",
"'a_sample', dir='a') genes_expr(d_a, tsne_a, genes, prefix='a_BGY', cmap=BLUE_GREEN_YELLOW_CMAP, w=w, h=h, dir='a/GeneExp', format=format) fig, ax",
"libcluster.colors() return [colors[clusters['Cluster'][i] - 1] for i in range(0, clusters.shape[0])] # def network(tsne,",
"cluster_plot(d, clusters, dim1=dim1, dim2=dim2, markers=markers, colors=colors, s=s, w=w, h=h, cluster_order=cluster_order, show_axes=show_axes, legend=legend, sort=sort,",
"ids is None: ids, gene_names = get_gene_names(data) ret = [] for g in",
"< 255) & (b > 200) # # # d = im_data[np.where(grey_areas)] #",
"# enable if edges desired im1.paste(im2, (0, 0), im2) im1.save(out, 'png') def genes_expr_outline(data,",
"plot figure pc = 1 for c in cluster_order: i = c -",
"dim=[1, 2], cmap=None, marker='o', s=MARKER_SIZE, alpha=EXP_ALPHA, fig=None, ax=None, norm=None): # plt.cm.plasma): fig, ax",
"add titles to plots plot_order: list, optional List of cluster ids in the",
"# # if add_titles: # if isinstance(cluster, int): # prefix = 'C' #",
"is not supported by this function.' % version) else: raise ValueError( 'Matrix HDF5",
"= data # .tolist() return cluster_map, labels def umi_tpm(data): # each column is",
"DataFrame Clusters in colors : list, color Colors of points add_titles : bool",
"= base_tsne_plot(tsne, marker=marker, c=c, s=s, label=label, fig=fig, ax=ax) #libtsne.tsne_legend(ax, labels, colors) libcluster.format_simple_axes(ax, title=\"t-SNE\")",
"linewidth=linewidth, edgecolors=edgecolors, ax=ax) tmp = 'tmp{}.png'.format(bin) libplot.savefig(fig, tmp, pad=0) plt.close(fig) im = imagelib.open(tmp)",
"ax=None, norm=None): # plt.cm.plasma): out = 'pca_expr_{}_t{}_vs_t{}.pdf'.format(name, 1, 2) fig, ax = base_pca_expr_plot(data,",
"# x2=None, # cmap=BLUE_YELLOW_CMAP, # marker='o', # s=MARKER_SIZE, # alpha=EXP_ALPHA, # out=None, #",
"samples, colors=None, size=SUBPLOT_SIZE): # \"\"\" # Plot each cluster separately to highlight samples",
"tables import pandas as pd from sklearn.manifold import TSNE import sklearn.preprocessing from sklearn.preprocessing",
"tsne, clusters.iloc[:, 0].tolist(), metric='euclidean') x2 = silhouette_samples( tsne_umi_log2, clusters.iloc[:, 0].tolist(), metric='euclidean') fig, ax",
"def umi_norm_log2(data): d = umi_norm(data) print(type(d)) return umi_log2(d) def scale(d, clip=None, min=None, max=None,",
"< -3] = -3 #e[e > 3] = 3 ax.scatter(x, y, c=e, s=s,",
"try the gene names idx = np.where(gene_names == g)[0] if idx.size > 0:",
"font_color='white', font_family='Arial') libplot.format_axes(ax) libplot.savefig(fig, '{}_centroid_network.pdf'.format(name)) def centroids(tsne, clusters): cids = list(sorted(set(clusters['Cluster'].tolist()))) ret =",
"1 if i < len(colors): # colors[cid - 1] #colors[i] #np.where(clusters['Cluster'] == cluster)[0]]",
"color Colors of points add_titles : bool Whether to add titles to plots",
"'#003380', '#2ca05a', '#ffd42a', '#ffdd55']) BGY_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list( 'bgy', ['#003366', '#004d99', '#40bf80', '#ffe066', '#ffd633'])",
"color.mean() # # #print(x[i], y[i], mean) # # #if mean > 0.5: #",
"cluster ids in the order they should be rendered Returns ------- fig :",
"norm = matplotlib.colors.Normalize(vmin=-3, vmax=3, clip=True) #cmap = plt.cm.plasma ids, gene_names = get_gene_names(data) exp",
"d1[d1 >= 0].quantile(TNSE_AX_Q)] ylim = [d2[d2 < 0].quantile(1 - TNSE_AX_Q), d2[d2 >= 0].quantile(TNSE_AX_Q)]",
"'#40bf80', '#ffe066', '#ffd633']) GRAY_PURPLE_YELLOW_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list( 'grey_purple_yellow', ['#e6e6e6', '#3333ff', '#ff33ff', '#ffe066']) GYBLGRYL_CMAP =",
"figure A new Matplotlib figure used to make the plot \"\"\" if cluster_order",
"if out is not None: libplot.savefig(fig, out) return fig, ax def create_cluster_plot(d, clusters,",
"l = x.shape[0] elif type(x) is pd.core.frame.DataFrame: l = x.shape[0] else: return None",
"pandas dataframe (dense) Parameters ---------- gbm : a GeneBCMatrix Returns ------- object :",
"len(x2))}) libplot.boxplot(df2, 'Cluster', 'Silhouette Score', colors=libcluster.colors(), ax=ax) ax.set_ylim([-1, 1]) ax.set_title('tsne-ah') libplot.savefig(fig, '{}_silhouette.pdf'.format(name)) def",
"i in range(0, len(cluster_order)): print('index', i, cluster_order[i]) cluster = cluster_order[i] if isinstance(colors, dict):",
"the same number of elements as data has rows. d1 : int, optional",
"gene_names=gene_names) ax = libplot.new_ax(fig, rows, cols, i + 1) expr_plot(tsne, exp, ax=ax, cmap=cmap,",
"# ax.set_title('{}{} ({:,})'.format(prefix, cluster, len(idx1)), color=color) # # # libplot.invisible_axes(ax) pc += 1",
"name, k=5): # A = kneighbors_graph(tsne, k, mode='distance', metric='euclidean').toarray() # # #A =",
"bin + 1 idx_bin = np.where(binnumber == bi)[0] idx_other = np.where(binnumber != bi)[0]",
"vmax=3, clip=True) #cmap = plt.cm.plasma ids, gene_names = get_gene_names(data) print(ids, gene_names, genes) gene_ids",
"libplot.savefig(fig, out, pad=0) plt.close(fig) im1 = Image.open('tmp.png') # Edge detect on what is",
"columns=['Cluster']) return df def create_cluster_samples(tsne_umi_log2, clusters, sample_names, name, method='tsne', format='png', dir='.', w=16, h=16,",
"100 overlaps.append(o) df = pd.DataFrame( {'Cluster': list(range(1, c1.shape[0] + 1)), 'Overlap %': overlaps})",
"formatting \"\"\" if ax is None: fig, ax = libplot.new_fig() libplot.scatter(tsne['TSNE-1'], tsne['TSNE-2'], c=c,",
"np.median(reads_per_bc) scaling_factors = median_reads_per_bc / reads_per_bc scaled = data.multiply(scaling_factors) # , axis=1) return",
"one is created. ax : matplotlib ax, optional Supply an axis object on",
"im_base = imagelib.new(iw, iw) for bin in range(0, bins): bi = bin +",
"exp, dim=dim, cmap=cmap, marker=marker, s=s, alpha=alpha, fig=fig, w=w, h=h, ax=ax, show_axes=show_axes, colorbar=colorbar, norm=norm,",
"expression plot. # # Parameters # ---------- # data : pandas.DataFrame # t-sne",
"norm(e[i]) # color = cmap(int(en * cmap.N)) # color = np.array(color) # #",
"Pandas dataframe Cells x tsne tsne data. Columns should be labeled 'TSNE-1', 'TSNE-2'",
"idx_bin = np.where(binnumber == bi)[0] idx_other = np.where(binnumber != bi)[0] tsne_other = tsne.iloc[idx_other,",
"tmp) plt.close(fig) # Open image # im = imagelib.open(tmp) # im_no_bg = imagelib.remove_background(im)",
"& (b < 255) & (b > 200) # # d = im_data[np.where(grey_areas)]",
"np.array(im1.convert('RGBA')) # # r = im_data[:, :, 0] # g = im_data[:, :,",
"'tmp{}.png'.format(i) libplot.savefig(fig, tmp) plt.close(fig) # Open image # im = imagelib.open(tmp) # im_no_bg",
"must have the same number of elements as data has rows. d1 :",
"idx = np.where(abs(z) < sdmax)[0] # (d > x1) & (d < x2))[0]",
"for i in range(0, len(cluster_order)): print('index', i, cluster_order[i]) cluster = cluster_order[i] if isinstance(colors,",
"format) print('Creating', out, '...') libplot.savefig(fig, out) libplot.savefig(fig, 'tmp.png') plt.close(fig) def cluster_grid(tsne, clusters, colors=None,",
"else: d_a = umi_norm_log2_scale(d_a) pca_a = libtsne.load_pca(d_a, 'a', cache=cache) # pca.iloc[idx,:] tsne_a =",
"# # # #edges1 = feature.canny(rgb2gray(im_data)) # # #print(edges1.shape) # # #skimage.io.imsave('tmp_canny_{}.png'.format(bin), edges1)",
": list, color Colors of points add_titles : bool Whether to add titles",
"'indices', obj=gbm.matrix.indices) f.create_carray(group, 'indptr', obj=gbm.matrix.indptr) f.create_carray(group, 'shape', obj=gbm.matrix.shape) except: raise Exception(\"Failed to write",
"= pd.DataFrame({'Silhouette Score': x2, 'Cluster': clusters.iloc[:, 0].tolist( ), 'Label': np.repeat('tsne-ah', len(x2))}) libplot.boxplot(df2, 'Cluster',",
"from sklearn.neighbors import kneighbors_graph from scipy.interpolate import griddata import h5py from scipy.interpolate import",
"ids=ids, gene_names=gene_names) ax = libplot.new_ax(fig, rows, cols, i + 1) expr_plot(tsne, exp, ax=ax,",
"subplot=211) df = pd.DataFrame({'Silhouette Score': x1, 'Cluster': clusters.iloc[:, 0].tolist( ), 'Label': np.repeat('tsne-10x', len(x1))})",
"# # if out is not None: # libplot.savefig(fig, out, pad=0) # #",
"to highlight samples # # Parameters # ---------- # tsne : Pandas dataframe",
"sklearn.preprocessing.scale(d, axis=axis) #sd = sd.T if isinstance(clip, float) or isinstance(clip, int): max =",
"& (g == b) # # #d = im_data[np.where(black_areas)] # #d[:, 0:3] =",
"os.path.exists(dir): mkdir(dir) if index is None: index = data.index if isinstance(genes, pd.core.frame.DataFrame): genes",
"= np.array(list(range(0, len(ids)))) if colors is None: colors = libcluster.get_colors() for i in",
"G=nx.from_numpy_matrix(A) # pos=nx.spring_layout(G) #, k=2) # # #node_color = (c_phen['Cluster'][0:A.shape[0]] - 1).tolist() #",
"tpm(gbm): m = gbm.matrix s = 1 / m.sum(axis=0) mn = m.multiply(s) tpm",
"#black_areas = (a > 0) #(r < 255) | (g < 255) |",
"= '-{}'.format(c) print(id) print(np.where(d.index.str.contains(id))[0]) sc[np.where(d.index.str.contains(id))[0]] = s c += 1 print(np.unique(d.index.values)) print(np.unique(sc)) df",
"pc1 - 1], pca.iloc[i, pc2 - 1]) ax.text(pca.iloc[i, pc1 - 1], pca.iloc[i, pc2",
"return expr_plot(tsne, exp, fig=fig, ax=ax, cmap=cmap, out=out) def separate_cluster(tsne, clusters, cluster, color='black', background=BACKGROUND_SAMPLE_COLOR,",
"labels = {} for i in range(0, c.shape[0]): labels[i] = i + 1",
"height of new ax. Returns ------- fig : Matplotlib figure A new Matplotlib",
"For a given gene list, get all of the transcripts. Parameters ---------- data",
"from sklearn.preprocessing import RobustScaler from sklearn.preprocessing import MinMaxScaler from sklearn.metrics import silhouette_samples from",
"axis object on which to render the plot, otherwise a new one is",
"create_merge_cluster_info(d_b, c_b, 'b', sample_names=samples, dir='b') create_cluster_samples(tsne_b, c_b, samples, 'b_sample', dir='b') genes_expr(d_b, tsne_b, genes,",
"& (b > 200) # # d = im_data[np.where(grey_areas)] # d[:, :] =",
"0.98) #(0.8, 0.8, 0.8) #(0.85, 0.85, 0.85 BACKGROUND_SAMPLE_COLOR = [0.75, 0.75, 0.75] EDGE_COLOR",
"a figure object on which to render the plot, otherwise a new one",
"= np.where(genes == gene_name)[0] if len(gene_indices) == 0: raise Exception(\"%s was not found",
"if out is not None: libplot.savefig(fig, out, pad=0) return fig, ax def base_pca_expr_plot(data,",
"base_pca_expr_plot(data, exp, dim=[1, 2], cmap=None, marker='o', s=MARKER_SIZE, alpha=EXP_ALPHA, fig=None, ax=None, norm=None): # plt.cm.plasma):",
"on what is left (the clusters) imageWithEdges = im1.filter(ImageFilter.FIND_EDGES) im_data = np.array(imageWithEdges.convert('RGBA')) #r",
"sep='\\t') def mkdir(path): \"\"\" Make dirs including any parents and avoid raising exception",
"linewidth=linewidth, add_titles=False, show_background=False) ax.set_xlim(xlim) ax.set_ylim(ylim) if not show_axes: libplot.invisible_axes(ax) legend_params = dict(LEGEND_PARAMS) if",
"colors=None, edgecolors=EDGE_COLOR, linewidth=EDGE_WIDTH, dim1=0, dim2=1, w=8, alpha=ALPHA, # libplot.ALPHA, show_axes=True, legend=True, sort=True, outline=True):",
"5, mode='distance', metric='euclidean').toarray() G = nx.from_numpy_matrix(A) pos = nx.spring_layout(G) fig, ax = libplot.newfig(w=8,",
"rows, cols = expr_grid_size(gene_ids, size=size) fig = libplot.new_base_fig(w=w, h=h) for i in range(0,",
"= points[hull.vertices, 1] xp = np.append(xp, xp[0]) yp = np.append(yp, yp[0]) ax.plot(xp, yp,",
"# libplot.invisible_axes(ax) pc += 1 return fig def create_cluster_grid(tsne, clusters, name, colors=None, cols=-1,",
"array expression values for each data point so it must have the same",
"g)[0] for index in indexes: ret.append((index, ids[index], gene_names[index])) return ret def get_gene_data(data, g,",
"np.array(color) # # c1 = color.copy() # c1[-1] = 0.5 # # #print(c1)",
"or not cache: print('{} was not found, creating it with...'.format(file)) # Find the",
"min=None, max=None, axis=1): if isinstance(d, SparseDataFrame): print('UMI norm log2 scale sparse') sd =",
"id = '-{}'.format(c) print(id) print(np.where(d.index.str.contains(id))[0]) sc[np.where(d.index.str.contains(id))[0]] = s c += 1 print(np.unique(d.index.values)) print(np.unique(sc))",
"isinstance(min, float) or isinstance(min, int): print('z min', min) sd[np.where(sd < min)] = min",
"= 1 # fx = interp1d(points[hull.vertices, 0], points[hull.vertices, 1], kind='cubic') # fy =",
"try: dsets = {} print(f.list_nodes('/')) for node in f.walk_nodes('/' + genome, 'Array'): dsets[node.name]",
"# # grey_areas = (r < 255) & (r > 200) & (g",
"pca_plot_base(pca, clusters, pc1=1, pc2=2, marker='o', labels=False, s=MARKER_SIZE, w=8, h=8, fig=None, ax=None): colors =",
"edgecolors, linewidth=linewidth, s=s) if add_titles: if isinstance(cluster, int): prefix = 'C' else: prefix",
":, 3] # (r < 255) | (g < 255) | (b <",
"method='tsne', format='png', dir='.', w=16, h=16, legend=True): sc = sample_clusters(clusters, sample_names) create_cluster_plot(tsne_umi_log2, sc, name,",
"original image to highlight cluster # enable if edges desired im1.paste(im2, (0, 0),",
"= [d2[d2 < 0].quantile(1 - TNSE_AX_Q), d2[d2 >= 0].quantile(TNSE_AX_Q)] #print(xlim, ylim) # ax.set_xlim(xlim)",
"# # libplot.savefig(fig, 'network_{}.pdf'.format(name)) def plot_centroids(tsne, clusters, name): c = centroids(tsne, clusters) fig,",
"ny) x = x[idx] y = y[idx] #centroid = [x.sum() / x.size, y.sum()",
"min) sd[np.where(sd < min)] = min if isinstance(max, float) or isinstance(max, int): print('z",
"norm log2 scale sparse') sd = StandardScaler(with_mean=False).fit_transform(d.T.matrix) return SparseDataFrame(sd.T, index=d.index, columns=d.columns) else: #",
"= get_gene_names(data) gene_ids = get_gene_ids(data, genes, ids=ids, gene_names=gene_names) for i in range(0, len(gene_ids)):",
"cmap=plt.cm.plasma, out=None): \"\"\" Plot multiple genes on a grid. Parameters ---------- data :",
"ids=None, gene_names=None): if ids is None: ids, gene_names = get_gene_names(data) if isinstance(g, list):",
"< min)] = min if isinstance(max, float) or isinstance(max, int): print('z max', max)",
"# ax.scatter(x[i], # y[i], # c=[c1], # s=s, # marker=marker, # edgecolors='none', #edgecolors,",
"else: return None cols = int(np.ceil(np.sqrt(l))) w = size * cols rows =",
"x.shape[0] else: return None cols = int(np.ceil(np.sqrt(l))) w = size * cols rows",
"y, c=e, s=s, marker=marker, alpha=alpha, cmap=cmap, norm=norm, edgecolors='none', # edgecolors, linewidth=linewidth) # for",
"add_titles=False) # get x y lim xlim = ax.get_xlim() ylim = ax.get_ylim() fig,",
"legend=True, sort=True, outline=True): cluster_order = list(sorted(set(clusters['Cluster']))) im_base = imagelib.new(w * 300, w *",
"for T-SNE/2D space reduced representation of data. Parameters ---------- data : Pandas dataframe",
"decode(barcodes), matrix) def save_matrix_to_h5(gbm, filename, genome): flt = tables.Filters(complevel=1) with tables.open_file(filename, 'w', filters=flt)",
"ax = libplot.newfig(w=9, h=7, subplot=211) df = pd.DataFrame({'Silhouette Score': x1, 'Cluster': clusters.iloc[:, 0].tolist(",
"ret.append((index, ids[index], gene_names[index])) return ret def get_gene_data(data, g, ids=None, gene_names=None): if ids is",
"im_outline, inplace=True) # # find gray areas and mask # im_data = np.array(im1.convert('RGBA'))",
"as np import scipy.sparse as sp_sparse import tables import pandas as pd from",
"import distance import networkx as nx import os import phenograph import libplot import",
"colors[cid - 1] #colors[i] #np.where(clusters['Cluster'] == cluster)[0]] color = colors[i] else: color =",
"otherwise a new one is created. ax : matplotlib ax, optional Supply an",
"= None # [0.3, 0.3, 0.3] #'#4d4d4d' EDGE_WIDTH = 0 # 0.25 ALPHA",
"pca_plot(pca, clusters, pc1=pc1, pc2=pc2, labels=labels, marker=marker, legend=legend, s=s, w=w, h=h, fig=fig, ax=ax) libplot.savefig(fig,",
"f.create_carray(group, 'barcodes', obj=gbm.barcodes) f.create_carray(group, 'data', obj=gbm.matrix.data) f.create_carray(group, 'indices', obj=gbm.matrix.indices) f.create_carray(group, 'indptr', obj=gbm.matrix.indptr) f.create_carray(group,",
"exp = get_gene_data(data, gene) return expr_plot(tsne, exp, fig=fig, ax=ax, cmap=cmap, out=out) def separate_cluster(tsne,",
"# \"\"\" # # fig, ax = expr_plot(tsne, # exp, # t='TSNE', #",
"for i in range(0, pca.shape[1]): for j in range(i + 1, pca.shape[1]): create_cluster_plot(pca,",
"if isinstance(cluster, int): # prefix = 'C' # else: # prefix = ''",
"ax=ax) ax.set_ylim([-1, 1]) ax.set_title('tsne-ah') libplot.savefig(fig, '{}_silhouette.pdf'.format(name)) def node_color_from_cluster(clusters): colors = libcluster.colors() return [colors[clusters['Cluster'][i]",
"0.5: # ax.scatter(x[i], # y[i], # c='#ffffff00', # s=s, # marker=marker, # norm=norm,",
"genome): with h5py.File(filename, 'r') as f: if u'version' in f.attrs: if f.attrs['version'] >",
"= np.where(clusters['Cluster'] != cluster)[0] # Plot background points if show_background: x = tsne.iloc[idx2,",
"None: colors = libcluster.get_colors() for i in indices: print('index', i) cluster = ids[i]",
"get_gene_names(data) if isinstance(g, list): g = np.array(g) if isinstance(g, np.ndarray): idx = np.where(np.isin(ids,",
"points[hull.vertices, 0] yp = points[hull.vertices, 1] xp = np.append(xp, xp[0]) yp = np.append(yp,",
"== cluster)[0] # idx2 = np.where(clusters['Cluster'] != cluster)[0] # # # Plot background",
"fig=None, ax=None): \"\"\" Create a tsne plot without the formatting Parameters ---------- d",
"= pd.DataFrame( {'Cluster': list(range(1, c1.shape[0] + 1)), 'Overlap %': overlaps}) df.set_index('Cluster', inplace=True) df.to_csv('{}_cluster_overlaps.txt'.format(name),",
"Parameters ---------- data : Pandas dataframe Genes x samples expression matrix tsne :",
"indexes = np.where(ids == g)[0] if indexes.size > 0: for index in indexes:",
"type='tsne', format='pdf'): \"\"\" Plot each cluster into its own plot file. \"\"\" ids",
"ids ids : Index, optional Index of gene ids gene_names : Index, optional",
"cols = expr_grid_size(gene_ids, size=size) fig = libplot.new_base_fig(w=w, h=h) for i in range(0, len(gene_ids)):",
"figure, optional Supply a figure object on which to render the plot, otherwise",
"marker=marker, alpha=alpha, cmap=cmap, norm=norm, edgecolors='none', # edgecolors, linewidth=linewidth) # for i in range(0,",
"None: out = '{}_expr.pdf'.format(method) fig, ax = expr_plot(tsne, exp, dim=dim, cmap=cmap, marker=marker, s=s,",
"for c in cluster_order: i = c - 1 cluster = ids[i] #",
"['#162d50', '#afc6e9']) BLUE_GREEN_YELLOW_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list( 'bgy', ['#162d50', '#214478', '#217844', '#ffcc00', '#ffdd55']) # BGY_CMAP",
"alpha=1, w=libplot.DEFAULT_WIDTH, h=libplot.DEFAULT_HEIGHT, fig=None, ax=None, norm=None): # plt.cm.plasma): \"\"\" Base function for creating",
"int): prefix = 'C' else: prefix = '' ax.set_title('{}{} ({:,})'.format( prefix, cluster, len(idx1)),",
"if isinstance(data, SparseDataFrame): return data[idx, :].to_array() else: return data.iloc[idx, :].values def gene_expr_grid(data, tsne,",
"# libplot.savefig(fig, '{}/tsne_{}_sample_clusters.png'.format(dir, name)) # #libplot.savefig(fig, '{}/tsne_{}separate_clusters.pdf'.format(dir, name)) # # def load_clusters(pca, headers,",
"'#ffff00']) # BGY_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list('bgy', ['#00264d', '#003366', '#339933', '#e6e600', '#ffff33']) # BGY_CMAP =",
"pc1=1, pc2=2, marker='o', labels=False, legend=True, s=MARKER_SIZE, w=8, h=8, fig=None, ax=None, dir='.', format='png'): out",
"s=s, colorbar=colorbar, norm=norm, alpha=alpha, linewidth=linewidth, edgecolors=edgecolors, ax=ax) tmp = 'tmp{}.png'.format(bin) libplot.savefig(fig, tmp, pad=0)",
"(a, b)) for a, b in zip(x, y)]) sd = d.std() m =",
"im_edges = im2.filter(ImageFilter.FIND_EDGES) # # im_smooth = im_edges.filter(ImageFilter.SMOOTH) # # # paste outline",
"#colors[i] #np.where(clusters['Cluster'] == cluster)[0]] color = colors[i] else: color = 'black' else: color",
"to plots plot_order: list, optional List of cluster ids in the order they",
"# # fig = libplot.new_base_fig(w=w, h=w) # # if colors is None: #",
"e.std() # limit to 3 std for z-scores #e[e < -3] = -3",
"if cluster_order is None: ids = np.array(list(sorted(set(clusters['Cluster'])))) cluster_order = np.array(list(range(0, len(ids)))) + 1",
"def subsample_matrix(gbm, barcode_indices): return GeneBCMatrix(gbm.gene_ids, gbm.gene_names, gbm.barcodes[barcode_indices], gbm.matrix[:, barcode_indices]) def get_expression(gbm, gene_name, genes=None):",
"each column is a cell reads_per_bc = data.sum(axis=0) # int(np.round(np.median(reads_per_bc))) median_reads_per_bc = np.median(reads_per_bc)",
"one is created. norm : Normalize, optional Specify how colors should be normalized",
"0.3] #'#4d4d4d' EDGE_WIDTH = 0 # 0.25 ALPHA = 0.9 BLUE_YELLOW_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list(",
"= 0 # # for sample in samples: # id = '-{}'.format(sid +",
"x = tsne.iloc[np.where(clusters['Cluster'] == c)[0], :] centroid = (x.sum(axis=0) / x.shape[0]).tolist() ret[i, 0]",
"#libcluster.format_axes(ax, title=t) return fig, ax def expr_plot(data, exp, dim=[1, 2], cmap=plt.cm.magma, marker='o', s=MARKER_SIZE,",
"create_pca_plot(pca, clusters, name, pc1=1, pc2=2, marker='o', labels=False, legend=True, s=MARKER_SIZE, w=8, h=8, fig=None, ax=None,",
"scaled def umi_norm_log2(data): d = umi_norm(data) print(type(d)) return umi_log2(d) def scale(d, clip=None, min=None,",
"= data[:, :, 2] a = im_data[:, :, 3] # (r < 255)",
"= '{}/pca_{}_pc{}_vs_pc{}.{}'.format(dir, name, pc1, pc2, format) fig, ax = pca_plot(pca, clusters, pc1=pc1, pc2=pc2,",
"= data[:, :, 0] #g = data[:, :, 1] #b = data[:, :,",
"'a', dir='a') create_merge_cluster_info(d_a, c_a, 'a', sample_names=samples, dir='a') create_cluster_samples(tsne_a, c_a, samples, 'a_sample', dir='a') genes_expr(d_a,",
"cids = list(sorted(set(clusters['Cluster'].tolist()))) ret = np.zeros((len(cids), 2)) for i in range(0, len(cids)): c",
"(g < 255) & (g > 200) & (b < 255) & (b",
"umi_norm(data): \"\"\" Scale each library to its median size Parameters ---------- data :",
"# s=MARKER_SIZE, # alpha=EXP_ALPHA, # out=None, # fig=None, # ax=None, # norm=None, #",
"of the background x = tsne.iloc[idx1, 0] y = tsne.iloc[idx1, 1] #print('sep', cluster,",
"gene_indices = np.where(genes == gene_name)[0] if len(gene_indices) == 0: raise Exception(\"%s was not",
"missing one or more required datasets.\") #GeneBCMatrix = collections.namedtuple('FeatureBCMatrix', ['feature_ids', 'feature_names', 'barcodes', 'matrix'])",
"except: pass def split_a_b(counts, samples, w=6, h=6, format='pdf'): \"\"\" Split cells into a",
"# nx.draw_networkx(G, pos=pos, with_labels=False, ax=ax, node_size=50, node_color=node_color, vmax=(clusters['Cluster'].max() - 1), cmap=libcluster.colormap()) # #",
"d1=d1, # d2=d2, # x1=x1, # x2=x2, # cmap=cmap, # marker=marker, # s=s,",
"tables.Filters(complevel=1) with tables.open_file(filename, 'w', filters=flt) as f: try: group = f.create_group(f.root, genome) f.create_carray(group,",
"markers=markers, alpha=alpha, s=s, ax=ax, cluster_order=cluster_order, sort=sort) #set_tsne_ax_lim(tsne, ax) # libcluster.format_axes(ax) if not show_axes:",
"+ 1), pc2=(j + 1), marker=marker, s=s) def pca_base_plots(pca, clusters, n=10, marker='o', s=MARKER_SIZE):",
"RobustScaler from sklearn.preprocessing import MinMaxScaler from sklearn.metrics import silhouette_samples from sklearn.neighbors import kneighbors_graph",
"file = libtsne.get_cluster_file(name) if not os.path.isfile(file) or not cache: print('{} was not found,",
"'#217844', '#ffcc00', '#ffdd55']) # BGY_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list('bgy', ['#002255', '#2ca05a', '#ffd42a']) # BGY_CMAP =",
"xt = np.linspace(x.min(), x.max(), 100, endpoint=True) # yt = np.linspace(y.min(), y.max(), 100, endpoint=True)",
"ids[i] #print('Label {}'.format(l)) indices = np.where(clusters['Cluster'] == l)[0] n = len(indices) label =",
"'{}/tsne_{}separate_clusters.pdf'.format(dir, name)) # # # def tsne_cluster_sample_grid(tsne, clusters, samples, colors=None, size=SUBPLOT_SIZE): # \"\"\"",
"file format version (%d) is an newer version that is not supported by",
"sep='\\t') idx = np.where(counts.columns.isin(b_barcodes['Barcode'].values))[0] d_b = counts.iloc[:, idx] d_b = libcluster.remove_empty_rows(d_b) if isinstance(d_a,",
"Pandas dataframe # Cells x tsne tsne data. Columns should be labeled 'TSNE-1',",
"Whether to add titles to plots w: int, optional width of new ax.",
"label=label) if labels: l = pca.index.values for i in range(0, pca.shape[0]): print(pca.shape, pca.iloc[i,",
"idx] d_a = libcluster.remove_empty_rows(d_a) if isinstance(d_a, SparseDataFrame): d_a = umi_norm_log2(d_a) else: d_a =",
"# else: # prefix = '' # # ax.set_title('{}{} ({:,})'.format(prefix, cluster, len(idx1)), color=color)",
"= im_edges.filter(ImageFilter.SMOOTH) # im_smooth.save('edges.png', 'png') # # im2.paste(im_smooth, (0, 0), im_smooth) # #",
"y, c=colors[sid], ax=ax) # # sid += 1 # # ax.set_title('C{} ({:,})'.format(c, len(idx1)),",
"#(r < 255) | (g < 255) | (b < 255) #(r >",
"= exp[idx] # if (e.min() == 0): #print('Data does not appear to be",
"cids = list(sorted(set(clusters['Cluster']))) # # rows = int(np.ceil(np.sqrt(len(cids)))) # # w = size",
">= 0].quantile(TNSE_AX_Q)] ylim = [d2[d2 < 0].quantile(1 - TNSE_AX_Q), d2[d2 >= 0].quantile(TNSE_AX_Q)] #print(xlim,",
"prefix='', index=None, dir='GeneExp', cmap=BGY_CMAP, norm=None, w=6, s=30, alpha=1, linewidth=EDGE_WIDTH, edgecolors='none', colorbar=True, method='tsne', bins=10,",
"gene_ids[i][1] gene = gene_ids[i][2] print(gene_id, gene) exp = get_gene_data(data, gene_id, ids=ids, gene_names=gene_names) #fig,",
"cluster_grid(tsne, clusters, colors=None, cols=-1, size=SUBPLOT_SIZE, add_titles=True, cluster_order=None): \"\"\" Plot each cluster separately to",
"show_axes: libplot.invisible_axes(ax) return fig, ax # def expr_plot(tsne, # exp, # d1=1, #",
"values always appear on top idx = np.argsort(exp) #np.argsort(abs(exp)) # np.argsort(exp) x =",
"k, mode='distance', metric='euclidean').toarray() overlaps = [] for i in range(0, c1.shape[0]): ids1 =",
"return fig, ax def base_cluster_plot_outline(out, d, clusters, s=libplot.MARKER_SIZE, colors=None, edgecolors=EDGE_COLOR, linewidth=EDGE_WIDTH, dim1=0, dim2=1,",
"[255, 255, 255, 0] # im_data[np.where(grey_areas)] = d # # im2 = Image.fromarray(im_data)",
"cmap=libcluster.colormap()) nx.draw_networkx(G, with_labels=True, labels=labels, ax=ax, node_size=800, node_color=node_color, font_color='white', font_family='Arial') libplot.format_axes(ax) libplot.savefig(fig, '{}_centroid_network.pdf'.format(name)) def",
"clusters from {}...'.format(file)) return pd.read_csv(file, sep='\\t', header=0, index_col=0) def silhouette(tsne, tsne_umi_log2, clusters, name):",
"subsample_matrix(gbm, barcode_indices): return GeneBCMatrix(gbm.gene_ids, gbm.gene_names, gbm.barcodes[barcode_indices], gbm.matrix[:, barcode_indices]) def get_expression(gbm, gene_name, genes=None): if",
"# l] else: color = 'black' ax.scatter(x, y, color=color, edgecolor=color, s=s, marker=marker, alpha=libplot.ALPHA,",
"+ 1)) # # x = tsne.iloc[idx2, 0] # y = tsne.iloc[idx2, 1]",
"idx2 = np.where(clusters['Cluster'] != cluster)[0] # # # Plot background points # #",
"interesting clusters labels, graph, Q = phenograph.cluster(pca, k=20) if min(labels) == -1: new_label",
"pd.DataFrame(RobustScaler().fit_transform(d.T).T, index=d.index, columns=d.columns) def umi_norm_log2_scale(data, clip=None): d = umi_norm_log2(data) return scale(d, clip=clip) def",
"= colors[i] # l] else: color = 'black' ax.scatter(x, y, color=color, edgecolor=color, s=s,",
"create_cluster_plot(tsne_b, c_b, 'b', dir='b') create_cluster_grid(tsne_b, c_b, 'b', dir='b') create_merge_cluster_info(d_b, c_b, 'b', sample_names=samples, dir='b')",
"0: return pd.DataFrame(RobustScaler().fit_transform(d), index=d.index, columns=d.columns) else: return pd.DataFrame(RobustScaler().fit_transform(d.T).T, index=d.index, columns=d.columns) def umi_norm_log2_scale(data, clip=None):",
"# plt.cm.plasma): fig, ax = base_expr_plot(data, exp, t='PC', dim=dim, cmap=cmap, marker=marker, s=s, fig=fig,",
"z-scored. Transforming now...') # zscore #e = (e - e.mean()) / e.std() #print(e.min(),",
"# # # paste outline onto clusters # im2.paste(im_smooth, (0, 0), im_smooth) #",
"int(np.ceil(np.sqrt(n))) rows = int(np.ceil(n / cols)) w = size * cols h =",
"# # G=nx.from_numpy_matrix(A) # pos=nx.spring_layout(G) #, k=2) # # #node_color = (c_phen['Cluster'][0:A.shape[0]] -",
"= separate_cluster(d, clusters, cluster, color=color, size=w, s=s, linewidth=linewidth, add_titles=False) # get x y",
"points[hull.vertices,1]) #zi = griddata((x, y), avg1, (xi, yi)) #ax.contour(xi, yi, z, levels=1) def",
"255) & (b > 200) # # # d = im_data[np.where(grey_areas)] # d[:,",
"b) & (g == b) black_areas = (a > 0) d = im_data[np.where(black_areas)]",
"gbm_to_df(gbm): return pd.DataFrame(gbm.matrix.todense(), index=gbm.gene_names, columns=gbm.barcodes) def get_barcode_counts(gbm): ret = [] for i in",
"show legend. \"\"\" if ax is None: fig, ax = libplot.new_fig(w=w, h=h) libcluster.scatter_clusters(d.iloc[:,",
"libcluster.colors() # # for i in range(0, len(cids)): # c = cids[i] #",
"= interp1d(points[hull.vertices, 0], points[hull.vertices, 1], kind='cubic') # fy = interp1d(points[hull.vertices, 1], points[hull.vertices, 0],",
"labels[np.where(labels == -1)] = new_label labels += 1 libtsne.write_clusters(headers, labels, name) cluster_map, data",
"node_color=node_color, font_color='white', font_family='Arial') libplot.format_axes(ax) libplot.savefig(fig, '{}_centroid_network.pdf'.format(name)) def centroids(tsne, clusters): cids = list(sorted(set(clusters['Cluster'].tolist()))) ret",
"k=5): # A = kneighbors_graph(tsne, k, mode='distance', metric='euclidean').toarray() # # #A = A[0:500,",
"print('Creating', out, '...') libplot.savefig(fig, out) libplot.savefig(fig, 'tmp.png') plt.close(fig) def cluster_grid(tsne, clusters, colors=None, cols=-1,",
"2], cmap=None, marker='o', s=MARKER_SIZE, alpha=EXP_ALPHA, fig=None, ax=None, w=libplot.DEFAULT_WIDTH, h=libplot.DEFAULT_HEIGHT, edgecolors=EDGE_COLOR, linewidth=EDGE_WIDTH, norm=None, method='tsne',",
"DataFrame data table containing and index genes : list List of strings of",
"points[hull.vertices, 0], kind='cubic') # # xt = np.linspace(x.min(), x.max(), 100, endpoint=True) # yt",
"smooth_edges(im1, im1) # # # Edge detect on what is left (the clusters)",
"bgedgecolor, linewidth=linewidth, s=s) #fig, ax = libplot.new_fig() #expr_plot(tsne, exp, ax=ax) #libplot.add_colorbar(fig, cmap) exp_bin",
"np.where(clusters['Cluster'] != c)[0] # # # Plot background points # # ax =",
"#libtsne.tsne_legend(ax, labels, colors) libcluster.format_simple_axes(ax, title=\"PC\") if legend: libcluster.format_legend(ax, cols=6, markerscale=2) return fig, ax",
"avg = (avg - avg.mean()) / avg.std() avg[avg < -1.5] = -1.5 avg[avg",
"by labelling cells by sample/batch. \"\"\" sc = np.array(['' for i in range(0,",
"metric='euclidean').toarray() # # #A = A[0:500, 0:500] # # G=nx.from_numpy_matrix(A) # pos=nx.spring_layout(G) #,",
"tmp, pad=0) plt.close(fig) im = imagelib.open(tmp) im_no_bg = imagelib.remove_background(im) im_edges = imagelib.edges(im_no_bg) im_smooth",
"tsne.iloc[idx1, 0] # y = tsne.iloc[idx1, 1] # # if isinstance(colors, dict): #",
"prefix='', dim=[1, 2], index=None, dir='GeneExp', cmap=BGY_CMAP, norm=None, w=4, h=4, s=30, alpha=ALPHA, linewidth=EDGE_WIDTH, edgecolors='none',",
"in f['matrix']['features']['name']] barcodes = list(f['matrix']['barcodes'][:]) matrix = sp_sparse.csc_matrix( (f['matrix']['data'], f['matrix']['indices'], f['matrix']['indptr']), shape=f['matrix']['shape']) return",
"imagelib TNSE_AX_Q = 0.999 MARKER_SIZE = 10 SUBPLOT_SIZE = 4 EXP_ALPHA = 0.8",
"fig=None, ax=None, w=libplot.DEFAULT_WIDTH, h=libplot.DEFAULT_HEIGHT, edgecolors=EDGE_COLOR, linewidth=EDGE_WIDTH, norm=None, method='tsne', show_axes=False, colorbar=True, out=None): # plt.cm.plasma):",
"matplotlib.colors.LinearSegmentedColormap.from_list('bgy', ['#00264d', '#003366', '#339933', '#e6e600', '#ffff33']) # BGY_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list('bgy', ['#003366', '#40bf80', '#ffff33'])",
"vmax=(c.shape[0] - 1), cmap=libcluster.colormap()) nx.draw_networkx(G, with_labels=True, labels=labels, ax=ax, node_size=800, node_color=node_color, font_color='white', font_family='Arial') libplot.format_axes(ax)",
"tsne_other = tsne.iloc[idx_other, :] fig, ax = libplot.new_fig(w, w) x = tsne_other.iloc[:, 0]",
"#avg[idx] #avg1[idx] = 1 # fx = interp1d(points[hull.vertices, 0], points[hull.vertices, 1], kind='cubic') #",
"color bar rows += 1 h = size * rows return w, h,",
"cache=cache) c_a = libtsne.load_phenograph_clusters(pca_a, 'a', cache=cache) create_pca_plot(pca_a, c_a, 'a', dir='a') create_cluster_plot(tsne_a, c_a, 'a',",
"#libcluster.format_simple_axes(ax, title=\"t-SNE\") #libcluster.format_legend(ax, cols=6, markerscale=2) if out is not None: libplot.savefig(fig, out) return",
"h=h) ids = list(sorted(set(clusters['Cluster']))) for i in range(0, len(ids)): l = ids[i] #print('Label",
"the figure \"\"\" if ax is None: fig, ax = libplot.new_fig(size, size) #print('Label",
"columns are tsne dimensions exp : numpy array expression values for each data",
"print('z max', max) sd[np.where(sd > max)] = max return pd.DataFrame(sd, index=d.index, columns=d.columns) def",
"Transforming now...') # zscore #e = (e - e.mean()) / e.std() #print(e.min(), e.max())",
"exp, dim=[1, 2], cmap=None, marker='o', s=MARKER_SIZE, alpha=EXP_ALPHA, fig=None, ax=None, w=libplot.DEFAULT_WIDTH, h=libplot.DEFAULT_HEIGHT, edgecolors=EDGE_COLOR, linewidth=EDGE_WIDTH,",
"b) # # #d = im_data[np.where(black_areas)] # #d[:, 0:3] = [64, 64, 64]",
"index in indexes: ret.append((index, ids[index], gene_names[index])) return ret def get_gene_data(data, g, ids=None, gene_names=None):",
"libplot.scatter(x, y, c=BACKGROUND_SAMPLE_COLOR, ax=ax) # # # Plot cluster over the top of",
"= 1000000 / reads_per_bc scaled = data.multiply(scaling_factors) # , axis=1) return scaled def",
"float) or isinstance(max, int): print('z max', max) sd[np.where(sd > max)] = max return",
"data['{}-{}'.format(t, d1)][idx] y = data.iloc[idx, dim[1] - 1].values # data['{}-{}'.format(t, d2)][idx] e =",
"gene = gene_ids[i][2] print(gene, gene_id) exp = get_gene_data(data, gene_id, ids=ids, gene_names=gene_names) ax =",
"out) def cluster_plot(tsne, clusters, dim1=0, dim2=1, markers='o', s=libplot.MARKER_SIZE, colors=None, w=8, h=8, legend=True, show_axes=False,",
"y), avg1, (xi, yi)) #ax.contour(xi, yi, z, levels=1) def gene_expr(data, tsne, gene, fig=None,",
"im2) imagelib.save(im_base, out) def avg_expr(data, tsne, genes, cid, clusters, prefix='', index=None, dir='GeneExp', cmap=OR_RED_CMAP,",
"\"\"\" exp = get_gene_data(data, gene) return expr_plot(tsne, exp, fig=fig, ax=ax, cmap=cmap, out=out) def",
"alpha=alpha, ax=ax, norm=norm) return fig, ax def pca_expr_plot(data, expr, name, dim=[1, 2], cmap=None,",
"into a and b \"\"\" cache = True counts = libcluster.remove_empty_rows(counts) # ['AICDA',",
"#node_color = (c_phen['Cluster'][0:A.shape[0]] - 1).tolist() # node_color = (clusters['Cluster'] - 1).tolist() # #",
"from scipy.interpolate import interp1d from scipy.spatial import distance import networkx as nx import",
"pos=pos, with_labels=False, ax=ax, node_size=50, node_color=node_color, vmax=(clusters['Cluster'].max() - 1), cmap=libcluster.colormap()) # # libplot.savefig(fig, 'network_{}.pdf'.format(name))",
"ax = libplot.new_fig(w, h) is_first = True base_expr_plot(data, exp, dim=dim, s=s, marker=marker, edgecolors=edgecolors,",
"reads_per_bc scaled = data.multiply(scaling_factors) # , axis=1) return scaled def umi_norm_log2(data): d =",
"if l % cols == 0: # Assume we will add a row",
"d = np.array([distance.euclidean(centroid, (a, b)) for a, b in zip(x, y)]) sd =",
"add_titles=True, cluster_order=None, method='tsne', dir='.', out=None): fig = cluster_grid(tsne, clusters, colors=colors, cols=cols, size=size, add_titles=add_titles,",
"== '/': dir = dir[:-1] if not os.path.exists(dir): mkdir(dir) if index is None:",
"cluster_plot(tsne_b, c_b, legend=False, w=w, h=h) libplot.savefig(fig, 'b/b_tsne_clusters_med.pdf') def sample_clusters(d, sample_names): \"\"\" Create a",
"+= 1 return fig def create_cluster_grid(tsne, clusters, name, colors=None, cols=-1, size=SUBPLOT_SIZE, add_titles=True, cluster_order=None,",
"raise ValueError( 'Matrix HDF5 file format version (%d) is an newer version that",
"= get_gene_names(data) gene_ids = get_gene_ids(data, genes, ids=ids, gene_names=gene_names) w, h, rows, cols =",
"b) black_areas = (a > 0) d = im_data[np.where(black_areas)] d[:, 0:3] = [64,",
"SUBPLOT_SIZE = 4 EXP_ALPHA = 0.8 # '#f2f2f2' #(0.98, 0.98, 0.98) #(0.8, 0.8,",
"genes = data.index ids = genes return ids.values, genes.values def get_gene_ids(data, genes, ids=None,",
"= (c_phen['Cluster'][0:A.shape[0]] - 1).tolist() # node_color = (clusters['Cluster'] - 1).tolist() # # fig,",
"libplot.newfig(w=9) df2 = pd.DataFrame({'Silhouette Score': x2, 'Cluster': clusters.iloc[:, 0].tolist( ), 'Label': np.repeat('tsne-ah', len(x2))})",
"d2 = tsne.iloc[:, 1] xlim = [d1[d1 < 0].quantile(1 - TNSE_AX_Q), d1[d1 >=",
"(b < 255) & (b > 200) # # # d = im_data[np.where(grey_areas)]",
"tsne.iloc[idx2, 1] # libplot.scatter(x, y, c=BACKGROUND_SAMPLE_COLOR, ax=ax) # # # Plot cluster over",
"save_matrix_to_h5(gbm, filename, genome): flt = tables.Filters(complevel=1) with tables.open_file(filename, 'w', filters=flt) as f: try:",
"alpha=alpha, s=s, ax=ax, cluster_order=cluster_order, sort=sort) #set_tsne_ax_lim(tsne, ax) # libcluster.format_axes(ax) if not show_axes: libplot.invisible_axes(ax)",
"def pca_plot(pca, clusters, pc1=1, pc2=2, marker='o', labels=False, s=MARKER_SIZE, w=8, h=8, legend=True, fig=None, ax=None):",
"ret.append(np.sum(gbm.matrix[:, i].toarray())) return ret def df(gbm): \"\"\" Converts a GeneBCMatrix to a pandas",
"= 100 labels[np.where(labels == -1)] = new_label labels += 1 libtsne.write_clusters(headers, labels, name)",
"n) df2 = pca.iloc[indices, ] x = df2.iloc[:, pc1 - 1] y =",
"cluster)[0][0] print('index', i, cluster, colors) if isinstance(colors, dict): color = colors.get(cluster, 'black') elif",
"& (g > 200) & (b < 255) & (b > 200) #",
"Cells x tsne tsne data. Columns should be labeled 'TSNE-1', 'TSNE-2' etc #",
"cmap=cmap, marker=marker, s=s, alpha=alpha, fig=fig, ax=ax, norm=norm) libplot.savefig(fig, out) plt.close(fig) return fig, ax",
"Supply a figure object on which to render the plot, otherwise a new",
"elif type(x) is pd.core.frame.DataFrame: l = x.shape[0] else: return None cols = int(np.ceil(np.sqrt(l)))",
"exp, ax=ax) #libplot.add_colorbar(fig, cmap) exp_bin = exp[idx_bin] tsne_bin = tsne.iloc[idx_bin, :] expr_plot(tsne_bin, exp_bin,",
"optional Plot width h : int, optional Plot height alpha : float (0,",
"= np.array([distance.euclidean(centroid, (a, b)) for a, b in zip(x, y)]) sd = d.std()",
"im_no_bg im_smooth = imagelib.smooth(im_outline) imagelib.save(im_smooth, 'smooth.png') # im_smooth imagelib.paste(im_base, im_smooth, inplace=True) else: imagelib.paste(im_base,",
"Columns should be labeled 'TSNE-1', 'TSNE-2' etc # clusters : DataFrame # Clusters",
"(x.sum(axis=0) / x.shape[0]).tolist() ret[i, 0] = centroid[0] ret[i, 1] = centroid[1] return ret",
"'#214478', '#217844', '#ffcc00', '#ffdd55']) # BGY_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list('bgy', ['#002255', '#2ca05a', '#ffd42a']) # BGY_CMAP",
"index=d.index, columns=d.columns) def min_max_scale(d, min=0, max=1, axis=1): #m = d.min(axis=1) #std = (d",
"linewidth=linewidth, edgecolors=edgecolors) if out is not None: libplot.savefig(fig, out, pad=0) return fig, ax",
"Base function for creating an expression plot for T-SNE/2D space reduced representation of",
"g)[0] if idx.size > 0: # if id exists, pick the first idx",
": pandas.DataFrame # t-sne 2D data # \"\"\" # # fig, ax =",
"#print('Data does not appear to be z-scored. Transforming now...') # zscore #e =",
"alpha=alpha, fig=fig, w=w, h=h, ax=ax, show_axes=show_axes, colorbar=colorbar, norm=norm, linewidth=linewidth, edgecolors=edgecolors) if out is",
"to highlight cluster # enable if edges desired im1.paste(im2, (0, 0), im2) im1.save(out,",
"format='png', dir='.', w=16, h=16, legend=True): sc = sample_clusters(clusters, sample_names) create_cluster_plot(tsne_umi_log2, sc, name, method=method,",
"separate_clusters(tsne, clusters, name, colors=None, size=4, add_titles=True, type='tsne', format='pdf'): \"\"\" Plot each cluster into",
"int, optional height of new ax. Returns ------- fig : Matplotlib figure A",
"obj=gbm.barcodes) f.create_carray(group, 'data', obj=gbm.matrix.data) f.create_carray(group, 'indices', obj=gbm.matrix.indices) f.create_carray(group, 'indptr', obj=gbm.matrix.indptr) f.create_carray(group, 'shape', obj=gbm.matrix.shape)",
"g, ids=None, gene_names=None): if ids is None: ids, gene_names = get_gene_names(data) if isinstance(g,",
"matplotlib.colors.LinearSegmentedColormap.from_list( 'blue', ['#162d50', '#afc6e9']) BLUE_GREEN_YELLOW_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list( 'bgy', ['#162d50', '#214478', '#217844', '#ffcc00', '#ffdd55'])",
"add titles to plots w: int, optional width of new ax. h: int,",
"edges on top of original image to highlight cluster # enable if edges",
"w=w, h=h, colorbar=colorbar, norm=norm, alpha=alpha, fig=fig, ax=ax) x = tsne.iloc[:, 0].values # data['{}-{}'.format(t,",
"alpha=EXP_ALPHA, fig=None, ax=None, norm=None): # plt.cm.plasma): out = 'pca_expr_{}_t{}_vs_t{}.pdf'.format(name, 1, 2) fig, ax",
"return w, h, rows, cols def get_gene_names(data): if ';' in data.index[0]: ids, genes",
"h=8, fig=None, ax=None): colors = libcluster.get_colors() if ax is None: fig, ax =",
"# \"\"\" # Creates a basic t-sne expression plot. # # Parameters #",
"dict): legend_params.update(legend) else: pass if legend_params['show']: libcluster.format_legend(ax, cols=legend_params['cols'], markerscale=legend_params['markerscale']) libplot.invisible_axes(ax) tmp = 'tmp{}.png'.format(i)",
"= libcluster.colormap() labels = {} for i in range(0, c.shape[0]): labels[i] = i",
"> 0)[0] ids3 = np.intersect1d(ids1, ids2) o = len(ids3) / 5 * 100",
"the background x = tsne.iloc[idx1, 0] y = tsne.iloc[idx1, 1] #print('sep', cluster, color)",
"plt import collections import numpy as np import scipy.sparse as sp_sparse import tables",
"in # # Returns # ------- # fig : Matplotlib figure # A",
"= matplotlib.colors.Normalize(vmin=-3, vmax=3, clip=True) #cmap = plt.cm.plasma ids, gene_names = get_gene_names(data) print(ids, gene_names,",
"# #b = data[:, :, 2] # #a = im_data[:, :, 3] #",
"d2[d2 >= 0].quantile(TNSE_AX_Q)] #print(xlim, ylim) # ax.set_xlim(xlim) # ax.set_ylim(ylim) def base_cluster_plot(d, clusters, markers=None,",
"if out is not None: # libplot.savefig(fig, out, pad=0) # # return fig,",
"clusters, name, colors=None, cols=-1, size=SUBPLOT_SIZE, add_titles=True, cluster_order=None, method='tsne', dir='.', out=None): fig = cluster_grid(tsne,",
"create_cluster_samples(tsne_umi_log2, clusters, sample_names, name, method='tsne', format='png', dir='.', w=16, h=16, legend=True): sc = sample_clusters(clusters,",
"fig : matplotlib figure, optional Supply a figure object on which to render",
"1]) ax.set_title('tsne-10x') #libplot.savefig(fig, 'RK10001_10003_clust-phen_silhouette.pdf') ax = fig.add_subplot(212) # libplot.newfig(w=9) df2 = pd.DataFrame({'Silhouette Score':",
"= libplot.new_ax(fig, subplot=(rows, rows, i + 1)) # # x = tsne.iloc[idx2, 0]",
"= np.linspace(x.min(), x.max(), 100, endpoint=True) # yt = np.linspace(y.min(), y.max(), 100, endpoint=True) #",
"points = np.array([[p1, p2] for p1, p2 in zip(x, y)]) hull = ConvexHull(points)",
"list, color Colors of points add_titles : bool Whether to add titles to",
"counts.iloc[:, idx] d_a = libcluster.remove_empty_rows(d_a) if isinstance(d_a, SparseDataFrame): d_a = umi_norm_log2(d_a) else: d_a",
"# #im2.save('edges.png', 'png') # # im_smooth = im_edges.filter(ImageFilter.SMOOTH) # im_smooth.save('edges.png', 'png') # #",
"cluster_order=cluster_order, sort=sort) #set_tsne_ax_lim(tsne, ax) # libcluster.format_axes(ax) if not show_axes: libplot.invisible_axes(ax) legend_params = dict(LEGEND_PARAMS)",
"len(cids)): c = cids[i] x = tsne.iloc[np.where(clusters['Cluster'] == c)[0], :] centroid = (x.sum(axis=0)",
"h=libplot.DEFAULT_HEIGHT, show_axes=False, fig=None, ax=None, norm=None, colorbar=False): # plt.cm.plasma): \"\"\" Creates a base expression",
"enable if edges desired im1.paste(im2, (0, 0), im2) im1.save(out, 'png') def genes_expr_outline(data, tsne,",
"= tsne.iloc[idx1, 0] # y = tsne.iloc[idx1, 1] # # libplot.scatter(x, y, c=colors[sid],",
"= {} print(f.list_nodes('/')) for node in f.walk_nodes('/' + genome, 'Array'): dsets[node.name] = node.read()",
"= np.array([[x, y] for x, y in zip(x1, y1)]) #hull = ConvexHull(points) #ax.plot(points[hull.vertices,0],",
"{'show': True, 'cols': 4, 'markerscale': 2} CLUSTER_101_COLOR = (0.3, 0.3, 0.3) np.random.seed(0) GeneBCMatrix",
"find gray areas and mask # im_data = np.array(im1.convert('RGBA')) # # r =",
"= base_pca_expr_plot(data, expr, dim=dim, cmap=cmap, marker=marker, s=s, alpha=alpha, fig=fig, ax=ax, norm=norm) libplot.savefig(fig, out)",
"StandardScaler().fit_transform(d.T) sd = sklearn.preprocessing.scale(d, axis=axis) #sd = sd.T if isinstance(clip, float) or isinstance(clip,",
"print(binnumber.min(), binnumber.max()) iw = w * 300 im_base = imagelib.new(iw, iw) for bin",
"plt.close(fig) im = imagelib.open(tmp) im_no_bg = imagelib.remove_background(im) im_edges = imagelib.edges(im_no_bg) im_smooth = imagelib.smooth(im_edges)",
"gene_names, genes) gene_ids = get_gene_ids(data, genes, ids=ids, gene_names=gene_names) print(gene_ids) for i in range(0,",
"color=color) # # # libplot.invisible_axes(ax) pc += 1 return fig def create_cluster_grid(tsne, clusters,",
"s=s, w=w, h=h, cluster_order=cluster_order, show_axes=show_axes, legend=legend, sort=sort, out=out) def base_tsne_plot(tsne, marker='o', s=libplot.MARKER_SIZE, c='red',",
"'/': dir = dir[:-1] if not os.path.exists(dir): mkdir(dir) if index is None: index",
"kind='cubic') # # xt = np.linspace(x.min(), x.max(), 100, endpoint=True) # yt = np.linspace(y.min(),",
"c - 1 cluster = ids[i] # look up index for color purposes",
"scale(d, clip=clip) def read_clusters(file): print('Reading clusters from {}...'.format(file)) return pd.read_csv(file, sep='\\t', header=0, index_col=0)",
"== g)[0] if indexes.size > 0: for index in indexes: ret.append((index, ids[index], gene_names[index]))",
"if indexes.size > 0: for index in indexes: ret.append((index, ids[index], gene_names[index])) else: #",
"\"\"\" try: os.makedirs(path) except: pass def split_a_b(counts, samples, w=6, h=6, format='pdf'): \"\"\" Split",
"fig, ax = libplot.new_fig() libplot.scatter(tsne['TSNE-1'], tsne['TSNE-2'], c=c, marker=marker, label=label, s=s, ax=ax) return fig,",
"0.5 # # #print(c1) # # ax.scatter(x[i], # y[i], # c=[c1], # s=s,",
"d2=d2, # x1=x1, # x2=x2, # cmap=cmap, # marker=marker, # s=s, # alpha=alpha,",
"optional height of new ax. Returns ------- fig : Matplotlib figure A new",
"raise ValueError( 'Matrix HDF5 file format version (%d) is an older version that",
"0.85, 0.85 BACKGROUND_SAMPLE_COLOR = [0.75, 0.75, 0.75] EDGE_COLOR = None # [0.3, 0.3,",
"if axis == 0: return pd.DataFrame(MinMaxScaler(feature_range=(min, max)).fit_transform(d), index=d.index, columns=d.columns) else: return pd.DataFrame(MinMaxScaler(feature_range=(min, max)).fit_transform(d.T).T,",
"< 255) | (g < 255) | (b < 255) #(r > 0)",
"= c - 1 cluster = ids[i] # look up index for color",
"libtsne.load_phenograph_clusters(pca_b, 'b', cache=cache) create_pca_plot(pca_b, c_b, 'b', dir='b') create_cluster_plot(tsne_b, c_b, 'b', dir='b') create_cluster_grid(tsne_b, c_b,",
"\"\"\" is_first = False if ax is None: fig, ax = libplot.new_fig(w, h)",
"'#5fd38d', '#ffd42a']) EXP_NORM = matplotlib.colors.Normalize(-1, 3, clip=True) LEGEND_PARAMS = {'show': True, 'cols': 4,",
"def expr_grid_size(x, size=SUBPLOT_SIZE): \"\"\" Auto size grid to look nice. \"\"\" if type(x)",
"color = colors[i] else: color = CLUSTER_101_COLOR else: color = 'black' fig, ax",
"color = colors.get(cluster, 'black') elif isinstance(colors, list): #i = cluster - 1 if",
"255) | (g < 255) | (b < 255) #(r > 0) &",
"else: d_b = umi_norm_log2_scale(d_b) pca_b = libtsne.load_pca(d_b, 'b', cache=cache) # pca.iloc[idx_b,:] tsne_b =",
"s=s, colorbar=colorbar, norm=norm, alpha=alpha, linewidth=linewidth, edgecolors=edgecolors) if gene_id != gene: out = '{}/{}_expr_{}_{}.{}'.format(dir,",
"# sid = 0 # # for sample in samples: # id =",
"TNSE_AX_Q), d1[d1 >= 0].quantile(TNSE_AX_Q)] ylim = [d2[d2 < 0].quantile(1 - TNSE_AX_Q), d2[d2 >=",
"try the gene names idx = np.where(np.isin(gene_names, g))[0] if idx.size < 1: return",
"+= 1 h = size * rows return w, h, rows, cols def",
"norm=None, w=libplot.DEFAULT_WIDTH, h=libplot.DEFAULT_HEIGHT, alpha=1.0, colorbar=False, method='tsne', fig=None, ax=None, sdmax=0.5): \"\"\" Plot multiple genes",
"# # #skimage.io.imsave('tmp_canny_{}.png'.format(bin), edges1) # # im2 = Image.fromarray(im_data) # # im_no_gray, im_smooth",
"import StandardScaler from sklearn.preprocessing import RobustScaler from sklearn.preprocessing import MinMaxScaler from sklearn.metrics import",
"a GeneBCMatrix Returns ------- object : Pandas DataFrame shape(n_cells, n_genes) \"\"\" df =",
"def pca_expr_plot(data, expr, name, dim=[1, 2], cmap=None, marker='o', s=MARKER_SIZE, alpha=EXP_ALPHA, fig=None, ax=None, norm=None):",
"data point so it must have the same number of elements as data",
"& (r == g) & (r == b) & (g == b) #",
"isinstance(legend, dict): legend_params.update(legend) else: pass if legend_params['show']: libcluster.format_legend(ax, cols=legend_params['cols'], markerscale=legend_params['markerscale']) return fig, ax",
"+ 1), marker=marker, s=s, ax=ax) si += 1 return fig def pca_plot_base(pca, clusters,",
"expr_plot(tsne, # exp, # d1=1, # d2=2, # x1=None, # x2=None, # cmap=BLUE_YELLOW_CMAP,",
"w) x = tsne_other.iloc[:, 0] y = tsne_other.iloc[:, 1] libplot.scatter(x, y, c=[background], ax=ax,",
"'Silhouette Score', colors=libcluster.colors(), ax=ax) ax.set_ylim([-1, 1]) ax.set_title('tsne-10x') #libplot.savefig(fig, 'RK10001_10003_clust-phen_silhouette.pdf') ax = fig.add_subplot(212) #",
"k=2) # # #node_color = (c_phen['Cluster'][0:A.shape[0]] - 1).tolist() # node_color = (clusters['Cluster'] -",
"1, 2) fig, ax = base_pca_expr_plot(data, expr, dim=dim, cmap=cmap, marker=marker, s=s, alpha=alpha, fig=fig,",
"\"\"\" Plot multiple genes on a grid. Parameters ---------- data : Pandas dataframe",
"ax=ax) # idx1 = np.where(clusters['Cluster'] == cluster)[0] # idx2 = np.where(clusters['Cluster'] != cluster)[0]",
"get_gene_data(data, gene_id, ids=ids, gene_names=gene_names) bin_means, bin_edges, binnumber = binned_statistic(exp, exp, bins=bins) print(binnumber.min(), binnumber.max())",
"'data', obj=gbm.matrix.data) f.create_carray(group, 'indices', obj=gbm.matrix.indices) f.create_carray(group, 'indptr', obj=gbm.matrix.indptr) f.create_carray(group, 'shape', obj=gbm.matrix.shape) except: raise",
"== cluster)[0]] color = colors[i] else: color = CLUSTER_101_COLOR else: color = 'black'",
"to plot figure pc = 1 for c in cluster_order: i = c",
"c = centroids(tsne, clusters) fig, ax = libplot.newfig(w=5, h=5) ax.scatter(c[:, 0], c[:, 1],",
"= tsne.iloc[idx2, 0] y = tsne.iloc[idx2, 1] libplot.scatter(x, y, c=[background], ax=ax, edgecolors='none', #",
"#scaled = std * (max - min) + min # return scaled if",
"points # # ax = libplot.new_ax(fig, subplot=(rows, rows, i + 1)) # #",
"x = data.iloc[idx, dim[0] - 1].values # data['{}-{}'.format(t, d1)][idx] y = data.iloc[idx, dim[1]",
"binnumber.max()) iw = w * 300 im_base = imagelib.new(iw, iw) for bin in",
"header=0, sep='\\t') idx = np.where(counts.columns.isin(b_barcodes['Barcode'].values))[0] d_b = counts.iloc[:, idx] d_b = libcluster.remove_empty_rows(d_b) if",
"= pd.read_csv('../a_barcodes.tsv', header=0, sep='\\t') idx = np.where(counts.columns.isin(a_barcodes['Barcode'].values))[0] d_a = counts.iloc[:, idx] d_a =",
"= binned_statistic(exp, exp, bins=bins) print(binnumber.min(), binnumber.max()) iw = w * 300 im_base =",
"x = tsne.iloc[idx1, 0] # y = tsne.iloc[idx1, 1] # # libplot.scatter(x, y,",
"0) & (r == g) & (r == b) & (g == b)",
"if isinstance(max, float) or isinstance(max, int): print('z max', max) sd[np.where(sd > max)] =",
"'#afc6e9']) BLUE_GREEN_YELLOW_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list( 'bgy', ['#162d50', '#214478', '#217844', '#ffcc00', '#ffdd55']) # BGY_CMAP =",
"#print('Label {}'.format(l)) # idx2 = np.where(clusters['Cluster'] != c)[0] # # # Plot background",
"# linewidth=linewidth) # # # # mean = color.mean() # # #print(x[i], y[i],",
"# # #print(edges1.shape) # # #skimage.io.imsave('tmp_canny_{}.png'.format(bin), edges1) # # im2 = Image.fromarray(im_data) #",
"inplace=True) else: imagelib.paste(im_base, im, inplace=True) # # find gray areas and mask #",
"# Assume we will add a row for a color bar rows +=",
"1] # # libplot.scatter(x, y, c=BACKGROUND_SAMPLE_COLOR, ax=ax) # # # Plot cluster over",
"# norm=norm, # edgecolors=[color], # linewidth=linewidth) #libcluster.format_axes(ax, title=t) return fig, ax def expr_plot(data,",
"True counts = libcluster.remove_empty_rows(counts) # ['AICDA', 'CD83', 'CXCR4', 'MKI67', 'MYC', 'PCNA', 'PRDM1'] genes",
"# clusters : DataFrame # Clusters in # # Returns # ------- #",
"else: imagelib.paste(im_base, im, inplace=True) # # find gray areas and mask # im_data",
"plot file. \"\"\" ids = list(sorted(set(clusters['Cluster']))) indices = np.array(list(range(0, len(ids)))) if colors is",
"rows, si)) pca_plot_base(pca, clusters, pc1=(i + 1), pc2=(j + 1), marker=marker, s=s, ax=ax)",
"add_titles: # if isinstance(cluster, int): # prefix = 'C' # else: # prefix",
"0)[0] ids3 = np.intersect1d(ids1, ids2) o = len(ids3) / 5 * 100 overlaps.append(o)",
"id exists, pick the first idx = idx[0] else: # if id does",
"genes, prefix='', index=None, dir='GeneExp', cmap=BGY_CMAP, norm=None, w=6, s=30, alpha=1, linewidth=EDGE_WIDTH, edgecolors='none', colorbar=True, method='tsne',",
"'#ffd42a', '#ffdd55']) # BGY_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list('bgy', ['#003366', '#339966', '#ffff66', '#ffff00') # BGY_CMAP =",
"\"\"\" Make dirs including any parents and avoid raising exception to work more",
"we will add a row for a color bar rows += 1 h",
"= imagelib.remove_background(im) im_edges = imagelib.edges(im) im_outline = imagelib.paste(im, im_edges) # im_no_bg im_smooth =",
"ax def separate_clusters(tsne, clusters, name, colors=None, size=4, add_titles=True, type='tsne', format='pdf'): \"\"\" Plot each",
"# d[:, :] = [255, 255, 255, 0] # im_data[np.where(grey_areas)] = d #",
"collections.namedtuple( 'GeneBCMatrix', ['gene_ids', 'gene_names', 'barcodes', 'matrix']) def decode(items): return np.array([x.decode('utf-8') for x in",
"# Plot background points # # ax = libplot.new_ax(fig, subplot=(rows, rows, i +",
"min if isinstance(max, float) or isinstance(max, int): print('z max', max) sd[np.where(sd > max)]",
"pandas as pd from sklearn.manifold import TSNE import sklearn.preprocessing from sklearn.preprocessing import StandardScaler",
"1]) ax.set_title('tsne-ah') libplot.savefig(fig, '{}_silhouette.pdf'.format(name)) def node_color_from_cluster(clusters): colors = libcluster.colors() return [colors[clusters['Cluster'][i] - 1]",
"gene_names = get_gene_names(data) print(ids, gene_names, genes) gene_ids = get_gene_ids(data, genes, ids=ids, gene_names=gene_names) print(gene_ids)",
"= matplotlib.colors.LinearSegmentedColormap.from_list( 'bgy', ['#002255', '#003380', '#2ca05a', '#ffd42a', '#ffdd55']) BGY_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list( 'bgy', ['#003366',",
"- 1]) ax.text(pca.iloc[i, pc1 - 1], pca.iloc[i, pc2 - 1], pca.index[i]) return fig,",
"# A new Matplotlib figure used to make the plot # \"\"\" #",
"if colors is None: colors = libcluster.get_colors() # Where to plot figure pc",
"ids1 = np.where(a1[i, :] > 0)[0] ids2 = np.where(a2[i, :] > 0)[0] ids3",
"ids = np.array(list(sorted(set(clusters['Cluster'])))) cluster_order = np.array(list(range(0, len(ids)))) + 1 n = cluster_order.size if",
"1), marker=marker, s=s, ax=ax) si += 1 return fig def pca_plot_base(pca, clusters, pc1=1,",
"# marker='o', # s=MARKER_SIZE, # alpha=EXP_ALPHA, # out=None, # fig=None, # ax=None, #",
"plotted (usually 1) d2 : int, optional Second dimension being plotted (usually 2)",
"1 for i in range(0, n): for j in range(i + 1, n):",
"name, colors=None, cols=-1, size=SUBPLOT_SIZE, add_titles=True, cluster_order=None, method='tsne', dir='.', out=None): fig = cluster_grid(tsne, clusters,",
"print('z min', min) sd[np.where(sd < min)] = min if isinstance(max, float) or isinstance(max,",
"\"\"\" if cluster_order is None: ids = np.array(list(sorted(set(clusters['Cluster'])))) cluster_order = np.array(list(range(0, len(ids)))) +",
"samples expression matrix tsne : Pandas dataframe Cells x tsne tsne data. Columns",
"= im_data[:, :, 1] # b = im_data[:, :, 2] # # print(tmp,",
"= tsne_cluster_sample_grid(tsne, clusters, samples, colors, size) # # libplot.savefig(fig, '{}/tsne_{}_sample_clusters.png'.format(dir, name)) # #libplot.savefig(fig,",
"# # ax.scatter(x[i], # y[i], # c=[c1], # s=s, # marker=marker, # edgecolors='none',",
"'#ffdd55']) BLUE_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list( 'blue', ['#162d50', '#afc6e9']) BLUE_GREEN_YELLOW_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list( 'bgy', ['#162d50', '#214478',",
"\"\"\" Plot a cluster separately to highlight where the samples are Parameters ----------",
"genes, prefix='a_BGY', cmap=BLUE_GREEN_YELLOW_CMAP, w=w, h=h, dir='a/GeneExp', format=format) fig, ax = cluster_plot(tsne_a, c_a, legend=False,",
"'a', dir='a') create_cluster_grid(tsne_a, c_a, 'a', dir='a') create_merge_cluster_info(d_a, c_a, 'a', sample_names=samples, dir='a') create_cluster_samples(tsne_a, c_a,",
"int, optional First dimension being plotted (usually 1) d2 : int, optional Second",
"1], c=None) libplot.format_axes(ax) libplot.savefig(fig, '{}_centroids.pdf'.format(name)) def centroid_network(tsne, clusters, name): c = centroids(tsne, clusters)",
"# BGY_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list('bgy', ['#002255', '#003380', '#2ca05a', '#ffd42a', '#ffdd55']) # BGY_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list('bgy',",
": a GeneBCMatrix Returns ------- object : Pandas DataFrame shape(n_cells, n_genes) \"\"\" df",
"im_outline = imagelib.paste(im_no_bg, im_smooth) imagelib.paste(im_base, im_outline, inplace=True) # # find gray areas and",
"# ---------- # data : pandas.DataFrame # t-sne 2D data # \"\"\" #",
"for x, y in zip(x1, y1)]) #hull = ConvexHull(points) #ax.plot(points[hull.vertices,0], points[hull.vertices,1]) #zi =",
"\"\"\" if ax is None: fig, ax = libplot.new_fig(w=w, h=h) libcluster.scatter_clusters(d.iloc[:, dim1].values, d.iloc[:,",
"== l)[0] n = len(indices) label = 'C{} ({:,})'.format(l, n) df2 = pca.iloc[indices,",
"= 0 # 0.25 ALPHA = 0.9 BLUE_YELLOW_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list( 'blue_yellow', ['#162d50', '#ffdd55'])",
"c_a, 'a', sample_names=samples, dir='a') create_cluster_samples(tsne_a, c_a, samples, 'a_sample', dir='a') genes_expr(d_a, tsne_a, genes, prefix='a_BGY',",
"'bgy', ['#002255', '#003380', '#2ca05a', '#ffd42a', '#ffdd55']) BGY_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list( 'bgy', ['#003366', '#004d99', '#40bf80',",
"0.9 BLUE_YELLOW_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list( 'blue_yellow', ['#162d50', '#ffdd55']) BLUE_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list( 'blue', ['#162d50', '#afc6e9'])",
"1] libplot.scatter(x, y, c=[background], ax=ax, edgecolors='none', # bgedgecolor, linewidth=linewidth, s=s) # Plot cluster",
":] centroid = (x.sum(axis=0) / x.shape[0]).tolist() ret[i, 0] = centroid[0] ret[i, 1] =",
"= imagelib.smooth_edges(im_no_bg) # imagelib.paste(im_no_bg, im_smooth, inplace=True) # imagelib.save(im_no_bg, 'smooth.png') # imagelib.paste(im_base, im_no_bg, inplace=True)",
"data['{}-{}'.format(t, d2)][idx] idx = np.where(clusters['Cluster'] == cid)[0] nx = 500 ny = 500",
"100, endpoint=True) # # xp = points[hull.vertices, 0] yp = points[hull.vertices, 1] xp",
"# # im_data = np.array(im_edges.convert('RGBA')) # # #r = data[:, :, 0] #",
"size=w, s=s, linewidth=linewidth, add_titles=False) # get x y lim xlim = ax.get_xlim() ylim",
"pca.index.values for i in range(0, pca.shape[0]): print(pca.shape, pca.iloc[i, pc1 - 1], pca.iloc[i, pc2",
"# im_data[np.where(grey_areas)] = d # # im2 = Image.fromarray(im_data) # # # Edge",
"is created and returned. ax : matplotlib axis If ax is a supplied",
"its own plot file. \"\"\" ids = list(sorted(set(clusters['Cluster']))) indices = np.array(list(range(0, len(ids)))) if",
"have the same number of elements as data has rows. d1 : int,",
"load_clusters(pca, headers, name, cache=True): file = libtsne.get_cluster_file(name) if not os.path.isfile(file) or not cache:",
"in indexes: ret.append((index, ids[index], gene_names[index])) return ret def get_gene_data(data, g, ids=None, gene_names=None): if",
"'black' ax.scatter(x, y, color=color, edgecolor=color, s=s, marker=marker, alpha=libplot.ALPHA, label=label) if labels: l =",
"prefix = 'C' # else: # prefix = '' # # ax.set_title('{}{} ({:,})'.format(prefix,",
"markerscale=legend_params['markerscale']) libplot.invisible_axes(ax) tmp = 'tmp{}.png'.format(i) libplot.savefig(fig, tmp) plt.close(fig) # Open image # im",
"# en = norm(e[i]) # color = cmap(int(en * cmap.N)) # color =",
"dataframe # Cells x tsne tsne data. Columns should be labeled 'TSNE-1', 'TSNE-2'",
"dim2=dim2, markers=markers, colors=colors, s=s, w=w, h=h, cluster_order=cluster_order, show_axes=show_axes, legend=legend, sort=sort, out=out) def base_tsne_plot(tsne,",
"pca.iloc[i, pc2 - 1]) ax.text(pca.iloc[i, pc1 - 1], pca.iloc[i, pc2 - 1], pca.index[i])",
"import networkx as nx import os import phenograph import libplot import libcluster import",
"= imagelib.new(iw, iw) for bin in range(0, bins): bi = bin + 1",
"colorbar=colorbar, norm=norm, alpha=alpha, linewidth=linewidth, edgecolors=edgecolors) if gene_id != gene: out = '{}/{}_expr_{}_{}.{}'.format(dir, method,",
"# # libplot.invisible_axes(ax) # # if out is not None: # libplot.savefig(fig, out,",
"cols == -1: cols = int(np.ceil(np.sqrt(n))) rows = int(np.ceil(n / cols)) w =",
"yi = np.linspace(y.min(), y.max(), ny) x = x[idx] y = y[idx] #centroid =",
"[d1[d1 < 0].quantile(1 - TNSE_AX_Q), d1[d1 >= 0].quantile(TNSE_AX_Q)] ylim = [d2[d2 < 0].quantile(1",
"render the figure \"\"\" if ax is None: fig, ax = libplot.new_fig(size, size)",
"range(0, len(cids)): # c = cids[i] # # #print('Label {}'.format(l)) # idx2 =",
"indices = np.array(list(range(0, len(ids)))) if colors is None: colors = libcluster.get_colors() for i",
"---------- # data : pandas.DataFrame # t-sne 2D data # \"\"\" # #",
"reduced representation of data. Parameters ---------- data : Pandas dataframe features x dimensions,",
"dirs including any parents and avoid raising exception to work more like mkdir",
"Exception(\"File is missing one or more required datasets.\") #GeneBCMatrix = collections.namedtuple('FeatureBCMatrix', ['feature_ids', 'feature_names',",
"out, pad=0) plt.close(fig) im1 = Image.open('tmp.png') # Edge detect on what is left",
"(b > 200) # # # d = im_data[np.where(grey_areas)] # d[:, :] =",
"/ reads_per_bc scaled = data.multiply(scaling_factors) # , axis=1) return scaled def umi_norm_log2(data): d",
"def to_csv(gbm, file, sep='\\t'): df(gbm).to_csv(file, sep=sep, header=True, index=True) def sum(gbm, axis=0): return gbm.matrix.sum(axis=axis)",
"import Image, ImageFilter from scipy.stats import binned_statistic import imagelib TNSE_AX_Q = 0.999 MARKER_SIZE",
"# # Plot background points # # ax = libplot.new_ax(fig, subplot=(rows, rows, i",
"= centroids(tsne2, clusters) a1 = kneighbors_graph(c1, k, mode='distance', metric='euclidean').toarray() a2 = kneighbors_graph(c2, k,",
"isinstance(g, list): g = np.array(g) if isinstance(g, np.ndarray): idx = np.where(np.isin(ids, g))[0] if",
"np.repeat('tsne-10x', len(x1))}) libplot.boxplot(df, 'Cluster', 'Silhouette Score', colors=libcluster.colors(), ax=ax) ax.set_ylim([-1, 1]) ax.set_title('tsne-10x') #libplot.savefig(fig, 'RK10001_10003_clust-phen_silhouette.pdf')",
"cmap=None, size=SUBPLOT_SIZE): \"\"\" Plot multiple genes on a grid. Parameters ---------- data :",
"'Cluster': clusters.iloc[:, 0].tolist( ), 'Label': np.repeat('tsne-10x', len(x1))}) libplot.boxplot(df, 'Cluster', 'Silhouette Score', colors=libcluster.colors(), ax=ax)",
"= imagelib.smooth(im_edges) im_outline = imagelib.paste(im_no_bg, im_smooth) imagelib.paste(im_base, im_outline, inplace=True) # # find gray",
"= im_data[:, :, 2] # # grey_areas = (r < 255) & (r",
"log2 scale sparse') sd = StandardScaler(with_mean=False).fit_transform(d.T.matrix) return SparseDataFrame(sd.T, index=d.index, columns=d.columns) else: # StandardScaler().fit_transform(d.T)",
"w=8, h=8, legend=True, fig=None, ax=None): fig, ax = pca_plot_base(pca, clusters, pc1=pc1, pc2=pc2, marker=marker,",
"= idx[0] else: # if id does not exist, try the gene names",
"y = tsne.iloc[:, 1].values # data['{}-{}'.format(t, d2)][idx] idx = np.where(clusters['Cluster'] == cid)[0] nx",
"-max if isinstance(min, float) or isinstance(min, int): print('z min', min) sd[np.where(sd < min)]",
"libcluster.get_colors() for i in indices: print('index', i) cluster = ids[i] if isinstance(colors, dict):",
"'#ffe066']) OR_RED_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list( 'or_red', matplotlib.cm.OrRd(range(4, 256))) BU_PU_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list( 'bu_pu', matplotlib.cm.BuPu(range(4, 256)))",
"# # Returns # ------- # fig : Matplotlib figure # A new",
"background=BACKGROUND_SAMPLE_COLOR): \"\"\" Plot multiple genes on a grid. Parameters ---------- data : Pandas",
":, 1] # b = im_data[:, :, 2] # # print(tmp, r.shape) #",
"1 # fx = interp1d(points[hull.vertices, 0], points[hull.vertices, 1], kind='cubic') # fy = interp1d(points[hull.vertices,",
"cluster, color=color, add_titles=add_titles, size=size) out = '{}_sep_clust_{}_c{}.{}'.format(type, name, cluster, format) print('Creating', out, '...')",
"def umi_norm(data): \"\"\" Scale each library to its median size Parameters ---------- data",
"data['{}-{}'.format(t, d1)][idx] y = tsne.iloc[:, 1].values # data['{}-{}'.format(t, d2)][idx] idx = np.where(clusters['Cluster'] ==",
"outline: im_no_bg = imagelib.remove_background(im) im_edges = imagelib.edges(im) im_outline = imagelib.paste(im, im_edges) # im_no_bg",
"look pretty. \"\"\" d1 = tsne.iloc[:, 0] d2 = tsne.iloc[:, 1] xlim =",
"c)[0] # # # Plot background points # # ax = libplot.new_ax(fig, subplot=(rows,",
"data[idx, :].to_array() else: return data.iloc[idx, :].values def gene_expr_grid(data, tsne, genes, cmap=None, size=SUBPLOT_SIZE): \"\"\"",
"rows. d1 : int, optional First dimension being plotted (usually 1) d2 :",
"out = '{}/pca_{}_pc{}_vs_pc{}.{}'.format(dir, name, pc1, pc2, format) fig, ax = pca_plot(pca, clusters, pc1=pc1,",
"labels, colors) libcluster.format_simple_axes(ax, title=\"t-SNE\") libcluster.format_legend(ax, cols=6, markerscale=2) return fig, ax def base_expr_plot(data, exp,",
"method, gene, gene_id, format) else: out = '{}/{}_expr_{}.{}'.format(dir, method, gene, format) libplot.savefig(fig, 'tmp.png',",
"filename, genome): flt = tables.Filters(complevel=1) with tables.open_file(filename, 'w', filters=flt) as f: try: group",
"str directory to create. \"\"\" try: os.makedirs(path) except: pass def split_a_b(counts, samples, w=6,",
"for j in range(i + 1, pca.shape[1]): create_cluster_plot(pca, labels, name, pc1=( i +",
":, 2] # # print(tmp, r.shape) # # grey_areas = (r < 255)",
"libplot.new_ax(fig, subplot=(rows, rows, si)) pca_plot_base(pca, clusters, pc1=(i + 1), pc2=(j + 1), marker=marker,",
"ax, optional Supply an axis object on which to render the plot, otherwise",
"libplot.savefig(fig, out, pad=2) plt.close(fig) def set_tsne_ax_lim(tsne, ax): \"\"\" Set the t-SNE x,y limits",
"d2 : int, optional Second dimension being plotted (usually 2) fig : matplotlib",
"scipy.sparse as sp_sparse import tables import pandas as pd from sklearn.manifold import TSNE",
"= norm(e[i]) # color = cmap(int(en * cmap.N)) # color = np.array(color) #",
"legend elif isinstance(legend, dict): legend_params.update(legend) else: pass if legend_params['show']: libcluster.format_legend(ax, cols=legend_params['cols'], markerscale=legend_params['markerscale']) return",
"create_cluster_grid(tsne_b, c_b, 'b', dir='b') create_merge_cluster_info(d_b, c_b, 'b', sample_names=samples, dir='b') create_cluster_samples(tsne_b, c_b, samples, 'b_sample',",
"column is a cell reads_per_bc = data.sum(axis=0) # int(np.round(np.median(reads_per_bc))) median_reads_per_bc = np.median(reads_per_bc) scaling_factors",
"= umi_norm_log2(d_a) else: d_a = umi_norm_log2_scale(d_a) pca_a = libtsne.load_pca(d_a, 'a', cache=cache) # pca.iloc[idx,:]",
"#cmap = plt.cm.plasma ids, gene_names = get_gene_names(data) gene_ids = get_gene_ids(data, genes, ids=ids, gene_names=gene_names)",
"c1[-1] = 0.5 # # #print(c1) # # ax.scatter(x[i], # y[i], # c=[c1],",
"tsne_a, genes, prefix='a_BGY', cmap=BLUE_GREEN_YELLOW_CMAP, w=w, h=h, dir='a/GeneExp', format=format) fig, ax = cluster_plot(tsne_a, c_a,",
"'b/b_tsne_clusters_med.pdf') def sample_clusters(d, sample_names): \"\"\" Create a cluster matrix based on by labelling",
"x tsne tsne data. Columns should be labeled 'TSNE-1', 'TSNE-2' etc genes :",
"try the gene names indexes = np.where(gene_names == g)[0] for index in indexes:",
"samples # # Parameters # ---------- # tsne : Pandas dataframe # Cells",
"1] xlim = [d1[d1 < 0].quantile(1 - TNSE_AX_Q), d1[d1 >= 0].quantile(TNSE_AX_Q)] ylim =",
"kneighbors_graph(c2, k, mode='distance', metric='euclidean').toarray() overlaps = [] for i in range(0, c1.shape[0]): ids1",
"ax = base_pca_expr_plot(data, expr, dim=dim, cmap=cmap, marker=marker, s=s, alpha=alpha, fig=fig, ax=ax, norm=norm) libplot.savefig(fig,",
"fig, ax def base_pca_expr_plot(data, exp, dim=[1, 2], cmap=None, marker='o', s=MARKER_SIZE, alpha=EXP_ALPHA, fig=None, ax=None,",
"TNSE_AX_Q), d2[d2 >= 0].quantile(TNSE_AX_Q)] #print(xlim, ylim) # ax.set_xlim(xlim) # ax.set_ylim(ylim) def base_cluster_plot(d, clusters,",
"(d - m) / sd # find all points within 1 sd of",
"exist, try the gene names idx = np.where(np.isin(gene_names, g))[0] if idx.size < 1:",
"pretty. \"\"\" d1 = tsne.iloc[:, 0] d2 = tsne.iloc[:, 1] xlim = [d1[d1",
"0): #print('Data does not appear to be z-scored. Transforming now...') # zscore #e",
": int, optional First dimension being plotted (usually 1) d2 : int, optional",
"\"\"\" if out is None: out = '{}_expr.pdf'.format(method) fig, ax = expr_plot(tsne, exp,",
"tsne data. Columns should be labeled 'TSNE-1', 'TSNE-2' etc # clusters : DataFrame",
"(clusters['Cluster'] - 1).tolist() # # fig, ax = libplot.newfig(w=10, h=10) # # nx.draw_networkx(G,",
"overlaps}) df.set_index('Cluster', inplace=True) df.to_csv('{}_cluster_overlaps.txt'.format(name), sep='\\t') def mkdir(path): \"\"\" Make dirs including any parents",
"sc = np.array(['' for i in range(0, d.shape[0])], dtype=object) c = 1 for",
"= libplot.newfig(w=10, h=10) # # nx.draw_networkx(G, pos=pos, with_labels=False, ax=ax, node_size=50, node_color=node_color, vmax=(clusters['Cluster'].max() -",
"fig, ax = expr_plot(tsne, # exp, # t='TSNE', # d1=d1, # d2=d2, #",
"color=color, edgecolor=color, s=s, marker=marker, alpha=libplot.ALPHA, label=label) if labels: l = pca.index.values for i",
"sns from libsparse.libsparse import SparseDataFrame from lib10x.sample import * from scipy.spatial import ConvexHull",
"cols = int(np.ceil(np.sqrt(n))) rows = int(np.ceil(n / cols)) w = size * cols",
"np.where(binnumber == bi)[0] idx_other = np.where(binnumber != bi)[0] tsne_other = tsne.iloc[idx_other, :] fig,",
"to a pandas dataframe (dense) Parameters ---------- gbm : a GeneBCMatrix Returns -------",
"\"\"\" sc = np.array(['' for i in range(0, d.shape[0])], dtype=object) c = 1",
"umi_tpm_log2(data): d = umi_tpm(data) return umi_log2(d) def umi_norm(data): \"\"\" Scale each library to",
"ids in the order they should be rendered Returns ------- fig : Matplotlib",
"= matplotlib.colors.Normalize(vmin=-3, vmax=3, clip=True) if norm is None: norm = libplot.NORM_3 # Sort",
"'TSNE-2' etc # clusters : DataFrame # Clusters in # # Returns #",
"BGY_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list('bgy', ['#002255', '#003380', '#2ca05a', '#ffd42a', '#ffdd55']) # BGY_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list('bgy', ['#003366',",
"out=None): fig = cluster_grid(tsne, clusters, colors=colors, cols=cols, size=size, add_titles=add_titles, cluster_order=cluster_order) if out is",
"matplotlib.colors.LinearSegmentedColormap.from_list( 'bgy', ['#002255', '#003380', '#2ca05a', '#ffd42a', '#ffdd55']) BGY_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list( 'bgy', ['#003366', '#004d99',",
"ax): \"\"\" Set the t-SNE x,y limits to look pretty. \"\"\" d1 =",
"markers. show_axes : bool, optional, default true Whether to show axes on plot",
"width h : int, optional Plot height alpha : float (0, 1), optional",
"= d.min(axis=1) #std = (d - m) / (d.max(axis=1) - m) #scaled =",
"cluster_order=cluster_order) if out is None: out = '{}/{}_{}_separate_clusters.png'.format(dir, method, name) libplot.savefig(fig, out, pad=0)",
"(0, 0), im_smooth) # # im_base.paste(im2, (0, 0), im2) if gene_id != gene:",
"# Plot cluster over the top of the background # # sid =",
"nice. \"\"\" if type(x) is int: l = x elif type(x) is list:",
"label = 'C{} ({:,})'.format(l, n) df2 = pca.iloc[indices, ] x = df2.iloc[:, pc1",
"ids3 = np.intersect1d(ids1, ids2) o = len(ids3) / 5 * 100 overlaps.append(o) df",
"return [colors[clusters['Cluster'][i] - 1] for i in range(0, clusters.shape[0])] # def network(tsne, clusters,",
"= size * cols rows = int(l / cols) + 2 if l",
"# # libplot.savefig(fig, '{}/tsne_{}_sample_clusters.png'.format(dir, name)) # #libplot.savefig(fig, '{}/tsne_{}separate_clusters.pdf'.format(dir, name)) # # def load_clusters(pca,",
"scale(d, clip=None, min=None, max=None, axis=1): if isinstance(d, SparseDataFrame): print('UMI norm log2 scale sparse')",
"return cluster_plot(d, clusters, dim1=dim1, dim2=dim2, markers=markers, colors=colors, s=s, w=w, h=h, cluster_order=cluster_order, show_axes=show_axes, legend=legend,",
"centroid = (x.sum(axis=0) / x.shape[0]).tolist() ret[i, 0] = centroid[0] ret[i, 1] = centroid[1]",
"index_col=0) def silhouette(tsne, tsne_umi_log2, clusters, name): # measure cluster worth x1 = silhouette_samples(",
"else: raise ValueError( 'Matrix HDF5 file format version (%d) is an older version",
"ids : Index, optional Index of gene ids gene_names : Index, optional Index",
"to render the plot, otherwise a new one is created. norm : Normalize,",
"* 300, w * 300) for i in range(0, len(cluster_order)): print('index', i, cluster_order[i])",
"= matplotlib.colors.Normalize(vmin=-3, vmax=3, clip=True) #cmap = plt.cm.plasma ids, gene_names = get_gene_names(data) gene_ids =",
"list): #i = cluster - 1 if i < len(colors): # colors[cid -",
"max)).fit_transform(d), index=d.index, columns=d.columns) else: return pd.DataFrame(MinMaxScaler(feature_range=(min, max)).fit_transform(d.T).T, index=d.index, columns=d.columns) def rscale(d, min=0, max=1,",
"(avg - avg.min()) / (avg.max() - avg.min()) # min_max_scale(avg) create_expr_plot(tsne, avg, cmap=cmap, w=w,",
"base_tsne_plot(tsne, marker=marker, c=c, s=s, label=label, fig=fig, ax=ax) #libtsne.tsne_legend(ax, labels, colors) libcluster.format_simple_axes(ax, title=\"t-SNE\") libcluster.format_legend(ax,",
"fig, ax = libplot.new_fig(size, size) #print('Label {}'.format(l)) idx1 = np.where(clusters['Cluster'] == cluster)[0] idx2",
"cluster over the top of the background x = tsne.iloc[idx1, 0] y =",
"markers=None, s=libplot.MARKER_SIZE, colors=None, edgecolors=EDGE_COLOR, linewidth=EDGE_WIDTH, dim1=0, dim2=1, w=8, h=8, alpha=ALPHA, # libplot.ALPHA, show_axes=True,",
"# # fig, ax = libplot.newfig(w=10, h=10) # # nx.draw_networkx(G, pos=pos, with_labels=False, ax=ax,",
"bar. \"\"\" is_first = False if ax is None: fig, ax = libplot.new_fig(w,",
"# libplot.scatter(x, y, c=color, ax=ax) # # if add_titles: # if isinstance(cluster, int):",
"clusters, colors=colors, cols=cols, size=size, add_titles=add_titles, cluster_order=cluster_order) if out is None: out = '{}/{}_{}_separate_clusters.png'.format(dir,",
"genes, ids=ids, gene_names=gene_names) for i in range(0, len(gene_ids)): gene_id = gene_ids[i][1] gene =",
"return scaled if axis == 0: return pd.DataFrame(MinMaxScaler(feature_range=(min, max)).fit_transform(d), index=d.index, columns=d.columns) else: return",
"0.8, 0.8) #(0.85, 0.85, 0.85 BACKGROUND_SAMPLE_COLOR = [0.75, 0.75, 0.75] EDGE_COLOR = None",
"get_gene_data(data, gene_id, ids=ids, gene_names=gene_names) #fig, ax = libplot.new_fig() #expr_plot(tsne, exp, ax=ax) #libplot.add_colorbar(fig, cmap)",
"plt.cm.plasma): \"\"\" Base function for creating an expression plot for T-SNE/2D space reduced",
"sd.T if isinstance(clip, float) or isinstance(clip, int): max = abs(clip) min = -max",
"= np.argsort(exp) #np.argsort(abs(exp)) # np.argsort(exp) x = data.iloc[idx, dim[0] - 1].values # data['{}-{}'.format(t,",
"reads_per_bc scaled = data.multiply(scaling_factors) # , axis=1) return scaled def umi_log2(d): if isinstance(d,",
"cols rows = int(l / cols) + 2 if l % cols ==",
"#if mean > 0.5: # ax.scatter(x[i], # y[i], # c='#ffffff00', # s=s, #",
"pca.iloc[i, pc1 - 1], pca.iloc[i, pc2 - 1]) ax.text(pca.iloc[i, pc1 - 1], pca.iloc[i,",
"#GeneBCMatrix = collections.namedtuple('FeatureBCMatrix', ['feature_ids', 'feature_names', 'barcodes', 'matrix']) def get_matrix_from_h5_v2(filename, genome): with h5py.File(filename, 'r')",
"ax=ax, norm=norm) libplot.savefig(fig, out) plt.close(fig) return fig, ax def expr_grid_size(x, size=SUBPLOT_SIZE): \"\"\" Auto",
"dataframe Matrix of umi counts \"\"\" # each column is a cell reads_per_bc",
"isinstance(cluster, int): prefix = 'C' else: prefix = '' ax.set_title('{}{} ({:,})'.format( prefix, cluster,",
"'#ffff33']) # BGY_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list('bgy', ['#003366', '#40bf80', '#ffff33']) BGY_ORIG_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list( 'bgy', ['#002255',",
"color.copy() # c1[-1] = 0.5 # # #print(c1) # # ax.scatter(x[i], # y[i],",
"header=0) mkdir('a') a_barcodes = pd.read_csv('../a_barcodes.tsv', header=0, sep='\\t') idx = np.where(counts.columns.isin(a_barcodes['Barcode'].values))[0] d_a = counts.iloc[:,",
": DataFrame data table containing and index genes : list List of strings",
"clusters, dim1=0, dim2=1, markers='o', s=libplot.MARKER_SIZE, colors=None, w=8, h=8, legend=True, show_axes=False, sort=True, cluster_order=None, fig=None,",
"'#ffd42a']) EXP_NORM = matplotlib.colors.Normalize(-1, 3, clip=True) LEGEND_PARAMS = {'show': True, 'cols': 4, 'markerscale':",
"sd[np.where(sd < min)] = min if isinstance(max, float) or isinstance(max, int): print('z max',",
"cols=-1, size=SUBPLOT_SIZE, add_titles=True, cluster_order=None): \"\"\" Plot each cluster separately to highlight where the",
"cid)[0] nx = 500 ny = 500 xi = np.linspace(x.min(), x.max(), nx) yi",
"cols h = size * rows fig = libplot.new_base_fig(w=w, h=h) if colors is",
"# #A = A[0:500, 0:500] # # G=nx.from_numpy_matrix(A) # pos=nx.spring_layout(G) #, k=2) #",
"h=h, cluster_order=cluster_order, legend=legend, sort=sort, show_axes=show_axes, fig=fig, ax=ax) #libtsne.tsne_legend(ax, labels, colors) #libcluster.format_simple_axes(ax, title=\"t-SNE\") #libcluster.format_legend(ax,",
"create a new axis and attach to figure before returning. \"\"\" if ax",
"np.linspace(y.min(), y.max(), 100, endpoint=True) # # xp = points[hull.vertices, 0] yp = points[hull.vertices,",
"def mkdir(path): \"\"\" Make dirs including any parents and avoid raising exception to",
"EXP_NORM = matplotlib.colors.Normalize(-1, 3, clip=True) LEGEND_PARAMS = {'show': True, 'cols': 4, 'markerscale': 2}",
"for a, b in zip(x, y)]) sd = d.std() m = d.mean() print(m,",
"clusters : DataFrame Clusters in colors : list, color Colors of points add_titles",
"print(id) print(np.where(d.index.str.contains(id))[0]) sc[np.where(d.index.str.contains(id))[0]] = s c += 1 print(np.unique(d.index.values)) print(np.unique(sc)) df = pd.DataFrame(sc,",
"# libplot.newfig(w=9) df2 = pd.DataFrame({'Silhouette Score': x2, 'Cluster': clusters.iloc[:, 0].tolist( ), 'Label': np.repeat('tsne-ah',",
"overlaps.append(o) df = pd.DataFrame( {'Cluster': list(range(1, c1.shape[0] + 1)), 'Overlap %': overlaps}) df.set_index('Cluster',",
"False if ax is None: fig, ax = libplot.new_fig(w, h) is_first = True",
"zip(x, y)]) hull = ConvexHull(points) #x1 = x[idx] #y1 = y[idx] # avg1",
"gene_names=gene_names) bin_means, bin_edges, binnumber = binned_statistic(exp, exp, bins=bins) print(binnumber.min(), binnumber.max()) iw = w",
"';' in data.index[0]: ids, genes = data.index.str.split(';').str else: genes = data.index ids =",
"d_b = umi_norm_log2(d_b) else: d_b = umi_norm_log2_scale(d_b) pca_b = libtsne.load_pca(d_b, 'b', cache=cache) #",
"if add_titles: if isinstance(cluster, int): prefix = 'C' else: prefix = '' ax.set_title('{}{}",
"fig, ax = expr_plot(tsne, exp, cmap=cmap, dim=dim, w=w, h=h, s=s, colorbar=colorbar, norm=norm, alpha=alpha,",
"x,y limits to look pretty. \"\"\" d1 = tsne.iloc[:, 0] d2 = tsne.iloc[:,",
"function.' % version) feature_ids = [x.decode('ascii', 'ignore') for x in f['matrix']['features']['id']] feature_names =",
"1).tolist() # node_color = (clusters['Cluster'] - 1).tolist() # # fig, ax = libplot.newfig(w=10,",
"n): for j in range(i + 1, n): ax = libplot.new_ax(fig, subplot=(rows, rows,",
"(the clusters) imageWithEdges = im1.filter(ImageFilter.FIND_EDGES) im_data = np.array(imageWithEdges.convert('RGBA')) #r = data[:, :, 0]",
"genome) except KeyError: raise Exception(\"File is missing one or more required datasets.\") #GeneBCMatrix",
"idx = idx[0] else: # if id does not exist, try the gene",
"s=s, w=w, h=h, cluster_order=cluster_order, legend=legend, sort=sort, show_axes=show_axes, fig=fig, ax=ax) #libtsne.tsne_legend(ax, labels, colors) #libcluster.format_simple_axes(ax,",
"Plot width h : int, optional Plot height alpha : float (0, 1),",
"gene_ids = get_gene_ids(data, genes, ids=ids, gene_names=gene_names) for i in range(0, len(gene_ids)): gene_id =",
"libplot.format_axes(ax) libplot.savefig(fig, '{}_centroids.pdf'.format(name)) def centroid_network(tsne, clusters, name): c = centroids(tsne, clusters) A =",
"c_b, 'b', dir='b') create_merge_cluster_info(d_b, c_b, 'b', sample_names=samples, dir='b') create_cluster_samples(tsne_b, c_b, samples, 'b_sample', dir='b')",
"= im_data[:, :, 0] # g = im_data[:, :, 1] # b =",
"TSNE import sklearn.preprocessing from sklearn.preprocessing import StandardScaler from sklearn.preprocessing import RobustScaler from sklearn.preprocessing",
"out = '{}/{}_{}_separate_clusters.png'.format(dir, method, name) libplot.savefig(fig, out, pad=0) #libplot.savefig(fig, '{}/tsne_{}separate_clusters.pdf'.format(dir, name)) # #",
"new Matplotlib figure used to make the plot \"\"\" if type(genes) is pd.core.frame.DataFrame:",
"not appear to be z-scored. Transforming now...') # zscore #e = (e -",
"colors=None, cols=-1, size=SUBPLOT_SIZE, add_titles=True, cluster_order=None, method='tsne', dir='.', out=None): fig = cluster_grid(tsne, clusters, colors=colors,",
"with tables.open_file(filename, 'r') as f: try: dsets = {} print(f.list_nodes('/')) for node in",
"found, creating it with...'.format(file)) # Find the interesting clusters labels, graph, Q =",
"tsne, genes, prefix='', dim=[1, 2], index=None, dir='GeneExp', cmap=BGY_CMAP, norm=None, w=4, h=4, s=30, alpha=ALPHA,",
"libcluster.get_colors() if ax is None: fig, ax = libplot.new_fig(w=w, h=h) ids = list(sorted(set(clusters['Cluster'])))",
"cols)) w = size * cols h = size * rows fig =",
"h=16, legend=True): sc = sample_clusters(clusters, sample_names) create_cluster_plot(tsne_umi_log2, sc, name, method=method, format=format, dir=dir, w=w,",
"1] for i in range(0, clusters.shape[0])] # def network(tsne, clusters, name, k=5): #",
"= 0.5 # # #print(c1) # # ax.scatter(x[i], # y[i], # c=[c1], #",
"cluster separately to highlight samples # # Parameters # ---------- # tsne :",
"isinstance(d_a, SparseDataFrame): d_a = umi_norm_log2(d_a) else: d_a = umi_norm_log2_scale(d_a) pca_a = libtsne.load_pca(d_a, 'a',",
"sparse') sd = StandardScaler(with_mean=False).fit_transform(d.T.matrix) return SparseDataFrame(sd.T, index=d.index, columns=d.columns) else: # StandardScaler().fit_transform(d.T) sd =",
"name): c = centroids(tsne, clusters) A = kneighbors_graph(c, 5, mode='distance', metric='euclidean').toarray() G =",
"x[idx] y = y[idx] points = np.array([[p1, p2] for p1, p2 in zip(x,",
"clip=None, min=None, max=None, axis=1): if isinstance(d, SparseDataFrame): print('UMI norm log2 scale sparse') sd",
"version) feature_ids = [x.decode('ascii', 'ignore') for x in f['matrix']['features']['id']] feature_names = [x.decode('ascii', 'ignore')",
"& (r == g) & (r == b) & (g == b) black_areas",
"list of gene names.\" % gene_name) return gbm.matrix[gene_indices[0], :].toarray().squeeze() def gbm_to_df(gbm): return pd.DataFrame(gbm.matrix.todense(),",
"= counts.iloc[:, idx] d_a = libcluster.remove_empty_rows(d_a) if isinstance(d_a, SparseDataFrame): d_a = umi_norm_log2(d_a) else:",
"norm=norm) #libcluster.format_simple_axes(ax, title=t) if not show_axes: libplot.invisible_axes(ax) return fig, ax # def expr_plot(tsne,",
"Cluster column giving each cell a cluster label. s : int, optional Marker",
"= pd.read_csv('../../../../expression_genes.txt', header=0) mkdir('a') a_barcodes = pd.read_csv('../a_barcodes.tsv', header=0, sep='\\t') idx = np.where(counts.columns.isin(a_barcodes['Barcode'].values))[0] d_a",
": matplotlib figure, optional Supply a figure object on which to render the",
"fx = interp1d(points[hull.vertices, 0], points[hull.vertices, 1], kind='cubic') # fy = interp1d(points[hull.vertices, 1], points[hull.vertices,",
"im = imagelib.open(tmp) if outline: im_no_bg = imagelib.remove_background(im) im_edges = imagelib.edges(im) im_outline =",
"h=10) # # nx.draw_networkx(G, pos=pos, with_labels=False, ax=ax, node_size=50, node_color=node_color, vmax=(clusters['Cluster'].max() - 1), cmap=libcluster.colormap())",
"1 return fig def pca_plot_base(pca, clusters, pc1=1, pc2=2, marker='o', labels=False, s=MARKER_SIZE, w=8, h=8,",
"'png') def genes_expr_outline(data, tsne, genes, prefix='', index=None, dir='GeneExp', cmap=BGY_CMAP, norm=None, w=6, s=30, alpha=1,",
"be rendered Returns ------- fig : Matplotlib figure A new Matplotlib figure used",
"with tables.open_file(filename, 'w', filters=flt) as f: try: group = f.create_group(f.root, genome) f.create_carray(group, 'genes',",
"returned. ax : matplotlib axis If ax is a supplied argument, return this,",
"legend=True, show_axes=False, sort=True, cluster_order=None, fig=None, ax=None, out=None): fig, ax = base_cluster_plot(tsne, clusters, markers=markers,",
"df = pd.DataFrame( {'Cluster': list(range(1, c1.shape[0] + 1)), 'Overlap %': overlaps}) df.set_index('Cluster', inplace=True)",
"Whether to show axes on plot legend : bool, optional, default true Whether",
"for i in range(0, len(cids)): c = cids[i] x = tsne.iloc[np.where(clusters['Cluster'] == c)[0],",
"df def to_csv(gbm, file, sep='\\t'): df(gbm).to_csv(file, sep=sep, header=True, index=True) def sum(gbm, axis=0): return",
"# # # mean = color.mean() # # #print(x[i], y[i], mean) # #",
"marker=marker, s=s, alpha=alpha, fig=fig, w=w, h=h, ax=ax, show_axes=show_axes, colorbar=colorbar, norm=norm, linewidth=linewidth, edgecolors=edgecolors) if",
"is pd.core.frame.DataFrame: genes = genes['Genes'].values ids, gene_names = get_gene_names(data) gene_ids = get_gene_ids(data, genes,",
"libplot.boxplot(df, 'Cluster', 'Silhouette Score', colors=libcluster.colors(), ax=ax) ax.set_ylim([-1, 1]) ax.set_title('tsne-10x') #libplot.savefig(fig, 'RK10001_10003_clust-phen_silhouette.pdf') ax =",
"norm=norm, # edgecolors=[color], # linewidth=linewidth) #libcluster.format_axes(ax, title=t) return fig, ax def expr_plot(data, exp,",
"tsne_bin = tsne.iloc[idx_bin, :] expr_plot(tsne_bin, exp_bin, cmap=cmap, s=s, colorbar=colorbar, norm=norm, alpha=alpha, linewidth=linewidth, edgecolors=edgecolors,",
"BGY_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list('bgy', ['#003366', '#40bf80', '#ffff33']) BGY_ORIG_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list( 'bgy', ['#002255', '#003380', '#2ca05a',",
"is a cell reads_per_bc = data.sum(axis=0) scaling_factors = 1000000 / reads_per_bc scaled =",
"* rows fig = libplot.new_base_fig(w=w, h=w) si = 1 for i in range(0,",
"name, colors=None, size=4, add_titles=True, type='tsne', format='pdf'): \"\"\" Plot each cluster into its own",
"dir='.', out=None): if out is None: # libtsne.get_tsne_plot_name(name)) out = '{}/{}_{}.{}'.format(dir, method, name,",
"ids=None, gene_names=None): \"\"\" For a given gene list, get all of the transcripts.",
"exp, t='PC', dim=dim, cmap=cmap, marker=marker, s=s, fig=fig, alpha=alpha, ax=ax, norm=norm) return fig, ax",
"# im2.paste(im_smooth, (0, 0), im_smooth) # # # overlay edges on top of",
"mean) # # #if mean > 0.5: # ax.scatter(x[i], # y[i], # c='#ffffff00',",
"np.where(gene_names == g)[0] if idx.size > 0: idx = idx[0] else: return None",
"in range(0, len(ids)): l = ids[i] #print('Label {}'.format(l)) indices = np.where(clusters['Cluster'] == l)[0]",
"# # # d = im_data[np.where(grey_areas)] # d[:, :] = [255, 255, 255,",
"= data.index ids = genes return ids.values, genes.values def get_gene_ids(data, genes, ids=None, gene_names=None):",
"# im_no_bg im_smooth = imagelib.smooth(im_outline) imagelib.save(im_smooth, 'smooth.png') # im_smooth imagelib.paste(im_base, im_smooth, inplace=True) else:",
"pca_expr_plot(data, expr, name, dim=[1, 2], cmap=None, marker='o', s=MARKER_SIZE, alpha=EXP_ALPHA, fig=None, ax=None, norm=None): #",
"be labeled 'TSNE-1', 'TSNE-2' etc clusters : DataFrame Clusters in colors : list,",
"column giving each cell a cluster label. s : int, optional Marker size",
"pd.DataFrame(RobustScaler().fit_transform(d), index=d.index, columns=d.columns) else: return pd.DataFrame(RobustScaler().fit_transform(d.T).T, index=d.index, columns=d.columns) def umi_norm_log2_scale(data, clip=None): d =",
":] > 0)[0] ids3 = np.intersect1d(ids1, ids2) o = len(ids3) / 5 *",
"yi)) #ax.contour(xi, yi, z, levels=1) def gene_expr(data, tsne, gene, fig=None, ax=None, cmap=plt.cm.plasma, out=None):",
"if isinstance(d_a, SparseDataFrame): d_a = umi_norm_log2(d_a) else: d_a = umi_norm_log2_scale(d_a) pca_a = libtsne.load_pca(d_a,",
"markerscale=2) return fig, ax def base_expr_plot(data, exp, dim=[1, 2], cmap=plt.cm.plasma, marker='o', edgecolors=EDGE_COLOR, linewidth=1,",
"\"\"\" # fig = tsne_cluster_sample_grid(tsne, clusters, samples, colors, size) # # libplot.savefig(fig, '{}/tsne_{}_sample_clusters.png'.format(dir,",
"genes, ids=ids, gene_names=gene_names) w, h, rows, cols = expr_grid_size(gene_ids, size=size) fig = libplot.new_base_fig(w=w,",
"zscore #e = (e - e.mean()) / e.std() #print(e.min(), e.max()) # z-score #e",
"GeneBCMatrix(feature_ids, feature_names, decode(barcodes), matrix) def save_matrix_to_h5(gbm, filename, genome): flt = tables.Filters(complevel=1) with tables.open_file(filename,",
"#sd = sd.T if isinstance(clip, float) or isinstance(clip, int): max = abs(clip) min",
"- 1], pca.iloc[i, pc2 - 1]) ax.text(pca.iloc[i, pc1 - 1], pca.iloc[i, pc2 -",
"2], index=None, dir='GeneExp', cmap=BGY_CMAP, norm=None, w=4, h=4, s=30, alpha=ALPHA, linewidth=EDGE_WIDTH, edgecolors='none', colorbar=True, method='tsne',",
"mode='distance', metric='euclidean').toarray() # # #A = A[0:500, 0:500] # # G=nx.from_numpy_matrix(A) # pos=nx.spring_layout(G)",
"= np.zeros(x.size) #avg[idx] #avg1[idx] = 1 # fx = interp1d(points[hull.vertices, 0], points[hull.vertices, 1],",
"ax=None): \"\"\" Create a tsne plot without the formatting \"\"\" if ax is",
"basic t-sne expression plot. # # Parameters # ---------- # data : pandas.DataFrame",
"plot \"\"\" if type(genes) is pd.core.frame.DataFrame: genes = genes['Genes'].values ids, gene_names = get_gene_names(data)",
"#e = (e - e.mean()) / e.std() # limit to 3 std for",
"x.size, y.sum() / y.size] centroid = [(x * avg[idx]).sum() / avg[idx].sum(), (y *",
"tsne2, clusters, name, k=5): c1 = centroids(tsne1, clusters) c2 = centroids(tsne2, clusters) a1",
"genome): with tables.open_file(filename, 'r') as f: try: dsets = {} print(f.list_nodes('/')) for node",
"= size * cols h = size * rows fig = libplot.new_base_fig(w=w, h=h)",
"0.3, 0.3] #'#4d4d4d' EDGE_WIDTH = 0 # 0.25 ALPHA = 0.9 BLUE_YELLOW_CMAP =",
"# zscore #e = (e - e.mean()) / e.std() #print(e.min(), e.max()) # z-score",
"tsne.iloc[:, 0].values # data['{}-{}'.format(t, d1)][idx] y = tsne.iloc[:, 1].values # data['{}-{}'.format(t, d2)][idx] idx",
"c in cluster_order: i = c - 1 cluster = ids[i] # look",
"color=color, size=w, s=s, linewidth=linewidth, add_titles=False) # get x y lim xlim = ax.get_xlim()",
"3] = 3 ax.scatter(x, y, c=e, s=s, marker=marker, alpha=alpha, cmap=cmap, norm=norm, edgecolors='none', #",
"------- object : Pandas DataFrame shape(n_cells, n_genes) \"\"\" df = pd.DataFrame(gbm.matrix.todense()) df.index =",
"df(gbm): \"\"\" Converts a GeneBCMatrix to a pandas dataframe (dense) Parameters ---------- gbm",
"else: color = 'black' ax = libplot.new_ax(fig, subplot=(rows, cols, pc)) separate_cluster(tsne, clusters, cluster,",
"# limit to 3 std for z-scores #e[e < -3] = -3 #e[e",
"l = x elif type(x) is list: l = len(x) elif type(x) is",
"for i in range(0, d.shape[0])], dtype=object) c = 1 for s in sample_names:",
"without the formatting Parameters ---------- d : Pandas dataframe t-sne, umap data clusters",
"from scipy.spatial import distance import networkx as nx import os import phenograph import",
"ImageFilter from scipy.stats import binned_statistic import imagelib TNSE_AX_Q = 0.999 MARKER_SIZE = 10",
"None: libplot.savefig(fig, out, pad=0) return fig, ax def base_pca_expr_plot(data, exp, dim=[1, 2], cmap=None,",
"metric='euclidean').toarray() G = nx.from_numpy_matrix(A) pos = nx.spring_layout(G) fig, ax = libplot.newfig(w=8, h=8) #",
"== -1)] = new_label labels += 1 libtsne.write_clusters(headers, labels, name) cluster_map, data =",
"# Clusters in # # Returns # ------- # fig : Matplotlib figure",
"is None: norm = matplotlib.colors.Normalize(vmin=-3, vmax=3, clip=True) #cmap = plt.cm.plasma ids, gene_names =",
"name): # measure cluster worth x1 = silhouette_samples( tsne, clusters.iloc[:, 0].tolist(), metric='euclidean') x2",
"0] y = tsne_other.iloc[:, 1] libplot.scatter(x, y, c=[background], ax=ax, edgecolors='none', # bgedgecolor, linewidth=linewidth,",
"out = 'pca_expr_{}_t{}_vs_t{}.pdf'.format(name, 1, 2) fig, ax = base_pca_expr_plot(data, expr, dim=dim, cmap=cmap, marker=marker,",
"create_pca_plot(pca_b, c_b, 'b', dir='b') create_cluster_plot(tsne_b, c_b, 'b', dir='b') create_cluster_grid(tsne_b, c_b, 'b', dir='b') create_merge_cluster_info(d_b,",
"+ 1)), 'Overlap %': overlaps}) df.set_index('Cluster', inplace=True) df.to_csv('{}_cluster_overlaps.txt'.format(name), sep='\\t') def mkdir(path): \"\"\" Make",
"(g == b) # # #d = im_data[np.where(black_areas)] # #d[:, 0:3] = [64,",
"overlay edges on top of original image to highlight cluster # enable if",
"= int(np.ceil(np.sqrt(len(cids)))) # # w = size * rows # # fig =",
"h=h, cluster_order=cluster_order, show_axes=show_axes, legend=legend, sort=sort, out=out) def base_tsne_plot(tsne, marker='o', s=libplot.MARKER_SIZE, c='red', label=None, fig=None,",
"dim2=1, markers='o', s=libplot.MARKER_SIZE, colors=None, w=8, h=8, legend=True, show_axes=False, sort=True, cluster_order=None, fig=None, ax=None, out=None):",
"# pos=nx.spring_layout(G) #, k=2) # # #node_color = (c_phen['Cluster'][0:A.shape[0]] - 1).tolist() # node_color",
"axis=axis) #sd = sd.T if isinstance(clip, float) or isinstance(clip, int): max = abs(clip)",
"= data[:, :, 1] #b = data[:, :, 2] a = im_data[:, :,",
"matplotlib.colors.Normalize(vmin=-3, vmax=3, clip=True) #cmap = plt.cm.plasma ids, gene_names = get_gene_names(data) gene_ids = get_gene_ids(data,",
"marker=marker, s=s) def pca_base_plots(pca, clusters, n=10, marker='o', s=MARKER_SIZE): rows = libplot.grid_size(n) w =",
"dataframe features x dimensions, e.g. rows are cells and columns are tsne dimensions",
"colorbar=colorbar, norm=norm, alpha=alpha, linewidth=linewidth, edgecolors=edgecolors, ax=ax) tmp = 'tmp{}.png'.format(bin) libplot.savefig(fig, tmp, pad=0) plt.close(fig)",
"cols=legend_params['cols'], markerscale=legend_params['markerscale']) return fig, ax def base_cluster_plot_outline(out, d, clusters, s=libplot.MARKER_SIZE, colors=None, edgecolors=EDGE_COLOR, linewidth=EDGE_WIDTH,",
"# cids = list(sorted(set(clusters['Cluster']))) # # rows = int(np.ceil(np.sqrt(len(cids)))) # # w =",
": Matplotlib axes Axes used to render the figure \"\"\" if ax is",
"clusters, name, k=5): c1 = centroids(tsne1, clusters) c2 = centroids(tsne2, clusters) a1 =",
"# BGY_CMAP, norm=None, w=libplot.DEFAULT_WIDTH, h=libplot.DEFAULT_HEIGHT, alpha=1.0, colorbar=False, method='tsne', fig=None, ax=None, sdmax=0.5): \"\"\" Plot",
"Specify how colors should be normalized Returns ------- fig : matplotlib figure If",
"os.makedirs(path) except: pass def split_a_b(counts, samples, w=6, h=6, format='pdf'): \"\"\" Split cells into",
"for i in range(0, x.size): # en = norm(e[i]) # color = cmap(int(en",
"H5 file.\") def subsample_matrix(gbm, barcode_indices): return GeneBCMatrix(gbm.gene_ids, gbm.gene_names, gbm.barcodes[barcode_indices], gbm.matrix[:, barcode_indices]) def get_expression(gbm,",
"\"\"\" Auto size grid to look nice. \"\"\" if type(x) is int: l",
"in range(i + 1, pca.shape[1]): create_cluster_plot(pca, labels, name, pc1=( i + 1), pc2=(j",
"umi_norm_log2_scale(d_a) pca_a = libtsne.load_pca(d_a, 'a', cache=cache) # pca.iloc[idx,:] tsne_a = libtsne.load_pca_tsne(pca_a, 'a', cache=cache)",
"64] im_data[np.where(black_areas)] = d im2 = Image.fromarray(im_data) im2.save('edges.png', 'png') # overlay edges on",
"0.3) np.random.seed(0) GeneBCMatrix = collections.namedtuple( 'GeneBCMatrix', ['gene_ids', 'gene_names', 'barcodes', 'matrix']) def decode(items): return",
"object : Pandas DataFrame shape(n_cells, n_genes) \"\"\" df = pd.DataFrame(gbm.matrix.todense()) df.index = gbm.gene_names",
"if ax is None: fig, ax = libplot.new_fig(w, h) is_first = True base_expr_plot(data,",
"ax = base_cluster_plot(tsne, clusters, markers=markers, colors=colors, dim1=dim1, dim2=dim2, s=s, w=w, h=h, cluster_order=cluster_order, legend=legend,",
"tsne : Pandas dataframe Cells x tsne tsne data. Columns should be labeled",
"cluster - 1 if i < len(colors): # colors[cid - 1] #colors[i] #np.where(clusters['Cluster']",
"= size * rows fig = libplot.new_base_fig(w=w, h=h) if colors is None: colors",
"ids[index], gene_names[index])) else: # if id does not exist, try the gene names",
"pc1 - 1], pca.iloc[i, pc2 - 1], pca.index[i]) return fig, ax def pca_plot(pca,",
"of centroid idx = np.where(abs(z) < sdmax)[0] # (d > x1) & (d",
"new one is created. ax : matplotlib ax, optional Supply an axis object",
"pc += 1 return fig def create_cluster_grid(tsne, clusters, name, colors=None, cols=-1, size=SUBPLOT_SIZE, add_titles=True,",
"= tsne.iloc[:, 1] xlim = [d1[d1 < 0].quantile(1 - TNSE_AX_Q), d1[d1 >= 0].quantile(TNSE_AX_Q)]",
"title=\"t-SNE\") #libcluster.format_legend(ax, cols=6, markerscale=2) if out is not None: libplot.savefig(fig, out) return fig,",
"first idx = idx[0] else: # if id does not exist, try the",
"ax=ax, norm=norm) return fig, ax def pca_expr_plot(data, expr, name, dim=[1, 2], cmap=None, marker='o',",
"'C' else: prefix = '' ax.set_title('{}{} ({:,})'.format( prefix, cluster, len(idx1)), color=color) ax.axis('off') #",
"SparseDataFrame): d_b = umi_norm_log2(d_b) else: d_b = umi_norm_log2_scale(d_b) pca_b = libtsne.load_pca(d_b, 'b', cache=cache)",
"found in list of gene names.\" % gene_name) return gbm.matrix[gene_indices[0], :].toarray().squeeze() def gbm_to_df(gbm):",
"is missing one or more required datasets.\") #GeneBCMatrix = collections.namedtuple('FeatureBCMatrix', ['feature_ids', 'feature_names', 'barcodes',",
"y[idx] points = np.array([[p1, p2] for p1, p2 in zip(x, y)]) hull =",
"x = tsne.iloc[idx2, 0] # y = tsne.iloc[idx2, 1] # libplot.scatter(x, y, c=BACKGROUND_SAMPLE_COLOR,",
"edgecolor=color, s=s, marker=marker, alpha=libplot.ALPHA, label=label) if labels: l = pca.index.values for i in",
"return umi_log2(d) def scale(d, clip=None, min=None, max=None, axis=1): if isinstance(d, SparseDataFrame): print('UMI norm",
"# pca.iloc[idx,:] tsne_a = libtsne.load_pca_tsne(pca_a, 'a', cache=cache) c_a = libtsne.load_phenograph_clusters(pca_a, 'a', cache=cache) create_pca_plot(pca_a,",
"linewidth=linewidth) # # # # mean = color.mean() # # #print(x[i], y[i], mean)",
"cluster)[0] idx2 = np.where(clusters['Cluster'] != cluster)[0] # Plot background points if show_background: x",
"pca_plot(pca, clusters, pc1=1, pc2=2, marker='o', labels=False, s=MARKER_SIZE, w=8, h=8, legend=True, fig=None, ax=None): fig,",
"len(x) elif type(x) is np.ndarray: l = x.shape[0] elif type(x) is pd.core.frame.DataFrame: l",
"d # # # #edges1 = feature.canny(rgb2gray(im_data)) # # #print(edges1.shape) # # #skimage.io.imsave('tmp_canny_{}.png'.format(bin),",
"'matrix']) def get_matrix_from_h5_v2(filename, genome): with h5py.File(filename, 'r') as f: if u'version' in f.attrs:",
"# x = tsne.iloc[idx2, 0] # y = tsne.iloc[idx2, 1] # # libplot.scatter(x,",
"dtype=object) c = 1 for s in sample_names: id = '-{}'.format(c) print(id) print(np.where(d.index.str.contains(id))[0])",
"ax = libplot.new_fig(w=w, h=h) # if norm is None and exp.min() < 0:",
"colorbar=colorbar) # # set_tsne_ax_lim(tsne, ax) # # libplot.invisible_axes(ax) # # if out is",
"ids, gene_names = get_gene_names(data) print(ids, gene_names, genes) gene_ids = get_gene_ids(data, genes, ids=ids, gene_names=gene_names)",
"%': overlaps}) df.set_index('Cluster', inplace=True) df.to_csv('{}_cluster_overlaps.txt'.format(name), sep='\\t') def mkdir(path): \"\"\" Make dirs including any",
"['AICDA', 'CD83', 'CXCR4', 'MKI67', 'MYC', 'PCNA', 'PRDM1'] genes = pd.read_csv('../../../../expression_genes.txt', header=0) mkdir('a') a_barcodes",
"m = d.mean() print(m, sd) z = (d - m) / sd #",
"ax) # libcluster.format_axes(ax) if not show_axes: libplot.invisible_axes(ax) legend_params = dict(LEGEND_PARAMS) if isinstance(legend, bool):",
"import matplotlib # matplotlib.use('agg') import matplotlib.pyplot as plt import collections import numpy as",
"# #black_areas = (a > 0) #(r < 255) | (g < 255)",
"edgecolors=[color], # linewidth=linewidth) #libcluster.format_axes(ax, title=t) return fig, ax def expr_plot(data, exp, dim=[1, 2],",
"linewidth=EDGE_WIDTH, fig=None, ax=None): \"\"\" Plot a cluster separately to highlight where the samples",
"colors[i] # l] else: color = 'black' ax.scatter(x, y, color=color, edgecolor=color, s=s, marker=marker,",
"= [] for i in range(len(gbm.barcodes)): ret.append(np.sum(gbm.matrix[:, i].toarray())) return ret def df(gbm): \"\"\"",
"# norm=norm, # w=w, # h=h, # colorbar=colorbar) # # set_tsne_ax_lim(tsne, ax) #",
"> 0: for index in indexes: ret.append((index, ids[index], gene_names[index])) else: # if id",
"ax def base_pca_expr_plot(data, exp, dim=[1, 2], cmap=None, marker='o', s=MARKER_SIZE, alpha=EXP_ALPHA, fig=None, ax=None, norm=None):",
"plt.cm.plasma ids, gene_names = get_gene_names(data) print(ids, gene_names, genes) gene_ids = get_gene_ids(data, genes, ids=ids,",
"{}'.format(l)) indices = np.where(clusters['Cluster'] == l)[0] n = len(indices) label = 'C{} ({:,})'.format(l,",
"= np.array(imageWithEdges.convert('RGBA')) #r = data[:, :, 0] #g = data[:, :, 1] #b",
"libcluster.remove_empty_rows(d_b) if isinstance(d_a, SparseDataFrame): d_b = umi_norm_log2(d_b) else: d_b = umi_norm_log2_scale(d_b) pca_b =",
"new figure is created and returned. ax : matplotlib axis If ax is",
"z, levels=1) def gene_expr(data, tsne, gene, fig=None, ax=None, cmap=plt.cm.plasma, out=None): \"\"\" Plot multiple",
"title=t) return fig, ax def expr_plot(data, exp, dim=[1, 2], cmap=plt.cm.magma, marker='o', s=MARKER_SIZE, alpha=1,",
"= matplotlib.colors.LinearSegmentedColormap.from_list('bgy', ['#0066ff', '#37c871', '#ffd42a']) # BGY_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list('bgy', ['#003380', '#5fd38d', '#ffd42a']) EXP_NORM",
"y = tsne.iloc[idx2, 1] libplot.scatter(x, y, c=[background], ax=ax, edgecolors='none', # bgedgecolor, linewidth=linewidth, s=s)",
"cluster_map, data = libtsne.read_clusters(file) labels = data # .tolist() return cluster_map, labels def",
"cluster_grid(tsne, clusters, colors=colors, cols=cols, size=size, add_titles=add_titles, cluster_order=cluster_order) if out is None: out =",
"marker=marker, # s=s, # alpha=alpha, # fig=fig, # ax=ax, # norm=norm, # w=w,",
"2) fig, ax = base_pca_expr_plot(data, expr, dim=dim, cmap=cmap, marker=marker, s=s, alpha=alpha, fig=fig, ax=ax,",
"labels[i] = i + 1 #nx.draw_networkx(G, pos=pos, with_labels=False, ax=ax, node_size=200, node_color=node_color, vmax=(c.shape[0] -",
"matplotlib.colors.Normalize(vmin=-3, vmax=3, clip=True) #cmap = plt.cm.plasma ids, gene_names = get_gene_names(data) exp = get_gene_data(data,",
"edgecolors='none', # edgecolors, linewidth=linewidth) # for i in range(0, x.size): # en =",
"Sort by expression level so that extreme values always appear on top idx",
"2 if l % cols == 0: # Assume we will add a",
"the background # # sid = 0 # # for sample in samples:",
"fig, ax = base_cluster_plot(tsne, clusters, markers=markers, colors=colors, dim1=dim1, dim2=dim2, s=s, w=w, h=h, cluster_order=cluster_order,",
"idx1 = np.where((clusters['Cluster'] == c) & clusters.index.str.contains(id))[0] # # x = tsne.iloc[idx1, 0]",
"/ avg[idx].sum(), (y * avg[idx]).sum() / avg[idx].sum()] d = np.array([distance.euclidean(centroid, (a, b)) for",
"legend : bool, optional, default true Whether to show legend. \"\"\" if ax",
"t='PC', dim=dim, cmap=cmap, marker=marker, s=s, fig=fig, alpha=alpha, ax=ax, norm=norm) return fig, ax def",
"np.linspace(x.min(), x.max(), 100, endpoint=True) # yt = np.linspace(y.min(), y.max(), 100, endpoint=True) # #",
"x = tsne.iloc[idx1, 0] y = tsne.iloc[idx1, 1] #print('sep', cluster, color) color =",
"# fig : Matplotlib figure # A new Matplotlib figure used to make",
"edgecolors='none', #edgecolors, # linewidth=linewidth) # # # # mean = color.mean() # #",
"= nx.spring_layout(G) fig, ax = libplot.newfig(w=8, h=8) # list(range(0, c.shape[0])) node_color = libcluster.colors()[0:c.shape[0]]",
"fig=None, ax=None): \"\"\" Plot a cluster separately to highlight where the samples are",
"# if colorbar or is_first: if colorbar: libplot.add_colorbar(fig, cmap, norm=norm) #libcluster.format_simple_axes(ax, title=t) if",
"import SparseDataFrame from lib10x.sample import * from scipy.spatial import ConvexHull from PIL import",
"ax.set_ylim(ylim) if not show_axes: libplot.invisible_axes(ax) legend_params = dict(LEGEND_PARAMS) if isinstance(legend, bool): legend_params['show'] =",
"labeled 'TSNE-1', 'TSNE-2' etc genes : array List of gene names Returns -------",
"im_data[:, :, 3] # (r < 255) | (g < 255) | (b",
"im1) # # # Edge detect on what is left (the clusters) #",
"['#002255', '#003380', '#2ca05a', '#ffd42a', '#ffdd55']) # BGY_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list('bgy', ['#003366', '#339966', '#ffff66', '#ffff00')",
"centroids(tsne2, clusters) a1 = kneighbors_graph(c1, k, mode='distance', metric='euclidean').toarray() a2 = kneighbors_graph(c2, k, mode='distance',",
": Normalize, optional Specify how colors should be normalized Returns ------- fig :",
"legend=False, w=w, h=h) libplot.savefig(fig, 'b/b_tsne_clusters_med.pdf') def sample_clusters(d, sample_names): \"\"\" Create a cluster matrix",
"def cluster_grid(tsne, clusters, colors=None, cols=-1, size=SUBPLOT_SIZE, add_titles=True, cluster_order=None): \"\"\" Plot each cluster separately",
"gbm.matrix[:, barcode_indices]) def get_expression(gbm, gene_name, genes=None): if genes is None: genes = gbm.gene_names",
"Matplotlib figure A new Matplotlib figure used to make the plot \"\"\" if",
"len(gene_ids)): # gene id gene_id = gene_ids[i][1] gene = gene_ids[i][2] print(gene, gene_id) exp",
"pass if legend_params['show']: libcluster.format_legend(ax, cols=legend_params['cols'], markerscale=legend_params['markerscale']) return fig, ax def base_cluster_plot_outline(out, d, clusters,",
"im_data[:, :, 0] # g = im_data[:, :, 1] # b = im_data[:,",
"= [x.sum() / x.size, y.sum() / y.size] centroid = [(x * avg[idx]).sum() /",
"# # im2 = Image.fromarray(im_data) # # # Edge detect on what is",
"if out is None: out = '{}_expr.pdf'.format(method) fig, ax = expr_plot(tsne, exp, dim=dim,",
"= tables.Filters(complevel=1) with tables.open_file(filename, 'w', filters=flt) as f: try: group = f.create_group(f.root, genome)",
"alpha=alpha, cmap=cmap, norm=norm, w=w, h=h, ax=ax) # if colorbar or is_first: if colorbar:",
"h=h) if colors is None: colors = libcluster.get_colors() # Where to plot figure",
"c.shape[0]): labels[i] = i + 1 #nx.draw_networkx(G, pos=pos, with_labels=False, ax=ax, node_size=200, node_color=node_color, vmax=(c.shape[0]",
"= d # # # #edges1 = feature.canny(rgb2gray(im_data)) # # #print(edges1.shape) # #",
"= 'black' else: color = 'black' fig, ax = separate_cluster(d, clusters, cluster, color=color,",
"dim=dim, w=w, h=h, s=s, colorbar=colorbar, norm=norm, alpha=alpha, linewidth=linewidth, edgecolors=edgecolors) if gene_id != gene:",
"gene_expr(data, tsne, gene, fig=None, ax=None, cmap=plt.cm.plasma, out=None): \"\"\" Plot multiple genes on a",
"# w=w, # h=h, # colorbar=colorbar) # # set_tsne_ax_lim(tsne, ax) # # libplot.invisible_axes(ax)",
"node.read() print(dsets) matrix = sp_sparse.csc_matrix( (dsets['data'], dsets['indices'], dsets['indptr']), shape=dsets['shape']) return GeneBCMatrix(decode(dsets['genes']), decode(dsets['gene_names']), decode(dsets['barcodes']),",
"marker=marker, s=s, ax=ax) si += 1 return fig def pca_plot_base(pca, clusters, pc1=1, pc2=2,",
"# edgecolors=[color], # linewidth=linewidth) #libcluster.format_axes(ax, title=t) return fig, ax def expr_plot(data, exp, dim=[1,",
"f['matrix']['indices'], f['matrix']['indptr']), shape=f['matrix']['shape']) return GeneBCMatrix(feature_ids, feature_names, decode(barcodes), matrix) def save_matrix_to_h5(gbm, filename, genome): flt",
"clusters, name, k=5): # A = kneighbors_graph(tsne, k, mode='distance', metric='euclidean').toarray() # # #A",
"= matplotlib.colors.LinearSegmentedColormap.from_list( 'bu_pu', matplotlib.cm.BuPu(range(4, 256))) # BGY_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list('bgy', ['#0066ff', '#37c871', '#ffd42a']) #",
"pass def split_a_b(counts, samples, w=6, h=6, format='pdf'): \"\"\" Split cells into a and",
"idx = np.where(counts.columns.isin(a_barcodes['Barcode'].values))[0] d_a = counts.iloc[:, idx] d_a = libcluster.remove_empty_rows(d_a) if isinstance(d_a, SparseDataFrame):",
"from sklearn.manifold import TSNE import sklearn.preprocessing from sklearn.preprocessing import StandardScaler from sklearn.preprocessing import",
"# # def tsne_cluster_sample_grid(tsne, clusters, samples, colors=None, size=SUBPLOT_SIZE): # \"\"\" # Plot each",
"Colors of points add_titles : bool Whether to add titles to plots w:",
"axis == 0: return pd.DataFrame(MinMaxScaler(feature_range=(min, max)).fit_transform(d), index=d.index, columns=d.columns) else: return pd.DataFrame(MinMaxScaler(feature_range=(min, max)).fit_transform(d.T).T, index=d.index,",
"# exp, # t='TSNE', # d1=d1, # d2=d2, # x1=x1, # x2=x2, #",
":, 0] # g = im_data[:, :, 1] # b = im_data[:, :,",
"0] # y = tsne.iloc[idx2, 1] # # libplot.scatter(x, y, c=BACKGROUND_SAMPLE_COLOR, ax=ax) #",
"print(pca.shape, pca.iloc[i, pc1 - 1], pca.iloc[i, pc2 - 1]) ax.text(pca.iloc[i, pc1 - 1],",
"# # Parameters # ---------- # tsne : Pandas dataframe # Cells x",
"to make the plot # \"\"\" # # # cids = list(sorted(set(clusters['Cluster']))) #",
"plt.cm.plasma): \"\"\" Creates and saves a presentation tsne plot \"\"\" if out is",
"'TSNE-2' etc genes : array List of gene names \"\"\" if dir[-1] ==",
"else: # if id does not exist, try the gene names indexes =",
"min)] = min if isinstance(max, float) or isinstance(max, int): print('z max', max) sd[np.where(sd",
"exception to work more like mkdir -p Parameters ---------- path : str directory",
"'#f2f2f2' #(0.98, 0.98, 0.98) #(0.8, 0.8, 0.8) #(0.85, 0.85, 0.85 BACKGROUND_SAMPLE_COLOR = [0.75,",
"(avg - avg.mean()) / avg.std() avg[avg < -1.5] = -1.5 avg[avg > 1.5]",
"sep='\\t') idx = np.where(counts.columns.isin(a_barcodes['Barcode'].values))[0] d_a = counts.iloc[:, idx] d_a = libcluster.remove_empty_rows(d_a) if isinstance(d_a,",
"= 1.5 avg = (avg - avg.min()) / (avg.max() - avg.min()) # min_max_scale(avg)",
"0.75] EDGE_COLOR = None # [0.3, 0.3, 0.3] #'#4d4d4d' EDGE_WIDTH = 0 #",
"None else: idx = np.where(ids == g)[0] if idx.size > 0: # if",
"to write H5 file.\") def subsample_matrix(gbm, barcode_indices): return GeneBCMatrix(gbm.gene_ids, gbm.gene_names, gbm.barcodes[barcode_indices], gbm.matrix[:, barcode_indices])",
"of n cells with a Cluster column giving each cell a cluster label.",
"libcluster.colors()[0:c.shape[0]] cmap = libcluster.colormap() labels = {} for i in range(0, c.shape[0]): labels[i]",
"c = cids[i] x = tsne.iloc[np.where(clusters['Cluster'] == c)[0], :] centroid = (x.sum(axis=0) /",
"h = size * rows return w, h, rows, cols def get_gene_names(data): if",
"= matplotlib.colors.Normalize(vmin=-3, vmax=3, clip=True) #cmap = plt.cm.plasma ids, gene_names = get_gene_names(data) exp =",
"df(gbm).to_csv(file, sep=sep, header=True, index=True) def sum(gbm, axis=0): return gbm.matrix.sum(axis=axis) def tpm(gbm): m =",
"tsne_cluster_sample_grid(tsne, clusters, samples, colors, size) # # libplot.savefig(fig, '{}/tsne_{}_sample_clusters.png'.format(dir, name)) # #libplot.savefig(fig, '{}/tsne_{}separate_clusters.pdf'.format(dir,",
"return d.log2(add=1) else: return (d + 1).apply(np.log2) def umi_tpm_log2(data): d = umi_tpm(data) return",
"2] # # grey_areas = (r < 255) & (r > 200) &",
"fig=None, ax=None, out=None): fig, ax = base_cluster_plot(tsne, clusters, markers=markers, colors=colors, dim1=dim1, dim2=dim2, s=s,",
"overlay edges on top of original image to highlight cluster # im_base.paste(im2, (0,",
"300 im_base = imagelib.new(iw, iw) for bin in range(0, bins): bi = bin",
"#libplot.savefig(fig, '{}/tsne_{}separate_clusters.pdf'.format(dir, name)) # # # def tsne_cluster_sample_grid(tsne, clusters, samples, colors=None, size=SUBPLOT_SIZE): #",
"np.array([[x, y] for x, y in zip(x1, y1)]) #hull = ConvexHull(points) #ax.plot(points[hull.vertices,0], points[hull.vertices,1])",
"on what is left (the clusters) # im_edges = im2.filter(ImageFilter.FIND_EDGES) # # #",
"norm=norm, alpha=alpha, linewidth=linewidth, edgecolors=edgecolors) if gene_id != gene: out = '{}/{}_expr_{}_{}.{}'.format(dir, method, gene,",
"BGY_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list('bgy', ['#003366', '#339966', '#ffff66', '#ffff00') # BGY_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list('bgy', ['#001a33', '#003366',",
"norm=None, w=6, s=30, alpha=1, linewidth=EDGE_WIDTH, edgecolors='none', colorbar=True, method='tsne', bins=10, background=BACKGROUND_SAMPLE_COLOR): \"\"\" Plot multiple",
"-*- \"\"\" Created on Wed Jun 6 16:51:15 2018 @author: antony \"\"\" import",
"scaling_factors = 1000000 / reads_per_bc scaled = data.multiply(scaling_factors) # , axis=1) return scaled",
"not found in list of gene names.\" % gene_name) return gbm.matrix[gene_indices[0], :].toarray().squeeze() def",
"data. Columns should be labeled 'TSNE-1', 'TSNE-2' etc clusters : DataFrame Clusters in",
"s=s, linewidth=linewidth, add_titles=False, show_background=False) ax.set_xlim(xlim) ax.set_ylim(ylim) if not show_axes: libplot.invisible_axes(ax) legend_params = dict(LEGEND_PARAMS)",
"by sample/batch. \"\"\" sc = np.array(['' for i in range(0, d.shape[0])], dtype=object) c",
"abs(clip) min = -max if isinstance(min, float) or isinstance(min, int): print('z min', min)",
"None: # colors = libcluster.colors() # # for i in range(0, len(cids)): #",
"= 4 EXP_ALPHA = 0.8 # '#f2f2f2' #(0.98, 0.98, 0.98) #(0.8, 0.8, 0.8)",
": matplotlib axis If ax is a supplied argument, return this, otherwise create",
"cluster = ids[i] # look up index for color purposes #i = np.where(ids",
"x tsne tsne data. Columns should be labeled 'TSNE-1', 'TSNE-2' etc cluster :",
"im = imagelib.open(tmp) # im_no_bg = imagelib.remove_background(im) # im_smooth = imagelib.smooth_edges(im_no_bg) # imagelib.paste(im_no_bg,",
"ids=ids, gene_names=gene_names) avg = exp.mean(axis=0) avg = (avg - avg.mean()) / avg.std() avg[avg",
"#ax.plot(points[hull.vertices[0], 0], points[hull.vertices[[0, -1]], 1]) #points = np.array([[x, y] for x, y in",
"in colors: color = colors[i] # l] else: color = 'black' ax.scatter(x, y,",
"else: color = 'black' ax.scatter(x, y, color=color, edgecolor=color, s=s, marker=marker, alpha=libplot.ALPHA, label=label) if",
"sklearn.manifold import TSNE import sklearn.preprocessing from sklearn.preprocessing import StandardScaler from sklearn.preprocessing import RobustScaler",
"4 EXP_ALPHA = 0.8 # '#f2f2f2' #(0.98, 0.98, 0.98) #(0.8, 0.8, 0.8) #(0.85,",
"#libplot.add_colorbar(fig, cmap) exp_bin = exp[idx_bin] tsne_bin = tsne.iloc[idx_bin, :] expr_plot(tsne_bin, exp_bin, cmap=cmap, s=s,",
"libplot.new_fig(w, h) is_first = True base_expr_plot(data, exp, dim=dim, s=s, marker=marker, edgecolors=edgecolors, linewidth=linewidth, alpha=alpha,",
"int(np.ceil(np.sqrt(l))) w = size * cols rows = int(l / cols) + 2",
"== b) black_areas = (a > 0) d = im_data[np.where(black_areas)] d[:, 0:3] =",
"0.8) #(0.85, 0.85, 0.85 BACKGROUND_SAMPLE_COLOR = [0.75, 0.75, 0.75] EDGE_COLOR = None #",
"#im2.save('edges.png', 'png') # # im_smooth = im_edges.filter(ImageFilter.SMOOTH) # im_smooth.save('edges.png', 'png') # # im2.paste(im_smooth,",
"== cluster)[0][0] print('index', i, cluster, colors) if isinstance(colors, dict): color = colors.get(cluster, 'black')",
"pd.DataFrame( {'Cluster': list(range(1, c1.shape[0] + 1)), 'Overlap %': overlaps}) df.set_index('Cluster', inplace=True) df.to_csv('{}_cluster_overlaps.txt'.format(name), sep='\\t')",
"# 0.25 ALPHA = 0.9 BLUE_YELLOW_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list( 'blue_yellow', ['#162d50', '#ffdd55']) BLUE_CMAP =",
"cluster)[0]] color = colors[i] else: color = 'black' else: color = 'black' fig,",
"fig, ax def pca_plot(pca, clusters, pc1=1, pc2=2, marker='o', labels=False, s=MARKER_SIZE, w=8, h=8, legend=True,",
"c2 = centroids(tsne2, clusters) a1 = kneighbors_graph(c1, k, mode='distance', metric='euclidean').toarray() a2 = kneighbors_graph(c2,",
"path : str directory to create. \"\"\" try: os.makedirs(path) except: pass def split_a_b(counts,",
": Pandas DataFrame shape(n_cells, n_genes) \"\"\" df = pd.DataFrame(gbm.matrix.todense()) df.index = gbm.gene_names df.columns",
"imagelib.edges(im_no_bg) im_smooth = imagelib.smooth(im_edges) im_outline = imagelib.paste(im_no_bg, im_smooth) imagelib.paste(im_base, im_outline, inplace=True) # #",
"= min if isinstance(max, float) or isinstance(max, int): print('z max', max) sd[np.where(sd >",
"1: # if id does not exist, try the gene names idx =",
"= [x.decode('ascii', 'ignore') for x in f['matrix']['features']['name']] barcodes = list(f['matrix']['barcodes'][:]) matrix = sp_sparse.csc_matrix(",
"0] yp = points[hull.vertices, 1] xp = np.append(xp, xp[0]) yp = np.append(yp, yp[0])",
"cluster matrix based on by labelling cells by sample/batch. \"\"\" sc = np.array([''",
"= cluster_plot(tsne_a, c_a, legend=False, w=w, h=h) libplot.savefig(fig, 'a/a_tsne_clusters_med.pdf') # b mkdir('b') b_barcodes =",
"matplotlib.colors.LinearSegmentedColormap.from_list('bgy', ['#003366', '#339966', '#ffff66', '#ffff00') # BGY_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list('bgy', ['#001a33', '#003366', '#339933', '#ffff66',",
"is an older version that is not supported by this function.' % version)",
"grid. Parameters ---------- data : Pandas dataframe Genes x samples expression matrix tsne",
"dir[-1] == '/': dir = dir[:-1] if not os.path.exists(dir): mkdir(dir) if index is",
"ax.scatter(x, y, c=e, s=s, marker=marker, alpha=alpha, cmap=cmap, norm=norm, edgecolors='none', # edgecolors, linewidth=linewidth) #",
"more like mkdir -p Parameters ---------- path : str directory to create. \"\"\"",
"tsne_b, genes, prefix='b_BGY', cmap=BLUE_GREEN_YELLOW_CMAP, w=w, h=h, dir='b/GeneExp', format=format) fig, ax = cluster_plot(tsne_b, c_b,",
"if ax is None: fig, ax = libplot.new_fig(w=w, h=h) ids = list(sorted(set(clusters['Cluster']))) for",
"names Returns ------- fig : Matplotlib figure A new Matplotlib figure used to",
"Cells x tsne tsne data. Columns should be labeled 'TSNE-1', 'TSNE-2' etc cluster",
"= umi_norm_log2_scale(d_a) pca_a = libtsne.load_pca(d_a, 'a', cache=cache) # pca.iloc[idx,:] tsne_a = libtsne.load_pca_tsne(pca_a, 'a',",
"x y lim xlim = ax.get_xlim() ylim = ax.get_ylim() fig, ax = separate_cluster(d,",
"'TSNE-1', 'TSNE-2' etc cluster : int Clusters in colors : list, color Colors",
"plot # \"\"\" # # # cids = list(sorted(set(clusters['Cluster']))) # # rows =",
"pc1=pc1, pc2=pc2, marker=marker, labels=labels, s=s, w=w, h=h, fig=fig, ax=ax) #libtsne.tsne_legend(ax, labels, colors) libcluster.format_simple_axes(ax,",
"s=s, # marker=marker, # norm=norm, # edgecolors=[color], # linewidth=linewidth) #libcluster.format_axes(ax, title=t) return fig,",
"'#003380', '#2ca05a', '#ffd42a', '#ffdd55']) # BGY_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list('bgy', ['#003366', '#339966', '#ffff66', '#ffff00') #",
"= len(indices) label = 'C{} ({:,})'.format(l, n) df2 = pca.iloc[indices, ] x =",
"# BGY_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list('bgy', ['#001a33', '#003366', '#339933', '#ffff66', '#ffff00']) # BGY_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list('bgy',",
"'...') libplot.savefig(fig, out) libplot.savefig(fig, 'tmp.png') plt.close(fig) def cluster_grid(tsne, clusters, colors=None, cols=-1, size=SUBPLOT_SIZE, add_titles=True,",
"inplace=True) # imagelib.save(im_no_bg, 'smooth.png') # imagelib.paste(im_base, im_no_bg, inplace=True) im = imagelib.open(tmp) if outline:",
"h=h) libplot.savefig(fig, 'b/b_tsne_clusters_med.pdf') def sample_clusters(d, sample_names): \"\"\" Create a cluster matrix based on",
"fig, ax = pca_plot(pca, clusters, pc1=pc1, pc2=pc2, labels=labels, marker=marker, legend=legend, s=s, w=w, h=h,",
"how colors should be normalized Returns ------- fig : matplotlib figure If fig",
"w=w, h=h, dir='a/GeneExp', format=format) fig, ax = cluster_plot(tsne_a, c_a, legend=False, w=w, h=h) libplot.savefig(fig,",
"= list(sorted(set(clusters['Cluster']))) im_base = imagelib.new(w * 300, w * 300) for i in",
"if type(genes) is pd.core.frame.DataFrame: genes = genes['Genes'].values ids, gene_names = get_gene_names(data) gene_ids =",
"get_matrix_from_h5_v2(filename, genome): with h5py.File(filename, 'r') as f: if u'version' in f.attrs: if f.attrs['version']",
"= df2.iloc[:, pc2 - 1] if i in colors: color = colors[i] #",
"matplotlib.colors.LinearSegmentedColormap.from_list('bgy', ['#002255', '#003380', '#2ca05a', '#ffd42a', '#ffdd55']) # BGY_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list('bgy', ['#003366', '#339966', '#ffff66',",
"idx = np.where(np.isin(gene_names, g))[0] if idx.size < 1: return None else: idx =",
"sdmax)[0] # (d > x1) & (d < x2))[0] x = x[idx] y",
"tsne.iloc[idx2, 0] # y = tsne.iloc[idx2, 1] # libplot.scatter(x, y, c=BACKGROUND_SAMPLE_COLOR, ax=ax) #",
"h=h) for i in range(0, len(gene_ids)): # gene id gene_id = gene_ids[i][1] gene",
"clusters) # im_edges = im2.filter(ImageFilter.FIND_EDGES) # # im_smooth = im_edges.filter(ImageFilter.SMOOTH) # # #",
"dim2].values, clusters, colors=colors, edgecolors=edgecolors, linewidth=linewidth, markers=markers, alpha=alpha, s=s, ax=ax, cluster_order=cluster_order, sort=sort) #set_tsne_ax_lim(tsne, ax)",
"is None: colors = libcluster.get_colors() for i in indices: print('index', i) cluster =",
"# x = tsne.iloc[idx1, 0] # y = tsne.iloc[idx1, 1] # # if",
"print(np.unique(d.index.values)) print(np.unique(sc)) df = pd.DataFrame(sc, index=d.index, columns=['Cluster']) return df def create_cluster_samples(tsne_umi_log2, clusters, sample_names,",
"Make dirs including any parents and avoid raising exception to work more like",
"'7f' libplot.scatter(x, y, c=color, ax=ax, edgecolors='none', # edgecolors, linewidth=linewidth, s=s) if add_titles: if",
"im1.paste(im2, (0, 0), im2) im1.save(out, 'png') def genes_expr_outline(data, tsne, genes, prefix='', index=None, dir='GeneExp',",
"libtsne.load_pca(d_b, 'b', cache=cache) # pca.iloc[idx_b,:] tsne_b = libtsne.load_pca_tsne(pca_b, 'b', cache=cache) c_b = libtsne.load_phenograph_clusters(pca_b,",
"ax=ax) # # if add_titles: # if isinstance(cluster, int): # prefix = 'C'",
"np.array(['' for i in range(0, d.shape[0])], dtype=object) c = 1 for s in",
": list List of strings of gene ids ids : Index, optional Index",
"highlight cluster # enable if edges desired im1.paste(im2, (0, 0), im2) im1.save(out, 'png')",
"colors[cluster] elif isinstance(colors, list): if cluster < len(colors): # np.where(clusters['Cluster'] == cluster)[0]] color",
"['#00264d', '#003366', '#339933', '#e6e600', '#ffff33']) # BGY_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list('bgy', ['#003366', '#40bf80', '#ffff33']) BGY_ORIG_CMAP",
"separate_cluster(tsne, clusters, cluster, color=color, add_titles=add_titles, ax=ax) # idx1 = np.where(clusters['Cluster'] == cluster)[0] #",
"marker=marker, s=s, fig=fig, alpha=alpha, ax=ax, norm=norm) return fig, ax def pca_expr_plot(data, expr, name,",
"x2 = silhouette_samples( tsne_umi_log2, clusters.iloc[:, 0].tolist(), metric='euclidean') fig, ax = libplot.newfig(w=9, h=7, subplot=211)",
"0] # g = im_data[:, :, 1] # b = im_data[:, :, 2]",
"fig=None, ax=None): colors = libcluster.get_colors() if ax is None: fig, ax = libplot.new_fig(w=w,",
"name, cluster, format) print('Creating', out, '...') libplot.savefig(fig, out) libplot.savefig(fig, 'tmp.png') plt.close(fig) def cluster_grid(tsne,",
"min = -max if isinstance(min, float) or isinstance(min, int): print('z min', min) sd[np.where(sd",
"libplot.scatter(x, y, c=color, ax=ax, edgecolors='none', # edgecolors, linewidth=linewidth, s=s) if add_titles: if isinstance(cluster,",
"= kneighbors_graph(c1, k, mode='distance', metric='euclidean').toarray() a2 = kneighbors_graph(c2, k, mode='distance', metric='euclidean').toarray() overlaps =",
"tsne plot \"\"\" if out is None: out = '{}_expr.pdf'.format(method) fig, ax =",
"= get_gene_ids(data, genes, ids=ids, gene_names=gene_names) print(gene_ids) for i in range(0, len(gene_ids)): gene_id =",
"h=7, subplot=211) df = pd.DataFrame({'Silhouette Score': x1, 'Cluster': clusters.iloc[:, 0].tolist( ), 'Label': np.repeat('tsne-10x',",
":].toarray().squeeze() def gbm_to_df(gbm): return pd.DataFrame(gbm.matrix.todense(), index=gbm.gene_names, columns=gbm.barcodes) def get_barcode_counts(gbm): ret = [] for",
"c=[c1], # s=s, # marker=marker, # edgecolors='none', #edgecolors, # linewidth=linewidth) # # #",
"Colors of points add_titles : bool Whether to add titles to plots plot_order:",
"c) & clusters.index.str.contains(id))[0] # # x = tsne.iloc[idx1, 0] # y = tsne.iloc[idx1,",
"axes on plot legend : bool, optional, default true Whether to show legend.",
"i, cluster, colors) if isinstance(colors, dict): color = colors.get(cluster, 'black') elif isinstance(colors, list):",
"GeneBCMatrix(gbm.gene_ids, gbm.gene_names, gbm.barcodes[barcode_indices], gbm.matrix[:, barcode_indices]) def get_expression(gbm, gene_name, genes=None): if genes is None:",
"title=\"t-SNE\") libcluster.format_legend(ax, cols=6, markerscale=2) return fig, ax def base_expr_plot(data, exp, dim=[1, 2], cmap=plt.cm.plasma,",
"of gene names \"\"\" if dir[-1] == '/': dir = dir[:-1] if not",
"= nx.from_numpy_matrix(A) pos = nx.spring_layout(G) fig, ax = libplot.newfig(w=8, h=8) # list(range(0, c.shape[0]))",
"silhouette(tsne, tsne_umi_log2, clusters, name): # measure cluster worth x1 = silhouette_samples( tsne, clusters.iloc[:,",
"# h=h, # colorbar=colorbar) # # set_tsne_ax_lim(tsne, ax) # # libplot.invisible_axes(ax) # #",
"exp, dim=[1, 2], cmap=plt.cm.magma, marker='o', s=MARKER_SIZE, alpha=1, edgecolors=EDGE_COLOR, linewidth=EDGE_WIDTH, w=libplot.DEFAULT_WIDTH, h=libplot.DEFAULT_HEIGHT, show_axes=False, fig=None,",
"w, h, rows, cols def get_gene_names(data): if ';' in data.index[0]: ids, genes =",
"name, format) print(out) return cluster_plot(d, clusters, dim1=dim1, dim2=dim2, markers=markers, colors=colors, s=s, w=w, h=h,",
"image to highlight cluster # enable if edges desired im1.paste(im2, (0, 0), im2)",
"columns=d.columns) def rscale(d, min=0, max=1, axis=1): if axis == 0: return pd.DataFrame(RobustScaler().fit_transform(d), index=d.index,",
"| (g < 255) | (b < 255) #(r > 0) & (r",
"colorbar=False, method='tsne', fig=None, ax=None, sdmax=0.5): \"\"\" Plot multiple genes on a grid. Parameters",
"c_a, 'a', dir='a') create_merge_cluster_info(d_a, c_a, 'a', sample_names=samples, dir='a') create_cluster_samples(tsne_a, c_a, samples, 'a_sample', dir='a')",
"return (d + 1).apply(np.log2) def umi_tpm_log2(data): d = umi_tpm(data) return umi_log2(d) def umi_norm(data):",
"Score', colors=libcluster.colors(), ax=ax) ax.set_ylim([-1, 1]) ax.set_title('tsne-ah') libplot.savefig(fig, '{}_silhouette.pdf'.format(name)) def node_color_from_cluster(clusters): colors = libcluster.colors()",
"a basic t-sne expression plot. # # Parameters # ---------- # data :",
"#cmap = plt.cm.plasma ids, gene_names = get_gene_names(data) exp = get_gene_data(data, genes, ids=ids, gene_names=gene_names)",
"for color purposes #i = np.where(ids == cluster)[0][0] print('index', i, cluster, colors) if",
"colors is None: colors = libcluster.get_colors() for i in indices: print('index', i) cluster",
"np.array(imageWithEdges.convert('RGBA')) #r = data[:, :, 0] #g = data[:, :, 1] #b =",
"x[idx] #y1 = y[idx] # avg1 = np.zeros(x.size) #avg[idx] #avg1[idx] = 1 #",
"None: ids, gene_names = get_gene_names(data) ret = [] for g in genes: indexes",
"0 # # for sample in samples: # id = '-{}'.format(sid + 1)",
"name, pc1=1, pc2=2, marker='o', labels=False, legend=True, s=MARKER_SIZE, w=8, h=8, fig=None, ax=None, dir='.', format='png'):",
"= 3 ax.scatter(x, y, c=e, s=s, marker=marker, alpha=alpha, cmap=cmap, norm=norm, edgecolors='none', # edgecolors,",
"clusters, samples, colors=None, size=SUBPLOT_SIZE): # \"\"\" # Plot each cluster separately to highlight",
"x2, 'Cluster': clusters.iloc[:, 0].tolist( ), 'Label': np.repeat('tsne-ah', len(x2))}) libplot.boxplot(df2, 'Cluster', 'Silhouette Score', colors=libcluster.colors(),",
"samples, name, colors=None, size=SUBPLOT_SIZE, dir='.'): # \"\"\" # Plot separate clusters colored by",
"y = data.iloc[idx, dim[1] - 1].values # data['{}-{}'.format(t, d2)][idx] e = exp[idx] #",
"np.array([[p1, p2] for p1, p2 in zip(x, y)]) hull = ConvexHull(points) #x1 =",
"matrix) except tables.NoSuchNodeError: raise Exception(\"Genome %s does not exist in this file.\" %",
"200) # # # d = im_data[np.where(grey_areas)] # d[:, :] = [255, 255,",
"#libcluster.format_simple_axes(ax, title=t) if not show_axes: libplot.invisible_axes(ax) return fig, ax # def expr_plot(tsne, #",
"gene_ids[i][1])) libplot.add_colorbar(fig, cmap) return fig def genes_expr(data, tsne, genes, prefix='', dim=[1, 2], index=None,",
"from {}...'.format(file)) return pd.read_csv(file, sep='\\t', header=0, index_col=0) def silhouette(tsne, tsne_umi_log2, clusters, name): #",
"dir='b') create_cluster_plot(tsne_b, c_b, 'b', dir='b') create_cluster_grid(tsne_b, c_b, 'b', dir='b') create_merge_cluster_info(d_b, c_b, 'b', sample_names=samples,",
"'a', dir='a') create_cluster_plot(tsne_a, c_a, 'a', dir='a') create_cluster_grid(tsne_a, c_a, 'a', dir='a') create_merge_cluster_info(d_a, c_a, 'a',",
"import os import phenograph import libplot import libcluster import libtsne import seaborn as",
"\"\"\" if dir[-1] == '/': dir = dir[:-1] if not os.path.exists(dir): mkdir(dir) if",
"else: color = 'black' else: color = 'black' fig, ax = separate_cluster(d, clusters,",
"# #edges1 = feature.canny(rgb2gray(im_data)) # # #print(edges1.shape) # # #skimage.io.imsave('tmp_canny_{}.png'.format(bin), edges1) # #",
"- 1 if i < len(colors): # colors[cid - 1] #colors[i] #np.where(clusters['Cluster'] ==",
"list List of strings of gene ids ids : Index, optional Index of",
"b)) for a, b in zip(x, y)]) sd = d.std() m = d.mean()",
"node_color = libcluster.colors()[0:c.shape[0]] cmap = libcluster.colormap() labels = {} for i in range(0,",
"pd.core.frame.DataFrame: genes = genes['Genes'].values ids, gene_names = get_gene_names(data) gene_ids = get_gene_ids(data, genes, ids=ids,",
"return fig def pca_plot_base(pca, clusters, pc1=1, pc2=2, marker='o', labels=False, s=MARKER_SIZE, w=8, h=8, fig=None,",
"f: try: dsets = {} print(f.list_nodes('/')) for node in f.walk_nodes('/' + genome, 'Array'):",
"is None: ids = np.array(list(sorted(set(clusters['Cluster'])))) cluster_order = np.array(list(range(0, len(ids)))) + 1 n =",
"# y = tsne.iloc[idx1, 1] # # libplot.scatter(x, y, c=colors[sid], ax=ax) # #",
"clusters) a1 = kneighbors_graph(c1, k, mode='distance', metric='euclidean').toarray() a2 = kneighbors_graph(c2, k, mode='distance', metric='euclidean').toarray()",
"Genes x samples expression matrix tsne : Pandas dataframe Cells x tsne tsne",
"Q = phenograph.cluster(pca, k=20) if min(labels) == -1: new_label = 100 labels[np.where(labels ==",
"c='red', label=None, fig=None, ax=None): \"\"\" Create a tsne plot without the formatting \"\"\"",
"dim=dim, cmap=cmap, marker=marker, s=s, alpha=alpha, fig=fig, ax=ax, norm=norm) libplot.savefig(fig, out) plt.close(fig) return fig,",
"ax.set_title('{}{} ({:,})'.format(prefix, cluster, len(idx1)), color=color) # # # libplot.invisible_axes(ax) pc += 1 return",
"0].values # data['{}-{}'.format(t, d1)][idx] y = tsne.iloc[:, 1].values # data['{}-{}'.format(t, d2)][idx] idx =",
"y1)]) #hull = ConvexHull(points) #ax.plot(points[hull.vertices,0], points[hull.vertices,1]) #zi = griddata((x, y), avg1, (xi, yi))",
"= imagelib.open(tmp) im_no_bg = imagelib.remove_background(im) im_edges = imagelib.edges(im_no_bg) im_smooth = imagelib.smooth(im_edges) im_outline =",
"ids.values, genes.values def get_gene_ids(data, genes, ids=None, gene_names=None): \"\"\" For a given gene list,",
"ax=None, w=libplot.DEFAULT_WIDTH, h=libplot.DEFAULT_HEIGHT, edgecolors=EDGE_COLOR, linewidth=EDGE_WIDTH, norm=None, method='tsne', show_axes=False, colorbar=True, out=None): # plt.cm.plasma): \"\"\"",
"['gene_ids', 'gene_names', 'barcodes', 'matrix']) def decode(items): return np.array([x.decode('utf-8') for x in items]) def",
"pd.DataFrame({'Silhouette Score': x2, 'Cluster': clusters.iloc[:, 0].tolist( ), 'Label': np.repeat('tsne-ah', len(x2))}) libplot.boxplot(df2, 'Cluster', 'Silhouette",
"libplot.invisible_axes(ax) # # if out is not None: # libplot.savefig(fig, out, pad=0) #",
"return pd.DataFrame(gbm.matrix.todense(), index=gbm.gene_names, columns=gbm.barcodes) def get_barcode_counts(gbm): ret = [] for i in range(len(gbm.barcodes)):",
"ids=ids, gene_names=gene_names) for i in range(0, len(gene_ids)): gene_id = gene_ids[i][1] gene = gene_ids[i][2]",
"# ---------- # tsne : Pandas dataframe # Cells x tsne tsne data.",
"#points = np.array([[x, y] for x, y in zip(x1, y1)]) #hull = ConvexHull(points)",
"or isinstance(max, int): print('z max', max) sd[np.where(sd > max)] = max return pd.DataFrame(sd,",
"dir='b') create_merge_cluster_info(d_b, c_b, 'b', sample_names=samples, dir='b') create_cluster_samples(tsne_b, c_b, samples, 'b_sample', dir='b') genes_expr(d_b, tsne_b,",
"isinstance(legend, dict): legend_params.update(legend) else: pass if legend_params['show']: libcluster.format_legend(ax, cols=legend_params['cols'], markerscale=legend_params['markerscale']) libplot.invisible_axes(ax) tmp =",
"# overlay edges on top of original image to highlight cluster # im_base.paste(im2,",
"= 0.8 # '#f2f2f2' #(0.98, 0.98, 0.98) #(0.8, 0.8, 0.8) #(0.85, 0.85, 0.85",
"if axis == 0: return pd.DataFrame(RobustScaler().fit_transform(d), index=d.index, columns=d.columns) else: return pd.DataFrame(RobustScaler().fit_transform(d.T).T, index=d.index, columns=d.columns)",
"np.where(clusters['Cluster'] == l)[0] n = len(indices) label = 'C{} ({:,})'.format(l, n) df2 =",
"required datasets.\") #GeneBCMatrix = collections.namedtuple('FeatureBCMatrix', ['feature_ids', 'feature_names', 'barcodes', 'matrix']) def get_matrix_from_h5_v2(filename, genome): with",
": Pandas dataframe Genes x samples expression matrix tsne : Pandas dataframe Cells",
"s : int, optional Marker size w : int, optional Plot width h",
"as sns from libsparse.libsparse import SparseDataFrame from lib10x.sample import * from scipy.spatial import",
"'grey_purple_yellow', ['#e6e6e6', '#3333ff', '#ff33ff', '#ffe066']) GYBLGRYL_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list( 'grey_blue_green_yellow', ['#e6e6e6', '#0055d4', '#00aa44', '#ffe066'])",
"clusters, prefix='', index=None, dir='GeneExp', cmap=OR_RED_CMAP, # BGY_CMAP, norm=None, w=libplot.DEFAULT_WIDTH, h=libplot.DEFAULT_HEIGHT, alpha=1.0, colorbar=False, method='tsne',",
"= Image.open('tmp.png') # Edge detect on what is left (the clusters) imageWithEdges =",
"Pandas dataframe features x dimensions, e.g. rows are cells and columns are tsne",
"else: # prefix = '' # # ax.set_title('{}{} ({:,})'.format(prefix, cluster, len(idx1)), color=color) #",
"= pca.index.values for i in range(0, pca.shape[0]): print(pca.shape, pca.iloc[i, pc1 - 1], pca.iloc[i,",
"= tsne.iloc[idx1, 1] # # if isinstance(colors, dict): # color = colors[cluster] #",
"a pandas dataframe (dense) Parameters ---------- gbm : a GeneBCMatrix Returns ------- object",
"imagelib.paste(im_no_bg, im_smooth) imagelib.paste(im_base, im_outline, inplace=True) # # find gray areas and mask #",
"w=w, h=h, fig=fig, ax=ax) #libtsne.tsne_legend(ax, labels, colors) libcluster.format_simple_axes(ax, title=\"PC\") if legend: libcluster.format_legend(ax, cols=6,",
"add_titles=add_titles, size=size) out = '{}_sep_clust_{}_c{}.{}'.format(type, name, cluster, format) print('Creating', out, '...') libplot.savefig(fig, out)",
"in zip(x, y)]) sd = d.std() m = d.mean() print(m, sd) z =",
"= libplot.newfig(w=8, h=8) # list(range(0, c.shape[0])) node_color = libcluster.colors()[0:c.shape[0]] cmap = libcluster.colormap() labels",
"#plt.cm.plasma): # \"\"\" # Creates a basic t-sne expression plot. # # Parameters",
"'grey_blue_green_yellow', ['#e6e6e6', '#0055d4', '#00aa44', '#ffe066']) OR_RED_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list( 'or_red', matplotlib.cm.OrRd(range(4, 256))) BU_PU_CMAP =",
"import tables import pandas as pd from sklearn.manifold import TSNE import sklearn.preprocessing from",
"ax def tsne_plot(tsne, marker='o', s=libplot.MARKER_SIZE, c='red', label=None, fig=None, ax=None): fig, ax = base_tsne_plot(tsne,",
"show_axes : bool, optional, default true Whether to show axes on plot legend",
"'Overlap %': overlaps}) df.set_index('Cluster', inplace=True) df.to_csv('{}_cluster_overlaps.txt'.format(name), sep='\\t') def mkdir(path): \"\"\" Make dirs including",
"matrix = sp_sparse.csc_matrix( (dsets['data'], dsets['indices'], dsets['indptr']), shape=dsets['shape']) return GeneBCMatrix(decode(dsets['genes']), decode(dsets['gene_names']), decode(dsets['barcodes']), matrix) except",
"marker='o', labels=False, legend=True, s=MARKER_SIZE, w=8, h=8, fig=None, ax=None, dir='.', format='png'): out = '{}/pca_{}_pc{}_vs_pc{}.{}'.format(dir,",
"dim1=0, dim2=1, markers='o', s=libplot.MARKER_SIZE, colors=None, w=8, h=8, legend=True, show_axes=False, sort=True, cluster_order=None, fig=None, ax=None,",
"c_b, legend=False, w=w, h=h) libplot.savefig(fig, 'b/b_tsne_clusters_med.pdf') def sample_clusters(d, sample_names): \"\"\" Create a cluster",
"rows, cols, i + 1) expr_plot(tsne, exp, ax=ax, cmap=cmap, colorbar=False) # if i",
"# #im3 = Image.fromarray(im_data) # #im2.save('edges.png', 'png') # # im_smooth = im_edges.filter(ImageFilter.SMOOTH) #",
"color=color, add_titles=add_titles, ax=ax) # idx1 = np.where(clusters['Cluster'] == cluster)[0] # idx2 = np.where(clusters['Cluster']",
"create_cluster_grid(tsne_a, c_a, 'a', dir='a') create_merge_cluster_info(d_a, c_a, 'a', sample_names=samples, dir='a') create_cluster_samples(tsne_a, c_a, samples, 'a_sample',",
"int(np.round(np.median(reads_per_bc))) median_reads_per_bc = np.median(reads_per_bc) scaling_factors = median_reads_per_bc / reads_per_bc scaled = data.multiply(scaling_factors) #",
"an expression plot for T-SNE/2D space reduced representation of data. Parameters ---------- data",
"BU_PU_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list( 'bu_pu', matplotlib.cm.BuPu(range(4, 256))) # BGY_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list('bgy', ['#0066ff', '#37c871', '#ffd42a'])",
"figure A new Matplotlib figure used to make the plot ax : Matplotlib",
"im_smooth = im_edges.filter(ImageFilter.SMOOTH) # # # paste outline onto clusters # im2.paste(im_smooth, (0,",
"b mkdir('b') b_barcodes = pd.read_csv('../b_barcodes.tsv', header=0, sep='\\t') idx = np.where(counts.columns.isin(b_barcodes['Barcode'].values))[0] d_b = counts.iloc[:,",
"black_areas = (a > 0) d = im_data[np.where(black_areas)] d[:, 0:3] = [64, 64,",
"is None: fig, ax = libplot.new_fig(w=w, h=h) ids = list(sorted(set(clusters['Cluster']))) for i in",
"points # # # # x = tsne.iloc[idx2, 0] # y = tsne.iloc[idx2,",
"= StandardScaler(with_mean=False).fit_transform(d.T.matrix) return SparseDataFrame(sd.T, index=d.index, columns=d.columns) else: # StandardScaler().fit_transform(d.T) sd = sklearn.preprocessing.scale(d, axis=axis)",
"not exist in this file.\" % genome) except KeyError: raise Exception(\"File is missing",
"= (clusters['Cluster'] - 1).tolist() # # fig, ax = libplot.newfig(w=10, h=10) # #",
"if genes is None: genes = gbm.gene_names gene_indices = np.where(genes == gene_name)[0] if",
"\"\"\" # Plot each cluster separately to highlight samples # # Parameters #",
"a2 = kneighbors_graph(c2, k, mode='distance', metric='euclidean').toarray() overlaps = [] for i in range(0,",
"# colorbar=True): #plt.cm.plasma): # \"\"\" # Creates a basic t-sne expression plot. #",
"libplot.scatter(x, y, c=color, ax=ax) # # if add_titles: # if isinstance(cluster, int): #",
"this file.\" % genome) except KeyError: raise Exception(\"File is missing one or more",
"plot without the formatting Parameters ---------- d : Pandas dataframe t-sne, umap data",
"import * from scipy.spatial import ConvexHull from PIL import Image, ImageFilter from scipy.stats",
"umi_norm_log2_scale(data, clip=None): d = umi_norm_log2(data) return scale(d, clip=clip) def read_clusters(file): print('Reading clusters from",
"'smooth.png') # im_smooth imagelib.paste(im_base, im_smooth, inplace=True) else: imagelib.paste(im_base, im, inplace=True) # # find",
"\"\"\" For a given gene list, get all of the transcripts. Parameters ----------",
"genome, 'Array'): dsets[node.name] = node.read() # for node in f.walk_nodes('/matrix', 'Array'): # dsets[node.name]",
"#norm = matplotlib.colors.Normalize(vmin=-3, vmax=3, clip=True) if norm is None: norm = libplot.NORM_3 #",
"is None: out = '{}_expr.pdf'.format(method) fig, ax = expr_plot(tsne, exp, dim=dim, cmap=cmap, marker=marker,",
"== c)[0], :] centroid = (x.sum(axis=0) / x.shape[0]).tolist() ret[i, 0] = centroid[0] ret[i,",
"legend=True, sort=True, show_axes=False, ax=None, cluster_order=None, format='png', dir='.', out=None): if out is None: #",
"im_smooth) imagelib.paste(im_base, im_outline, inplace=True) # # find gray areas and mask # im_data",
"None: out = '{}/{}_{}_separate_clusters.png'.format(dir, method, name) libplot.savefig(fig, out, pad=0) #libplot.savefig(fig, '{}/tsne_{}separate_clusters.pdf'.format(dir, name)) #",
"print(np.where(d.index.str.contains(id))[0]) sc[np.where(d.index.str.contains(id))[0]] = s c += 1 print(np.unique(d.index.values)) print(np.unique(sc)) df = pd.DataFrame(sc, index=d.index,",
"#m = d.min(axis=1) #std = (d - m) / (d.max(axis=1) - m) #scaled",
"[x.decode('ascii', 'ignore') for x in f['matrix']['features']['id']] feature_names = [x.decode('ascii', 'ignore') for x in",
"ids2 = np.where(a2[i, :] > 0)[0] ids3 = np.intersect1d(ids1, ids2) o = len(ids3)",
"return the supplied figure, otherwise a new figure is created and returned. ax",
"idx.size < 1: # if id does not exist, try the gene names",
"= 1 for c in cluster_order: i = c - 1 cluster =",
"({:,})'.format(prefix, cluster, len(idx1)), color=color) # # # libplot.invisible_axes(ax) pc += 1 return fig",
"= (avg - avg.mean()) / avg.std() avg[avg < -1.5] = -1.5 avg[avg >",
"# # c1 = color.copy() # c1[-1] = 0.5 # # #print(c1) #",
"optional Index of gene names Returns ------- list list of tuples of (index,",
"should be labeled 'TSNE-1', 'TSNE-2' etc genes : array List of gene names",
"cols) + 2 if l % cols == 0: # Assume we will",
"libplot.savefig(fig, 'b/b_tsne_clusters_med.pdf') def sample_clusters(d, sample_names): \"\"\" Create a cluster matrix based on by",
"with h5py.File(filename, 'r') as f: if u'version' in f.attrs: if f.attrs['version'] > 2:",
"a_barcodes = pd.read_csv('../a_barcodes.tsv', header=0, sep='\\t') idx = np.where(counts.columns.isin(a_barcodes['Barcode'].values))[0] d_a = counts.iloc[:, idx] d_a",
"im_no_bg, inplace=True) im = imagelib.open(tmp) if outline: im_no_bg = imagelib.remove_background(im) im_edges = imagelib.edges(im)",
"clusters) # im_edges = im2.filter(ImageFilter.FIND_EDGES) # # # im_data = np.array(im_edges.convert('RGBA')) # #",
"color = np.array(color) # # c1 = color.copy() # c1[-1] = 0.5 #",
"dir[:-1] if not os.path.exists(dir): mkdir(dir) if index is None: index = data.index if",
"max', max) sd[np.where(sd > max)] = max return pd.DataFrame(sd, index=d.index, columns=d.columns) def min_max_scale(d,",
"libcluster.remove_empty_rows(d_a) if isinstance(d_a, SparseDataFrame): d_a = umi_norm_log2(d_a) else: d_a = umi_norm_log2_scale(d_a) pca_a =",
"500 ny = 500 xi = np.linspace(x.min(), x.max(), nx) yi = np.linspace(y.min(), y.max(),",
"import binned_statistic import imagelib TNSE_AX_Q = 0.999 MARKER_SIZE = 10 SUBPLOT_SIZE = 4",
"ax=ax) libplot.savefig(fig, out, pad=2) plt.close(fig) def set_tsne_ax_lim(tsne, ax): \"\"\" Set the t-SNE x,y",
"else: return data.iloc[idx, :].values def gene_expr_grid(data, tsne, genes, cmap=None, size=SUBPLOT_SIZE): \"\"\" Plot multiple",
"fig=None, ax=None, norm=None): # plt.cm.plasma): fig, ax = base_expr_plot(data, exp, t='PC', dim=dim, cmap=cmap,",
"Clusters in colors : list, color Colors of points add_titles : bool Whether",
"'#ffdd55']) # BGY_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list('bgy', ['#003366', '#339966', '#ffff66', '#ffff00') # BGY_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list('bgy',",
"fig is a supplied argument, return the supplied figure, otherwise a new figure",
"return umi_log2(d) def umi_norm(data): \"\"\" Scale each library to its median size Parameters",
"plt.cm.plasma ids, gene_names = get_gene_names(data) gene_ids = get_gene_ids(data, genes, ids=ids, gene_names=gene_names) for i",
"each cluster into its own plot file. \"\"\" ids = list(sorted(set(clusters['Cluster']))) indices =",
"= matplotlib.colors.LinearSegmentedColormap.from_list('bgy', ['#002255', '#2ca05a', '#ffd42a']) # BGY_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list('bgy', ['#002255', '#003380', '#2ca05a', '#ffd42a',",
"# # Non transparent areas are edges # #black_areas = (a > 0)",
"index=None, dir='GeneExp', cmap=BGY_CMAP, norm=None, w=4, h=4, s=30, alpha=ALPHA, linewidth=EDGE_WIDTH, edgecolors='none', colorbar=True, method='tsne', format='png'):",
"optional width of new ax. h: int, optional height of new ax. Returns",
"if len(gene_indices) == 0: raise Exception(\"%s was not found in list of gene",
"decode(dsets['gene_names']), decode(dsets['barcodes']), matrix) except tables.NoSuchNodeError: raise Exception(\"Genome %s does not exist in this",
"'{}/tsne_{}_sample_clusters.png'.format(dir, name)) # #libplot.savefig(fig, '{}/tsne_{}separate_clusters.pdf'.format(dir, name)) # # def load_clusters(pca, headers, name, cache=True):",
"a row for a color bar rows += 1 h = size *",
"to highlight cluster #im_base.paste(im2, (0, 0), im2) imagelib.save(im_base, out) def avg_expr(data, tsne, genes,",
"argument, return the supplied figure, otherwise a new figure is created and returned.",
":].to_array() else: return data.iloc[idx, :].values def gene_expr_grid(data, tsne, genes, cmap=None, size=SUBPLOT_SIZE): \"\"\" Plot",
"from sklearn.preprocessing import StandardScaler from sklearn.preprocessing import RobustScaler from sklearn.preprocessing import MinMaxScaler from",
"ax=None, sdmax=0.5): \"\"\" Plot multiple genes on a grid. Parameters ---------- data :",
"= '{}/{}_expr_{}_{}.png'.format(dir, method, gene, gene_id) else: out = '{}/{}_expr_{}.png'.format(dir, method, gene) print(out) #",
"l = pca.index.values for i in range(0, pca.shape[0]): print(pca.shape, pca.iloc[i, pc1 - 1],",
"expr_grid_size(gene_ids, size=size) fig = libplot.new_base_fig(w=w, h=h) for i in range(0, len(gene_ids)): # gene",
"format) libplot.savefig(fig, 'tmp.png', pad=0) libplot.savefig(fig, out, pad=0) plt.close(fig) im1 = Image.open('tmp.png') # Edge",
"image to highlight cluster #im_base.paste(im2, (0, 0), im2) imagelib.save(im_base, out) def avg_expr(data, tsne,",
"norm=norm, linewidth=linewidth, edgecolors=edgecolors) if out is not None: libplot.savefig(fig, out, pad=0) return fig,",
"#(r > 0) & (r == g) & (r == b) & (g",
"s=s, fig=fig, alpha=alpha, ax=ax, norm=norm) return fig, ax def pca_expr_plot(data, expr, name, dim=[1,",
"# #print(x[i], y[i], mean) # # #if mean > 0.5: # ax.scatter(x[i], #",
"clusters) A = kneighbors_graph(c, 5, mode='distance', metric='euclidean').toarray() G = nx.from_numpy_matrix(A) pos = nx.spring_layout(G)",
"was not found, creating it with...'.format(file)) # Find the interesting clusters labels, graph,",
"d2=2, # x1=None, # x2=None, # cmap=BLUE_YELLOW_CMAP, # marker='o', # s=MARKER_SIZE, # alpha=EXP_ALPHA,",
"# pca.iloc[idx_b,:] tsne_b = libtsne.load_pca_tsne(pca_b, 'b', cache=cache) c_b = libtsne.load_phenograph_clusters(pca_b, 'b', cache=cache) create_pca_plot(pca_b,",
"gene_id, gene_name) \"\"\" if ids is None: ids, gene_names = get_gene_names(data) ret =",
"), 'Label': np.repeat('tsne-10x', len(x1))}) libplot.boxplot(df, 'Cluster', 'Silhouette Score', colors=libcluster.colors(), ax=ax) ax.set_ylim([-1, 1]) ax.set_title('tsne-10x')",
"# # cids = list(sorted(set(clusters['Cluster']))) # # rows = int(np.ceil(np.sqrt(len(cids)))) # # w",
"def umi_tpm_log2(data): d = umi_tpm(data) return umi_log2(d) def umi_norm(data): \"\"\" Scale each library",
"shape=f['matrix']['shape']) return GeneBCMatrix(feature_ids, feature_names, decode(barcodes), matrix) def save_matrix_to_h5(gbm, filename, genome): flt = tables.Filters(complevel=1)",
"out = '{}/{}_expr_{}.{}'.format(dir, method, gene, format) libplot.savefig(fig, 'tmp.png', pad=0) libplot.savefig(fig, out, pad=0) plt.close(fig)",
"exp_bin, cmap=cmap, s=s, colorbar=colorbar, norm=norm, alpha=alpha, linewidth=linewidth, edgecolors=edgecolors, ax=ax) tmp = 'tmp{}.png'.format(bin) libplot.savefig(fig,",
"= data.sum(axis=0) # int(np.round(np.median(reads_per_bc))) median_reads_per_bc = np.median(reads_per_bc) scaling_factors = median_reads_per_bc / reads_per_bc scaled",
"dataframe Genes x samples expression matrix tsne : Pandas dataframe Cells x tsne",
"# libcluster.format_axes(ax) # else: # libplot.invisible_axes(ax) ax.set_title('{} ({})'.format(gene_ids[i][2], gene_ids[i][1])) libplot.add_colorbar(fig, cmap) return fig",
"else: out = '{}/{}_expr_{}.{}'.format(dir, method, gene, format) libplot.savefig(fig, 'tmp.png', pad=0) libplot.savefig(fig, out, pad=0)",
"in the order they should be rendered Returns ------- fig : Matplotlib figure",
"imagelib.paste(im_base, im_outline, inplace=True) # # find gray areas and mask # im_data =",
"colors=libcluster.colors(), ax=ax) ax.set_ylim([-1, 1]) ax.set_title('tsne-10x') #libplot.savefig(fig, 'RK10001_10003_clust-phen_silhouette.pdf') ax = fig.add_subplot(212) # libplot.newfig(w=9) df2",
"size=4, alpha=ALPHA, s=MARKER_SIZE, edgecolors='white', linewidth=EDGE_WIDTH, fig=None, ax=None): \"\"\" Plot a cluster separately to",
"umi_log2(d): if isinstance(d, SparseDataFrame): print('UMI norm log2 sparse') return d.log2(add=1) else: return (d",
"sep='\\t'): df(gbm).to_csv(file, sep=sep, header=True, index=True) def sum(gbm, axis=0): return gbm.matrix.sum(axis=axis) def tpm(gbm): m",
"= matplotlib.colors.LinearSegmentedColormap.from_list('bgy', ['#001a33', '#003366', '#339933', '#ffff66', '#ffff00']) # BGY_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list('bgy', ['#00264d', '#003366',",
"0: #norm = matplotlib.colors.Normalize(vmin=-3, vmax=3, clip=True) if norm is None: norm = libplot.NORM_3",
"os import phenograph import libplot import libcluster import libtsne import seaborn as sns",
"new ax. h: int, optional height of new ax. Returns ------- fig :",
"(0, 0), im2) im1.save(out, 'png') def genes_expr_outline(data, tsne, genes, prefix='', index=None, dir='GeneExp', cmap=BGY_CMAP,",
"mn = m.multiply(s) tpm = mn.multiply(1000000) return GeneBCMatrix(gbm.gene_ids, gbm.gene_names, gbm.barcodes, tpm) def create_cluster_plots(pca,",
"------- fig : matplotlib figure If fig is a supplied argument, return the",
"norm=None, w=4, h=4, s=30, alpha=ALPHA, linewidth=EDGE_WIDTH, edgecolors='none', colorbar=True, method='tsne', format='png'): \"\"\" Plot multiple",
"avg.std() avg[avg < -1.5] = -1.5 avg[avg > 1.5] = 1.5 avg =",
"> 1.5] = 1.5 avg = (avg - avg.min()) / (avg.max() - avg.min())",
"def tsne_plot(tsne, marker='o', s=libplot.MARKER_SIZE, c='red', label=None, fig=None, ax=None): fig, ax = base_tsne_plot(tsne, marker=marker,",
"Edge detect on what is left (the clusters) # im_edges = im2.filter(ImageFilter.FIND_EDGES) #",
"median_reads_per_bc = np.median(reads_per_bc) scaling_factors = median_reads_per_bc / reads_per_bc scaled = data.multiply(scaling_factors) # ,",
"im_no_gray, im_smooth = smooth_edges(im1, im1) # # # Edge detect on what is",
"fig=None, ax=None, norm=None): # plt.cm.plasma): \"\"\" Base function for creating an expression plot",
"# ['AICDA', 'CD83', 'CXCR4', 'MKI67', 'MYC', 'PCNA', 'PRDM1'] genes = pd.read_csv('../../../../expression_genes.txt', header=0) mkdir('a')",
"= [64, 64, 64] im_data[np.where(black_areas)] = d im2 = Image.fromarray(im_data) im2.save('edges.png', 'png') #",
"0.999 MARKER_SIZE = 10 SUBPLOT_SIZE = 4 EXP_ALPHA = 0.8 # '#f2f2f2' #(0.98,",
"bi)[0] tsne_other = tsne.iloc[idx_other, :] fig, ax = libplot.new_fig(w, w) x = tsne_other.iloc[:,",
"tsne.iloc[idx1, 1] #print('sep', cluster, color) color = color # + '7f' libplot.scatter(x, y,",
"fig = libplot.new_base_fig(w=w, h=w) si = 1 for i in range(0, n): for",
"print(f.list_nodes('/')) for node in f.walk_nodes('/' + genome, 'Array'): dsets[node.name] = node.read() # for",
"ax.scatter(x, y, color=color, edgecolor=color, s=s, marker=marker, alpha=libplot.ALPHA, label=label) if labels: l = pca.index.values",
"0].quantile(1 - TNSE_AX_Q), d2[d2 >= 0].quantile(TNSE_AX_Q)] #print(xlim, ylim) # ax.set_xlim(xlim) # ax.set_ylim(ylim) def",
"< sdmax)[0] # (d > x1) & (d < x2))[0] x = x[idx]",
", axis=1) return scaled def umi_log2(d): if isinstance(d, SparseDataFrame): print('UMI norm log2 sparse')",
"colors : list, color Colors of points add_titles : bool Whether to add",
"be labeled 'TSNE-1', 'TSNE-2' etc cluster : int Clusters in colors : list,",
"#print(e.min(), e.max()) # z-score #e = (e - e.mean()) / e.std() # limit",
"= '{}/{}_expr_{}.png'.format(dir, method, gene) print(out) # overlay edges on top of original image",
"create_expr_plot(tsne, exp, dim=[1, 2], cmap=None, marker='o', s=MARKER_SIZE, alpha=EXP_ALPHA, fig=None, ax=None, w=libplot.DEFAULT_WIDTH, h=libplot.DEFAULT_HEIGHT, edgecolors=EDGE_COLOR,",
"d_a = umi_norm_log2_scale(d_a) pca_a = libtsne.load_pca(d_a, 'a', cache=cache) # pca.iloc[idx,:] tsne_a = libtsne.load_pca_tsne(pca_a,",
"---------- data : Pandas dataframe Genes x samples expression matrix tsne : Pandas",
"pc2, format) fig, ax = pca_plot(pca, clusters, pc1=pc1, pc2=pc2, labels=labels, marker=marker, legend=legend, s=s,",
"\"\"\" # # fig, ax = expr_plot(tsne, # exp, # t='TSNE', # d1=d1,",
"d.iloc[:, dim2].values, clusters, colors=colors, edgecolors=edgecolors, linewidth=linewidth, markers=markers, alpha=alpha, s=s, ax=ax, cluster_order=cluster_order, sort=sort) #set_tsne_ax_lim(tsne,",
"in f.attrs: if f.attrs['version'] > 2: raise ValueError( 'Matrix HDF5 file format version",
"pick the first idx = idx[0] else: # if id does not exist,",
"print('index', i) cluster = ids[i] if isinstance(colors, dict): color = colors[cluster] elif isinstance(colors,",
"iw) for bin in range(0, bins): bi = bin + 1 idx_bin =",
"if add_titles: # if isinstance(cluster, int): # prefix = 'C' # else: #",
"centroid[1] return ret def knn_method_overlaps(tsne1, tsne2, clusters, name, k=5): c1 = centroids(tsne1, clusters)",
"# # ax.set_title('{}{} ({:,})'.format(prefix, cluster, len(idx1)), color=color) # # # libplot.invisible_axes(ax) pc +=",
"/ (d.max(axis=1) - m) #scaled = std * (max - min) + min",
"return df def create_cluster_samples(tsne_umi_log2, clusters, sample_names, name, method='tsne', format='png', dir='.', w=16, h=16, legend=True):",
"x.shape[0] elif type(x) is pd.core.frame.DataFrame: l = x.shape[0] else: return None cols =",
"idx] d_b = libcluster.remove_empty_rows(d_b) if isinstance(d_a, SparseDataFrame): d_b = umi_norm_log2(d_b) else: d_b =",
"and adds a color bar. \"\"\" is_first = False if ax is None:",
"0] # y = tsne.iloc[idx1, 1] # # libplot.scatter(x, y, c=colors[sid], ax=ax) #",
"def expr_plot(data, exp, dim=[1, 2], cmap=plt.cm.magma, marker='o', s=MARKER_SIZE, alpha=1, edgecolors=EDGE_COLOR, linewidth=EDGE_WIDTH, w=libplot.DEFAULT_WIDTH, h=libplot.DEFAULT_HEIGHT,",
"if out is None: out = '{}/{}_{}_separate_clusters.png'.format(dir, method, name) libplot.savefig(fig, out, pad=0) #libplot.savefig(fig,",
"collections.namedtuple('FeatureBCMatrix', ['feature_ids', 'feature_names', 'barcodes', 'matrix']) def get_matrix_from_h5_v2(filename, genome): with h5py.File(filename, 'r') as f:",
"c_b, 'b', dir='b') create_cluster_grid(tsne_b, c_b, 'b', dir='b') create_merge_cluster_info(d_b, c_b, 'b', sample_names=samples, dir='b') create_cluster_samples(tsne_b,",
"ax.text(pca.iloc[i, pc1 - 1], pca.iloc[i, pc2 - 1], pca.index[i]) return fig, ax def",
"] x = df2.iloc[:, pc1 - 1] y = df2.iloc[:, pc2 - 1]",
"ax def base_cluster_plot_outline(out, d, clusters, s=libplot.MARKER_SIZE, colors=None, edgecolors=EDGE_COLOR, linewidth=EDGE_WIDTH, dim1=0, dim2=1, w=8, alpha=ALPHA,",
"genes) gene_ids = get_gene_ids(data, genes, ids=ids, gene_names=gene_names) print(gene_ids) for i in range(0, len(gene_ids)):",
"pc2 - 1], pca.index[i]) return fig, ax def pca_plot(pca, clusters, pc1=1, pc2=2, marker='o',",
"= new_label labels += 1 libtsne.write_clusters(headers, labels, name) cluster_map, data = libtsne.read_clusters(file) labels",
"1 return fig def create_cluster_grid(tsne, clusters, name, colors=None, cols=-1, size=SUBPLOT_SIZE, add_titles=True, cluster_order=None, method='tsne',",
"im_smooth.save('edges.png', 'png') # # im2.paste(im_smooth, (0, 0), im_smooth) # # im_base.paste(im2, (0, 0),",
"d, clusters, s=libplot.MARKER_SIZE, colors=None, edgecolors=EDGE_COLOR, linewidth=EDGE_WIDTH, dim1=0, dim2=1, w=8, alpha=ALPHA, # libplot.ALPHA, show_axes=True,",
"the background # # x = tsne.iloc[idx1, 0] # y = tsne.iloc[idx1, 1]",
"h=libplot.DEFAULT_HEIGHT, fig=None, ax=None, norm=None): # plt.cm.plasma): \"\"\" Base function for creating an expression",
"gene_ids[i][1] gene = gene_ids[i][2] print(gene_id, gene) exp = get_gene_data(data, gene_id, ids=ids, gene_names=gene_names) bin_means,",
"not show_axes: libplot.invisible_axes(ax) return fig, ax # def expr_plot(tsne, # exp, # d1=1,",
"exists, pick the first idx = idx[0] else: # if id does not",
"colorbar=colorbar, norm=norm, alpha=alpha, fig=fig, ax=ax) x = tsne.iloc[:, 0].values # data['{}-{}'.format(t, d1)][idx] y",
"has rows. d1 : int, optional First dimension being plotted (usually 1) d2",
"* cmap.N)) # color = np.array(color) # # c1 = color.copy() # c1[-1]",
"look nice. \"\"\" if type(x) is int: l = x elif type(x) is",
"print('{} was not found, creating it with...'.format(file)) # Find the interesting clusters labels,",
"Non transparent areas are edges # #black_areas = (a > 0) #(r <",
"# # x = tsne.iloc[idx2, 0] # y = tsne.iloc[idx2, 1] # libplot.scatter(x,",
"= imagelib.smooth(im_outline) imagelib.save(im_smooth, 'smooth.png') # im_smooth imagelib.paste(im_base, im_smooth, inplace=True) else: imagelib.paste(im_base, im, inplace=True)",
"bool): legend_params['show'] = legend elif isinstance(legend, dict): legend_params.update(legend) else: pass if legend_params['show']: libcluster.format_legend(ax,",
"np.where(ids == g)[0] if idx.size > 0: # if id exists, pick the",
"GeneBCMatrix(gbm.gene_ids, gbm.gene_names, gbm.barcodes, tpm) def create_cluster_plots(pca, labels, name, marker='o', s=MARKER_SIZE): for i in",
"# c1[-1] = 0.5 # # #print(c1) # # ax.scatter(x[i], # y[i], #",
"def get_gene_names(data): if ';' in data.index[0]: ids, genes = data.index.str.split(';').str else: genes =",
"clusters) fig, ax = libplot.newfig(w=5, h=5) ax.scatter(c[:, 0], c[:, 1], c=None) libplot.format_axes(ax) libplot.savefig(fig,",
"make the plot \"\"\" if cluster_order is None: ids = np.array(list(sorted(set(clusters['Cluster'])))) cluster_order =",
"# x1=x1, # x2=x2, # cmap=cmap, # marker=marker, # s=s, # alpha=alpha, #",
"x tsne tsne data. Columns should be labeled 'TSNE-1', 'TSNE-2' etc # clusters",
"-1.5] = -1.5 avg[avg > 1.5] = 1.5 avg = (avg - avg.min())",
"= imagelib.new(w * 300, w * 300) for i in range(0, len(cluster_order)): print('index',",
"size=SUBPLOT_SIZE): \"\"\" Auto size grid to look nice. \"\"\" if type(x) is int:",
"range(0, c1.shape[0]): ids1 = np.where(a1[i, :] > 0)[0] ids2 = np.where(a2[i, :] >",
"Supply an axis object on which to render the plot, otherwise a new",
"pd.read_csv(file, sep='\\t', header=0, index_col=0) def silhouette(tsne, tsne_umi_log2, clusters, name): # measure cluster worth",
"rows, i + 1)) # # x = tsne.iloc[idx2, 0] # y =",
"'bgy', ['#003366', '#004d99', '#40bf80', '#ffe066', '#ffd633']) GRAY_PURPLE_YELLOW_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list( 'grey_purple_yellow', ['#e6e6e6', '#3333ff', '#ff33ff',",
"pd.DataFrame(MinMaxScaler(feature_range=(min, max)).fit_transform(d), index=d.index, columns=d.columns) else: return pd.DataFrame(MinMaxScaler(feature_range=(min, max)).fit_transform(d.T).T, index=d.index, columns=d.columns) def rscale(d, min=0,",
"pca_base_plots(pca, clusters, n=10, marker='o', s=MARKER_SIZE): rows = libplot.grid_size(n) w = 4 * rows",
"of original image to highlight cluster #im_base.paste(im2, (0, 0), im2) imagelib.save(im_base, out) def",
"= 'black' else: color = 'black' ax = libplot.new_ax(fig, subplot=(rows, cols, pc)) separate_cluster(tsne,",
"get_expression(gbm, gene_name, genes=None): if genes is None: genes = gbm.gene_names gene_indices = np.where(genes",
"# # #d = im_data[np.where(black_areas)] # #d[:, 0:3] = [64, 64, 64] #",
"point so it must have the same number of elements as data has",
"cluster < len(colors): # np.where(clusters['Cluster'] == cluster)[0]] color = colors[i] else: color =",
"= x[idx] y = y[idx] points = np.array([[p1, p2] for p1, p2 in",
"data : pandas.DataFrame # t-sne 2D data # \"\"\" # # fig, ax",
"return fig, ax def create_cluster_plot(d, clusters, name, dim1=0, dim2=1, method='tsne', markers='o', s=libplot.MARKER_SIZE, w=8,",
"# np.argsort(exp) x = data.iloc[idx, dim[0] - 1].values # data['{}-{}'.format(t, d1)][idx] y =",
"% gene_name) return gbm.matrix[gene_indices[0], :].toarray().squeeze() def gbm_to_df(gbm): return pd.DataFrame(gbm.matrix.todense(), index=gbm.gene_names, columns=gbm.barcodes) def get_barcode_counts(gbm):",
"A new Matplotlib figure used to make the plot \"\"\" if type(genes) is",
"= gbm.gene_names gene_indices = np.where(genes == gene_name)[0] if len(gene_indices) == 0: raise Exception(\"%s",
"= libcluster.colors() # # for i in range(0, len(cids)): # c = cids[i]",
"1), pc2=(j + 1), marker=marker, s=s) def pca_base_plots(pca, clusters, n=10, marker='o', s=MARKER_SIZE): rows",
"a color bar rows += 1 h = size * rows return w,",
"m) / sd # find all points within 1 sd of centroid idx",
"else: # if id does not exist, try the gene names idx =",
"# d1=1, # d2=2, # x1=None, # x2=None, # cmap=BLUE_YELLOW_CMAP, # marker='o', #",
"idx1 = np.where(clusters['Cluster'] == cluster)[0] # idx2 = np.where(clusters['Cluster'] != cluster)[0] # #",
"index=d.index, columns=['Cluster']) return df def create_cluster_samples(tsne_umi_log2, clusters, sample_names, name, method='tsne', format='png', dir='.', w=16,",
"g = im_data[:, :, 1] # b = im_data[:, :, 2] # #",
"libplot.savefig(fig, out, pad=0) # # return fig, ax def create_expr_plot(tsne, exp, dim=[1, 2],",
"# if out is not None: # libplot.savefig(fig, out, pad=0) # # return",
"get_gene_data(data, gene) return expr_plot(tsne, exp, fig=fig, ax=ax, cmap=cmap, out=out) def separate_cluster(tsne, clusters, cluster,",
"top of original image to highlight cluster #im_base.paste(im2, (0, 0), im2) imagelib.save(im_base, out)",
"= max return pd.DataFrame(sd, index=d.index, columns=d.columns) def min_max_scale(d, min=0, max=1, axis=1): #m =",
"Creates a base expression plot and adds a color bar. \"\"\" is_first =",
"node_color = (clusters['Cluster'] - 1).tolist() # # fig, ax = libplot.newfig(w=10, h=10) #",
"x.shape[0]).tolist() ret[i, 0] = centroid[0] ret[i, 1] = centroid[1] return ret def knn_method_overlaps(tsne1,",
"ax.scatter(x[i], # y[i], # c=[c1], # s=s, # marker=marker, # edgecolors='none', #edgecolors, #",
"y, c=color, ax=ax) # # if add_titles: # if isinstance(cluster, int): # prefix",
"i in range(len(gbm.barcodes)): ret.append(np.sum(gbm.matrix[:, i].toarray())) return ret def df(gbm): \"\"\" Converts a GeneBCMatrix",
"len(ids)))) + 1 n = cluster_order.size if cols == -1: cols = int(np.ceil(np.sqrt(n)))",
"rows = int(np.ceil(np.sqrt(len(cids)))) # # w = size * rows # # fig",
"#libplot.add_colorbar(fig, cmap) fig, ax = expr_plot(tsne, exp, cmap=cmap, dim=dim, w=w, h=h, s=s, colorbar=colorbar,",
"x1=x1, # x2=x2, # cmap=cmap, # marker=marker, # s=s, # alpha=alpha, # fig=fig,",
"= (a > 0) d = im_data[np.where(black_areas)] d[:, 0:3] = [64, 64, 64]",
"= [] for i in range(0, c1.shape[0]): ids1 = np.where(a1[i, :] > 0)[0]",
"# # im_no_gray, im_smooth = smooth_edges(im1, im1) # # # Edge detect on",
"def umi_tpm(data): # each column is a cell reads_per_bc = data.sum(axis=0) scaling_factors =",
"linewidth=EDGE_WIDTH, edgecolors='none', colorbar=True, method='tsne', bins=10, background=BACKGROUND_SAMPLE_COLOR): \"\"\" Plot multiple genes on a grid.",
"= cids[i] # # #print('Label {}'.format(l)) # idx2 = np.where(clusters['Cluster'] != c)[0] #",
"in range(0, len(cids)): # c = cids[i] # # #print('Label {}'.format(l)) # idx2",
"title=t) if not show_axes: libplot.invisible_axes(ax) return fig, ax # def expr_plot(tsne, # exp,",
"- 1] if i in colors: color = colors[i] # l] else: color",
"exp_bin = exp[idx_bin] tsne_bin = tsne.iloc[idx_bin, :] expr_plot(tsne_bin, exp_bin, cmap=cmap, s=s, colorbar=colorbar, norm=norm,",
"= tsne.iloc[idx1, 0] # y = tsne.iloc[idx1, 1] # # if isinstance(colors, dict):",
"[(x * avg[idx]).sum() / avg[idx].sum(), (y * avg[idx]).sum() / avg[idx].sum()] d = np.array([distance.euclidean(centroid,",
"cluster # im_base.paste(im2, (0, 0), im2) # break imagelib.save(im_base, out) def cluster_plot(tsne, clusters,",
"0] y = tsne.iloc[idx2, 1] libplot.scatter(x, y, c=[background], ax=ax, edgecolors='none', # bgedgecolor, linewidth=linewidth,",
"alpha=ALPHA, # libplot.ALPHA, show_axes=True, legend=True, sort=True, outline=True): cluster_order = list(sorted(set(clusters['Cluster']))) im_base = imagelib.new(w",
"cols = int(np.ceil(np.sqrt(l))) w = size * cols rows = int(l / cols)",
"= genes return ids.values, genes.values def get_gene_ids(data, genes, ids=None, gene_names=None): \"\"\" For a",
"'#ffdd55']) # BGY_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list('bgy', ['#002255', '#2ca05a', '#ffd42a']) # BGY_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list('bgy', ['#002255',",
"print(dsets) matrix = sp_sparse.csc_matrix( (dsets['data'], dsets['indices'], dsets['indptr']), shape=dsets['shape']) return GeneBCMatrix(decode(dsets['genes']), decode(dsets['gene_names']), decode(dsets['barcodes']), matrix)",
"norm = matplotlib.colors.Normalize(vmin=-3, vmax=3, clip=True) #cmap = plt.cm.plasma ids, gene_names = get_gene_names(data) gene_ids",
"that is not supported by this function.' % version) else: raise ValueError( 'Matrix",
"separate_cluster(tsne, clusters, cluster, color='black', background=BACKGROUND_SAMPLE_COLOR, bgedgecolor='#808080', show_background=True, add_titles=True, size=4, alpha=ALPHA, s=MARKER_SIZE, edgecolors='white', linewidth=EDGE_WIDTH,",
"pos=nx.spring_layout(G) #, k=2) # # #node_color = (c_phen['Cluster'][0:A.shape[0]] - 1).tolist() # node_color =",
"all of the transcripts. Parameters ---------- data : DataFrame data table containing and",
"gene) return expr_plot(tsne, exp, fig=fig, ax=ax, cmap=cmap, out=out) def separate_cluster(tsne, clusters, cluster, color='black',",
"gene_names=gene_names) for i in range(0, len(gene_ids)): gene_id = gene_ids[i][1] gene = gene_ids[i][2] print(gene_id,",
"# imagelib.paste(im_no_bg, im_smooth, inplace=True) # imagelib.save(im_no_bg, 'smooth.png') # imagelib.paste(im_base, im_no_bg, inplace=True) im =",
"sklearn.neighbors import kneighbors_graph from scipy.interpolate import griddata import h5py from scipy.interpolate import interp1d",
"# BGY_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list('bgy', ['#00264d', '#003366', '#339933', '#e6e600', '#ffff33']) # BGY_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list('bgy',",
"= griddata((x, y), avg1, (xi, yi)) #ax.contour(xi, yi, z, levels=1) def gene_expr(data, tsne,",
"order they should be rendered Returns ------- fig : Matplotlib figure A new",
"samples, w=6, h=6, format='pdf'): \"\"\" Split cells into a and b \"\"\" cache",
"points within 1 sd of centroid idx = np.where(abs(z) < sdmax)[0] # (d",
"1 # # ax.set_title('C{} ({:,})'.format(c, len(idx1)), color=colors[i]) # libplot.invisible_axes(ax) # # #set_tsne_ax_lim(tsne, ax)",
"1)) # # x = tsne.iloc[idx2, 0] # y = tsne.iloc[idx2, 1] #",
"# g = im_data[:, :, 1] # b = im_data[:, :, 2] #",
"= list(sorted(set(clusters['Cluster']))) indices = np.array(list(range(0, len(ids)))) if colors is None: colors = libcluster.get_colors()",
"fig = libplot.new_base_fig(w=w, h=w) # # if colors is None: # colors =",
"1 / m.sum(axis=0) mn = m.multiply(s) tpm = mn.multiply(1000000) return GeneBCMatrix(gbm.gene_ids, gbm.gene_names, gbm.barcodes,",
"libplot.savefig(fig, '{}/tsne_{}_sample_clusters.png'.format(dir, name)) # #libplot.savefig(fig, '{}/tsne_{}separate_clusters.pdf'.format(dir, name)) # # def load_clusters(pca, headers, name,",
"256))) BU_PU_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list( 'bu_pu', matplotlib.cm.BuPu(range(4, 256))) # BGY_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list('bgy', ['#0066ff', '#37c871',",
"for i in range(0, len(ids)): l = ids[i] #print('Label {}'.format(l)) indices = np.where(clusters['Cluster']",
"im_smooth = imagelib.smooth(im_outline) imagelib.save(im_smooth, 'smooth.png') # im_smooth imagelib.paste(im_base, im_smooth, inplace=True) else: imagelib.paste(im_base, im,",
"file, sep='\\t'): df(gbm).to_csv(file, sep=sep, header=True, index=True) def sum(gbm, axis=0): return gbm.matrix.sum(axis=axis) def tpm(gbm):",
"overlay edges on top of original image to highlight cluster #im_base.paste(im2, (0, 0),",
"# look up index for color purposes #i = np.where(ids == cluster)[0][0] print('index',",
"node_size=800, node_color=node_color, font_color='white', font_family='Arial') libplot.format_axes(ax) libplot.savefig(fig, '{}_centroid_network.pdf'.format(name)) def centroids(tsne, clusters): cids = list(sorted(set(clusters['Cluster'].tolist())))",
"# #im_data[np.where(black_areas)] = d # # #im3 = Image.fromarray(im_data) # #im2.save('edges.png', 'png') #",
"expr_plot(data, exp, dim=[1, 2], cmap=plt.cm.magma, marker='o', s=MARKER_SIZE, alpha=1, edgecolors=EDGE_COLOR, linewidth=EDGE_WIDTH, w=libplot.DEFAULT_WIDTH, h=libplot.DEFAULT_HEIGHT, show_axes=False,",
"xp[0]) yp = np.append(yp, yp[0]) ax.plot(xp, yp, 'k-') #ax.plot(points[hull.vertices[0], 0], points[hull.vertices[[0, -1]], 1])",
"TNSE_AX_Q = 0.999 MARKER_SIZE = 10 SUBPLOT_SIZE = 4 EXP_ALPHA = 0.8 #",
": Pandas dataframe t-sne, umap data clusters : Pandas dataframe n x 1",
"cache=cache) # pca.iloc[idx_b,:] tsne_b = libtsne.load_pca_tsne(pca_b, 'b', cache=cache) c_b = libtsne.load_phenograph_clusters(pca_b, 'b', cache=cache)",
"return df def to_csv(gbm, file, sep='\\t'): df(gbm).to_csv(file, sep=sep, header=True, index=True) def sum(gbm, axis=0):",
"= np.array(list(range(0, len(ids)))) + 1 n = cluster_order.size if cols == -1: cols",
"norm=norm, alpha=alpha, linewidth=linewidth, edgecolors=edgecolors, ax=ax) tmp = 'tmp{}.png'.format(bin) libplot.savefig(fig, tmp, pad=0) plt.close(fig) im",
"0: idx = idx[0] else: return None if isinstance(data, SparseDataFrame): return data[idx, :].to_array()",
"gene, fig=None, ax=None, cmap=plt.cm.plasma, out=None): \"\"\" Plot multiple genes on a grid. Parameters",
"#nx.draw_networkx(G, pos=pos, with_labels=False, ax=ax, node_size=200, node_color=node_color, vmax=(c.shape[0] - 1), cmap=libcluster.colormap()) nx.draw_networkx(G, with_labels=True, labels=labels,",
"what is left (the clusters) # im_edges = im2.filter(ImageFilter.FIND_EDGES) # # im_smooth =",
"labeled 'TSNE-1', 'TSNE-2' etc genes : array List of gene names \"\"\" if",
"= np.append(xp, xp[0]) yp = np.append(yp, yp[0]) ax.plot(xp, yp, 'k-') #ax.plot(points[hull.vertices[0], 0], points[hull.vertices[[0,",
"if idx.size > 0: idx = idx[0] else: return None if isinstance(data, SparseDataFrame):",
"pc2=pc2, labels=labels, marker=marker, legend=legend, s=s, w=w, h=h, fig=fig, ax=ax) libplot.savefig(fig, out, pad=2) plt.close(fig)",
"fig, ax = libplot.new_fig(w=w, h=h) # if norm is None and exp.min() <",
"ax = expr_plot(tsne, exp, dim=dim, cmap=cmap, marker=marker, s=s, alpha=alpha, fig=fig, w=w, h=h, ax=ax,",
"min', min) sd[np.where(sd < min)] = min if isinstance(max, float) or isinstance(max, int):",
"pc1=pc1, pc2=pc2, labels=labels, marker=marker, legend=legend, s=s, w=w, h=h, fig=fig, ax=ax) libplot.savefig(fig, out, pad=2)",
"gene names \"\"\" if dir[-1] == '/': dir = dir[:-1] if not os.path.exists(dir):",
"r = im_data[:, :, 0] # g = im_data[:, :, 1] # b",
"x1, 'Cluster': clusters.iloc[:, 0].tolist( ), 'Label': np.repeat('tsne-10x', len(x1))}) libplot.boxplot(df, 'Cluster', 'Silhouette Score', colors=libcluster.colors(),",
"from sklearn.preprocessing import MinMaxScaler from sklearn.metrics import silhouette_samples from sklearn.neighbors import kneighbors_graph from",
"j in range(i + 1, n): ax = libplot.new_ax(fig, subplot=(rows, rows, si)) pca_plot_base(pca,",
"return None if isinstance(data, SparseDataFrame): return data[idx, :].to_array() else: return data.iloc[idx, :].values def",
"a new one is created. norm : Normalize, optional Specify how colors should",
"# # # im_data = np.array(im_edges.convert('RGBA')) # # #r = data[:, :, 0]",
"- m) / sd # find all points within 1 sd of centroid",
"else: pass if legend_params['show']: libcluster.format_legend(ax, cols=legend_params['cols'], markerscale=legend_params['markerscale']) libplot.invisible_axes(ax) tmp = 'tmp{}.png'.format(i) libplot.savefig(fig, tmp)",
"\"\"\" if ids is None: ids, gene_names = get_gene_names(data) ret = [] for",
"each data point so it must have the same number of elements as",
"#avg1[idx] = 1 # fx = interp1d(points[hull.vertices, 0], points[hull.vertices, 1], kind='cubic') # fy",
"h=libplot.DEFAULT_HEIGHT, # colorbar=True): #plt.cm.plasma): # \"\"\" # Creates a basic t-sne expression plot.",
"= imagelib.remove_background(im) # im_smooth = imagelib.smooth_edges(im_no_bg) # imagelib.paste(im_no_bg, im_smooth, inplace=True) # imagelib.save(im_no_bg, 'smooth.png')",
"cells with a Cluster column giving each cell a cluster label. s :",
"a, b in zip(x, y)]) sd = d.std() m = d.mean() print(m, sd)",
"Exception(\"%s was not found in list of gene names.\" % gene_name) return gbm.matrix[gene_indices[0],",
"sc[np.where(d.index.str.contains(id))[0]] = s c += 1 print(np.unique(d.index.values)) print(np.unique(sc)) df = pd.DataFrame(sc, index=d.index, columns=['Cluster'])",
"imagelib.save(im_no_bg, 'smooth.png') # imagelib.paste(im_base, im_no_bg, inplace=True) im = imagelib.open(tmp) if outline: im_no_bg =",
"centroids(tsne, clusters): cids = list(sorted(set(clusters['Cluster'].tolist()))) ret = np.zeros((len(cids), 2)) for i in range(0,",
"columns=gbm.barcodes) def get_barcode_counts(gbm): ret = [] for i in range(len(gbm.barcodes)): ret.append(np.sum(gbm.matrix[:, i].toarray())) return",
"ax) # # libplot.invisible_axes(ax) # # if out is not None: # libplot.savefig(fig,",
"ax = separate_cluster(d, clusters, cluster, color=color, size=w, s=s, linewidth=linewidth, add_titles=False) # get x",
"labels += 1 libtsne.write_clusters(headers, labels, name) cluster_map, data = libtsne.read_clusters(file) labels = data",
"fig : Matplotlib figure # A new Matplotlib figure used to make the",
"color = colors[cluster] elif isinstance(colors, list): if cluster < len(colors): # np.where(clusters['Cluster'] ==",
"plot \"\"\" if out is None: out = '{}_expr.pdf'.format(method) fig, ax = expr_plot(tsne,",
"gene = gene_ids[i][2] print(gene_id, gene) exp = get_gene_data(data, gene_id, ids=ids, gene_names=gene_names) bin_means, bin_edges,",
"200) & (b < 255) & (b > 200) # # d =",
"1 table of n cells with a Cluster column giving each cell a",
"top of the background # # x = tsne.iloc[idx1, 0] # y =",
"['#001a33', '#003366', '#339933', '#ffff66', '#ffff00']) # BGY_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list('bgy', ['#00264d', '#003366', '#339933', '#e6e600',",
"dim[1] - 1].values # data['{}-{}'.format(t, d2)][idx] e = exp[idx] # if (e.min() ==",
"#print('Label {}'.format(l)) indices = np.where(clusters['Cluster'] == l)[0] n = len(indices) label = 'C{}",
"def gene_expr_grid(data, tsne, genes, cmap=None, size=SUBPLOT_SIZE): \"\"\" Plot multiple genes on a grid.",
"= tsne.iloc[idx2, 1] # libplot.scatter(x, y, c=BACKGROUND_SAMPLE_COLOR, ax=ax) # # # Plot cluster",
"= libplot.NORM_3 # Sort by expression level so that extreme values always appear",
"read_clusters(file): print('Reading clusters from {}...'.format(file)) return pd.read_csv(file, sep='\\t', header=0, index_col=0) def silhouette(tsne, tsne_umi_log2,",
"pca_b = libtsne.load_pca(d_b, 'b', cache=cache) # pca.iloc[idx_b,:] tsne_b = libtsne.load_pca_tsne(pca_b, 'b', cache=cache) c_b",
"a and b \"\"\" cache = True counts = libcluster.remove_empty_rows(counts) # ['AICDA', 'CD83',",
"% cols == 0: # Assume we will add a row for a",
"colorbar=True): #plt.cm.plasma): # \"\"\" # Creates a basic t-sne expression plot. # #",
"scaled = data.multiply(scaling_factors) # , axis=1) return scaled def umi_log2(d): if isinstance(d, SparseDataFrame):",
"c=[background], ax=ax, edgecolors='none', # bgedgecolor, linewidth=linewidth, s=s) # Plot cluster over the top",
"and exp.min() < 0: #norm = matplotlib.colors.Normalize(vmin=-3, vmax=3, clip=True) if norm is None:",
"tsne, genes, cid, clusters, prefix='', index=None, dir='GeneExp', cmap=OR_RED_CMAP, # BGY_CMAP, norm=None, w=libplot.DEFAULT_WIDTH, h=libplot.DEFAULT_HEIGHT,",
"ids, genes = data.index.str.split(';').str else: genes = data.index ids = genes return ids.values,",
"to show axes on plot legend : bool, optional, default true Whether to",
"= get_gene_data(data, gene_id, ids=ids, gene_names=gene_names) #fig, ax = libplot.new_fig() #expr_plot(tsne, exp, ax=ax) #libplot.add_colorbar(fig,",
"in range(0, bins): bi = bin + 1 idx_bin = np.where(binnumber == bi)[0]",
"# -*- coding: utf-8 -*- \"\"\" Created on Wed Jun 6 16:51:15 2018",
"= df2.iloc[:, pc1 - 1] y = df2.iloc[:, pc2 - 1] if i",
"node in f.walk_nodes('/matrix', 'Array'): # dsets[node.name] = node.read() print(dsets) matrix = sp_sparse.csc_matrix( (dsets['data'],",
"of tuples of (index, gene_id, gene_name) \"\"\" if ids is None: ids, gene_names",
"legend=False, w=w, h=h) libplot.savefig(fig, 'a/a_tsne_clusters_med.pdf') # b mkdir('b') b_barcodes = pd.read_csv('../b_barcodes.tsv', header=0, sep='\\t')",
"== g)[0] if idx.size > 0: # if id exists, pick the first",
"(0, 0), im2) if gene_id != gene: out = '{}/{}_expr_{}_{}.png'.format(dir, method, gene, gene_id)",
"fig=None, ax=None, cmap=plt.cm.plasma, out=None): \"\"\" Plot multiple genes on a grid. Parameters ----------",
"= int(np.ceil(n / cols)) w = size * cols h = size *",
"alpha=alpha, fig=fig, ax=ax, norm=norm) libplot.savefig(fig, out) plt.close(fig) return fig, ax def expr_grid_size(x, size=SUBPLOT_SIZE):",
"elif type(x) is np.ndarray: l = x.shape[0] elif type(x) is pd.core.frame.DataFrame: l =",
"xi = np.linspace(x.min(), x.max(), nx) yi = np.linspace(y.min(), y.max(), ny) x = x[idx]",
"legend=legend, sort=sort, out=out) def base_tsne_plot(tsne, marker='o', s=libplot.MARKER_SIZE, c='red', label=None, fig=None, ax=None): \"\"\" Create",
"Parameters ---------- path : str directory to create. \"\"\" try: os.makedirs(path) except: pass",
"w=w, h=h, cluster_order=cluster_order, legend=legend, sort=sort, show_axes=show_axes, fig=fig, ax=ax) #libtsne.tsne_legend(ax, labels, colors) #libcluster.format_simple_axes(ax, title=\"t-SNE\")",
"colors is None: colors = libcluster.get_colors() # Where to plot figure pc =",
"h5py.File(filename, 'r') as f: if u'version' in f.attrs: if f.attrs['version'] > 2: raise",
"clusters, name, colors=None, size=4, add_titles=True, type='tsne', format='pdf'): \"\"\" Plot each cluster into its",
"# A = kneighbors_graph(tsne, k, mode='distance', metric='euclidean').toarray() # # #A = A[0:500, 0:500]",
"if norm is None: norm = matplotlib.colors.Normalize(vmin=-3, vmax=3, clip=True) #cmap = plt.cm.plasma ids,",
"cids[i] x = tsne.iloc[np.where(clusters['Cluster'] == c)[0], :] centroid = (x.sum(axis=0) / x.shape[0]).tolist() ret[i,",
"otherwise a new one is created. norm : Normalize, optional Specify how colors",
"int(np.ceil(np.sqrt(len(cids)))) # # w = size * rows # # fig = libplot.new_base_fig(w=w,",
"Find the interesting clusters labels, graph, Q = phenograph.cluster(pca, k=20) if min(labels) ==",
"color = 'black' fig, ax = separate_cluster(tsne, clusters, cluster, color=color, add_titles=add_titles, size=size) out",
"1) expr_plot(tsne, exp, ax=ax, cmap=cmap, colorbar=False) # if i == 0: # libcluster.format_axes(ax)",
"make the plot ax : Matplotlib axes Axes used to render the figure",
"= im1.filter(ImageFilter.FIND_EDGES) im_data = np.array(imageWithEdges.convert('RGBA')) #r = data[:, :, 0] #g = data[:,",
"endpoint=True) # # xp = points[hull.vertices, 0] yp = points[hull.vertices, 1] xp =",
"gbm.gene_names df.columns = gbm.barcodes return df def to_csv(gbm, file, sep='\\t'): df(gbm).to_csv(file, sep=sep, header=True,",
"ValueError( 'Matrix HDF5 file format version (%d) is an older version that is",
"cluster)[0]] color = colors[i] else: color = 'black' else: color = 'black' ax",
"Matrix of umi counts \"\"\" # each column is a cell reads_per_bc =",
"dim=[1, 2], cmap=plt.cm.magma, marker='o', s=MARKER_SIZE, alpha=1, edgecolors=EDGE_COLOR, linewidth=EDGE_WIDTH, w=libplot.DEFAULT_WIDTH, h=libplot.DEFAULT_HEIGHT, show_axes=False, fig=None, ax=None,",
"pd from sklearn.manifold import TSNE import sklearn.preprocessing from sklearn.preprocessing import StandardScaler from sklearn.preprocessing",
"ConvexHull(points) #x1 = x[idx] #y1 = y[idx] # avg1 = np.zeros(x.size) #avg[idx] #avg1[idx]",
"+ genome, 'Array'): dsets[node.name] = node.read() # for node in f.walk_nodes('/matrix', 'Array'): #",
"genes, ids=ids, gene_names=gene_names) avg = exp.mean(axis=0) avg = (avg - avg.mean()) / avg.std()",
"columns=d.columns) else: return pd.DataFrame(MinMaxScaler(feature_range=(min, max)).fit_transform(d.T).T, index=d.index, columns=d.columns) def rscale(d, min=0, max=1, axis=1): if",
"None: libplot.savefig(fig, out) return fig, ax def create_cluster_plot(d, clusters, name, dim1=0, dim2=1, method='tsne',",
": array List of gene names \"\"\" if dir[-1] == '/': dir =",
"'TSNE-1', 'TSNE-2' etc genes : array List of gene names \"\"\" if dir[-1]",
"im2.filter(ImageFilter.FIND_EDGES) # # # im_data = np.array(im_edges.convert('RGBA')) # # #r = data[:, :,",
"= std * (max - min) + min # return scaled if axis",
"dataframe t-sne, umap data clusters : Pandas dataframe n x 1 table of",
"s=MARKER_SIZE, w=8, h=8, fig=None, ax=None): colors = libcluster.get_colors() if ax is None: fig,",
"= cluster_grid(tsne, clusters, colors=colors, cols=cols, size=size, add_titles=add_titles, cluster_order=cluster_order) if out is None: out",
"'#ff33ff', '#ffe066']) GYBLGRYL_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list( 'grey_blue_green_yellow', ['#e6e6e6', '#0055d4', '#00aa44', '#ffe066']) OR_RED_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list(",
"of points add_titles : bool Whether to add titles to plots plot_order: list,",
"w=6, s=30, alpha=1, linewidth=EDGE_WIDTH, edgecolors='none', colorbar=True, method='tsne', bins=10, background=BACKGROUND_SAMPLE_COLOR): \"\"\" Plot multiple genes",
"get_gene_names(data) ret = [] for g in genes: indexes = np.where(ids == g)[0]",
"idx.size > 0: # if id exists, pick the first idx = idx[0]",
"libplot.scatter(x, y, c=colors[sid], ax=ax) # # sid += 1 # # ax.set_title('C{} ({:,})'.format(c,",
"list): if cluster < len(colors): # np.where(clusters['Cluster'] == cluster)[0]] color = colors[i] else:",
"labels, name) cluster_map, data = libtsne.read_clusters(file) labels = data # .tolist() return cluster_map,",
"= data.multiply(scaling_factors) # , axis=1) return scaled def umi_log2(d): if isinstance(d, SparseDataFrame): print('UMI",
"for creating an expression plot for T-SNE/2D space reduced representation of data. Parameters",
"libplot.savefig(fig, 'network_{}.pdf'.format(name)) def plot_centroids(tsne, clusters, name): c = centroids(tsne, clusters) fig, ax =",
"plot, otherwise a new one is created. norm : Normalize, optional Specify how",
"return np.array([x.decode('utf-8') for x in items]) def get_matrix_from_h5(filename, genome): with tables.open_file(filename, 'r') as",
"= libplot.new_fig(w=w, h=h) ids = list(sorted(set(clusters['Cluster']))) for i in range(0, len(ids)): l =",
"# ------- # fig : Matplotlib figure # A new Matplotlib figure used",
"of the transcripts. Parameters ---------- data : DataFrame data table containing and index",
"for node in f.walk_nodes('/' + genome, 'Array'): dsets[node.name] = node.read() # for node",
"if cols == -1: cols = int(np.ceil(np.sqrt(n))) rows = int(np.ceil(n / cols)) w",
"fig = cluster_grid(tsne, clusters, colors=colors, cols=cols, size=size, add_titles=add_titles, cluster_order=cluster_order) if out is None:",
"bar rows += 1 h = size * rows return w, h, rows,",
"df.index = gbm.gene_names df.columns = gbm.barcodes return df def to_csv(gbm, file, sep='\\t'): df(gbm).to_csv(file,",
"color = 'black' ax.scatter(x, y, color=color, edgecolor=color, s=s, marker=marker, alpha=libplot.ALPHA, label=label) if labels:",
"pca_plot_base(pca, clusters, pc1=pc1, pc2=pc2, marker=marker, labels=labels, s=s, w=w, h=h, fig=fig, ax=ax) #libtsne.tsne_legend(ax, labels,",
"edgecolors=EDGE_COLOR, linewidth=EDGE_WIDTH, w=libplot.DEFAULT_WIDTH, h=libplot.DEFAULT_HEIGHT, show_axes=False, fig=None, ax=None, norm=None, colorbar=False): # plt.cm.plasma): \"\"\" Creates",
"np.append(yp, yp[0]) ax.plot(xp, yp, 'k-') #ax.plot(points[hull.vertices[0], 0], points[hull.vertices[[0, -1]], 1]) #points = np.array([[x,",
"\"\"\" df = pd.DataFrame(gbm.matrix.todense()) df.index = gbm.gene_names df.columns = gbm.barcodes return df def",
"Normalize, optional Specify how colors should be normalized Returns ------- fig : matplotlib",
"return pd.DataFrame(RobustScaler().fit_transform(d.T).T, index=d.index, columns=d.columns) def umi_norm_log2_scale(data, clip=None): d = umi_norm_log2(data) return scale(d, clip=clip)",
"= tsne_other.iloc[:, 1] libplot.scatter(x, y, c=[background], ax=ax, edgecolors='none', # bgedgecolor, linewidth=linewidth, s=s) #fig,",
"'{}/{}_expr_{}.{}'.format(dir, method, gene, format) libplot.savefig(fig, 'tmp.png', pad=0) libplot.savefig(fig, out, pad=0) plt.close(fig) im1 =",
"ax=ax) #libplot.add_colorbar(fig, cmap) exp_bin = exp[idx_bin] tsne_bin = tsne.iloc[idx_bin, :] expr_plot(tsne_bin, exp_bin, cmap=cmap,",
"= im_data[:, :, 1] # b = im_data[:, :, 2] # # grey_areas",
"= data.index if isinstance(genes, pd.core.frame.DataFrame): genes = genes['Genes'].values if norm is None: norm",
"as nx import os import phenograph import libplot import libcluster import libtsne import",
"out) return fig, ax def create_cluster_plot(d, clusters, name, dim1=0, dim2=1, method='tsne', markers='o', s=libplot.MARKER_SIZE,",
"clip=True) LEGEND_PARAMS = {'show': True, 'cols': 4, 'markerscale': 2} CLUSTER_101_COLOR = (0.3, 0.3,",
"# # # Non transparent areas are edges # #black_areas = (a >",
"* cols h = size * rows fig = libplot.new_base_fig(w=w, h=h) if colors",
"# c='#ffffff00', # s=s, # marker=marker, # norm=norm, # edgecolors=[color], # linewidth=linewidth) #libcluster.format_axes(ax,",
"'png') # overlay edges on top of original image to highlight cluster #",
"c='red', label=None, fig=None, ax=None): fig, ax = base_tsne_plot(tsne, marker=marker, c=c, s=s, label=label, fig=fig,",
"import griddata import h5py from scipy.interpolate import interp1d from scipy.spatial import distance import",
"ax=ax) #libtsne.tsne_legend(ax, labels, colors) libcluster.format_simple_axes(ax, title=\"t-SNE\") libcluster.format_legend(ax, cols=6, markerscale=2) return fig, ax def",
"Clusters in # # Returns # ------- # fig : Matplotlib figure #",
"# x2=x2, # cmap=cmap, # marker=marker, # s=s, # alpha=alpha, # fig=fig, #",
"------- # fig : Matplotlib figure # A new Matplotlib figure used to",
"if not show_axes: libplot.invisible_axes(ax) return fig, ax # def expr_plot(tsne, # exp, #",
"for index in indexes: ret.append((index, ids[index], gene_names[index])) else: # if id does not",
"'TSNE-2' etc genes : array List of gene names \"\"\" exp = get_gene_data(data,",
"d.shape[0])], dtype=object) c = 1 for s in sample_names: id = '-{}'.format(c) print(id)",
"linewidth=EDGE_WIDTH, norm=None, method='tsne', show_axes=False, colorbar=True, out=None): # plt.cm.plasma): \"\"\" Creates and saves a",
"'Cluster', 'Silhouette Score', colors=libcluster.colors(), ax=ax) ax.set_ylim([-1, 1]) ax.set_title('tsne-10x') #libplot.savefig(fig, 'RK10001_10003_clust-phen_silhouette.pdf') ax = fig.add_subplot(212)",
"Image.fromarray(im_data) # # im_no_gray, im_smooth = smooth_edges(im1, im1) # # # Edge detect",
"linewidth=linewidth, alpha=alpha, cmap=cmap, norm=norm, w=w, h=h, ax=ax) # if colorbar or is_first: if",
"= imagelib.paste(im, im_edges) # im_no_bg im_smooth = imagelib.smooth(im_outline) imagelib.save(im_smooth, 'smooth.png') # im_smooth imagelib.paste(im_base,",
"/ avg.std() avg[avg < -1.5] = -1.5 avg[avg > 1.5] = 1.5 avg",
"def decode(items): return np.array([x.decode('utf-8') for x in items]) def get_matrix_from_h5(filename, genome): with tables.open_file(filename,",
"(0, 0), im_smooth) # # # overlay edges on top of original image",
"of (index, gene_id, gene_name) \"\"\" if ids is None: ids, gene_names = get_gene_names(data)",
"& (r > 200) & (g < 255) & (g > 200) &",
"Plot each cluster separately to highlight samples # # Parameters # ---------- #",
"dim=dim, cmap=cmap, marker=marker, s=s, fig=fig, alpha=alpha, ax=ax, norm=norm) return fig, ax def pca_expr_plot(data,",
"method, gene) print(out) # overlay edges on top of original image to highlight",
"scipy.interpolate import griddata import h5py from scipy.interpolate import interp1d from scipy.spatial import distance",
"# #d[:, 0:3] = [64, 64, 64] # #im_data[np.where(black_areas)] = d # #",
"return pd.DataFrame(MinMaxScaler(feature_range=(min, max)).fit_transform(d), index=d.index, columns=d.columns) else: return pd.DataFrame(MinMaxScaler(feature_range=(min, max)).fit_transform(d.T).T, index=d.index, columns=d.columns) def rscale(d,",
"elif type(x) is list: l = len(x) elif type(x) is np.ndarray: l =",
"kneighbors_graph(tsne, k, mode='distance', metric='euclidean').toarray() # # #A = A[0:500, 0:500] # # G=nx.from_numpy_matrix(A)",
"base_expr_plot(data, exp, dim=dim, s=s, marker=marker, edgecolors=edgecolors, linewidth=linewidth, alpha=alpha, cmap=cmap, norm=norm, w=w, h=h, ax=ax)",
"= tsne.iloc[:, 1].values # data['{}-{}'.format(t, d2)][idx] idx = np.where(clusters['Cluster'] == cid)[0] nx =",
"# d1=d1, # d2=d2, # x1=x1, # x2=x2, # cmap=cmap, # marker=marker, #",
"ax=ax) si += 1 return fig def pca_plot_base(pca, clusters, pc1=1, pc2=2, marker='o', labels=False,",
"dim1=0, dim2=1, method='tsne', markers='o', s=libplot.MARKER_SIZE, w=8, h=8, colors=None, legend=True, sort=True, show_axes=False, ax=None, cluster_order=None,",
"return fig, ax def expr_grid_size(x, size=SUBPLOT_SIZE): \"\"\" Auto size grid to look nice.",
"matplotlib.colors.Normalize(vmin=-3, vmax=3, clip=True) if norm is None: norm = libplot.NORM_3 # Sort by",
"if not os.path.exists(dir): mkdir(dir) if index is None: index = data.index if isinstance(genes,",
"pd.read_csv('../../../../expression_genes.txt', header=0) mkdir('a') a_barcodes = pd.read_csv('../a_barcodes.tsv', header=0, sep='\\t') idx = np.where(counts.columns.isin(a_barcodes['Barcode'].values))[0] d_a =",
"c_a = libtsne.load_phenograph_clusters(pca_a, 'a', cache=cache) create_pca_plot(pca_a, c_a, 'a', dir='a') create_cluster_plot(tsne_a, c_a, 'a', dir='a')",
"BGY_ORIG_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list( 'bgy', ['#002255', '#003380', '#2ca05a', '#ffd42a', '#ffdd55']) BGY_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list( 'bgy',",
"exp, dim=[1, 2], cmap=plt.cm.plasma, marker='o', edgecolors=EDGE_COLOR, linewidth=1, s=MARKER_SIZE, alpha=1, w=libplot.DEFAULT_WIDTH, h=libplot.DEFAULT_HEIGHT, fig=None, ax=None,",
"= umi_norm(data) print(type(d)) return umi_log2(d) def scale(d, clip=None, min=None, max=None, axis=1): if isinstance(d,",
"= sd.T if isinstance(clip, float) or isinstance(clip, int): max = abs(clip) min =",
"y = y[idx] #centroid = [x.sum() / x.size, y.sum() / y.size] centroid =",
"== c) & clusters.index.str.contains(id))[0] # # x = tsne.iloc[idx1, 0] # y =",
"not None: libplot.savefig(fig, out, pad=0) return fig, ax def base_pca_expr_plot(data, exp, dim=[1, 2],",
"not os.path.exists(dir): mkdir(dir) if index is None: index = data.index if isinstance(genes, pd.core.frame.DataFrame):",
"0].tolist( ), 'Label': np.repeat('tsne-ah', len(x2))}) libplot.boxplot(df2, 'Cluster', 'Silhouette Score', colors=libcluster.colors(), ax=ax) ax.set_ylim([-1, 1])",
"markers=markers, colors=colors, dim1=dim1, dim2=dim2, s=s, w=w, h=h, cluster_order=cluster_order, legend=legend, sort=sort, show_axes=show_axes, fig=fig, ax=ax)",
"yp = points[hull.vertices, 1] xp = np.append(xp, xp[0]) yp = np.append(yp, yp[0]) ax.plot(xp,",
"BGY_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list('bgy', ['#001a33', '#003366', '#339933', '#ffff66', '#ffff00']) # BGY_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list('bgy', ['#00264d',",
"np.where(np.isin(gene_names, g))[0] if idx.size < 1: return None else: idx = np.where(ids ==",
"color = CLUSTER_101_COLOR else: color = 'black' fig, ax = separate_cluster(tsne, clusters, cluster,",
"= cluster - 1 if i < len(colors): # colors[cid - 1] #colors[i]",
"== cluster)[0]] color = colors[i] else: color = 'black' else: color = 'black'",
"= sp_sparse.csc_matrix( (f['matrix']['data'], f['matrix']['indices'], f['matrix']['indptr']), shape=f['matrix']['shape']) return GeneBCMatrix(feature_ids, feature_names, decode(barcodes), matrix) def save_matrix_to_h5(gbm,",
"'indptr', obj=gbm.matrix.indptr) f.create_carray(group, 'shape', obj=gbm.matrix.shape) except: raise Exception(\"Failed to write H5 file.\") def",
"ax = libplot.new_fig() #expr_plot(tsne, exp, ax=ax) #libplot.add_colorbar(fig, cmap) exp_bin = exp[idx_bin] tsne_bin =",
"import seaborn as sns from libsparse.libsparse import SparseDataFrame from lib10x.sample import * from",
"if legend_params['show']: libcluster.format_legend(ax, cols=legend_params['cols'], markerscale=legend_params['markerscale']) return fig, ax def base_cluster_plot_outline(out, d, clusters, s=libplot.MARKER_SIZE,",
"'blue', ['#162d50', '#afc6e9']) BLUE_GREEN_YELLOW_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list( 'bgy', ['#162d50', '#214478', '#217844', '#ffcc00', '#ffdd55']) #",
"1), marker=marker, s=s) def pca_base_plots(pca, clusters, n=10, marker='o', s=MARKER_SIZE): rows = libplot.grid_size(n) w",
"= silhouette_samples( tsne_umi_log2, clusters.iloc[:, 0].tolist(), metric='euclidean') fig, ax = libplot.newfig(w=9, h=7, subplot=211) df",
"- 1], pca.index[i]) return fig, ax def pca_plot(pca, clusters, pc1=1, pc2=2, marker='o', labels=False,",
"show_axes=True, legend=True, sort=True, cluster_order=None, fig=None, ax=None): \"\"\" Create a tsne plot without the",
"-1: cols = int(np.ceil(np.sqrt(n))) rows = int(np.ceil(n / cols)) w = size *",
"[] for i in range(len(gbm.barcodes)): ret.append(np.sum(gbm.matrix[:, i].toarray())) return ret def df(gbm): \"\"\" Converts",
"is list: l = len(x) elif type(x) is np.ndarray: l = x.shape[0] elif",
"y, c=BACKGROUND_SAMPLE_COLOR, ax=ax) # # # Plot cluster over the top of the",
"0].quantile(TNSE_AX_Q)] ylim = [d2[d2 < 0].quantile(1 - TNSE_AX_Q), d2[d2 >= 0].quantile(TNSE_AX_Q)] #print(xlim, ylim)",
"color = 'black' ax = libplot.new_ax(fig, subplot=(rows, cols, pc)) separate_cluster(tsne, clusters, cluster, color=color,",
"dsets[node.name] = node.read() print(dsets) matrix = sp_sparse.csc_matrix( (dsets['data'], dsets['indices'], dsets['indptr']), shape=dsets['shape']) return GeneBCMatrix(decode(dsets['genes']),",
"c=BACKGROUND_SAMPLE_COLOR, ax=ax) # # # Plot cluster over the top of the background",
"tsne tsne data. Columns should be labeled 'TSNE-1', 'TSNE-2' etc genes : array",
"(f['matrix']['data'], f['matrix']['indices'], f['matrix']['indptr']), shape=f['matrix']['shape']) return GeneBCMatrix(feature_ids, feature_names, decode(barcodes), matrix) def save_matrix_to_h5(gbm, filename, genome):",
"# fig = tsne_cluster_sample_grid(tsne, clusters, samples, colors, size) # # libplot.savefig(fig, '{}/tsne_{}_sample_clusters.png'.format(dir, name))",
"BLUE_GREEN_YELLOW_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list( 'bgy', ['#162d50', '#214478', '#217844', '#ffcc00', '#ffdd55']) # BGY_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list('bgy',",
"h5py from scipy.interpolate import interp1d from scipy.spatial import distance import networkx as nx",
"w=w, h=h, s=s, colorbar=colorbar, norm=norm, alpha=alpha, linewidth=linewidth, edgecolors=edgecolors) if gene_id != gene: out",
"alpha=alpha, linewidth=linewidth, edgecolors=edgecolors) if gene_id != gene: out = '{}/{}_expr_{}_{}.{}'.format(dir, method, gene, gene_id,",
"elif isinstance(colors, list): #i = cluster - 1 if i < len(colors): #",
"Parameters ---------- tsne : Pandas dataframe Cells x tsne tsne data. Columns should",
"w=libplot.DEFAULT_WIDTH, h=libplot.DEFAULT_HEIGHT, show_axes=False, fig=None, ax=None, norm=None, colorbar=False): # plt.cm.plasma): \"\"\" Creates a base",
"< 255) & (b > 200) # # d = im_data[np.where(grey_areas)] # d[:,",
"- e.mean()) / e.std() #print(e.min(), e.max()) # z-score #e = (e - e.mean())",
"# bgedgecolor, linewidth=linewidth, s=s) #fig, ax = libplot.new_fig() #expr_plot(tsne, exp, ax=ax) #libplot.add_colorbar(fig, cmap)",
"#std = (d - m) / (d.max(axis=1) - m) #scaled = std *",
"y)]) sd = d.std() m = d.mean() print(m, sd) z = (d -",
"scipy.spatial import ConvexHull from PIL import Image, ImageFilter from scipy.stats import binned_statistic import",
"gene_names=gene_names) #fig, ax = libplot.new_fig() #expr_plot(tsne, exp, ax=ax) #libplot.add_colorbar(fig, cmap) fig, ax =",
"idx = np.where(gene_names == g)[0] if idx.size > 0: idx = idx[0] else:",
"matrix tsne : Pandas dataframe Cells x tsne tsne data. Columns should be",
"ax=ax) x = tsne.iloc[:, 0].values # data['{}-{}'.format(t, d1)][idx] y = tsne.iloc[:, 1].values #",
"return ret def df(gbm): \"\"\" Converts a GeneBCMatrix to a pandas dataframe (dense)",
"clip=clip) def read_clusters(file): print('Reading clusters from {}...'.format(file)) return pd.read_csv(file, sep='\\t', header=0, index_col=0) def",
"def split_a_b(counts, samples, w=6, h=6, format='pdf'): \"\"\" Split cells into a and b",
"\"\"\" Creates a base expression plot and adds a color bar. \"\"\" is_first",
"ax=ax, show_axes=show_axes, colorbar=colorbar, norm=norm, linewidth=linewidth, edgecolors=edgecolors) if out is not None: libplot.savefig(fig, out,",
"tables.NoSuchNodeError: raise Exception(\"Genome %s does not exist in this file.\" % genome) except",
"Image.fromarray(im_data) # # # Edge detect on what is left (the clusters) #",
"'or_red', matplotlib.cm.OrRd(range(4, 256))) BU_PU_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list( 'bu_pu', matplotlib.cm.BuPu(range(4, 256))) # BGY_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list('bgy',",
"rscale(d, min=0, max=1, axis=1): if axis == 0: return pd.DataFrame(RobustScaler().fit_transform(d), index=d.index, columns=d.columns) else:",
"tsne plot without the formatting Parameters ---------- d : Pandas dataframe t-sne, umap",
"# Plot each cluster separately to highlight samples # # Parameters # ----------",
"im2.filter(ImageFilter.FIND_EDGES) # # im_smooth = im_edges.filter(ImageFilter.SMOOTH) # # # paste outline onto clusters",
"s=30, alpha=ALPHA, linewidth=EDGE_WIDTH, edgecolors='none', colorbar=True, method='tsne', format='png'): \"\"\" Plot multiple genes on a",
"the gene names idx = np.where(np.isin(gene_names, g))[0] if idx.size < 1: return None",
"# [0.3, 0.3, 0.3] #'#4d4d4d' EDGE_WIDTH = 0 # 0.25 ALPHA = 0.9",
"median_reads_per_bc / reads_per_bc scaled = data.multiply(scaling_factors) # , axis=1) return scaled def umi_norm_log2(data):",
"-3 #e[e > 3] = 3 ax.scatter(x, y, c=e, s=s, marker=marker, alpha=alpha, cmap=cmap,",
"import scipy.sparse as sp_sparse import tables import pandas as pd from sklearn.manifold import",
"metric='euclidean') fig, ax = libplot.newfig(w=9, h=7, subplot=211) df = pd.DataFrame({'Silhouette Score': x1, 'Cluster':",
"elif isinstance(legend, dict): legend_params.update(legend) else: pass if legend_params['show']: libcluster.format_legend(ax, cols=legend_params['cols'], markerscale=legend_params['markerscale']) return fig,",
"HDF5 file format version (%d) is an older version that is not supported",
"pc2=2, marker='o', labels=False, legend=True, s=MARKER_SIZE, w=8, h=8, fig=None, ax=None, dir='.', format='png'): out =",
"y.sum() / y.size] centroid = [(x * avg[idx]).sum() / avg[idx].sum(), (y * avg[idx]).sum()",
"(y * avg[idx]).sum() / avg[idx].sum()] d = np.array([distance.euclidean(centroid, (a, b)) for a, b",
"/ (avg.max() - avg.min()) # min_max_scale(avg) create_expr_plot(tsne, avg, cmap=cmap, w=w, h=h, colorbar=colorbar, norm=norm,",
"colors[i] # else: # color = 'black' # # libplot.scatter(x, y, c=color, ax=ax)",
": array List of gene names \"\"\" exp = get_gene_data(data, gene) return expr_plot(tsne,",
"out=None, # fig=None, # ax=None, # norm=None, # w=libplot.DEFAULT_WIDTH, # h=libplot.DEFAULT_HEIGHT, # colorbar=True):",
"i + 1 #nx.draw_networkx(G, pos=pos, with_labels=False, ax=ax, node_size=200, node_color=node_color, vmax=(c.shape[0] - 1), cmap=libcluster.colormap())",
"clusters colored by sample # \"\"\" # fig = tsne_cluster_sample_grid(tsne, clusters, samples, colors,",
"fig=fig, alpha=alpha, ax=ax, norm=norm) return fig, ax def pca_expr_plot(data, expr, name, dim=[1, 2],",
"base_tsne_plot(tsne, marker='o', s=libplot.MARKER_SIZE, c='red', label=None, fig=None, ax=None): \"\"\" Create a tsne plot without",
"libplot.add_colorbar(fig, cmap, norm=norm) #libcluster.format_simple_axes(ax, title=t) if not show_axes: libplot.invisible_axes(ax) return fig, ax #",
"gene_ids[i][1] gene = gene_ids[i][2] print(gene, gene_id) exp = get_gene_data(data, gene_id, ids=ids, gene_names=gene_names) ax",
"f.attrs: if f.attrs['version'] > 2: raise ValueError( 'Matrix HDF5 file format version (%d)",
"gbm.gene_names gene_indices = np.where(genes == gene_name)[0] if len(gene_indices) == 0: raise Exception(\"%s was",
"c = cids[i] # # #print('Label {}'.format(l)) # idx2 = np.where(clusters['Cluster'] != c)[0]",
"if ax is None: fig, ax = libplot.new_fig(w=w, h=h) libcluster.scatter_clusters(d.iloc[:, dim1].values, d.iloc[:, dim2].values,",
"= 'black' fig, ax = separate_cluster(d, clusters, cluster, color=color, size=w, s=s, linewidth=linewidth, add_titles=False)",
"isinstance(colors, dict): # color = colors[cluster] # elif isinstance(colors, list): # color =",
"libplot.savefig(fig, 'tmp.png') plt.close(fig) def cluster_grid(tsne, clusters, colors=None, cols=-1, size=SUBPLOT_SIZE, add_titles=True, cluster_order=None): \"\"\" Plot",
"ids[i] if isinstance(colors, dict): color = colors[cluster] elif isinstance(colors, list): if cluster <",
"print(gene_id, gene) exp = get_gene_data(data, gene_id, ids=ids, gene_names=gene_names) #fig, ax = libplot.new_fig() #expr_plot(tsne,",
"on top of original image to highlight cluster # enable if edges desired",
"axis=1) return scaled def umi_log2(d): if isinstance(d, SparseDataFrame): print('UMI norm log2 sparse') return",
"= np.linspace(y.min(), y.max(), 100, endpoint=True) # # xp = points[hull.vertices, 0] yp =",
"with...'.format(file)) # Find the interesting clusters labels, graph, Q = phenograph.cluster(pca, k=20) if",
"= d # # im2 = Image.fromarray(im_data) # # # Edge detect on",
"= matplotlib.colors.LinearSegmentedColormap.from_list( 'blue', ['#162d50', '#afc6e9']) BLUE_GREEN_YELLOW_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list( 'bgy', ['#162d50', '#214478', '#217844', '#ffcc00',",
"# dsets[node.name] = node.read() print(dsets) matrix = sp_sparse.csc_matrix( (dsets['data'], dsets['indices'], dsets['indptr']), shape=dsets['shape']) return",
"that extreme values always appear on top idx = np.argsort(exp) #np.argsort(abs(exp)) # np.argsort(exp)",
": Pandas dataframe Matrix of umi counts \"\"\" # each column is a",
"ax=ax, node_size=800, node_color=node_color, font_color='white', font_family='Arial') libplot.format_axes(ax) libplot.savefig(fig, '{}_centroid_network.pdf'.format(name)) def centroids(tsne, clusters): cids =",
"as plt import collections import numpy as np import scipy.sparse as sp_sparse import",
"if isinstance(cluster, int): prefix = 'C' else: prefix = '' ax.set_title('{}{} ({:,})'.format( prefix,",
"['feature_ids', 'feature_names', 'barcodes', 'matrix']) def get_matrix_from_h5_v2(filename, genome): with h5py.File(filename, 'r') as f: if",
"return fig, ax def expr_plot(data, exp, dim=[1, 2], cmap=plt.cm.magma, marker='o', s=MARKER_SIZE, alpha=1, edgecolors=EDGE_COLOR,",
"ax is None: fig, ax = libplot.new_fig(w=w, h=h) # if norm is None",
"StandardScaler from sklearn.preprocessing import RobustScaler from sklearn.preprocessing import MinMaxScaler from sklearn.metrics import silhouette_samples",
"= [x.decode('ascii', 'ignore') for x in f['matrix']['features']['id']] feature_names = [x.decode('ascii', 'ignore') for x",
"= tsne_other.iloc[:, 0] y = tsne_other.iloc[:, 1] libplot.scatter(x, y, c=[background], ax=ax, edgecolors='none', #",
"to 3 std for z-scores #e[e < -3] = -3 #e[e > 3]",
"of umi counts \"\"\" # each column is a cell reads_per_bc = data.sum(axis=0)",
": bool Whether to add titles to plots w: int, optional width of",
"['#003366', '#40bf80', '#ffff33']) BGY_ORIG_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list( 'bgy', ['#002255', '#003380', '#2ca05a', '#ffd42a', '#ffdd55']) BGY_CMAP",
"'-{}'.format(c) print(id) print(np.where(d.index.str.contains(id))[0]) sc[np.where(d.index.str.contains(id))[0]] = s c += 1 print(np.unique(d.index.values)) print(np.unique(sc)) df =",
"cluster_order[i] if isinstance(colors, dict): color = colors[cluster] elif isinstance(colors, list): if cluster <",
"names indexes = np.where(gene_names == g)[0] for index in indexes: ret.append((index, ids[index], gene_names[index]))",
"ids = genes return ids.values, genes.values def get_gene_ids(data, genes, ids=None, gene_names=None): \"\"\" For",
"pd.DataFrame(sc, index=d.index, columns=['Cluster']) return df def create_cluster_samples(tsne_umi_log2, clusters, sample_names, name, method='tsne', format='png', dir='.',",
"colors=libcluster.colors(), ax=ax) ax.set_ylim([-1, 1]) ax.set_title('tsne-ah') libplot.savefig(fig, '{}_silhouette.pdf'.format(name)) def node_color_from_cluster(clusters): colors = libcluster.colors() return",
"= '{}/{}_{}.{}'.format(dir, method, name, format) print(out) return cluster_plot(d, clusters, dim1=dim1, dim2=dim2, markers=markers, colors=colors,",
"subplot=(rows, rows, i + 1)) # # x = tsne.iloc[idx2, 0] # y",
"try: os.makedirs(path) except: pass def split_a_b(counts, samples, w=6, h=6, format='pdf'): \"\"\" Split cells",
"& (r == b) & (g == b) # # #d = im_data[np.where(black_areas)]",
"np.where(gene_names == g)[0] for index in indexes: ret.append((index, ids[index], gene_names[index])) return ret def",
"# s=s, # alpha=alpha, # fig=fig, # ax=ax, # norm=norm, # w=w, #",
"= libplot.new_ax(fig, subplot=(rows, cols, pc)) separate_cluster(tsne, clusters, cluster, color=color, add_titles=add_titles, ax=ax) # idx1",
"tsne_other.iloc[:, 1] libplot.scatter(x, y, c=[background], ax=ax, edgecolors='none', # bgedgecolor, linewidth=linewidth, s=s) #fig, ax",
"is_first = False if ax is None: fig, ax = libplot.new_fig(w, h) is_first",
"dir='a/GeneExp', format=format) fig, ax = cluster_plot(tsne_a, c_a, legend=False, w=w, h=h) libplot.savefig(fig, 'a/a_tsne_clusters_med.pdf') #",
"cols=cols, size=size, add_titles=add_titles, cluster_order=cluster_order) if out is None: out = '{}/{}_{}_separate_clusters.png'.format(dir, method, name)",
"# each column is a cell reads_per_bc = data.sum(axis=0) # int(np.round(np.median(reads_per_bc))) median_reads_per_bc =",
"Matplotlib figure A new Matplotlib figure used to make the plot ax :",
"s=s) def pca_base_plots(pca, clusters, n=10, marker='o', s=MARKER_SIZE): rows = libplot.grid_size(n) w = 4",
"min(labels) == -1: new_label = 100 labels[np.where(labels == -1)] = new_label labels +=",
"file format version (%d) is an older version that is not supported by",
"labels, colors) libcluster.format_simple_axes(ax, title=\"PC\") if legend: libcluster.format_legend(ax, cols=6, markerscale=2) return fig, ax def",
"exp = get_gene_data(data, gene_id, ids=ids, gene_names=gene_names) #fig, ax = libplot.new_fig() #expr_plot(tsne, exp, ax=ax)",
"dir='b') genes_expr(d_b, tsne_b, genes, prefix='b_BGY', cmap=BLUE_GREEN_YELLOW_CMAP, w=w, h=h, dir='b/GeneExp', format=format) fig, ax =",
"coding: utf-8 -*- \"\"\" Created on Wed Jun 6 16:51:15 2018 @author: antony",
"16:51:15 2018 @author: antony \"\"\" import matplotlib # matplotlib.use('agg') import matplotlib.pyplot as plt",
"'#e6e600', '#ffff33']) # BGY_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list('bgy', ['#003366', '#40bf80', '#ffff33']) BGY_ORIG_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list( 'bgy',",
"# x = tsne.iloc[idx2, 0] # y = tsne.iloc[idx2, 1] # libplot.scatter(x, y,",
"ylim) # ax.set_xlim(xlim) # ax.set_ylim(ylim) def base_cluster_plot(d, clusters, markers=None, s=libplot.MARKER_SIZE, colors=None, edgecolors=EDGE_COLOR, linewidth=EDGE_WIDTH,",
"dict): # color = colors[cluster] # elif isinstance(colors, list): # color = colors[i]",
"\"\"\" Plot each cluster into its own plot file. \"\"\" ids = list(sorted(set(clusters['Cluster'])))",
"1] = centroid[1] return ret def knn_method_overlaps(tsne1, tsne2, clusters, name, k=5): c1 =",
"to plots w: int, optional width of new ax. h: int, optional height",
"is not None: libplot.savefig(fig, out, pad=0) return fig, ax def base_pca_expr_plot(data, exp, dim=[1,",
"format=format) fig, ax = cluster_plot(tsne_a, c_a, legend=False, w=w, h=h) libplot.savefig(fig, 'a/a_tsne_clusters_med.pdf') # b",
"---------- path : str directory to create. \"\"\" try: os.makedirs(path) except: pass def",
"# # overlay edges on top of original image to highlight cluster #",
"create_cluster_grid(tsne, clusters, name, colors=None, cols=-1, size=SUBPLOT_SIZE, add_titles=True, cluster_order=None, method='tsne', dir='.', out=None): fig =",
"cache=cache) create_pca_plot(pca_b, c_b, 'b', dir='b') create_cluster_plot(tsne_b, c_b, 'b', dir='b') create_cluster_grid(tsne_b, c_b, 'b', dir='b')",
"ax = separate_cluster(d, clusters, cluster, color=color, size=w, s=s, linewidth=linewidth, add_titles=False, show_background=False) ax.set_xlim(xlim) ax.set_ylim(ylim)",
"list(sorted(set(clusters['Cluster']))) indices = np.array(list(range(0, len(ids)))) if colors is None: colors = libcluster.get_colors() for",
"decode(items): return np.array([x.decode('utf-8') for x in items]) def get_matrix_from_h5(filename, genome): with tables.open_file(filename, 'r')",
"ax = libplot.new_ax(fig, subplot=(rows, cols, pc)) separate_cluster(tsne, clusters, cluster, color=color, add_titles=add_titles, ax=ax) #",
"== 0: return pd.DataFrame(MinMaxScaler(feature_range=(min, max)).fit_transform(d), index=d.index, columns=d.columns) else: return pd.DataFrame(MinMaxScaler(feature_range=(min, max)).fit_transform(d.T).T, index=d.index, columns=d.columns)",
"as sp_sparse import tables import pandas as pd from sklearn.manifold import TSNE import",
"b) & (g == b) # # #d = im_data[np.where(black_areas)] # #d[:, 0:3]",
"# # return fig, ax def create_expr_plot(tsne, exp, dim=[1, 2], cmap=None, marker='o', s=MARKER_SIZE,",
"'Label': np.repeat('tsne-ah', len(x2))}) libplot.boxplot(df2, 'Cluster', 'Silhouette Score', colors=libcluster.colors(), ax=ax) ax.set_ylim([-1, 1]) ax.set_title('tsne-ah') libplot.savefig(fig,",
"1)), 'Overlap %': overlaps}) df.set_index('Cluster', inplace=True) df.to_csv('{}_cluster_overlaps.txt'.format(name), sep='\\t') def mkdir(path): \"\"\" Make dirs",
"# # print(tmp, r.shape) # # grey_areas = (r < 255) & (r",
"plt.close(fig) def cluster_grid(tsne, clusters, colors=None, cols=-1, size=SUBPLOT_SIZE, add_titles=True, cluster_order=None): \"\"\" Plot each cluster",
"h=h, colorbar=colorbar, norm=norm, alpha=alpha, fig=fig, ax=ax) x = tsne.iloc[:, 0].values # data['{}-{}'.format(t, d1)][idx]",
"# # # x = tsne.iloc[idx2, 0] # y = tsne.iloc[idx2, 1] #",
"used to render the figure \"\"\" if ax is None: fig, ax =",
"'pca_expr_{}_t{}_vs_t{}.pdf'.format(name, 1, 2) fig, ax = base_pca_expr_plot(data, expr, dim=dim, cmap=cmap, marker=marker, s=s, alpha=alpha,",
"each cluster separately to highlight samples # # Parameters # ---------- # tsne",
"'b', cache=cache) create_pca_plot(pca_b, c_b, 'b', dir='b') create_cluster_plot(tsne_b, c_b, 'b', dir='b') create_cluster_grid(tsne_b, c_b, 'b',",
"e.mean()) / e.std() # limit to 3 std for z-scores #e[e < -3]",
"prefix = '' # # ax.set_title('{}{} ({:,})'.format(prefix, cluster, len(idx1)), color=color) # # #",
"version (%d) is an newer version that is not supported by this function.'",
"k=5): c1 = centroids(tsne1, clusters) c2 = centroids(tsne2, clusters) a1 = kneighbors_graph(c1, k,",
"- 1].values # data['{}-{}'.format(t, d1)][idx] y = data.iloc[idx, dim[1] - 1].values # data['{}-{}'.format(t,",
"cluster over the top of the background # # sid = 0 #",
"dir='a') create_cluster_plot(tsne_a, c_a, 'a', dir='a') create_cluster_grid(tsne_a, c_a, 'a', dir='a') create_merge_cluster_info(d_a, c_a, 'a', sample_names=samples,",
"\"\"\" Create a tsne plot without the formatting \"\"\" if ax is None:",
"\"\"\" Scale each library to its median size Parameters ---------- data : Pandas",
"norm=norm) return fig, ax def pca_expr_plot(data, expr, name, dim=[1, 2], cmap=None, marker='o', s=MARKER_SIZE,",
"# #g = data[:, :, 1] # #b = data[:, :, 2] #",
"ax=None, norm=None): # plt.cm.plasma): \"\"\" Base function for creating an expression plot for",
"> 2: raise ValueError( 'Matrix HDF5 file format version (%d) is an newer",
"of data. Parameters ---------- data : Pandas dataframe features x dimensions, e.g. rows",
"= color.mean() # # #print(x[i], y[i], mean) # # #if mean > 0.5:",
"data[:, :, 2] # #a = im_data[:, :, 3] # # # Non",
"isinstance(g, np.ndarray): idx = np.where(np.isin(ids, g))[0] if idx.size < 1: # if id",
"an older version that is not supported by this function.' % version) feature_ids",
"= tsne.iloc[idx_bin, :] expr_plot(tsne_bin, exp_bin, cmap=cmap, s=s, colorbar=colorbar, norm=norm, alpha=alpha, linewidth=linewidth, edgecolors=edgecolors, ax=ax)",
"'{}/{}_{}.{}'.format(dir, method, name, format) print(out) return cluster_plot(d, clusters, dim1=dim1, dim2=dim2, markers=markers, colors=colors, s=s,",
"exp[idx] # if (e.min() == 0): #print('Data does not appear to be z-scored.",
"dim1].values, d.iloc[:, dim2].values, clusters, colors=colors, edgecolors=edgecolors, linewidth=linewidth, markers=markers, alpha=alpha, s=s, ax=ax, cluster_order=cluster_order, sort=sort)",
"tsne dimensions exp : numpy array expression values for each data point so",
"sort=True, cluster_order=None, fig=None, ax=None, out=None): fig, ax = base_cluster_plot(tsne, clusters, markers=markers, colors=colors, dim1=dim1,",
"isinstance(colors, list): # color = colors[i] # else: # color = 'black' #",
"== bi)[0] idx_other = np.where(binnumber != bi)[0] tsne_other = tsne.iloc[idx_other, :] fig, ax",
"e = exp[idx] # if (e.min() == 0): #print('Data does not appear to",
"= x[idx] #y1 = y[idx] # avg1 = np.zeros(x.size) #avg[idx] #avg1[idx] = 1",
"i in colors: color = colors[i] # l] else: color = 'black' ax.scatter(x,",
"pad=0) # # return fig, ax def create_expr_plot(tsne, exp, dim=[1, 2], cmap=None, marker='o',",
"ax=ax, edgecolors='none', # bgedgecolor, linewidth=linewidth, s=s) # Plot cluster over the top of",
"def create_cluster_plots(pca, labels, name, marker='o', s=MARKER_SIZE): for i in range(0, pca.shape[1]): for j",
"cluster separately to highlight where the samples are Parameters ---------- tsne : Pandas",
"for node in f.walk_nodes('/matrix', 'Array'): # dsets[node.name] = node.read() print(dsets) matrix = sp_sparse.csc_matrix(",
"in indexes: ret.append((index, ids[index], gene_names[index])) else: # if id does not exist, try",
"or more required datasets.\") #GeneBCMatrix = collections.namedtuple('FeatureBCMatrix', ['feature_ids', 'feature_names', 'barcodes', 'matrix']) def get_matrix_from_h5_v2(filename,",
"yp[0]) ax.plot(xp, yp, 'k-') #ax.plot(points[hull.vertices[0], 0], points[hull.vertices[[0, -1]], 1]) #points = np.array([[x, y]",
"cols, pc)) separate_cluster(tsne, clusters, cluster, color=color, add_titles=add_titles, ax=ax) # idx1 = np.where(clusters['Cluster'] ==",
"does not exist in this file.\" % genome) except KeyError: raise Exception(\"File is",
"ALPHA = 0.9 BLUE_YELLOW_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list( 'blue_yellow', ['#162d50', '#ffdd55']) BLUE_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list( 'blue',",
"in data.index[0]: ids, genes = data.index.str.split(';').str else: genes = data.index ids = genes",
"new one is created. norm : Normalize, optional Specify how colors should be",
"genes = genes['Genes'].values if norm is None: norm = matplotlib.colors.Normalize(vmin=-3, vmax=3, clip=True) #cmap",
"f.create_carray(group, 'gene_names', obj=gbm.gene_names) f.create_carray(group, 'barcodes', obj=gbm.barcodes) f.create_carray(group, 'data', obj=gbm.matrix.data) f.create_carray(group, 'indices', obj=gbm.matrix.indices) f.create_carray(group,",
"background=BACKGROUND_SAMPLE_COLOR, bgedgecolor='#808080', show_background=True, add_titles=True, size=4, alpha=ALPHA, s=MARKER_SIZE, edgecolors='white', linewidth=EDGE_WIDTH, fig=None, ax=None): \"\"\" Plot",
": matplotlib figure If fig is a supplied argument, return the supplied figure,",
"top of the background x = tsne.iloc[idx1, 0] y = tsne.iloc[idx1, 1] #print('sep',",
"(r == g) & (r == b) & (g == b) black_areas =",
"clusters, cluster, color=color, add_titles=add_titles, ax=ax) # idx1 = np.where(clusters['Cluster'] == cluster)[0] # idx2",
"\"\"\" # Plot separate clusters colored by sample # \"\"\" # fig =",
"range(i + 1, n): ax = libplot.new_ax(fig, subplot=(rows, rows, si)) pca_plot_base(pca, clusters, pc1=(i",
"s=s, w=w, h=h, fig=fig, ax=ax) libplot.savefig(fig, out, pad=2) plt.close(fig) def set_tsne_ax_lim(tsne, ax): \"\"\"",
"clusters.shape[0])] # def network(tsne, clusters, name, k=5): # A = kneighbors_graph(tsne, k, mode='distance',",
"# elif isinstance(colors, list): # color = colors[i] # else: # color =",
"# fy = interp1d(points[hull.vertices, 1], points[hull.vertices, 0], kind='cubic') # # xt = np.linspace(x.min(),",
"pass if legend_params['show']: libcluster.format_legend(ax, cols=legend_params['cols'], markerscale=legend_params['markerscale']) libplot.invisible_axes(ax) tmp = 'tmp{}.png'.format(i) libplot.savefig(fig, tmp) plt.close(fig)",
"# # im_smooth = im_edges.filter(ImageFilter.SMOOTH) # # # paste outline onto clusters #",
"'tmp{}.png'.format(bin) libplot.savefig(fig, tmp, pad=0) plt.close(fig) im = imagelib.open(tmp) im_no_bg = imagelib.remove_background(im) im_edges =",
"linewidth=linewidth) #libcluster.format_axes(ax, title=t) return fig, ax def expr_plot(data, exp, dim=[1, 2], cmap=plt.cm.magma, marker='o',",
"a color bar. \"\"\" is_first = False if ax is None: fig, ax",
"ax = libplot.new_fig(w, w) x = tsne_other.iloc[:, 0] y = tsne_other.iloc[:, 1] libplot.scatter(x,",
"= libplot.newfig(w=9, h=7, subplot=211) df = pd.DataFrame({'Silhouette Score': x1, 'Cluster': clusters.iloc[:, 0].tolist( ),",
"= matplotlib.colors.LinearSegmentedColormap.from_list('bgy', ['#003366', '#40bf80', '#ffff33']) BGY_ORIG_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list( 'bgy', ['#002255', '#003380', '#2ca05a', '#ffd42a',",
"# color = cmap(int(en * cmap.N)) # color = np.array(color) # # c1",
"libplot.scatter(x, y, c=[background], ax=ax, edgecolors='none', # bgedgecolor, linewidth=linewidth, s=s) #fig, ax = libplot.new_fig()",
"on Wed Jun 6 16:51:15 2018 @author: antony \"\"\" import matplotlib # matplotlib.use('agg')",
"ret.append((index, ids[index], gene_names[index])) else: # if id does not exist, try the gene",
"+= 1 print(np.unique(d.index.values)) print(np.unique(sc)) df = pd.DataFrame(sc, index=d.index, columns=['Cluster']) return df def create_cluster_samples(tsne_umi_log2,",
"colorbar=colorbar, norm=norm, linewidth=linewidth, edgecolors=edgecolors) if out is not None: libplot.savefig(fig, out, pad=0) return",
"cache=cache) create_pca_plot(pca_a, c_a, 'a', dir='a') create_cluster_plot(tsne_a, c_a, 'a', dir='a') create_cluster_grid(tsne_a, c_a, 'a', dir='a')",
"Create a cluster matrix based on by labelling cells by sample/batch. \"\"\" sc",
"== 0: return pd.DataFrame(RobustScaler().fit_transform(d), index=d.index, columns=d.columns) else: return pd.DataFrame(RobustScaler().fit_transform(d.T).T, index=d.index, columns=d.columns) def umi_norm_log2_scale(data,",
"s=libplot.MARKER_SIZE, w=8, h=8, colors=None, legend=True, sort=True, show_axes=False, ax=None, cluster_order=None, format='png', dir='.', out=None): if",
"i, cluster_order[i]) cluster = cluster_order[i] if isinstance(colors, dict): color = colors[cluster] elif isinstance(colors,",
"out = '{}_expr.pdf'.format(method) fig, ax = expr_plot(tsne, exp, dim=dim, cmap=cmap, marker=marker, s=s, alpha=alpha,",
"= pca_plot(pca, clusters, pc1=pc1, pc2=pc2, labels=labels, marker=marker, legend=legend, s=s, w=w, h=h, fig=fig, ax=ax)",
"# libplot.scatter(x, y, c=colors[sid], ax=ax) # # sid += 1 # # ax.set_title('C{}",
"> 0) d = im_data[np.where(black_areas)] d[:, 0:3] = [64, 64, 64] im_data[np.where(black_areas)] =",
"avg, cmap=cmap, w=w, h=h, colorbar=colorbar, norm=norm, alpha=alpha, fig=fig, ax=ax) x = tsne.iloc[:, 0].values",
"find all points within 1 sd of centroid idx = np.where(abs(z) < sdmax)[0]",
"fig, ax = libplot.new_fig(w, w) x = tsne_other.iloc[:, 0] y = tsne_other.iloc[:, 1]",
"['#002255', '#2ca05a', '#ffd42a']) # BGY_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list('bgy', ['#002255', '#003380', '#2ca05a', '#ffd42a', '#ffdd55']) #",
"the plot \"\"\" if type(genes) is pd.core.frame.DataFrame: genes = genes['Genes'].values ids, gene_names =",
"= sp_sparse.csc_matrix( (dsets['data'], dsets['indices'], dsets['indptr']), shape=dsets['shape']) return GeneBCMatrix(decode(dsets['genes']), decode(dsets['gene_names']), decode(dsets['barcodes']), matrix) except tables.NoSuchNodeError:",
"presentation tsne plot \"\"\" if out is None: out = '{}_expr.pdf'.format(method) fig, ax",
"color = colors[i] else: color = 'black' else: color = 'black' ax =",
"'TSNE-1', 'TSNE-2' etc clusters : DataFrame Clusters in colors : list, color Colors",
"3] # # # Non transparent areas are edges # #black_areas = (a",
"> max)] = max return pd.DataFrame(sd, index=d.index, columns=d.columns) def min_max_scale(d, min=0, max=1, axis=1):",
"i in range(0, pca.shape[0]): print(pca.shape, pca.iloc[i, pc1 - 1], pca.iloc[i, pc2 - 1])",
"/ reads_per_bc scaled = data.multiply(scaling_factors) # , axis=1) return scaled def umi_log2(d): if",
"ret def knn_method_overlaps(tsne1, tsne2, clusters, name, k=5): c1 = centroids(tsne1, clusters) c2 =",
"bi)[0] idx_other = np.where(binnumber != bi)[0] tsne_other = tsne.iloc[idx_other, :] fig, ax =",
"sid += 1 # # ax.set_title('C{} ({:,})'.format(c, len(idx1)), color=colors[i]) # libplot.invisible_axes(ax) # #",
"'TSNE-2' etc cluster : int Clusters in colors : list, color Colors of",
"ids[index], gene_names[index])) return ret def get_gene_data(data, g, ids=None, gene_names=None): if ids is None:",
"out = '{}/{}_expr_{}_{}.png'.format(dir, method, gene, gene_id) else: out = '{}/{}_expr_{}.png'.format(dir, method, gene) print(out)",
"# # mean = color.mean() # # #print(x[i], y[i], mean) # # #if",
"clip=True) #cmap = plt.cm.plasma ids, gene_names = get_gene_names(data) gene_ids = get_gene_ids(data, genes, ids=ids,",
"ax.set_ylim([-1, 1]) ax.set_title('tsne-10x') #libplot.savefig(fig, 'RK10001_10003_clust-phen_silhouette.pdf') ax = fig.add_subplot(212) # libplot.newfig(w=9) df2 = pd.DataFrame({'Silhouette",
"add_titles=False, show_background=False) ax.set_xlim(xlim) ax.set_ylim(ylim) if not show_axes: libplot.invisible_axes(ax) legend_params = dict(LEGEND_PARAMS) if isinstance(legend,",
"# prefix = 'C' # else: # prefix = '' # # ax.set_title('{}{}",
"cluster)[0] # idx2 = np.where(clusters['Cluster'] != cluster)[0] # # # Plot background points",
"idx = np.where(ids == g)[0] if idx.size > 0: # if id exists,",
"!= c)[0] # # # Plot background points # # ax = libplot.new_ax(fig,",
"= s c += 1 print(np.unique(d.index.values)) print(np.unique(sc)) df = pd.DataFrame(sc, index=d.index, columns=['Cluster']) return",
"get all of the transcripts. Parameters ---------- data : DataFrame data table containing",
"out=None): if out is None: # libtsne.get_tsne_plot_name(name)) out = '{}/{}_{}.{}'.format(dir, method, name, format)",
"# Creates a basic t-sne expression plot. # # Parameters # ---------- #",
"of the background # # sid = 0 # # for sample in",
"ax is None: fig, ax = libplot.new_fig(size, size) #print('Label {}'.format(l)) idx1 = np.where(clusters['Cluster']",
"d1=1, # d2=2, # x1=None, # x2=None, # cmap=BLUE_YELLOW_CMAP, # marker='o', # s=MARKER_SIZE,",
"h=8) # list(range(0, c.shape[0])) node_color = libcluster.colors()[0:c.shape[0]] cmap = libcluster.colormap() labels = {}",
"points[hull.vertices, 1], kind='cubic') # fy = interp1d(points[hull.vertices, 1], points[hull.vertices, 0], kind='cubic') # #",
"matplotlib.pyplot as plt import collections import numpy as np import scipy.sparse as sp_sparse",
"# w = size * rows # # fig = libplot.new_base_fig(w=w, h=w) #",
"subplot=(rows, cols, pc)) separate_cluster(tsne, clusters, cluster, color=color, add_titles=add_titles, ax=ax) # idx1 = np.where(clusters['Cluster']",
"'barcodes', obj=gbm.barcodes) f.create_carray(group, 'data', obj=gbm.matrix.data) f.create_carray(group, 'indices', obj=gbm.matrix.indices) f.create_carray(group, 'indptr', obj=gbm.matrix.indptr) f.create_carray(group, 'shape',",
"+ 1) expr_plot(tsne, exp, ax=ax, cmap=cmap, colorbar=False) # if i == 0: #",
"= size * rows return w, h, rows, cols def get_gene_names(data): if ';'",
"id = '-{}'.format(sid + 1) # idx1 = np.where((clusters['Cluster'] == c) & clusters.index.str.contains(id))[0]",
"metric='euclidean') x2 = silhouette_samples( tsne_umi_log2, clusters.iloc[:, 0].tolist(), metric='euclidean') fig, ax = libplot.newfig(w=9, h=7,",
"data.index[0]: ids, genes = data.index.str.split(';').str else: genes = data.index ids = genes return",
"if show_background: x = tsne.iloc[idx2, 0] y = tsne.iloc[idx2, 1] libplot.scatter(x, y, c=[background],",
"i + 1)) # # x = tsne.iloc[idx2, 0] # y = tsne.iloc[idx2,",
": array List of gene names Returns ------- fig : Matplotlib figure A",
"= centroid[1] return ret def knn_method_overlaps(tsne1, tsne2, clusters, name, k=5): c1 = centroids(tsne1,",
"legend. \"\"\" if ax is None: fig, ax = libplot.new_fig(w=w, h=h) libcluster.scatter_clusters(d.iloc[:, dim1].values,",
"- e.mean()) / e.std() # limit to 3 std for z-scores #e[e <",
"to render the plot, otherwise a new one is created. ax : matplotlib",
"are edges # #black_areas = (a > 0) #(r < 255) | (g",
"'Array'): dsets[node.name] = node.read() # for node in f.walk_nodes('/matrix', 'Array'): # dsets[node.name] =",
"bool Whether to add titles to plots plot_order: list, optional List of cluster",
"get_gene_data(data, g, ids=None, gene_names=None): if ids is None: ids, gene_names = get_gene_names(data) if",
"# idx1 = np.where(clusters['Cluster'] == cluster)[0] # idx2 = np.where(clusters['Cluster'] != cluster)[0] #",
"x in f['matrix']['features']['name']] barcodes = list(f['matrix']['barcodes'][:]) matrix = sp_sparse.csc_matrix( (f['matrix']['data'], f['matrix']['indices'], f['matrix']['indptr']), shape=f['matrix']['shape'])",
"PIL import Image, ImageFilter from scipy.stats import binned_statistic import imagelib TNSE_AX_Q = 0.999",
"c_a, legend=False, w=w, h=h) libplot.savefig(fig, 'a/a_tsne_clusters_med.pdf') # b mkdir('b') b_barcodes = pd.read_csv('../b_barcodes.tsv', header=0,",
"in f['matrix']['features']['id']] feature_names = [x.decode('ascii', 'ignore') for x in f['matrix']['features']['name']] barcodes = list(f['matrix']['barcodes'][:])",
"= genes['Genes'].values ids, gene_names = get_gene_names(data) gene_ids = get_gene_ids(data, genes, ids=ids, gene_names=gene_names) w,",
"cmap=None, marker='o', s=MARKER_SIZE, alpha=EXP_ALPHA, fig=None, ax=None, norm=None): # plt.cm.plasma): out = 'pca_expr_{}_t{}_vs_t{}.pdf'.format(name, 1,",
"labels=False, legend=True, s=MARKER_SIZE, w=8, h=8, fig=None, ax=None, dir='.', format='png'): out = '{}/pca_{}_pc{}_vs_pc{}.{}'.format(dir, name,",
"s=MARKER_SIZE, w=8, h=8, fig=None, ax=None, dir='.', format='png'): out = '{}/pca_{}_pc{}_vs_pc{}.{}'.format(dir, name, pc1, pc2,",
"len(indices) label = 'C{} ({:,})'.format(l, n) df2 = pca.iloc[indices, ] x = df2.iloc[:,",
"color = 'black' fig, ax = separate_cluster(d, clusters, cluster, color=color, size=w, s=s, linewidth=linewidth,",
": str directory to create. \"\"\" try: os.makedirs(path) except: pass def split_a_b(counts, samples,",
"counts.iloc[:, idx] d_b = libcluster.remove_empty_rows(d_b) if isinstance(d_a, SparseDataFrame): d_b = umi_norm_log2(d_b) else: d_b",
"2], cmap=plt.cm.magma, marker='o', s=MARKER_SIZE, alpha=1, edgecolors=EDGE_COLOR, linewidth=EDGE_WIDTH, w=libplot.DEFAULT_WIDTH, h=libplot.DEFAULT_HEIGHT, show_axes=False, fig=None, ax=None, norm=None,",
"marker=marker, edgecolors=edgecolors, linewidth=linewidth, alpha=alpha, cmap=cmap, norm=norm, w=w, h=h, ax=ax) # if colorbar or",
"pd.DataFrame(sd, index=d.index, columns=d.columns) def min_max_scale(d, min=0, max=1, axis=1): #m = d.min(axis=1) #std =",
"d # # im2 = Image.fromarray(im_data) # # # Edge detect on what",
"ConvexHull(points) #ax.plot(points[hull.vertices,0], points[hull.vertices,1]) #zi = griddata((x, y), avg1, (xi, yi)) #ax.contour(xi, yi, z,",
"clusters, cluster, color=color, add_titles=add_titles, size=size) out = '{}_sep_clust_{}_c{}.{}'.format(type, name, cluster, format) print('Creating', out,",
"# # r = im_data[:, :, 0] # g = im_data[:, :, 1]",
"ax.set_title('C{} ({:,})'.format(c, len(idx1)), color=colors[i]) # libplot.invisible_axes(ax) # # #set_tsne_ax_lim(tsne, ax) # # return",
"ret = [] for g in genes: indexes = np.where(ids == g)[0] if",
"'#2ca05a', '#ffd42a', '#ffdd55']) # BGY_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list('bgy', ['#003366', '#339966', '#ffff66', '#ffff00') # BGY_CMAP",
"gene_names = get_gene_names(data) gene_ids = get_gene_ids(data, genes, ids=ids, gene_names=gene_names) for i in range(0,",
"== 0): #print('Data does not appear to be z-scored. Transforming now...') # zscore",
"s in sample_names: id = '-{}'.format(c) print(id) print(np.where(d.index.str.contains(id))[0]) sc[np.where(d.index.str.contains(id))[0]] = s c +=",
"in cluster_order: i = c - 1 cluster = ids[i] # look up",
"# linewidth=linewidth) #libcluster.format_axes(ax, title=t) return fig, ax def expr_plot(data, exp, dim=[1, 2], cmap=plt.cm.magma,",
"shape(n_cells, n_genes) \"\"\" df = pd.DataFrame(gbm.matrix.todense()) df.index = gbm.gene_names df.columns = gbm.barcodes return",
"rows = libplot.grid_size(n) w = 4 * rows fig = libplot.new_base_fig(w=w, h=w) si",
"cluster_order: i = c - 1 cluster = ids[i] # look up index",
"linewidth=EDGE_WIDTH, edgecolors='none', colorbar=True, method='tsne', format='png'): \"\"\" Plot multiple genes on a grid. Parameters",
"def genes_expr_outline(data, tsne, genes, prefix='', index=None, dir='GeneExp', cmap=BGY_CMAP, norm=None, w=6, s=30, alpha=1, linewidth=EDGE_WIDTH,",
"libplot.boxplot(df2, 'Cluster', 'Silhouette Score', colors=libcluster.colors(), ax=ax) ax.set_ylim([-1, 1]) ax.set_title('tsne-ah') libplot.savefig(fig, '{}_silhouette.pdf'.format(name)) def node_color_from_cluster(clusters):",
"# for sample in samples: # id = '-{}'.format(sid + 1) # idx1",
"if edges desired im1.paste(im2, (0, 0), im2) im1.save(out, 'png') def genes_expr_outline(data, tsne, genes,",
"# color = np.array(color) # # c1 = color.copy() # c1[-1] = 0.5",
"['#003366', '#004d99', '#40bf80', '#ffe066', '#ffd633']) GRAY_PURPLE_YELLOW_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list( 'grey_purple_yellow', ['#e6e6e6', '#3333ff', '#ff33ff', '#ffe066'])",
"np.array(list(range(0, len(ids)))) + 1 n = cluster_order.size if cols == -1: cols =",
"#edges1 = feature.canny(rgb2gray(im_data)) # # #print(edges1.shape) # # #skimage.io.imsave('tmp_canny_{}.png'.format(bin), edges1) # # im2",
"i].toarray())) return ret def df(gbm): \"\"\" Converts a GeneBCMatrix to a pandas dataframe",
"pca.iloc[i, pc2 - 1], pca.index[i]) return fig, ax def pca_plot(pca, clusters, pc1=1, pc2=2,",
": bool Whether to add titles to plots plot_order: list, optional List of",
"tables.open_file(filename, 'r') as f: try: dsets = {} print(f.list_nodes('/')) for node in f.walk_nodes('/'",
"(%d) is an newer version that is not supported by this function.' %",
"w: int, optional width of new ax. h: int, optional height of new",
"return GeneBCMatrix(feature_ids, feature_names, decode(barcodes), matrix) def save_matrix_to_h5(gbm, filename, genome): flt = tables.Filters(complevel=1) with",
"edges on top of original image to highlight cluster # im_base.paste(im2, (0, 0),",
"np.linspace(x.min(), x.max(), nx) yi = np.linspace(y.min(), y.max(), ny) x = x[idx] y =",
"in range(0, clusters.shape[0])] # def network(tsne, clusters, name, k=5): # A = kneighbors_graph(tsne,",
"'markerscale': 2} CLUSTER_101_COLOR = (0.3, 0.3, 0.3) np.random.seed(0) GeneBCMatrix = collections.namedtuple( 'GeneBCMatrix', ['gene_ids',",
"# Sort by expression level so that extreme values always appear on top",
"linewidth=linewidth, edgecolors=edgecolors) if gene_id != gene: out = '{}/{}_expr_{}_{}.{}'.format(dir, method, gene, gene_id, format)",
"on top idx = np.argsort(exp) #np.argsort(abs(exp)) # np.argsort(exp) x = data.iloc[idx, dim[0] -",
"alpha=EXP_ALPHA, fig=None, ax=None, norm=None): # plt.cm.plasma): fig, ax = base_expr_plot(data, exp, t='PC', dim=dim,",
"max=1, axis=1): #m = d.min(axis=1) #std = (d - m) / (d.max(axis=1) -",
"d.mean() print(m, sd) z = (d - m) / sd # find all",
"from scipy.stats import binned_statistic import imagelib TNSE_AX_Q = 0.999 MARKER_SIZE = 10 SUBPLOT_SIZE",
"tsne tsne data. Columns should be labeled 'TSNE-1', 'TSNE-2' etc cluster : int",
"if id does not exist, try the gene names idx = np.where(np.isin(gene_names, g))[0]",
"size * cols rows = int(l / cols) + 2 if l %",
"== g) & (r == b) & (g == b) black_areas = (a",
"= centroids(tsne, clusters) A = kneighbors_graph(c, 5, mode='distance', metric='euclidean').toarray() G = nx.from_numpy_matrix(A) pos",
"as data has rows. d1 : int, optional First dimension being plotted (usually",
"# h=libplot.DEFAULT_HEIGHT, # colorbar=True): #plt.cm.plasma): # \"\"\" # Creates a basic t-sne expression",
"'cols': 4, 'markerscale': 2} CLUSTER_101_COLOR = (0.3, 0.3, 0.3) np.random.seed(0) GeneBCMatrix = collections.namedtuple(",
"# '#f2f2f2' #(0.98, 0.98, 0.98) #(0.8, 0.8, 0.8) #(0.85, 0.85, 0.85 BACKGROUND_SAMPLE_COLOR =",
"= cmap(int(en * cmap.N)) # color = np.array(color) # # c1 = color.copy()",
"counts \"\"\" # each column is a cell reads_per_bc = data.sum(axis=0) # int(np.round(np.median(reads_per_bc)))",
"= np.where(counts.columns.isin(a_barcodes['Barcode'].values))[0] d_a = counts.iloc[:, idx] d_a = libcluster.remove_empty_rows(d_a) if isinstance(d_a, SparseDataFrame): d_a",
"alpha=ALPHA, # libplot.ALPHA, show_axes=True, legend=True, sort=True, cluster_order=None, fig=None, ax=None): \"\"\" Create a tsne",
"# def tsne_cluster_sample_grid(tsne, clusters, samples, colors=None, size=SUBPLOT_SIZE): # \"\"\" # Plot each cluster",
"return scale(d, clip=clip) def read_clusters(file): print('Reading clusters from {}...'.format(file)) return pd.read_csv(file, sep='\\t', header=0,",
"dir='GeneExp', cmap=BGY_CMAP, norm=None, w=6, s=30, alpha=1, linewidth=EDGE_WIDTH, edgecolors='none', colorbar=True, method='tsne', bins=10, background=BACKGROUND_SAMPLE_COLOR): \"\"\"",
"= '{}/{}_expr_{}.{}'.format(dir, method, gene, format) libplot.savefig(fig, 'tmp.png', pad=0) libplot.savefig(fig, out, pad=0) plt.close(fig) im1",
"umi_norm_log2(data): d = umi_norm(data) print(type(d)) return umi_log2(d) def scale(d, clip=None, min=None, max=None, axis=1):",
"gene_id, ids=ids, gene_names=gene_names) ax = libplot.new_ax(fig, rows, cols, i + 1) expr_plot(tsne, exp,",
"was not found in list of gene names.\" % gene_name) return gbm.matrix[gene_indices[0], :].toarray().squeeze()",
"colors=None, legend=True, sort=True, show_axes=False, ax=None, cluster_order=None, format='png', dir='.', out=None): if out is None:",
"3 ax.scatter(x, y, c=e, s=s, marker=marker, alpha=alpha, cmap=cmap, norm=norm, edgecolors='none', # edgecolors, linewidth=linewidth)",
"libcluster.remove_empty_rows(counts) # ['AICDA', 'CD83', 'CXCR4', 'MKI67', 'MYC', 'PCNA', 'PRDM1'] genes = pd.read_csv('../../../../expression_genes.txt', header=0)",
"dataframe Cells x tsne tsne data. Columns should be labeled 'TSNE-1', 'TSNE-2' etc",
"s=libplot.MARKER_SIZE, c='red', label=None, fig=None, ax=None): fig, ax = base_tsne_plot(tsne, marker=marker, c=c, s=s, label=label,",
"s=MARKER_SIZE): rows = libplot.grid_size(n) w = 4 * rows fig = libplot.new_base_fig(w=w, h=w)",
"d.std() m = d.mean() print(m, sd) z = (d - m) / sd",
"+ 1), marker=marker, s=s) def pca_base_plots(pca, clusters, n=10, marker='o', s=MARKER_SIZE): rows = libplot.grid_size(n)",
"libplot.invisible_axes(ax) legend_params = dict(LEGEND_PARAMS) if isinstance(legend, bool): legend_params['show'] = legend elif isinstance(legend, dict):",
"libcluster.format_simple_axes(ax, title=\"PC\") if legend: libcluster.format_legend(ax, cols=6, markerscale=2) return fig, ax def create_pca_plot(pca, clusters,",
"- 1] #colors[i] #np.where(clusters['Cluster'] == cluster)[0]] color = colors[i] else: color = 'black'",
"# idx1 = np.where((clusters['Cluster'] == c) & clusters.index.str.contains(id))[0] # # x = tsne.iloc[idx1,",
"None: # libplot.savefig(fig, out, pad=0) # # return fig, ax def create_expr_plot(tsne, exp,",
"scale sparse') sd = StandardScaler(with_mean=False).fit_transform(d.T.matrix) return SparseDataFrame(sd.T, index=d.index, columns=d.columns) else: # StandardScaler().fit_transform(d.T) sd",
"np.where(clusters['Cluster'] != cluster)[0] # # # Plot background points # # # #",
"= size * rows # # fig = libplot.new_base_fig(w=w, h=w) # # if",
"sp_sparse.csc_matrix( (f['matrix']['data'], f['matrix']['indices'], f['matrix']['indptr']), shape=f['matrix']['shape']) return GeneBCMatrix(feature_ids, feature_names, decode(barcodes), matrix) def save_matrix_to_h5(gbm, filename,",
"matplotlib.colors.Normalize(vmin=-3, vmax=3, clip=True) #cmap = plt.cm.plasma ids, gene_names = get_gene_names(data) print(ids, gene_names, genes)",
"ids[i] # look up index for color purposes #i = np.where(ids == cluster)[0][0]",
"tsne.iloc[idx1, 0] y = tsne.iloc[idx1, 1] #print('sep', cluster, color) color = color #",
"= np.where(binnumber != bi)[0] tsne_other = tsne.iloc[idx_other, :] fig, ax = libplot.new_fig(w, w)",
"names.\" % gene_name) return gbm.matrix[gene_indices[0], :].toarray().squeeze() def gbm_to_df(gbm): return pd.DataFrame(gbm.matrix.todense(), index=gbm.gene_names, columns=gbm.barcodes) def",
"> 200) & (b < 255) & (b > 200) # # #",
"fig def pca_plot_base(pca, clusters, pc1=1, pc2=2, marker='o', labels=False, s=MARKER_SIZE, w=8, h=8, fig=None, ax=None):",
"# # #A = A[0:500, 0:500] # # G=nx.from_numpy_matrix(A) # pos=nx.spring_layout(G) #, k=2)",
"genes_expr_outline(data, tsne, genes, prefix='', index=None, dir='GeneExp', cmap=BGY_CMAP, norm=None, w=6, s=30, alpha=1, linewidth=EDGE_WIDTH, edgecolors='none',",
"64, 64] im_data[np.where(black_areas)] = d im2 = Image.fromarray(im_data) im2.save('edges.png', 'png') # overlay edges",
"in range(len(gbm.barcodes)): ret.append(np.sum(gbm.matrix[:, i].toarray())) return ret def df(gbm): \"\"\" Converts a GeneBCMatrix to",
"sid = 0 # # for sample in samples: # id = '-{}'.format(sid",
"np.array(g) if isinstance(g, np.ndarray): idx = np.where(np.isin(ids, g))[0] if idx.size < 1: #",
"if isinstance(colors, dict): # color = colors[cluster] # elif isinstance(colors, list): # color",
"axis and attach to figure before returning. \"\"\" if ax is None: fig,",
"def centroid_network(tsne, clusters, name): c = centroids(tsne, clusters) A = kneighbors_graph(c, 5, mode='distance',",
"= 1 for i in range(0, n): for j in range(i + 1,",
"mode='distance', metric='euclidean').toarray() overlaps = [] for i in range(0, c1.shape[0]): ids1 = np.where(a1[i,",
"= np.median(reads_per_bc) scaling_factors = median_reads_per_bc / reads_per_bc scaled = data.multiply(scaling_factors) # , axis=1)",
"tsne data. Columns should be labeled 'TSNE-1', 'TSNE-2' etc cluster : int Clusters",
"gene_names = get_gene_names(data) ret = [] for g in genes: indexes = np.where(ids",
"def gene_expr(data, tsne, gene, fig=None, ax=None, cmap=plt.cm.plasma, out=None): \"\"\" Plot multiple genes on",
"pc)) separate_cluster(tsne, clusters, cluster, color=color, add_titles=add_titles, ax=ax) # idx1 = np.where(clusters['Cluster'] == cluster)[0]",
"normalized Returns ------- fig : matplotlib figure If fig is a supplied argument,",
"format) fig, ax = pca_plot(pca, clusters, pc1=pc1, pc2=pc2, labels=labels, marker=marker, legend=legend, s=s, w=w,",
"avg[idx]).sum() / avg[idx].sum(), (y * avg[idx]).sum() / avg[idx].sum()] d = np.array([distance.euclidean(centroid, (a, b))",
"SparseDataFrame): print('UMI norm log2 scale sparse') sd = StandardScaler(with_mean=False).fit_transform(d.T.matrix) return SparseDataFrame(sd.T, index=d.index, columns=d.columns)",
"imagelib.paste(im_base, im, inplace=True) # # find gray areas and mask # im_data =",
"== 0: # libcluster.format_axes(ax) # else: # libplot.invisible_axes(ax) ax.set_title('{} ({})'.format(gene_ids[i][2], gene_ids[i][1])) libplot.add_colorbar(fig, cmap)",
"figure used to make the plot ax : Matplotlib axes Axes used to",
"x = x[idx] y = y[idx] points = np.array([[p1, p2] for p1, p2",
"ny = 500 xi = np.linspace(x.min(), x.max(), nx) yi = np.linspace(y.min(), y.max(), ny)",
"out) libplot.savefig(fig, 'tmp.png') plt.close(fig) def cluster_grid(tsne, clusters, colors=None, cols=-1, size=SUBPLOT_SIZE, add_titles=True, cluster_order=None): \"\"\"",
"genes return ids.values, genes.values def get_gene_ids(data, genes, ids=None, gene_names=None): \"\"\" For a given",
"ax=None, dir='.', format='png'): out = '{}/pca_{}_pc{}_vs_pc{}.{}'.format(dir, name, pc1, pc2, format) fig, ax =",
"h=8, colors=None, legend=True, sort=True, show_axes=False, ax=None, cluster_order=None, format='png', dir='.', out=None): if out is",
"gene list, get all of the transcripts. Parameters ---------- data : DataFrame data",
"ax def pca_expr_plot(data, expr, name, dim=[1, 2], cmap=None, marker='o', s=MARKER_SIZE, alpha=EXP_ALPHA, fig=None, ax=None,",
"['#e6e6e6', '#3333ff', '#ff33ff', '#ffe066']) GYBLGRYL_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list( 'grey_blue_green_yellow', ['#e6e6e6', '#0055d4', '#00aa44', '#ffe066']) OR_RED_CMAP",
"edgecolors='none', # bgedgecolor, linewidth=linewidth, s=s) #fig, ax = libplot.new_fig() #expr_plot(tsne, exp, ax=ax) #libplot.add_colorbar(fig,",
"measure cluster worth x1 = silhouette_samples( tsne, clusters.iloc[:, 0].tolist(), metric='euclidean') x2 = silhouette_samples(",
"i in range(0, len(ids)): l = ids[i] #print('Label {}'.format(l)) indices = np.where(clusters['Cluster'] ==",
"import numpy as np import scipy.sparse as sp_sparse import tables import pandas as",
"libplot.savefig(fig, out) plt.close(fig) return fig, ax def expr_grid_size(x, size=SUBPLOT_SIZE): \"\"\" Auto size grid",
"Plot separate clusters colored by sample # \"\"\" # fig = tsne_cluster_sample_grid(tsne, clusters,",
"elements as data has rows. d1 : int, optional First dimension being plotted",
"marker='o', s=MARKER_SIZE, alpha=EXP_ALPHA, fig=None, ax=None, w=libplot.DEFAULT_WIDTH, h=libplot.DEFAULT_HEIGHT, edgecolors=EDGE_COLOR, linewidth=EDGE_WIDTH, norm=None, method='tsne', show_axes=False, colorbar=True,",
"data # .tolist() return cluster_map, labels def umi_tpm(data): # each column is a",
"def tsne_cluster_sample_grid(tsne, clusters, samples, colors=None, size=SUBPLOT_SIZE): # \"\"\" # Plot each cluster separately",
"gene_names=None): if ids is None: ids, gene_names = get_gene_names(data) if isinstance(g, list): g",
"levels=1) def gene_expr(data, tsne, gene, fig=None, ax=None, cmap=plt.cm.plasma, out=None): \"\"\" Plot multiple genes",
"fig.add_subplot(212) # libplot.newfig(w=9) df2 = pd.DataFrame({'Silhouette Score': x2, 'Cluster': clusters.iloc[:, 0].tolist( ), 'Label':",
"# BGY_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list('bgy', ['#0066ff', '#37c871', '#ffd42a']) # BGY_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list('bgy', ['#003380', '#5fd38d',",
"'k-') #ax.plot(points[hull.vertices[0], 0], points[hull.vertices[[0, -1]], 1]) #points = np.array([[x, y] for x, y",
"1) d2 : int, optional Second dimension being plotted (usually 2) fig :",
"imagelib.save(im_base, out) def avg_expr(data, tsne, genes, cid, clusters, prefix='', index=None, dir='GeneExp', cmap=OR_RED_CMAP, #",
"if idx.size < 1: # if id does not exist, try the gene",
"matplotlib.colors.LinearSegmentedColormap.from_list('bgy', ['#0066ff', '#37c871', '#ffd42a']) # BGY_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list('bgy', ['#003380', '#5fd38d', '#ffd42a']) EXP_NORM =",
"gene_name) \"\"\" if ids is None: ids, gene_names = get_gene_names(data) ret = []",
"dir='a') create_merge_cluster_info(d_a, c_a, 'a', sample_names=samples, dir='a') create_cluster_samples(tsne_a, c_a, samples, 'a_sample', dir='a') genes_expr(d_a, tsne_a,",
"1], kind='cubic') # fy = interp1d(points[hull.vertices, 1], points[hull.vertices, 0], kind='cubic') # # xt",
"return fig def genes_expr(data, tsne, genes, prefix='', dim=[1, 2], index=None, dir='GeneExp', cmap=BGY_CMAP, norm=None,",
"cluster, colors) if isinstance(colors, dict): color = colors.get(cluster, 'black') elif isinstance(colors, list): #i",
"#print(edges1.shape) # # #skimage.io.imsave('tmp_canny_{}.png'.format(bin), edges1) # # im2 = Image.fromarray(im_data) # # im_no_gray,",
"alpha=EXP_ALPHA, fig=None, ax=None, w=libplot.DEFAULT_WIDTH, h=libplot.DEFAULT_HEIGHT, edgecolors=EDGE_COLOR, linewidth=EDGE_WIDTH, norm=None, method='tsne', show_axes=False, colorbar=True, out=None): #",
"= '{}_sep_clust_{}_c{}.{}'.format(type, name, cluster, format) print('Creating', out, '...') libplot.savefig(fig, out) libplot.savefig(fig, 'tmp.png') plt.close(fig)",
"linewidth=linewidth, s=s) if add_titles: if isinstance(cluster, int): prefix = 'C' else: prefix =",
"# # # Plot cluster over the top of the background # #",
":, 1] #b = data[:, :, 2] a = im_data[:, :, 3] #",
"Returns ------- object : Pandas DataFrame shape(n_cells, n_genes) \"\"\" df = pd.DataFrame(gbm.matrix.todense()) df.index",
"libtsne.get_tsne_plot_name(name)) out = '{}/{}_{}.{}'.format(dir, method, name, format) print(out) return cluster_plot(d, clusters, dim1=dim1, dim2=dim2,",
"table of n cells with a Cluster column giving each cell a cluster",
"kneighbors_graph(c1, k, mode='distance', metric='euclidean').toarray() a2 = kneighbors_graph(c2, k, mode='distance', metric='euclidean').toarray() overlaps = []",
"what is left (the clusters) # im_edges = im2.filter(ImageFilter.FIND_EDGES) # # # im_data",
"0:3] = [64, 64, 64] # #im_data[np.where(black_areas)] = d # # #im3 =",
"= libplot.new_ax(fig, subplot=(rows, rows, si)) pca_plot_base(pca, clusters, pc1=(i + 1), pc2=(j + 1),",
"* 100 overlaps.append(o) df = pd.DataFrame( {'Cluster': list(range(1, c1.shape[0] + 1)), 'Overlap %':",
"# for node in f.walk_nodes('/matrix', 'Array'): # dsets[node.name] = node.read() print(dsets) matrix =",
"tsne, genes, cmap=None, size=SUBPLOT_SIZE): \"\"\" Plot multiple genes on a grid. Parameters ----------",
"im2) if gene_id != gene: out = '{}/{}_expr_{}_{}.png'.format(dir, method, gene, gene_id) else: out",
"= im2.filter(ImageFilter.FIND_EDGES) # # im_smooth = im_edges.filter(ImageFilter.SMOOTH) # # # paste outline onto",
"labels: l = pca.index.values for i in range(0, pca.shape[0]): print(pca.shape, pca.iloc[i, pc1 -",
"is None: genes = gbm.gene_names gene_indices = np.where(genes == gene_name)[0] if len(gene_indices) ==",
"y)]) hull = ConvexHull(points) #x1 = x[idx] #y1 = y[idx] # avg1 =",
": Matplotlib figure # A new Matplotlib figure used to make the plot",
"im_edges.filter(ImageFilter.SMOOTH) # # # paste outline onto clusters # im2.paste(im_smooth, (0, 0), im_smooth)",
"= 500 ny = 500 xi = np.linspace(x.min(), x.max(), nx) yi = np.linspace(y.min(),",
"c=None) libplot.format_axes(ax) libplot.savefig(fig, '{}_centroids.pdf'.format(name)) def centroid_network(tsne, clusters, name): c = centroids(tsne, clusters) A",
"\"\"\" if ax is None: fig, ax = libplot.new_fig() libplot.scatter(tsne['TSNE-1'], tsne['TSNE-2'], c=c, marker=marker,",
"legend_params.update(legend) else: pass if legend_params['show']: libcluster.format_legend(ax, cols=legend_params['cols'], markerscale=legend_params['markerscale']) return fig, ax def base_cluster_plot_outline(out,",
"Creates a basic t-sne expression plot. # # Parameters # ---------- # data",
"clusters) imageWithEdges = im1.filter(ImageFilter.FIND_EDGES) im_data = np.array(imageWithEdges.convert('RGBA')) #r = data[:, :, 0] #g",
"1), cmap=libcluster.colormap()) nx.draw_networkx(G, with_labels=True, labels=labels, ax=ax, node_size=800, node_color=node_color, font_color='white', font_family='Arial') libplot.format_axes(ax) libplot.savefig(fig, '{}_centroid_network.pdf'.format(name))",
"show_axes=False, sort=True, cluster_order=None, fig=None, ax=None, out=None): fig, ax = base_cluster_plot(tsne, clusters, markers=markers, colors=colors,",
"c += 1 print(np.unique(d.index.values)) print(np.unique(sc)) df = pd.DataFrame(sc, index=d.index, columns=['Cluster']) return df def",
"fig=None, ax=None): fig, ax = pca_plot_base(pca, clusters, pc1=pc1, pc2=pc2, marker=marker, labels=labels, s=s, w=w,",
"def base_expr_plot(data, exp, dim=[1, 2], cmap=plt.cm.plasma, marker='o', edgecolors=EDGE_COLOR, linewidth=1, s=MARKER_SIZE, alpha=1, w=libplot.DEFAULT_WIDTH, h=libplot.DEFAULT_HEIGHT,",
"# find gray areas and mask # im_data = np.array(im1.convert('RGBA')) # # r",
"color bar. \"\"\" is_first = False if ax is None: fig, ax =",
"= x.shape[0] else: return None cols = int(np.ceil(np.sqrt(l))) w = size * cols",
"libplot.invisible_axes(ax) pc += 1 return fig def create_cluster_grid(tsne, clusters, name, colors=None, cols=-1, size=SUBPLOT_SIZE,",
"n cells with a Cluster column giving each cell a cluster label. s",
"ax = libplot.new_fig(w=w, h=h) ids = list(sorted(set(clusters['Cluster']))) for i in range(0, len(ids)): l",
"values for each data point so it must have the same number of",
"# Cells x tsne tsne data. Columns should be labeled 'TSNE-1', 'TSNE-2' etc",
"return cluster_map, labels def umi_tpm(data): # each column is a cell reads_per_bc =",
"0 # 0.25 ALPHA = 0.9 BLUE_YELLOW_CMAP = matplotlib.colors.LinearSegmentedColormap.from_list( 'blue_yellow', ['#162d50', '#ffdd55']) BLUE_CMAP",
"for p1, p2 in zip(x, y)]) hull = ConvexHull(points) #x1 = x[idx] #y1",
"a supplied argument, return the supplied figure, otherwise a new figure is created",
"top of original image to highlight cluster # enable if edges desired im1.paste(im2,",
"# if colors is None: # colors = libcluster.colors() # # for i",
"= get_gene_names(data) if isinstance(g, list): g = np.array(g) if isinstance(g, np.ndarray): idx =",
"fig, ax def pca_expr_plot(data, expr, name, dim=[1, 2], cmap=None, marker='o', s=MARKER_SIZE, alpha=EXP_ALPHA, fig=None,",
"(0, 0), im2) imagelib.save(im_base, out) def avg_expr(data, tsne, genes, cid, clusters, prefix='', index=None,",
"# colors[cid - 1] #colors[i] #np.where(clusters['Cluster'] == cluster)[0]] color = colors[i] else: color",
"< 0].quantile(1 - TNSE_AX_Q), d1[d1 >= 0].quantile(TNSE_AX_Q)] ylim = [d2[d2 < 0].quantile(1 -",
": DataFrame # Clusters in # # Returns # ------- # fig :",
"ax.set_title('tsne-10x') #libplot.savefig(fig, 'RK10001_10003_clust-phen_silhouette.pdf') ax = fig.add_subplot(212) # libplot.newfig(w=9) df2 = pd.DataFrame({'Silhouette Score': x2,",
"index in indexes: ret.append((index, ids[index], gene_names[index])) else: # if id does not exist,",
"grey_areas = (r < 255) & (r > 200) & (g < 255)",
"cmap) return fig def genes_expr(data, tsne, genes, prefix='', dim=[1, 2], index=None, dir='GeneExp', cmap=BGY_CMAP,",
"umi_tpm(data) return umi_log2(d) def umi_norm(data): \"\"\" Scale each library to its median size",
"size=SUBPLOT_SIZE, add_titles=True, cluster_order=None, method='tsne', dir='.', out=None): fig = cluster_grid(tsne, clusters, colors=colors, cols=cols, size=size,",
"out is None: # libtsne.get_tsne_plot_name(name)) out = '{}/{}_{}.{}'.format(dir, method, name, format) print(out) return",
"cluster)[0] # # # Plot background points # # # # x =",
"= tsne.iloc[idx2, 1] libplot.scatter(x, y, c=[background], ax=ax, edgecolors='none', # bgedgecolor, linewidth=linewidth, s=s) #"
] |
[
"standard GAN\"<https://arxiv.org/abs/1807.00734>`_ ). Assumes, real label is 1 and fake label is 0",
"Adversarial Nets # URL: https://arxiv.org/abs/1406.2661 g_minimax = g_minimax d_minimax = d_minimax # Paper:",
"isinstance(invert_labels, bool) if invert_labels: return - (1 - d_of_fake.sigmoid()).clamp(eps).log().mean() return - d_of_fake.sigmoid().clamp(eps).log().mean() def",
"missing from standard GAN\"<https://arxiv.org/abs/1807.00734>`_ ). Assumes, real label is 1 and fake label",
"\"\"\" assert isinstance(d_of_real, torch.Tensor) assert isinstance(d_of_fake, torch.Tensor) assert isinstance(invert_labels, bool) if invert_labels: return",
"(d_of_real - d_of_fake.mean()).sigmoid().clamp(eps) dra_fr = (d_of_fake - d_of_real.mean()).sigmoid().clamp(eps) if invert_labels: return - (dra_rf.log()",
"1 is real and 0 is fake. Fake --> D(G(z)) = d_of_fake =",
"key element missing from # standard GAN # URL: https://arxiv.org/pdf/1807.00734.pdf g_relativistic = g_relativistic",
"r\"\"\"Minimax loss for discriminator. (`\"Generative Adversarial Nets\" <https://papers.nips.cc/paper/5423-generative-adversarial-nets.pdf>`_). Assumes, real label is 1",
"real and 0 is fake. Fake --> D(G(z)) = d_of_fake = d_of_g_of_z Real",
"d_of_fake: torch.Tensor, invert_labels: bool = False): r\"\"\"Minimax loss for discriminator. (`\"Generative Adversarial Nets\"",
"for generator. (`\"The relativistic discriminator: a key element missing from standard GAN\"<https://arxiv.org/abs/1807.00734>`_ ).",
"bool) if invert_labels: return - (d_of_fake - d_of_real.mean()).sigmoid().clamp(eps).log() return - (1 - (d_of_fake",
"d_of_real.mean()).sigmoid()).clamp(eps).log() def d_relativistic(d_of_real: torch.Tensor, d_of_fake: torch.Tensor, invert_labels: bool = False): r\"\"\"Relativistic loss for",
"log(σ(d_of_fake - E[d_of_real])) Args: d_of_real (torch.Tensor, required): discriminator output of real. d_of_fake (torch.Tensor,",
"# Paper: Generative Adversarial Nets # URL: https://arxiv.org/abs/1406.2661 g_minimax = g_minimax d_minimax =",
")) - log(1 - σ( d_of_fake )) Args: d_of_real (torch.Tensor, required): discriminator output",
"discriminator output of real. d_of_fake (torch.Tensor, required): discriminator output of fake. invert_labels (bool,",
"σ(d_of_fake - E[d_of_real])) Args: d_of_real (torch.Tensor, required): discriminator output of real. d_of_fake (torch.Tensor,",
"))^2 + σ( d_of_fake )^2) / 2 Args: d_of_real (torch.Tensor, required): discriminator output",
"- σ( d_of_fake ))^2 Args: d_of_fake (torch.Tensor, required): discriminator output of fake. invert_labels",
"+ (1 - dra_fr).log()).mean() return - ((1 - dra_rf).log() + dra_fr.log()).mean() class AdversarialLoss:",
"for generator. (`\"Least Squares Generative Adversarial Networks\"<https://arxiv.org/abs/1611.04076>`_). Assumes, real label is 1 and",
"\"\"\" assert isinstance(d_of_fake, torch.Tensor) assert isinstance(invert_labels, bool) if invert_labels: return - (1 -",
"- σ(d_of_fake - E[d_of_real])) Args: d_of_real (torch.Tensor, required): discriminator output of real. d_of_fake",
"URL: https://arxiv.org/abs/1406.2661 g_minimax = g_minimax d_minimax = d_minimax # Paper: Least Squares Generative",
"torch.Tensor, invert_labels: bool = False): r\"\"\"Relativistic loss for generator. (`\"The relativistic discriminator: a",
"- d_of_fake.sigmoid().clamp(eps).log().mean() def d_minimax(d_of_real: torch.Tensor, d_of_fake: torch.Tensor, invert_labels: bool = False): r\"\"\"Minimax loss",
"r\"\"\"Minimax loss for generator. (`\"Generative Adversarial Nets\" <https://papers.nips.cc/paper/5423-generative-adversarial-nets.pdf>`_). Assumes, real label is 1",
"torch.Tensor) assert isinstance(d_of_fake, torch.Tensor) assert isinstance(invert_labels, bool) if invert_labels: rloss = d_of_real.sigmoid().pow(2) floss",
"))^2 Args: d_of_fake (torch.Tensor, required): discriminator output of fake. invert_labels (bool, optional): Inverts",
"E[d_of_fake])) - log(σ(d_of_fake - E[d_of_real])) Args: d_of_real (torch.Tensor, required): discriminator output of real.",
"is real and 0 is fake. Fake --> D(G(z)) = d_of_fake = d_of_g_of_z",
"d_of_real = D(I). loss = - log(σ( d_of_real )) - log(1 - σ(",
"= (d_of_fake - d_of_real.mean()).sigmoid().clamp(eps) if invert_labels: return - (dra_rf.log() + (1 - dra_fr).log()).mean()",
"Paper: The relativistic discriminatorr: a key element missing from # standard GAN #",
"= D(G(z)) and d_of_real = D(I). loss = - log(1 - σ(d_of_fake -",
"- d_of_fake.sigmoid().clamp(eps).log() else: rloss = - d_of_real.sigmoid().clamp(eps).log() floss = - (1 - d_of_fake.sigmoid()).clamp(eps).log()",
"return (rloss + floss).mean() / 2 def g_least_squares(d_of_fake: torch.Tensor, invert_labels: bool = False):",
"if invert_labels: rloss = - (1 - d_of_real.sigmoid()).clamp(eps).log() floss = - d_of_fake.sigmoid().clamp(eps).log() else:",
"def g_least_squares(d_of_fake: torch.Tensor, invert_labels: bool = False): r\"\"\"Least squares loss for generator. (`\"Least",
"- (d_of_fake - d_of_real.mean()).sigmoid().clamp(eps).log() return - (1 - (d_of_fake - d_of_real.mean()).sigmoid()).clamp(eps).log() def d_relativistic(d_of_real:",
"d_of_real = D(I). loss = - log(1 - σ(d_of_fake - E[d_of_real])) Args: d_of_real",
"labels). d_of_fake = D(G(z)) and d_of_real = D(I). loss = ((1 - σ(",
"(1 - d_of_fake.sigmoid()).clamp(eps).log() return (rloss + floss).mean() / 2 def g_least_squares(d_of_fake: torch.Tensor, invert_labels:",
"element missing from # standard GAN # URL: https://arxiv.org/pdf/1807.00734.pdf g_relativistic = g_relativistic d_relativistic",
"required): discriminator output of fake. invert_labels (bool, optional): Inverts real and fake labels",
"assert isinstance(invert_labels, bool) if invert_labels: rloss = - (1 - d_of_real.sigmoid()).clamp(eps).log() floss =",
"/ 2 def g_relativistic(d_of_real: torch.Tensor, d_of_fake: torch.Tensor, invert_labels: bool = False): r\"\"\"Relativistic loss",
"= - log(1 - σ(d_of_fake - E[d_of_real])) Args: d_of_real (torch.Tensor, required): discriminator output",
"- σ( d_of_real ))^2 + σ( d_of_fake )^2) / 2 Args: d_of_real (torch.Tensor,",
"\"\"\" # Paper: Generative Adversarial Nets # URL: https://arxiv.org/abs/1406.2661 g_minimax = g_minimax d_minimax",
"fake labels). d_of_fake = D(G(z)) and d_of_real = D(I). loss = ((1 -",
"bool) if invert_labels: return d_of_fake.sigmoid().pow(2).mean() return (1 - d_of_fake.sigmoid()).pow(2).mean() def d_least_squares(d_of_real: torch.Tensor, d_of_fake:",
"assert isinstance(d_of_fake, torch.Tensor) assert isinstance(invert_labels, bool) if invert_labels: return - (1 - d_of_fake.sigmoid()).clamp(eps).log().mean()",
"2 Args: d_of_real (torch.Tensor, required): discriminator output of real. d_of_fake (torch.Tensor, required): discriminator",
"fake labels to 0 and 1 respectively (default: :obj:`\"False\"`). \"\"\" assert isinstance(d_of_fake, torch.Tensor)",
"fake label is 0 (use invert_labels to flip real and fake labels). d_of_fake",
"D(I). loss = - log(σ( d_of_real )) - log(1 - σ( d_of_fake ))",
"assert isinstance(d_of_fake, torch.Tensor) assert isinstance(invert_labels, bool) dra_rf = (d_of_real - d_of_fake.mean()).sigmoid().clamp(eps) dra_fr =",
"((1 - σ( d_of_real ))^2 + σ( d_of_fake )^2) / 2 Args: d_of_real",
"D(G(z)) and d_of_real = D(I). loss = ((1 - σ( d_of_real ))^2 +",
"- σ(d_of_real - E[d_of_fake])) - log(σ(d_of_fake - E[d_of_real])) Args: d_of_real (torch.Tensor, required): discriminator",
"if invert_labels: return - (d_of_fake - d_of_real.mean()).sigmoid().clamp(eps).log() return - (1 - (d_of_fake -",
"assert isinstance(d_of_fake, torch.Tensor) assert isinstance(invert_labels, bool) if invert_labels: return - (d_of_fake - d_of_real.mean()).sigmoid().clamp(eps).log()",
"\"\"\" assert isinstance(d_of_fake, torch.Tensor) assert isinstance(invert_labels, bool) if invert_labels: return d_of_fake.sigmoid().pow(2).mean() return (1",
"invert_labels: bool = False): r\"\"\"Minimax loss for discriminator. (`\"Generative Adversarial Nets\" <https://papers.nips.cc/paper/5423-generative-adversarial-nets.pdf>`_). Assumes,",
"= D(G(z)) and d_of_real = D(I). loss = - log(1 - σ(d_of_real -",
"generator. (`\"The relativistic discriminator: a key element missing from standard GAN\"<https://arxiv.org/abs/1807.00734>`_ ). Assumes,",
"Squares Generative Adversarial Networks\"<https://arxiv.org/abs/1611.04076>`_). Assumes, real label is 1 and fake label is",
"losses. Assumes 1 is real and 0 is fake. Fake --> D(G(z)) =",
"(1 - d_of_fake.sigmoid()).pow(2).mean() def d_least_squares(d_of_real: torch.Tensor, d_of_fake: torch.Tensor, invert_labels: bool = False): r\"\"\"Least",
"= ((1 - σ( d_of_real ))^2 + σ( d_of_fake )^2) / 2 Args:",
"(1 - d_of_fake.sigmoid()).clamp(eps).log().mean() return - d_of_fake.sigmoid().clamp(eps).log().mean() def d_minimax(d_of_real: torch.Tensor, d_of_fake: torch.Tensor, invert_labels: bool",
"dra_rf).log() + dra_fr.log()).mean() class AdversarialLoss: r\"\"\"Adversarial losses. Assumes 1 is real and 0",
"d_of_fake.sigmoid()).pow(2).mean() def d_least_squares(d_of_real: torch.Tensor, d_of_fake: torch.Tensor, invert_labels: bool = False): r\"\"\"Least squares loss",
"torch.Tensor, d_of_fake: torch.Tensor, invert_labels: bool = False): r\"\"\"Minimax loss for discriminator. (`\"Generative Adversarial",
"\"\"\" assert isinstance(d_of_real, torch.Tensor) assert isinstance(d_of_fake, torch.Tensor) assert isinstance(invert_labels, bool) dra_rf = (d_of_real",
"Inverts real and fake labels to 0 and 1 respectively (default: :obj:`\"False\"`). \"\"\"",
"d_of_real.mean()).sigmoid().clamp(eps).log() return - (1 - (d_of_fake - d_of_real.mean()).sigmoid()).clamp(eps).log() def d_relativistic(d_of_real: torch.Tensor, d_of_fake: torch.Tensor,",
"d_of_fake.mean()).sigmoid().clamp(eps) dra_fr = (d_of_fake - d_of_real.mean()).sigmoid().clamp(eps) if invert_labels: return - (dra_rf.log() + (1",
"output of fake. invert_labels (bool, optional): Inverts real and fake labels to 0",
"D(G(z)) and d_of_real = D(I). loss = - log(1 - σ(d_of_real - E[d_of_fake]))",
"d_of_fake = D(G(z)). loss = (1 - σ( d_of_fake ))^2 Args: d_of_fake (torch.Tensor,",
"d_of_fake: torch.Tensor, invert_labels: bool = False): r\"\"\"Least squares loss for generator. (`\"Least Squares",
"False): r\"\"\"Least squares loss for generator. (`\"Least Squares Generative Adversarial Networks\"<https://arxiv.org/abs/1611.04076>`_). Assumes, real",
"invert_labels to flip real and fake labels). d_of_fake = D(G(z)). loss = (1",
"0 (use invert_labels to flip real and fake labels). d_of_fake = D(G(z)). loss",
"assert isinstance(d_of_real, torch.Tensor) assert isinstance(d_of_fake, torch.Tensor) assert isinstance(invert_labels, bool) dra_rf = (d_of_real -",
"Networks # URL: https://arxiv.org/abs/1611.04076 g_least_squares = g_least_squares d_least_squares = d_least_squares # Paper: The",
"- log(σ( d_of_real )) - log(1 - σ( d_of_fake )) Args: d_of_real (torch.Tensor,",
"floss = d_of_fake.sigmoid().pow(2) return (rloss + floss).mean() / 2 def g_relativistic(d_of_real: torch.Tensor, d_of_fake:",
"= D(G(z)). loss = - log(σ( d_of_fake )) Args: d_of_fake (torch.Tensor, required): discriminator",
"σ( d_of_fake )^2) / 2 Args: d_of_real (torch.Tensor, required): discriminator output of real.",
"= - log(1 - σ(d_of_real - E[d_of_fake])) - log(σ(d_of_fake - E[d_of_real])) Args: d_of_real",
"= - log(σ( d_of_real )) - log(1 - σ( d_of_fake )) Args: d_of_real",
"and fake labels). d_of_fake = D(G(z)). loss = (1 - σ( d_of_fake ))^2",
"Networks\"<https://arxiv.org/abs/1611.04076>`_). Assumes, real label is 1 and fake label is 0 (use invert_labels",
"Paper: Least Squares Generative Adversarial Networks # URL: https://arxiv.org/abs/1611.04076 g_least_squares = g_least_squares d_least_squares",
"False): r\"\"\"Relativistic loss for generator. (`\"The relativistic discriminator: a key element missing from",
"discriminator output of fake. invert_labels (bool, optional): Inverts real and fake labels to",
"= - (1 - d_of_fake.sigmoid()).clamp(eps).log() return (rloss + floss).mean() / 2 def g_least_squares(d_of_fake:",
"label is 1 and fake label is 0 (use invert_labels to flip real",
"real label is 1 and fake label is 0 (use invert_labels to flip",
"isinstance(d_of_real, torch.Tensor) assert isinstance(d_of_fake, torch.Tensor) assert isinstance(invert_labels, bool) dra_rf = (d_of_real - d_of_fake.mean()).sigmoid().clamp(eps)",
"assert isinstance(d_of_fake, torch.Tensor) assert isinstance(invert_labels, bool) if invert_labels: return d_of_fake.sigmoid().pow(2).mean() return (1 -",
"missing from # standard GAN # URL: https://arxiv.org/pdf/1807.00734.pdf g_relativistic = g_relativistic d_relativistic =",
"- d_of_fake.sigmoid()).clamp(eps).log() return (rloss + floss).mean() / 2 def g_least_squares(d_of_fake: torch.Tensor, invert_labels: bool",
"d_of_real ))^2 + σ( d_of_fake )^2) / 2 Args: d_of_real (torch.Tensor, required): discriminator",
"- d_of_real.sigmoid()).pow(2) floss = d_of_fake.sigmoid().pow(2) return (rloss + floss).mean() / 2 def g_relativistic(d_of_real:",
"to flip real and fake labels). d_of_fake = D(G(z)) and d_of_real = D(I).",
"- (dra_rf.log() + (1 - dra_fr).log()).mean() return - ((1 - dra_rf).log() + dra_fr.log()).mean()",
"rloss = d_of_real.sigmoid().pow(2) floss = (1 - d_of_fake.sigmoid()).pow(2) else: rloss = (1 -",
"dra_fr).log()).mean() return - ((1 - dra_rf).log() + dra_fr.log()).mean() class AdversarialLoss: r\"\"\"Adversarial losses. Assumes",
"d_of_real.sigmoid()).pow(2) floss = d_of_fake.sigmoid().pow(2) return (rloss + floss).mean() / 2 def g_relativistic(d_of_real: torch.Tensor,",
"Squares Generative Adversarial Networks # URL: https://arxiv.org/abs/1611.04076 g_least_squares = g_least_squares d_least_squares = d_least_squares",
"return - (1 - d_of_fake.sigmoid()).clamp(eps).log().mean() return - d_of_fake.sigmoid().clamp(eps).log().mean() def d_minimax(d_of_real: torch.Tensor, d_of_fake: torch.Tensor,",
"def g_minimax(d_of_fake: torch.Tensor, invert_labels: bool = False): r\"\"\"Minimax loss for generator. (`\"Generative Adversarial",
"assert isinstance(d_of_fake, torch.Tensor) assert isinstance(invert_labels, bool) if invert_labels: rloss = - (1 -",
"d_minimax # Paper: Least Squares Generative Adversarial Networks # URL: https://arxiv.org/abs/1611.04076 g_least_squares =",
"invert_labels (bool, optional): Inverts real and fake labels to 0 and 1 respectively",
"and d_of_real = D(I). loss = - log(1 - σ(d_of_real - E[d_of_fake])) -",
"- dra_fr).log()).mean() return - ((1 - dra_rf).log() + dra_fr.log()).mean() class AdversarialLoss: r\"\"\"Adversarial losses.",
"bool) if invert_labels: return - (1 - d_of_fake.sigmoid()).clamp(eps).log().mean() return - d_of_fake.sigmoid().clamp(eps).log().mean() def d_minimax(d_of_real:",
"labels). d_of_fake = D(G(z)). loss = (1 - σ( d_of_fake ))^2 Args: d_of_fake",
"isinstance(d_of_real, torch.Tensor) assert isinstance(d_of_fake, torch.Tensor) assert isinstance(invert_labels, bool) if invert_labels: rloss = d_of_real.sigmoid().pow(2)",
"- log(1 - σ(d_of_real - E[d_of_fake])) - log(σ(d_of_fake - E[d_of_real])) Args: d_of_real (torch.Tensor,",
"d_of_fake ))^2 Args: d_of_fake (torch.Tensor, required): discriminator output of fake. invert_labels (bool, optional):",
"invert_labels to flip real and fake labels). d_of_fake = D(G(z)). loss = -",
"- log(σ(d_of_fake - E[d_of_real])) Args: d_of_real (torch.Tensor, required): discriminator output of real. d_of_fake",
"# URL: https://arxiv.org/abs/1611.04076 g_least_squares = g_least_squares d_least_squares = d_least_squares # Paper: The relativistic",
"a key element missing from standard GAN\"<https://arxiv.org/abs/1807.00734>`_ ). Assumes, real label is 1",
"d_of_fake = d_of_g_of_z Real --> D(I) = d_of_real \"\"\" # Paper: Generative Adversarial",
"torch.Tensor, invert_labels: bool = False): r\"\"\"Minimax loss for discriminator. (`\"Generative Adversarial Nets\" <https://papers.nips.cc/paper/5423-generative-adversarial-nets.pdf>`_).",
"= (1 - σ( d_of_fake ))^2 Args: d_of_fake (torch.Tensor, required): discriminator output of",
"d_of_fake.sigmoid()).pow(2) else: rloss = (1 - d_of_real.sigmoid()).pow(2) floss = d_of_fake.sigmoid().pow(2) return (rloss +",
"return - (d_of_fake - d_of_real.mean()).sigmoid().clamp(eps).log() return - (1 - (d_of_fake - d_of_real.mean()).sigmoid()).clamp(eps).log() def",
"= False): r\"\"\"Least squares loss for generator. (`\"Least Squares Generative Adversarial Networks\"<https://arxiv.org/abs/1611.04076>`_). Assumes,",
"loss = - log(σ( d_of_real )) - log(1 - σ( d_of_fake )) Args:",
"assert isinstance(d_of_fake, torch.Tensor) assert isinstance(invert_labels, bool) if invert_labels: rloss = d_of_real.sigmoid().pow(2) floss =",
"= d_of_fake = d_of_g_of_z Real --> D(I) = d_of_real \"\"\" # Paper: Generative",
"σ( d_of_real ))^2 + σ( d_of_fake )^2) / 2 Args: d_of_real (torch.Tensor, required):",
"fake labels). d_of_fake = D(G(z)). loss = (1 - σ( d_of_fake ))^2 Args:",
"+ floss).mean() / 2 def g_relativistic(d_of_real: torch.Tensor, d_of_fake: torch.Tensor, invert_labels: bool = False):",
"Adversarial Networks # URL: https://arxiv.org/abs/1611.04076 g_least_squares = g_least_squares d_least_squares = d_least_squares # Paper:",
"assert isinstance(d_of_real, torch.Tensor) assert isinstance(d_of_fake, torch.Tensor) assert isinstance(invert_labels, bool) if invert_labels: return -",
"d_of_fake = D(G(z)) and d_of_real = D(I). loss = - log(1 - σ(d_of_fake",
"flip real and fake labels). d_of_fake = D(G(z)) and d_of_real = D(I). loss",
"rloss = (1 - d_of_real.sigmoid()).pow(2) floss = d_of_fake.sigmoid().pow(2) return (rloss + floss).mean() /",
"torch.Tensor) assert isinstance(d_of_fake, torch.Tensor) assert isinstance(invert_labels, bool) dra_rf = (d_of_real - d_of_fake.mean()).sigmoid().clamp(eps) dra_fr",
"return - (dra_rf.log() + (1 - dra_fr).log()).mean() return - ((1 - dra_rf).log() +",
"--> D(G(z)) = d_of_fake = d_of_g_of_z Real --> D(I) = d_of_real \"\"\" #",
"from # standard GAN # URL: https://arxiv.org/pdf/1807.00734.pdf g_relativistic = g_relativistic d_relativistic = d_relativistic",
"g_relativistic(d_of_real: torch.Tensor, d_of_fake: torch.Tensor, invert_labels: bool = False): r\"\"\"Relativistic loss for generator. (`\"The",
":: loss :: AdversarialLoss\"\"\" __all__ = [\"AdversarialLoss\"] import torch import numpy as np",
"respectively (default: :obj:`\"False\"`). \"\"\" assert isinstance(d_of_fake, torch.Tensor) assert isinstance(invert_labels, bool) if invert_labels: return",
"labels). d_of_fake = D(G(z)) and d_of_real = D(I). loss = - log(1 -",
"fake labels to 0 and 1 respectively (default: :obj:`\"False\"`). \"\"\" assert isinstance(d_of_real, torch.Tensor)",
"if invert_labels: return - (1 - d_of_fake.sigmoid()).clamp(eps).log().mean() return - d_of_fake.sigmoid().clamp(eps).log().mean() def d_minimax(d_of_real: torch.Tensor,",
"= D(G(z)). loss = (1 - σ( d_of_fake ))^2 Args: d_of_fake (torch.Tensor, required):",
"(`\"The relativistic discriminator: a key element missing from standard GAN\"<https://arxiv.org/abs/1807.00734>`_ ). Assumes, real",
"GAN\"<https://arxiv.org/abs/1807.00734>`_ ). Assumes, real label is 1 and fake label is 0 (use",
"Adversarial Nets\" <https://papers.nips.cc/paper/5423-generative-adversarial-nets.pdf>`_). Assumes, real label is 1 and fake label is 0",
"= False): r\"\"\"Minimax loss for generator. (`\"Generative Adversarial Nets\" <https://papers.nips.cc/paper/5423-generative-adversarial-nets.pdf>`_). Assumes, real label",
"--> D(I) = d_of_real \"\"\" # Paper: Generative Adversarial Nets # URL: https://arxiv.org/abs/1406.2661",
"labels to 0 and 1 respectively (default: :obj:`\"False\"`). \"\"\" assert isinstance(d_of_fake, torch.Tensor) assert",
"fake. invert_labels (bool, optional): Inverts real and fake labels to 0 and 1",
"g_minimax d_minimax = d_minimax # Paper: Least Squares Generative Adversarial Networks # URL:",
"d_of_fake.sigmoid().clamp(eps).log().mean() def d_minimax(d_of_real: torch.Tensor, d_of_fake: torch.Tensor, invert_labels: bool = False): r\"\"\"Minimax loss for",
"return - ((1 - dra_rf).log() + dra_fr.log()).mean() class AdversarialLoss: r\"\"\"Adversarial losses. Assumes 1",
"loss = - log(1 - σ(d_of_fake - E[d_of_real])) Args: d_of_real (torch.Tensor, required): discriminator",
"invert_labels: return - (1 - d_of_fake.sigmoid()).clamp(eps).log().mean() return - d_of_fake.sigmoid().clamp(eps).log().mean() def d_minimax(d_of_real: torch.Tensor, d_of_fake:",
"loss for discriminator. (`\"Generative Adversarial Nets\" <https://papers.nips.cc/paper/5423-generative-adversarial-nets.pdf>`_). Assumes, real label is 1 and",
"from standard GAN\"<https://arxiv.org/abs/1807.00734>`_ ). Assumes, real label is 1 and fake label is",
"if invert_labels: return - (dra_rf.log() + (1 - dra_fr).log()).mean() return - ((1 -",
"- E[d_of_real])) Args: d_of_real (torch.Tensor, required): discriminator output of real. d_of_fake (torch.Tensor, required):",
"d_of_real = D(I). loss = - log(1 - σ(d_of_real - E[d_of_fake])) - log(σ(d_of_fake",
"= d_of_real \"\"\" # Paper: Generative Adversarial Nets # URL: https://arxiv.org/abs/1406.2661 g_minimax =",
"invert_labels: bool = False): r\"\"\"Relativistic loss for generator. (`\"The relativistic discriminator: a key",
"discriminatorr: a key element missing from # standard GAN # URL: https://arxiv.org/pdf/1807.00734.pdf g_relativistic",
"(1 - σ( d_of_fake ))^2 Args: d_of_fake (torch.Tensor, required): discriminator output of fake.",
"- d_of_real.sigmoid().clamp(eps).log() floss = - (1 - d_of_fake.sigmoid()).clamp(eps).log() return (rloss + floss).mean() /",
"Args: d_of_real (torch.Tensor, required): discriminator output of real. d_of_fake (torch.Tensor, required): discriminator output",
"# Paper: The relativistic discriminatorr: a key element missing from # standard GAN",
"if invert_labels: return d_of_fake.sigmoid().pow(2).mean() return (1 - d_of_fake.sigmoid()).pow(2).mean() def d_least_squares(d_of_real: torch.Tensor, d_of_fake: torch.Tensor,",
"(torch.Tensor, required): discriminator output of fake. invert_labels (bool, optional): Inverts real and fake",
"Real --> D(I) = d_of_real \"\"\" # Paper: Generative Adversarial Nets # URL:",
"and fake label is 0 (use invert_labels to flip real and fake labels).",
"is 1 and fake label is 0 (use invert_labels to flip real and",
"Nets\" <https://papers.nips.cc/paper/5423-generative-adversarial-nets.pdf>`_). Assumes, real label is 1 and fake label is 0 (use",
"and d_of_real = D(I). loss = - log(1 - σ(d_of_fake - E[d_of_real])) Args:",
"1 respectively (default: :obj:`\"False\"`). \"\"\" assert isinstance(d_of_fake, torch.Tensor) assert isinstance(invert_labels, bool) if invert_labels:",
"d_minimax(d_of_real: torch.Tensor, d_of_fake: torch.Tensor, invert_labels: bool = False): r\"\"\"Minimax loss for discriminator. (`\"Generative",
"= D(G(z)) and d_of_real = D(I). loss = - log(σ( d_of_real )) -",
"isinstance(d_of_real, torch.Tensor) assert isinstance(d_of_fake, torch.Tensor) assert isinstance(invert_labels, bool) if invert_labels: return - (d_of_fake",
"= D(I). loss = - log(σ( d_of_real )) - log(1 - σ( d_of_fake",
"(dra_rf.log() + (1 - dra_fr).log()).mean() return - ((1 - dra_rf).log() + dra_fr.log()).mean() class",
"False): r\"\"\"Minimax loss for generator. (`\"Generative Adversarial Nets\" <https://papers.nips.cc/paper/5423-generative-adversarial-nets.pdf>`_). Assumes, real label is",
"r\"\"\"Relativistic loss for generator. (`\"The relativistic discriminator: a key element missing from standard",
"isinstance(invert_labels, bool) if invert_labels: return - (d_of_fake - d_of_real.mean()).sigmoid().clamp(eps).log() return - (1 -",
"d_of_fake = D(G(z)) and d_of_real = D(I). loss = - log(1 - σ(d_of_real",
"return d_of_fake.sigmoid().pow(2).mean() return (1 - d_of_fake.sigmoid()).pow(2).mean() def d_least_squares(d_of_real: torch.Tensor, d_of_fake: torch.Tensor, invert_labels: bool",
"D(I) = d_of_real \"\"\" # Paper: Generative Adversarial Nets # URL: https://arxiv.org/abs/1406.2661 g_minimax",
"is 0 (use invert_labels to flip real and fake labels). d_of_fake = D(G(z))",
"(d_of_fake - d_of_real.mean()).sigmoid().clamp(eps) if invert_labels: return - (dra_rf.log() + (1 - dra_fr).log()).mean() return",
"isinstance(d_of_fake, torch.Tensor) assert isinstance(invert_labels, bool) if invert_labels: rloss = d_of_real.sigmoid().pow(2) floss = (1",
"isinstance(invert_labels, bool) if invert_labels: rloss = - (1 - d_of_real.sigmoid()).clamp(eps).log() floss = -",
"d_least_squares # Paper: The relativistic discriminatorr: a key element missing from # standard",
"bool = False): r\"\"\"Minimax loss for generator. (`\"Generative Adversarial Nets\" <https://papers.nips.cc/paper/5423-generative-adversarial-nets.pdf>`_). Assumes, real",
"else: rloss = (1 - d_of_real.sigmoid()).pow(2) floss = d_of_fake.sigmoid().pow(2) return (rloss + floss).mean()",
"= np.finfo(float).eps def g_minimax(d_of_fake: torch.Tensor, invert_labels: bool = False): r\"\"\"Minimax loss for generator.",
"import torch import numpy as np eps = np.finfo(float).eps def g_minimax(d_of_fake: torch.Tensor, invert_labels:",
"d_of_fake.sigmoid().pow(2) return (rloss + floss).mean() / 2 def g_relativistic(d_of_real: torch.Tensor, d_of_fake: torch.Tensor, invert_labels:",
"d_of_g_of_z Real --> D(I) = d_of_real \"\"\" # Paper: Generative Adversarial Nets #",
"- d_of_fake.sigmoid()).pow(2) else: rloss = (1 - d_of_real.sigmoid()).pow(2) floss = d_of_fake.sigmoid().pow(2) return (rloss",
"= D(I). loss = ((1 - σ( d_of_real ))^2 + σ( d_of_fake )^2)",
"torch.Tensor) assert isinstance(invert_labels, bool) if invert_labels: return d_of_fake.sigmoid().pow(2).mean() return (1 - d_of_fake.sigmoid()).pow(2).mean() def",
"bool) if invert_labels: rloss = d_of_real.sigmoid().pow(2) floss = (1 - d_of_fake.sigmoid()).pow(2) else: rloss",
"<gh_stars>10-100 \"\"\"TensorMONK :: loss :: AdversarialLoss\"\"\" __all__ = [\"AdversarialLoss\"] import torch import numpy",
"def d_minimax(d_of_real: torch.Tensor, d_of_fake: torch.Tensor, invert_labels: bool = False): r\"\"\"Minimax loss for discriminator.",
"class AdversarialLoss: r\"\"\"Adversarial losses. Assumes 1 is real and 0 is fake. Fake",
"fake labels). d_of_fake = D(G(z)). loss = - log(σ( d_of_fake )) Args: d_of_fake",
"- log(1 - σ( d_of_fake )) Args: d_of_real (torch.Tensor, required): discriminator output of",
"(default: :obj:`\"False\"`). \"\"\" assert isinstance(d_of_real, torch.Tensor) assert isinstance(d_of_fake, torch.Tensor) assert isinstance(invert_labels, bool) dra_rf",
"= (1 - d_of_fake.sigmoid()).pow(2) else: rloss = (1 - d_of_real.sigmoid()).pow(2) floss = d_of_fake.sigmoid().pow(2)",
"Assumes 1 is real and 0 is fake. Fake --> D(G(z)) = d_of_fake",
"to 0 and 1 respectively (default: :obj:`\"False\"`). \"\"\" assert isinstance(d_of_real, torch.Tensor) assert isinstance(d_of_fake,",
"σ(d_of_real - E[d_of_fake])) - log(σ(d_of_fake - E[d_of_real])) Args: d_of_real (torch.Tensor, required): discriminator output",
"label is 0 (use invert_labels to flip real and fake labels). d_of_fake =",
"0 (use invert_labels to flip real and fake labels). d_of_fake = D(G(z)) and",
"- (1 - d_of_fake.sigmoid()).clamp(eps).log().mean() return - d_of_fake.sigmoid().clamp(eps).log().mean() def d_minimax(d_of_real: torch.Tensor, d_of_fake: torch.Tensor, invert_labels:",
"(`\"Least Squares Generative Adversarial Networks\"<https://arxiv.org/abs/1611.04076>`_). Assumes, real label is 1 and fake label",
"log(σ( d_of_fake )) Args: d_of_fake (torch.Tensor, required): discriminator output of fake. invert_labels (bool,",
"invert_labels: return - (d_of_fake - d_of_real.mean()).sigmoid().clamp(eps).log() return - (1 - (d_of_fake - d_of_real.mean()).sigmoid()).clamp(eps).log()",
"(default: :obj:`\"False\"`). \"\"\" assert isinstance(d_of_real, torch.Tensor) assert isinstance(d_of_fake, torch.Tensor) assert isinstance(invert_labels, bool) if",
"generator. (`\"Generative Adversarial Nets\" <https://papers.nips.cc/paper/5423-generative-adversarial-nets.pdf>`_). Assumes, real label is 1 and fake label",
"g_minimax(d_of_fake: torch.Tensor, invert_labels: bool = False): r\"\"\"Minimax loss for generator. (`\"Generative Adversarial Nets\"",
"import numpy as np eps = np.finfo(float).eps def g_minimax(d_of_fake: torch.Tensor, invert_labels: bool =",
"(1 - dra_fr).log()).mean() return - ((1 - dra_rf).log() + dra_fr.log()).mean() class AdversarialLoss: r\"\"\"Adversarial",
"real and fake labels). d_of_fake = D(G(z)) and d_of_real = D(I). loss =",
"def g_relativistic(d_of_real: torch.Tensor, d_of_fake: torch.Tensor, invert_labels: bool = False): r\"\"\"Relativistic loss for generator.",
"dra_fr = (d_of_fake - d_of_real.mean()).sigmoid().clamp(eps) if invert_labels: return - (dra_rf.log() + (1 -",
"loss for generator. (`\"Generative Adversarial Nets\" <https://papers.nips.cc/paper/5423-generative-adversarial-nets.pdf>`_). Assumes, real label is 1 and",
"(rloss + floss).mean() / 2 def g_least_squares(d_of_fake: torch.Tensor, invert_labels: bool = False): r\"\"\"Least",
"/ 2 Args: d_of_real (torch.Tensor, required): discriminator output of real. d_of_fake (torch.Tensor, required):",
"= d_minimax # Paper: Least Squares Generative Adversarial Networks # URL: https://arxiv.org/abs/1611.04076 g_least_squares",
"= [\"AdversarialLoss\"] import torch import numpy as np eps = np.finfo(float).eps def g_minimax(d_of_fake:",
"bool = False): r\"\"\"Minimax loss for discriminator. (`\"Generative Adversarial Nets\" <https://papers.nips.cc/paper/5423-generative-adversarial-nets.pdf>`_). Assumes, real",
"isinstance(d_of_fake, torch.Tensor) assert isinstance(invert_labels, bool) if invert_labels: return d_of_fake.sigmoid().pow(2).mean() return (1 - d_of_fake.sigmoid()).pow(2).mean()",
"for discriminator. (`\"Generative Adversarial Nets\" <https://papers.nips.cc/paper/5423-generative-adversarial-nets.pdf>`_). Assumes, real label is 1 and fake",
"- log(σ( d_of_fake )) Args: d_of_fake (torch.Tensor, required): discriminator output of fake. invert_labels",
"generator. (`\"Least Squares Generative Adversarial Networks\"<https://arxiv.org/abs/1611.04076>`_). Assumes, real label is 1 and fake",
"D(G(z)) = d_of_fake = d_of_g_of_z Real --> D(I) = d_of_real \"\"\" # Paper:",
"+ σ( d_of_fake )^2) / 2 Args: d_of_real (torch.Tensor, required): discriminator output of",
"relativistic discriminatorr: a key element missing from # standard GAN # URL: https://arxiv.org/pdf/1807.00734.pdf",
"(torch.Tensor, required): discriminator output of real. d_of_fake (torch.Tensor, required): discriminator output of fake.",
"- d_of_real.mean()).sigmoid().clamp(eps) if invert_labels: return - (dra_rf.log() + (1 - dra_fr).log()).mean() return -",
"= D(I). loss = - log(1 - σ(d_of_fake - E[d_of_real])) Args: d_of_real (torch.Tensor,",
"D(G(z)). loss = - log(σ( d_of_fake )) Args: d_of_fake (torch.Tensor, required): discriminator output",
"is 0 (use invert_labels to flip real and fake labels). d_of_fake = D(G(z)).",
"= - d_of_fake.sigmoid().clamp(eps).log() else: rloss = - d_of_real.sigmoid().clamp(eps).log() floss = - (1 -",
"to 0 and 1 respectively (default: :obj:`\"False\"`). \"\"\" assert isinstance(d_of_fake, torch.Tensor) assert isinstance(invert_labels,",
"(1 - d_of_fake.sigmoid()).pow(2) else: rloss = (1 - d_of_real.sigmoid()).pow(2) floss = d_of_fake.sigmoid().pow(2) return",
"bool) if invert_labels: rloss = - (1 - d_of_real.sigmoid()).clamp(eps).log() floss = - d_of_fake.sigmoid().clamp(eps).log()",
"Generative Adversarial Networks\"<https://arxiv.org/abs/1611.04076>`_). Assumes, real label is 1 and fake label is 0",
"is fake. Fake --> D(G(z)) = d_of_fake = d_of_g_of_z Real --> D(I) =",
"floss).mean() / 2 def g_relativistic(d_of_real: torch.Tensor, d_of_fake: torch.Tensor, invert_labels: bool = False): r\"\"\"Relativistic",
"assert isinstance(d_of_real, torch.Tensor) assert isinstance(d_of_fake, torch.Tensor) assert isinstance(invert_labels, bool) if invert_labels: rloss =",
"for generator. (`\"Generative Adversarial Nets\" <https://papers.nips.cc/paper/5423-generative-adversarial-nets.pdf>`_). Assumes, real label is 1 and fake",
"of real. d_of_fake (torch.Tensor, required): discriminator output of fake. invert_labels (bool, optional): Inverts",
"(bool, optional): Inverts real and fake labels to 0 and 1 respectively (default:",
"2 def g_least_squares(d_of_fake: torch.Tensor, invert_labels: bool = False): r\"\"\"Least squares loss for generator.",
"of fake. invert_labels (bool, optional): Inverts real and fake labels to 0 and",
"loss = (1 - σ( d_of_fake ))^2 Args: d_of_fake (torch.Tensor, required): discriminator output",
"return (rloss + floss).mean() / 2 def g_relativistic(d_of_real: torch.Tensor, d_of_fake: torch.Tensor, invert_labels: bool",
"to flip real and fake labels). d_of_fake = D(G(z)). loss = - log(σ(",
"(rloss + floss).mean() / 2 def g_relativistic(d_of_real: torch.Tensor, d_of_fake: torch.Tensor, invert_labels: bool =",
"invert_labels: return - (dra_rf.log() + (1 - dra_fr).log()).mean() return - ((1 - dra_rf).log()",
"d_of_real.sigmoid()).clamp(eps).log() floss = - d_of_fake.sigmoid().clamp(eps).log() else: rloss = - d_of_real.sigmoid().clamp(eps).log() floss = -",
"isinstance(invert_labels, bool) dra_rf = (d_of_real - d_of_fake.mean()).sigmoid().clamp(eps) dra_fr = (d_of_fake - d_of_real.mean()).sigmoid().clamp(eps) if",
"return - d_of_fake.sigmoid().clamp(eps).log().mean() def d_minimax(d_of_real: torch.Tensor, d_of_fake: torch.Tensor, invert_labels: bool = False): r\"\"\"Minimax",
"assert isinstance(invert_labels, bool) if invert_labels: return - (d_of_fake - d_of_real.mean()).sigmoid().clamp(eps).log() return - (1",
"rloss = - (1 - d_of_real.sigmoid()).clamp(eps).log() floss = - d_of_fake.sigmoid().clamp(eps).log() else: rloss =",
"0 and 1 respectively (default: :obj:`\"False\"`). \"\"\" assert isinstance(d_of_real, torch.Tensor) assert isinstance(d_of_fake, torch.Tensor)",
"floss = (1 - d_of_fake.sigmoid()).pow(2) else: rloss = (1 - d_of_real.sigmoid()).pow(2) floss =",
"torch.Tensor, invert_labels: bool = False): r\"\"\"Least squares loss for generator. (`\"Least Squares Generative",
"torch.Tensor) assert isinstance(invert_labels, bool) if invert_labels: return - (1 - d_of_fake.sigmoid()).clamp(eps).log().mean() return -",
"Paper: Generative Adversarial Nets # URL: https://arxiv.org/abs/1406.2661 g_minimax = g_minimax d_minimax = d_minimax",
"https://arxiv.org/abs/1406.2661 g_minimax = g_minimax d_minimax = d_minimax # Paper: Least Squares Generative Adversarial",
"respectively (default: :obj:`\"False\"`). \"\"\" assert isinstance(d_of_real, torch.Tensor) assert isinstance(d_of_fake, torch.Tensor) assert isinstance(invert_labels, bool)",
"squares loss for generator. (`\"Least Squares Generative Adversarial Networks\"<https://arxiv.org/abs/1611.04076>`_). Assumes, real label is",
"d_least_squares(d_of_real: torch.Tensor, d_of_fake: torch.Tensor, invert_labels: bool = False): r\"\"\"Least squares loss for generator.",
"invert_labels: return d_of_fake.sigmoid().pow(2).mean() return (1 - d_of_fake.sigmoid()).pow(2).mean() def d_least_squares(d_of_real: torch.Tensor, d_of_fake: torch.Tensor, invert_labels:",
"discriminator. (`\"Generative Adversarial Nets\" <https://papers.nips.cc/paper/5423-generative-adversarial-nets.pdf>`_). Assumes, real label is 1 and fake label",
"= g_minimax d_minimax = d_minimax # Paper: Least Squares Generative Adversarial Networks #",
"d_of_fake )) Args: d_of_fake (torch.Tensor, required): discriminator output of fake. invert_labels (bool, optional):",
":obj:`\"False\"`). \"\"\" assert isinstance(d_of_fake, torch.Tensor) assert isinstance(invert_labels, bool) if invert_labels: return - (1",
"invert_labels: rloss = - (1 - d_of_real.sigmoid()).clamp(eps).log() floss = - d_of_fake.sigmoid().clamp(eps).log() else: rloss",
"- σ( d_of_fake )) Args: d_of_real (torch.Tensor, required): discriminator output of real. d_of_fake",
"D(G(z)) and d_of_real = D(I). loss = - log(1 - σ(d_of_fake - E[d_of_real]))",
"real and fake labels to 0 and 1 respectively (default: :obj:`\"False\"`). \"\"\" assert",
"= g_least_squares d_least_squares = d_least_squares # Paper: The relativistic discriminatorr: a key element",
"invert_labels: bool = False): r\"\"\"Least squares loss for generator. (`\"Least Squares Generative Adversarial",
"+ floss).mean() / 2 def g_least_squares(d_of_fake: torch.Tensor, invert_labels: bool = False): r\"\"\"Least squares",
"d_of_real \"\"\" # Paper: Generative Adversarial Nets # URL: https://arxiv.org/abs/1406.2661 g_minimax = g_minimax",
"flip real and fake labels). d_of_fake = D(G(z)). loss = (1 - σ(",
"g_least_squares d_least_squares = d_least_squares # Paper: The relativistic discriminatorr: a key element missing",
"assert isinstance(invert_labels, bool) if invert_labels: return - (1 - d_of_fake.sigmoid()).clamp(eps).log().mean() return - d_of_fake.sigmoid().clamp(eps).log().mean()",
"np.finfo(float).eps def g_minimax(d_of_fake: torch.Tensor, invert_labels: bool = False): r\"\"\"Minimax loss for generator. (`\"Generative",
"log(1 - σ(d_of_real - E[d_of_fake])) - log(σ(d_of_fake - E[d_of_real])) Args: d_of_real (torch.Tensor, required):",
"= d_of_real.sigmoid().pow(2) floss = (1 - d_of_fake.sigmoid()).pow(2) else: rloss = (1 - d_of_real.sigmoid()).pow(2)",
"loss = - log(1 - σ(d_of_real - E[d_of_fake])) - log(σ(d_of_fake - E[d_of_real])) Args:",
"floss = - (1 - d_of_fake.sigmoid()).clamp(eps).log() return (rloss + floss).mean() / 2 def",
"- d_of_fake.sigmoid()).clamp(eps).log().mean() return - d_of_fake.sigmoid().clamp(eps).log().mean() def d_minimax(d_of_real: torch.Tensor, d_of_fake: torch.Tensor, invert_labels: bool =",
"labels). d_of_fake = D(G(z)) and d_of_real = D(I). loss = - log(σ( d_of_real",
"Generative Adversarial Nets # URL: https://arxiv.org/abs/1406.2661 g_minimax = g_minimax d_minimax = d_minimax #",
"fake labels). d_of_fake = D(G(z)) and d_of_real = D(I). loss = - log(σ(",
"g_least_squares(d_of_fake: torch.Tensor, invert_labels: bool = False): r\"\"\"Least squares loss for generator. (`\"Least Squares",
"- d_of_real.mean()).sigmoid().clamp(eps).log() return - (1 - (d_of_fake - d_of_real.mean()).sigmoid()).clamp(eps).log() def d_relativistic(d_of_real: torch.Tensor, d_of_fake:",
":obj:`\"False\"`). \"\"\" assert isinstance(d_of_real, torch.Tensor) assert isinstance(d_of_fake, torch.Tensor) assert isinstance(invert_labels, bool) if invert_labels:",
"d_of_fake.sigmoid()).clamp(eps).log().mean() return - d_of_fake.sigmoid().clamp(eps).log().mean() def d_minimax(d_of_real: torch.Tensor, d_of_fake: torch.Tensor, invert_labels: bool = False):",
"(d_of_fake - d_of_real.mean()).sigmoid().clamp(eps).log() return - (1 - (d_of_fake - d_of_real.mean()).sigmoid()).clamp(eps).log() def d_relativistic(d_of_real: torch.Tensor,",
"Fake --> D(G(z)) = d_of_fake = d_of_g_of_z Real --> D(I) = d_of_real \"\"\"",
"and fake labels). d_of_fake = D(G(z)) and d_of_real = D(I). loss = ((1",
"1 respectively (default: :obj:`\"False\"`). \"\"\" assert isinstance(d_of_real, torch.Tensor) assert isinstance(d_of_fake, torch.Tensor) assert isinstance(invert_labels,",
"key element missing from standard GAN\"<https://arxiv.org/abs/1807.00734>`_ ). Assumes, real label is 1 and",
"fake labels). d_of_fake = D(G(z)) and d_of_real = D(I). loss = - log(1",
"isinstance(invert_labels, bool) if invert_labels: return d_of_fake.sigmoid().pow(2).mean() return (1 - d_of_fake.sigmoid()).pow(2).mean() def d_least_squares(d_of_real: torch.Tensor,",
"d_of_fake = D(G(z)) and d_of_real = D(I). loss = - log(σ( d_of_real ))",
"torch.Tensor) assert isinstance(d_of_fake, torch.Tensor) assert isinstance(invert_labels, bool) if invert_labels: return - (d_of_fake -",
"Assumes, real label is 1 and fake label is 0 (use invert_labels to",
"eps = np.finfo(float).eps def g_minimax(d_of_fake: torch.Tensor, invert_labels: bool = False): r\"\"\"Minimax loss for",
"= False): r\"\"\"Minimax loss for discriminator. (`\"Generative Adversarial Nets\" <https://papers.nips.cc/paper/5423-generative-adversarial-nets.pdf>`_). Assumes, real label",
"invert_labels: rloss = d_of_real.sigmoid().pow(2) floss = (1 - d_of_fake.sigmoid()).pow(2) else: rloss = (1",
"isinstance(d_of_fake, torch.Tensor) assert isinstance(invert_labels, bool) if invert_labels: return - (d_of_fake - d_of_real.mean()).sigmoid().clamp(eps).log() return",
"- (d_of_fake - d_of_real.mean()).sigmoid()).clamp(eps).log() def d_relativistic(d_of_real: torch.Tensor, d_of_fake: torch.Tensor, invert_labels: bool = False):",
"(1 - (d_of_fake - d_of_real.mean()).sigmoid()).clamp(eps).log() def d_relativistic(d_of_real: torch.Tensor, d_of_fake: torch.Tensor, invert_labels: bool =",
"1 and fake label is 0 (use invert_labels to flip real and fake",
"labels). d_of_fake = D(G(z)). loss = - log(σ( d_of_fake )) Args: d_of_fake (torch.Tensor,",
"a key element missing from # standard GAN # URL: https://arxiv.org/pdf/1807.00734.pdf g_relativistic =",
"Least Squares Generative Adversarial Networks # URL: https://arxiv.org/abs/1611.04076 g_least_squares = g_least_squares d_least_squares =",
"isinstance(invert_labels, bool) if invert_labels: rloss = d_of_real.sigmoid().pow(2) floss = (1 - d_of_fake.sigmoid()).pow(2) else:",
")) Args: d_of_real (torch.Tensor, required): discriminator output of real. d_of_fake (torch.Tensor, required): discriminator",
"https://arxiv.org/abs/1611.04076 g_least_squares = g_least_squares d_least_squares = d_least_squares # Paper: The relativistic discriminatorr: a",
"d_least_squares = d_least_squares # Paper: The relativistic discriminatorr: a key element missing from",
"r\"\"\"Least squares loss for generator. (`\"Least Squares Generative Adversarial Networks\"<https://arxiv.org/abs/1611.04076>`_). Assumes, real label",
"= - log(σ( d_of_fake )) Args: d_of_fake (torch.Tensor, required): discriminator output of fake.",
"d_of_fake.sigmoid().pow(2).mean() return (1 - d_of_fake.sigmoid()).pow(2).mean() def d_least_squares(d_of_real: torch.Tensor, d_of_fake: torch.Tensor, invert_labels: bool =",
"fake. Fake --> D(G(z)) = d_of_fake = d_of_g_of_z Real --> D(I) = d_of_real",
"- d_of_fake.sigmoid()).pow(2).mean() def d_least_squares(d_of_real: torch.Tensor, d_of_fake: torch.Tensor, invert_labels: bool = False): r\"\"\"Least squares",
"\"\"\"TensorMONK :: loss :: AdversarialLoss\"\"\" __all__ = [\"AdversarialLoss\"] import torch import numpy as",
"log(1 - σ( d_of_fake )) Args: d_of_real (torch.Tensor, required): discriminator output of real.",
"d_relativistic(d_of_real: torch.Tensor, d_of_fake: torch.Tensor, invert_labels: bool = False): r\"\"\"Relativistic loss for generator. (`\"The",
"- E[d_of_fake])) - log(σ(d_of_fake - E[d_of_real])) Args: d_of_real (torch.Tensor, required): discriminator output of",
"d_of_fake )^2) / 2 Args: d_of_real (torch.Tensor, required): discriminator output of real. d_of_fake",
"- (1 - d_of_fake.sigmoid()).clamp(eps).log() return (rloss + floss).mean() / 2 def g_least_squares(d_of_fake: torch.Tensor,",
"and 0 is fake. Fake --> D(G(z)) = d_of_fake = d_of_g_of_z Real -->",
"0 and 1 respectively (default: :obj:`\"False\"`). \"\"\" assert isinstance(d_of_fake, torch.Tensor) assert isinstance(invert_labels, bool)",
"torch.Tensor, d_of_fake: torch.Tensor, invert_labels: bool = False): r\"\"\"Relativistic loss for generator. (`\"The relativistic",
"d_of_fake: torch.Tensor, invert_labels: bool = False): r\"\"\"Relativistic loss for generator. (`\"The relativistic discriminator:",
"d_minimax = d_minimax # Paper: Least Squares Generative Adversarial Networks # URL: https://arxiv.org/abs/1611.04076",
":obj:`\"False\"`). \"\"\" assert isinstance(d_of_fake, torch.Tensor) assert isinstance(invert_labels, bool) if invert_labels: return d_of_fake.sigmoid().pow(2).mean() return",
"and d_of_real = D(I). loss = - log(σ( d_of_real )) - log(1 -",
"d_of_fake = D(G(z)) and d_of_real = D(I). loss = ((1 - σ( d_of_real",
"def d_least_squares(d_of_real: torch.Tensor, d_of_fake: torch.Tensor, invert_labels: bool = False): r\"\"\"Least squares loss for",
"E[d_of_real])) Args: d_of_real (torch.Tensor, required): discriminator output of real. d_of_fake (torch.Tensor, required): discriminator",
"isinstance(d_of_real, torch.Tensor) assert isinstance(d_of_fake, torch.Tensor) assert isinstance(invert_labels, bool) if invert_labels: rloss = -",
"isinstance(d_of_fake, torch.Tensor) assert isinstance(invert_labels, bool) if invert_labels: rloss = - (1 - d_of_real.sigmoid()).clamp(eps).log()",
"= - (1 - d_of_real.sigmoid()).clamp(eps).log() floss = - d_of_fake.sigmoid().clamp(eps).log() else: rloss = -",
"= D(I). loss = - log(1 - σ(d_of_real - E[d_of_fake])) - log(σ(d_of_fake -",
"The relativistic discriminatorr: a key element missing from # standard GAN # URL:",
"and 1 respectively (default: :obj:`\"False\"`). \"\"\" assert isinstance(d_of_fake, torch.Tensor) assert isinstance(invert_labels, bool) if",
"- (1 - (d_of_fake - d_of_real.mean()).sigmoid()).clamp(eps).log() def d_relativistic(d_of_real: torch.Tensor, d_of_fake: torch.Tensor, invert_labels: bool",
"isinstance(d_of_fake, torch.Tensor) assert isinstance(invert_labels, bool) if invert_labels: return - (1 - d_of_fake.sigmoid()).clamp(eps).log().mean() return",
"AdversarialLoss\"\"\" __all__ = [\"AdversarialLoss\"] import torch import numpy as np eps = np.finfo(float).eps",
"- log(1 - σ(d_of_fake - E[d_of_real])) Args: d_of_real (torch.Tensor, required): discriminator output of",
"as np eps = np.finfo(float).eps def g_minimax(d_of_fake: torch.Tensor, invert_labels: bool = False): r\"\"\"Minimax",
"Nets # URL: https://arxiv.org/abs/1406.2661 g_minimax = g_minimax d_minimax = d_minimax # Paper: Least",
"URL: https://arxiv.org/abs/1611.04076 g_least_squares = g_least_squares d_least_squares = d_least_squares # Paper: The relativistic discriminatorr:",
":: AdversarialLoss\"\"\" __all__ = [\"AdversarialLoss\"] import torch import numpy as np eps =",
"output of real. d_of_fake (torch.Tensor, required): discriminator output of fake. invert_labels (bool, optional):",
"loss = - log(σ( d_of_fake )) Args: d_of_fake (torch.Tensor, required): discriminator output of",
"D(I). loss = ((1 - σ( d_of_real ))^2 + σ( d_of_fake )^2) /",
"d_of_fake.sigmoid().clamp(eps).log() else: rloss = - d_of_real.sigmoid().clamp(eps).log() floss = - (1 - d_of_fake.sigmoid()).clamp(eps).log() return",
"torch.Tensor, d_of_fake: torch.Tensor, invert_labels: bool = False): r\"\"\"Least squares loss for generator. (`\"Least",
"σ( d_of_fake )) Args: d_of_real (torch.Tensor, required): discriminator output of real. d_of_fake (torch.Tensor,",
"invert_labels to flip real and fake labels). d_of_fake = D(G(z)) and d_of_real =",
"(default: :obj:`\"False\"`). \"\"\" assert isinstance(d_of_fake, torch.Tensor) assert isinstance(invert_labels, bool) if invert_labels: return d_of_fake.sigmoid().pow(2).mean()",
"torch.Tensor) assert isinstance(invert_labels, bool) if invert_labels: rloss = - (1 - d_of_real.sigmoid()).clamp(eps).log() floss",
"AdversarialLoss: r\"\"\"Adversarial losses. Assumes 1 is real and 0 is fake. Fake -->",
"(use invert_labels to flip real and fake labels). d_of_fake = D(G(z)). loss =",
"dra_fr.log()).mean() class AdversarialLoss: r\"\"\"Adversarial losses. Assumes 1 is real and 0 is fake.",
"= d_of_fake.sigmoid().pow(2) return (rloss + floss).mean() / 2 def g_relativistic(d_of_real: torch.Tensor, d_of_fake: torch.Tensor,",
"d_of_fake (torch.Tensor, required): discriminator output of fake. invert_labels (bool, optional): Inverts real and",
"loss for generator. (`\"The relativistic discriminator: a key element missing from standard GAN\"<https://arxiv.org/abs/1807.00734>`_",
"and fake labels to 0 and 1 respectively (default: :obj:`\"False\"`). \"\"\" assert isinstance(d_of_fake,",
"# URL: https://arxiv.org/abs/1406.2661 g_minimax = g_minimax d_minimax = d_minimax # Paper: Least Squares",
"- (1 - d_of_real.sigmoid()).clamp(eps).log() floss = - d_of_fake.sigmoid().clamp(eps).log() else: rloss = - d_of_real.sigmoid().clamp(eps).log()",
"(use invert_labels to flip real and fake labels). d_of_fake = D(G(z)) and d_of_real",
"g_least_squares = g_least_squares d_least_squares = d_least_squares # Paper: The relativistic discriminatorr: a key",
"else: rloss = - d_of_real.sigmoid().clamp(eps).log() floss = - (1 - d_of_fake.sigmoid()).clamp(eps).log() return (rloss",
"relativistic discriminator: a key element missing from standard GAN\"<https://arxiv.org/abs/1807.00734>`_ ). Assumes, real label",
"d_of_fake = D(G(z)). loss = - log(σ( d_of_fake )) Args: d_of_fake (torch.Tensor, required):",
"D(I). loss = - log(1 - σ(d_of_fake - E[d_of_real])) Args: d_of_real (torch.Tensor, required):",
":obj:`\"False\"`). \"\"\" assert isinstance(d_of_real, torch.Tensor) assert isinstance(d_of_fake, torch.Tensor) assert isinstance(invert_labels, bool) dra_rf =",
"- dra_rf).log() + dra_fr.log()).mean() class AdversarialLoss: r\"\"\"Adversarial losses. Assumes 1 is real and",
"D(G(z)). loss = (1 - σ( d_of_fake ))^2 Args: d_of_fake (torch.Tensor, required): discriminator",
"bool = False): r\"\"\"Least squares loss for generator. (`\"Least Squares Generative Adversarial Networks\"<https://arxiv.org/abs/1611.04076>`_).",
"g_minimax = g_minimax d_minimax = d_minimax # Paper: Least Squares Generative Adversarial Networks",
"0 is fake. Fake --> D(G(z)) = d_of_fake = d_of_g_of_z Real --> D(I)",
"assert isinstance(invert_labels, bool) dra_rf = (d_of_real - d_of_fake.mean()).sigmoid().clamp(eps) dra_fr = (d_of_fake - d_of_real.mean()).sigmoid().clamp(eps)",
"# Paper: Least Squares Generative Adversarial Networks # URL: https://arxiv.org/abs/1611.04076 g_least_squares = g_least_squares",
")) Args: d_of_fake (torch.Tensor, required): discriminator output of fake. invert_labels (bool, optional): Inverts",
"d_of_real.sigmoid().clamp(eps).log() floss = - (1 - d_of_fake.sigmoid()).clamp(eps).log() return (rloss + floss).mean() / 2",
"(d_of_fake - d_of_real.mean()).sigmoid()).clamp(eps).log() def d_relativistic(d_of_real: torch.Tensor, d_of_fake: torch.Tensor, invert_labels: bool = False): r\"\"\"Relativistic",
"d_of_real.mean()).sigmoid().clamp(eps) if invert_labels: return - (dra_rf.log() + (1 - dra_fr).log()).mean() return - ((1",
"numpy as np eps = np.finfo(float).eps def g_minimax(d_of_fake: torch.Tensor, invert_labels: bool = False):",
"loss = ((1 - σ( d_of_real ))^2 + σ( d_of_fake )^2) / 2",
"= d_least_squares # Paper: The relativistic discriminatorr: a key element missing from #",
"assert isinstance(invert_labels, bool) if invert_labels: return d_of_fake.sigmoid().pow(2).mean() return (1 - d_of_fake.sigmoid()).pow(2).mean() def d_least_squares(d_of_real:",
"((1 - dra_rf).log() + dra_fr.log()).mean() class AdversarialLoss: r\"\"\"Adversarial losses. Assumes 1 is real",
"loss for generator. (`\"Least Squares Generative Adversarial Networks\"<https://arxiv.org/abs/1611.04076>`_). Assumes, real label is 1",
"torch import numpy as np eps = np.finfo(float).eps def g_minimax(d_of_fake: torch.Tensor, invert_labels: bool",
"loss :: AdversarialLoss\"\"\" __all__ = [\"AdversarialLoss\"] import torch import numpy as np eps",
"(1 - d_of_real.sigmoid()).pow(2) floss = d_of_fake.sigmoid().pow(2) return (rloss + floss).mean() / 2 def",
"σ( d_of_fake ))^2 Args: d_of_fake (torch.Tensor, required): discriminator output of fake. invert_labels (bool,",
"floss = - d_of_fake.sigmoid().clamp(eps).log() else: rloss = - d_of_real.sigmoid().clamp(eps).log() floss = - (1",
"torch.Tensor) assert isinstance(d_of_fake, torch.Tensor) assert isinstance(invert_labels, bool) if invert_labels: rloss = - (1",
"real and fake labels). d_of_fake = D(G(z)). loss = - log(σ( d_of_fake ))",
"d_of_real )) - log(1 - σ( d_of_fake )) Args: d_of_real (torch.Tensor, required): discriminator",
"d_of_real = D(I). loss = ((1 - σ( d_of_real ))^2 + σ( d_of_fake",
"dra_rf = (d_of_real - d_of_fake.mean()).sigmoid().clamp(eps) dra_fr = (d_of_fake - d_of_real.mean()).sigmoid().clamp(eps) if invert_labels: return",
"return - (1 - (d_of_fake - d_of_real.mean()).sigmoid()).clamp(eps).log() def d_relativistic(d_of_real: torch.Tensor, d_of_fake: torch.Tensor, invert_labels:",
"bool = False): r\"\"\"Relativistic loss for generator. (`\"The relativistic discriminator: a key element",
"bool) dra_rf = (d_of_real - d_of_fake.mean()).sigmoid().clamp(eps) dra_fr = (d_of_fake - d_of_real.mean()).sigmoid().clamp(eps) if invert_labels:",
"log(1 - σ(d_of_fake - E[d_of_real])) Args: d_of_real (torch.Tensor, required): discriminator output of real.",
"= D(G(z)) and d_of_real = D(I). loss = ((1 - σ( d_of_real ))^2",
"Generative Adversarial Networks # URL: https://arxiv.org/abs/1611.04076 g_least_squares = g_least_squares d_least_squares = d_least_squares #",
"- d_of_fake.mean()).sigmoid().clamp(eps) dra_fr = (d_of_fake - d_of_real.mean()).sigmoid().clamp(eps) if invert_labels: return - (dra_rf.log() +",
"- d_of_real.sigmoid()).clamp(eps).log() floss = - d_of_fake.sigmoid().clamp(eps).log() else: rloss = - d_of_real.sigmoid().clamp(eps).log() floss =",
"D(I). loss = - log(1 - σ(d_of_real - E[d_of_fake])) - log(σ(d_of_fake - E[d_of_real]))",
"torch.Tensor, invert_labels: bool = False): r\"\"\"Minimax loss for generator. (`\"Generative Adversarial Nets\" <https://papers.nips.cc/paper/5423-generative-adversarial-nets.pdf>`_).",
"d_of_real (torch.Tensor, required): discriminator output of real. d_of_fake (torch.Tensor, required): discriminator output of",
"<https://papers.nips.cc/paper/5423-generative-adversarial-nets.pdf>`_). Assumes, real label is 1 and fake label is 0 (use invert_labels",
"and fake labels). d_of_fake = D(G(z)). loss = - log(σ( d_of_fake )) Args:",
"= (1 - d_of_real.sigmoid()).pow(2) floss = d_of_fake.sigmoid().pow(2) return (rloss + floss).mean() / 2",
"optional): Inverts real and fake labels to 0 and 1 respectively (default: :obj:`\"False\"`).",
"element missing from standard GAN\"<https://arxiv.org/abs/1807.00734>`_ ). Assumes, real label is 1 and fake",
"isinstance(d_of_fake, torch.Tensor) assert isinstance(invert_labels, bool) dra_rf = (d_of_real - d_of_fake.mean()).sigmoid().clamp(eps) dra_fr = (d_of_fake",
"to flip real and fake labels). d_of_fake = D(G(z)). loss = (1 -",
"def d_relativistic(d_of_real: torch.Tensor, d_of_fake: torch.Tensor, invert_labels: bool = False): r\"\"\"Relativistic loss for generator.",
"= d_of_g_of_z Real --> D(I) = d_of_real \"\"\" # Paper: Generative Adversarial Nets",
"[\"AdversarialLoss\"] import torch import numpy as np eps = np.finfo(float).eps def g_minimax(d_of_fake: torch.Tensor,",
"/ 2 def g_least_squares(d_of_fake: torch.Tensor, invert_labels: bool = False): r\"\"\"Least squares loss for",
"real and fake labels). d_of_fake = D(G(z)). loss = (1 - σ( d_of_fake",
")^2) / 2 Args: d_of_real (torch.Tensor, required): discriminator output of real. d_of_fake (torch.Tensor,",
"torch.Tensor) assert isinstance(invert_labels, bool) if invert_labels: rloss = d_of_real.sigmoid().pow(2) floss = (1 -",
"(`\"Generative Adversarial Nets\" <https://papers.nips.cc/paper/5423-generative-adversarial-nets.pdf>`_). Assumes, real label is 1 and fake label is",
"2 def g_relativistic(d_of_real: torch.Tensor, d_of_fake: torch.Tensor, invert_labels: bool = False): r\"\"\"Relativistic loss for",
"\"\"\" assert isinstance(d_of_real, torch.Tensor) assert isinstance(d_of_fake, torch.Tensor) assert isinstance(invert_labels, bool) if invert_labels: rloss",
"Args: d_of_fake (torch.Tensor, required): discriminator output of fake. invert_labels (bool, optional): Inverts real",
"discriminator: a key element missing from standard GAN\"<https://arxiv.org/abs/1807.00734>`_ ). Assumes, real label is",
"- d_of_real.mean()).sigmoid()).clamp(eps).log() def d_relativistic(d_of_real: torch.Tensor, d_of_fake: torch.Tensor, invert_labels: bool = False): r\"\"\"Relativistic loss",
"invert_labels: bool = False): r\"\"\"Minimax loss for generator. (`\"Generative Adversarial Nets\" <https://papers.nips.cc/paper/5423-generative-adversarial-nets.pdf>`_). Assumes,",
"d_of_fake )) Args: d_of_real (torch.Tensor, required): discriminator output of real. d_of_fake (torch.Tensor, required):",
"Adversarial Networks\"<https://arxiv.org/abs/1611.04076>`_). Assumes, real label is 1 and fake label is 0 (use",
"log(σ( d_of_real )) - log(1 - σ( d_of_fake )) Args: d_of_real (torch.Tensor, required):",
"and 1 respectively (default: :obj:`\"False\"`). \"\"\" assert isinstance(d_of_real, torch.Tensor) assert isinstance(d_of_fake, torch.Tensor) assert",
"and d_of_real = D(I). loss = ((1 - σ( d_of_real ))^2 + σ(",
"required): discriminator output of real. d_of_fake (torch.Tensor, required): discriminator output of fake. invert_labels",
"if invert_labels: rloss = d_of_real.sigmoid().pow(2) floss = (1 - d_of_fake.sigmoid()).pow(2) else: rloss =",
"). Assumes, real label is 1 and fake label is 0 (use invert_labels",
"d_of_real.sigmoid().pow(2) floss = (1 - d_of_fake.sigmoid()).pow(2) else: rloss = (1 - d_of_real.sigmoid()).pow(2) floss",
"and fake labels to 0 and 1 respectively (default: :obj:`\"False\"`). \"\"\" assert isinstance(d_of_real,",
"r\"\"\"Adversarial losses. Assumes 1 is real and 0 is fake. Fake --> D(G(z))",
"D(G(z)) and d_of_real = D(I). loss = - log(σ( d_of_real )) - log(1",
"False): r\"\"\"Minimax loss for discriminator. (`\"Generative Adversarial Nets\" <https://papers.nips.cc/paper/5423-generative-adversarial-nets.pdf>`_). Assumes, real label is",
"floss).mean() / 2 def g_least_squares(d_of_fake: torch.Tensor, invert_labels: bool = False): r\"\"\"Least squares loss",
"labels to 0 and 1 respectively (default: :obj:`\"False\"`). \"\"\" assert isinstance(d_of_real, torch.Tensor) assert",
"rloss = - d_of_real.sigmoid().clamp(eps).log() floss = - (1 - d_of_fake.sigmoid()).clamp(eps).log() return (rloss +",
"and fake labels). d_of_fake = D(G(z)) and d_of_real = D(I). loss = -",
"real. d_of_fake (torch.Tensor, required): discriminator output of fake. invert_labels (bool, optional): Inverts real",
"+ dra_fr.log()).mean() class AdversarialLoss: r\"\"\"Adversarial losses. Assumes 1 is real and 0 is",
"d_of_fake.sigmoid()).clamp(eps).log() return (rloss + floss).mean() / 2 def g_least_squares(d_of_fake: torch.Tensor, invert_labels: bool =",
"assert isinstance(invert_labels, bool) if invert_labels: rloss = d_of_real.sigmoid().pow(2) floss = (1 - d_of_fake.sigmoid()).pow(2)",
"torch.Tensor) assert isinstance(invert_labels, bool) if invert_labels: return - (d_of_fake - d_of_real.mean()).sigmoid().clamp(eps).log() return -",
"np eps = np.finfo(float).eps def g_minimax(d_of_fake: torch.Tensor, invert_labels: bool = False): r\"\"\"Minimax loss",
"= (d_of_real - d_of_fake.mean()).sigmoid().clamp(eps) dra_fr = (d_of_fake - d_of_real.mean()).sigmoid().clamp(eps) if invert_labels: return -",
"return (1 - d_of_fake.sigmoid()).pow(2).mean() def d_least_squares(d_of_real: torch.Tensor, d_of_fake: torch.Tensor, invert_labels: bool = False):",
"torch.Tensor) assert isinstance(invert_labels, bool) dra_rf = (d_of_real - d_of_fake.mean()).sigmoid().clamp(eps) dra_fr = (d_of_fake -",
"(default: :obj:`\"False\"`). \"\"\" assert isinstance(d_of_fake, torch.Tensor) assert isinstance(invert_labels, bool) if invert_labels: return -",
"- ((1 - dra_rf).log() + dra_fr.log()).mean() class AdversarialLoss: r\"\"\"Adversarial losses. Assumes 1 is",
"(1 - d_of_real.sigmoid()).clamp(eps).log() floss = - d_of_fake.sigmoid().clamp(eps).log() else: rloss = - d_of_real.sigmoid().clamp(eps).log() floss",
"flip real and fake labels). d_of_fake = D(G(z)). loss = - log(σ( d_of_fake",
"= False): r\"\"\"Relativistic loss for generator. (`\"The relativistic discriminator: a key element missing",
"= - d_of_real.sigmoid().clamp(eps).log() floss = - (1 - d_of_fake.sigmoid()).clamp(eps).log() return (rloss + floss).mean()",
"__all__ = [\"AdversarialLoss\"] import torch import numpy as np eps = np.finfo(float).eps def"
] |
[
"interpreter window. \"\"\" if image: self.mat_plot_2d.plot_array( array=self.fit.data, visuals_2d=self.visuals_with_include_2d, auto_labels=mp.AutoLabels(title=\"Image\", filename=\"image_2d\"), ) if noise_map:",
"visuals_2d=self.visuals_with_include_2d, auto_labels=mp.AutoLabels( title=\"Signal-To-Noise Map\", filename=\"signal_to_noise_map\" ), ) if model_image: self.mat_plot_2d.plot_array( array=self.fit.model_data, visuals_2d=self.visuals_with_include_2d, auto_labels=mp.AutoLabels(title=\"Model",
"the data is output if the output_type is a file format (e.g. png,",
") if noise_map: self.mat_plot_2d.plot_array( array=self.fit.noise_map, visuals_2d=self.visuals_with_include_2d, auto_labels=mp.AutoLabels(title=\"Noise-Map\", filename=\"noise_map\"), ) if signal_to_noise_map: self.mat_plot_2d.plot_array( array=self.fit.signal_to_noise_map,",
"data is output. File formats (e.g. png, fits) output the data to harddisk.",
"), mask=self.extract_2d(\"mask\", self.fit.mask), border=self.extract_2d(\"border\", self.fit.mask.border_grid_sub_1.binned), ) def figures_2d( self, image=False, noise_map=False, signal_to_noise_map=False, model_image=False,",
"include as inc from autoarray.plot.mat_wrap import mat_plot as mp from autoarray.fit import fit",
"origin=self.extract_2d( \"origin\", grid_2d_irregular.Grid2DIrregular(grid=[self.fit.mask.origin]) ), mask=self.extract_2d(\"mask\", self.fit.mask), border=self.extract_2d(\"border\", self.fit.mask.border_grid_sub_1.binned), ) def figures_2d( self, image=False,",
"png, fits) output_format : str How the data is output. File formats (e.g.",
"grid_2d_irregular class AbstractFitImagingPlotter(abstract_plotters.AbstractPlotter): def __init__(self, fit, mat_plot_2d, visuals_2d, include_2d): super().__init__( mat_plot_2d=mat_plot_2d, include_2d=include_2d, visuals_2d=visuals_2d",
"import visuals as vis from autoarray.plot.mat_wrap import include as inc from autoarray.plot.mat_wrap import",
"border=self.extract_2d(\"border\", self.fit.mask.border_grid_sub_1.binned), ) def figures_2d( self, image=False, noise_map=False, signal_to_noise_map=False, model_image=False, residual_map=False, normalized_residual_map=False, chi_squared_map=False,",
"visualization and output type can be fully customized. Parameters ----------- fit : autolens.lens.fitting.Fitter",
"can be fully customized. Parameters ----------- fit : autolens.lens.fitting.Fitter Class containing fit between",
"residual_map, chi_squared_map etc.) output_path : str The path where the data is output",
"a file format (e.g. png, fits) output_format : str How the data is",
"auto_labels=mp.AutoLabels( title=\"Normalized Residual Map\", filename=\"normalized_residual_map\" ), ) if chi_squared_map: self.mat_plot_2d.plot_array( array=self.fit.chi_squared_map, visuals_2d=self.visuals_with_include_2d, auto_labels=mp.AutoLabels(",
"signal_to_noise_map=False, model_image=False, residual_map=False, normalized_residual_map=False, chi_squared_map=False, auto_filename=\"subplot_fit_imaging\", ): self._subplot_custom_plot( image=image, noise_map=noise_map, signal_to_noise_map=signal_to_noise_map, model_image=model_image, residual_map=residual_map,",
"fits) output the data to harddisk. 'show' displays the data \\ in the",
"chi_squared_map=chi_squared_map, auto_labels=mp.AutoLabels(filename=auto_filename), ) def subplot_fit_imaging(self): return self.subplot( image=True, signal_to_noise_map=True, model_image=True, residual_map=True, normalized_residual_map=True, chi_squared_map=True,",
"filename=\"model_image\"), ) if residual_map: self.mat_plot_2d.plot_array( array=self.fit.residual_map, visuals_2d=self.visuals_with_include_2d, auto_labels=mp.AutoLabels( title=\"Residual Map\", filename=\"residual_map\" ), )",
"f.FitImaging, mat_plot_2d: mp.MatPlot2D = mp.MatPlot2D(), visuals_2d: vis.Visuals2D = vis.Visuals2D(), include_2d: inc.Include2D = inc.Include2D(),",
"filename=\"noise_map\"), ) if signal_to_noise_map: self.mat_plot_2d.plot_array( array=self.fit.signal_to_noise_map, visuals_2d=self.visuals_with_include_2d, auto_labels=mp.AutoLabels( title=\"Signal-To-Noise Map\", filename=\"signal_to_noise_map\" ), )",
"vis.Visuals2D = vis.Visuals2D(), include_2d: inc.Include2D = inc.Include2D(), ): super().__init__( fit=fit, mat_plot_2d=mat_plot_2d, include_2d=include_2d, visuals_2d=visuals_2d,",
") self.fit = fit @property def visuals_with_include_2d(self): return self.visuals_2d + self.visuals_2d.__class__( origin=self.extract_2d( \"origin\",",
"How the data is output. File formats (e.g. png, fits) output the data",
"the data is output. File formats (e.g. png, fits) output the data to",
"visuals as vis from autoarray.plot.mat_wrap import include as inc from autoarray.plot.mat_wrap import mat_plot",
"Map\", filename=\"signal_to_noise_map\" ), ) if model_image: self.mat_plot_2d.plot_array( array=self.fit.model_data, visuals_2d=self.visuals_with_include_2d, auto_labels=mp.AutoLabels(title=\"Model Image\", filename=\"model_image\"), )",
"Map\", filename=\"residual_map\" ), ) if normalized_residual_map: self.mat_plot_2d.plot_array( array=self.fit.normalized_residual_map, visuals_2d=self.visuals_with_include_2d, auto_labels=mp.AutoLabels( title=\"Normalized Residual Map\",",
"between the model data and observed lens data (including residual_map, chi_squared_map etc.) output_path",
"to harddisk. 'show' displays the data \\ in the python interpreter window. \"\"\"",
"Map\", filename=\"chi_squared_map\" ), ) def subplot( self, image=False, noise_map=False, signal_to_noise_map=False, model_image=False, residual_map=False, normalized_residual_map=False,",
"customized. Parameters ----------- fit : autolens.lens.fitting.Fitter Class containing fit between the model data",
"output_path : str The path where the data is output if the output_type",
"signal_to_noise_map=False, model_image=False, residual_map=False, normalized_residual_map=False, chi_squared_map=False, ): \"\"\"Plot the model data of an analysis,",
"from autoarray.plot.mat_wrap import mat_plot as mp from autoarray.fit import fit as f from",
"fit between the model data and observed lens data (including residual_map, chi_squared_map etc.)",
"etc.) output_path : str The path where the data is output if the",
"chi_squared_map=True, ) class FitImagingPlotter(AbstractFitImagingPlotter): def __init__( self, fit: f.FitImaging, mat_plot_2d: mp.MatPlot2D = mp.MatPlot2D(),",
"from autoarray.plot import abstract_plotters from autoarray.plot.mat_wrap import visuals as vis from autoarray.plot.mat_wrap import",
"(e.g. png, fits) output_format : str How the data is output. File formats",
"signal_to_noise_map=signal_to_noise_map, model_image=model_image, residual_map=residual_map, normalized_residual_map=normalized_residual_map, chi_squared_map=chi_squared_map, auto_labels=mp.AutoLabels(filename=auto_filename), ) def subplot_fit_imaging(self): return self.subplot( image=True, signal_to_noise_map=True,",
"mat_plot_2d: mp.MatPlot2D = mp.MatPlot2D(), visuals_2d: vis.Visuals2D = vis.Visuals2D(), include_2d: inc.Include2D = inc.Include2D(), ):",
"return self.visuals_2d + self.visuals_2d.__class__( origin=self.extract_2d( \"origin\", grid_2d_irregular.Grid2DIrregular(grid=[self.fit.mask.origin]) ), mask=self.extract_2d(\"mask\", self.fit.mask), border=self.extract_2d(\"border\", self.fit.mask.border_grid_sub_1.binned), )",
"array=self.fit.model_data, visuals_2d=self.visuals_with_include_2d, auto_labels=mp.AutoLabels(title=\"Model Image\", filename=\"model_image\"), ) if residual_map: self.mat_plot_2d.plot_array( array=self.fit.residual_map, visuals_2d=self.visuals_with_include_2d, auto_labels=mp.AutoLabels( title=\"Residual",
"Class containing fit between the model data and observed lens data (including residual_map,",
"\"origin\", grid_2d_irregular.Grid2DIrregular(grid=[self.fit.mask.origin]) ), mask=self.extract_2d(\"mask\", self.fit.mask), border=self.extract_2d(\"border\", self.fit.mask.border_grid_sub_1.binned), ) def figures_2d( self, image=False, noise_map=False,",
"analysis, using the *Fitter* class object. The visualization and output type can be",
"autoarray.fit import fit as f from autoarray.structures.grids.two_d import grid_2d_irregular class AbstractFitImagingPlotter(abstract_plotters.AbstractPlotter): def __init__(self,",
"<filename>autoarray/plot/fit_imaging_plotters.py from autoarray.plot import abstract_plotters from autoarray.plot.mat_wrap import visuals as vis from autoarray.plot.mat_wrap",
"the output_type is a file format (e.g. png, fits) output_format : str How",
"image=False, noise_map=False, signal_to_noise_map=False, model_image=False, residual_map=False, normalized_residual_map=False, chi_squared_map=False, auto_filename=\"subplot_fit_imaging\", ): self._subplot_custom_plot( image=image, noise_map=noise_map, signal_to_noise_map=signal_to_noise_map,",
"fit @property def visuals_with_include_2d(self): return self.visuals_2d + self.visuals_2d.__class__( origin=self.extract_2d( \"origin\", grid_2d_irregular.Grid2DIrregular(grid=[self.fit.mask.origin]) ), mask=self.extract_2d(\"mask\",",
"class object. The visualization and output type can be fully customized. Parameters -----------",
"auto_filename=\"subplot_fit_imaging\", ): self._subplot_custom_plot( image=image, noise_map=noise_map, signal_to_noise_map=signal_to_noise_map, model_image=model_image, residual_map=residual_map, normalized_residual_map=normalized_residual_map, chi_squared_map=chi_squared_map, auto_labels=mp.AutoLabels(filename=auto_filename), ) def",
"image=image, noise_map=noise_map, signal_to_noise_map=signal_to_noise_map, model_image=model_image, residual_map=residual_map, normalized_residual_map=normalized_residual_map, chi_squared_map=chi_squared_map, auto_labels=mp.AutoLabels(filename=auto_filename), ) def subplot_fit_imaging(self): return self.subplot(",
"self.mat_plot_2d.plot_array( array=self.fit.noise_map, visuals_2d=self.visuals_with_include_2d, auto_labels=mp.AutoLabels(title=\"Noise-Map\", filename=\"noise_map\"), ) if signal_to_noise_map: self.mat_plot_2d.plot_array( array=self.fit.signal_to_noise_map, visuals_2d=self.visuals_with_include_2d, auto_labels=mp.AutoLabels( title=\"Signal-To-Noise",
") def subplot_fit_imaging(self): return self.subplot( image=True, signal_to_noise_map=True, model_image=True, residual_map=True, normalized_residual_map=True, chi_squared_map=True, ) class",
"residual_map=True, normalized_residual_map=True, chi_squared_map=True, ) class FitImagingPlotter(AbstractFitImagingPlotter): def __init__( self, fit: f.FitImaging, mat_plot_2d: mp.MatPlot2D",
"import mat_plot as mp from autoarray.fit import fit as f from autoarray.structures.grids.two_d import",
"The visualization and output type can be fully customized. Parameters ----------- fit :",
"----------- fit : autolens.lens.fitting.Fitter Class containing fit between the model data and observed",
") if normalized_residual_map: self.mat_plot_2d.plot_array( array=self.fit.normalized_residual_map, visuals_2d=self.visuals_with_include_2d, auto_labels=mp.AutoLabels( title=\"Normalized Residual Map\", filename=\"normalized_residual_map\" ), )",
"fit as f from autoarray.structures.grids.two_d import grid_2d_irregular class AbstractFitImagingPlotter(abstract_plotters.AbstractPlotter): def __init__(self, fit, mat_plot_2d,",
"autoarray.plot.mat_wrap import mat_plot as mp from autoarray.fit import fit as f from autoarray.structures.grids.two_d",
"window. \"\"\" if image: self.mat_plot_2d.plot_array( array=self.fit.data, visuals_2d=self.visuals_with_include_2d, auto_labels=mp.AutoLabels(title=\"Image\", filename=\"image_2d\"), ) if noise_map: self.mat_plot_2d.plot_array(",
"): \"\"\"Plot the model data of an analysis, using the *Fitter* class object.",
"visuals_2d: vis.Visuals2D = vis.Visuals2D(), include_2d: inc.Include2D = inc.Include2D(), ): super().__init__( fit=fit, mat_plot_2d=mat_plot_2d, include_2d=include_2d,",
"visuals_2d=self.visuals_with_include_2d, auto_labels=mp.AutoLabels( title=\"Residual Map\", filename=\"residual_map\" ), ) if normalized_residual_map: self.mat_plot_2d.plot_array( array=self.fit.normalized_residual_map, visuals_2d=self.visuals_with_include_2d, auto_labels=mp.AutoLabels(",
"where the data is output if the output_type is a file format (e.g.",
"residual_map: self.mat_plot_2d.plot_array( array=self.fit.residual_map, visuals_2d=self.visuals_with_include_2d, auto_labels=mp.AutoLabels( title=\"Residual Map\", filename=\"residual_map\" ), ) if normalized_residual_map: self.mat_plot_2d.plot_array(",
"chi_squared_map=False, auto_filename=\"subplot_fit_imaging\", ): self._subplot_custom_plot( image=image, noise_map=noise_map, signal_to_noise_map=signal_to_noise_map, model_image=model_image, residual_map=residual_map, normalized_residual_map=normalized_residual_map, chi_squared_map=chi_squared_map, auto_labels=mp.AutoLabels(filename=auto_filename), )",
"def __init__(self, fit, mat_plot_2d, visuals_2d, include_2d): super().__init__( mat_plot_2d=mat_plot_2d, include_2d=include_2d, visuals_2d=visuals_2d ) self.fit =",
"mask=self.extract_2d(\"mask\", self.fit.mask), border=self.extract_2d(\"border\", self.fit.mask.border_grid_sub_1.binned), ) def figures_2d( self, image=False, noise_map=False, signal_to_noise_map=False, model_image=False, residual_map=False,",
"normalized_residual_map=False, chi_squared_map=False, ): \"\"\"Plot the model data of an analysis, using the *Fitter*",
"'show' displays the data \\ in the python interpreter window. \"\"\" if image:",
"filename=\"image_2d\"), ) if noise_map: self.mat_plot_2d.plot_array( array=self.fit.noise_map, visuals_2d=self.visuals_with_include_2d, auto_labels=mp.AutoLabels(title=\"Noise-Map\", filename=\"noise_map\"), ) if signal_to_noise_map: self.mat_plot_2d.plot_array(",
"self.mat_plot_2d.plot_array( array=self.fit.normalized_residual_map, visuals_2d=self.visuals_with_include_2d, auto_labels=mp.AutoLabels( title=\"Normalized Residual Map\", filename=\"normalized_residual_map\" ), ) if chi_squared_map: self.mat_plot_2d.plot_array(",
"Map\", filename=\"normalized_residual_map\" ), ) if chi_squared_map: self.mat_plot_2d.plot_array( array=self.fit.chi_squared_map, visuals_2d=self.visuals_with_include_2d, auto_labels=mp.AutoLabels( title=\"Chi-Squared Map\", filename=\"chi_squared_map\"",
"is output if the output_type is a file format (e.g. png, fits) output_format",
"path where the data is output if the output_type is a file format",
"normalized_residual_map=False, chi_squared_map=False, auto_filename=\"subplot_fit_imaging\", ): self._subplot_custom_plot( image=image, noise_map=noise_map, signal_to_noise_map=signal_to_noise_map, model_image=model_image, residual_map=residual_map, normalized_residual_map=normalized_residual_map, chi_squared_map=chi_squared_map, auto_labels=mp.AutoLabels(filename=auto_filename),",
"image=True, signal_to_noise_map=True, model_image=True, residual_map=True, normalized_residual_map=True, chi_squared_map=True, ) class FitImagingPlotter(AbstractFitImagingPlotter): def __init__( self, fit:",
"using the *Fitter* class object. The visualization and output type can be fully",
"self.visuals_2d + self.visuals_2d.__class__( origin=self.extract_2d( \"origin\", grid_2d_irregular.Grid2DIrregular(grid=[self.fit.mask.origin]) ), mask=self.extract_2d(\"mask\", self.fit.mask), border=self.extract_2d(\"border\", self.fit.mask.border_grid_sub_1.binned), ) def",
"data of an analysis, using the *Fitter* class object. The visualization and output",
": str How the data is output. File formats (e.g. png, fits) output",
"if chi_squared_map: self.mat_plot_2d.plot_array( array=self.fit.chi_squared_map, visuals_2d=self.visuals_with_include_2d, auto_labels=mp.AutoLabels( title=\"Chi-Squared Map\", filename=\"chi_squared_map\" ), ) def subplot(",
"mp from autoarray.fit import fit as f from autoarray.structures.grids.two_d import grid_2d_irregular class AbstractFitImagingPlotter(abstract_plotters.AbstractPlotter):",
": str The path where the data is output if the output_type is",
"output if the output_type is a file format (e.g. png, fits) output_format :",
"def subplot( self, image=False, noise_map=False, signal_to_noise_map=False, model_image=False, residual_map=False, normalized_residual_map=False, chi_squared_map=False, auto_filename=\"subplot_fit_imaging\", ): self._subplot_custom_plot(",
"visuals_2d, include_2d): super().__init__( mat_plot_2d=mat_plot_2d, include_2d=include_2d, visuals_2d=visuals_2d ) self.fit = fit @property def visuals_with_include_2d(self):",
"chi_squared_map etc.) output_path : str The path where the data is output if",
"residual_map=False, normalized_residual_map=False, chi_squared_map=False, ): \"\"\"Plot the model data of an analysis, using the",
"visuals_2d=self.visuals_with_include_2d, auto_labels=mp.AutoLabels( title=\"Chi-Squared Map\", filename=\"chi_squared_map\" ), ) def subplot( self, image=False, noise_map=False, signal_to_noise_map=False,",
"and output type can be fully customized. Parameters ----------- fit : autolens.lens.fitting.Fitter Class",
"def visuals_with_include_2d(self): return self.visuals_2d + self.visuals_2d.__class__( origin=self.extract_2d( \"origin\", grid_2d_irregular.Grid2DIrregular(grid=[self.fit.mask.origin]) ), mask=self.extract_2d(\"mask\", self.fit.mask), border=self.extract_2d(\"border\",",
"subplot_fit_imaging(self): return self.subplot( image=True, signal_to_noise_map=True, model_image=True, residual_map=True, normalized_residual_map=True, chi_squared_map=True, ) class FitImagingPlotter(AbstractFitImagingPlotter): def",
"is a file format (e.g. png, fits) output_format : str How the data",
"self.mat_plot_2d.plot_array( array=self.fit.residual_map, visuals_2d=self.visuals_with_include_2d, auto_labels=mp.AutoLabels( title=\"Residual Map\", filename=\"residual_map\" ), ) if normalized_residual_map: self.mat_plot_2d.plot_array( array=self.fit.normalized_residual_map,",
"fit : autolens.lens.fitting.Fitter Class containing fit between the model data and observed lens",
": autolens.lens.fitting.Fitter Class containing fit between the model data and observed lens data",
"output type can be fully customized. Parameters ----------- fit : autolens.lens.fitting.Fitter Class containing",
"Parameters ----------- fit : autolens.lens.fitting.Fitter Class containing fit between the model data and",
"__init__(self, fit, mat_plot_2d, visuals_2d, include_2d): super().__init__( mat_plot_2d=mat_plot_2d, include_2d=include_2d, visuals_2d=visuals_2d ) self.fit = fit",
"def subplot_fit_imaging(self): return self.subplot( image=True, signal_to_noise_map=True, model_image=True, residual_map=True, normalized_residual_map=True, chi_squared_map=True, ) class FitImagingPlotter(AbstractFitImagingPlotter):",
"noise_map=False, signal_to_noise_map=False, model_image=False, residual_map=False, normalized_residual_map=False, chi_squared_map=False, ): \"\"\"Plot the model data of an",
"the model data and observed lens data (including residual_map, chi_squared_map etc.) output_path :",
"as f from autoarray.structures.grids.two_d import grid_2d_irregular class AbstractFitImagingPlotter(abstract_plotters.AbstractPlotter): def __init__(self, fit, mat_plot_2d, visuals_2d,",
"autoarray.plot.mat_wrap import include as inc from autoarray.plot.mat_wrap import mat_plot as mp from autoarray.fit",
"array=self.fit.data, visuals_2d=self.visuals_with_include_2d, auto_labels=mp.AutoLabels(title=\"Image\", filename=\"image_2d\"), ) if noise_map: self.mat_plot_2d.plot_array( array=self.fit.noise_map, visuals_2d=self.visuals_with_include_2d, auto_labels=mp.AutoLabels(title=\"Noise-Map\", filename=\"noise_map\"), )",
"autoarray.structures.grids.two_d import grid_2d_irregular class AbstractFitImagingPlotter(abstract_plotters.AbstractPlotter): def __init__(self, fit, mat_plot_2d, visuals_2d, include_2d): super().__init__( mat_plot_2d=mat_plot_2d,",
"from autoarray.structures.grids.two_d import grid_2d_irregular class AbstractFitImagingPlotter(abstract_plotters.AbstractPlotter): def __init__(self, fit, mat_plot_2d, visuals_2d, include_2d): super().__init__(",
"mat_plot_2d=mat_plot_2d, include_2d=include_2d, visuals_2d=visuals_2d ) self.fit = fit @property def visuals_with_include_2d(self): return self.visuals_2d +",
"of an analysis, using the *Fitter* class object. The visualization and output type",
"the data \\ in the python interpreter window. \"\"\" if image: self.mat_plot_2d.plot_array( array=self.fit.data,",
") if signal_to_noise_map: self.mat_plot_2d.plot_array( array=self.fit.signal_to_noise_map, visuals_2d=self.visuals_with_include_2d, auto_labels=mp.AutoLabels( title=\"Signal-To-Noise Map\", filename=\"signal_to_noise_map\" ), ) if",
"), ) if model_image: self.mat_plot_2d.plot_array( array=self.fit.model_data, visuals_2d=self.visuals_with_include_2d, auto_labels=mp.AutoLabels(title=\"Model Image\", filename=\"model_image\"), ) if residual_map:",
"str How the data is output. File formats (e.g. png, fits) output the",
"Residual Map\", filename=\"normalized_residual_map\" ), ) if chi_squared_map: self.mat_plot_2d.plot_array( array=self.fit.chi_squared_map, visuals_2d=self.visuals_with_include_2d, auto_labels=mp.AutoLabels( title=\"Chi-Squared Map\",",
"FitImagingPlotter(AbstractFitImagingPlotter): def __init__( self, fit: f.FitImaging, mat_plot_2d: mp.MatPlot2D = mp.MatPlot2D(), visuals_2d: vis.Visuals2D =",
"signal_to_noise_map: self.mat_plot_2d.plot_array( array=self.fit.signal_to_noise_map, visuals_2d=self.visuals_with_include_2d, auto_labels=mp.AutoLabels( title=\"Signal-To-Noise Map\", filename=\"signal_to_noise_map\" ), ) if model_image: self.mat_plot_2d.plot_array(",
"as inc from autoarray.plot.mat_wrap import mat_plot as mp from autoarray.fit import fit as",
"self.fit.mask), border=self.extract_2d(\"border\", self.fit.mask.border_grid_sub_1.binned), ) def figures_2d( self, image=False, noise_map=False, signal_to_noise_map=False, model_image=False, residual_map=False, normalized_residual_map=False,",
"formats (e.g. png, fits) output the data to harddisk. 'show' displays the data",
"import include as inc from autoarray.plot.mat_wrap import mat_plot as mp from autoarray.fit import",
"auto_labels=mp.AutoLabels(title=\"Image\", filename=\"image_2d\"), ) if noise_map: self.mat_plot_2d.plot_array( array=self.fit.noise_map, visuals_2d=self.visuals_with_include_2d, auto_labels=mp.AutoLabels(title=\"Noise-Map\", filename=\"noise_map\"), ) if signal_to_noise_map:",
"title=\"Chi-Squared Map\", filename=\"chi_squared_map\" ), ) def subplot( self, image=False, noise_map=False, signal_to_noise_map=False, model_image=False, residual_map=False,",
"model_image=model_image, residual_map=residual_map, normalized_residual_map=normalized_residual_map, chi_squared_map=chi_squared_map, auto_labels=mp.AutoLabels(filename=auto_filename), ) def subplot_fit_imaging(self): return self.subplot( image=True, signal_to_noise_map=True, model_image=True,",
"mat_plot_2d, visuals_2d, include_2d): super().__init__( mat_plot_2d=mat_plot_2d, include_2d=include_2d, visuals_2d=visuals_2d ) self.fit = fit @property def",
") if residual_map: self.mat_plot_2d.plot_array( array=self.fit.residual_map, visuals_2d=self.visuals_with_include_2d, auto_labels=mp.AutoLabels( title=\"Residual Map\", filename=\"residual_map\" ), ) if",
"if the output_type is a file format (e.g. png, fits) output_format : str",
"+ self.visuals_2d.__class__( origin=self.extract_2d( \"origin\", grid_2d_irregular.Grid2DIrregular(grid=[self.fit.mask.origin]) ), mask=self.extract_2d(\"mask\", self.fit.mask), border=self.extract_2d(\"border\", self.fit.mask.border_grid_sub_1.binned), ) def figures_2d(",
"File formats (e.g. png, fits) output the data to harddisk. 'show' displays the",
"chi_squared_map=False, ): \"\"\"Plot the model data of an analysis, using the *Fitter* class",
"self.visuals_2d.__class__( origin=self.extract_2d( \"origin\", grid_2d_irregular.Grid2DIrregular(grid=[self.fit.mask.origin]) ), mask=self.extract_2d(\"mask\", self.fit.mask), border=self.extract_2d(\"border\", self.fit.mask.border_grid_sub_1.binned), ) def figures_2d( self,",
"if signal_to_noise_map: self.mat_plot_2d.plot_array( array=self.fit.signal_to_noise_map, visuals_2d=self.visuals_with_include_2d, auto_labels=mp.AutoLabels( title=\"Signal-To-Noise Map\", filename=\"signal_to_noise_map\" ), ) if model_image:",
"if model_image: self.mat_plot_2d.plot_array( array=self.fit.model_data, visuals_2d=self.visuals_with_include_2d, auto_labels=mp.AutoLabels(title=\"Model Image\", filename=\"model_image\"), ) if residual_map: self.mat_plot_2d.plot_array( array=self.fit.residual_map,",
"self.subplot( image=True, signal_to_noise_map=True, model_image=True, residual_map=True, normalized_residual_map=True, chi_squared_map=True, ) class FitImagingPlotter(AbstractFitImagingPlotter): def __init__( self,",
"output the data to harddisk. 'show' displays the data \\ in the python",
"the data to harddisk. 'show' displays the data \\ in the python interpreter",
"def __init__( self, fit: f.FitImaging, mat_plot_2d: mp.MatPlot2D = mp.MatPlot2D(), visuals_2d: vis.Visuals2D = vis.Visuals2D(),",
"output. File formats (e.g. png, fits) output the data to harddisk. 'show' displays",
"filename=\"signal_to_noise_map\" ), ) if model_image: self.mat_plot_2d.plot_array( array=self.fit.model_data, visuals_2d=self.visuals_with_include_2d, auto_labels=mp.AutoLabels(title=\"Model Image\", filename=\"model_image\"), ) if",
"), ) if chi_squared_map: self.mat_plot_2d.plot_array( array=self.fit.chi_squared_map, visuals_2d=self.visuals_with_include_2d, auto_labels=mp.AutoLabels( title=\"Chi-Squared Map\", filename=\"chi_squared_map\" ), )",
"noise_map=False, signal_to_noise_map=False, model_image=False, residual_map=False, normalized_residual_map=False, chi_squared_map=False, auto_filename=\"subplot_fit_imaging\", ): self._subplot_custom_plot( image=image, noise_map=noise_map, signal_to_noise_map=signal_to_noise_map, model_image=model_image,",
"import abstract_plotters from autoarray.plot.mat_wrap import visuals as vis from autoarray.plot.mat_wrap import include as",
"the model data of an analysis, using the *Fitter* class object. The visualization",
"the *Fitter* class object. The visualization and output type can be fully customized.",
"(e.g. png, fits) output the data to harddisk. 'show' displays the data \\",
"self.fit.mask.border_grid_sub_1.binned), ) def figures_2d( self, image=False, noise_map=False, signal_to_noise_map=False, model_image=False, residual_map=False, normalized_residual_map=False, chi_squared_map=False, ):",
"= fit @property def visuals_with_include_2d(self): return self.visuals_2d + self.visuals_2d.__class__( origin=self.extract_2d( \"origin\", grid_2d_irregular.Grid2DIrregular(grid=[self.fit.mask.origin]) ),",
"figures_2d( self, image=False, noise_map=False, signal_to_noise_map=False, model_image=False, residual_map=False, normalized_residual_map=False, chi_squared_map=False, ): \"\"\"Plot the model",
"if image: self.mat_plot_2d.plot_array( array=self.fit.data, visuals_2d=self.visuals_with_include_2d, auto_labels=mp.AutoLabels(title=\"Image\", filename=\"image_2d\"), ) if noise_map: self.mat_plot_2d.plot_array( array=self.fit.noise_map, visuals_2d=self.visuals_with_include_2d,",
"title=\"Signal-To-Noise Map\", filename=\"signal_to_noise_map\" ), ) if model_image: self.mat_plot_2d.plot_array( array=self.fit.model_data, visuals_2d=self.visuals_with_include_2d, auto_labels=mp.AutoLabels(title=\"Model Image\", filename=\"model_image\"),",
"): self._subplot_custom_plot( image=image, noise_map=noise_map, signal_to_noise_map=signal_to_noise_map, model_image=model_image, residual_map=residual_map, normalized_residual_map=normalized_residual_map, chi_squared_map=chi_squared_map, auto_labels=mp.AutoLabels(filename=auto_filename), ) def subplot_fit_imaging(self):",
"model_image=True, residual_map=True, normalized_residual_map=True, chi_squared_map=True, ) class FitImagingPlotter(AbstractFitImagingPlotter): def __init__( self, fit: f.FitImaging, mat_plot_2d:",
"self._subplot_custom_plot( image=image, noise_map=noise_map, signal_to_noise_map=signal_to_noise_map, model_image=model_image, residual_map=residual_map, normalized_residual_map=normalized_residual_map, chi_squared_map=chi_squared_map, auto_labels=mp.AutoLabels(filename=auto_filename), ) def subplot_fit_imaging(self): return",
"model_image=False, residual_map=False, normalized_residual_map=False, chi_squared_map=False, auto_filename=\"subplot_fit_imaging\", ): self._subplot_custom_plot( image=image, noise_map=noise_map, signal_to_noise_map=signal_to_noise_map, model_image=model_image, residual_map=residual_map, normalized_residual_map=normalized_residual_map,",
"auto_labels=mp.AutoLabels( title=\"Signal-To-Noise Map\", filename=\"signal_to_noise_map\" ), ) if model_image: self.mat_plot_2d.plot_array( array=self.fit.model_data, visuals_2d=self.visuals_with_include_2d, auto_labels=mp.AutoLabels(title=\"Model Image\",",
"include_2d=include_2d, visuals_2d=visuals_2d ) self.fit = fit @property def visuals_with_include_2d(self): return self.visuals_2d + self.visuals_2d.__class__(",
"visuals_2d=self.visuals_with_include_2d, auto_labels=mp.AutoLabels(title=\"Noise-Map\", filename=\"noise_map\"), ) if signal_to_noise_map: self.mat_plot_2d.plot_array( array=self.fit.signal_to_noise_map, visuals_2d=self.visuals_with_include_2d, auto_labels=mp.AutoLabels( title=\"Signal-To-Noise Map\", filename=\"signal_to_noise_map\"",
"data is output if the output_type is a file format (e.g. png, fits)",
"visuals_with_include_2d(self): return self.visuals_2d + self.visuals_2d.__class__( origin=self.extract_2d( \"origin\", grid_2d_irregular.Grid2DIrregular(grid=[self.fit.mask.origin]) ), mask=self.extract_2d(\"mask\", self.fit.mask), border=self.extract_2d(\"border\", self.fit.mask.border_grid_sub_1.binned),",
"Image\", filename=\"model_image\"), ) if residual_map: self.mat_plot_2d.plot_array( array=self.fit.residual_map, visuals_2d=self.visuals_with_include_2d, auto_labels=mp.AutoLabels( title=\"Residual Map\", filename=\"residual_map\" ),",
"if residual_map: self.mat_plot_2d.plot_array( array=self.fit.residual_map, visuals_2d=self.visuals_with_include_2d, auto_labels=mp.AutoLabels( title=\"Residual Map\", filename=\"residual_map\" ), ) if normalized_residual_map:",
"class FitImagingPlotter(AbstractFitImagingPlotter): def __init__( self, fit: f.FitImaging, mat_plot_2d: mp.MatPlot2D = mp.MatPlot2D(), visuals_2d: vis.Visuals2D",
"return self.subplot( image=True, signal_to_noise_map=True, model_image=True, residual_map=True, normalized_residual_map=True, chi_squared_map=True, ) class FitImagingPlotter(AbstractFitImagingPlotter): def __init__(",
"model_image=False, residual_map=False, normalized_residual_map=False, chi_squared_map=False, ): \"\"\"Plot the model data of an analysis, using",
"auto_labels=mp.AutoLabels(filename=auto_filename), ) def subplot_fit_imaging(self): return self.subplot( image=True, signal_to_noise_map=True, model_image=True, residual_map=True, normalized_residual_map=True, chi_squared_map=True, )",
"in the python interpreter window. \"\"\" if image: self.mat_plot_2d.plot_array( array=self.fit.data, visuals_2d=self.visuals_with_include_2d, auto_labels=mp.AutoLabels(title=\"Image\", filename=\"image_2d\"),",
"autoarray.plot import abstract_plotters from autoarray.plot.mat_wrap import visuals as vis from autoarray.plot.mat_wrap import include",
"self, image=False, noise_map=False, signal_to_noise_map=False, model_image=False, residual_map=False, normalized_residual_map=False, chi_squared_map=False, ): \"\"\"Plot the model data",
"grid_2d_irregular.Grid2DIrregular(grid=[self.fit.mask.origin]) ), mask=self.extract_2d(\"mask\", self.fit.mask), border=self.extract_2d(\"border\", self.fit.mask.border_grid_sub_1.binned), ) def figures_2d( self, image=False, noise_map=False, signal_to_noise_map=False,",
"image: self.mat_plot_2d.plot_array( array=self.fit.data, visuals_2d=self.visuals_with_include_2d, auto_labels=mp.AutoLabels(title=\"Image\", filename=\"image_2d\"), ) if noise_map: self.mat_plot_2d.plot_array( array=self.fit.noise_map, visuals_2d=self.visuals_with_include_2d, auto_labels=mp.AutoLabels(title=\"Noise-Map\",",
"visuals_2d=self.visuals_with_include_2d, auto_labels=mp.AutoLabels(title=\"Model Image\", filename=\"model_image\"), ) if residual_map: self.mat_plot_2d.plot_array( array=self.fit.residual_map, visuals_2d=self.visuals_with_include_2d, auto_labels=mp.AutoLabels( title=\"Residual Map\",",
"as mp from autoarray.fit import fit as f from autoarray.structures.grids.two_d import grid_2d_irregular class",
"include_2d): super().__init__( mat_plot_2d=mat_plot_2d, include_2d=include_2d, visuals_2d=visuals_2d ) self.fit = fit @property def visuals_with_include_2d(self): return",
"self.mat_plot_2d.plot_array( array=self.fit.data, visuals_2d=self.visuals_with_include_2d, auto_labels=mp.AutoLabels(title=\"Image\", filename=\"image_2d\"), ) if noise_map: self.mat_plot_2d.plot_array( array=self.fit.noise_map, visuals_2d=self.visuals_with_include_2d, auto_labels=mp.AutoLabels(title=\"Noise-Map\", filename=\"noise_map\"),",
"filename=\"chi_squared_map\" ), ) def subplot( self, image=False, noise_map=False, signal_to_noise_map=False, model_image=False, residual_map=False, normalized_residual_map=False, chi_squared_map=False,",
"lens data (including residual_map, chi_squared_map etc.) output_path : str The path where the",
"image=False, noise_map=False, signal_to_noise_map=False, model_image=False, residual_map=False, normalized_residual_map=False, chi_squared_map=False, ): \"\"\"Plot the model data of",
"__init__( self, fit: f.FitImaging, mat_plot_2d: mp.MatPlot2D = mp.MatPlot2D(), visuals_2d: vis.Visuals2D = vis.Visuals2D(), include_2d:",
"mp.MatPlot2D = mp.MatPlot2D(), visuals_2d: vis.Visuals2D = vis.Visuals2D(), include_2d: inc.Include2D = inc.Include2D(), ): super().__init__(",
"vis from autoarray.plot.mat_wrap import include as inc from autoarray.plot.mat_wrap import mat_plot as mp",
"from autoarray.plot.mat_wrap import visuals as vis from autoarray.plot.mat_wrap import include as inc from",
"containing fit between the model data and observed lens data (including residual_map, chi_squared_map",
"residual_map=residual_map, normalized_residual_map=normalized_residual_map, chi_squared_map=chi_squared_map, auto_labels=mp.AutoLabels(filename=auto_filename), ) def subplot_fit_imaging(self): return self.subplot( image=True, signal_to_noise_map=True, model_image=True, residual_map=True,",
"The path where the data is output if the output_type is a file",
"file format (e.g. png, fits) output_format : str How the data is output.",
"), ) def subplot( self, image=False, noise_map=False, signal_to_noise_map=False, model_image=False, residual_map=False, normalized_residual_map=False, chi_squared_map=False, auto_filename=\"subplot_fit_imaging\",",
"title=\"Normalized Residual Map\", filename=\"normalized_residual_map\" ), ) if chi_squared_map: self.mat_plot_2d.plot_array( array=self.fit.chi_squared_map, visuals_2d=self.visuals_with_include_2d, auto_labels=mp.AutoLabels( title=\"Chi-Squared",
"normalized_residual_map=normalized_residual_map, chi_squared_map=chi_squared_map, auto_labels=mp.AutoLabels(filename=auto_filename), ) def subplot_fit_imaging(self): return self.subplot( image=True, signal_to_noise_map=True, model_image=True, residual_map=True, normalized_residual_map=True,",
"model_image: self.mat_plot_2d.plot_array( array=self.fit.model_data, visuals_2d=self.visuals_with_include_2d, auto_labels=mp.AutoLabels(title=\"Model Image\", filename=\"model_image\"), ) if residual_map: self.mat_plot_2d.plot_array( array=self.fit.residual_map, visuals_2d=self.visuals_with_include_2d,",
"\"\"\"Plot the model data of an analysis, using the *Fitter* class object. The",
"fit, mat_plot_2d, visuals_2d, include_2d): super().__init__( mat_plot_2d=mat_plot_2d, include_2d=include_2d, visuals_2d=visuals_2d ) self.fit = fit @property",
"object. The visualization and output type can be fully customized. Parameters ----------- fit",
"super().__init__( mat_plot_2d=mat_plot_2d, include_2d=include_2d, visuals_2d=visuals_2d ) self.fit = fit @property def visuals_with_include_2d(self): return self.visuals_2d",
"f from autoarray.structures.grids.two_d import grid_2d_irregular class AbstractFitImagingPlotter(abstract_plotters.AbstractPlotter): def __init__(self, fit, mat_plot_2d, visuals_2d, include_2d):",
"class AbstractFitImagingPlotter(abstract_plotters.AbstractPlotter): def __init__(self, fit, mat_plot_2d, visuals_2d, include_2d): super().__init__( mat_plot_2d=mat_plot_2d, include_2d=include_2d, visuals_2d=visuals_2d )",
"visuals_2d=self.visuals_with_include_2d, auto_labels=mp.AutoLabels(title=\"Image\", filename=\"image_2d\"), ) if noise_map: self.mat_plot_2d.plot_array( array=self.fit.noise_map, visuals_2d=self.visuals_with_include_2d, auto_labels=mp.AutoLabels(title=\"Noise-Map\", filename=\"noise_map\"), ) if",
"fit: f.FitImaging, mat_plot_2d: mp.MatPlot2D = mp.MatPlot2D(), visuals_2d: vis.Visuals2D = vis.Visuals2D(), include_2d: inc.Include2D =",
"noise_map: self.mat_plot_2d.plot_array( array=self.fit.noise_map, visuals_2d=self.visuals_with_include_2d, auto_labels=mp.AutoLabels(title=\"Noise-Map\", filename=\"noise_map\"), ) if signal_to_noise_map: self.mat_plot_2d.plot_array( array=self.fit.signal_to_noise_map, visuals_2d=self.visuals_with_include_2d, auto_labels=mp.AutoLabels(",
"auto_labels=mp.AutoLabels( title=\"Residual Map\", filename=\"residual_map\" ), ) if normalized_residual_map: self.mat_plot_2d.plot_array( array=self.fit.normalized_residual_map, visuals_2d=self.visuals_with_include_2d, auto_labels=mp.AutoLabels( title=\"Normalized",
"\"\"\" if image: self.mat_plot_2d.plot_array( array=self.fit.data, visuals_2d=self.visuals_with_include_2d, auto_labels=mp.AutoLabels(title=\"Image\", filename=\"image_2d\"), ) if noise_map: self.mat_plot_2d.plot_array( array=self.fit.noise_map,",
"chi_squared_map: self.mat_plot_2d.plot_array( array=self.fit.chi_squared_map, visuals_2d=self.visuals_with_include_2d, auto_labels=mp.AutoLabels( title=\"Chi-Squared Map\", filename=\"chi_squared_map\" ), ) def subplot( self,",
") class FitImagingPlotter(AbstractFitImagingPlotter): def __init__( self, fit: f.FitImaging, mat_plot_2d: mp.MatPlot2D = mp.MatPlot2D(), visuals_2d:",
"self, fit: f.FitImaging, mat_plot_2d: mp.MatPlot2D = mp.MatPlot2D(), visuals_2d: vis.Visuals2D = vis.Visuals2D(), include_2d: inc.Include2D",
"as vis from autoarray.plot.mat_wrap import include as inc from autoarray.plot.mat_wrap import mat_plot as",
"if noise_map: self.mat_plot_2d.plot_array( array=self.fit.noise_map, visuals_2d=self.visuals_with_include_2d, auto_labels=mp.AutoLabels(title=\"Noise-Map\", filename=\"noise_map\"), ) if signal_to_noise_map: self.mat_plot_2d.plot_array( array=self.fit.signal_to_noise_map, visuals_2d=self.visuals_with_include_2d,",
"from autoarray.fit import fit as f from autoarray.structures.grids.two_d import grid_2d_irregular class AbstractFitImagingPlotter(abstract_plotters.AbstractPlotter): def",
") if model_image: self.mat_plot_2d.plot_array( array=self.fit.model_data, visuals_2d=self.visuals_with_include_2d, auto_labels=mp.AutoLabels(title=\"Model Image\", filename=\"model_image\"), ) if residual_map: self.mat_plot_2d.plot_array(",
"(including residual_map, chi_squared_map etc.) output_path : str The path where the data is",
"if normalized_residual_map: self.mat_plot_2d.plot_array( array=self.fit.normalized_residual_map, visuals_2d=self.visuals_with_include_2d, auto_labels=mp.AutoLabels( title=\"Normalized Residual Map\", filename=\"normalized_residual_map\" ), ) if",
"fully customized. Parameters ----------- fit : autolens.lens.fitting.Fitter Class containing fit between the model",
"data \\ in the python interpreter window. \"\"\" if image: self.mat_plot_2d.plot_array( array=self.fit.data, visuals_2d=self.visuals_with_include_2d,",
") if chi_squared_map: self.mat_plot_2d.plot_array( array=self.fit.chi_squared_map, visuals_2d=self.visuals_with_include_2d, auto_labels=mp.AutoLabels( title=\"Chi-Squared Map\", filename=\"chi_squared_map\" ), ) def",
"output_format : str How the data is output. File formats (e.g. png, fits)",
"auto_labels=mp.AutoLabels( title=\"Chi-Squared Map\", filename=\"chi_squared_map\" ), ) def subplot( self, image=False, noise_map=False, signal_to_noise_map=False, model_image=False,",
"signal_to_noise_map=True, model_image=True, residual_map=True, normalized_residual_map=True, chi_squared_map=True, ) class FitImagingPlotter(AbstractFitImagingPlotter): def __init__( self, fit: f.FitImaging,",
"an analysis, using the *Fitter* class object. The visualization and output type can",
"AbstractFitImagingPlotter(abstract_plotters.AbstractPlotter): def __init__(self, fit, mat_plot_2d, visuals_2d, include_2d): super().__init__( mat_plot_2d=mat_plot_2d, include_2d=include_2d, visuals_2d=visuals_2d ) self.fit",
"and observed lens data (including residual_map, chi_squared_map etc.) output_path : str The path",
"str The path where the data is output if the output_type is a",
"), ) if normalized_residual_map: self.mat_plot_2d.plot_array( array=self.fit.normalized_residual_map, visuals_2d=self.visuals_with_include_2d, auto_labels=mp.AutoLabels( title=\"Normalized Residual Map\", filename=\"normalized_residual_map\" ),",
"*Fitter* class object. The visualization and output type can be fully customized. Parameters",
"self, image=False, noise_map=False, signal_to_noise_map=False, model_image=False, residual_map=False, normalized_residual_map=False, chi_squared_map=False, auto_filename=\"subplot_fit_imaging\", ): self._subplot_custom_plot( image=image, noise_map=noise_map,",
"import grid_2d_irregular class AbstractFitImagingPlotter(abstract_plotters.AbstractPlotter): def __init__(self, fit, mat_plot_2d, visuals_2d, include_2d): super().__init__( mat_plot_2d=mat_plot_2d, include_2d=include_2d,",
"output_type is a file format (e.g. png, fits) output_format : str How the",
"array=self.fit.residual_map, visuals_2d=self.visuals_with_include_2d, auto_labels=mp.AutoLabels( title=\"Residual Map\", filename=\"residual_map\" ), ) if normalized_residual_map: self.mat_plot_2d.plot_array( array=self.fit.normalized_residual_map, visuals_2d=self.visuals_with_include_2d,",
"is output. File formats (e.g. png, fits) output the data to harddisk. 'show'",
"import fit as f from autoarray.structures.grids.two_d import grid_2d_irregular class AbstractFitImagingPlotter(abstract_plotters.AbstractPlotter): def __init__(self, fit,",
"normalized_residual_map=True, chi_squared_map=True, ) class FitImagingPlotter(AbstractFitImagingPlotter): def __init__( self, fit: f.FitImaging, mat_plot_2d: mp.MatPlot2D =",
") def subplot( self, image=False, noise_map=False, signal_to_noise_map=False, model_image=False, residual_map=False, normalized_residual_map=False, chi_squared_map=False, auto_filename=\"subplot_fit_imaging\", ):",
"mat_plot as mp from autoarray.fit import fit as f from autoarray.structures.grids.two_d import grid_2d_irregular",
"type can be fully customized. Parameters ----------- fit : autolens.lens.fitting.Fitter Class containing fit",
"subplot( self, image=False, noise_map=False, signal_to_noise_map=False, model_image=False, residual_map=False, normalized_residual_map=False, chi_squared_map=False, auto_filename=\"subplot_fit_imaging\", ): self._subplot_custom_plot( image=image,",
"autoarray.plot.mat_wrap import visuals as vis from autoarray.plot.mat_wrap import include as inc from autoarray.plot.mat_wrap",
"observed lens data (including residual_map, chi_squared_map etc.) output_path : str The path where",
"visuals_2d=self.visuals_with_include_2d, auto_labels=mp.AutoLabels( title=\"Normalized Residual Map\", filename=\"normalized_residual_map\" ), ) if chi_squared_map: self.mat_plot_2d.plot_array( array=self.fit.chi_squared_map, visuals_2d=self.visuals_with_include_2d,",
"data (including residual_map, chi_squared_map etc.) output_path : str The path where the data",
"harddisk. 'show' displays the data \\ in the python interpreter window. \"\"\" if",
"python interpreter window. \"\"\" if image: self.mat_plot_2d.plot_array( array=self.fit.data, visuals_2d=self.visuals_with_include_2d, auto_labels=mp.AutoLabels(title=\"Image\", filename=\"image_2d\"), ) if",
"normalized_residual_map: self.mat_plot_2d.plot_array( array=self.fit.normalized_residual_map, visuals_2d=self.visuals_with_include_2d, auto_labels=mp.AutoLabels( title=\"Normalized Residual Map\", filename=\"normalized_residual_map\" ), ) if chi_squared_map:",
"array=self.fit.signal_to_noise_map, visuals_2d=self.visuals_with_include_2d, auto_labels=mp.AutoLabels( title=\"Signal-To-Noise Map\", filename=\"signal_to_noise_map\" ), ) if model_image: self.mat_plot_2d.plot_array( array=self.fit.model_data, visuals_2d=self.visuals_with_include_2d,",
"array=self.fit.normalized_residual_map, visuals_2d=self.visuals_with_include_2d, auto_labels=mp.AutoLabels( title=\"Normalized Residual Map\", filename=\"normalized_residual_map\" ), ) if chi_squared_map: self.mat_plot_2d.plot_array( array=self.fit.chi_squared_map,",
") def figures_2d( self, image=False, noise_map=False, signal_to_noise_map=False, model_image=False, residual_map=False, normalized_residual_map=False, chi_squared_map=False, ): \"\"\"Plot",
"title=\"Residual Map\", filename=\"residual_map\" ), ) if normalized_residual_map: self.mat_plot_2d.plot_array( array=self.fit.normalized_residual_map, visuals_2d=self.visuals_with_include_2d, auto_labels=mp.AutoLabels( title=\"Normalized Residual",
"= vis.Visuals2D(), include_2d: inc.Include2D = inc.Include2D(), ): super().__init__( fit=fit, mat_plot_2d=mat_plot_2d, include_2d=include_2d, visuals_2d=visuals_2d, )",
"displays the data \\ in the python interpreter window. \"\"\" if image: self.mat_plot_2d.plot_array(",
"noise_map=noise_map, signal_to_noise_map=signal_to_noise_map, model_image=model_image, residual_map=residual_map, normalized_residual_map=normalized_residual_map, chi_squared_map=chi_squared_map, auto_labels=mp.AutoLabels(filename=auto_filename), ) def subplot_fit_imaging(self): return self.subplot( image=True,",
"filename=\"residual_map\" ), ) if normalized_residual_map: self.mat_plot_2d.plot_array( array=self.fit.normalized_residual_map, visuals_2d=self.visuals_with_include_2d, auto_labels=mp.AutoLabels( title=\"Normalized Residual Map\", filename=\"normalized_residual_map\"",
"mp.MatPlot2D(), visuals_2d: vis.Visuals2D = vis.Visuals2D(), include_2d: inc.Include2D = inc.Include2D(), ): super().__init__( fit=fit, mat_plot_2d=mat_plot_2d,",
"inc from autoarray.plot.mat_wrap import mat_plot as mp from autoarray.fit import fit as f",
"png, fits) output the data to harddisk. 'show' displays the data \\ in",
"array=self.fit.chi_squared_map, visuals_2d=self.visuals_with_include_2d, auto_labels=mp.AutoLabels( title=\"Chi-Squared Map\", filename=\"chi_squared_map\" ), ) def subplot( self, image=False, noise_map=False,",
"residual_map=False, normalized_residual_map=False, chi_squared_map=False, auto_filename=\"subplot_fit_imaging\", ): self._subplot_custom_plot( image=image, noise_map=noise_map, signal_to_noise_map=signal_to_noise_map, model_image=model_image, residual_map=residual_map, normalized_residual_map=normalized_residual_map, chi_squared_map=chi_squared_map,",
"auto_labels=mp.AutoLabels(title=\"Model Image\", filename=\"model_image\"), ) if residual_map: self.mat_plot_2d.plot_array( array=self.fit.residual_map, visuals_2d=self.visuals_with_include_2d, auto_labels=mp.AutoLabels( title=\"Residual Map\", filename=\"residual_map\"",
"model data and observed lens data (including residual_map, chi_squared_map etc.) output_path : str",
"be fully customized. Parameters ----------- fit : autolens.lens.fitting.Fitter Class containing fit between the",
"data to harddisk. 'show' displays the data \\ in the python interpreter window.",
"filename=\"normalized_residual_map\" ), ) if chi_squared_map: self.mat_plot_2d.plot_array( array=self.fit.chi_squared_map, visuals_2d=self.visuals_with_include_2d, auto_labels=mp.AutoLabels( title=\"Chi-Squared Map\", filename=\"chi_squared_map\" ),",
"from autoarray.plot.mat_wrap import include as inc from autoarray.plot.mat_wrap import mat_plot as mp from",
"@property def visuals_with_include_2d(self): return self.visuals_2d + self.visuals_2d.__class__( origin=self.extract_2d( \"origin\", grid_2d_irregular.Grid2DIrregular(grid=[self.fit.mask.origin]) ), mask=self.extract_2d(\"mask\", self.fit.mask),",
"auto_labels=mp.AutoLabels(title=\"Noise-Map\", filename=\"noise_map\"), ) if signal_to_noise_map: self.mat_plot_2d.plot_array( array=self.fit.signal_to_noise_map, visuals_2d=self.visuals_with_include_2d, auto_labels=mp.AutoLabels( title=\"Signal-To-Noise Map\", filename=\"signal_to_noise_map\" ),",
"the python interpreter window. \"\"\" if image: self.mat_plot_2d.plot_array( array=self.fit.data, visuals_2d=self.visuals_with_include_2d, auto_labels=mp.AutoLabels(title=\"Image\", filename=\"image_2d\"), )",
"fits) output_format : str How the data is output. File formats (e.g. png,",
"abstract_plotters from autoarray.plot.mat_wrap import visuals as vis from autoarray.plot.mat_wrap import include as inc",
"autolens.lens.fitting.Fitter Class containing fit between the model data and observed lens data (including",
"visuals_2d=visuals_2d ) self.fit = fit @property def visuals_with_include_2d(self): return self.visuals_2d + self.visuals_2d.__class__( origin=self.extract_2d(",
"self.mat_plot_2d.plot_array( array=self.fit.signal_to_noise_map, visuals_2d=self.visuals_with_include_2d, auto_labels=mp.AutoLabels( title=\"Signal-To-Noise Map\", filename=\"signal_to_noise_map\" ), ) if model_image: self.mat_plot_2d.plot_array( array=self.fit.model_data,",
"self.mat_plot_2d.plot_array( array=self.fit.chi_squared_map, visuals_2d=self.visuals_with_include_2d, auto_labels=mp.AutoLabels( title=\"Chi-Squared Map\", filename=\"chi_squared_map\" ), ) def subplot( self, image=False,",
"data and observed lens data (including residual_map, chi_squared_map etc.) output_path : str The",
"\\ in the python interpreter window. \"\"\" if image: self.mat_plot_2d.plot_array( array=self.fit.data, visuals_2d=self.visuals_with_include_2d, auto_labels=mp.AutoLabels(title=\"Image\",",
"array=self.fit.noise_map, visuals_2d=self.visuals_with_include_2d, auto_labels=mp.AutoLabels(title=\"Noise-Map\", filename=\"noise_map\"), ) if signal_to_noise_map: self.mat_plot_2d.plot_array( array=self.fit.signal_to_noise_map, visuals_2d=self.visuals_with_include_2d, auto_labels=mp.AutoLabels( title=\"Signal-To-Noise Map\",",
"self.mat_plot_2d.plot_array( array=self.fit.model_data, visuals_2d=self.visuals_with_include_2d, auto_labels=mp.AutoLabels(title=\"Model Image\", filename=\"model_image\"), ) if residual_map: self.mat_plot_2d.plot_array( array=self.fit.residual_map, visuals_2d=self.visuals_with_include_2d, auto_labels=mp.AutoLabels(",
"= mp.MatPlot2D(), visuals_2d: vis.Visuals2D = vis.Visuals2D(), include_2d: inc.Include2D = inc.Include2D(), ): super().__init__( fit=fit,",
"def figures_2d( self, image=False, noise_map=False, signal_to_noise_map=False, model_image=False, residual_map=False, normalized_residual_map=False, chi_squared_map=False, ): \"\"\"Plot the",
"model data of an analysis, using the *Fitter* class object. The visualization and",
"format (e.g. png, fits) output_format : str How the data is output. File",
"self.fit = fit @property def visuals_with_include_2d(self): return self.visuals_2d + self.visuals_2d.__class__( origin=self.extract_2d( \"origin\", grid_2d_irregular.Grid2DIrregular(grid=[self.fit.mask.origin])"
] |
[
"self.call_sense_hat_function('clear') def get_analog(self): \"\"\"Gets the digital value as a tuple specifying this is",
"use_emulator self.sense_hat = None self.digital_value = 0 self.analog_value = 0.0 self.image_file = os.path.join('/etc/myDevices/plugins/cayenne-plugin-sensehat/data/image.png')",
"= self.call_sense_hat_function('get_gyroscope_raw') if values is not None: rps = [] rps.append(values['x']) rps.append(values['y']) rps.append(values['z'])",
"is not None: rps = [] rps.append(values['x']) rps.append(values['y']) rps.append(values['z']) return rps def get_magnetometer(self):",
"Sense HAT add-on board for Raspberry Pi. \"\"\" import os from multiprocessing.managers import",
"self.analog_value = 0.0 self.image_file = os.path.join('/etc/myDevices/plugins/cayenne-plugin-sensehat/data/image.png') self.call_sense_hat_function('clear') def init_sense_hat(self): \"\"\"Initializes connection to Sense",
"HAT add-on board for Raspberry Pi. \"\"\" import os from multiprocessing.managers import RemoteError",
"not None: g_force = [] g_force.append(values['x']) g_force.append(values['y']) g_force.append(values['z']) return (g_force, 'accel', 'g') def",
"function_name) value = func(*args) return value except EOFError as e: error(e) sense_hat =",
"use_emulator=False): \"\"\"Initializes Sense HAT device. Arguments: use_emulator: True if the Sense HAT Emulator",
"to Sense HAT service and gets a SenseHat shared object.\"\"\" if not self.sense_hat:",
"\"\"\"Class for interacting with a Sense HAT device\"\"\" def __init__(self, use_emulator=False): \"\"\"Initializes Sense",
"actuator.\"\"\" return (self.analog_value, 'analog_actuator') def set_analog(self, value): \"\"\"Displays the analog value on the",
"self.digital_value: self.call_sense_hat_function('load_image', self.image_file) else: self.call_sense_hat_function('clear') def get_analog(self): \"\"\"Gets the digital value as a",
"self.image_file) else: self.call_sense_hat_function('clear') def get_analog(self): \"\"\"Gets the digital value as a tuple specifying",
"return (self.call_sense_hat_function('get_temperature'), 'temp', 'c') def get_humidity(self): \"\"\"Gets the humidity as a tuple with",
"= self.manager.SenseHat() except ConnectionRefusedError as e: info('Sense HAT service connection refused') error(e) except",
"digital value is equal to True.\"\"\" self.digital_value = value if self.digital_value: self.call_sense_hat_function('load_image', self.image_file)",
"Sense HAT service and gets a SenseHat shared object.\"\"\" if not self.sense_hat: try:",
"magnetometer.\"\"\" #Not currently supported in Cayenne values = self.call_sense_hat_function('get_compass_raw') if values is not",
"self.call_sense_hat_function('get_gyroscope_raw') if values is not None: rps = [] rps.append(values['x']) rps.append(values['y']) rps.append(values['z']) return",
"Arguments to pass to the function. \"\"\" self.init_sense_hat() try: if self.sense_hat is not",
"for interfacing with the Sense HAT add-on board for Raspberry Pi. \"\"\" import",
"sensehat.manager import connect_client class SenseHAT(): \"\"\"Class for interacting with a Sense HAT device\"\"\"",
"(self.analog_value, 'analog_actuator') def set_analog(self, value): \"\"\"Displays the analog value on the Sense HAT",
"info('Sense HAT service connection refused') error(e) except RemoteError as e: error('Failed to connect",
"type and unit.\"\"\" value = self.call_sense_hat_function('get_pressure') if value is not None: return (value",
"rps = [] rps.append(values['x']) rps.append(values['y']) rps.append(values['z']) return rps def get_magnetometer(self): \"\"\"Gets microteslas from",
"error, exception, info from sensehat.manager import connect_client class SenseHAT(): \"\"\"Class for interacting with",
"= use_emulator self.sense_hat = None self.digital_value = 0 self.analog_value = 0.0 self.image_file =",
"\"\"\" This module provides a class for interfacing with the Sense HAT add-on",
"'g') def get_gyroscope(self): \"\"\"Gets radians per second from the gyroscope.\"\"\" #Not currently supported",
"function_name: Name of the function to call. args: Arguments to pass to the",
"return value except EOFError as e: error(e) sense_hat = None except AttributeError as",
"if not self.sense_hat: try: self.manager = connect_client() self.manager.use_emulator(self.use_emulator) self.sense_hat = self.manager.SenseHat() except ConnectionRefusedError",
"return (g_force, 'accel', 'g') def get_gyroscope(self): \"\"\"Gets radians per second from the gyroscope.\"\"\"",
"the function. \"\"\" self.init_sense_hat() try: if self.sense_hat is not None: func = getattr(self.sense_hat,",
"the humidity as a tuple with type and unit.\"\"\" return (self.call_sense_hat_function('get_humidity'), 'rel_hum', 'p')",
"of the function to call. args: Arguments to pass to the function. \"\"\"",
"unit.\"\"\" value = self.call_sense_hat_function('get_pressure') if value is not None: return (value * 100,",
"import error, exception, info from sensehat.manager import connect_client class SenseHAT(): \"\"\"Class for interacting",
"humidity as a tuple with type and unit.\"\"\" return (self.call_sense_hat_function('get_humidity'), 'rel_hum', 'p') def",
"except RemoteError as e: error('Failed to connect to Sense HAT device') def call_sense_hat_function(self,",
"add-on board for Raspberry Pi. \"\"\" import os from multiprocessing.managers import RemoteError from",
"and unit.\"\"\" return (self.call_sense_hat_function('get_humidity'), 'rel_hum', 'p') def get_pressure(self): \"\"\"Gets the pressure as a",
"try: self.manager = connect_client() self.manager.use_emulator(self.use_emulator) self.sense_hat = self.manager.SenseHat() except ConnectionRefusedError as e: info('Sense",
"func = getattr(self.sense_hat, function_name) value = func(*args) return value except EOFError as e:",
"\"\"\"Gets the temperature as a tuple with type and unit.\"\"\" return (self.call_sense_hat_function('get_temperature'), 'temp',",
"Pi. \"\"\" import os from multiprocessing.managers import RemoteError from myDevices.utils.logger import error, exception,",
"\"\"\" self.use_emulator = use_emulator self.sense_hat = None self.digital_value = 0 self.analog_value = 0.0",
"def get_acclerometer(self): \"\"\"Gets the g-force as a tuple with type and unit.\"\"\" values",
"as a tuple with type and unit.\"\"\" value = self.call_sense_hat_function('get_pressure') if value is",
"connect_client() self.manager.use_emulator(self.use_emulator) self.sense_hat = self.manager.SenseHat() except ConnectionRefusedError as e: info('Sense HAT service connection",
"\"\"\"Calls a function of the SenseHat shared object. Arguments: function_name: Name of the",
"self.call_sense_hat_function('load_image', self.image_file) else: self.call_sense_hat_function('clear') def get_analog(self): \"\"\"Gets the digital value as a tuple",
"\"\"\"Gets the humidity as a tuple with type and unit.\"\"\" return (self.call_sense_hat_function('get_humidity'), 'rel_hum',",
"the Emulator to be installed and running on the desktop. \"\"\" self.use_emulator =",
"per second from the gyroscope.\"\"\" #Not currently supported in Cayenne values = self.call_sense_hat_function('get_gyroscope_raw')",
"self.init_sense_hat() try: if self.sense_hat is not None: func = getattr(self.sense_hat, function_name) value =",
"'accel', 'g') def get_gyroscope(self): \"\"\"Gets radians per second from the gyroscope.\"\"\" #Not currently",
"values = self.call_sense_hat_function('get_gyroscope_raw') if values is not None: rps = [] rps.append(values['x']) rps.append(values['y'])",
"specifying this is an analog actuator.\"\"\" return (self.analog_value, 'analog_actuator') def set_analog(self, value): \"\"\"Displays",
"to connect to Sense HAT device') def call_sense_hat_function(self, function_name, *args): \"\"\"Calls a function",
"info from sensehat.manager import connect_client class SenseHAT(): \"\"\"Class for interacting with a Sense",
"a tuple with type and unit.\"\"\" return (self.call_sense_hat_function('get_temperature'), 'temp', 'c') def get_humidity(self): \"\"\"Gets",
"rps.append(values['x']) rps.append(values['y']) rps.append(values['z']) return rps def get_magnetometer(self): \"\"\"Gets microteslas from the magnetometer.\"\"\" #Not",
"os from multiprocessing.managers import RemoteError from myDevices.utils.logger import error, exception, info from sensehat.manager",
"= func(*args) return value except EOFError as e: error(e) sense_hat = None except",
"refused') error(e) except RemoteError as e: error('Failed to connect to Sense HAT device')",
"board for Raspberry Pi. \"\"\" import os from multiprocessing.managers import RemoteError from myDevices.utils.logger",
"on the Sense HAT LED matrix if the digital value is equal to",
"to be installed and running on the desktop. \"\"\" self.use_emulator = use_emulator self.sense_hat",
"tuple with type and unit.\"\"\" return (self.call_sense_hat_function('get_temperature'), 'temp', 'c') def get_humidity(self): \"\"\"Gets the",
"value except EOFError as e: error(e) sense_hat = None except AttributeError as e:",
"\"\"\"Gets the digital value as a tuple specifying this is a digital actuator.\"\"\"",
"sense_hat = None def get_temperature(self): \"\"\"Gets the temperature as a tuple with type",
"Sense HAT Emulator should be used. This requires the Emulator to be installed",
"rps def get_magnetometer(self): \"\"\"Gets microteslas from the magnetometer.\"\"\" #Not currently supported in Cayenne",
"return rps def get_magnetometer(self): \"\"\"Gets microteslas from the magnetometer.\"\"\" #Not currently supported in",
"SenseHat shared object. Arguments: function_name: Name of the function to call. args: Arguments",
"def get_analog(self): \"\"\"Gets the digital value as a tuple specifying this is an",
"except ConnectionRefusedError as e: info('Sense HAT service connection refused') error(e) except RemoteError as",
"g-force as a tuple with type and unit.\"\"\" values = self.call_sense_hat_function('get_accelerometer_raw') if values",
"= [] gyro.append(values['x']) gyro.append(values['y']) gyro.append(values['z']) return gyro def get_digital(self): \"\"\"Gets the digital value",
"the Sense HAT add-on board for Raspberry Pi. \"\"\" import os from multiprocessing.managers",
"tuple with type and unit.\"\"\" values = self.call_sense_hat_function('get_accelerometer_raw') if values is not None:",
"gyro = [] gyro.append(values['x']) gyro.append(values['y']) gyro.append(values['z']) return gyro def get_digital(self): \"\"\"Gets the digital",
"if values is not None: rps = [] rps.append(values['x']) rps.append(values['y']) rps.append(values['z']) return rps",
"'analog_actuator') def set_analog(self, value): \"\"\"Displays the analog value on the Sense HAT LED",
"None: func = getattr(self.sense_hat, function_name) value = func(*args) return value except EOFError as",
"exception, info from sensehat.manager import connect_client class SenseHAT(): \"\"\"Class for interacting with a",
"is not None: g_force = [] g_force.append(values['x']) g_force.append(values['y']) g_force.append(values['z']) return (g_force, 'accel', 'g')",
"is an analog actuator.\"\"\" return (self.analog_value, 'analog_actuator') def set_analog(self, value): \"\"\"Displays the analog",
"as a tuple with type and unit.\"\"\" return (self.call_sense_hat_function('get_humidity'), 'rel_hum', 'p') def get_pressure(self):",
"supported in Cayenne values = self.call_sense_hat_function('get_compass_raw') if values is not None: gyro =",
"gyro.append(values['z']) return gyro def get_digital(self): \"\"\"Gets the digital value as a tuple specifying",
"import connect_client class SenseHAT(): \"\"\"Class for interacting with a Sense HAT device\"\"\" def",
"shared object. Arguments: function_name: Name of the function to call. args: Arguments to",
"as e: error(e) sense_hat = None def get_temperature(self): \"\"\"Gets the temperature as a",
"values is not None: rps = [] rps.append(values['x']) rps.append(values['y']) rps.append(values['z']) return rps def",
"if values is not None: gyro = [] gyro.append(values['x']) gyro.append(values['y']) gyro.append(values['z']) return gyro",
"if the Sense HAT Emulator should be used. This requires the Emulator to",
"in Cayenne values = self.call_sense_hat_function('get_gyroscope_raw') if values is not None: rps = []",
"def __init__(self, use_emulator=False): \"\"\"Initializes Sense HAT device. Arguments: use_emulator: True if the Sense",
"return (self.call_sense_hat_function('get_humidity'), 'rel_hum', 'p') def get_pressure(self): \"\"\"Gets the pressure as a tuple with",
"= connect_client() self.manager.use_emulator(self.use_emulator) self.sense_hat = self.manager.SenseHat() except ConnectionRefusedError as e: info('Sense HAT service",
"None: return (value * 100, 'bp', 'pa') def get_acclerometer(self): \"\"\"Gets the g-force as",
"as a tuple specifying this is a digital actuator.\"\"\" return (self.digital_value, 'digital_actuator') def",
"if self.digital_value: self.call_sense_hat_function('load_image', self.image_file) else: self.call_sense_hat_function('clear') def get_analog(self): \"\"\"Gets the digital value as",
"return gyro def get_digital(self): \"\"\"Gets the digital value as a tuple specifying this",
"analog value on the Sense HAT LED matrix.\"\"\" self.analog_value = value self.call_sense_hat_function('show_message', str(self.analog_value))",
"gyro.append(values['y']) gyro.append(values['z']) return gyro def get_digital(self): \"\"\"Gets the digital value as a tuple",
"self.call_sense_hat_function('get_compass_raw') if values is not None: gyro = [] gyro.append(values['x']) gyro.append(values['y']) gyro.append(values['z']) return",
"self.call_sense_hat_function('get_accelerometer_raw') if values is not None: g_force = [] g_force.append(values['x']) g_force.append(values['y']) g_force.append(values['z']) return",
"SenseHat shared object.\"\"\" if not self.sense_hat: try: self.manager = connect_client() self.manager.use_emulator(self.use_emulator) self.sense_hat =",
"self.manager.use_emulator(self.use_emulator) self.sense_hat = self.manager.SenseHat() except ConnectionRefusedError as e: info('Sense HAT service connection refused')",
"= value if self.digital_value: self.call_sense_hat_function('load_image', self.image_file) else: self.call_sense_hat_function('clear') def get_analog(self): \"\"\"Gets the digital",
"self.call_sense_hat_function('get_pressure') if value is not None: return (value * 100, 'bp', 'pa') def",
"def get_temperature(self): \"\"\"Gets the temperature as a tuple with type and unit.\"\"\" return",
"is a digital actuator.\"\"\" return (self.digital_value, 'digital_actuator') def set_digital(self, value): \"\"\"Displays an image",
"Emulator should be used. This requires the Emulator to be installed and running",
"e: error(e) sense_hat = None def get_temperature(self): \"\"\"Gets the temperature as a tuple",
"the pressure as a tuple with type and unit.\"\"\" value = self.call_sense_hat_function('get_pressure') if",
"requires the Emulator to be installed and running on the desktop. \"\"\" self.use_emulator",
"as a tuple with type and unit.\"\"\" values = self.call_sense_hat_function('get_accelerometer_raw') if values is",
"to True.\"\"\" self.digital_value = value if self.digital_value: self.call_sense_hat_function('load_image', self.image_file) else: self.call_sense_hat_function('clear') def get_analog(self):",
"the digital value as a tuple specifying this is an analog actuator.\"\"\" return",
"not None: return (value * 100, 'bp', 'pa') def get_acclerometer(self): \"\"\"Gets the g-force",
"get_gyroscope(self): \"\"\"Gets radians per second from the gyroscope.\"\"\" #Not currently supported in Cayenne",
"equal to True.\"\"\" self.digital_value = value if self.digital_value: self.call_sense_hat_function('load_image', self.image_file) else: self.call_sense_hat_function('clear') def",
"= self.call_sense_hat_function('get_accelerometer_raw') if values is not None: g_force = [] g_force.append(values['x']) g_force.append(values['y']) g_force.append(values['z'])",
"e: info('Sense HAT service connection refused') error(e) except RemoteError as e: error('Failed to",
"= None self.digital_value = 0 self.analog_value = 0.0 self.image_file = os.path.join('/etc/myDevices/plugins/cayenne-plugin-sensehat/data/image.png') self.call_sense_hat_function('clear') def",
"tuple with type and unit.\"\"\" value = self.call_sense_hat_function('get_pressure') if value is not None:",
"not None: rps = [] rps.append(values['x']) rps.append(values['y']) rps.append(values['z']) return rps def get_magnetometer(self): \"\"\"Gets",
"is not None: return (value * 100, 'bp', 'pa') def get_acclerometer(self): \"\"\"Gets the",
"def get_humidity(self): \"\"\"Gets the humidity as a tuple with type and unit.\"\"\" return",
"HAT device. Arguments: use_emulator: True if the Sense HAT Emulator should be used.",
"HAT service and gets a SenseHat shared object.\"\"\" if not self.sense_hat: try: self.manager",
"'temp', 'c') def get_humidity(self): \"\"\"Gets the humidity as a tuple with type and",
"values is not None: gyro = [] gyro.append(values['x']) gyro.append(values['y']) gyro.append(values['z']) return gyro def",
"if value is not None: return (value * 100, 'bp', 'pa') def get_acclerometer(self):",
"desktop. \"\"\" self.use_emulator = use_emulator self.sense_hat = None self.digital_value = 0 self.analog_value =",
"\"\"\"Gets the g-force as a tuple with type and unit.\"\"\" values = self.call_sense_hat_function('get_accelerometer_raw')",
"object. Arguments: function_name: Name of the function to call. args: Arguments to pass",
"import os from multiprocessing.managers import RemoteError from myDevices.utils.logger import error, exception, info from",
"a tuple with type and unit.\"\"\" values = self.call_sense_hat_function('get_accelerometer_raw') if values is not",
"currently supported in Cayenne values = self.call_sense_hat_function('get_gyroscope_raw') if values is not None: rps",
"a digital actuator.\"\"\" return (self.digital_value, 'digital_actuator') def set_digital(self, value): \"\"\"Displays an image on",
"0.0 self.image_file = os.path.join('/etc/myDevices/plugins/cayenne-plugin-sensehat/data/image.png') self.call_sense_hat_function('clear') def init_sense_hat(self): \"\"\"Initializes connection to Sense HAT service",
"second from the gyroscope.\"\"\" #Not currently supported in Cayenne values = self.call_sense_hat_function('get_gyroscope_raw') if",
"try: if self.sense_hat is not None: func = getattr(self.sense_hat, function_name) value = func(*args)",
"get_pressure(self): \"\"\"Gets the pressure as a tuple with type and unit.\"\"\" value =",
"'digital_actuator') def set_digital(self, value): \"\"\"Displays an image on the Sense HAT LED matrix",
"not None: gyro = [] gyro.append(values['x']) gyro.append(values['y']) gyro.append(values['z']) return gyro def get_digital(self): \"\"\"Gets",
"True if the Sense HAT Emulator should be used. This requires the Emulator",
"function. \"\"\" self.init_sense_hat() try: if self.sense_hat is not None: func = getattr(self.sense_hat, function_name)",
"except EOFError as e: error(e) sense_hat = None except AttributeError as e: error(e)",
"pressure as a tuple with type and unit.\"\"\" value = self.call_sense_hat_function('get_pressure') if value",
"\"\"\"Displays the analog value on the Sense HAT LED matrix.\"\"\" self.analog_value = value",
"\"\"\"Gets the pressure as a tuple with type and unit.\"\"\" value = self.call_sense_hat_function('get_pressure')",
"self.sense_hat = self.manager.SenseHat() except ConnectionRefusedError as e: info('Sense HAT service connection refused') error(e)",
"with type and unit.\"\"\" value = self.call_sense_hat_function('get_pressure') if value is not None: return",
"e: error('Failed to connect to Sense HAT device') def call_sense_hat_function(self, function_name, *args): \"\"\"Calls",
"return (self.analog_value, 'analog_actuator') def set_analog(self, value): \"\"\"Displays the analog value on the Sense",
"function to call. args: Arguments to pass to the function. \"\"\" self.init_sense_hat() try:",
"connection refused') error(e) except RemoteError as e: error('Failed to connect to Sense HAT",
"This requires the Emulator to be installed and running on the desktop. \"\"\"",
"value is equal to True.\"\"\" self.digital_value = value if self.digital_value: self.call_sense_hat_function('load_image', self.image_file) else:",
"RemoteError as e: error('Failed to connect to Sense HAT device') def call_sense_hat_function(self, function_name,",
"self.manager.SenseHat() except ConnectionRefusedError as e: info('Sense HAT service connection refused') error(e) except RemoteError",
"[] gyro.append(values['x']) gyro.append(values['y']) gyro.append(values['z']) return gyro def get_digital(self): \"\"\"Gets the digital value as",
"digital value as a tuple specifying this is a digital actuator.\"\"\" return (self.digital_value,",
"= os.path.join('/etc/myDevices/plugins/cayenne-plugin-sensehat/data/image.png') self.call_sense_hat_function('clear') def init_sense_hat(self): \"\"\"Initializes connection to Sense HAT service and gets",
"HAT Emulator should be used. This requires the Emulator to be installed and",
"g_force.append(values['z']) return (g_force, 'accel', 'g') def get_gyroscope(self): \"\"\"Gets radians per second from the",
"should be used. This requires the Emulator to be installed and running on",
"used. This requires the Emulator to be installed and running on the desktop.",
"gyro.append(values['x']) gyro.append(values['y']) gyro.append(values['z']) return gyro def get_digital(self): \"\"\"Gets the digital value as a",
"g_force.append(values['y']) g_force.append(values['z']) return (g_force, 'accel', 'g') def get_gyroscope(self): \"\"\"Gets radians per second from",
"value): \"\"\"Displays an image on the Sense HAT LED matrix if the digital",
"LED matrix if the digital value is equal to True.\"\"\" self.digital_value = value",
"a tuple specifying this is an analog actuator.\"\"\" return (self.analog_value, 'analog_actuator') def set_analog(self,",
"type and unit.\"\"\" return (self.call_sense_hat_function('get_humidity'), 'rel_hum', 'p') def get_pressure(self): \"\"\"Gets the pressure as",
"HAT service connection refused') error(e) except RemoteError as e: error('Failed to connect to",
"with a Sense HAT device\"\"\" def __init__(self, use_emulator=False): \"\"\"Initializes Sense HAT device. Arguments:",
"* 100, 'bp', 'pa') def get_acclerometer(self): \"\"\"Gets the g-force as a tuple with",
"running on the desktop. \"\"\" self.use_emulator = use_emulator self.sense_hat = None self.digital_value =",
"to the function. \"\"\" self.init_sense_hat() try: if self.sense_hat is not None: func =",
"as e: error('Failed to connect to Sense HAT device') def call_sense_hat_function(self, function_name, *args):",
"to Sense HAT device') def call_sense_hat_function(self, function_name, *args): \"\"\"Calls a function of the",
"None self.digital_value = 0 self.analog_value = 0.0 self.image_file = os.path.join('/etc/myDevices/plugins/cayenne-plugin-sensehat/data/image.png') self.call_sense_hat_function('clear') def init_sense_hat(self):",
"get_analog(self): \"\"\"Gets the digital value as a tuple specifying this is an analog",
"None: g_force = [] g_force.append(values['x']) g_force.append(values['y']) g_force.append(values['z']) return (g_force, 'accel', 'g') def get_gyroscope(self):",
"as e: error(e) sense_hat = None except AttributeError as e: error(e) sense_hat =",
"self.call_sense_hat_function('clear') def init_sense_hat(self): \"\"\"Initializes connection to Sense HAT service and gets a SenseHat",
"digital value as a tuple specifying this is an analog actuator.\"\"\" return (self.analog_value,",
"object.\"\"\" if not self.sense_hat: try: self.manager = connect_client() self.manager.use_emulator(self.use_emulator) self.sense_hat = self.manager.SenseHat() except",
"device\"\"\" def __init__(self, use_emulator=False): \"\"\"Initializes Sense HAT device. Arguments: use_emulator: True if the",
"else: self.call_sense_hat_function('clear') def get_analog(self): \"\"\"Gets the digital value as a tuple specifying this",
"self.digital_value = value if self.digital_value: self.call_sense_hat_function('load_image', self.image_file) else: self.call_sense_hat_function('clear') def get_analog(self): \"\"\"Gets the",
"= self.call_sense_hat_function('get_compass_raw') if values is not None: gyro = [] gyro.append(values['x']) gyro.append(values['y']) gyro.append(values['z'])",
"= None except AttributeError as e: error(e) sense_hat = None def get_temperature(self): \"\"\"Gets",
"True.\"\"\" self.digital_value = value if self.digital_value: self.call_sense_hat_function('load_image', self.image_file) else: self.call_sense_hat_function('clear') def get_analog(self): \"\"\"Gets",
"get_magnetometer(self): \"\"\"Gets microteslas from the magnetometer.\"\"\" #Not currently supported in Cayenne values =",
"the digital value as a tuple specifying this is a digital actuator.\"\"\" return",
"def get_gyroscope(self): \"\"\"Gets radians per second from the gyroscope.\"\"\" #Not currently supported in",
"RemoteError from myDevices.utils.logger import error, exception, info from sensehat.manager import connect_client class SenseHAT():",
"error(e) except RemoteError as e: error('Failed to connect to Sense HAT device') def",
"def call_sense_hat_function(self, function_name, *args): \"\"\"Calls a function of the SenseHat shared object. Arguments:",
"image on the Sense HAT LED matrix if the digital value is equal",
"= None def get_temperature(self): \"\"\"Gets the temperature as a tuple with type and",
"os.path.join('/etc/myDevices/plugins/cayenne-plugin-sensehat/data/image.png') self.call_sense_hat_function('clear') def init_sense_hat(self): \"\"\"Initializes connection to Sense HAT service and gets a",
"not self.sense_hat: try: self.manager = connect_client() self.manager.use_emulator(self.use_emulator) self.sense_hat = self.manager.SenseHat() except ConnectionRefusedError as",
"g_force = [] g_force.append(values['x']) g_force.append(values['y']) g_force.append(values['z']) return (g_force, 'accel', 'g') def get_gyroscope(self): \"\"\"Gets",
"if the digital value is equal to True.\"\"\" self.digital_value = value if self.digital_value:",
"module provides a class for interfacing with the Sense HAT add-on board for",
"class for interfacing with the Sense HAT add-on board for Raspberry Pi. \"\"\"",
"provides a class for interfacing with the Sense HAT add-on board for Raspberry",
"error('Failed to connect to Sense HAT device') def call_sense_hat_function(self, function_name, *args): \"\"\"Calls a",
"of the SenseHat shared object. Arguments: function_name: Name of the function to call.",
"(self.digital_value, 'digital_actuator') def set_digital(self, value): \"\"\"Displays an image on the Sense HAT LED",
"a tuple with type and unit.\"\"\" return (self.call_sense_hat_function('get_humidity'), 'rel_hum', 'p') def get_pressure(self): \"\"\"Gets",
"*args): \"\"\"Calls a function of the SenseHat shared object. Arguments: function_name: Name of",
"type and unit.\"\"\" return (self.call_sense_hat_function('get_temperature'), 'temp', 'c') def get_humidity(self): \"\"\"Gets the humidity as",
"the analog value on the Sense HAT LED matrix.\"\"\" self.analog_value = value self.call_sense_hat_function('show_message',",
"'p') def get_pressure(self): \"\"\"Gets the pressure as a tuple with type and unit.\"\"\"",
"= [] rps.append(values['x']) rps.append(values['y']) rps.append(values['z']) return rps def get_magnetometer(self): \"\"\"Gets microteslas from the",
"the SenseHat shared object. Arguments: function_name: Name of the function to call. args:",
"self.use_emulator = use_emulator self.sense_hat = None self.digital_value = 0 self.analog_value = 0.0 self.image_file",
"Arguments: function_name: Name of the function to call. args: Arguments to pass to",
"get_digital(self): \"\"\"Gets the digital value as a tuple specifying this is a digital",
"tuple with type and unit.\"\"\" return (self.call_sense_hat_function('get_humidity'), 'rel_hum', 'p') def get_pressure(self): \"\"\"Gets the",
"an image on the Sense HAT LED matrix if the digital value is",
"in Cayenne values = self.call_sense_hat_function('get_compass_raw') if values is not None: gyro = []",
"self.sense_hat is not None: func = getattr(self.sense_hat, function_name) value = func(*args) return value",
"interfacing with the Sense HAT add-on board for Raspberry Pi. \"\"\" import os",
"connection to Sense HAT service and gets a SenseHat shared object.\"\"\" if not",
"service and gets a SenseHat shared object.\"\"\" if not self.sense_hat: try: self.manager =",
"service connection refused') error(e) except RemoteError as e: error('Failed to connect to Sense",
"be used. This requires the Emulator to be installed and running on the",
"get_temperature(self): \"\"\"Gets the temperature as a tuple with type and unit.\"\"\" return (self.call_sense_hat_function('get_temperature'),",
"an analog actuator.\"\"\" return (self.analog_value, 'analog_actuator') def set_analog(self, value): \"\"\"Displays the analog value",
"multiprocessing.managers import RemoteError from myDevices.utils.logger import error, exception, info from sensehat.manager import connect_client",
"for Raspberry Pi. \"\"\" import os from multiprocessing.managers import RemoteError from myDevices.utils.logger import",
"Emulator to be installed and running on the desktop. \"\"\" self.use_emulator = use_emulator",
"if self.sense_hat is not None: func = getattr(self.sense_hat, function_name) value = func(*args) return",
"(value * 100, 'bp', 'pa') def get_acclerometer(self): \"\"\"Gets the g-force as a tuple",
"g_force.append(values['x']) g_force.append(values['y']) g_force.append(values['z']) return (g_force, 'accel', 'g') def get_gyroscope(self): \"\"\"Gets radians per second",
"Sense HAT device') def call_sense_hat_function(self, function_name, *args): \"\"\"Calls a function of the SenseHat",
"values = self.call_sense_hat_function('get_compass_raw') if values is not None: gyro = [] gyro.append(values['x']) gyro.append(values['y'])",
"if values is not None: g_force = [] g_force.append(values['x']) g_force.append(values['y']) g_force.append(values['z']) return (g_force,",
"[] rps.append(values['x']) rps.append(values['y']) rps.append(values['z']) return rps def get_magnetometer(self): \"\"\"Gets microteslas from the magnetometer.\"\"\"",
"the Sense HAT LED matrix if the digital value is equal to True.\"\"\"",
"gyroscope.\"\"\" #Not currently supported in Cayenne values = self.call_sense_hat_function('get_gyroscope_raw') if values is not",
"\"\"\" self.init_sense_hat() try: if self.sense_hat is not None: func = getattr(self.sense_hat, function_name) value",
"with type and unit.\"\"\" values = self.call_sense_hat_function('get_accelerometer_raw') if values is not None: g_force",
"HAT device\"\"\" def __init__(self, use_emulator=False): \"\"\"Initializes Sense HAT device. Arguments: use_emulator: True if",
"a tuple specifying this is a digital actuator.\"\"\" return (self.digital_value, 'digital_actuator') def set_digital(self,",
"getattr(self.sense_hat, function_name) value = func(*args) return value except EOFError as e: error(e) sense_hat",
"actuator.\"\"\" return (self.digital_value, 'digital_actuator') def set_digital(self, value): \"\"\"Displays an image on the Sense",
"init_sense_hat(self): \"\"\"Initializes connection to Sense HAT service and gets a SenseHat shared object.\"\"\"",
"the magnetometer.\"\"\" #Not currently supported in Cayenne values = self.call_sense_hat_function('get_compass_raw') if values is",
"SenseHAT(): \"\"\"Class for interacting with a Sense HAT device\"\"\" def __init__(self, use_emulator=False): \"\"\"Initializes",
"set_analog(self, value): \"\"\"Displays the analog value on the Sense HAT LED matrix.\"\"\" self.analog_value",
"the digital value is equal to True.\"\"\" self.digital_value = value if self.digital_value: self.call_sense_hat_function('load_image',",
"'pa') def get_acclerometer(self): \"\"\"Gets the g-force as a tuple with type and unit.\"\"\"",
"0 self.analog_value = 0.0 self.image_file = os.path.join('/etc/myDevices/plugins/cayenne-plugin-sensehat/data/image.png') self.call_sense_hat_function('clear') def init_sense_hat(self): \"\"\"Initializes connection to",
"a class for interfacing with the Sense HAT add-on board for Raspberry Pi.",
"e: error(e) sense_hat = None except AttributeError as e: error(e) sense_hat = None",
"get_humidity(self): \"\"\"Gets the humidity as a tuple with type and unit.\"\"\" return (self.call_sense_hat_function('get_humidity'),",
"#Not currently supported in Cayenne values = self.call_sense_hat_function('get_gyroscope_raw') if values is not None:",
"the temperature as a tuple with type and unit.\"\"\" return (self.call_sense_hat_function('get_temperature'), 'temp', 'c')",
"and unit.\"\"\" return (self.call_sense_hat_function('get_temperature'), 'temp', 'c') def get_humidity(self): \"\"\"Gets the humidity as a",
"= 0 self.analog_value = 0.0 self.image_file = os.path.join('/etc/myDevices/plugins/cayenne-plugin-sensehat/data/image.png') self.call_sense_hat_function('clear') def init_sense_hat(self): \"\"\"Initializes connection",
"to call. args: Arguments to pass to the function. \"\"\" self.init_sense_hat() try: if",
"analog actuator.\"\"\" return (self.analog_value, 'analog_actuator') def set_analog(self, value): \"\"\"Displays the analog value on",
"AttributeError as e: error(e) sense_hat = None def get_temperature(self): \"\"\"Gets the temperature as",
"\"\"\"Displays an image on the Sense HAT LED matrix if the digital value",
"tuple specifying this is a digital actuator.\"\"\" return (self.digital_value, 'digital_actuator') def set_digital(self, value):",
"digital actuator.\"\"\" return (self.digital_value, 'digital_actuator') def set_digital(self, value): \"\"\"Displays an image on the",
"error(e) sense_hat = None except AttributeError as e: error(e) sense_hat = None def",
"[] g_force.append(values['x']) g_force.append(values['y']) g_force.append(values['z']) return (g_force, 'accel', 'g') def get_gyroscope(self): \"\"\"Gets radians per",
"gyro def get_digital(self): \"\"\"Gets the digital value as a tuple specifying this is",
"on the desktop. \"\"\" self.use_emulator = use_emulator self.sense_hat = None self.digital_value = 0",
"self.manager = connect_client() self.manager.use_emulator(self.use_emulator) self.sense_hat = self.manager.SenseHat() except ConnectionRefusedError as e: info('Sense HAT",
"Cayenne values = self.call_sense_hat_function('get_compass_raw') if values is not None: gyro = [] gyro.append(values['x'])",
"def get_digital(self): \"\"\"Gets the digital value as a tuple specifying this is a",
"100, 'bp', 'pa') def get_acclerometer(self): \"\"\"Gets the g-force as a tuple with type",
"Raspberry Pi. \"\"\" import os from multiprocessing.managers import RemoteError from myDevices.utils.logger import error,",
"def set_digital(self, value): \"\"\"Displays an image on the Sense HAT LED matrix if",
"a Sense HAT device\"\"\" def __init__(self, use_emulator=False): \"\"\"Initializes Sense HAT device. Arguments: use_emulator:",
"sense_hat = None except AttributeError as e: error(e) sense_hat = None def get_temperature(self):",
"(self.call_sense_hat_function('get_humidity'), 'rel_hum', 'p') def get_pressure(self): \"\"\"Gets the pressure as a tuple with type",
"temperature as a tuple with type and unit.\"\"\" return (self.call_sense_hat_function('get_temperature'), 'temp', 'c') def",
"\"\"\"Initializes Sense HAT device. Arguments: use_emulator: True if the Sense HAT Emulator should",
"rps.append(values['z']) return rps def get_magnetometer(self): \"\"\"Gets microteslas from the magnetometer.\"\"\" #Not currently supported",
"(g_force, 'accel', 'g') def get_gyroscope(self): \"\"\"Gets radians per second from the gyroscope.\"\"\" #Not",
"Cayenne values = self.call_sense_hat_function('get_gyroscope_raw') if values is not None: rps = [] rps.append(values['x'])",
"args: Arguments to pass to the function. \"\"\" self.init_sense_hat() try: if self.sense_hat is",
"def set_analog(self, value): \"\"\"Displays the analog value on the Sense HAT LED matrix.\"\"\"",
"\"\"\" import os from multiprocessing.managers import RemoteError from myDevices.utils.logger import error, exception, info",
"self.sense_hat: try: self.manager = connect_client() self.manager.use_emulator(self.use_emulator) self.sense_hat = self.manager.SenseHat() except ConnectionRefusedError as e:",
"'rel_hum', 'p') def get_pressure(self): \"\"\"Gets the pressure as a tuple with type and",
"return (value * 100, 'bp', 'pa') def get_acclerometer(self): \"\"\"Gets the g-force as a",
"use_emulator: True if the Sense HAT Emulator should be used. This requires the",
"= 0.0 self.image_file = os.path.join('/etc/myDevices/plugins/cayenne-plugin-sensehat/data/image.png') self.call_sense_hat_function('clear') def init_sense_hat(self): \"\"\"Initializes connection to Sense HAT",
"connect to Sense HAT device') def call_sense_hat_function(self, function_name, *args): \"\"\"Calls a function of",
"currently supported in Cayenne values = self.call_sense_hat_function('get_compass_raw') if values is not None: gyro",
"myDevices.utils.logger import error, exception, info from sensehat.manager import connect_client class SenseHAT(): \"\"\"Class for",
"function of the SenseHat shared object. Arguments: function_name: Name of the function to",
"to pass to the function. \"\"\" self.init_sense_hat() try: if self.sense_hat is not None:",
"set_digital(self, value): \"\"\"Displays an image on the Sense HAT LED matrix if the",
"value as a tuple specifying this is an analog actuator.\"\"\" return (self.analog_value, 'analog_actuator')",
"= self.call_sense_hat_function('get_pressure') if value is not None: return (value * 100, 'bp', 'pa')",
"'c') def get_humidity(self): \"\"\"Gets the humidity as a tuple with type and unit.\"\"\"",
"\"\"\"Initializes connection to Sense HAT service and gets a SenseHat shared object.\"\"\" if",
"def get_magnetometer(self): \"\"\"Gets microteslas from the magnetometer.\"\"\" #Not currently supported in Cayenne values",
"call_sense_hat_function(self, function_name, *args): \"\"\"Calls a function of the SenseHat shared object. Arguments: function_name:",
"def get_pressure(self): \"\"\"Gets the pressure as a tuple with type and unit.\"\"\" value",
"None: gyro = [] gyro.append(values['x']) gyro.append(values['y']) gyro.append(values['z']) return gyro def get_digital(self): \"\"\"Gets the",
"unit.\"\"\" return (self.call_sense_hat_function('get_humidity'), 'rel_hum', 'p') def get_pressure(self): \"\"\"Gets the pressure as a tuple",
"error(e) sense_hat = None def get_temperature(self): \"\"\"Gets the temperature as a tuple with",
"This module provides a class for interfacing with the Sense HAT add-on board",
"installed and running on the desktop. \"\"\" self.use_emulator = use_emulator self.sense_hat = None",
"device') def call_sense_hat_function(self, function_name, *args): \"\"\"Calls a function of the SenseHat shared object.",
"gets a SenseHat shared object.\"\"\" if not self.sense_hat: try: self.manager = connect_client() self.manager.use_emulator(self.use_emulator)",
"self.digital_value = 0 self.analog_value = 0.0 self.image_file = os.path.join('/etc/myDevices/plugins/cayenne-plugin-sensehat/data/image.png') self.call_sense_hat_function('clear') def init_sense_hat(self): \"\"\"Initializes",
"with type and unit.\"\"\" return (self.call_sense_hat_function('get_humidity'), 'rel_hum', 'p') def get_pressure(self): \"\"\"Gets the pressure",
"ConnectionRefusedError as e: info('Sense HAT service connection refused') error(e) except RemoteError as e:",
"from myDevices.utils.logger import error, exception, info from sensehat.manager import connect_client class SenseHAT(): \"\"\"Class",
"microteslas from the magnetometer.\"\"\" #Not currently supported in Cayenne values = self.call_sense_hat_function('get_compass_raw') if",
"except AttributeError as e: error(e) sense_hat = None def get_temperature(self): \"\"\"Gets the temperature",
"func(*args) return value except EOFError as e: error(e) sense_hat = None except AttributeError",
"and unit.\"\"\" value = self.call_sense_hat_function('get_pressure') if value is not None: return (value *",
"with type and unit.\"\"\" return (self.call_sense_hat_function('get_temperature'), 'temp', 'c') def get_humidity(self): \"\"\"Gets the humidity",
"the desktop. \"\"\" self.use_emulator = use_emulator self.sense_hat = None self.digital_value = 0 self.analog_value",
"the gyroscope.\"\"\" #Not currently supported in Cayenne values = self.call_sense_hat_function('get_gyroscope_raw') if values is",
"Sense HAT device. Arguments: use_emulator: True if the Sense HAT Emulator should be",
"#Not currently supported in Cayenne values = self.call_sense_hat_function('get_compass_raw') if values is not None:",
"Arguments: use_emulator: True if the Sense HAT Emulator should be used. This requires",
"\"\"\"Gets radians per second from the gyroscope.\"\"\" #Not currently supported in Cayenne values",
"= getattr(self.sense_hat, function_name) value = func(*args) return value except EOFError as e: error(e)",
"(self.call_sense_hat_function('get_temperature'), 'temp', 'c') def get_humidity(self): \"\"\"Gets the humidity as a tuple with type",
"HAT device') def call_sense_hat_function(self, function_name, *args): \"\"\"Calls a function of the SenseHat shared",
"a function of the SenseHat shared object. Arguments: function_name: Name of the function",
"the g-force as a tuple with type and unit.\"\"\" values = self.call_sense_hat_function('get_accelerometer_raw') if",
"__init__(self, use_emulator=False): \"\"\"Initializes Sense HAT device. Arguments: use_emulator: True if the Sense HAT",
"the function to call. args: Arguments to pass to the function. \"\"\" self.init_sense_hat()",
"'bp', 'pa') def get_acclerometer(self): \"\"\"Gets the g-force as a tuple with type and",
"from sensehat.manager import connect_client class SenseHAT(): \"\"\"Class for interacting with a Sense HAT",
"as a tuple specifying this is an analog actuator.\"\"\" return (self.analog_value, 'analog_actuator') def",
"interacting with a Sense HAT device\"\"\" def __init__(self, use_emulator=False): \"\"\"Initializes Sense HAT device.",
"value is not None: return (value * 100, 'bp', 'pa') def get_acclerometer(self): \"\"\"Gets",
"value if self.digital_value: self.call_sense_hat_function('load_image', self.image_file) else: self.call_sense_hat_function('clear') def get_analog(self): \"\"\"Gets the digital value",
"Sense HAT device\"\"\" def __init__(self, use_emulator=False): \"\"\"Initializes Sense HAT device. Arguments: use_emulator: True",
"import RemoteError from myDevices.utils.logger import error, exception, info from sensehat.manager import connect_client class",
"Name of the function to call. args: Arguments to pass to the function.",
"this is a digital actuator.\"\"\" return (self.digital_value, 'digital_actuator') def set_digital(self, value): \"\"\"Displays an",
"values is not None: g_force = [] g_force.append(values['x']) g_force.append(values['y']) g_force.append(values['z']) return (g_force, 'accel',",
"Sense HAT LED matrix if the digital value is equal to True.\"\"\" self.digital_value",
"device. Arguments: use_emulator: True if the Sense HAT Emulator should be used. This",
"call. args: Arguments to pass to the function. \"\"\" self.init_sense_hat() try: if self.sense_hat",
"type and unit.\"\"\" values = self.call_sense_hat_function('get_accelerometer_raw') if values is not None: g_force =",
"EOFError as e: error(e) sense_hat = None except AttributeError as e: error(e) sense_hat",
"a tuple with type and unit.\"\"\" value = self.call_sense_hat_function('get_pressure') if value is not",
"from multiprocessing.managers import RemoteError from myDevices.utils.logger import error, exception, info from sensehat.manager import",
"value = func(*args) return value except EOFError as e: error(e) sense_hat = None",
"from the magnetometer.\"\"\" #Not currently supported in Cayenne values = self.call_sense_hat_function('get_compass_raw') if values",
"unit.\"\"\" return (self.call_sense_hat_function('get_temperature'), 'temp', 'c') def get_humidity(self): \"\"\"Gets the humidity as a tuple",
"value = self.call_sense_hat_function('get_pressure') if value is not None: return (value * 100, 'bp',",
"and unit.\"\"\" values = self.call_sense_hat_function('get_accelerometer_raw') if values is not None: g_force = []",
"as a tuple with type and unit.\"\"\" return (self.call_sense_hat_function('get_temperature'), 'temp', 'c') def get_humidity(self):",
"tuple specifying this is an analog actuator.\"\"\" return (self.analog_value, 'analog_actuator') def set_analog(self, value):",
"and running on the desktop. \"\"\" self.use_emulator = use_emulator self.sense_hat = None self.digital_value",
"return (self.digital_value, 'digital_actuator') def set_digital(self, value): \"\"\"Displays an image on the Sense HAT",
"\"\"\"Gets microteslas from the magnetometer.\"\"\" #Not currently supported in Cayenne values = self.call_sense_hat_function('get_compass_raw')",
"from the gyroscope.\"\"\" #Not currently supported in Cayenne values = self.call_sense_hat_function('get_gyroscope_raw') if values",
"value as a tuple specifying this is a digital actuator.\"\"\" return (self.digital_value, 'digital_actuator')",
"not None: func = getattr(self.sense_hat, function_name) value = func(*args) return value except EOFError",
"class SenseHAT(): \"\"\"Class for interacting with a Sense HAT device\"\"\" def __init__(self, use_emulator=False):",
"is equal to True.\"\"\" self.digital_value = value if self.digital_value: self.call_sense_hat_function('load_image', self.image_file) else: self.call_sense_hat_function('clear')",
"None: rps = [] rps.append(values['x']) rps.append(values['y']) rps.append(values['z']) return rps def get_magnetometer(self): \"\"\"Gets microteslas",
"self.image_file = os.path.join('/etc/myDevices/plugins/cayenne-plugin-sensehat/data/image.png') self.call_sense_hat_function('clear') def init_sense_hat(self): \"\"\"Initializes connection to Sense HAT service and",
"as e: info('Sense HAT service connection refused') error(e) except RemoteError as e: error('Failed",
"HAT LED matrix if the digital value is equal to True.\"\"\" self.digital_value =",
"is not None: func = getattr(self.sense_hat, function_name) value = func(*args) return value except",
"pass to the function. \"\"\" self.init_sense_hat() try: if self.sense_hat is not None: func",
"this is an analog actuator.\"\"\" return (self.analog_value, 'analog_actuator') def set_analog(self, value): \"\"\"Displays the",
"function_name, *args): \"\"\"Calls a function of the SenseHat shared object. Arguments: function_name: Name",
"specifying this is a digital actuator.\"\"\" return (self.digital_value, 'digital_actuator') def set_digital(self, value): \"\"\"Displays",
"for interacting with a Sense HAT device\"\"\" def __init__(self, use_emulator=False): \"\"\"Initializes Sense HAT",
"get_acclerometer(self): \"\"\"Gets the g-force as a tuple with type and unit.\"\"\" values =",
"a SenseHat shared object.\"\"\" if not self.sense_hat: try: self.manager = connect_client() self.manager.use_emulator(self.use_emulator) self.sense_hat",
"shared object.\"\"\" if not self.sense_hat: try: self.manager = connect_client() self.manager.use_emulator(self.use_emulator) self.sense_hat = self.manager.SenseHat()",
"is not None: gyro = [] gyro.append(values['x']) gyro.append(values['y']) gyro.append(values['z']) return gyro def get_digital(self):",
"def init_sense_hat(self): \"\"\"Initializes connection to Sense HAT service and gets a SenseHat shared",
"None def get_temperature(self): \"\"\"Gets the temperature as a tuple with type and unit.\"\"\"",
"= [] g_force.append(values['x']) g_force.append(values['y']) g_force.append(values['z']) return (g_force, 'accel', 'g') def get_gyroscope(self): \"\"\"Gets radians",
"the Sense HAT Emulator should be used. This requires the Emulator to be",
"supported in Cayenne values = self.call_sense_hat_function('get_gyroscope_raw') if values is not None: rps =",
"None except AttributeError as e: error(e) sense_hat = None def get_temperature(self): \"\"\"Gets the",
"unit.\"\"\" values = self.call_sense_hat_function('get_accelerometer_raw') if values is not None: g_force = [] g_force.append(values['x'])",
"radians per second from the gyroscope.\"\"\" #Not currently supported in Cayenne values =",
"\"\"\"Gets the digital value as a tuple specifying this is an analog actuator.\"\"\"",
"be installed and running on the desktop. \"\"\" self.use_emulator = use_emulator self.sense_hat =",
"connect_client class SenseHAT(): \"\"\"Class for interacting with a Sense HAT device\"\"\" def __init__(self,",
"self.sense_hat = None self.digital_value = 0 self.analog_value = 0.0 self.image_file = os.path.join('/etc/myDevices/plugins/cayenne-plugin-sensehat/data/image.png') self.call_sense_hat_function('clear')",
"values = self.call_sense_hat_function('get_accelerometer_raw') if values is not None: g_force = [] g_force.append(values['x']) g_force.append(values['y'])",
"value): \"\"\"Displays the analog value on the Sense HAT LED matrix.\"\"\" self.analog_value =",
"matrix if the digital value is equal to True.\"\"\" self.digital_value = value if",
"with the Sense HAT add-on board for Raspberry Pi. \"\"\" import os from",
"rps.append(values['y']) rps.append(values['z']) return rps def get_magnetometer(self): \"\"\"Gets microteslas from the magnetometer.\"\"\" #Not currently",
"and gets a SenseHat shared object.\"\"\" if not self.sense_hat: try: self.manager = connect_client()"
] |
[
"_shutdown(): print(__file__, \"_shutdown\") # https://docs.python.org/3/library/threading.html#threading.excepthook # a green thread # FIXME: fix wapy",
"- self.last) - self.slice if self.delta < 0: self.delta = 0 yield from",
"is None: self.name = \"%s-%s\" % (self.__class__.__name__, id(self)) self.status = None async def",
"__await__(self): if self.status is True: rtc = aio.rtclock() self.delta = (rtc - self.last)",
"aio.error = None aio.paused = False aio.fd = {} aio.pstab = {} def",
"True: rtc = aio.rtclock() self.delta = (rtc - self.last) - self.slice if self.delta",
"= False aio.fd = {} aio.pstab = {} def _shutdown(): print(__file__, \"_shutdown\") #",
"proc(srv): return aio.pstab.get(srv) class Runnable: def __await__(self): yield from aio.pstab.get(self).__await__() # replace with",
"raise RuntimeError(\"wait not supported\") class Thread: def __init__( self, group=None, target=None, name=None, args=(),",
"(self.__class__.__name__, id(self)) self.status = None async def wrap(self): for idle in self.run(*self.args, **self.kwargs):",
"aio.rtclock() self.delta = (rtc - self.last) - self.slice if self.delta < 0: self.delta",
"self.count += 1 return True def release(self): self.count -= 1 def locked(self): return",
"context here async with aio.ctx(self.slice).call(coro): self.status = False except Exception as e: self.status",
"async with aio.ctx(self.slice).call(coro): self.status = False except Exception as e: self.status = repr(e)",
"aio.create_task(self.runner(coro)) aio.pstab[self.name].append(self) return self def join(self): embed.enable_irq() while self.is_alive(): aio_suspend() embed.disable_irq() def __bool__(self):",
"= self.run(*self.args, **self.kwargs) pdb(\"168:\", self.name, \"starting\", coro) aio.create_task(self.runner(coro)) aio.pstab[self.name].append(self) return self def join(self):",
"0 self.last = aio.rtclock() if target: if hasattr(target, \"run\"): if name is None:",
"is True: rtc = aio.rtclock() self.delta = (rtc - self.last) - self.slice if",
"aio.sleep_ms(self.slice - int(self.delta / 2)) self.last = rtc __await__ = __iter__ else: def",
"release(self): self.lock.release() def wait(self, timeout=None): raise RuntimeError(\"notify not supported\") def wait_for(self, predicate, timeout=None):",
"= repr(e) sys.print_exception(e, sys.stderr) if __UPY__: def __iter__(self): if self.status is True: rtc",
"__init__( self, group=None, target=None, name=None, args=(), kwargs={}, *, daemon=None ): # def __init__(self,",
"% (self.run.__name__, id(self)) except: pass else: target = self if self.name is None:",
"target = self if self.name is None: self.name = \"%s-%s\" % (self.__class__.__name__, id(self))",
"wapy BUG 882 so target can be None too in preempt mode #",
"self.last = rtc def rt(self, slice): self.slice = int(float(slice) * 1_000) return self",
"import aio import inspect # mark not started but no error aio.error =",
"return self def start(self): aio.pstab.setdefault(self.name, []) if self.run: if not inspect.iscoroutinefunction(self.run): self.status =",
"self.status = False except Exception as e: self.status = repr(e) sys.print_exception(e, sys.stderr) if",
"name self.slice = 0 self.last = aio.rtclock() if target: if hasattr(target, \"run\"): if",
"local context here async with aio.ctx(self.slice).call(coro): self.status = False except Exception as e:",
"timeout=None): raise RuntimeError(\"wait not supported\") class Thread: def __init__( self, group=None, target=None, name=None,",
"mode # TODO: default granularity with https://docs.python.org/3/library/sys.html#sys.setswitchinterval class Lock: count = 0 def",
"acquire(self, *args): return self.lock.acquire() def release(self): self.lock.release() def wait(self, timeout=None): raise RuntimeError(\"notify not",
"return aio.sleep( float(self.slice - int(self.delta / 2)) / 1_000 ) self.last = rtc",
"aio.rtclock() if target: if hasattr(target, \"run\"): if name is None: self.name = name",
"\"starting\", coro) aio.create_task(self.runner(coro)) aio.pstab[self.name].append(self) return self def join(self): embed.enable_irq() while self.is_alive(): aio_suspend() embed.disable_irq()",
"if target: if hasattr(target, \"run\"): if name is None: self.name = name or",
"= {} def _shutdown(): print(__file__, \"_shutdown\") # https://docs.python.org/3/library/threading.html#threading.excepthook # a green thread #",
"with aio.ctx(self.slice).call(coro): self.status = False except Exception as e: self.status = repr(e) sys.print_exception(e,",
"<filename>support/cross/aio/gthread.py import aio import inspect # mark not started but no error aio.error",
"lock or Lock() def acquire(self, *args): return self.lock.acquire() def release(self): self.lock.release() def wait(self,",
"= aio.rtclock() self.delta = (rtc - self.last) - self.slice if self.delta < 0:",
"def wait(self, timeout=None): raise RuntimeError(\"notify not supported\") def wait_for(self, predicate, timeout=None): raise RuntimeError(\"wait",
"True try: # TODO: pass thread local context here async with aio.ctx(self.slice).call(coro): self.status",
"return self.lock.acquire() def release(self): self.lock.release() def wait(self, timeout=None): raise RuntimeError(\"notify not supported\") def",
"thread local context here async with aio.ctx(self.slice).call(coro): self.status = False except Exception as",
"= {} aio.pstab = {} def _shutdown(): print(__file__, \"_shutdown\") # https://docs.python.org/3/library/threading.html#threading.excepthook # a",
"= aio.rtclock() if target: if hasattr(target, \"run\"): if name is None: self.name =",
"runner(self, coro): self.status = True try: # TODO: pass thread local context here",
"- int(self.delta / 2)) / 1_000 ) self.last = rtc def rt(self, slice):",
"rtc def rt(self, slice): self.slice = int(float(slice) * 1_000) return self def start(self):",
"- int(self.delta / 2)) / 1_000 ).__await__() # return aio.sleep( float(self.slice - int(self.delta",
"else: target = self if self.name is None: self.name = \"%s-%s\" % (self.__class__.__name__,",
"else: coro = self.run(*self.args, **self.kwargs) pdb(\"168:\", self.name, \"starting\", coro) aio.create_task(self.runner(coro)) aio.pstab[self.name].append(self) return self",
"= int(float(slice) * 1_000) return self def start(self): aio.pstab.setdefault(self.name, []) if self.run: if",
"None: try: self.name = \"%s-%s\" % (self.run.__name__, id(self)) except: pass else: target =",
"return True def release(self): self.count -= 1 def locked(self): return self.count>0 class Condition:",
"not started but no error aio.error = None aio.paused = False aio.fd =",
"rtc = aio.rtclock() self.delta = (rtc - self.last) - self.slice if self.delta <",
"self.is_alive() and not aio.exit def is_alive(self): return self.status is True def service(srv, *argv,",
"= service def proc(srv): return aio.pstab.get(srv) class Runnable: def __await__(self): yield from aio.pstab.get(self).__await__()",
"hasattr(target, \"run\"): if name is None: self.name = name or target.__class__.__name__ self.run =",
"def _shutdown(): print(__file__, \"_shutdown\") # https://docs.python.org/3/library/threading.html#threading.excepthook # a green thread # FIXME: fix",
"wait(self, timeout=None): raise RuntimeError(\"notify not supported\") def wait_for(self, predicate, timeout=None): raise RuntimeError(\"wait not",
"= rtc __await__ = __iter__ else: def __await__(self): if self.status is True: rtc",
"def __iter__(self): if self.status is True: rtc = aio.rtclock() self.delta = (rtc -",
"[]) if self.run: if not inspect.iscoroutinefunction(self.run): self.status = True aio.create_task(self.wrap()) else: coro =",
"aio.create_task(self.wrap()) else: coro = self.run(*self.args, **self.kwargs) pdb(\"168:\", self.name, \"starting\", coro) aio.create_task(self.runner(coro)) aio.pstab[self.name].append(self) return",
"/ 2)) / 1_000 ).__await__() # return aio.sleep( float(self.slice - int(self.delta / 2))",
"cpy yield from aio.sleep_ms( float(self.slice - int(self.delta / 2)) / 1_000 ).__await__() #",
"is None: try: self.name = \"%s-%s\" % (self.run.__name__, id(self)) except: pass else: target",
"supported\") def wait_for(self, predicate, timeout=None): raise RuntimeError(\"wait not supported\") class Thread: def __init__(",
"*args): return self.lock.acquire() def release(self): self.lock.release() def wait(self, timeout=None): raise RuntimeError(\"notify not supported\")",
"if not inspect.iscoroutinefunction(self.run): self.status = True aio.create_task(self.wrap()) else: coro = self.run(*self.args, **self.kwargs) pdb(\"168:\",",
"class Runnable: def __await__(self): yield from aio.pstab.get(self).__await__() # replace with green threading import",
"aio_suspend() embed.disable_irq() def __bool__(self): return self.is_alive() and not aio.exit def is_alive(self): return self.status",
"idle in self.run(*self.args, **self.kwargs): await aio.sleep(0) async def runner(self, coro): self.status = True",
"0 yield from aio.sleep_ms(self.slice - int(self.delta / 2)) self.last = rtc __await__ =",
"blocking=True, timeout=- 1): self.count += 1 return True def release(self): self.count -= 1",
"pdb(\"168:\", self.name, \"starting\", coro) aio.create_task(self.runner(coro)) aio.pstab[self.name].append(self) return self def join(self): embed.enable_irq() while self.is_alive():",
"thr.__await__ return aio.pstab.setdefault(srv, thr) aio.task = service def proc(srv): return aio.pstab.get(srv) class Runnable:",
"Exception as e: self.status = repr(e) sys.print_exception(e, sys.stderr) if __UPY__: def __iter__(self): if",
"timeout=- 1): self.count += 1 return True def release(self): self.count -= 1 def",
"mark not started but no error aio.error = None aio.paused = False aio.fd",
"True aio.create_task(self.wrap()) else: coro = self.run(*self.args, **self.kwargs) pdb(\"168:\", self.name, \"starting\", coro) aio.create_task(self.runner(coro)) aio.pstab[self.name].append(self)",
"def start(self): aio.pstab.setdefault(self.name, []) if self.run: if not inspect.iscoroutinefunction(self.run): self.status = True aio.create_task(self.wrap())",
"wait_for(self, predicate, timeout=None): raise RuntimeError(\"wait not supported\") class Thread: def __init__( self, group=None,",
"def __bool__(self): return self.is_alive() and not aio.exit def is_alive(self): return self.status is True",
"self.name = \"%s-%s\" % (self.run.__name__, id(self)) except: pass else: target = self if",
"aio.pstab[self.name].append(self) return self def join(self): embed.enable_irq() while self.is_alive(): aio_suspend() embed.disable_irq() def __bool__(self): return",
"args self.kwargs = kwargs self.name = name self.slice = 0 self.last = aio.rtclock()",
"return self.is_alive() and not aio.exit def is_alive(self): return self.status is True def service(srv,",
"return aio.pstab.get(srv) class Runnable: def __await__(self): yield from aio.pstab.get(self).__await__() # replace with green",
"count = 0 def __enter__(self): self.acquire() def __exit__(self, *tb): self.release() def acquire(self, blocking=True,",
"thr = aio.Thread(group=None, target=srv, args=argv, kwargs=kw).start() srv.__await__ = thr.__await__ return aio.pstab.setdefault(srv, thr) aio.task",
"def join(self): embed.enable_irq() while self.is_alive(): aio_suspend() embed.disable_irq() def __bool__(self): return self.is_alive() and not",
"target=None, name=None, args=(), kwargs={}, *, daemon=None ): # def __init__(self, group=None, target=None, name=None,",
"float(self.slice - int(self.delta / 2)) / 1_000 ) self.last = rtc def rt(self,",
"coro = self.run(*self.args, **self.kwargs) pdb(\"168:\", self.name, \"starting\", coro) aio.create_task(self.runner(coro)) aio.pstab[self.name].append(self) return self def",
"+= 1 return True def release(self): self.count -= 1 def locked(self): return self.count>0",
"started but no error aio.error = None aio.paused = False aio.fd = {}",
"0: self.delta = 0 # no sleep_ms on cpy yield from aio.sleep_ms( float(self.slice",
"# mark not started but no error aio.error = None aio.paused = False",
"self.last = aio.rtclock() if target: if hasattr(target, \"run\"): if name is None: self.name",
"id(self)) self.status = None async def wrap(self): for idle in self.run(*self.args, **self.kwargs): await",
"= 0 def __enter__(self): self.acquire() def __exit__(self, *tb): self.release() def acquire(self, blocking=True, timeout=-",
"as e: self.status = repr(e) sys.print_exception(e, sys.stderr) if __UPY__: def __iter__(self): if self.status",
"None: self.name = name or target.__class__.__name__ self.run = target.run else: self.run = target",
"= False except Exception as e: self.status = repr(e) sys.print_exception(e, sys.stderr) if __UPY__:",
"not aio.exit def is_alive(self): return self.status is True def service(srv, *argv, **kw): embed.log(f\"starting",
"print(__file__, \"_shutdown\") # https://docs.python.org/3/library/threading.html#threading.excepthook # a green thread # FIXME: fix wapy BUG",
"granularity with https://docs.python.org/3/library/sys.html#sys.setswitchinterval class Lock: count = 0 def __enter__(self): self.acquire() def __exit__(self,",
"try: self.name = \"%s-%s\" % (self.run.__name__, id(self)) except: pass else: target = self",
"except: pass else: target = self if self.name is None: self.name = \"%s-%s\"",
"- self.slice if self.delta < 0: self.delta = 0 # no sleep_ms on",
"{} aio.pstab = {} def _shutdown(): print(__file__, \"_shutdown\") # https://docs.python.org/3/library/threading.html#threading.excepthook # a green",
"- self.slice if self.delta < 0: self.delta = 0 yield from aio.sleep_ms(self.slice -",
"True def service(srv, *argv, **kw): embed.log(f\"starting green thread : {srv}\") thr = aio.Thread(group=None,",
"__init__(self, group=None, target=None, name=None, args=(), kwargs={}): self.args = args self.kwargs = kwargs self.name",
") self.last = rtc def rt(self, slice): self.slice = int(float(slice) * 1_000) return",
"2)) self.last = rtc __await__ = __iter__ else: def __await__(self): if self.status is",
"if hasattr(target, \"run\"): if name is None: self.name = name or target.__class__.__name__ self.run",
"self.name = name or target.__class__.__name__ self.run = target.run else: self.run = target if",
"try: # TODO: pass thread local context here async with aio.ctx(self.slice).call(coro): self.status =",
"if self.run: if not inspect.iscoroutinefunction(self.run): self.status = True aio.create_task(self.wrap()) else: coro = self.run(*self.args,",
"await aio.sleep(0) async def runner(self, coro): self.status = True try: # TODO: pass",
"= \"%s-%s\" % (self.__class__.__name__, id(self)) self.status = None async def wrap(self): for idle",
"self.last) - self.slice if self.delta < 0: self.delta = 0 # no sleep_ms",
"async def runner(self, coro): self.status = True try: # TODO: pass thread local",
"no error aio.error = None aio.paused = False aio.fd = {} aio.pstab =",
"is None: self.name = name or target.__class__.__name__ self.run = target.run else: self.run =",
"Condition: def __init__(self, lock=None): self.lock = lock or Lock() def acquire(self, *args): return",
"__iter__(self): if self.status is True: rtc = aio.rtclock() self.delta = (rtc - self.last)",
"aio import inspect # mark not started but no error aio.error = None",
"self.slice if self.delta < 0: self.delta = 0 yield from aio.sleep_ms(self.slice - int(self.delta",
"a green thread # FIXME: fix wapy BUG 882 so target can be",
"def locked(self): return self.count>0 class Condition: def __init__(self, lock=None): self.lock = lock or",
"False aio.fd = {} aio.pstab = {} def _shutdown(): print(__file__, \"_shutdown\") # https://docs.python.org/3/library/threading.html#threading.excepthook",
"int(float(slice) * 1_000) return self def start(self): aio.pstab.setdefault(self.name, []) if self.run: if not",
"def release(self): self.lock.release() def wait(self, timeout=None): raise RuntimeError(\"notify not supported\") def wait_for(self, predicate,",
"self.slice = 0 self.last = aio.rtclock() if target: if hasattr(target, \"run\"): if name",
"= args self.kwargs = kwargs self.name = name self.slice = 0 self.last =",
"not inspect.iscoroutinefunction(self.run): self.status = True aio.create_task(self.wrap()) else: coro = self.run(*self.args, **self.kwargs) pdb(\"168:\", self.name,",
"rt(self, slice): self.slice = int(float(slice) * 1_000) return self def start(self): aio.pstab.setdefault(self.name, [])",
"aio.ctx(self.slice).call(coro): self.status = False except Exception as e: self.status = repr(e) sys.print_exception(e, sys.stderr)",
"Lock: count = 0 def __enter__(self): self.acquire() def __exit__(self, *tb): self.release() def acquire(self,",
"self def start(self): aio.pstab.setdefault(self.name, []) if self.run: if not inspect.iscoroutinefunction(self.run): self.status = True",
"kwargs={}): self.args = args self.kwargs = kwargs self.name = name self.slice = 0",
"2)) / 1_000 ).__await__() # return aio.sleep( float(self.slice - int(self.delta / 2)) /",
"def __enter__(self): self.acquire() def __exit__(self, *tb): self.release() def acquire(self, blocking=True, timeout=- 1): self.count",
"self.run: if not inspect.iscoroutinefunction(self.run): self.status = True aio.create_task(self.wrap()) else: coro = self.run(*self.args, **self.kwargs)",
"self.slice = int(float(slice) * 1_000) return self def start(self): aio.pstab.setdefault(self.name, []) if self.run:",
"thread # FIXME: fix wapy BUG 882 so target can be None too",
"target.__class__.__name__ self.run = target.run else: self.run = target if name is None: try:",
"def __exit__(self, *tb): self.release() def acquire(self, blocking=True, timeout=- 1): self.count += 1 return",
"if self.delta < 0: self.delta = 0 yield from aio.sleep_ms(self.slice - int(self.delta /",
"self.delta = 0 # no sleep_ms on cpy yield from aio.sleep_ms( float(self.slice -",
"import inspect # mark not started but no error aio.error = None aio.paused",
"\"run\"): if name is None: self.name = name or target.__class__.__name__ self.run = target.run",
"preempt mode # TODO: default granularity with https://docs.python.org/3/library/sys.html#sys.setswitchinterval class Lock: count = 0",
"self.is_alive(): aio_suspend() embed.disable_irq() def __bool__(self): return self.is_alive() and not aio.exit def is_alive(self): return",
"# TODO: pass thread local context here async with aio.ctx(self.slice).call(coro): self.status = False",
"(self.run.__name__, id(self)) except: pass else: target = self if self.name is None: self.name",
"RuntimeError(\"wait not supported\") class Thread: def __init__( self, group=None, target=None, name=None, args=(), kwargs={},",
"target can be None too in preempt mode # TODO: default granularity with",
"self.release() def acquire(self, blocking=True, timeout=- 1): self.count += 1 return True def release(self):",
"self.name is None: self.name = \"%s-%s\" % (self.__class__.__name__, id(self)) self.status = None async",
"float(self.slice - int(self.delta / 2)) / 1_000 ).__await__() # return aio.sleep( float(self.slice -",
"args=(), kwargs={}, *, daemon=None ): # def __init__(self, group=None, target=None, name=None, args=(), kwargs={}):",
"self.name = name self.slice = 0 self.last = aio.rtclock() if target: if hasattr(target,",
"if name is None: try: self.name = \"%s-%s\" % (self.run.__name__, id(self)) except: pass",
"aio.pstab.setdefault(srv, thr) aio.task = service def proc(srv): return aio.pstab.get(srv) class Runnable: def __await__(self):",
"kwargs={}, *, daemon=None ): # def __init__(self, group=None, target=None, name=None, args=(), kwargs={}): self.args",
"0: self.delta = 0 yield from aio.sleep_ms(self.slice - int(self.delta / 2)) self.last =",
"inspect.iscoroutinefunction(self.run): self.status = True aio.create_task(self.wrap()) else: coro = self.run(*self.args, **self.kwargs) pdb(\"168:\", self.name, \"starting\",",
"be None too in preempt mode # TODO: default granularity with https://docs.python.org/3/library/sys.html#sys.setswitchinterval class",
"self.acquire() def __exit__(self, *tb): self.release() def acquire(self, blocking=True, timeout=- 1): self.count += 1",
"(rtc - self.last) - self.slice if self.delta < 0: self.delta = 0 yield",
"thread : {srv}\") thr = aio.Thread(group=None, target=srv, args=argv, kwargs=kw).start() srv.__await__ = thr.__await__ return",
"embed.disable_irq() def __bool__(self): return self.is_alive() and not aio.exit def is_alive(self): return self.status is",
"while self.is_alive(): aio_suspend() embed.disable_irq() def __bool__(self): return self.is_alive() and not aio.exit def is_alive(self):",
"< 0: self.delta = 0 yield from aio.sleep_ms(self.slice - int(self.delta / 2)) self.last",
"self def join(self): embed.enable_irq() while self.is_alive(): aio_suspend() embed.disable_irq() def __bool__(self): return self.is_alive() and",
"or Lock() def acquire(self, *args): return self.lock.acquire() def release(self): self.lock.release() def wait(self, timeout=None):",
"error aio.error = None aio.paused = False aio.fd = {} aio.pstab = {}",
"self.last = rtc __await__ = __iter__ else: def __await__(self): if self.status is True:",
"self.count -= 1 def locked(self): return self.count>0 class Condition: def __init__(self, lock=None): self.lock",
"def rt(self, slice): self.slice = int(float(slice) * 1_000) return self def start(self): aio.pstab.setdefault(self.name,",
"https://docs.python.org/3/library/sys.html#sys.setswitchinterval class Lock: count = 0 def __enter__(self): self.acquire() def __exit__(self, *tb): self.release()",
"self.slice if self.delta < 0: self.delta = 0 # no sleep_ms on cpy",
"self.args = args self.kwargs = kwargs self.name = name self.slice = 0 self.last",
"sys.stderr) if __UPY__: def __iter__(self): if self.status is True: rtc = aio.rtclock() self.delta",
"Lock() def acquire(self, *args): return self.lock.acquire() def release(self): self.lock.release() def wait(self, timeout=None): raise",
"or target.__class__.__name__ self.run = target.run else: self.run = target if name is None:",
"yield from aio.sleep_ms( float(self.slice - int(self.delta / 2)) / 1_000 ).__await__() # return",
"kwargs=kw).start() srv.__await__ = thr.__await__ return aio.pstab.setdefault(srv, thr) aio.task = service def proc(srv): return",
"< 0: self.delta = 0 # no sleep_ms on cpy yield from aio.sleep_ms(",
"e: self.status = repr(e) sys.print_exception(e, sys.stderr) if __UPY__: def __iter__(self): if self.status is",
"): # def __init__(self, group=None, target=None, name=None, args=(), kwargs={}): self.args = args self.kwargs",
"class Thread: def __init__( self, group=None, target=None, name=None, args=(), kwargs={}, *, daemon=None ):",
"# a green thread # FIXME: fix wapy BUG 882 so target can",
"self.name = \"%s-%s\" % (self.__class__.__name__, id(self)) self.status = None async def wrap(self): for",
"self.status = repr(e) sys.print_exception(e, sys.stderr) if __UPY__: def __iter__(self): if self.status is True:",
"\"_shutdown\") # https://docs.python.org/3/library/threading.html#threading.excepthook # a green thread # FIXME: fix wapy BUG 882",
"is True def service(srv, *argv, **kw): embed.log(f\"starting green thread : {srv}\") thr =",
"lock=None): self.lock = lock or Lock() def acquire(self, *args): return self.lock.acquire() def release(self):",
"TODO: default granularity with https://docs.python.org/3/library/sys.html#sys.setswitchinterval class Lock: count = 0 def __enter__(self): self.acquire()",
"def __init__( self, group=None, target=None, name=None, args=(), kwargs={}, *, daemon=None ): # def",
"name=None, args=(), kwargs={}): self.args = args self.kwargs = kwargs self.name = name self.slice",
"\"%s-%s\" % (self.__class__.__name__, id(self)) self.status = None async def wrap(self): for idle in",
"def __await__(self): yield from aio.pstab.get(self).__await__() # replace with green threading import sys sys.modules[\"threading\"]",
"*tb): self.release() def acquire(self, blocking=True, timeout=- 1): self.count += 1 return True def",
"fix wapy BUG 882 so target can be None too in preempt mode",
"aio.paused = False aio.fd = {} aio.pstab = {} def _shutdown(): print(__file__, \"_shutdown\")",
"name is None: self.name = name or target.__class__.__name__ self.run = target.run else: self.run",
"sleep_ms on cpy yield from aio.sleep_ms( float(self.slice - int(self.delta / 2)) / 1_000",
"self if self.name is None: self.name = \"%s-%s\" % (self.__class__.__name__, id(self)) self.status =",
"target=None, name=None, args=(), kwargs={}): self.args = args self.kwargs = kwargs self.name = name",
"from aio.sleep_ms(self.slice - int(self.delta / 2)) self.last = rtc __await__ = __iter__ else:",
"id(self)) except: pass else: target = self if self.name is None: self.name =",
"self.delta < 0: self.delta = 0 # no sleep_ms on cpy yield from",
"supported\") class Thread: def __init__( self, group=None, target=None, name=None, args=(), kwargs={}, *, daemon=None",
"self.status is True def service(srv, *argv, **kw): embed.log(f\"starting green thread : {srv}\") thr",
"args=(), kwargs={}): self.args = args self.kwargs = kwargs self.name = name self.slice =",
"* 1_000) return self def start(self): aio.pstab.setdefault(self.name, []) if self.run: if not inspect.iscoroutinefunction(self.run):",
"__exit__(self, *tb): self.release() def acquire(self, blocking=True, timeout=- 1): self.count += 1 return True",
"/ 2)) self.last = rtc __await__ = __iter__ else: def __await__(self): if self.status",
"# def __init__(self, group=None, target=None, name=None, args=(), kwargs={}): self.args = args self.kwargs =",
"= None aio.paused = False aio.fd = {} aio.pstab = {} def _shutdown():",
"aio.sleep(0) async def runner(self, coro): self.status = True try: # TODO: pass thread",
"aio.pstab.get(srv) class Runnable: def __await__(self): yield from aio.pstab.get(self).__await__() # replace with green threading",
"# FIXME: fix wapy BUG 882 so target can be None too in",
"target.run else: self.run = target if name is None: try: self.name = \"%s-%s\"",
"target: if hasattr(target, \"run\"): if name is None: self.name = name or target.__class__.__name__",
"target=srv, args=argv, kwargs=kw).start() srv.__await__ = thr.__await__ return aio.pstab.setdefault(srv, thr) aio.task = service def",
"is_alive(self): return self.status is True def service(srv, *argv, **kw): embed.log(f\"starting green thread :",
"= aio.Thread(group=None, target=srv, args=argv, kwargs=kw).start() srv.__await__ = thr.__await__ return aio.pstab.setdefault(srv, thr) aio.task =",
"acquire(self, blocking=True, timeout=- 1): self.count += 1 return True def release(self): self.count -=",
"name is None: try: self.name = \"%s-%s\" % (self.run.__name__, id(self)) except: pass else:",
"0 # no sleep_ms on cpy yield from aio.sleep_ms( float(self.slice - int(self.delta /",
"async def wrap(self): for idle in self.run(*self.args, **self.kwargs): await aio.sleep(0) async def runner(self,",
"group=None, target=None, name=None, args=(), kwargs={}, *, daemon=None ): # def __init__(self, group=None, target=None,",
"None async def wrap(self): for idle in self.run(*self.args, **self.kwargs): await aio.sleep(0) async def",
"self.run(*self.args, **self.kwargs): await aio.sleep(0) async def runner(self, coro): self.status = True try: #",
"def __await__(self): if self.status is True: rtc = aio.rtclock() self.delta = (rtc -",
"aio.pstab = {} def _shutdown(): print(__file__, \"_shutdown\") # https://docs.python.org/3/library/threading.html#threading.excepthook # a green thread",
"def service(srv, *argv, **kw): embed.log(f\"starting green thread : {srv}\") thr = aio.Thread(group=None, target=srv,",
"if __UPY__: def __iter__(self): if self.status is True: rtc = aio.rtclock() self.delta =",
"with https://docs.python.org/3/library/sys.html#sys.setswitchinterval class Lock: count = 0 def __enter__(self): self.acquire() def __exit__(self, *tb):",
"but no error aio.error = None aio.paused = False aio.fd = {} aio.pstab",
"*, daemon=None ): # def __init__(self, group=None, target=None, name=None, args=(), kwargs={}): self.args =",
"daemon=None ): # def __init__(self, group=None, target=None, name=None, args=(), kwargs={}): self.args = args",
"coro): self.status = True try: # TODO: pass thread local context here async",
"**self.kwargs) pdb(\"168:\", self.name, \"starting\", coro) aio.create_task(self.runner(coro)) aio.pstab[self.name].append(self) return self def join(self): embed.enable_irq() while",
"self.status = True aio.create_task(self.wrap()) else: coro = self.run(*self.args, **self.kwargs) pdb(\"168:\", self.name, \"starting\", coro)",
"def wait_for(self, predicate, timeout=None): raise RuntimeError(\"wait not supported\") class Thread: def __init__( self,",
"__bool__(self): return self.is_alive() and not aio.exit def is_alive(self): return self.status is True def",
"else: def __await__(self): if self.status is True: rtc = aio.rtclock() self.delta = (rtc",
"= 0 # no sleep_ms on cpy yield from aio.sleep_ms( float(self.slice - int(self.delta",
"self.lock.acquire() def release(self): self.lock.release() def wait(self, timeout=None): raise RuntimeError(\"notify not supported\") def wait_for(self,",
"if self.status is True: rtc = aio.rtclock() self.delta = (rtc - self.last) -",
"None aio.paused = False aio.fd = {} aio.pstab = {} def _shutdown(): print(__file__,",
"aio.fd = {} aio.pstab = {} def _shutdown(): print(__file__, \"_shutdown\") # https://docs.python.org/3/library/threading.html#threading.excepthook #",
"too in preempt mode # TODO: default granularity with https://docs.python.org/3/library/sys.html#sys.setswitchinterval class Lock: count",
"= rtc def rt(self, slice): self.slice = int(float(slice) * 1_000) return self def",
"join(self): embed.enable_irq() while self.is_alive(): aio_suspend() embed.disable_irq() def __bool__(self): return self.is_alive() and not aio.exit",
"return self.status is True def service(srv, *argv, **kw): embed.log(f\"starting green thread : {srv}\")",
"= name or target.__class__.__name__ self.run = target.run else: self.run = target if name",
"wrap(self): for idle in self.run(*self.args, **self.kwargs): await aio.sleep(0) async def runner(self, coro): self.status",
"on cpy yield from aio.sleep_ms( float(self.slice - int(self.delta / 2)) / 1_000 ).__await__()",
"- self.last) - self.slice if self.delta < 0: self.delta = 0 # no",
"default granularity with https://docs.python.org/3/library/sys.html#sys.setswitchinterval class Lock: count = 0 def __enter__(self): self.acquire() def",
"int(self.delta / 2)) / 1_000 ) self.last = rtc def rt(self, slice): self.slice",
"1_000) return self def start(self): aio.pstab.setdefault(self.name, []) if self.run: if not inspect.iscoroutinefunction(self.run): self.status",
"def release(self): self.count -= 1 def locked(self): return self.count>0 class Condition: def __init__(self,",
"self.last) - self.slice if self.delta < 0: self.delta = 0 yield from aio.sleep_ms(self.slice",
"aio.sleep( float(self.slice - int(self.delta / 2)) / 1_000 ) self.last = rtc def",
"if name is None: self.name = name or target.__class__.__name__ self.run = target.run else:",
"can be None too in preempt mode # TODO: default granularity with https://docs.python.org/3/library/sys.html#sys.setswitchinterval",
"aio.sleep_ms( float(self.slice - int(self.delta / 2)) / 1_000 ).__await__() # return aio.sleep( float(self.slice",
"raise RuntimeError(\"notify not supported\") def wait_for(self, predicate, timeout=None): raise RuntimeError(\"wait not supported\") class",
"1 def locked(self): return self.count>0 class Condition: def __init__(self, lock=None): self.lock = lock",
"int(self.delta / 2)) / 1_000 ).__await__() # return aio.sleep( float(self.slice - int(self.delta /",
"coro) aio.create_task(self.runner(coro)) aio.pstab[self.name].append(self) return self def join(self): embed.enable_irq() while self.is_alive(): aio_suspend() embed.disable_irq() def",
"= name self.slice = 0 self.last = aio.rtclock() if target: if hasattr(target, \"run\"):",
"def acquire(self, *args): return self.lock.acquire() def release(self): self.lock.release() def wait(self, timeout=None): raise RuntimeError(\"notify",
"1): self.count += 1 return True def release(self): self.count -= 1 def locked(self):",
"0 def __enter__(self): self.acquire() def __exit__(self, *tb): self.release() def acquire(self, blocking=True, timeout=- 1):",
"def wrap(self): for idle in self.run(*self.args, **self.kwargs): await aio.sleep(0) async def runner(self, coro):",
"self.run = target if name is None: try: self.name = \"%s-%s\" % (self.run.__name__,",
"class Condition: def __init__(self, lock=None): self.lock = lock or Lock() def acquire(self, *args):",
"= 0 self.last = aio.rtclock() if target: if hasattr(target, \"run\"): if name is",
"self, group=None, target=None, name=None, args=(), kwargs={}, *, daemon=None ): # def __init__(self, group=None,",
"group=None, target=None, name=None, args=(), kwargs={}): self.args = args self.kwargs = kwargs self.name =",
"name or target.__class__.__name__ self.run = target.run else: self.run = target if name is",
"= True aio.create_task(self.wrap()) else: coro = self.run(*self.args, **self.kwargs) pdb(\"168:\", self.name, \"starting\", coro) aio.create_task(self.runner(coro))",
"1_000 ).__await__() # return aio.sleep( float(self.slice - int(self.delta / 2)) / 1_000 )",
"= kwargs self.name = name self.slice = 0 self.last = aio.rtclock() if target:",
"thr) aio.task = service def proc(srv): return aio.pstab.get(srv) class Runnable: def __await__(self): yield",
"TODO: pass thread local context here async with aio.ctx(self.slice).call(coro): self.status = False except",
"# return aio.sleep( float(self.slice - int(self.delta / 2)) / 1_000 ) self.last =",
"__await__(self): yield from aio.pstab.get(self).__await__() # replace with green threading import sys sys.modules[\"threading\"] =",
"yield from aio.pstab.get(self).__await__() # replace with green threading import sys sys.modules[\"threading\"] = sys.modules[\"aio.gthread\"]",
"def is_alive(self): return self.status is True def service(srv, *argv, **kw): embed.log(f\"starting green thread",
"class Lock: count = 0 def __enter__(self): self.acquire() def __exit__(self, *tb): self.release() def",
"sys.print_exception(e, sys.stderr) if __UPY__: def __iter__(self): if self.status is True: rtc = aio.rtclock()",
"= \"%s-%s\" % (self.run.__name__, id(self)) except: pass else: target = self if self.name",
"self.run(*self.args, **self.kwargs) pdb(\"168:\", self.name, \"starting\", coro) aio.create_task(self.runner(coro)) aio.pstab[self.name].append(self) return self def join(self): embed.enable_irq()",
"return self def join(self): embed.enable_irq() while self.is_alive(): aio_suspend() embed.disable_irq() def __bool__(self): return self.is_alive()",
"target if name is None: try: self.name = \"%s-%s\" % (self.run.__name__, id(self)) except:",
"False except Exception as e: self.status = repr(e) sys.print_exception(e, sys.stderr) if __UPY__: def",
"if self.name is None: self.name = \"%s-%s\" % (self.__class__.__name__, id(self)) self.status = None",
"self.delta = (rtc - self.last) - self.slice if self.delta < 0: self.delta =",
"= None async def wrap(self): for idle in self.run(*self.args, **self.kwargs): await aio.sleep(0) async",
"pass thread local context here async with aio.ctx(self.slice).call(coro): self.status = False except Exception",
"green thread : {srv}\") thr = aio.Thread(group=None, target=srv, args=argv, kwargs=kw).start() srv.__await__ = thr.__await__",
"(rtc - self.last) - self.slice if self.delta < 0: self.delta = 0 #",
"Runnable: def __await__(self): yield from aio.pstab.get(self).__await__() # replace with green threading import sys",
"rtc __await__ = __iter__ else: def __await__(self): if self.status is True: rtc =",
"inspect # mark not started but no error aio.error = None aio.paused =",
"# TODO: default granularity with https://docs.python.org/3/library/sys.html#sys.setswitchinterval class Lock: count = 0 def __enter__(self):",
"srv.__await__ = thr.__await__ return aio.pstab.setdefault(srv, thr) aio.task = service def proc(srv): return aio.pstab.get(srv)",
"from aio.sleep_ms( float(self.slice - int(self.delta / 2)) / 1_000 ).__await__() # return aio.sleep(",
"1 return True def release(self): self.count -= 1 def locked(self): return self.count>0 class",
"and not aio.exit def is_alive(self): return self.status is True def service(srv, *argv, **kw):",
"predicate, timeout=None): raise RuntimeError(\"wait not supported\") class Thread: def __init__( self, group=None, target=None,",
"Thread: def __init__( self, group=None, target=None, name=None, args=(), kwargs={}, *, daemon=None ): #",
"yield from aio.sleep_ms(self.slice - int(self.delta / 2)) self.last = rtc __await__ = __iter__",
"self.lock = lock or Lock() def acquire(self, *args): return self.lock.acquire() def release(self): self.lock.release()",
"**self.kwargs): await aio.sleep(0) async def runner(self, coro): self.status = True try: # TODO:",
"aio.pstab.setdefault(self.name, []) if self.run: if not inspect.iscoroutinefunction(self.run): self.status = True aio.create_task(self.wrap()) else: coro",
"here async with aio.ctx(self.slice).call(coro): self.status = False except Exception as e: self.status =",
"aio.exit def is_alive(self): return self.status is True def service(srv, *argv, **kw): embed.log(f\"starting green",
"1_000 ) self.last = rtc def rt(self, slice): self.slice = int(float(slice) * 1_000)",
"*argv, **kw): embed.log(f\"starting green thread : {srv}\") thr = aio.Thread(group=None, target=srv, args=argv, kwargs=kw).start()",
"**kw): embed.log(f\"starting green thread : {srv}\") thr = aio.Thread(group=None, target=srv, args=argv, kwargs=kw).start() srv.__await__",
"service def proc(srv): return aio.pstab.get(srv) class Runnable: def __await__(self): yield from aio.pstab.get(self).__await__() #",
"args=argv, kwargs=kw).start() srv.__await__ = thr.__await__ return aio.pstab.setdefault(srv, thr) aio.task = service def proc(srv):",
"# https://docs.python.org/3/library/threading.html#threading.excepthook # a green thread # FIXME: fix wapy BUG 882 so",
"self.name, \"starting\", coro) aio.create_task(self.runner(coro)) aio.pstab[self.name].append(self) return self def join(self): embed.enable_irq() while self.is_alive(): aio_suspend()",
"882 so target can be None too in preempt mode # TODO: default",
"-= 1 def locked(self): return self.count>0 class Condition: def __init__(self, lock=None): self.lock =",
"/ 1_000 ) self.last = rtc def rt(self, slice): self.slice = int(float(slice) *",
"def __init__(self, lock=None): self.lock = lock or Lock() def acquire(self, *args): return self.lock.acquire()",
"None too in preempt mode # TODO: default granularity with https://docs.python.org/3/library/sys.html#sys.setswitchinterval class Lock:",
"int(self.delta / 2)) self.last = rtc __await__ = __iter__ else: def __await__(self): if",
"\"%s-%s\" % (self.run.__name__, id(self)) except: pass else: target = self if self.name is",
"def proc(srv): return aio.pstab.get(srv) class Runnable: def __await__(self): yield from aio.pstab.get(self).__await__() # replace",
").__await__() # return aio.sleep( float(self.slice - int(self.delta / 2)) / 1_000 ) self.last",
"aio.Thread(group=None, target=srv, args=argv, kwargs=kw).start() srv.__await__ = thr.__await__ return aio.pstab.setdefault(srv, thr) aio.task = service",
"slice): self.slice = int(float(slice) * 1_000) return self def start(self): aio.pstab.setdefault(self.name, []) if",
"self.status is True: rtc = aio.rtclock() self.delta = (rtc - self.last) - self.slice",
"RuntimeError(\"notify not supported\") def wait_for(self, predicate, timeout=None): raise RuntimeError(\"wait not supported\") class Thread:",
"= (rtc - self.last) - self.slice if self.delta < 0: self.delta = 0",
"self.delta = 0 yield from aio.sleep_ms(self.slice - int(self.delta / 2)) self.last = rtc",
"in self.run(*self.args, **self.kwargs): await aio.sleep(0) async def runner(self, coro): self.status = True try:",
"= __iter__ else: def __await__(self): if self.status is True: rtc = aio.rtclock() self.delta",
"timeout=None): raise RuntimeError(\"notify not supported\") def wait_for(self, predicate, timeout=None): raise RuntimeError(\"wait not supported\")",
"True def release(self): self.count -= 1 def locked(self): return self.count>0 class Condition: def",
"/ 1_000 ).__await__() # return aio.sleep( float(self.slice - int(self.delta / 2)) / 1_000",
"__init__(self, lock=None): self.lock = lock or Lock() def acquire(self, *args): return self.lock.acquire() def",
"green thread # FIXME: fix wapy BUG 882 so target can be None",
"self.delta < 0: self.delta = 0 yield from aio.sleep_ms(self.slice - int(self.delta / 2))",
"__UPY__: def __iter__(self): if self.status is True: rtc = aio.rtclock() self.delta = (rtc",
"= target.run else: self.run = target if name is None: try: self.name =",
"2)) / 1_000 ) self.last = rtc def rt(self, slice): self.slice = int(float(slice)",
"except Exception as e: self.status = repr(e) sys.print_exception(e, sys.stderr) if __UPY__: def __iter__(self):",
"return self.count>0 class Condition: def __init__(self, lock=None): self.lock = lock or Lock() def",
"embed.log(f\"starting green thread : {srv}\") thr = aio.Thread(group=None, target=srv, args=argv, kwargs=kw).start() srv.__await__ =",
"__await__ = __iter__ else: def __await__(self): if self.status is True: rtc = aio.rtclock()",
"embed.enable_irq() while self.is_alive(): aio_suspend() embed.disable_irq() def __bool__(self): return self.is_alive() and not aio.exit def",
"https://docs.python.org/3/library/threading.html#threading.excepthook # a green thread # FIXME: fix wapy BUG 882 so target",
"def __init__(self, group=None, target=None, name=None, args=(), kwargs={}): self.args = args self.kwargs = kwargs",
"self.status = True try: # TODO: pass thread local context here async with",
"# no sleep_ms on cpy yield from aio.sleep_ms( float(self.slice - int(self.delta / 2))",
"kwargs self.name = name self.slice = 0 self.last = aio.rtclock() if target: if",
"= target if name is None: try: self.name = \"%s-%s\" % (self.run.__name__, id(self))",
"{} def _shutdown(): print(__file__, \"_shutdown\") # https://docs.python.org/3/library/threading.html#threading.excepthook # a green thread # FIXME:",
"def runner(self, coro): self.status = True try: # TODO: pass thread local context",
"None: self.name = \"%s-%s\" % (self.__class__.__name__, id(self)) self.status = None async def wrap(self):",
"- int(self.delta / 2)) self.last = rtc __await__ = __iter__ else: def __await__(self):",
"/ 2)) / 1_000 ) self.last = rtc def rt(self, slice): self.slice =",
"self.count>0 class Condition: def __init__(self, lock=None): self.lock = lock or Lock() def acquire(self,",
"name=None, args=(), kwargs={}, *, daemon=None ): # def __init__(self, group=None, target=None, name=None, args=(),",
"__enter__(self): self.acquire() def __exit__(self, *tb): self.release() def acquire(self, blocking=True, timeout=- 1): self.count +=",
"self.status = None async def wrap(self): for idle in self.run(*self.args, **self.kwargs): await aio.sleep(0)",
"self.lock.release() def wait(self, timeout=None): raise RuntimeError(\"notify not supported\") def wait_for(self, predicate, timeout=None): raise",
"= True try: # TODO: pass thread local context here async with aio.ctx(self.slice).call(coro):",
"repr(e) sys.print_exception(e, sys.stderr) if __UPY__: def __iter__(self): if self.status is True: rtc =",
"= self if self.name is None: self.name = \"%s-%s\" % (self.__class__.__name__, id(self)) self.status",
"start(self): aio.pstab.setdefault(self.name, []) if self.run: if not inspect.iscoroutinefunction(self.run): self.status = True aio.create_task(self.wrap()) else:",
"% (self.__class__.__name__, id(self)) self.status = None async def wrap(self): for idle in self.run(*self.args,",
"if self.delta < 0: self.delta = 0 # no sleep_ms on cpy yield",
"self.run = target.run else: self.run = target if name is None: try: self.name",
"release(self): self.count -= 1 def locked(self): return self.count>0 class Condition: def __init__(self, lock=None):",
"def acquire(self, blocking=True, timeout=- 1): self.count += 1 return True def release(self): self.count",
"FIXME: fix wapy BUG 882 so target can be None too in preempt",
"locked(self): return self.count>0 class Condition: def __init__(self, lock=None): self.lock = lock or Lock()",
"= lock or Lock() def acquire(self, *args): return self.lock.acquire() def release(self): self.lock.release() def",
"BUG 882 so target can be None too in preempt mode # TODO:",
"else: self.run = target if name is None: try: self.name = \"%s-%s\" %",
"aio.task = service def proc(srv): return aio.pstab.get(srv) class Runnable: def __await__(self): yield from",
"= 0 yield from aio.sleep_ms(self.slice - int(self.delta / 2)) self.last = rtc __await__",
"for idle in self.run(*self.args, **self.kwargs): await aio.sleep(0) async def runner(self, coro): self.status =",
"{srv}\") thr = aio.Thread(group=None, target=srv, args=argv, kwargs=kw).start() srv.__await__ = thr.__await__ return aio.pstab.setdefault(srv, thr)",
"= thr.__await__ return aio.pstab.setdefault(srv, thr) aio.task = service def proc(srv): return aio.pstab.get(srv) class",
"not supported\") class Thread: def __init__( self, group=None, target=None, name=None, args=(), kwargs={}, *,",
": {srv}\") thr = aio.Thread(group=None, target=srv, args=argv, kwargs=kw).start() srv.__await__ = thr.__await__ return aio.pstab.setdefault(srv,",
"service(srv, *argv, **kw): embed.log(f\"starting green thread : {srv}\") thr = aio.Thread(group=None, target=srv, args=argv,",
"not supported\") def wait_for(self, predicate, timeout=None): raise RuntimeError(\"wait not supported\") class Thread: def",
"so target can be None too in preempt mode # TODO: default granularity",
"in preempt mode # TODO: default granularity with https://docs.python.org/3/library/sys.html#sys.setswitchinterval class Lock: count =",
"self.kwargs = kwargs self.name = name self.slice = 0 self.last = aio.rtclock() if",
"return aio.pstab.setdefault(srv, thr) aio.task = service def proc(srv): return aio.pstab.get(srv) class Runnable: def",
"no sleep_ms on cpy yield from aio.sleep_ms( float(self.slice - int(self.delta / 2)) /",
"__iter__ else: def __await__(self): if self.status is True: rtc = aio.rtclock() self.delta =",
"pass else: target = self if self.name is None: self.name = \"%s-%s\" %"
] |
[
"prompting a user for a name of a theme to be set or",
"colors provided in X resource database (configured in ~/.Xresources file). The application may",
"may be extended with support for different ways of prompting a user for",
"tool for applications using colors provided in X resource database (configured in ~/.Xresources",
"\"\"\" ====================== base16-theme-switcher ====================== Base16-theme-switcher is an extensible color theme configuration tool for",
"themes for other applications. \"\"\" __title__ = 'base16-theme-switcher' __version__ = '1.0.0b2' __author__ =",
"configuring themes for other applications. \"\"\" __title__ = 'base16-theme-switcher' __version__ = '1.0.0b2' __author__",
"~/.Xresources file). The application may be extended with support for different ways of",
"application may be extended with support for different ways of prompting a user",
"base16-theme-switcher ====================== Base16-theme-switcher is an extensible color theme configuration tool for applications using",
"for different ways of prompting a user for a name of a theme",
"configuration tool for applications using colors provided in X resource database (configured in",
"for other applications. \"\"\" __title__ = 'base16-theme-switcher' __version__ = '1.0.0b2' __author__ = '<NAME>'",
"\"\"\" __title__ = 'base16-theme-switcher' __version__ = '1.0.0b2' __author__ = '<NAME>' __license__ = 'MIT'",
"ways of prompting a user for a name of a theme to be",
"be extended with support for different ways of prompting a user for a",
"= '1.0.0b2' __author__ = '<NAME>' __license__ = 'MIT' __copyright__ = 'Copyright 2017 <NAME>'",
"theme configuration tool for applications using colors provided in X resource database (configured",
"for applications using colors provided in X resource database (configured in ~/.Xresources file).",
"__title__ = 'base16-theme-switcher' __version__ = '1.0.0b2' __author__ = '<NAME>' __license__ = 'MIT' __copyright__",
"different ways of prompting a user for a name of a theme to",
"is an extensible color theme configuration tool for applications using colors provided in",
"database (configured in ~/.Xresources file). The application may be extended with support for",
"= 'base16-theme-switcher' __version__ = '1.0.0b2' __author__ = '<NAME>' __license__ = 'MIT' __copyright__ =",
"support for different ways of prompting a user for a name of a",
"an extensible color theme configuration tool for applications using colors provided in X",
"extended with support for different ways of prompting a user for a name",
"color theme configuration tool for applications using colors provided in X resource database",
"using colors provided in X resource database (configured in ~/.Xresources file). The application",
"of a theme to be set or for configuring themes for other applications.",
"in X resource database (configured in ~/.Xresources file). The application may be extended",
"user for a name of a theme to be set or for configuring",
"set or for configuring themes for other applications. \"\"\" __title__ = 'base16-theme-switcher' __version__",
"The application may be extended with support for different ways of prompting a",
"or for configuring themes for other applications. \"\"\" __title__ = 'base16-theme-switcher' __version__ =",
"__version__ = '1.0.0b2' __author__ = '<NAME>' __license__ = 'MIT' __copyright__ = 'Copyright 2017",
"(configured in ~/.Xresources file). The application may be extended with support for different",
"name of a theme to be set or for configuring themes for other",
"'base16-theme-switcher' __version__ = '1.0.0b2' __author__ = '<NAME>' __license__ = 'MIT' __copyright__ = 'Copyright",
"X resource database (configured in ~/.Xresources file). The application may be extended with",
"extensible color theme configuration tool for applications using colors provided in X resource",
"theme to be set or for configuring themes for other applications. \"\"\" __title__",
"a user for a name of a theme to be set or for",
"for configuring themes for other applications. \"\"\" __title__ = 'base16-theme-switcher' __version__ = '1.0.0b2'",
"====================== base16-theme-switcher ====================== Base16-theme-switcher is an extensible color theme configuration tool for applications",
"Base16-theme-switcher is an extensible color theme configuration tool for applications using colors provided",
"other applications. \"\"\" __title__ = 'base16-theme-switcher' __version__ = '1.0.0b2' __author__ = '<NAME>' __license__",
"with support for different ways of prompting a user for a name of",
"applications using colors provided in X resource database (configured in ~/.Xresources file). The",
"of prompting a user for a name of a theme to be set",
"<gh_stars>0 \"\"\" ====================== base16-theme-switcher ====================== Base16-theme-switcher is an extensible color theme configuration tool",
"for a name of a theme to be set or for configuring themes",
"be set or for configuring themes for other applications. \"\"\" __title__ = 'base16-theme-switcher'",
"====================== Base16-theme-switcher is an extensible color theme configuration tool for applications using colors",
"resource database (configured in ~/.Xresources file). The application may be extended with support",
"in ~/.Xresources file). The application may be extended with support for different ways",
"file). The application may be extended with support for different ways of prompting",
"a theme to be set or for configuring themes for other applications. \"\"\"",
"a name of a theme to be set or for configuring themes for",
"applications. \"\"\" __title__ = 'base16-theme-switcher' __version__ = '1.0.0b2' __author__ = '<NAME>' __license__ =",
"provided in X resource database (configured in ~/.Xresources file). The application may be",
"to be set or for configuring themes for other applications. \"\"\" __title__ ="
] |
[
"\"beamid\": 64157, \"acf\": True, \"vlimacf\": (18, 45), \"zlim_pl\": [None, None], \"vlim_pl\": [72, 90],",
"None], \"vlim_pl\": [72, 90], \"flim_pl\": [3.5, 5.5], \"odir\": \"out/2015-10-07\", \"vlim\": [25, 55], \"zlim\":",
"from isrutils.looper import simpleloop # %% users param P = { \"path\": \"~/data/2015-10-07/isr\",",
"= { \"path\": \"~/data/2015-10-07/isr\", \"beamid\": 64157, \"acf\": True, \"vlimacf\": (18, 45), \"zlim_pl\": [None,",
"#!/usr/bin/env python from isrutils.looper import simpleloop # %% users param P = {",
"%% users param P = { \"path\": \"~/data/2015-10-07/isr\", \"beamid\": 64157, \"acf\": True, \"vlimacf\":",
"# %% users param P = { \"path\": \"~/data/2015-10-07/isr\", \"beamid\": 64157, \"acf\": True,",
"\"out/2015-10-07\", \"vlim\": [25, 55], \"zlim\": (90, None), \"verbose\": True, } # %% flist",
"\"path\": \"~/data/2015-10-07/isr\", \"beamid\": 64157, \"acf\": True, \"vlimacf\": (18, 45), \"zlim_pl\": [None, None], \"vlim_pl\":",
"\"odir\": \"out/2015-10-07\", \"vlim\": [25, 55], \"zlim\": (90, None), \"verbose\": True, } # %%",
"[None, None], \"vlim_pl\": [72, 90], \"flim_pl\": [3.5, 5.5], \"odir\": \"out/2015-10-07\", \"vlim\": [25, 55],",
"\"zlim_pl\": [None, None], \"vlim_pl\": [72, 90], \"flim_pl\": [3.5, 5.5], \"odir\": \"out/2015-10-07\", \"vlim\": [25,",
"simpleloop # %% users param P = { \"path\": \"~/data/2015-10-07/isr\", \"beamid\": 64157, \"acf\":",
"45), \"zlim_pl\": [None, None], \"vlim_pl\": [72, 90], \"flim_pl\": [3.5, 5.5], \"odir\": \"out/2015-10-07\", \"vlim\":",
"[3.5, 5.5], \"odir\": \"out/2015-10-07\", \"vlim\": [25, 55], \"zlim\": (90, None), \"verbose\": True, }",
"(18, 45), \"zlim_pl\": [None, None], \"vlim_pl\": [72, 90], \"flim_pl\": [3.5, 5.5], \"odir\": \"out/2015-10-07\",",
"64157, \"acf\": True, \"vlimacf\": (18, 45), \"zlim_pl\": [None, None], \"vlim_pl\": [72, 90], \"flim_pl\":",
"90], \"flim_pl\": [3.5, 5.5], \"odir\": \"out/2015-10-07\", \"vlim\": [25, 55], \"zlim\": (90, None), \"verbose\":",
"[72, 90], \"flim_pl\": [3.5, 5.5], \"odir\": \"out/2015-10-07\", \"vlim\": [25, 55], \"zlim\": (90, None),",
"\"flim_pl\": [3.5, 5.5], \"odir\": \"out/2015-10-07\", \"vlim\": [25, 55], \"zlim\": (90, None), \"verbose\": True,",
"\"zlim\": (90, None), \"verbose\": True, } # %% flist = () simpleloop(flist, P)",
"\"~/data/2015-10-07/isr\", \"beamid\": 64157, \"acf\": True, \"vlimacf\": (18, 45), \"zlim_pl\": [None, None], \"vlim_pl\": [72,",
"\"vlim\": [25, 55], \"zlim\": (90, None), \"verbose\": True, } # %% flist =",
"\"vlim_pl\": [72, 90], \"flim_pl\": [3.5, 5.5], \"odir\": \"out/2015-10-07\", \"vlim\": [25, 55], \"zlim\": (90,",
"\"acf\": True, \"vlimacf\": (18, 45), \"zlim_pl\": [None, None], \"vlim_pl\": [72, 90], \"flim_pl\": [3.5,",
"5.5], \"odir\": \"out/2015-10-07\", \"vlim\": [25, 55], \"zlim\": (90, None), \"verbose\": True, } #",
"param P = { \"path\": \"~/data/2015-10-07/isr\", \"beamid\": 64157, \"acf\": True, \"vlimacf\": (18, 45),",
"55], \"zlim\": (90, None), \"verbose\": True, } # %% flist = () simpleloop(flist,",
"P = { \"path\": \"~/data/2015-10-07/isr\", \"beamid\": 64157, \"acf\": True, \"vlimacf\": (18, 45), \"zlim_pl\":",
"True, \"vlimacf\": (18, 45), \"zlim_pl\": [None, None], \"vlim_pl\": [72, 90], \"flim_pl\": [3.5, 5.5],",
"[25, 55], \"zlim\": (90, None), \"verbose\": True, } # %% flist = ()",
"{ \"path\": \"~/data/2015-10-07/isr\", \"beamid\": 64157, \"acf\": True, \"vlimacf\": (18, 45), \"zlim_pl\": [None, None],",
"isrutils.looper import simpleloop # %% users param P = { \"path\": \"~/data/2015-10-07/isr\", \"beamid\":",
"python from isrutils.looper import simpleloop # %% users param P = { \"path\":",
"import simpleloop # %% users param P = { \"path\": \"~/data/2015-10-07/isr\", \"beamid\": 64157,",
"\"vlimacf\": (18, 45), \"zlim_pl\": [None, None], \"vlim_pl\": [72, 90], \"flim_pl\": [3.5, 5.5], \"odir\":",
"users param P = { \"path\": \"~/data/2015-10-07/isr\", \"beamid\": 64157, \"acf\": True, \"vlimacf\": (18,"
] |
[
"path(\"admin/\", admin.site.urls), # path(\"\", views.RoomList.as_view(), name=\"room_list\"), # path(\"<slug:pk>/\", views.RoomDetail.as_view(), name=\"room_detail\"), # path(\"create_message/\", views.TurboTest.as_view(),",
"urlpatterns: path('blog/', include('blog.urls')) \"\"\" from django.contrib import admin from django.views.generic import TemplateView from",
"list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/4.0/topics/http/urls/ Examples: Function",
"URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from",
"Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf",
"to urlpatterns: path('blog/', include('blog.urls')) \"\"\" from django.contrib import admin from django.views.generic import TemplateView",
"function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/',",
"= [ path(\"admin/\", admin.site.urls), # path(\"\", views.RoomList.as_view(), name=\"room_list\"), # path(\"<slug:pk>/\", views.RoomDetail.as_view(), name=\"room_detail\"), #",
"include('blog.urls')) \"\"\" from django.contrib import admin from django.views.generic import TemplateView from django.urls import",
"Examples: Function views 1. Add an import: from my_app import views 2. Add",
"1. Add an import: from other_app.views import Home 2. Add a URL to",
"Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import",
"see: https://docs.djangoproject.com/en/4.0/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views",
"views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1.",
"from django.contrib import admin from django.views.generic import TemplateView from django.urls import path from",
"please see: https://docs.djangoproject.com/en/4.0/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import",
"import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) \"\"\" from",
"admin.site.urls), # path(\"\", views.RoomList.as_view(), name=\"room_list\"), # path(\"<slug:pk>/\", views.RoomDetail.as_view(), name=\"room_detail\"), # path(\"create_message/\", views.TurboTest.as_view(), name=\"message_create\"),",
"Configuration The `urlpatterns` list routes URLs to views. For more information please see:",
"import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views",
"views urlpatterns = [ path(\"admin/\", admin.site.urls), # path(\"\", views.RoomList.as_view(), name=\"room_list\"), # path(\"<slug:pk>/\", views.RoomDetail.as_view(),",
"Add an import: from other_app.views import Home 2. Add a URL to urlpatterns:",
"\"\"\"turbotutorial URL Configuration The `urlpatterns` list routes URLs to views. For more information",
"import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another",
"django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) \"\"\"",
"\"\"\" from django.contrib import admin from django.views.generic import TemplateView from django.urls import path",
"django.urls import path from chat import views urlpatterns = [ path(\"admin/\", admin.site.urls), #",
"2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1.",
"URLconf 1. Import the include() function: from django.urls import include, path 2. Add",
"a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import:",
"Add an import: from my_app import views 2. Add a URL to urlpatterns:",
"urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import",
"import path from chat import views urlpatterns = [ path(\"admin/\", admin.site.urls), # path(\"\",",
"django.views.generic import TemplateView from django.urls import path from chat import views urlpatterns =",
"chat import views urlpatterns = [ path(\"admin/\", admin.site.urls), # path(\"\", views.RoomList.as_view(), name=\"room_list\"), #",
"Including another URLconf 1. Import the include() function: from django.urls import include, path",
"path('blog/', include('blog.urls')) \"\"\" from django.contrib import admin from django.views.generic import TemplateView from django.urls",
"path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) \"\"\" from django.contrib import",
"path from chat import views urlpatterns = [ path(\"admin/\", admin.site.urls), # path(\"\", views.RoomList.as_view(),",
"# path(\"\", views.RoomList.as_view(), name=\"room_list\"), # path(\"<slug:pk>/\", views.RoomDetail.as_view(), name=\"room_detail\"), # path(\"create_message/\", views.TurboTest.as_view(), name=\"message_create\"), path(\"quickstart/\",",
"other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including",
"URL Configuration The `urlpatterns` list routes URLs to views. For more information please",
"For more information please see: https://docs.djangoproject.com/en/4.0/topics/http/urls/ Examples: Function views 1. Add an import:",
"from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')",
"include() function: from django.urls import include, path 2. Add a URL to urlpatterns:",
"from chat import views urlpatterns = [ path(\"admin/\", admin.site.urls), # path(\"\", views.RoomList.as_view(), name=\"room_list\"),",
"an import: from my_app import views 2. Add a URL to urlpatterns: path('',",
"from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home')",
"import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(),",
"URLs to views. For more information please see: https://docs.djangoproject.com/en/4.0/topics/http/urls/ Examples: Function views 1.",
"more information please see: https://docs.djangoproject.com/en/4.0/topics/http/urls/ Examples: Function views 1. Add an import: from",
"admin from django.views.generic import TemplateView from django.urls import path from chat import views",
"Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an",
"URL to urlpatterns: path('blog/', include('blog.urls')) \"\"\" from django.contrib import admin from django.views.generic import",
"`urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/4.0/topics/http/urls/ Examples:",
"views.RoomList.as_view(), name=\"room_list\"), # path(\"<slug:pk>/\", views.RoomDetail.as_view(), name=\"room_detail\"), # path(\"create_message/\", views.TurboTest.as_view(), name=\"message_create\"), path(\"quickstart/\", TemplateView.as_view(template_name=\"broadcast_example.html\")), ]",
"views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2.",
"name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add",
"from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))",
"views. For more information please see: https://docs.djangoproject.com/en/4.0/topics/http/urls/ Examples: Function views 1. Add an",
"views 1. Add an import: from my_app import views 2. Add a URL",
"1. Add an import: from my_app import views 2. Add a URL to",
"Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import",
"https://docs.djangoproject.com/en/4.0/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2.",
"[ path(\"admin/\", admin.site.urls), # path(\"\", views.RoomList.as_view(), name=\"room_list\"), # path(\"<slug:pk>/\", views.RoomDetail.as_view(), name=\"room_detail\"), # path(\"create_message/\",",
"urlpatterns = [ path(\"admin/\", admin.site.urls), # path(\"\", views.RoomList.as_view(), name=\"room_list\"), # path(\"<slug:pk>/\", views.RoomDetail.as_view(), name=\"room_detail\"),",
"import views urlpatterns = [ path(\"admin/\", admin.site.urls), # path(\"\", views.RoomList.as_view(), name=\"room_list\"), # path(\"<slug:pk>/\",",
"import admin from django.views.generic import TemplateView from django.urls import path from chat import",
"my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based",
"TemplateView from django.urls import path from chat import views urlpatterns = [ path(\"admin/\",",
"to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views",
"the include() function: from django.urls import include, path 2. Add a URL to",
"2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) \"\"\" from django.contrib import admin",
"from django.views.generic import TemplateView from django.urls import path from chat import views urlpatterns",
"Class-based views 1. Add an import: from other_app.views import Home 2. Add a",
"import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home,",
"Function views 1. Add an import: from my_app import views 2. Add a",
"Import the include() function: from django.urls import include, path 2. Add a URL",
"name='home') Including another URLconf 1. Import the include() function: from django.urls import include,",
"urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from",
"a URL to urlpatterns: path('blog/', include('blog.urls')) \"\"\" from django.contrib import admin from django.views.generic",
"routes URLs to views. For more information please see: https://docs.djangoproject.com/en/4.0/topics/http/urls/ Examples: Function views",
"Add a URL to urlpatterns: path('blog/', include('blog.urls')) \"\"\" from django.contrib import admin from",
"path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls",
"path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home",
"import TemplateView from django.urls import path from chat import views urlpatterns = [",
"to views. For more information please see: https://docs.djangoproject.com/en/4.0/topics/http/urls/ Examples: Function views 1. Add",
"from django.urls import path from chat import views urlpatterns = [ path(\"admin/\", admin.site.urls),",
"an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('',",
"django.contrib import admin from django.views.generic import TemplateView from django.urls import path from chat",
"2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add",
"path(\"\", views.RoomList.as_view(), name=\"room_list\"), # path(\"<slug:pk>/\", views.RoomDetail.as_view(), name=\"room_detail\"), # path(\"create_message/\", views.TurboTest.as_view(), name=\"message_create\"), path(\"quickstart/\", TemplateView.as_view(template_name=\"broadcast_example.html\")),",
"to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function:",
"1. Import the include() function: from django.urls import include, path 2. Add a",
"a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the",
"another URLconf 1. Import the include() function: from django.urls import include, path 2.",
"include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) \"\"\" from django.contrib",
"information please see: https://docs.djangoproject.com/en/4.0/topics/http/urls/ Examples: Function views 1. Add an import: from my_app",
"views 1. Add an import: from other_app.views import Home 2. Add a URL",
"URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include()",
"The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/4.0/topics/http/urls/"
] |
[
"# Postgres POSTGRES_NAME = os.environ.get('POSTGRES_NAME') POSTGRES_USER = os.environ.get('POSTGRES_USER') POSTGRES_PASSWORD = os.environ.get('POSTGRES_PASSWORD') POSTGRES_HOST =",
"= os.environ.get('ETL_DEFAULT_DATE') # Postgres POSTGRES_NAME = os.environ.get('POSTGRES_NAME') POSTGRES_USER = os.environ.get('POSTGRES_USER') POSTGRES_PASSWORD = os.environ.get('POSTGRES_PASSWORD')",
"ETL_DEFAULT_DATE = os.environ.get('ETL_DEFAULT_DATE') # Postgres POSTGRES_NAME = os.environ.get('POSTGRES_NAME') POSTGRES_USER = os.environ.get('POSTGRES_USER') POSTGRES_PASSWORD =",
"= int(os.environ.get('ETL_SYNC_DELAY')) ETL_FILE_STATE = os.environ.get('ETL_FILE_STATE') ETL_DEFAULT_DATE = os.environ.get('ETL_DEFAULT_DATE') # Postgres POSTGRES_NAME = os.environ.get('POSTGRES_NAME')",
"ETL_MODE = os.environ.get('ETL_MODE') ETL_CHUNK_SIZE = int(os.environ.get('ETL_CHUNK_SIZE')) ETL_SYNC_DELAY = int(os.environ.get('ETL_SYNC_DELAY')) ETL_FILE_STATE = os.environ.get('ETL_FILE_STATE') ETL_DEFAULT_DATE",
"os.environ.get('POSTGRES_PASSWORD') POSTGRES_HOST = os.environ.get('POSTGRES_HOST') POSTGRES_PORT = os.environ.get('POSTGRES_PORT') # Elasticsearch ELASTICSEARCH_HOST = os.environ.get('ELASTICSEARCH_HOST') ELASTICSEARCH_PORT",
"os.environ.get('ETL_MODE') ETL_CHUNK_SIZE = int(os.environ.get('ETL_CHUNK_SIZE')) ETL_SYNC_DELAY = int(os.environ.get('ETL_SYNC_DELAY')) ETL_FILE_STATE = os.environ.get('ETL_FILE_STATE') ETL_DEFAULT_DATE = os.environ.get('ETL_DEFAULT_DATE')",
"os.environ.get('POSTGRES_USER') POSTGRES_PASSWORD = os.environ.get('POSTGRES_PASSWORD') POSTGRES_HOST = os.environ.get('POSTGRES_HOST') POSTGRES_PORT = os.environ.get('POSTGRES_PORT') # Elasticsearch ELASTICSEARCH_HOST",
"= os.environ.get('POSTGRES_PASSWORD') POSTGRES_HOST = os.environ.get('POSTGRES_HOST') POSTGRES_PORT = os.environ.get('POSTGRES_PORT') # Elasticsearch ELASTICSEARCH_HOST = os.environ.get('ELASTICSEARCH_HOST')",
"ETL_CHUNK_SIZE = int(os.environ.get('ETL_CHUNK_SIZE')) ETL_SYNC_DELAY = int(os.environ.get('ETL_SYNC_DELAY')) ETL_FILE_STATE = os.environ.get('ETL_FILE_STATE') ETL_DEFAULT_DATE = os.environ.get('ETL_DEFAULT_DATE') #",
"ETL_FILE_STATE = os.environ.get('ETL_FILE_STATE') ETL_DEFAULT_DATE = os.environ.get('ETL_DEFAULT_DATE') # Postgres POSTGRES_NAME = os.environ.get('POSTGRES_NAME') POSTGRES_USER =",
"ETL ETL_MODE = os.environ.get('ETL_MODE') ETL_CHUNK_SIZE = int(os.environ.get('ETL_CHUNK_SIZE')) ETL_SYNC_DELAY = int(os.environ.get('ETL_SYNC_DELAY')) ETL_FILE_STATE = os.environ.get('ETL_FILE_STATE')",
"int(os.environ.get('ETL_CHUNK_SIZE')) ETL_SYNC_DELAY = int(os.environ.get('ETL_SYNC_DELAY')) ETL_FILE_STATE = os.environ.get('ETL_FILE_STATE') ETL_DEFAULT_DATE = os.environ.get('ETL_DEFAULT_DATE') # Postgres POSTGRES_NAME",
"os.environ.get('ETL_DEFAULT_DATE') # Postgres POSTGRES_NAME = os.environ.get('POSTGRES_NAME') POSTGRES_USER = os.environ.get('POSTGRES_USER') POSTGRES_PASSWORD = os.environ.get('POSTGRES_PASSWORD') POSTGRES_HOST",
"import os # ETL ETL_MODE = os.environ.get('ETL_MODE') ETL_CHUNK_SIZE = int(os.environ.get('ETL_CHUNK_SIZE')) ETL_SYNC_DELAY = int(os.environ.get('ETL_SYNC_DELAY'))",
"ETL_SYNC_DELAY = int(os.environ.get('ETL_SYNC_DELAY')) ETL_FILE_STATE = os.environ.get('ETL_FILE_STATE') ETL_DEFAULT_DATE = os.environ.get('ETL_DEFAULT_DATE') # Postgres POSTGRES_NAME =",
"POSTGRES_USER = os.environ.get('POSTGRES_USER') POSTGRES_PASSWORD = os.environ.get('POSTGRES_PASSWORD') POSTGRES_HOST = os.environ.get('POSTGRES_HOST') POSTGRES_PORT = os.environ.get('POSTGRES_PORT') #",
"POSTGRES_NAME = os.environ.get('POSTGRES_NAME') POSTGRES_USER = os.environ.get('POSTGRES_USER') POSTGRES_PASSWORD = os.environ.get('POSTGRES_PASSWORD') POSTGRES_HOST = os.environ.get('POSTGRES_HOST') POSTGRES_PORT",
"POSTGRES_HOST = os.environ.get('POSTGRES_HOST') POSTGRES_PORT = os.environ.get('POSTGRES_PORT') # Elasticsearch ELASTICSEARCH_HOST = os.environ.get('ELASTICSEARCH_HOST') ELASTICSEARCH_PORT =",
"= os.environ.get('POSTGRES_USER') POSTGRES_PASSWORD = os.environ.get('POSTGRES_PASSWORD') POSTGRES_HOST = os.environ.get('POSTGRES_HOST') POSTGRES_PORT = os.environ.get('POSTGRES_PORT') # Elasticsearch",
"= os.environ.get('ETL_FILE_STATE') ETL_DEFAULT_DATE = os.environ.get('ETL_DEFAULT_DATE') # Postgres POSTGRES_NAME = os.environ.get('POSTGRES_NAME') POSTGRES_USER = os.environ.get('POSTGRES_USER')",
"int(os.environ.get('ETL_SYNC_DELAY')) ETL_FILE_STATE = os.environ.get('ETL_FILE_STATE') ETL_DEFAULT_DATE = os.environ.get('ETL_DEFAULT_DATE') # Postgres POSTGRES_NAME = os.environ.get('POSTGRES_NAME') POSTGRES_USER",
"os.environ.get('ETL_FILE_STATE') ETL_DEFAULT_DATE = os.environ.get('ETL_DEFAULT_DATE') # Postgres POSTGRES_NAME = os.environ.get('POSTGRES_NAME') POSTGRES_USER = os.environ.get('POSTGRES_USER') POSTGRES_PASSWORD",
"= int(os.environ.get('ETL_CHUNK_SIZE')) ETL_SYNC_DELAY = int(os.environ.get('ETL_SYNC_DELAY')) ETL_FILE_STATE = os.environ.get('ETL_FILE_STATE') ETL_DEFAULT_DATE = os.environ.get('ETL_DEFAULT_DATE') # Postgres",
"os.environ.get('POSTGRES_NAME') POSTGRES_USER = os.environ.get('POSTGRES_USER') POSTGRES_PASSWORD = os.environ.get('POSTGRES_PASSWORD') POSTGRES_HOST = os.environ.get('POSTGRES_HOST') POSTGRES_PORT = os.environ.get('POSTGRES_PORT')",
"os # ETL ETL_MODE = os.environ.get('ETL_MODE') ETL_CHUNK_SIZE = int(os.environ.get('ETL_CHUNK_SIZE')) ETL_SYNC_DELAY = int(os.environ.get('ETL_SYNC_DELAY')) ETL_FILE_STATE",
"= os.environ.get('POSTGRES_NAME') POSTGRES_USER = os.environ.get('POSTGRES_USER') POSTGRES_PASSWORD = os.environ.get('POSTGRES_PASSWORD') POSTGRES_HOST = os.environ.get('POSTGRES_HOST') POSTGRES_PORT =",
"POSTGRES_PASSWORD = os.environ.get('POSTGRES_PASSWORD') POSTGRES_HOST = os.environ.get('POSTGRES_HOST') POSTGRES_PORT = os.environ.get('POSTGRES_PORT') # Elasticsearch ELASTICSEARCH_HOST =",
"# ETL ETL_MODE = os.environ.get('ETL_MODE') ETL_CHUNK_SIZE = int(os.environ.get('ETL_CHUNK_SIZE')) ETL_SYNC_DELAY = int(os.environ.get('ETL_SYNC_DELAY')) ETL_FILE_STATE =",
"Postgres POSTGRES_NAME = os.environ.get('POSTGRES_NAME') POSTGRES_USER = os.environ.get('POSTGRES_USER') POSTGRES_PASSWORD = os.environ.get('POSTGRES_PASSWORD') POSTGRES_HOST = os.environ.get('POSTGRES_HOST')",
"= os.environ.get('POSTGRES_HOST') POSTGRES_PORT = os.environ.get('POSTGRES_PORT') # Elasticsearch ELASTICSEARCH_HOST = os.environ.get('ELASTICSEARCH_HOST') ELASTICSEARCH_PORT = os.environ.get('ELASTICSEARCH_PORT')",
"= os.environ.get('ETL_MODE') ETL_CHUNK_SIZE = int(os.environ.get('ETL_CHUNK_SIZE')) ETL_SYNC_DELAY = int(os.environ.get('ETL_SYNC_DELAY')) ETL_FILE_STATE = os.environ.get('ETL_FILE_STATE') ETL_DEFAULT_DATE ="
] |
[
"sender_email = SENDER_EMAIL receiver_email = RECEIVER_EMAIL password = <PASSWORD> # Create a multipart",
"in to server using secure context and send email context = ssl.create_default_context() with",
"load_dotenv(os.path.join(project_folder, '.env')) SENDER_EMAIL = os.getenv(\"SENDER_EMAIL\") RECEIVER_EMAIL = os.getenv(\"RECEIVER_EMAIL\") EMAIL_PASSWORD = os.getenv(\"EMAIL_PASSWORD\") def send(email_subject,",
"RECEIVER_EMAIL password = <PASSWORD> # Create a multipart message and set headers message",
"pair to attachment part part.add_header( \"Content-Disposition\", f\"attachment; filename= {filename}\", ) # Add attachment",
"= <PASSWORD> # Create a multipart message and set headers message = MIMEMultipart()",
"convert message to string message.attach(part) text = message.as_string() # Log in to server",
"project_folder = os.path.expanduser('~/Pi-Backup-Files/facial_recognition') # adjust as appropriate load_dotenv(os.path.join(project_folder, '.env')) SENDER_EMAIL = os.getenv(\"SENDER_EMAIL\") RECEIVER_EMAIL",
"to attachment part part.add_header( \"Content-Disposition\", f\"attachment; filename= {filename}\", ) # Add attachment to",
"In same directory as script # Open PDF file in binary mode with",
"Path #load_dotenv(\".env\") project_folder = os.path.expanduser('~/Pi-Backup-Files/facial_recognition') # adjust as appropriate load_dotenv(os.path.join(project_folder, '.env')) SENDER_EMAIL =",
"= os.getenv(\"EMAIL_PASSWORD\") def send(email_subject, ): subject = \"Intruder Detected!\" body = \"Please see",
"from email.mime.text import MIMEText from dotenv import load_dotenv, find_dotenv import os from pathlib",
"Email client can usually download this automatically as attachment part = MIMEBase(\"application\", \"octet-stream\")",
"message[\"To\"] = receiver_email message[\"Subject\"] = subject #message[\"Bcc\"] = receiver_email # Recommended for mass",
"text = message.as_string() # Log in to server using secure context and send",
"from email.mime.base import MIMEBase from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from",
"import MIMEBase from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from dotenv import",
"= \"Please see the attached picture.\" sender_email = SENDER_EMAIL receiver_email = RECEIVER_EMAIL password",
"filename = \"image.jpg\" # In same directory as script # Open PDF file",
"part part.add_header( \"Content-Disposition\", f\"attachment; filename= {filename}\", ) # Add attachment to message and",
"Add header as key/value pair to attachment part part.add_header( \"Content-Disposition\", f\"attachment; filename= {filename}\",",
"file in ASCII characters to send by email encoders.encode_base64(part) # Add header as",
"pathlib import Path #load_dotenv(\".env\") project_folder = os.path.expanduser('~/Pi-Backup-Files/facial_recognition') # adjust as appropriate load_dotenv(os.path.join(project_folder, '.env'))",
"RECEIVER_EMAIL = os.getenv(\"RECEIVER_EMAIL\") EMAIL_PASSWORD = os.getenv(\"EMAIL_PASSWORD\") def send(email_subject, ): subject = \"Intruder Detected!\"",
"dotenv import load_dotenv, find_dotenv import os from pathlib import Path #load_dotenv(\".env\") project_folder =",
"\"octet-stream\") part.set_payload(attachment.read()) # Encode file in ASCII characters to send by email encoders.encode_base64(part)",
"message.attach(part) text = message.as_string() # Log in to server using secure context and",
"sender_email message[\"To\"] = receiver_email message[\"Subject\"] = subject #message[\"Bcc\"] = receiver_email # Recommended for",
"# In same directory as script # Open PDF file in binary mode",
"Add file as application/octet-stream # Email client can usually download this automatically as",
"from email import encoders from email.mime.base import MIMEBase from email.mime.multipart import MIMEMultipart from",
"emails # Add body to email message.attach(MIMEText(body, \"plain\")) filename = \"image.jpg\" # In",
"attachment: # Add file as application/octet-stream # Email client can usually download this",
"= os.getenv(\"SENDER_EMAIL\") RECEIVER_EMAIL = os.getenv(\"RECEIVER_EMAIL\") EMAIL_PASSWORD = os.getenv(\"EMAIL_PASSWORD\") def send(email_subject, ): subject =",
"EMAIL_PASSWORD = os.getenv(\"EMAIL_PASSWORD\") def send(email_subject, ): subject = \"Intruder Detected!\" body = \"Please",
"\"plain\")) filename = \"image.jpg\" # In same directory as script # Open PDF",
"and set headers message = MIMEMultipart() message[\"From\"] = sender_email message[\"To\"] = receiver_email message[\"Subject\"]",
"# Create a multipart message and set headers message = MIMEMultipart() message[\"From\"] =",
"# Add body to email message.attach(MIMEText(body, \"plain\")) filename = \"image.jpg\" # In same",
"email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from dotenv import load_dotenv, find_dotenv import",
") # Add attachment to message and convert message to string message.attach(part) text",
"script # Open PDF file in binary mode with open(filename, \"rb\") as attachment:",
"to message and convert message to string message.attach(part) text = message.as_string() # Log",
"= \"Intruder Detected!\" body = \"Please see the attached picture.\" sender_email = SENDER_EMAIL",
"part.set_payload(attachment.read()) # Encode file in ASCII characters to send by email encoders.encode_base64(part) #",
"secure context and send email context = ssl.create_default_context() with smtplib.SMTP_SSL(\"smtp.gmail.com\", 465, context=context) as",
"file as application/octet-stream # Email client can usually download this automatically as attachment",
"send(email_subject, ): subject = \"Intruder Detected!\" body = \"Please see the attached picture.\"",
"from dotenv import load_dotenv, find_dotenv import os from pathlib import Path #load_dotenv(\".env\") project_folder",
"SENDER_EMAIL receiver_email = RECEIVER_EMAIL password = <PASSWORD> # Create a multipart message and",
"import email, smtplib, ssl from email import encoders from email.mime.base import MIMEBase from",
"SENDER_EMAIL = os.getenv(\"SENDER_EMAIL\") RECEIVER_EMAIL = os.getenv(\"RECEIVER_EMAIL\") EMAIL_PASSWORD = os.getenv(\"EMAIL_PASSWORD\") def send(email_subject, ): subject",
"message[\"Subject\"] = subject #message[\"Bcc\"] = receiver_email # Recommended for mass emails # Add",
"MIMEMultipart() message[\"From\"] = sender_email message[\"To\"] = receiver_email message[\"Subject\"] = subject #message[\"Bcc\"] = receiver_email",
"and send email context = ssl.create_default_context() with smtplib.SMTP_SSL(\"smtp.gmail.com\", 465, context=context) as server: server.login(sender_email,",
"receiver_email = RECEIVER_EMAIL password = <PASSWORD> # Create a multipart message and set",
"= MIMEBase(\"application\", \"octet-stream\") part.set_payload(attachment.read()) # Encode file in ASCII characters to send by",
"as attachment part = MIMEBase(\"application\", \"octet-stream\") part.set_payload(attachment.read()) # Encode file in ASCII characters",
"Detected!\" body = \"Please see the attached picture.\" sender_email = SENDER_EMAIL receiver_email =",
"set headers message = MIMEMultipart() message[\"From\"] = sender_email message[\"To\"] = receiver_email message[\"Subject\"] =",
"= os.path.expanduser('~/Pi-Backup-Files/facial_recognition') # adjust as appropriate load_dotenv(os.path.join(project_folder, '.env')) SENDER_EMAIL = os.getenv(\"SENDER_EMAIL\") RECEIVER_EMAIL =",
"{filename}\", ) # Add attachment to message and convert message to string message.attach(part)",
"can usually download this automatically as attachment part = MIMEBase(\"application\", \"octet-stream\") part.set_payload(attachment.read()) #",
"password = <PASSWORD> # Create a multipart message and set headers message =",
"key/value pair to attachment part part.add_header( \"Content-Disposition\", f\"attachment; filename= {filename}\", ) # Add",
"automatically as attachment part = MIMEBase(\"application\", \"octet-stream\") part.set_payload(attachment.read()) # Encode file in ASCII",
"import Path #load_dotenv(\".env\") project_folder = os.path.expanduser('~/Pi-Backup-Files/facial_recognition') # adjust as appropriate load_dotenv(os.path.join(project_folder, '.env')) SENDER_EMAIL",
"header as key/value pair to attachment part part.add_header( \"Content-Disposition\", f\"attachment; filename= {filename}\", )",
"with smtplib.SMTP_SSL(\"smtp.gmail.com\", 465, context=context) as server: server.login(sender_email, password) server.sendmail(sender_email, receiver_email, text) if __name__",
"import MIMEMultipart from email.mime.text import MIMEText from dotenv import load_dotenv, find_dotenv import os",
"multipart message and set headers message = MIMEMultipart() message[\"From\"] = sender_email message[\"To\"] =",
"Add attachment to message and convert message to string message.attach(part) text = message.as_string()",
"# Recommended for mass emails # Add body to email message.attach(MIMEText(body, \"plain\")) filename",
"message and convert message to string message.attach(part) text = message.as_string() # Log in",
"= receiver_email message[\"Subject\"] = subject #message[\"Bcc\"] = receiver_email # Recommended for mass emails",
"to send by email encoders.encode_base64(part) # Add header as key/value pair to attachment",
"to string message.attach(part) text = message.as_string() # Log in to server using secure",
"PDF file in binary mode with open(filename, \"rb\") as attachment: # Add file",
"= sender_email message[\"To\"] = receiver_email message[\"Subject\"] = subject #message[\"Bcc\"] = receiver_email # Recommended",
"import load_dotenv, find_dotenv import os from pathlib import Path #load_dotenv(\".env\") project_folder = os.path.expanduser('~/Pi-Backup-Files/facial_recognition')",
"context = ssl.create_default_context() with smtplib.SMTP_SSL(\"smtp.gmail.com\", 465, context=context) as server: server.login(sender_email, password) server.sendmail(sender_email, receiver_email,",
"# Add attachment to message and convert message to string message.attach(part) text =",
"the attached picture.\" sender_email = SENDER_EMAIL receiver_email = RECEIVER_EMAIL password = <PASSWORD> #",
"load_dotenv, find_dotenv import os from pathlib import Path #load_dotenv(\".env\") project_folder = os.path.expanduser('~/Pi-Backup-Files/facial_recognition') #",
"message to string message.attach(part) text = message.as_string() # Log in to server using",
"# Email client can usually download this automatically as attachment part = MIMEBase(\"application\",",
"ASCII characters to send by email encoders.encode_base64(part) # Add header as key/value pair",
"f\"attachment; filename= {filename}\", ) # Add attachment to message and convert message to",
"Encode file in ASCII characters to send by email encoders.encode_base64(part) # Add header",
"file in binary mode with open(filename, \"rb\") as attachment: # Add file as",
"receiver_email # Recommended for mass emails # Add body to email message.attach(MIMEText(body, \"plain\"))",
"subject #message[\"Bcc\"] = receiver_email # Recommended for mass emails # Add body to",
"characters to send by email encoders.encode_base64(part) # Add header as key/value pair to",
"to email message.attach(MIMEText(body, \"plain\")) filename = \"image.jpg\" # In same directory as script",
"using secure context and send email context = ssl.create_default_context() with smtplib.SMTP_SSL(\"smtp.gmail.com\", 465, context=context)",
"Open PDF file in binary mode with open(filename, \"rb\") as attachment: # Add",
"in binary mode with open(filename, \"rb\") as attachment: # Add file as application/octet-stream",
"ssl.create_default_context() with smtplib.SMTP_SSL(\"smtp.gmail.com\", 465, context=context) as server: server.login(sender_email, password) server.sendmail(sender_email, receiver_email, text) if",
"# Encode file in ASCII characters to send by email encoders.encode_base64(part) # Add",
"find_dotenv import os from pathlib import Path #load_dotenv(\".env\") project_folder = os.path.expanduser('~/Pi-Backup-Files/facial_recognition') # adjust",
"with open(filename, \"rb\") as attachment: # Add file as application/octet-stream # Email client",
"open(filename, \"rb\") as attachment: # Add file as application/octet-stream # Email client can",
"# Open PDF file in binary mode with open(filename, \"rb\") as attachment: #",
"binary mode with open(filename, \"rb\") as attachment: # Add file as application/octet-stream #",
"\"rb\") as attachment: # Add file as application/octet-stream # Email client can usually",
"465, context=context) as server: server.login(sender_email, password) server.sendmail(sender_email, receiver_email, text) if __name__ == \"__main__\":",
"download this automatically as attachment part = MIMEBase(\"application\", \"octet-stream\") part.set_payload(attachment.read()) # Encode file",
"part.add_header( \"Content-Disposition\", f\"attachment; filename= {filename}\", ) # Add attachment to message and convert",
"encoders.encode_base64(part) # Add header as key/value pair to attachment part part.add_header( \"Content-Disposition\", f\"attachment;",
"#load_dotenv(\".env\") project_folder = os.path.expanduser('~/Pi-Backup-Files/facial_recognition') # adjust as appropriate load_dotenv(os.path.join(project_folder, '.env')) SENDER_EMAIL = os.getenv(\"SENDER_EMAIL\")",
"\"Please see the attached picture.\" sender_email = SENDER_EMAIL receiver_email = RECEIVER_EMAIL password =",
"\"Content-Disposition\", f\"attachment; filename= {filename}\", ) # Add attachment to message and convert message",
"string message.attach(part) text = message.as_string() # Log in to server using secure context",
"= os.getenv(\"RECEIVER_EMAIL\") EMAIL_PASSWORD = os.getenv(\"EMAIL_PASSWORD\") def send(email_subject, ): subject = \"Intruder Detected!\" body",
"mass emails # Add body to email message.attach(MIMEText(body, \"plain\")) filename = \"image.jpg\" #",
"part = MIMEBase(\"application\", \"octet-stream\") part.set_payload(attachment.read()) # Encode file in ASCII characters to send",
"in ASCII characters to send by email encoders.encode_base64(part) # Add header as key/value",
"context=context) as server: server.login(sender_email, password) server.sendmail(sender_email, receiver_email, text) if __name__ == \"__main__\": send()",
"email.mime.text import MIMEText from dotenv import load_dotenv, find_dotenv import os from pathlib import",
"os.getenv(\"EMAIL_PASSWORD\") def send(email_subject, ): subject = \"Intruder Detected!\" body = \"Please see the",
"# Add file as application/octet-stream # Email client can usually download this automatically",
"encoders from email.mime.base import MIMEBase from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText",
"email.mime.base import MIMEBase from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from dotenv",
"import MIMEText from dotenv import load_dotenv, find_dotenv import os from pathlib import Path",
"attached picture.\" sender_email = SENDER_EMAIL receiver_email = RECEIVER_EMAIL password = <PASSWORD> # Create",
"picture.\" sender_email = SENDER_EMAIL receiver_email = RECEIVER_EMAIL password = <PASSWORD> # Create a",
"as attachment: # Add file as application/octet-stream # Email client can usually download",
"from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from dotenv import load_dotenv, find_dotenv",
"Log in to server using secure context and send email context = ssl.create_default_context()",
"= \"image.jpg\" # In same directory as script # Open PDF file in",
"import encoders from email.mime.base import MIMEBase from email.mime.multipart import MIMEMultipart from email.mime.text import",
"os.getenv(\"SENDER_EMAIL\") RECEIVER_EMAIL = os.getenv(\"RECEIVER_EMAIL\") EMAIL_PASSWORD = os.getenv(\"EMAIL_PASSWORD\") def send(email_subject, ): subject = \"Intruder",
"= ssl.create_default_context() with smtplib.SMTP_SSL(\"smtp.gmail.com\", 465, context=context) as server: server.login(sender_email, password) server.sendmail(sender_email, receiver_email, text)",
"attachment part part.add_header( \"Content-Disposition\", f\"attachment; filename= {filename}\", ) # Add attachment to message",
"= message.as_string() # Log in to server using secure context and send email",
"attachment part = MIMEBase(\"application\", \"octet-stream\") part.set_payload(attachment.read()) # Encode file in ASCII characters to",
"'.env')) SENDER_EMAIL = os.getenv(\"SENDER_EMAIL\") RECEIVER_EMAIL = os.getenv(\"RECEIVER_EMAIL\") EMAIL_PASSWORD = os.getenv(\"EMAIL_PASSWORD\") def send(email_subject, ):",
"directory as script # Open PDF file in binary mode with open(filename, \"rb\")",
"<filename>send_email.py import email, smtplib, ssl from email import encoders from email.mime.base import MIMEBase",
"adjust as appropriate load_dotenv(os.path.join(project_folder, '.env')) SENDER_EMAIL = os.getenv(\"SENDER_EMAIL\") RECEIVER_EMAIL = os.getenv(\"RECEIVER_EMAIL\") EMAIL_PASSWORD =",
"MIMEMultipart from email.mime.text import MIMEText from dotenv import load_dotenv, find_dotenv import os from",
"by email encoders.encode_base64(part) # Add header as key/value pair to attachment part part.add_header(",
"email import encoders from email.mime.base import MIMEBase from email.mime.multipart import MIMEMultipart from email.mime.text",
"email, smtplib, ssl from email import encoders from email.mime.base import MIMEBase from email.mime.multipart",
"usually download this automatically as attachment part = MIMEBase(\"application\", \"octet-stream\") part.set_payload(attachment.read()) # Encode",
"client can usually download this automatically as attachment part = MIMEBase(\"application\", \"octet-stream\") part.set_payload(attachment.read())",
"#message[\"Bcc\"] = receiver_email # Recommended for mass emails # Add body to email",
"\"image.jpg\" # In same directory as script # Open PDF file in binary",
"= SENDER_EMAIL receiver_email = RECEIVER_EMAIL password = <PASSWORD> # Create a multipart message",
"application/octet-stream # Email client can usually download this automatically as attachment part =",
"attachment to message and convert message to string message.attach(part) text = message.as_string() #",
"os from pathlib import Path #load_dotenv(\".env\") project_folder = os.path.expanduser('~/Pi-Backup-Files/facial_recognition') # adjust as appropriate",
"message.attach(MIMEText(body, \"plain\")) filename = \"image.jpg\" # In same directory as script # Open",
"= MIMEMultipart() message[\"From\"] = sender_email message[\"To\"] = receiver_email message[\"Subject\"] = subject #message[\"Bcc\"] =",
"for mass emails # Add body to email message.attach(MIMEText(body, \"plain\")) filename = \"image.jpg\"",
"<PASSWORD> # Create a multipart message and set headers message = MIMEMultipart() message[\"From\"]",
"import os from pathlib import Path #load_dotenv(\".env\") project_folder = os.path.expanduser('~/Pi-Backup-Files/facial_recognition') # adjust as",
"ssl from email import encoders from email.mime.base import MIMEBase from email.mime.multipart import MIMEMultipart",
"a multipart message and set headers message = MIMEMultipart() message[\"From\"] = sender_email message[\"To\"]",
"MIMEText from dotenv import load_dotenv, find_dotenv import os from pathlib import Path #load_dotenv(\".env\")",
"body to email message.attach(MIMEText(body, \"plain\")) filename = \"image.jpg\" # In same directory as",
"email context = ssl.create_default_context() with smtplib.SMTP_SSL(\"smtp.gmail.com\", 465, context=context) as server: server.login(sender_email, password) server.sendmail(sender_email,",
"Create a multipart message and set headers message = MIMEMultipart() message[\"From\"] = sender_email",
"server using secure context and send email context = ssl.create_default_context() with smtplib.SMTP_SSL(\"smtp.gmail.com\", 465,",
"message = MIMEMultipart() message[\"From\"] = sender_email message[\"To\"] = receiver_email message[\"Subject\"] = subject #message[\"Bcc\"]",
"# Add header as key/value pair to attachment part part.add_header( \"Content-Disposition\", f\"attachment; filename=",
"appropriate load_dotenv(os.path.join(project_folder, '.env')) SENDER_EMAIL = os.getenv(\"SENDER_EMAIL\") RECEIVER_EMAIL = os.getenv(\"RECEIVER_EMAIL\") EMAIL_PASSWORD = os.getenv(\"EMAIL_PASSWORD\") def",
"= receiver_email # Recommended for mass emails # Add body to email message.attach(MIMEText(body,",
"message.as_string() # Log in to server using secure context and send email context",
"from pathlib import Path #load_dotenv(\".env\") project_folder = os.path.expanduser('~/Pi-Backup-Files/facial_recognition') # adjust as appropriate load_dotenv(os.path.join(project_folder,",
"\"Intruder Detected!\" body = \"Please see the attached picture.\" sender_email = SENDER_EMAIL receiver_email",
"email encoders.encode_base64(part) # Add header as key/value pair to attachment part part.add_header( \"Content-Disposition\",",
"smtplib, ssl from email import encoders from email.mime.base import MIMEBase from email.mime.multipart import",
"see the attached picture.\" sender_email = SENDER_EMAIL receiver_email = RECEIVER_EMAIL password = <PASSWORD>",
"as script # Open PDF file in binary mode with open(filename, \"rb\") as",
"to server using secure context and send email context = ssl.create_default_context() with smtplib.SMTP_SSL(\"smtp.gmail.com\",",
"message and set headers message = MIMEMultipart() message[\"From\"] = sender_email message[\"To\"] = receiver_email",
"same directory as script # Open PDF file in binary mode with open(filename,",
"= subject #message[\"Bcc\"] = receiver_email # Recommended for mass emails # Add body",
"body = \"Please see the attached picture.\" sender_email = SENDER_EMAIL receiver_email = RECEIVER_EMAIL",
"send email context = ssl.create_default_context() with smtplib.SMTP_SSL(\"smtp.gmail.com\", 465, context=context) as server: server.login(sender_email, password)",
"MIMEBase from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from dotenv import load_dotenv,",
"): subject = \"Intruder Detected!\" body = \"Please see the attached picture.\" sender_email",
"Recommended for mass emails # Add body to email message.attach(MIMEText(body, \"plain\")) filename =",
"subject = \"Intruder Detected!\" body = \"Please see the attached picture.\" sender_email =",
"as appropriate load_dotenv(os.path.join(project_folder, '.env')) SENDER_EMAIL = os.getenv(\"SENDER_EMAIL\") RECEIVER_EMAIL = os.getenv(\"RECEIVER_EMAIL\") EMAIL_PASSWORD = os.getenv(\"EMAIL_PASSWORD\")",
"= RECEIVER_EMAIL password = <PASSWORD> # Create a multipart message and set headers",
"receiver_email message[\"Subject\"] = subject #message[\"Bcc\"] = receiver_email # Recommended for mass emails #",
"headers message = MIMEMultipart() message[\"From\"] = sender_email message[\"To\"] = receiver_email message[\"Subject\"] = subject",
"as application/octet-stream # Email client can usually download this automatically as attachment part",
"this automatically as attachment part = MIMEBase(\"application\", \"octet-stream\") part.set_payload(attachment.read()) # Encode file in",
"and convert message to string message.attach(part) text = message.as_string() # Log in to",
"send by email encoders.encode_base64(part) # Add header as key/value pair to attachment part",
"Add body to email message.attach(MIMEText(body, \"plain\")) filename = \"image.jpg\" # In same directory",
"mode with open(filename, \"rb\") as attachment: # Add file as application/octet-stream # Email",
"os.path.expanduser('~/Pi-Backup-Files/facial_recognition') # adjust as appropriate load_dotenv(os.path.join(project_folder, '.env')) SENDER_EMAIL = os.getenv(\"SENDER_EMAIL\") RECEIVER_EMAIL = os.getenv(\"RECEIVER_EMAIL\")",
"email message.attach(MIMEText(body, \"plain\")) filename = \"image.jpg\" # In same directory as script #",
"as key/value pair to attachment part part.add_header( \"Content-Disposition\", f\"attachment; filename= {filename}\", ) #",
"# Log in to server using secure context and send email context =",
"def send(email_subject, ): subject = \"Intruder Detected!\" body = \"Please see the attached",
"context and send email context = ssl.create_default_context() with smtplib.SMTP_SSL(\"smtp.gmail.com\", 465, context=context) as server:",
"smtplib.SMTP_SSL(\"smtp.gmail.com\", 465, context=context) as server: server.login(sender_email, password) server.sendmail(sender_email, receiver_email, text) if __name__ ==",
"# adjust as appropriate load_dotenv(os.path.join(project_folder, '.env')) SENDER_EMAIL = os.getenv(\"SENDER_EMAIL\") RECEIVER_EMAIL = os.getenv(\"RECEIVER_EMAIL\") EMAIL_PASSWORD",
"filename= {filename}\", ) # Add attachment to message and convert message to string",
"message[\"From\"] = sender_email message[\"To\"] = receiver_email message[\"Subject\"] = subject #message[\"Bcc\"] = receiver_email #",
"MIMEBase(\"application\", \"octet-stream\") part.set_payload(attachment.read()) # Encode file in ASCII characters to send by email",
"os.getenv(\"RECEIVER_EMAIL\") EMAIL_PASSWORD = os.getenv(\"EMAIL_PASSWORD\") def send(email_subject, ): subject = \"Intruder Detected!\" body ="
] |
[
"in l2: return True else: return False def break_compound(self,l1): for i in l1:",
": \").split(\"^\") def contains(self,l1,l2,x): if x in l2: return True else: return False",
"else: return False def break_compound(self,l1): for i in l1: self.stack.append(i) def process(self): self.accept()",
"True else: return False def break_compound(self,l1): for i in l1: self.stack.append(i) def process(self):",
"def __init__(self): self.start = [] self.goal = [] self.stack = [] self.actions =",
"process(self): self.accept() self.stack.append(goal) while len(self.stack) != 0: #Break compound clause onto stack if",
"Start state : \").split(\"^\") self.goal = input(\"Enter Goal state : \").split(\"^\") def contains(self,l1,l2,x):",
"= [] self.actions = ['Stack','UnStack','Pick','Put'] self.predicate = ['On','OnTable'] self.prereq = ['Clear','Holding','ArmEmpty'] def accept(self):",
"= [] self.stack = [] self.actions = ['Stack','UnStack','Pick','Put'] self.predicate = ['On','OnTable'] self.prereq =",
"self.accept() self.stack.append(goal) while len(self.stack) != 0: #Break compound clause onto stack if len(self.stack[-1])",
"while len(self.stack) != 0: #Break compound clause onto stack if len(self.stack[-1]) > 1:",
"self.stack.append(goal) while len(self.stack) != 0: #Break compound clause onto stack if len(self.stack[-1]) >",
"return False def break_compound(self,l1): for i in l1: self.stack.append(i) def process(self): self.accept() self.stack.append(goal)",
"self.predicate = ['On','OnTable'] self.prereq = ['Clear','Holding','ArmEmpty'] def accept(self): self.start = input(\"Enter Start state",
"= ['Clear','Holding','ArmEmpty'] def accept(self): self.start = input(\"Enter Start state : \").split(\"^\") self.goal =",
"break_compound(self,l1): for i in l1: self.stack.append(i) def process(self): self.accept() self.stack.append(goal) while len(self.stack) !=",
"def contains(self,l1,l2,x): if x in l2: return True else: return False def break_compound(self,l1):",
"contains(self,l1,l2,x): if x in l2: return True else: return False def break_compound(self,l1): for",
"['Stack','UnStack','Pick','Put'] self.predicate = ['On','OnTable'] self.prereq = ['Clear','Holding','ArmEmpty'] def accept(self): self.start = input(\"Enter Start",
"i in l1: self.stack.append(i) def process(self): self.accept() self.stack.append(goal) while len(self.stack) != 0: #Break",
"self.prereq = ['Clear','Holding','ArmEmpty'] def accept(self): self.start = input(\"Enter Start state : \").split(\"^\") self.goal",
"= input(\"Enter Start state : \").split(\"^\") self.goal = input(\"Enter Goal state : \").split(\"^\")",
"for i in l1: self.stack.append(i) def process(self): self.accept() self.stack.append(goal) while len(self.stack) != 0:",
"= [] self.goal = [] self.stack = [] self.actions = ['Stack','UnStack','Pick','Put'] self.predicate =",
"return True else: return False def break_compound(self,l1): for i in l1: self.stack.append(i) def",
"[] self.stack = [] self.actions = ['Stack','UnStack','Pick','Put'] self.predicate = ['On','OnTable'] self.prereq = ['Clear','Holding','ArmEmpty']",
"Goal state : \").split(\"^\") def contains(self,l1,l2,x): if x in l2: return True else:",
"[] self.goal = [] self.stack = [] self.actions = ['Stack','UnStack','Pick','Put'] self.predicate = ['On','OnTable']",
"self.start = [] self.goal = [] self.stack = [] self.actions = ['Stack','UnStack','Pick','Put'] self.predicate",
"self.stack = [] self.actions = ['Stack','UnStack','Pick','Put'] self.predicate = ['On','OnTable'] self.prereq = ['Clear','Holding','ArmEmpty'] def",
"\").split(\"^\") def contains(self,l1,l2,x): if x in l2: return True else: return False def",
"input(\"Enter Start state : \").split(\"^\") self.goal = input(\"Enter Goal state : \").split(\"^\") def",
"l1: self.stack.append(i) def process(self): self.accept() self.stack.append(goal) while len(self.stack) != 0: #Break compound clause",
"self.start = input(\"Enter Start state : \").split(\"^\") self.goal = input(\"Enter Goal state :",
"self.actions = ['Stack','UnStack','Pick','Put'] self.predicate = ['On','OnTable'] self.prereq = ['Clear','Holding','ArmEmpty'] def accept(self): self.start =",
"\").split(\"^\") self.goal = input(\"Enter Goal state : \").split(\"^\") def contains(self,l1,l2,x): if x in",
"self.goal = input(\"Enter Goal state : \").split(\"^\") def contains(self,l1,l2,x): if x in l2:",
"in l1: self.stack.append(i) def process(self): self.accept() self.stack.append(goal) while len(self.stack) != 0: #Break compound",
"len(self.stack) != 0: #Break compound clause onto stack if len(self.stack[-1]) > 1: break_compound(self.stack[-1])",
"state : \").split(\"^\") self.goal = input(\"Enter Goal state : \").split(\"^\") def contains(self,l1,l2,x): if",
"= ['On','OnTable'] self.prereq = ['Clear','Holding','ArmEmpty'] def accept(self): self.start = input(\"Enter Start state :",
"['On','OnTable'] self.prereq = ['Clear','Holding','ArmEmpty'] def accept(self): self.start = input(\"Enter Start state : \").split(\"^\")",
"l2: return True else: return False def break_compound(self,l1): for i in l1: self.stack.append(i)",
"class GSP: def __init__(self): self.start = [] self.goal = [] self.stack = []",
"self.goal = [] self.stack = [] self.actions = ['Stack','UnStack','Pick','Put'] self.predicate = ['On','OnTable'] self.prereq",
"= input(\"Enter Goal state : \").split(\"^\") def contains(self,l1,l2,x): if x in l2: return",
"x in l2: return True else: return False def break_compound(self,l1): for i in",
"accept(self): self.start = input(\"Enter Start state : \").split(\"^\") self.goal = input(\"Enter Goal state",
"def break_compound(self,l1): for i in l1: self.stack.append(i) def process(self): self.accept() self.stack.append(goal) while len(self.stack)",
"GSP: def __init__(self): self.start = [] self.goal = [] self.stack = [] self.actions",
"input(\"Enter Goal state : \").split(\"^\") def contains(self,l1,l2,x): if x in l2: return True",
"False def break_compound(self,l1): for i in l1: self.stack.append(i) def process(self): self.accept() self.stack.append(goal) while",
"def accept(self): self.start = input(\"Enter Start state : \").split(\"^\") self.goal = input(\"Enter Goal",
"['Clear','Holding','ArmEmpty'] def accept(self): self.start = input(\"Enter Start state : \").split(\"^\") self.goal = input(\"Enter",
": \").split(\"^\") self.goal = input(\"Enter Goal state : \").split(\"^\") def contains(self,l1,l2,x): if x",
"if x in l2: return True else: return False def break_compound(self,l1): for i",
"state : \").split(\"^\") def contains(self,l1,l2,x): if x in l2: return True else: return",
"__init__(self): self.start = [] self.goal = [] self.stack = [] self.actions = ['Stack','UnStack','Pick','Put']",
"[] self.actions = ['Stack','UnStack','Pick','Put'] self.predicate = ['On','OnTable'] self.prereq = ['Clear','Holding','ArmEmpty'] def accept(self): self.start",
"self.stack.append(i) def process(self): self.accept() self.stack.append(goal) while len(self.stack) != 0: #Break compound clause onto",
"= ['Stack','UnStack','Pick','Put'] self.predicate = ['On','OnTable'] self.prereq = ['Clear','Holding','ArmEmpty'] def accept(self): self.start = input(\"Enter",
"def process(self): self.accept() self.stack.append(goal) while len(self.stack) != 0: #Break compound clause onto stack"
] |
[
"<gh_stars>0 import os import numpy as np import torch from utils.readdata import read_dicts_from_file,read_triples_from_file,turn_triples_to_label_dict",
"self.relation_dict, with_reverse=with_reverse) self.valid_triples_with_reverse,self.valid_triples_for_classification = self.read_triple_from_file(os.path.join(data_path, valid_data_name), self.entity_dict, self.relation_dict, with_reverse=with_reverse) self.test_triples_with_reverse,self.test_triples_for_classification = self.read_triple_from_file(os.path.join(data_path, test_data_name),",
"classification_triples_label = [] with open(filename) as file: for line in file: head, relation,",
"[] classification_triples_label = [] with open(filename) as file: for line in file: head,",
"read_dicts_from_file,read_triples_from_file,turn_triples_to_label_dict class TripleClassificationData(object): def __init__(self,data_path,train_data_name,valid_data_name,test_data_name,with_reverse=False): self.entity_dict,self.relation_dict = read_dicts_from_file( [os.path.join(data_path,train_data_name), os.path.join(data_path,valid_data_name), os.path.join(data_path,test_data_name)], with_reverse=with_reverse )",
"batch_size if end_index >= self.train_numbers: end_index = self.train_numbers pointer = end_index current_batch_size =",
"end_index current_batch_size = end_index - start_index new_batch_train_triple_true = random_train_triple[start_index:end_index,:].copy() new_batch_train_triple_fake = random_train_triple[start_index:end_index,:].copy() random_words",
"len(self.train_triples_with_reverse) self.train_triples_dict = turn_triples_to_label_dict(self.train_triples_with_reverse) self.valid_triples_dict = turn_triples_to_label_dict(self.valid_triples_with_reverse) self.test_triples_dict = turn_triples_to_label_dict(self.test_triples_with_reverse) self.gold_triples_dict = dict(list(self.train_triples_dict.items())",
"= self.train_triples_numpy_array[random_index] pointer = 0 while pointer < self.train_numbers: start_index = pointer end_index",
"(new_batch_train_triple_fake[index,0], new_batch_train_triple_fake[index,1], random_words[index]) in self.train_triples_dict: random_words[index] = np.random.randint(0,self.entity_numbers) new_batch_train_triple_fake[index,2] = random_words[index] yield torch.tensor(new_batch_train_triple_true).long().cuda(),torch.tensor(new_batch_train_triple_fake).long().cuda()",
"line.strip().split('\\t') if int(label) == 1: triples_list.append([ entity_dict[head], relation_dict[relation], entity_dict[tail] ]) if with_reverse: relation_reverse",
"triples_list.append([ entity_dict[head], relation_dict[relation], entity_dict[tail] ]) if with_reverse: relation_reverse = relation + '_reverse' triples_list.append([",
"= self.read_triple_from_file(os.path.join(data_path, valid_data_name), self.entity_dict, self.relation_dict, with_reverse=with_reverse) self.test_triples_with_reverse,self.test_triples_for_classification = self.read_triple_from_file(os.path.join(data_path, test_data_name), self.entity_dict, self.relation_dict, with_reverse=with_reverse)",
"= np.array(self.train_triples_with_reverse).astype(np.int32) self.valid_triples_for_classification = np.array(self.valid_triples_for_classification).astype(np.int32) self.test_triples_for_classification = np.array(self.test_triples_for_classification).astype(np.int32) def read_triple_from_file(self,filename,entity_dict,relation_dict,with_reverse): triples_list = []",
"self.valid_triples_dict = turn_triples_to_label_dict(self.valid_triples_with_reverse) self.test_triples_dict = turn_triples_to_label_dict(self.test_triples_with_reverse) self.gold_triples_dict = dict(list(self.train_triples_dict.items()) + list(self.valid_triples_dict.items()) + list(self.test_triples_dict.items()))",
"= self.read_triple_from_file(os.path.join(data_path, test_data_name), self.entity_dict, self.relation_dict, with_reverse=with_reverse) self.train_numbers = len(self.train_triples_with_reverse) self.train_triples_dict = turn_triples_to_label_dict(self.train_triples_with_reverse) self.valid_triples_dict",
"relation + '_reverse' triples_list.append([ entity_dict[tail], relation_dict[relation_reverse], entity_dict[head] ]) classification_triples_label.append([ entity_dict[head], relation_dict[relation], entity_dict[tail], label",
"entity_dict[head], relation_dict[relation], entity_dict[tail], label ]) return triples_list,classification_triples_label def get_batch(self,batch_size): random_index = np.random.permutation(self.train_numbers) random_train_triple",
"in range(current_batch_size): while (new_batch_train_triple_fake[index,0], new_batch_train_triple_fake[index,1], random_words[index]) in self.train_triples_dict: random_words[index] = np.random.randint(0,self.entity_numbers) new_batch_train_triple_fake[index,2] =",
"= len(self.entity_dict.keys()) self.relation_numbers = len(self.relation_dict.keys()) self.train_triples_with_reverse = read_triples_from_file(os.path.join(data_path, train_data_name), self.entity_dict, self.relation_dict, with_reverse=with_reverse) self.valid_triples_with_reverse,self.valid_triples_for_classification",
"self.train_triples_numpy_array = np.array(self.train_triples_with_reverse).astype(np.int32) self.valid_triples_for_classification = np.array(self.valid_triples_for_classification).astype(np.int32) self.test_triples_for_classification = np.array(self.test_triples_for_classification).astype(np.int32) def read_triple_from_file(self,filename,entity_dict,relation_dict,with_reverse): triples_list =",
"= relation + '_reverse' triples_list.append([ entity_dict[tail], relation_dict[relation_reverse], entity_dict[head] ]) classification_triples_label.append([ entity_dict[head], relation_dict[relation], entity_dict[tail],",
"self.relation_numbers = len(self.relation_dict.keys()) self.train_triples_with_reverse = read_triples_from_file(os.path.join(data_path, train_data_name), self.entity_dict, self.relation_dict, with_reverse=with_reverse) self.valid_triples_with_reverse,self.valid_triples_for_classification = self.read_triple_from_file(os.path.join(data_path,",
"os.path.join(data_path,test_data_name)], with_reverse=with_reverse ) self.entity_numbers = len(self.entity_dict.keys()) self.relation_numbers = len(self.relation_dict.keys()) self.train_triples_with_reverse = read_triples_from_file(os.path.join(data_path, train_data_name),",
"]) classification_triples_label.append([ entity_dict[head], relation_dict[relation], entity_dict[tail], label ]) return triples_list,classification_triples_label def get_batch(self,batch_size): random_index =",
"if with_reverse: relation_reverse = relation + '_reverse' triples_list.append([ entity_dict[tail], relation_dict[relation_reverse], entity_dict[head] ]) classification_triples_label.append([",
"= pointer end_index = start_index + batch_size if end_index >= self.train_numbers: end_index =",
"return triples_list,classification_triples_label def get_batch(self,batch_size): random_index = np.random.permutation(self.train_numbers) random_train_triple = self.train_triples_numpy_array[random_index] pointer = 0",
"list(self.test_triples_dict.items())) #del self.train_triples_with_reverse del self.valid_triples_dict del self.test_triples_dict self.train_triples_numpy_array = np.array(self.train_triples_with_reverse).astype(np.int32) self.valid_triples_for_classification = np.array(self.valid_triples_for_classification).astype(np.int32)",
"read_dicts_from_file( [os.path.join(data_path,train_data_name), os.path.join(data_path,valid_data_name), os.path.join(data_path,test_data_name)], with_reverse=with_reverse ) self.entity_numbers = len(self.entity_dict.keys()) self.relation_numbers = len(self.relation_dict.keys()) self.train_triples_with_reverse",
"self.valid_triples_dict del self.test_triples_dict self.train_triples_numpy_array = np.array(self.train_triples_with_reverse).astype(np.int32) self.valid_triples_for_classification = np.array(self.valid_triples_for_classification).astype(np.int32) self.test_triples_for_classification = np.array(self.test_triples_for_classification).astype(np.int32) def",
"random_train_triple[start_index:end_index,:].copy() new_batch_train_triple_fake = random_train_triple[start_index:end_index,:].copy() random_words = np.random.randint(0,self.entity_numbers,current_batch_size) for index in range(current_batch_size): while (new_batch_train_triple_fake[index,0],",
"+ list(self.valid_triples_dict.items()) + list(self.test_triples_dict.items())) #del self.train_triples_with_reverse del self.valid_triples_dict del self.test_triples_dict self.train_triples_numpy_array = np.array(self.train_triples_with_reverse).astype(np.int32)",
"= turn_triples_to_label_dict(self.train_triples_with_reverse) self.valid_triples_dict = turn_triples_to_label_dict(self.valid_triples_with_reverse) self.test_triples_dict = turn_triples_to_label_dict(self.test_triples_with_reverse) self.gold_triples_dict = dict(list(self.train_triples_dict.items()) + list(self.valid_triples_dict.items())",
"import os import numpy as np import torch from utils.readdata import read_dicts_from_file,read_triples_from_file,turn_triples_to_label_dict class",
"list(self.valid_triples_dict.items()) + list(self.test_triples_dict.items())) #del self.train_triples_with_reverse del self.valid_triples_dict del self.test_triples_dict self.train_triples_numpy_array = np.array(self.train_triples_with_reverse).astype(np.int32) self.valid_triples_for_classification",
"= line.strip().split('\\t') if int(label) == 1: triples_list.append([ entity_dict[head], relation_dict[relation], entity_dict[tail] ]) if with_reverse:",
"with_reverse=with_reverse) self.test_triples_with_reverse,self.test_triples_for_classification = self.read_triple_from_file(os.path.join(data_path, test_data_name), self.entity_dict, self.relation_dict, with_reverse=with_reverse) self.train_numbers = len(self.train_triples_with_reverse) self.train_triples_dict =",
"for line in file: head, relation, tail, label = line.strip().split('\\t') if int(label) ==",
"= len(self.train_triples_with_reverse) self.train_triples_dict = turn_triples_to_label_dict(self.train_triples_with_reverse) self.valid_triples_dict = turn_triples_to_label_dict(self.valid_triples_with_reverse) self.test_triples_dict = turn_triples_to_label_dict(self.test_triples_with_reverse) self.gold_triples_dict =",
"= np.random.randint(0,self.entity_numbers,current_batch_size) for index in range(current_batch_size): while (new_batch_train_triple_fake[index,0], new_batch_train_triple_fake[index,1], random_words[index]) in self.train_triples_dict: random_words[index]",
"triples_list = [] classification_triples_label = [] with open(filename) as file: for line in",
"if int(label) == 1: triples_list.append([ entity_dict[head], relation_dict[relation], entity_dict[tail] ]) if with_reverse: relation_reverse =",
"= self.train_numbers pointer = end_index current_batch_size = end_index - start_index new_batch_train_triple_true = random_train_triple[start_index:end_index,:].copy()",
"as np import torch from utils.readdata import read_dicts_from_file,read_triples_from_file,turn_triples_to_label_dict class TripleClassificationData(object): def __init__(self,data_path,train_data_name,valid_data_name,test_data_name,with_reverse=False): self.entity_dict,self.relation_dict",
"with_reverse: relation_reverse = relation + '_reverse' triples_list.append([ entity_dict[tail], relation_dict[relation_reverse], entity_dict[head] ]) classification_triples_label.append([ entity_dict[head],",
"self.entity_dict, self.relation_dict, with_reverse=with_reverse) self.valid_triples_with_reverse,self.valid_triples_for_classification = self.read_triple_from_file(os.path.join(data_path, valid_data_name), self.entity_dict, self.relation_dict, with_reverse=with_reverse) self.test_triples_with_reverse,self.test_triples_for_classification = self.read_triple_from_file(os.path.join(data_path,",
"self.train_triples_dict = turn_triples_to_label_dict(self.train_triples_with_reverse) self.valid_triples_dict = turn_triples_to_label_dict(self.valid_triples_with_reverse) self.test_triples_dict = turn_triples_to_label_dict(self.test_triples_with_reverse) self.gold_triples_dict = dict(list(self.train_triples_dict.items()) +",
"file: for line in file: head, relation, tail, label = line.strip().split('\\t') if int(label)",
"def get_batch(self,batch_size): random_index = np.random.permutation(self.train_numbers) random_train_triple = self.train_triples_numpy_array[random_index] pointer = 0 while pointer",
"= turn_triples_to_label_dict(self.valid_triples_with_reverse) self.test_triples_dict = turn_triples_to_label_dict(self.test_triples_with_reverse) self.gold_triples_dict = dict(list(self.train_triples_dict.items()) + list(self.valid_triples_dict.items()) + list(self.test_triples_dict.items())) #del",
"self.relation_dict, with_reverse=with_reverse) self.train_numbers = len(self.train_triples_with_reverse) self.train_triples_dict = turn_triples_to_label_dict(self.train_triples_with_reverse) self.valid_triples_dict = turn_triples_to_label_dict(self.valid_triples_with_reverse) self.test_triples_dict =",
"self.read_triple_from_file(os.path.join(data_path, valid_data_name), self.entity_dict, self.relation_dict, with_reverse=with_reverse) self.test_triples_with_reverse,self.test_triples_for_classification = self.read_triple_from_file(os.path.join(data_path, test_data_name), self.entity_dict, self.relation_dict, with_reverse=with_reverse) self.train_numbers",
"end_index = start_index + batch_size if end_index >= self.train_numbers: end_index = self.train_numbers pointer",
"head, relation, tail, label = line.strip().split('\\t') if int(label) == 1: triples_list.append([ entity_dict[head], relation_dict[relation],",
"import numpy as np import torch from utils.readdata import read_dicts_from_file,read_triples_from_file,turn_triples_to_label_dict class TripleClassificationData(object): def",
"len(self.entity_dict.keys()) self.relation_numbers = len(self.relation_dict.keys()) self.train_triples_with_reverse = read_triples_from_file(os.path.join(data_path, train_data_name), self.entity_dict, self.relation_dict, with_reverse=with_reverse) self.valid_triples_with_reverse,self.valid_triples_for_classification =",
"start_index + batch_size if end_index >= self.train_numbers: end_index = self.train_numbers pointer = end_index",
"random_index = np.random.permutation(self.train_numbers) random_train_triple = self.train_triples_numpy_array[random_index] pointer = 0 while pointer < self.train_numbers:",
"self.test_triples_dict = turn_triples_to_label_dict(self.test_triples_with_reverse) self.gold_triples_dict = dict(list(self.train_triples_dict.items()) + list(self.valid_triples_dict.items()) + list(self.test_triples_dict.items())) #del self.train_triples_with_reverse del",
"self.entity_dict, self.relation_dict, with_reverse=with_reverse) self.train_numbers = len(self.train_triples_with_reverse) self.train_triples_dict = turn_triples_to_label_dict(self.train_triples_with_reverse) self.valid_triples_dict = turn_triples_to_label_dict(self.valid_triples_with_reverse) self.test_triples_dict",
"__init__(self,data_path,train_data_name,valid_data_name,test_data_name,with_reverse=False): self.entity_dict,self.relation_dict = read_dicts_from_file( [os.path.join(data_path,train_data_name), os.path.join(data_path,valid_data_name), os.path.join(data_path,test_data_name)], with_reverse=with_reverse ) self.entity_numbers = len(self.entity_dict.keys()) self.relation_numbers",
"open(filename) as file: for line in file: head, relation, tail, label = line.strip().split('\\t')",
"for index in range(current_batch_size): while (new_batch_train_triple_fake[index,0], new_batch_train_triple_fake[index,1], random_words[index]) in self.train_triples_dict: random_words[index] = np.random.randint(0,self.entity_numbers)",
"self.read_triple_from_file(os.path.join(data_path, test_data_name), self.entity_dict, self.relation_dict, with_reverse=with_reverse) self.train_numbers = len(self.train_triples_with_reverse) self.train_triples_dict = turn_triples_to_label_dict(self.train_triples_with_reverse) self.valid_triples_dict =",
"def read_triple_from_file(self,filename,entity_dict,relation_dict,with_reverse): triples_list = [] classification_triples_label = [] with open(filename) as file: for",
"self.train_triples_numpy_array[random_index] pointer = 0 while pointer < self.train_numbers: start_index = pointer end_index =",
"len(self.relation_dict.keys()) self.train_triples_with_reverse = read_triples_from_file(os.path.join(data_path, train_data_name), self.entity_dict, self.relation_dict, with_reverse=with_reverse) self.valid_triples_with_reverse,self.valid_triples_for_classification = self.read_triple_from_file(os.path.join(data_path, valid_data_name), self.entity_dict,",
"random_words = np.random.randint(0,self.entity_numbers,current_batch_size) for index in range(current_batch_size): while (new_batch_train_triple_fake[index,0], new_batch_train_triple_fake[index,1], random_words[index]) in self.train_triples_dict:",
"np.random.randint(0,self.entity_numbers,current_batch_size) for index in range(current_batch_size): while (new_batch_train_triple_fake[index,0], new_batch_train_triple_fake[index,1], random_words[index]) in self.train_triples_dict: random_words[index] =",
"self.entity_dict, self.relation_dict, with_reverse=with_reverse) self.test_triples_with_reverse,self.test_triples_for_classification = self.read_triple_from_file(os.path.join(data_path, test_data_name), self.entity_dict, self.relation_dict, with_reverse=with_reverse) self.train_numbers = len(self.train_triples_with_reverse)",
"self.train_numbers: end_index = self.train_numbers pointer = end_index current_batch_size = end_index - start_index new_batch_train_triple_true",
"with_reverse=with_reverse ) self.entity_numbers = len(self.entity_dict.keys()) self.relation_numbers = len(self.relation_dict.keys()) self.train_triples_with_reverse = read_triples_from_file(os.path.join(data_path, train_data_name), self.entity_dict,",
") self.entity_numbers = len(self.entity_dict.keys()) self.relation_numbers = len(self.relation_dict.keys()) self.train_triples_with_reverse = read_triples_from_file(os.path.join(data_path, train_data_name), self.entity_dict, self.relation_dict,",
"+ batch_size if end_index >= self.train_numbers: end_index = self.train_numbers pointer = end_index current_batch_size",
"self.entity_numbers = len(self.entity_dict.keys()) self.relation_numbers = len(self.relation_dict.keys()) self.train_triples_with_reverse = read_triples_from_file(os.path.join(data_path, train_data_name), self.entity_dict, self.relation_dict, with_reverse=with_reverse)",
"self.valid_triples_with_reverse,self.valid_triples_for_classification = self.read_triple_from_file(os.path.join(data_path, valid_data_name), self.entity_dict, self.relation_dict, with_reverse=with_reverse) self.test_triples_with_reverse,self.test_triples_for_classification = self.read_triple_from_file(os.path.join(data_path, test_data_name), self.entity_dict, self.relation_dict,",
"np.array(self.train_triples_with_reverse).astype(np.int32) self.valid_triples_for_classification = np.array(self.valid_triples_for_classification).astype(np.int32) self.test_triples_for_classification = np.array(self.test_triples_for_classification).astype(np.int32) def read_triple_from_file(self,filename,entity_dict,relation_dict,with_reverse): triples_list = [] classification_triples_label",
"os import numpy as np import torch from utils.readdata import read_dicts_from_file,read_triples_from_file,turn_triples_to_label_dict class TripleClassificationData(object):",
"= [] with open(filename) as file: for line in file: head, relation, tail,",
"os.path.join(data_path,valid_data_name), os.path.join(data_path,test_data_name)], with_reverse=with_reverse ) self.entity_numbers = len(self.entity_dict.keys()) self.relation_numbers = len(self.relation_dict.keys()) self.train_triples_with_reverse = read_triples_from_file(os.path.join(data_path,",
"triples_list.append([ entity_dict[tail], relation_dict[relation_reverse], entity_dict[head] ]) classification_triples_label.append([ entity_dict[head], relation_dict[relation], entity_dict[tail], label ]) return triples_list,classification_triples_label",
"while (new_batch_train_triple_fake[index,0], new_batch_train_triple_fake[index,1], random_words[index]) in self.train_triples_dict: random_words[index] = np.random.randint(0,self.entity_numbers) new_batch_train_triple_fake[index,2] = random_words[index] yield",
"utils.readdata import read_dicts_from_file,read_triples_from_file,turn_triples_to_label_dict class TripleClassificationData(object): def __init__(self,data_path,train_data_name,valid_data_name,test_data_name,with_reverse=False): self.entity_dict,self.relation_dict = read_dicts_from_file( [os.path.join(data_path,train_data_name), os.path.join(data_path,valid_data_name), os.path.join(data_path,test_data_name)],",
"current_batch_size = end_index - start_index new_batch_train_triple_true = random_train_triple[start_index:end_index,:].copy() new_batch_train_triple_fake = random_train_triple[start_index:end_index,:].copy() random_words =",
"tail, label = line.strip().split('\\t') if int(label) == 1: triples_list.append([ entity_dict[head], relation_dict[relation], entity_dict[tail] ])",
"TripleClassificationData(object): def __init__(self,data_path,train_data_name,valid_data_name,test_data_name,with_reverse=False): self.entity_dict,self.relation_dict = read_dicts_from_file( [os.path.join(data_path,train_data_name), os.path.join(data_path,valid_data_name), os.path.join(data_path,test_data_name)], with_reverse=with_reverse ) self.entity_numbers =",
"relation_dict[relation_reverse], entity_dict[head] ]) classification_triples_label.append([ entity_dict[head], relation_dict[relation], entity_dict[tail], label ]) return triples_list,classification_triples_label def get_batch(self,batch_size):",
"= 0 while pointer < self.train_numbers: start_index = pointer end_index = start_index +",
"np import torch from utils.readdata import read_dicts_from_file,read_triples_from_file,turn_triples_to_label_dict class TripleClassificationData(object): def __init__(self,data_path,train_data_name,valid_data_name,test_data_name,with_reverse=False): self.entity_dict,self.relation_dict =",
"class TripleClassificationData(object): def __init__(self,data_path,train_data_name,valid_data_name,test_data_name,with_reverse=False): self.entity_dict,self.relation_dict = read_dicts_from_file( [os.path.join(data_path,train_data_name), os.path.join(data_path,valid_data_name), os.path.join(data_path,test_data_name)], with_reverse=with_reverse ) self.entity_numbers",
"del self.valid_triples_dict del self.test_triples_dict self.train_triples_numpy_array = np.array(self.train_triples_with_reverse).astype(np.int32) self.valid_triples_for_classification = np.array(self.valid_triples_for_classification).astype(np.int32) self.test_triples_for_classification = np.array(self.test_triples_for_classification).astype(np.int32)",
"dict(list(self.train_triples_dict.items()) + list(self.valid_triples_dict.items()) + list(self.test_triples_dict.items())) #del self.train_triples_with_reverse del self.valid_triples_dict del self.test_triples_dict self.train_triples_numpy_array =",
"self.train_numbers: start_index = pointer end_index = start_index + batch_size if end_index >= self.train_numbers:",
">= self.train_numbers: end_index = self.train_numbers pointer = end_index current_batch_size = end_index - start_index",
"]) if with_reverse: relation_reverse = relation + '_reverse' triples_list.append([ entity_dict[tail], relation_dict[relation_reverse], entity_dict[head] ])",
"classification_triples_label.append([ entity_dict[head], relation_dict[relation], entity_dict[tail], label ]) return triples_list,classification_triples_label def get_batch(self,batch_size): random_index = np.random.permutation(self.train_numbers)",
"= random_train_triple[start_index:end_index,:].copy() random_words = np.random.randint(0,self.entity_numbers,current_batch_size) for index in range(current_batch_size): while (new_batch_train_triple_fake[index,0], new_batch_train_triple_fake[index,1], random_words[index])",
"end_index >= self.train_numbers: end_index = self.train_numbers pointer = end_index current_batch_size = end_index -",
"numpy as np import torch from utils.readdata import read_dicts_from_file,read_triples_from_file,turn_triples_to_label_dict class TripleClassificationData(object): def __init__(self,data_path,train_data_name,valid_data_name,test_data_name,with_reverse=False):",
"relation, tail, label = line.strip().split('\\t') if int(label) == 1: triples_list.append([ entity_dict[head], relation_dict[relation], entity_dict[tail]",
"1: triples_list.append([ entity_dict[head], relation_dict[relation], entity_dict[tail] ]) if with_reverse: relation_reverse = relation + '_reverse'",
"+ '_reverse' triples_list.append([ entity_dict[tail], relation_dict[relation_reverse], entity_dict[head] ]) classification_triples_label.append([ entity_dict[head], relation_dict[relation], entity_dict[tail], label ])",
"new_batch_train_triple_true = random_train_triple[start_index:end_index,:].copy() new_batch_train_triple_fake = random_train_triple[start_index:end_index,:].copy() random_words = np.random.randint(0,self.entity_numbers,current_batch_size) for index in range(current_batch_size):",
"self.relation_dict, with_reverse=with_reverse) self.test_triples_with_reverse,self.test_triples_for_classification = self.read_triple_from_file(os.path.join(data_path, test_data_name), self.entity_dict, self.relation_dict, with_reverse=with_reverse) self.train_numbers = len(self.train_triples_with_reverse) self.train_triples_dict",
"self.test_triples_dict self.train_triples_numpy_array = np.array(self.train_triples_with_reverse).astype(np.int32) self.valid_triples_for_classification = np.array(self.valid_triples_for_classification).astype(np.int32) self.test_triples_for_classification = np.array(self.test_triples_for_classification).astype(np.int32) def read_triple_from_file(self,filename,entity_dict,relation_dict,with_reverse): triples_list",
"entity_dict[tail] ]) if with_reverse: relation_reverse = relation + '_reverse' triples_list.append([ entity_dict[tail], relation_dict[relation_reverse], entity_dict[head]",
"read_triple_from_file(self,filename,entity_dict,relation_dict,with_reverse): triples_list = [] classification_triples_label = [] with open(filename) as file: for line",
"file: head, relation, tail, label = line.strip().split('\\t') if int(label) == 1: triples_list.append([ entity_dict[head],",
"[os.path.join(data_path,train_data_name), os.path.join(data_path,valid_data_name), os.path.join(data_path,test_data_name)], with_reverse=with_reverse ) self.entity_numbers = len(self.entity_dict.keys()) self.relation_numbers = len(self.relation_dict.keys()) self.train_triples_with_reverse =",
"np.array(self.valid_triples_for_classification).astype(np.int32) self.test_triples_for_classification = np.array(self.test_triples_for_classification).astype(np.int32) def read_triple_from_file(self,filename,entity_dict,relation_dict,with_reverse): triples_list = [] classification_triples_label = [] with",
"with_reverse=with_reverse) self.valid_triples_with_reverse,self.valid_triples_for_classification = self.read_triple_from_file(os.path.join(data_path, valid_data_name), self.entity_dict, self.relation_dict, with_reverse=with_reverse) self.test_triples_with_reverse,self.test_triples_for_classification = self.read_triple_from_file(os.path.join(data_path, test_data_name), self.entity_dict,",
"torch from utils.readdata import read_dicts_from_file,read_triples_from_file,turn_triples_to_label_dict class TripleClassificationData(object): def __init__(self,data_path,train_data_name,valid_data_name,test_data_name,with_reverse=False): self.entity_dict,self.relation_dict = read_dicts_from_file( [os.path.join(data_path,train_data_name),",
"self.train_numbers = len(self.train_triples_with_reverse) self.train_triples_dict = turn_triples_to_label_dict(self.train_triples_with_reverse) self.valid_triples_dict = turn_triples_to_label_dict(self.valid_triples_with_reverse) self.test_triples_dict = turn_triples_to_label_dict(self.test_triples_with_reverse) self.gold_triples_dict",
"in file: head, relation, tail, label = line.strip().split('\\t') if int(label) == 1: triples_list.append([",
"turn_triples_to_label_dict(self.valid_triples_with_reverse) self.test_triples_dict = turn_triples_to_label_dict(self.test_triples_with_reverse) self.gold_triples_dict = dict(list(self.train_triples_dict.items()) + list(self.valid_triples_dict.items()) + list(self.test_triples_dict.items())) #del self.train_triples_with_reverse",
"test_data_name), self.entity_dict, self.relation_dict, with_reverse=with_reverse) self.train_numbers = len(self.train_triples_with_reverse) self.train_triples_dict = turn_triples_to_label_dict(self.train_triples_with_reverse) self.valid_triples_dict = turn_triples_to_label_dict(self.valid_triples_with_reverse)",
"entity_dict[head] ]) classification_triples_label.append([ entity_dict[head], relation_dict[relation], entity_dict[tail], label ]) return triples_list,classification_triples_label def get_batch(self,batch_size): random_index",
"= [] classification_triples_label = [] with open(filename) as file: for line in file:",
"entity_dict[tail], label ]) return triples_list,classification_triples_label def get_batch(self,batch_size): random_index = np.random.permutation(self.train_numbers) random_train_triple = self.train_triples_numpy_array[random_index]",
"with open(filename) as file: for line in file: head, relation, tail, label =",
"random_train_triple[start_index:end_index,:].copy() random_words = np.random.randint(0,self.entity_numbers,current_batch_size) for index in range(current_batch_size): while (new_batch_train_triple_fake[index,0], new_batch_train_triple_fake[index,1], random_words[index]) in",
"start_index new_batch_train_triple_true = random_train_triple[start_index:end_index,:].copy() new_batch_train_triple_fake = random_train_triple[start_index:end_index,:].copy() random_words = np.random.randint(0,self.entity_numbers,current_batch_size) for index in",
"random_train_triple = self.train_triples_numpy_array[random_index] pointer = 0 while pointer < self.train_numbers: start_index = pointer",
"label = line.strip().split('\\t') if int(label) == 1: triples_list.append([ entity_dict[head], relation_dict[relation], entity_dict[tail] ]) if",
"= read_triples_from_file(os.path.join(data_path, train_data_name), self.entity_dict, self.relation_dict, with_reverse=with_reverse) self.valid_triples_with_reverse,self.valid_triples_for_classification = self.read_triple_from_file(os.path.join(data_path, valid_data_name), self.entity_dict, self.relation_dict, with_reverse=with_reverse)",
"self.gold_triples_dict = dict(list(self.train_triples_dict.items()) + list(self.valid_triples_dict.items()) + list(self.test_triples_dict.items())) #del self.train_triples_with_reverse del self.valid_triples_dict del self.test_triples_dict",
"self.test_triples_with_reverse,self.test_triples_for_classification = self.read_triple_from_file(os.path.join(data_path, test_data_name), self.entity_dict, self.relation_dict, with_reverse=with_reverse) self.train_numbers = len(self.train_triples_with_reverse) self.train_triples_dict = turn_triples_to_label_dict(self.train_triples_with_reverse)",
"start_index = pointer end_index = start_index + batch_size if end_index >= self.train_numbers: end_index",
"relation_dict[relation], entity_dict[tail] ]) if with_reverse: relation_reverse = relation + '_reverse' triples_list.append([ entity_dict[tail], relation_dict[relation_reverse],",
"as file: for line in file: head, relation, tail, label = line.strip().split('\\t') if",
"turn_triples_to_label_dict(self.test_triples_with_reverse) self.gold_triples_dict = dict(list(self.train_triples_dict.items()) + list(self.valid_triples_dict.items()) + list(self.test_triples_dict.items())) #del self.train_triples_with_reverse del self.valid_triples_dict del",
"relation_reverse = relation + '_reverse' triples_list.append([ entity_dict[tail], relation_dict[relation_reverse], entity_dict[head] ]) classification_triples_label.append([ entity_dict[head], relation_dict[relation],",
"[] with open(filename) as file: for line in file: head, relation, tail, label",
"new_batch_train_triple_fake = random_train_triple[start_index:end_index,:].copy() random_words = np.random.randint(0,self.entity_numbers,current_batch_size) for index in range(current_batch_size): while (new_batch_train_triple_fake[index,0], new_batch_train_triple_fake[index,1],",
"< self.train_numbers: start_index = pointer end_index = start_index + batch_size if end_index >=",
"= np.random.permutation(self.train_numbers) random_train_triple = self.train_triples_numpy_array[random_index] pointer = 0 while pointer < self.train_numbers: start_index",
"= read_dicts_from_file( [os.path.join(data_path,train_data_name), os.path.join(data_path,valid_data_name), os.path.join(data_path,test_data_name)], with_reverse=with_reverse ) self.entity_numbers = len(self.entity_dict.keys()) self.relation_numbers = len(self.relation_dict.keys())",
"0 while pointer < self.train_numbers: start_index = pointer end_index = start_index + batch_size",
"pointer = end_index current_batch_size = end_index - start_index new_batch_train_triple_true = random_train_triple[start_index:end_index,:].copy() new_batch_train_triple_fake =",
"= np.array(self.test_triples_for_classification).astype(np.int32) def read_triple_from_file(self,filename,entity_dict,relation_dict,with_reverse): triples_list = [] classification_triples_label = [] with open(filename) as",
"from utils.readdata import read_dicts_from_file,read_triples_from_file,turn_triples_to_label_dict class TripleClassificationData(object): def __init__(self,data_path,train_data_name,valid_data_name,test_data_name,with_reverse=False): self.entity_dict,self.relation_dict = read_dicts_from_file( [os.path.join(data_path,train_data_name), os.path.join(data_path,valid_data_name),",
"self.train_triples_with_reverse del self.valid_triples_dict del self.test_triples_dict self.train_triples_numpy_array = np.array(self.train_triples_with_reverse).astype(np.int32) self.valid_triples_for_classification = np.array(self.valid_triples_for_classification).astype(np.int32) self.test_triples_for_classification =",
"np.random.permutation(self.train_numbers) random_train_triple = self.train_triples_numpy_array[random_index] pointer = 0 while pointer < self.train_numbers: start_index =",
"with_reverse=with_reverse) self.train_numbers = len(self.train_triples_with_reverse) self.train_triples_dict = turn_triples_to_label_dict(self.train_triples_with_reverse) self.valid_triples_dict = turn_triples_to_label_dict(self.valid_triples_with_reverse) self.test_triples_dict = turn_triples_to_label_dict(self.test_triples_with_reverse)",
"= np.array(self.valid_triples_for_classification).astype(np.int32) self.test_triples_for_classification = np.array(self.test_triples_for_classification).astype(np.int32) def read_triple_from_file(self,filename,entity_dict,relation_dict,with_reverse): triples_list = [] classification_triples_label = []",
"pointer end_index = start_index + batch_size if end_index >= self.train_numbers: end_index = self.train_numbers",
"while pointer < self.train_numbers: start_index = pointer end_index = start_index + batch_size if",
"import read_dicts_from_file,read_triples_from_file,turn_triples_to_label_dict class TripleClassificationData(object): def __init__(self,data_path,train_data_name,valid_data_name,test_data_name,with_reverse=False): self.entity_dict,self.relation_dict = read_dicts_from_file( [os.path.join(data_path,train_data_name), os.path.join(data_path,valid_data_name), os.path.join(data_path,test_data_name)], with_reverse=with_reverse",
"= len(self.relation_dict.keys()) self.train_triples_with_reverse = read_triples_from_file(os.path.join(data_path, train_data_name), self.entity_dict, self.relation_dict, with_reverse=with_reverse) self.valid_triples_with_reverse,self.valid_triples_for_classification = self.read_triple_from_file(os.path.join(data_path, valid_data_name),",
"def __init__(self,data_path,train_data_name,valid_data_name,test_data_name,with_reverse=False): self.entity_dict,self.relation_dict = read_dicts_from_file( [os.path.join(data_path,train_data_name), os.path.join(data_path,valid_data_name), os.path.join(data_path,test_data_name)], with_reverse=with_reverse ) self.entity_numbers = len(self.entity_dict.keys())",
"= turn_triples_to_label_dict(self.test_triples_with_reverse) self.gold_triples_dict = dict(list(self.train_triples_dict.items()) + list(self.valid_triples_dict.items()) + list(self.test_triples_dict.items())) #del self.train_triples_with_reverse del self.valid_triples_dict",
"label ]) return triples_list,classification_triples_label def get_batch(self,batch_size): random_index = np.random.permutation(self.train_numbers) random_train_triple = self.train_triples_numpy_array[random_index] pointer",
"- start_index new_batch_train_triple_true = random_train_triple[start_index:end_index,:].copy() new_batch_train_triple_fake = random_train_triple[start_index:end_index,:].copy() random_words = np.random.randint(0,self.entity_numbers,current_batch_size) for index",
"turn_triples_to_label_dict(self.train_triples_with_reverse) self.valid_triples_dict = turn_triples_to_label_dict(self.valid_triples_with_reverse) self.test_triples_dict = turn_triples_to_label_dict(self.test_triples_with_reverse) self.gold_triples_dict = dict(list(self.train_triples_dict.items()) + list(self.valid_triples_dict.items()) +",
"pointer < self.train_numbers: start_index = pointer end_index = start_index + batch_size if end_index",
"== 1: triples_list.append([ entity_dict[head], relation_dict[relation], entity_dict[tail] ]) if with_reverse: relation_reverse = relation +",
"int(label) == 1: triples_list.append([ entity_dict[head], relation_dict[relation], entity_dict[tail] ]) if with_reverse: relation_reverse = relation",
"read_triples_from_file(os.path.join(data_path, train_data_name), self.entity_dict, self.relation_dict, with_reverse=with_reverse) self.valid_triples_with_reverse,self.valid_triples_for_classification = self.read_triple_from_file(os.path.join(data_path, valid_data_name), self.entity_dict, self.relation_dict, with_reverse=with_reverse) self.test_triples_with_reverse,self.test_triples_for_classification",
"pointer = 0 while pointer < self.train_numbers: start_index = pointer end_index = start_index",
"'_reverse' triples_list.append([ entity_dict[tail], relation_dict[relation_reverse], entity_dict[head] ]) classification_triples_label.append([ entity_dict[head], relation_dict[relation], entity_dict[tail], label ]) return",
"= random_train_triple[start_index:end_index,:].copy() new_batch_train_triple_fake = random_train_triple[start_index:end_index,:].copy() random_words = np.random.randint(0,self.entity_numbers,current_batch_size) for index in range(current_batch_size): while",
"train_data_name), self.entity_dict, self.relation_dict, with_reverse=with_reverse) self.valid_triples_with_reverse,self.valid_triples_for_classification = self.read_triple_from_file(os.path.join(data_path, valid_data_name), self.entity_dict, self.relation_dict, with_reverse=with_reverse) self.test_triples_with_reverse,self.test_triples_for_classification =",
"= start_index + batch_size if end_index >= self.train_numbers: end_index = self.train_numbers pointer =",
"+ list(self.test_triples_dict.items())) #del self.train_triples_with_reverse del self.valid_triples_dict del self.test_triples_dict self.train_triples_numpy_array = np.array(self.train_triples_with_reverse).astype(np.int32) self.valid_triples_for_classification =",
"line in file: head, relation, tail, label = line.strip().split('\\t') if int(label) == 1:",
"relation_dict[relation], entity_dict[tail], label ]) return triples_list,classification_triples_label def get_batch(self,batch_size): random_index = np.random.permutation(self.train_numbers) random_train_triple =",
"self.train_numbers pointer = end_index current_batch_size = end_index - start_index new_batch_train_triple_true = random_train_triple[start_index:end_index,:].copy() new_batch_train_triple_fake",
"valid_data_name), self.entity_dict, self.relation_dict, with_reverse=with_reverse) self.test_triples_with_reverse,self.test_triples_for_classification = self.read_triple_from_file(os.path.join(data_path, test_data_name), self.entity_dict, self.relation_dict, with_reverse=with_reverse) self.train_numbers =",
"]) return triples_list,classification_triples_label def get_batch(self,batch_size): random_index = np.random.permutation(self.train_numbers) random_train_triple = self.train_triples_numpy_array[random_index] pointer =",
"index in range(current_batch_size): while (new_batch_train_triple_fake[index,0], new_batch_train_triple_fake[index,1], random_words[index]) in self.train_triples_dict: random_words[index] = np.random.randint(0,self.entity_numbers) new_batch_train_triple_fake[index,2]",
"triples_list,classification_triples_label def get_batch(self,batch_size): random_index = np.random.permutation(self.train_numbers) random_train_triple = self.train_triples_numpy_array[random_index] pointer = 0 while",
"end_index = self.train_numbers pointer = end_index current_batch_size = end_index - start_index new_batch_train_triple_true =",
"import torch from utils.readdata import read_dicts_from_file,read_triples_from_file,turn_triples_to_label_dict class TripleClassificationData(object): def __init__(self,data_path,train_data_name,valid_data_name,test_data_name,with_reverse=False): self.entity_dict,self.relation_dict = read_dicts_from_file(",
"self.valid_triples_for_classification = np.array(self.valid_triples_for_classification).astype(np.int32) self.test_triples_for_classification = np.array(self.test_triples_for_classification).astype(np.int32) def read_triple_from_file(self,filename,entity_dict,relation_dict,with_reverse): triples_list = [] classification_triples_label =",
"entity_dict[head], relation_dict[relation], entity_dict[tail] ]) if with_reverse: relation_reverse = relation + '_reverse' triples_list.append([ entity_dict[tail],",
"np.array(self.test_triples_for_classification).astype(np.int32) def read_triple_from_file(self,filename,entity_dict,relation_dict,with_reverse): triples_list = [] classification_triples_label = [] with open(filename) as file:",
"get_batch(self,batch_size): random_index = np.random.permutation(self.train_numbers) random_train_triple = self.train_triples_numpy_array[random_index] pointer = 0 while pointer <",
"end_index - start_index new_batch_train_triple_true = random_train_triple[start_index:end_index,:].copy() new_batch_train_triple_fake = random_train_triple[start_index:end_index,:].copy() random_words = np.random.randint(0,self.entity_numbers,current_batch_size) for",
"= dict(list(self.train_triples_dict.items()) + list(self.valid_triples_dict.items()) + list(self.test_triples_dict.items())) #del self.train_triples_with_reverse del self.valid_triples_dict del self.test_triples_dict self.train_triples_numpy_array",
"entity_dict[tail], relation_dict[relation_reverse], entity_dict[head] ]) classification_triples_label.append([ entity_dict[head], relation_dict[relation], entity_dict[tail], label ]) return triples_list,classification_triples_label def",
"= end_index current_batch_size = end_index - start_index new_batch_train_triple_true = random_train_triple[start_index:end_index,:].copy() new_batch_train_triple_fake = random_train_triple[start_index:end_index,:].copy()",
"self.test_triples_for_classification = np.array(self.test_triples_for_classification).astype(np.int32) def read_triple_from_file(self,filename,entity_dict,relation_dict,with_reverse): triples_list = [] classification_triples_label = [] with open(filename)",
"range(current_batch_size): while (new_batch_train_triple_fake[index,0], new_batch_train_triple_fake[index,1], random_words[index]) in self.train_triples_dict: random_words[index] = np.random.randint(0,self.entity_numbers) new_batch_train_triple_fake[index,2] = random_words[index]",
"self.train_triples_with_reverse = read_triples_from_file(os.path.join(data_path, train_data_name), self.entity_dict, self.relation_dict, with_reverse=with_reverse) self.valid_triples_with_reverse,self.valid_triples_for_classification = self.read_triple_from_file(os.path.join(data_path, valid_data_name), self.entity_dict, self.relation_dict,",
"= end_index - start_index new_batch_train_triple_true = random_train_triple[start_index:end_index,:].copy() new_batch_train_triple_fake = random_train_triple[start_index:end_index,:].copy() random_words = np.random.randint(0,self.entity_numbers,current_batch_size)",
"self.entity_dict,self.relation_dict = read_dicts_from_file( [os.path.join(data_path,train_data_name), os.path.join(data_path,valid_data_name), os.path.join(data_path,test_data_name)], with_reverse=with_reverse ) self.entity_numbers = len(self.entity_dict.keys()) self.relation_numbers =",
"if end_index >= self.train_numbers: end_index = self.train_numbers pointer = end_index current_batch_size = end_index",
"del self.test_triples_dict self.train_triples_numpy_array = np.array(self.train_triples_with_reverse).astype(np.int32) self.valid_triples_for_classification = np.array(self.valid_triples_for_classification).astype(np.int32) self.test_triples_for_classification = np.array(self.test_triples_for_classification).astype(np.int32) def read_triple_from_file(self,filename,entity_dict,relation_dict,with_reverse):",
"#del self.train_triples_with_reverse del self.valid_triples_dict del self.test_triples_dict self.train_triples_numpy_array = np.array(self.train_triples_with_reverse).astype(np.int32) self.valid_triples_for_classification = np.array(self.valid_triples_for_classification).astype(np.int32) self.test_triples_for_classification"
] |
[
"absolute_import from goonpug import app def main(): app.run(debug=True) if __name__ == '__main__': main()",
"python from __future__ import absolute_import from goonpug import app def main(): app.run(debug=True) if",
"#!/usr/bin/env python from __future__ import absolute_import from goonpug import app def main(): app.run(debug=True)",
"__future__ import absolute_import from goonpug import app def main(): app.run(debug=True) if __name__ ==",
"from __future__ import absolute_import from goonpug import app def main(): app.run(debug=True) if __name__",
"import absolute_import from goonpug import app def main(): app.run(debug=True) if __name__ == '__main__':"
] |
[
"are equal\"\"\" if not isinstance(other, GetUniverseGraphicsGraphicIdOk): return False return self.__dict__ == other.__dict__ def",
"noqa: E501 :return: The sof_hull_name of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 :rtype: str",
"noqa: E501 self._graphic_id = graphic_id @property def graphic_file(self): \"\"\"Gets the graphic_file of this",
"E501 :param sof_fation_name: The sof_fation_name of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 :type: str",
"getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x,",
":rtype: str \"\"\" return self._collision_file @collision_file.setter def collision_file(self, collision_file): \"\"\"Sets the collision_file of",
"\"\"\"Returns the string representation of the model\"\"\" return pprint.pformat(self.to_dict()) def __repr__(self): \"\"\"For `print`",
"noqa: E501 :rtype: str \"\"\" return self._icon_folder @icon_folder.setter def icon_folder(self, icon_folder): \"\"\"Sets the",
"__repr__(self): \"\"\"For `print` and `pprint`\"\"\" return self.to_str() def __eq__(self, other): \"\"\"Returns true if",
"The sof_hull_name of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 :type: str \"\"\" self._sof_hull_name =",
"sof_race_name if sof_fation_name is not None: self.sof_fation_name = sof_fation_name if sof_dna is not",
"0.8.0 Generated by: https://github.com/swagger-api/swagger-codegen.git \"\"\" import pprint import re # noqa: F401 import",
"re # noqa: F401 import six class GetUniverseGraphicsGraphicIdOk(object): \"\"\"NOTE: This class is auto",
"is not None: self.sof_hull_name = sof_hull_name if collision_file is not None: self.collision_file =",
"this GetUniverseGraphicsGraphicIdOk. # noqa: E501 :rtype: int \"\"\" return self._graphic_id @graphic_id.setter def graphic_id(self,",
"if sof_hull_name is not None: self.sof_hull_name = sof_hull_name if collision_file is not None:",
"noqa: E501 :type: str \"\"\" self._icon_folder = icon_folder def to_dict(self): \"\"\"Returns the model",
"None self._sof_race_name = None self._sof_fation_name = None self._sof_dna = None self._sof_hull_name = None",
"# noqa: E501 :return: The icon_folder of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 :rtype:",
"# noqa: E501 :param icon_folder: The icon_folder of this GetUniverseGraphicsGraphicIdOk. # noqa: E501",
"of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 :rtype: str \"\"\" return self._sof_race_name @sof_race_name.setter def",
"string # noqa: E501 :return: The icon_folder of this GetUniverseGraphicsGraphicIdOk. # noqa: E501",
"key is attribute name and the value is json key in definition. \"\"\"",
"graphic_file is not None: self.graphic_file = graphic_file if sof_race_name is not None: self.sof_race_name",
"sof_dna: The sof_dna of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 :type: str \"\"\" self._sof_dna",
"graphic_file of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 graphic_file string # noqa: E501 :return:",
"E501 sof_dna string # noqa: E501 :return: The sof_dna of this GetUniverseGraphicsGraphicIdOk. #",
"of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 graphic_id integer # noqa: E501 :return: The",
"return self._sof_race_name @sof_race_name.setter def sof_race_name(self, sof_race_name): \"\"\"Sets the sof_race_name of this GetUniverseGraphicsGraphicIdOk. sof_race_name",
"self._sof_race_name @sof_race_name.setter def sof_race_name(self, sof_race_name): \"\"\"Sets the sof_race_name of this GetUniverseGraphicsGraphicIdOk. sof_race_name string",
"# noqa: E501 sof_race_name string # noqa: E501 :return: The sof_race_name of this",
"# noqa: E501 :rtype: str \"\"\" return self._collision_file @collision_file.setter def collision_file(self, collision_file): \"\"\"Sets",
"The sof_dna of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 :rtype: str \"\"\" return self._sof_dna",
"# noqa: E501 :return: The sof_hull_name of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 :rtype:",
"GetUniverseGraphicsGraphicIdOk. collision_file string # noqa: E501 :param collision_file: The collision_file of this GetUniverseGraphicsGraphicIdOk.",
"The collision_file of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 :rtype: str \"\"\" return self._collision_file",
"self._sof_hull_name = sof_hull_name @property def collision_file(self): \"\"\"Gets the collision_file of this GetUniverseGraphicsGraphicIdOk. #",
"(dict): The key is attribute name and the value is attribute type. attribute_map",
":return: The graphic_id of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 :rtype: int \"\"\" return",
"self._collision_file = collision_file @property def icon_folder(self): \"\"\"Gets the icon_folder of this GetUniverseGraphicsGraphicIdOk. #",
"E501 :type: str \"\"\" self._collision_file = collision_file @property def icon_folder(self): \"\"\"Gets the icon_folder",
"str \"\"\" self._graphic_file = graphic_file @property def sof_race_name(self): \"\"\"Gets the sof_race_name of this",
"self.graphic_file = graphic_file if sof_race_name is not None: self.sof_race_name = sof_race_name if sof_fation_name",
"self._sof_fation_name = sof_fation_name @property def sof_dna(self): \"\"\"Gets the sof_dna of this GetUniverseGraphicsGraphicIdOk. #",
"noqa: E501 :param icon_folder: The icon_folder of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 :type:",
"value for `graphic_id`, must not be `None`\") # noqa: E501 self._graphic_id = graphic_id",
":return: The graphic_file of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 :rtype: str \"\"\" return",
"\"\"\"Sets the icon_folder of this GetUniverseGraphicsGraphicIdOk. icon_folder string # noqa: E501 :param icon_folder:",
"int \"\"\" if graphic_id is None: raise ValueError(\"Invalid value for `graphic_id`, must not",
"# noqa: E501 :param sof_race_name: The sof_race_name of this GetUniverseGraphicsGraphicIdOk. # noqa: E501",
"self._graphic_id @graphic_id.setter def graphic_id(self, graphic_id): \"\"\"Sets the graphic_id of this GetUniverseGraphicsGraphicIdOk. graphic_id integer",
":rtype: str \"\"\" return self._sof_dna @sof_dna.setter def sof_dna(self, sof_dna): \"\"\"Sets the sof_dna of",
"sof_dna): \"\"\"Sets the sof_dna of this GetUniverseGraphicsGraphicIdOk. sof_dna string # noqa: E501 :param",
"= sof_race_name if sof_fation_name is not None: self.sof_fation_name = sof_fation_name if sof_dna is",
"E501 :rtype: str \"\"\" return self._sof_fation_name @sof_fation_name.setter def sof_fation_name(self, sof_fation_name): \"\"\"Sets the sof_fation_name",
"\"\"\"Gets the icon_folder of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 icon_folder string # noqa:",
"result def to_str(self): \"\"\"Returns the string representation of the model\"\"\" return pprint.pformat(self.to_dict()) def",
"sof_fation_name of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 sof_fation_name string # noqa: E501 :return:",
"= collision_file if icon_folder is not None: self.icon_folder = icon_folder @property def graphic_id(self):",
"GetUniverseGraphicsGraphicIdOk. # noqa: E501 :type: str \"\"\" self._collision_file = collision_file @property def icon_folder(self):",
"= sof_hull_name if collision_file is not None: self.collision_file = collision_file if icon_folder is",
"str \"\"\" self._collision_file = collision_file @property def icon_folder(self): \"\"\"Gets the icon_folder of this",
"list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, \"to_dict\") else x, value",
"string representation of the model\"\"\" return pprint.pformat(self.to_dict()) def __repr__(self): \"\"\"For `print` and `pprint`\"\"\"",
"An OpenAPI for EVE Online # noqa: E501 OpenAPI spec version: 0.8.0 Generated",
"six class GetUniverseGraphicsGraphicIdOk(object): \"\"\"NOTE: This class is auto generated by the swagger code",
"'str', 'icon_folder': 'str' } attribute_map = { 'graphic_id': 'graphic_id', 'graphic_file': 'graphic_file', 'sof_race_name': 'sof_race_name',",
":type: str \"\"\" self._sof_fation_name = sof_fation_name @property def sof_dna(self): \"\"\"Gets the sof_dna of",
"is not None: self.graphic_file = graphic_file if sof_race_name is not None: self.sof_race_name =",
"x.to_dict() if hasattr(x, \"to_dict\") else x, value )) elif hasattr(value, \"to_dict\"): result[attr] =",
"`print` and `pprint`\"\"\" return self.to_str() def __eq__(self, other): \"\"\"Returns true if both objects",
"is not None: self.sof_fation_name = sof_fation_name if sof_dna is not None: self.sof_dna =",
"= sof_dna if sof_hull_name is not None: self.sof_hull_name = sof_hull_name if collision_file is",
"None: raise ValueError(\"Invalid value for `graphic_id`, must not be `None`\") # noqa: E501",
"attribute name and the value is attribute type. attribute_map (dict): The key is",
"The graphic_file of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 :type: str \"\"\" self._graphic_file =",
"this GetUniverseGraphicsGraphicIdOk. # noqa: E501 :type: str \"\"\" self._sof_fation_name = sof_fation_name @property def",
"hasattr(value, \"to_dict\"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item:",
"the sof_hull_name of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 sof_hull_name string # noqa: E501",
":type: int \"\"\" if graphic_id is None: raise ValueError(\"Invalid value for `graphic_id`, must",
"this GetUniverseGraphicsGraphicIdOk. # noqa: E501 :rtype: str \"\"\" return self._sof_hull_name @sof_hull_name.setter def sof_hull_name(self,",
"this GetUniverseGraphicsGraphicIdOk. graphic_id integer # noqa: E501 :param graphic_id: The graphic_id of this",
"E501 :rtype: str \"\"\" return self._sof_race_name @sof_race_name.setter def sof_race_name(self, sof_race_name): \"\"\"Sets the sof_race_name",
"the graphic_file of this GetUniverseGraphicsGraphicIdOk. graphic_file string # noqa: E501 :param graphic_file: The",
"noqa: E501 OpenAPI spec version: 0.8.0 Generated by: https://github.com/swagger-api/swagger-codegen.git \"\"\" import pprint import",
"icon_folder): \"\"\"Sets the icon_folder of this GetUniverseGraphicsGraphicIdOk. icon_folder string # noqa: E501 :param",
"= sof_fation_name @property def sof_dna(self): \"\"\"Gets the sof_dna of this GetUniverseGraphicsGraphicIdOk. # noqa:",
"of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 graphic_file string # noqa: E501 :return: The",
"graphic_id is None: raise ValueError(\"Invalid value for `graphic_id`, must not be `None`\") #",
"GetUniverseGraphicsGraphicIdOk. # noqa: E501 sof_hull_name string # noqa: E501 :return: The sof_hull_name of",
"of this GetUniverseGraphicsGraphicIdOk. sof_race_name string # noqa: E501 :param sof_race_name: The sof_race_name of",
"@sof_dna.setter def sof_dna(self, sof_dna): \"\"\"Sets the sof_dna of this GetUniverseGraphicsGraphicIdOk. sof_dna string #",
"E501 sof_hull_name string # noqa: E501 :return: The sof_hull_name of this GetUniverseGraphicsGraphicIdOk. #",
"this GetUniverseGraphicsGraphicIdOk. # noqa: E501 sof_dna string # noqa: E501 :return: The sof_dna",
"sof_dna @property def sof_hull_name(self): \"\"\"Gets the sof_hull_name of this GetUniverseGraphicsGraphicIdOk. # noqa: E501",
"The graphic_file of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 :rtype: str \"\"\" return self._graphic_file",
"{ 'graphic_id': 'graphic_id', 'graphic_file': 'graphic_file', 'sof_race_name': 'sof_race_name', 'sof_fation_name': 'sof_fation_name', 'sof_dna': 'sof_dna', 'sof_hull_name': 'sof_hull_name',",
"the sof_dna of this GetUniverseGraphicsGraphicIdOk. sof_dna string # noqa: E501 :param sof_dna: The",
"\"\"\"NOTE: This class is auto generated by the swagger code generator program. Do",
"graphic_id): \"\"\"Sets the graphic_id of this GetUniverseGraphicsGraphicIdOk. graphic_id integer # noqa: E501 :param",
"collision_file=None, icon_folder=None): # noqa: E501 \"\"\"GetUniverseGraphicsGraphicIdOk - a model defined in Swagger\"\"\" #",
"hasattr(item[1], \"to_dict\") else item, value.items() )) else: result[attr] = value return result def",
"int \"\"\" return self._graphic_id @graphic_id.setter def graphic_id(self, graphic_id): \"\"\"Sets the graphic_id of this",
"this GetUniverseGraphicsGraphicIdOk. # noqa: E501 :type: str \"\"\" self._collision_file = collision_file @property def",
"sof_dna if sof_hull_name is not None: self.sof_hull_name = sof_hull_name if collision_file is not",
"<filename>swagger_client/models/get_universe_graphics_graphic_id_ok.py # coding: utf-8 \"\"\" EVE Swagger Interface An OpenAPI for EVE Online",
"Attributes: swagger_types (dict): The key is attribute name and the value is attribute",
"noqa: E501 :return: The sof_fation_name of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 :rtype: str",
"# noqa: E501 \"\"\"GetUniverseGraphicsGraphicIdOk - a model defined in Swagger\"\"\" # noqa: E501",
"collision_file of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 :type: str \"\"\" self._collision_file = collision_file",
"} attribute_map = { 'graphic_id': 'graphic_id', 'graphic_file': 'graphic_file', 'sof_race_name': 'sof_race_name', 'sof_fation_name': 'sof_fation_name', 'sof_dna':",
"lambda x: x.to_dict() if hasattr(x, \"to_dict\") else x, value )) elif hasattr(value, \"to_dict\"):",
"version: 0.8.0 Generated by: https://github.com/swagger-api/swagger-codegen.git \"\"\" import pprint import re # noqa: F401",
"other.__dict__ def __ne__(self, other): \"\"\"Returns true if both objects are not equal\"\"\" return",
"swagger_types = { 'graphic_id': 'int', 'graphic_file': 'str', 'sof_race_name': 'str', 'sof_fation_name': 'str', 'sof_dna': 'str',",
"\"\"\" import pprint import re # noqa: F401 import six class GetUniverseGraphicsGraphicIdOk(object): \"\"\"NOTE:",
"self._graphic_file @graphic_file.setter def graphic_file(self, graphic_file): \"\"\"Sets the graphic_file of this GetUniverseGraphicsGraphicIdOk. graphic_file string",
"icon_folder def to_dict(self): \"\"\"Returns the model properties as a dict\"\"\" result = {}",
"# noqa: E501 :rtype: str \"\"\" return self._sof_dna @sof_dna.setter def sof_dna(self, sof_dna): \"\"\"Sets",
"is not None: self.icon_folder = icon_folder @property def graphic_id(self): \"\"\"Gets the graphic_id of",
"return self._icon_folder @icon_folder.setter def icon_folder(self, icon_folder): \"\"\"Sets the icon_folder of this GetUniverseGraphicsGraphicIdOk. icon_folder",
"str \"\"\" self._sof_hull_name = sof_hull_name @property def collision_file(self): \"\"\"Gets the collision_file of this",
"'sof_fation_name': 'sof_fation_name', 'sof_dna': 'sof_dna', 'sof_hull_name': 'sof_hull_name', 'collision_file': 'collision_file', 'icon_folder': 'icon_folder' } def __init__(self,",
"None: self.sof_dna = sof_dna if sof_hull_name is not None: self.sof_hull_name = sof_hull_name if",
"return self._collision_file @collision_file.setter def collision_file(self, collision_file): \"\"\"Sets the collision_file of this GetUniverseGraphicsGraphicIdOk. collision_file",
"of this GetUniverseGraphicsGraphicIdOk. sof_fation_name string # noqa: E501 :param sof_fation_name: The sof_fation_name of",
"GetUniverseGraphicsGraphicIdOk. sof_fation_name string # noqa: E501 :param sof_fation_name: The sof_fation_name of this GetUniverseGraphicsGraphicIdOk.",
"\"\"\" self._sof_hull_name = sof_hull_name @property def collision_file(self): \"\"\"Gets the collision_file of this GetUniverseGraphicsGraphicIdOk.",
"sof_hull_name @property def collision_file(self): \"\"\"Gets the collision_file of this GetUniverseGraphicsGraphicIdOk. # noqa: E501",
"sof_race_name): \"\"\"Sets the sof_race_name of this GetUniverseGraphicsGraphicIdOk. sof_race_name string # noqa: E501 :param",
"list(map( lambda x: x.to_dict() if hasattr(x, \"to_dict\") else x, value )) elif hasattr(value,",
"raise ValueError(\"Invalid value for `graphic_id`, must not be `None`\") # noqa: E501 self._graphic_id",
"def sof_race_name(self): \"\"\"Gets the sof_race_name of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 sof_race_name string",
"None self.graphic_id = graphic_id if graphic_file is not None: self.graphic_file = graphic_file if",
"of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 sof_fation_name string # noqa: E501 :return: The",
"F401 import six class GetUniverseGraphicsGraphicIdOk(object): \"\"\"NOTE: This class is auto generated by the",
"\"\"\" Attributes: swagger_types (dict): The key is attribute name and the value is",
"Swagger Interface An OpenAPI for EVE Online # noqa: E501 OpenAPI spec version:",
"self._graphic_file = graphic_file @property def sof_race_name(self): \"\"\"Gets the sof_race_name of this GetUniverseGraphicsGraphicIdOk. #",
"\"to_dict\"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0],",
"\"\"\" self._graphic_file = graphic_file @property def sof_race_name(self): \"\"\"Gets the sof_race_name of this GetUniverseGraphicsGraphicIdOk.",
"# noqa: E501 :param sof_dna: The sof_dna of this GetUniverseGraphicsGraphicIdOk. # noqa: E501",
"of this GetUniverseGraphicsGraphicIdOk. collision_file string # noqa: E501 :param collision_file: The collision_file of",
"this GetUniverseGraphicsGraphicIdOk. # noqa: E501 :rtype: str \"\"\" return self._sof_dna @sof_dna.setter def sof_dna(self,",
"value return result def to_str(self): \"\"\"Returns the string representation of the model\"\"\" return",
"and the value is json key in definition. \"\"\" swagger_types = { 'graphic_id':",
"dict\"\"\" result = {} for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr)",
"noqa: E501 self._graphic_id = None self._graphic_file = None self._sof_race_name = None self._sof_fation_name =",
"GetUniverseGraphicsGraphicIdOk. # noqa: E501 :rtype: str \"\"\" return self._icon_folder @icon_folder.setter def icon_folder(self, icon_folder):",
"self._sof_hull_name = None self._collision_file = None self._icon_folder = None self.discriminator = None self.graphic_id",
"@sof_hull_name.setter def sof_hull_name(self, sof_hull_name): \"\"\"Sets the sof_hull_name of this GetUniverseGraphicsGraphicIdOk. sof_hull_name string #",
"sof_dna(self): \"\"\"Gets the sof_dna of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 sof_dna string #",
"'sof_race_name': 'sof_race_name', 'sof_fation_name': 'sof_fation_name', 'sof_dna': 'sof_dna', 'sof_hull_name': 'sof_hull_name', 'collision_file': 'collision_file', 'icon_folder': 'icon_folder' }",
"if not isinstance(other, GetUniverseGraphicsGraphicIdOk): return False return self.__dict__ == other.__dict__ def __ne__(self, other):",
"@sof_fation_name.setter def sof_fation_name(self, sof_fation_name): \"\"\"Sets the sof_fation_name of this GetUniverseGraphicsGraphicIdOk. sof_fation_name string #",
"= value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if",
"GetUniverseGraphicsGraphicIdOk. # noqa: E501 :rtype: str \"\"\" return self._sof_hull_name @sof_hull_name.setter def sof_hull_name(self, sof_hull_name):",
":rtype: str \"\"\" return self._sof_hull_name @sof_hull_name.setter def sof_hull_name(self, sof_hull_name): \"\"\"Sets the sof_hull_name of",
"# noqa: E501 :rtype: str \"\"\" return self._sof_race_name @sof_race_name.setter def sof_race_name(self, sof_race_name): \"\"\"Sets",
":rtype: str \"\"\" return self._graphic_file @graphic_file.setter def graphic_file(self, graphic_file): \"\"\"Sets the graphic_file of",
":param sof_fation_name: The sof_fation_name of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 :type: str \"\"\"",
"string # noqa: E501 :param sof_race_name: The sof_race_name of this GetUniverseGraphicsGraphicIdOk. # noqa:",
"class GetUniverseGraphicsGraphicIdOk(object): \"\"\"NOTE: This class is auto generated by the swagger code generator",
"the icon_folder of this GetUniverseGraphicsGraphicIdOk. icon_folder string # noqa: E501 :param icon_folder: The",
"The sof_race_name of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 :rtype: str \"\"\" return self._sof_race_name",
"of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 :rtype: int \"\"\" return self._graphic_id @graphic_id.setter def",
"sof_race_name @property def sof_fation_name(self): \"\"\"Gets the sof_fation_name of this GetUniverseGraphicsGraphicIdOk. # noqa: E501",
"E501 :rtype: str \"\"\" return self._sof_hull_name @sof_hull_name.setter def sof_hull_name(self, sof_hull_name): \"\"\"Sets the sof_hull_name",
"None: self.icon_folder = icon_folder @property def graphic_id(self): \"\"\"Gets the graphic_id of this GetUniverseGraphicsGraphicIdOk.",
"of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 :type: str \"\"\" self._sof_fation_name = sof_fation_name @property",
"# noqa: E501 :type: int \"\"\" if graphic_id is None: raise ValueError(\"Invalid value",
"string # noqa: E501 :return: The sof_hull_name of this GetUniverseGraphicsGraphicIdOk. # noqa: E501",
"noqa: E501 graphic_file string # noqa: E501 :return: The graphic_file of this GetUniverseGraphicsGraphicIdOk.",
"_ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map(",
"\"\"\"Gets the sof_dna of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 sof_dna string # noqa:",
":rtype: str \"\"\" return self._sof_race_name @sof_race_name.setter def sof_race_name(self, sof_race_name): \"\"\"Sets the sof_race_name of",
"return result def to_str(self): \"\"\"Returns the string representation of the model\"\"\" return pprint.pformat(self.to_dict())",
"= None self._icon_folder = None self.discriminator = None self.graphic_id = graphic_id if graphic_file",
"E501 :type: str \"\"\" self._icon_folder = icon_folder def to_dict(self): \"\"\"Returns the model properties",
"the model\"\"\" return pprint.pformat(self.to_dict()) def __repr__(self): \"\"\"For `print` and `pprint`\"\"\" return self.to_str() def",
"def icon_folder(self, icon_folder): \"\"\"Sets the icon_folder of this GetUniverseGraphicsGraphicIdOk. icon_folder string # noqa:",
"icon_folder: The icon_folder of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 :type: str \"\"\" self._icon_folder",
"string # noqa: E501 :param collision_file: The collision_file of this GetUniverseGraphicsGraphicIdOk. # noqa:",
"\"\"\" return self._sof_dna @sof_dna.setter def sof_dna(self, sof_dna): \"\"\"Sets the sof_dna of this GetUniverseGraphicsGraphicIdOk.",
"string # noqa: E501 :param sof_hull_name: The sof_hull_name of this GetUniverseGraphicsGraphicIdOk. # noqa:",
"def graphic_file(self, graphic_file): \"\"\"Sets the graphic_file of this GetUniverseGraphicsGraphicIdOk. graphic_file string # noqa:",
"sof_hull_name of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 :type: str \"\"\" self._sof_hull_name = sof_hull_name",
"if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, \"to_dict\") else",
"sof_hull_name of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 sof_hull_name string # noqa: E501 :return:",
"of this GetUniverseGraphicsGraphicIdOk. sof_hull_name string # noqa: E501 :param sof_hull_name: The sof_hull_name of",
"# noqa: E501 :return: The collision_file of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 :rtype:",
"elif hasattr(value, \"to_dict\"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda",
"E501 :param sof_dna: The sof_dna of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 :type: str",
"value is json key in definition. \"\"\" swagger_types = { 'graphic_id': 'int', 'graphic_file':",
"not None: self.sof_dna = sof_dna if sof_hull_name is not None: self.sof_hull_name = sof_hull_name",
"The key is attribute name and the value is json key in definition.",
"\"\"\"Sets the graphic_id of this GetUniverseGraphicsGraphicIdOk. graphic_id integer # noqa: E501 :param graphic_id:",
":rtype: int \"\"\" return self._graphic_id @graphic_id.setter def graphic_id(self, graphic_id): \"\"\"Sets the graphic_id of",
"= dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], \"to_dict\") else item, value.items() ))",
"of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 collision_file string # noqa: E501 :return: The",
"E501 graphic_id integer # noqa: E501 :return: The graphic_id of this GetUniverseGraphicsGraphicIdOk. #",
"this GetUniverseGraphicsGraphicIdOk. # noqa: E501 :type: str \"\"\" self._graphic_file = graphic_file @property def",
"EVE Online # noqa: E501 OpenAPI spec version: 0.8.0 Generated by: https://github.com/swagger-api/swagger-codegen.git \"\"\"",
"result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, \"to_dict\") else x, value ))",
"= graphic_file if sof_race_name is not None: self.sof_race_name = sof_race_name if sof_fation_name is",
"= None self.graphic_id = graphic_id if graphic_file is not None: self.graphic_file = graphic_file",
"a dict\"\"\" result = {} for attr, _ in six.iteritems(self.swagger_types): value = getattr(self,",
"graphic_file of this GetUniverseGraphicsGraphicIdOk. graphic_file string # noqa: E501 :param graphic_file: The graphic_file",
"def __repr__(self): \"\"\"For `print` and `pprint`\"\"\" return self.to_str() def __eq__(self, other): \"\"\"Returns true",
"E501 :return: The graphic_file of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 :rtype: str \"\"\"",
"= sof_fation_name if sof_dna is not None: self.sof_dna = sof_dna if sof_hull_name is",
"# noqa: E501 sof_fation_name string # noqa: E501 :return: The sof_fation_name of this",
"return self._sof_hull_name @sof_hull_name.setter def sof_hull_name(self, sof_hull_name): \"\"\"Sets the sof_hull_name of this GetUniverseGraphicsGraphicIdOk. sof_hull_name",
"\"\"\" return self._collision_file @collision_file.setter def collision_file(self, collision_file): \"\"\"Sets the collision_file of this GetUniverseGraphicsGraphicIdOk.",
"sof_dna is not None: self.sof_dna = sof_dna if sof_hull_name is not None: self.sof_hull_name",
"is attribute name and the value is json key in definition. \"\"\" swagger_types",
"of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 sof_race_name string # noqa: E501 :return: The",
"not None: self.sof_fation_name = sof_fation_name if sof_dna is not None: self.sof_dna = sof_dna",
"of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 :type: str \"\"\" self._icon_folder = icon_folder def",
"# noqa: E501 :param graphic_file: The graphic_file of this GetUniverseGraphicsGraphicIdOk. # noqa: E501",
"string # noqa: E501 :param sof_dna: The sof_dna of this GetUniverseGraphicsGraphicIdOk. # noqa:",
"\"\"\" return self._graphic_file @graphic_file.setter def graphic_file(self, graphic_file): \"\"\"Sets the graphic_file of this GetUniverseGraphicsGraphicIdOk.",
"`None`\") # noqa: E501 self._graphic_id = graphic_id @property def graphic_file(self): \"\"\"Gets the graphic_file",
"def collision_file(self, collision_file): \"\"\"Sets the collision_file of this GetUniverseGraphicsGraphicIdOk. collision_file string # noqa:",
"self._sof_dna @sof_dna.setter def sof_dna(self, sof_dna): \"\"\"Sets the sof_dna of this GetUniverseGraphicsGraphicIdOk. sof_dna string",
"by: https://github.com/swagger-api/swagger-codegen.git \"\"\" import pprint import re # noqa: F401 import six class",
"sof_race_name of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 sof_race_name string # noqa: E501 :return:",
"noqa: E501 :rtype: str \"\"\" return self._sof_fation_name @sof_fation_name.setter def sof_fation_name(self, sof_fation_name): \"\"\"Sets the",
"'graphic_id': 'graphic_id', 'graphic_file': 'graphic_file', 'sof_race_name': 'sof_race_name', 'sof_fation_name': 'sof_fation_name', 'sof_dna': 'sof_dna', 'sof_hull_name': 'sof_hull_name', 'collision_file':",
"\"\"\" return self._sof_hull_name @sof_hull_name.setter def sof_hull_name(self, sof_hull_name): \"\"\"Sets the sof_hull_name of this GetUniverseGraphicsGraphicIdOk.",
"# noqa: E501 :type: str \"\"\" self._sof_race_name = sof_race_name @property def sof_fation_name(self): \"\"\"Gets",
"sof_hull_name(self, sof_hull_name): \"\"\"Sets the sof_hull_name of this GetUniverseGraphicsGraphicIdOk. sof_hull_name string # noqa: E501",
"def to_dict(self): \"\"\"Returns the model properties as a dict\"\"\" result = {} for",
"sof_race_name(self, sof_race_name): \"\"\"Sets the sof_race_name of this GetUniverseGraphicsGraphicIdOk. sof_race_name string # noqa: E501",
"\"\"\" return self._icon_folder @icon_folder.setter def icon_folder(self, icon_folder): \"\"\"Sets the icon_folder of this GetUniverseGraphicsGraphicIdOk.",
"\"\"\"Returns true if both objects are equal\"\"\" if not isinstance(other, GetUniverseGraphicsGraphicIdOk): return False",
"\"\"\"Gets the graphic_file of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 graphic_file string # noqa:",
"sof_fation_name is not None: self.sof_fation_name = sof_fation_name if sof_dna is not None: self.sof_dna",
"str \"\"\" return self._collision_file @collision_file.setter def collision_file(self, collision_file): \"\"\"Sets the collision_file of this",
"__eq__(self, other): \"\"\"Returns true if both objects are equal\"\"\" if not isinstance(other, GetUniverseGraphicsGraphicIdOk):",
"GetUniverseGraphicsGraphicIdOk. graphic_id integer # noqa: E501 :param graphic_id: The graphic_id of this GetUniverseGraphicsGraphicIdOk.",
"x: x.to_dict() if hasattr(x, \"to_dict\") else x, value )) elif hasattr(value, \"to_dict\"): result[attr]",
"lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], \"to_dict\") else item, value.items() )) else: result[attr]",
"GetUniverseGraphicsGraphicIdOk. # noqa: E501 :rtype: str \"\"\" return self._collision_file @collision_file.setter def collision_file(self, collision_file):",
"The icon_folder of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 :type: str \"\"\" self._icon_folder =",
"of the model\"\"\" return pprint.pformat(self.to_dict()) def __repr__(self): \"\"\"For `print` and `pprint`\"\"\" return self.to_str()",
"of this GetUniverseGraphicsGraphicIdOk. sof_dna string # noqa: E501 :param sof_dna: The sof_dna of",
"to_dict(self): \"\"\"Returns the model properties as a dict\"\"\" result = {} for attr,",
":return: The sof_fation_name of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 :rtype: str \"\"\" return",
"\"\"\" return self._sof_fation_name @sof_fation_name.setter def sof_fation_name(self, sof_fation_name): \"\"\"Sets the sof_fation_name of this GetUniverseGraphicsGraphicIdOk.",
"'int', 'graphic_file': 'str', 'sof_race_name': 'str', 'sof_fation_name': 'str', 'sof_dna': 'str', 'sof_hull_name': 'str', 'collision_file': 'str',",
":rtype: str \"\"\" return self._icon_folder @icon_folder.setter def icon_folder(self, icon_folder): \"\"\"Sets the icon_folder of",
"noqa: E501 :param graphic_id: The graphic_id of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 :type:",
"of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 :type: str \"\"\" self._sof_hull_name = sof_hull_name @property",
"'str', 'sof_dna': 'str', 'sof_hull_name': 'str', 'collision_file': 'str', 'icon_folder': 'str' } attribute_map = {",
"def graphic_file(self): \"\"\"Gets the graphic_file of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 graphic_file string",
"icon_folder(self): \"\"\"Gets the icon_folder of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 icon_folder string #",
"both objects are equal\"\"\" if not isinstance(other, GetUniverseGraphicsGraphicIdOk): return False return self.__dict__ ==",
"sof_dna string # noqa: E501 :return: The sof_dna of this GetUniverseGraphicsGraphicIdOk. # noqa:",
"E501 icon_folder string # noqa: E501 :return: The icon_folder of this GetUniverseGraphicsGraphicIdOk. #",
"of this GetUniverseGraphicsGraphicIdOk. icon_folder string # noqa: E501 :param icon_folder: The icon_folder of",
"noqa: E501 :type: int \"\"\" if graphic_id is None: raise ValueError(\"Invalid value for",
"import six class GetUniverseGraphicsGraphicIdOk(object): \"\"\"NOTE: This class is auto generated by the swagger",
"\"\"\"GetUniverseGraphicsGraphicIdOk - a model defined in Swagger\"\"\" # noqa: E501 self._graphic_id = None",
"integer # noqa: E501 :return: The graphic_id of this GetUniverseGraphicsGraphicIdOk. # noqa: E501",
"E501 sof_fation_name string # noqa: E501 :return: The sof_fation_name of this GetUniverseGraphicsGraphicIdOk. #",
"x, value )) elif hasattr(value, \"to_dict\"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr]",
"GetUniverseGraphicsGraphicIdOk. # noqa: E501 sof_dna string # noqa: E501 :return: The sof_dna of",
"sof_hull_name: The sof_hull_name of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 :type: str \"\"\" self._sof_hull_name",
"and the value is attribute type. attribute_map (dict): The key is attribute name",
"graphic_id of this GetUniverseGraphicsGraphicIdOk. graphic_id integer # noqa: E501 :param graphic_id: The graphic_id",
"E501 :rtype: int \"\"\" return self._graphic_id @graphic_id.setter def graphic_id(self, graphic_id): \"\"\"Sets the graphic_id",
"sof_race_name of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 :rtype: str \"\"\" return self._sof_race_name @sof_race_name.setter",
"# coding: utf-8 \"\"\" EVE Swagger Interface An OpenAPI for EVE Online #",
"graphic_id if graphic_file is not None: self.graphic_file = graphic_file if sof_race_name is not",
"in definition. \"\"\" swagger_types = { 'graphic_id': 'int', 'graphic_file': 'str', 'sof_race_name': 'str', 'sof_fation_name':",
"of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 :rtype: str \"\"\" return self._icon_folder @icon_folder.setter def",
"string # noqa: E501 :param sof_fation_name: The sof_fation_name of this GetUniverseGraphicsGraphicIdOk. # noqa:",
"= getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if",
"GetUniverseGraphicsGraphicIdOk. # noqa: E501 :rtype: str \"\"\" return self._sof_race_name @sof_race_name.setter def sof_race_name(self, sof_race_name):",
"E501 :param collision_file: The collision_file of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 :type: str",
"graphic_id of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 :type: int \"\"\" if graphic_id is",
"\"\"\"For `print` and `pprint`\"\"\" return self.to_str() def __eq__(self, other): \"\"\"Returns true if both",
"# noqa: E501 graphic_file string # noqa: E501 :return: The graphic_file of this",
"sof_hull_name of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 :rtype: str \"\"\" return self._sof_hull_name @sof_hull_name.setter",
"\"\"\" if graphic_id is None: raise ValueError(\"Invalid value for `graphic_id`, must not be",
"The sof_dna of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 :type: str \"\"\" self._sof_dna =",
"E501 self._graphic_id = None self._graphic_file = None self._sof_race_name = None self._sof_fation_name = None",
"of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 :rtype: str \"\"\" return self._sof_hull_name @sof_hull_name.setter def",
"objects are equal\"\"\" if not isinstance(other, GetUniverseGraphicsGraphicIdOk): return False return self.__dict__ == other.__dict__",
"self._icon_folder = icon_folder def to_dict(self): \"\"\"Returns the model properties as a dict\"\"\" result",
"'graphic_file': 'graphic_file', 'sof_race_name': 'sof_race_name', 'sof_fation_name': 'sof_fation_name', 'sof_dna': 'sof_dna', 'sof_hull_name': 'sof_hull_name', 'collision_file': 'collision_file', 'icon_folder':",
"icon_folder is not None: self.icon_folder = icon_folder @property def graphic_id(self): \"\"\"Gets the graphic_id",
"str \"\"\" return self._graphic_file @graphic_file.setter def graphic_file(self, graphic_file): \"\"\"Sets the graphic_file of this",
"'sof_fation_name': 'str', 'sof_dna': 'str', 'sof_hull_name': 'str', 'collision_file': 'str', 'icon_folder': 'str' } attribute_map =",
"@property def sof_dna(self): \"\"\"Gets the sof_dna of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 sof_dna",
"dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], \"to_dict\") else item,",
"of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 :rtype: str \"\"\" return self._sof_dna @sof_dna.setter def",
"GetUniverseGraphicsGraphicIdOk. # noqa: E501 collision_file string # noqa: E501 :return: The collision_file of",
"noqa: E501 icon_folder string # noqa: E501 :return: The icon_folder of this GetUniverseGraphicsGraphicIdOk.",
"key is attribute name and the value is attribute type. attribute_map (dict): The",
"self._sof_hull_name @sof_hull_name.setter def sof_hull_name(self, sof_hull_name): \"\"\"Sets the sof_hull_name of this GetUniverseGraphicsGraphicIdOk. sof_hull_name string",
"the value is json key in definition. \"\"\" swagger_types = { 'graphic_id': 'int',",
"not None: self.icon_folder = icon_folder @property def graphic_id(self): \"\"\"Gets the graphic_id of this",
"is attribute name and the value is attribute type. attribute_map (dict): The key",
"by the swagger code generator program. Do not edit the class manually. \"\"\"",
"self._graphic_id = None self._graphic_file = None self._sof_race_name = None self._sof_fation_name = None self._sof_dna",
"def graphic_id(self): \"\"\"Gets the graphic_id of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 graphic_id integer",
"str \"\"\" self._sof_fation_name = sof_fation_name @property def sof_dna(self): \"\"\"Gets the sof_dna of this",
"manually. \"\"\" \"\"\" Attributes: swagger_types (dict): The key is attribute name and the",
"None: self.sof_hull_name = sof_hull_name if collision_file is not None: self.collision_file = collision_file if",
"= graphic_file @property def sof_race_name(self): \"\"\"Gets the sof_race_name of this GetUniverseGraphicsGraphicIdOk. # noqa:",
"noqa: E501 \"\"\"GetUniverseGraphicsGraphicIdOk - a model defined in Swagger\"\"\" # noqa: E501 self._graphic_id",
"E501 :param sof_hull_name: The sof_hull_name of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 :type: str",
"# noqa: E501 :param collision_file: The collision_file of this GetUniverseGraphicsGraphicIdOk. # noqa: E501",
"graphic_file(self): \"\"\"Gets the graphic_file of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 graphic_file string #",
"noqa: E501 :type: str \"\"\" self._collision_file = collision_file @property def icon_folder(self): \"\"\"Gets the",
"icon_folder string # noqa: E501 :param icon_folder: The icon_folder of this GetUniverseGraphicsGraphicIdOk. #",
"result[attr] = value return result def to_str(self): \"\"\"Returns the string representation of the",
"def to_str(self): \"\"\"Returns the string representation of the model\"\"\" return pprint.pformat(self.to_dict()) def __repr__(self):",
"return self.to_str() def __eq__(self, other): \"\"\"Returns true if both objects are equal\"\"\" if",
"item: (item[0], item[1].to_dict()) if hasattr(item[1], \"to_dict\") else item, value.items() )) else: result[attr] =",
":param collision_file: The collision_file of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 :type: str \"\"\"",
"str \"\"\" self._icon_folder = icon_folder def to_dict(self): \"\"\"Returns the model properties as a",
":return: The sof_hull_name of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 :rtype: str \"\"\" return",
"this GetUniverseGraphicsGraphicIdOk. # noqa: E501 :type: str \"\"\" self._sof_dna = sof_dna @property def",
"of this GetUniverseGraphicsGraphicIdOk. graphic_id integer # noqa: E501 :param graphic_id: The graphic_id of",
"self._sof_race_name = sof_race_name @property def sof_fation_name(self): \"\"\"Gets the sof_fation_name of this GetUniverseGraphicsGraphicIdOk. #",
"item[1].to_dict()) if hasattr(item[1], \"to_dict\") else item, value.items() )) else: result[attr] = value return",
"'sof_fation_name', 'sof_dna': 'sof_dna', 'sof_hull_name': 'sof_hull_name', 'collision_file': 'collision_file', 'icon_folder': 'icon_folder' } def __init__(self, graphic_id=None,",
"self.sof_fation_name = sof_fation_name if sof_dna is not None: self.sof_dna = sof_dna if sof_hull_name",
"noqa: E501 sof_dna string # noqa: E501 :return: The sof_dna of this GetUniverseGraphicsGraphicIdOk.",
"GetUniverseGraphicsGraphicIdOk): return False return self.__dict__ == other.__dict__ def __ne__(self, other): \"\"\"Returns true if",
"return False return self.__dict__ == other.__dict__ def __ne__(self, other): \"\"\"Returns true if both",
":type: str \"\"\" self._graphic_file = graphic_file @property def sof_race_name(self): \"\"\"Gets the sof_race_name of",
"this GetUniverseGraphicsGraphicIdOk. sof_fation_name string # noqa: E501 :param sof_fation_name: The sof_fation_name of this",
"self._graphic_id = graphic_id @property def graphic_file(self): \"\"\"Gets the graphic_file of this GetUniverseGraphicsGraphicIdOk. #",
"# noqa: E501 OpenAPI spec version: 0.8.0 Generated by: https://github.com/swagger-api/swagger-codegen.git \"\"\" import pprint",
"string # noqa: E501 :return: The sof_dna of this GetUniverseGraphicsGraphicIdOk. # noqa: E501",
"E501 collision_file string # noqa: E501 :return: The collision_file of this GetUniverseGraphicsGraphicIdOk. #",
"if sof_fation_name is not None: self.sof_fation_name = sof_fation_name if sof_dna is not None:",
"GetUniverseGraphicsGraphicIdOk. # noqa: E501 :type: str \"\"\" self._sof_hull_name = sof_hull_name @property def collision_file(self):",
"graphic_id: The graphic_id of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 :type: int \"\"\" if",
"this GetUniverseGraphicsGraphicIdOk. # noqa: E501 collision_file string # noqa: E501 :return: The collision_file",
"sof_fation_name(self): \"\"\"Gets the sof_fation_name of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 sof_fation_name string #",
"sof_race_name=None, sof_fation_name=None, sof_dna=None, sof_hull_name=None, collision_file=None, icon_folder=None): # noqa: E501 \"\"\"GetUniverseGraphicsGraphicIdOk - a model",
":type: str \"\"\" self._sof_race_name = sof_race_name @property def sof_fation_name(self): \"\"\"Gets the sof_fation_name of",
"E501 :rtype: str \"\"\" return self._icon_folder @icon_folder.setter def icon_folder(self, icon_folder): \"\"\"Sets the icon_folder",
"\"\"\" swagger_types = { 'graphic_id': 'int', 'graphic_file': 'str', 'sof_race_name': 'str', 'sof_fation_name': 'str', 'sof_dna':",
"self._icon_folder @icon_folder.setter def icon_folder(self, icon_folder): \"\"\"Sets the icon_folder of this GetUniverseGraphicsGraphicIdOk. icon_folder string",
"sof_race_name: The sof_race_name of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 :type: str \"\"\" self._sof_race_name",
"icon_folder=None): # noqa: E501 \"\"\"GetUniverseGraphicsGraphicIdOk - a model defined in Swagger\"\"\" # noqa:",
"sof_hull_name is not None: self.sof_hull_name = sof_hull_name if collision_file is not None: self.collision_file",
"noqa: E501 :return: The icon_folder of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 :rtype: str",
"@property def graphic_id(self): \"\"\"Gets the graphic_id of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 graphic_id",
"this GetUniverseGraphicsGraphicIdOk. sof_hull_name string # noqa: E501 :param sof_hull_name: The sof_hull_name of this",
"= graphic_id @property def graphic_file(self): \"\"\"Gets the graphic_file of this GetUniverseGraphicsGraphicIdOk. # noqa:",
"E501 :type: str \"\"\" self._graphic_file = graphic_file @property def sof_race_name(self): \"\"\"Gets the sof_race_name",
"E501 :return: The sof_fation_name of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 :rtype: str \"\"\"",
"'graphic_id', 'graphic_file': 'graphic_file', 'sof_race_name': 'sof_race_name', 'sof_fation_name': 'sof_fation_name', 'sof_dna': 'sof_dna', 'sof_hull_name': 'sof_hull_name', 'collision_file': 'collision_file',",
"'str', 'sof_race_name': 'str', 'sof_fation_name': 'str', 'sof_dna': 'str', 'sof_hull_name': 'str', 'collision_file': 'str', 'icon_folder': 'str'",
"= value return result def to_str(self): \"\"\"Returns the string representation of the model\"\"\"",
"not be `None`\") # noqa: E501 self._graphic_id = graphic_id @property def graphic_file(self): \"\"\"Gets",
"this GetUniverseGraphicsGraphicIdOk. # noqa: E501 sof_hull_name string # noqa: E501 :return: The sof_hull_name",
"E501 :return: The sof_dna of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 :rtype: str \"\"\"",
"# noqa: E501 :return: The sof_dna of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 :rtype:",
"result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict())",
"else x, value )) elif hasattr(value, \"to_dict\"): result[attr] = value.to_dict() elif isinstance(value, dict):",
"E501 :return: The sof_hull_name of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 :rtype: str \"\"\"",
"= None self._sof_race_name = None self._sof_fation_name = None self._sof_dna = None self._sof_hull_name =",
"\"\"\"Sets the sof_fation_name of this GetUniverseGraphicsGraphicIdOk. sof_fation_name string # noqa: E501 :param sof_fation_name:",
":param graphic_id: The graphic_id of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 :type: int \"\"\"",
"not edit the class manually. \"\"\" \"\"\" Attributes: swagger_types (dict): The key is",
"utf-8 \"\"\" EVE Swagger Interface An OpenAPI for EVE Online # noqa: E501",
"is None: raise ValueError(\"Invalid value for `graphic_id`, must not be `None`\") # noqa:",
"E501 :type: str \"\"\" self._sof_fation_name = sof_fation_name @property def sof_dna(self): \"\"\"Gets the sof_dna",
"def sof_fation_name(self): \"\"\"Gets the sof_fation_name of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 sof_fation_name string",
"# noqa: E501 :type: str \"\"\" self._icon_folder = icon_folder def to_dict(self): \"\"\"Returns the",
"E501 :type: str \"\"\" self._sof_dna = sof_dna @property def sof_hull_name(self): \"\"\"Gets the sof_hull_name",
"coding: utf-8 \"\"\" EVE Swagger Interface An OpenAPI for EVE Online # noqa:",
"None: self.sof_fation_name = sof_fation_name if sof_dna is not None: self.sof_dna = sof_dna if",
"noqa: E501 :type: str \"\"\" self._sof_dna = sof_dna @property def sof_hull_name(self): \"\"\"Gets the",
"graphic_file: The graphic_file of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 :type: str \"\"\" self._graphic_file",
"@collision_file.setter def collision_file(self, collision_file): \"\"\"Sets the collision_file of this GetUniverseGraphicsGraphicIdOk. collision_file string #",
"code generator program. Do not edit the class manually. \"\"\" \"\"\" Attributes: swagger_types",
"\"\"\" self._collision_file = collision_file @property def icon_folder(self): \"\"\"Gets the icon_folder of this GetUniverseGraphicsGraphicIdOk.",
"GetUniverseGraphicsGraphicIdOk. # noqa: E501 graphic_file string # noqa: E501 :return: The graphic_file of",
"# noqa: E501 :type: str \"\"\" self._sof_hull_name = sof_hull_name @property def collision_file(self): \"\"\"Gets",
"of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 :rtype: str \"\"\" return self._sof_fation_name @sof_fation_name.setter def",
"ValueError(\"Invalid value for `graphic_id`, must not be `None`\") # noqa: E501 self._graphic_id =",
"collision_file string # noqa: E501 :return: The collision_file of this GetUniverseGraphicsGraphicIdOk. # noqa:",
"graphic_file): \"\"\"Sets the graphic_file of this GetUniverseGraphicsGraphicIdOk. graphic_file string # noqa: E501 :param",
"noqa: E501 :param sof_race_name: The sof_race_name of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 :type:",
"attribute_map (dict): The key is attribute name and the value is json key",
"noqa: E501 collision_file string # noqa: E501 :return: The collision_file of this GetUniverseGraphicsGraphicIdOk.",
"OpenAPI for EVE Online # noqa: E501 OpenAPI spec version: 0.8.0 Generated by:",
"defined in Swagger\"\"\" # noqa: E501 self._graphic_id = None self._graphic_file = None self._sof_race_name",
"is not None: self.sof_race_name = sof_race_name if sof_fation_name is not None: self.sof_fation_name =",
"noqa: E501 :rtype: str \"\"\" return self._sof_dna @sof_dna.setter def sof_dna(self, sof_dna): \"\"\"Sets the",
"# noqa: E501 graphic_id integer # noqa: E501 :return: The graphic_id of this",
"the sof_dna of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 sof_dna string # noqa: E501",
"type. attribute_map (dict): The key is attribute name and the value is json",
":param sof_dna: The sof_dna of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 :type: str \"\"\"",
"E501 :rtype: str \"\"\" return self._collision_file @collision_file.setter def collision_file(self, collision_file): \"\"\"Sets the collision_file",
"\"\"\"Gets the collision_file of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 collision_file string # noqa:",
"graphic_file of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 :type: str \"\"\" self._graphic_file = graphic_file",
"'icon_folder': 'icon_folder' } def __init__(self, graphic_id=None, graphic_file=None, sof_race_name=None, sof_fation_name=None, sof_dna=None, sof_hull_name=None, collision_file=None, icon_folder=None):",
"sof_hull_name): \"\"\"Sets the sof_hull_name of this GetUniverseGraphicsGraphicIdOk. sof_hull_name string # noqa: E501 :param",
"sof_hull_name of this GetUniverseGraphicsGraphicIdOk. sof_hull_name string # noqa: E501 :param sof_hull_name: The sof_hull_name",
"The collision_file of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 :type: str \"\"\" self._collision_file =",
"@property def sof_fation_name(self): \"\"\"Gets the sof_fation_name of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 sof_fation_name",
"# noqa: E501 :rtype: str \"\"\" return self._sof_hull_name @sof_hull_name.setter def sof_hull_name(self, sof_hull_name): \"\"\"Sets",
"= None self._sof_dna = None self._sof_hull_name = None self._collision_file = None self._icon_folder =",
"the sof_fation_name of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 sof_fation_name string # noqa: E501",
"this GetUniverseGraphicsGraphicIdOk. # noqa: E501 sof_race_name string # noqa: E501 :return: The sof_race_name",
"@icon_folder.setter def icon_folder(self, icon_folder): \"\"\"Sets the icon_folder of this GetUniverseGraphicsGraphicIdOk. icon_folder string #",
"self._collision_file = None self._icon_folder = None self.discriminator = None self.graphic_id = graphic_id if",
"sof_race_name(self): \"\"\"Gets the sof_race_name of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 sof_race_name string #",
"this GetUniverseGraphicsGraphicIdOk. # noqa: E501 :type: str \"\"\" self._sof_hull_name = sof_hull_name @property def",
"'str', 'sof_fation_name': 'str', 'sof_dna': 'str', 'sof_hull_name': 'str', 'collision_file': 'str', 'icon_folder': 'str' } attribute_map",
"'str', 'sof_hull_name': 'str', 'collision_file': 'str', 'icon_folder': 'str' } attribute_map = { 'graphic_id': 'graphic_id',",
"# noqa: E501 :rtype: str \"\"\" return self._graphic_file @graphic_file.setter def graphic_file(self, graphic_file): \"\"\"Sets",
"str \"\"\" return self._sof_dna @sof_dna.setter def sof_dna(self, sof_dna): \"\"\"Sets the sof_dna of this",
"this GetUniverseGraphicsGraphicIdOk. # noqa: E501 graphic_file string # noqa: E501 :return: The graphic_file",
")) elif hasattr(value, \"to_dict\"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map(",
"- a model defined in Swagger\"\"\" # noqa: E501 self._graphic_id = None self._graphic_file",
"\"\"\" self._sof_fation_name = sof_fation_name @property def sof_dna(self): \"\"\"Gets the sof_dna of this GetUniverseGraphicsGraphicIdOk.",
"icon_folder @property def graphic_id(self): \"\"\"Gets the graphic_id of this GetUniverseGraphicsGraphicIdOk. # noqa: E501",
"noqa: E501 :param sof_fation_name: The sof_fation_name of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 :type:",
"six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x:",
"# noqa: E501 :type: str \"\"\" self._collision_file = collision_file @property def icon_folder(self): \"\"\"Gets",
"GetUniverseGraphicsGraphicIdOk. # noqa: E501 graphic_id integer # noqa: E501 :return: The graphic_id of",
"noqa: E501 :rtype: str \"\"\" return self._graphic_file @graphic_file.setter def graphic_file(self, graphic_file): \"\"\"Sets the",
"graphic_file @property def sof_race_name(self): \"\"\"Gets the sof_race_name of this GetUniverseGraphicsGraphicIdOk. # noqa: E501",
"the collision_file of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 collision_file string # noqa: E501",
"generated by the swagger code generator program. Do not edit the class manually.",
"collision_file if icon_folder is not None: self.icon_folder = icon_folder @property def graphic_id(self): \"\"\"Gets",
"\"\"\" return self._graphic_id @graphic_id.setter def graphic_id(self, graphic_id): \"\"\"Sets the graphic_id of this GetUniverseGraphicsGraphicIdOk.",
"E501 :param graphic_file: The graphic_file of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 :type: str",
"noqa: E501 sof_fation_name string # noqa: E501 :return: The sof_fation_name of this GetUniverseGraphicsGraphicIdOk.",
"sof_dna of this GetUniverseGraphicsGraphicIdOk. sof_dna string # noqa: E501 :param sof_dna: The sof_dna",
"GetUniverseGraphicsGraphicIdOk. # noqa: E501 :type: str \"\"\" self._sof_fation_name = sof_fation_name @property def sof_dna(self):",
"\"\"\"Sets the graphic_file of this GetUniverseGraphicsGraphicIdOk. graphic_file string # noqa: E501 :param graphic_file:",
"the graphic_file of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 graphic_file string # noqa: E501",
"OpenAPI spec version: 0.8.0 Generated by: https://github.com/swagger-api/swagger-codegen.git \"\"\" import pprint import re #",
"string # noqa: E501 :return: The sof_race_name of this GetUniverseGraphicsGraphicIdOk. # noqa: E501",
"= icon_folder def to_dict(self): \"\"\"Returns the model properties as a dict\"\"\" result =",
"name and the value is json key in definition. \"\"\" swagger_types = {",
"sof_hull_name if collision_file is not None: self.collision_file = collision_file if icon_folder is not",
"string # noqa: E501 :param icon_folder: The icon_folder of this GetUniverseGraphicsGraphicIdOk. # noqa:",
"E501 :param graphic_id: The graphic_id of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 :type: int",
"noqa: E501 :type: str \"\"\" self._sof_race_name = sof_race_name @property def sof_fation_name(self): \"\"\"Gets the",
"None self._collision_file = None self._icon_folder = None self.discriminator = None self.graphic_id = graphic_id",
"= None self._sof_hull_name = None self._collision_file = None self._icon_folder = None self.discriminator =",
"this GetUniverseGraphicsGraphicIdOk. # noqa: E501 graphic_id integer # noqa: E501 :return: The graphic_id",
"E501 :param sof_race_name: The sof_race_name of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 :type: str",
"(dict): The key is attribute name and the value is json key in",
"key in definition. \"\"\" swagger_types = { 'graphic_id': 'int', 'graphic_file': 'str', 'sof_race_name': 'str',",
"value.items() )) else: result[attr] = value return result def to_str(self): \"\"\"Returns the string",
"None: self.collision_file = collision_file if icon_folder is not None: self.icon_folder = icon_folder @property",
"# noqa: E501 :return: The graphic_id of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 :rtype:",
"sof_race_name of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 :type: str \"\"\" self._sof_race_name = sof_race_name",
"not None: self.graphic_file = graphic_file if sof_race_name is not None: self.sof_race_name = sof_race_name",
"= None self._graphic_file = None self._sof_race_name = None self._sof_fation_name = None self._sof_dna =",
"# noqa: E501 sof_dna string # noqa: E501 :return: The sof_dna of this",
"graphic_id(self): \"\"\"Gets the graphic_id of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 graphic_id integer #",
"'sof_dna': 'sof_dna', 'sof_hull_name': 'sof_hull_name', 'collision_file': 'collision_file', 'icon_folder': 'icon_folder' } def __init__(self, graphic_id=None, graphic_file=None,",
"__init__(self, graphic_id=None, graphic_file=None, sof_race_name=None, sof_fation_name=None, sof_dna=None, sof_hull_name=None, collision_file=None, icon_folder=None): # noqa: E501 \"\"\"GetUniverseGraphicsGraphicIdOk",
":param sof_race_name: The sof_race_name of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 :type: str \"\"\"",
"# noqa: E501 icon_folder string # noqa: E501 :return: The icon_folder of this",
"\"\"\"Sets the sof_hull_name of this GetUniverseGraphicsGraphicIdOk. sof_hull_name string # noqa: E501 :param sof_hull_name:",
"name and the value is attribute type. attribute_map (dict): The key is attribute",
"# noqa: E501 :return: The sof_race_name of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 :rtype:",
"noqa: E501 :param graphic_file: The graphic_file of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 :type:",
"collision_file of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 collision_file string # noqa: E501 :return:",
"collision_file string # noqa: E501 :param collision_file: The collision_file of this GetUniverseGraphicsGraphicIdOk. #",
"GetUniverseGraphicsGraphicIdOk. # noqa: E501 :rtype: str \"\"\" return self._sof_dna @sof_dna.setter def sof_dna(self, sof_dna):",
"sof_fation_name(self, sof_fation_name): \"\"\"Sets the sof_fation_name of this GetUniverseGraphicsGraphicIdOk. sof_fation_name string # noqa: E501",
"E501 :rtype: str \"\"\" return self._graphic_file @graphic_file.setter def graphic_file(self, graphic_file): \"\"\"Sets the graphic_file",
"= sof_dna @property def sof_hull_name(self): \"\"\"Gets the sof_hull_name of this GetUniverseGraphicsGraphicIdOk. # noqa:",
":return: The icon_folder of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 :rtype: str \"\"\" return",
"the graphic_id of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 graphic_id integer # noqa: E501",
"def sof_hull_name(self, sof_hull_name): \"\"\"Sets the sof_hull_name of this GetUniverseGraphicsGraphicIdOk. sof_hull_name string # noqa:",
"GetUniverseGraphicsGraphicIdOk. # noqa: E501 :type: str \"\"\" self._icon_folder = icon_folder def to_dict(self): \"\"\"Returns",
")) else: result[attr] = value return result def to_str(self): \"\"\"Returns the string representation",
"collision_file is not None: self.collision_file = collision_file if icon_folder is not None: self.icon_folder",
"GetUniverseGraphicsGraphicIdOk. # noqa: E501 :type: int \"\"\" if graphic_id is None: raise ValueError(\"Invalid",
"The sof_race_name of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 :type: str \"\"\" self._sof_race_name =",
"this GetUniverseGraphicsGraphicIdOk. # noqa: E501 :rtype: str \"\"\" return self._icon_folder @icon_folder.setter def icon_folder(self,",
"\"\"\"Returns the model properties as a dict\"\"\" result = {} for attr, _",
"attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] =",
"return pprint.pformat(self.to_dict()) def __repr__(self): \"\"\"For `print` and `pprint`\"\"\" return self.to_str() def __eq__(self, other):",
"This class is auto generated by the swagger code generator program. Do not",
"def sof_dna(self): \"\"\"Gets the sof_dna of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 sof_dna string",
"'graphic_file', 'sof_race_name': 'sof_race_name', 'sof_fation_name': 'sof_fation_name', 'sof_dna': 'sof_dna', 'sof_hull_name': 'sof_hull_name', 'collision_file': 'collision_file', 'icon_folder': 'icon_folder'",
"noqa: F401 import six class GetUniverseGraphicsGraphicIdOk(object): \"\"\"NOTE: This class is auto generated by",
"string # noqa: E501 :return: The graphic_file of this GetUniverseGraphicsGraphicIdOk. # noqa: E501",
"graphic_file if sof_race_name is not None: self.sof_race_name = sof_race_name if sof_fation_name is not",
"of this GetUniverseGraphicsGraphicIdOk. graphic_file string # noqa: E501 :param graphic_file: The graphic_file of",
"this GetUniverseGraphicsGraphicIdOk. # noqa: E501 :rtype: str \"\"\" return self._collision_file @collision_file.setter def collision_file(self,",
"graphic_id integer # noqa: E501 :param graphic_id: The graphic_id of this GetUniverseGraphicsGraphicIdOk. #",
"# noqa: E501 :type: str \"\"\" self._graphic_file = graphic_file @property def sof_race_name(self): \"\"\"Gets",
"# noqa: E501 :type: str \"\"\" self._sof_dna = sof_dna @property def sof_hull_name(self): \"\"\"Gets",
"def sof_hull_name(self): \"\"\"Gets the sof_hull_name of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 sof_hull_name string",
"# noqa: E501 collision_file string # noqa: E501 :return: The collision_file of this",
"class is auto generated by the swagger code generator program. Do not edit",
"the class manually. \"\"\" \"\"\" Attributes: swagger_types (dict): The key is attribute name",
"'sof_dna': 'str', 'sof_hull_name': 'str', 'collision_file': 'str', 'icon_folder': 'str' } attribute_map = { 'graphic_id':",
"sof_fation_name: The sof_fation_name of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 :type: str \"\"\" self._sof_fation_name",
"GetUniverseGraphicsGraphicIdOk. sof_dna string # noqa: E501 :param sof_dna: The sof_dna of this GetUniverseGraphicsGraphicIdOk.",
"noqa: E501 :rtype: str \"\"\" return self._collision_file @collision_file.setter def collision_file(self, collision_file): \"\"\"Sets the",
"`pprint`\"\"\" return self.to_str() def __eq__(self, other): \"\"\"Returns true if both objects are equal\"\"\"",
"# noqa: E501 :return: The graphic_file of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 :rtype:",
":type: str \"\"\" self._collision_file = collision_file @property def icon_folder(self): \"\"\"Gets the icon_folder of",
"dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], \"to_dict\") else item, value.items() )) else:",
"noqa: E501 graphic_id integer # noqa: E501 :return: The graphic_id of this GetUniverseGraphicsGraphicIdOk.",
"def __eq__(self, other): \"\"\"Returns true if both objects are equal\"\"\" if not isinstance(other,",
"json key in definition. \"\"\" swagger_types = { 'graphic_id': 'int', 'graphic_file': 'str', 'sof_race_name':",
"@sof_race_name.setter def sof_race_name(self, sof_race_name): \"\"\"Sets the sof_race_name of this GetUniverseGraphicsGraphicIdOk. sof_race_name string #",
"str \"\"\" return self._icon_folder @icon_folder.setter def icon_folder(self, icon_folder): \"\"\"Sets the icon_folder of this",
"'icon_folder' } def __init__(self, graphic_id=None, graphic_file=None, sof_race_name=None, sof_fation_name=None, sof_dna=None, sof_hull_name=None, collision_file=None, icon_folder=None): #",
":param graphic_file: The graphic_file of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 :type: str \"\"\"",
"self._sof_dna = None self._sof_hull_name = None self._collision_file = None self._icon_folder = None self.discriminator",
"class manually. \"\"\" \"\"\" Attributes: swagger_types (dict): The key is attribute name and",
"def __ne__(self, other): \"\"\"Returns true if both objects are not equal\"\"\" return not",
"sof_fation_name string # noqa: E501 :param sof_fation_name: The sof_fation_name of this GetUniverseGraphicsGraphicIdOk. #",
"def collision_file(self): \"\"\"Gets the collision_file of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 collision_file string",
"'sof_race_name', 'sof_fation_name': 'sof_fation_name', 'sof_dna': 'sof_dna', 'sof_hull_name': 'sof_hull_name', 'collision_file': 'collision_file', 'icon_folder': 'icon_folder' } def",
"GetUniverseGraphicsGraphicIdOk. sof_hull_name string # noqa: E501 :param sof_hull_name: The sof_hull_name of this GetUniverseGraphicsGraphicIdOk.",
"of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 :rtype: str \"\"\" return self._collision_file @collision_file.setter def",
"E501 :type: int \"\"\" if graphic_id is None: raise ValueError(\"Invalid value for `graphic_id`,",
"graphic_id(self, graphic_id): \"\"\"Sets the graphic_id of this GetUniverseGraphicsGraphicIdOk. graphic_id integer # noqa: E501",
"for `graphic_id`, must not be `None`\") # noqa: E501 self._graphic_id = graphic_id @property",
"\"\"\"Sets the collision_file of this GetUniverseGraphicsGraphicIdOk. collision_file string # noqa: E501 :param collision_file:",
"isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], \"to_dict\") else",
"edit the class manually. \"\"\" \"\"\" Attributes: swagger_types (dict): The key is attribute",
"sof_fation_name=None, sof_dna=None, sof_hull_name=None, collision_file=None, icon_folder=None): # noqa: E501 \"\"\"GetUniverseGraphicsGraphicIdOk - a model defined",
"# noqa: E501 :param sof_fation_name: The sof_fation_name of this GetUniverseGraphicsGraphicIdOk. # noqa: E501",
"this GetUniverseGraphicsGraphicIdOk. # noqa: E501 :rtype: str \"\"\" return self._sof_fation_name @sof_fation_name.setter def sof_fation_name(self,",
"'collision_file': 'str', 'icon_folder': 'str' } attribute_map = { 'graphic_id': 'graphic_id', 'graphic_file': 'graphic_file', 'sof_race_name':",
"of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 sof_dna string # noqa: E501 :return: The",
"GetUniverseGraphicsGraphicIdOk(object): \"\"\"NOTE: This class is auto generated by the swagger code generator program.",
"is not None: self.collision_file = collision_file if icon_folder is not None: self.icon_folder =",
"None: self.graphic_file = graphic_file if sof_race_name is not None: self.sof_race_name = sof_race_name if",
"self.sof_hull_name = sof_hull_name if collision_file is not None: self.collision_file = collision_file if icon_folder",
"} def __init__(self, graphic_id=None, graphic_file=None, sof_race_name=None, sof_fation_name=None, sof_dna=None, sof_hull_name=None, collision_file=None, icon_folder=None): # noqa:",
"'sof_hull_name', 'collision_file': 'collision_file', 'icon_folder': 'icon_folder' } def __init__(self, graphic_id=None, graphic_file=None, sof_race_name=None, sof_fation_name=None, sof_dna=None,",
"GetUniverseGraphicsGraphicIdOk. # noqa: E501 :type: str \"\"\" self._sof_race_name = sof_race_name @property def sof_fation_name(self):",
"in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda",
"attribute name and the value is json key in definition. \"\"\" swagger_types =",
"sof_hull_name string # noqa: E501 :return: The sof_hull_name of this GetUniverseGraphicsGraphicIdOk. # noqa:",
"this GetUniverseGraphicsGraphicIdOk. # noqa: E501 :rtype: str \"\"\" return self._sof_race_name @sof_race_name.setter def sof_race_name(self,",
":param sof_hull_name: The sof_hull_name of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 :type: str \"\"\"",
"self._sof_race_name = None self._sof_fation_name = None self._sof_dna = None self._sof_hull_name = None self._collision_file",
"noqa: E501 :return: The graphic_id of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 :rtype: int",
"swagger code generator program. Do not edit the class manually. \"\"\" \"\"\" Attributes:",
"graphic_id of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 :rtype: int \"\"\" return self._graphic_id @graphic_id.setter",
"self.discriminator = None self.graphic_id = graphic_id if graphic_file is not None: self.graphic_file =",
":return: The sof_race_name of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 :rtype: str \"\"\" return",
"the sof_hull_name of this GetUniverseGraphicsGraphicIdOk. sof_hull_name string # noqa: E501 :param sof_hull_name: The",
"GetUniverseGraphicsGraphicIdOk. # noqa: E501 sof_fation_name string # noqa: E501 :return: The sof_fation_name of",
"graphic_file string # noqa: E501 :param graphic_file: The graphic_file of this GetUniverseGraphicsGraphicIdOk. #",
"isinstance(other, GetUniverseGraphicsGraphicIdOk): return False return self.__dict__ == other.__dict__ def __ne__(self, other): \"\"\"Returns true",
"noqa: E501 :return: The collision_file of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 :rtype: str",
"\"to_dict\") else x, value )) elif hasattr(value, \"to_dict\"): result[attr] = value.to_dict() elif isinstance(value,",
"The graphic_id of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 :rtype: int \"\"\" return self._graphic_id",
":type: str \"\"\" self._sof_dna = sof_dna @property def sof_hull_name(self): \"\"\"Gets the sof_hull_name of",
"this GetUniverseGraphicsGraphicIdOk. # noqa: E501 icon_folder string # noqa: E501 :return: The icon_folder",
"'sof_race_name': 'str', 'sof_fation_name': 'str', 'sof_dna': 'str', 'sof_hull_name': 'str', 'collision_file': 'str', 'icon_folder': 'str' }",
"= None self._collision_file = None self._icon_folder = None self.discriminator = None self.graphic_id =",
"this GetUniverseGraphicsGraphicIdOk. sof_dna string # noqa: E501 :param sof_dna: The sof_dna of this",
"\"\"\"Gets the sof_hull_name of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 sof_hull_name string # noqa:",
"the graphic_id of this GetUniverseGraphicsGraphicIdOk. graphic_id integer # noqa: E501 :param graphic_id: The",
"= None self.discriminator = None self.graphic_id = graphic_id if graphic_file is not None:",
"noqa: E501 sof_hull_name string # noqa: E501 :return: The sof_hull_name of this GetUniverseGraphicsGraphicIdOk.",
"sof_hull_name string # noqa: E501 :param sof_hull_name: The sof_hull_name of this GetUniverseGraphicsGraphicIdOk. #",
"@property def collision_file(self): \"\"\"Gets the collision_file of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 collision_file",
"the swagger code generator program. Do not edit the class manually. \"\"\" \"\"\"",
"if sof_race_name is not None: self.sof_race_name = sof_race_name if sof_fation_name is not None:",
"def __init__(self, graphic_id=None, graphic_file=None, sof_race_name=None, sof_fation_name=None, sof_dna=None, sof_hull_name=None, collision_file=None, icon_folder=None): # noqa: E501",
"GetUniverseGraphicsGraphicIdOk. # noqa: E501 :rtype: int \"\"\" return self._graphic_id @graphic_id.setter def graphic_id(self, graphic_id):",
"\"\"\" self._icon_folder = icon_folder def to_dict(self): \"\"\"Returns the model properties as a dict\"\"\"",
"E501 :param icon_folder: The icon_folder of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 :type: str",
"@graphic_id.setter def graphic_id(self, graphic_id): \"\"\"Sets the graphic_id of this GetUniverseGraphicsGraphicIdOk. graphic_id integer #",
"= sof_race_name @property def sof_fation_name(self): \"\"\"Gets the sof_fation_name of this GetUniverseGraphicsGraphicIdOk. # noqa:",
"sof_hull_name=None, collision_file=None, icon_folder=None): # noqa: E501 \"\"\"GetUniverseGraphicsGraphicIdOk - a model defined in Swagger\"\"\"",
"== other.__dict__ def __ne__(self, other): \"\"\"Returns true if both objects are not equal\"\"\"",
"this GetUniverseGraphicsGraphicIdOk. icon_folder string # noqa: E501 :param icon_folder: The icon_folder of this",
"is not None: self.sof_dna = sof_dna if sof_hull_name is not None: self.sof_hull_name =",
"if graphic_id is None: raise ValueError(\"Invalid value for `graphic_id`, must not be `None`\")",
"the icon_folder of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 icon_folder string # noqa: E501",
"'graphic_file': 'str', 'sof_race_name': 'str', 'sof_fation_name': 'str', 'sof_dna': 'str', 'sof_hull_name': 'str', 'collision_file': 'str', 'icon_folder':",
"this GetUniverseGraphicsGraphicIdOk. collision_file string # noqa: E501 :param collision_file: The collision_file of this",
"properties as a dict\"\"\" result = {} for attr, _ in six.iteritems(self.swagger_types): value",
"sof_race_name of this GetUniverseGraphicsGraphicIdOk. sof_race_name string # noqa: E501 :param sof_race_name: The sof_race_name",
"program. Do not edit the class manually. \"\"\" \"\"\" Attributes: swagger_types (dict): The",
"a model defined in Swagger\"\"\" # noqa: E501 self._graphic_id = None self._graphic_file =",
"this GetUniverseGraphicsGraphicIdOk. graphic_file string # noqa: E501 :param graphic_file: The graphic_file of this",
"sof_fation_name @property def sof_dna(self): \"\"\"Gets the sof_dna of this GetUniverseGraphicsGraphicIdOk. # noqa: E501",
"not None: self.collision_file = collision_file if icon_folder is not None: self.icon_folder = icon_folder",
"self._sof_dna = sof_dna @property def sof_hull_name(self): \"\"\"Gets the sof_hull_name of this GetUniverseGraphicsGraphicIdOk. #",
"else: result[attr] = value return result def to_str(self): \"\"\"Returns the string representation of",
"str \"\"\" self._sof_dna = sof_dna @property def sof_hull_name(self): \"\"\"Gets the sof_hull_name of this",
"{ 'graphic_id': 'int', 'graphic_file': 'str', 'sof_race_name': 'str', 'sof_fation_name': 'str', 'sof_dna': 'str', 'sof_hull_name': 'str',",
"self._sof_fation_name @sof_fation_name.setter def sof_fation_name(self, sof_fation_name): \"\"\"Sets the sof_fation_name of this GetUniverseGraphicsGraphicIdOk. sof_fation_name string",
"representation of the model\"\"\" return pprint.pformat(self.to_dict()) def __repr__(self): \"\"\"For `print` and `pprint`\"\"\" return",
"for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr]",
"of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 :type: str \"\"\" self._collision_file = collision_file @property",
"'str', 'collision_file': 'str', 'icon_folder': 'str' } attribute_map = { 'graphic_id': 'graphic_id', 'graphic_file': 'graphic_file',",
"of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 icon_folder string # noqa: E501 :return: The",
"# noqa: F401 import six class GetUniverseGraphicsGraphicIdOk(object): \"\"\"NOTE: This class is auto generated",
"of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 :type: int \"\"\" if graphic_id is None:",
"`graphic_id`, must not be `None`\") # noqa: E501 self._graphic_id = graphic_id @property def",
"this GetUniverseGraphicsGraphicIdOk. # noqa: E501 :rtype: str \"\"\" return self._graphic_file @graphic_file.setter def graphic_file(self,",
"noqa: E501 :return: The sof_dna of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 :rtype: str",
"the sof_race_name of this GetUniverseGraphicsGraphicIdOk. sof_race_name string # noqa: E501 :param sof_race_name: The",
"(item[0], item[1].to_dict()) if hasattr(item[1], \"to_dict\") else item, value.items() )) else: result[attr] = value",
"true if both objects are equal\"\"\" if not isinstance(other, GetUniverseGraphicsGraphicIdOk): return False return",
"if both objects are equal\"\"\" if not isinstance(other, GetUniverseGraphicsGraphicIdOk): return False return self.__dict__",
"The sof_fation_name of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 :type: str \"\"\" self._sof_fation_name =",
"is json key in definition. \"\"\" swagger_types = { 'graphic_id': 'int', 'graphic_file': 'str',",
"self.__dict__ == other.__dict__ def __ne__(self, other): \"\"\"Returns true if both objects are not",
"EVE Swagger Interface An OpenAPI for EVE Online # noqa: E501 OpenAPI spec",
"isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, \"to_dict\") else x,",
"E501 :type: str \"\"\" self._sof_race_name = sof_race_name @property def sof_fation_name(self): \"\"\"Gets the sof_fation_name",
"def graphic_id(self, graphic_id): \"\"\"Sets the graphic_id of this GetUniverseGraphicsGraphicIdOk. graphic_id integer # noqa:",
"return self._sof_fation_name @sof_fation_name.setter def sof_fation_name(self, sof_fation_name): \"\"\"Sets the sof_fation_name of this GetUniverseGraphicsGraphicIdOk. sof_fation_name",
"graphic_file(self, graphic_file): \"\"\"Sets the graphic_file of this GetUniverseGraphicsGraphicIdOk. graphic_file string # noqa: E501",
"'icon_folder': 'str' } attribute_map = { 'graphic_id': 'graphic_id', 'graphic_file': 'graphic_file', 'sof_race_name': 'sof_race_name', 'sof_fation_name':",
"import pprint import re # noqa: F401 import six class GetUniverseGraphicsGraphicIdOk(object): \"\"\"NOTE: This",
"is attribute type. attribute_map (dict): The key is attribute name and the value",
"of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 :rtype: str \"\"\" return self._graphic_file @graphic_file.setter def",
"of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 :type: str \"\"\" self._graphic_file = graphic_file @property",
"value )) elif hasattr(value, \"to_dict\"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] =",
"= sof_hull_name @property def collision_file(self): \"\"\"Gets the collision_file of this GetUniverseGraphicsGraphicIdOk. # noqa:",
"The sof_fation_name of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 :rtype: str \"\"\" return self._sof_fation_name",
"\"\"\" self._sof_dna = sof_dna @property def sof_hull_name(self): \"\"\"Gets the sof_hull_name of this GetUniverseGraphicsGraphicIdOk.",
"icon_folder of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 :type: str \"\"\" self._icon_folder = icon_folder",
"equal\"\"\" if not isinstance(other, GetUniverseGraphicsGraphicIdOk): return False return self.__dict__ == other.__dict__ def __ne__(self,",
"icon_folder of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 icon_folder string # noqa: E501 :return:",
"sof_race_name string # noqa: E501 :return: The sof_race_name of this GetUniverseGraphicsGraphicIdOk. # noqa:",
"collision_file(self, collision_file): \"\"\"Sets the collision_file of this GetUniverseGraphicsGraphicIdOk. collision_file string # noqa: E501",
"model properties as a dict\"\"\" result = {} for attr, _ in six.iteritems(self.swagger_types):",
"and `pprint`\"\"\" return self.to_str() def __eq__(self, other): \"\"\"Returns true if both objects are",
"str \"\"\" return self._sof_race_name @sof_race_name.setter def sof_race_name(self, sof_race_name): \"\"\"Sets the sof_race_name of this",
"@property def icon_folder(self): \"\"\"Gets the icon_folder of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 icon_folder",
"The sof_hull_name of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 :rtype: str \"\"\" return self._sof_hull_name",
"noqa: E501 :return: The sof_race_name of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 :rtype: str",
"noqa: E501 :type: str \"\"\" self._sof_fation_name = sof_fation_name @property def sof_dna(self): \"\"\"Gets the",
"self.to_str() def __eq__(self, other): \"\"\"Returns true if both objects are equal\"\"\" if not",
"# noqa: E501 :rtype: str \"\"\" return self._sof_fation_name @sof_fation_name.setter def sof_fation_name(self, sof_fation_name): \"\"\"Sets",
"str \"\"\" return self._sof_hull_name @sof_hull_name.setter def sof_hull_name(self, sof_hull_name): \"\"\"Sets the sof_hull_name of this",
"@property def graphic_file(self): \"\"\"Gets the graphic_file of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 graphic_file",
"swagger_types (dict): The key is attribute name and the value is attribute type.",
"integer # noqa: E501 :param graphic_id: The graphic_id of this GetUniverseGraphicsGraphicIdOk. # noqa:",
"False return self.__dict__ == other.__dict__ def __ne__(self, other): \"\"\"Returns true if both objects",
"sof_hull_name(self): \"\"\"Gets the sof_hull_name of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 sof_hull_name string #",
"graphic_file string # noqa: E501 :return: The graphic_file of this GetUniverseGraphicsGraphicIdOk. # noqa:",
"str \"\"\" self._sof_race_name = sof_race_name @property def sof_fation_name(self): \"\"\"Gets the sof_fation_name of this",
"E501 :return: The collision_file of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 :rtype: str \"\"\"",
"# noqa: E501 :param graphic_id: The graphic_id of this GetUniverseGraphicsGraphicIdOk. # noqa: E501",
"attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, \"to_dict\")",
"result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], \"to_dict\") else item, value.items()",
"# noqa: E501 self._graphic_id = None self._graphic_file = None self._sof_race_name = None self._sof_fation_name",
"if sof_dna is not None: self.sof_dna = sof_dna if sof_hull_name is not None:",
"The graphic_id of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 :type: int \"\"\" if graphic_id",
"as a dict\"\"\" result = {} for attr, _ in six.iteritems(self.swagger_types): value =",
"string # noqa: E501 :return: The sof_fation_name of this GetUniverseGraphicsGraphicIdOk. # noqa: E501",
"def sof_fation_name(self, sof_fation_name): \"\"\"Sets the sof_fation_name of this GetUniverseGraphicsGraphicIdOk. sof_fation_name string # noqa:",
"# noqa: E501 :param sof_hull_name: The sof_hull_name of this GetUniverseGraphicsGraphicIdOk. # noqa: E501",
"Generated by: https://github.com/swagger-api/swagger-codegen.git \"\"\" import pprint import re # noqa: F401 import six",
"in Swagger\"\"\" # noqa: E501 self._graphic_id = None self._graphic_file = None self._sof_race_name =",
"None self._sof_dna = None self._sof_hull_name = None self._collision_file = None self._icon_folder = None",
"this GetUniverseGraphicsGraphicIdOk. sof_race_name string # noqa: E501 :param sof_race_name: The sof_race_name of this",
"noqa: E501 :param collision_file: The collision_file of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 :type:",
"noqa: E501 :type: str \"\"\" self._sof_hull_name = sof_hull_name @property def collision_file(self): \"\"\"Gets the",
"str \"\"\" return self._sof_fation_name @sof_fation_name.setter def sof_fation_name(self, sof_fation_name): \"\"\"Sets the sof_fation_name of this",
"GetUniverseGraphicsGraphicIdOk. # noqa: E501 sof_race_name string # noqa: E501 :return: The sof_race_name of",
"Do not edit the class manually. \"\"\" \"\"\" Attributes: swagger_types (dict): The key",
"graphic_id=None, graphic_file=None, sof_race_name=None, sof_fation_name=None, sof_dna=None, sof_hull_name=None, collision_file=None, icon_folder=None): # noqa: E501 \"\"\"GetUniverseGraphicsGraphicIdOk -",
"self.icon_folder = icon_folder @property def graphic_id(self): \"\"\"Gets the graphic_id of this GetUniverseGraphicsGraphicIdOk. #",
"E501 :rtype: str \"\"\" return self._sof_dna @sof_dna.setter def sof_dna(self, sof_dna): \"\"\"Sets the sof_dna",
"graphic_id integer # noqa: E501 :return: The graphic_id of this GetUniverseGraphicsGraphicIdOk. # noqa:",
"\"\"\"Gets the graphic_id of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 graphic_id integer # noqa:",
":return: The sof_dna of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 :rtype: str \"\"\" return",
"to_str(self): \"\"\"Returns the string representation of the model\"\"\" return pprint.pformat(self.to_dict()) def __repr__(self): \"\"\"For",
"= { 'graphic_id': 'int', 'graphic_file': 'str', 'sof_race_name': 'str', 'sof_fation_name': 'str', 'sof_dna': 'str', 'sof_hull_name':",
"sof_fation_name of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 :rtype: str \"\"\" return self._sof_fation_name @sof_fation_name.setter",
"\"\"\" \"\"\" Attributes: swagger_types (dict): The key is attribute name and the value",
"self.sof_race_name = sof_race_name if sof_fation_name is not None: self.sof_fation_name = sof_fation_name if sof_dna",
"GetUniverseGraphicsGraphicIdOk. # noqa: E501 :type: str \"\"\" self._sof_dna = sof_dna @property def sof_hull_name(self):",
":return: The collision_file of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 :rtype: str \"\"\" return",
"other): \"\"\"Returns true if both objects are not equal\"\"\" return not self ==",
"Interface An OpenAPI for EVE Online # noqa: E501 OpenAPI spec version: 0.8.0",
"the value is attribute type. attribute_map (dict): The key is attribute name and",
"'sof_hull_name': 'str', 'collision_file': 'str', 'icon_folder': 'str' } attribute_map = { 'graphic_id': 'graphic_id', 'graphic_file':",
"sof_race_name is not None: self.sof_race_name = sof_race_name if sof_fation_name is not None: self.sof_fation_name",
"collision_file of this GetUniverseGraphicsGraphicIdOk. collision_file string # noqa: E501 :param collision_file: The collision_file",
"return self._graphic_id @graphic_id.setter def graphic_id(self, graphic_id): \"\"\"Sets the graphic_id of this GetUniverseGraphicsGraphicIdOk. graphic_id",
"the collision_file of this GetUniverseGraphicsGraphicIdOk. collision_file string # noqa: E501 :param collision_file: The",
"of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 :type: str \"\"\" self._sof_race_name = sof_race_name @property",
"not None: self.sof_race_name = sof_race_name if sof_fation_name is not None: self.sof_fation_name = sof_fation_name",
":rtype: str \"\"\" return self._sof_fation_name @sof_fation_name.setter def sof_fation_name(self, sof_fation_name): \"\"\"Sets the sof_fation_name of",
"Online # noqa: E501 OpenAPI spec version: 0.8.0 Generated by: https://github.com/swagger-api/swagger-codegen.git \"\"\" import",
"self.sof_dna = sof_dna if sof_hull_name is not None: self.sof_hull_name = sof_hull_name if collision_file",
"self.collision_file = collision_file if icon_folder is not None: self.icon_folder = icon_folder @property def",
"attribute type. attribute_map (dict): The key is attribute name and the value is",
"'sof_dna', 'sof_hull_name': 'sof_hull_name', 'collision_file': 'collision_file', 'icon_folder': 'icon_folder' } def __init__(self, graphic_id=None, graphic_file=None, sof_race_name=None,",
"@property def sof_race_name(self): \"\"\"Gets the sof_race_name of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 sof_race_name",
"__ne__(self, other): \"\"\"Returns true if both objects are not equal\"\"\" return not self",
"self._collision_file @collision_file.setter def collision_file(self, collision_file): \"\"\"Sets the collision_file of this GetUniverseGraphicsGraphicIdOk. collision_file string",
"sof_dna(self, sof_dna): \"\"\"Sets the sof_dna of this GetUniverseGraphicsGraphicIdOk. sof_dna string # noqa: E501",
"value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1],",
"noqa: E501 :param sof_hull_name: The sof_hull_name of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 :type:",
"return self.__dict__ == other.__dict__ def __ne__(self, other): \"\"\"Returns true if both objects are",
"sof_dna of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 sof_dna string # noqa: E501 :return:",
"The key is attribute name and the value is attribute type. attribute_map (dict):",
"\"\"\"Gets the sof_fation_name of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 sof_fation_name string # noqa:",
"the string representation of the model\"\"\" return pprint.pformat(self.to_dict()) def __repr__(self): \"\"\"For `print` and",
"sof_fation_name if sof_dna is not None: self.sof_dna = sof_dna if sof_hull_name is not",
"sof_fation_name of this GetUniverseGraphicsGraphicIdOk. sof_fation_name string # noqa: E501 :param sof_fation_name: The sof_fation_name",
"attribute_map = { 'graphic_id': 'graphic_id', 'graphic_file': 'graphic_file', 'sof_race_name': 'sof_race_name', 'sof_fation_name': 'sof_fation_name', 'sof_dna': 'sof_dna',",
"model defined in Swagger\"\"\" # noqa: E501 self._graphic_id = None self._graphic_file = None",
"None self._sof_hull_name = None self._collision_file = None self._icon_folder = None self.discriminator = None",
"None: self.sof_race_name = sof_race_name if sof_fation_name is not None: self.sof_fation_name = sof_fation_name if",
"return self._sof_dna @sof_dna.setter def sof_dna(self, sof_dna): \"\"\"Sets the sof_dna of this GetUniverseGraphicsGraphicIdOk. sof_dna",
"E501 :return: The icon_folder of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 :rtype: str \"\"\"",
"E501 \"\"\"GetUniverseGraphicsGraphicIdOk - a model defined in Swagger\"\"\" # noqa: E501 self._graphic_id =",
"= None self._sof_fation_name = None self._sof_dna = None self._sof_hull_name = None self._collision_file =",
"icon_folder(self, icon_folder): \"\"\"Sets the icon_folder of this GetUniverseGraphicsGraphicIdOk. icon_folder string # noqa: E501",
"None self._sof_fation_name = None self._sof_dna = None self._sof_hull_name = None self._collision_file = None",
"is auto generated by the swagger code generator program. Do not edit the",
"self._icon_folder = None self.discriminator = None self.graphic_id = graphic_id if graphic_file is not",
"self._graphic_file = None self._sof_race_name = None self._sof_fation_name = None self._sof_dna = None self._sof_hull_name",
"GetUniverseGraphicsGraphicIdOk. icon_folder string # noqa: E501 :param icon_folder: The icon_folder of this GetUniverseGraphicsGraphicIdOk.",
"if graphic_file is not None: self.graphic_file = graphic_file if sof_race_name is not None:",
"'str' } attribute_map = { 'graphic_id': 'graphic_id', 'graphic_file': 'graphic_file', 'sof_race_name': 'sof_race_name', 'sof_fation_name': 'sof_fation_name',",
"None self._graphic_file = None self._sof_race_name = None self._sof_fation_name = None self._sof_dna = None",
"None self.discriminator = None self.graphic_id = graphic_id if graphic_file is not None: self.graphic_file",
"noqa: E501 :return: The graphic_file of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 :rtype: str",
"collision_file @property def icon_folder(self): \"\"\"Gets the icon_folder of this GetUniverseGraphicsGraphicIdOk. # noqa: E501",
"https://github.com/swagger-api/swagger-codegen.git \"\"\" import pprint import re # noqa: F401 import six class GetUniverseGraphicsGraphicIdOk(object):",
"sof_dna=None, sof_hull_name=None, collision_file=None, icon_folder=None): # noqa: E501 \"\"\"GetUniverseGraphicsGraphicIdOk - a model defined in",
"of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 sof_hull_name string # noqa: E501 :return: The",
"other): \"\"\"Returns true if both objects are equal\"\"\" if not isinstance(other, GetUniverseGraphicsGraphicIdOk): return",
"hasattr(x, \"to_dict\") else x, value )) elif hasattr(value, \"to_dict\"): result[attr] = value.to_dict() elif",
"# noqa: E501 sof_hull_name string # noqa: E501 :return: The sof_hull_name of this",
"E501 self._graphic_id = graphic_id @property def graphic_file(self): \"\"\"Gets the graphic_file of this GetUniverseGraphicsGraphicIdOk.",
"this GetUniverseGraphicsGraphicIdOk. # noqa: E501 sof_fation_name string # noqa: E501 :return: The sof_fation_name",
"sof_dna string # noqa: E501 :param sof_dna: The sof_dna of this GetUniverseGraphicsGraphicIdOk. #",
"noqa: E501 :param sof_dna: The sof_dna of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 :type:",
"'collision_file': 'collision_file', 'icon_folder': 'icon_folder' } def __init__(self, graphic_id=None, graphic_file=None, sof_race_name=None, sof_fation_name=None, sof_dna=None, sof_hull_name=None,",
":param icon_folder: The icon_folder of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 :type: str \"\"\"",
"= { 'graphic_id': 'graphic_id', 'graphic_file': 'graphic_file', 'sof_race_name': 'sof_race_name', 'sof_fation_name': 'sof_fation_name', 'sof_dna': 'sof_dna', 'sof_hull_name':",
"sof_fation_name): \"\"\"Sets the sof_fation_name of this GetUniverseGraphicsGraphicIdOk. sof_fation_name string # noqa: E501 :param",
"collision_file: The collision_file of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 :type: str \"\"\" self._collision_file",
"definition. \"\"\" swagger_types = { 'graphic_id': 'int', 'graphic_file': 'str', 'sof_race_name': 'str', 'sof_fation_name': 'str',",
"sof_fation_name string # noqa: E501 :return: The sof_fation_name of this GetUniverseGraphicsGraphicIdOk. # noqa:",
"collision_file of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 :rtype: str \"\"\" return self._collision_file @collision_file.setter",
"import re # noqa: F401 import six class GetUniverseGraphicsGraphicIdOk(object): \"\"\"NOTE: This class is",
"must not be `None`\") # noqa: E501 self._graphic_id = graphic_id @property def graphic_file(self):",
"item, value.items() )) else: result[attr] = value return result def to_str(self): \"\"\"Returns the",
"Swagger\"\"\" # noqa: E501 self._graphic_id = None self._graphic_file = None self._sof_race_name = None",
"elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], \"to_dict\")",
"pprint.pformat(self.to_dict()) def __repr__(self): \"\"\"For `print` and `pprint`\"\"\" return self.to_str() def __eq__(self, other): \"\"\"Returns",
":type: str \"\"\" self._sof_hull_name = sof_hull_name @property def collision_file(self): \"\"\"Gets the collision_file of",
"= collision_file @property def icon_folder(self): \"\"\"Gets the icon_folder of this GetUniverseGraphicsGraphicIdOk. # noqa:",
"\"\"\"Returns true if both objects are not equal\"\"\" return not self == other",
"E501 sof_race_name string # noqa: E501 :return: The sof_race_name of this GetUniverseGraphicsGraphicIdOk. #",
"for EVE Online # noqa: E501 OpenAPI spec version: 0.8.0 Generated by: https://github.com/swagger-api/swagger-codegen.git",
"this GetUniverseGraphicsGraphicIdOk. # noqa: E501 :type: str \"\"\" self._sof_race_name = sof_race_name @property def",
"if collision_file is not None: self.collision_file = collision_file if icon_folder is not None:",
"auto generated by the swagger code generator program. Do not edit the class",
"{} for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list):",
"pprint import re # noqa: F401 import six class GetUniverseGraphicsGraphicIdOk(object): \"\"\"NOTE: This class",
"not None: self.sof_hull_name = sof_hull_name if collision_file is not None: self.collision_file = collision_file",
"GetUniverseGraphicsGraphicIdOk. sof_race_name string # noqa: E501 :param sof_race_name: The sof_race_name of this GetUniverseGraphicsGraphicIdOk.",
"E501 graphic_file string # noqa: E501 :return: The graphic_file of this GetUniverseGraphicsGraphicIdOk. #",
"'collision_file', 'icon_folder': 'icon_folder' } def __init__(self, graphic_id=None, graphic_file=None, sof_race_name=None, sof_fation_name=None, sof_dna=None, sof_hull_name=None, collision_file=None,",
"E501 :return: The graphic_id of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 :rtype: int \"\"\"",
"sof_race_name string # noqa: E501 :param sof_race_name: The sof_race_name of this GetUniverseGraphicsGraphicIdOk. #",
"value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict()",
"'graphic_id': 'int', 'graphic_file': 'str', 'sof_race_name': 'str', 'sof_fation_name': 'str', 'sof_dna': 'str', 'sof_hull_name': 'str', 'collision_file':",
"graphic_id @property def graphic_file(self): \"\"\"Gets the graphic_file of this GetUniverseGraphicsGraphicIdOk. # noqa: E501",
"noqa: E501 :rtype: int \"\"\" return self._graphic_id @graphic_id.setter def graphic_id(self, graphic_id): \"\"\"Sets the",
"sof_dna of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 :rtype: str \"\"\" return self._sof_dna @sof_dna.setter",
"# noqa: E501 :type: str \"\"\" self._sof_fation_name = sof_fation_name @property def sof_dna(self): \"\"\"Gets",
"self._sof_fation_name = None self._sof_dna = None self._sof_hull_name = None self._collision_file = None self._icon_folder",
"string # noqa: E501 :param graphic_file: The graphic_file of this GetUniverseGraphicsGraphicIdOk. # noqa:",
"spec version: 0.8.0 Generated by: https://github.com/swagger-api/swagger-codegen.git \"\"\" import pprint import re # noqa:",
"noqa: E501 :type: str \"\"\" self._graphic_file = graphic_file @property def sof_race_name(self): \"\"\"Gets the",
"@graphic_file.setter def graphic_file(self, graphic_file): \"\"\"Sets the graphic_file of this GetUniverseGraphicsGraphicIdOk. graphic_file string #",
"@property def sof_hull_name(self): \"\"\"Gets the sof_hull_name of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 sof_hull_name",
"generator program. Do not edit the class manually. \"\"\" \"\"\" Attributes: swagger_types (dict):",
"this GetUniverseGraphicsGraphicIdOk. # noqa: E501 :type: str \"\"\" self._icon_folder = icon_folder def to_dict(self):",
"if hasattr(item[1], \"to_dict\") else item, value.items() )) else: result[attr] = value return result",
"= graphic_id if graphic_file is not None: self.graphic_file = graphic_file if sof_race_name is",
"\"\"\"Sets the sof_race_name of this GetUniverseGraphicsGraphicIdOk. sof_race_name string # noqa: E501 :param sof_race_name:",
"GetUniverseGraphicsGraphicIdOk. # noqa: E501 :type: str \"\"\" self._graphic_file = graphic_file @property def sof_race_name(self):",
"icon_folder of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 :rtype: str \"\"\" return self._icon_folder @icon_folder.setter",
"return self._graphic_file @graphic_file.setter def graphic_file(self, graphic_file): \"\"\"Sets the graphic_file of this GetUniverseGraphicsGraphicIdOk. graphic_file",
"value is attribute type. attribute_map (dict): The key is attribute name and the",
"the sof_fation_name of this GetUniverseGraphicsGraphicIdOk. sof_fation_name string # noqa: E501 :param sof_fation_name: The",
"sof_fation_name of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 :type: str \"\"\" self._sof_fation_name = sof_fation_name",
"graphic_file=None, sof_race_name=None, sof_fation_name=None, sof_dna=None, sof_hull_name=None, collision_file=None, icon_folder=None): # noqa: E501 \"\"\"GetUniverseGraphicsGraphicIdOk - a",
"\"\"\"Gets the sof_race_name of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 sof_race_name string # noqa:",
"= list(map( lambda x: x.to_dict() if hasattr(x, \"to_dict\") else x, value )) elif",
"model\"\"\" return pprint.pformat(self.to_dict()) def __repr__(self): \"\"\"For `print` and `pprint`\"\"\" return self.to_str() def __eq__(self,",
"E501 :return: The sof_race_name of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 :rtype: str \"\"\"",
"icon_folder of this GetUniverseGraphicsGraphicIdOk. icon_folder string # noqa: E501 :param icon_folder: The icon_folder",
"else item, value.items() )) else: result[attr] = value return result def to_str(self): \"\"\"Returns",
"# noqa: E501 :rtype: int \"\"\" return self._graphic_id @graphic_id.setter def graphic_id(self, graphic_id): \"\"\"Sets",
"# noqa: E501 :rtype: str \"\"\" return self._icon_folder @icon_folder.setter def icon_folder(self, icon_folder): \"\"\"Sets",
"if icon_folder is not None: self.icon_folder = icon_folder @property def graphic_id(self): \"\"\"Gets the",
"GetUniverseGraphicsGraphicIdOk. graphic_file string # noqa: E501 :param graphic_file: The graphic_file of this GetUniverseGraphicsGraphicIdOk.",
"E501 :type: str \"\"\" self._sof_hull_name = sof_hull_name @property def collision_file(self): \"\"\"Gets the collision_file",
"\"\"\" self._sof_race_name = sof_race_name @property def sof_fation_name(self): \"\"\"Gets the sof_fation_name of this GetUniverseGraphicsGraphicIdOk.",
"# noqa: E501 self._graphic_id = graphic_id @property def graphic_file(self): \"\"\"Gets the graphic_file of",
"\"\"\"Sets the sof_dna of this GetUniverseGraphicsGraphicIdOk. sof_dna string # noqa: E501 :param sof_dna:",
"noqa: E501 :rtype: str \"\"\" return self._sof_race_name @sof_race_name.setter def sof_race_name(self, sof_race_name): \"\"\"Sets the",
"graphic_id of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 graphic_id integer # noqa: E501 :return:",
"GetUniverseGraphicsGraphicIdOk. # noqa: E501 icon_folder string # noqa: E501 :return: The icon_folder of",
"\"\"\" return self._sof_race_name @sof_race_name.setter def sof_race_name(self, sof_race_name): \"\"\"Sets the sof_race_name of this GetUniverseGraphicsGraphicIdOk.",
"sof_dna of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 :type: str \"\"\" self._sof_dna = sof_dna",
"icon_folder string # noqa: E501 :return: The icon_folder of this GetUniverseGraphicsGraphicIdOk. # noqa:",
"result = {} for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if",
"= {} for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value,",
"collision_file(self): \"\"\"Gets the collision_file of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 collision_file string #",
"= icon_folder @property def graphic_id(self): \"\"\"Gets the graphic_id of this GetUniverseGraphicsGraphicIdOk. # noqa:",
"\"to_dict\") else item, value.items() )) else: result[attr] = value return result def to_str(self):",
"GetUniverseGraphicsGraphicIdOk. # noqa: E501 :rtype: str \"\"\" return self._sof_fation_name @sof_fation_name.setter def sof_fation_name(self, sof_fation_name):",
"the sof_race_name of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 sof_race_name string # noqa: E501",
"this GetUniverseGraphicsGraphicIdOk. # noqa: E501 :type: int \"\"\" if graphic_id is None: raise",
"not isinstance(other, GetUniverseGraphicsGraphicIdOk): return False return self.__dict__ == other.__dict__ def __ne__(self, other): \"\"\"Returns",
"'sof_hull_name': 'sof_hull_name', 'collision_file': 'collision_file', 'icon_folder': 'icon_folder' } def __init__(self, graphic_id=None, graphic_file=None, sof_race_name=None, sof_fation_name=None,",
"of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 :type: str \"\"\" self._sof_dna = sof_dna @property",
"if hasattr(x, \"to_dict\") else x, value )) elif hasattr(value, \"to_dict\"): result[attr] = value.to_dict()",
"def sof_race_name(self, sof_race_name): \"\"\"Sets the sof_race_name of this GetUniverseGraphicsGraphicIdOk. sof_race_name string # noqa:",
"noqa: E501 sof_race_name string # noqa: E501 :return: The sof_race_name of this GetUniverseGraphicsGraphicIdOk.",
"E501 OpenAPI spec version: 0.8.0 Generated by: https://github.com/swagger-api/swagger-codegen.git \"\"\" import pprint import re",
"be `None`\") # noqa: E501 self._graphic_id = graphic_id @property def graphic_file(self): \"\"\"Gets the",
"None self._icon_folder = None self.discriminator = None self.graphic_id = graphic_id if graphic_file is",
"noqa: E501 :rtype: str \"\"\" return self._sof_hull_name @sof_hull_name.setter def sof_hull_name(self, sof_hull_name): \"\"\"Sets the",
"collision_file): \"\"\"Sets the collision_file of this GetUniverseGraphicsGraphicIdOk. collision_file string # noqa: E501 :param",
"string # noqa: E501 :return: The collision_file of this GetUniverseGraphicsGraphicIdOk. # noqa: E501",
"\"\"\" EVE Swagger Interface An OpenAPI for EVE Online # noqa: E501 OpenAPI",
"def sof_dna(self, sof_dna): \"\"\"Sets the sof_dna of this GetUniverseGraphicsGraphicIdOk. sof_dna string # noqa:",
"# noqa: E501 :return: The sof_fation_name of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 :rtype:",
"def icon_folder(self): \"\"\"Gets the icon_folder of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 icon_folder string",
"the model properties as a dict\"\"\" result = {} for attr, _ in",
"self.graphic_id = graphic_id if graphic_file is not None: self.graphic_file = graphic_file if sof_race_name",
":type: str \"\"\" self._icon_folder = icon_folder def to_dict(self): \"\"\"Returns the model properties as",
"GetUniverseGraphicsGraphicIdOk. # noqa: E501 :rtype: str \"\"\" return self._graphic_file @graphic_file.setter def graphic_file(self, graphic_file):",
"The icon_folder of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 :rtype: str \"\"\" return self._icon_folder",
"graphic_file of this GetUniverseGraphicsGraphicIdOk. # noqa: E501 :rtype: str \"\"\" return self._graphic_file @graphic_file.setter"
] |
[
"[\"traj_dist/cydist/sspd.pyx\"]), Extension(\"traj_dist.cydist.dtw\", [\"traj_dist/cydist/dtw.pyx\"]), Extension(\"traj_dist.cydist.lcss\", [\"traj_dist/cydist/lcss.pyx\"]), Extension(\"traj_dist.cydist.hausdorff\", [\"traj_dist/cydist/hausdorff.pyx\"]), Extension(\"traj_dist.cydist.discret_frechet\", [\"traj_dist/cydist/discret_frechet.pyx\"]), Extension(\"traj_dist.cydist.frechet\", [\"traj_dist/cydist/frechet.pyx\"]), Extension(\"traj_dist.cydist.segment_distance\", [\"traj_dist/cydist/segment_distance.pyx\"]),",
"Extension(\"traj_dist.cydist.lcss\", [\"traj_dist/cydist/lcss.pyx\"]), Extension(\"traj_dist.cydist.hausdorff\", [\"traj_dist/cydist/hausdorff.pyx\"]), Extension(\"traj_dist.cydist.discret_frechet\", [\"traj_dist/cydist/discret_frechet.pyx\"]), Extension(\"traj_dist.cydist.frechet\", [\"traj_dist/cydist/frechet.pyx\"]), Extension(\"traj_dist.cydist.segment_distance\", [\"traj_dist/cydist/segment_distance.pyx\"]), Extension(\"traj_dist.cydist.sowd\", [\"traj_dist/cydist/sowd.pyx\"]), Extension(\"traj_dist.cydist.erp\",",
"import numpy import os from glob import glob \"\"\" ext_modules = [Extension(\"traj_dist.cydist.basic_geographical\", [\"traj_dist/cydist/basic_geographical.pyx\"]),",
"os from glob import glob \"\"\" ext_modules = [Extension(\"traj_dist.cydist.basic_geographical\", [\"traj_dist/cydist/basic_geographical.pyx\"]), Extension(\"traj_dist.cydist.basic_euclidean\", [\"traj_dist/cydist/basic_euclidean.pyx\"]), Extension(\"traj_dist.cydist.sspd\",",
"cythonize, build_ext import numpy import os from glob import glob \"\"\" ext_modules =",
"[Extension(\"traj_dist.cydist.basic_geographical\", [\"traj_dist/cydist/basic_geographical.pyx\"]), Extension(\"traj_dist.cydist.basic_euclidean\", [\"traj_dist/cydist/basic_euclidean.pyx\"]), Extension(\"traj_dist.cydist.sspd\", [\"traj_dist/cydist/sspd.pyx\"]), Extension(\"traj_dist.cydist.dtw\", [\"traj_dist/cydist/dtw.pyx\"]), Extension(\"traj_dist.cydist.lcss\", [\"traj_dist/cydist/lcss.pyx\"]), Extension(\"traj_dist.cydist.hausdorff\", [\"traj_dist/cydist/hausdorff.pyx\"]), Extension(\"traj_dist.cydist.discret_frechet\",",
"include_dirs=[numpy.get_include()], install_requires=[\"numpy>=1.14.0\", \"cython>=0.27.3\", \"shapely>=1.6.3\", \"geohash2>=1.1\", 'pandas>=0.20.3', 'scipy>=0.19.1'], description=\"Distance to compare 2D-trajectories in Cython\",",
"\"\"\" sources = glob('traj_dist/cydist/*.pyx') extensions = [ Extension(filename.split('.')[0].replace(os.path.sep, '.'), sources=[filename], ) for filename",
"author=\"<NAME>\", author_email=\"<EMAIL>\", cmdclass={'build_ext': build_ext}, # ext_modules=ext_modules, ext_modules=extensions, include_dirs=[numpy.get_include()], install_requires=[\"numpy>=1.14.0\", \"cython>=0.27.3\", \"shapely>=1.6.3\", \"geohash2>=1.1\", 'pandas>=0.20.3',",
"sources] setup( name=\"trajectory_distance_py3\", version=\"1.0.1\", author=\"<NAME>\", author_email=\"<EMAIL>\", cmdclass={'build_ext': build_ext}, # ext_modules=ext_modules, ext_modules=extensions, include_dirs=[numpy.get_include()], install_requires=[\"numpy>=1.14.0\",",
"[\"traj_dist/cydist/basic_geographical.pyx\"]), Extension(\"traj_dist.cydist.basic_euclidean\", [\"traj_dist/cydist/basic_euclidean.pyx\"]), Extension(\"traj_dist.cydist.sspd\", [\"traj_dist/cydist/sspd.pyx\"]), Extension(\"traj_dist.cydist.dtw\", [\"traj_dist/cydist/dtw.pyx\"]), Extension(\"traj_dist.cydist.lcss\", [\"traj_dist/cydist/lcss.pyx\"]), Extension(\"traj_dist.cydist.hausdorff\", [\"traj_dist/cydist/hausdorff.pyx\"]), Extension(\"traj_dist.cydist.discret_frechet\", [\"traj_dist/cydist/discret_frechet.pyx\"]),",
"Extension(\"traj_dist.cydist.edr\", [\"traj_dist/cydist/edr.pyx\"])] \"\"\" sources = glob('traj_dist/cydist/*.pyx') extensions = [ Extension(filename.split('.')[0].replace(os.path.sep, '.'), sources=[filename], )",
"import Extension from Cython.Build import cythonize, build_ext import numpy import os from glob",
"\"\"\" ext_modules = [Extension(\"traj_dist.cydist.basic_geographical\", [\"traj_dist/cydist/basic_geographical.pyx\"]), Extension(\"traj_dist.cydist.basic_euclidean\", [\"traj_dist/cydist/basic_euclidean.pyx\"]), Extension(\"traj_dist.cydist.sspd\", [\"traj_dist/cydist/sspd.pyx\"]), Extension(\"traj_dist.cydist.dtw\", [\"traj_dist/cydist/dtw.pyx\"]), Extension(\"traj_dist.cydist.lcss\", [\"traj_dist/cydist/lcss.pyx\"]),",
"[\"traj_dist/cydist/segment_distance.pyx\"]), Extension(\"traj_dist.cydist.sowd\", [\"traj_dist/cydist/sowd.pyx\"]), Extension(\"traj_dist.cydist.erp\", [\"traj_dist/cydist/erp.pyx\"]), Extension(\"traj_dist.cydist.edr\", [\"traj_dist/cydist/edr.pyx\"])] \"\"\" sources = glob('traj_dist/cydist/*.pyx') extensions =",
"\"cython>=0.27.3\", \"shapely>=1.6.3\", \"geohash2>=1.1\", 'pandas>=0.20.3', 'scipy>=0.19.1'], description=\"Distance to compare 2D-trajectories in Cython\", packages=find_packages() )",
"import glob \"\"\" ext_modules = [Extension(\"traj_dist.cydist.basic_geographical\", [\"traj_dist/cydist/basic_geographical.pyx\"]), Extension(\"traj_dist.cydist.basic_euclidean\", [\"traj_dist/cydist/basic_euclidean.pyx\"]), Extension(\"traj_dist.cydist.sspd\", [\"traj_dist/cydist/sspd.pyx\"]), Extension(\"traj_dist.cydist.dtw\", [\"traj_dist/cydist/dtw.pyx\"]),",
"[\"traj_dist/cydist/basic_euclidean.pyx\"]), Extension(\"traj_dist.cydist.sspd\", [\"traj_dist/cydist/sspd.pyx\"]), Extension(\"traj_dist.cydist.dtw\", [\"traj_dist/cydist/dtw.pyx\"]), Extension(\"traj_dist.cydist.lcss\", [\"traj_dist/cydist/lcss.pyx\"]), Extension(\"traj_dist.cydist.hausdorff\", [\"traj_dist/cydist/hausdorff.pyx\"]), Extension(\"traj_dist.cydist.discret_frechet\", [\"traj_dist/cydist/discret_frechet.pyx\"]), Extension(\"traj_dist.cydist.frechet\", [\"traj_dist/cydist/frechet.pyx\"]),",
"[\"traj_dist/cydist/frechet.pyx\"]), Extension(\"traj_dist.cydist.segment_distance\", [\"traj_dist/cydist/segment_distance.pyx\"]), Extension(\"traj_dist.cydist.sowd\", [\"traj_dist/cydist/sowd.pyx\"]), Extension(\"traj_dist.cydist.erp\", [\"traj_dist/cydist/erp.pyx\"]), Extension(\"traj_dist.cydist.edr\", [\"traj_dist/cydist/edr.pyx\"])] \"\"\" sources = glob('traj_dist/cydist/*.pyx')",
"from Cython.Build import cythonize, build_ext import numpy import os from glob import glob",
"filename in sources] setup( name=\"trajectory_distance_py3\", version=\"1.0.1\", author=\"<NAME>\", author_email=\"<EMAIL>\", cmdclass={'build_ext': build_ext}, # ext_modules=ext_modules, ext_modules=extensions,",
"sources=[filename], ) for filename in sources] setup( name=\"trajectory_distance_py3\", version=\"1.0.1\", author=\"<NAME>\", author_email=\"<EMAIL>\", cmdclass={'build_ext': build_ext},",
"= glob('traj_dist/cydist/*.pyx') extensions = [ Extension(filename.split('.')[0].replace(os.path.sep, '.'), sources=[filename], ) for filename in sources]",
"build_ext}, # ext_modules=ext_modules, ext_modules=extensions, include_dirs=[numpy.get_include()], install_requires=[\"numpy>=1.14.0\", \"cython>=0.27.3\", \"shapely>=1.6.3\", \"geohash2>=1.1\", 'pandas>=0.20.3', 'scipy>=0.19.1'], description=\"Distance to",
"= [ Extension(filename.split('.')[0].replace(os.path.sep, '.'), sources=[filename], ) for filename in sources] setup( name=\"trajectory_distance_py3\", version=\"1.0.1\",",
"cmdclass={'build_ext': build_ext}, # ext_modules=ext_modules, ext_modules=extensions, include_dirs=[numpy.get_include()], install_requires=[\"numpy>=1.14.0\", \"cython>=0.27.3\", \"shapely>=1.6.3\", \"geohash2>=1.1\", 'pandas>=0.20.3', 'scipy>=0.19.1'], description=\"Distance",
"sources = glob('traj_dist/cydist/*.pyx') extensions = [ Extension(filename.split('.')[0].replace(os.path.sep, '.'), sources=[filename], ) for filename in",
"Extension(filename.split('.')[0].replace(os.path.sep, '.'), sources=[filename], ) for filename in sources] setup( name=\"trajectory_distance_py3\", version=\"1.0.1\", author=\"<NAME>\", author_email=\"<EMAIL>\",",
"setup( name=\"trajectory_distance_py3\", version=\"1.0.1\", author=\"<NAME>\", author_email=\"<EMAIL>\", cmdclass={'build_ext': build_ext}, # ext_modules=ext_modules, ext_modules=extensions, include_dirs=[numpy.get_include()], install_requires=[\"numpy>=1.14.0\", \"cython>=0.27.3\",",
"glob \"\"\" ext_modules = [Extension(\"traj_dist.cydist.basic_geographical\", [\"traj_dist/cydist/basic_geographical.pyx\"]), Extension(\"traj_dist.cydist.basic_euclidean\", [\"traj_dist/cydist/basic_euclidean.pyx\"]), Extension(\"traj_dist.cydist.sspd\", [\"traj_dist/cydist/sspd.pyx\"]), Extension(\"traj_dist.cydist.dtw\", [\"traj_dist/cydist/dtw.pyx\"]), Extension(\"traj_dist.cydist.lcss\",",
"glob('traj_dist/cydist/*.pyx') extensions = [ Extension(filename.split('.')[0].replace(os.path.sep, '.'), sources=[filename], ) for filename in sources] setup(",
"from Cython.Distutils.extension import Extension from Cython.Build import cythonize, build_ext import numpy import os",
"'.'), sources=[filename], ) for filename in sources] setup( name=\"trajectory_distance_py3\", version=\"1.0.1\", author=\"<NAME>\", author_email=\"<EMAIL>\", cmdclass={'build_ext':",
"[\"traj_dist/cydist/lcss.pyx\"]), Extension(\"traj_dist.cydist.hausdorff\", [\"traj_dist/cydist/hausdorff.pyx\"]), Extension(\"traj_dist.cydist.discret_frechet\", [\"traj_dist/cydist/discret_frechet.pyx\"]), Extension(\"traj_dist.cydist.frechet\", [\"traj_dist/cydist/frechet.pyx\"]), Extension(\"traj_dist.cydist.segment_distance\", [\"traj_dist/cydist/segment_distance.pyx\"]), Extension(\"traj_dist.cydist.sowd\", [\"traj_dist/cydist/sowd.pyx\"]), Extension(\"traj_dist.cydist.erp\", [\"traj_dist/cydist/erp.pyx\"]),",
") for filename in sources] setup( name=\"trajectory_distance_py3\", version=\"1.0.1\", author=\"<NAME>\", author_email=\"<EMAIL>\", cmdclass={'build_ext': build_ext}, #",
"Extension(\"traj_dist.cydist.discret_frechet\", [\"traj_dist/cydist/discret_frechet.pyx\"]), Extension(\"traj_dist.cydist.frechet\", [\"traj_dist/cydist/frechet.pyx\"]), Extension(\"traj_dist.cydist.segment_distance\", [\"traj_dist/cydist/segment_distance.pyx\"]), Extension(\"traj_dist.cydist.sowd\", [\"traj_dist/cydist/sowd.pyx\"]), Extension(\"traj_dist.cydist.erp\", [\"traj_dist/cydist/erp.pyx\"]), Extension(\"traj_dist.cydist.edr\", [\"traj_dist/cydist/edr.pyx\"])] \"\"\"",
"setuptools import setup, find_packages from Cython.Distutils.extension import Extension from Cython.Build import cythonize, build_ext",
"import setup, find_packages from Cython.Distutils.extension import Extension from Cython.Build import cythonize, build_ext import",
"extensions = [ Extension(filename.split('.')[0].replace(os.path.sep, '.'), sources=[filename], ) for filename in sources] setup( name=\"trajectory_distance_py3\",",
"numpy import os from glob import glob \"\"\" ext_modules = [Extension(\"traj_dist.cydist.basic_geographical\", [\"traj_dist/cydist/basic_geographical.pyx\"]), Extension(\"traj_dist.cydist.basic_euclidean\",",
"Extension(\"traj_dist.cydist.sspd\", [\"traj_dist/cydist/sspd.pyx\"]), Extension(\"traj_dist.cydist.dtw\", [\"traj_dist/cydist/dtw.pyx\"]), Extension(\"traj_dist.cydist.lcss\", [\"traj_dist/cydist/lcss.pyx\"]), Extension(\"traj_dist.cydist.hausdorff\", [\"traj_dist/cydist/hausdorff.pyx\"]), Extension(\"traj_dist.cydist.discret_frechet\", [\"traj_dist/cydist/discret_frechet.pyx\"]), Extension(\"traj_dist.cydist.frechet\", [\"traj_dist/cydist/frechet.pyx\"]), Extension(\"traj_dist.cydist.segment_distance\",",
"ext_modules = [Extension(\"traj_dist.cydist.basic_geographical\", [\"traj_dist/cydist/basic_geographical.pyx\"]), Extension(\"traj_dist.cydist.basic_euclidean\", [\"traj_dist/cydist/basic_euclidean.pyx\"]), Extension(\"traj_dist.cydist.sspd\", [\"traj_dist/cydist/sspd.pyx\"]), Extension(\"traj_dist.cydist.dtw\", [\"traj_dist/cydist/dtw.pyx\"]), Extension(\"traj_dist.cydist.lcss\", [\"traj_dist/cydist/lcss.pyx\"]), Extension(\"traj_dist.cydist.hausdorff\",",
"Extension(\"traj_dist.cydist.hausdorff\", [\"traj_dist/cydist/hausdorff.pyx\"]), Extension(\"traj_dist.cydist.discret_frechet\", [\"traj_dist/cydist/discret_frechet.pyx\"]), Extension(\"traj_dist.cydist.frechet\", [\"traj_dist/cydist/frechet.pyx\"]), Extension(\"traj_dist.cydist.segment_distance\", [\"traj_dist/cydist/segment_distance.pyx\"]), Extension(\"traj_dist.cydist.sowd\", [\"traj_dist/cydist/sowd.pyx\"]), Extension(\"traj_dist.cydist.erp\", [\"traj_dist/cydist/erp.pyx\"]), Extension(\"traj_dist.cydist.edr\",",
"ext_modules=ext_modules, ext_modules=extensions, include_dirs=[numpy.get_include()], install_requires=[\"numpy>=1.14.0\", \"cython>=0.27.3\", \"shapely>=1.6.3\", \"geohash2>=1.1\", 'pandas>=0.20.3', 'scipy>=0.19.1'], description=\"Distance to compare 2D-trajectories",
"= [Extension(\"traj_dist.cydist.basic_geographical\", [\"traj_dist/cydist/basic_geographical.pyx\"]), Extension(\"traj_dist.cydist.basic_euclidean\", [\"traj_dist/cydist/basic_euclidean.pyx\"]), Extension(\"traj_dist.cydist.sspd\", [\"traj_dist/cydist/sspd.pyx\"]), Extension(\"traj_dist.cydist.dtw\", [\"traj_dist/cydist/dtw.pyx\"]), Extension(\"traj_dist.cydist.lcss\", [\"traj_dist/cydist/lcss.pyx\"]), Extension(\"traj_dist.cydist.hausdorff\", [\"traj_dist/cydist/hausdorff.pyx\"]),",
"Extension(\"traj_dist.cydist.dtw\", [\"traj_dist/cydist/dtw.pyx\"]), Extension(\"traj_dist.cydist.lcss\", [\"traj_dist/cydist/lcss.pyx\"]), Extension(\"traj_dist.cydist.hausdorff\", [\"traj_dist/cydist/hausdorff.pyx\"]), Extension(\"traj_dist.cydist.discret_frechet\", [\"traj_dist/cydist/discret_frechet.pyx\"]), Extension(\"traj_dist.cydist.frechet\", [\"traj_dist/cydist/frechet.pyx\"]), Extension(\"traj_dist.cydist.segment_distance\", [\"traj_dist/cydist/segment_distance.pyx\"]), Extension(\"traj_dist.cydist.sowd\",",
"ext_modules=extensions, include_dirs=[numpy.get_include()], install_requires=[\"numpy>=1.14.0\", \"cython>=0.27.3\", \"shapely>=1.6.3\", \"geohash2>=1.1\", 'pandas>=0.20.3', 'scipy>=0.19.1'], description=\"Distance to compare 2D-trajectories in",
"from glob import glob \"\"\" ext_modules = [Extension(\"traj_dist.cydist.basic_geographical\", [\"traj_dist/cydist/basic_geographical.pyx\"]), Extension(\"traj_dist.cydist.basic_euclidean\", [\"traj_dist/cydist/basic_euclidean.pyx\"]), Extension(\"traj_dist.cydist.sspd\", [\"traj_dist/cydist/sspd.pyx\"]),",
"Extension from Cython.Build import cythonize, build_ext import numpy import os from glob import",
"import cythonize, build_ext import numpy import os from glob import glob \"\"\" ext_modules",
"[\"traj_dist/cydist/edr.pyx\"])] \"\"\" sources = glob('traj_dist/cydist/*.pyx') extensions = [ Extension(filename.split('.')[0].replace(os.path.sep, '.'), sources=[filename], ) for",
"[\"traj_dist/cydist/discret_frechet.pyx\"]), Extension(\"traj_dist.cydist.frechet\", [\"traj_dist/cydist/frechet.pyx\"]), Extension(\"traj_dist.cydist.segment_distance\", [\"traj_dist/cydist/segment_distance.pyx\"]), Extension(\"traj_dist.cydist.sowd\", [\"traj_dist/cydist/sowd.pyx\"]), Extension(\"traj_dist.cydist.erp\", [\"traj_dist/cydist/erp.pyx\"]), Extension(\"traj_dist.cydist.edr\", [\"traj_dist/cydist/edr.pyx\"])] \"\"\" sources",
"# ext_modules=ext_modules, ext_modules=extensions, include_dirs=[numpy.get_include()], install_requires=[\"numpy>=1.14.0\", \"cython>=0.27.3\", \"shapely>=1.6.3\", \"geohash2>=1.1\", 'pandas>=0.20.3', 'scipy>=0.19.1'], description=\"Distance to compare",
"Extension(\"traj_dist.cydist.frechet\", [\"traj_dist/cydist/frechet.pyx\"]), Extension(\"traj_dist.cydist.segment_distance\", [\"traj_dist/cydist/segment_distance.pyx\"]), Extension(\"traj_dist.cydist.sowd\", [\"traj_dist/cydist/sowd.pyx\"]), Extension(\"traj_dist.cydist.erp\", [\"traj_dist/cydist/erp.pyx\"]), Extension(\"traj_dist.cydist.edr\", [\"traj_dist/cydist/edr.pyx\"])] \"\"\" sources =",
"version=\"1.0.1\", author=\"<NAME>\", author_email=\"<EMAIL>\", cmdclass={'build_ext': build_ext}, # ext_modules=ext_modules, ext_modules=extensions, include_dirs=[numpy.get_include()], install_requires=[\"numpy>=1.14.0\", \"cython>=0.27.3\", \"shapely>=1.6.3\", \"geohash2>=1.1\",",
"glob import glob \"\"\" ext_modules = [Extension(\"traj_dist.cydist.basic_geographical\", [\"traj_dist/cydist/basic_geographical.pyx\"]), Extension(\"traj_dist.cydist.basic_euclidean\", [\"traj_dist/cydist/basic_euclidean.pyx\"]), Extension(\"traj_dist.cydist.sspd\", [\"traj_dist/cydist/sspd.pyx\"]), Extension(\"traj_dist.cydist.dtw\",",
"install_requires=[\"numpy>=1.14.0\", \"cython>=0.27.3\", \"shapely>=1.6.3\", \"geohash2>=1.1\", 'pandas>=0.20.3', 'scipy>=0.19.1'], description=\"Distance to compare 2D-trajectories in Cython\", packages=find_packages()",
"from setuptools import setup, find_packages from Cython.Distutils.extension import Extension from Cython.Build import cythonize,",
"for filename in sources] setup( name=\"trajectory_distance_py3\", version=\"1.0.1\", author=\"<NAME>\", author_email=\"<EMAIL>\", cmdclass={'build_ext': build_ext}, # ext_modules=ext_modules,",
"Extension(\"traj_dist.cydist.erp\", [\"traj_dist/cydist/erp.pyx\"]), Extension(\"traj_dist.cydist.edr\", [\"traj_dist/cydist/edr.pyx\"])] \"\"\" sources = glob('traj_dist/cydist/*.pyx') extensions = [ Extension(filename.split('.')[0].replace(os.path.sep, '.'),",
"Cython.Distutils.extension import Extension from Cython.Build import cythonize, build_ext import numpy import os from",
"import os from glob import glob \"\"\" ext_modules = [Extension(\"traj_dist.cydist.basic_geographical\", [\"traj_dist/cydist/basic_geographical.pyx\"]), Extension(\"traj_dist.cydist.basic_euclidean\", [\"traj_dist/cydist/basic_euclidean.pyx\"]),",
"[\"traj_dist/cydist/erp.pyx\"]), Extension(\"traj_dist.cydist.edr\", [\"traj_dist/cydist/edr.pyx\"])] \"\"\" sources = glob('traj_dist/cydist/*.pyx') extensions = [ Extension(filename.split('.')[0].replace(os.path.sep, '.'), sources=[filename],",
"[\"traj_dist/cydist/sowd.pyx\"]), Extension(\"traj_dist.cydist.erp\", [\"traj_dist/cydist/erp.pyx\"]), Extension(\"traj_dist.cydist.edr\", [\"traj_dist/cydist/edr.pyx\"])] \"\"\" sources = glob('traj_dist/cydist/*.pyx') extensions = [ Extension(filename.split('.')[0].replace(os.path.sep,",
"name=\"trajectory_distance_py3\", version=\"1.0.1\", author=\"<NAME>\", author_email=\"<EMAIL>\", cmdclass={'build_ext': build_ext}, # ext_modules=ext_modules, ext_modules=extensions, include_dirs=[numpy.get_include()], install_requires=[\"numpy>=1.14.0\", \"cython>=0.27.3\", \"shapely>=1.6.3\",",
"in sources] setup( name=\"trajectory_distance_py3\", version=\"1.0.1\", author=\"<NAME>\", author_email=\"<EMAIL>\", cmdclass={'build_ext': build_ext}, # ext_modules=ext_modules, ext_modules=extensions, include_dirs=[numpy.get_include()],",
"author_email=\"<EMAIL>\", cmdclass={'build_ext': build_ext}, # ext_modules=ext_modules, ext_modules=extensions, include_dirs=[numpy.get_include()], install_requires=[\"numpy>=1.14.0\", \"cython>=0.27.3\", \"shapely>=1.6.3\", \"geohash2>=1.1\", 'pandas>=0.20.3', 'scipy>=0.19.1'],",
"setup, find_packages from Cython.Distutils.extension import Extension from Cython.Build import cythonize, build_ext import numpy",
"Extension(\"traj_dist.cydist.segment_distance\", [\"traj_dist/cydist/segment_distance.pyx\"]), Extension(\"traj_dist.cydist.sowd\", [\"traj_dist/cydist/sowd.pyx\"]), Extension(\"traj_dist.cydist.erp\", [\"traj_dist/cydist/erp.pyx\"]), Extension(\"traj_dist.cydist.edr\", [\"traj_dist/cydist/edr.pyx\"])] \"\"\" sources = glob('traj_dist/cydist/*.pyx') extensions",
"[\"traj_dist/cydist/dtw.pyx\"]), Extension(\"traj_dist.cydist.lcss\", [\"traj_dist/cydist/lcss.pyx\"]), Extension(\"traj_dist.cydist.hausdorff\", [\"traj_dist/cydist/hausdorff.pyx\"]), Extension(\"traj_dist.cydist.discret_frechet\", [\"traj_dist/cydist/discret_frechet.pyx\"]), Extension(\"traj_dist.cydist.frechet\", [\"traj_dist/cydist/frechet.pyx\"]), Extension(\"traj_dist.cydist.segment_distance\", [\"traj_dist/cydist/segment_distance.pyx\"]), Extension(\"traj_dist.cydist.sowd\", [\"traj_dist/cydist/sowd.pyx\"]),",
"find_packages from Cython.Distutils.extension import Extension from Cython.Build import cythonize, build_ext import numpy import",
"Cython.Build import cythonize, build_ext import numpy import os from glob import glob \"\"\"",
"build_ext import numpy import os from glob import glob \"\"\" ext_modules = [Extension(\"traj_dist.cydist.basic_geographical\",",
"[\"traj_dist/cydist/hausdorff.pyx\"]), Extension(\"traj_dist.cydist.discret_frechet\", [\"traj_dist/cydist/discret_frechet.pyx\"]), Extension(\"traj_dist.cydist.frechet\", [\"traj_dist/cydist/frechet.pyx\"]), Extension(\"traj_dist.cydist.segment_distance\", [\"traj_dist/cydist/segment_distance.pyx\"]), Extension(\"traj_dist.cydist.sowd\", [\"traj_dist/cydist/sowd.pyx\"]), Extension(\"traj_dist.cydist.erp\", [\"traj_dist/cydist/erp.pyx\"]), Extension(\"traj_dist.cydist.edr\", [\"traj_dist/cydist/edr.pyx\"])]",
"Extension(\"traj_dist.cydist.sowd\", [\"traj_dist/cydist/sowd.pyx\"]), Extension(\"traj_dist.cydist.erp\", [\"traj_dist/cydist/erp.pyx\"]), Extension(\"traj_dist.cydist.edr\", [\"traj_dist/cydist/edr.pyx\"])] \"\"\" sources = glob('traj_dist/cydist/*.pyx') extensions = [",
"[ Extension(filename.split('.')[0].replace(os.path.sep, '.'), sources=[filename], ) for filename in sources] setup( name=\"trajectory_distance_py3\", version=\"1.0.1\", author=\"<NAME>\",",
"Extension(\"traj_dist.cydist.basic_euclidean\", [\"traj_dist/cydist/basic_euclidean.pyx\"]), Extension(\"traj_dist.cydist.sspd\", [\"traj_dist/cydist/sspd.pyx\"]), Extension(\"traj_dist.cydist.dtw\", [\"traj_dist/cydist/dtw.pyx\"]), Extension(\"traj_dist.cydist.lcss\", [\"traj_dist/cydist/lcss.pyx\"]), Extension(\"traj_dist.cydist.hausdorff\", [\"traj_dist/cydist/hausdorff.pyx\"]), Extension(\"traj_dist.cydist.discret_frechet\", [\"traj_dist/cydist/discret_frechet.pyx\"]), Extension(\"traj_dist.cydist.frechet\","
] |
[
"do professor abaixo salario = float(input('Qual o salário do funcionário R$ ')) if",
"de aumento será de {}'.format(nome, sal15 + salario)) # Neu codigo acima, do",
"100) if (salario >= 1250) * (10 * 10 / 100): print('O novo",
"salário do funcionário(a) {} com 15% de aumento será de {}'.format(nome, sal15 +",
"{}'.format(nome, sal10 + salario)) else: print('O novo salário do funcionário(a) {} com 15%",
"(salario >= 1250) * (10 * 10 / 100): print('O novo salário do",
"salario <= 1250: novo = salario + (salario * 15 / 100) else:",
"')) sal10 = (salario * 10 / 100) sal15 = (salario * 15",
"float(input('Qual o salário do funcionário R$ ')) sal10 = (salario * 10 /",
"novo salário do funcionário(a) {} com 10% de aumento será de {}'.format(nome, sal10",
"sal15 = (salario * 15 / 100) if (salario >= 1250) * (10",
"o nome do funcioário: ')) salario = float(input('Qual o salário do funcionário R$",
"10 / 100): print('O novo salário do funcionário(a) {} com 10% de aumento",
"salario + (salario * 15 / 100) else: novo = salario + (salario",
"+ salario)) # Neu codigo acima, do professor abaixo salario = float(input('Qual o",
"15 / 100) else: novo = salario + (salario * 10 / 100)",
"100) else: novo = salario + (salario * 10 / 100) print('Quem ganhava",
"* 10 / 100) sal15 = (salario * 15 / 100) if (salario",
"1250) * (10 * 10 / 100): print('O novo salário do funcionário(a) {}",
"15% de aumento será de {}'.format(nome, sal15 + salario)) # Neu codigo acima,",
"')) salario = float(input('Qual o salário do funcionário R$ ')) sal10 = (salario",
"1250: novo = salario + (salario * 15 / 100) else: novo =",
"do funcioário: ')) salario = float(input('Qual o salário do funcionário R$ ')) sal10",
"10 / 100) sal15 = (salario * 15 / 100) if (salario >=",
"if (salario >= 1250) * (10 * 10 / 100): print('O novo salário",
"salário do funcionário R$ ')) if salario <= 1250: novo = salario +",
"o salário do funcionário R$ ')) if salario <= 1250: novo = salario",
"abaixo salario = float(input('Qual o salário do funcionário R$ ')) if salario <=",
"+ (salario * 15 / 100) else: novo = salario + (salario *",
"novo salário do funcionário(a) {} com 15% de aumento será de {}'.format(nome, sal15",
"salario)) else: print('O novo salário do funcionário(a) {} com 15% de aumento será",
"salario + (salario * 10 / 100) print('Quem ganhava R${:.2f} passa a ganhar",
"= salario + (salario * 10 / 100) print('Quem ganhava R${:.2f} passa a",
"funcionário(a) {} com 10% de aumento será de {}'.format(nome, sal10 + salario)) else:",
"salario = float(input('Qual o salário do funcionário R$ ')) if salario <= 1250:",
"de {}'.format(nome, sal15 + salario)) # Neu codigo acima, do professor abaixo salario",
"str(input('Digite o nome do funcioário: ')) salario = float(input('Qual o salário do funcionário",
"professor abaixo salario = float(input('Qual o salário do funcionário R$ ')) if salario",
"{} com 15% de aumento será de {}'.format(nome, sal15 + salario)) # Neu",
"será de {}'.format(nome, sal15 + salario)) # Neu codigo acima, do professor abaixo",
"= float(input('Qual o salário do funcionário R$ ')) if salario <= 1250: novo",
"float(input('Qual o salário do funcionário R$ ')) if salario <= 1250: novo =",
"funcionário(a) {} com 15% de aumento será de {}'.format(nome, sal15 + salario)) #",
"de aumento será de {}'.format(nome, sal10 + salario)) else: print('O novo salário do",
"será de {}'.format(nome, sal10 + salario)) else: print('O novo salário do funcionário(a) {}",
"de {}'.format(nome, sal10 + salario)) else: print('O novo salário do funcionário(a) {} com",
"o salário do funcionário R$ ')) sal10 = (salario * 10 / 100)",
"(salario * 10 / 100) sal15 = (salario * 15 / 100) if",
"do funcionário R$ ')) if salario <= 1250: novo = salario + (salario",
"= salario + (salario * 15 / 100) else: novo = salario +",
"+ (salario * 10 / 100) print('Quem ganhava R${:.2f} passa a ganhar R${:.2f}",
"* 10 / 100): print('O novo salário do funcionário(a) {} com 10% de",
">= 1250) * (10 * 10 / 100): print('O novo salário do funcionário(a)",
"novo = salario + (salario * 15 / 100) else: novo = salario",
"{}'.format(nome, sal15 + salario)) # Neu codigo acima, do professor abaixo salario =",
"{} com 10% de aumento será de {}'.format(nome, sal10 + salario)) else: print('O",
"R$ ')) if salario <= 1250: novo = salario + (salario * 15",
"(salario * 10 / 100) print('Quem ganhava R${:.2f} passa a ganhar R${:.2f} agora'.format(salario,",
"100) sal15 = (salario * 15 / 100) if (salario >= 1250) *",
"aumento será de {}'.format(nome, sal15 + salario)) # Neu codigo acima, do professor",
"do funcionário(a) {} com 10% de aumento será de {}'.format(nome, sal10 + salario))",
"do funcionário(a) {} com 15% de aumento será de {}'.format(nome, sal15 + salario))",
"funcionário R$ ')) if salario <= 1250: novo = salario + (salario *",
"+ salario)) else: print('O novo salário do funcionário(a) {} com 15% de aumento",
"com 15% de aumento será de {}'.format(nome, sal15 + salario)) # Neu codigo",
"(10 * 10 / 100): print('O novo salário do funcionário(a) {} com 10%",
"funcionário R$ ')) sal10 = (salario * 10 / 100) sal15 = (salario",
"100): print('O novo salário do funcionário(a) {} com 10% de aumento será de",
"10% de aumento será de {}'.format(nome, sal10 + salario)) else: print('O novo salário",
"aumento será de {}'.format(nome, sal10 + salario)) else: print('O novo salário do funcionário(a)",
"/ 100): print('O novo salário do funcionário(a) {} com 10% de aumento será",
"(salario * 15 / 100) else: novo = salario + (salario * 10",
"sal10 = (salario * 10 / 100) sal15 = (salario * 15 /",
"print('O novo salário do funcionário(a) {} com 10% de aumento será de {}'.format(nome,",
"else: novo = salario + (salario * 10 / 100) print('Quem ganhava R${:.2f}",
"sal10 + salario)) else: print('O novo salário do funcionário(a) {} com 15% de",
"salário do funcionário(a) {} com 10% de aumento será de {}'.format(nome, sal10 +",
"com 10% de aumento será de {}'.format(nome, sal10 + salario)) else: print('O novo",
"(salario * 15 / 100) if (salario >= 1250) * (10 * 10",
"if salario <= 1250: novo = salario + (salario * 15 / 100)",
"* 10 / 100) print('Quem ganhava R${:.2f} passa a ganhar R${:.2f} agora'.format(salario, novo))",
"15 / 100) if (salario >= 1250) * (10 * 10 / 100):",
"codigo acima, do professor abaixo salario = float(input('Qual o salário do funcionário R$",
"')) if salario <= 1250: novo = salario + (salario * 15 /",
"do funcionário R$ ')) sal10 = (salario * 10 / 100) sal15 =",
"salario = float(input('Qual o salário do funcionário R$ ')) sal10 = (salario *",
"funcioário: ')) salario = float(input('Qual o salário do funcionário R$ ')) sal10 =",
"# Neu codigo acima, do professor abaixo salario = float(input('Qual o salário do",
"= str(input('Digite o nome do funcioário: ')) salario = float(input('Qual o salário do",
"novo = salario + (salario * 10 / 100) print('Quem ganhava R${:.2f} passa",
"= (salario * 15 / 100) if (salario >= 1250) * (10 *",
"= (salario * 10 / 100) sal15 = (salario * 15 / 100)",
"R$ ')) sal10 = (salario * 10 / 100) sal15 = (salario *",
"salario)) # Neu codigo acima, do professor abaixo salario = float(input('Qual o salário",
"= float(input('Qual o salário do funcionário R$ ')) sal10 = (salario * 10",
"/ 100) if (salario >= 1250) * (10 * 10 / 100): print('O",
"* (10 * 10 / 100): print('O novo salário do funcionário(a) {} com",
"print('O novo salário do funcionário(a) {} com 15% de aumento será de {}'.format(nome,",
"acima, do professor abaixo salario = float(input('Qual o salário do funcionário R$ '))",
"* 15 / 100) if (salario >= 1250) * (10 * 10 /",
"<= 1250: novo = salario + (salario * 15 / 100) else: novo",
"* 15 / 100) else: novo = salario + (salario * 10 /",
"salário do funcionário R$ ')) sal10 = (salario * 10 / 100) sal15",
"nome do funcioário: ')) salario = float(input('Qual o salário do funcionário R$ '))",
"else: print('O novo salário do funcionário(a) {} com 15% de aumento será de",
"Neu codigo acima, do professor abaixo salario = float(input('Qual o salário do funcionário",
"sal15 + salario)) # Neu codigo acima, do professor abaixo salario = float(input('Qual",
"nome = str(input('Digite o nome do funcioário: ')) salario = float(input('Qual o salário",
"/ 100) else: novo = salario + (salario * 10 / 100) print('Quem",
"/ 100) sal15 = (salario * 15 / 100) if (salario >= 1250)"
] |
[
"def load(h): h.add(_.Unsigned('numberOfCategories', 1)) with h.list('categories'): for i in range(0, h.get_l('numberOfCategories')): h.add(_.Codetable('categoryType', 1,",
"h.get_l('numberOfCategories')): h.add(_.Codetable('categoryType', 1, \"4.91.table\", _.Get('masterDir'), _.Get('localDir'))) h.add(_.Unsigned('codeFigure', 1)) h.add(_.Unsigned('scaleFactorOfLowerLimit', 1)) h.add(_.Unsigned('scaledValueOfLowerLimit', 4)) h.add(_.Unsigned('scaleFactorOfUpperLimit',",
"for i in range(0, h.get_l('numberOfCategories')): h.add(_.Codetable('categoryType', 1, \"4.91.table\", _.Get('masterDir'), _.Get('localDir'))) h.add(_.Unsigned('codeFigure', 1)) h.add(_.Unsigned('scaleFactorOfLowerLimit',",
"1, \"4.91.table\", _.Get('masterDir'), _.Get('localDir'))) h.add(_.Unsigned('codeFigure', 1)) h.add(_.Unsigned('scaleFactorOfLowerLimit', 1)) h.add(_.Unsigned('scaledValueOfLowerLimit', 4)) h.add(_.Unsigned('scaleFactorOfUpperLimit', 1)) h.add(_.Unsigned('scaledValueOfUpperLimit',",
"_ def load(h): h.add(_.Unsigned('numberOfCategories', 1)) with h.list('categories'): for i in range(0, h.get_l('numberOfCategories')): h.add(_.Codetable('categoryType',",
"load(h): h.add(_.Unsigned('numberOfCategories', 1)) with h.list('categories'): for i in range(0, h.get_l('numberOfCategories')): h.add(_.Codetable('categoryType', 1, \"4.91.table\",",
"range(0, h.get_l('numberOfCategories')): h.add(_.Codetable('categoryType', 1, \"4.91.table\", _.Get('masterDir'), _.Get('localDir'))) h.add(_.Unsigned('codeFigure', 1)) h.add(_.Unsigned('scaleFactorOfLowerLimit', 1)) h.add(_.Unsigned('scaledValueOfLowerLimit', 4))",
"with h.list('categories'): for i in range(0, h.get_l('numberOfCategories')): h.add(_.Codetable('categoryType', 1, \"4.91.table\", _.Get('masterDir'), _.Get('localDir'))) h.add(_.Unsigned('codeFigure',",
"h.add(_.Codetable('categoryType', 1, \"4.91.table\", _.Get('masterDir'), _.Get('localDir'))) h.add(_.Unsigned('codeFigure', 1)) h.add(_.Unsigned('scaleFactorOfLowerLimit', 1)) h.add(_.Unsigned('scaledValueOfLowerLimit', 4)) h.add(_.Unsigned('scaleFactorOfUpperLimit', 1))",
"h.add(_.Unsigned('numberOfCategories', 1)) with h.list('categories'): for i in range(0, h.get_l('numberOfCategories')): h.add(_.Codetable('categoryType', 1, \"4.91.table\", _.Get('masterDir'),",
"h.list('categories'): for i in range(0, h.get_l('numberOfCategories')): h.add(_.Codetable('categoryType', 1, \"4.91.table\", _.Get('masterDir'), _.Get('localDir'))) h.add(_.Unsigned('codeFigure', 1))",
"in range(0, h.get_l('numberOfCategories')): h.add(_.Codetable('categoryType', 1, \"4.91.table\", _.Get('masterDir'), _.Get('localDir'))) h.add(_.Unsigned('codeFigure', 1)) h.add(_.Unsigned('scaleFactorOfLowerLimit', 1)) h.add(_.Unsigned('scaledValueOfLowerLimit',",
"1)) with h.list('categories'): for i in range(0, h.get_l('numberOfCategories')): h.add(_.Codetable('categoryType', 1, \"4.91.table\", _.Get('masterDir'), _.Get('localDir')))",
"i in range(0, h.get_l('numberOfCategories')): h.add(_.Codetable('categoryType', 1, \"4.91.table\", _.Get('masterDir'), _.Get('localDir'))) h.add(_.Unsigned('codeFigure', 1)) h.add(_.Unsigned('scaleFactorOfLowerLimit', 1))",
"\"4.91.table\", _.Get('masterDir'), _.Get('localDir'))) h.add(_.Unsigned('codeFigure', 1)) h.add(_.Unsigned('scaleFactorOfLowerLimit', 1)) h.add(_.Unsigned('scaledValueOfLowerLimit', 4)) h.add(_.Unsigned('scaleFactorOfUpperLimit', 1)) h.add(_.Unsigned('scaledValueOfUpperLimit', 4))",
"as _ def load(h): h.add(_.Unsigned('numberOfCategories', 1)) with h.list('categories'): for i in range(0, h.get_l('numberOfCategories')):",
"import pyeccodes.accessors as _ def load(h): h.add(_.Unsigned('numberOfCategories', 1)) with h.list('categories'): for i in",
"pyeccodes.accessors as _ def load(h): h.add(_.Unsigned('numberOfCategories', 1)) with h.list('categories'): for i in range(0,"
] |
[
"Phylo.read(sys.argv[1], \"newick\") for idx, clade in enumerate(tree.find_clades()): if clade.name: clade.name = '%d\\t%s' %",
"clade.name # else: # clade.name = str(idx) # names = clade.name # print",
"idx, clade in enumerate(tree.find_clades()): if clade.name: clade.name = '%d\\t%s' % (idx, clade.name) print",
"= '%d\\t%s' % (idx, clade.name) print clade.name # else: # clade.name = str(idx)",
"{} tree = Phylo.read(sys.argv[1], \"newick\") for idx, clade in enumerate(tree.find_clades()): if clade.name: clade.name",
"'%d\\t%s' % (idx, clade.name) print clade.name # else: # clade.name = str(idx) #",
"names = {} tree = Phylo.read(sys.argv[1], \"newick\") for idx, clade in enumerate(tree.find_clades()): if",
"clade.name: clade.name = '%d\\t%s' % (idx, clade.name) print clade.name # else: # clade.name",
"<filename>genbank-fan/nwk_tree_parser.py import sys from Bio import Phylo names = {} tree = Phylo.read(sys.argv[1],",
"import sys from Bio import Phylo names = {} tree = Phylo.read(sys.argv[1], \"newick\")",
"Phylo names = {} tree = Phylo.read(sys.argv[1], \"newick\") for idx, clade in enumerate(tree.find_clades()):",
"import Phylo names = {} tree = Phylo.read(sys.argv[1], \"newick\") for idx, clade in",
"clade in enumerate(tree.find_clades()): if clade.name: clade.name = '%d\\t%s' % (idx, clade.name) print clade.name",
"(idx, clade.name) print clade.name # else: # clade.name = str(idx) # names =",
"in enumerate(tree.find_clades()): if clade.name: clade.name = '%d\\t%s' % (idx, clade.name) print clade.name #",
"clade.name) print clade.name # else: # clade.name = str(idx) # names = clade.name",
"# else: # clade.name = str(idx) # names = clade.name # print names",
"if clade.name: clade.name = '%d\\t%s' % (idx, clade.name) print clade.name # else: #",
"Bio import Phylo names = {} tree = Phylo.read(sys.argv[1], \"newick\") for idx, clade",
"sys from Bio import Phylo names = {} tree = Phylo.read(sys.argv[1], \"newick\") for",
"clade.name = '%d\\t%s' % (idx, clade.name) print clade.name # else: # clade.name =",
"= Phylo.read(sys.argv[1], \"newick\") for idx, clade in enumerate(tree.find_clades()): if clade.name: clade.name = '%d\\t%s'",
"enumerate(tree.find_clades()): if clade.name: clade.name = '%d\\t%s' % (idx, clade.name) print clade.name # else:",
"for idx, clade in enumerate(tree.find_clades()): if clade.name: clade.name = '%d\\t%s' % (idx, clade.name)",
"\"newick\") for idx, clade in enumerate(tree.find_clades()): if clade.name: clade.name = '%d\\t%s' % (idx,",
"= {} tree = Phylo.read(sys.argv[1], \"newick\") for idx, clade in enumerate(tree.find_clades()): if clade.name:",
"tree = Phylo.read(sys.argv[1], \"newick\") for idx, clade in enumerate(tree.find_clades()): if clade.name: clade.name =",
"from Bio import Phylo names = {} tree = Phylo.read(sys.argv[1], \"newick\") for idx,",
"print clade.name # else: # clade.name = str(idx) # names = clade.name #",
"% (idx, clade.name) print clade.name # else: # clade.name = str(idx) # names"
] |
[
"3 def reconnect(self, force=False): if force == True: self.mq_connected = False while not",
"__init__(self,host, port,root,authentication,user,password): self.mq_host = host self.mq_port = port self.mq_root = root self.mq_authentication =",
"= \"\" def __init__(self,host, port,root,authentication,user,password): self.mq_host = host self.mq_port = port self.mq_root =",
"self.mqttc.connect(host=self.mq_host,port=int(self.mq_port)) threading.Thread(target=self.startloop).start() self.mq_connected = True print(\"Connected to MQ!\") except Exception as ex: print(\"Could",
"{0}\".format(ex)) print(\"Trying again in 5 seconds...\") time.sleep(5) self.notify() def startloop(self): self.mqttc.loop_forever() def on_message(self,mqttc,",
"host self.mq_port = port self.mq_root = root self.mq_authentication = authentication self.mq_user = user",
"threading import time class HomieMQTT: \"\"\" Class for controlling Homie Convention. The Homie",
"self.mq_user = user self.mq_password = password #self.reconnect(force=True) threading.Thread(target=self.reconnect,args=(True,)).start() # try: # self.mqttc =",
"self.notify() def startloop(self): self.mqttc.loop_forever() def on_message(self,mqttc, obj, msg,): #INITIAL VALUES payload = msg.payload.decode(\"utf-8\")",
"to MQ: {0}\".format(ex)) print(\"Trying again in 5 seconds...\") time.sleep(5) self.notify() def startloop(self): self.mqttc.loop_forever()",
"# except: #print(\"No connection...\") # temp = 3 def reconnect(self, force=False): if force",
"True: self.mq_connected = False while not self.mq_connected: try: self.mqttc = mqtt.Client(client_id='Homie Adapter') if",
"temp[0] self.homie_device = temp[1] self.messages[topic] = payload def on_connect(self, client, userdata, flags, rc):",
"self.mq_authentication == True: self.mqttc.username_pw_set(username=self.mq_user, password=self.mq_password) self.mqttc.on_connect = self.on_connect self.mqttc.on_message = self.on_message self.mqttc.connect(host=self.mq_host,port=int(self.mq_port)) threading.Thread(target=self.startloop).start()",
"# threading.Thread(target=self.startloop).start() # except: #print(\"No connection...\") # temp = 3 def reconnect(self, force=False):",
"Homie Convention follows the following format: root/system name/device class (optional)/zone (optional)/device name/capability/command \"\"\"",
"self.mqttc.username_pw_set(username=self.mq_user, password=self.mq_password) self.mqttc.on_connect = self.on_connect self.mqttc.on_message = self.on_message self.mqttc.connect(host=self.mq_host,port=int(self.mq_port)) threading.Thread(target=self.startloop).start() self.mq_connected = True",
"msg.payload.decode(\"utf-8\") topic = str(msg.topic) temp = topic.split(\"/\") self.homie_parent = temp[0] self.homie_device = temp[1]",
"name/device class (optional)/zone (optional)/device name/capability/command \"\"\" DEVICES = [] messages = {} homie_parent",
"port,root,authentication,user,password): self.mq_host = host self.mq_port = port self.mq_root = root self.mq_authentication = authentication",
"threading.Thread(target=self.startloop).start() # except: #print(\"No connection...\") # temp = 3 def reconnect(self, force=False): if",
"int(port), 60) # self.mqttc.subscribe(root+\"/#\", 0) # threading.Thread(target=self.startloop).start() # except: #print(\"No connection...\") # temp",
"to MQ!\") except Exception as ex: print(\"Could not connect to MQ: {0}\".format(ex)) print(\"Trying",
"self.mqttc.connect(host, int(port), 60) # self.mqttc.subscribe(root+\"/#\", 0) # threading.Thread(target=self.startloop).start() # except: #print(\"No connection...\") #",
"Exception as ex: print(\"Could not connect to MQ: {0}\".format(ex)) print(\"Trying again in 5",
"payload = msg.payload.decode(\"utf-8\") topic = str(msg.topic) temp = topic.split(\"/\") self.homie_parent = temp[0] self.homie_device",
"self.messages[topic] = payload def on_connect(self, client, userdata, flags, rc): self.mqttc.subscribe(self.mq_root+\"/#\", 0) def notify(self):",
"60) # self.mqttc.subscribe(root+\"/#\", 0) # threading.Thread(target=self.startloop).start() # except: #print(\"No connection...\") # temp =",
"self.mqttc.on_message = self.on_message # print(\"Homey discovery started.....\") # self.mqttc.connect(host, int(port), 60) # self.mqttc.subscribe(root+\"/#\",",
"= str(msg.topic) temp = topic.split(\"/\") self.homie_parent = temp[0] self.homie_device = temp[1] self.messages[topic] =",
"[] messages = {} homie_parent = \"\" homie_device = \"\" def __init__(self,host, port,root,authentication,user,password):",
"== True: # self.mqttc.username_pw_set(username=user, password=password) # self.mqttc.on_message = self.on_message # print(\"Homey discovery started.....\")",
"mqtt import threading import time class HomieMQTT: \"\"\" Class for controlling Homie Convention.",
"import threading import time class HomieMQTT: \"\"\" Class for controlling Homie Convention. The",
"class (optional)/zone (optional)/device name/capability/command \"\"\" DEVICES = [] messages = {} homie_parent =",
"self.mq_root = root self.mq_authentication = authentication self.mq_user = user self.mq_password = password #self.reconnect(force=True)",
"temp = 3 def reconnect(self, force=False): if force == True: self.mq_connected = False",
"authentication == True: # self.mqttc.username_pw_set(username=user, password=password) # self.mqttc.on_message = self.on_message # print(\"Homey discovery",
"obj, msg,): #INITIAL VALUES payload = msg.payload.decode(\"utf-8\") topic = str(msg.topic) temp = topic.split(\"/\")",
"self.mq_connected: try: self.mqttc = mqtt.Client(client_id='Homie Adapter') if self.mq_authentication == True: self.mqttc.username_pw_set(username=self.mq_user, password=self.mq_password) self.mqttc.on_connect",
"as ex: print(\"Could not connect to MQ: {0}\".format(ex)) print(\"Trying again in 5 seconds...\")",
"self.on_message self.mqttc.connect(host=self.mq_host,port=int(self.mq_port)) threading.Thread(target=self.startloop).start() self.mq_connected = True print(\"Connected to MQ!\") except Exception as ex:",
"rc): self.mqttc.subscribe(self.mq_root+\"/#\", 0) def notify(self): #self.reconnect() threading.Thread(target=self.reconnect,args=(False,)).start() def getmessages(self): #print(self.mq_root) temp = self.mq_root.split(\"/\")",
"print(\"Could not connect to MQ: {0}\".format(ex)) print(\"Trying again in 5 seconds...\") time.sleep(5) self.notify()",
"def on_connect(self, client, userdata, flags, rc): self.mqttc.subscribe(self.mq_root+\"/#\", 0) def notify(self): #self.reconnect() threading.Thread(target=self.reconnect,args=(False,)).start() def",
"def notify(self): #self.reconnect() threading.Thread(target=self.reconnect,args=(False,)).start() def getmessages(self): #print(self.mq_root) temp = self.mq_root.split(\"/\") self.homie_parent = temp[0]",
"not connect to MQ: {0}\".format(ex)) print(\"Trying again in 5 seconds...\") time.sleep(5) self.notify() def",
"startloop(self): self.mqttc.loop_forever() def on_message(self,mqttc, obj, msg,): #INITIAL VALUES payload = msg.payload.decode(\"utf-8\") topic =",
"# try: # self.mqttc = mqtt.Client() # if authentication == True: # self.mqttc.username_pw_set(username=user,",
"# print(\"Homey discovery started.....\") # self.mqttc.connect(host, int(port), 60) # self.mqttc.subscribe(root+\"/#\", 0) # threading.Thread(target=self.startloop).start()",
"topic.split(\"/\") self.homie_parent = temp[0] self.homie_device = temp[1] self.messages[topic] = payload def on_connect(self, client,",
"#self.reconnect(force=True) threading.Thread(target=self.reconnect,args=(True,)).start() # try: # self.mqttc = mqtt.Client() # if authentication == True:",
"Class for controlling Homie Convention. The Homie Convention follows the following format: root/system",
"controlling Homie Convention. The Homie Convention follows the following format: root/system name/device class",
"following format: root/system name/device class (optional)/zone (optional)/device name/capability/command \"\"\" DEVICES = [] messages",
"threading.Thread(target=self.reconnect,args=(False,)).start() def getmessages(self): #print(self.mq_root) temp = self.mq_root.split(\"/\") self.homie_parent = temp[0] self.homie_device = temp[1]",
"== True: self.mq_connected = False while not self.mq_connected: try: self.mqttc = mqtt.Client(client_id='Homie Adapter')",
"0) def notify(self): #self.reconnect() threading.Thread(target=self.reconnect,args=(False,)).start() def getmessages(self): #print(self.mq_root) temp = self.mq_root.split(\"/\") self.homie_parent =",
"\"\"\" Class for controlling Homie Convention. The Homie Convention follows the following format:",
"DEVICES = [] messages = {} homie_parent = \"\" homie_device = \"\" def",
"= port self.mq_root = root self.mq_authentication = authentication self.mq_user = user self.mq_password =",
"(optional)/zone (optional)/device name/capability/command \"\"\" DEVICES = [] messages = {} homie_parent = \"\"",
"client, userdata, flags, rc): self.mqttc.subscribe(self.mq_root+\"/#\", 0) def notify(self): #self.reconnect() threading.Thread(target=self.reconnect,args=(False,)).start() def getmessages(self): #print(self.mq_root)",
"self.homie_device = temp[1] self.messages[topic] = payload def on_connect(self, client, userdata, flags, rc): self.mqttc.subscribe(self.mq_root+\"/#\",",
"# self.mqttc.username_pw_set(username=user, password=password) # self.mqttc.on_message = self.on_message # print(\"Homey discovery started.....\") # self.mqttc.connect(host,",
"in 5 seconds...\") time.sleep(5) self.notify() def startloop(self): self.mqttc.loop_forever() def on_message(self,mqttc, obj, msg,): #INITIAL",
"if self.mq_authentication == True: self.mqttc.username_pw_set(username=self.mq_user, password=self.mq_password) self.mqttc.on_connect = self.on_connect self.mqttc.on_message = self.on_message self.mqttc.connect(host=self.mq_host,port=int(self.mq_port))",
"try: self.mqttc = mqtt.Client(client_id='Homie Adapter') if self.mq_authentication == True: self.mqttc.username_pw_set(username=self.mq_user, password=self.mq_password) self.mqttc.on_connect =",
"homie_device = \"\" def __init__(self,host, port,root,authentication,user,password): self.mq_host = host self.mq_port = port self.mq_root",
"ex: print(\"Could not connect to MQ: {0}\".format(ex)) print(\"Trying again in 5 seconds...\") time.sleep(5)",
"temp = topic.split(\"/\") self.homie_parent = temp[0] self.homie_device = temp[1] self.messages[topic] = payload def",
"# self.mqttc.subscribe(root+\"/#\", 0) # threading.Thread(target=self.startloop).start() # except: #print(\"No connection...\") # temp = 3",
"discovery started.....\") # self.mqttc.connect(host, int(port), 60) # self.mqttc.subscribe(root+\"/#\", 0) # threading.Thread(target=self.startloop).start() # except:",
"The Homie Convention follows the following format: root/system name/device class (optional)/zone (optional)/device name/capability/command",
"format: root/system name/device class (optional)/zone (optional)/device name/capability/command \"\"\" DEVICES = [] messages =",
"msg,): #INITIAL VALUES payload = msg.payload.decode(\"utf-8\") topic = str(msg.topic) temp = topic.split(\"/\") self.homie_parent",
"self.mqttc.username_pw_set(username=user, password=password) # self.mqttc.on_message = self.on_message # print(\"Homey discovery started.....\") # self.mqttc.connect(host, int(port),",
"self.mqttc.subscribe(root+\"/#\", 0) # threading.Thread(target=self.startloop).start() # except: #print(\"No connection...\") # temp = 3 def",
"while not self.mq_connected: try: self.mqttc = mqtt.Client(client_id='Homie Adapter') if self.mq_authentication == True: self.mqttc.username_pw_set(username=self.mq_user,",
"self.on_connect self.mqttc.on_message = self.on_message self.mqttc.connect(host=self.mq_host,port=int(self.mq_port)) threading.Thread(target=self.startloop).start() self.mq_connected = True print(\"Connected to MQ!\") except",
"# self.mqttc.on_message = self.on_message # print(\"Homey discovery started.....\") # self.mqttc.connect(host, int(port), 60) #",
"= user self.mq_password = password #self.reconnect(force=True) threading.Thread(target=self.reconnect,args=(True,)).start() # try: # self.mqttc = mqtt.Client()",
"mqtt.Client() # if authentication == True: # self.mqttc.username_pw_set(username=user, password=password) # self.mqttc.on_message = self.on_message",
"# self.mqttc.connect(host, int(port), 60) # self.mqttc.subscribe(root+\"/#\", 0) # threading.Thread(target=self.startloop).start() # except: #print(\"No connection...\")",
"#print(self.mq_root) temp = self.mq_root.split(\"/\") self.homie_parent = temp[0] self.homie_device = temp[1] return self.messages, self.homie_parent,self.homie_device",
"def startloop(self): self.mqttc.loop_forever() def on_message(self,mqttc, obj, msg,): #INITIAL VALUES payload = msg.payload.decode(\"utf-8\") topic",
"Adapter') if self.mq_authentication == True: self.mqttc.username_pw_set(username=self.mq_user, password=self.mq_password) self.mqttc.on_connect = self.on_connect self.mqttc.on_message = self.on_message",
"password #self.reconnect(force=True) threading.Thread(target=self.reconnect,args=(True,)).start() # try: # self.mqttc = mqtt.Client() # if authentication ==",
"topic = str(msg.topic) temp = topic.split(\"/\") self.homie_parent = temp[0] self.homie_device = temp[1] self.messages[topic]",
"self.homie_parent = temp[0] self.homie_device = temp[1] self.messages[topic] = payload def on_connect(self, client, userdata,",
"= temp[0] self.homie_device = temp[1] self.messages[topic] = payload def on_connect(self, client, userdata, flags,",
"HomieMQTT: \"\"\" Class for controlling Homie Convention. The Homie Convention follows the following",
"time class HomieMQTT: \"\"\" Class for controlling Homie Convention. The Homie Convention follows",
"user self.mq_password = password #self.reconnect(force=True) threading.Thread(target=self.reconnect,args=(True,)).start() # try: # self.mqttc = mqtt.Client() #",
"self.mq_authentication = authentication self.mq_user = user self.mq_password = password #self.reconnect(force=True) threading.Thread(target=self.reconnect,args=(True,)).start() # try:",
"payload def on_connect(self, client, userdata, flags, rc): self.mqttc.subscribe(self.mq_root+\"/#\", 0) def notify(self): #self.reconnect() threading.Thread(target=self.reconnect,args=(False,)).start()",
"{} homie_parent = \"\" homie_device = \"\" def __init__(self,host, port,root,authentication,user,password): self.mq_host = host",
"except Exception as ex: print(\"Could not connect to MQ: {0}\".format(ex)) print(\"Trying again in",
"self.mqttc = mqtt.Client(client_id='Homie Adapter') if self.mq_authentication == True: self.mqttc.username_pw_set(username=self.mq_user, password=self.mq_password) self.mqttc.on_connect = self.on_connect",
"#INITIAL VALUES payload = msg.payload.decode(\"utf-8\") topic = str(msg.topic) temp = topic.split(\"/\") self.homie_parent =",
"= {} homie_parent = \"\" homie_device = \"\" def __init__(self,host, port,root,authentication,user,password): self.mq_host =",
"self.mqttc.subscribe(self.mq_root+\"/#\", 0) def notify(self): #self.reconnect() threading.Thread(target=self.reconnect,args=(False,)).start() def getmessages(self): #print(self.mq_root) temp = self.mq_root.split(\"/\") self.homie_parent",
"if force == True: self.mq_connected = False while not self.mq_connected: try: self.mqttc =",
"mqtt.Client(client_id='Homie Adapter') if self.mq_authentication == True: self.mqttc.username_pw_set(username=self.mq_user, password=self.mq_password) self.mqttc.on_connect = self.on_connect self.mqttc.on_message =",
"#print(\"No connection...\") # temp = 3 def reconnect(self, force=False): if force == True:",
"= password #self.reconnect(force=True) threading.Thread(target=self.reconnect,args=(True,)).start() # try: # self.mqttc = mqtt.Client() # if authentication",
"import paho.mqtt.client as mqtt import threading import time class HomieMQTT: \"\"\" Class for",
"connect to MQ: {0}\".format(ex)) print(\"Trying again in 5 seconds...\") time.sleep(5) self.notify() def startloop(self):",
"try: # self.mqttc = mqtt.Client() # if authentication == True: # self.mqttc.username_pw_set(username=user, password=password)",
"= payload def on_connect(self, client, userdata, flags, rc): self.mqttc.subscribe(self.mq_root+\"/#\", 0) def notify(self): #self.reconnect()",
"getmessages(self): #print(self.mq_root) temp = self.mq_root.split(\"/\") self.homie_parent = temp[0] self.homie_device = temp[1] return self.messages,",
"def on_message(self,mqttc, obj, msg,): #INITIAL VALUES payload = msg.payload.decode(\"utf-8\") topic = str(msg.topic) temp",
"#self.reconnect() threading.Thread(target=self.reconnect,args=(False,)).start() def getmessages(self): #print(self.mq_root) temp = self.mq_root.split(\"/\") self.homie_parent = temp[0] self.homie_device =",
"0) # threading.Thread(target=self.startloop).start() # except: #print(\"No connection...\") # temp = 3 def reconnect(self,",
"messages = {} homie_parent = \"\" homie_device = \"\" def __init__(self,host, port,root,authentication,user,password): self.mq_host",
"Convention. The Homie Convention follows the following format: root/system name/device class (optional)/zone (optional)/device",
"Convention follows the following format: root/system name/device class (optional)/zone (optional)/device name/capability/command \"\"\" DEVICES",
"password=password) # self.mqttc.on_message = self.on_message # print(\"Homey discovery started.....\") # self.mqttc.connect(host, int(port), 60)",
"self.mq_connected = True print(\"Connected to MQ!\") except Exception as ex: print(\"Could not connect",
"self.mqttc.loop_forever() def on_message(self,mqttc, obj, msg,): #INITIAL VALUES payload = msg.payload.decode(\"utf-8\") topic = str(msg.topic)",
"force == True: self.mq_connected = False while not self.mq_connected: try: self.mqttc = mqtt.Client(client_id='Homie",
"# self.mqttc = mqtt.Client() # if authentication == True: # self.mqttc.username_pw_set(username=user, password=password) #",
"threading.Thread(target=self.startloop).start() self.mq_connected = True print(\"Connected to MQ!\") except Exception as ex: print(\"Could not",
"userdata, flags, rc): self.mqttc.subscribe(self.mq_root+\"/#\", 0) def notify(self): #self.reconnect() threading.Thread(target=self.reconnect,args=(False,)).start() def getmessages(self): #print(self.mq_root) temp",
"notify(self): #self.reconnect() threading.Thread(target=self.reconnect,args=(False,)).start() def getmessages(self): #print(self.mq_root) temp = self.mq_root.split(\"/\") self.homie_parent = temp[0] self.homie_device",
"self.mq_password = password #self.reconnect(force=True) threading.Thread(target=self.reconnect,args=(True,)).start() # try: # self.mqttc = mqtt.Client() # if",
"root self.mq_authentication = authentication self.mq_user = user self.mq_password = password #self.reconnect(force=True) threading.Thread(target=self.reconnect,args=(True,)).start() #",
"print(\"Connected to MQ!\") except Exception as ex: print(\"Could not connect to MQ: {0}\".format(ex))",
"homie_parent = \"\" homie_device = \"\" def __init__(self,host, port,root,authentication,user,password): self.mq_host = host self.mq_port",
"if authentication == True: # self.mqttc.username_pw_set(username=user, password=password) # self.mqttc.on_message = self.on_message # print(\"Homey",
"= host self.mq_port = port self.mq_root = root self.mq_authentication = authentication self.mq_user =",
"= root self.mq_authentication = authentication self.mq_user = user self.mq_password = password #self.reconnect(force=True) threading.Thread(target=self.reconnect,args=(True,)).start()",
"str(msg.topic) temp = topic.split(\"/\") self.homie_parent = temp[0] self.homie_device = temp[1] self.messages[topic] = payload",
"self.mq_connected = False while not self.mq_connected: try: self.mqttc = mqtt.Client(client_id='Homie Adapter') if self.mq_authentication",
"flags, rc): self.mqttc.subscribe(self.mq_root+\"/#\", 0) def notify(self): #self.reconnect() threading.Thread(target=self.reconnect,args=(False,)).start() def getmessages(self): #print(self.mq_root) temp =",
"self.mqttc.on_connect = self.on_connect self.mqttc.on_message = self.on_message self.mqttc.connect(host=self.mq_host,port=int(self.mq_port)) threading.Thread(target=self.startloop).start() self.mq_connected = True print(\"Connected to",
"= self.on_connect self.mqttc.on_message = self.on_message self.mqttc.connect(host=self.mq_host,port=int(self.mq_port)) threading.Thread(target=self.startloop).start() self.mq_connected = True print(\"Connected to MQ!\")",
"on_connect(self, client, userdata, flags, rc): self.mqttc.subscribe(self.mq_root+\"/#\", 0) def notify(self): #self.reconnect() threading.Thread(target=self.reconnect,args=(False,)).start() def getmessages(self):",
"5 seconds...\") time.sleep(5) self.notify() def startloop(self): self.mqttc.loop_forever() def on_message(self,mqttc, obj, msg,): #INITIAL VALUES",
"port self.mq_root = root self.mq_authentication = authentication self.mq_user = user self.mq_password = password",
"Homie Convention. The Homie Convention follows the following format: root/system name/device class (optional)/zone",
"def reconnect(self, force=False): if force == True: self.mq_connected = False while not self.mq_connected:",
"= False while not self.mq_connected: try: self.mqttc = mqtt.Client(client_id='Homie Adapter') if self.mq_authentication ==",
"== True: self.mqttc.username_pw_set(username=self.mq_user, password=self.mq_password) self.mqttc.on_connect = self.on_connect self.mqttc.on_message = self.on_message self.mqttc.connect(host=self.mq_host,port=int(self.mq_port)) threading.Thread(target=self.startloop).start() self.mq_connected",
"= True print(\"Connected to MQ!\") except Exception as ex: print(\"Could not connect to",
"def getmessages(self): #print(self.mq_root) temp = self.mq_root.split(\"/\") self.homie_parent = temp[0] self.homie_device = temp[1] return",
"# if authentication == True: # self.mqttc.username_pw_set(username=user, password=password) # self.mqttc.on_message = self.on_message #",
"VALUES payload = msg.payload.decode(\"utf-8\") topic = str(msg.topic) temp = topic.split(\"/\") self.homie_parent = temp[0]",
"authentication self.mq_user = user self.mq_password = password #self.reconnect(force=True) threading.Thread(target=self.reconnect,args=(True,)).start() # try: # self.mqttc",
"self.mq_host = host self.mq_port = port self.mq_root = root self.mq_authentication = authentication self.mq_user",
"= authentication self.mq_user = user self.mq_password = password #self.reconnect(force=True) threading.Thread(target=self.reconnect,args=(True,)).start() # try: #",
"force=False): if force == True: self.mq_connected = False while not self.mq_connected: try: self.mqttc",
"time.sleep(5) self.notify() def startloop(self): self.mqttc.loop_forever() def on_message(self,mqttc, obj, msg,): #INITIAL VALUES payload =",
"import time class HomieMQTT: \"\"\" Class for controlling Homie Convention. The Homie Convention",
"True print(\"Connected to MQ!\") except Exception as ex: print(\"Could not connect to MQ:",
"connection...\") # temp = 3 def reconnect(self, force=False): if force == True: self.mq_connected",
"= mqtt.Client(client_id='Homie Adapter') if self.mq_authentication == True: self.mqttc.username_pw_set(username=self.mq_user, password=self.mq_password) self.mqttc.on_connect = self.on_connect self.mqttc.on_message",
"= msg.payload.decode(\"utf-8\") topic = str(msg.topic) temp = topic.split(\"/\") self.homie_parent = temp[0] self.homie_device =",
"follows the following format: root/system name/device class (optional)/zone (optional)/device name/capability/command \"\"\" DEVICES =",
"= mqtt.Client() # if authentication == True: # self.mqttc.username_pw_set(username=user, password=password) # self.mqttc.on_message =",
"again in 5 seconds...\") time.sleep(5) self.notify() def startloop(self): self.mqttc.loop_forever() def on_message(self,mqttc, obj, msg,):",
"(optional)/device name/capability/command \"\"\" DEVICES = [] messages = {} homie_parent = \"\" homie_device",
"root/system name/device class (optional)/zone (optional)/device name/capability/command \"\"\" DEVICES = [] messages = {}",
"print(\"Homey discovery started.....\") # self.mqttc.connect(host, int(port), 60) # self.mqttc.subscribe(root+\"/#\", 0) # threading.Thread(target=self.startloop).start() #",
"= self.on_message self.mqttc.connect(host=self.mq_host,port=int(self.mq_port)) threading.Thread(target=self.startloop).start() self.mq_connected = True print(\"Connected to MQ!\") except Exception as",
"= topic.split(\"/\") self.homie_parent = temp[0] self.homie_device = temp[1] self.messages[topic] = payload def on_connect(self,",
"\"\" def __init__(self,host, port,root,authentication,user,password): self.mq_host = host self.mq_port = port self.mq_root = root",
"True: self.mqttc.username_pw_set(username=self.mq_user, password=self.mq_password) self.mqttc.on_connect = self.on_connect self.mqttc.on_message = self.on_message self.mqttc.connect(host=self.mq_host,port=int(self.mq_port)) threading.Thread(target=self.startloop).start() self.mq_connected =",
"= temp[1] self.messages[topic] = payload def on_connect(self, client, userdata, flags, rc): self.mqttc.subscribe(self.mq_root+\"/#\", 0)",
"def __init__(self,host, port,root,authentication,user,password): self.mq_host = host self.mq_port = port self.mq_root = root self.mq_authentication",
"except: #print(\"No connection...\") # temp = 3 def reconnect(self, force=False): if force ==",
"as mqtt import threading import time class HomieMQTT: \"\"\" Class for controlling Homie",
"the following format: root/system name/device class (optional)/zone (optional)/device name/capability/command \"\"\" DEVICES = []",
"= [] messages = {} homie_parent = \"\" homie_device = \"\" def __init__(self,host,",
"= \"\" homie_device = \"\" def __init__(self,host, port,root,authentication,user,password): self.mq_host = host self.mq_port =",
"print(\"Trying again in 5 seconds...\") time.sleep(5) self.notify() def startloop(self): self.mqttc.loop_forever() def on_message(self,mqttc, obj,",
"started.....\") # self.mqttc.connect(host, int(port), 60) # self.mqttc.subscribe(root+\"/#\", 0) # threading.Thread(target=self.startloop).start() # except: #print(\"No",
"self.mqttc = mqtt.Client() # if authentication == True: # self.mqttc.username_pw_set(username=user, password=password) # self.mqttc.on_message",
"= 3 def reconnect(self, force=False): if force == True: self.mq_connected = False while",
"temp[1] self.messages[topic] = payload def on_connect(self, client, userdata, flags, rc): self.mqttc.subscribe(self.mq_root+\"/#\", 0) def",
"reconnect(self, force=False): if force == True: self.mq_connected = False while not self.mq_connected: try:",
"class HomieMQTT: \"\"\" Class for controlling Homie Convention. The Homie Convention follows the",
"= self.on_message # print(\"Homey discovery started.....\") # self.mqttc.connect(host, int(port), 60) # self.mqttc.subscribe(root+\"/#\", 0)",
"seconds...\") time.sleep(5) self.notify() def startloop(self): self.mqttc.loop_forever() def on_message(self,mqttc, obj, msg,): #INITIAL VALUES payload",
"False while not self.mq_connected: try: self.mqttc = mqtt.Client(client_id='Homie Adapter') if self.mq_authentication == True:",
"paho.mqtt.client as mqtt import threading import time class HomieMQTT: \"\"\" Class for controlling",
"\"\" homie_device = \"\" def __init__(self,host, port,root,authentication,user,password): self.mq_host = host self.mq_port = port",
"password=self.mq_password) self.mqttc.on_connect = self.on_connect self.mqttc.on_message = self.on_message self.mqttc.connect(host=self.mq_host,port=int(self.mq_port)) threading.Thread(target=self.startloop).start() self.mq_connected = True print(\"Connected",
"<gh_stars>0 import paho.mqtt.client as mqtt import threading import time class HomieMQTT: \"\"\" Class",
"MQ!\") except Exception as ex: print(\"Could not connect to MQ: {0}\".format(ex)) print(\"Trying again",
"self.mq_port = port self.mq_root = root self.mq_authentication = authentication self.mq_user = user self.mq_password",
"not self.mq_connected: try: self.mqttc = mqtt.Client(client_id='Homie Adapter') if self.mq_authentication == True: self.mqttc.username_pw_set(username=self.mq_user, password=self.mq_password)",
"MQ: {0}\".format(ex)) print(\"Trying again in 5 seconds...\") time.sleep(5) self.notify() def startloop(self): self.mqttc.loop_forever() def",
"on_message(self,mqttc, obj, msg,): #INITIAL VALUES payload = msg.payload.decode(\"utf-8\") topic = str(msg.topic) temp =",
"self.on_message # print(\"Homey discovery started.....\") # self.mqttc.connect(host, int(port), 60) # self.mqttc.subscribe(root+\"/#\", 0) #",
"threading.Thread(target=self.reconnect,args=(True,)).start() # try: # self.mqttc = mqtt.Client() # if authentication == True: #",
"\"\"\" DEVICES = [] messages = {} homie_parent = \"\" homie_device = \"\"",
"True: # self.mqttc.username_pw_set(username=user, password=password) # self.mqttc.on_message = self.on_message # print(\"Homey discovery started.....\") #",
"for controlling Homie Convention. The Homie Convention follows the following format: root/system name/device",
"self.mqttc.on_message = self.on_message self.mqttc.connect(host=self.mq_host,port=int(self.mq_port)) threading.Thread(target=self.startloop).start() self.mq_connected = True print(\"Connected to MQ!\") except Exception",
"# temp = 3 def reconnect(self, force=False): if force == True: self.mq_connected =",
"name/capability/command \"\"\" DEVICES = [] messages = {} homie_parent = \"\" homie_device ="
] |
[
"1 while lowerBound <= upperBound: m = (lowerBound + upperBound) // 2 if",
"> A[i+1] > ... > A[A.length - 1]. # # Example 1: #",
"10000 # 0 <= A[i] <= 10^6 # A is a mountain, as",
"A[1] < ... A[i-1] < A[i] > A[i+1] > ... > A[A.length -",
"an array that is definitely a mountain, return any i such that A[0]",
"... A[i-1] < A[i] > A[i+1] > ... > A[A.length - 1]. #",
"> ... > A[A.length - 1] # Given an array that is definitely",
"A[A.length - 1]. # # Example 1: # # Input: [0,1,0] # Output:",
"... > A[A.length - 1]. # # Example 1: # # Input: [0,1,0]",
"Output: 1 # Note: # # 3 <= A.length <= 10000 # 0",
"above. class Solution: def peakIndexInMountainArray(self, A): \"\"\" :type A: List[int] :rtype: int \"\"\"",
"mountain, return any i such that A[0] < A[1] < ... A[i-1] <",
"as defined above. class Solution: def peakIndexInMountainArray(self, A): \"\"\" :type A: List[int] :rtype:",
"= 0 upperBound = len(A) - 1 while lowerBound <= upperBound: m =",
"Binary Search # Let's call an array A a mountain if the following",
"# There exists some 0 < i < A.length - 1 such that",
"Let's call an array A a mountain if the following properties hold: #",
"Input: [0,2,1,0] # Output: 1 # Note: # # 3 <= A.length <=",
"Example 1: # # Input: [0,1,0] # Output: 1 # Example 2: #",
"upperBound) // 2 if A[m] > A[m-1] and A[m] > A[m+1]: return m",
"1 # Note: # # 3 <= A.length <= 10000 # 0 <=",
"exists some 0 < i < A.length - 1 such that A[0] <",
">= 3 # There exists some 0 < i < A.length - 1",
"A[0] < A[1] < ... A[i-1] < A[i] > A[i+1] > ... >",
":rtype: int \"\"\" lowerBound = 0 upperBound = len(A) - 1 while lowerBound",
"A: List[int] :rtype: int \"\"\" lowerBound = 0 upperBound = len(A) - 1",
"Search # Let's call an array A a mountain if the following properties",
"> ... > A[A.length - 1]. # # Example 1: # # Input:",
"# # Example 1: # # Input: [0,1,0] # Output: 1 # Example",
"class Solution: def peakIndexInMountainArray(self, A): \"\"\" :type A: List[int] :rtype: int \"\"\" lowerBound",
"- 1]. # # Example 1: # # Input: [0,1,0] # Output: 1",
"i < A.length - 1 such that A[0] < A[1] < ... A[i-1]",
"i such that A[0] < A[1] < ... A[i-1] < A[i] > A[i+1]",
"# Input: [0,1,0] # Output: 1 # Example 2: # # Input: [0,2,1,0]",
"[0,2,1,0] # Output: 1 # Note: # # 3 <= A.length <= 10000",
"< A.length - 1 such that A[0] < A[1] < ... A[i-1] <",
"# A.length >= 3 # There exists some 0 < i < A.length",
"There exists some 0 < i < A.length - 1 such that A[0]",
"and A[m] > A[m+1]: return m if A[m] < A[m+1]: lowerBound = m",
"< A[1] < ... A[i-1] < A[i] > A[i+1] > ... > A[A.length",
"// 2 if A[m] > A[m-1] and A[m] > A[m+1]: return m if",
"is definitely a mountain, return any i such that A[0] < A[1] <",
"# # A.length >= 3 # There exists some 0 < i <",
"A.length >= 3 # There exists some 0 < i < A.length -",
"- 1 such that A[0] < A[1] < ... A[i-1] < A[i] >",
"Example 2: # # Input: [0,2,1,0] # Output: 1 # Note: # #",
"upperBound = len(A) - 1 while lowerBound <= upperBound: m = (lowerBound +",
"len(A) - 1 while lowerBound <= upperBound: m = (lowerBound + upperBound) //",
"call an array A a mountain if the following properties hold: # #",
"A[m] > A[m+1]: return m if A[m] < A[m+1]: lowerBound = m else:",
"(lowerBound + upperBound) // 2 if A[m] > A[m-1] and A[m] > A[m+1]:",
"< ... A[i-1] < A[i] > A[i+1] > ... > A[A.length - 1].",
"<= 10000 # 0 <= A[i] <= 10^6 # A is a mountain,",
"Note: # # 3 <= A.length <= 10000 # 0 <= A[i] <=",
"is a mountain, as defined above. class Solution: def peakIndexInMountainArray(self, A): \"\"\" :type",
"\"\"\" :type A: List[int] :rtype: int \"\"\" lowerBound = 0 upperBound = len(A)",
"A is a mountain, as defined above. class Solution: def peakIndexInMountainArray(self, A): \"\"\"",
"defined above. class Solution: def peakIndexInMountainArray(self, A): \"\"\" :type A: List[int] :rtype: int",
"if A[m] > A[m-1] and A[m] > A[m+1]: return m if A[m] <",
"A a mountain if the following properties hold: # # A.length >= 3",
"1 such that A[0] < A[1] < ... A[i-1] < A[i] > A[i+1]",
"mountain, as defined above. class Solution: def peakIndexInMountainArray(self, A): \"\"\" :type A: List[int]",
"A[i] > A[i+1] > ... > A[A.length - 1]. # # Example 1:",
"... A[i-1] < A[i] > A[i+1] > ... > A[A.length - 1] #",
"A[m-1] and A[m] > A[m+1]: return m if A[m] < A[m+1]: lowerBound =",
"2 if A[m] > A[m-1] and A[m] > A[m+1]: return m if A[m]",
"10^6 # A is a mountain, as defined above. class Solution: def peakIndexInMountainArray(self,",
"array A a mountain if the following properties hold: # # A.length >=",
"m if A[m] < A[m+1]: lowerBound = m else: upperBound = m return",
"# Binary Search # Let's call an array A a mountain if the",
"> A[A.length - 1] # Given an array that is definitely a mountain,",
"List[int] :rtype: int \"\"\" lowerBound = 0 upperBound = len(A) - 1 while",
"an array A a mountain if the following properties hold: # # A.length",
"# Let's call an array A a mountain if the following properties hold:",
"A[i] <= 10^6 # A is a mountain, as defined above. class Solution:",
"return m if A[m] < A[m+1]: lowerBound = m else: upperBound = m",
"if A[m] < A[m+1]: lowerBound = m else: upperBound = m return m",
"\"\"\" lowerBound = 0 upperBound = len(A) - 1 while lowerBound <= upperBound:",
"> A[A.length - 1]. # # Example 1: # # Input: [0,1,0] #",
"hold: # # A.length >= 3 # There exists some 0 < i",
"while lowerBound <= upperBound: m = (lowerBound + upperBound) // 2 if A[m]",
"a mountain if the following properties hold: # # A.length >= 3 #",
"A[i] > A[i+1] > ... > A[A.length - 1] # Given an array",
"# 3 <= A.length <= 10000 # 0 <= A[i] <= 10^6 #",
"A.length - 1 such that A[0] < A[1] < ... A[i-1] < A[i]",
"if the following properties hold: # # A.length >= 3 # There exists",
"some 0 < i < A.length - 1 such that A[0] < A[1]",
"> A[m+1]: return m if A[m] < A[m+1]: lowerBound = m else: upperBound",
"Output: 1 # Example 2: # # Input: [0,2,1,0] # Output: 1 #",
"array that is definitely a mountain, return any i such that A[0] <",
"return any i such that A[0] < A[1] < ... A[i-1] < A[i]",
"# A is a mountain, as defined above. class Solution: def peakIndexInMountainArray(self, A):",
"1 # Example 2: # # Input: [0,2,1,0] # Output: 1 # Note:",
"A[i-1] < A[i] > A[i+1] > ... > A[A.length - 1]. # #",
"# # Input: [0,2,1,0] # Output: 1 # Note: # # 3 <=",
"1] # Given an array that is definitely a mountain, return any i",
"<= upperBound: m = (lowerBound + upperBound) // 2 if A[m] > A[m-1]",
"1]. # # Example 1: # # Input: [0,1,0] # Output: 1 #",
"< A[i] > A[i+1] > ... > A[A.length - 1]. # # Example",
"a mountain, as defined above. class Solution: def peakIndexInMountainArray(self, A): \"\"\" :type A:",
"= len(A) - 1 while lowerBound <= upperBound: m = (lowerBound + upperBound)",
"- 1] # Given an array that is definitely a mountain, return any",
"A[m+1]: return m if A[m] < A[m+1]: lowerBound = m else: upperBound =",
"0 upperBound = len(A) - 1 while lowerBound <= upperBound: m = (lowerBound",
"# Output: 1 # Note: # # 3 <= A.length <= 10000 #",
"# Output: 1 # Example 2: # # Input: [0,2,1,0] # Output: 1",
"A.length <= 10000 # 0 <= A[i] <= 10^6 # A is a",
"int \"\"\" lowerBound = 0 upperBound = len(A) - 1 while lowerBound <=",
"> A[m-1] and A[m] > A[m+1]: return m if A[m] < A[m+1]: lowerBound",
"A[A.length - 1] # Given an array that is definitely a mountain, return",
"# 0 <= A[i] <= 10^6 # A is a mountain, as defined",
"- 1 while lowerBound <= upperBound: m = (lowerBound + upperBound) // 2",
"the following properties hold: # # A.length >= 3 # There exists some",
"# # Input: [0,1,0] # Output: 1 # Example 2: # # Input:",
"< A[i] > A[i+1] > ... > A[A.length - 1] # Given an",
"Solution: def peakIndexInMountainArray(self, A): \"\"\" :type A: List[int] :rtype: int \"\"\" lowerBound =",
"that A[0] < A[1] < ... A[i-1] < A[i] > A[i+1] > ...",
"> A[i+1] > ... > A[A.length - 1] # Given an array that",
"A[i+1] > ... > A[A.length - 1] # Given an array that is",
"Given an array that is definitely a mountain, return any i such that",
"that is definitely a mountain, return any i such that A[0] < A[1]",
"<= A[i] <= 10^6 # A is a mountain, as defined above. class",
"# Given an array that is definitely a mountain, return any i such",
"< ... A[i-1] < A[i] > A[i+1] > ... > A[A.length - 1]",
"0 <= A[i] <= 10^6 # A is a mountain, as defined above.",
"following properties hold: # # A.length >= 3 # There exists some 0",
"0 < i < A.length - 1 such that A[0] < A[1] <",
"# Note: # # 3 <= A.length <= 10000 # 0 <= A[i]",
"1: # # Input: [0,1,0] # Output: 1 # Example 2: # #",
"A[i-1] < A[i] > A[i+1] > ... > A[A.length - 1] # Given",
"<= A.length <= 10000 # 0 <= A[i] <= 10^6 # A is",
"any i such that A[0] < A[1] < ... A[i-1] < A[i] >",
"2: # # Input: [0,2,1,0] # Output: 1 # Note: # # 3",
"# Input: [0,2,1,0] # Output: 1 # Note: # # 3 <= A.length",
"a mountain, return any i such that A[0] < A[1] < ... A[i-1]",
"# Example 2: # # Input: [0,2,1,0] # Output: 1 # Note: #",
"3 # There exists some 0 < i < A.length - 1 such",
"m = (lowerBound + upperBound) // 2 if A[m] > A[m-1] and A[m]",
"+ upperBound) // 2 if A[m] > A[m-1] and A[m] > A[m+1]: return",
"Input: [0,1,0] # Output: 1 # Example 2: # # Input: [0,2,1,0] #",
"definitely a mountain, return any i such that A[0] < A[1] < ...",
"A[m] > A[m-1] and A[m] > A[m+1]: return m if A[m] < A[m+1]:",
"lowerBound <= upperBound: m = (lowerBound + upperBound) // 2 if A[m] >",
"mountain if the following properties hold: # # A.length >= 3 # There",
"# # 3 <= A.length <= 10000 # 0 <= A[i] <= 10^6",
"def peakIndexInMountainArray(self, A): \"\"\" :type A: List[int] :rtype: int \"\"\" lowerBound = 0",
"3 <= A.length <= 10000 # 0 <= A[i] <= 10^6 # A",
"lowerBound = 0 upperBound = len(A) - 1 while lowerBound <= upperBound: m",
"A[i+1] > ... > A[A.length - 1]. # # Example 1: # #",
"# Example 1: # # Input: [0,1,0] # Output: 1 # Example 2:",
"... > A[A.length - 1] # Given an array that is definitely a",
"such that A[0] < A[1] < ... A[i-1] < A[i] > A[i+1] >",
"properties hold: # # A.length >= 3 # There exists some 0 <",
":type A: List[int] :rtype: int \"\"\" lowerBound = 0 upperBound = len(A) -",
"peakIndexInMountainArray(self, A): \"\"\" :type A: List[int] :rtype: int \"\"\" lowerBound = 0 upperBound",
"<= 10^6 # A is a mountain, as defined above. class Solution: def",
"[0,1,0] # Output: 1 # Example 2: # # Input: [0,2,1,0] # Output:",
"upperBound: m = (lowerBound + upperBound) // 2 if A[m] > A[m-1] and",
"= (lowerBound + upperBound) // 2 if A[m] > A[m-1] and A[m] >",
"A): \"\"\" :type A: List[int] :rtype: int \"\"\" lowerBound = 0 upperBound =",
"< i < A.length - 1 such that A[0] < A[1] < ..."
] |
[
"url=\"http://api.openweathermap.org/data/2.5/weather\" params=dict(q=place,appid=self[\"DEFAULT\"][\"API_KEY\"]) r = requests.get(url,params) r.raise_for_status() return r.json() # Write an example main",
"inherits from ConfigParser, and expects to find a file api.config containing a variable",
"Get and print London wind speeds wc = WeatherChecker() weather = wc.get_weather_at_place(\"London,UK\") print(weather)",
"r.raise_for_status() return r.json() # Write an example main routine in a __name__ ==",
"the file exists & contains the relevant info try: self[\"DEFAULT\"][\"API_KEY\"] except KeyError as",
"key read from an configuration file. ''' import requests import configparser class WeatherChecker(configparser.ConfigParser):",
"Read the config file super().__init__() self.read('api.config') # Make sure that the file exists",
"directory.\") def get_weather_at_place(self,place): ''' A wrapper to the OpenWeatherMap API. :param place: the",
"requests import configparser class WeatherChecker(configparser.ConfigParser): ''' Basic class to check weather at a",
"to nesta-toolbox.official.modules. The specific example here simply demonstrates how to check the weather",
"''' A wrapper to the OpenWeatherMap API. :param place: the query string for",
"exists & contains the relevant info try: self[\"DEFAULT\"][\"API_KEY\"] except KeyError as err: raise",
":param place: the query string for OpenWeatherMap :type place: str ''' url=\"http://api.openweathermap.org/data/2.5/weather\" params=dict(q=place,appid=self[\"DEFAULT\"][\"API_KEY\"])",
"self[\"DEFAULT\"][\"API_KEY\"] except KeyError as err: raise KeyError(\"Couldn't find DEFAULT.API_KEY variable in a \"",
"a file api.config containing a variable DEFAULT.API_KEY. Basic usage: wc = WeatherChecker() wc.get_weather_at_place(\"Some",
"in a \" \"file api.config in this directory.\") def get_weather_at_place(self,place): ''' A wrapper",
"parameters in self ''' # Read the config file super().__init__() self.read('api.config') # Make",
"this directory.\") def get_weather_at_place(self,place): ''' A wrapper to the OpenWeatherMap API. :param place:",
"an example of a python module. It contains all the required elements for",
"class to check weather at a given place. The class inherits from ConfigParser,",
"a variable DEFAULT.API_KEY. Basic usage: wc = WeatherChecker() wc.get_weather_at_place(\"Some place name\") ''' def",
"''' # Read the config file super().__init__() self.read('api.config') # Make sure that the",
"# Write an example main routine in a __name__ == __main__ snippet if",
"containing a variable DEFAULT.API_KEY. Basic usage: wc = WeatherChecker() wc.get_weather_at_place(\"Some place name\") '''",
"is an example of a python module. It contains all the required elements",
"here simply demonstrates how to check the weather in London, with the API",
"class inherits from ConfigParser, and expects to find a file api.config containing a",
"all the required elements for being promoted to nesta-toolbox.official.modules. The specific example here",
"Wrapper to ConfigParser, to read config file and store the parameters in self",
"except KeyError as err: raise KeyError(\"Couldn't find DEFAULT.API_KEY variable in a \" \"file",
"with the API key read from an configuration file. ''' import requests import",
"in self ''' # Read the config file super().__init__() self.read('api.config') # Make sure",
"Basic usage: wc = WeatherChecker() wc.get_weather_at_place(\"Some place name\") ''' def __init__(self): ''' Wrapper",
"self.read('api.config') # Make sure that the file exists & contains the relevant info",
"weather at a given place. The class inherits from ConfigParser, and expects to",
"''' def __init__(self): ''' Wrapper to ConfigParser, to read config file and store",
"store the parameters in self ''' # Read the config file super().__init__() self.read('api.config')",
"A wrapper to the OpenWeatherMap API. :param place: the query string for OpenWeatherMap",
"for being promoted to nesta-toolbox.official.modules. The specific example here simply demonstrates how to",
"variable in a \" \"file api.config in this directory.\") def get_weather_at_place(self,place): ''' A",
"r.json() # Write an example main routine in a __name__ == __main__ snippet",
"the query string for OpenWeatherMap :type place: str ''' url=\"http://api.openweathermap.org/data/2.5/weather\" params=dict(q=place,appid=self[\"DEFAULT\"][\"API_KEY\"]) r =",
"a given place. The class inherits from ConfigParser, and expects to find a",
"for OpenWeatherMap :type place: str ''' url=\"http://api.openweathermap.org/data/2.5/weather\" params=dict(q=place,appid=self[\"DEFAULT\"][\"API_KEY\"]) r = requests.get(url,params) r.raise_for_status() return",
"Write an example main routine in a __name__ == __main__ snippet if __name__",
"a __name__ == __main__ snippet if __name__ == \"__main__\": # Get and print",
"__init__(self): ''' Wrapper to ConfigParser, to read config file and store the parameters",
"configuration file. ''' import requests import configparser class WeatherChecker(configparser.ConfigParser): ''' Basic class to",
"WeatherChecker(configparser.ConfigParser): ''' Basic class to check weather at a given place. The class",
"API. :param place: the query string for OpenWeatherMap :type place: str ''' url=\"http://api.openweathermap.org/data/2.5/weather\"",
"place: the query string for OpenWeatherMap :type place: str ''' url=\"http://api.openweathermap.org/data/2.5/weather\" params=dict(q=place,appid=self[\"DEFAULT\"][\"API_KEY\"]) r",
"query string for OpenWeatherMap :type place: str ''' url=\"http://api.openweathermap.org/data/2.5/weather\" params=dict(q=place,appid=self[\"DEFAULT\"][\"API_KEY\"]) r = requests.get(url,params)",
"api.config in this directory.\") def get_weather_at_place(self,place): ''' A wrapper to the OpenWeatherMap API.",
"__name__ == __main__ snippet if __name__ == \"__main__\": # Get and print London",
"an configuration file. ''' import requests import configparser class WeatherChecker(configparser.ConfigParser): ''' Basic class",
"self ''' # Read the config file super().__init__() self.read('api.config') # Make sure that",
"place: str ''' url=\"http://api.openweathermap.org/data/2.5/weather\" params=dict(q=place,appid=self[\"DEFAULT\"][\"API_KEY\"]) r = requests.get(url,params) r.raise_for_status() return r.json() # Write",
"wrapper to the OpenWeatherMap API. :param place: the query string for OpenWeatherMap :type",
"ConfigParser, and expects to find a file api.config containing a variable DEFAULT.API_KEY. Basic",
"usage: wc = WeatherChecker() wc.get_weather_at_place(\"Some place name\") ''' def __init__(self): ''' Wrapper to",
"main routine in a __name__ == __main__ snippet if __name__ == \"__main__\": #",
"specific example here simply demonstrates how to check the weather in London, with",
"The class inherits from ConfigParser, and expects to find a file api.config containing",
"file. ''' import requests import configparser class WeatherChecker(configparser.ConfigParser): ''' Basic class to check",
"wc = WeatherChecker() wc.get_weather_at_place(\"Some place name\") ''' def __init__(self): ''' Wrapper to ConfigParser,",
"\"file api.config in this directory.\") def get_weather_at_place(self,place): ''' A wrapper to the OpenWeatherMap",
"demonstrates how to check the weather in London, with the API key read",
"file super().__init__() self.read('api.config') # Make sure that the file exists & contains the",
"api.config containing a variable DEFAULT.API_KEY. Basic usage: wc = WeatherChecker() wc.get_weather_at_place(\"Some place name\")",
"to read config file and store the parameters in self ''' # Read",
"file api.config containing a variable DEFAULT.API_KEY. Basic usage: wc = WeatherChecker() wc.get_weather_at_place(\"Some place",
"in this directory.\") def get_weather_at_place(self,place): ''' A wrapper to the OpenWeatherMap API. :param",
"configparser class WeatherChecker(configparser.ConfigParser): ''' Basic class to check weather at a given place.",
"\"__main__\": # Get and print London wind speeds wc = WeatherChecker() weather =",
"expects to find a file api.config containing a variable DEFAULT.API_KEY. Basic usage: wc",
"# Get and print London wind speeds wc = WeatherChecker() weather = wc.get_weather_at_place(\"London,UK\")",
"routine in a __name__ == __main__ snippet if __name__ == \"__main__\": # Get",
"file exists & contains the relevant info try: self[\"DEFAULT\"][\"API_KEY\"] except KeyError as err:",
"str ''' url=\"http://api.openweathermap.org/data/2.5/weather\" params=dict(q=place,appid=self[\"DEFAULT\"][\"API_KEY\"]) r = requests.get(url,params) r.raise_for_status() return r.json() # Write an",
"module. It contains all the required elements for being promoted to nesta-toolbox.official.modules. The",
"as err: raise KeyError(\"Couldn't find DEFAULT.API_KEY variable in a \" \"file api.config in",
"params=dict(q=place,appid=self[\"DEFAULT\"][\"API_KEY\"]) r = requests.get(url,params) r.raise_for_status() return r.json() # Write an example main routine",
"example of a python module. It contains all the required elements for being",
"API key read from an configuration file. ''' import requests import configparser class",
"contains the relevant info try: self[\"DEFAULT\"][\"API_KEY\"] except KeyError as err: raise KeyError(\"Couldn't find",
"at a given place. The class inherits from ConfigParser, and expects to find",
"= requests.get(url,params) r.raise_for_status() return r.json() # Write an example main routine in a",
"the API key read from an configuration file. ''' import requests import configparser",
"import requests import configparser class WeatherChecker(configparser.ConfigParser): ''' Basic class to check weather at",
"simply demonstrates how to check the weather in London, with the API key",
"KeyError as err: raise KeyError(\"Couldn't find DEFAULT.API_KEY variable in a \" \"file api.config",
"== \"__main__\": # Get and print London wind speeds wc = WeatherChecker() weather",
"the weather in London, with the API key read from an configuration file.",
"def __init__(self): ''' Wrapper to ConfigParser, to read config file and store the",
"''' Basic class to check weather at a given place. The class inherits",
"given place. The class inherits from ConfigParser, and expects to find a file",
"the parameters in self ''' # Read the config file super().__init__() self.read('api.config') #",
"from ConfigParser, and expects to find a file api.config containing a variable DEFAULT.API_KEY.",
"and store the parameters in self ''' # Read the config file super().__init__()",
"= WeatherChecker() wc.get_weather_at_place(\"Some place name\") ''' def __init__(self): ''' Wrapper to ConfigParser, to",
"config file and store the parameters in self ''' # Read the config",
"WeatherChecker() wc.get_weather_at_place(\"Some place name\") ''' def __init__(self): ''' Wrapper to ConfigParser, to read",
"variable DEFAULT.API_KEY. Basic usage: wc = WeatherChecker() wc.get_weather_at_place(\"Some place name\") ''' def __init__(self):",
"# Read the config file super().__init__() self.read('api.config') # Make sure that the file",
"OpenWeatherMap :type place: str ''' url=\"http://api.openweathermap.org/data/2.5/weather\" params=dict(q=place,appid=self[\"DEFAULT\"][\"API_KEY\"]) r = requests.get(url,params) r.raise_for_status() return r.json()",
"in London, with the API key read from an configuration file. ''' import",
"find DEFAULT.API_KEY variable in a \" \"file api.config in this directory.\") def get_weather_at_place(self,place):",
"def get_weather_at_place(self,place): ''' A wrapper to the OpenWeatherMap API. :param place: the query",
"required elements for being promoted to nesta-toolbox.official.modules. The specific example here simply demonstrates",
"& contains the relevant info try: self[\"DEFAULT\"][\"API_KEY\"] except KeyError as err: raise KeyError(\"Couldn't",
"r = requests.get(url,params) r.raise_for_status() return r.json() # Write an example main routine in",
"London, with the API key read from an configuration file. ''' import requests",
"a python module. It contains all the required elements for being promoted to",
"being promoted to nesta-toolbox.official.modules. The specific example here simply demonstrates how to check",
"config file super().__init__() self.read('api.config') # Make sure that the file exists & contains",
"to check weather at a given place. The class inherits from ConfigParser, and",
"example This is an example of a python module. It contains all the",
"relevant info try: self[\"DEFAULT\"][\"API_KEY\"] except KeyError as err: raise KeyError(\"Couldn't find DEFAULT.API_KEY variable",
"of a python module. It contains all the required elements for being promoted",
"__name__ == \"__main__\": # Get and print London wind speeds wc = WeatherChecker()",
"elements for being promoted to nesta-toolbox.official.modules. The specific example here simply demonstrates how",
"find a file api.config containing a variable DEFAULT.API_KEY. Basic usage: wc = WeatherChecker()",
"import configparser class WeatherChecker(configparser.ConfigParser): ''' Basic class to check weather at a given",
"place. The class inherits from ConfigParser, and expects to find a file api.config",
"info try: self[\"DEFAULT\"][\"API_KEY\"] except KeyError as err: raise KeyError(\"Couldn't find DEFAULT.API_KEY variable in",
"the OpenWeatherMap API. :param place: the query string for OpenWeatherMap :type place: str",
"to find a file api.config containing a variable DEFAULT.API_KEY. Basic usage: wc =",
"\" \"file api.config in this directory.\") def get_weather_at_place(self,place): ''' A wrapper to the",
"to the OpenWeatherMap API. :param place: the query string for OpenWeatherMap :type place:",
"how to check the weather in London, with the API key read from",
"''' import requests import configparser class WeatherChecker(configparser.ConfigParser): ''' Basic class to check weather",
"ConfigParser, to read config file and store the parameters in self ''' #",
"file and store the parameters in self ''' # Read the config file",
"string for OpenWeatherMap :type place: str ''' url=\"http://api.openweathermap.org/data/2.5/weather\" params=dict(q=place,appid=self[\"DEFAULT\"][\"API_KEY\"]) r = requests.get(url,params) r.raise_for_status()",
"# Make sure that the file exists & contains the relevant info try:",
":type place: str ''' url=\"http://api.openweathermap.org/data/2.5/weather\" params=dict(q=place,appid=self[\"DEFAULT\"][\"API_KEY\"]) r = requests.get(url,params) r.raise_for_status() return r.json() #",
"place name\") ''' def __init__(self): ''' Wrapper to ConfigParser, to read config file",
"in a __name__ == __main__ snippet if __name__ == \"__main__\": # Get and",
"DEFAULT.API_KEY variable in a \" \"file api.config in this directory.\") def get_weather_at_place(self,place): '''",
"OpenWeatherMap API. :param place: the query string for OpenWeatherMap :type place: str '''",
"contains all the required elements for being promoted to nesta-toolbox.official.modules. The specific example",
"Make sure that the file exists & contains the relevant info try: self[\"DEFAULT\"][\"API_KEY\"]",
"This is an example of a python module. It contains all the required",
"example main routine in a __name__ == __main__ snippet if __name__ == \"__main__\":",
"sure that the file exists & contains the relevant info try: self[\"DEFAULT\"][\"API_KEY\"] except",
"promoted to nesta-toolbox.official.modules. The specific example here simply demonstrates how to check the",
"python module. It contains all the required elements for being promoted to nesta-toolbox.official.modules.",
"weather in London, with the API key read from an configuration file. '''",
"example here simply demonstrates how to check the weather in London, with the",
"if __name__ == \"__main__\": # Get and print London wind speeds wc =",
"<reponame>jaklinger/nesta-toolbox<gh_stars>0 ''' example This is an example of a python module. It contains",
"read config file and store the parameters in self ''' # Read the",
"It contains all the required elements for being promoted to nesta-toolbox.official.modules. The specific",
"requests.get(url,params) r.raise_for_status() return r.json() # Write an example main routine in a __name__",
"return r.json() # Write an example main routine in a __name__ == __main__",
"KeyError(\"Couldn't find DEFAULT.API_KEY variable in a \" \"file api.config in this directory.\") def",
"to check the weather in London, with the API key read from an",
"check the weather in London, with the API key read from an configuration",
"nesta-toolbox.official.modules. The specific example here simply demonstrates how to check the weather in",
"an example main routine in a __name__ == __main__ snippet if __name__ ==",
"name\") ''' def __init__(self): ''' Wrapper to ConfigParser, to read config file and",
"a \" \"file api.config in this directory.\") def get_weather_at_place(self,place): ''' A wrapper to",
"err: raise KeyError(\"Couldn't find DEFAULT.API_KEY variable in a \" \"file api.config in this",
"raise KeyError(\"Couldn't find DEFAULT.API_KEY variable in a \" \"file api.config in this directory.\")",
"__main__ snippet if __name__ == \"__main__\": # Get and print London wind speeds",
"DEFAULT.API_KEY. Basic usage: wc = WeatherChecker() wc.get_weather_at_place(\"Some place name\") ''' def __init__(self): '''",
"the config file super().__init__() self.read('api.config') # Make sure that the file exists &",
"The specific example here simply demonstrates how to check the weather in London,",
"wc.get_weather_at_place(\"Some place name\") ''' def __init__(self): ''' Wrapper to ConfigParser, to read config",
"check weather at a given place. The class inherits from ConfigParser, and expects",
"try: self[\"DEFAULT\"][\"API_KEY\"] except KeyError as err: raise KeyError(\"Couldn't find DEFAULT.API_KEY variable in a",
"''' url=\"http://api.openweathermap.org/data/2.5/weather\" params=dict(q=place,appid=self[\"DEFAULT\"][\"API_KEY\"]) r = requests.get(url,params) r.raise_for_status() return r.json() # Write an example",
"to ConfigParser, to read config file and store the parameters in self '''",
"read from an configuration file. ''' import requests import configparser class WeatherChecker(configparser.ConfigParser): '''",
"''' example This is an example of a python module. It contains all",
"the relevant info try: self[\"DEFAULT\"][\"API_KEY\"] except KeyError as err: raise KeyError(\"Couldn't find DEFAULT.API_KEY",
"Basic class to check weather at a given place. The class inherits from",
"== __main__ snippet if __name__ == \"__main__\": # Get and print London wind",
"snippet if __name__ == \"__main__\": # Get and print London wind speeds wc",
"the required elements for being promoted to nesta-toolbox.official.modules. The specific example here simply",
"super().__init__() self.read('api.config') # Make sure that the file exists & contains the relevant",
"''' Wrapper to ConfigParser, to read config file and store the parameters in",
"get_weather_at_place(self,place): ''' A wrapper to the OpenWeatherMap API. :param place: the query string",
"and expects to find a file api.config containing a variable DEFAULT.API_KEY. Basic usage:",
"from an configuration file. ''' import requests import configparser class WeatherChecker(configparser.ConfigParser): ''' Basic",
"class WeatherChecker(configparser.ConfigParser): ''' Basic class to check weather at a given place. The",
"that the file exists & contains the relevant info try: self[\"DEFAULT\"][\"API_KEY\"] except KeyError"
] |
[
"17:44:25 ivo Exp $ \"\"\" Class to parse modes. The class is initialized",
"= \"\" plusparams = [] minparams = [] # XXX There's too much",
"Foo3 Foo4\"] for i in tests: m = mode(i) print \"String: %s\" %",
"minmode(self, index): return self._minmodes[index] def plusparams(self): return self._plusparams def minparams(self): return self._minparams def",
"first? pcount = 0 if modechars[0] == '+': min_start = find(modechars, '-') if",
"print \"String: %s\" % i print \"Plusmodes: %s\" % m.plusmodes() print \"Minmodes: %s\"",
"modes. The class is initialized with a modestring, the result methods will provide",
"i in tests: m = mode(i) print \"String: %s\" % i print \"Plusmodes:",
"pcount = pcount + 1 else: minparams.append(\"\") elif modechars[0] == '-': plus_start =",
":struis.intranet.amaze.nl 324 Vads #foo +tnl 12 x!~y@1.2.3.4 MODE #foo +l 21 Nick: x",
"1 else: plusparams.append(\"\") # or None? else: plusparams.append(\"\") self._plusmodes = plusmodes self._minmodes =",
"that require a parameter minparams.append(modeparams[pcount]) pcount = pcount + 1 else: minparams.append(\"\") for",
"index): return self._minmodes[index] def plusparams(self): return self._plusparams def minparams(self): return self._minparams def plusparam(self,",
"Nick: x Origin: x!~y@1.2.3.4 Target: #foo Command: MODE rest: +l rest: 21 Alternative",
"self._minmodes[index] def plusparams(self): return self._plusparams def minparams(self): return self._minparams def plusparam(self, index): return",
"1 else: minparams.append(\"\") elif modechars[0] == '-': plus_start = find(modechars, '+') if plus_start",
"+t-l :struis.intranet.amaze.nl 324 Vads #foo +tnl 12 x!~y@1.2.3.4 MODE #foo +l 21 Nick:",
"mode else: self.mode = split(mode, ' ') self.parse() def parse(self): modechars = self.mode[0]",
"[] minparams = [] # XXX There's too much duplications here # #",
"pcount + 1 else: plusparams.append(\"\") # or None? else: plusparams.append(\"\") for i in",
"in minmodes: if i in 'vobIe': # modes that require a parameter minparams.append(modeparams[pcount])",
"self._plusmodes[index] def minmode(self, index): return self._minmodes[index] def plusparams(self): return self._plusparams def minparams(self): return",
"minmodes self._plusparams = plusparams self._minparams = minparams def plusmodes(self): return self._plusmodes def minmodes(self):",
"Vads #foo +tnl 12 x!~y@1.2.3.4 MODE #foo +l 21 Nick: x Origin: x!~y@1.2.3.4",
"MODE #foo +bol b*!*@* MostUser 23 VladDrac!~ivo@10.34.213.210 MODE #foo +t-l :struis.intranet.amaze.nl 324 Vads",
"plusmodes = modechars[1:] for i in plusmodes: if i in 'volkbIe': # modes",
"parameter if len(modeparams) > pcount: plusparams.append(modeparams[pcount]) pcount = pcount + 1 else: plusparams.append(\"\")",
"i in 'volkbIe': # modes that require a parameter if len(modeparams) > pcount:",
"[] # XXX There's too much duplications here # # Are plusmodes always",
"MODE rest: +l rest: 21 Alternative interface for this class: get params by",
"self._minmodes = minmodes self._plusparams = plusparams self._minparams = minparams def plusmodes(self): return self._plusmodes",
"return self._plusmodes def minmodes(self): return self._minmodes def plusmode(self, index): return self._plusmodes[index] def minmode(self,",
"minmodes(self): return self._minmodes def plusmode(self, index): return self._plusmodes[index] def minmode(self, index): return self._minmodes[index]",
"get params by mode or, return plus/minmodes in (mode, param) pairs, i.e. +ookl",
"else: plusparams.append(\"\") # or None? else: plusparams.append(\"\") self._plusmodes = plusmodes self._minmodes = minmodes",
"\"+tnokb-lib VladDrac key *!*@* *!*@*.nl\", \"+tnkl\", \"+-\", \"+l- 10\", \"-oo+oo Foo1 Foo2 Foo3",
"a parameter minparams.append(modeparams[pcount]) pcount = pcount + 1 else: minparams.append(\"\") elif modechars[0] ==",
"plus_start = find(modechars, '+') if plus_start != -1: minmodes,plusmodes = split(modechars[1:], '+') else:",
"return self._plusparams[index] def minparam(self, index): return self._minparams[index] if __name__ == '__main__': # you",
"Class to parse modes. The class is initialized with a modestring, the result",
"+ookl Foo Bar key 12 -> (o, Foo), (o, Bar), (k, key), (l,",
"#foo +tnl 12 x!~y@1.2.3.4 MODE #foo +l 21 Nick: x Origin: x!~y@1.2.3.4 Target:",
"'-') else: plusmodes = modechars[1:] for i in plusmodes: if i in 'volkbIe':",
"= pcount + 1 else: plusparams.append(\"\") # or None? else: plusparams.append(\"\") self._plusmodes =",
"Test Test MODE Test :-i VladDrac!~ivo@10.34.213.210 MODE #foo +bol b*!*@* MostUser 23 VladDrac!~ivo@10.34.213.210",
"# # Are plusmodes always defined to come first? pcount = 0 if",
"always defined to come first? pcount = 0 if modechars[0] == '+': min_start",
"parameter minparams.append(modeparams[pcount]) pcount = pcount + 1 else: minparams.append(\"\") for i in plusmodes:",
"minmodes = \"\" plusparams = [] minparams = [] # XXX There's too",
"\"+l- 10\", \"-oo+oo Foo1 Foo2 Foo3 Foo4\"] for i in tests: m =",
"len(modeparams) > pcount: plusparams.append(modeparams[pcount]) pcount = pcount + 1 else: plusparams.append(\"\") # or",
"type(mode) in (type(()), type([])): self.mode = mode else: self.mode = split(mode, ' ')",
"pcount = pcount + 1 else: plusparams.append(\"\") # or None? else: plusparams.append(\"\") self._plusmodes",
"return self._plusmodes[index] def minmode(self, index): return self._minmodes[index] def plusparams(self): return self._plusparams def minparams(self):",
"= split(modechars[1:], '+') else: minmodes = modechars[1:] for i in minmodes: if i",
"\"\" self._minmodes = \"\" self._plusparams = \"\" self._minparams = \"\" self.setmode(mode) def setmode(self,",
"> pcount: plusparams.append(modeparams[pcount]) pcount = pcount + 1 else: plusparams.append(\"\") # or None?",
"will provide the parsed plus/min modes and parameters. TODO: banlist support? \"\"\" \"\"\"",
"index): return self._minparams[index] if __name__ == '__main__': # you won't get them as",
"Handle messages like: Vlads!^<EMAIL> MODE #foo +o Test Test MODE Test :-i VladDrac!~ivo@10.34.213.210",
"\"Minmodes: %s\" % m.minmodes() print \"Plusparams: \" print m.plusparams() print \"Minparams:\" print m.minparams()",
"the parsed plus/min modes and parameters. TODO: banlist support? \"\"\" \"\"\" Handle messages",
"= \"\" self._minparams = \"\" self.setmode(mode) def setmode(self, mode): if type(mode) in (type(()),",
"if len(modeparams) > pcount: plusparams.append(modeparams[pcount]) pcount = pcount + 1 else: plusparams.append(\"\") #",
"== '+': min_start = find(modechars, '-') if min_start != -1: plusmodes,minmodes = split(modechars[1:],",
"if plus_start != -1: minmodes,plusmodes = split(modechars[1:], '+') else: minmodes = modechars[1:] for",
"(k, key), (l, 12) \"\"\" from string import * class mode: def __init__(self,",
"12 -> (o, Foo), (o, Bar), (k, key), (l, 12) \"\"\" from string",
"in plusmodes: if i in 'volkbIe': # modes that require a parameter if",
"as the first on irc. tests = [ \"+tnokb-lib VladDrac key *!*@* *!*@*.nl\",",
"!= -1: minmodes,plusmodes = split(modechars[1:], '+') else: minmodes = modechars[1:] for i in",
"pcount = 0 if modechars[0] == '+': min_start = find(modechars, '-') if min_start",
"\"\" minmodes = \"\" plusparams = [] minparams = [] # XXX There's",
"modestring, the result methods will provide the parsed plus/min modes and parameters. TODO:",
"= minparams def plusmodes(self): return self._plusmodes def minmodes(self): return self._minmodes def plusmode(self, index):",
"key), (l, 12) \"\"\" from string import * class mode: def __init__(self, mode=None):",
"pcount + 1 else: minparams.append(\"\") elif modechars[0] == '-': plus_start = find(modechars, '+')",
"for i in tests: m = mode(i) print \"String: %s\" % i print",
"plusmodes = \"\" minmodes = \"\" plusparams = [] minparams = [] #",
"plusmodes,minmodes = split(modechars[1:], '-') else: plusmodes = modechars[1:] for i in plusmodes: if",
"TODO: banlist support? \"\"\" \"\"\" Handle messages like: Vlads!^<EMAIL> MODE #foo +o Test",
"21 Nick: x Origin: x!~y@1.2.3.4 Target: #foo Command: MODE rest: +l rest: 21",
"'+': min_start = find(modechars, '-') if min_start != -1: plusmodes,minmodes = split(modechars[1:], '-')",
"def minparams(self): return self._minparams def plusparam(self, index): return self._plusparams[index] def minparam(self, index): return",
"modes and parameters. TODO: banlist support? \"\"\" \"\"\" Handle messages like: Vlads!^<EMAIL> MODE",
"\"\" self._minparams = \"\" self.setmode(mode) def setmode(self, mode): if type(mode) in (type(()), type([])):",
"plus/min modes and parameters. TODO: banlist support? \"\"\" \"\"\" Handle messages like: Vlads!^<EMAIL>",
"+ 1 else: minparams.append(\"\") elif modechars[0] == '-': plus_start = find(modechars, '+') if",
"else: plusparams.append(\"\") for i in minmodes: if i in 'vobIe': # modes that",
"minparams = [] # XXX There's too much duplications here # # Are",
"self.parse() def parse(self): modechars = self.mode[0] modeparams = self.mode[1:] plusmodes = \"\" minmodes",
"#foo +l 21 Nick: x Origin: x!~y@1.2.3.4 Target: #foo Command: MODE rest: +l",
"self._plusmodes = plusmodes self._minmodes = minmodes self._plusparams = plusparams self._minparams = minparams def",
"[ \"+tnokb-lib VladDrac key *!*@* *!*@*.nl\", \"+tnkl\", \"+-\", \"+l- 10\", \"-oo+oo Foo1 Foo2",
"= mode(i) print \"String: %s\" % i print \"Plusmodes: %s\" % m.plusmodes() print",
"__name__ == '__main__': # you won't get them as complex as the first",
"for this class: get params by mode or, return plus/minmodes in (mode, param)",
"2002/02/05 17:44:25 ivo Exp $ \"\"\" Class to parse modes. The class is",
"= [ \"+tnokb-lib VladDrac key *!*@* *!*@*.nl\", \"+tnkl\", \"+-\", \"+l- 10\", \"-oo+oo Foo1",
"key 12 -> (o, Foo), (o, Bar), (k, key), (l, 12) \"\"\" from",
"index): return self._plusparams[index] def minparam(self, index): return self._minparams[index] if __name__ == '__main__': #",
"'__main__': # you won't get them as complex as the first on irc.",
"pcount: plusparams.append(modeparams[pcount]) pcount = pcount + 1 else: plusparams.append(\"\") # or None? else:",
"or, return plus/minmodes in (mode, param) pairs, i.e. +ookl Foo Bar key 12",
"rest: 21 Alternative interface for this class: get params by mode or, return",
"% m.plusmodes() print \"Minmodes: %s\" % m.minmodes() print \"Plusparams: \" print m.plusparams() print",
"+ 1 else: plusparams.append(\"\") # or None? else: plusparams.append(\"\") for i in minmodes:",
"split(modechars[1:], '-') else: plusmodes = modechars[1:] for i in plusmodes: if i in",
"# XXX There's too much duplications here # # Are plusmodes always defined",
"self._minmodes = \"\" self._plusparams = \"\" self._minparams = \"\" self.setmode(mode) def setmode(self, mode):",
"else: plusmodes = modechars[1:] for i in plusmodes: if i in 'volkbIe': #",
"21 Alternative interface for this class: get params by mode or, return plus/minmodes",
"= 0 if modechars[0] == '+': min_start = find(modechars, '-') if min_start !=",
"'+') if plus_start != -1: minmodes,plusmodes = split(modechars[1:], '+') else: minmodes = modechars[1:]",
"plusparams.append(\"\") # or None? else: plusparams.append(\"\") self._plusmodes = plusmodes self._minmodes = minmodes self._plusparams",
"i.e. +ookl Foo Bar key 12 -> (o, Foo), (o, Bar), (k, key),",
"'vobIe': # modes that require a parameter minparams.append(modeparams[pcount]) pcount = pcount + 1",
"class: get params by mode or, return plus/minmodes in (mode, param) pairs, i.e.",
"x!~y@1.2.3.4 MODE #foo +l 21 Nick: x Origin: x!~y@1.2.3.4 Target: #foo Command: MODE",
"Foo1 Foo2 Foo3 Foo4\"] for i in tests: m = mode(i) print \"String:",
"return self._minparams def plusparam(self, index): return self._plusparams[index] def minparam(self, index): return self._minparams[index] if",
"= minmodes self._plusparams = plusparams self._minparams = minparams def plusmodes(self): return self._plusmodes def",
"'+') else: minmodes = modechars[1:] for i in minmodes: if i in 'vobIe':",
"m = mode(i) print \"String: %s\" % i print \"Plusmodes: %s\" % m.plusmodes()",
"ivo Exp $ \"\"\" Class to parse modes. The class is initialized with",
"(type(()), type([])): self.mode = mode else: self.mode = split(mode, ' ') self.parse() def",
"def plusparams(self): return self._plusparams def minparams(self): return self._minparams def plusparam(self, index): return self._plusparams[index]",
"b*!*@* MostUser 23 VladDrac!~ivo@10.34.213.210 MODE #foo +t-l :struis.intranet.amaze.nl 324 Vads #foo +tnl 12",
"324 Vads #foo +tnl 12 x!~y@1.2.3.4 MODE #foo +l 21 Nick: x Origin:",
"parsed plus/min modes and parameters. TODO: banlist support? \"\"\" \"\"\" Handle messages like:",
"self._minparams = minparams def plusmodes(self): return self._plusmodes def minmodes(self): return self._minmodes def plusmode(self,",
"XXX There's too much duplications here # # Are plusmodes always defined to",
"= [] # XXX There's too much duplications here # # Are plusmodes",
"provide the parsed plus/min modes and parameters. TODO: banlist support? \"\"\" \"\"\" Handle",
"= modechars[1:] for i in minmodes: if i in 'vobIe': # modes that",
"irc. tests = [ \"+tnokb-lib VladDrac key *!*@* *!*@*.nl\", \"+tnkl\", \"+-\", \"+l- 10\",",
"minparams def plusmodes(self): return self._plusmodes def minmodes(self): return self._minmodes def plusmode(self, index): return",
"\"+-\", \"+l- 10\", \"-oo+oo Foo1 Foo2 Foo3 Foo4\"] for i in tests: m",
"interface for this class: get params by mode or, return plus/minmodes in (mode,",
"from string import * class mode: def __init__(self, mode=None): self._plusmodes = \"\" self._minmodes",
"1.3 2002/02/05 17:44:25 ivo Exp $ \"\"\" Class to parse modes. The class",
"% i print \"Plusmodes: %s\" % m.plusmodes() print \"Minmodes: %s\" % m.minmodes() print",
"def plusmodes(self): return self._plusmodes def minmodes(self): return self._minmodes def plusmode(self, index): return self._plusmodes[index]",
"!= -1: plusmodes,minmodes = split(modechars[1:], '-') else: plusmodes = modechars[1:] for i in",
"as complex as the first on irc. tests = [ \"+tnokb-lib VladDrac key",
"plusmodes self._minmodes = minmodes self._plusparams = plusparams self._minparams = minparams def plusmodes(self): return",
"(l, 12) \"\"\" from string import * class mode: def __init__(self, mode=None): self._plusmodes",
"plusparams.append(\"\") for i in minmodes: if i in 'vobIe': # modes that require",
"\"\" self.setmode(mode) def setmode(self, mode): if type(mode) in (type(()), type([])): self.mode = mode",
"None? else: plusparams.append(\"\") self._plusmodes = plusmodes self._minmodes = minmodes self._plusparams = plusparams self._minparams",
"else: minparams.append(\"\") for i in plusmodes: if i in 'volkbIe': # modes that",
"= plusparams self._minparams = minparams def plusmodes(self): return self._plusmodes def minmodes(self): return self._minmodes",
"+ 1 else: minparams.append(\"\") for i in plusmodes: if i in 'volkbIe': #",
"i in plusmodes: if i in 'volkbIe': # modes that require a parameter",
"m.plusmodes() print \"Minmodes: %s\" % m.minmodes() print \"Plusparams: \" print m.plusparams() print \"Minparams:\"",
"There's too much duplications here # # Are plusmodes always defined to come",
"minmodes = modechars[1:] for i in minmodes: if i in 'vobIe': # modes",
"-1: plusmodes,minmodes = split(modechars[1:], '-') else: plusmodes = modechars[1:] for i in plusmodes:",
"import * class mode: def __init__(self, mode=None): self._plusmodes = \"\" self._minmodes = \"\"",
"(mode, param) pairs, i.e. +ookl Foo Bar key 12 -> (o, Foo), (o,",
"= pcount + 1 else: plusparams.append(\"\") # or None? else: plusparams.append(\"\") for i",
"23 VladDrac!~ivo@10.34.213.210 MODE #foo +t-l :struis.intranet.amaze.nl 324 Vads #foo +tnl 12 x!~y@1.2.3.4 MODE",
"require a parameter minparams.append(modeparams[pcount]) pcount = pcount + 1 else: minparams.append(\"\") for i",
"The class is initialized with a modestring, the result methods will provide the",
"and parameters. TODO: banlist support? \"\"\" \"\"\" Handle messages like: Vlads!^<EMAIL> MODE #foo",
"0 if modechars[0] == '+': min_start = find(modechars, '-') if min_start != -1:",
"Exp $ \"\"\" Class to parse modes. The class is initialized with a",
"modechars[0] == '+': min_start = find(modechars, '-') if min_start != -1: plusmodes,minmodes =",
"complex as the first on irc. tests = [ \"+tnokb-lib VladDrac key *!*@*",
"<filename>src/controller/mode.py #!/usr/bin/python # $Id: mode.py,v 1.3 2002/02/05 17:44:25 ivo Exp $ \"\"\" Class",
"= find(modechars, '+') if plus_start != -1: minmodes,plusmodes = split(modechars[1:], '+') else: minmodes",
"MostUser 23 VladDrac!~ivo@10.34.213.210 MODE #foo +t-l :struis.intranet.amaze.nl 324 Vads #foo +tnl 12 x!~y@1.2.3.4",
"+l 21 Nick: x Origin: x!~y@1.2.3.4 Target: #foo Command: MODE rest: +l rest:",
"pairs, i.e. +ookl Foo Bar key 12 -> (o, Foo), (o, Bar), (k,",
"modes that require a parameter minparams.append(modeparams[pcount]) pcount = pcount + 1 else: minparams.append(\"\")",
"self._plusparams = plusparams self._minparams = minparams def plusmodes(self): return self._plusmodes def minmodes(self): return",
"the result methods will provide the parsed plus/min modes and parameters. TODO: banlist",
"* class mode: def __init__(self, mode=None): self._plusmodes = \"\" self._minmodes = \"\" self._plusparams",
"plusmode(self, index): return self._plusmodes[index] def minmode(self, index): return self._minmodes[index] def plusparams(self): return self._plusparams",
"$Id: mode.py,v 1.3 2002/02/05 17:44:25 ivo Exp $ \"\"\" Class to parse modes.",
"1 else: plusparams.append(\"\") # or None? else: plusparams.append(\"\") for i in minmodes: if",
"x Origin: x!~y@1.2.3.4 Target: #foo Command: MODE rest: +l rest: 21 Alternative interface",
"') self.parse() def parse(self): modechars = self.mode[0] modeparams = self.mode[1:] plusmodes = \"\"",
"parse(self): modechars = self.mode[0] modeparams = self.mode[1:] plusmodes = \"\" minmodes = \"\"",
"won't get them as complex as the first on irc. tests = [",
"-> (o, Foo), (o, Bar), (k, key), (l, 12) \"\"\" from string import",
"' ') self.parse() def parse(self): modechars = self.mode[0] modeparams = self.mode[1:] plusmodes =",
"self.mode = split(mode, ' ') self.parse() def parse(self): modechars = self.mode[0] modeparams =",
"self._minparams def plusparam(self, index): return self._plusparams[index] def minparam(self, index): return self._minparams[index] if __name__",
"+ 1 else: plusparams.append(\"\") # or None? else: plusparams.append(\"\") self._plusmodes = plusmodes self._minmodes",
"plusparams.append(modeparams[pcount]) pcount = pcount + 1 else: plusparams.append(\"\") # or None? else: plusparams.append(\"\")",
"= \"\" minmodes = \"\" plusparams = [] minparams = [] # XXX",
"#foo +o Test Test MODE Test :-i VladDrac!~ivo@10.34.213.210 MODE #foo +bol b*!*@* MostUser",
"for i in minmodes: if i in 'vobIe': # modes that require a",
"else: self.mode = split(mode, ' ') self.parse() def parse(self): modechars = self.mode[0] modeparams",
"that require a parameter minparams.append(modeparams[pcount]) pcount = pcount + 1 else: minparams.append(\"\") elif",
"= self.mode[0] modeparams = self.mode[1:] plusmodes = \"\" minmodes = \"\" plusparams =",
"in (mode, param) pairs, i.e. +ookl Foo Bar key 12 -> (o, Foo),",
"(o, Bar), (k, key), (l, 12) \"\"\" from string import * class mode:",
"plus/minmodes in (mode, param) pairs, i.e. +ookl Foo Bar key 12 -> (o,",
"you won't get them as complex as the first on irc. tests =",
"that require a parameter if len(modeparams) > pcount: plusparams.append(modeparams[pcount]) pcount = pcount +",
"%s\" % m.plusmodes() print \"Minmodes: %s\" % m.minmodes() print \"Plusparams: \" print m.plusparams()",
"self.setmode(mode) def setmode(self, mode): if type(mode) in (type(()), type([])): self.mode = mode else:",
"mode(i) print \"String: %s\" % i print \"Plusmodes: %s\" % m.plusmodes() print \"Minmodes:",
"setmode(self, mode): if type(mode) in (type(()), type([])): self.mode = mode else: self.mode =",
"= modechars[1:] for i in plusmodes: if i in 'volkbIe': # modes that",
"return plus/minmodes in (mode, param) pairs, i.e. +ookl Foo Bar key 12 ->",
"pcount = pcount + 1 else: minparams.append(\"\") for i in plusmodes: if i",
"plusparams.append(\"\") self._plusmodes = plusmodes self._minmodes = minmodes self._plusparams = plusparams self._minparams = minparams",
"\"\" self._plusparams = \"\" self._minparams = \"\" self.setmode(mode) def setmode(self, mode): if type(mode)",
"for i in plusmodes: if i in 'volkbIe': # modes that require a",
"#!/usr/bin/python # $Id: mode.py,v 1.3 2002/02/05 17:44:25 ivo Exp $ \"\"\" Class to",
"== '-': plus_start = find(modechars, '+') if plus_start != -1: minmodes,plusmodes = split(modechars[1:],",
"\"Plusmodes: %s\" % m.plusmodes() print \"Minmodes: %s\" % m.minmodes() print \"Plusparams: \" print",
"%s\" % i print \"Plusmodes: %s\" % m.plusmodes() print \"Minmodes: %s\" % m.minmodes()",
"a modestring, the result methods will provide the parsed plus/min modes and parameters.",
"in (type(()), type([])): self.mode = mode else: self.mode = split(mode, ' ') self.parse()",
"VladDrac key *!*@* *!*@*.nl\", \"+tnkl\", \"+-\", \"+l- 10\", \"-oo+oo Foo1 Foo2 Foo3 Foo4\"]",
"min_start != -1: plusmodes,minmodes = split(modechars[1:], '-') else: plusmodes = modechars[1:] for i",
"'volkbIe': # modes that require a parameter if len(modeparams) > pcount: plusparams.append(modeparams[pcount]) pcount",
"+o Test Test MODE Test :-i VladDrac!~ivo@10.34.213.210 MODE #foo +bol b*!*@* MostUser 23",
"else: minmodes = modechars[1:] for i in minmodes: if i in 'vobIe': #",
"= pcount + 1 else: minparams.append(\"\") for i in plusmodes: if i in",
"= self.mode[1:] plusmodes = \"\" minmodes = \"\" plusparams = [] minparams =",
"parse modes. The class is initialized with a modestring, the result methods will",
"= \"\" self.setmode(mode) def setmode(self, mode): if type(mode) in (type(()), type([])): self.mode =",
"= \"\" self._plusparams = \"\" self._minparams = \"\" self.setmode(mode) def setmode(self, mode): if",
"Test :-i VladDrac!~ivo@10.34.213.210 MODE #foo +bol b*!*@* MostUser 23 VladDrac!~ivo@10.34.213.210 MODE #foo +t-l",
"def plusparam(self, index): return self._plusparams[index] def minparam(self, index): return self._minparams[index] if __name__ ==",
"is initialized with a modestring, the result methods will provide the parsed plus/min",
"key *!*@* *!*@*.nl\", \"+tnkl\", \"+-\", \"+l- 10\", \"-oo+oo Foo1 Foo2 Foo3 Foo4\"] for",
"10\", \"-oo+oo Foo1 Foo2 Foo3 Foo4\"] for i in tests: m = mode(i)",
"def minparam(self, index): return self._minparams[index] if __name__ == '__main__': # you won't get",
"self.mode = mode else: self.mode = split(mode, ' ') self.parse() def parse(self): modechars",
"to parse modes. The class is initialized with a modestring, the result methods",
"modechars[1:] for i in minmodes: if i in 'vobIe': # modes that require",
"result methods will provide the parsed plus/min modes and parameters. TODO: banlist support?",
"support? \"\"\" \"\"\" Handle messages like: Vlads!^<EMAIL> MODE #foo +o Test Test MODE",
"self.mode[0] modeparams = self.mode[1:] plusmodes = \"\" minmodes = \"\" plusparams = []",
"plus_start != -1: minmodes,plusmodes = split(modechars[1:], '+') else: minmodes = modechars[1:] for i",
"+l rest: 21 Alternative interface for this class: get params by mode or,",
"= split(modechars[1:], '-') else: plusmodes = modechars[1:] for i in plusmodes: if i",
"defined to come first? pcount = 0 if modechars[0] == '+': min_start =",
"return self._minmodes def plusmode(self, index): return self._plusmodes[index] def minmode(self, index): return self._minmodes[index] def",
"Foo2 Foo3 Foo4\"] for i in tests: m = mode(i) print \"String: %s\"",
"a parameter minparams.append(modeparams[pcount]) pcount = pcount + 1 else: minparams.append(\"\") for i in",
"if __name__ == '__main__': # you won't get them as complex as the",
"\"\"\" \"\"\" Handle messages like: Vlads!^<EMAIL> MODE #foo +o Test Test MODE Test",
"= pcount + 1 else: minparams.append(\"\") elif modechars[0] == '-': plus_start = find(modechars,",
"elif modechars[0] == '-': plus_start = find(modechars, '+') if plus_start != -1: minmodes,plusmodes",
"index): return self._plusmodes[index] def minmode(self, index): return self._minmodes[index] def plusparams(self): return self._plusparams def",
"'-') if min_start != -1: plusmodes,minmodes = split(modechars[1:], '-') else: plusmodes = modechars[1:]",
"minparams.append(\"\") for i in plusmodes: if i in 'volkbIe': # modes that require",
"# or None? else: plusparams.append(\"\") self._plusmodes = plusmodes self._minmodes = minmodes self._plusparams =",
"modes that require a parameter if len(modeparams) > pcount: plusparams.append(modeparams[pcount]) pcount = pcount",
"def minmodes(self): return self._minmodes def plusmode(self, index): return self._plusmodes[index] def minmode(self, index): return",
"MODE #foo +l 21 Nick: x Origin: x!~y@1.2.3.4 Target: #foo Command: MODE rest:",
"if modechars[0] == '+': min_start = find(modechars, '-') if min_start != -1: plusmodes,minmodes",
"12 x!~y@1.2.3.4 MODE #foo +l 21 Nick: x Origin: x!~y@1.2.3.4 Target: #foo Command:",
"self._plusmodes = \"\" self._minmodes = \"\" self._plusparams = \"\" self._minparams = \"\" self.setmode(mode)",
"banlist support? \"\"\" \"\"\" Handle messages like: Vlads!^<EMAIL> MODE #foo +o Test Test",
"= plusmodes self._minmodes = minmodes self._plusparams = plusparams self._minparams = minparams def plusmodes(self):",
"to come first? pcount = 0 if modechars[0] == '+': min_start = find(modechars,",
"'-': plus_start = find(modechars, '+') if plus_start != -1: minmodes,plusmodes = split(modechars[1:], '+')",
"plusmodes(self): return self._plusmodes def minmodes(self): return self._minmodes def plusmode(self, index): return self._plusmodes[index] def",
"return self._plusparams def minparams(self): return self._minparams def plusparam(self, index): return self._plusparams[index] def minparam(self,",
"parameter minparams.append(modeparams[pcount]) pcount = pcount + 1 else: minparams.append(\"\") elif modechars[0] == '-':",
"\"\"\" Class to parse modes. The class is initialized with a modestring, the",
"plusparams = [] minparams = [] # XXX There's too much duplications here",
"modechars[1:] for i in plusmodes: if i in 'volkbIe': # modes that require",
"#foo Command: MODE rest: +l rest: 21 Alternative interface for this class: get",
"pcount = pcount + 1 else: plusparams.append(\"\") # or None? else: plusparams.append(\"\") for",
"*!*@*.nl\", \"+tnkl\", \"+-\", \"+l- 10\", \"-oo+oo Foo1 Foo2 Foo3 Foo4\"] for i in",
"self._plusparams = \"\" self._minparams = \"\" self.setmode(mode) def setmode(self, mode): if type(mode) in",
"find(modechars, '+') if plus_start != -1: minmodes,plusmodes = split(modechars[1:], '+') else: minmodes =",
"class mode: def __init__(self, mode=None): self._plusmodes = \"\" self._minmodes = \"\" self._plusparams =",
"x!~y@1.2.3.4 Target: #foo Command: MODE rest: +l rest: 21 Alternative interface for this",
"minparams.append(modeparams[pcount]) pcount = pcount + 1 else: minparams.append(\"\") for i in plusmodes: if",
"in tests: m = mode(i) print \"String: %s\" % i print \"Plusmodes: %s\"",
"minparams.append(\"\") elif modechars[0] == '-': plus_start = find(modechars, '+') if plus_start != -1:",
"like: Vlads!^<EMAIL> MODE #foo +o Test Test MODE Test :-i VladDrac!~ivo@10.34.213.210 MODE #foo",
"duplications here # # Are plusmodes always defined to come first? pcount =",
"string import * class mode: def __init__(self, mode=None): self._plusmodes = \"\" self._minmodes =",
"or None? else: plusparams.append(\"\") for i in minmodes: if i in 'vobIe': #",
"a parameter if len(modeparams) > pcount: plusparams.append(modeparams[pcount]) pcount = pcount + 1 else:",
"minparams.append(modeparams[pcount]) pcount = pcount + 1 else: minparams.append(\"\") elif modechars[0] == '-': plus_start",
"= [] minparams = [] # XXX There's too much duplications here #",
"mode): if type(mode) in (type(()), type([])): self.mode = mode else: self.mode = split(mode,",
"self._plusparams def minparams(self): return self._minparams def plusparam(self, index): return self._plusparams[index] def minparam(self, index):",
"i in minmodes: if i in 'vobIe': # modes that require a parameter",
"params by mode or, return plus/minmodes in (mode, param) pairs, i.e. +ookl Foo",
"self._plusparams[index] def minparam(self, index): return self._minparams[index] if __name__ == '__main__': # you won't",
"VladDrac!~ivo@10.34.213.210 MODE #foo +bol b*!*@* MostUser 23 VladDrac!~ivo@10.34.213.210 MODE #foo +t-l :struis.intranet.amaze.nl 324",
"i in 'vobIe': # modes that require a parameter minparams.append(modeparams[pcount]) pcount = pcount",
"in 'volkbIe': # modes that require a parameter if len(modeparams) > pcount: plusparams.append(modeparams[pcount])",
"with a modestring, the result methods will provide the parsed plus/min modes and",
"in 'vobIe': # modes that require a parameter minparams.append(modeparams[pcount]) pcount = pcount +",
"self._minparams = \"\" self.setmode(mode) def setmode(self, mode): if type(mode) in (type(()), type([])): self.mode",
"\"-oo+oo Foo1 Foo2 Foo3 Foo4\"] for i in tests: m = mode(i) print",
"i print \"Plusmodes: %s\" % m.plusmodes() print \"Minmodes: %s\" % m.minmodes() print \"Plusparams:",
"+tnl 12 x!~y@1.2.3.4 MODE #foo +l 21 Nick: x Origin: x!~y@1.2.3.4 Target: #foo",
"come first? pcount = 0 if modechars[0] == '+': min_start = find(modechars, '-')",
"class is initialized with a modestring, the result methods will provide the parsed",
"Bar key 12 -> (o, Foo), (o, Bar), (k, key), (l, 12) \"\"\"",
"by mode or, return plus/minmodes in (mode, param) pairs, i.e. +ookl Foo Bar",
"if type(mode) in (type(()), type([])): self.mode = mode else: self.mode = split(mode, '",
"= mode else: self.mode = split(mode, ' ') self.parse() def parse(self): modechars =",
"modechars[0] == '-': plus_start = find(modechars, '+') if plus_start != -1: minmodes,plusmodes =",
"too much duplications here # # Are plusmodes always defined to come first?",
"Origin: x!~y@1.2.3.4 Target: #foo Command: MODE rest: +l rest: 21 Alternative interface for",
"== '__main__': # you won't get them as complex as the first on",
"much duplications here # # Are plusmodes always defined to come first? pcount",
"(o, Foo), (o, Bar), (k, key), (l, 12) \"\"\" from string import *",
"minmodes,plusmodes = split(modechars[1:], '+') else: minmodes = modechars[1:] for i in minmodes: if",
"else: plusparams.append(\"\") self._plusmodes = plusmodes self._minmodes = minmodes self._plusparams = plusparams self._minparams =",
"self._plusmodes def minmodes(self): return self._minmodes def plusmode(self, index): return self._plusmodes[index] def minmode(self, index):",
"pcount + 1 else: plusparams.append(\"\") # or None? else: plusparams.append(\"\") self._plusmodes = plusmodes",
"tests = [ \"+tnokb-lib VladDrac key *!*@* *!*@*.nl\", \"+tnkl\", \"+-\", \"+l- 10\", \"-oo+oo",
"if i in 'volkbIe': # modes that require a parameter if len(modeparams) >",
"if i in 'vobIe': # modes that require a parameter minparams.append(modeparams[pcount]) pcount =",
"param) pairs, i.e. +ookl Foo Bar key 12 -> (o, Foo), (o, Bar),",
"print \"Minmodes: %s\" % m.minmodes() print \"Plusparams: \" print m.plusparams() print \"Minparams:\" print",
"Bar), (k, key), (l, 12) \"\"\" from string import * class mode: def",
"Are plusmodes always defined to come first? pcount = 0 if modechars[0] ==",
"minmodes: if i in 'vobIe': # modes that require a parameter minparams.append(modeparams[pcount]) pcount",
"return self._minmodes[index] def plusparams(self): return self._plusparams def minparams(self): return self._minparams def plusparam(self, index):",
"them as complex as the first on irc. tests = [ \"+tnokb-lib VladDrac",
"get them as complex as the first on irc. tests = [ \"+tnokb-lib",
"mode: def __init__(self, mode=None): self._plusmodes = \"\" self._minmodes = \"\" self._plusparams = \"\"",
"12) \"\"\" from string import * class mode: def __init__(self, mode=None): self._plusmodes =",
"def parse(self): modechars = self.mode[0] modeparams = self.mode[1:] plusmodes = \"\" minmodes =",
"self._minparams[index] if __name__ == '__main__': # you won't get them as complex as",
"on irc. tests = [ \"+tnokb-lib VladDrac key *!*@* *!*@*.nl\", \"+tnkl\", \"+-\", \"+l-",
"MODE #foo +o Test Test MODE Test :-i VladDrac!~ivo@10.34.213.210 MODE #foo +bol b*!*@*",
"minparam(self, index): return self._minparams[index] if __name__ == '__main__': # you won't get them",
"= split(mode, ' ') self.parse() def parse(self): modechars = self.mode[0] modeparams = self.mode[1:]",
":-i VladDrac!~ivo@10.34.213.210 MODE #foo +bol b*!*@* MostUser 23 VladDrac!~ivo@10.34.213.210 MODE #foo +t-l :struis.intranet.amaze.nl",
"plusmodes: if i in 'volkbIe': # modes that require a parameter if len(modeparams)",
"mode=None): self._plusmodes = \"\" self._minmodes = \"\" self._plusparams = \"\" self._minparams = \"\"",
"min_start = find(modechars, '-') if min_start != -1: plusmodes,minmodes = split(modechars[1:], '-') else:",
"parameters. TODO: banlist support? \"\"\" \"\"\" Handle messages like: Vlads!^<EMAIL> MODE #foo +o",
"type([])): self.mode = mode else: self.mode = split(mode, ' ') self.parse() def parse(self):",
"\"\"\" from string import * class mode: def __init__(self, mode=None): self._plusmodes = \"\"",
"__init__(self, mode=None): self._plusmodes = \"\" self._minmodes = \"\" self._plusparams = \"\" self._minparams =",
"= \"\" self._minmodes = \"\" self._plusparams = \"\" self._minparams = \"\" self.setmode(mode) def",
"# modes that require a parameter if len(modeparams) > pcount: plusparams.append(modeparams[pcount]) pcount =",
"# Are plusmodes always defined to come first? pcount = 0 if modechars[0]",
"self.mode[1:] plusmodes = \"\" minmodes = \"\" plusparams = [] minparams = []",
"$ \"\"\" Class to parse modes. The class is initialized with a modestring,",
"initialized with a modestring, the result methods will provide the parsed plus/min modes",
"\"+tnkl\", \"+-\", \"+l- 10\", \"-oo+oo Foo1 Foo2 Foo3 Foo4\"] for i in tests:",
"mode.py,v 1.3 2002/02/05 17:44:25 ivo Exp $ \"\"\" Class to parse modes. The",
"Foo Bar key 12 -> (o, Foo), (o, Bar), (k, key), (l, 12)",
"or None? else: plusparams.append(\"\") self._plusmodes = plusmodes self._minmodes = minmodes self._plusparams = plusparams",
"Target: #foo Command: MODE rest: +l rest: 21 Alternative interface for this class:",
"modeparams = self.mode[1:] plusmodes = \"\" minmodes = \"\" plusparams = [] minparams",
"# or None? else: plusparams.append(\"\") for i in minmodes: if i in 'vobIe':",
"require a parameter if len(modeparams) > pcount: plusparams.append(modeparams[pcount]) pcount = pcount + 1",
"plusparams(self): return self._plusparams def minparams(self): return self._minparams def plusparam(self, index): return self._plusparams[index] def",
"plusparams.append(\"\") # or None? else: plusparams.append(\"\") for i in minmodes: if i in",
"# modes that require a parameter minparams.append(modeparams[pcount]) pcount = pcount + 1 else:",
"if min_start != -1: plusmodes,minmodes = split(modechars[1:], '-') else: plusmodes = modechars[1:] for",
"modechars = self.mode[0] modeparams = self.mode[1:] plusmodes = \"\" minmodes = \"\" plusparams",
"Alternative interface for this class: get params by mode or, return plus/minmodes in",
"\"\" plusparams = [] minparams = [] # XXX There's too much duplications",
"self._minmodes def plusmode(self, index): return self._plusmodes[index] def minmode(self, index): return self._minmodes[index] def plusparams(self):",
"def plusmode(self, index): return self._plusmodes[index] def minmode(self, index): return self._minmodes[index] def plusparams(self): return",
"plusparams self._minparams = minparams def plusmodes(self): return self._plusmodes def minmodes(self): return self._minmodes def",
"this class: get params by mode or, return plus/minmodes in (mode, param) pairs,",
"plusmodes always defined to come first? pcount = 0 if modechars[0] == '+':",
"#foo +bol b*!*@* MostUser 23 VladDrac!~ivo@10.34.213.210 MODE #foo +t-l :struis.intranet.amaze.nl 324 Vads #foo",
"def setmode(self, mode): if type(mode) in (type(()), type([])): self.mode = mode else: self.mode",
"= find(modechars, '-') if min_start != -1: plusmodes,minmodes = split(modechars[1:], '-') else: plusmodes",
"VladDrac!~ivo@10.34.213.210 MODE #foo +t-l :struis.intranet.amaze.nl 324 Vads #foo +tnl 12 x!~y@1.2.3.4 MODE #foo",
"first on irc. tests = [ \"+tnokb-lib VladDrac key *!*@* *!*@*.nl\", \"+tnkl\", \"+-\",",
"Command: MODE rest: +l rest: 21 Alternative interface for this class: get params",
"def __init__(self, mode=None): self._plusmodes = \"\" self._minmodes = \"\" self._plusparams = \"\" self._minparams",
"\"\"\" Handle messages like: Vlads!^<EMAIL> MODE #foo +o Test Test MODE Test :-i",
"def minmode(self, index): return self._minmodes[index] def plusparams(self): return self._plusparams def minparams(self): return self._minparams",
"minparams(self): return self._minparams def plusparam(self, index): return self._plusparams[index] def minparam(self, index): return self._minparams[index]",
"# $Id: mode.py,v 1.3 2002/02/05 17:44:25 ivo Exp $ \"\"\" Class to parse",
"return self._minparams[index] if __name__ == '__main__': # you won't get them as complex",
"\"String: %s\" % i print \"Plusmodes: %s\" % m.plusmodes() print \"Minmodes: %s\" %",
"the first on irc. tests = [ \"+tnokb-lib VladDrac key *!*@* *!*@*.nl\", \"+tnkl\",",
"None? else: plusparams.append(\"\") for i in minmodes: if i in 'vobIe': # modes",
"*!*@* *!*@*.nl\", \"+tnkl\", \"+-\", \"+l- 10\", \"-oo+oo Foo1 Foo2 Foo3 Foo4\"] for i",
"require a parameter minparams.append(modeparams[pcount]) pcount = pcount + 1 else: minparams.append(\"\") elif modechars[0]",
"-1: minmodes,plusmodes = split(modechars[1:], '+') else: minmodes = modechars[1:] for i in minmodes:",
"rest: +l rest: 21 Alternative interface for this class: get params by mode",
"split(modechars[1:], '+') else: minmodes = modechars[1:] for i in minmodes: if i in",
"Vlads!^<EMAIL> MODE #foo +o Test Test MODE Test :-i VladDrac!~ivo@10.34.213.210 MODE #foo +bol",
"#foo +t-l :struis.intranet.amaze.nl 324 Vads #foo +tnl 12 x!~y@1.2.3.4 MODE #foo +l 21",
"else: plusparams.append(\"\") # or None? else: plusparams.append(\"\") for i in minmodes: if i",
"Foo4\"] for i in tests: m = mode(i) print \"String: %s\" % i",
"else: minparams.append(\"\") elif modechars[0] == '-': plus_start = find(modechars, '+') if plus_start !=",
"1 else: minparams.append(\"\") for i in plusmodes: if i in 'volkbIe': # modes",
"Test MODE Test :-i VladDrac!~ivo@10.34.213.210 MODE #foo +bol b*!*@* MostUser 23 VladDrac!~ivo@10.34.213.210 MODE",
"split(mode, ' ') self.parse() def parse(self): modechars = self.mode[0] modeparams = self.mode[1:] plusmodes",
"MODE #foo +t-l :struis.intranet.amaze.nl 324 Vads #foo +tnl 12 x!~y@1.2.3.4 MODE #foo +l",
"+bol b*!*@* MostUser 23 VladDrac!~ivo@10.34.213.210 MODE #foo +t-l :struis.intranet.amaze.nl 324 Vads #foo +tnl",
"print \"Plusmodes: %s\" % m.plusmodes() print \"Minmodes: %s\" % m.minmodes() print \"Plusparams: \"",
"here # # Are plusmodes always defined to come first? pcount = 0",
"find(modechars, '-') if min_start != -1: plusmodes,minmodes = split(modechars[1:], '-') else: plusmodes =",
"# you won't get them as complex as the first on irc. tests",
"pcount + 1 else: minparams.append(\"\") for i in plusmodes: if i in 'volkbIe':",
"tests: m = mode(i) print \"String: %s\" % i print \"Plusmodes: %s\" %",
"MODE Test :-i VladDrac!~ivo@10.34.213.210 MODE #foo +bol b*!*@* MostUser 23 VladDrac!~ivo@10.34.213.210 MODE #foo",
"Foo), (o, Bar), (k, key), (l, 12) \"\"\" from string import * class",
"methods will provide the parsed plus/min modes and parameters. TODO: banlist support? \"\"\"",
"plusparam(self, index): return self._plusparams[index] def minparam(self, index): return self._minparams[index] if __name__ == '__main__':",
"mode or, return plus/minmodes in (mode, param) pairs, i.e. +ookl Foo Bar key",
"messages like: Vlads!^<EMAIL> MODE #foo +o Test Test MODE Test :-i VladDrac!~ivo@10.34.213.210 MODE"
] |
[] |
[
"import RSNADataSet from .utils.score import compute_auroc from .utils.model import DenseNet121, DenseNet121Eff from math",
"epoch_train(self): loss_train_list = [] loss_valid_list = [] self.model.train() scheduler = StepLR(self.optimizer, step_size=6, gamma=0.002)",
"saved\", type =str) parser.add_argument(\"--optimised\", required=False, default=False, help=\"enable flag->eff model\", action='store_true') parser.add_argument(\"--alpha\", required=False, help=\"alpha",
"scheduler.step() train_loss_mean = np.mean(loss_train_list) valid_loss_mean = np.mean(loss_valid_list) return train_loss_mean, valid_loss_mean, auroc_mean def test(self):",
"np.load(os.path.join(numpy_path,'valid_list.npy')).tolist() test_list = np.load(os.path.join(numpy_path,'test_list.npy')).tolist() dataset_train = RSNADataSet(tr_list, labels, img_pth, transform=True) dataset_valid = RSNADataSet(val_list,",
"args.dpath img_pth = os.path.join(args.dpath, 'processed_data/') numpy_path = os.path.join(args.dpath, 'data_split/') with open(os.path.join(dpath, 'rsna_annotation.json')) as",
"= DataLoader( dataset=dataset_test, batch_size=1, shuffle=False, num_workers=4, pin_memory=False) # Construct Model if args.optimised: alpha",
"tq(enumerate(self.data_loader_train)): var_target = var_target.to(self.device) var_input = var_input.to(self.device) var_output= self.model(var_input) trainloss_value = self.loss_fn( var_output,",
"np.mean(loss_train_list) valid_loss_mean = np.mean(loss_valid_list) return train_loss_mean, valid_loss_mean, auroc_mean def test(self): cudnn.benchmark = True",
"self.test() print(f\"Epoch:{epoch_id + 1}| EndTime:{timestamp_end}| TestAUROC: {test_auroc}| ValidAUROC: {auroc_max}\") def valid(self): self.model.eval() loss_valid_r",
"= torch.cat((out_pred, var_output), 0) lossvalue = self.loss_fn( var_output, tfunc.one_hot(var_target.squeeze(1).long(), num_classes=self.class_count).float()) loss_valid_r += lossvalue.item()",
"torch.load(checkpoint) self.optimizer.load_state_dict(model_checkpoint['optimizer']) else: model_checkpoint = None self.loss_fn = torch.nn.BCELoss() def train(self, max_epoch, savepath):",
"= torch.nn.BCELoss() def train(self, max_epoch, savepath): train_loss_min = 1e+5 # A random very",
"valid_loss_min, 'optimizer' : self.optimizer.state_dict()}, os.path.join(savepath, f'm-epoch-{epoch_id}.pth')) test_auroc = self.test() print(f\"Epoch:{epoch_id + 1}| EndTime:{timestamp_end}|",
"loss_valid_r = 0 valid_batches = 0 # Counter for valid batches out_gt =",
"= model.to(self.device) self.data_loader_train = data_loader_train self.data_loader_valid = data_loader_valid self.data_loader_test = data_loader_test self.class_names =",
"zero self.optimizer = optim.Adam(self.model.parameters(), lr=lr) if checkpoint is not None: model_checkpoint = torch.load(checkpoint)",
"auroc_mean scheduler.step() train_loss_mean = np.mean(loss_train_list) valid_loss_mean = np.mean(loss_valid_list) return train_loss_mean, valid_loss_mean, auroc_mean def",
"args.epochs class_count = args.clscount #The objective is to classify the image into 3",
"required=False, default=False, help=\"enable flag->eff model\", action='store_true') parser.add_argument(\"--alpha\", required=False, help=\"alpha for the model\", default=(11",
"class_count) else: model = DenseNet121(class_count) # Train the Model savepath = args.spath rsna_trainer",
"batch_size=batch_size, shuffle=True, num_workers=4, pin_memory=False) data_loader_valid = DataLoader( dataset=dataset_valid, batch_size=batch_size, shuffle=False, num_workers=4, pin_memory=False) dataset_test",
"mean:{auroc_mean}') for i, auroc_val in enumerate(auroc_individual): print(f\"{self.class_names[i]}:{auroc_val}\") return auroc_mean def main(args): lr =",
"main(args): lr = args.lr checkpoint = args.checkpoint batch_size = args.bs max_epoch = args.epochs",
"DataLoader from torch.optim.lr_scheduler import StepLR from .utils.dataloader import RSNADataSet from .utils.score import compute_auroc",
"print(len(auroc_individual)) auroc_mean = np.array(auroc_individual).mean() return valid_loss, auroc_mean def epoch_train(self): loss_train_list = [] loss_valid_list",
"Setting maximum AUROC value as zero self.optimizer = optim.Adam(self.model.parameters(), lr=lr) if checkpoint is",
"# Construct Model if args.optimised: alpha = args.alpha phi = args.phi beta =",
"should be saved\", type =str) parser.add_argument(\"--optimised\", required=False, default=False, help=\"enable flag->eff model\", action='store_true') parser.add_argument(\"--alpha\",",
"value as zero self.optimizer = optim.Adam(self.model.parameters(), lr=lr) if checkpoint is not None: model_checkpoint",
"transform=True) data_loader_test = DataLoader( dataset=dataset_test, batch_size=1, shuffle=False, num_workers=4, pin_memory=False) # Construct Model if",
"with torch.no_grad(): for i, (var_input, var_target) in enumerate(self.data_loader_test): var_target = var_target.to(self.device) var_input =",
"loss_train_list = [] loss_valid_list = [] self.model.train() scheduler = StepLR(self.optimizer, step_size=6, gamma=0.002) for",
"self.loss_fn = torch.nn.BCELoss() def train(self, max_epoch, savepath): train_loss_min = 1e+5 # A random",
"rsna_trainer = RSNATrainer( model, data_loader_train, data_loader_valid, data_loader_test, class_count,checkpoint, device, class_names, lr) rsna_trainer.train(max_epoch, savepath)",
"train_loss_value = trainloss_value.item() loss_train_list.append(train_loss_value) if batch_id % (len(self.data_loader_train)-1) == 0 and batch_id !=",
"= train_loss self.current_valid_loss = valid_loss timestamp_end = time.strftime(\"%H%M%S-%d%m%Y\") if train_loss < train_loss_min: train_loss_min",
"dpath = args.dpath img_pth = os.path.join(args.dpath, 'processed_data/') numpy_path = os.path.join(args.dpath, 'data_split/') with open(os.path.join(dpath,",
"type = str) parser.add_argument(\"--bs\", required=False, default=16, help=\"Batchsize\", type=int) parser.add_argument(\"--dpath\", required=True, help=\"Path to folder",
"pin_memory=False) # Construct Model if args.optimised: alpha = args.alpha phi = args.phi beta",
"default=(11 / 6), type=float) parser.add_argument(\"--phi\", required=False, help=\"Phi for the model.\", default=1.0, type=float) parser.add_argument(\"--beta\",",
"DenseNet121Eff from math import sqrt import json from tqdm import tqdm as tq",
"lab_file: labels = json.load(lab_file) # Place numpy file containing train-valid-test split on tools",
"return train_loss_mean, valid_loss_mean, auroc_mean def test(self): cudnn.benchmark = True out_gt = torch.FloatTensor().to(self.device) out_pred",
"valid_loss_min: valid_loss_min = valid_loss torch.save({'epoch': epoch_id + 1, 'state_dict': self.model.state_dict(), 'best_loss': valid_loss_min, 'optimizer'",
"as lab_file: labels = json.load(lab_file) # Place numpy file containing train-valid-test split on",
"'processed_data/') numpy_path = os.path.join(args.dpath, 'data_split/') with open(os.path.join(dpath, 'rsna_annotation.json')) as lab_file: labels = json.load(lab_file)",
"np.load(os.path.join(numpy_path,'test_list.npy')).tolist() dataset_train = RSNADataSet(tr_list, labels, img_pth, transform=True) dataset_valid = RSNADataSet(val_list, labels, img_pth, transform=True)",
"self.optimizer.load_state_dict(model_checkpoint['optimizer']) else: model_checkpoint = None self.loss_fn = torch.nn.BCELoss() def train(self, max_epoch, savepath): train_loss_min",
"var_target) in tq(enumerate(self.data_loader_train)): var_target = var_target.to(self.device) var_input = var_input.to(self.device) var_output= self.model(var_input) trainloss_value =",
"required=False, help=\"Phi for the model.\", default=1.0, type=float) parser.add_argument(\"--beta\", required=False, help=\"Beta for the model.\",",
"class RSNATrainer(): def __init__(self, model, data_loader_train, data_loader_valid, data_loader_test, class_count, checkpoint, device, class_names, lr):",
"/ valid_batches auroc_individual = compute_auroc( tfunc.one_hot(out_gt.squeeze(1).long()).float(), out_pred, self.class_count) print(len(auroc_individual)) auroc_mean = np.array(auroc_individual).mean() return",
"data_loader_train self.data_loader_valid = data_loader_valid self.data_loader_test = data_loader_test self.class_names = class_names self.class_count = class_count",
"Lung Opacity / Not Normal'] # Data Loader dpath = args.dpath img_pth =",
"from math import sqrt import json from tqdm import tqdm as tq class",
"train_loss if valid_loss < valid_loss_min: valid_loss_min = valid_loss torch.save({'epoch': epoch_id + 1, 'state_dict':",
"self.loss_fn( var_output, tfunc.one_hot(var_target.squeeze(1).long(), num_classes=self.class_count).float()) loss_valid_r += lossvalue.item() valid_batches += 1 valid_loss = loss_valid_r",
"dataset=dataset_test, batch_size=1, shuffle=False, num_workers=4, pin_memory=False) # Construct Model if args.optimised: alpha = args.alpha",
"var_output = self.model(var_input.to(self.device)) out_pred = torch.cat((out_pred, var_output), 0) lossvalue = self.loss_fn( var_output, tfunc.one_hot(var_target.squeeze(1).long(),",
"{test_auroc}| ValidAUROC: {auroc_max}\") def valid(self): self.model.eval() loss_valid_r = 0 valid_batches = 0 #",
"if checkpoint is not None: model_checkpoint = torch.load(checkpoint) self.optimizer.load_state_dict(model_checkpoint['optimizer']) else: model_checkpoint = None",
"rsna_trainer.train(max_epoch, savepath) print(\"Model trained !\") if __name__==\"__main__\": parser = argparse.ArgumentParser() parser.add_argument(\"--lr\", required=False, help=\"Learning",
"phi = args.phi beta = args.beta if beta is None: beta = round(sqrt(2",
"valid batches out_gt = torch.FloatTensor().to(self.device) out_pred = torch.FloatTensor().to(self.device) with torch.no_grad(): for (var_input, var_target)",
"from .utils.score import compute_auroc from .utils.model import DenseNet121, DenseNet121Eff from math import sqrt",
"== 0 and batch_id != 0: validloss_value, auroc_mean = self.valid() loss_valid_list.append(validloss_value) if auroc_mean",
"scheduler = StepLR(self.optimizer, step_size=6, gamma=0.002) for batch_id, (var_input, var_target) in tq(enumerate(self.data_loader_train)): var_target =",
"1e+5 for epoch_id in range(max_epoch): print(f\"Epoch {epoch_id+1}/{max_epoch}\") self.gepoch_id = epoch_id train_loss, valid_loss, auroc_max",
"= var_input.to(self.device) var_output= self.model(var_input) trainloss_value = self.loss_fn( var_output, tfunc.one_hot(var_target.squeeze(1).long(), num_classes=self.class_count).float()) self.optimizer.zero_grad() trainloss_value.backward() self.optimizer.step()",
"valid_loss_mean = np.mean(loss_valid_list) return train_loss_mean, valid_loss_mean, auroc_mean def test(self): cudnn.benchmark = True out_gt",
"auroc obtained') self.auroc_max = auroc_mean scheduler.step() train_loss_mean = np.mean(loss_train_list) valid_loss_mean = np.mean(loss_valid_list) return",
"time.strftime(\"%H%M%S-%d%m%Y\") if train_loss < train_loss_min: train_loss_min = train_loss if valid_loss < valid_loss_min: valid_loss_min",
".utils.dataloader import RSNADataSet from .utils.score import compute_auroc from .utils.model import DenseNet121, DenseNet121Eff from",
"parser.add_argument(\"--dpath\", required=True, help=\"Path to folder containing all data\", type =str) parser.add_argument(\"--epochs\", required=False, default=15,",
"all data\", type =str) parser.add_argument(\"--epochs\", required=False, default=15, help=\"Number of epochs\", type=int) parser.add_argument(\"--clscount\", required=False,",
"** phi beta = beta ** phi model = DenseNet121Eff(alpha, beta, class_count) else:",
"beta is None: beta = round(sqrt(2 / alpha), 3) alpha = alpha **",
"c, h, w = var_input.size() var_input = var_input.view(-1, c, h, w) out =",
"to folder containing all data\", type =str) parser.add_argument(\"--epochs\", required=False, default=15, help=\"Number of epochs\",",
"return auroc_mean def main(args): lr = args.lr checkpoint = args.checkpoint batch_size = args.bs",
"from .utils.dataloader import RSNADataSet from .utils.score import compute_auroc from .utils.model import DenseNet121, DenseNet121Eff",
"shuffle=True, num_workers=4, pin_memory=False) data_loader_valid = DataLoader( dataset=dataset_valid, batch_size=batch_size, shuffle=False, num_workers=4, pin_memory=False) dataset_test =",
"if __name__==\"__main__\": parser = argparse.ArgumentParser() parser.add_argument(\"--lr\", required=False, help=\"Learning rate\", default=1e-4, type = float)",
"required=False, default=3, help=\"Number of classes\", type=int) parser.add_argument(\"--spath\", required=True, help=\"Path to folder in which",
"return valid_loss, auroc_mean def epoch_train(self): loss_train_list = [] loss_valid_list = [] self.model.train() scheduler",
"savepath): train_loss_min = 1e+5 # A random very high number valid_loss_min = 1e+5",
"__init__(self, model, data_loader_train, data_loader_valid, data_loader_test, class_count, checkpoint, device, class_names, lr): self.gepoch_id = 0",
"var_input.size() var_input = var_input.view(-1, c, h, w) out = self.model(var_input) out_pred = torch.cat((out_pred,",
"data_loader_test, class_count,checkpoint, device, class_names, lr) rsna_trainer.train(max_epoch, savepath) print(\"Model trained !\") if __name__==\"__main__\": parser",
"[] self.model.train() scheduler = StepLR(self.optimizer, step_size=6, gamma=0.002) for batch_id, (var_input, var_target) in tq(enumerate(self.data_loader_train)):",
"shuffle=False, num_workers=4, pin_memory=False) # Construct Model if args.optimised: alpha = args.alpha phi =",
"if torch.cuda.is_available() else \"cpu\") # use gpu if available class_names = ['Lung Opacity',",
"A random very high number valid_loss_min = 1e+5 for epoch_id in range(max_epoch): print(f\"Epoch",
"range(max_epoch): print(f\"Epoch {epoch_id+1}/{max_epoch}\") self.gepoch_id = epoch_id train_loss, valid_loss, auroc_max = self.epoch_train() self.current_train_loss =",
"valid_loss < valid_loss_min: valid_loss_min = valid_loss torch.save({'epoch': epoch_id + 1, 'state_dict': self.model.state_dict(), 'best_loss':",
"{auroc_max}\") def valid(self): self.model.eval() loss_valid_r = 0 valid_batches = 0 # Counter for",
"round(sqrt(2 / alpha), 3) alpha = alpha ** phi beta = beta **",
"num_classes=self.class_count).float()) loss_valid_r += lossvalue.item() valid_batches += 1 valid_loss = loss_valid_r / valid_batches auroc_individual",
"= torch.cat((out_pred, out), 0) auroc_individual = compute_auroc(tfunc.one_hot(out_gt.squeeze(1).long()).float(), out_pred, self.class_count) auroc_mean = np.array(auroc_individual).mean() print(f'AUROC",
"labels, img_pth, transform=True) data_loader_train = DataLoader( dataset=dataset_train, batch_size=batch_size, shuffle=True, num_workers=4, pin_memory=False) data_loader_valid =",
"import compute_auroc from .utils.model import DenseNet121, DenseNet121Eff from math import sqrt import json",
"parser.add_argument(\"--epochs\", required=False, default=15, help=\"Number of epochs\", type=int) parser.add_argument(\"--clscount\", required=False, default=3, help=\"Number of classes\",",
"AUROC value as zero self.optimizer = optim.Adam(self.model.parameters(), lr=lr) if checkpoint is not None:",
"auroc_individual = compute_auroc( tfunc.one_hot(out_gt.squeeze(1).long()).float(), out_pred, self.class_count) print(len(auroc_individual)) auroc_mean = np.array(auroc_individual).mean() return valid_loss, auroc_mean",
"tools folder tr_list = np.load(os.path.join(numpy_path,'train_list.npy')).tolist() val_list = np.load(os.path.join(numpy_path,'valid_list.npy')).tolist() test_list = np.load(os.path.join(numpy_path,'test_list.npy')).tolist() dataset_train =",
"args.beta if beta is None: beta = round(sqrt(2 / alpha), 3) alpha =",
"None: beta = round(sqrt(2 / alpha), 3) alpha = alpha ** phi beta",
"if valid_loss < valid_loss_min: valid_loss_min = valid_loss torch.save({'epoch': epoch_id + 1, 'state_dict': self.model.state_dict(),",
"which models should be saved\", type =str) parser.add_argument(\"--optimised\", required=False, default=False, help=\"enable flag->eff model\",",
"self.optimizer.state_dict()}, os.path.join(savepath, f'm-epoch-{epoch_id}.pth')) test_auroc = self.test() print(f\"Epoch:{epoch_id + 1}| EndTime:{timestamp_end}| TestAUROC: {test_auroc}| ValidAUROC:",
"= [] self.model.train() scheduler = StepLR(self.optimizer, step_size=6, gamma=0.002) for batch_id, (var_input, var_target) in",
"= StepLR(self.optimizer, step_size=6, gamma=0.002) for batch_id, (var_input, var_target) in tq(enumerate(self.data_loader_train)): var_target = var_target.to(self.device)",
"valid(self): self.model.eval() loss_valid_r = 0 valid_batches = 0 # Counter for valid batches",
"trainloss_value.backward() self.optimizer.step() train_loss_value = trainloss_value.item() loss_train_list.append(train_loss_value) if batch_id % (len(self.data_loader_train)-1) == 0 and",
"var_input = var_input.view(-1, c, h, w) out = self.model(var_input) out_pred = torch.cat((out_pred, out),",
"!= 0: validloss_value, auroc_mean = self.valid() loss_valid_list.append(validloss_value) if auroc_mean > self.auroc_max: print('Better auroc",
"img_pth, transform=True) dataset_valid = RSNADataSet(val_list, labels, img_pth, transform=True) data_loader_train = DataLoader( dataset=dataset_train, batch_size=batch_size,",
"the model\", default=(11 / 6), type=float) parser.add_argument(\"--phi\", required=False, help=\"Phi for the model.\", default=1.0,",
"DenseNet121Eff(alpha, beta, class_count) else: model = DenseNet121(class_count) # Train the Model savepath =",
"self.device = device self.model = model.to(self.device) self.data_loader_train = data_loader_train self.data_loader_valid = data_loader_valid self.data_loader_test",
"RSNATrainer(): def __init__(self, model, data_loader_train, data_loader_valid, data_loader_test, class_count, checkpoint, device, class_names, lr): self.gepoch_id",
"loss_train_list.append(train_loss_value) if batch_id % (len(self.data_loader_train)-1) == 0 and batch_id != 0: validloss_value, auroc_mean",
"dataset_train = RSNADataSet(tr_list, labels, img_pth, transform=True) dataset_valid = RSNADataSet(val_list, labels, img_pth, transform=True) data_loader_train",
"batch_size = args.bs max_epoch = args.epochs class_count = args.clscount #The objective is to",
"data\", type =str) parser.add_argument(\"--epochs\", required=False, default=15, help=\"Number of epochs\", type=int) parser.add_argument(\"--clscount\", required=False, default=3,",
"as tfunc from torch.utils.data import DataLoader from torch.optim.lr_scheduler import StepLR from .utils.dataloader import",
"= torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\") # use gpu if available class_names =",
"trained !\") if __name__==\"__main__\": parser = argparse.ArgumentParser() parser.add_argument(\"--lr\", required=False, help=\"Learning rate\", default=1e-4, type",
"= DataLoader( dataset=dataset_valid, batch_size=batch_size, shuffle=False, num_workers=4, pin_memory=False) dataset_test = RSNADataSet(test_list, labels, img_pth, transform=True)",
"self.model(var_input.to(self.device)) out_pred = torch.cat((out_pred, var_output), 0) lossvalue = self.loss_fn( var_output, tfunc.one_hot(var_target.squeeze(1).long(), num_classes=self.class_count).float()) loss_valid_r",
"= torch.FloatTensor().to(self.device) out_pred = torch.FloatTensor().to(self.device) self.model.eval() with torch.no_grad(): for i, (var_input, var_target) in",
"(var_input, var_target) in tq(enumerate(self.data_loader_train)): var_target = var_target.to(self.device) var_input = var_input.to(self.device) var_output= self.model(var_input) trainloss_value",
"val_list = np.load(os.path.join(numpy_path,'valid_list.npy')).tolist() test_list = np.load(os.path.join(numpy_path,'test_list.npy')).tolist() dataset_train = RSNADataSet(tr_list, labels, img_pth, transform=True) dataset_valid",
"alpha ** phi beta = beta ** phi model = DenseNet121Eff(alpha, beta, class_count)",
"0) lossvalue = self.loss_fn( var_output, tfunc.one_hot(var_target.squeeze(1).long(), num_classes=self.class_count).float()) loss_valid_r += lossvalue.item() valid_batches += 1",
"torch.FloatTensor().to(self.device) with torch.no_grad(): for (var_input, var_target) in tq(self.data_loader_valid): var_target = var_target.to(self.device) out_gt =",
"= 1e+5 # A random very high number valid_loss_min = 1e+5 for epoch_id",
"var_target) in tq(self.data_loader_valid): var_target = var_target.to(self.device) out_gt = torch.cat((out_gt, var_target), 0).to(self.device) _, c,",
"h, w = var_input.size() var_input = var_input.view(-1, c, h, w) var_output = self.model(var_input.to(self.device))",
"torch.cat((out_gt, var_target), 0).to(self.device) _, c, h, w = var_input.size() var_input = var_input.view(-1, c,",
"var_input.to(self.device) var_output= self.model(var_input) trainloss_value = self.loss_fn( var_output, tfunc.one_hot(var_target.squeeze(1).long(), num_classes=self.class_count).float()) self.optimizer.zero_grad() trainloss_value.backward() self.optimizer.step() train_loss_value",
"self.model = model.to(self.device) self.data_loader_train = data_loader_train self.data_loader_valid = data_loader_valid self.data_loader_test = data_loader_test self.class_names",
"1 valid_loss = loss_valid_r / valid_batches auroc_individual = compute_auroc( tfunc.one_hot(out_gt.squeeze(1).long()).float(), out_pred, self.class_count) print(len(auroc_individual))",
"pin_memory=False) data_loader_valid = DataLoader( dataset=dataset_valid, batch_size=batch_size, shuffle=False, num_workers=4, pin_memory=False) dataset_test = RSNADataSet(test_list, labels,",
"self.gepoch_id = 0 self.device = device self.model = model.to(self.device) self.data_loader_train = data_loader_train self.data_loader_valid",
"torch.cat((out_pred, var_output), 0) lossvalue = self.loss_fn( var_output, tfunc.one_hot(var_target.squeeze(1).long(), num_classes=self.class_count).float()) loss_valid_r += lossvalue.item() valid_batches",
"gamma=0.002) for batch_id, (var_input, var_target) in tq(enumerate(self.data_loader_train)): var_target = var_target.to(self.device) var_input = var_input.to(self.device)",
"print('Better auroc obtained') self.auroc_max = auroc_mean scheduler.step() train_loss_mean = np.mean(loss_train_list) valid_loss_mean = np.mean(loss_valid_list)",
"help=\"Path to folder containing all data\", type =str) parser.add_argument(\"--epochs\", required=False, default=15, help=\"Number of",
"into 3 classes device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\") # use gpu",
"batch_size=batch_size, shuffle=False, num_workers=4, pin_memory=False) dataset_test = RSNADataSet(test_list, labels, img_pth, transform=True) data_loader_test = DataLoader(",
"for the model.\", default=1.0, type=float) parser.add_argument(\"--beta\", required=False, help=\"Beta for the model.\", default=None, type=float)",
"= valid_loss torch.save({'epoch': epoch_id + 1, 'state_dict': self.model.state_dict(), 'best_loss': valid_loss_min, 'optimizer' : self.optimizer.state_dict()},",
"= np.array(auroc_individual).mean() print(f'AUROC mean:{auroc_mean}') for i, auroc_val in enumerate(auroc_individual): print(f\"{self.class_names[i]}:{auroc_val}\") return auroc_mean def",
"RSNADataSet(test_list, labels, img_pth, transform=True) data_loader_test = DataLoader( dataset=dataset_test, batch_size=1, shuffle=False, num_workers=4, pin_memory=False) #",
"f'm-epoch-{epoch_id}.pth')) test_auroc = self.test() print(f\"Epoch:{epoch_id + 1}| EndTime:{timestamp_end}| TestAUROC: {test_auroc}| ValidAUROC: {auroc_max}\") def",
"#The objective is to classify the image into 3 classes device = torch.device(\"cuda\"",
"= self.loss_fn( var_output, tfunc.one_hot(var_target.squeeze(1).long(), num_classes=self.class_count).float()) loss_valid_r += lossvalue.item() valid_batches += 1 valid_loss =",
"=str) parser.add_argument(\"--optimised\", required=False, default=False, help=\"enable flag->eff model\", action='store_true') parser.add_argument(\"--alpha\", required=False, help=\"alpha for the",
"parser.add_argument(\"--optimised\", required=False, default=False, help=\"enable flag->eff model\", action='store_true') parser.add_argument(\"--alpha\", required=False, help=\"alpha for the model\",",
"required=False, default=15, help=\"Number of epochs\", type=int) parser.add_argument(\"--clscount\", required=False, default=3, help=\"Number of classes\", type=int)",
"type =str) parser.add_argument(\"--optimised\", required=False, default=False, help=\"enable flag->eff model\", action='store_true') parser.add_argument(\"--alpha\", required=False, help=\"alpha for",
"data_loader_valid, data_loader_test, class_count, checkpoint, device, class_names, lr): self.gepoch_id = 0 self.device = device",
"var_target) in enumerate(self.data_loader_test): var_target = var_target.to(self.device) var_input = var_input.to(self.device) out_gt = torch.cat((out_gt, var_target),",
"def test(self): cudnn.benchmark = True out_gt = torch.FloatTensor().to(self.device) out_pred = torch.FloatTensor().to(self.device) self.model.eval() with",
"= data_loader_valid self.data_loader_test = data_loader_test self.class_names = class_names self.class_count = class_count self.auroc_max =",
"= class_names self.class_count = class_count self.auroc_max = 0.0 # Setting maximum AUROC value",
"self.data_loader_test = data_loader_test self.class_names = class_names self.class_count = class_count self.auroc_max = 0.0 #",
"as np import time import os import argparse import torch from torch.backends import",
"train_loss_min = 1e+5 # A random very high number valid_loss_min = 1e+5 for",
"epoch_id in range(max_epoch): print(f\"Epoch {epoch_id+1}/{max_epoch}\") self.gepoch_id = epoch_id train_loss, valid_loss, auroc_max = self.epoch_train()",
"dataset_valid = RSNADataSet(val_list, labels, img_pth, transform=True) data_loader_train = DataLoader( dataset=dataset_train, batch_size=batch_size, shuffle=True, num_workers=4,",
"img_pth, transform=True) data_loader_test = DataLoader( dataset=dataset_test, batch_size=1, shuffle=False, num_workers=4, pin_memory=False) # Construct Model",
"print(f\"Epoch {epoch_id+1}/{max_epoch}\") self.gepoch_id = epoch_id train_loss, valid_loss, auroc_max = self.epoch_train() self.current_train_loss = train_loss",
"# use gpu if available class_names = ['Lung Opacity', 'Normal', 'No Lung Opacity",
"def main(args): lr = args.lr checkpoint = args.checkpoint batch_size = args.bs max_epoch =",
"folder in which models should be saved\", type =str) parser.add_argument(\"--optimised\", required=False, default=False, help=\"enable",
"batch_id != 0: validloss_value, auroc_mean = self.valid() loss_valid_list.append(validloss_value) if auroc_mean > self.auroc_max: print('Better",
"cudnn from torch import optim import torch.nn.functional as tfunc from torch.utils.data import DataLoader",
"tqdm import tqdm as tq class RSNATrainer(): def __init__(self, model, data_loader_train, data_loader_valid, data_loader_test,",
"out_gt = torch.FloatTensor().to(self.device) out_pred = torch.FloatTensor().to(self.device) self.model.eval() with torch.no_grad(): for i, (var_input, var_target)",
"var_input = var_input.to(self.device) out_gt = torch.cat((out_gt, var_target), 0).to(self.device) _, c, h, w =",
"w = var_input.size() var_input = var_input.view(-1, c, h, w) out = self.model(var_input) out_pred",
"+= lossvalue.item() valid_batches += 1 valid_loss = loss_valid_r / valid_batches auroc_individual = compute_auroc(",
"if batch_id % (len(self.data_loader_train)-1) == 0 and batch_id != 0: validloss_value, auroc_mean =",
"for (var_input, var_target) in tq(self.data_loader_valid): var_target = var_target.to(self.device) out_gt = torch.cat((out_gt, var_target), 0).to(self.device)",
"lossvalue.item() valid_batches += 1 valid_loss = loss_valid_r / valid_batches auroc_individual = compute_auroc( tfunc.one_hot(out_gt.squeeze(1).long()).float(),",
"= compute_auroc(tfunc.one_hot(out_gt.squeeze(1).long()).float(), out_pred, self.class_count) auroc_mean = np.array(auroc_individual).mean() print(f'AUROC mean:{auroc_mean}') for i, auroc_val in",
"args.phi beta = args.beta if beta is None: beta = round(sqrt(2 / alpha),",
"transform=True) dataset_valid = RSNADataSet(val_list, labels, img_pth, transform=True) data_loader_train = DataLoader( dataset=dataset_train, batch_size=batch_size, shuffle=True,",
"torch import optim import torch.nn.functional as tfunc from torch.utils.data import DataLoader from torch.optim.lr_scheduler",
"var_output= self.model(var_input) trainloss_value = self.loss_fn( var_output, tfunc.one_hot(var_target.squeeze(1).long(), num_classes=self.class_count).float()) self.optimizer.zero_grad() trainloss_value.backward() self.optimizer.step() train_loss_value =",
"np.load(os.path.join(numpy_path,'train_list.npy')).tolist() val_list = np.load(os.path.join(numpy_path,'valid_list.npy')).tolist() test_list = np.load(os.path.join(numpy_path,'test_list.npy')).tolist() dataset_train = RSNADataSet(tr_list, labels, img_pth, transform=True)",
"is None: beta = round(sqrt(2 / alpha), 3) alpha = alpha ** phi",
"very high number valid_loss_min = 1e+5 for epoch_id in range(max_epoch): print(f\"Epoch {epoch_id+1}/{max_epoch}\") self.gepoch_id",
"lr = args.lr checkpoint = args.checkpoint batch_size = args.bs max_epoch = args.epochs class_count",
"/ alpha), 3) alpha = alpha ** phi beta = beta ** phi",
"required=False, default=16, help=\"Batchsize\", type=int) parser.add_argument(\"--dpath\", required=True, help=\"Path to folder containing all data\", type",
"var_target = var_target.to(self.device) var_input = var_input.to(self.device) out_gt = torch.cat((out_gt, var_target), 0).to(self.device) _, c,",
"model\", action='store_true') parser.add_argument(\"--alpha\", required=False, help=\"alpha for the model\", default=(11 / 6), type=float) parser.add_argument(\"--phi\",",
"torch.optim.lr_scheduler import StepLR from .utils.dataloader import RSNADataSet from .utils.score import compute_auroc from .utils.model",
"out_pred, self.class_count) print(len(auroc_individual)) auroc_mean = np.array(auroc_individual).mean() return valid_loss, auroc_mean def epoch_train(self): loss_train_list =",
"parser.add_argument(\"--checkpoint\", required=False, help=\"Checkpoint model weight\", default= None, type = str) parser.add_argument(\"--bs\", required=False, default=16,",
"available class_names = ['Lung Opacity', 'Normal', 'No Lung Opacity / Not Normal'] #",
"= compute_auroc( tfunc.one_hot(out_gt.squeeze(1).long()).float(), out_pred, self.class_count) print(len(auroc_individual)) auroc_mean = np.array(auroc_individual).mean() return valid_loss, auroc_mean def",
"= trainloss_value.item() loss_train_list.append(train_loss_value) if batch_id % (len(self.data_loader_train)-1) == 0 and batch_id != 0:",
"/ Not Normal'] # Data Loader dpath = args.dpath img_pth = os.path.join(args.dpath, 'processed_data/')",
"= var_target.to(self.device) out_gt = torch.cat((out_gt, var_target), 0).to(self.device) _, c, h, w = var_input.size()",
"= self.test() print(f\"Epoch:{epoch_id + 1}| EndTime:{timestamp_end}| TestAUROC: {test_auroc}| ValidAUROC: {auroc_max}\") def valid(self): self.model.eval()",
"import DataLoader from torch.optim.lr_scheduler import StepLR from .utils.dataloader import RSNADataSet from .utils.score import",
"float) parser.add_argument(\"--checkpoint\", required=False, help=\"Checkpoint model weight\", default= None, type = str) parser.add_argument(\"--bs\", required=False,",
"> self.auroc_max: print('Better auroc obtained') self.auroc_max = auroc_mean scheduler.step() train_loss_mean = np.mean(loss_train_list) valid_loss_mean",
"beta ** phi model = DenseNet121Eff(alpha, beta, class_count) else: model = DenseNet121(class_count) #",
"= os.path.join(args.dpath, 'processed_data/') numpy_path = os.path.join(args.dpath, 'data_split/') with open(os.path.join(dpath, 'rsna_annotation.json')) as lab_file: labels",
"var_target.to(self.device) out_gt = torch.cat((out_gt, var_target), 0).to(self.device) _, c, h, w = var_input.size() var_input",
"self.model(var_input) out_pred = torch.cat((out_pred, out), 0) auroc_individual = compute_auroc(tfunc.one_hot(out_gt.squeeze(1).long()).float(), out_pred, self.class_count) auroc_mean =",
"as zero self.optimizer = optim.Adam(self.model.parameters(), lr=lr) if checkpoint is not None: model_checkpoint =",
"tfunc from torch.utils.data import DataLoader from torch.optim.lr_scheduler import StepLR from .utils.dataloader import RSNADataSet",
"if available class_names = ['Lung Opacity', 'Normal', 'No Lung Opacity / Not Normal']",
"= RSNADataSet(test_list, labels, img_pth, transform=True) data_loader_test = DataLoader( dataset=dataset_test, batch_size=1, shuffle=False, num_workers=4, pin_memory=False)",
"Place numpy file containing train-valid-test split on tools folder tr_list = np.load(os.path.join(numpy_path,'train_list.npy')).tolist() val_list",
"\"cpu\") # use gpu if available class_names = ['Lung Opacity', 'Normal', 'No Lung",
"device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\") # use gpu if available class_names",
"if args.optimised: alpha = args.alpha phi = args.phi beta = args.beta if beta",
"Counter for valid batches out_gt = torch.FloatTensor().to(self.device) out_pred = torch.FloatTensor().to(self.device) with torch.no_grad(): for",
"transform=True) data_loader_train = DataLoader( dataset=dataset_train, batch_size=batch_size, shuffle=True, num_workers=4, pin_memory=False) data_loader_valid = DataLoader( dataset=dataset_valid,",
"= torch.load(checkpoint) self.optimizer.load_state_dict(model_checkpoint['optimizer']) else: model_checkpoint = None self.loss_fn = torch.nn.BCELoss() def train(self, max_epoch,",
"data_loader_train, data_loader_valid, data_loader_test, class_count,checkpoint, device, class_names, lr) rsna_trainer.train(max_epoch, savepath) print(\"Model trained !\") if",
"import optim import torch.nn.functional as tfunc from torch.utils.data import DataLoader from torch.optim.lr_scheduler import",
"else \"cpu\") # use gpu if available class_names = ['Lung Opacity', 'Normal', 'No",
"= ['Lung Opacity', 'Normal', 'No Lung Opacity / Not Normal'] # Data Loader",
"<reponame>e-ddykim/training_extensions<filename>misc/pytorch_toolkit/chest_xray_screening/chest_xray_screening/train.py import numpy as np import time import os import argparse import torch",
"to classify the image into 3 classes device = torch.device(\"cuda\" if torch.cuda.is_available() else",
"= RSNADataSet(tr_list, labels, img_pth, transform=True) dataset_valid = RSNADataSet(val_list, labels, img_pth, transform=True) data_loader_train =",
"from .utils.model import DenseNet121, DenseNet121Eff from math import sqrt import json from tqdm",
"dataset_test = RSNADataSet(test_list, labels, img_pth, transform=True) data_loader_test = DataLoader( dataset=dataset_test, batch_size=1, shuffle=False, num_workers=4,",
"required=False, help=\"Checkpoint model weight\", default= None, type = str) parser.add_argument(\"--bs\", required=False, default=16, help=\"Batchsize\",",
"def epoch_train(self): loss_train_list = [] loss_valid_list = [] self.model.train() scheduler = StepLR(self.optimizer, step_size=6,",
"enumerate(auroc_individual): print(f\"{self.class_names[i]}:{auroc_val}\") return auroc_mean def main(args): lr = args.lr checkpoint = args.checkpoint batch_size",
"model = DenseNet121Eff(alpha, beta, class_count) else: model = DenseNet121(class_count) # Train the Model",
"= args.clscount #The objective is to classify the image into 3 classes device",
"str) parser.add_argument(\"--bs\", required=False, default=16, help=\"Batchsize\", type=int) parser.add_argument(\"--dpath\", required=True, help=\"Path to folder containing all",
"_, c, h, w = var_input.size() var_input = var_input.view(-1, c, h, w) var_output",
"in which models should be saved\", type =str) parser.add_argument(\"--optimised\", required=False, default=False, help=\"enable flag->eff",
"self.optimizer = optim.Adam(self.model.parameters(), lr=lr) if checkpoint is not None: model_checkpoint = torch.load(checkpoint) self.optimizer.load_state_dict(model_checkpoint['optimizer'])",
"img_pth, transform=True) data_loader_train = DataLoader( dataset=dataset_train, batch_size=batch_size, shuffle=True, num_workers=4, pin_memory=False) data_loader_valid = DataLoader(",
"= var_target.to(self.device) var_input = var_input.to(self.device) var_output= self.model(var_input) trainloss_value = self.loss_fn( var_output, tfunc.one_hot(var_target.squeeze(1).long(), num_classes=self.class_count).float())",
"labels, img_pth, transform=True) data_loader_test = DataLoader( dataset=dataset_test, batch_size=1, shuffle=False, num_workers=4, pin_memory=False) # Construct",
"var_input.view(-1, c, h, w) var_output = self.model(var_input.to(self.device)) out_pred = torch.cat((out_pred, var_output), 0) lossvalue",
"epoch_id + 1, 'state_dict': self.model.state_dict(), 'best_loss': valid_loss_min, 'optimizer' : self.optimizer.state_dict()}, os.path.join(savepath, f'm-epoch-{epoch_id}.pth')) test_auroc",
"'best_loss': valid_loss_min, 'optimizer' : self.optimizer.state_dict()}, os.path.join(savepath, f'm-epoch-{epoch_id}.pth')) test_auroc = self.test() print(f\"Epoch:{epoch_id + 1}|",
"'data_split/') with open(os.path.join(dpath, 'rsna_annotation.json')) as lab_file: labels = json.load(lab_file) # Place numpy file",
"Opacity / Not Normal'] # Data Loader dpath = args.dpath img_pth = os.path.join(args.dpath,",
"import time import os import argparse import torch from torch.backends import cudnn from",
"= str) parser.add_argument(\"--bs\", required=False, default=16, help=\"Batchsize\", type=int) parser.add_argument(\"--dpath\", required=True, help=\"Path to folder containing",
"out), 0) auroc_individual = compute_auroc(tfunc.one_hot(out_gt.squeeze(1).long()).float(), out_pred, self.class_count) auroc_mean = np.array(auroc_individual).mean() print(f'AUROC mean:{auroc_mean}') for",
"data_loader_test = DataLoader( dataset=dataset_test, batch_size=1, shuffle=False, num_workers=4, pin_memory=False) # Construct Model if args.optimised:",
"dataset=dataset_valid, batch_size=batch_size, shuffle=False, num_workers=4, pin_memory=False) dataset_test = RSNADataSet(test_list, labels, img_pth, transform=True) data_loader_test =",
"if beta is None: beta = round(sqrt(2 / alpha), 3) alpha = alpha",
"image into 3 classes device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\") # use",
"=str) parser.add_argument(\"--epochs\", required=False, default=15, help=\"Number of epochs\", type=int) parser.add_argument(\"--clscount\", required=False, default=3, help=\"Number of",
"0 self.device = device self.model = model.to(self.device) self.data_loader_train = data_loader_train self.data_loader_valid = data_loader_valid",
"default= None, type = str) parser.add_argument(\"--bs\", required=False, default=16, help=\"Batchsize\", type=int) parser.add_argument(\"--dpath\", required=True, help=\"Path",
"torch.nn.BCELoss() def train(self, max_epoch, savepath): train_loss_min = 1e+5 # A random very high",
"enumerate(self.data_loader_test): var_target = var_target.to(self.device) var_input = var_input.to(self.device) out_gt = torch.cat((out_gt, var_target), 0).to(self.device) _,",
"import torch.nn.functional as tfunc from torch.utils.data import DataLoader from torch.optim.lr_scheduler import StepLR from",
"the image into 3 classes device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\") #",
"required=False, help=\"Learning rate\", default=1e-4, type = float) parser.add_argument(\"--checkpoint\", required=False, help=\"Checkpoint model weight\", default=",
"and batch_id != 0: validloss_value, auroc_mean = self.valid() loss_valid_list.append(validloss_value) if auroc_mean > self.auroc_max:",
"num_workers=4, pin_memory=False) dataset_test = RSNADataSet(test_list, labels, img_pth, transform=True) data_loader_test = DataLoader( dataset=dataset_test, batch_size=1,",
"= beta ** phi model = DenseNet121Eff(alpha, beta, class_count) else: model = DenseNet121(class_count)",
"sqrt import json from tqdm import tqdm as tq class RSNATrainer(): def __init__(self,",
"trainloss_value.item() loss_train_list.append(train_loss_value) if batch_id % (len(self.data_loader_train)-1) == 0 and batch_id != 0: validloss_value,",
"class_count,checkpoint, device, class_names, lr) rsna_trainer.train(max_epoch, savepath) print(\"Model trained !\") if __name__==\"__main__\": parser =",
"= torch.FloatTensor().to(self.device) self.model.eval() with torch.no_grad(): for i, (var_input, var_target) in enumerate(self.data_loader_test): var_target =",
"import numpy as np import time import os import argparse import torch from",
"auroc_max = self.epoch_train() self.current_train_loss = train_loss self.current_valid_loss = valid_loss timestamp_end = time.strftime(\"%H%M%S-%d%m%Y\") if",
"import argparse import torch from torch.backends import cudnn from torch import optim import",
"maximum AUROC value as zero self.optimizer = optim.Adam(self.model.parameters(), lr=lr) if checkpoint is not",
"var_output, tfunc.one_hot(var_target.squeeze(1).long(), num_classes=self.class_count).float()) self.optimizer.zero_grad() trainloss_value.backward() self.optimizer.step() train_loss_value = trainloss_value.item() loss_train_list.append(train_loss_value) if batch_id %",
"'optimizer' : self.optimizer.state_dict()}, os.path.join(savepath, f'm-epoch-{epoch_id}.pth')) test_auroc = self.test() print(f\"Epoch:{epoch_id + 1}| EndTime:{timestamp_end}| TestAUROC:",
"= 0.0 # Setting maximum AUROC value as zero self.optimizer = optim.Adam(self.model.parameters(), lr=lr)",
"lr): self.gepoch_id = 0 self.device = device self.model = model.to(self.device) self.data_loader_train = data_loader_train",
"folder tr_list = np.load(os.path.join(numpy_path,'train_list.npy')).tolist() val_list = np.load(os.path.join(numpy_path,'valid_list.npy')).tolist() test_list = np.load(os.path.join(numpy_path,'test_list.npy')).tolist() dataset_train = RSNADataSet(tr_list,",
"help=\"Phi for the model.\", default=1.0, type=float) parser.add_argument(\"--beta\", required=False, help=\"Beta for the model.\", default=None,",
"is not None: model_checkpoint = torch.load(checkpoint) self.optimizer.load_state_dict(model_checkpoint['optimizer']) else: model_checkpoint = None self.loss_fn =",
"folder containing all data\", type =str) parser.add_argument(\"--epochs\", required=False, default=15, help=\"Number of epochs\", type=int)",
"torch.utils.data import DataLoader from torch.optim.lr_scheduler import StepLR from .utils.dataloader import RSNADataSet from .utils.score",
"parser.add_argument(\"--bs\", required=False, default=16, help=\"Batchsize\", type=int) parser.add_argument(\"--dpath\", required=True, help=\"Path to folder containing all data\",",
"# Train the Model savepath = args.spath rsna_trainer = RSNATrainer( model, data_loader_train, data_loader_valid,",
"default=15, help=\"Number of epochs\", type=int) parser.add_argument(\"--clscount\", required=False, default=3, help=\"Number of classes\", type=int) parser.add_argument(\"--spath\",",
"valid_batches auroc_individual = compute_auroc( tfunc.one_hot(out_gt.squeeze(1).long()).float(), out_pred, self.class_count) print(len(auroc_individual)) auroc_mean = np.array(auroc_individual).mean() return valid_loss,",
"= auroc_mean scheduler.step() train_loss_mean = np.mean(loss_train_list) valid_loss_mean = np.mean(loss_valid_list) return train_loss_mean, valid_loss_mean, auroc_mean",
"self.auroc_max: print('Better auroc obtained') self.auroc_max = auroc_mean scheduler.step() train_loss_mean = np.mean(loss_train_list) valid_loss_mean =",
"is to classify the image into 3 classes device = torch.device(\"cuda\" if torch.cuda.is_available()",
"var_target.to(self.device) var_input = var_input.to(self.device) var_output= self.model(var_input) trainloss_value = self.loss_fn( var_output, tfunc.one_hot(var_target.squeeze(1).long(), num_classes=self.class_count).float()) self.optimizer.zero_grad()",
"beta = args.beta if beta is None: beta = round(sqrt(2 / alpha), 3)",
"= 0 self.device = device self.model = model.to(self.device) self.data_loader_train = data_loader_train self.data_loader_valid =",
"= DenseNet121Eff(alpha, beta, class_count) else: model = DenseNet121(class_count) # Train the Model savepath",
"var_target.to(self.device) var_input = var_input.to(self.device) out_gt = torch.cat((out_gt, var_target), 0).to(self.device) _, c, h, w",
"alpha), 3) alpha = alpha ** phi beta = beta ** phi model",
"rate\", default=1e-4, type = float) parser.add_argument(\"--checkpoint\", required=False, help=\"Checkpoint model weight\", default= None, type",
"model = DenseNet121(class_count) # Train the Model savepath = args.spath rsna_trainer = RSNATrainer(",
"for the model\", default=(11 / 6), type=float) parser.add_argument(\"--phi\", required=False, help=\"Phi for the model.\",",
"= class_count self.auroc_max = 0.0 # Setting maximum AUROC value as zero self.optimizer",
"self.valid() loss_valid_list.append(validloss_value) if auroc_mean > self.auroc_max: print('Better auroc obtained') self.auroc_max = auroc_mean scheduler.step()",
"torch.FloatTensor().to(self.device) self.model.eval() with torch.no_grad(): for i, (var_input, var_target) in enumerate(self.data_loader_test): var_target = var_target.to(self.device)",
"max_epoch = args.epochs class_count = args.clscount #The objective is to classify the image",
"RSNADataSet(val_list, labels, img_pth, transform=True) data_loader_train = DataLoader( dataset=dataset_train, batch_size=batch_size, shuffle=True, num_workers=4, pin_memory=False) data_loader_valid",
"data_loader_valid = DataLoader( dataset=dataset_valid, batch_size=batch_size, shuffle=False, num_workers=4, pin_memory=False) dataset_test = RSNADataSet(test_list, labels, img_pth,",
"batch_size=1, shuffle=False, num_workers=4, pin_memory=False) # Construct Model if args.optimised: alpha = args.alpha phi",
"valid_loss_min = valid_loss torch.save({'epoch': epoch_id + 1, 'state_dict': self.model.state_dict(), 'best_loss': valid_loss_min, 'optimizer' :",
"# Data Loader dpath = args.dpath img_pth = os.path.join(args.dpath, 'processed_data/') numpy_path = os.path.join(args.dpath,",
"DenseNet121, DenseNet121Eff from math import sqrt import json from tqdm import tqdm as",
"Train the Model savepath = args.spath rsna_trainer = RSNATrainer( model, data_loader_train, data_loader_valid, data_loader_test,",
"argparse import torch from torch.backends import cudnn from torch import optim import torch.nn.functional",
"= os.path.join(args.dpath, 'data_split/') with open(os.path.join(dpath, 'rsna_annotation.json')) as lab_file: labels = json.load(lab_file) # Place",
"type=float) parser.add_argument(\"--beta\", required=False, help=\"Beta for the model.\", default=None, type=float) custom_args = parser.parse_args() main(custom_args)",
"parser.add_argument(\"--spath\", required=True, help=\"Path to folder in which models should be saved\", type =str)",
"compute_auroc(tfunc.one_hot(out_gt.squeeze(1).long()).float(), out_pred, self.class_count) auroc_mean = np.array(auroc_individual).mean() print(f'AUROC mean:{auroc_mean}') for i, auroc_val in enumerate(auroc_individual):",
"trainloss_value = self.loss_fn( var_output, tfunc.one_hot(var_target.squeeze(1).long(), num_classes=self.class_count).float()) self.optimizer.zero_grad() trainloss_value.backward() self.optimizer.step() train_loss_value = trainloss_value.item() loss_train_list.append(train_loss_value)",
"= RSNATrainer( model, data_loader_train, data_loader_valid, data_loader_test, class_count,checkpoint, device, class_names, lr) rsna_trainer.train(max_epoch, savepath) print(\"Model",
"= args.lr checkpoint = args.checkpoint batch_size = args.bs max_epoch = args.epochs class_count =",
"h, w) var_output = self.model(var_input.to(self.device)) out_pred = torch.cat((out_pred, var_output), 0) lossvalue = self.loss_fn(",
"= np.mean(loss_train_list) valid_loss_mean = np.mean(loss_valid_list) return train_loss_mean, valid_loss_mean, auroc_mean def test(self): cudnn.benchmark =",
"= self.model(var_input.to(self.device)) out_pred = torch.cat((out_pred, var_output), 0) lossvalue = self.loss_fn( var_output, tfunc.one_hot(var_target.squeeze(1).long(), num_classes=self.class_count).float())",
"= [] loss_valid_list = [] self.model.train() scheduler = StepLR(self.optimizer, step_size=6, gamma=0.002) for batch_id,",
"valid_loss torch.save({'epoch': epoch_id + 1, 'state_dict': self.model.state_dict(), 'best_loss': valid_loss_min, 'optimizer' : self.optimizer.state_dict()}, os.path.join(savepath,",
"RSNADataSet from .utils.score import compute_auroc from .utils.model import DenseNet121, DenseNet121Eff from math import",
"help=\"enable flag->eff model\", action='store_true') parser.add_argument(\"--alpha\", required=False, help=\"alpha for the model\", default=(11 / 6),",
"self.model(var_input) trainloss_value = self.loss_fn( var_output, tfunc.one_hot(var_target.squeeze(1).long(), num_classes=self.class_count).float()) self.optimizer.zero_grad() trainloss_value.backward() self.optimizer.step() train_loss_value = trainloss_value.item()",
"type = float) parser.add_argument(\"--checkpoint\", required=False, help=\"Checkpoint model weight\", default= None, type = str)",
"DenseNet121(class_count) # Train the Model savepath = args.spath rsna_trainer = RSNATrainer( model, data_loader_train,",
"var_output), 0) lossvalue = self.loss_fn( var_output, tfunc.one_hot(var_target.squeeze(1).long(), num_classes=self.class_count).float()) loss_valid_r += lossvalue.item() valid_batches +=",
"= None self.loss_fn = torch.nn.BCELoss() def train(self, max_epoch, savepath): train_loss_min = 1e+5 #",
"= valid_loss timestamp_end = time.strftime(\"%H%M%S-%d%m%Y\") if train_loss < train_loss_min: train_loss_min = train_loss if",
"train_loss_min: train_loss_min = train_loss if valid_loss < valid_loss_min: valid_loss_min = valid_loss torch.save({'epoch': epoch_id",
"class_names self.class_count = class_count self.auroc_max = 0.0 # Setting maximum AUROC value as",
"var_input.to(self.device) out_gt = torch.cat((out_gt, var_target), 0).to(self.device) _, c, h, w = var_input.size() var_input",
"out_pred = torch.cat((out_pred, var_output), 0) lossvalue = self.loss_fn( var_output, tfunc.one_hot(var_target.squeeze(1).long(), num_classes=self.class_count).float()) loss_valid_r +=",
"var_target = var_target.to(self.device) var_input = var_input.to(self.device) var_output= self.model(var_input) trainloss_value = self.loss_fn( var_output, tfunc.one_hot(var_target.squeeze(1).long(),",
"parser.add_argument(\"--alpha\", required=False, help=\"alpha for the model\", default=(11 / 6), type=float) parser.add_argument(\"--phi\", required=False, help=\"Phi",
"6), type=float) parser.add_argument(\"--phi\", required=False, help=\"Phi for the model.\", default=1.0, type=float) parser.add_argument(\"--beta\", required=False, help=\"Beta",
"!\") if __name__==\"__main__\": parser = argparse.ArgumentParser() parser.add_argument(\"--lr\", required=False, help=\"Learning rate\", default=1e-4, type =",
"valid_loss, auroc_mean def epoch_train(self): loss_train_list = [] loss_valid_list = [] self.model.train() scheduler =",
"= optim.Adam(self.model.parameters(), lr=lr) if checkpoint is not None: model_checkpoint = torch.load(checkpoint) self.optimizer.load_state_dict(model_checkpoint['optimizer']) else:",
"json.load(lab_file) # Place numpy file containing train-valid-test split on tools folder tr_list =",
"import sqrt import json from tqdm import tqdm as tq class RSNATrainer(): def",
"np import time import os import argparse import torch from torch.backends import cudnn",
"import os import argparse import torch from torch.backends import cudnn from torch import",
"0 and batch_id != 0: validloss_value, auroc_mean = self.valid() loss_valid_list.append(validloss_value) if auroc_mean >",
"3) alpha = alpha ** phi beta = beta ** phi model =",
"(len(self.data_loader_train)-1) == 0 and batch_id != 0: validloss_value, auroc_mean = self.valid() loss_valid_list.append(validloss_value) if",
"= float) parser.add_argument(\"--checkpoint\", required=False, help=\"Checkpoint model weight\", default= None, type = str) parser.add_argument(\"--bs\",",
"os import argparse import torch from torch.backends import cudnn from torch import optim",
"model, data_loader_train, data_loader_valid, data_loader_test, class_count, checkpoint, device, class_names, lr): self.gepoch_id = 0 self.device",
"torch.backends import cudnn from torch import optim import torch.nn.functional as tfunc from torch.utils.data",
"tq(self.data_loader_valid): var_target = var_target.to(self.device) out_gt = torch.cat((out_gt, var_target), 0).to(self.device) _, c, h, w",
"in tq(enumerate(self.data_loader_train)): var_target = var_target.to(self.device) var_input = var_input.to(self.device) var_output= self.model(var_input) trainloss_value = self.loss_fn(",
"StepLR(self.optimizer, step_size=6, gamma=0.002) for batch_id, (var_input, var_target) in tq(enumerate(self.data_loader_train)): var_target = var_target.to(self.device) var_input",
"out_pred = torch.FloatTensor().to(self.device) self.model.eval() with torch.no_grad(): for i, (var_input, var_target) in enumerate(self.data_loader_test): var_target",
"epoch_id train_loss, valid_loss, auroc_max = self.epoch_train() self.current_train_loss = train_loss self.current_valid_loss = valid_loss timestamp_end",
"< train_loss_min: train_loss_min = train_loss if valid_loss < valid_loss_min: valid_loss_min = valid_loss torch.save({'epoch':",
"None, type = str) parser.add_argument(\"--bs\", required=False, default=16, help=\"Batchsize\", type=int) parser.add_argument(\"--dpath\", required=True, help=\"Path to",
"alpha = alpha ** phi beta = beta ** phi model = DenseNet121Eff(alpha,",
"timestamp_end = time.strftime(\"%H%M%S-%d%m%Y\") if train_loss < train_loss_min: train_loss_min = train_loss if valid_loss <",
"auroc_mean def test(self): cudnn.benchmark = True out_gt = torch.FloatTensor().to(self.device) out_pred = torch.FloatTensor().to(self.device) self.model.eval()",
"import DenseNet121, DenseNet121Eff from math import sqrt import json from tqdm import tqdm",
"as tq class RSNATrainer(): def __init__(self, model, data_loader_train, data_loader_valid, data_loader_test, class_count, checkpoint, device,",
"device, class_names, lr): self.gepoch_id = 0 self.device = device self.model = model.to(self.device) self.data_loader_train",
"auroc_mean > self.auroc_max: print('Better auroc obtained') self.auroc_max = auroc_mean scheduler.step() train_loss_mean = np.mean(loss_train_list)",
"0 valid_batches = 0 # Counter for valid batches out_gt = torch.FloatTensor().to(self.device) out_pred",
"var_input.size() var_input = var_input.view(-1, c, h, w) var_output = self.model(var_input.to(self.device)) out_pred = torch.cat((out_pred,",
"from torch.backends import cudnn from torch import optim import torch.nn.functional as tfunc from",
"class_names, lr): self.gepoch_id = 0 self.device = device self.model = model.to(self.device) self.data_loader_train =",
"= torch.cat((out_gt, var_target), 0).to(self.device) _, c, h, w = var_input.size() var_input = var_input.view(-1,",
"the Model savepath = args.spath rsna_trainer = RSNATrainer( model, data_loader_train, data_loader_valid, data_loader_test, class_count,checkpoint,",
"import torch from torch.backends import cudnn from torch import optim import torch.nn.functional as",
"= var_input.size() var_input = var_input.view(-1, c, h, w) var_output = self.model(var_input.to(self.device)) out_pred =",
"Model if args.optimised: alpha = args.alpha phi = args.phi beta = args.beta if",
"= time.strftime(\"%H%M%S-%d%m%Y\") if train_loss < train_loss_min: train_loss_min = train_loss if valid_loss < valid_loss_min:",
"= self.epoch_train() self.current_train_loss = train_loss self.current_valid_loss = valid_loss timestamp_end = time.strftime(\"%H%M%S-%d%m%Y\") if train_loss",
"for valid batches out_gt = torch.FloatTensor().to(self.device) out_pred = torch.FloatTensor().to(self.device) with torch.no_grad(): for (var_input,",
"with open(os.path.join(dpath, 'rsna_annotation.json')) as lab_file: labels = json.load(lab_file) # Place numpy file containing",
"args.optimised: alpha = args.alpha phi = args.phi beta = args.beta if beta is",
"print(\"Model trained !\") if __name__==\"__main__\": parser = argparse.ArgumentParser() parser.add_argument(\"--lr\", required=False, help=\"Learning rate\", default=1e-4,",
"for i, (var_input, var_target) in enumerate(self.data_loader_test): var_target = var_target.to(self.device) var_input = var_input.to(self.device) out_gt",
".utils.model import DenseNet121, DenseNet121Eff from math import sqrt import json from tqdm import",
"= np.load(os.path.join(numpy_path,'train_list.npy')).tolist() val_list = np.load(os.path.join(numpy_path,'valid_list.npy')).tolist() test_list = np.load(os.path.join(numpy_path,'test_list.npy')).tolist() dataset_train = RSNADataSet(tr_list, labels, img_pth,",
"max_epoch, savepath): train_loss_min = 1e+5 # A random very high number valid_loss_min =",
"= epoch_id train_loss, valid_loss, auroc_max = self.epoch_train() self.current_train_loss = train_loss self.current_valid_loss = valid_loss",
"= var_input.view(-1, c, h, w) var_output = self.model(var_input.to(self.device)) out_pred = torch.cat((out_pred, var_output), 0)",
"torch.FloatTensor().to(self.device) out_pred = torch.FloatTensor().to(self.device) self.model.eval() with torch.no_grad(): for i, (var_input, var_target) in enumerate(self.data_loader_test):",
"to folder in which models should be saved\", type =str) parser.add_argument(\"--optimised\", required=False, default=False,",
"= self.loss_fn( var_output, tfunc.one_hot(var_target.squeeze(1).long(), num_classes=self.class_count).float()) self.optimizer.zero_grad() trainloss_value.backward() self.optimizer.step() train_loss_value = trainloss_value.item() loss_train_list.append(train_loss_value) if",
"parser.add_argument(\"--clscount\", required=False, default=3, help=\"Number of classes\", type=int) parser.add_argument(\"--spath\", required=True, help=\"Path to folder in",
"_, c, h, w = var_input.size() var_input = var_input.view(-1, c, h, w) out",
"type =str) parser.add_argument(\"--epochs\", required=False, default=15, help=\"Number of epochs\", type=int) parser.add_argument(\"--clscount\", required=False, default=3, help=\"Number",
"of classes\", type=int) parser.add_argument(\"--spath\", required=True, help=\"Path to folder in which models should be",
"self.data_loader_valid = data_loader_valid self.data_loader_test = data_loader_test self.class_names = class_names self.class_count = class_count self.auroc_max",
"model_checkpoint = torch.load(checkpoint) self.optimizer.load_state_dict(model_checkpoint['optimizer']) else: model_checkpoint = None self.loss_fn = torch.nn.BCELoss() def train(self,",
"self.current_train_loss = train_loss self.current_valid_loss = valid_loss timestamp_end = time.strftime(\"%H%M%S-%d%m%Y\") if train_loss < train_loss_min:",
"train_loss_min = train_loss if valid_loss < valid_loss_min: valid_loss_min = valid_loss torch.save({'epoch': epoch_id +",
"numpy as np import time import os import argparse import torch from torch.backends",
"= args.beta if beta is None: beta = round(sqrt(2 / alpha), 3) alpha",
"in enumerate(auroc_individual): print(f\"{self.class_names[i]}:{auroc_val}\") return auroc_mean def main(args): lr = args.lr checkpoint = args.checkpoint",
"beta = beta ** phi model = DenseNet121Eff(alpha, beta, class_count) else: model =",
".utils.score import compute_auroc from .utils.model import DenseNet121, DenseNet121Eff from math import sqrt import",
"model_checkpoint = None self.loss_fn = torch.nn.BCELoss() def train(self, max_epoch, savepath): train_loss_min = 1e+5",
"None self.loss_fn = torch.nn.BCELoss() def train(self, max_epoch, savepath): train_loss_min = 1e+5 # A",
"loss_valid_list = [] self.model.train() scheduler = StepLR(self.optimizer, step_size=6, gamma=0.002) for batch_id, (var_input, var_target)",
"batch_id, (var_input, var_target) in tq(enumerate(self.data_loader_train)): var_target = var_target.to(self.device) var_input = var_input.to(self.device) var_output= self.model(var_input)",
"'state_dict': self.model.state_dict(), 'best_loss': valid_loss_min, 'optimizer' : self.optimizer.state_dict()}, os.path.join(savepath, f'm-epoch-{epoch_id}.pth')) test_auroc = self.test() print(f\"Epoch:{epoch_id",
"var_output, tfunc.one_hot(var_target.squeeze(1).long(), num_classes=self.class_count).float()) loss_valid_r += lossvalue.item() valid_batches += 1 valid_loss = loss_valid_r /",
"def valid(self): self.model.eval() loss_valid_r = 0 valid_batches = 0 # Counter for valid",
"= args.checkpoint batch_size = args.bs max_epoch = args.epochs class_count = args.clscount #The objective",
"out_pred = torch.FloatTensor().to(self.device) with torch.no_grad(): for (var_input, var_target) in tq(self.data_loader_valid): var_target = var_target.to(self.device)",
"default=1e-4, type = float) parser.add_argument(\"--checkpoint\", required=False, help=\"Checkpoint model weight\", default= None, type =",
"containing train-valid-test split on tools folder tr_list = np.load(os.path.join(numpy_path,'train_list.npy')).tolist() val_list = np.load(os.path.join(numpy_path,'valid_list.npy')).tolist() test_list",
"args.lr checkpoint = args.checkpoint batch_size = args.bs max_epoch = args.epochs class_count = args.clscount",
"shuffle=False, num_workers=4, pin_memory=False) dataset_test = RSNADataSet(test_list, labels, img_pth, transform=True) data_loader_test = DataLoader( dataset=dataset_test,",
"model\", default=(11 / 6), type=float) parser.add_argument(\"--phi\", required=False, help=\"Phi for the model.\", default=1.0, type=float)",
"tfunc.one_hot(var_target.squeeze(1).long(), num_classes=self.class_count).float()) loss_valid_r += lossvalue.item() valid_batches += 1 valid_loss = loss_valid_r / valid_batches",
"else: model = DenseNet121(class_count) # Train the Model savepath = args.spath rsna_trainer =",
"required=False, help=\"alpha for the model\", default=(11 / 6), type=float) parser.add_argument(\"--phi\", required=False, help=\"Phi for",
"be saved\", type =str) parser.add_argument(\"--optimised\", required=False, default=False, help=\"enable flag->eff model\", action='store_true') parser.add_argument(\"--alpha\", required=False,",
"help=\"alpha for the model\", default=(11 / 6), type=float) parser.add_argument(\"--phi\", required=False, help=\"Phi for the",
"checkpoint is not None: model_checkpoint = torch.load(checkpoint) self.optimizer.load_state_dict(model_checkpoint['optimizer']) else: model_checkpoint = None self.loss_fn",
"json from tqdm import tqdm as tq class RSNATrainer(): def __init__(self, model, data_loader_train,",
"open(os.path.join(dpath, 'rsna_annotation.json')) as lab_file: labels = json.load(lab_file) # Place numpy file containing train-valid-test",
"optim.Adam(self.model.parameters(), lr=lr) if checkpoint is not None: model_checkpoint = torch.load(checkpoint) self.optimizer.load_state_dict(model_checkpoint['optimizer']) else: model_checkpoint",
"valid_loss timestamp_end = time.strftime(\"%H%M%S-%d%m%Y\") if train_loss < train_loss_min: train_loss_min = train_loss if valid_loss",
"DataLoader( dataset=dataset_valid, batch_size=batch_size, shuffle=False, num_workers=4, pin_memory=False) dataset_test = RSNADataSet(test_list, labels, img_pth, transform=True) data_loader_test",
"from tqdm import tqdm as tq class RSNATrainer(): def __init__(self, model, data_loader_train, data_loader_valid,",
"auroc_val in enumerate(auroc_individual): print(f\"{self.class_names[i]}:{auroc_val}\") return auroc_mean def main(args): lr = args.lr checkpoint =",
"(var_input, var_target) in enumerate(self.data_loader_test): var_target = var_target.to(self.device) var_input = var_input.to(self.device) out_gt = torch.cat((out_gt,",
"on tools folder tr_list = np.load(os.path.join(numpy_path,'train_list.npy')).tolist() val_list = np.load(os.path.join(numpy_path,'valid_list.npy')).tolist() test_list = np.load(os.path.join(numpy_path,'test_list.npy')).tolist() dataset_train",
"cudnn.benchmark = True out_gt = torch.FloatTensor().to(self.device) out_pred = torch.FloatTensor().to(self.device) self.model.eval() with torch.no_grad(): for",
"model weight\", default= None, type = str) parser.add_argument(\"--bs\", required=False, default=16, help=\"Batchsize\", type=int) parser.add_argument(\"--dpath\",",
"default=3, help=\"Number of classes\", type=int) parser.add_argument(\"--spath\", required=True, help=\"Path to folder in which models",
"from torch.utils.data import DataLoader from torch.optim.lr_scheduler import StepLR from .utils.dataloader import RSNADataSet from",
"= argparse.ArgumentParser() parser.add_argument(\"--lr\", required=False, help=\"Learning rate\", default=1e-4, type = float) parser.add_argument(\"--checkpoint\", required=False, help=\"Checkpoint",
"step_size=6, gamma=0.002) for batch_id, (var_input, var_target) in tq(enumerate(self.data_loader_train)): var_target = var_target.to(self.device) var_input =",
"np.mean(loss_valid_list) return train_loss_mean, valid_loss_mean, auroc_mean def test(self): cudnn.benchmark = True out_gt = torch.FloatTensor().to(self.device)",
"out_gt = torch.cat((out_gt, var_target), 0).to(self.device) _, c, h, w = var_input.size() var_input =",
"obtained') self.auroc_max = auroc_mean scheduler.step() train_loss_mean = np.mean(loss_train_list) valid_loss_mean = np.mean(loss_valid_list) return train_loss_mean,",
"+ 1, 'state_dict': self.model.state_dict(), 'best_loss': valid_loss_min, 'optimizer' : self.optimizer.state_dict()}, os.path.join(savepath, f'm-epoch-{epoch_id}.pth')) test_auroc =",
"valid_loss, auroc_max = self.epoch_train() self.current_train_loss = train_loss self.current_valid_loss = valid_loss timestamp_end = time.strftime(\"%H%M%S-%d%m%Y\")",
"os.path.join(savepath, f'm-epoch-{epoch_id}.pth')) test_auroc = self.test() print(f\"Epoch:{epoch_id + 1}| EndTime:{timestamp_end}| TestAUROC: {test_auroc}| ValidAUROC: {auroc_max}\")",
"auroc_mean = self.valid() loss_valid_list.append(validloss_value) if auroc_mean > self.auroc_max: print('Better auroc obtained') self.auroc_max =",
"loss_valid_list.append(validloss_value) if auroc_mean > self.auroc_max: print('Better auroc obtained') self.auroc_max = auroc_mean scheduler.step() train_loss_mean",
"= np.load(os.path.join(numpy_path,'test_list.npy')).tolist() dataset_train = RSNADataSet(tr_list, labels, img_pth, transform=True) dataset_valid = RSNADataSet(val_list, labels, img_pth,",
"self.model.eval() loss_valid_r = 0 valid_batches = 0 # Counter for valid batches out_gt",
"with torch.no_grad(): for (var_input, var_target) in tq(self.data_loader_valid): var_target = var_target.to(self.device) out_gt = torch.cat((out_gt,",
"= 0 # Counter for valid batches out_gt = torch.FloatTensor().to(self.device) out_pred = torch.FloatTensor().to(self.device)",
"i, (var_input, var_target) in enumerate(self.data_loader_test): var_target = var_target.to(self.device) var_input = var_input.to(self.device) out_gt =",
"= RSNADataSet(val_list, labels, img_pth, transform=True) data_loader_train = DataLoader( dataset=dataset_train, batch_size=batch_size, shuffle=True, num_workers=4, pin_memory=False)",
"math import sqrt import json from tqdm import tqdm as tq class RSNATrainer():",
"= args.alpha phi = args.phi beta = args.beta if beta is None: beta",
"if auroc_mean > self.auroc_max: print('Better auroc obtained') self.auroc_max = auroc_mean scheduler.step() train_loss_mean =",
"= DataLoader( dataset=dataset_train, batch_size=batch_size, shuffle=True, num_workers=4, pin_memory=False) data_loader_valid = DataLoader( dataset=dataset_valid, batch_size=batch_size, shuffle=False,",
"args.bs max_epoch = args.epochs class_count = args.clscount #The objective is to classify the",
"os.path.join(args.dpath, 'processed_data/') numpy_path = os.path.join(args.dpath, 'data_split/') with open(os.path.join(dpath, 'rsna_annotation.json')) as lab_file: labels =",
"file containing train-valid-test split on tools folder tr_list = np.load(os.path.join(numpy_path,'train_list.npy')).tolist() val_list = np.load(os.path.join(numpy_path,'valid_list.npy')).tolist()",
"ValidAUROC: {auroc_max}\") def valid(self): self.model.eval() loss_valid_r = 0 valid_batches = 0 # Counter",
"gpu if available class_names = ['Lung Opacity', 'Normal', 'No Lung Opacity / Not",
"# Place numpy file containing train-valid-test split on tools folder tr_list = np.load(os.path.join(numpy_path,'train_list.npy')).tolist()",
"data_loader_test, class_count, checkpoint, device, class_names, lr): self.gepoch_id = 0 self.device = device self.model",
"valid_loss = loss_valid_r / valid_batches auroc_individual = compute_auroc( tfunc.one_hot(out_gt.squeeze(1).long()).float(), out_pred, self.class_count) print(len(auroc_individual)) auroc_mean",
"default=16, help=\"Batchsize\", type=int) parser.add_argument(\"--dpath\", required=True, help=\"Path to folder containing all data\", type =str)",
"tfunc.one_hot(out_gt.squeeze(1).long()).float(), out_pred, self.class_count) print(len(auroc_individual)) auroc_mean = np.array(auroc_individual).mean() return valid_loss, auroc_mean def epoch_train(self): loss_train_list",
"torch.cuda.is_available() else \"cpu\") # use gpu if available class_names = ['Lung Opacity', 'Normal',",
"= args.bs max_epoch = args.epochs class_count = args.clscount #The objective is to classify",
"savepath) print(\"Model trained !\") if __name__==\"__main__\": parser = argparse.ArgumentParser() parser.add_argument(\"--lr\", required=False, help=\"Learning rate\",",
"data_loader_train, data_loader_valid, data_loader_test, class_count, checkpoint, device, class_names, lr): self.gepoch_id = 0 self.device =",
"self.class_names = class_names self.class_count = class_count self.auroc_max = 0.0 # Setting maximum AUROC",
"= var_input.size() var_input = var_input.view(-1, c, h, w) out = self.model(var_input) out_pred =",
"= json.load(lab_file) # Place numpy file containing train-valid-test split on tools folder tr_list",
"self.class_count) auroc_mean = np.array(auroc_individual).mean() print(f'AUROC mean:{auroc_mean}') for i, auroc_val in enumerate(auroc_individual): print(f\"{self.class_names[i]}:{auroc_val}\") return",
"0.0 # Setting maximum AUROC value as zero self.optimizer = optim.Adam(self.model.parameters(), lr=lr) if",
"np.array(auroc_individual).mean() print(f'AUROC mean:{auroc_mean}') for i, auroc_val in enumerate(auroc_individual): print(f\"{self.class_names[i]}:{auroc_val}\") return auroc_mean def main(args):",
"model.\", default=1.0, type=float) parser.add_argument(\"--beta\", required=False, help=\"Beta for the model.\", default=None, type=float) custom_args =",
"in range(max_epoch): print(f\"Epoch {epoch_id+1}/{max_epoch}\") self.gepoch_id = epoch_id train_loss, valid_loss, auroc_max = self.epoch_train() self.current_train_loss",
"= torch.FloatTensor().to(self.device) out_pred = torch.FloatTensor().to(self.device) with torch.no_grad(): for (var_input, var_target) in tq(self.data_loader_valid): var_target",
"classify the image into 3 classes device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")",
"in enumerate(self.data_loader_test): var_target = var_target.to(self.device) var_input = var_input.to(self.device) out_gt = torch.cat((out_gt, var_target), 0).to(self.device)",
"'rsna_annotation.json')) as lab_file: labels = json.load(lab_file) # Place numpy file containing train-valid-test split",
"= np.mean(loss_valid_list) return train_loss_mean, valid_loss_mean, auroc_mean def test(self): cudnn.benchmark = True out_gt =",
"class_count self.auroc_max = 0.0 # Setting maximum AUROC value as zero self.optimizer =",
"= loss_valid_r / valid_batches auroc_individual = compute_auroc( tfunc.one_hot(out_gt.squeeze(1).long()).float(), out_pred, self.class_count) print(len(auroc_individual)) auroc_mean =",
"Not Normal'] # Data Loader dpath = args.dpath img_pth = os.path.join(args.dpath, 'processed_data/') numpy_path",
"checkpoint, device, class_names, lr): self.gepoch_id = 0 self.device = device self.model = model.to(self.device)",
"of epochs\", type=int) parser.add_argument(\"--clscount\", required=False, default=3, help=\"Number of classes\", type=int) parser.add_argument(\"--spath\", required=True, help=\"Path",
"args.checkpoint batch_size = args.bs max_epoch = args.epochs class_count = args.clscount #The objective is",
"1}| EndTime:{timestamp_end}| TestAUROC: {test_auroc}| ValidAUROC: {auroc_max}\") def valid(self): self.model.eval() loss_valid_r = 0 valid_batches",
"import tqdm as tq class RSNATrainer(): def __init__(self, model, data_loader_train, data_loader_valid, data_loader_test, class_count,",
"self.auroc_max = auroc_mean scheduler.step() train_loss_mean = np.mean(loss_train_list) valid_loss_mean = np.mean(loss_valid_list) return train_loss_mean, valid_loss_mean,",
"Opacity', 'Normal', 'No Lung Opacity / Not Normal'] # Data Loader dpath =",
"test_auroc = self.test() print(f\"Epoch:{epoch_id + 1}| EndTime:{timestamp_end}| TestAUROC: {test_auroc}| ValidAUROC: {auroc_max}\") def valid(self):",
"lossvalue = self.loss_fn( var_output, tfunc.one_hot(var_target.squeeze(1).long(), num_classes=self.class_count).float()) loss_valid_r += lossvalue.item() valid_batches += 1 valid_loss",
"valid_loss_min = 1e+5 for epoch_id in range(max_epoch): print(f\"Epoch {epoch_id+1}/{max_epoch}\") self.gepoch_id = epoch_id train_loss,",
"= self.valid() loss_valid_list.append(validloss_value) if auroc_mean > self.auroc_max: print('Better auroc obtained') self.auroc_max = auroc_mean",
"lr) rsna_trainer.train(max_epoch, savepath) print(\"Model trained !\") if __name__==\"__main__\": parser = argparse.ArgumentParser() parser.add_argument(\"--lr\", required=False,",
"number valid_loss_min = 1e+5 for epoch_id in range(max_epoch): print(f\"Epoch {epoch_id+1}/{max_epoch}\") self.gepoch_id = epoch_id",
"= 0 valid_batches = 0 # Counter for valid batches out_gt = torch.FloatTensor().to(self.device)",
"0 # Counter for valid batches out_gt = torch.FloatTensor().to(self.device) out_pred = torch.FloatTensor().to(self.device) with",
"help=\"Batchsize\", type=int) parser.add_argument(\"--dpath\", required=True, help=\"Path to folder containing all data\", type =str) parser.add_argument(\"--epochs\",",
"lr=lr) if checkpoint is not None: model_checkpoint = torch.load(checkpoint) self.optimizer.load_state_dict(model_checkpoint['optimizer']) else: model_checkpoint =",
"= var_target.to(self.device) var_input = var_input.to(self.device) out_gt = torch.cat((out_gt, var_target), 0).to(self.device) _, c, h,",
"out = self.model(var_input) out_pred = torch.cat((out_pred, out), 0) auroc_individual = compute_auroc(tfunc.one_hot(out_gt.squeeze(1).long()).float(), out_pred, self.class_count)",
"class_count, checkpoint, device, class_names, lr): self.gepoch_id = 0 self.device = device self.model =",
"True out_gt = torch.FloatTensor().to(self.device) out_pred = torch.FloatTensor().to(self.device) self.model.eval() with torch.no_grad(): for i, (var_input,",
"torch.no_grad(): for (var_input, var_target) in tq(self.data_loader_valid): var_target = var_target.to(self.device) out_gt = torch.cat((out_gt, var_target),",
"= device self.model = model.to(self.device) self.data_loader_train = data_loader_train self.data_loader_valid = data_loader_valid self.data_loader_test =",
"help=\"Number of classes\", type=int) parser.add_argument(\"--spath\", required=True, help=\"Path to folder in which models should",
"objective is to classify the image into 3 classes device = torch.device(\"cuda\" if",
"class_names = ['Lung Opacity', 'Normal', 'No Lung Opacity / Not Normal'] # Data",
"tq class RSNATrainer(): def __init__(self, model, data_loader_train, data_loader_valid, data_loader_test, class_count, checkpoint, device, class_names,",
"{epoch_id+1}/{max_epoch}\") self.gepoch_id = epoch_id train_loss, valid_loss, auroc_max = self.epoch_train() self.current_train_loss = train_loss self.current_valid_loss",
"var_input = var_input.to(self.device) var_output= self.model(var_input) trainloss_value = self.loss_fn( var_output, tfunc.one_hot(var_target.squeeze(1).long(), num_classes=self.class_count).float()) self.optimizer.zero_grad() trainloss_value.backward()",
"out_pred = torch.cat((out_pred, out), 0) auroc_individual = compute_auroc(tfunc.one_hot(out_gt.squeeze(1).long()).float(), out_pred, self.class_count) auroc_mean = np.array(auroc_individual).mean()",
"test(self): cudnn.benchmark = True out_gt = torch.FloatTensor().to(self.device) out_pred = torch.FloatTensor().to(self.device) self.model.eval() with torch.no_grad():",
"labels, img_pth, transform=True) dataset_valid = RSNADataSet(val_list, labels, img_pth, transform=True) data_loader_train = DataLoader( dataset=dataset_train,",
"RSNATrainer( model, data_loader_train, data_loader_valid, data_loader_test, class_count,checkpoint, device, class_names, lr) rsna_trainer.train(max_epoch, savepath) print(\"Model trained",
"out_gt = torch.FloatTensor().to(self.device) out_pred = torch.FloatTensor().to(self.device) with torch.no_grad(): for (var_input, var_target) in tq(self.data_loader_valid):",
"train-valid-test split on tools folder tr_list = np.load(os.path.join(numpy_path,'train_list.npy')).tolist() val_list = np.load(os.path.join(numpy_path,'valid_list.npy')).tolist() test_list =",
"Data Loader dpath = args.dpath img_pth = os.path.join(args.dpath, 'processed_data/') numpy_path = os.path.join(args.dpath, 'data_split/')",
"0) auroc_individual = compute_auroc(tfunc.one_hot(out_gt.squeeze(1).long()).float(), out_pred, self.class_count) auroc_mean = np.array(auroc_individual).mean() print(f'AUROC mean:{auroc_mean}') for i,",
"alpha = args.alpha phi = args.phi beta = args.beta if beta is None:",
"= args.epochs class_count = args.clscount #The objective is to classify the image into",
"= args.phi beta = args.beta if beta is None: beta = round(sqrt(2 /",
"print(f'AUROC mean:{auroc_mean}') for i, auroc_val in enumerate(auroc_individual): print(f\"{self.class_names[i]}:{auroc_val}\") return auroc_mean def main(args): lr",
"= args.dpath img_pth = os.path.join(args.dpath, 'processed_data/') numpy_path = os.path.join(args.dpath, 'data_split/') with open(os.path.join(dpath, 'rsna_annotation.json'))",
"DataLoader( dataset=dataset_train, batch_size=batch_size, shuffle=True, num_workers=4, pin_memory=False) data_loader_valid = DataLoader( dataset=dataset_valid, batch_size=batch_size, shuffle=False, num_workers=4,",
"type=int) parser.add_argument(\"--dpath\", required=True, help=\"Path to folder containing all data\", type =str) parser.add_argument(\"--epochs\", required=False,",
"class_names, lr) rsna_trainer.train(max_epoch, savepath) print(\"Model trained !\") if __name__==\"__main__\": parser = argparse.ArgumentParser() parser.add_argument(\"--lr\",",
"default=1.0, type=float) parser.add_argument(\"--beta\", required=False, help=\"Beta for the model.\", default=None, type=float) custom_args = parser.parse_args()",
"= data_loader_test self.class_names = class_names self.class_count = class_count self.auroc_max = 0.0 # Setting",
"device self.model = model.to(self.device) self.data_loader_train = data_loader_train self.data_loader_valid = data_loader_valid self.data_loader_test = data_loader_test",
"argparse.ArgumentParser() parser.add_argument(\"--lr\", required=False, help=\"Learning rate\", default=1e-4, type = float) parser.add_argument(\"--checkpoint\", required=False, help=\"Checkpoint model",
"% (len(self.data_loader_train)-1) == 0 and batch_id != 0: validloss_value, auroc_mean = self.valid() loss_valid_list.append(validloss_value)",
"torch.FloatTensor().to(self.device) out_pred = torch.FloatTensor().to(self.device) with torch.no_grad(): for (var_input, var_target) in tq(self.data_loader_valid): var_target =",
"w) var_output = self.model(var_input.to(self.device)) out_pred = torch.cat((out_pred, var_output), 0) lossvalue = self.loss_fn( var_output,",
"phi beta = beta ** phi model = DenseNet121Eff(alpha, beta, class_count) else: model",
"parser.add_argument(\"--lr\", required=False, help=\"Learning rate\", default=1e-4, type = float) parser.add_argument(\"--checkpoint\", required=False, help=\"Checkpoint model weight\",",
"print(f\"Epoch:{epoch_id + 1}| EndTime:{timestamp_end}| TestAUROC: {test_auroc}| ValidAUROC: {auroc_max}\") def valid(self): self.model.eval() loss_valid_r =",
"torch.nn.functional as tfunc from torch.utils.data import DataLoader from torch.optim.lr_scheduler import StepLR from .utils.dataloader",
"if train_loss < train_loss_min: train_loss_min = train_loss if valid_loss < valid_loss_min: valid_loss_min =",
"= 1e+5 for epoch_id in range(max_epoch): print(f\"Epoch {epoch_id+1}/{max_epoch}\") self.gepoch_id = epoch_id train_loss, valid_loss,",
"else: model_checkpoint = None self.loss_fn = torch.nn.BCELoss() def train(self, max_epoch, savepath): train_loss_min =",
"tqdm as tq class RSNATrainer(): def __init__(self, model, data_loader_train, data_loader_valid, data_loader_test, class_count, checkpoint,",
"device, class_names, lr) rsna_trainer.train(max_epoch, savepath) print(\"Model trained !\") if __name__==\"__main__\": parser = argparse.ArgumentParser()",
"flag->eff model\", action='store_true') parser.add_argument(\"--alpha\", required=False, help=\"alpha for the model\", default=(11 / 6), type=float)",
"validloss_value, auroc_mean = self.valid() loss_valid_list.append(validloss_value) if auroc_mean > self.auroc_max: print('Better auroc obtained') self.auroc_max",
"self.model.state_dict(), 'best_loss': valid_loss_min, 'optimizer' : self.optimizer.state_dict()}, os.path.join(savepath, f'm-epoch-{epoch_id}.pth')) test_auroc = self.test() print(f\"Epoch:{epoch_id +",
"self.optimizer.step() train_loss_value = trainloss_value.item() loss_train_list.append(train_loss_value) if batch_id % (len(self.data_loader_train)-1) == 0 and batch_id",
"loss_valid_r += lossvalue.item() valid_batches += 1 valid_loss = loss_valid_r / valid_batches auroc_individual =",
"torch.no_grad(): for i, (var_input, var_target) in enumerate(self.data_loader_test): var_target = var_target.to(self.device) var_input = var_input.to(self.device)",
"i, auroc_val in enumerate(auroc_individual): print(f\"{self.class_names[i]}:{auroc_val}\") return auroc_mean def main(args): lr = args.lr checkpoint",
"use gpu if available class_names = ['Lung Opacity', 'Normal', 'No Lung Opacity /",
"default=False, help=\"enable flag->eff model\", action='store_true') parser.add_argument(\"--alpha\", required=False, help=\"alpha for the model\", default=(11 /",
"self.epoch_train() self.current_train_loss = train_loss self.current_valid_loss = valid_loss timestamp_end = time.strftime(\"%H%M%S-%d%m%Y\") if train_loss <",
"weight\", default= None, type = str) parser.add_argument(\"--bs\", required=False, default=16, help=\"Batchsize\", type=int) parser.add_argument(\"--dpath\", required=True,",
"labels = json.load(lab_file) # Place numpy file containing train-valid-test split on tools folder",
"pin_memory=False) dataset_test = RSNADataSet(test_list, labels, img_pth, transform=True) data_loader_test = DataLoader( dataset=dataset_test, batch_size=1, shuffle=False,",
"time import os import argparse import torch from torch.backends import cudnn from torch",
"Normal'] # Data Loader dpath = args.dpath img_pth = os.path.join(args.dpath, 'processed_data/') numpy_path =",
"auroc_mean def main(args): lr = args.lr checkpoint = args.checkpoint batch_size = args.bs max_epoch",
"args.clscount #The objective is to classify the image into 3 classes device =",
"None: model_checkpoint = torch.load(checkpoint) self.optimizer.load_state_dict(model_checkpoint['optimizer']) else: model_checkpoint = None self.loss_fn = torch.nn.BCELoss() def",
"tfunc.one_hot(var_target.squeeze(1).long(), num_classes=self.class_count).float()) self.optimizer.zero_grad() trainloss_value.backward() self.optimizer.step() train_loss_value = trainloss_value.item() loss_train_list.append(train_loss_value) if batch_id % (len(self.data_loader_train)-1)",
"Construct Model if args.optimised: alpha = args.alpha phi = args.phi beta = args.beta",
"1, 'state_dict': self.model.state_dict(), 'best_loss': valid_loss_min, 'optimizer' : self.optimizer.state_dict()}, os.path.join(savepath, f'm-epoch-{epoch_id}.pth')) test_auroc = self.test()",
"= var_input.to(self.device) out_gt = torch.cat((out_gt, var_target), 0).to(self.device) _, c, h, w = var_input.size()",
"data_loader_test self.class_names = class_names self.class_count = class_count self.auroc_max = 0.0 # Setting maximum",
"test_list = np.load(os.path.join(numpy_path,'test_list.npy')).tolist() dataset_train = RSNADataSet(tr_list, labels, img_pth, transform=True) dataset_valid = RSNADataSet(val_list, labels,",
"= var_input.view(-1, c, h, w) out = self.model(var_input) out_pred = torch.cat((out_pred, out), 0)",
"self.loss_fn( var_output, tfunc.one_hot(var_target.squeeze(1).long(), num_classes=self.class_count).float()) self.optimizer.zero_grad() trainloss_value.backward() self.optimizer.step() train_loss_value = trainloss_value.item() loss_train_list.append(train_loss_value) if batch_id",
"classes device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\") # use gpu if available",
"type=float) parser.add_argument(\"--phi\", required=False, help=\"Phi for the model.\", default=1.0, type=float) parser.add_argument(\"--beta\", required=False, help=\"Beta for",
"from torch.optim.lr_scheduler import StepLR from .utils.dataloader import RSNADataSet from .utils.score import compute_auroc from",
"= alpha ** phi beta = beta ** phi model = DenseNet121Eff(alpha, beta,",
"random very high number valid_loss_min = 1e+5 for epoch_id in range(max_epoch): print(f\"Epoch {epoch_id+1}/{max_epoch}\")",
"Loader dpath = args.dpath img_pth = os.path.join(args.dpath, 'processed_data/') numpy_path = os.path.join(args.dpath, 'data_split/') with",
"numpy file containing train-valid-test split on tools folder tr_list = np.load(os.path.join(numpy_path,'train_list.npy')).tolist() val_list =",
"model, data_loader_train, data_loader_valid, data_loader_test, class_count,checkpoint, device, class_names, lr) rsna_trainer.train(max_epoch, savepath) print(\"Model trained !\")",
"self.model.train() scheduler = StepLR(self.optimizer, step_size=6, gamma=0.002) for batch_id, (var_input, var_target) in tq(enumerate(self.data_loader_train)): var_target",
"= np.load(os.path.join(numpy_path,'valid_list.npy')).tolist() test_list = np.load(os.path.join(numpy_path,'test_list.npy')).tolist() dataset_train = RSNADataSet(tr_list, labels, img_pth, transform=True) dataset_valid =",
"self.current_valid_loss = valid_loss timestamp_end = time.strftime(\"%H%M%S-%d%m%Y\") if train_loss < train_loss_min: train_loss_min = train_loss",
"num_classes=self.class_count).float()) self.optimizer.zero_grad() trainloss_value.backward() self.optimizer.step() train_loss_value = trainloss_value.item() loss_train_list.append(train_loss_value) if batch_id % (len(self.data_loader_train)-1) ==",
"split on tools folder tr_list = np.load(os.path.join(numpy_path,'train_list.npy')).tolist() val_list = np.load(os.path.join(numpy_path,'valid_list.npy')).tolist() test_list = np.load(os.path.join(numpy_path,'test_list.npy')).tolist()",
"self.class_count = class_count self.auroc_max = 0.0 # Setting maximum AUROC value as zero",
"for i, auroc_val in enumerate(auroc_individual): print(f\"{self.class_names[i]}:{auroc_val}\") return auroc_mean def main(args): lr = args.lr",
"num_workers=4, pin_memory=False) data_loader_valid = DataLoader( dataset=dataset_valid, batch_size=batch_size, shuffle=False, num_workers=4, pin_memory=False) dataset_test = RSNADataSet(test_list,",
"checkpoint = args.checkpoint batch_size = args.bs max_epoch = args.epochs class_count = args.clscount #The",
"class_count = args.clscount #The objective is to classify the image into 3 classes",
"torch.save({'epoch': epoch_id + 1, 'state_dict': self.model.state_dict(), 'best_loss': valid_loss_min, 'optimizer' : self.optimizer.state_dict()}, os.path.join(savepath, f'm-epoch-{epoch_id}.pth'))",
"valid_batches = 0 # Counter for valid batches out_gt = torch.FloatTensor().to(self.device) out_pred =",
"valid_batches += 1 valid_loss = loss_valid_r / valid_batches auroc_individual = compute_auroc( tfunc.one_hot(out_gt.squeeze(1).long()).float(), out_pred,",
"StepLR from .utils.dataloader import RSNADataSet from .utils.score import compute_auroc from .utils.model import DenseNet121,",
"= round(sqrt(2 / alpha), 3) alpha = alpha ** phi beta = beta",
"var_target = var_target.to(self.device) out_gt = torch.cat((out_gt, var_target), 0).to(self.device) _, c, h, w =",
"parser.add_argument(\"--phi\", required=False, help=\"Phi for the model.\", default=1.0, type=float) parser.add_argument(\"--beta\", required=False, help=\"Beta for the",
"valid_loss_mean, auroc_mean def test(self): cudnn.benchmark = True out_gt = torch.FloatTensor().to(self.device) out_pred = torch.FloatTensor().to(self.device)",
"loss_valid_r / valid_batches auroc_individual = compute_auroc( tfunc.one_hot(out_gt.squeeze(1).long()).float(), out_pred, self.class_count) print(len(auroc_individual)) auroc_mean = np.array(auroc_individual).mean()",
"0: validloss_value, auroc_mean = self.valid() loss_valid_list.append(validloss_value) if auroc_mean > self.auroc_max: print('Better auroc obtained')",
"the model.\", default=1.0, type=float) parser.add_argument(\"--beta\", required=False, help=\"Beta for the model.\", default=None, type=float) custom_args",
"var_target), 0).to(self.device) _, c, h, w = var_input.size() var_input = var_input.view(-1, c, h,",
"out_pred, self.class_count) auroc_mean = np.array(auroc_individual).mean() print(f'AUROC mean:{auroc_mean}') for i, auroc_val in enumerate(auroc_individual): print(f\"{self.class_names[i]}:{auroc_val}\")",
"batch_id % (len(self.data_loader_train)-1) == 0 and batch_id != 0: validloss_value, auroc_mean = self.valid()",
"# Setting maximum AUROC value as zero self.optimizer = optim.Adam(self.model.parameters(), lr=lr) if checkpoint",
"import json from tqdm import tqdm as tq class RSNATrainer(): def __init__(self, model,",
"1e+5 # A random very high number valid_loss_min = 1e+5 for epoch_id in",
"self.auroc_max = 0.0 # Setting maximum AUROC value as zero self.optimizer = optim.Adam(self.model.parameters(),",
"for epoch_id in range(max_epoch): print(f\"Epoch {epoch_id+1}/{max_epoch}\") self.gepoch_id = epoch_id train_loss, valid_loss, auroc_max =",
"compute_auroc from .utils.model import DenseNet121, DenseNet121Eff from math import sqrt import json from",
"torch.cat((out_pred, out), 0) auroc_individual = compute_auroc(tfunc.one_hot(out_gt.squeeze(1).long()).float(), out_pred, self.class_count) auroc_mean = np.array(auroc_individual).mean() print(f'AUROC mean:{auroc_mean}')",
"required=True, help=\"Path to folder in which models should be saved\", type =str) parser.add_argument(\"--optimised\",",
"os.path.join(args.dpath, 'data_split/') with open(os.path.join(dpath, 'rsna_annotation.json')) as lab_file: labels = json.load(lab_file) # Place numpy",
"= True out_gt = torch.FloatTensor().to(self.device) out_pred = torch.FloatTensor().to(self.device) self.model.eval() with torch.no_grad(): for i,",
"data_loader_valid self.data_loader_test = data_loader_test self.class_names = class_names self.class_count = class_count self.auroc_max = 0.0",
"num_workers=4, pin_memory=False) # Construct Model if args.optimised: alpha = args.alpha phi = args.phi",
"train_loss < train_loss_min: train_loss_min = train_loss if valid_loss < valid_loss_min: valid_loss_min = valid_loss",
"type=int) parser.add_argument(\"--clscount\", required=False, default=3, help=\"Number of classes\", type=int) parser.add_argument(\"--spath\", required=True, help=\"Path to folder",
"self.optimizer.zero_grad() trainloss_value.backward() self.optimizer.step() train_loss_value = trainloss_value.item() loss_train_list.append(train_loss_value) if batch_id % (len(self.data_loader_train)-1) == 0",
"train_loss self.current_valid_loss = valid_loss timestamp_end = time.strftime(\"%H%M%S-%d%m%Y\") if train_loss < train_loss_min: train_loss_min =",
"savepath = args.spath rsna_trainer = RSNATrainer( model, data_loader_train, data_loader_valid, data_loader_test, class_count,checkpoint, device, class_names,",
"models should be saved\", type =str) parser.add_argument(\"--optimised\", required=False, default=False, help=\"enable flag->eff model\", action='store_true')",
"DataLoader( dataset=dataset_test, batch_size=1, shuffle=False, num_workers=4, pin_memory=False) # Construct Model if args.optimised: alpha =",
"train_loss_mean = np.mean(loss_train_list) valid_loss_mean = np.mean(loss_valid_list) return train_loss_mean, valid_loss_mean, auroc_mean def test(self): cudnn.benchmark",
"help=\"Checkpoint model weight\", default= None, type = str) parser.add_argument(\"--bs\", required=False, default=16, help=\"Batchsize\", type=int)",
"# A random very high number valid_loss_min = 1e+5 for epoch_id in range(max_epoch):",
"< valid_loss_min: valid_loss_min = valid_loss torch.save({'epoch': epoch_id + 1, 'state_dict': self.model.state_dict(), 'best_loss': valid_loss_min,",
"c, h, w) out = self.model(var_input) out_pred = torch.cat((out_pred, out), 0) auroc_individual =",
"/ 6), type=float) parser.add_argument(\"--phi\", required=False, help=\"Phi for the model.\", default=1.0, type=float) parser.add_argument(\"--beta\", required=False,",
"w = var_input.size() var_input = var_input.view(-1, c, h, w) var_output = self.model(var_input.to(self.device)) out_pred",
"self.class_count) print(len(auroc_individual)) auroc_mean = np.array(auroc_individual).mean() return valid_loss, auroc_mean def epoch_train(self): loss_train_list = []",
"np.array(auroc_individual).mean() return valid_loss, auroc_mean def epoch_train(self): loss_train_list = [] loss_valid_list = [] self.model.train()",
"dataset=dataset_train, batch_size=batch_size, shuffle=True, num_workers=4, pin_memory=False) data_loader_valid = DataLoader( dataset=dataset_valid, batch_size=batch_size, shuffle=False, num_workers=4, pin_memory=False)",
"import StepLR from .utils.dataloader import RSNADataSet from .utils.score import compute_auroc from .utils.model import",
"__name__==\"__main__\": parser = argparse.ArgumentParser() parser.add_argument(\"--lr\", required=False, help=\"Learning rate\", default=1e-4, type = float) parser.add_argument(\"--checkpoint\",",
"c, h, w = var_input.size() var_input = var_input.view(-1, c, h, w) var_output =",
"from torch import optim import torch.nn.functional as tfunc from torch.utils.data import DataLoader from",
"in tq(self.data_loader_valid): var_target = var_target.to(self.device) out_gt = torch.cat((out_gt, var_target), 0).to(self.device) _, c, h,",
"auroc_individual = compute_auroc(tfunc.one_hot(out_gt.squeeze(1).long()).float(), out_pred, self.class_count) auroc_mean = np.array(auroc_individual).mean() print(f'AUROC mean:{auroc_mean}') for i, auroc_val",
"+= 1 valid_loss = loss_valid_r / valid_batches auroc_individual = compute_auroc( tfunc.one_hot(out_gt.squeeze(1).long()).float(), out_pred, self.class_count)",
"# Counter for valid batches out_gt = torch.FloatTensor().to(self.device) out_pred = torch.FloatTensor().to(self.device) with torch.no_grad():",
"compute_auroc( tfunc.one_hot(out_gt.squeeze(1).long()).float(), out_pred, self.class_count) print(len(auroc_individual)) auroc_mean = np.array(auroc_individual).mean() return valid_loss, auroc_mean def epoch_train(self):",
"auroc_mean = np.array(auroc_individual).mean() return valid_loss, auroc_mean def epoch_train(self): loss_train_list = [] loss_valid_list =",
"** phi model = DenseNet121Eff(alpha, beta, class_count) else: model = DenseNet121(class_count) # Train",
"phi model = DenseNet121Eff(alpha, beta, class_count) else: model = DenseNet121(class_count) # Train the",
"action='store_true') parser.add_argument(\"--alpha\", required=False, help=\"alpha for the model\", default=(11 / 6), type=float) parser.add_argument(\"--phi\", required=False,",
"w) out = self.model(var_input) out_pred = torch.cat((out_pred, out), 0) auroc_individual = compute_auroc(tfunc.one_hot(out_gt.squeeze(1).long()).float(), out_pred,",
"= torch.FloatTensor().to(self.device) with torch.no_grad(): for (var_input, var_target) in tq(self.data_loader_valid): var_target = var_target.to(self.device) out_gt",
"epochs\", type=int) parser.add_argument(\"--clscount\", required=False, default=3, help=\"Number of classes\", type=int) parser.add_argument(\"--spath\", required=True, help=\"Path to",
"'No Lung Opacity / Not Normal'] # Data Loader dpath = args.dpath img_pth",
"type=int) parser.add_argument(\"--spath\", required=True, help=\"Path to folder in which models should be saved\", type",
"'Normal', 'No Lung Opacity / Not Normal'] # Data Loader dpath = args.dpath",
"0).to(self.device) _, c, h, w = var_input.size() var_input = var_input.view(-1, c, h, w)",
"import cudnn from torch import optim import torch.nn.functional as tfunc from torch.utils.data import",
"[] loss_valid_list = [] self.model.train() scheduler = StepLR(self.optimizer, step_size=6, gamma=0.002) for batch_id, (var_input,",
"help=\"Path to folder in which models should be saved\", type =str) parser.add_argument(\"--optimised\", required=False,",
"data_loader_valid, data_loader_test, class_count,checkpoint, device, class_names, lr) rsna_trainer.train(max_epoch, savepath) print(\"Model trained !\") if __name__==\"__main__\":",
"numpy_path = os.path.join(args.dpath, 'data_split/') with open(os.path.join(dpath, 'rsna_annotation.json')) as lab_file: labels = json.load(lab_file) #",
"= DenseNet121(class_count) # Train the Model savepath = args.spath rsna_trainer = RSNATrainer( model,",
"Model savepath = args.spath rsna_trainer = RSNATrainer( model, data_loader_train, data_loader_valid, data_loader_test, class_count,checkpoint, device,",
"['Lung Opacity', 'Normal', 'No Lung Opacity / Not Normal'] # Data Loader dpath",
"EndTime:{timestamp_end}| TestAUROC: {test_auroc}| ValidAUROC: {auroc_max}\") def valid(self): self.model.eval() loss_valid_r = 0 valid_batches =",
"+ 1}| EndTime:{timestamp_end}| TestAUROC: {test_auroc}| ValidAUROC: {auroc_max}\") def valid(self): self.model.eval() loss_valid_r = 0",
"c, h, w) var_output = self.model(var_input.to(self.device)) out_pred = torch.cat((out_pred, var_output), 0) lossvalue =",
"img_pth = os.path.join(args.dpath, 'processed_data/') numpy_path = os.path.join(args.dpath, 'data_split/') with open(os.path.join(dpath, 'rsna_annotation.json')) as lab_file:",
"parser = argparse.ArgumentParser() parser.add_argument(\"--lr\", required=False, help=\"Learning rate\", default=1e-4, type = float) parser.add_argument(\"--checkpoint\", required=False,",
"self.gepoch_id = epoch_id train_loss, valid_loss, auroc_max = self.epoch_train() self.current_train_loss = train_loss self.current_valid_loss =",
"train_loss_mean, valid_loss_mean, auroc_mean def test(self): cudnn.benchmark = True out_gt = torch.FloatTensor().to(self.device) out_pred =",
"tr_list = np.load(os.path.join(numpy_path,'train_list.npy')).tolist() val_list = np.load(os.path.join(numpy_path,'valid_list.npy')).tolist() test_list = np.load(os.path.join(numpy_path,'test_list.npy')).tolist() dataset_train = RSNADataSet(tr_list, labels,",
"help=\"Number of epochs\", type=int) parser.add_argument(\"--clscount\", required=False, default=3, help=\"Number of classes\", type=int) parser.add_argument(\"--spath\", required=True,",
"not None: model_checkpoint = torch.load(checkpoint) self.optimizer.load_state_dict(model_checkpoint['optimizer']) else: model_checkpoint = None self.loss_fn = torch.nn.BCELoss()",
"h, w = var_input.size() var_input = var_input.view(-1, c, h, w) out = self.model(var_input)",
"train(self, max_epoch, savepath): train_loss_min = 1e+5 # A random very high number valid_loss_min",
"= self.model(var_input) out_pred = torch.cat((out_pred, out), 0) auroc_individual = compute_auroc(tfunc.one_hot(out_gt.squeeze(1).long()).float(), out_pred, self.class_count) auroc_mean",
"auroc_mean = np.array(auroc_individual).mean() print(f'AUROC mean:{auroc_mean}') for i, auroc_val in enumerate(auroc_individual): print(f\"{self.class_names[i]}:{auroc_val}\") return auroc_mean",
"optim import torch.nn.functional as tfunc from torch.utils.data import DataLoader from torch.optim.lr_scheduler import StepLR",
"self.data_loader_train = data_loader_train self.data_loader_valid = data_loader_valid self.data_loader_test = data_loader_test self.class_names = class_names self.class_count",
"TestAUROC: {test_auroc}| ValidAUROC: {auroc_max}\") def valid(self): self.model.eval() loss_valid_r = 0 valid_batches = 0",
"for batch_id, (var_input, var_target) in tq(enumerate(self.data_loader_train)): var_target = var_target.to(self.device) var_input = var_input.to(self.device) var_output=",
"print(f\"{self.class_names[i]}:{auroc_val}\") return auroc_mean def main(args): lr = args.lr checkpoint = args.checkpoint batch_size =",
"help=\"Learning rate\", default=1e-4, type = float) parser.add_argument(\"--checkpoint\", required=False, help=\"Checkpoint model weight\", default= None,",
"def train(self, max_epoch, savepath): train_loss_min = 1e+5 # A random very high number",
"torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\") # use gpu if available class_names = ['Lung",
"high number valid_loss_min = 1e+5 for epoch_id in range(max_epoch): print(f\"Epoch {epoch_id+1}/{max_epoch}\") self.gepoch_id =",
"model.to(self.device) self.data_loader_train = data_loader_train self.data_loader_valid = data_loader_valid self.data_loader_test = data_loader_test self.class_names = class_names",
"batches out_gt = torch.FloatTensor().to(self.device) out_pred = torch.FloatTensor().to(self.device) with torch.no_grad(): for (var_input, var_target) in",
"= args.spath rsna_trainer = RSNATrainer( model, data_loader_train, data_loader_valid, data_loader_test, class_count,checkpoint, device, class_names, lr)",
"(var_input, var_target) in tq(self.data_loader_valid): var_target = var_target.to(self.device) out_gt = torch.cat((out_gt, var_target), 0).to(self.device) _,",
"def __init__(self, model, data_loader_train, data_loader_valid, data_loader_test, class_count, checkpoint, device, class_names, lr): self.gepoch_id =",
"= data_loader_train self.data_loader_valid = data_loader_valid self.data_loader_test = data_loader_test self.class_names = class_names self.class_count =",
"train_loss, valid_loss, auroc_max = self.epoch_train() self.current_train_loss = train_loss self.current_valid_loss = valid_loss timestamp_end =",
"data_loader_train = DataLoader( dataset=dataset_train, batch_size=batch_size, shuffle=True, num_workers=4, pin_memory=False) data_loader_valid = DataLoader( dataset=dataset_valid, batch_size=batch_size,",
"= train_loss if valid_loss < valid_loss_min: valid_loss_min = valid_loss torch.save({'epoch': epoch_id + 1,",
"args.spath rsna_trainer = RSNATrainer( model, data_loader_train, data_loader_valid, data_loader_test, class_count,checkpoint, device, class_names, lr) rsna_trainer.train(max_epoch,",
"containing all data\", type =str) parser.add_argument(\"--epochs\", required=False, default=15, help=\"Number of epochs\", type=int) parser.add_argument(\"--clscount\",",
"RSNADataSet(tr_list, labels, img_pth, transform=True) dataset_valid = RSNADataSet(val_list, labels, img_pth, transform=True) data_loader_train = DataLoader(",
"auroc_mean def epoch_train(self): loss_train_list = [] loss_valid_list = [] self.model.train() scheduler = StepLR(self.optimizer,",
"beta = round(sqrt(2 / alpha), 3) alpha = alpha ** phi beta =",
"required=True, help=\"Path to folder containing all data\", type =str) parser.add_argument(\"--epochs\", required=False, default=15, help=\"Number",
": self.optimizer.state_dict()}, os.path.join(savepath, f'm-epoch-{epoch_id}.pth')) test_auroc = self.test() print(f\"Epoch:{epoch_id + 1}| EndTime:{timestamp_end}| TestAUROC: {test_auroc}|",
"= np.array(auroc_individual).mean() return valid_loss, auroc_mean def epoch_train(self): loss_train_list = [] loss_valid_list = []",
"3 classes device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\") # use gpu if",
"var_input.view(-1, c, h, w) out = self.model(var_input) out_pred = torch.cat((out_pred, out), 0) auroc_individual",
"args.alpha phi = args.phi beta = args.beta if beta is None: beta =",
"h, w) out = self.model(var_input) out_pred = torch.cat((out_pred, out), 0) auroc_individual = compute_auroc(tfunc.one_hot(out_gt.squeeze(1).long()).float(),",
"var_input = var_input.view(-1, c, h, w) var_output = self.model(var_input.to(self.device)) out_pred = torch.cat((out_pred, var_output),",
"self.model.eval() with torch.no_grad(): for i, (var_input, var_target) in enumerate(self.data_loader_test): var_target = var_target.to(self.device) var_input",
"beta, class_count) else: model = DenseNet121(class_count) # Train the Model savepath = args.spath",
"classes\", type=int) parser.add_argument(\"--spath\", required=True, help=\"Path to folder in which models should be saved\",",
"torch from torch.backends import cudnn from torch import optim import torch.nn.functional as tfunc"
] |
[
"def __init__(self, parent=None): super(self_QlineEdit, self).__init__(parent) def event(self, event): if event.type() == QEvent.MouseButtonPress: mouseEvent",
"* from PyQt5.QtGui import * class self_QlineEdit(QtWidgets.QLineEdit): clicked = pyqtSignal() def __init__(self, parent=None):",
"PyQt5.QtGui import * class self_QlineEdit(QtWidgets.QLineEdit): clicked = pyqtSignal() def __init__(self, parent=None): super(self_QlineEdit, self).__init__(parent)",
"= pyqtSignal() def __init__(self, parent=None): super(self_QlineEdit, self).__init__(parent) def event(self, event): if event.type() ==",
"class self_QlineEdit(QtWidgets.QLineEdit): clicked = pyqtSignal() def __init__(self, parent=None): super(self_QlineEdit, self).__init__(parent) def event(self, event):",
"import * class self_QlineEdit(QtWidgets.QLineEdit): clicked = pyqtSignal() def __init__(self, parent=None): super(self_QlineEdit, self).__init__(parent) def",
"event.type() == QEvent.MouseButtonPress: mouseEvent = QMouseEvent(event) if mouseEvent.buttons() == Qt.LeftButton: self.clicked.emit() return QtWidgets.QLineEdit.event(self,event)",
"<reponame>vonlippmann/Deep-_Style_Transfer from PyQt5 import QtCore, QtGui, QtWidgets from PyQt5.QtCore import * from PyQt5.QtGui",
"from PyQt5.QtCore import * from PyQt5.QtGui import * class self_QlineEdit(QtWidgets.QLineEdit): clicked = pyqtSignal()",
"clicked = pyqtSignal() def __init__(self, parent=None): super(self_QlineEdit, self).__init__(parent) def event(self, event): if event.type()",
"if event.type() == QEvent.MouseButtonPress: mouseEvent = QMouseEvent(event) if mouseEvent.buttons() == Qt.LeftButton: self.clicked.emit() return",
"def event(self, event): if event.type() == QEvent.MouseButtonPress: mouseEvent = QMouseEvent(event) if mouseEvent.buttons() ==",
"QtWidgets from PyQt5.QtCore import * from PyQt5.QtGui import * class self_QlineEdit(QtWidgets.QLineEdit): clicked =",
"self_QlineEdit(QtWidgets.QLineEdit): clicked = pyqtSignal() def __init__(self, parent=None): super(self_QlineEdit, self).__init__(parent) def event(self, event): if",
"from PyQt5 import QtCore, QtGui, QtWidgets from PyQt5.QtCore import * from PyQt5.QtGui import",
"super(self_QlineEdit, self).__init__(parent) def event(self, event): if event.type() == QEvent.MouseButtonPress: mouseEvent = QMouseEvent(event) if",
"PyQt5.QtCore import * from PyQt5.QtGui import * class self_QlineEdit(QtWidgets.QLineEdit): clicked = pyqtSignal() def",
"QtGui, QtWidgets from PyQt5.QtCore import * from PyQt5.QtGui import * class self_QlineEdit(QtWidgets.QLineEdit): clicked",
"QtCore, QtGui, QtWidgets from PyQt5.QtCore import * from PyQt5.QtGui import * class self_QlineEdit(QtWidgets.QLineEdit):",
"PyQt5 import QtCore, QtGui, QtWidgets from PyQt5.QtCore import * from PyQt5.QtGui import *",
"from PyQt5.QtGui import * class self_QlineEdit(QtWidgets.QLineEdit): clicked = pyqtSignal() def __init__(self, parent=None): super(self_QlineEdit,",
"self).__init__(parent) def event(self, event): if event.type() == QEvent.MouseButtonPress: mouseEvent = QMouseEvent(event) if mouseEvent.buttons()",
"import QtCore, QtGui, QtWidgets from PyQt5.QtCore import * from PyQt5.QtGui import * class",
"event(self, event): if event.type() == QEvent.MouseButtonPress: mouseEvent = QMouseEvent(event) if mouseEvent.buttons() == Qt.LeftButton:",
"event): if event.type() == QEvent.MouseButtonPress: mouseEvent = QMouseEvent(event) if mouseEvent.buttons() == Qt.LeftButton: self.clicked.emit()",
"pyqtSignal() def __init__(self, parent=None): super(self_QlineEdit, self).__init__(parent) def event(self, event): if event.type() == QEvent.MouseButtonPress:",
"__init__(self, parent=None): super(self_QlineEdit, self).__init__(parent) def event(self, event): if event.type() == QEvent.MouseButtonPress: mouseEvent =",
"import * from PyQt5.QtGui import * class self_QlineEdit(QtWidgets.QLineEdit): clicked = pyqtSignal() def __init__(self,",
"* class self_QlineEdit(QtWidgets.QLineEdit): clicked = pyqtSignal() def __init__(self, parent=None): super(self_QlineEdit, self).__init__(parent) def event(self,",
"parent=None): super(self_QlineEdit, self).__init__(parent) def event(self, event): if event.type() == QEvent.MouseButtonPress: mouseEvent = QMouseEvent(event)"
] |
[
"import shutil raw_path = \"/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/eth_brownie-1.15.0-py3.9.egg/brownie/project/brownie_project\" install_path = \"/Users/aeneas/.brownie/packages/brownie/brownie_project@0.1\" shutil.rmtree(install_path) # os.makedirs(install_path) shutil.copytree(raw_path, install_path)",
"os import shutil raw_path = \"/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/eth_brownie-1.15.0-py3.9.egg/brownie/project/brownie_project\" install_path = \"/Users/aeneas/.brownie/packages/brownie/brownie_project@0.1\" shutil.rmtree(install_path) # os.makedirs(install_path) shutil.copytree(raw_path,",
"import os import shutil raw_path = \"/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/eth_brownie-1.15.0-py3.9.egg/brownie/project/brownie_project\" install_path = \"/Users/aeneas/.brownie/packages/brownie/brownie_project@0.1\" shutil.rmtree(install_path) # os.makedirs(install_path)",
"<reponame>AeneasHe/eth-brownie-enhance<filename>tmp/test.py import os import shutil raw_path = \"/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/eth_brownie-1.15.0-py3.9.egg/brownie/project/brownie_project\" install_path = \"/Users/aeneas/.brownie/packages/brownie/brownie_project@0.1\" shutil.rmtree(install_path) #"
] |
[
"random seed = '<KEY>' def generate(num: int): ''' Generate num random strings. '''",
"''' Generate num random strings. ''' text = '' for i in range(num):",
"Generate num random strings. ''' text = '' for i in range(num): text",
"import random seed = '<KEY>' def generate(num: int): ''' Generate num random strings.",
"''' text = '' for i in range(num): text += random.choice(seed) return text",
"int): ''' Generate num random strings. ''' text = '' for i in",
"'<KEY>' def generate(num: int): ''' Generate num random strings. ''' text = ''",
"strings. ''' text = '' for i in range(num): text += random.choice(seed) return",
"def generate(num: int): ''' Generate num random strings. ''' text = '' for",
"generate(num: int): ''' Generate num random strings. ''' text = '' for i",
"random strings. ''' text = '' for i in range(num): text += random.choice(seed)",
"num random strings. ''' text = '' for i in range(num): text +=",
"<reponame>Cyberbolt/CyberDB<filename>cyberdb/extensions/nonce.py import random seed = '<KEY>' def generate(num: int): ''' Generate num random",
"seed = '<KEY>' def generate(num: int): ''' Generate num random strings. ''' text",
"= '<KEY>' def generate(num: int): ''' Generate num random strings. ''' text ="
] |
[
"import glob import os import io excludes = ['vanderwalt', 'bibderwalt'] # status_file_root possible",
"= os.path.join(build_dir, 'toc.json') proc_conf = os.path.join(work_dir, '../scipy_proc.json') xref_conf = os.path.join(build_dir, 'doi_batch.xml') status_file =",
"= os.path.join(build_dir, 'doi_batch.xml') status_file = os.path.join(static_dir, status_file_name) if os.path.isfile(toc_list): with io.open(toc_list, 'r', encoding='utf-8')",
"'draft' status_file_name = ''.join([status_file_base, '.sty']) work_dir = os.path.dirname(__file__) papers_dir = os.path.join(work_dir, '../papers') output_dir",
"os.path.join(static_dir, 'toc.txt') build_dir = os.path.join(work_dir, '_build') pdf_dir = os.path.join(build_dir, 'pdfs') html_dir = os.path.join(build_dir,",
"os.path.join(build_dir, 'html') bib_dir = os.path.join(html_dir, 'bib') toc_conf = os.path.join(build_dir, 'toc.json') proc_conf = os.path.join(work_dir,",
"draft, conference, ready status_file_base = 'draft' status_file_name = ''.join([status_file_base, '.sty']) work_dir = os.path.dirname(__file__)",
"possible values: draft, conference, ready status_file_base = 'draft' status_file_name = ''.join([status_file_base, '.sty']) work_dir",
"= ['vanderwalt', 'bibderwalt'] # status_file_root possible values: draft, conference, ready status_file_base = 'draft'",
"os.path.join(work_dir, '_static') css_file = os.path.join(static_dir, 'scipy-proc.css') toc_list = os.path.join(static_dir, 'toc.txt') build_dir = os.path.join(work_dir,",
"status_file_name = ''.join([status_file_base, '.sty']) work_dir = os.path.dirname(__file__) papers_dir = os.path.join(work_dir, '../papers') output_dir =",
"io.open(toc_list, 'r', encoding='utf-8') as f: dirs = f.read().splitlines() else: dirs = sorted([os.path.basename(d) for",
"'toc.json') proc_conf = os.path.join(work_dir, '../scipy_proc.json') xref_conf = os.path.join(build_dir, 'doi_batch.xml') status_file = os.path.join(static_dir, status_file_name)",
"os.path.join(work_dir, '../scipy_proc.json') xref_conf = os.path.join(build_dir, 'doi_batch.xml') status_file = os.path.join(static_dir, status_file_name) if os.path.isfile(toc_list): with",
"toc_list = os.path.join(static_dir, 'toc.txt') build_dir = os.path.join(work_dir, '_build') pdf_dir = os.path.join(build_dir, 'pdfs') html_dir",
"static_dir = os.path.join(work_dir, '_static') css_file = os.path.join(static_dir, 'scipy-proc.css') toc_list = os.path.join(static_dir, 'toc.txt') build_dir",
"'doi_batch.xml') status_file = os.path.join(static_dir, status_file_name) if os.path.isfile(toc_list): with io.open(toc_list, 'r', encoding='utf-8') as f:",
"as f: dirs = f.read().splitlines() else: dirs = sorted([os.path.basename(d) for d in glob.glob('%s/*'",
"papers_dir = os.path.join(work_dir, '../papers') output_dir = os.path.join(work_dir, '../output') template_dir = os.path.join(work_dir, '_templates') static_dir",
"os.path.dirname(__file__) papers_dir = os.path.join(work_dir, '../papers') output_dir = os.path.join(work_dir, '../output') template_dir = os.path.join(work_dir, '_templates')",
"dirs = f.read().splitlines() else: dirs = sorted([os.path.basename(d) for d in glob.glob('%s/*' % papers_dir)",
"os.path.join(html_dir, 'bib') toc_conf = os.path.join(build_dir, 'toc.json') proc_conf = os.path.join(work_dir, '../scipy_proc.json') xref_conf = os.path.join(build_dir,",
"= os.path.join(build_dir, 'pdfs') html_dir = os.path.join(build_dir, 'html') bib_dir = os.path.join(html_dir, 'bib') toc_conf =",
"'scipy-proc.css') toc_list = os.path.join(static_dir, 'toc.txt') build_dir = os.path.join(work_dir, '_build') pdf_dir = os.path.join(build_dir, 'pdfs')",
"values: draft, conference, ready status_file_base = 'draft' status_file_name = ''.join([status_file_base, '.sty']) work_dir =",
"os import io excludes = ['vanderwalt', 'bibderwalt'] # status_file_root possible values: draft, conference,",
"output_dir = os.path.join(work_dir, '../output') template_dir = os.path.join(work_dir, '_templates') static_dir = os.path.join(work_dir, '_static') css_file",
"'pdfs') html_dir = os.path.join(build_dir, 'html') bib_dir = os.path.join(html_dir, 'bib') toc_conf = os.path.join(build_dir, 'toc.json')",
"ready status_file_base = 'draft' status_file_name = ''.join([status_file_base, '.sty']) work_dir = os.path.dirname(__file__) papers_dir =",
"f.read().splitlines() else: dirs = sorted([os.path.basename(d) for d in glob.glob('%s/*' % papers_dir) if os.path.isdir(d)",
"work_dir = os.path.dirname(__file__) papers_dir = os.path.join(work_dir, '../papers') output_dir = os.path.join(work_dir, '../output') template_dir =",
"status_file_name) if os.path.isfile(toc_list): with io.open(toc_list, 'r', encoding='utf-8') as f: dirs = f.read().splitlines() else:",
"glob.glob('%s/*' % papers_dir) if os.path.isdir(d) and not any(e in d for e in",
"status_file_base = 'draft' status_file_name = ''.join([status_file_base, '.sty']) work_dir = os.path.dirname(__file__) papers_dir = os.path.join(work_dir,",
"'bibderwalt'] # status_file_root possible values: draft, conference, ready status_file_base = 'draft' status_file_name =",
"conference, ready status_file_base = 'draft' status_file_name = ''.join([status_file_base, '.sty']) work_dir = os.path.dirname(__file__) papers_dir",
"proc_conf = os.path.join(work_dir, '../scipy_proc.json') xref_conf = os.path.join(build_dir, 'doi_batch.xml') status_file = os.path.join(static_dir, status_file_name) if",
"bib_dir = os.path.join(html_dir, 'bib') toc_conf = os.path.join(build_dir, 'toc.json') proc_conf = os.path.join(work_dir, '../scipy_proc.json') xref_conf",
"'.sty']) work_dir = os.path.dirname(__file__) papers_dir = os.path.join(work_dir, '../papers') output_dir = os.path.join(work_dir, '../output') template_dir",
"'_build') pdf_dir = os.path.join(build_dir, 'pdfs') html_dir = os.path.join(build_dir, 'html') bib_dir = os.path.join(html_dir, 'bib')",
"= os.path.join(html_dir, 'bib') toc_conf = os.path.join(build_dir, 'toc.json') proc_conf = os.path.join(work_dir, '../scipy_proc.json') xref_conf =",
"'_static') css_file = os.path.join(static_dir, 'scipy-proc.css') toc_list = os.path.join(static_dir, 'toc.txt') build_dir = os.path.join(work_dir, '_build')",
"= sorted([os.path.basename(d) for d in glob.glob('%s/*' % papers_dir) if os.path.isdir(d) and not any(e",
"dirs = sorted([os.path.basename(d) for d in glob.glob('%s/*' % papers_dir) if os.path.isdir(d) and not",
"= os.path.join(work_dir, '_build') pdf_dir = os.path.join(build_dir, 'pdfs') html_dir = os.path.join(build_dir, 'html') bib_dir =",
"= os.path.join(work_dir, '_templates') static_dir = os.path.join(work_dir, '_static') css_file = os.path.join(static_dir, 'scipy-proc.css') toc_list =",
"= os.path.join(build_dir, 'html') bib_dir = os.path.join(html_dir, 'bib') toc_conf = os.path.join(build_dir, 'toc.json') proc_conf =",
"if os.path.isfile(toc_list): with io.open(toc_list, 'r', encoding='utf-8') as f: dirs = f.read().splitlines() else: dirs",
"= os.path.join(work_dir, '_static') css_file = os.path.join(static_dir, 'scipy-proc.css') toc_list = os.path.join(static_dir, 'toc.txt') build_dir =",
"with io.open(toc_list, 'r', encoding='utf-8') as f: dirs = f.read().splitlines() else: dirs = sorted([os.path.basename(d)",
"'_templates') static_dir = os.path.join(work_dir, '_static') css_file = os.path.join(static_dir, 'scipy-proc.css') toc_list = os.path.join(static_dir, 'toc.txt')",
"os.path.join(build_dir, 'doi_batch.xml') status_file = os.path.join(static_dir, status_file_name) if os.path.isfile(toc_list): with io.open(toc_list, 'r', encoding='utf-8') as",
"os.path.join(build_dir, 'pdfs') html_dir = os.path.join(build_dir, 'html') bib_dir = os.path.join(html_dir, 'bib') toc_conf = os.path.join(build_dir,",
"status_file = os.path.join(static_dir, status_file_name) if os.path.isfile(toc_list): with io.open(toc_list, 'r', encoding='utf-8') as f: dirs",
"= os.path.join(static_dir, 'toc.txt') build_dir = os.path.join(work_dir, '_build') pdf_dir = os.path.join(build_dir, 'pdfs') html_dir =",
"'../papers') output_dir = os.path.join(work_dir, '../output') template_dir = os.path.join(work_dir, '_templates') static_dir = os.path.join(work_dir, '_static')",
"= os.path.join(static_dir, status_file_name) if os.path.isfile(toc_list): with io.open(toc_list, 'r', encoding='utf-8') as f: dirs =",
"# status_file_root possible values: draft, conference, ready status_file_base = 'draft' status_file_name = ''.join([status_file_base,",
"= os.path.join(work_dir, '../output') template_dir = os.path.join(work_dir, '_templates') static_dir = os.path.join(work_dir, '_static') css_file =",
"'html') bib_dir = os.path.join(html_dir, 'bib') toc_conf = os.path.join(build_dir, 'toc.json') proc_conf = os.path.join(work_dir, '../scipy_proc.json')",
"'../output') template_dir = os.path.join(work_dir, '_templates') static_dir = os.path.join(work_dir, '_static') css_file = os.path.join(static_dir, 'scipy-proc.css')",
"os.path.join(work_dir, '../papers') output_dir = os.path.join(work_dir, '../output') template_dir = os.path.join(work_dir, '_templates') static_dir = os.path.join(work_dir,",
"in glob.glob('%s/*' % papers_dir) if os.path.isdir(d) and not any(e in d for e",
"'../scipy_proc.json') xref_conf = os.path.join(build_dir, 'doi_batch.xml') status_file = os.path.join(static_dir, status_file_name) if os.path.isfile(toc_list): with io.open(toc_list,",
"xref_conf = os.path.join(build_dir, 'doi_batch.xml') status_file = os.path.join(static_dir, status_file_name) if os.path.isfile(toc_list): with io.open(toc_list, 'r',",
"= f.read().splitlines() else: dirs = sorted([os.path.basename(d) for d in glob.glob('%s/*' % papers_dir) if",
"os.path.join(work_dir, '_templates') static_dir = os.path.join(work_dir, '_static') css_file = os.path.join(static_dir, 'scipy-proc.css') toc_list = os.path.join(static_dir,",
"'bib') toc_conf = os.path.join(build_dir, 'toc.json') proc_conf = os.path.join(work_dir, '../scipy_proc.json') xref_conf = os.path.join(build_dir, 'doi_batch.xml')",
"else: dirs = sorted([os.path.basename(d) for d in glob.glob('%s/*' % papers_dir) if os.path.isdir(d) and",
"'toc.txt') build_dir = os.path.join(work_dir, '_build') pdf_dir = os.path.join(build_dir, 'pdfs') html_dir = os.path.join(build_dir, 'html')",
"io excludes = ['vanderwalt', 'bibderwalt'] # status_file_root possible values: draft, conference, ready status_file_base",
"template_dir = os.path.join(work_dir, '_templates') static_dir = os.path.join(work_dir, '_static') css_file = os.path.join(static_dir, 'scipy-proc.css') toc_list",
"= ''.join([status_file_base, '.sty']) work_dir = os.path.dirname(__file__) papers_dir = os.path.join(work_dir, '../papers') output_dir = os.path.join(work_dir,",
"''.join([status_file_base, '.sty']) work_dir = os.path.dirname(__file__) papers_dir = os.path.join(work_dir, '../papers') output_dir = os.path.join(work_dir, '../output')",
"import io excludes = ['vanderwalt', 'bibderwalt'] # status_file_root possible values: draft, conference, ready",
"os.path.join(build_dir, 'toc.json') proc_conf = os.path.join(work_dir, '../scipy_proc.json') xref_conf = os.path.join(build_dir, 'doi_batch.xml') status_file = os.path.join(static_dir,",
"css_file = os.path.join(static_dir, 'scipy-proc.css') toc_list = os.path.join(static_dir, 'toc.txt') build_dir = os.path.join(work_dir, '_build') pdf_dir",
"html_dir = os.path.join(build_dir, 'html') bib_dir = os.path.join(html_dir, 'bib') toc_conf = os.path.join(build_dir, 'toc.json') proc_conf",
"import os import io excludes = ['vanderwalt', 'bibderwalt'] # status_file_root possible values: draft,",
"sorted([os.path.basename(d) for d in glob.glob('%s/*' % papers_dir) if os.path.isdir(d) and not any(e in",
"'r', encoding='utf-8') as f: dirs = f.read().splitlines() else: dirs = sorted([os.path.basename(d) for d",
"glob import os import io excludes = ['vanderwalt', 'bibderwalt'] # status_file_root possible values:",
"pdf_dir = os.path.join(build_dir, 'pdfs') html_dir = os.path.join(build_dir, 'html') bib_dir = os.path.join(html_dir, 'bib') toc_conf",
"os.path.join(work_dir, '../output') template_dir = os.path.join(work_dir, '_templates') static_dir = os.path.join(work_dir, '_static') css_file = os.path.join(static_dir,",
"os.path.join(work_dir, '_build') pdf_dir = os.path.join(build_dir, 'pdfs') html_dir = os.path.join(build_dir, 'html') bib_dir = os.path.join(html_dir,",
"d in glob.glob('%s/*' % papers_dir) if os.path.isdir(d) and not any(e in d for",
"status_file_root possible values: draft, conference, ready status_file_base = 'draft' status_file_name = ''.join([status_file_base, '.sty'])",
"= os.path.join(work_dir, '../scipy_proc.json') xref_conf = os.path.join(build_dir, 'doi_batch.xml') status_file = os.path.join(static_dir, status_file_name) if os.path.isfile(toc_list):",
"os.path.isfile(toc_list): with io.open(toc_list, 'r', encoding='utf-8') as f: dirs = f.read().splitlines() else: dirs =",
"= 'draft' status_file_name = ''.join([status_file_base, '.sty']) work_dir = os.path.dirname(__file__) papers_dir = os.path.join(work_dir, '../papers')",
"['vanderwalt', 'bibderwalt'] # status_file_root possible values: draft, conference, ready status_file_base = 'draft' status_file_name",
"= os.path.dirname(__file__) papers_dir = os.path.join(work_dir, '../papers') output_dir = os.path.join(work_dir, '../output') template_dir = os.path.join(work_dir,",
"= os.path.join(static_dir, 'scipy-proc.css') toc_list = os.path.join(static_dir, 'toc.txt') build_dir = os.path.join(work_dir, '_build') pdf_dir =",
"os.path.join(static_dir, status_file_name) if os.path.isfile(toc_list): with io.open(toc_list, 'r', encoding='utf-8') as f: dirs = f.read().splitlines()",
"toc_conf = os.path.join(build_dir, 'toc.json') proc_conf = os.path.join(work_dir, '../scipy_proc.json') xref_conf = os.path.join(build_dir, 'doi_batch.xml') status_file",
"excludes = ['vanderwalt', 'bibderwalt'] # status_file_root possible values: draft, conference, ready status_file_base =",
"<filename>publisher/conf.py import glob import os import io excludes = ['vanderwalt', 'bibderwalt'] # status_file_root",
"% papers_dir) if os.path.isdir(d) and not any(e in d for e in excludes)])",
"encoding='utf-8') as f: dirs = f.read().splitlines() else: dirs = sorted([os.path.basename(d) for d in",
"for d in glob.glob('%s/*' % papers_dir) if os.path.isdir(d) and not any(e in d",
"build_dir = os.path.join(work_dir, '_build') pdf_dir = os.path.join(build_dir, 'pdfs') html_dir = os.path.join(build_dir, 'html') bib_dir",
"os.path.join(static_dir, 'scipy-proc.css') toc_list = os.path.join(static_dir, 'toc.txt') build_dir = os.path.join(work_dir, '_build') pdf_dir = os.path.join(build_dir,",
"f: dirs = f.read().splitlines() else: dirs = sorted([os.path.basename(d) for d in glob.glob('%s/*' %",
"= os.path.join(work_dir, '../papers') output_dir = os.path.join(work_dir, '../output') template_dir = os.path.join(work_dir, '_templates') static_dir ="
] |
[
"PacketManager: def __init__(self): self.packets = [] def add_packet(self, packet): Packet(packet) self.packets.append(packet) def read_packet(self,",
"__init__(self): self.packets = [] def add_packet(self, packet): Packet(packet) self.packets.append(packet) def read_packet(self, number): try:",
"False class Packet: def __init__(self, packet): self._packet = packet def get_packet(self): return self._packet",
"print(packet.number) except: return False class Packet: def __init__(self, packet): self._packet = packet def",
"class PacketManager: def __init__(self): self.packets = [] def add_packet(self, packet): Packet(packet) self.packets.append(packet) def",
"def read_packet(self, number): try: packet = self.packets[number] print(packet.number) except: return False class Packet:",
"def add_packet(self, packet): Packet(packet) self.packets.append(packet) def read_packet(self, number): try: packet = self.packets[number] print(packet.number)",
"= self.packets[number] print(packet.number) except: return False class Packet: def __init__(self, packet): self._packet =",
"self.packets.append(packet) def read_packet(self, number): try: packet = self.packets[number] print(packet.number) except: return False class",
"return False class Packet: def __init__(self, packet): self._packet = packet def get_packet(self): return",
"self.packets[number] print(packet.number) except: return False class Packet: def __init__(self, packet): self._packet = packet",
"number): try: packet = self.packets[number] print(packet.number) except: return False class Packet: def __init__(self,",
"except: return False class Packet: def __init__(self, packet): self._packet = packet def get_packet(self):",
"packet = self.packets[number] print(packet.number) except: return False class Packet: def __init__(self, packet): self._packet",
"add_packet(self, packet): Packet(packet) self.packets.append(packet) def read_packet(self, number): try: packet = self.packets[number] print(packet.number) except:",
"packet): Packet(packet) self.packets.append(packet) def read_packet(self, number): try: packet = self.packets[number] print(packet.number) except: return",
"[] def add_packet(self, packet): Packet(packet) self.packets.append(packet) def read_packet(self, number): try: packet = self.packets[number]",
"try: packet = self.packets[number] print(packet.number) except: return False class Packet: def __init__(self, packet):",
"self.packets = [] def add_packet(self, packet): Packet(packet) self.packets.append(packet) def read_packet(self, number): try: packet",
"= [] def add_packet(self, packet): Packet(packet) self.packets.append(packet) def read_packet(self, number): try: packet =",
"Packet(packet) self.packets.append(packet) def read_packet(self, number): try: packet = self.packets[number] print(packet.number) except: return False",
"<filename>run/packet_manager.py class PacketManager: def __init__(self): self.packets = [] def add_packet(self, packet): Packet(packet) self.packets.append(packet)",
"def __init__(self): self.packets = [] def add_packet(self, packet): Packet(packet) self.packets.append(packet) def read_packet(self, number):",
"read_packet(self, number): try: packet = self.packets[number] print(packet.number) except: return False class Packet: def"
] |
[] |
[
"import DSPFatal @guvectorize([\"void(float32[:], float32, float32, float32, float32[:])\", \"void(float64[:], float64, float64, float64, float64[:])\"], \"(n),(),(),()->()\",",
"Find the index where the waveform value crosses the threshold, walking either forward",
"t_out[0] = np.nan if np.isnan(w_in).any() or np.isnan(a_threshold) or np.isnan(t_start) or np.isnan(walk_forward): return if",
"1: for i in range(int(t_start), len(w_in) - 1, 1): if w_in[i] <= a_threshold",
"if np.floor(walk_forward) != walk_forward: raise DSPFatal('The search direction must be an integer') if",
"np.nan if np.isnan(w_in).any() or np.isnan(a_threshold) or np.isnan(t_start) or np.isnan(walk_forward): return if np.floor(t_start) !=",
"np.isnan(walk_forward): return if np.floor(t_start) != t_start: raise DSPFatal('The starting index must be an",
"\"unit\": \"ns\", \"prereqs\": [\"wf_atrap\", \"bl_std\", \"tp_start\"] } \"\"\" t_out[0] = np.nan if np.isnan(w_in).any()",
"(1) search direction t_out : float The index where the waveform value crosses",
"in range(int(t_start), 1, -1): if w_in[i-1] < a_threshold <= w_in[i]: t_out[0] = i",
"the waveform value crosses the threshold, walking either forward or backward from the",
"from pygama.dsp.errors import DSPFatal @guvectorize([\"void(float32[:], float32, float32, float32, float32[:])\", \"void(float64[:], float64, float64, float64,",
"float The index where the waveform value crosses the threshold Processing Chain Example",
"len(w_in): raise DSPFatal('The starting index is out of range') if int(walk_forward) == 1:",
"be an integer') if np.floor(walk_forward) != walk_forward: raise DSPFatal('The search direction must be",
"input waveform a_threshold : float The threshold value t_start : int The starting",
"for i in range(int(t_start), len(w_in) - 1, 1): if w_in[i] <= a_threshold <",
": float The index where the waveform value crosses the threshold Processing Chain",
"w_in[i] <= a_threshold < w_in[i+1]: t_out[0] = i return else: for i in",
"numba import guvectorize from pygama.dsp.errors import DSPFatal @guvectorize([\"void(float32[:], float32, float32, float32, float32[:])\", \"void(float64[:],",
"must be an integer') if int(t_start) < 0 or int(t_start) >= len(w_in): raise",
"int(walk_forward) == 1: for i in range(int(t_start), len(w_in) - 1, 1): if w_in[i]",
"walk_forward, t_out): \"\"\" Find the index where the waveform value crosses the threshold,",
"threshold, walking either forward or backward from the starting index. Parameters ---------- w_in",
"\"pygama.dsp.processors\", \"args\": [\"wf_atrap\", \"bl_std\", \"tp_start\", 0, \"tp_0\"], \"unit\": \"ns\", \"prereqs\": [\"wf_atrap\", \"bl_std\", \"tp_start\"]",
"= np.nan if np.isnan(w_in).any() or np.isnan(a_threshold) or np.isnan(t_start) or np.isnan(walk_forward): return if np.floor(t_start)",
"crosses the threshold, walking either forward or backward from the starting index. Parameters",
"from the starting index. Parameters ---------- w_in : array-like The input waveform a_threshold",
"starting index walk_forward: int The backward (0) or forward (1) search direction t_out",
"< 0 or int(t_start) >= len(w_in): raise DSPFatal('The starting index is out of",
"import guvectorize from pygama.dsp.errors import DSPFatal @guvectorize([\"void(float32[:], float32, float32, float32, float32[:])\", \"void(float64[:], float64,",
"Chain Example ------------------------ \"tp_0\": { \"function\": \"time_point_thresh\", \"module\": \"pygama.dsp.processors\", \"args\": [\"wf_atrap\", \"bl_std\", \"tp_start\",",
"return else: for i in range(int(t_start), 1, -1): if w_in[i-1] < a_threshold <=",
"Parameters ---------- w_in : array-like The input waveform a_threshold : float The threshold",
"time_point_thresh(w_in, a_threshold, t_start, walk_forward, t_out): \"\"\" Find the index where the waveform value",
"search direction t_out : float The index where the waveform value crosses the",
"np from numba import guvectorize from pygama.dsp.errors import DSPFatal @guvectorize([\"void(float32[:], float32, float32, float32,",
"DSPFatal @guvectorize([\"void(float32[:], float32, float32, float32, float32[:])\", \"void(float64[:], float64, float64, float64, float64[:])\"], \"(n),(),(),()->()\", nopython=True,",
"value crosses the threshold, walking either forward or backward from the starting index.",
"} \"\"\" t_out[0] = np.nan if np.isnan(w_in).any() or np.isnan(a_threshold) or np.isnan(t_start) or np.isnan(walk_forward):",
"DSPFatal('The search direction must be an integer') if int(t_start) < 0 or int(t_start)",
"is out of range') if int(walk_forward) == 1: for i in range(int(t_start), len(w_in)",
"starting index is out of range') if int(walk_forward) == 1: for i in",
"raise DSPFatal('The search direction must be an integer') if int(t_start) < 0 or",
"0 or int(t_start) >= len(w_in): raise DSPFatal('The starting index is out of range')",
"starting index must be an integer') if np.floor(walk_forward) != walk_forward: raise DSPFatal('The search",
"index is out of range') if int(walk_forward) == 1: for i in range(int(t_start),",
"the threshold, walking either forward or backward from the starting index. Parameters ----------",
"nopython=True, cache=True) def time_point_thresh(w_in, a_threshold, t_start, walk_forward, t_out): \"\"\" Find the index where",
"float64, float64[:])\"], \"(n),(),(),()->()\", nopython=True, cache=True) def time_point_thresh(w_in, a_threshold, t_start, walk_forward, t_out): \"\"\" Find",
"t_out : float The index where the waveform value crosses the threshold Processing",
"for i in range(int(t_start), 1, -1): if w_in[i-1] < a_threshold <= w_in[i]: t_out[0]",
"range(int(t_start), len(w_in) - 1, 1): if w_in[i] <= a_threshold < w_in[i+1]: t_out[0] =",
"\"time_point_thresh\", \"module\": \"pygama.dsp.processors\", \"args\": [\"wf_atrap\", \"bl_std\", \"tp_start\", 0, \"tp_0\"], \"unit\": \"ns\", \"prereqs\": [\"wf_atrap\",",
"[\"wf_atrap\", \"bl_std\", \"tp_start\"] } \"\"\" t_out[0] = np.nan if np.isnan(w_in).any() or np.isnan(a_threshold) or",
"numpy as np from numba import guvectorize from pygama.dsp.errors import DSPFatal @guvectorize([\"void(float32[:], float32,",
"walking either forward or backward from the starting index. Parameters ---------- w_in :",
"\"tp_start\", 0, \"tp_0\"], \"unit\": \"ns\", \"prereqs\": [\"wf_atrap\", \"bl_std\", \"tp_start\"] } \"\"\" t_out[0] =",
"\"ns\", \"prereqs\": [\"wf_atrap\", \"bl_std\", \"tp_start\"] } \"\"\" t_out[0] = np.nan if np.isnan(w_in).any() or",
"1): if w_in[i] <= a_threshold < w_in[i+1]: t_out[0] = i return else: for",
"or np.isnan(t_start) or np.isnan(walk_forward): return if np.floor(t_start) != t_start: raise DSPFatal('The starting index",
"= i return else: for i in range(int(t_start), 1, -1): if w_in[i-1] <",
"the starting index. Parameters ---------- w_in : array-like The input waveform a_threshold :",
"the index where the waveform value crosses the threshold, walking either forward or",
"float64[:])\"], \"(n),(),(),()->()\", nopython=True, cache=True) def time_point_thresh(w_in, a_threshold, t_start, walk_forward, t_out): \"\"\" Find the",
"the waveform value crosses the threshold Processing Chain Example ------------------------ \"tp_0\": { \"function\":",
"or int(t_start) >= len(w_in): raise DSPFatal('The starting index is out of range') if",
"np.floor(t_start) != t_start: raise DSPFatal('The starting index must be an integer') if np.floor(walk_forward)",
"\"void(float64[:], float64, float64, float64, float64[:])\"], \"(n),(),(),()->()\", nopython=True, cache=True) def time_point_thresh(w_in, a_threshold, t_start, walk_forward,",
"waveform value crosses the threshold Processing Chain Example ------------------------ \"tp_0\": { \"function\": \"time_point_thresh\",",
"as np from numba import guvectorize from pygama.dsp.errors import DSPFatal @guvectorize([\"void(float32[:], float32, float32,",
"the threshold Processing Chain Example ------------------------ \"tp_0\": { \"function\": \"time_point_thresh\", \"module\": \"pygama.dsp.processors\", \"args\":",
"\"tp_0\": { \"function\": \"time_point_thresh\", \"module\": \"pygama.dsp.processors\", \"args\": [\"wf_atrap\", \"bl_std\", \"tp_start\", 0, \"tp_0\"], \"unit\":",
"0, \"tp_0\"], \"unit\": \"ns\", \"prereqs\": [\"wf_atrap\", \"bl_std\", \"tp_start\"] } \"\"\" t_out[0] = np.nan",
"float The threshold value t_start : int The starting index walk_forward: int The",
"w_in[i+1]: t_out[0] = i return else: for i in range(int(t_start), 1, -1): if",
"a_threshold, t_start, walk_forward, t_out): \"\"\" Find the index where the waveform value crosses",
"1, 1): if w_in[i] <= a_threshold < w_in[i+1]: t_out[0] = i return else:",
"crosses the threshold Processing Chain Example ------------------------ \"tp_0\": { \"function\": \"time_point_thresh\", \"module\": \"pygama.dsp.processors\",",
"integer') if np.floor(walk_forward) != walk_forward: raise DSPFatal('The search direction must be an integer')",
"int(t_start) < 0 or int(t_start) >= len(w_in): raise DSPFatal('The starting index is out",
"index where the waveform value crosses the threshold Processing Chain Example ------------------------ \"tp_0\":",
"if np.floor(t_start) != t_start: raise DSPFatal('The starting index must be an integer') if",
"return if np.floor(t_start) != t_start: raise DSPFatal('The starting index must be an integer')",
"or np.isnan(walk_forward): return if np.floor(t_start) != t_start: raise DSPFatal('The starting index must be",
"{ \"function\": \"time_point_thresh\", \"module\": \"pygama.dsp.processors\", \"args\": [\"wf_atrap\", \"bl_std\", \"tp_start\", 0, \"tp_0\"], \"unit\": \"ns\",",
"raise DSPFatal('The starting index must be an integer') if np.floor(walk_forward) != walk_forward: raise",
"backward (0) or forward (1) search direction t_out : float The index where",
"must be an integer') if np.floor(walk_forward) != walk_forward: raise DSPFatal('The search direction must",
"range(int(t_start), 1, -1): if w_in[i-1] < a_threshold <= w_in[i]: t_out[0] = i return",
"DSPFatal('The starting index must be an integer') if np.floor(walk_forward) != walk_forward: raise DSPFatal('The",
"starting index. Parameters ---------- w_in : array-like The input waveform a_threshold : float",
"forward or backward from the starting index. Parameters ---------- w_in : array-like The",
"direction must be an integer') if int(t_start) < 0 or int(t_start) >= len(w_in):",
"t_out[0] = i return else: for i in range(int(t_start), 1, -1): if w_in[i-1]",
"either forward or backward from the starting index. Parameters ---------- w_in : array-like",
"\"\"\" t_out[0] = np.nan if np.isnan(w_in).any() or np.isnan(a_threshold) or np.isnan(t_start) or np.isnan(walk_forward): return",
"where the waveform value crosses the threshold Processing Chain Example ------------------------ \"tp_0\": {",
"The threshold value t_start : int The starting index walk_forward: int The backward",
"len(w_in) - 1, 1): if w_in[i] <= a_threshold < w_in[i+1]: t_out[0] = i",
"\"module\": \"pygama.dsp.processors\", \"args\": [\"wf_atrap\", \"bl_std\", \"tp_start\", 0, \"tp_0\"], \"unit\": \"ns\", \"prereqs\": [\"wf_atrap\", \"bl_std\",",
"Processing Chain Example ------------------------ \"tp_0\": { \"function\": \"time_point_thresh\", \"module\": \"pygama.dsp.processors\", \"args\": [\"wf_atrap\", \"bl_std\",",
"------------------------ \"tp_0\": { \"function\": \"time_point_thresh\", \"module\": \"pygama.dsp.processors\", \"args\": [\"wf_atrap\", \"bl_std\", \"tp_start\", 0, \"tp_0\"],",
"or forward (1) search direction t_out : float The index where the waveform",
"index must be an integer') if np.floor(walk_forward) != walk_forward: raise DSPFatal('The search direction",
"!= t_start: raise DSPFatal('The starting index must be an integer') if np.floor(walk_forward) !=",
"an integer') if np.floor(walk_forward) != walk_forward: raise DSPFatal('The search direction must be an",
"i in range(int(t_start), len(w_in) - 1, 1): if w_in[i] <= a_threshold < w_in[i+1]:",
"np.isnan(t_start) or np.isnan(walk_forward): return if np.floor(t_start) != t_start: raise DSPFatal('The starting index must",
"else: for i in range(int(t_start), 1, -1): if w_in[i-1] < a_threshold <= w_in[i]:",
"or backward from the starting index. Parameters ---------- w_in : array-like The input",
"array-like The input waveform a_threshold : float The threshold value t_start : int",
"index. Parameters ---------- w_in : array-like The input waveform a_threshold : float The",
"index walk_forward: int The backward (0) or forward (1) search direction t_out :",
"Example ------------------------ \"tp_0\": { \"function\": \"time_point_thresh\", \"module\": \"pygama.dsp.processors\", \"args\": [\"wf_atrap\", \"bl_std\", \"tp_start\", 0,",
"np.isnan(w_in).any() or np.isnan(a_threshold) or np.isnan(t_start) or np.isnan(walk_forward): return if np.floor(t_start) != t_start: raise",
"cache=True) def time_point_thresh(w_in, a_threshold, t_start, walk_forward, t_out): \"\"\" Find the index where the",
"float32, float32, float32[:])\", \"void(float64[:], float64, float64, float64, float64[:])\"], \"(n),(),(),()->()\", nopython=True, cache=True) def time_point_thresh(w_in,",
"int The starting index walk_forward: int The backward (0) or forward (1) search",
"t_out): \"\"\" Find the index where the waveform value crosses the threshold, walking",
"waveform value crosses the threshold, walking either forward or backward from the starting",
"an integer') if int(t_start) < 0 or int(t_start) >= len(w_in): raise DSPFatal('The starting",
"float32, float32, float32, float32[:])\", \"void(float64[:], float64, float64, float64, float64[:])\"], \"(n),(),(),()->()\", nopython=True, cache=True) def",
"walk_forward: raise DSPFatal('The search direction must be an integer') if int(t_start) < 0",
"backward from the starting index. Parameters ---------- w_in : array-like The input waveform",
"if w_in[i] <= a_threshold < w_in[i+1]: t_out[0] = i return else: for i",
"of range') if int(walk_forward) == 1: for i in range(int(t_start), len(w_in) - 1,",
"\"(n),(),(),()->()\", nopython=True, cache=True) def time_point_thresh(w_in, a_threshold, t_start, walk_forward, t_out): \"\"\" Find the index",
"range') if int(walk_forward) == 1: for i in range(int(t_start), len(w_in) - 1, 1):",
"forward (1) search direction t_out : float The index where the waveform value",
"int(t_start) >= len(w_in): raise DSPFatal('The starting index is out of range') if int(walk_forward)",
"float64, float64, float64[:])\"], \"(n),(),(),()->()\", nopython=True, cache=True) def time_point_thresh(w_in, a_threshold, t_start, walk_forward, t_out): \"\"\"",
"< w_in[i+1]: t_out[0] = i return else: for i in range(int(t_start), 1, -1):",
"\"bl_std\", \"tp_start\"] } \"\"\" t_out[0] = np.nan if np.isnan(w_in).any() or np.isnan(a_threshold) or np.isnan(t_start)",
"float32, float32[:])\", \"void(float64[:], float64, float64, float64, float64[:])\"], \"(n),(),(),()->()\", nopython=True, cache=True) def time_point_thresh(w_in, a_threshold,",
"\"tp_0\"], \"unit\": \"ns\", \"prereqs\": [\"wf_atrap\", \"bl_std\", \"tp_start\"] } \"\"\" t_out[0] = np.nan if",
"pygama.dsp.errors import DSPFatal @guvectorize([\"void(float32[:], float32, float32, float32, float32[:])\", \"void(float64[:], float64, float64, float64, float64[:])\"],",
"\"tp_start\"] } \"\"\" t_out[0] = np.nan if np.isnan(w_in).any() or np.isnan(a_threshold) or np.isnan(t_start) or",
"- 1, 1): if w_in[i] <= a_threshold < w_in[i+1]: t_out[0] = i return",
"or np.isnan(a_threshold) or np.isnan(t_start) or np.isnan(walk_forward): return if np.floor(t_start) != t_start: raise DSPFatal('The",
"walk_forward: int The backward (0) or forward (1) search direction t_out : float",
": int The starting index walk_forward: int The backward (0) or forward (1)",
"out of range') if int(walk_forward) == 1: for i in range(int(t_start), len(w_in) -",
"where the waveform value crosses the threshold, walking either forward or backward from",
"\"\"\" Find the index where the waveform value crosses the threshold, walking either",
"np.floor(walk_forward) != walk_forward: raise DSPFatal('The search direction must be an integer') if int(t_start)",
"\"bl_std\", \"tp_start\", 0, \"tp_0\"], \"unit\": \"ns\", \"prereqs\": [\"wf_atrap\", \"bl_std\", \"tp_start\"] } \"\"\" t_out[0]",
"search direction must be an integer') if int(t_start) < 0 or int(t_start) >=",
"float64, float64, float64, float64[:])\"], \"(n),(),(),()->()\", nopython=True, cache=True) def time_point_thresh(w_in, a_threshold, t_start, walk_forward, t_out):",
"---------- w_in : array-like The input waveform a_threshold : float The threshold value",
"def time_point_thresh(w_in, a_threshold, t_start, walk_forward, t_out): \"\"\" Find the index where the waveform",
"w_in : array-like The input waveform a_threshold : float The threshold value t_start",
": array-like The input waveform a_threshold : float The threshold value t_start :",
"\"prereqs\": [\"wf_atrap\", \"bl_std\", \"tp_start\"] } \"\"\" t_out[0] = np.nan if np.isnan(w_in).any() or np.isnan(a_threshold)",
">= len(w_in): raise DSPFatal('The starting index is out of range') if int(walk_forward) ==",
"t_start, walk_forward, t_out): \"\"\" Find the index where the waveform value crosses the",
"index where the waveform value crosses the threshold, walking either forward or backward",
"value crosses the threshold Processing Chain Example ------------------------ \"tp_0\": { \"function\": \"time_point_thresh\", \"module\":",
"a_threshold < w_in[i+1]: t_out[0] = i return else: for i in range(int(t_start), 1,",
"(0) or forward (1) search direction t_out : float The index where the",
"i return else: for i in range(int(t_start), 1, -1): if w_in[i-1] < a_threshold",
"<= a_threshold < w_in[i+1]: t_out[0] = i return else: for i in range(int(t_start),",
"a_threshold : float The threshold value t_start : int The starting index walk_forward:",
"value t_start : int The starting index walk_forward: int The backward (0) or",
"if np.isnan(w_in).any() or np.isnan(a_threshold) or np.isnan(t_start) or np.isnan(walk_forward): return if np.floor(t_start) != t_start:",
"The index where the waveform value crosses the threshold Processing Chain Example ------------------------",
"threshold Processing Chain Example ------------------------ \"tp_0\": { \"function\": \"time_point_thresh\", \"module\": \"pygama.dsp.processors\", \"args\": [\"wf_atrap\",",
"in range(int(t_start), len(w_in) - 1, 1): if w_in[i] <= a_threshold < w_in[i+1]: t_out[0]",
"import numpy as np from numba import guvectorize from pygama.dsp.errors import DSPFatal @guvectorize([\"void(float32[:],",
"== 1: for i in range(int(t_start), len(w_in) - 1, 1): if w_in[i] <=",
"integer') if int(t_start) < 0 or int(t_start) >= len(w_in): raise DSPFatal('The starting index",
"t_start: raise DSPFatal('The starting index must be an integer') if np.floor(walk_forward) != walk_forward:",
"np.isnan(a_threshold) or np.isnan(t_start) or np.isnan(walk_forward): return if np.floor(t_start) != t_start: raise DSPFatal('The starting",
"[\"wf_atrap\", \"bl_std\", \"tp_start\", 0, \"tp_0\"], \"unit\": \"ns\", \"prereqs\": [\"wf_atrap\", \"bl_std\", \"tp_start\"] } \"\"\"",
"raise DSPFatal('The starting index is out of range') if int(walk_forward) == 1: for",
"DSPFatal('The starting index is out of range') if int(walk_forward) == 1: for i",
": float The threshold value t_start : int The starting index walk_forward: int",
"if int(walk_forward) == 1: for i in range(int(t_start), len(w_in) - 1, 1): if",
"i in range(int(t_start), 1, -1): if w_in[i-1] < a_threshold <= w_in[i]: t_out[0] =",
"int The backward (0) or forward (1) search direction t_out : float The",
"if int(t_start) < 0 or int(t_start) >= len(w_in): raise DSPFatal('The starting index is",
"waveform a_threshold : float The threshold value t_start : int The starting index",
"The input waveform a_threshold : float The threshold value t_start : int The",
"threshold value t_start : int The starting index walk_forward: int The backward (0)",
"t_start : int The starting index walk_forward: int The backward (0) or forward",
"\"function\": \"time_point_thresh\", \"module\": \"pygama.dsp.processors\", \"args\": [\"wf_atrap\", \"bl_std\", \"tp_start\", 0, \"tp_0\"], \"unit\": \"ns\", \"prereqs\":",
"The starting index walk_forward: int The backward (0) or forward (1) search direction",
"float32[:])\", \"void(float64[:], float64, float64, float64, float64[:])\"], \"(n),(),(),()->()\", nopython=True, cache=True) def time_point_thresh(w_in, a_threshold, t_start,",
"direction t_out : float The index where the waveform value crosses the threshold",
"from numba import guvectorize from pygama.dsp.errors import DSPFatal @guvectorize([\"void(float32[:], float32, float32, float32, float32[:])\",",
"be an integer') if int(t_start) < 0 or int(t_start) >= len(w_in): raise DSPFatal('The",
"\"args\": [\"wf_atrap\", \"bl_std\", \"tp_start\", 0, \"tp_0\"], \"unit\": \"ns\", \"prereqs\": [\"wf_atrap\", \"bl_std\", \"tp_start\"] }",
"!= walk_forward: raise DSPFatal('The search direction must be an integer') if int(t_start) <",
"@guvectorize([\"void(float32[:], float32, float32, float32, float32[:])\", \"void(float64[:], float64, float64, float64, float64[:])\"], \"(n),(),(),()->()\", nopython=True, cache=True)",
"guvectorize from pygama.dsp.errors import DSPFatal @guvectorize([\"void(float32[:], float32, float32, float32, float32[:])\", \"void(float64[:], float64, float64,",
"The backward (0) or forward (1) search direction t_out : float The index"
] |
[
"input1=int(input(\"enter a number:\")) print(\"prints the range of natural numbers\") for i in range(1,",
"print(\"prints the range of natural numbers\") for i in range(1, input1+1): print(\"%d\" %",
"a number:\")) print(\"prints the range of natural numbers\") for i in range(1, input1+1):",
"the range of natural numbers\") for i in range(1, input1+1): print(\"%d\" % (i))``",
"number:\")) print(\"prints the range of natural numbers\") for i in range(1, input1+1): print(\"%d\""
] |
[
"metadata\"\"\" TITLE = \"aiocometd\" DESCRIPTION = \"CometD client for asyncio\" KEYWORDS = \"asyncio",
"<gh_stars>10-100 \"\"\"Package metadata\"\"\" TITLE = \"aiocometd\" DESCRIPTION = \"CometD client for asyncio\" KEYWORDS",
"= \"CometD client for asyncio\" KEYWORDS = \"asyncio aiohttp comet cometd bayeux push",
"= \"https://github.com/robertmrk/aiocometd\" PROJECT_URLS = { \"CI\": \"https://travis-ci.org/robertmrk/aiocometd\", \"Coverage\": \"https://coveralls.io/github/robertmrk/aiocometd\", \"Docs\": \"http://aiocometd.readthedocs.io/\" } VERSION",
"KEYWORDS = \"asyncio aiohttp comet cometd bayeux push streaming\" URL = \"https://github.com/robertmrk/aiocometd\" PROJECT_URLS",
"= \"aiocometd\" DESCRIPTION = \"CometD client for asyncio\" KEYWORDS = \"asyncio aiohttp comet",
"for asyncio\" KEYWORDS = \"asyncio aiohttp comet cometd bayeux push streaming\" URL =",
"\"https://github.com/robertmrk/aiocometd\" PROJECT_URLS = { \"CI\": \"https://travis-ci.org/robertmrk/aiocometd\", \"Coverage\": \"https://coveralls.io/github/robertmrk/aiocometd\", \"Docs\": \"http://aiocometd.readthedocs.io/\" } VERSION =",
"\"https://travis-ci.org/robertmrk/aiocometd\", \"Coverage\": \"https://coveralls.io/github/robertmrk/aiocometd\", \"Docs\": \"http://aiocometd.readthedocs.io/\" } VERSION = \"0.4.5\" AUTHOR = \"<NAME>\" AUTHOR_EMAIL",
"comet cometd bayeux push streaming\" URL = \"https://github.com/robertmrk/aiocometd\" PROJECT_URLS = { \"CI\": \"https://travis-ci.org/robertmrk/aiocometd\",",
"aiohttp comet cometd bayeux push streaming\" URL = \"https://github.com/robertmrk/aiocometd\" PROJECT_URLS = { \"CI\":",
"client for asyncio\" KEYWORDS = \"asyncio aiohttp comet cometd bayeux push streaming\" URL",
"push streaming\" URL = \"https://github.com/robertmrk/aiocometd\" PROJECT_URLS = { \"CI\": \"https://travis-ci.org/robertmrk/aiocometd\", \"Coverage\": \"https://coveralls.io/github/robertmrk/aiocometd\", \"Docs\":",
"= \"asyncio aiohttp comet cometd bayeux push streaming\" URL = \"https://github.com/robertmrk/aiocometd\" PROJECT_URLS =",
"DESCRIPTION = \"CometD client for asyncio\" KEYWORDS = \"asyncio aiohttp comet cometd bayeux",
"\"CI\": \"https://travis-ci.org/robertmrk/aiocometd\", \"Coverage\": \"https://coveralls.io/github/robertmrk/aiocometd\", \"Docs\": \"http://aiocometd.readthedocs.io/\" } VERSION = \"0.4.5\" AUTHOR = \"<NAME>\"",
"cometd bayeux push streaming\" URL = \"https://github.com/robertmrk/aiocometd\" PROJECT_URLS = { \"CI\": \"https://travis-ci.org/robertmrk/aiocometd\", \"Coverage\":",
"PROJECT_URLS = { \"CI\": \"https://travis-ci.org/robertmrk/aiocometd\", \"Coverage\": \"https://coveralls.io/github/robertmrk/aiocometd\", \"Docs\": \"http://aiocometd.readthedocs.io/\" } VERSION = \"0.4.5\"",
"\"https://coveralls.io/github/robertmrk/aiocometd\", \"Docs\": \"http://aiocometd.readthedocs.io/\" } VERSION = \"0.4.5\" AUTHOR = \"<NAME>\" AUTHOR_EMAIL = \"<EMAIL>\"",
"streaming\" URL = \"https://github.com/robertmrk/aiocometd\" PROJECT_URLS = { \"CI\": \"https://travis-ci.org/robertmrk/aiocometd\", \"Coverage\": \"https://coveralls.io/github/robertmrk/aiocometd\", \"Docs\": \"http://aiocometd.readthedocs.io/\"",
"bayeux push streaming\" URL = \"https://github.com/robertmrk/aiocometd\" PROJECT_URLS = { \"CI\": \"https://travis-ci.org/robertmrk/aiocometd\", \"Coverage\": \"https://coveralls.io/github/robertmrk/aiocometd\",",
"\"CometD client for asyncio\" KEYWORDS = \"asyncio aiohttp comet cometd bayeux push streaming\"",
"\"Coverage\": \"https://coveralls.io/github/robertmrk/aiocometd\", \"Docs\": \"http://aiocometd.readthedocs.io/\" } VERSION = \"0.4.5\" AUTHOR = \"<NAME>\" AUTHOR_EMAIL =",
"= { \"CI\": \"https://travis-ci.org/robertmrk/aiocometd\", \"Coverage\": \"https://coveralls.io/github/robertmrk/aiocometd\", \"Docs\": \"http://aiocometd.readthedocs.io/\" } VERSION = \"0.4.5\" AUTHOR",
"\"\"\"Package metadata\"\"\" TITLE = \"aiocometd\" DESCRIPTION = \"CometD client for asyncio\" KEYWORDS =",
"\"asyncio aiohttp comet cometd bayeux push streaming\" URL = \"https://github.com/robertmrk/aiocometd\" PROJECT_URLS = {",
"URL = \"https://github.com/robertmrk/aiocometd\" PROJECT_URLS = { \"CI\": \"https://travis-ci.org/robertmrk/aiocometd\", \"Coverage\": \"https://coveralls.io/github/robertmrk/aiocometd\", \"Docs\": \"http://aiocometd.readthedocs.io/\" }",
"TITLE = \"aiocometd\" DESCRIPTION = \"CometD client for asyncio\" KEYWORDS = \"asyncio aiohttp",
"\"aiocometd\" DESCRIPTION = \"CometD client for asyncio\" KEYWORDS = \"asyncio aiohttp comet cometd",
"asyncio\" KEYWORDS = \"asyncio aiohttp comet cometd bayeux push streaming\" URL = \"https://github.com/robertmrk/aiocometd\"",
"{ \"CI\": \"https://travis-ci.org/robertmrk/aiocometd\", \"Coverage\": \"https://coveralls.io/github/robertmrk/aiocometd\", \"Docs\": \"http://aiocometd.readthedocs.io/\" } VERSION = \"0.4.5\" AUTHOR ="
] |
[
"data_obj_y_test.data_id result_y_test['columnNames'] = data_obj_y_test.column_names result['X_train'] = result_X_train result['X_test'] = result_X_test result['y_train'] = result_y_train",
"handler.mlsklearn.util import regqeust_arg_to_sklearn_arg from sklearn.model_selection import train_test_split from data.persistence import * from data.data_source",
"* from data.data_source import DataSource from data.data_storage import DataStorage class TrainTestSplitHandler(tornado.web.RequestHandler): def post(self):",
"data_id == None: raise Exception(\"please input data_id\") data_column_names = json_data.get('dataColumnNames', None) if data_column_names",
"pd.DataFrame(X_train, columns=data_column_names) data_obj_X_train = DataStorage.create_data_obj_by_pandas_data(X_train) X_test = pd.DataFrame(X_test, columns=data_column_names) data_obj_X_test = DataStorage.create_data_obj_by_pandas_data(X_test) y_train",
"DataStorage.create_data_obj_by_pandas_data(y_train) y_test = pd.DataFrame(y_test, columns=[target_column_name]) data_obj_y_test = DataStorage.create_data_obj_by_pandas_data(y_test) result = {} result_X_train =",
"y_test = train_test_split(*arrays, **sklearn_arg) X_train = pd.DataFrame(X_train, columns=data_column_names) data_obj_X_train = DataStorage.create_data_obj_by_pandas_data(X_train) X_test =",
"DataSource from data.data_storage import DataStorage class TrainTestSplitHandler(tornado.web.RequestHandler): def post(self): try: json_data = json.loads(self.request.body)",
"result_X_train result['X_test'] = result_X_test result['y_train'] = result_y_train result['y_test'] = result_y_test self.write(json.dumps(result)) else: raise",
"{} result_y_train['dataID'] = data_obj_y_train.data_id result_y_train['columnNames'] = data_obj_y_train.column_names result_y_test = {} result_y_test['dataID'] = data_obj_y_test.data_id",
"= data_obj_y_train.data_id result_y_train['columnNames'] = data_obj_y_train.column_names result_y_test = {} result_y_test['dataID'] = data_obj_y_test.data_id result_y_test['columnNames'] =",
"regqeust_arg_to_sklearn_arg from sklearn.model_selection import train_test_split from data.persistence import * from data.data_source import DataSource",
"data = data_obj.pandas_data[data_column_names] target = data_obj.pandas_data[target_column_name] data = data.values target = target.values sklearn_arg",
"tornado import json import uuid import pandas as pd from handler.mlsklearn.util import regqeust_arg_to_sklearn_arg",
"= data_obj_y_test.data_id result_y_test['columnNames'] = data_obj_y_test.column_names result['X_train'] = result_X_train result['X_test'] = result_X_test result['y_train'] =",
"pd from handler.mlsklearn.util import regqeust_arg_to_sklearn_arg from sklearn.model_selection import train_test_split from data.persistence import *",
"result = {} result_X_train = {} result_X_train['dataID'] = data_obj_X_train.data_id result_X_train['columnNames'] = data_obj_X_train.column_names result_X_test",
"data_obj_X_train.data_id result_X_train['columnNames'] = data_obj_X_train.column_names result_X_test = {} result_X_test['dataID'] = data_obj_X_test.data_id result_X_test['columnNames'] = data_obj_X_test.column_names",
"{} result_X_test['dataID'] = data_obj_X_test.data_id result_X_test['columnNames'] = data_obj_X_test.column_names result_y_train = {} result_y_train['dataID'] = data_obj_y_train.data_id",
"= {} result_y_train['dataID'] = data_obj_y_train.data_id result_y_train['columnNames'] = data_obj_y_train.column_names result_y_test = {} result_y_test['dataID'] =",
"input data_id\") data_column_names = json_data.get('dataColumnNames', None) if data_column_names == None: raise Exception(\"please input",
"pd.DataFrame(y_train, columns=[target_column_name]) data_obj_y_train = DataStorage.create_data_obj_by_pandas_data(y_train) y_test = pd.DataFrame(y_test, columns=[target_column_name]) data_obj_y_test = DataStorage.create_data_obj_by_pandas_data(y_test) result",
"data.persistence import * from data.data_source import DataSource from data.data_storage import DataStorage class TrainTestSplitHandler(tornado.web.RequestHandler):",
"uuid import pandas as pd from handler.mlsklearn.util import regqeust_arg_to_sklearn_arg from sklearn.model_selection import train_test_split",
"data_obj_X_test = DataStorage.create_data_obj_by_pandas_data(X_test) y_train = pd.DataFrame(y_train, columns=[target_column_name]) data_obj_y_train = DataStorage.create_data_obj_by_pandas_data(y_train) y_test = pd.DataFrame(y_test,",
"target] X_train, X_test, y_train, y_test = train_test_split(*arrays, **sklearn_arg) X_train = pd.DataFrame(X_train, columns=data_column_names) data_obj_X_train",
"DataStorage class TrainTestSplitHandler(tornado.web.RequestHandler): def post(self): try: json_data = json.loads(self.request.body) data_id = json_data.get('dataID', None)",
"import DataSource from data.data_storage import DataStorage class TrainTestSplitHandler(tornado.web.RequestHandler): def post(self): try: json_data =",
"sklearn_arg = json_data.get('sklearn', None) data_obj = DataStorage.get_data_obj_by_data_id(data_id) if data_obj: data_column_names = data_column_names.split(',') data",
"as pd from handler.mlsklearn.util import regqeust_arg_to_sklearn_arg from sklearn.model_selection import train_test_split from data.persistence import",
"import DataStorage class TrainTestSplitHandler(tornado.web.RequestHandler): def post(self): try: json_data = json.loads(self.request.body) data_id = json_data.get('dataID',",
"data_obj = DataStorage.get_data_obj_by_data_id(data_id) if data_obj: data_column_names = data_column_names.split(',') data = data_obj.pandas_data[data_column_names] target =",
"= data_obj_y_test.column_names result['X_train'] = result_X_train result['X_test'] = result_X_test result['y_train'] = result_y_train result['y_test'] =",
"input dataColumnNames\") target_column_name = json_data.get('targetColumnName', None) if target_column_name == None: raise Exception(\"please input",
"result_y_train = {} result_y_train['dataID'] = data_obj_y_train.data_id result_y_train['columnNames'] = data_obj_y_train.column_names result_y_test = {} result_y_test['dataID']",
"from data.data_source import DataSource from data.data_storage import DataStorage class TrainTestSplitHandler(tornado.web.RequestHandler): def post(self): try:",
"data_obj_y_train = DataStorage.create_data_obj_by_pandas_data(y_train) y_test = pd.DataFrame(y_test, columns=[target_column_name]) data_obj_y_test = DataStorage.create_data_obj_by_pandas_data(y_test) result = {}",
"DataStorage.get_data_obj_by_data_id(data_id) if data_obj: data_column_names = data_column_names.split(',') data = data_obj.pandas_data[data_column_names] target = data_obj.pandas_data[target_column_name] data",
"json_data.get('dataColumnNames', None) if data_column_names == None: raise Exception(\"please input dataColumnNames\") target_column_name = json_data.get('targetColumnName',",
"= data_column_names.split(',') data = data_obj.pandas_data[data_column_names] target = data_obj.pandas_data[target_column_name] data = data.values target =",
"Exception(\"please input targetColumnName\") sklearn_arg = json_data.get('sklearn', None) data_obj = DataStorage.get_data_obj_by_data_id(data_id) if data_obj: data_column_names",
"result_y_train['columnNames'] = data_obj_y_train.column_names result_y_test = {} result_y_test['dataID'] = data_obj_y_test.data_id result_y_test['columnNames'] = data_obj_y_test.column_names result['X_train']",
"= regqeust_arg_to_sklearn_arg(sklearn_arg, ['test_size', 'random_state']) arrays = [data, target] X_train, X_test, y_train, y_test =",
"json_data = json.loads(self.request.body) data_id = json_data.get('dataID', None) if data_id == None: raise Exception(\"please",
"targetColumnName\") sklearn_arg = json_data.get('sklearn', None) data_obj = DataStorage.get_data_obj_by_data_id(data_id) if data_obj: data_column_names = data_column_names.split(',')",
"from sklearn.model_selection import train_test_split from data.persistence import * from data.data_source import DataSource from",
"result_y_test['dataID'] = data_obj_y_test.data_id result_y_test['columnNames'] = data_obj_y_test.column_names result['X_train'] = result_X_train result['X_test'] = result_X_test result['y_train']",
"result_X_test result['y_train'] = result_y_train result['y_test'] = result_y_test self.write(json.dumps(result)) else: raise Exception(\"invalid source_id\") except",
"train_test_split from data.persistence import * from data.data_source import DataSource from data.data_storage import DataStorage",
"result_X_train['columnNames'] = data_obj_X_train.column_names result_X_test = {} result_X_test['dataID'] = data_obj_X_test.data_id result_X_test['columnNames'] = data_obj_X_test.column_names result_y_train",
"if data_column_names == None: raise Exception(\"please input dataColumnNames\") target_column_name = json_data.get('targetColumnName', None) if",
"data_obj_y_test.column_names result['X_train'] = result_X_train result['X_test'] = result_X_test result['y_train'] = result_y_train result['y_test'] = result_y_test",
"= result_y_train result['y_test'] = result_y_test self.write(json.dumps(result)) else: raise Exception(\"invalid source_id\") except Exception as",
"result['y_train'] = result_y_train result['y_test'] = result_y_test self.write(json.dumps(result)) else: raise Exception(\"invalid source_id\") except Exception",
"None: raise Exception(\"please input targetColumnName\") sklearn_arg = json_data.get('sklearn', None) data_obj = DataStorage.get_data_obj_by_data_id(data_id) if",
"= DataStorage.get_data_obj_by_data_id(data_id) if data_obj: data_column_names = data_column_names.split(',') data = data_obj.pandas_data[data_column_names] target = data_obj.pandas_data[target_column_name]",
"sklearn.model_selection import train_test_split from data.persistence import * from data.data_source import DataSource from data.data_storage",
"data_obj: data_column_names = data_column_names.split(',') data = data_obj.pandas_data[data_column_names] target = data_obj.pandas_data[target_column_name] data = data.values",
"= data_obj_X_train.column_names result_X_test = {} result_X_test['dataID'] = data_obj_X_test.data_id result_X_test['columnNames'] = data_obj_X_test.column_names result_y_train =",
"data_obj_X_test.data_id result_X_test['columnNames'] = data_obj_X_test.column_names result_y_train = {} result_y_train['dataID'] = data_obj_y_train.data_id result_y_train['columnNames'] = data_obj_y_train.column_names",
"result_y_test['columnNames'] = data_obj_y_test.column_names result['X_train'] = result_X_train result['X_test'] = result_X_test result['y_train'] = result_y_train result['y_test']",
"target_column_name == None: raise Exception(\"please input targetColumnName\") sklearn_arg = json_data.get('sklearn', None) data_obj =",
"pandas as pd from handler.mlsklearn.util import regqeust_arg_to_sklearn_arg from sklearn.model_selection import train_test_split from data.persistence",
"= {} result_X_train['dataID'] = data_obj_X_train.data_id result_X_train['columnNames'] = data_obj_X_train.column_names result_X_test = {} result_X_test['dataID'] =",
"{} result_y_test['dataID'] = data_obj_y_test.data_id result_y_test['columnNames'] = data_obj_y_test.column_names result['X_train'] = result_X_train result['X_test'] = result_X_test",
"y_train = pd.DataFrame(y_train, columns=[target_column_name]) data_obj_y_train = DataStorage.create_data_obj_by_pandas_data(y_train) y_test = pd.DataFrame(y_test, columns=[target_column_name]) data_obj_y_test =",
"= data_obj_X_test.data_id result_X_test['columnNames'] = data_obj_X_test.column_names result_y_train = {} result_y_train['dataID'] = data_obj_y_train.data_id result_y_train['columnNames'] =",
"= json_data.get('dataID', None) if data_id == None: raise Exception(\"please input data_id\") data_column_names =",
"= data_obj_X_test.column_names result_y_train = {} result_y_train['dataID'] = data_obj_y_train.data_id result_y_train['columnNames'] = data_obj_y_train.column_names result_y_test =",
"Exception(\"please input data_id\") data_column_names = json_data.get('dataColumnNames', None) if data_column_names == None: raise Exception(\"please",
"import pandas as pd from handler.mlsklearn.util import regqeust_arg_to_sklearn_arg from sklearn.model_selection import train_test_split from",
"None) data_obj = DataStorage.get_data_obj_by_data_id(data_id) if data_obj: data_column_names = data_column_names.split(',') data = data_obj.pandas_data[data_column_names] target",
"regqeust_arg_to_sklearn_arg(sklearn_arg, ['test_size', 'random_state']) arrays = [data, target] X_train, X_test, y_train, y_test = train_test_split(*arrays,",
"[data, target] X_train, X_test, y_train, y_test = train_test_split(*arrays, **sklearn_arg) X_train = pd.DataFrame(X_train, columns=data_column_names)",
"= DataStorage.create_data_obj_by_pandas_data(X_train) X_test = pd.DataFrame(X_test, columns=data_column_names) data_obj_X_test = DataStorage.create_data_obj_by_pandas_data(X_test) y_train = pd.DataFrame(y_train, columns=[target_column_name])",
"columns=data_column_names) data_obj_X_test = DataStorage.create_data_obj_by_pandas_data(X_test) y_train = pd.DataFrame(y_train, columns=[target_column_name]) data_obj_y_train = DataStorage.create_data_obj_by_pandas_data(y_train) y_test =",
"data_obj.pandas_data[data_column_names] target = data_obj.pandas_data[target_column_name] data = data.values target = target.values sklearn_arg = regqeust_arg_to_sklearn_arg(sklearn_arg,",
"import json import uuid import pandas as pd from handler.mlsklearn.util import regqeust_arg_to_sklearn_arg from",
"data_column_names == None: raise Exception(\"please input dataColumnNames\") target_column_name = json_data.get('targetColumnName', None) if target_column_name",
"result_y_test = {} result_y_test['dataID'] = data_obj_y_test.data_id result_y_test['columnNames'] = data_obj_y_test.column_names result['X_train'] = result_X_train result['X_test']",
"columns=data_column_names) data_obj_X_train = DataStorage.create_data_obj_by_pandas_data(X_train) X_test = pd.DataFrame(X_test, columns=data_column_names) data_obj_X_test = DataStorage.create_data_obj_by_pandas_data(X_test) y_train =",
"['test_size', 'random_state']) arrays = [data, target] X_train, X_test, y_train, y_test = train_test_split(*arrays, **sklearn_arg)",
"None) if target_column_name == None: raise Exception(\"please input targetColumnName\") sklearn_arg = json_data.get('sklearn', None)",
"target.values sklearn_arg = regqeust_arg_to_sklearn_arg(sklearn_arg, ['test_size', 'random_state']) arrays = [data, target] X_train, X_test, y_train,",
"= DataStorage.create_data_obj_by_pandas_data(y_test) result = {} result_X_train = {} result_X_train['dataID'] = data_obj_X_train.data_id result_X_train['columnNames'] =",
"post(self): try: json_data = json.loads(self.request.body) data_id = json_data.get('dataID', None) if data_id == None:",
"= [data, target] X_train, X_test, y_train, y_test = train_test_split(*arrays, **sklearn_arg) X_train = pd.DataFrame(X_train,",
"= data_obj_X_train.data_id result_X_train['columnNames'] = data_obj_X_train.column_names result_X_test = {} result_X_test['dataID'] = data_obj_X_test.data_id result_X_test['columnNames'] =",
"if data_id == None: raise Exception(\"please input data_id\") data_column_names = json_data.get('dataColumnNames', None) if",
"X_train = pd.DataFrame(X_train, columns=data_column_names) data_obj_X_train = DataStorage.create_data_obj_by_pandas_data(X_train) X_test = pd.DataFrame(X_test, columns=data_column_names) data_obj_X_test =",
"pd.DataFrame(X_test, columns=data_column_names) data_obj_X_test = DataStorage.create_data_obj_by_pandas_data(X_test) y_train = pd.DataFrame(y_train, columns=[target_column_name]) data_obj_y_train = DataStorage.create_data_obj_by_pandas_data(y_train) y_test",
"= json_data.get('dataColumnNames', None) if data_column_names == None: raise Exception(\"please input dataColumnNames\") target_column_name =",
"y_test = pd.DataFrame(y_test, columns=[target_column_name]) data_obj_y_test = DataStorage.create_data_obj_by_pandas_data(y_test) result = {} result_X_train = {}",
"None) if data_column_names == None: raise Exception(\"please input dataColumnNames\") target_column_name = json_data.get('targetColumnName', None)",
"data.data_storage import DataStorage class TrainTestSplitHandler(tornado.web.RequestHandler): def post(self): try: json_data = json.loads(self.request.body) data_id =",
"= data_obj.pandas_data[data_column_names] target = data_obj.pandas_data[target_column_name] data = data.values target = target.values sklearn_arg =",
"arrays = [data, target] X_train, X_test, y_train, y_test = train_test_split(*arrays, **sklearn_arg) X_train =",
"import uuid import pandas as pd from handler.mlsklearn.util import regqeust_arg_to_sklearn_arg from sklearn.model_selection import",
"= data_obj.pandas_data[target_column_name] data = data.values target = target.values sklearn_arg = regqeust_arg_to_sklearn_arg(sklearn_arg, ['test_size', 'random_state'])",
"{} result_X_train = {} result_X_train['dataID'] = data_obj_X_train.data_id result_X_train['columnNames'] = data_obj_X_train.column_names result_X_test = {}",
"= json.loads(self.request.body) data_id = json_data.get('dataID', None) if data_id == None: raise Exception(\"please input",
"== None: raise Exception(\"please input data_id\") data_column_names = json_data.get('dataColumnNames', None) if data_column_names ==",
"input targetColumnName\") sklearn_arg = json_data.get('sklearn', None) data_obj = DataStorage.get_data_obj_by_data_id(data_id) if data_obj: data_column_names =",
"data_column_names.split(',') data = data_obj.pandas_data[data_column_names] target = data_obj.pandas_data[target_column_name] data = data.values target = target.values",
"data_obj_y_test = DataStorage.create_data_obj_by_pandas_data(y_test) result = {} result_X_train = {} result_X_train['dataID'] = data_obj_X_train.data_id result_X_train['columnNames']",
"import tornado import json import uuid import pandas as pd from handler.mlsklearn.util import",
"target_column_name = json_data.get('targetColumnName', None) if target_column_name == None: raise Exception(\"please input targetColumnName\") sklearn_arg",
"Exception(\"please input dataColumnNames\") target_column_name = json_data.get('targetColumnName', None) if target_column_name == None: raise Exception(\"please",
"json.loads(self.request.body) data_id = json_data.get('dataID', None) if data_id == None: raise Exception(\"please input data_id\")",
"train_test_split(*arrays, **sklearn_arg) X_train = pd.DataFrame(X_train, columns=data_column_names) data_obj_X_train = DataStorage.create_data_obj_by_pandas_data(X_train) X_test = pd.DataFrame(X_test, columns=data_column_names)",
"DataStorage.create_data_obj_by_pandas_data(y_test) result = {} result_X_train = {} result_X_train['dataID'] = data_obj_X_train.data_id result_X_train['columnNames'] = data_obj_X_train.column_names",
"result_X_train = {} result_X_train['dataID'] = data_obj_X_train.data_id result_X_train['columnNames'] = data_obj_X_train.column_names result_X_test = {} result_X_test['dataID']",
"class TrainTestSplitHandler(tornado.web.RequestHandler): def post(self): try: json_data = json.loads(self.request.body) data_id = json_data.get('dataID', None) if",
"import regqeust_arg_to_sklearn_arg from sklearn.model_selection import train_test_split from data.persistence import * from data.data_source import",
"data.values target = target.values sklearn_arg = regqeust_arg_to_sklearn_arg(sklearn_arg, ['test_size', 'random_state']) arrays = [data, target]",
"from data.persistence import * from data.data_source import DataSource from data.data_storage import DataStorage class",
"json import uuid import pandas as pd from handler.mlsklearn.util import regqeust_arg_to_sklearn_arg from sklearn.model_selection",
"result_X_test = {} result_X_test['dataID'] = data_obj_X_test.data_id result_X_test['columnNames'] = data_obj_X_test.column_names result_y_train = {} result_y_train['dataID']",
"X_test = pd.DataFrame(X_test, columns=data_column_names) data_obj_X_test = DataStorage.create_data_obj_by_pandas_data(X_test) y_train = pd.DataFrame(y_train, columns=[target_column_name]) data_obj_y_train =",
"pd.DataFrame(y_test, columns=[target_column_name]) data_obj_y_test = DataStorage.create_data_obj_by_pandas_data(y_test) result = {} result_X_train = {} result_X_train['dataID'] =",
"result['X_test'] = result_X_test result['y_train'] = result_y_train result['y_test'] = result_y_test self.write(json.dumps(result)) else: raise Exception(\"invalid",
"data = data.values target = target.values sklearn_arg = regqeust_arg_to_sklearn_arg(sklearn_arg, ['test_size', 'random_state']) arrays =",
"if target_column_name == None: raise Exception(\"please input targetColumnName\") sklearn_arg = json_data.get('sklearn', None) data_obj",
"'random_state']) arrays = [data, target] X_train, X_test, y_train, y_test = train_test_split(*arrays, **sklearn_arg) X_train",
"result['y_test'] = result_y_test self.write(json.dumps(result)) else: raise Exception(\"invalid source_id\") except Exception as e: self.write(str(e))",
"target = target.values sklearn_arg = regqeust_arg_to_sklearn_arg(sklearn_arg, ['test_size', 'random_state']) arrays = [data, target] X_train,",
"{} result_X_train['dataID'] = data_obj_X_train.data_id result_X_train['columnNames'] = data_obj_X_train.column_names result_X_test = {} result_X_test['dataID'] = data_obj_X_test.data_id",
"result_X_test['columnNames'] = data_obj_X_test.column_names result_y_train = {} result_y_train['dataID'] = data_obj_y_train.data_id result_y_train['columnNames'] = data_obj_y_train.column_names result_y_test",
"= target.values sklearn_arg = regqeust_arg_to_sklearn_arg(sklearn_arg, ['test_size', 'random_state']) arrays = [data, target] X_train, X_test,",
"json_data.get('sklearn', None) data_obj = DataStorage.get_data_obj_by_data_id(data_id) if data_obj: data_column_names = data_column_names.split(',') data = data_obj.pandas_data[data_column_names]",
"result_X_train['dataID'] = data_obj_X_train.data_id result_X_train['columnNames'] = data_obj_X_train.column_names result_X_test = {} result_X_test['dataID'] = data_obj_X_test.data_id result_X_test['columnNames']",
"result_X_test['dataID'] = data_obj_X_test.data_id result_X_test['columnNames'] = data_obj_X_test.column_names result_y_train = {} result_y_train['dataID'] = data_obj_y_train.data_id result_y_train['columnNames']",
"data_obj_y_train.data_id result_y_train['columnNames'] = data_obj_y_train.column_names result_y_test = {} result_y_test['dataID'] = data_obj_y_test.data_id result_y_test['columnNames'] = data_obj_y_test.column_names",
"== None: raise Exception(\"please input targetColumnName\") sklearn_arg = json_data.get('sklearn', None) data_obj = DataStorage.get_data_obj_by_data_id(data_id)",
"X_train, X_test, y_train, y_test = train_test_split(*arrays, **sklearn_arg) X_train = pd.DataFrame(X_train, columns=data_column_names) data_obj_X_train =",
"raise Exception(\"please input dataColumnNames\") target_column_name = json_data.get('targetColumnName', None) if target_column_name == None: raise",
"**sklearn_arg) X_train = pd.DataFrame(X_train, columns=data_column_names) data_obj_X_train = DataStorage.create_data_obj_by_pandas_data(X_train) X_test = pd.DataFrame(X_test, columns=data_column_names) data_obj_X_test",
"target = data_obj.pandas_data[target_column_name] data = data.values target = target.values sklearn_arg = regqeust_arg_to_sklearn_arg(sklearn_arg, ['test_size',",
"= data.values target = target.values sklearn_arg = regqeust_arg_to_sklearn_arg(sklearn_arg, ['test_size', 'random_state']) arrays = [data,",
"= {} result_X_train = {} result_X_train['dataID'] = data_obj_X_train.data_id result_X_train['columnNames'] = data_obj_X_train.column_names result_X_test =",
"== None: raise Exception(\"please input dataColumnNames\") target_column_name = json_data.get('targetColumnName', None) if target_column_name ==",
"= json_data.get('sklearn', None) data_obj = DataStorage.get_data_obj_by_data_id(data_id) if data_obj: data_column_names = data_column_names.split(',') data =",
"columns=[target_column_name]) data_obj_y_train = DataStorage.create_data_obj_by_pandas_data(y_train) y_test = pd.DataFrame(y_test, columns=[target_column_name]) data_obj_y_test = DataStorage.create_data_obj_by_pandas_data(y_test) result =",
"= result_X_train result['X_test'] = result_X_test result['y_train'] = result_y_train result['y_test'] = result_y_test self.write(json.dumps(result)) else:",
"X_test, y_train, y_test = train_test_split(*arrays, **sklearn_arg) X_train = pd.DataFrame(X_train, columns=data_column_names) data_obj_X_train = DataStorage.create_data_obj_by_pandas_data(X_train)",
"= pd.DataFrame(y_test, columns=[target_column_name]) data_obj_y_test = DataStorage.create_data_obj_by_pandas_data(y_test) result = {} result_X_train = {} result_X_train['dataID']",
"y_train, y_test = train_test_split(*arrays, **sklearn_arg) X_train = pd.DataFrame(X_train, columns=data_column_names) data_obj_X_train = DataStorage.create_data_obj_by_pandas_data(X_train) X_test",
"None: raise Exception(\"please input dataColumnNames\") target_column_name = json_data.get('targetColumnName', None) if target_column_name == None:",
"TrainTestSplitHandler(tornado.web.RequestHandler): def post(self): try: json_data = json.loads(self.request.body) data_id = json_data.get('dataID', None) if data_id",
"if data_obj: data_column_names = data_column_names.split(',') data = data_obj.pandas_data[data_column_names] target = data_obj.pandas_data[target_column_name] data =",
"import * from data.data_source import DataSource from data.data_storage import DataStorage class TrainTestSplitHandler(tornado.web.RequestHandler): def",
"try: json_data = json.loads(self.request.body) data_id = json_data.get('dataID', None) if data_id == None: raise",
"None: raise Exception(\"please input data_id\") data_column_names = json_data.get('dataColumnNames', None) if data_column_names == None:",
"data_id\") data_column_names = json_data.get('dataColumnNames', None) if data_column_names == None: raise Exception(\"please input dataColumnNames\")",
"= data_obj_y_train.column_names result_y_test = {} result_y_test['dataID'] = data_obj_y_test.data_id result_y_test['columnNames'] = data_obj_y_test.column_names result['X_train'] =",
"data_id = json_data.get('dataID', None) if data_id == None: raise Exception(\"please input data_id\") data_column_names",
"dataColumnNames\") target_column_name = json_data.get('targetColumnName', None) if target_column_name == None: raise Exception(\"please input targetColumnName\")",
"from data.data_storage import DataStorage class TrainTestSplitHandler(tornado.web.RequestHandler): def post(self): try: json_data = json.loads(self.request.body) data_id",
"= result_X_test result['y_train'] = result_y_train result['y_test'] = result_y_test self.write(json.dumps(result)) else: raise Exception(\"invalid source_id\")",
"data_obj_X_train.column_names result_X_test = {} result_X_test['dataID'] = data_obj_X_test.data_id result_X_test['columnNames'] = data_obj_X_test.column_names result_y_train = {}",
"result_y_train result['y_test'] = result_y_test self.write(json.dumps(result)) else: raise Exception(\"invalid source_id\") except Exception as e:",
"result['X_train'] = result_X_train result['X_test'] = result_X_test result['y_train'] = result_y_train result['y_test'] = result_y_test self.write(json.dumps(result))",
"json_data.get('targetColumnName', None) if target_column_name == None: raise Exception(\"please input targetColumnName\") sklearn_arg = json_data.get('sklearn',",
"= pd.DataFrame(y_train, columns=[target_column_name]) data_obj_y_train = DataStorage.create_data_obj_by_pandas_data(y_train) y_test = pd.DataFrame(y_test, columns=[target_column_name]) data_obj_y_test = DataStorage.create_data_obj_by_pandas_data(y_test)",
"= DataStorage.create_data_obj_by_pandas_data(X_test) y_train = pd.DataFrame(y_train, columns=[target_column_name]) data_obj_y_train = DataStorage.create_data_obj_by_pandas_data(y_train) y_test = pd.DataFrame(y_test, columns=[target_column_name])",
"data_obj_X_train = DataStorage.create_data_obj_by_pandas_data(X_train) X_test = pd.DataFrame(X_test, columns=data_column_names) data_obj_X_test = DataStorage.create_data_obj_by_pandas_data(X_test) y_train = pd.DataFrame(y_train,",
"from handler.mlsklearn.util import regqeust_arg_to_sklearn_arg from sklearn.model_selection import train_test_split from data.persistence import * from",
"columns=[target_column_name]) data_obj_y_test = DataStorage.create_data_obj_by_pandas_data(y_test) result = {} result_X_train = {} result_X_train['dataID'] = data_obj_X_train.data_id",
"= pd.DataFrame(X_train, columns=data_column_names) data_obj_X_train = DataStorage.create_data_obj_by_pandas_data(X_train) X_test = pd.DataFrame(X_test, columns=data_column_names) data_obj_X_test = DataStorage.create_data_obj_by_pandas_data(X_test)",
"= {} result_y_test['dataID'] = data_obj_y_test.data_id result_y_test['columnNames'] = data_obj_y_test.column_names result['X_train'] = result_X_train result['X_test'] =",
"= pd.DataFrame(X_test, columns=data_column_names) data_obj_X_test = DataStorage.create_data_obj_by_pandas_data(X_test) y_train = pd.DataFrame(y_train, columns=[target_column_name]) data_obj_y_train = DataStorage.create_data_obj_by_pandas_data(y_train)",
"= {} result_X_test['dataID'] = data_obj_X_test.data_id result_X_test['columnNames'] = data_obj_X_test.column_names result_y_train = {} result_y_train['dataID'] =",
"result_y_train['dataID'] = data_obj_y_train.data_id result_y_train['columnNames'] = data_obj_y_train.column_names result_y_test = {} result_y_test['dataID'] = data_obj_y_test.data_id result_y_test['columnNames']",
"DataStorage.create_data_obj_by_pandas_data(X_test) y_train = pd.DataFrame(y_train, columns=[target_column_name]) data_obj_y_train = DataStorage.create_data_obj_by_pandas_data(y_train) y_test = pd.DataFrame(y_test, columns=[target_column_name]) data_obj_y_test",
"import train_test_split from data.persistence import * from data.data_source import DataSource from data.data_storage import",
"DataStorage.create_data_obj_by_pandas_data(X_train) X_test = pd.DataFrame(X_test, columns=data_column_names) data_obj_X_test = DataStorage.create_data_obj_by_pandas_data(X_test) y_train = pd.DataFrame(y_train, columns=[target_column_name]) data_obj_y_train",
"data_obj_y_train.column_names result_y_test = {} result_y_test['dataID'] = data_obj_y_test.data_id result_y_test['columnNames'] = data_obj_y_test.column_names result['X_train'] = result_X_train",
"json_data.get('dataID', None) if data_id == None: raise Exception(\"please input data_id\") data_column_names = json_data.get('dataColumnNames',",
"data_column_names = json_data.get('dataColumnNames', None) if data_column_names == None: raise Exception(\"please input dataColumnNames\") target_column_name",
"data_obj_X_test.column_names result_y_train = {} result_y_train['dataID'] = data_obj_y_train.data_id result_y_train['columnNames'] = data_obj_y_train.column_names result_y_test = {}",
"= train_test_split(*arrays, **sklearn_arg) X_train = pd.DataFrame(X_train, columns=data_column_names) data_obj_X_train = DataStorage.create_data_obj_by_pandas_data(X_train) X_test = pd.DataFrame(X_test,",
"def post(self): try: json_data = json.loads(self.request.body) data_id = json_data.get('dataID', None) if data_id ==",
"data.data_source import DataSource from data.data_storage import DataStorage class TrainTestSplitHandler(tornado.web.RequestHandler): def post(self): try: json_data",
"data_column_names = data_column_names.split(',') data = data_obj.pandas_data[data_column_names] target = data_obj.pandas_data[target_column_name] data = data.values target",
"raise Exception(\"please input targetColumnName\") sklearn_arg = json_data.get('sklearn', None) data_obj = DataStorage.get_data_obj_by_data_id(data_id) if data_obj:",
"sklearn_arg = regqeust_arg_to_sklearn_arg(sklearn_arg, ['test_size', 'random_state']) arrays = [data, target] X_train, X_test, y_train, y_test",
"raise Exception(\"please input data_id\") data_column_names = json_data.get('dataColumnNames', None) if data_column_names == None: raise",
"None) if data_id == None: raise Exception(\"please input data_id\") data_column_names = json_data.get('dataColumnNames', None)",
"= DataStorage.create_data_obj_by_pandas_data(y_train) y_test = pd.DataFrame(y_test, columns=[target_column_name]) data_obj_y_test = DataStorage.create_data_obj_by_pandas_data(y_test) result = {} result_X_train",
"= json_data.get('targetColumnName', None) if target_column_name == None: raise Exception(\"please input targetColumnName\") sklearn_arg =",
"data_obj.pandas_data[target_column_name] data = data.values target = target.values sklearn_arg = regqeust_arg_to_sklearn_arg(sklearn_arg, ['test_size', 'random_state']) arrays"
] |
[
"< 0: # No more pages return None prev_slug = page_slugs[prev_index] return self.pages[prev_slug]",
"+ 1 if next_index > len(page_slugs) - 1: # No more pages return",
"self.initial = self.initial or initial page_initial = {} kwargs = self.kwargs.copy() if 'initial'",
"= self.kwargs.copy() if 'initial' in kwargs: kwargs.pop('initial') for slug, PageClass in self.pageclasses.items(): if",
"pages return None prev_slug = page_slugs[prev_index] return self.pages[prev_slug] def initialize(self, initial=None, **kwargs): pages",
"self def bind(self, data=None, files=None, initial=None): pages = [] for slug, Page in",
"/ float(num_pages) return pages_done == num_pages return None @property def cleaned_data(self): cleaned_data =",
"for field in form.file_fields(): yield field def first_page(self): if not self.is_initialized: self.initialize() first_slug",
"= page_slugs[next_index] return self.pages[next_slug] def prev_page(self, slug): \"\"\" Returns prev page if any,",
"self.pages.values()) num_pages = len(self.pages) self.percentage_done = 100 * pages_done / float(num_pages) return pages_done",
"if any, None otherwise. Returns ValueError if slug does not exist in the",
"\"\"\" Returns prev page if any, None otherwise. Returns ValueError if slug does",
"self.bind(data=data, files=files, initial=initial) def file_fields(self): if self.is_multipart(): for form in self.pages.values(): for field",
"0: # No more pages return None prev_slug = page_slugs[prev_index] return self.pages[prev_slug] def",
"tuple(self.pages.keys()) current_index = page_slugs.index(slug) # ValueError prev_index = current_index - 1 if prev_index",
"self.files = files self.initial = initial or self.initial return self @property def is_initialized(self):",
"self.initial return self @property def is_initialized(self): return self.pages is not None @property def",
"\"\"\" if not self.is_initialized: self.initialize() page_slugs = tuple(self.pages.keys()) current_index = page_slugs.index(slug) # ValueError",
"in self.pages.values()) num_pages = len(self.pages) self.percentage_done = 100 * pages_done / float(num_pages) return",
"return self @property def is_initialized(self): return self.pages is not None @property def is_bound(self):",
"= page.cleaned_data return cleaned_data def preview(self): lines = [] for page in self.pages.values():",
"cleaned_data = {} if self.is_bound: for slug, page in self.pages.items(): page.is_valid() cleaned_data[slug] =",
"initial=None, **kwargs): self.initial = initial self.kwargs = kwargs self.pageclasses = OrderedDict([(page.slug, page) for",
"None next_slug = page_slugs[next_index] return self.pages[next_slug] def prev_page(self, slug): \"\"\" Returns prev page",
"**kwargs) pages.append((slug, page)) self.pages = OrderedDict(pages) return self def bind(self, data=None, files=None, initial=None):",
"if self.is_multipart(): for form in self.pages.values(): for field in form.file_fields(): yield field def",
"page = Page().bind(data=data, files=files, initial=None) pages.append((slug, page)) self.pages = OrderedDict(pages) self.data = data",
"Returns next page if any, None otherwise. Returns ValueError if slug does not",
"page_initial = {} kwargs = self.kwargs.copy() if 'initial' in kwargs: kwargs.pop('initial') for slug,",
"__future__ import unicode_literals from collections import OrderedDict import logging import copy LOGGER =",
"= kwargs self.pageclasses = OrderedDict([(page.slug, page) for page in self.pages]) self.pages = None",
"num_pages = len(self.pages) self.percentage_done = 100 * pages_done / float(num_pages) return pages_done ==",
"self.files) return False def is_multipart(self): return any(page.is_multipart() for page in self.pages.values()) def is_valid(self):",
"if self.is_initialized: pages_done = sum(bool(page.is_valid()) for page in self.pages.values()) num_pages = len(self.pages) self.percentage_done",
"slug): \"\"\" Returns next page if any, None otherwise. Returns ValueError if slug",
"return any(page.is_multipart() for page in self.pages.values()) def is_valid(self): if self.is_initialized: pages_done = sum(bool(page.is_valid())",
"= current_index + 1 if next_index > len(page_slugs) - 1: # No more",
"slug, page in self.pages.items(): page.is_valid() initial[slug] = page.get_initial_data() return initial def get_data(self): return",
"= page_slugs[prev_index] return self.pages[prev_slug] def initialize(self, initial=None, **kwargs): pages = [] self.initial =",
"= data self.files = files self.initialize(self.initial) self.bind(data=data, files=files, initial=initial) def file_fields(self): if self.is_multipart():",
"= OrderedDict(pages) return self def bind(self, data=None, files=None, initial=None): pages = [] for",
"next page if any, None otherwise. Returns ValueError if slug does not exist",
"initial = {} if self.is_initialized: for slug, page in self.pages.items(): page.is_valid() initial[slug] =",
"if prev_index < 0: # No more pages return None prev_slug = page_slugs[prev_index]",
"is not None @property def is_bound(self): if self.is_initialized: return bool(self.data or self.files) return",
"= OrderedDict([(page.slug, page) for page in self.pages]) self.pages = None self.data = data",
"self.is_bound: for slug, page in self.pages.items(): page.is_valid() cleaned_data[slug] = page.cleaned_data return cleaned_data def",
"@property def is_initialized(self): return self.pages is not None @property def is_bound(self): if self.is_initialized:",
"return self.pages[next_slug] def prev_page(self, slug): \"\"\" Returns prev page if any, None otherwise.",
"next_index = current_index + 1 if next_index > len(page_slugs) - 1: # No",
"import OrderedDict import logging import copy LOGGER = logging.getLogger(__name__) class MultiPageForm(object): help_text =",
"any(page.is_multipart() for page in self.pages.values()) def is_valid(self): if self.is_initialized: pages_done = sum(bool(page.is_valid()) for",
"self.files = files self.initialize(self.initial) self.bind(data=data, files=files, initial=initial) def file_fields(self): if self.is_multipart(): for form",
"if 'initial' in kwargs: kwargs.pop('initial') for slug, PageClass in self.pageclasses.items(): if self.initial: page_initial",
"{} if self.is_bound: for slug, page in self.pages.items(): page.is_valid() cleaned_data[slug] = page.cleaned_data return",
"last_page(self): if not self.is_initialized: self.initialize() last_slug = tuple(self.pages.keys())[-1] return self.pages[last_slug] def next_page(self, slug):",
"return None @property def cleaned_data(self): cleaned_data = {} if self.is_bound: for slug, page",
"page in self.pages.items(): page.is_valid() initial[slug] = page.get_initial_data() return initial def get_data(self): return self.data",
"in the pages \"\"\" if not self.is_initialized: self.initialize() page_slugs = tuple(self.pages.keys()) current_index =",
"self.kwargs.copy() if 'initial' in kwargs: kwargs.pop('initial') for slug, PageClass in self.pageclasses.items(): if self.initial:",
"more pages return None prev_slug = page_slugs[prev_index] return self.pages[prev_slug] def initialize(self, initial=None, **kwargs):",
"page if any, None otherwise. Returns ValueError if slug does not exist in",
"def is_multipart(self): return any(page.is_multipart() for page in self.pages.values()) def is_valid(self): if self.is_initialized: pages_done",
"self.kwargs = kwargs self.pageclasses = OrderedDict([(page.slug, page) for page in self.pages]) self.pages =",
"= PageClass().initialize(initial=page_initial, **kwargs) pages.append((slug, page)) self.pages = OrderedDict(pages) return self def bind(self, data=None,",
"kwargs.pop('initial') for slug, PageClass in self.pageclasses.items(): if self.initial: page_initial = self.initial.get(slug, {}) page",
"the pages \"\"\" if not self.is_initialized: self.initialize() page_slugs = tuple(self.pages.keys()) current_index = page_slugs.index(slug)",
"page_slugs.index(slug) # ValueError next_index = current_index + 1 if next_index > len(page_slugs) -",
"is_initialized(self): return self.pages is not None @property def is_bound(self): if self.is_initialized: return bool(self.data",
"self.initial.get(slug, {}) page = PageClass().initialize(initial=page_initial, **kwargs) pages.append((slug, page)) self.pages = OrderedDict(pages) return self",
"= [] for slug, Page in self.pageclasses.items(): page = Page().bind(data=data, files=files, initial=None) pages.append((slug,",
"if next_index > len(page_slugs) - 1: # No more pages return None next_slug",
"not exist in the pages \"\"\" if not self.is_initialized: self.initialize() page_slugs = tuple(self.pages.keys())",
"def cleaned_data(self): cleaned_data = {} if self.is_bound: for slug, page in self.pages.items(): page.is_valid()",
"ValueError if slug does not exist in the pages \"\"\" if not self.is_initialized:",
"in self.pages.values(): for field in form.file_fields(): yield field def first_page(self): if not self.is_initialized:",
"initial self.kwargs = kwargs self.pageclasses = OrderedDict([(page.slug, page) for page in self.pages]) self.pages",
"page_initial = self.initial.get(slug, {}) page = PageClass().initialize(initial=page_initial, **kwargs) pages.append((slug, page)) self.pages = OrderedDict(pages)",
"for page in self.pages.values()) num_pages = len(self.pages) self.percentage_done = 100 * pages_done /",
"yield field def first_page(self): if not self.is_initialized: self.initialize() first_slug = tuple(self.pages.keys())[0] return self.pages[first_slug]",
"current_index + 1 if next_index > len(page_slugs) - 1: # No more pages",
"self @property def is_initialized(self): return self.pages is not None @property def is_bound(self): if",
"self.initial: page_initial = self.initial.get(slug, {}) page = PageClass().initialize(initial=page_initial, **kwargs) pages.append((slug, page)) self.pages =",
"len(self.pages) self.percentage_done = 100 * pages_done / float(num_pages) return pages_done == num_pages return",
"@property def cleaned_data(self): cleaned_data = {} if self.is_bound: for slug, page in self.pages.items():",
"def is_initialized(self): return self.pages is not None @property def is_bound(self): if self.is_initialized: return",
"self.pages = OrderedDict(pages) return self def bind(self, data=None, files=None, initial=None): pages = []",
"is_valid(self): if self.is_initialized: pages_done = sum(bool(page.is_valid()) for page in self.pages.values()) num_pages = len(self.pages)",
"self.is_multipart(): for form in self.pages.values(): for field in form.file_fields(): yield field def first_page(self):",
"'initial' in kwargs: kwargs.pop('initial') for slug, PageClass in self.pageclasses.items(): if self.initial: page_initial =",
"0.0 def __init__(self, data=None, files=None, initial=None, **kwargs): self.initial = initial self.kwargs = kwargs",
"= page_slugs.index(slug) # ValueError prev_index = current_index - 1 if prev_index < 0:",
"prev_slug = page_slugs[prev_index] return self.pages[prev_slug] def initialize(self, initial=None, **kwargs): pages = [] self.initial",
"data=None, files=None, initial=None): pages = [] for slug, Page in self.pageclasses.items(): page =",
"page.cleaned_data return cleaned_data def preview(self): lines = [] for page in self.pages.values(): lines.append(page.preview())",
"if self.is_bound: for slug, page in self.pages.items(): page.is_valid() cleaned_data[slug] = page.cleaned_data return cleaned_data",
"files=None, initial=None, **kwargs): self.initial = initial self.kwargs = kwargs self.pageclasses = OrderedDict([(page.slug, page)",
"= {} if self.is_bound: for slug, page in self.pages.items(): page.is_valid() cleaned_data[slug] = page.cleaned_data",
"for form in self.pages.values(): for field in form.file_fields(): yield field def first_page(self): if",
"# No more pages return None prev_slug = page_slugs[prev_index] return self.pages[prev_slug] def initialize(self,",
"= [] for page in self.pages.values(): lines.append(page.preview()) return lines def get_initial_data(self): initial =",
"initial=None) pages.append((slug, page)) self.pages = OrderedDict(pages) self.data = data self.files = files self.initial",
"lines = [] for page in self.pages.values(): lines.append(page.preview()) return lines def get_initial_data(self): initial",
"kwargs: kwargs.pop('initial') for slug, PageClass in self.pageclasses.items(): if self.initial: page_initial = self.initial.get(slug, {})",
"> len(page_slugs) - 1: # No more pages return None next_slug = page_slugs[next_index]",
"files=files, initial=initial) def file_fields(self): if self.is_multipart(): for form in self.pages.values(): for field in",
"prev_index < 0: # No more pages return None prev_slug = page_slugs[prev_index] return",
"= len(self.pages) self.percentage_done = 100 * pages_done / float(num_pages) return pages_done == num_pages",
"otherwise. Returns ValueError if slug does not exist in the pages \"\"\" if",
"def preview(self): lines = [] for page in self.pages.values(): lines.append(page.preview()) return lines def",
"= 100 * pages_done / float(num_pages) return pages_done == num_pages return None @property",
"in form.file_fields(): yield field def first_page(self): if not self.is_initialized: self.initialize() first_slug = tuple(self.pages.keys())[0]",
"slug, PageClass in self.pageclasses.items(): if self.initial: page_initial = self.initial.get(slug, {}) page = PageClass().initialize(initial=page_initial,",
"return lines def get_initial_data(self): initial = {} if self.is_initialized: for slug, page in",
"if slug does not exist in the pages \"\"\" if not self.is_initialized: self.initialize()",
"self.pages[first_slug] def last_page(self): if not self.is_initialized: self.initialize() last_slug = tuple(self.pages.keys())[-1] return self.pages[last_slug] def",
"pages_done / float(num_pages) return pages_done == num_pages return None @property def cleaned_data(self): cleaned_data",
"self.is_initialized: self.initialize() page_slugs = tuple(self.pages.keys()) current_index = page_slugs.index(slug) # ValueError next_index = current_index",
"initial page_initial = {} kwargs = self.kwargs.copy() if 'initial' in kwargs: kwargs.pop('initial') for",
"if not self.is_initialized: self.initialize() page_slugs = tuple(self.pages.keys()) current_index = page_slugs.index(slug) # ValueError next_index",
"prev_page(self, slug): \"\"\" Returns prev page if any, None otherwise. Returns ValueError if",
"not self.is_initialized: self.initialize() first_slug = tuple(self.pages.keys())[0] return self.pages[first_slug] def last_page(self): if not self.is_initialized:",
"float(num_pages) return pages_done == num_pages return None @property def cleaned_data(self): cleaned_data = {}",
"- 1 if prev_index < 0: # No more pages return None prev_slug",
"from collections import OrderedDict import logging import copy LOGGER = logging.getLogger(__name__) class MultiPageForm(object):",
"self.initialize() page_slugs = tuple(self.pages.keys()) current_index = page_slugs.index(slug) # ValueError next_index = current_index +",
"= tuple(self.pages.keys())[-1] return self.pages[last_slug] def next_page(self, slug): \"\"\" Returns next page if any,",
"return self.pages[last_slug] def next_page(self, slug): \"\"\" Returns next page if any, None otherwise.",
"self.pages.values()) def is_valid(self): if self.is_initialized: pages_done = sum(bool(page.is_valid()) for page in self.pages.values()) num_pages",
"class MultiPageForm(object): help_text = '' percentage_done = 0.0 def __init__(self, data=None, files=None, initial=None,",
"for slug, page in self.pages.items(): page.is_valid() initial[slug] = page.get_initial_data() return initial def get_data(self):",
"OrderedDict([(page.slug, page) for page in self.pages]) self.pages = None self.data = data self.files",
"- 1: # No more pages return None next_slug = page_slugs[next_index] return self.pages[next_slug]",
"data=None, files=None, initial=None, **kwargs): self.initial = initial self.kwargs = kwargs self.pageclasses = OrderedDict([(page.slug,",
"files self.initialize(self.initial) self.bind(data=data, files=files, initial=initial) def file_fields(self): if self.is_multipart(): for form in self.pages.values():",
"first_slug = tuple(self.pages.keys())[0] return self.pages[first_slug] def last_page(self): if not self.is_initialized: self.initialize() last_slug =",
"return self def bind(self, data=None, files=None, initial=None): pages = [] for slug, Page",
"None @property def is_bound(self): if self.is_initialized: return bool(self.data or self.files) return False def",
"self.pageclasses.items(): page = Page().bind(data=data, files=files, initial=None) pages.append((slug, page)) self.pages = OrderedDict(pages) self.data =",
"= files self.initialize(self.initial) self.bind(data=data, files=files, initial=initial) def file_fields(self): if self.is_multipart(): for form in",
"ValueError prev_index = current_index - 1 if prev_index < 0: # No more",
"= None self.data = data self.files = files self.initialize(self.initial) self.bind(data=data, files=files, initial=initial) def",
"in self.pageclasses.items(): page = Page().bind(data=data, files=files, initial=None) pages.append((slug, page)) self.pages = OrderedDict(pages) self.data",
"self.data = data self.files = files self.initial = initial or self.initial return self",
"= page_slugs.index(slug) # ValueError next_index = current_index + 1 if next_index > len(page_slugs)",
"for page in self.pages.values()) def is_valid(self): if self.is_initialized: pages_done = sum(bool(page.is_valid()) for page",
"def prev_page(self, slug): \"\"\" Returns prev page if any, None otherwise. Returns ValueError",
"current_index = page_slugs.index(slug) # ValueError prev_index = current_index - 1 if prev_index <",
"def is_bound(self): if self.is_initialized: return bool(self.data or self.files) return False def is_multipart(self): return",
"self.initial = initial self.kwargs = kwargs self.pageclasses = OrderedDict([(page.slug, page) for page in",
"page_slugs = tuple(self.pages.keys()) current_index = page_slugs.index(slug) # ValueError next_index = current_index + 1",
"PageClass in self.pageclasses.items(): if self.initial: page_initial = self.initial.get(slug, {}) page = PageClass().initialize(initial=page_initial, **kwargs)",
"OrderedDict(pages) return self def bind(self, data=None, files=None, initial=None): pages = [] for slug,",
"pages = [] self.initial = self.initial or initial page_initial = {} kwargs =",
"unicode_literals from collections import OrderedDict import logging import copy LOGGER = logging.getLogger(__name__) class",
"OrderedDict(pages) self.data = data self.files = files self.initial = initial or self.initial return",
"return bool(self.data or self.files) return False def is_multipart(self): return any(page.is_multipart() for page in",
"does not exist in the pages \"\"\" if not self.is_initialized: self.initialize() page_slugs =",
"return self.pages[first_slug] def last_page(self): if not self.is_initialized: self.initialize() last_slug = tuple(self.pages.keys())[-1] return self.pages[last_slug]",
"kwargs = self.kwargs.copy() if 'initial' in kwargs: kwargs.pop('initial') for slug, PageClass in self.pageclasses.items():",
"for slug, Page in self.pageclasses.items(): page = Page().bind(data=data, files=files, initial=None) pages.append((slug, page)) self.pages",
"self.initial or initial page_initial = {} kwargs = self.kwargs.copy() if 'initial' in kwargs:",
"self.initialize() last_slug = tuple(self.pages.keys())[-1] return self.pages[last_slug] def next_page(self, slug): \"\"\" Returns next page",
"data self.files = files self.initial = initial or self.initial return self @property def",
"Returns ValueError if slug does not exist in the pages \"\"\" if not",
"None otherwise. Returns ValueError if slug does not exist in the pages \"\"\"",
"self.initialize() page_slugs = tuple(self.pages.keys()) current_index = page_slugs.index(slug) # ValueError prev_index = current_index -",
"in self.pages]) self.pages = None self.data = data self.files = files self.initialize(self.initial) self.bind(data=data,",
"MultiPageForm(object): help_text = '' percentage_done = 0.0 def __init__(self, data=None, files=None, initial=None, **kwargs):",
"pages_done == num_pages return None @property def cleaned_data(self): cleaned_data = {} if self.is_bound:",
"tuple(self.pages.keys())[0] return self.pages[first_slug] def last_page(self): if not self.is_initialized: self.initialize() last_slug = tuple(self.pages.keys())[-1] return",
"if not self.is_initialized: self.initialize() last_slug = tuple(self.pages.keys())[-1] return self.pages[last_slug] def next_page(self, slug): \"\"\"",
"def is_valid(self): if self.is_initialized: pages_done = sum(bool(page.is_valid()) for page in self.pages.values()) num_pages =",
"self.pages is not None @property def is_bound(self): if self.is_initialized: return bool(self.data or self.files)",
"self.pages.items(): page.is_valid() cleaned_data[slug] = page.cleaned_data return cleaned_data def preview(self): lines = [] for",
"slug does not exist in the pages \"\"\" if not self.is_initialized: self.initialize() page_slugs",
"files=None, initial=None): pages = [] for slug, Page in self.pageclasses.items(): page = Page().bind(data=data,",
"{} kwargs = self.kwargs.copy() if 'initial' in kwargs: kwargs.pop('initial') for slug, PageClass in",
"cleaned_data(self): cleaned_data = {} if self.is_bound: for slug, page in self.pages.items(): page.is_valid() cleaned_data[slug]",
"for page in self.pages]) self.pages = None self.data = data self.files = files",
"def next_page(self, slug): \"\"\" Returns next page if any, None otherwise. Returns ValueError",
"1 if next_index > len(page_slugs) - 1: # No more pages return None",
"page)) self.pages = OrderedDict(pages) return self def bind(self, data=None, files=None, initial=None): pages =",
"def initialize(self, initial=None, **kwargs): pages = [] self.initial = self.initial or initial page_initial",
"in kwargs: kwargs.pop('initial') for slug, PageClass in self.pageclasses.items(): if self.initial: page_initial = self.initial.get(slug,",
"page in self.pages.values()) def is_valid(self): if self.is_initialized: pages_done = sum(bool(page.is_valid()) for page in",
"pages = [] for slug, Page in self.pageclasses.items(): page = Page().bind(data=data, files=files, initial=None)",
"if self.is_initialized: for slug, page in self.pages.items(): page.is_valid() initial[slug] = page.get_initial_data() return initial",
"not self.is_initialized: self.initialize() page_slugs = tuple(self.pages.keys()) current_index = page_slugs.index(slug) # ValueError prev_index =",
"self.is_initialized: self.initialize() last_slug = tuple(self.pages.keys())[-1] return self.pages[last_slug] def next_page(self, slug): \"\"\" Returns next",
"return cleaned_data def preview(self): lines = [] for page in self.pages.values(): lines.append(page.preview()) return",
"self.percentage_done = 100 * pages_done / float(num_pages) return pages_done == num_pages return None",
"is_bound(self): if self.is_initialized: return bool(self.data or self.files) return False def is_multipart(self): return any(page.is_multipart()",
"num_pages return None @property def cleaned_data(self): cleaned_data = {} if self.is_bound: for slug,",
"initialize(self, initial=None, **kwargs): pages = [] self.initial = self.initial or initial page_initial =",
"page) for page in self.pages]) self.pages = None self.data = data self.files =",
"import copy LOGGER = logging.getLogger(__name__) class MultiPageForm(object): help_text = '' percentage_done = 0.0",
"page in self.pages]) self.pages = None self.data = data self.files = files self.initialize(self.initial)",
"self.initialize() first_slug = tuple(self.pages.keys())[0] return self.pages[first_slug] def last_page(self): if not self.is_initialized: self.initialize() last_slug",
"files self.initial = initial or self.initial return self @property def is_initialized(self): return self.pages",
"page_slugs = tuple(self.pages.keys()) current_index = page_slugs.index(slug) # ValueError prev_index = current_index - 1",
"page_slugs[next_index] return self.pages[next_slug] def prev_page(self, slug): \"\"\" Returns prev page if any, None",
"collections import OrderedDict import logging import copy LOGGER = logging.getLogger(__name__) class MultiPageForm(object): help_text",
"preview(self): lines = [] for page in self.pages.values(): lines.append(page.preview()) return lines def get_initial_data(self):",
"logging import copy LOGGER = logging.getLogger(__name__) class MultiPageForm(object): help_text = '' percentage_done =",
"from __future__ import unicode_literals from collections import OrderedDict import logging import copy LOGGER",
"initial or self.initial return self @property def is_initialized(self): return self.pages is not None",
"not None @property def is_bound(self): if self.is_initialized: return bool(self.data or self.files) return False",
"1: # No more pages return None next_slug = page_slugs[next_index] return self.pages[next_slug] def",
"# ValueError next_index = current_index + 1 if next_index > len(page_slugs) - 1:",
"= [] self.initial = self.initial or initial page_initial = {} kwargs = self.kwargs.copy()",
"def file_fields(self): if self.is_multipart(): for form in self.pages.values(): for field in form.file_fields(): yield",
"lines.append(page.preview()) return lines def get_initial_data(self): initial = {} if self.is_initialized: for slug, page",
"\"\"\" Returns next page if any, None otherwise. Returns ValueError if slug does",
"self.is_initialized: self.initialize() first_slug = tuple(self.pages.keys())[0] return self.pages[first_slug] def last_page(self): if not self.is_initialized: self.initialize()",
"**kwargs): pages = [] self.initial = self.initial or initial page_initial = {} kwargs",
"return self.pages is not None @property def is_bound(self): if self.is_initialized: return bool(self.data or",
"in self.pages.items(): page.is_valid() cleaned_data[slug] = page.cleaned_data return cleaned_data def preview(self): lines = []",
"self.is_initialized: pages_done = sum(bool(page.is_valid()) for page in self.pages.values()) num_pages = len(self.pages) self.percentage_done =",
"None self.data = data self.files = files self.initialize(self.initial) self.bind(data=data, files=files, initial=initial) def file_fields(self):",
"{}) page = PageClass().initialize(initial=page_initial, **kwargs) pages.append((slug, page)) self.pages = OrderedDict(pages) return self def",
"return None prev_slug = page_slugs[prev_index] return self.pages[prev_slug] def initialize(self, initial=None, **kwargs): pages =",
"pages \"\"\" if not self.is_initialized: self.initialize() page_slugs = tuple(self.pages.keys()) current_index = page_slugs.index(slug) #",
"= Page().bind(data=data, files=files, initial=None) pages.append((slug, page)) self.pages = OrderedDict(pages) self.data = data self.files",
"for page in self.pages.values(): lines.append(page.preview()) return lines def get_initial_data(self): initial = {} if",
"sum(bool(page.is_valid()) for page in self.pages.values()) num_pages = len(self.pages) self.percentage_done = 100 * pages_done",
"page.is_valid() cleaned_data[slug] = page.cleaned_data return cleaned_data def preview(self): lines = [] for page",
"prev page if any, None otherwise. Returns ValueError if slug does not exist",
"LOGGER = logging.getLogger(__name__) class MultiPageForm(object): help_text = '' percentage_done = 0.0 def __init__(self,",
"self.data = data self.files = files self.initialize(self.initial) self.bind(data=data, files=files, initial=initial) def file_fields(self): if",
"'' percentage_done = 0.0 def __init__(self, data=None, files=None, initial=None, **kwargs): self.initial = initial",
"return None next_slug = page_slugs[next_index] return self.pages[next_slug] def prev_page(self, slug): \"\"\" Returns prev",
"page in self.pages.items(): page.is_valid() cleaned_data[slug] = page.cleaned_data return cleaned_data def preview(self): lines =",
"any, None otherwise. Returns ValueError if slug does not exist in the pages",
"initial=None, **kwargs): pages = [] self.initial = self.initial or initial page_initial = {}",
"<reponame>kaleissin/django-multipageforms from __future__ import unicode_literals from collections import OrderedDict import logging import copy",
"= initial self.kwargs = kwargs self.pageclasses = OrderedDict([(page.slug, page) for page in self.pages])",
"percentage_done = 0.0 def __init__(self, data=None, files=None, initial=None, **kwargs): self.initial = initial self.kwargs",
"__init__(self, data=None, files=None, initial=None, **kwargs): self.initial = initial self.kwargs = kwargs self.pageclasses =",
"current_index - 1 if prev_index < 0: # No more pages return None",
"bool(self.data or self.files) return False def is_multipart(self): return any(page.is_multipart() for page in self.pages.values())",
"pages return None next_slug = page_slugs[next_index] return self.pages[next_slug] def prev_page(self, slug): \"\"\" Returns",
"self.pages = OrderedDict(pages) self.data = data self.files = files self.initial = initial or",
"files=files, initial=None) pages.append((slug, page)) self.pages = OrderedDict(pages) self.data = data self.files = files",
"in self.pages.values(): lines.append(page.preview()) return lines def get_initial_data(self): initial = {} if self.is_initialized: for",
"None prev_slug = page_slugs[prev_index] return self.pages[prev_slug] def initialize(self, initial=None, **kwargs): pages = []",
"import logging import copy LOGGER = logging.getLogger(__name__) class MultiPageForm(object): help_text = '' percentage_done",
"logging.getLogger(__name__) class MultiPageForm(object): help_text = '' percentage_done = 0.0 def __init__(self, data=None, files=None,",
"next_page(self, slug): \"\"\" Returns next page if any, None otherwise. Returns ValueError if",
"page in self.pages.values()) num_pages = len(self.pages) self.percentage_done = 100 * pages_done / float(num_pages)",
"exist in the pages \"\"\" if not self.is_initialized: self.initialize() page_slugs = tuple(self.pages.keys()) current_index",
"= OrderedDict(pages) self.data = data self.files = files self.initial = initial or self.initial",
"help_text = '' percentage_done = 0.0 def __init__(self, data=None, files=None, initial=None, **kwargs): self.initial",
"self.pages]) self.pages = None self.data = data self.files = files self.initialize(self.initial) self.bind(data=data, files=files,",
"slug): \"\"\" Returns prev page if any, None otherwise. Returns ValueError if slug",
"= data self.files = files self.initial = initial or self.initial return self @property",
"import unicode_literals from collections import OrderedDict import logging import copy LOGGER = logging.getLogger(__name__)",
"Page().bind(data=data, files=files, initial=None) pages.append((slug, page)) self.pages = OrderedDict(pages) self.data = data self.files =",
"self.pageclasses = OrderedDict([(page.slug, page) for page in self.pages]) self.pages = None self.data =",
"page = PageClass().initialize(initial=page_initial, **kwargs) pages.append((slug, page)) self.pages = OrderedDict(pages) return self def bind(self,",
"self.is_initialized: self.initialize() page_slugs = tuple(self.pages.keys()) current_index = page_slugs.index(slug) # ValueError prev_index = current_index",
"# ValueError prev_index = current_index - 1 if prev_index < 0: # No",
"return pages_done == num_pages return None @property def cleaned_data(self): cleaned_data = {} if",
"= tuple(self.pages.keys()) current_index = page_slugs.index(slug) # ValueError prev_index = current_index - 1 if",
"for slug, page in self.pages.items(): page.is_valid() cleaned_data[slug] = page.cleaned_data return cleaned_data def preview(self):",
"def bind(self, data=None, files=None, initial=None): pages = [] for slug, Page in self.pageclasses.items():",
"= self.initial.get(slug, {}) page = PageClass().initialize(initial=page_initial, **kwargs) pages.append((slug, page)) self.pages = OrderedDict(pages) return",
"copy LOGGER = logging.getLogger(__name__) class MultiPageForm(object): help_text = '' percentage_done = 0.0 def",
"in self.pages.values()) def is_valid(self): if self.is_initialized: pages_done = sum(bool(page.is_valid()) for page in self.pages.values())",
"= logging.getLogger(__name__) class MultiPageForm(object): help_text = '' percentage_done = 0.0 def __init__(self, data=None,",
"= tuple(self.pages.keys())[0] return self.pages[first_slug] def last_page(self): if not self.is_initialized: self.initialize() last_slug = tuple(self.pages.keys())[-1]",
"or initial page_initial = {} kwargs = self.kwargs.copy() if 'initial' in kwargs: kwargs.pop('initial')",
"* pages_done / float(num_pages) return pages_done == num_pages return None @property def cleaned_data(self):",
"current_index = page_slugs.index(slug) # ValueError next_index = current_index + 1 if next_index >",
"lines def get_initial_data(self): initial = {} if self.is_initialized: for slug, page in self.pages.items():",
"first_page(self): if not self.is_initialized: self.initialize() first_slug = tuple(self.pages.keys())[0] return self.pages[first_slug] def last_page(self): if",
"is_multipart(self): return any(page.is_multipart() for page in self.pages.values()) def is_valid(self): if self.is_initialized: pages_done =",
"slug, Page in self.pageclasses.items(): page = Page().bind(data=data, files=files, initial=None) pages.append((slug, page)) self.pages =",
"if not self.is_initialized: self.initialize() first_slug = tuple(self.pages.keys())[0] return self.pages[first_slug] def last_page(self): if not",
"ValueError next_index = current_index + 1 if next_index > len(page_slugs) - 1: #",
"or self.initial return self @property def is_initialized(self): return self.pages is not None @property",
"field in form.file_fields(): yield field def first_page(self): if not self.is_initialized: self.initialize() first_slug =",
"form.file_fields(): yield field def first_page(self): if not self.is_initialized: self.initialize() first_slug = tuple(self.pages.keys())[0] return",
"tuple(self.pages.keys()) current_index = page_slugs.index(slug) # ValueError next_index = current_index + 1 if next_index",
"return False def is_multipart(self): return any(page.is_multipart() for page in self.pages.values()) def is_valid(self): if",
"get_initial_data(self): initial = {} if self.is_initialized: for slug, page in self.pages.items(): page.is_valid() initial[slug]",
"not self.is_initialized: self.initialize() page_slugs = tuple(self.pages.keys()) current_index = page_slugs.index(slug) # ValueError next_index =",
"cleaned_data def preview(self): lines = [] for page in self.pages.values(): lines.append(page.preview()) return lines",
"self.is_initialized: for slug, page in self.pages.items(): page.is_valid() initial[slug] = page.get_initial_data() return initial def",
"self.initial = initial or self.initial return self @property def is_initialized(self): return self.pages is",
"if not self.is_initialized: self.initialize() page_slugs = tuple(self.pages.keys()) current_index = page_slugs.index(slug) # ValueError prev_index",
"page_slugs.index(slug) # ValueError prev_index = current_index - 1 if prev_index < 0: #",
"= {} kwargs = self.kwargs.copy() if 'initial' in kwargs: kwargs.pop('initial') for slug, PageClass",
"file_fields(self): if self.is_multipart(): for form in self.pages.values(): for field in form.file_fields(): yield field",
"No more pages return None next_slug = page_slugs[next_index] return self.pages[next_slug] def prev_page(self, slug):",
"[] for slug, Page in self.pageclasses.items(): page = Page().bind(data=data, files=files, initial=None) pages.append((slug, page))",
"slug, page in self.pages.items(): page.is_valid() cleaned_data[slug] = page.cleaned_data return cleaned_data def preview(self): lines",
"bind(self, data=None, files=None, initial=None): pages = [] for slug, Page in self.pageclasses.items(): page",
"len(page_slugs) - 1: # No more pages return None next_slug = page_slugs[next_index] return",
"= files self.initial = initial or self.initial return self @property def is_initialized(self): return",
"self.pages.values(): lines.append(page.preview()) return lines def get_initial_data(self): initial = {} if self.is_initialized: for slug,",
"1 if prev_index < 0: # No more pages return None prev_slug =",
"= current_index - 1 if prev_index < 0: # No more pages return",
"page_slugs[prev_index] return self.pages[prev_slug] def initialize(self, initial=None, **kwargs): pages = [] self.initial = self.initial",
"initial=None): pages = [] for slug, Page in self.pageclasses.items(): page = Page().bind(data=data, files=files,",
"page)) self.pages = OrderedDict(pages) self.data = data self.files = files self.initial = initial",
"pages.append((slug, page)) self.pages = OrderedDict(pages) return self def bind(self, data=None, files=None, initial=None): pages",
"next_index > len(page_slugs) - 1: # No more pages return None next_slug =",
"self.initialize(self.initial) self.bind(data=data, files=files, initial=initial) def file_fields(self): if self.is_multipart(): for form in self.pages.values(): for",
"self.pages.values(): for field in form.file_fields(): yield field def first_page(self): if not self.is_initialized: self.initialize()",
"@property def is_bound(self): if self.is_initialized: return bool(self.data or self.files) return False def is_multipart(self):",
"def get_initial_data(self): initial = {} if self.is_initialized: for slug, page in self.pages.items(): page.is_valid()",
"= initial or self.initial return self @property def is_initialized(self): return self.pages is not",
"cleaned_data[slug] = page.cleaned_data return cleaned_data def preview(self): lines = [] for page in",
"= sum(bool(page.is_valid()) for page in self.pages.values()) num_pages = len(self.pages) self.percentage_done = 100 *",
"{} if self.is_initialized: for slug, page in self.pages.items(): page.is_valid() initial[slug] = page.get_initial_data() return",
"False def is_multipart(self): return any(page.is_multipart() for page in self.pages.values()) def is_valid(self): if self.is_initialized:",
"PageClass().initialize(initial=page_initial, **kwargs) pages.append((slug, page)) self.pages = OrderedDict(pages) return self def bind(self, data=None, files=None,",
"**kwargs): self.initial = initial self.kwargs = kwargs self.pageclasses = OrderedDict([(page.slug, page) for page",
"= tuple(self.pages.keys()) current_index = page_slugs.index(slug) # ValueError next_index = current_index + 1 if",
"= {} if self.is_initialized: for slug, page in self.pages.items(): page.is_valid() initial[slug] = page.get_initial_data()",
"OrderedDict import logging import copy LOGGER = logging.getLogger(__name__) class MultiPageForm(object): help_text = ''",
"page in self.pages.values(): lines.append(page.preview()) return lines def get_initial_data(self): initial = {} if self.is_initialized:",
"or self.files) return False def is_multipart(self): return any(page.is_multipart() for page in self.pages.values()) def",
"self.pages[prev_slug] def initialize(self, initial=None, **kwargs): pages = [] self.initial = self.initial or initial",
"for slug, PageClass in self.pageclasses.items(): if self.initial: page_initial = self.initial.get(slug, {}) page =",
"[] for page in self.pages.values(): lines.append(page.preview()) return lines def get_initial_data(self): initial = {}",
"kwargs self.pageclasses = OrderedDict([(page.slug, page) for page in self.pages]) self.pages = None self.data",
"def __init__(self, data=None, files=None, initial=None, **kwargs): self.initial = initial self.kwargs = kwargs self.pageclasses",
"[] self.initial = self.initial or initial page_initial = {} kwargs = self.kwargs.copy() if",
"return self.pages[prev_slug] def initialize(self, initial=None, **kwargs): pages = [] self.initial = self.initial or",
"100 * pages_done / float(num_pages) return pages_done == num_pages return None @property def",
"pages.append((slug, page)) self.pages = OrderedDict(pages) self.data = data self.files = files self.initial =",
"initial=initial) def file_fields(self): if self.is_multipart(): for form in self.pages.values(): for field in form.file_fields():",
"last_slug = tuple(self.pages.keys())[-1] return self.pages[last_slug] def next_page(self, slug): \"\"\" Returns next page if",
"None @property def cleaned_data(self): cleaned_data = {} if self.is_bound: for slug, page in",
"in self.pageclasses.items(): if self.initial: page_initial = self.initial.get(slug, {}) page = PageClass().initialize(initial=page_initial, **kwargs) pages.append((slug,",
"def last_page(self): if not self.is_initialized: self.initialize() last_slug = tuple(self.pages.keys())[-1] return self.pages[last_slug] def next_page(self,",
"= '' percentage_done = 0.0 def __init__(self, data=None, files=None, initial=None, **kwargs): self.initial =",
"next_slug = page_slugs[next_index] return self.pages[next_slug] def prev_page(self, slug): \"\"\" Returns prev page if",
"self.pages[last_slug] def next_page(self, slug): \"\"\" Returns next page if any, None otherwise. Returns",
"tuple(self.pages.keys())[-1] return self.pages[last_slug] def next_page(self, slug): \"\"\" Returns next page if any, None",
"self.pages[next_slug] def prev_page(self, slug): \"\"\" Returns prev page if any, None otherwise. Returns",
"No more pages return None prev_slug = page_slugs[prev_index] return self.pages[prev_slug] def initialize(self, initial=None,",
"form in self.pages.values(): for field in form.file_fields(): yield field def first_page(self): if not",
"if self.initial: page_initial = self.initial.get(slug, {}) page = PageClass().initialize(initial=page_initial, **kwargs) pages.append((slug, page)) self.pages",
"self.pages = None self.data = data self.files = files self.initialize(self.initial) self.bind(data=data, files=files, initial=initial)",
"# No more pages return None next_slug = page_slugs[next_index] return self.pages[next_slug] def prev_page(self,",
"def first_page(self): if not self.is_initialized: self.initialize() first_slug = tuple(self.pages.keys())[0] return self.pages[first_slug] def last_page(self):",
"pages_done = sum(bool(page.is_valid()) for page in self.pages.values()) num_pages = len(self.pages) self.percentage_done = 100",
"self.is_initialized: return bool(self.data or self.files) return False def is_multipart(self): return any(page.is_multipart() for page",
"Returns prev page if any, None otherwise. Returns ValueError if slug does not",
"prev_index = current_index - 1 if prev_index < 0: # No more pages",
"== num_pages return None @property def cleaned_data(self): cleaned_data = {} if self.is_bound: for",
"more pages return None next_slug = page_slugs[next_index] return self.pages[next_slug] def prev_page(self, slug): \"\"\"",
"= self.initial or initial page_initial = {} kwargs = self.kwargs.copy() if 'initial' in",
"field def first_page(self): if not self.is_initialized: self.initialize() first_slug = tuple(self.pages.keys())[0] return self.pages[first_slug] def",
"data self.files = files self.initialize(self.initial) self.bind(data=data, files=files, initial=initial) def file_fields(self): if self.is_multipart(): for",
"if self.is_initialized: return bool(self.data or self.files) return False def is_multipart(self): return any(page.is_multipart() for",
"= 0.0 def __init__(self, data=None, files=None, initial=None, **kwargs): self.initial = initial self.kwargs =",
"self.pageclasses.items(): if self.initial: page_initial = self.initial.get(slug, {}) page = PageClass().initialize(initial=page_initial, **kwargs) pages.append((slug, page))",
"Page in self.pageclasses.items(): page = Page().bind(data=data, files=files, initial=None) pages.append((slug, page)) self.pages = OrderedDict(pages)",
"not self.is_initialized: self.initialize() last_slug = tuple(self.pages.keys())[-1] return self.pages[last_slug] def next_page(self, slug): \"\"\" Returns"
] |
[
"(f'Lag Performance Statistics for {tickers} ({num_of_years} years):') for lag in lags: my_rs =",
"1 plt.subplots() my_rs = (pos.shift(1)*rs).sum(1) my_rs.cumsum().apply(np.exp).plot(title='Full Portfolio Strategy Performance') rs.mean(1).cumsum().apply(np.exp).plot() plt.legend(['Portfolio MA Performace',",
"with Lags') plt.legend(lags, bbox_to_anchor=(1.1, 0.95)) plt.show() # Transaction Costs tc_pct = 0.01 delta_pos",
"('With Look-Ahead Bias: ' + str(100 * round(my_rs1.cumsum().apply(np.exp).tolist()[-1], 4)) + '%') print('Without Look-Ahead",
"= int(365.25*num_of_years)) yf_prices = yf.download(tickers, start=start) # Individual Stock Strategy prices = yf_prices['Adj",
"= (pos.shift(1)*rs) my_rs.cumsum().apply(np.exp).plot(title='Individual Stocks Strategy Performance') plt.show() print ('-' * 60) print (f'Performance",
"my_rs.cumsum().apply(np.exp).plot(title='Full Portfolio Strategy Performance') rs.mean(1).cumsum().apply(np.exp).plot() plt.legend(['Portfolio MA Performace', 'Buy and Hold Performnace']) plt.show()",
"my_rs2.cumsum().apply(np.exp).plot() plt.title('Full Portfolio Performance') plt.legend(['Without Transaction Costs', 'With Transaction Costs']) plt.show() print ('-'",
"({num_of_years} years):') for lag in lags: my_rs = (pos.shift(lag)*rs).sum(1) my_rs.cumsum().apply(np.exp).plot() lagged_rs[lag] = my_rs.sum()",
"ma_x = prices.rolling(w1).mean() - prices.rolling(w2).mean() pos = ma_x.apply(np.sign) fig, ax = plt.subplots(2,1) ma_x.plot(ax=ax[0],",
"ma_x.plot(ax=ax[0], title=f'{individual_stock} Moving Average Crossovers and Positions') pos.plot(ax=ax[1]) plt.show() my_rs = pos.shift(1)*rs plt.subplots()",
"0.95)) plt.show() # Transaction Costs tc_pct = 0.01 delta_pos = pos.diff(1).abs().sum(1) my_tcs =",
"Strategy prices = yf_prices['Adj Close'][individual_stock] rs = prices.apply(np.log).diff(1).fillna(0) w1 = 5 w2 =",
"matplotlib.pyplot as plt import datetime from yahoo_fin import stock_info as si plt.rcParams['figure.figsize'] =",
"yf_prices = yf.download(tickers, start=start) # Individual Stock Strategy prices = yf_prices['Adj Close'][individual_stock] rs",
"lags: my_rs = (pos.shift(lag)*rs).sum(1) my_rs.cumsum().apply(np.exp).plot() lagged_rs[lag] = my_rs.sum() print (f'Lag {lag} Return: '",
"str(100 * round(my_rs2.cumsum().apply(np.exp).tolist()[-1], 4)) + '%') # Signal Lags lags = range(1, 11)",
"str(100 * round(my_rs.cumsum().apply(np.exp)[tickers[i]].tolist()[-1], 4)) + '%') i = i + 1 plt.subplots() my_rs",
"5 w2 = 22 ma_x = prices.rolling(w1).mean() - prices.rolling(w2).mean() pos = ma_x.apply(np.sign) fig,",
"w2 = 22 ma_x = prices.rolling(w1).mean() - prices.rolling(w2).mean() pos = ma_x.apply(np.sign) fig, ax",
"'%') i = i + 1 plt.subplots() my_rs = (pos.shift(1)*rs).sum(1) my_rs.cumsum().apply(np.exp).plot(title='Full Portfolio Strategy",
"pd.Series(dtype=float, index=lags) print ('-' * 60) print (f'Lag Performance Statistics for {tickers} ({num_of_years}",
"my_rs1.cumsum().apply(np.exp).plot(title='Full Portfolio Performance') my_rs2.cumsum().apply(np.exp).plot() plt.legend(['With Look-Ahead Bias', 'Without Look-Ahead Bias']) plt.show() print ('-'",
"for {tickers[i]}: ' + str(100 * round(my_rs.cumsum().apply(np.exp)[tickers[i]].tolist()[-1], 4)) + '%') i = i",
"datetime.date.today() - datetime.timedelta(days = int(365.25*num_of_years)) yf_prices = yf.download(tickers, start=start) # Individual Stock Strategy",
"print (f'Performance Statistics for {tickers} ({num_of_years} years):') print ('With Look-Ahead Bias: ' +",
"= (pos.shift(1)*rs).sum(1) my_rs2 = (pos.shift(1)*rs).sum(1) - my_tcs plt.subplots() my_rs1.cumsum().apply(np.exp).plot() my_rs2.cumsum().apply(np.exp).plot() plt.title('Full Portfolio Performance')",
"Transaction Costs']) plt.show() print ('-' * 60) print (f'Performance Statistics for {tickers} ({num_of_years}",
"= (pos.shift(lag)*rs).sum(1) my_rs.cumsum().apply(np.exp).plot() lagged_rs[lag] = my_rs.sum() print (f'Lag {lag} Return: ' + str(100",
"as pd import yfinance as yf import matplotlib.pyplot as plt import datetime from",
"Bias my_rs1 = (pos*rs).sum(1) my_rs2 = (pos.shift(1)*rs).sum(1) plt.subplots() my_rs1.cumsum().apply(np.exp).plot(title='Full Portfolio Performance') my_rs2.cumsum().apply(np.exp).plot() plt.legend(['With",
"for {num_of_years} years:') for i in range(len(tickers)): print (f'Moving Average Return for {tickers[i]}:",
"si.tickers_dow() individual_stock = input(f\"Which of the following stocks would you like to backtest",
"print (f'Performance Statistics for {individual_stock} ({num_of_years} years):') print ('Moving Average Return: ' +",
"Return: ' + str(100 * round(my_rs.cumsum().apply(np.exp).tolist()[-1], 4)) + '%') print('Buy and Hold Return:",
"ma_x.apply(np.sign) pos /= pos.abs().sum(1).values.reshape(-1,1) fig, ax = plt.subplots(2,1) ma_x.plot(ax=ax[0], title='Individual Moving Average Crossovers",
"input(f\"Which of the following stocks would you like to backtest \\n{tickers}\\n:\") num_of_years =",
"* 60) print (f'Performance Statistics for {tickers} ({num_of_years} years):') print ('Moving Average Return:",
"Costs tc_pct = 0.01 delta_pos = pos.diff(1).abs().sum(1) my_tcs = tc_pct*delta_pos my_rs1 = (pos.shift(1)*rs).sum(1)",
"'With Transaction Costs']) plt.show() print ('-' * 60) print (f'Performance Statistics for {tickers}",
"Positions') ax[0].legend(bbox_to_anchor=(1.1, 1.05)) pos.plot(ax=ax[1]) ax[1].legend(bbox_to_anchor=(1.1, 1.05)) plt.show() my_rs = (pos.shift(1)*rs) my_rs.cumsum().apply(np.exp).plot(title='Individual Stocks Strategy",
"+ '%') plt.title('Full Portfolio Strategy Performance with Lags') plt.legend(lags, bbox_to_anchor=(1.1, 0.95)) plt.show() #",
"= tc_pct*delta_pos my_rs1 = (pos.shift(1)*rs).sum(1) my_rs2 = (pos.shift(1)*rs).sum(1) - my_tcs plt.subplots() my_rs1.cumsum().apply(np.exp).plot() my_rs2.cumsum().apply(np.exp).plot()",
"* 60) print (f'Performance Statistics for {tickers} ({num_of_years} years):') print ('Without Transaction Costs:",
"print('Buy and Hold Return: ' + str(100 * round(rs.mean(1).cumsum().apply(np.exp).tolist()[-1], 4)) + '%') #",
"= 5 w2 = 22 ma_x = prices.rolling(w1).mean() - prices.rolling(w2).mean() pos = ma_x.apply(np.sign)",
"bbox_to_anchor=(1.1, 0.95)) plt.show() # Transaction Costs tc_pct = 0.01 delta_pos = pos.diff(1).abs().sum(1) my_tcs",
"{tickers} ({num_of_years} years):') print ('Without Transaction Costs: ' + str(100 * round(my_rs1.cumsum().apply(np.exp).tolist()[-1], 4))",
"' + str(100 * round(my_rs1.cumsum().apply(np.exp).tolist()[-1], 4)) + '%') print('With Transaction Costs: ' +",
"Look-Ahead Bias', 'Without Look-Ahead Bias']) plt.show() print ('-' * 60) print (f'Performance Statistics",
"for {tickers} ({num_of_years} years):') print ('With Look-Ahead Bias: ' + str(100 * round(my_rs1.cumsum().apply(np.exp).tolist()[-1],",
"round(my_rs2.cumsum().apply(np.exp).tolist()[-1], 4)) + '%') # Signal Lags lags = range(1, 11) lagged_rs =",
"title='Individual Moving Average Crossovers and Positions') ax[0].legend(bbox_to_anchor=(1.1, 1.05)) pos.plot(ax=ax[1]) ax[1].legend(bbox_to_anchor=(1.1, 1.05)) plt.show() my_rs",
"print ('-' * 60) print (f'Performance Statistics for {tickers} ({num_of_years} years):') print ('With",
"('Without Transaction Costs: ' + str(100 * round(my_rs1.cumsum().apply(np.exp).tolist()[-1], 4)) + '%') print('With Transaction",
"+ '%') print('With Transaction Costs: ' + str(100 * round(my_rs2.cumsum().apply(np.exp).tolist()[-1], 4)) + '%')",
"in range(len(tickers)): print (f'Moving Average Return for {tickers[i]}: ' + str(100 * round(my_rs.cumsum().apply(np.exp)[tickers[i]].tolist()[-1],",
"lagged_rs[lag] = my_rs.sum() print (f'Lag {lag} Return: ' + str(100 * round(my_rs.cumsum().apply(np.exp).tolist()[-1], 4))",
"22 ma_x = prices.rolling(w1).mean() - prices.rolling(w2).mean() pos = ma_x.apply(np.sign) fig, ax = plt.subplots(2,1)",
"w1 = 5 w2 = 22 ma_x = prices.rolling(w1).mean() - prices.rolling(w2).mean() pos =",
"Average Return for {tickers[i]}: ' + str(100 * round(my_rs.cumsum().apply(np.exp)[tickers[i]].tolist()[-1], 4)) + '%') i",
"print('Without Look-Ahead Bias: ' + str(100 * round(my_rs2.cumsum().apply(np.exp).tolist()[-1], 4)) + '%') # Signal",
"my_rs = (pos.shift(lag)*rs).sum(1) my_rs.cumsum().apply(np.exp).plot() lagged_rs[lag] = my_rs.sum() print (f'Lag {lag} Return: ' +",
"'%') print('Buy and Hold Return: ' + str(100 * round(rs.cumsum().apply(np.exp).tolist()[-1], 4)) + '%')",
"plt.rcParams['figure.figsize'] = (15, 10) tickers = si.tickers_dow() individual_stock = input(f\"Which of the following",
"my_rs.cumsum().apply(np.exp).plot() lagged_rs[lag] = my_rs.sum() print (f'Lag {lag} Return: ' + str(100 * round(my_rs.cumsum().apply(np.exp).tolist()[-1],",
"= 1 start = datetime.date.today() - datetime.timedelta(days = int(365.25*num_of_years)) yf_prices = yf.download(tickers, start=start)",
"Performance Statistics for {tickers} ({num_of_years} years):') for lag in lags: my_rs = (pos.shift(lag)*rs).sum(1)",
"Performnace']) plt.show() print ('-' * 60) print (f'Performance Statistics for {tickers} ({num_of_years} years):')",
"start = datetime.date.today() - datetime.timedelta(days = int(365.25*num_of_years)) yf_prices = yf.download(tickers, start=start) # Individual",
"Statistics for {tickers} ({num_of_years} years):') print ('With Look-Ahead Bias: ' + str(100 *",
"as plt import datetime from yahoo_fin import stock_info as si plt.rcParams['figure.figsize'] = (15,",
"stocks would you like to backtest \\n{tickers}\\n:\") num_of_years = 1 start = datetime.date.today()",
"int(365.25*num_of_years)) yf_prices = yf.download(tickers, start=start) # Individual Stock Strategy prices = yf_prices['Adj Close'][individual_stock]",
"tc_pct = 0.01 delta_pos = pos.diff(1).abs().sum(1) my_tcs = tc_pct*delta_pos my_rs1 = (pos.shift(1)*rs).sum(1) my_rs2",
"my_rs1 = (pos.shift(1)*rs).sum(1) my_rs2 = (pos.shift(1)*rs).sum(1) - my_tcs plt.subplots() my_rs1.cumsum().apply(np.exp).plot() my_rs2.cumsum().apply(np.exp).plot() plt.title('Full Portfolio",
"yfinance as yf import matplotlib.pyplot as plt import datetime from yahoo_fin import stock_info",
"my_rs.cumsum().apply(np.exp).plot(title='Individual Stocks Strategy Performance') plt.show() print ('-' * 60) print (f'Performance Statistics for",
"Portfolio Strategy Performance') rs.mean(1).cumsum().apply(np.exp).plot() plt.legend(['Portfolio MA Performace', 'Buy and Hold Performnace']) plt.show() print",
"= ma_x.apply(np.sign) pos /= pos.abs().sum(1).values.reshape(-1,1) fig, ax = plt.subplots(2,1) ma_x.plot(ax=ax[0], title='Individual Moving Average",
"1.05)) pos.plot(ax=ax[1]) ax[1].legend(bbox_to_anchor=(1.1, 1.05)) plt.show() my_rs = (pos.shift(1)*rs) my_rs.cumsum().apply(np.exp).plot(title='Individual Stocks Strategy Performance') plt.show()",
"Statistics for {tickers} ({num_of_years} years):') print ('Without Transaction Costs: ' + str(100 *",
"pos.plot(ax=ax[1]) ax[1].legend(bbox_to_anchor=(1.1, 1.05)) plt.show() my_rs = (pos.shift(1)*rs) my_rs.cumsum().apply(np.exp).plot(title='Individual Stocks Strategy Performance') plt.show() print",
"si plt.rcParams['figure.figsize'] = (15, 10) tickers = si.tickers_dow() individual_stock = input(f\"Which of the",
"import numpy as np import pandas as pd import yfinance as yf import",
"' + str(100 * round(rs.mean(1).cumsum().apply(np.exp).tolist()[-1], 4)) + '%') # Portfolio Tests # Look-Ahead",
"MA Strategy Performance') rs.cumsum().apply(np.exp).plot() plt.legend([f'{individual_stock} MA Performace', f'{individual_stock} Buy and Hold Performnace']) plt.show()",
"Performance') rs.cumsum().apply(np.exp).plot() plt.legend([f'{individual_stock} MA Performace', f'{individual_stock} Buy and Hold Performnace']) plt.show() print (f'Performance",
"range(len(tickers)): print (f'Moving Average Return for {tickers[i]}: ' + str(100 * round(my_rs.cumsum().apply(np.exp)[tickers[i]].tolist()[-1], 4))",
"and Hold Performnace']) plt.show() print (f'Performance Statistics for {individual_stock} ({num_of_years} years):') print ('Moving",
"Return: ' + str(100 * round(rs.mean(1).cumsum().apply(np.exp).tolist()[-1], 4)) + '%') # Portfolio Tests #",
"Look-Ahead Bias: ' + str(100 * round(my_rs2.cumsum().apply(np.exp).tolist()[-1], 4)) + '%') # Signal Lags",
"4)) + '%') # Portfolio Tests # Look-Ahead Bias my_rs1 = (pos*rs).sum(1) my_rs2",
"ma_x.plot(ax=ax[0], title='Individual Moving Average Crossovers and Positions') ax[0].legend(bbox_to_anchor=(1.1, 1.05)) pos.plot(ax=ax[1]) ax[1].legend(bbox_to_anchor=(1.1, 1.05)) plt.show()",
"round(my_rs1.cumsum().apply(np.exp).tolist()[-1], 4)) + '%') print('With Transaction Costs: ' + str(100 * round(my_rs2.cumsum().apply(np.exp).tolist()[-1], 4))",
"' + str(100 * round(my_rs.cumsum().apply(np.exp).tolist()[-1], 4)) + '%') plt.title('Full Portfolio Strategy Performance with",
"(pos.shift(1)*rs).sum(1) plt.subplots() my_rs1.cumsum().apply(np.exp).plot(title='Full Portfolio Performance') my_rs2.cumsum().apply(np.exp).plot() plt.legend(['With Look-Ahead Bias', 'Without Look-Ahead Bias']) plt.show()",
"{tickers} ({num_of_years} years):') for lag in lags: my_rs = (pos.shift(lag)*rs).sum(1) my_rs.cumsum().apply(np.exp).plot() lagged_rs[lag] =",
"Bias: ' + str(100 * round(my_rs1.cumsum().apply(np.exp).tolist()[-1], 4)) + '%') print('Without Look-Ahead Bias: '",
"plt.subplots() my_rs.cumsum().apply(np.exp).plot(title=f'{individual_stock} MA Strategy Performance') rs.cumsum().apply(np.exp).plot() plt.legend([f'{individual_stock} MA Performace', f'{individual_stock} Buy and Hold",
"(pos.shift(1)*rs).sum(1) - my_tcs plt.subplots() my_rs1.cumsum().apply(np.exp).plot() my_rs2.cumsum().apply(np.exp).plot() plt.title('Full Portfolio Performance') plt.legend(['Without Transaction Costs', 'With",
"* round(my_rs1.cumsum().apply(np.exp).tolist()[-1], 4)) + '%') print('Without Look-Ahead Bias: ' + str(100 * round(my_rs2.cumsum().apply(np.exp).tolist()[-1],",
"= 22 ma_x = prices.rolling(w1).mean() - prices.rolling(w2).mean() pos = ma_x.apply(np.sign) pos /= pos.abs().sum(1).values.reshape(-1,1)",
"{num_of_years} years:') for i in range(len(tickers)): print (f'Moving Average Return for {tickers[i]}: '",
"would you like to backtest \\n{tickers}\\n:\") num_of_years = 1 start = datetime.date.today() -",
"= yf.download(tickers, start=start) # Individual Stock Strategy prices = yf_prices['Adj Close'][individual_stock] rs =",
"= plt.subplots(2,1) ma_x.plot(ax=ax[0], title='Individual Moving Average Crossovers and Positions') ax[0].legend(bbox_to_anchor=(1.1, 1.05)) pos.plot(ax=ax[1]) ax[1].legend(bbox_to_anchor=(1.1,",
"import pandas as pd import yfinance as yf import matplotlib.pyplot as plt import",
"' + str(100 * round(my_rs1.cumsum().apply(np.exp).tolist()[-1], 4)) + '%') print('Without Look-Ahead Bias: ' +",
"(f'Performance Statistics for {tickers} ({num_of_years} years):') print ('Moving Average Return: ' + str(100",
"print ('-' * 60) print (f'Performance Statistics for {tickers} ({num_of_years} years):') print ('Without",
"* round(rs.cumsum().apply(np.exp).tolist()[-1], 4)) + '%') # Full Portfolio Strategy prices = yf_prices['Adj Close']",
"round(my_rs.cumsum().apply(np.exp)[tickers[i]].tolist()[-1], 4)) + '%') i = i + 1 plt.subplots() my_rs = (pos.shift(1)*rs).sum(1)",
"# Portfolio Tests # Look-Ahead Bias my_rs1 = (pos*rs).sum(1) my_rs2 = (pos.shift(1)*rs).sum(1) plt.subplots()",
"(f'Lag {lag} Return: ' + str(100 * round(my_rs.cumsum().apply(np.exp).tolist()[-1], 4)) + '%') plt.title('Full Portfolio",
"Statistics for {tickers} ({num_of_years} years):') for lag in lags: my_rs = (pos.shift(lag)*rs).sum(1) my_rs.cumsum().apply(np.exp).plot()",
"Statistics for {num_of_years} years:') for i in range(len(tickers)): print (f'Moving Average Return for",
"'%') print('Without Look-Ahead Bias: ' + str(100 * round(my_rs2.cumsum().apply(np.exp).tolist()[-1], 4)) + '%') #",
"(pos.shift(lag)*rs).sum(1) my_rs.cumsum().apply(np.exp).plot() lagged_rs[lag] = my_rs.sum() print (f'Lag {lag} Return: ' + str(100 *",
"= pos.diff(1).abs().sum(1) my_tcs = tc_pct*delta_pos my_rs1 = (pos.shift(1)*rs).sum(1) my_rs2 = (pos.shift(1)*rs).sum(1) - my_tcs",
"years):') print ('Without Transaction Costs: ' + str(100 * round(my_rs1.cumsum().apply(np.exp).tolist()[-1], 4)) + '%')",
"Transaction Costs tc_pct = 0.01 delta_pos = pos.diff(1).abs().sum(1) my_tcs = tc_pct*delta_pos my_rs1 =",
"my_rs.sum() print (f'Lag {lag} Return: ' + str(100 * round(my_rs.cumsum().apply(np.exp).tolist()[-1], 4)) + '%')",
"{tickers} ({num_of_years} years):') print ('Moving Average Return: ' + str(100 * round(my_rs.cumsum().apply(np.exp).tolist()[-1], 4))",
"plt.title('Full Portfolio Strategy Performance with Lags') plt.legend(lags, bbox_to_anchor=(1.1, 0.95)) plt.show() # Transaction Costs",
"round(my_rs.cumsum().apply(np.exp).tolist()[-1], 4)) + '%') plt.title('Full Portfolio Strategy Performance with Lags') plt.legend(lags, bbox_to_anchor=(1.1, 0.95))",
"= prices.rolling(w1).mean() - prices.rolling(w2).mean() pos = ma_x.apply(np.sign) pos /= pos.abs().sum(1).values.reshape(-1,1) fig, ax =",
"backtest \\n{tickers}\\n:\") num_of_years = 1 start = datetime.date.today() - datetime.timedelta(days = int(365.25*num_of_years)) yf_prices",
"print ('-' * 60) print (f'Performance Statistics for {num_of_years} years:') for i in",
"Look-Ahead Bias']) plt.show() print ('-' * 60) print (f'Performance Statistics for {tickers} ({num_of_years}",
"= i + 1 plt.subplots() my_rs = (pos.shift(1)*rs).sum(1) my_rs.cumsum().apply(np.exp).plot(title='Full Portfolio Strategy Performance') rs.mean(1).cumsum().apply(np.exp).plot()",
"+ str(100 * round(my_rs.cumsum().apply(np.exp).tolist()[-1], 4)) + '%') plt.title('Full Portfolio Strategy Performance with Lags')",
"you like to backtest \\n{tickers}\\n:\") num_of_years = 1 start = datetime.date.today() - datetime.timedelta(days",
"\\n{tickers}\\n:\") num_of_years = 1 start = datetime.date.today() - datetime.timedelta(days = int(365.25*num_of_years)) yf_prices =",
"Transaction Costs', 'With Transaction Costs']) plt.show() print ('-' * 60) print (f'Performance Statistics",
"- prices.rolling(w2).mean() pos = ma_x.apply(np.sign) fig, ax = plt.subplots(2,1) ma_x.plot(ax=ax[0], title=f'{individual_stock} Moving Average",
"and Hold Return: ' + str(100 * round(rs.mean(1).cumsum().apply(np.exp).tolist()[-1], 4)) + '%') # Portfolio",
"# Look-Ahead Bias my_rs1 = (pos*rs).sum(1) my_rs2 = (pos.shift(1)*rs).sum(1) plt.subplots() my_rs1.cumsum().apply(np.exp).plot(title='Full Portfolio Performance')",
"rs.mean(1).cumsum().apply(np.exp).plot() plt.legend(['Portfolio MA Performace', 'Buy and Hold Performnace']) plt.show() print ('-' * 60)",
"as yf import matplotlib.pyplot as plt import datetime from yahoo_fin import stock_info as",
"yf_prices['Adj Close'][individual_stock] rs = prices.apply(np.log).diff(1).fillna(0) w1 = 5 w2 = 22 ma_x =",
"' + str(100 * round(my_rs.cumsum().apply(np.exp).tolist()[-1], 4)) + '%') print('Buy and Hold Return: '",
"my_rs = (pos.shift(1)*rs).sum(1) my_rs.cumsum().apply(np.exp).plot(title='Full Portfolio Strategy Performance') rs.mean(1).cumsum().apply(np.exp).plot() plt.legend(['Portfolio MA Performace', 'Buy and",
"= my_rs.sum() print (f'Lag {lag} Return: ' + str(100 * round(my_rs.cumsum().apply(np.exp).tolist()[-1], 4)) +",
"5 w2 = 22 ma_x = prices.rolling(w1).mean() - prices.rolling(w2).mean() pos = ma_x.apply(np.sign) pos",
"Moving Average Crossovers and Positions') pos.plot(ax=ax[1]) plt.show() my_rs = pos.shift(1)*rs plt.subplots() my_rs.cumsum().apply(np.exp).plot(title=f'{individual_stock} MA",
"(f'Performance Statistics for {tickers} ({num_of_years} years):') print ('Without Transaction Costs: ' + str(100",
"* round(my_rs.cumsum().apply(np.exp).tolist()[-1], 4)) + '%') print('Buy and Hold Return: ' + str(100 *",
"as np import pandas as pd import yfinance as yf import matplotlib.pyplot as",
"+ str(100 * round(rs.cumsum().apply(np.exp).tolist()[-1], 4)) + '%') # Full Portfolio Strategy prices =",
"pos = ma_x.apply(np.sign) fig, ax = plt.subplots(2,1) ma_x.plot(ax=ax[0], title=f'{individual_stock} Moving Average Crossovers and",
"round(my_rs.cumsum().apply(np.exp).tolist()[-1], 4)) + '%') print('Buy and Hold Return: ' + str(100 * round(rs.mean(1).cumsum().apply(np.exp).tolist()[-1],",
"Moving Average Crossovers and Positions') ax[0].legend(bbox_to_anchor=(1.1, 1.05)) pos.plot(ax=ax[1]) ax[1].legend(bbox_to_anchor=(1.1, 1.05)) plt.show() my_rs =",
"ax = plt.subplots(2,1) ma_x.plot(ax=ax[0], title=f'{individual_stock} Moving Average Crossovers and Positions') pos.plot(ax=ax[1]) plt.show() my_rs",
"= 0.01 delta_pos = pos.diff(1).abs().sum(1) my_tcs = tc_pct*delta_pos my_rs1 = (pos.shift(1)*rs).sum(1) my_rs2 =",
"my_rs = pos.shift(1)*rs plt.subplots() my_rs.cumsum().apply(np.exp).plot(title=f'{individual_stock} MA Strategy Performance') rs.cumsum().apply(np.exp).plot() plt.legend([f'{individual_stock} MA Performace', f'{individual_stock}",
"yahoo_fin import stock_info as si plt.rcParams['figure.figsize'] = (15, 10) tickers = si.tickers_dow() individual_stock",
"str(100 * round(my_rs1.cumsum().apply(np.exp).tolist()[-1], 4)) + '%') print('With Transaction Costs: ' + str(100 *",
"0.01 delta_pos = pos.diff(1).abs().sum(1) my_tcs = tc_pct*delta_pos my_rs1 = (pos.shift(1)*rs).sum(1) my_rs2 = (pos.shift(1)*rs).sum(1)",
"({num_of_years} years):') print ('Without Transaction Costs: ' + str(100 * round(my_rs1.cumsum().apply(np.exp).tolist()[-1], 4)) +",
"4)) + '%') # Full Portfolio Strategy prices = yf_prices['Adj Close'] rs =",
"(pos.shift(1)*rs).sum(1) my_rs2 = (pos.shift(1)*rs).sum(1) - my_tcs plt.subplots() my_rs1.cumsum().apply(np.exp).plot() my_rs2.cumsum().apply(np.exp).plot() plt.title('Full Portfolio Performance') plt.legend(['Without",
"= yf_prices['Adj Close'][individual_stock] rs = prices.apply(np.log).diff(1).fillna(0) w1 = 5 w2 = 22 ma_x",
"print ('Without Transaction Costs: ' + str(100 * round(my_rs1.cumsum().apply(np.exp).tolist()[-1], 4)) + '%') print('With",
"' + str(100 * round(my_rs.cumsum().apply(np.exp)[tickers[i]].tolist()[-1], 4)) + '%') i = i + 1",
"* 60) print (f'Performance Statistics for {tickers} ({num_of_years} years):') print ('With Look-Ahead Bias:",
"Portfolio Strategy Performance with Lags') plt.legend(lags, bbox_to_anchor=(1.1, 0.95)) plt.show() # Transaction Costs tc_pct",
"Full Portfolio Strategy prices = yf_prices['Adj Close'] rs = prices.apply(np.log).diff(1).fillna(0) w1 = 5",
"my_rs2 = (pos.shift(1)*rs).sum(1) plt.subplots() my_rs1.cumsum().apply(np.exp).plot(title='Full Portfolio Performance') my_rs2.cumsum().apply(np.exp).plot() plt.legend(['With Look-Ahead Bias', 'Without Look-Ahead",
"Look-Ahead Bias: ' + str(100 * round(my_rs1.cumsum().apply(np.exp).tolist()[-1], 4)) + '%') print('Without Look-Ahead Bias:",
"+ str(100 * round(my_rs1.cumsum().apply(np.exp).tolist()[-1], 4)) + '%') print('Without Look-Ahead Bias: ' + str(100",
"60) print (f'Lag Performance Statistics for {tickers} ({num_of_years} years):') for lag in lags:",
"/= pos.abs().sum(1).values.reshape(-1,1) fig, ax = plt.subplots(2,1) ma_x.plot(ax=ax[0], title='Individual Moving Average Crossovers and Positions')",
"'Buy and Hold Performnace']) plt.show() print ('-' * 60) print (f'Performance Statistics for",
"* round(my_rs.cumsum().apply(np.exp).tolist()[-1], 4)) + '%') plt.title('Full Portfolio Strategy Performance with Lags') plt.legend(lags, bbox_to_anchor=(1.1,",
"Portfolio Tests # Look-Ahead Bias my_rs1 = (pos*rs).sum(1) my_rs2 = (pos.shift(1)*rs).sum(1) plt.subplots() my_rs1.cumsum().apply(np.exp).plot(title='Full",
"i in range(len(tickers)): print (f'Moving Average Return for {tickers[i]}: ' + str(100 *",
"print ('With Look-Ahead Bias: ' + str(100 * round(my_rs1.cumsum().apply(np.exp).tolist()[-1], 4)) + '%') print('Without",
"1.05)) plt.show() my_rs = (pos.shift(1)*rs) my_rs.cumsum().apply(np.exp).plot(title='Individual Stocks Strategy Performance') plt.show() print ('-' *",
"plt.subplots() my_rs = (pos.shift(1)*rs).sum(1) my_rs.cumsum().apply(np.exp).plot(title='Full Portfolio Strategy Performance') rs.mean(1).cumsum().apply(np.exp).plot() plt.legend(['Portfolio MA Performace', 'Buy",
"prices.rolling(w2).mean() pos = ma_x.apply(np.sign) fig, ax = plt.subplots(2,1) ma_x.plot(ax=ax[0], title=f'{individual_stock} Moving Average Crossovers",
"Signal Lags lags = range(1, 11) lagged_rs = pd.Series(dtype=float, index=lags) print ('-' *",
"my_tcs = tc_pct*delta_pos my_rs1 = (pos.shift(1)*rs).sum(1) my_rs2 = (pos.shift(1)*rs).sum(1) - my_tcs plt.subplots() my_rs1.cumsum().apply(np.exp).plot()",
"for {tickers} ({num_of_years} years):') print ('Moving Average Return: ' + str(100 * round(my_rs.cumsum().apply(np.exp).tolist()[-1],",
"print (f'Performance Statistics for {tickers} ({num_of_years} years):') print ('Without Transaction Costs: ' +",
"my_rs1.cumsum().apply(np.exp).plot() my_rs2.cumsum().apply(np.exp).plot() plt.title('Full Portfolio Performance') plt.legend(['Without Transaction Costs', 'With Transaction Costs']) plt.show() print",
"+ '%') # Portfolio Tests # Look-Ahead Bias my_rs1 = (pos*rs).sum(1) my_rs2 =",
"plt.legend(['With Look-Ahead Bias', 'Without Look-Ahead Bias']) plt.show() print ('-' * 60) print (f'Performance",
"'%') # Signal Lags lags = range(1, 11) lagged_rs = pd.Series(dtype=float, index=lags) print",
"plt.legend(['Without Transaction Costs', 'With Transaction Costs']) plt.show() print ('-' * 60) print (f'Performance",
"pos /= pos.abs().sum(1).values.reshape(-1,1) fig, ax = plt.subplots(2,1) ma_x.plot(ax=ax[0], title='Individual Moving Average Crossovers and",
"Return for {tickers[i]}: ' + str(100 * round(my_rs.cumsum().apply(np.exp)[tickers[i]].tolist()[-1], 4)) + '%') i =",
"range(1, 11) lagged_rs = pd.Series(dtype=float, index=lags) print ('-' * 60) print (f'Lag Performance",
"60) print (f'Performance Statistics for {tickers} ({num_of_years} years):') print ('Without Transaction Costs: '",
"(f'Moving Average Return for {tickers[i]}: ' + str(100 * round(my_rs.cumsum().apply(np.exp)[tickers[i]].tolist()[-1], 4)) + '%')",
"* round(my_rs1.cumsum().apply(np.exp).tolist()[-1], 4)) + '%') print('With Transaction Costs: ' + str(100 * round(my_rs2.cumsum().apply(np.exp).tolist()[-1],",
"in lags: my_rs = (pos.shift(lag)*rs).sum(1) my_rs.cumsum().apply(np.exp).plot() lagged_rs[lag] = my_rs.sum() print (f'Lag {lag} Return:",
"'Without Look-Ahead Bias']) plt.show() print ('-' * 60) print (f'Performance Statistics for {tickers}",
"+ str(100 * round(my_rs2.cumsum().apply(np.exp).tolist()[-1], 4)) + '%') # Signal Lags lags = range(1,",
"Strategy Performance') rs.cumsum().apply(np.exp).plot() plt.legend([f'{individual_stock} MA Performace', f'{individual_stock} Buy and Hold Performnace']) plt.show() print",
"round(my_rs1.cumsum().apply(np.exp).tolist()[-1], 4)) + '%') print('Without Look-Ahead Bias: ' + str(100 * round(my_rs2.cumsum().apply(np.exp).tolist()[-1], 4))",
"'%') # Full Portfolio Strategy prices = yf_prices['Adj Close'] rs = prices.apply(np.log).diff(1).fillna(0) w1",
"('-' * 60) print (f'Performance Statistics for {tickers} ({num_of_years} years):') print ('With Look-Ahead",
"11) lagged_rs = pd.Series(dtype=float, index=lags) print ('-' * 60) print (f'Lag Performance Statistics",
"(f'Performance Statistics for {individual_stock} ({num_of_years} years):') print ('Moving Average Return: ' + str(100",
"print ('-' * 60) print (f'Performance Statistics for {tickers} ({num_of_years} years):') print ('Moving",
"= si.tickers_dow() individual_stock = input(f\"Which of the following stocks would you like to",
"Strategy prices = yf_prices['Adj Close'] rs = prices.apply(np.log).diff(1).fillna(0) w1 = 5 w2 =",
"Strategy Performance with Lags') plt.legend(lags, bbox_to_anchor=(1.1, 0.95)) plt.show() # Transaction Costs tc_pct =",
"Portfolio Strategy prices = yf_prices['Adj Close'] rs = prices.apply(np.log).diff(1).fillna(0) w1 = 5 w2",
"tickers = si.tickers_dow() individual_stock = input(f\"Which of the following stocks would you like",
"import yfinance as yf import matplotlib.pyplot as plt import datetime from yahoo_fin import",
"Performance') plt.show() print ('-' * 60) print (f'Performance Statistics for {num_of_years} years:') for",
"= plt.subplots(2,1) ma_x.plot(ax=ax[0], title=f'{individual_stock} Moving Average Crossovers and Positions') pos.plot(ax=ax[1]) plt.show() my_rs =",
"Performance') my_rs2.cumsum().apply(np.exp).plot() plt.legend(['With Look-Ahead Bias', 'Without Look-Ahead Bias']) plt.show() print ('-' * 60)",
"Return: ' + str(100 * round(my_rs.cumsum().apply(np.exp).tolist()[-1], 4)) + '%') plt.title('Full Portfolio Strategy Performance",
"for {tickers} ({num_of_years} years):') print ('Without Transaction Costs: ' + str(100 * round(my_rs1.cumsum().apply(np.exp).tolist()[-1],",
"('-' * 60) print (f'Performance Statistics for {num_of_years} years:') for i in range(len(tickers)):",
"for i in range(len(tickers)): print (f'Moving Average Return for {tickers[i]}: ' + str(100",
"Crossovers and Positions') pos.plot(ax=ax[1]) plt.show() my_rs = pos.shift(1)*rs plt.subplots() my_rs.cumsum().apply(np.exp).plot(title=f'{individual_stock} MA Strategy Performance')",
"Costs: ' + str(100 * round(my_rs1.cumsum().apply(np.exp).tolist()[-1], 4)) + '%') print('With Transaction Costs: '",
"+ str(100 * round(my_rs.cumsum().apply(np.exp)[tickers[i]].tolist()[-1], 4)) + '%') i = i + 1 plt.subplots()",
"my_rs2.cumsum().apply(np.exp).plot() plt.legend(['With Look-Ahead Bias', 'Without Look-Ahead Bias']) plt.show() print ('-' * 60) print",
"(15, 10) tickers = si.tickers_dow() individual_stock = input(f\"Which of the following stocks would",
"and Positions') ax[0].legend(bbox_to_anchor=(1.1, 1.05)) pos.plot(ax=ax[1]) ax[1].legend(bbox_to_anchor=(1.1, 1.05)) plt.show() my_rs = (pos.shift(1)*rs) my_rs.cumsum().apply(np.exp).plot(title='Individual Stocks",
"ma_x.apply(np.sign) fig, ax = plt.subplots(2,1) ma_x.plot(ax=ax[0], title=f'{individual_stock} Moving Average Crossovers and Positions') pos.plot(ax=ax[1])",
"= (15, 10) tickers = si.tickers_dow() individual_stock = input(f\"Which of the following stocks",
"{lag} Return: ' + str(100 * round(my_rs.cumsum().apply(np.exp).tolist()[-1], 4)) + '%') plt.title('Full Portfolio Strategy",
"lags = range(1, 11) lagged_rs = pd.Series(dtype=float, index=lags) print ('-' * 60) print",
"('-' * 60) print (f'Lag Performance Statistics for {tickers} ({num_of_years} years):') for lag",
"+ '%') i = i + 1 plt.subplots() my_rs = (pos.shift(1)*rs).sum(1) my_rs.cumsum().apply(np.exp).plot(title='Full Portfolio",
"Average Return: ' + str(100 * round(my_rs.cumsum().apply(np.exp).tolist()[-1], 4)) + '%') print('Buy and Hold",
"str(100 * round(rs.mean(1).cumsum().apply(np.exp).tolist()[-1], 4)) + '%') # Portfolio Tests # Look-Ahead Bias my_rs1",
"' + str(100 * round(rs.cumsum().apply(np.exp).tolist()[-1], 4)) + '%') # Full Portfolio Strategy prices",
"round(rs.cumsum().apply(np.exp).tolist()[-1], 4)) + '%') # Full Portfolio Strategy prices = yf_prices['Adj Close'] rs",
"for {individual_stock} ({num_of_years} years):') print ('Moving Average Return: ' + str(100 * round(my_rs.cumsum().apply(np.exp).tolist()[-1],",
"'%') print('Buy and Hold Return: ' + str(100 * round(rs.mean(1).cumsum().apply(np.exp).tolist()[-1], 4)) + '%')",
"Hold Return: ' + str(100 * round(rs.mean(1).cumsum().apply(np.exp).tolist()[-1], 4)) + '%') # Portfolio Tests",
"Costs', 'With Transaction Costs']) plt.show() print ('-' * 60) print (f'Performance Statistics for",
"= datetime.date.today() - datetime.timedelta(days = int(365.25*num_of_years)) yf_prices = yf.download(tickers, start=start) # Individual Stock",
"import stock_info as si plt.rcParams['figure.figsize'] = (15, 10) tickers = si.tickers_dow() individual_stock =",
"'%') # Portfolio Tests # Look-Ahead Bias my_rs1 = (pos*rs).sum(1) my_rs2 = (pos.shift(1)*rs).sum(1)",
"Positions') pos.plot(ax=ax[1]) plt.show() my_rs = pos.shift(1)*rs plt.subplots() my_rs.cumsum().apply(np.exp).plot(title=f'{individual_stock} MA Strategy Performance') rs.cumsum().apply(np.exp).plot() plt.legend([f'{individual_stock}",
"round(my_rs.cumsum().apply(np.exp).tolist()[-1], 4)) + '%') print('Buy and Hold Return: ' + str(100 * round(rs.cumsum().apply(np.exp).tolist()[-1],",
"Performance') rs.mean(1).cumsum().apply(np.exp).plot() plt.legend(['Portfolio MA Performace', 'Buy and Hold Performnace']) plt.show() print ('-' *",
"w2 = 22 ma_x = prices.rolling(w1).mean() - prices.rolling(w2).mean() pos = ma_x.apply(np.sign) pos /=",
"plt.show() print ('-' * 60) print (f'Performance Statistics for {num_of_years} years:') for i",
"4)) + '%') # Signal Lags lags = range(1, 11) lagged_rs = pd.Series(dtype=float,",
"+ '%') # Signal Lags lags = range(1, 11) lagged_rs = pd.Series(dtype=float, index=lags)",
"stock_info as si plt.rcParams['figure.figsize'] = (15, 10) tickers = si.tickers_dow() individual_stock = input(f\"Which",
"(f'Performance Statistics for {tickers} ({num_of_years} years):') print ('With Look-Ahead Bias: ' + str(100",
"plt import datetime from yahoo_fin import stock_info as si plt.rcParams['figure.figsize'] = (15, 10)",
"# Full Portfolio Strategy prices = yf_prices['Adj Close'] rs = prices.apply(np.log).diff(1).fillna(0) w1 =",
"Statistics for {tickers} ({num_of_years} years):') print ('Moving Average Return: ' + str(100 *",
"round(rs.mean(1).cumsum().apply(np.exp).tolist()[-1], 4)) + '%') # Portfolio Tests # Look-Ahead Bias my_rs1 = (pos*rs).sum(1)",
"years):') print ('Moving Average Return: ' + str(100 * round(my_rs.cumsum().apply(np.exp).tolist()[-1], 4)) + '%')",
"plt.show() my_rs = pos.shift(1)*rs plt.subplots() my_rs.cumsum().apply(np.exp).plot(title=f'{individual_stock} MA Strategy Performance') rs.cumsum().apply(np.exp).plot() plt.legend([f'{individual_stock} MA Performace',",
"like to backtest \\n{tickers}\\n:\") num_of_years = 1 start = datetime.date.today() - datetime.timedelta(days =",
"Performance with Lags') plt.legend(lags, bbox_to_anchor=(1.1, 0.95)) plt.show() # Transaction Costs tc_pct = 0.01",
"60) print (f'Performance Statistics for {tickers} ({num_of_years} years):') print ('Moving Average Return: '",
"plt.legend(['Portfolio MA Performace', 'Buy and Hold Performnace']) plt.show() print ('-' * 60) print",
"(f'Performance Statistics for {num_of_years} years:') for i in range(len(tickers)): print (f'Moving Average Return",
"of the following stocks would you like to backtest \\n{tickers}\\n:\") num_of_years = 1",
"{individual_stock} ({num_of_years} years):') print ('Moving Average Return: ' + str(100 * round(my_rs.cumsum().apply(np.exp).tolist()[-1], 4))",
"num_of_years = 1 start = datetime.date.today() - datetime.timedelta(days = int(365.25*num_of_years)) yf_prices = yf.download(tickers,",
"MA Performace', 'Buy and Hold Performnace']) plt.show() print ('-' * 60) print (f'Performance",
"years):') for lag in lags: my_rs = (pos.shift(lag)*rs).sum(1) my_rs.cumsum().apply(np.exp).plot() lagged_rs[lag] = my_rs.sum() print",
"Strategy Performance') plt.show() print ('-' * 60) print (f'Performance Statistics for {num_of_years} years:')",
"i + 1 plt.subplots() my_rs = (pos.shift(1)*rs).sum(1) my_rs.cumsum().apply(np.exp).plot(title='Full Portfolio Strategy Performance') rs.mean(1).cumsum().apply(np.exp).plot() plt.legend(['Portfolio",
"(pos*rs).sum(1) my_rs2 = (pos.shift(1)*rs).sum(1) plt.subplots() my_rs1.cumsum().apply(np.exp).plot(title='Full Portfolio Performance') my_rs2.cumsum().apply(np.exp).plot() plt.legend(['With Look-Ahead Bias', 'Without",
"plt.legend([f'{individual_stock} MA Performace', f'{individual_stock} Buy and Hold Performnace']) plt.show() print (f'Performance Statistics for",
"({num_of_years} years):') print ('Moving Average Return: ' + str(100 * round(my_rs.cumsum().apply(np.exp).tolist()[-1], 4)) +",
"prices = yf_prices['Adj Close'][individual_stock] rs = prices.apply(np.log).diff(1).fillna(0) w1 = 5 w2 = 22",
"print (f'Performance Statistics for {num_of_years} years:') for i in range(len(tickers)): print (f'Moving Average",
"4)) + '%') plt.title('Full Portfolio Strategy Performance with Lags') plt.legend(lags, bbox_to_anchor=(1.1, 0.95)) plt.show()",
"plt.subplots() my_rs1.cumsum().apply(np.exp).plot() my_rs2.cumsum().apply(np.exp).plot() plt.title('Full Portfolio Performance') plt.legend(['Without Transaction Costs', 'With Transaction Costs']) plt.show()",
"prices.rolling(w1).mean() - prices.rolling(w2).mean() pos = ma_x.apply(np.sign) fig, ax = plt.subplots(2,1) ma_x.plot(ax=ax[0], title=f'{individual_stock} Moving",
"= pos.shift(1)*rs plt.subplots() my_rs.cumsum().apply(np.exp).plot(title=f'{individual_stock} MA Strategy Performance') rs.cumsum().apply(np.exp).plot() plt.legend([f'{individual_stock} MA Performace', f'{individual_stock} Buy",
"Lags') plt.legend(lags, bbox_to_anchor=(1.1, 0.95)) plt.show() # Transaction Costs tc_pct = 0.01 delta_pos =",
"Stocks Strategy Performance') plt.show() print ('-' * 60) print (f'Performance Statistics for {num_of_years}",
"= prices.apply(np.log).diff(1).fillna(0) w1 = 5 w2 = 22 ma_x = prices.rolling(w1).mean() - prices.rolling(w2).mean()",
"Strategy Performance') rs.mean(1).cumsum().apply(np.exp).plot() plt.legend(['Portfolio MA Performace', 'Buy and Hold Performnace']) plt.show() print ('-'",
"Lags lags = range(1, 11) lagged_rs = pd.Series(dtype=float, index=lags) print ('-' * 60)",
"individual_stock = input(f\"Which of the following stocks would you like to backtest \\n{tickers}\\n:\")",
"print('Buy and Hold Return: ' + str(100 * round(rs.cumsum().apply(np.exp).tolist()[-1], 4)) + '%') #",
"numpy as np import pandas as pd import yfinance as yf import matplotlib.pyplot",
"pandas as pd import yfinance as yf import matplotlib.pyplot as plt import datetime",
"pos.shift(1)*rs plt.subplots() my_rs.cumsum().apply(np.exp).plot(title=f'{individual_stock} MA Strategy Performance') rs.cumsum().apply(np.exp).plot() plt.legend([f'{individual_stock} MA Performace', f'{individual_stock} Buy and",
"index=lags) print ('-' * 60) print (f'Lag Performance Statistics for {tickers} ({num_of_years} years):')",
"({num_of_years} years):') print ('With Look-Ahead Bias: ' + str(100 * round(my_rs1.cumsum().apply(np.exp).tolist()[-1], 4)) +",
"lagged_rs = pd.Series(dtype=float, index=lags) print ('-' * 60) print (f'Lag Performance Statistics for",
"# Individual Stock Strategy prices = yf_prices['Adj Close'][individual_stock] rs = prices.apply(np.log).diff(1).fillna(0) w1 =",
"print (f'Lag {lag} Return: ' + str(100 * round(my_rs.cumsum().apply(np.exp).tolist()[-1], 4)) + '%') plt.title('Full",
"rs.cumsum().apply(np.exp).plot() plt.legend([f'{individual_stock} MA Performace', f'{individual_stock} Buy and Hold Performnace']) plt.show() print (f'Performance Statistics",
"as si plt.rcParams['figure.figsize'] = (15, 10) tickers = si.tickers_dow() individual_stock = input(f\"Which of",
"Hold Performnace']) plt.show() print (f'Performance Statistics for {individual_stock} ({num_of_years} years):') print ('Moving Average",
"Statistics for {individual_stock} ({num_of_years} years):') print ('Moving Average Return: ' + str(100 *",
"plt.subplots() my_rs1.cumsum().apply(np.exp).plot(title='Full Portfolio Performance') my_rs2.cumsum().apply(np.exp).plot() plt.legend(['With Look-Ahead Bias', 'Without Look-Ahead Bias']) plt.show() print",
"str(100 * round(my_rs.cumsum().apply(np.exp).tolist()[-1], 4)) + '%') plt.title('Full Portfolio Strategy Performance with Lags') plt.legend(lags,",
"'%') plt.title('Full Portfolio Strategy Performance with Lags') plt.legend(lags, bbox_to_anchor=(1.1, 0.95)) plt.show() # Transaction",
"np import pandas as pd import yfinance as yf import matplotlib.pyplot as plt",
"print ('-' * 60) print (f'Lag Performance Statistics for {tickers} ({num_of_years} years):') for",
"prices.rolling(w2).mean() pos = ma_x.apply(np.sign) pos /= pos.abs().sum(1).values.reshape(-1,1) fig, ax = plt.subplots(2,1) ma_x.plot(ax=ax[0], title='Individual",
"+ str(100 * round(my_rs.cumsum().apply(np.exp).tolist()[-1], 4)) + '%') print('Buy and Hold Return: ' +",
"pd import yfinance as yf import matplotlib.pyplot as plt import datetime from yahoo_fin",
"+ str(100 * round(rs.mean(1).cumsum().apply(np.exp).tolist()[-1], 4)) + '%') # Portfolio Tests # Look-Ahead Bias",
"import matplotlib.pyplot as plt import datetime from yahoo_fin import stock_info as si plt.rcParams['figure.figsize']",
"fig, ax = plt.subplots(2,1) ma_x.plot(ax=ax[0], title='Individual Moving Average Crossovers and Positions') ax[0].legend(bbox_to_anchor=(1.1, 1.05))",
"* round(rs.mean(1).cumsum().apply(np.exp).tolist()[-1], 4)) + '%') # Portfolio Tests # Look-Ahead Bias my_rs1 =",
"Average Crossovers and Positions') ax[0].legend(bbox_to_anchor=(1.1, 1.05)) pos.plot(ax=ax[1]) ax[1].legend(bbox_to_anchor=(1.1, 1.05)) plt.show() my_rs = (pos.shift(1)*rs)",
"fig, ax = plt.subplots(2,1) ma_x.plot(ax=ax[0], title=f'{individual_stock} Moving Average Crossovers and Positions') pos.plot(ax=ax[1]) plt.show()",
"{tickers[i]}: ' + str(100 * round(my_rs.cumsum().apply(np.exp)[tickers[i]].tolist()[-1], 4)) + '%') i = i +",
"('-' * 60) print (f'Performance Statistics for {tickers} ({num_of_years} years):') print ('Moving Average",
"prices = yf_prices['Adj Close'] rs = prices.apply(np.log).diff(1).fillna(0) w1 = 5 w2 = 22",
"= (pos.shift(1)*rs).sum(1) my_rs.cumsum().apply(np.exp).plot(title='Full Portfolio Strategy Performance') rs.mean(1).cumsum().apply(np.exp).plot() plt.legend(['Portfolio MA Performace', 'Buy and Hold",
"ax = plt.subplots(2,1) ma_x.plot(ax=ax[0], title='Individual Moving Average Crossovers and Positions') ax[0].legend(bbox_to_anchor=(1.1, 1.05)) pos.plot(ax=ax[1])",
"Average Crossovers and Positions') pos.plot(ax=ax[1]) plt.show() my_rs = pos.shift(1)*rs plt.subplots() my_rs.cumsum().apply(np.exp).plot(title=f'{individual_stock} MA Strategy",
"+ '%') print('Buy and Hold Return: ' + str(100 * round(rs.cumsum().apply(np.exp).tolist()[-1], 4)) +",
"yf_prices['Adj Close'] rs = prices.apply(np.log).diff(1).fillna(0) w1 = 5 w2 = 22 ma_x =",
"my_rs2 = (pos.shift(1)*rs).sum(1) - my_tcs plt.subplots() my_rs1.cumsum().apply(np.exp).plot() my_rs2.cumsum().apply(np.exp).plot() plt.title('Full Portfolio Performance') plt.legend(['Without Transaction",
"(pos.shift(1)*rs) my_rs.cumsum().apply(np.exp).plot(title='Individual Stocks Strategy Performance') plt.show() print ('-' * 60) print (f'Performance Statistics",
"years):') print ('With Look-Ahead Bias: ' + str(100 * round(my_rs1.cumsum().apply(np.exp).tolist()[-1], 4)) + '%')",
"- datetime.timedelta(days = int(365.25*num_of_years)) yf_prices = yf.download(tickers, start=start) # Individual Stock Strategy prices",
"4)) + '%') i = i + 1 plt.subplots() my_rs = (pos.shift(1)*rs).sum(1) my_rs.cumsum().apply(np.exp).plot(title='Full",
"datetime.timedelta(days = int(365.25*num_of_years)) yf_prices = yf.download(tickers, start=start) # Individual Stock Strategy prices =",
"following stocks would you like to backtest \\n{tickers}\\n:\") num_of_years = 1 start =",
"* 60) print (f'Lag Performance Statistics for {tickers} ({num_of_years} years):') for lag in",
"= (pos*rs).sum(1) my_rs2 = (pos.shift(1)*rs).sum(1) plt.subplots() my_rs1.cumsum().apply(np.exp).plot(title='Full Portfolio Performance') my_rs2.cumsum().apply(np.exp).plot() plt.legend(['With Look-Ahead Bias',",
"Bias', 'Without Look-Ahead Bias']) plt.show() print ('-' * 60) print (f'Performance Statistics for",
"pos.plot(ax=ax[1]) plt.show() my_rs = pos.shift(1)*rs plt.subplots() my_rs.cumsum().apply(np.exp).plot(title=f'{individual_stock} MA Strategy Performance') rs.cumsum().apply(np.exp).plot() plt.legend([f'{individual_stock} MA",
"pos.diff(1).abs().sum(1) my_tcs = tc_pct*delta_pos my_rs1 = (pos.shift(1)*rs).sum(1) my_rs2 = (pos.shift(1)*rs).sum(1) - my_tcs plt.subplots()",
"Stock Strategy prices = yf_prices['Adj Close'][individual_stock] rs = prices.apply(np.log).diff(1).fillna(0) w1 = 5 w2",
"plt.subplots(2,1) ma_x.plot(ax=ax[0], title='Individual Moving Average Crossovers and Positions') ax[0].legend(bbox_to_anchor=(1.1, 1.05)) pos.plot(ax=ax[1]) ax[1].legend(bbox_to_anchor=(1.1, 1.05))",
"= range(1, 11) lagged_rs = pd.Series(dtype=float, index=lags) print ('-' * 60) print (f'Lag",
"+ str(100 * round(my_rs1.cumsum().apply(np.exp).tolist()[-1], 4)) + '%') print('With Transaction Costs: ' + str(100",
"ma_x = prices.rolling(w1).mean() - prices.rolling(w2).mean() pos = ma_x.apply(np.sign) pos /= pos.abs().sum(1).values.reshape(-1,1) fig, ax",
"print ('Moving Average Return: ' + str(100 * round(my_rs.cumsum().apply(np.exp).tolist()[-1], 4)) + '%') print('Buy",
"MA Performace', f'{individual_stock} Buy and Hold Performnace']) plt.show() print (f'Performance Statistics for {individual_stock}",
"Close'] rs = prices.apply(np.log).diff(1).fillna(0) w1 = 5 w2 = 22 ma_x = prices.rolling(w1).mean()",
"print (f'Moving Average Return for {tickers[i]}: ' + str(100 * round(my_rs.cumsum().apply(np.exp)[tickers[i]].tolist()[-1], 4)) +",
"- my_tcs plt.subplots() my_rs1.cumsum().apply(np.exp).plot() my_rs2.cumsum().apply(np.exp).plot() plt.title('Full Portfolio Performance') plt.legend(['Without Transaction Costs', 'With Transaction",
"= input(f\"Which of the following stocks would you like to backtest \\n{tickers}\\n:\") num_of_years",
"datetime from yahoo_fin import stock_info as si plt.rcParams['figure.figsize'] = (15, 10) tickers =",
"('Moving Average Return: ' + str(100 * round(my_rs.cumsum().apply(np.exp).tolist()[-1], 4)) + '%') print('Buy and",
"10) tickers = si.tickers_dow() individual_stock = input(f\"Which of the following stocks would you",
"title=f'{individual_stock} Moving Average Crossovers and Positions') pos.plot(ax=ax[1]) plt.show() my_rs = pos.shift(1)*rs plt.subplots() my_rs.cumsum().apply(np.exp).plot(title=f'{individual_stock}",
"start=start) # Individual Stock Strategy prices = yf_prices['Adj Close'][individual_stock] rs = prices.apply(np.log).diff(1).fillna(0) w1",
"Close'][individual_stock] rs = prices.apply(np.log).diff(1).fillna(0) w1 = 5 w2 = 22 ma_x = prices.rolling(w1).mean()",
"my_rs.cumsum().apply(np.exp).plot(title=f'{individual_stock} MA Strategy Performance') rs.cumsum().apply(np.exp).plot() plt.legend([f'{individual_stock} MA Performace', f'{individual_stock} Buy and Hold Performnace'])",
"prices.rolling(w1).mean() - prices.rolling(w2).mean() pos = ma_x.apply(np.sign) pos /= pos.abs().sum(1).values.reshape(-1,1) fig, ax = plt.subplots(2,1)",
"and Hold Performnace']) plt.show() print ('-' * 60) print (f'Performance Statistics for {tickers}",
"print (f'Lag Performance Statistics for {tickers} ({num_of_years} years):') for lag in lags: my_rs",
"delta_pos = pos.diff(1).abs().sum(1) my_tcs = tc_pct*delta_pos my_rs1 = (pos.shift(1)*rs).sum(1) my_rs2 = (pos.shift(1)*rs).sum(1) -",
"('-' * 60) print (f'Performance Statistics for {tickers} ({num_of_years} years):') print ('Without Transaction",
"pos = ma_x.apply(np.sign) pos /= pos.abs().sum(1).values.reshape(-1,1) fig, ax = plt.subplots(2,1) ma_x.plot(ax=ax[0], title='Individual Moving",
"4)) + '%') print('Buy and Hold Return: ' + str(100 * round(rs.cumsum().apply(np.exp).tolist()[-1], 4))",
"for {tickers} ({num_of_years} years):') for lag in lags: my_rs = (pos.shift(lag)*rs).sum(1) my_rs.cumsum().apply(np.exp).plot() lagged_rs[lag]",
"Buy and Hold Performnace']) plt.show() print (f'Performance Statistics for {individual_stock} ({num_of_years} years):') print",
"tc_pct*delta_pos my_rs1 = (pos.shift(1)*rs).sum(1) my_rs2 = (pos.shift(1)*rs).sum(1) - my_tcs plt.subplots() my_rs1.cumsum().apply(np.exp).plot() my_rs2.cumsum().apply(np.exp).plot() plt.title('Full",
"Performace', f'{individual_stock} Buy and Hold Performnace']) plt.show() print (f'Performance Statistics for {individual_stock} ({num_of_years}",
"+ '%') print('Buy and Hold Return: ' + str(100 * round(rs.mean(1).cumsum().apply(np.exp).tolist()[-1], 4)) +",
"+ '%') # Full Portfolio Strategy prices = yf_prices['Adj Close'] rs = prices.apply(np.log).diff(1).fillna(0)",
"{tickers} ({num_of_years} years):') print ('With Look-Ahead Bias: ' + str(100 * round(my_rs1.cumsum().apply(np.exp).tolist()[-1], 4))",
"= yf_prices['Adj Close'] rs = prices.apply(np.log).diff(1).fillna(0) w1 = 5 w2 = 22 ma_x",
"print (f'Performance Statistics for {tickers} ({num_of_years} years):') print ('Moving Average Return: ' +",
"+ '%') print('Without Look-Ahead Bias: ' + str(100 * round(my_rs2.cumsum().apply(np.exp).tolist()[-1], 4)) + '%')",
"Tests # Look-Ahead Bias my_rs1 = (pos*rs).sum(1) my_rs2 = (pos.shift(1)*rs).sum(1) plt.subplots() my_rs1.cumsum().apply(np.exp).plot(title='Full Portfolio",
"' + str(100 * round(my_rs2.cumsum().apply(np.exp).tolist()[-1], 4)) + '%') # Signal Lags lags =",
"= (pos.shift(1)*rs).sum(1) - my_tcs plt.subplots() my_rs1.cumsum().apply(np.exp).plot() my_rs2.cumsum().apply(np.exp).plot() plt.title('Full Portfolio Performance') plt.legend(['Without Transaction Costs',",
"plt.show() print (f'Performance Statistics for {individual_stock} ({num_of_years} years):') print ('Moving Average Return: '",
"60) print (f'Performance Statistics for {tickers} ({num_of_years} years):') print ('With Look-Ahead Bias: '",
"years:') for i in range(len(tickers)): print (f'Moving Average Return for {tickers[i]}: ' +",
"1 start = datetime.date.today() - datetime.timedelta(days = int(365.25*num_of_years)) yf_prices = yf.download(tickers, start=start) #",
"my_rs = (pos.shift(1)*rs) my_rs.cumsum().apply(np.exp).plot(title='Individual Stocks Strategy Performance') plt.show() print ('-' * 60) print",
"my_rs1 = (pos*rs).sum(1) my_rs2 = (pos.shift(1)*rs).sum(1) plt.subplots() my_rs1.cumsum().apply(np.exp).plot(title='Full Portfolio Performance') my_rs2.cumsum().apply(np.exp).plot() plt.legend(['With Look-Ahead",
"to backtest \\n{tickers}\\n:\") num_of_years = 1 start = datetime.date.today() - datetime.timedelta(days = int(365.25*num_of_years))",
"= 22 ma_x = prices.rolling(w1).mean() - prices.rolling(w2).mean() pos = ma_x.apply(np.sign) fig, ax =",
"plt.legend(lags, bbox_to_anchor=(1.1, 0.95)) plt.show() # Transaction Costs tc_pct = 0.01 delta_pos = pos.diff(1).abs().sum(1)",
"= prices.rolling(w1).mean() - prices.rolling(w2).mean() pos = ma_x.apply(np.sign) fig, ax = plt.subplots(2,1) ma_x.plot(ax=ax[0], title=f'{individual_stock}",
"Bias']) plt.show() print ('-' * 60) print (f'Performance Statistics for {tickers} ({num_of_years} years):')",
"rs = prices.apply(np.log).diff(1).fillna(0) w1 = 5 w2 = 22 ma_x = prices.rolling(w1).mean() -",
"yf import matplotlib.pyplot as plt import datetime from yahoo_fin import stock_info as si",
"Return: ' + str(100 * round(rs.cumsum().apply(np.exp).tolist()[-1], 4)) + '%') # Full Portfolio Strategy",
"Hold Performnace']) plt.show() print ('-' * 60) print (f'Performance Statistics for {tickers} ({num_of_years}",
"pos.abs().sum(1).values.reshape(-1,1) fig, ax = plt.subplots(2,1) ma_x.plot(ax=ax[0], title='Individual Moving Average Crossovers and Positions') ax[0].legend(bbox_to_anchor=(1.1,",
"str(100 * round(rs.cumsum().apply(np.exp).tolist()[-1], 4)) + '%') # Full Portfolio Strategy prices = yf_prices['Adj",
"plt.show() print ('-' * 60) print (f'Performance Statistics for {tickers} ({num_of_years} years):') print",
"Costs']) plt.show() print ('-' * 60) print (f'Performance Statistics for {tickers} ({num_of_years} years):')",
"* round(my_rs2.cumsum().apply(np.exp).tolist()[-1], 4)) + '%') # Signal Lags lags = range(1, 11) lagged_rs",
"for lag in lags: my_rs = (pos.shift(lag)*rs).sum(1) my_rs.cumsum().apply(np.exp).plot() lagged_rs[lag] = my_rs.sum() print (f'Lag",
"yf.download(tickers, start=start) # Individual Stock Strategy prices = yf_prices['Adj Close'][individual_stock] rs = prices.apply(np.log).diff(1).fillna(0)",
"+ 1 plt.subplots() my_rs = (pos.shift(1)*rs).sum(1) my_rs.cumsum().apply(np.exp).plot(title='Full Portfolio Strategy Performance') rs.mean(1).cumsum().apply(np.exp).plot() plt.legend(['Portfolio MA",
"# Signal Lags lags = range(1, 11) lagged_rs = pd.Series(dtype=float, index=lags) print ('-'",
"(pos.shift(1)*rs).sum(1) my_rs.cumsum().apply(np.exp).plot(title='Full Portfolio Strategy Performance') rs.mean(1).cumsum().apply(np.exp).plot() plt.legend(['Portfolio MA Performace', 'Buy and Hold Performnace'])",
"Performnace']) plt.show() print (f'Performance Statistics for {individual_stock} ({num_of_years} years):') print ('Moving Average Return:",
"import datetime from yahoo_fin import stock_info as si plt.rcParams['figure.figsize'] = (15, 10) tickers",
"and Positions') pos.plot(ax=ax[1]) plt.show() my_rs = pos.shift(1)*rs plt.subplots() my_rs.cumsum().apply(np.exp).plot(title=f'{individual_stock} MA Strategy Performance') rs.cumsum().apply(np.exp).plot()",
"Hold Return: ' + str(100 * round(rs.cumsum().apply(np.exp).tolist()[-1], 4)) + '%') # Full Portfolio",
"60) print (f'Performance Statistics for {num_of_years} years:') for i in range(len(tickers)): print (f'Moving",
"ax[1].legend(bbox_to_anchor=(1.1, 1.05)) plt.show() my_rs = (pos.shift(1)*rs) my_rs.cumsum().apply(np.exp).plot(title='Individual Stocks Strategy Performance') plt.show() print ('-'",
"my_tcs plt.subplots() my_rs1.cumsum().apply(np.exp).plot() my_rs2.cumsum().apply(np.exp).plot() plt.title('Full Portfolio Performance') plt.legend(['Without Transaction Costs', 'With Transaction Costs'])",
"4)) + '%') print('With Transaction Costs: ' + str(100 * round(my_rs2.cumsum().apply(np.exp).tolist()[-1], 4)) +",
"- prices.rolling(w2).mean() pos = ma_x.apply(np.sign) pos /= pos.abs().sum(1).values.reshape(-1,1) fig, ax = plt.subplots(2,1) ma_x.plot(ax=ax[0],",
"prices.apply(np.log).diff(1).fillna(0) w1 = 5 w2 = 22 ma_x = prices.rolling(w1).mean() - prices.rolling(w2).mean() pos",
"plt.title('Full Portfolio Performance') plt.legend(['Without Transaction Costs', 'With Transaction Costs']) plt.show() print ('-' *",
"Portfolio Performance') plt.legend(['Without Transaction Costs', 'With Transaction Costs']) plt.show() print ('-' * 60)",
"f'{individual_stock} Buy and Hold Performnace']) plt.show() print (f'Performance Statistics for {individual_stock} ({num_of_years} years):')",
"plt.show() # Transaction Costs tc_pct = 0.01 delta_pos = pos.diff(1).abs().sum(1) my_tcs = tc_pct*delta_pos",
"the following stocks would you like to backtest \\n{tickers}\\n:\") num_of_years = 1 start",
"Crossovers and Positions') ax[0].legend(bbox_to_anchor=(1.1, 1.05)) pos.plot(ax=ax[1]) ax[1].legend(bbox_to_anchor=(1.1, 1.05)) plt.show() my_rs = (pos.shift(1)*rs) my_rs.cumsum().apply(np.exp).plot(title='Individual",
"plt.show() my_rs = (pos.shift(1)*rs) my_rs.cumsum().apply(np.exp).plot(title='Individual Stocks Strategy Performance') plt.show() print ('-' * 60)",
"4)) + '%') print('Buy and Hold Return: ' + str(100 * round(rs.mean(1).cumsum().apply(np.exp).tolist()[-1], 4))",
"and Hold Return: ' + str(100 * round(rs.cumsum().apply(np.exp).tolist()[-1], 4)) + '%') # Full",
"Performace', 'Buy and Hold Performnace']) plt.show() print ('-' * 60) print (f'Performance Statistics",
"lag in lags: my_rs = (pos.shift(lag)*rs).sum(1) my_rs.cumsum().apply(np.exp).plot() lagged_rs[lag] = my_rs.sum() print (f'Lag {lag}",
"= ma_x.apply(np.sign) fig, ax = plt.subplots(2,1) ma_x.plot(ax=ax[0], title=f'{individual_stock} Moving Average Crossovers and Positions')",
"= (pos.shift(1)*rs).sum(1) plt.subplots() my_rs1.cumsum().apply(np.exp).plot(title='Full Portfolio Performance') my_rs2.cumsum().apply(np.exp).plot() plt.legend(['With Look-Ahead Bias', 'Without Look-Ahead Bias'])",
"22 ma_x = prices.rolling(w1).mean() - prices.rolling(w2).mean() pos = ma_x.apply(np.sign) pos /= pos.abs().sum(1).values.reshape(-1,1) fig,",
"# Transaction Costs tc_pct = 0.01 delta_pos = pos.diff(1).abs().sum(1) my_tcs = tc_pct*delta_pos my_rs1",
"= pd.Series(dtype=float, index=lags) print ('-' * 60) print (f'Lag Performance Statistics for {tickers}",
"Bias: ' + str(100 * round(my_rs2.cumsum().apply(np.exp).tolist()[-1], 4)) + '%') # Signal Lags lags",
"* 60) print (f'Performance Statistics for {num_of_years} years:') for i in range(len(tickers)): print",
"Look-Ahead Bias my_rs1 = (pos*rs).sum(1) my_rs2 = (pos.shift(1)*rs).sum(1) plt.subplots() my_rs1.cumsum().apply(np.exp).plot(title='Full Portfolio Performance') my_rs2.cumsum().apply(np.exp).plot()",
"Performance') plt.legend(['Without Transaction Costs', 'With Transaction Costs']) plt.show() print ('-' * 60) print",
"* round(my_rs.cumsum().apply(np.exp)[tickers[i]].tolist()[-1], 4)) + '%') i = i + 1 plt.subplots() my_rs =",
"Individual Stock Strategy prices = yf_prices['Adj Close'][individual_stock] rs = prices.apply(np.log).diff(1).fillna(0) w1 = 5",
"Transaction Costs: ' + str(100 * round(my_rs1.cumsum().apply(np.exp).tolist()[-1], 4)) + '%') print('With Transaction Costs:",
"Portfolio Performance') my_rs2.cumsum().apply(np.exp).plot() plt.legend(['With Look-Ahead Bias', 'Without Look-Ahead Bias']) plt.show() print ('-' *",
"str(100 * round(my_rs.cumsum().apply(np.exp).tolist()[-1], 4)) + '%') print('Buy and Hold Return: ' + str(100",
"ax[0].legend(bbox_to_anchor=(1.1, 1.05)) pos.plot(ax=ax[1]) ax[1].legend(bbox_to_anchor=(1.1, 1.05)) plt.show() my_rs = (pos.shift(1)*rs) my_rs.cumsum().apply(np.exp).plot(title='Individual Stocks Strategy Performance')",
"from yahoo_fin import stock_info as si plt.rcParams['figure.figsize'] = (15, 10) tickers = si.tickers_dow()",
"str(100 * round(my_rs1.cumsum().apply(np.exp).tolist()[-1], 4)) + '%') print('Without Look-Ahead Bias: ' + str(100 *",
"4)) + '%') print('Without Look-Ahead Bias: ' + str(100 * round(my_rs2.cumsum().apply(np.exp).tolist()[-1], 4)) +",
"i = i + 1 plt.subplots() my_rs = (pos.shift(1)*rs).sum(1) my_rs.cumsum().apply(np.exp).plot(title='Full Portfolio Strategy Performance')",
"plt.subplots(2,1) ma_x.plot(ax=ax[0], title=f'{individual_stock} Moving Average Crossovers and Positions') pos.plot(ax=ax[1]) plt.show() my_rs = pos.shift(1)*rs"
] |
[
"coding: utf-8 -*- \"\"\" Created on Tue May 22 14:07:42 2018 @author: HORSE",
"May 22 14:07:42 2018 @author: HORSE \"\"\" import logging import logging.handlers import os",
"os def ARLogger(log_filename = 'log.txt'): # if not os.path.exists('logs'): # os.makedirs('logs') fmt =",
"-*- \"\"\" Created on Tue May 22 14:07:42 2018 @author: HORSE \"\"\" import",
"logging import logging.handlers import os def ARLogger(log_filename = 'log.txt'): # if not os.path.exists('logs'):",
"'log.txt'): # if not os.path.exists('logs'): # os.makedirs('logs') fmt = '%(asctime)s %(levelname)s %(message)s' datefmt",
"on Tue May 22 14:07:42 2018 @author: HORSE \"\"\" import logging import logging.handlers",
"\"\"\" Created on Tue May 22 14:07:42 2018 @author: HORSE \"\"\" import logging",
"14:07:42 2018 @author: HORSE \"\"\" import logging import logging.handlers import os def ARLogger(log_filename",
"# os.makedirs('logs') fmt = '%(asctime)s %(levelname)s %(message)s' datefmt = '%Y-%m-%d %H:%M:%S' ar_logger =",
"Tue May 22 14:07:42 2018 @author: HORSE \"\"\" import logging import logging.handlers import",
"%(message)s' datefmt = '%Y-%m-%d %H:%M:%S' ar_logger = logging.getLogger('ARLogger') ar_logger.setLevel(logging.INFO) handler = logging.handlers.RotatingFileHandler( log_filename,",
"Created on Tue May 22 14:07:42 2018 @author: HORSE \"\"\" import logging import",
"HORSE \"\"\" import logging import logging.handlers import os def ARLogger(log_filename = 'log.txt'): #",
"# -*- coding: utf-8 -*- \"\"\" Created on Tue May 22 14:07:42 2018",
"'%Y-%m-%d %H:%M:%S' ar_logger = logging.getLogger('ARLogger') ar_logger.setLevel(logging.INFO) handler = logging.handlers.RotatingFileHandler( log_filename, maxBytes=10000*4, backupCount=5) formatter",
"= '%(asctime)s %(levelname)s %(message)s' datefmt = '%Y-%m-%d %H:%M:%S' ar_logger = logging.getLogger('ARLogger') ar_logger.setLevel(logging.INFO) handler",
"logging.handlers import os def ARLogger(log_filename = 'log.txt'): # if not os.path.exists('logs'): # os.makedirs('logs')",
"utf-8 -*- \"\"\" Created on Tue May 22 14:07:42 2018 @author: HORSE \"\"\"",
"ar_logger = logging.getLogger('ARLogger') ar_logger.setLevel(logging.INFO) handler = logging.handlers.RotatingFileHandler( log_filename, maxBytes=10000*4, backupCount=5) formatter = logging.Formatter(fmt,",
"= 'log.txt'): # if not os.path.exists('logs'): # os.makedirs('logs') fmt = '%(asctime)s %(levelname)s %(message)s'",
"-*- coding: utf-8 -*- \"\"\" Created on Tue May 22 14:07:42 2018 @author:",
"os.makedirs('logs') fmt = '%(asctime)s %(levelname)s %(message)s' datefmt = '%Y-%m-%d %H:%M:%S' ar_logger = logging.getLogger('ARLogger')",
"%(levelname)s %(message)s' datefmt = '%Y-%m-%d %H:%M:%S' ar_logger = logging.getLogger('ARLogger') ar_logger.setLevel(logging.INFO) handler = logging.handlers.RotatingFileHandler(",
"ARLogger(log_filename = 'log.txt'): # if not os.path.exists('logs'): # os.makedirs('logs') fmt = '%(asctime)s %(levelname)s",
"import logging import logging.handlers import os def ARLogger(log_filename = 'log.txt'): # if not",
"%H:%M:%S' ar_logger = logging.getLogger('ARLogger') ar_logger.setLevel(logging.INFO) handler = logging.handlers.RotatingFileHandler( log_filename, maxBytes=10000*4, backupCount=5) formatter =",
"if not os.path.exists('logs'): # os.makedirs('logs') fmt = '%(asctime)s %(levelname)s %(message)s' datefmt = '%Y-%m-%d",
"'%(asctime)s %(levelname)s %(message)s' datefmt = '%Y-%m-%d %H:%M:%S' ar_logger = logging.getLogger('ARLogger') ar_logger.setLevel(logging.INFO) handler =",
"= logging.getLogger('ARLogger') ar_logger.setLevel(logging.INFO) handler = logging.handlers.RotatingFileHandler( log_filename, maxBytes=10000*4, backupCount=5) formatter = logging.Formatter(fmt, datefmt)",
"datefmt = '%Y-%m-%d %H:%M:%S' ar_logger = logging.getLogger('ARLogger') ar_logger.setLevel(logging.INFO) handler = logging.handlers.RotatingFileHandler( log_filename, maxBytes=10000*4,",
"= '%Y-%m-%d %H:%M:%S' ar_logger = logging.getLogger('ARLogger') ar_logger.setLevel(logging.INFO) handler = logging.handlers.RotatingFileHandler( log_filename, maxBytes=10000*4, backupCount=5)",
"import os def ARLogger(log_filename = 'log.txt'): # if not os.path.exists('logs'): # os.makedirs('logs') fmt",
"import logging.handlers import os def ARLogger(log_filename = 'log.txt'): # if not os.path.exists('logs'): #",
"\"\"\" import logging import logging.handlers import os def ARLogger(log_filename = 'log.txt'): # if",
"logging.getLogger('ARLogger') ar_logger.setLevel(logging.INFO) handler = logging.handlers.RotatingFileHandler( log_filename, maxBytes=10000*4, backupCount=5) formatter = logging.Formatter(fmt, datefmt) handler.setFormatter(formatter)",
"not os.path.exists('logs'): # os.makedirs('logs') fmt = '%(asctime)s %(levelname)s %(message)s' datefmt = '%Y-%m-%d %H:%M:%S'",
"= logging.handlers.RotatingFileHandler( log_filename, maxBytes=10000*4, backupCount=5) formatter = logging.Formatter(fmt, datefmt) handler.setFormatter(formatter) ar_logger.addHandler(handler) return ar_logger",
"handler = logging.handlers.RotatingFileHandler( log_filename, maxBytes=10000*4, backupCount=5) formatter = logging.Formatter(fmt, datefmt) handler.setFormatter(formatter) ar_logger.addHandler(handler) return",
"@author: HORSE \"\"\" import logging import logging.handlers import os def ARLogger(log_filename = 'log.txt'):",
"def ARLogger(log_filename = 'log.txt'): # if not os.path.exists('logs'): # os.makedirs('logs') fmt = '%(asctime)s",
"2018 @author: HORSE \"\"\" import logging import logging.handlers import os def ARLogger(log_filename =",
"os.path.exists('logs'): # os.makedirs('logs') fmt = '%(asctime)s %(levelname)s %(message)s' datefmt = '%Y-%m-%d %H:%M:%S' ar_logger",
"ar_logger.setLevel(logging.INFO) handler = logging.handlers.RotatingFileHandler( log_filename, maxBytes=10000*4, backupCount=5) formatter = logging.Formatter(fmt, datefmt) handler.setFormatter(formatter) ar_logger.addHandler(handler)",
"# if not os.path.exists('logs'): # os.makedirs('logs') fmt = '%(asctime)s %(levelname)s %(message)s' datefmt =",
"22 14:07:42 2018 @author: HORSE \"\"\" import logging import logging.handlers import os def",
"fmt = '%(asctime)s %(levelname)s %(message)s' datefmt = '%Y-%m-%d %H:%M:%S' ar_logger = logging.getLogger('ARLogger') ar_logger.setLevel(logging.INFO)"
] |
[
"False for i in range(SERVER_THREAD_COUNT): self.queue.put(None) w.join() def main(): pinger = PingerDaemon() pinger.run()",
"while not self.shuttingdown: try: for p in ping_list: if 'targets' in p and",
"try: targets = yaml.load(open(PING_FILE)) except Exception as e: LOG.error('Failed to load Ping targets:",
"interval=1, timeout=5): if timeout <= count * interval: timeout = count * interval",
"'Node responded to ping in %s ms avg (> %s ms)' % (avg,",
"'Ping' correlate = _PING_ALERTS raw_data = stdout try: self.api.send_alert( resource=resource, event=event, correlate=correlate, group=group,",
"import time import subprocess import threading import Queue import re import logging import",
"= p['environment'] service = p['service'] retries = p.get('retries', PING_MAX_RETRIES) self.queue.put((environment, service, target, retries,",
"Defaults resource += ':icmp' group = 'Ping' correlate = _PING_ALERTS raw_data = stdout",
"= Client() # Initialiase ping targets ping_list = init_targets() # Start worker threads",
"if 'targets' in p and p['targets']: for target in p['targets']: environment = p['environment']",
"else: rc, rtt, loss, stdout = self.pinger(resource, count=5, timeout=PING_MAX_TIMEOUT) if rc != PING_OK",
"else: cmd = \"ping -q -c %s -i %s -w %s %s\" %",
"from alertaclient.api import Client __version__ = '3.3.0' LOG = logging.getLogger('alerta.pinger') LOG.setLevel(logging.DEBUG) LOG.addHandler(logging.StreamHandler()) PING_FILE",
"def __init__(self): self.shuttingdown = False def run(self): self.running = True # Create internal",
"(> %s ms)' % (avg, PING_SLOW_CRITICAL) elif avg > PING_SLOW_WARNING: event = 'PingSlow'",
"(count, interval, timeout, node) else: cmd = \"ping -q -c %s -i %s",
"broker def run(self): while True: LOG.debug('Waiting on input queue...') item = self.queue.get() if",
"LOG.debug('Waiting on input queue...') item = self.queue.get() if not item: LOG.info('%s is shutting",
"time.sleep(LOOP_EVERY) LOG.info('Ping queue length is %d', self.queue.qsize()) except (KeyboardInterrupt, SystemExit): self.shuttingdown = True",
"init_targets() # Start worker threads LOG.debug('Starting %s worker threads...', SERVER_THREAD_COUNT) for i in",
"ping in %s ms avg (> %s ms)' % (avg, PING_SLOW_CRITICAL) elif avg",
"(> %s ms)' % (avg, PING_SLOW_WARNING) else: event = 'PingOK' severity = 'normal'",
"load Ping targets: %s', e) LOG.info('Loaded %d Ping targets OK', len(targets)) return targets",
"unspecified error with ping # Initialise Rules def init_targets(): targets = list() LOG.info('Loading",
"=> %s (rc=%d)', cmd, stdout, rc) m = re.search('(?P<loss>\\d+(\\.\\d+)?)% packet loss', stdout) if",
"Queue import re import logging import yaml from alertaclient.api import Client __version__ =",
"rc, rtt, loss, stdout = self.pinger(resource, count=2, timeout=5) else: rc, rtt, loss, stdout",
"Ping targets: %s', e) LOG.info('Loaded %d Ping targets OK', len(targets)) return targets class",
"self.queue.get() if not item: LOG.info('%s is shutting down.', self.getName()) break environment, service, resource,",
"p in ping_list: if 'targets' in p and p['targets']: for target in p['targets']:",
"__init__(self): self.shuttingdown = False def run(self): self.running = True # Create internal queue",
"rtt if avg > PING_SLOW_CRITICAL: event = 'PingSlow' severity = 'critical' text =",
"yaml.load(open(PING_FILE)) except Exception as e: LOG.error('Failed to load Ping targets: %s', e) LOG.info('Loaded",
"all ping replies received within timeout PING_FAILED = 1 # some or all",
"self.queue.put((environment, service, target, retries, time.time())) LOG.debug('Send heartbeat...') try: origin = '{}/{}'.format('pinger', platform.uname()[1]) self.api.heartbeat(origin,",
"resource) self.queue.task_done() @staticmethod def pinger(node, count=1, interval=1, timeout=5): if timeout <= count *",
"PING_MAX_TIMEOUT = 15 # seconds PING_MAX_RETRIES = 2 PING_SLOW_WARNING = 200 # ms",
"alive %s', node, rtt) else: LOG.info('%s: not responding', node) return rc, rtt, loss,",
"service, resource, retries, queue_time = item if time.time() - queue_time > LOOP_EVERY: LOG.warning('Ping",
"tuple(rtt) elif rc == PING_FAILED: event = 'PingFailed' severity = 'major' text =",
"_PING_ALERTS = [ 'PingFailed', 'PingSlow', 'PingOK', 'PingError', ] PING_OK = 0 # all",
"e: LOG.warning('Failed to send alert: %s', e) self.queue.task_done() LOG.info('%s ping %s complete.', self.getName(),",
"as e: LOG.warning('Failed to send heartbeat: %s', e) time.sleep(LOOP_EVERY) LOG.info('Ping queue length is",
"self.shuttingdown = False def run(self): self.running = True # Create internal queue self.queue",
"or all ping replies not received or did not respond within timeout PING_ERROR",
"expired after %d seconds.', resource, int(time.time() - queue_time)) self.queue.task_done() continue LOG.info('%s pinging %s...',",
"LOG.warning('Failed to send alert: %s', e) self.queue.task_done() LOG.info('%s ping %s complete.', self.getName(), resource)",
"%s -i %s -t %s %s\" % (count, interval, timeout, node) else: cmd",
"w.getName()) while not self.shuttingdown: try: for p in ping_list: if 'targets' in p",
"self.shuttingdown: try: for p in ping_list: if 'targets' in p and p['targets']: for",
"def __init__(self, api, queue): threading.Thread.__init__(self) LOG.debug('Initialising %s...', self.getName()) self.last_event = {} self.queue =",
"= Queue.Queue() self.api = Client() # Initialiase ping targets ping_list = init_targets() #",
"'warning' text = 'Node responded to ping in %s ms avg (> %s",
"all ping replies not received or did not respond within timeout PING_ERROR =",
"= 200 # ms PING_SLOW_CRITICAL = 500 # ms SERVER_THREAD_COUNT = 20 LOOP_EVERY",
"':icmp' group = 'Ping' correlate = _PING_ALERTS raw_data = stdout try: self.api.send_alert( resource=resource,",
"ping = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE, stderr=subprocess.STDOUT) stdout = ping.communicate()[0].rstrip('\\n') rc = ping.returncode LOG.debug('Ping %s",
"PingerDaemon(object): def __init__(self): self.shuttingdown = False def run(self): self.running = True # Create",
"self.queue) try: w.start() except Exception as e: LOG.error('Worker thread #%s did not start:",
"ping node %s.' % resource value = stdout else: LOG.warning('Unknown ping return code:",
"> LOOP_EVERY: LOG.warning('Ping request to %s expired after %d seconds.', resource, int(time.time() -",
"within timeout PING_ERROR = 2 # unspecified error with ping # Initialise Rules",
"import Client __version__ = '3.3.0' LOG = logging.getLogger('alerta.pinger') LOG.setLevel(logging.DEBUG) LOG.addHandler(logging.StreamHandler()) PING_FILE = 'alert-pinger.targets'",
"to ping in %s ms avg (> %s ms)' % (avg, PING_SLOW_WARNING) else:",
"e) self.queue.task_done() LOG.info('%s ping %s complete.', self.getName(), resource) self.queue.task_done() @staticmethod def pinger(node, count=1,",
"stdout) if m: loss = m.group('loss') else: loss = 'n/a' m = re.search('(?P<min>\\d+\\.\\d+)/(?P<avg>\\d+\\.\\d+)/(?P<max>\\d+\\.\\d+)/(?P<mdev>\\d+\\.\\d+)\\s+ms',",
"# Initialiase ping targets ping_list = init_targets() # Start worker threads LOG.debug('Starting %s",
"= 'normal' text = 'Node responding to ping avg/max %s/%s ms.' % tuple(rtt)",
"environment, service, resource, retries, queue_time = item if time.time() - queue_time > LOOP_EVERY:",
"'major' text = 'Node did not respond to ping or timed out within",
"False def run(self): self.running = True # Create internal queue self.queue = Queue.Queue()",
"%s', w.getName()) while not self.shuttingdown: try: for p in ping_list: if 'targets' in",
"Client() # Initialiase ping targets ping_list = init_targets() # Start worker threads LOG.debug('Starting",
"except Exception as e: LOG.error('Worker thread #%s did not start: %s', i, e)",
"text = 'Could not ping node %s.' % resource value = stdout else:",
"%s seconds' % PING_MAX_TIMEOUT value = '%s%% packet loss' % loss elif rc",
"= [ 'PingFailed', 'PingSlow', 'PingOK', 'PingError', ] PING_OK = 0 # all ping",
"- queue_time)) self.queue.task_done() continue LOG.info('%s pinging %s...', self.getName(), resource) if retries > 1:",
"LOG.warning('Failed to send heartbeat: %s', e) time.sleep(LOOP_EVERY) LOG.info('Ping queue length is %d', self.queue.qsize())",
"15 # seconds PING_MAX_RETRIES = 2 PING_SLOW_WARNING = 200 # ms PING_SLOW_CRITICAL =",
"= 'Could not ping node %s.' % resource value = stdout else: LOG.warning('Unknown",
"time.time() - queue_time > LOOP_EVERY: LOG.warning('Ping request to %s expired after %d seconds.',",
"= 'alert-pinger.targets' PING_MAX_TIMEOUT = 15 # seconds PING_MAX_RETRIES = 2 PING_SLOW_WARNING = 200",
"PING_OK = 0 # all ping replies received within timeout PING_FAILED = 1",
"return code: %s', rc) continue # Defaults resource += ':icmp' group = 'Ping'",
"PING_FAILED = 1 # some or all ping replies not received or did",
"count=5, timeout=PING_MAX_TIMEOUT) if rc != PING_OK and retries: LOG.info('Retrying ping %s %s more",
"LOG.info('%s: not responding', node) return rc, rtt, loss, stdout class PingerDaemon(object): def __init__(self):",
"%d seconds.', resource, int(time.time() - queue_time)) self.queue.task_done() continue LOG.info('%s pinging %s...', self.getName(), resource)",
"avg/max %s/%s ms.' % tuple(rtt) value = '%s/%s ms' % tuple(rtt) elif rc",
"'PingOK' severity = 'normal' text = 'Node responding to ping avg/max %s/%s ms.'",
"stdout try: self.api.send_alert( resource=resource, event=event, correlate=correlate, group=group, value=value, severity=severity, environment=environment, service=service, text=text, event_type='serviceAlert',",
"Create internal queue self.queue = Queue.Queue() self.api = Client() # Initialiase ping targets",
"stdout else: LOG.warning('Unknown ping return code: %s', rc) continue # Defaults resource +=",
"- queue_time > LOOP_EVERY: LOG.warning('Ping request to %s expired after %d seconds.', resource,",
"if rc == 0: LOG.info('%s: is alive %s', node, rtt) else: LOG.info('%s: not",
"retries = p.get('retries', PING_MAX_RETRIES) self.queue.put((environment, service, target, retries, time.time())) LOG.debug('Send heartbeat...') try: origin",
"e: LOG.warning('Failed to send heartbeat: %s', e) time.sleep(LOOP_EVERY) LOG.info('Ping queue length is %d',",
"'alert-pinger.targets' PING_MAX_TIMEOUT = 15 # seconds PING_MAX_RETRIES = 2 PING_SLOW_WARNING = 200 #",
"%s %s\" % (count, interval, timeout, node) else: cmd = \"ping -q -c",
"if not item: LOG.info('%s is shutting down.', self.getName()) break environment, service, resource, retries,",
"%s (rc=%d)', cmd, stdout, rc) m = re.search('(?P<loss>\\d+(\\.\\d+)?)% packet loss', stdout) if m:",
"'{}/{}'.format('pinger', platform.uname()[1]) self.api.heartbeat(origin, tags=[__version__]) except Exception as e: LOG.warning('Failed to send heartbeat: %s',",
"+ 1 if timeout > PING_MAX_TIMEOUT: timeout = PING_MAX_TIMEOUT if sys.platform == \"darwin\":",
"init_targets(): targets = list() LOG.info('Loading Ping targets...') try: targets = yaml.load(open(PING_FILE)) except Exception",
"= 'PingOK' severity = 'normal' text = 'Node responding to ping avg/max %s/%s",
"not respond to ping or timed out within %s seconds' % PING_MAX_TIMEOUT value",
"environment = p['environment'] service = p['service'] retries = p.get('retries', PING_MAX_RETRIES) self.queue.put((environment, service, target,",
"%s ms avg (> %s ms)' % (avg, PING_SLOW_WARNING) else: event = 'PingOK'",
"after %d seconds.', resource, int(time.time() - queue_time)) self.queue.task_done() continue LOG.info('%s pinging %s...', self.getName(),",
"alert: %s', e) self.queue.task_done() LOG.info('%s ping %s complete.', self.getName(), resource) self.queue.task_done() @staticmethod def",
"!= PING_OK and retries: LOG.info('Retrying ping %s %s more times', resource, retries) self.queue.put((environment,",
"'PingError' severity = 'warning' text = 'Could not ping node %s.' % resource",
"timeout PING_ERROR = 2 # unspecified error with ping # Initialise Rules def",
"ms' % tuple(rtt) elif rc == PING_FAILED: event = 'PingFailed' severity = 'major'",
"to load Ping targets: %s', e) LOG.info('Loaded %d Ping targets OK', len(targets)) return",
"if time.time() - queue_time > LOOP_EVERY: LOG.warning('Ping request to %s expired after %d",
"LOG.info('%s ping %s complete.', self.getName(), resource) self.queue.task_done() @staticmethod def pinger(node, count=1, interval=1, timeout=5):",
"resource=resource, event=event, correlate=correlate, group=group, value=value, severity=severity, environment=environment, service=service, text=text, event_type='serviceAlert', raw_data=raw_data, ) except",
"value = '%s%% packet loss' % loss elif rc == PING_ERROR: event =",
"LOG.info('%s: is alive %s', node, rtt) else: LOG.info('%s: not responding', node) return rc,",
"= \"ping -q -c %s -i %s -w %s %s\" % (count, interval,",
"ms PING_SLOW_CRITICAL = 500 # ms SERVER_THREAD_COUNT = 20 LOOP_EVERY = 30 _PING_ALERTS",
"= 2 # unspecified error with ping # Initialise Rules def init_targets(): targets",
"loss' % loss elif rc == PING_ERROR: event = 'PingError' severity = 'warning'",
"- 1, time.time())) self.queue.task_done() continue if rc == PING_OK: avg, max = rtt",
"timeout = count * interval + 1 if timeout > PING_MAX_TIMEOUT: timeout =",
"ms)' % (avg, PING_SLOW_WARNING) else: event = 'PingOK' severity = 'normal' text =",
"if avg > PING_SLOW_CRITICAL: event = 'PingSlow' severity = 'critical' text = 'Node",
"timeout = PING_MAX_TIMEOUT if sys.platform == \"darwin\": cmd = \"ping -q -c %s",
"p['service'] retries = p.get('retries', PING_MAX_RETRIES) self.queue.put((environment, service, target, retries, time.time())) LOG.debug('Send heartbeat...') try:",
"i in range(SERVER_THREAD_COUNT): w = WorkerThread(self.api, self.queue) try: w.start() except Exception as e:",
"interval, timeout, node) ping = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE, stderr=subprocess.STDOUT) stdout = ping.communicate()[0].rstrip('\\n') rc =",
"\"ping -q -c %s -i %s -w %s %s\" % (count, interval, timeout,",
"self.getName(), resource) self.queue.task_done() @staticmethod def pinger(node, count=1, interval=1, timeout=5): if timeout <= count",
"request received...') self.running = False for i in range(SERVER_THREAD_COUNT): self.queue.put(None) w.join() def main():",
"timeout=5): if timeout <= count * interval: timeout = count * interval +",
"in range(SERVER_THREAD_COUNT): w = WorkerThread(self.api, self.queue) try: w.start() except Exception as e: LOG.error('Worker",
"yaml from alertaclient.api import Client __version__ = '3.3.0' LOG = logging.getLogger('alerta.pinger') LOG.setLevel(logging.DEBUG) LOG.addHandler(logging.StreamHandler())",
"loss, stdout = self.pinger(resource, count=5, timeout=PING_MAX_TIMEOUT) if rc != PING_OK and retries: LOG.info('Retrying",
"interval: timeout = count * interval + 1 if timeout > PING_MAX_TIMEOUT: timeout",
"PING_SLOW_CRITICAL: event = 'PingSlow' severity = 'critical' text = 'Node responded to ping",
"1 if timeout > PING_MAX_TIMEOUT: timeout = PING_MAX_TIMEOUT if sys.platform == \"darwin\": cmd",
"event = 'PingOK' severity = 'normal' text = 'Node responding to ping avg/max",
"= 'warning' text = 'Node responded to ping in %s ms avg (>",
"Rules def init_targets(): targets = list() LOG.info('Loading Ping targets...') try: targets = yaml.load(open(PING_FILE))",
"tags=[__version__]) except Exception as e: LOG.warning('Failed to send heartbeat: %s', e) time.sleep(LOOP_EVERY) LOG.info('Ping",
"# all ping replies received within timeout PING_FAILED = 1 # some or",
"Start worker threads LOG.debug('Starting %s worker threads...', SERVER_THREAD_COUNT) for i in range(SERVER_THREAD_COUNT): w",
"complete.', self.getName(), resource) self.queue.task_done() @staticmethod def pinger(node, count=1, interval=1, timeout=5): if timeout <=",
"origin = '{}/{}'.format('pinger', platform.uname()[1]) self.api.heartbeat(origin, tags=[__version__]) except Exception as e: LOG.warning('Failed to send",
"'critical' text = 'Node responded to ping in %s ms avg (> %s",
"else: LOG.warning('Unknown ping return code: %s', rc) continue # Defaults resource += ':icmp'",
"event = 'PingError' severity = 'warning' text = 'Could not ping node %s.'",
"LOG.info('Ping queue length is %d', self.queue.qsize()) except (KeyboardInterrupt, SystemExit): self.shuttingdown = True LOG.info('Shutdown",
"is %d', self.queue.qsize()) except (KeyboardInterrupt, SystemExit): self.shuttingdown = True LOG.info('Shutdown request received...') self.running",
"'Node responding to ping avg/max %s/%s ms.' % tuple(rtt) value = '%s/%s ms'",
"# Defaults resource += ':icmp' group = 'Ping' correlate = _PING_ALERTS raw_data =",
"% (count, interval, timeout, node) ping = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE, stderr=subprocess.STDOUT) stdout = ping.communicate()[0].rstrip('\\n')",
"subprocess import threading import Queue import re import logging import yaml from alertaclient.api",
"range(SERVER_THREAD_COUNT): self.queue.put(None) w.join() def main(): pinger = PingerDaemon() pinger.run() if __name__ == '__main__':",
"% tuple(rtt) elif rc == PING_FAILED: event = 'PingFailed' severity = 'major' text",
"text=text, event_type='serviceAlert', raw_data=raw_data, ) except Exception as e: LOG.warning('Failed to send alert: %s',",
"timeout, node) else: cmd = \"ping -q -c %s -i %s -w %s",
"loss, stdout class PingerDaemon(object): def __init__(self): self.shuttingdown = False def run(self): self.running =",
"LOOP_EVERY = 30 _PING_ALERTS = [ 'PingFailed', 'PingSlow', 'PingOK', 'PingError', ] PING_OK =",
"i in range(SERVER_THREAD_COUNT): self.queue.put(None) w.join() def main(): pinger = PingerDaemon() pinger.run() if __name__",
"send heartbeat: %s', e) time.sleep(LOOP_EVERY) LOG.info('Ping queue length is %d', self.queue.qsize()) except (KeyboardInterrupt,",
"elif avg > PING_SLOW_WARNING: event = 'PingSlow' severity = 'warning' text = 'Node",
"{} self.queue = queue # internal queue self.api = api # message broker",
"resource, retries, queue_time = item if time.time() - queue_time > LOOP_EVERY: LOG.warning('Ping request",
"and retries: LOG.info('Retrying ping %s %s more times', resource, retries) self.queue.put((environment, service, resource,",
"# ms SERVER_THREAD_COUNT = 20 LOOP_EVERY = 30 _PING_ALERTS = [ 'PingFailed', 'PingSlow',",
"self.pinger(resource, count=2, timeout=5) else: rc, rtt, loss, stdout = self.pinger(resource, count=5, timeout=PING_MAX_TIMEOUT) if",
"self.queue.task_done() LOG.info('%s ping %s complete.', self.getName(), resource) self.queue.task_done() @staticmethod def pinger(node, count=1, interval=1,",
"import threading import Queue import re import logging import yaml from alertaclient.api import",
"def pinger(node, count=1, interval=1, timeout=5): if timeout <= count * interval: timeout =",
"e) time.sleep(LOOP_EVERY) LOG.info('Ping queue length is %d', self.queue.qsize()) except (KeyboardInterrupt, SystemExit): self.shuttingdown =",
"Exception as e: LOG.error('Failed to load Ping targets: %s', e) LOG.info('Loaded %d Ping",
"500 # ms SERVER_THREAD_COUNT = 20 LOOP_EVERY = 30 _PING_ALERTS = [ 'PingFailed',",
"= init_targets() # Start worker threads LOG.debug('Starting %s worker threads...', SERVER_THREAD_COUNT) for i",
"= count * interval + 1 if timeout > PING_MAX_TIMEOUT: timeout = PING_MAX_TIMEOUT",
"stdout = self.pinger(resource, count=2, timeout=5) else: rc, rtt, loss, stdout = self.pinger(resource, count=5,",
"avg > PING_SLOW_CRITICAL: event = 'PingSlow' severity = 'critical' text = 'Node responded",
"[ 'PingFailed', 'PingSlow', 'PingOK', 'PingError', ] PING_OK = 0 # all ping replies",
"targets class WorkerThread(threading.Thread): def __init__(self, api, queue): threading.Thread.__init__(self) LOG.debug('Initialising %s...', self.getName()) self.last_event =",
"worker thread: %s', w.getName()) while not self.shuttingdown: try: for p in ping_list: if",
"2 PING_SLOW_WARNING = 200 # ms PING_SLOW_CRITICAL = 500 # ms SERVER_THREAD_COUNT =",
"LOG.info('Retrying ping %s %s more times', resource, retries) self.queue.put((environment, service, resource, retries -",
"= re.search('(?P<loss>\\d+(\\.\\d+)?)% packet loss', stdout) if m: loss = m.group('loss') else: loss =",
"node, rtt) else: LOG.info('%s: not responding', node) return rc, rtt, loss, stdout class",
"self.queue = Queue.Queue() self.api = Client() # Initialiase ping targets ping_list = init_targets()",
"return targets class WorkerThread(threading.Thread): def __init__(self, api, queue): threading.Thread.__init__(self) LOG.debug('Initialising %s...', self.getName()) self.last_event",
"= 'critical' text = 'Node responded to ping in %s ms avg (>",
"= 'Node did not respond to ping or timed out within %s seconds'",
"w.start() except Exception as e: LOG.error('Worker thread #%s did not start: %s', i,",
"__init__(self, api, queue): threading.Thread.__init__(self) LOG.debug('Initialising %s...', self.getName()) self.last_event = {} self.queue = queue",
"tuple(rtt) value = '%s/%s ms' % tuple(rtt) elif rc == PING_FAILED: event =",
"% resource value = stdout else: LOG.warning('Unknown ping return code: %s', rc) continue",
"stdout class PingerDaemon(object): def __init__(self): self.shuttingdown = False def run(self): self.running = True",
"= item if time.time() - queue_time > LOOP_EVERY: LOG.warning('Ping request to %s expired",
"event = 'PingFailed' severity = 'major' text = 'Node did not respond to",
"queue self.queue = Queue.Queue() self.api = Client() # Initialiase ping targets ping_list =",
"threading import Queue import re import logging import yaml from alertaclient.api import Client",
"rc == PING_FAILED: event = 'PingFailed' severity = 'major' text = 'Node did",
"-i %s -t %s %s\" % (count, interval, timeout, node) else: cmd =",
"in range(SERVER_THREAD_COUNT): self.queue.put(None) w.join() def main(): pinger = PingerDaemon() pinger.run() if __name__ ==",
"rc) continue # Defaults resource += ':icmp' group = 'Ping' correlate = _PING_ALERTS",
"stdout, rc) m = re.search('(?P<loss>\\d+(\\.\\d+)?)% packet loss', stdout) if m: loss = m.group('loss')",
"= 2 PING_SLOW_WARNING = 200 # ms PING_SLOW_CRITICAL = 500 # ms SERVER_THREAD_COUNT",
"'n/a' m = re.search('(?P<min>\\d+\\.\\d+)/(?P<avg>\\d+\\.\\d+)/(?P<max>\\d+\\.\\d+)/(?P<mdev>\\d+\\.\\d+)\\s+ms', stdout) if m: rtt = (float(m.group('avg')), float(m.group('max'))) else: rtt",
"#%s did not start: %s', i, e) continue LOG.info('Started worker thread: %s', w.getName())",
"= {} self.queue = queue # internal queue self.api = api # message",
"= 'Ping' correlate = _PING_ALERTS raw_data = stdout try: self.api.send_alert( resource=resource, event=event, correlate=correlate,",
"= PING_MAX_TIMEOUT if sys.platform == \"darwin\": cmd = \"ping -q -c %s -i",
"logging.getLogger('alerta.pinger') LOG.setLevel(logging.DEBUG) LOG.addHandler(logging.StreamHandler()) PING_FILE = 'alert-pinger.targets' PING_MAX_TIMEOUT = 15 # seconds PING_MAX_RETRIES =",
"subprocess.Popen(cmd.split(), stdout=subprocess.PIPE, stderr=subprocess.STDOUT) stdout = ping.communicate()[0].rstrip('\\n') rc = ping.returncode LOG.debug('Ping %s => %s",
"target in p['targets']: environment = p['environment'] service = p['service'] retries = p.get('retries', PING_MAX_RETRIES)",
"timeout=5) else: rc, rtt, loss, stdout = self.pinger(resource, count=5, timeout=PING_MAX_TIMEOUT) if rc !=",
"-c %s -i %s -w %s %s\" % (count, interval, timeout, node) ping",
"else: rtt = (0, 0) if rc == 0: LOG.info('%s: is alive %s',",
"out within %s seconds' % PING_MAX_TIMEOUT value = '%s%% packet loss' % loss",
"for target in p['targets']: environment = p['environment'] service = p['service'] retries = p.get('retries',",
"'Could not ping node %s.' % resource value = stdout else: LOG.warning('Unknown ping",
"rtt) else: LOG.info('%s: not responding', node) return rc, rtt, loss, stdout class PingerDaemon(object):",
"%s...', self.getName(), resource) if retries > 1: rc, rtt, loss, stdout = self.pinger(resource,",
"%s %s\" % (count, interval, timeout, node) ping = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE, stderr=subprocess.STDOUT) stdout",
"%s -w %s %s\" % (count, interval, timeout, node) ping = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE,",
"count=1, interval=1, timeout=5): if timeout <= count * interval: timeout = count *",
"run(self): self.running = True # Create internal queue self.queue = Queue.Queue() self.api =",
"# seconds PING_MAX_RETRIES = 2 PING_SLOW_WARNING = 200 # ms PING_SLOW_CRITICAL = 500",
"error with ping # Initialise Rules def init_targets(): targets = list() LOG.info('Loading Ping",
"rc != PING_OK and retries: LOG.info('Retrying ping %s %s more times', resource, retries)",
"1: rc, rtt, loss, stdout = self.pinger(resource, count=2, timeout=5) else: rc, rtt, loss,",
"return rc, rtt, loss, stdout class PingerDaemon(object): def __init__(self): self.shuttingdown = False def",
"SERVER_THREAD_COUNT = 20 LOOP_EVERY = 30 _PING_ALERTS = [ 'PingFailed', 'PingSlow', 'PingOK', 'PingError',",
"ping_list = init_targets() # Start worker threads LOG.debug('Starting %s worker threads...', SERVER_THREAD_COUNT) for",
"re.search('(?P<loss>\\d+(\\.\\d+)?)% packet loss', stdout) if m: loss = m.group('loss') else: loss = 'n/a'",
"= subprocess.Popen(cmd.split(), stdout=subprocess.PIPE, stderr=subprocess.STDOUT) stdout = ping.communicate()[0].rstrip('\\n') rc = ping.returncode LOG.debug('Ping %s =>",
"if m: rtt = (float(m.group('avg')), float(m.group('max'))) else: rtt = (0, 0) if rc",
"LOG.error('Worker thread #%s did not start: %s', i, e) continue LOG.info('Started worker thread:",
"queue_time)) self.queue.task_done() continue LOG.info('%s pinging %s...', self.getName(), resource) if retries > 1: rc,",
"value = '%s/%s ms' % tuple(rtt) elif rc == PING_FAILED: event = 'PingFailed'",
"import yaml from alertaclient.api import Client __version__ = '3.3.0' LOG = logging.getLogger('alerta.pinger') LOG.setLevel(logging.DEBUG)",
"self.queue.task_done() continue if rc == PING_OK: avg, max = rtt if avg >",
"LOG.info('Loading Ping targets...') try: targets = yaml.load(open(PING_FILE)) except Exception as e: LOG.error('Failed to",
"self.queue.put((environment, service, resource, retries - 1, time.time())) self.queue.task_done() continue if rc == PING_OK:",
"PING_MAX_TIMEOUT: timeout = PING_MAX_TIMEOUT if sys.platform == \"darwin\": cmd = \"ping -q -c",
"targets = list() LOG.info('Loading Ping targets...') try: targets = yaml.load(open(PING_FILE)) except Exception as",
"retries > 1: rc, rtt, loss, stdout = self.pinger(resource, count=2, timeout=5) else: rc,",
"correlate=correlate, group=group, value=value, severity=severity, environment=environment, service=service, text=text, event_type='serviceAlert', raw_data=raw_data, ) except Exception as",
"value=value, severity=severity, environment=environment, service=service, text=text, event_type='serviceAlert', raw_data=raw_data, ) except Exception as e: LOG.warning('Failed",
"timeout, node) ping = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE, stderr=subprocess.STDOUT) stdout = ping.communicate()[0].rstrip('\\n') rc = ping.returncode",
"rc, rtt, loss, stdout class PingerDaemon(object): def __init__(self): self.shuttingdown = False def run(self):",
"group = 'Ping' correlate = _PING_ALERTS raw_data = stdout try: self.api.send_alert( resource=resource, event=event,",
"SERVER_THREAD_COUNT) for i in range(SERVER_THREAD_COUNT): w = WorkerThread(self.api, self.queue) try: w.start() except Exception",
"interval, timeout, node) else: cmd = \"ping -q -c %s -i %s -w",
"PING_MAX_TIMEOUT if sys.platform == \"darwin\": cmd = \"ping -q -c %s -i %s",
"not responding', node) return rc, rtt, loss, stdout class PingerDaemon(object): def __init__(self): self.shuttingdown",
"PING_ERROR: event = 'PingError' severity = 'warning' text = 'Could not ping node",
"'PingFailed', 'PingSlow', 'PingOK', 'PingError', ] PING_OK = 0 # all ping replies received",
"%s/%s ms.' % tuple(rtt) value = '%s/%s ms' % tuple(rtt) elif rc ==",
"self.queue.qsize()) except (KeyboardInterrupt, SystemExit): self.shuttingdown = True LOG.info('Shutdown request received...') self.running = False",
"LOG.debug('Send heartbeat...') try: origin = '{}/{}'.format('pinger', platform.uname()[1]) self.api.heartbeat(origin, tags=[__version__]) except Exception as e:",
"p['targets']: for target in p['targets']: environment = p['environment'] service = p['service'] retries =",
"platform.uname()[1]) self.api.heartbeat(origin, tags=[__version__]) except Exception as e: LOG.warning('Failed to send heartbeat: %s', e)",
"to %s expired after %d seconds.', resource, int(time.time() - queue_time)) self.queue.task_done() continue LOG.info('%s",
"] PING_OK = 0 # all ping replies received within timeout PING_FAILED =",
"* interval + 1 if timeout > PING_MAX_TIMEOUT: timeout = PING_MAX_TIMEOUT if sys.platform",
"m = re.search('(?P<min>\\d+\\.\\d+)/(?P<avg>\\d+\\.\\d+)/(?P<max>\\d+\\.\\d+)/(?P<mdev>\\d+\\.\\d+)\\s+ms', stdout) if m: rtt = (float(m.group('avg')), float(m.group('max'))) else: rtt =",
"LOG.setLevel(logging.DEBUG) LOG.addHandler(logging.StreamHandler()) PING_FILE = 'alert-pinger.targets' PING_MAX_TIMEOUT = 15 # seconds PING_MAX_RETRIES = 2",
"heartbeat: %s', e) time.sleep(LOOP_EVERY) LOG.info('Ping queue length is %d', self.queue.qsize()) except (KeyboardInterrupt, SystemExit):",
"= False for i in range(SERVER_THREAD_COUNT): self.queue.put(None) w.join() def main(): pinger = PingerDaemon()",
"'PingSlow' severity = 'warning' text = 'Node responded to ping in %s ms",
"Queue.Queue() self.api = Client() # Initialiase ping targets ping_list = init_targets() # Start",
"% (avg, PING_SLOW_WARNING) else: event = 'PingOK' severity = 'normal' text = 'Node",
"1 # some or all ping replies not received or did not respond",
"%s...', self.getName()) self.last_event = {} self.queue = queue # internal queue self.api =",
"except Exception as e: LOG.warning('Failed to send heartbeat: %s', e) time.sleep(LOOP_EVERY) LOG.info('Ping queue",
"if retries > 1: rc, rtt, loss, stdout = self.pinger(resource, count=2, timeout=5) else:",
"node) else: cmd = \"ping -q -c %s -i %s -w %s %s\"",
"PING_SLOW_CRITICAL = 500 # ms SERVER_THREAD_COUNT = 20 LOOP_EVERY = 30 _PING_ALERTS =",
"= ping.returncode LOG.debug('Ping %s => %s (rc=%d)', cmd, stdout, rc) m = re.search('(?P<loss>\\d+(\\.\\d+)?)%",
"p.get('retries', PING_MAX_RETRIES) self.queue.put((environment, service, target, retries, time.time())) LOG.debug('Send heartbeat...') try: origin = '{}/{}'.format('pinger',",
"thread #%s did not start: %s', i, e) continue LOG.info('Started worker thread: %s',",
"LOG.debug('Initialising %s...', self.getName()) self.last_event = {} self.queue = queue # internal queue self.api",
"= 20 LOOP_EVERY = 30 _PING_ALERTS = [ 'PingFailed', 'PingSlow', 'PingOK', 'PingError', ]",
"PING_MAX_TIMEOUT value = '%s%% packet loss' % loss elif rc == PING_ERROR: event",
"%s expired after %d seconds.', resource, int(time.time() - queue_time)) self.queue.task_done() continue LOG.info('%s pinging",
"worker threads LOG.debug('Starting %s worker threads...', SERVER_THREAD_COUNT) for i in range(SERVER_THREAD_COUNT): w =",
"for i in range(SERVER_THREAD_COUNT): self.queue.put(None) w.join() def main(): pinger = PingerDaemon() pinger.run() if",
"= logging.getLogger('alerta.pinger') LOG.setLevel(logging.DEBUG) LOG.addHandler(logging.StreamHandler()) PING_FILE = 'alert-pinger.targets' PING_MAX_TIMEOUT = 15 # seconds PING_MAX_RETRIES",
"30 _PING_ALERTS = [ 'PingFailed', 'PingSlow', 'PingOK', 'PingError', ] PING_OK = 0 #",
"LOG.warning('Unknown ping return code: %s', rc) continue # Defaults resource += ':icmp' group",
"internal queue self.queue = Queue.Queue() self.api = Client() # Initialiase ping targets ping_list",
"service, target, retries, time.time())) LOG.debug('Send heartbeat...') try: origin = '{}/{}'.format('pinger', platform.uname()[1]) self.api.heartbeat(origin, tags=[__version__])",
"> PING_MAX_TIMEOUT: timeout = PING_MAX_TIMEOUT if sys.platform == \"darwin\": cmd = \"ping -q",
"PING_FAILED: event = 'PingFailed' severity = 'major' text = 'Node did not respond",
"request to %s expired after %d seconds.', resource, int(time.time() - queue_time)) self.queue.task_done() continue",
"== PING_ERROR: event = 'PingError' severity = 'warning' text = 'Could not ping",
"severity = 'critical' text = 'Node responded to ping in %s ms avg",
"'3.3.0' LOG = logging.getLogger('alerta.pinger') LOG.setLevel(logging.DEBUG) LOG.addHandler(logging.StreamHandler()) PING_FILE = 'alert-pinger.targets' PING_MAX_TIMEOUT = 15 #",
"-t %s %s\" % (count, interval, timeout, node) else: cmd = \"ping -q",
"200 # ms PING_SLOW_CRITICAL = 500 # ms SERVER_THREAD_COUNT = 20 LOOP_EVERY =",
"rtt, loss, stdout class PingerDaemon(object): def __init__(self): self.shuttingdown = False def run(self): self.running",
"> PING_SLOW_WARNING: event = 'PingSlow' severity = 'warning' text = 'Node responded to",
"severity = 'warning' text = 'Could not ping node %s.' % resource value",
"= self.pinger(resource, count=5, timeout=PING_MAX_TIMEOUT) if rc != PING_OK and retries: LOG.info('Retrying ping %s",
"'warning' text = 'Could not ping node %s.' % resource value = stdout",
"import logging import yaml from alertaclient.api import Client __version__ = '3.3.0' LOG =",
"try: self.api.send_alert( resource=resource, event=event, correlate=correlate, group=group, value=value, severity=severity, environment=environment, service=service, text=text, event_type='serviceAlert', raw_data=raw_data,",
"%s', e) self.queue.task_done() LOG.info('%s ping %s complete.', self.getName(), resource) self.queue.task_done() @staticmethod def pinger(node,",
"= api # message broker def run(self): while True: LOG.debug('Waiting on input queue...')",
"True: LOG.debug('Waiting on input queue...') item = self.queue.get() if not item: LOG.info('%s is",
"self.running = True # Create internal queue self.queue = Queue.Queue() self.api = Client()",
"= stdout try: self.api.send_alert( resource=resource, event=event, correlate=correlate, group=group, value=value, severity=severity, environment=environment, service=service, text=text,",
"for i in range(SERVER_THREAD_COUNT): w = WorkerThread(self.api, self.queue) try: w.start() except Exception as",
"text = 'Node responded to ping in %s ms avg (> %s ms)'",
"%s', e) LOG.info('Loaded %d Ping targets OK', len(targets)) return targets class WorkerThread(threading.Thread): def",
"message broker def run(self): while True: LOG.debug('Waiting on input queue...') item = self.queue.get()",
"rc == 0: LOG.info('%s: is alive %s', node, rtt) else: LOG.info('%s: not responding',",
"queue): threading.Thread.__init__(self) LOG.debug('Initialising %s...', self.getName()) self.last_event = {} self.queue = queue # internal",
"= queue # internal queue self.api = api # message broker def run(self):",
"= 30 _PING_ALERTS = [ 'PingFailed', 'PingSlow', 'PingOK', 'PingError', ] PING_OK = 0",
"api # message broker def run(self): while True: LOG.debug('Waiting on input queue...') item",
"%s ms avg (> %s ms)' % (avg, PING_SLOW_CRITICAL) elif avg > PING_SLOW_WARNING:",
"ping %s %s more times', resource, retries) self.queue.put((environment, service, resource, retries - 1,",
"if rc != PING_OK and retries: LOG.info('Retrying ping %s %s more times', resource,",
"ms avg (> %s ms)' % (avg, PING_SLOW_WARNING) else: event = 'PingOK' severity",
"LOG.debug('Ping %s => %s (rc=%d)', cmd, stdout, rc) m = re.search('(?P<loss>\\d+(\\.\\d+)?)% packet loss',",
"cmd, stdout, rc) m = re.search('(?P<loss>\\d+(\\.\\d+)?)% packet loss', stdout) if m: loss =",
"else: event = 'PingOK' severity = 'normal' text = 'Node responding to ping",
"ping.returncode LOG.debug('Ping %s => %s (rc=%d)', cmd, stdout, rc) m = re.search('(?P<loss>\\d+(\\.\\d+)?)% packet",
"received...') self.running = False for i in range(SERVER_THREAD_COUNT): self.queue.put(None) w.join() def main(): pinger",
"= 15 # seconds PING_MAX_RETRIES = 2 PING_SLOW_WARNING = 200 # ms PING_SLOW_CRITICAL",
"<= count * interval: timeout = count * interval + 1 if timeout",
"= True # Create internal queue self.queue = Queue.Queue() self.api = Client() #",
"except (KeyboardInterrupt, SystemExit): self.shuttingdown = True LOG.info('Shutdown request received...') self.running = False for",
"not item: LOG.info('%s is shutting down.', self.getName()) break environment, service, resource, retries, queue_time",
"'%s/%s ms' % tuple(rtt) elif rc == PING_FAILED: event = 'PingFailed' severity =",
"respond to ping or timed out within %s seconds' % PING_MAX_TIMEOUT value =",
"Exception as e: LOG.warning('Failed to send alert: %s', e) self.queue.task_done() LOG.info('%s ping %s",
"(rc=%d)', cmd, stdout, rc) m = re.search('(?P<loss>\\d+(\\.\\d+)?)% packet loss', stdout) if m: loss",
"as e: LOG.warning('Failed to send alert: %s', e) self.queue.task_done() LOG.info('%s ping %s complete.',",
"loss, stdout = self.pinger(resource, count=2, timeout=5) else: rc, rtt, loss, stdout = self.pinger(resource,",
"LOG.info('%s is shutting down.', self.getName()) break environment, service, resource, retries, queue_time = item",
"queue_time > LOOP_EVERY: LOG.warning('Ping request to %s expired after %d seconds.', resource, int(time.time()",
"LOG.warning('Ping request to %s expired after %d seconds.', resource, int(time.time() - queue_time)) self.queue.task_done()",
"resource += ':icmp' group = 'Ping' correlate = _PING_ALERTS raw_data = stdout try:",
"worker threads...', SERVER_THREAD_COUNT) for i in range(SERVER_THREAD_COUNT): w = WorkerThread(self.api, self.queue) try: w.start()",
"= 1 # some or all ping replies not received or did not",
"= 'Node responding to ping avg/max %s/%s ms.' % tuple(rtt) value = '%s/%s",
"WorkerThread(threading.Thread): def __init__(self, api, queue): threading.Thread.__init__(self) LOG.debug('Initialising %s...', self.getName()) self.last_event = {} self.queue",
"replies not received or did not respond within timeout PING_ERROR = 2 #",
"%s ms)' % (avg, PING_SLOW_WARNING) else: event = 'PingOK' severity = 'normal' text",
"% tuple(rtt) value = '%s/%s ms' % tuple(rtt) elif rc == PING_FAILED: event",
"LOOP_EVERY: LOG.warning('Ping request to %s expired after %d seconds.', resource, int(time.time() - queue_time))",
"(0, 0) if rc == 0: LOG.info('%s: is alive %s', node, rtt) else:",
"threading.Thread.__init__(self) LOG.debug('Initialising %s...', self.getName()) self.last_event = {} self.queue = queue # internal queue",
"= 'PingSlow' severity = 'warning' text = 'Node responded to ping in %s",
"rtt, loss, stdout = self.pinger(resource, count=5, timeout=PING_MAX_TIMEOUT) if rc != PING_OK and retries:",
"m: loss = m.group('loss') else: loss = 'n/a' m = re.search('(?P<min>\\d+\\.\\d+)/(?P<avg>\\d+\\.\\d+)/(?P<max>\\d+\\.\\d+)/(?P<mdev>\\d+\\.\\d+)\\s+ms', stdout) if",
"int(time.time() - queue_time)) self.queue.task_done() continue LOG.info('%s pinging %s...', self.getName(), resource) if retries >",
"rc, rtt, loss, stdout = self.pinger(resource, count=5, timeout=PING_MAX_TIMEOUT) if rc != PING_OK and",
"length is %d', self.queue.qsize()) except (KeyboardInterrupt, SystemExit): self.shuttingdown = True LOG.info('Shutdown request received...')",
"avg (> %s ms)' % (avg, PING_SLOW_WARNING) else: event = 'PingOK' severity =",
"== PING_OK: avg, max = rtt if avg > PING_SLOW_CRITICAL: event = 'PingSlow'",
"re import logging import yaml from alertaclient.api import Client __version__ = '3.3.0' LOG",
"did not start: %s', i, e) continue LOG.info('Started worker thread: %s', w.getName()) while",
"%s ms)' % (avg, PING_SLOW_CRITICAL) elif avg > PING_SLOW_WARNING: event = 'PingSlow' severity",
"ping replies received within timeout PING_FAILED = 1 # some or all ping",
"self.pinger(resource, count=5, timeout=PING_MAX_TIMEOUT) if rc != PING_OK and retries: LOG.info('Retrying ping %s %s",
"<filename>integrations/pinger/pinger.py import sys import platform import time import subprocess import threading import Queue",
"Client __version__ = '3.3.0' LOG = logging.getLogger('alerta.pinger') LOG.setLevel(logging.DEBUG) LOG.addHandler(logging.StreamHandler()) PING_FILE = 'alert-pinger.targets' PING_MAX_TIMEOUT",
"node %s.' % resource value = stdout else: LOG.warning('Unknown ping return code: %s',",
"PING_OK: avg, max = rtt if avg > PING_SLOW_CRITICAL: event = 'PingSlow' severity",
"stdout = self.pinger(resource, count=5, timeout=PING_MAX_TIMEOUT) if rc != PING_OK and retries: LOG.info('Retrying ping",
"loss = 'n/a' m = re.search('(?P<min>\\d+\\.\\d+)/(?P<avg>\\d+\\.\\d+)/(?P<max>\\d+\\.\\d+)/(?P<mdev>\\d+\\.\\d+)\\s+ms', stdout) if m: rtt = (float(m.group('avg')), float(m.group('max')))",
"try: origin = '{}/{}'.format('pinger', platform.uname()[1]) self.api.heartbeat(origin, tags=[__version__]) except Exception as e: LOG.warning('Failed to",
"'Node did not respond to ping or timed out within %s seconds' %",
"event=event, correlate=correlate, group=group, value=value, severity=severity, environment=environment, service=service, text=text, event_type='serviceAlert', raw_data=raw_data, ) except Exception",
"responding to ping avg/max %s/%s ms.' % tuple(rtt) value = '%s/%s ms' %",
"self.api.send_alert( resource=resource, event=event, correlate=correlate, group=group, value=value, severity=severity, environment=environment, service=service, text=text, event_type='serviceAlert', raw_data=raw_data, )",
"LOG.debug('Starting %s worker threads...', SERVER_THREAD_COUNT) for i in range(SERVER_THREAD_COUNT): w = WorkerThread(self.api, self.queue)",
"interval + 1 if timeout > PING_MAX_TIMEOUT: timeout = PING_MAX_TIMEOUT if sys.platform ==",
"-c %s -i %s -t %s %s\" % (count, interval, timeout, node) else:",
"pinger(node, count=1, interval=1, timeout=5): if timeout <= count * interval: timeout = count",
"service=service, text=text, event_type='serviceAlert', raw_data=raw_data, ) except Exception as e: LOG.warning('Failed to send alert:",
"rc = ping.returncode LOG.debug('Ping %s => %s (rc=%d)', cmd, stdout, rc) m =",
"= WorkerThread(self.api, self.queue) try: w.start() except Exception as e: LOG.error('Worker thread #%s did",
"1, time.time())) self.queue.task_done() continue if rc == PING_OK: avg, max = rtt if",
"within %s seconds' % PING_MAX_TIMEOUT value = '%s%% packet loss' % loss elif",
"targets...') try: targets = yaml.load(open(PING_FILE)) except Exception as e: LOG.error('Failed to load Ping",
"did not respond within timeout PING_ERROR = 2 # unspecified error with ping",
"LOG.info('Loaded %d Ping targets OK', len(targets)) return targets class WorkerThread(threading.Thread): def __init__(self, api,",
"%s', rc) continue # Defaults resource += ':icmp' group = 'Ping' correlate =",
"else: LOG.info('%s: not responding', node) return rc, rtt, loss, stdout class PingerDaemon(object): def",
"> 1: rc, rtt, loss, stdout = self.pinger(resource, count=2, timeout=5) else: rc, rtt,",
"= p['service'] retries = p.get('retries', PING_MAX_RETRIES) self.queue.put((environment, service, target, retries, time.time())) LOG.debug('Send heartbeat...')",
"to send alert: %s', e) self.queue.task_done() LOG.info('%s ping %s complete.', self.getName(), resource) self.queue.task_done()",
"w = WorkerThread(self.api, self.queue) try: w.start() except Exception as e: LOG.error('Worker thread #%s",
"%s more times', resource, retries) self.queue.put((environment, service, resource, retries - 1, time.time())) self.queue.task_done()",
"break environment, service, resource, retries, queue_time = item if time.time() - queue_time >",
"responding', node) return rc, rtt, loss, stdout class PingerDaemon(object): def __init__(self): self.shuttingdown =",
"value = stdout else: LOG.warning('Unknown ping return code: %s', rc) continue # Defaults",
"loss = m.group('loss') else: loss = 'n/a' m = re.search('(?P<min>\\d+\\.\\d+)/(?P<avg>\\d+\\.\\d+)/(?P<max>\\d+\\.\\d+)/(?P<mdev>\\d+\\.\\d+)\\s+ms', stdout) if m:",
"thread: %s', w.getName()) while not self.shuttingdown: try: for p in ping_list: if 'targets'",
"PING_SLOW_CRITICAL) elif avg > PING_SLOW_WARNING: event = 'PingSlow' severity = 'warning' text =",
"self.api = Client() # Initialiase ping targets ping_list = init_targets() # Start worker",
"to ping in %s ms avg (> %s ms)' % (avg, PING_SLOW_CRITICAL) elif",
"on input queue...') item = self.queue.get() if not item: LOG.info('%s is shutting down.',",
"ms)' % (avg, PING_SLOW_CRITICAL) elif avg > PING_SLOW_WARNING: event = 'PingSlow' severity =",
"rc == PING_OK: avg, max = rtt if avg > PING_SLOW_CRITICAL: event =",
"try: for p in ping_list: if 'targets' in p and p['targets']: for target",
"= p.get('retries', PING_MAX_RETRIES) self.queue.put((environment, service, target, retries, time.time())) LOG.debug('Send heartbeat...') try: origin =",
"ping return code: %s', rc) continue # Defaults resource += ':icmp' group =",
"LOG = logging.getLogger('alerta.pinger') LOG.setLevel(logging.DEBUG) LOG.addHandler(logging.StreamHandler()) PING_FILE = 'alert-pinger.targets' PING_MAX_TIMEOUT = 15 # seconds",
"or timed out within %s seconds' % PING_MAX_TIMEOUT value = '%s%% packet loss'",
"(count, interval, timeout, node) ping = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE, stderr=subprocess.STDOUT) stdout = ping.communicate()[0].rstrip('\\n') rc",
"Initialiase ping targets ping_list = init_targets() # Start worker threads LOG.debug('Starting %s worker",
"%s -t %s %s\" % (count, interval, timeout, node) else: cmd = \"ping",
"i, e) continue LOG.info('Started worker thread: %s', w.getName()) while not self.shuttingdown: try: for",
"'%s%% packet loss' % loss elif rc == PING_ERROR: event = 'PingError' severity",
"= (float(m.group('avg')), float(m.group('max'))) else: rtt = (0, 0) if rc == 0: LOG.info('%s:",
"count * interval + 1 if timeout > PING_MAX_TIMEOUT: timeout = PING_MAX_TIMEOUT if",
"e) continue LOG.info('Started worker thread: %s', w.getName()) while not self.shuttingdown: try: for p",
"_PING_ALERTS raw_data = stdout try: self.api.send_alert( resource=resource, event=event, correlate=correlate, group=group, value=value, severity=severity, environment=environment,",
"threads LOG.debug('Starting %s worker threads...', SERVER_THREAD_COUNT) for i in range(SERVER_THREAD_COUNT): w = WorkerThread(self.api,",
"for p in ping_list: if 'targets' in p and p['targets']: for target in",
"respond within timeout PING_ERROR = 2 # unspecified error with ping # Initialise",
"PING_ERROR = 2 # unspecified error with ping # Initialise Rules def init_targets():",
"# Initialise Rules def init_targets(): targets = list() LOG.info('Loading Ping targets...') try: targets",
"queue_time = item if time.time() - queue_time > LOOP_EVERY: LOG.warning('Ping request to %s",
"'targets' in p and p['targets']: for target in p['targets']: environment = p['environment'] service",
"received or did not respond within timeout PING_ERROR = 2 # unspecified error",
"continue # Defaults resource += ':icmp' group = 'Ping' correlate = _PING_ALERTS raw_data",
"targets ping_list = init_targets() # Start worker threads LOG.debug('Starting %s worker threads...', SERVER_THREAD_COUNT)",
"seconds.', resource, int(time.time() - queue_time)) self.queue.task_done() continue LOG.info('%s pinging %s...', self.getName(), resource) if",
"# message broker def run(self): while True: LOG.debug('Waiting on input queue...') item =",
"timed out within %s seconds' % PING_MAX_TIMEOUT value = '%s%% packet loss' %",
"in p and p['targets']: for target in p['targets']: environment = p['environment'] service =",
"= \"ping -q -c %s -i %s -t %s %s\" % (count, interval,",
"'PingOK', 'PingError', ] PING_OK = 0 # all ping replies received within timeout",
"timeout > PING_MAX_TIMEOUT: timeout = PING_MAX_TIMEOUT if sys.platform == \"darwin\": cmd = \"ping",
"queue self.api = api # message broker def run(self): while True: LOG.debug('Waiting on",
"code: %s', rc) continue # Defaults resource += ':icmp' group = 'Ping' correlate",
"len(targets)) return targets class WorkerThread(threading.Thread): def __init__(self, api, queue): threading.Thread.__init__(self) LOG.debug('Initialising %s...', self.getName())",
"elif rc == PING_ERROR: event = 'PingError' severity = 'warning' text = 'Could",
"resource, retries) self.queue.put((environment, service, resource, retries - 1, time.time())) self.queue.task_done() continue if rc",
"= (0, 0) if rc == 0: LOG.info('%s: is alive %s', node, rtt)",
"@staticmethod def pinger(node, count=1, interval=1, timeout=5): if timeout <= count * interval: timeout",
"else: loss = 'n/a' m = re.search('(?P<min>\\d+\\.\\d+)/(?P<avg>\\d+\\.\\d+)/(?P<max>\\d+\\.\\d+)/(?P<mdev>\\d+\\.\\d+)\\s+ms', stdout) if m: rtt = (float(m.group('avg')),",
"correlate = _PING_ALERTS raw_data = stdout try: self.api.send_alert( resource=resource, event=event, correlate=correlate, group=group, value=value,",
"= 'PingSlow' severity = 'critical' text = 'Node responded to ping in %s",
"+= ':icmp' group = 'Ping' correlate = _PING_ALERTS raw_data = stdout try: self.api.send_alert(",
"queue length is %d', self.queue.qsize()) except (KeyboardInterrupt, SystemExit): self.shuttingdown = True LOG.info('Shutdown request",
"2 # unspecified error with ping # Initialise Rules def init_targets(): targets =",
"environment=environment, service=service, text=text, event_type='serviceAlert', raw_data=raw_data, ) except Exception as e: LOG.warning('Failed to send",
"self.last_event = {} self.queue = queue # internal queue self.api = api #",
"ms.' % tuple(rtt) value = '%s/%s ms' % tuple(rtt) elif rc == PING_FAILED:",
"% (avg, PING_SLOW_CRITICAL) elif avg > PING_SLOW_WARNING: event = 'PingSlow' severity = 'warning'",
"PING_SLOW_WARNING = 200 # ms PING_SLOW_CRITICAL = 500 # ms SERVER_THREAD_COUNT = 20",
"rc) m = re.search('(?P<loss>\\d+(\\.\\d+)?)% packet loss', stdout) if m: loss = m.group('loss') else:",
"severity = 'warning' text = 'Node responded to ping in %s ms avg",
"heartbeat...') try: origin = '{}/{}'.format('pinger', platform.uname()[1]) self.api.heartbeat(origin, tags=[__version__]) except Exception as e: LOG.warning('Failed",
"avg > PING_SLOW_WARNING: event = 'PingSlow' severity = 'warning' text = 'Node responded",
"= m.group('loss') else: loss = 'n/a' m = re.search('(?P<min>\\d+\\.\\d+)/(?P<avg>\\d+\\.\\d+)/(?P<max>\\d+\\.\\d+)/(?P<mdev>\\d+\\.\\d+)\\s+ms', stdout) if m: rtt",
"m.group('loss') else: loss = 'n/a' m = re.search('(?P<min>\\d+\\.\\d+)/(?P<avg>\\d+\\.\\d+)/(?P<max>\\d+\\.\\d+)/(?P<mdev>\\d+\\.\\d+)\\s+ms', stdout) if m: rtt =",
"targets: %s', e) LOG.info('Loaded %d Ping targets OK', len(targets)) return targets class WorkerThread(threading.Thread):",
"if sys.platform == \"darwin\": cmd = \"ping -q -c %s -i %s -t",
"'PingSlow' severity = 'critical' text = 'Node responded to ping in %s ms",
"if timeout > PING_MAX_TIMEOUT: timeout = PING_MAX_TIMEOUT if sys.platform == \"darwin\": cmd =",
"node) ping = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE, stderr=subprocess.STDOUT) stdout = ping.communicate()[0].rstrip('\\n') rc = ping.returncode LOG.debug('Ping",
"continue LOG.info('%s pinging %s...', self.getName(), resource) if retries > 1: rc, rtt, loss,",
"time.time())) LOG.debug('Send heartbeat...') try: origin = '{}/{}'.format('pinger', platform.uname()[1]) self.api.heartbeat(origin, tags=[__version__]) except Exception as",
"= '{}/{}'.format('pinger', platform.uname()[1]) self.api.heartbeat(origin, tags=[__version__]) except Exception as e: LOG.warning('Failed to send heartbeat:",
"is shutting down.', self.getName()) break environment, service, resource, retries, queue_time = item if",
"retries: LOG.info('Retrying ping %s %s more times', resource, retries) self.queue.put((environment, service, resource, retries",
"timeout <= count * interval: timeout = count * interval + 1 if",
"packet loss' % loss elif rc == PING_ERROR: event = 'PingError' severity =",
"timeout PING_FAILED = 1 # some or all ping replies not received or",
"PING_FILE = 'alert-pinger.targets' PING_MAX_TIMEOUT = 15 # seconds PING_MAX_RETRIES = 2 PING_SLOW_WARNING =",
"shutting down.', self.getName()) break environment, service, resource, retries, queue_time = item if time.time()",
"or did not respond within timeout PING_ERROR = 2 # unspecified error with",
"raw_data=raw_data, ) except Exception as e: LOG.warning('Failed to send alert: %s', e) self.queue.task_done()",
"self.queue.task_done() continue LOG.info('%s pinging %s...', self.getName(), resource) if retries > 1: rc, rtt,",
"packet loss', stdout) if m: loss = m.group('loss') else: loss = 'n/a' m",
"event = 'PingSlow' severity = 'warning' text = 'Node responded to ping in",
"%s', i, e) continue LOG.info('Started worker thread: %s', w.getName()) while not self.shuttingdown: try:",
"# unspecified error with ping # Initialise Rules def init_targets(): targets = list()",
"Ping targets...') try: targets = yaml.load(open(PING_FILE)) except Exception as e: LOG.error('Failed to load",
"resource, retries - 1, time.time())) self.queue.task_done() continue if rc == PING_OK: avg, max",
"%s', node, rtt) else: LOG.info('%s: not responding', node) return rc, rtt, loss, stdout",
"= False def run(self): self.running = True # Create internal queue self.queue =",
"%s', e) time.sleep(LOOP_EVERY) LOG.info('Ping queue length is %d', self.queue.qsize()) except (KeyboardInterrupt, SystemExit): self.shuttingdown",
"as e: LOG.error('Failed to load Ping targets: %s', e) LOG.info('Loaded %d Ping targets",
"re.search('(?P<min>\\d+\\.\\d+)/(?P<avg>\\d+\\.\\d+)/(?P<max>\\d+\\.\\d+)/(?P<mdev>\\d+\\.\\d+)\\s+ms', stdout) if m: rtt = (float(m.group('avg')), float(m.group('max'))) else: rtt = (0, 0)",
"in %s ms avg (> %s ms)' % (avg, PING_SLOW_CRITICAL) elif avg >",
"retries, queue_time = item if time.time() - queue_time > LOOP_EVERY: LOG.warning('Ping request to",
"is alive %s', node, rtt) else: LOG.info('%s: not responding', node) return rc, rtt,",
"item if time.time() - queue_time > LOOP_EVERY: LOG.warning('Ping request to %s expired after",
"= 'warning' text = 'Could not ping node %s.' % resource value =",
"\"darwin\": cmd = \"ping -q -c %s -i %s -t %s %s\" %",
"== 0: LOG.info('%s: is alive %s', node, rtt) else: LOG.info('%s: not responding', node)",
"if timeout <= count * interval: timeout = count * interval + 1",
"0 # all ping replies received within timeout PING_FAILED = 1 # some",
"ping replies not received or did not respond within timeout PING_ERROR = 2",
"not respond within timeout PING_ERROR = 2 # unspecified error with ping #",
"-i %s -w %s %s\" % (count, interval, timeout, node) ping = subprocess.Popen(cmd.split(),",
"= ping.communicate()[0].rstrip('\\n') rc = ping.returncode LOG.debug('Ping %s => %s (rc=%d)', cmd, stdout, rc)",
"import Queue import re import logging import yaml from alertaclient.api import Client __version__",
"sys import platform import time import subprocess import threading import Queue import re",
"ping %s complete.', self.getName(), resource) self.queue.task_done() @staticmethod def pinger(node, count=1, interval=1, timeout=5): if",
"as e: LOG.error('Worker thread #%s did not start: %s', i, e) continue LOG.info('Started",
"self.getName(), resource) if retries > 1: rc, rtt, loss, stdout = self.pinger(resource, count=2,",
"float(m.group('max'))) else: rtt = (0, 0) if rc == 0: LOG.info('%s: is alive",
"True LOG.info('Shutdown request received...') self.running = False for i in range(SERVER_THREAD_COUNT): self.queue.put(None) w.join()",
"LOG.info('%s pinging %s...', self.getName(), resource) if retries > 1: rc, rtt, loss, stdout",
"m = re.search('(?P<loss>\\d+(\\.\\d+)?)% packet loss', stdout) if m: loss = m.group('loss') else: loss",
"seconds PING_MAX_RETRIES = 2 PING_SLOW_WARNING = 200 # ms PING_SLOW_CRITICAL = 500 #",
"PING_MAX_RETRIES = 2 PING_SLOW_WARNING = 200 # ms PING_SLOW_CRITICAL = 500 # ms",
"ping in %s ms avg (> %s ms)' % (avg, PING_SLOW_WARNING) else: event",
"LOG.info('Shutdown request received...') self.running = False for i in range(SERVER_THREAD_COUNT): self.queue.put(None) w.join() def",
"class WorkerThread(threading.Thread): def __init__(self, api, queue): threading.Thread.__init__(self) LOG.debug('Initialising %s...', self.getName()) self.last_event = {}",
"event = 'PingSlow' severity = 'critical' text = 'Node responded to ping in",
"rtt = (0, 0) if rc == 0: LOG.info('%s: is alive %s', node,",
"self.getName()) break environment, service, resource, retries, queue_time = item if time.time() - queue_time",
"targets = yaml.load(open(PING_FILE)) except Exception as e: LOG.error('Failed to load Ping targets: %s',",
"WorkerThread(self.api, self.queue) try: w.start() except Exception as e: LOG.error('Worker thread #%s did not",
"ping # Initialise Rules def init_targets(): targets = list() LOG.info('Loading Ping targets...') try:",
"avg, max = rtt if avg > PING_SLOW_CRITICAL: event = 'PingSlow' severity =",
"ping avg/max %s/%s ms.' % tuple(rtt) value = '%s/%s ms' % tuple(rtt) elif",
"= True LOG.info('Shutdown request received...') self.running = False for i in range(SERVER_THREAD_COUNT): self.queue.put(None)",
"severity = 'major' text = 'Node did not respond to ping or timed",
"%s\" % (count, interval, timeout, node) else: cmd = \"ping -q -c %s",
"= '%s%% packet loss' % loss elif rc == PING_ERROR: event = 'PingError'",
"self.running = False for i in range(SERVER_THREAD_COUNT): self.queue.put(None) w.join() def main(): pinger =",
"if m: loss = m.group('loss') else: loss = 'n/a' m = re.search('(?P<min>\\d+\\.\\d+)/(?P<avg>\\d+\\.\\d+)/(?P<max>\\d+\\.\\d+)/(?P<mdev>\\d+\\.\\d+)\\s+ms', stdout)",
"self.queue.task_done() @staticmethod def pinger(node, count=1, interval=1, timeout=5): if timeout <= count * interval:",
"input queue...') item = self.queue.get() if not item: LOG.info('%s is shutting down.', self.getName())",
"p and p['targets']: for target in p['targets']: environment = p['environment'] service = p['service']",
"= '%s/%s ms' % tuple(rtt) elif rc == PING_FAILED: event = 'PingFailed' severity",
"to ping avg/max %s/%s ms.' % tuple(rtt) value = '%s/%s ms' % tuple(rtt)",
"ms avg (> %s ms)' % (avg, PING_SLOW_CRITICAL) elif avg > PING_SLOW_WARNING: event",
"= 'n/a' m = re.search('(?P<min>\\d+\\.\\d+)/(?P<avg>\\d+\\.\\d+)/(?P<max>\\d+\\.\\d+)/(?P<mdev>\\d+\\.\\d+)\\s+ms', stdout) if m: rtt = (float(m.group('avg')), float(m.group('max'))) else:",
"'PingFailed' severity = 'major' text = 'Node did not respond to ping or",
"stderr=subprocess.STDOUT) stdout = ping.communicate()[0].rstrip('\\n') rc = ping.returncode LOG.debug('Ping %s => %s (rc=%d)', cmd,",
"ping_list: if 'targets' in p and p['targets']: for target in p['targets']: environment =",
"time import subprocess import threading import Queue import re import logging import yaml",
"retries - 1, time.time())) self.queue.task_done() continue if rc == PING_OK: avg, max =",
"stdout) if m: rtt = (float(m.group('avg')), float(m.group('max'))) else: rtt = (0, 0) if",
"Initialise Rules def init_targets(): targets = list() LOG.info('Loading Ping targets...') try: targets =",
"times', resource, retries) self.queue.put((environment, service, resource, retries - 1, time.time())) self.queue.task_done() continue if",
"api, queue): threading.Thread.__init__(self) LOG.debug('Initialising %s...', self.getName()) self.last_event = {} self.queue = queue #",
"seconds' % PING_MAX_TIMEOUT value = '%s%% packet loss' % loss elif rc ==",
"import re import logging import yaml from alertaclient.api import Client __version__ = '3.3.0'",
"rtt, loss, stdout = self.pinger(resource, count=2, timeout=5) else: rc, rtt, loss, stdout =",
"down.', self.getName()) break environment, service, resource, retries, queue_time = item if time.time() -",
"ping.communicate()[0].rstrip('\\n') rc = ping.returncode LOG.debug('Ping %s => %s (rc=%d)', cmd, stdout, rc) m",
"PING_OK and retries: LOG.info('Retrying ping %s %s more times', resource, retries) self.queue.put((environment, service,",
"'PingSlow', 'PingOK', 'PingError', ] PING_OK = 0 # all ping replies received within",
"0) if rc == 0: LOG.info('%s: is alive %s', node, rtt) else: LOG.info('%s:",
"self.api.heartbeat(origin, tags=[__version__]) except Exception as e: LOG.warning('Failed to send heartbeat: %s', e) time.sleep(LOOP_EVERY)",
"resource value = stdout else: LOG.warning('Unknown ping return code: %s', rc) continue #",
"not start: %s', i, e) continue LOG.info('Started worker thread: %s', w.getName()) while not",
"%s.' % resource value = stdout else: LOG.warning('Unknown ping return code: %s', rc)",
"while True: LOG.debug('Waiting on input queue...') item = self.queue.get() if not item: LOG.info('%s",
"in p['targets']: environment = p['environment'] service = p['service'] retries = p.get('retries', PING_MAX_RETRIES) self.queue.put((environment,",
"ping or timed out within %s seconds' % PING_MAX_TIMEOUT value = '%s%% packet",
"= stdout else: LOG.warning('Unknown ping return code: %s', rc) continue # Defaults resource",
"def init_targets(): targets = list() LOG.info('Loading Ping targets...') try: targets = yaml.load(open(PING_FILE)) except",
"= self.queue.get() if not item: LOG.info('%s is shutting down.', self.getName()) break environment, service,",
"= rtt if avg > PING_SLOW_CRITICAL: event = 'PingSlow' severity = 'critical' text",
"stdout=subprocess.PIPE, stderr=subprocess.STDOUT) stdout = ping.communicate()[0].rstrip('\\n') rc = ping.returncode LOG.debug('Ping %s => %s (rc=%d)',",
"# Create internal queue self.queue = Queue.Queue() self.api = Client() # Initialiase ping",
"# some or all ping replies not received or did not respond within",
"received within timeout PING_FAILED = 1 # some or all ping replies not",
"Exception as e: LOG.warning('Failed to send heartbeat: %s', e) time.sleep(LOOP_EVERY) LOG.info('Ping queue length",
"loss', stdout) if m: loss = m.group('loss') else: loss = 'n/a' m =",
"'PingError', ] PING_OK = 0 # all ping replies received within timeout PING_FAILED",
"= self.pinger(resource, count=2, timeout=5) else: rc, rtt, loss, stdout = self.pinger(resource, count=5, timeout=PING_MAX_TIMEOUT)",
"node) return rc, rtt, loss, stdout class PingerDaemon(object): def __init__(self): self.shuttingdown = False",
"self.getName()) self.last_event = {} self.queue = queue # internal queue self.api = api",
"sys.platform == \"darwin\": cmd = \"ping -q -c %s -i %s -t %s",
"list() LOG.info('Loading Ping targets...') try: targets = yaml.load(open(PING_FILE)) except Exception as e: LOG.error('Failed",
"event_type='serviceAlert', raw_data=raw_data, ) except Exception as e: LOG.warning('Failed to send alert: %s', e)",
"= 0 # all ping replies received within timeout PING_FAILED = 1 #",
"loss elif rc == PING_ERROR: event = 'PingError' severity = 'warning' text =",
"item = self.queue.get() if not item: LOG.info('%s is shutting down.', self.getName()) break environment,",
"True # Create internal queue self.queue = Queue.Queue() self.api = Client() # Initialiase",
"% (count, interval, timeout, node) else: cmd = \"ping -q -c %s -i",
"__version__ = '3.3.0' LOG = logging.getLogger('alerta.pinger') LOG.setLevel(logging.DEBUG) LOG.addHandler(logging.StreamHandler()) PING_FILE = 'alert-pinger.targets' PING_MAX_TIMEOUT =",
"try: w.start() except Exception as e: LOG.error('Worker thread #%s did not start: %s',",
"= 500 # ms SERVER_THREAD_COUNT = 20 LOOP_EVERY = 30 _PING_ALERTS = [",
"# internal queue self.api = api # message broker def run(self): while True:",
"except Exception as e: LOG.warning('Failed to send alert: %s', e) self.queue.task_done() LOG.info('%s ping",
"group=group, value=value, severity=severity, environment=environment, service=service, text=text, event_type='serviceAlert', raw_data=raw_data, ) except Exception as e:",
"OK', len(targets)) return targets class WorkerThread(threading.Thread): def __init__(self, api, queue): threading.Thread.__init__(self) LOG.debug('Initialising %s...',",
"# ms PING_SLOW_CRITICAL = 500 # ms SERVER_THREAD_COUNT = 20 LOOP_EVERY = 30",
"def run(self): self.running = True # Create internal queue self.queue = Queue.Queue() self.api",
"= re.search('(?P<min>\\d+\\.\\d+)/(?P<avg>\\d+\\.\\d+)/(?P<max>\\d+\\.\\d+)/(?P<mdev>\\d+\\.\\d+)\\s+ms', stdout) if m: rtt = (float(m.group('avg')), float(m.group('max'))) else: rtt = (0,",
"% PING_MAX_TIMEOUT value = '%s%% packet loss' % loss elif rc == PING_ERROR:",
"continue if rc == PING_OK: avg, max = rtt if avg > PING_SLOW_CRITICAL:",
"count * interval: timeout = count * interval + 1 if timeout >",
"resource) if retries > 1: rc, rtt, loss, stdout = self.pinger(resource, count=2, timeout=5)",
"PING_MAX_RETRIES) self.queue.put((environment, service, target, retries, time.time())) LOG.debug('Send heartbeat...') try: origin = '{}/{}'.format('pinger', platform.uname()[1])",
"LOG.addHandler(logging.StreamHandler()) PING_FILE = 'alert-pinger.targets' PING_MAX_TIMEOUT = 15 # seconds PING_MAX_RETRIES = 2 PING_SLOW_WARNING",
"in %s ms avg (> %s ms)' % (avg, PING_SLOW_WARNING) else: event =",
"= yaml.load(open(PING_FILE)) except Exception as e: LOG.error('Failed to load Ping targets: %s', e)",
"p['environment'] service = p['service'] retries = p.get('retries', PING_MAX_RETRIES) self.queue.put((environment, service, target, retries, time.time()))",
"to ping or timed out within %s seconds' % PING_MAX_TIMEOUT value = '%s%%",
"Exception as e: LOG.error('Worker thread #%s did not start: %s', i, e) continue",
"in ping_list: if 'targets' in p and p['targets']: for target in p['targets']: environment",
"did not respond to ping or timed out within %s seconds' % PING_MAX_TIMEOUT",
"internal queue self.api = api # message broker def run(self): while True: LOG.debug('Waiting",
"more times', resource, retries) self.queue.put((environment, service, resource, retries - 1, time.time())) self.queue.task_done() continue",
"e: LOG.error('Worker thread #%s did not start: %s', i, e) continue LOG.info('Started worker",
"severity = 'normal' text = 'Node responding to ping avg/max %s/%s ms.' %",
"LOG.error('Failed to load Ping targets: %s', e) LOG.info('Loaded %d Ping targets OK', len(targets))",
"= 'PingFailed' severity = 'major' text = 'Node did not respond to ping",
"%d', self.queue.qsize()) except (KeyboardInterrupt, SystemExit): self.shuttingdown = True LOG.info('Shutdown request received...') self.running =",
"ms SERVER_THREAD_COUNT = 20 LOOP_EVERY = 30 _PING_ALERTS = [ 'PingFailed', 'PingSlow', 'PingOK',",
"resource, int(time.time() - queue_time)) self.queue.task_done() continue LOG.info('%s pinging %s...', self.getName(), resource) if retries",
"# Start worker threads LOG.debug('Starting %s worker threads...', SERVER_THREAD_COUNT) for i in range(SERVER_THREAD_COUNT):",
"alertaclient.api import Client __version__ = '3.3.0' LOG = logging.getLogger('alerta.pinger') LOG.setLevel(logging.DEBUG) LOG.addHandler(logging.StreamHandler()) PING_FILE =",
"replies received within timeout PING_FAILED = 1 # some or all ping replies",
"responded to ping in %s ms avg (> %s ms)' % (avg, PING_SLOW_WARNING)",
"%s complete.', self.getName(), resource) self.queue.task_done() @staticmethod def pinger(node, count=1, interval=1, timeout=5): if timeout",
"cmd = \"ping -q -c %s -i %s -t %s %s\" % (count,",
"severity=severity, environment=environment, service=service, text=text, event_type='serviceAlert', raw_data=raw_data, ) except Exception as e: LOG.warning('Failed to",
"self.queue.put(None) w.join() def main(): pinger = PingerDaemon() pinger.run() if __name__ == '__main__': main()",
"import sys import platform import time import subprocess import threading import Queue import",
"with ping # Initialise Rules def init_targets(): targets = list() LOG.info('Loading Ping targets...')",
"timeout=PING_MAX_TIMEOUT) if rc != PING_OK and retries: LOG.info('Retrying ping %s %s more times',",
"avg (> %s ms)' % (avg, PING_SLOW_CRITICAL) elif avg > PING_SLOW_WARNING: event =",
"responded to ping in %s ms avg (> %s ms)' % (avg, PING_SLOW_CRITICAL)",
"platform import time import subprocess import threading import Queue import re import logging",
"raw_data = stdout try: self.api.send_alert( resource=resource, event=event, correlate=correlate, group=group, value=value, severity=severity, environment=environment, service=service,",
"logging import yaml from alertaclient.api import Client __version__ = '3.3.0' LOG = logging.getLogger('alerta.pinger')",
"queue...') item = self.queue.get() if not item: LOG.info('%s is shutting down.', self.getName()) break",
"%s\" % (count, interval, timeout, node) ping = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE, stderr=subprocess.STDOUT) stdout =",
"target, retries, time.time())) LOG.debug('Send heartbeat...') try: origin = '{}/{}'.format('pinger', platform.uname()[1]) self.api.heartbeat(origin, tags=[__version__]) except",
"run(self): while True: LOG.debug('Waiting on input queue...') item = self.queue.get() if not item:",
"send alert: %s', e) self.queue.task_done() LOG.info('%s ping %s complete.', self.getName(), resource) self.queue.task_done() @staticmethod",
"%s => %s (rc=%d)', cmd, stdout, rc) m = re.search('(?P<loss>\\d+(\\.\\d+)?)% packet loss', stdout)",
"20 LOOP_EVERY = 30 _PING_ALERTS = [ 'PingFailed', 'PingSlow', 'PingOK', 'PingError', ] PING_OK",
"%d Ping targets OK', len(targets)) return targets class WorkerThread(threading.Thread): def __init__(self, api, queue):",
"PING_SLOW_WARNING: event = 'PingSlow' severity = 'warning' text = 'Node responded to ping",
"import platform import time import subprocess import threading import Queue import re import",
"max = rtt if avg > PING_SLOW_CRITICAL: event = 'PingSlow' severity = 'critical'",
"%s %s more times', resource, retries) self.queue.put((environment, service, resource, retries - 1, time.time()))",
"%s worker threads...', SERVER_THREAD_COUNT) for i in range(SERVER_THREAD_COUNT): w = WorkerThread(self.api, self.queue) try:",
"retries, time.time())) LOG.debug('Send heartbeat...') try: origin = '{}/{}'.format('pinger', platform.uname()[1]) self.api.heartbeat(origin, tags=[__version__]) except Exception",
"retries) self.queue.put((environment, service, resource, retries - 1, time.time())) self.queue.task_done() continue if rc ==",
"= 'major' text = 'Node did not respond to ping or timed out",
"def run(self): while True: LOG.debug('Waiting on input queue...') item = self.queue.get() if not",
"= '3.3.0' LOG = logging.getLogger('alerta.pinger') LOG.setLevel(logging.DEBUG) LOG.addHandler(logging.StreamHandler()) PING_FILE = 'alert-pinger.targets' PING_MAX_TIMEOUT = 15",
"ping targets ping_list = init_targets() # Start worker threads LOG.debug('Starting %s worker threads...',",
"pinging %s...', self.getName(), resource) if retries > 1: rc, rtt, loss, stdout =",
"count=2, timeout=5) else: rc, rtt, loss, stdout = self.pinger(resource, count=5, timeout=PING_MAX_TIMEOUT) if rc",
"%s -i %s -w %s %s\" % (count, interval, timeout, node) ping =",
"range(SERVER_THREAD_COUNT): w = WorkerThread(self.api, self.queue) try: w.start() except Exception as e: LOG.error('Worker thread",
"rtt = (float(m.group('avg')), float(m.group('max'))) else: rtt = (0, 0) if rc == 0:",
"0: LOG.info('%s: is alive %s', node, rtt) else: LOG.info('%s: not responding', node) return",
"some or all ping replies not received or did not respond within timeout",
"Ping targets OK', len(targets)) return targets class WorkerThread(threading.Thread): def __init__(self, api, queue): threading.Thread.__init__(self)",
"self.api = api # message broker def run(self): while True: LOG.debug('Waiting on input",
"(avg, PING_SLOW_CRITICAL) elif avg > PING_SLOW_WARNING: event = 'PingSlow' severity = 'warning' text",
"stdout = ping.communicate()[0].rstrip('\\n') rc = ping.returncode LOG.debug('Ping %s => %s (rc=%d)', cmd, stdout,",
"SystemExit): self.shuttingdown = True LOG.info('Shutdown request received...') self.running = False for i in",
"not received or did not respond within timeout PING_ERROR = 2 # unspecified",
"= _PING_ALERTS raw_data = stdout try: self.api.send_alert( resource=resource, event=event, correlate=correlate, group=group, value=value, severity=severity,",
") except Exception as e: LOG.warning('Failed to send alert: %s', e) self.queue.task_done() LOG.info('%s",
"continue LOG.info('Started worker thread: %s', w.getName()) while not self.shuttingdown: try: for p in",
"import subprocess import threading import Queue import re import logging import yaml from",
"= 'PingError' severity = 'warning' text = 'Could not ping node %s.' %",
"e) LOG.info('Loaded %d Ping targets OK', len(targets)) return targets class WorkerThread(threading.Thread): def __init__(self,",
"p['targets']: environment = p['environment'] service = p['service'] retries = p.get('retries', PING_MAX_RETRIES) self.queue.put((environment, service,",
"start: %s', i, e) continue LOG.info('Started worker thread: %s', w.getName()) while not self.shuttingdown:",
"-w %s %s\" % (count, interval, timeout, node) ping = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE, stderr=subprocess.STDOUT)",
"not self.shuttingdown: try: for p in ping_list: if 'targets' in p and p['targets']:",
"\"ping -q -c %s -i %s -t %s %s\" % (count, interval, timeout,",
"if rc == PING_OK: avg, max = rtt if avg > PING_SLOW_CRITICAL: event",
"e: LOG.error('Failed to load Ping targets: %s', e) LOG.info('Loaded %d Ping targets OK',",
"self.queue = queue # internal queue self.api = api # message broker def",
"== PING_FAILED: event = 'PingFailed' severity = 'major' text = 'Node did not",
"text = 'Node responding to ping avg/max %s/%s ms.' % tuple(rtt) value =",
"within timeout PING_FAILED = 1 # some or all ping replies not received",
"rc == PING_ERROR: event = 'PingError' severity = 'warning' text = 'Could not",
"class PingerDaemon(object): def __init__(self): self.shuttingdown = False def run(self): self.running = True #",
"item: LOG.info('%s is shutting down.', self.getName()) break environment, service, resource, retries, queue_time =",
"PING_SLOW_WARNING) else: event = 'PingOK' severity = 'normal' text = 'Node responding to",
"targets OK', len(targets)) return targets class WorkerThread(threading.Thread): def __init__(self, api, queue): threading.Thread.__init__(self) LOG.debug('Initialising",
"not ping node %s.' % resource value = stdout else: LOG.warning('Unknown ping return",
"'normal' text = 'Node responding to ping avg/max %s/%s ms.' % tuple(rtt) value",
"* interval: timeout = count * interval + 1 if timeout > PING_MAX_TIMEOUT:",
"(KeyboardInterrupt, SystemExit): self.shuttingdown = True LOG.info('Shutdown request received...') self.running = False for i",
"except Exception as e: LOG.error('Failed to load Ping targets: %s', e) LOG.info('Loaded %d",
"cmd = \"ping -q -c %s -i %s -w %s %s\" % (count,",
"LOG.info('Started worker thread: %s', w.getName()) while not self.shuttingdown: try: for p in ping_list:",
"threads...', SERVER_THREAD_COUNT) for i in range(SERVER_THREAD_COUNT): w = WorkerThread(self.api, self.queue) try: w.start() except",
"queue # internal queue self.api = api # message broker def run(self): while",
"service, resource, retries - 1, time.time())) self.queue.task_done() continue if rc == PING_OK: avg,",
"= 'Node responded to ping in %s ms avg (> %s ms)' %",
"-q -c %s -i %s -t %s %s\" % (count, interval, timeout, node)",
"m: rtt = (float(m.group('avg')), float(m.group('max'))) else: rtt = (0, 0) if rc ==",
"text = 'Node did not respond to ping or timed out within %s",
"to send heartbeat: %s', e) time.sleep(LOOP_EVERY) LOG.info('Ping queue length is %d', self.queue.qsize()) except",
"self.shuttingdown = True LOG.info('Shutdown request received...') self.running = False for i in range(SERVER_THREAD_COUNT):",
"= list() LOG.info('Loading Ping targets...') try: targets = yaml.load(open(PING_FILE)) except Exception as e:",
"time.time())) self.queue.task_done() continue if rc == PING_OK: avg, max = rtt if avg",
"== \"darwin\": cmd = \"ping -q -c %s -i %s -t %s %s\"",
"-q -c %s -i %s -w %s %s\" % (count, interval, timeout, node)",
"(float(m.group('avg')), float(m.group('max'))) else: rtt = (0, 0) if rc == 0: LOG.info('%s: is",
"% loss elif rc == PING_ERROR: event = 'PingError' severity = 'warning' text",
"elif rc == PING_FAILED: event = 'PingFailed' severity = 'major' text = 'Node",
"and p['targets']: for target in p['targets']: environment = p['environment'] service = p['service'] retries",
"(avg, PING_SLOW_WARNING) else: event = 'PingOK' severity = 'normal' text = 'Node responding",
"> PING_SLOW_CRITICAL: event = 'PingSlow' severity = 'critical' text = 'Node responded to",
"service = p['service'] retries = p.get('retries', PING_MAX_RETRIES) self.queue.put((environment, service, target, retries, time.time())) LOG.debug('Send"
] |
[
"sizes[column_or_row] = int(sizing[1](area_size, remaining_size)) calculate_custom_sizes(column_sizings_by_type, column_widths, area.w, area.w - sum(column_widths)) calculate_custom_sizes(row_sizings_by_type, row_heights, area.h,",
"spacing=3) for column in range(grid.column_count): grid.set_child_column_sizing(column) for row in range(grid.row_count): grid.set_child_row_sizing(row) self.assertEqual(0, grid.widest_child_in_column(2))",
"= int(287 * (1 - 0.8139)) self.assertEqual(Panel.Rect(2, 3, width_0, height_0), child_0_0.rect_outer) self.assertEqual(Panel.Rect(2, 8",
"column_widths, self.widest_child_in_column) calculate_child_sizes(row_sizings_by_type, row_heights, self.tallest_child_in_row) def calculate_percentage_sizes(sizings_by_type, sizes, area_size): for sizing_tuple in sizings_by_type.get(self.PERCENTAGE,",
"grid = GridLayout(column_count=20, row_count=20, spacing=5) grid.add_rect(self.gui.create(Panel), rect_left) self.assertEqual(empty, grid.area_empty(rect_right)) def test_single_fixed(self): grid =",
"grid.tallest_child_in_row(2)) def test_tallest_child_in_column_or_row_2(self): def create_grid(): grid = GridLayout(column_count=5, row_count=5, spacing=3) for column in",
"self.parent.margins = (20, 30, 40, 50) def test_tallest_child_in_column_or_row_1(self): grid = GridLayout(column_count=5, row_count=5, spacing=3)",
"of width) | 1px # | Custom (custom function) | configurable # |",
"1 height_1 = int(287 * 0.5) self.assertEqual(Panel.Rect(2, 3, width_0, height_0), child_0_0.rect_outer) self.assertEqual(Panel.Rect(2, 8",
"1, 1, 1)) grid.layout(self.parent) self.assertEqual(Panel.Rect( 2, 3, 101, 18), child_0_0.rect_outer) self.assertEqual(Panel.Rect(108, 3, 19,",
"# In case a panel spans multiple columns, determine the height as a",
"= (66, 38) grid.add_rect(child, Rect(2, 1, 3, 2)) self.assertEqual(20, grid.widest_child_in_column(2)) self.assertEqual(20, grid.widest_child_in_column(3)) self.assertEqual(20,",
"# proportional amount. return int((panel.rect_outer.h - (rect.h - 1) * self.spacing) / rect.h)",
"row_sizings_by_type.get(self.FILL, []) if fill_rows: row_heights[fill_rows[0][0]] = area.h - sum(row_heights) # Allocate extra width",
"9), True), ] for rect_left, rect_right, empty in scenarios: with self.subTest(rect_left=rect_left, rect_right=rect_right, empty=empty):",
"= (panel.rect_inner .move(-panel.x, -panel.y) .shrink( 0, 0, (self.column_count - 1) * self.spacing, (self.row_count",
"grid.set_even_row_sizing(0) grid.set_even_row_sizing(1) def create_child(rect): child = self.gui.create(Panel) child.parent = self.parent child.padding = (10,",
"= largest_func(column_or_row) calculate_child_sizes(column_sizings_by_type, column_widths, self.widest_child_in_column) calculate_child_sizes(row_sizings_by_type, row_heights, self.tallest_child_in_row) def calculate_percentage_sizes(sizings_by_type, sizes, area_size): for",
"function) | configurable # | Even (equally divide) | 1px # | Fill",
"0, 1, 1)) child_1_1 = create_child(Rect(1, 1, 1, 1)) grid.layout(self.parent) width_0 = int(189",
"sizing)) row_sizings_by_type[sizing[0]] = group # Determine column widths and row heights. column_widths =",
"(11, 16, 8, 2) child.size = (53, 81) grid.add(child, 0, 0) grid.layout(self.parent) width",
"# Since even sizing is the default we should make sure it works",
"grid.add(child, 0, 0) grid.layout(self.parent) self.assertEqual(Panel.Rect(13, 19, 175, 274), child.rect) def test_multiple_fill(self): grid =",
"child_1_0 = create_child(Rect(1, 0, 1, 1)) child_1_1 = create_child(Rect(1, 1, 1, 1)) grid.layout(self.parent)",
"# | Even (equally divide) | 1px # | Fill (use remaining space)",
"= int(287 * 0.5) + 1 height_1 = int(287 * 0.5) self.assertEqual(Panel.Rect(2, 3,",
"row_count=2, spacing=5) grid.set_percentage_column_sizing(0, 0.333) grid.set_percentage_column_sizing(1, 0.333) grid.set_percentage_row_sizing(0, 0.8139) grid.set_percentage_row_sizing(1, 1 - 0.8139) def",
"self.column_sizings[column] = (self.CHILD,) def set_child_row_sizing(self, row): self.row_sizings[row] = (self.CHILD,) def set_percentage_column_sizing(self, column, percentage):",
"= (self.FILL,) def set_fill_row_sizing(self, row): self.row_sizings[row] = (self.FILL,) def widest_child_in_column(self, column): column_rect =",
"def custom_sizing(area_size, remaining_size): return area_size ** 0.5 def custom_extra(extra): return extra / 2",
"# # The types of sizing in the table above are ordered in",
") column_sizings_by_type = dict() row_sizings_by_type = dict() # Group columns and rows by",
"child_1_1.rect_outer) def test_single_child(self): grid = GridLayout(spacing=5) grid.set_child_column_sizing(0) grid.set_child_row_sizing(0) child = self.gui.create(Panel) child.parent =",
"column): self.column_sizings[column] = (self.FILL,) def set_fill_row_sizing(self, row): self.row_sizings[row] = (self.FILL,) def widest_child_in_column(self, column):",
"= allocate_extra_even(column_sizings_by_type, column_widths, extra_width) extra_height = allocate_extra_even(row_sizings_by_type, row_heights, extra_height) # Save column widths",
"0, 4, 2), Rect(1, 1, 9, 9), False), (Rect(10, 2, 4, 4), Rect(1,",
"rows. extra_width = max(area.w - sum(column_widths), 0) extra_height = max(area.h - sum(row_heights), 0)",
"panel grid.add(child, column, row) grid.layout(panel) def main(): from desky.gui import example #example(grid_example) unittest.main()",
"extra_func=zero_func): self.column_sizings[column] = (self.CUSTOM, sizing_func, extra_func) def set_custom_row_sizing(self, row, sizing_func, extra_func=zero_func): self.row_sizings[row] =",
"for sizing_tuple in sizings_by_type.get(self.CUSTOM, []): column_or_row, sizing = sizing_tuple sizes[column_or_row] = int(sizing[1](area_size, remaining_size))",
"grid = GridLayout(column_count=2, row_count=2, spacing=5) grid.set_child_column_sizing(0) grid.set_child_column_sizing(1) grid.set_child_row_sizing(0) grid.set_child_row_sizing(1) def create_child(rect, size): child",
"grid.set_child_column_sizing(column) for row in range(grid.row_count): grid.set_child_row_sizing(row) return grid with self.subTest(\"column\"): grid = create_grid()",
"width_0, 3, width_1, height_0), child_1_0.rect_outer) self.assertEqual(Panel.Rect(7 + width_0, 8 + height_0, width_1, height_1),",
"height_1), child_0_1.rect_outer) self.assertEqual(Panel.Rect(7 + width_0, 3, width_1, height_0), child_1_0.rect_outer) self.assertEqual(Panel.Rect(7 + width_0, 8",
"columns and rows by their sizing types while preserving the order. for column",
"self.row_count = row_count self.spacing = spacing def add(self, panel, column, row, column_count=1, row_count=1):",
"= panel def remove(self, panel): self.panels = valfilter(lambda p: p != panel, self.panels)",
"- sum(row_heights) # Allocate extra width and height to columns and rows. extra_width",
"sum(row_heights[:rect.y]) + rect.y * self.spacing width = sum(column_widths[rect.x:rect.right]) + (rect.w - 1) *",
"- 0.8139)) self.assertEqual(Panel.Rect(2, 3, width_0, height_0), child_0_0.rect_outer) self.assertEqual(Panel.Rect(2, 8 + height_0, width_0, height_1),",
"grid.set_fill_column_sizing(0) grid.set_fill_row_sizing(0) child = self.gui.create(Panel) child.parent = self.parent child.padding = (10, 8, 6,",
"grid = GridLayout(spacing=5) grid.set_fill_column_sizing(0) grid.set_fill_row_sizing(0) child = self.gui.create(Panel) child.parent = self.parent child.padding =",
"4) child.margins = (11, 16, 8, 2) child.size = (9999, 9999) grid.add_rect(child, rect)",
"resulting layout exceeds the bounds of the parent, it is up to the",
"self.column_count, 1) rect_panel_tuples_that_intersect_row = list( filter( lambda rect_panel_tuple: rect_panel_tuple[0].intersects(row_rect), self.panels.items())) def calculate_height(rect_panel_tuple): rect,",
"for rect_other in self.panels.keys(): if rect.intersects(rect_other): return False return True def set_fixed_column_sizing(self, column,",
"1, 1, 1), (61, 31)) child_1_0 = create_child(Rect(1, 0, 1, 2), (25, 87))",
"from desky.rect import Rect from desky.panel import Panel from enum import Enum from",
"self.assertEqual(Panel.Rect(13, 19, final_width, final_height), child.rect) def test_multiple_custom(self): def custom_sizing_1(area_size, remaining_size): return area_size **",
"Position child panels. for rect, panel in self.panels.items(): x = area.x + sum(column_widths[:rect.x])",
"sizes): for sizing_tuple in sizings_by_type.get(self.FIXED, []): column_or_row, sizing = sizing_tuple sizes[column_or_row] = sizing[1]",
"sizing_tuple in sizings_by_type.get(self.PERCENTAGE, []): column_or_row, _ = sizing_tuple amount = min(extra, 1) sizes[column_or_row]",
"sizings are evaluated first. Custom is then # evaluated and is given the",
"reduce(max, map(calculate_height, rect_panel_tuples_that_intersect_row), 0) def layout(self, panel): area = (panel.rect_inner .move(-panel.x, -panel.y) .shrink(",
"while preserving the order. for column in range(self.column_count): sizing = self.column_sizings.get(column, (self.EVEN,)) group",
"97, 73, 80), child_1_1.rect_outer) def test_multiple_child_2(self): grid = GridLayout(column_count=2, row_count=2, spacing=5) grid.set_child_column_sizing(0) grid.set_child_column_sizing(1)",
"dict() row_sizings_by_type = dict() # Group columns and rows by their sizing types",
"9), False), (Rect(10, 2, 4, 4), Rect(1, 1, 9, 9), True), ] for",
"def zero_func(): return 0 class GridLayout: FIXED = 0 CHILD = 1 PERCENTAGE",
"Gui self.gui = Gui() self.parent = self.gui.create(Panel) self.parent.size = (200, 300) self.parent.padding =",
"final_width, final_height), child.rect) def test_multiple_custom(self): def custom_sizing_1(area_size, remaining_size): return area_size ** 0.8 def",
"0.5) self.assertEqual(Panel.Rect(2, 3, width_0, height_0), child_0_0.rect_outer) self.assertEqual(Panel.Rect(2, 8 + height_0, width_0, height_1), child_0_1.rect_outer)",
"= GridLayout(column_count=2, row_count=2, spacing=5) grid.set_percentage_column_sizing(0, 0.333) grid.set_percentage_column_sizing(1, 0.333) grid.set_percentage_row_sizing(0, 0.8139) grid.set_percentage_row_sizing(1, 1 -",
"child_1_0 = create_child(Rect(1, 0, 1, 1)) child_0_1 = create_child(Rect(0, 1, 1, 1)) child_1_1",
"reduce, partial from toolz.dicttoolz import valfilter # | Type of sizing | Maximum",
"| 0px # | Child (use child size) | 0px # | Percentage",
"and rows to even sizing. for default in (True, False): with self.subTest(default=default): grid",
"grid.add_rect(child, rect) return child child_0_0 = create_child(Rect(0, 0, 1, 1), (58, 39)) child_1_0",
"row in range(self.row_count): sizing = self.row_sizings.get(row, (self.EVEN,)) group = row_sizings_by_type.get(sizing[0], list()) group.append((row, sizing))",
"child_1_0 = create_child(Rect(1, 0, 1, 1), (25, 71)) child_0_1 = create_child(Rect(0, 1, 1,",
"0, 1, 1), (25, 71)) child_0_1 = create_child(Rect(0, 1, 1, 1), (61, 62))",
"0px # | Child (use child size) | 0px # | Percentage (30%",
"column): column_rect = Rect(column, 0, 1, self.row_count) rect_panel_tuples_that_intersect_column = list( filter( lambda rect_panel_tuple:",
"scenarios = [ (Rect(2, 0, 4, 2), Rect(1, 1, 9, 9), False), (Rect(10,",
"= int(189 * 0.3333) width_1 = 189 - int(189 * 0.3333) height_0 =",
"self.subTest(\"column\"): grid = create_grid() child = self.gui.create(Panel) child.size = (66, 38) grid.add_rect(child, Rect(2,",
"scenarios: with self.subTest(rect_left=rect_left, rect_right=rect_right, empty=empty): grid = GridLayout(column_count=20, row_count=20, spacing=5) grid.add_rect(self.gui.create(Panel), rect_left) self.assertEqual(empty,",
"the height as a # proportional amount. return int((panel.rect_outer.h - (rect.h - 1)",
"for default in (True, False): with self.subTest(default=default): grid = GridLayout(spacing=5) if not default:",
"largest_func(column_or_row) calculate_child_sizes(column_sizings_by_type, column_widths, self.widest_child_in_column) calculate_child_sizes(row_sizings_by_type, row_heights, self.tallest_child_in_row) def calculate_percentage_sizes(sizings_by_type, sizes, area_size): for sizing_tuple",
"height_1), child_1_1.rect_outer) def test_single_even(self): # Since even sizing is the default we should",
"rect.w) return reduce(max, map(calculate_width, rect_panel_tuples_that_intersect_column), 0) def tallest_child_in_row(self, row): row_rect = Rect(0, row,",
"/ rect.h) return reduce(max, map(calculate_height, rect_panel_tuples_that_intersect_row), 0) def layout(self, panel): area = (panel.rect_inner",
"+ rect.x * self.spacing y = area.y + sum(row_heights[:rect.y]) + rect.y * self.spacing",
"row in range(grid.row_count): grid.set_child_row_sizing(row) return grid with self.subTest(\"column\"): grid = create_grid() child =",
"grid.widest_child_in_column(2)) with self.subTest(\"column\"): grid = create_grid() child = self.gui.create(Panel) child.size = (38, 60)",
"final_height = root_height + int((292 - root_height) / 2) - 18 self.assertEqual(Panel.Rect(13, 19,",
"0.333) - 19 + 1 height = int(self.parent.rect_inner.h * 0.8) - 18 +",
"self.assertEqual(20, grid.tallest_child_in_row(2)) self.assertEqual(20, grid.tallest_child_in_row(3)) self.assertEqual(20, grid.tallest_child_in_row(4)) def test_area_empty(self): scenarios = [ (Rect(2, 0,",
"[ (Rect(2, 0, 4, 2), Rect(1, 1, 9, 9), False), (Rect(10, 2, 4,",
"** 0.5 def custom_extra(extra): return extra / 2 grid = GridLayout(spacing=5) grid.set_custom_column_sizing(0, custom_sizing,",
"= dict() row_sizings_by_type = dict() # Group columns and rows by their sizing",
"self.row_sizings[row] = (self.CUSTOM, sizing_func, extra_func) def set_even_column_sizing(self, column): self.column_sizings[column] = (self.EVEN,) def set_even_row_sizing(self,",
"self.assertEqual(20, grid.tallest_child_in_row(3)) self.assertEqual(20, grid.tallest_child_in_row(4)) def test_area_empty(self): scenarios = [ (Rect(2, 0, 4, 2),",
"1, 1, 1)) grid.layout(self.parent) self.assertEqual(Panel.Rect( 2, 3, 101, 33), child_0_0.rect_outer) self.assertEqual(Panel.Rect(108, 3, 58,",
"to even sizing. for default in (True, False): with self.subTest(default=default): grid = GridLayout(spacing=5)",
"* self.spacing) ) column_sizings_by_type = dict() row_sizings_by_type = dict() # Group columns and",
"amount. return int((panel.rect_outer.w - (rect.w - 1) * self.spacing) / rect.w) return reduce(max,",
"0, (self.column_count - 1) * self.spacing, (self.row_count - 1) * self.spacing) ) column_sizings_by_type",
"sizes, extra): for sizing_tuple in sizings_by_type.get(self.CUSTOM, []): column_or_row, sizing = sizing_tuple amount =",
"sizing_tuple sizes[column_or_row] = int(sizing[1](area_size, remaining_size)) calculate_custom_sizes(column_sizings_by_type, column_widths, area.w, area.w - sum(column_widths)) calculate_custom_sizes(row_sizings_by_type, row_heights,",
"for column in range(0, grid.column_count): child = gui.create(Panel) child.parent = panel grid.add(child, column,",
"- 0.8139) def create_child(rect): child = self.gui.create(Panel) child.parent = self.parent child.padding = (10,",
"0.8 grid = GridLayout(column_count=2, row_count=2, spacing=5) grid.set_custom_column_sizing(0, custom_sizing_1, partial(min, 1)) grid.set_custom_column_sizing(1, custom_sizing_2, partial(min,",
"= sizing_tuple sizes[column_or_row] = sizing[1] calculate_fixed_sizes(column_sizings_by_type, column_widths) calculate_fixed_sizes(row_sizings_by_type, row_heights) def calculate_child_sizes(sizings_by_type, sizes, largest_func):",
"calculate_child_sizes(sizings_by_type, sizes, largest_func): for sizing_tuple in sizings_by_type.get(self.CHILD, []): column_or_row, _ = sizing_tuple sizes[column_or_row]",
"height_0), child_1_0.rect_outer) self.assertEqual(Panel.Rect(7 + width_0, 8 + height_0, width_1, height_1), child_1_1.rect_outer) def grid_example(gui):",
"child_1_0.rect_outer) self.assertEqual(Panel.Rect( 2, 97, 80, 80), child_0_1.rect_outer) self.assertEqual(Panel.Rect(87, 97, 73, 80), child_1_1.rect_outer) def",
"grid.tallest_child_in_row(2)) self.assertEqual(20, grid.tallest_child_in_row(3)) self.assertEqual(20, grid.tallest_child_in_row(4)) def test_area_empty(self): scenarios = [ (Rect(2, 0, 4,",
"amount = int(sizing[2](extra)) sizes[column_or_row] += amount extra -= amount return extra extra_width =",
"for rect_left, rect_right, empty in scenarios: with self.subTest(rect_left=rect_left, rect_right=rect_right, empty=empty): grid = GridLayout(column_count=20,",
"even sizing. for default in (True, False): with self.subTest(default=default): grid = GridLayout(spacing=5) if",
"percentage): self.row_sizings[row] = (self.PERCENTAGE, percentage) def set_custom_column_sizing(self, column, sizing_func, extra_func=zero_func): self.column_sizings[column] = (self.CUSTOM,",
"1, 1)) child_1_0 = create_child(Rect(1, 0, 1, 1)) child_0_1 = create_child(Rect(0, 1, 1,",
"[]) if fill_rows: row_heights[fill_rows[0][0]] = area.h - sum(row_heights) # Allocate extra width and",
"def set_percentage_row_sizing(self, row, percentage): self.row_sizings[row] = (self.PERCENTAGE, percentage) def set_custom_column_sizing(self, column, sizing_func, extra_func=zero_func):",
"column_widths, area.w - sum(column_widths)) calculate_even_sizes( row_sizings_by_type, row_heights, area.h - sum(row_heights)) fill_columns = column_sizings_by_type.get(self.FILL,",
"(self.FIXED, size) def set_child_column_sizing(self, column): self.column_sizings[column] = (self.CHILD,) def set_child_row_sizing(self, row): self.row_sizings[row] =",
"def test_tallest_child_in_column_or_row_2(self): def create_grid(): grid = GridLayout(column_count=5, row_count=5, spacing=3) for column in range(grid.column_count):",
"* self.spacing height = sum(row_heights[rect.y:rect.bottom]) + (rect.h - 1) * self.spacing panel.rect_outer =",
"row in range(0, grid.row_count): for column in range(0, grid.column_count): child = gui.create(Panel) child.parent",
"space evenly between # themselves. Fill evaluates last and will take the remaining",
"= sizing_tuple amount = int(sizing[2](extra)) sizes[column_or_row] += amount extra -= amount return extra",
"def test_area_empty(self): scenarios = [ (Rect(2, 0, 4, 2), Rect(1, 1, 9, 9),",
"# Allocate extra width and height to columns and rows. extra_width = max(area.w",
"extra_width = max(area.w - sum(column_widths), 0) extra_height = max(area.h - sum(row_heights), 0) def",
"grid.set_fixed_row_sizing(1, 93) def create_child(rect): child = self.gui.create(Panel) child.parent = self.parent child.padding = (10,",
"- root_height) / 2) - 18 self.assertEqual(Panel.Rect(13, 19, final_width, final_height), child.rect) def test_multiple_custom(self):",
"(25, 87)) grid.layout(self.parent) self.assertEqual(Panel.Rect( 2, 3, 80, 50), child_0_0.rect_outer) self.assertEqual(Panel.Rect( 2, 58, 80,",
"Group columns and rows by their sizing types while preserving the order. for",
"grid = GridLayout(column_count=2, row_count=2, spacing=5) grid.set_fixed_column_sizing(0, 101) grid.set_fixed_column_sizing(1, 0) grid.set_fixed_row_sizing(0, 0) grid.set_fixed_row_sizing(1, 93)",
"child panels. for rect, panel in self.panels.items(): x = area.x + sum(column_widths[:rect.x]) +",
"calculate_fixed_sizes(sizings_by_type, sizes): for sizing_tuple in sizings_by_type.get(self.FIXED, []): column_or_row, sizing = sizing_tuple sizes[column_or_row] =",
"calculate_fixed_sizes(row_sizings_by_type, row_heights) def calculate_child_sizes(sizings_by_type, sizes, largest_func): for sizing_tuple in sizings_by_type.get(self.CHILD, []): column_or_row, _",
"= allocate_extra_even(row_sizings_by_type, row_heights, extra_height) # Save column widths and row heights for users",
"root_height) / 2) - 18 self.assertEqual(Panel.Rect(13, 19, final_width, final_height), child.rect) def test_multiple_custom(self): def",
"0.3333) grid.set_fill_column_sizing(1) grid.set_fill_row_sizing(0) grid.set_fixed_row_sizing(1, 100) def create_child(rect): child = self.gui.create(Panel) child.parent = self.parent",
"in self.panels.keys(): if rect.intersects(rect_other): return False return True def set_fixed_column_sizing(self, column, size): self.column_sizings[column]",
"test_multiple_even(self): grid = GridLayout(column_count=2, row_count=2, spacing=5) grid.set_even_column_sizing(0) grid.set_even_column_sizing(1) grid.set_even_row_sizing(0) grid.set_even_row_sizing(1) def create_child(rect): child",
"layout(self, panel): area = (panel.rect_inner .move(-panel.x, -panel.y) .shrink( 0, 0, (self.column_count - 1)",
"Type of sizing | Maximum extra width allocation # -------------------------------------------------------------- # | Fixed",
"empty in scenarios: with self.subTest(rect_left=rect_left, rect_right=rect_right, empty=empty): grid = GridLayout(column_count=20, row_count=20, spacing=5) grid.add_rect(self.gui.create(Panel),",
"= area.h - sum(row_heights) # Allocate extra width and height to columns and",
"rect_panel_tuple: rect_panel_tuple[0].intersects(column_rect), self.panels.items())) def calculate_width(rect_panel_tuple): rect, panel = rect_panel_tuple # In case a",
"31)) child_0_1 = create_child(Rect(0, 1, 1, 1), (61, 31)) child_1_0 = create_child(Rect(1, 0,",
"max(area.w - sum(column_widths), 0) extra_height = max(area.h - sum(row_heights), 0) def allocate_extra_percentage(sizings_by_type, sizes,",
"18), child_1_0.rect_outer) self.assertEqual(Panel.Rect( 2, 8, 101, 93), child_0_1.rect_outer) self.assertEqual(Panel.Rect(108, 8, 19, 93), child_1_1.rect_outer)",
"column, percentage): self.column_sizings[column] = (self.PERCENTAGE, percentage) def set_percentage_row_sizing(self, row, percentage): self.row_sizings[row] = (self.PERCENTAGE,",
"child_1_0.rect_outer) self.assertEqual(Panel.Rect( 2, 8, 101, 93), child_0_1.rect_outer) self.assertEqual(Panel.Rect(108, 8, 19, 93), child_1_1.rect_outer) def",
"partial(min, 1)) grid.set_custom_row_sizing(0, custom_sizing_2, partial(min, 1)) grid.set_custom_row_sizing(1, custom_sizing_1, partial(min, 1)) def create_child(rect): child",
"101, 93), child_0_1.rect_outer) self.assertEqual(Panel.Rect(108, 8, 19, 93), child_1_1.rect_outer) def test_single_child(self): grid = GridLayout(spacing=5)",
"self.assertEqual(Panel.Rect(87, 97, 73, 80), child_1_1.rect_outer) def test_multiple_child_2(self): grid = GridLayout(column_count=2, row_count=2, spacing=5) grid.set_child_column_sizing(0)",
"500) panel.padding = (8, 16, 24, 32) grid = GridLayout(column_count = 3, row_count",
"rect_other in self.panels.keys(): if rect.intersects(rect_other): return False return True def set_fixed_column_sizing(self, column, size):",
"- root_width) / 2) - 19 final_height = root_height + int((292 - root_height)",
"grid.set_child_column_sizing(0) grid.set_child_row_sizing(0) child = self.gui.create(Panel) child.parent = self.parent child.padding = (10, 8, 6,",
"in scenarios: with self.subTest(rect_left=rect_left, rect_right=rect_right, empty=empty): grid = GridLayout(column_count=20, row_count=20, spacing=5) grid.add_rect(self.gui.create(Panel), rect_left)",
"heights for users to access. self.column_widths = column_widths self.row_heights = row_heights # Position",
"height_1), child_1_1.rect_outer) def grid_example(gui): panel = gui.create(Panel) panel.rect = (50, 50, 500, 500)",
"grid = create_grid() child = self.gui.create(Panel) child.size = (38, 60) grid.add(child, 1, 2)",
"300) self.parent.padding = (2, 3, 4, 5) self.parent.margins = (20, 30, 40, 50)",
"_ = sizing_tuple amount = min(extra, 1) sizes[column_or_row] += amount extra -= amount",
"1, 1)) child_1_1 = create_child(Rect(1, 1, 1, 1)) grid.layout(self.parent) width_0 = int(189 *",
"for sizing_tuple in sizings_by_type.get(self.EVEN, []): column_or_row, _ = sizing_tuple sizes[column_or_row] = size calculate_even_sizes(",
"row, column_count, row_count)) def add_rect(self, panel, rect): assert(rect.x >= 0) assert(rect.y >= 0)",
"int(287 * 0.8139) + 1 height_1 = int(287 * (1 - 0.8139)) self.assertEqual(Panel.Rect(2,",
"exceeds the bounds of the parent, it is up to the # parent",
"# parent to decide if it should resize. def zero_func(): return 0 class",
"def calculate_custom_sizes(sizings_by_type, sizes, area_size, remaining_size): for sizing_tuple in sizings_by_type.get(self.CUSTOM, []): column_or_row, sizing =",
"100) def create_child(rect): child = self.gui.create(Panel) child.parent = self.parent child.padding = (10, 8,",
"0): self.panels = dict() self.column_sizings = dict() self.row_sizings = dict() self.column_count = column_count",
"(11, 16, 8, 2) child.size = (53, 81) grid.add(child, 0, 0) grid.layout(self.parent) root_width",
"120) child = self.gui.create(Panel) child.parent = self.parent child.padding = (10, 8, 6, 4)",
"we don't excplicitly set the columns and rows to even sizing. for default",
"add_rect(self, panel, rect): assert(rect.x >= 0) assert(rect.y >= 0) assert(rect.right <= self.column_count) assert(rect.bottom",
"child size) | 0px # | Percentage (30% of width) | 1px #",
"# -------------------------------------------------------------- # | Fixed (200 px) | 0px # | Child (use",
"grid = GridLayout(column_count=5, row_count=5, spacing=3) for column in range(grid.column_count): grid.set_child_column_sizing(column) for row in",
"for sizing_tuple in sizings_by_type.get(self.CHILD, []): column_or_row, _ = sizing_tuple sizes[column_or_row] = largest_func(column_or_row) calculate_child_sizes(column_sizings_by_type,",
"return extra extra_width = allocate_extra_percentage(column_sizings_by_type, column_widths, extra_width) extra_height = allocate_extra_percentage(row_sizings_by_type, row_heights, extra_height) def",
"= list( filter( lambda rect_panel_tuple: rect_panel_tuple[0].intersects(column_rect), self.panels.items())) def calculate_width(rect_panel_tuple): rect, panel = rect_panel_tuple",
"1), (25, 71)) child_0_1 = create_child(Rect(0, 1, 1, 1), (61, 62)) child_1_1 =",
"0) grid.layout(self.parent) self.assertEqual(Panel.Rect(13, 19, 175, 274), child.rect) def test_multiple_even(self): grid = GridLayout(column_count=2, row_count=2,",
"* 0.5) + 1 width_1 = int(189 * 0.5) height_0 = int(287 *",
"0, 0) grid.layout(self.parent) self.assertEqual(Panel.Rect(13, 19, 71, 102), child.rect) def test_multiple_fixed_1(self): grid = GridLayout(column_count=2,",
"0) grid.layout(self.parent) self.assertEqual(Panel.Rect(13, 19, 175, 274), child.rect) def test_multiple_fill(self): grid = GridLayout(column_count=2, row_count=2,",
"+ height_0, width_0, height_1), child_0_1.rect_outer) self.assertEqual(Panel.Rect(7 + width_0, 3, width_1, height_0), child_1_0.rect_outer) self.assertEqual(Panel.Rect(7",
"column_or_row, _ = sizing_tuple amount = min(extra, 1) sizes[column_or_row] += amount extra -=",
"range(grid.row_count): grid.set_child_row_sizing(row) self.assertEqual(0, grid.widest_child_in_column(2)) self.assertEqual(0, grid.tallest_child_in_row(2)) def test_tallest_child_in_column_or_row_2(self): def create_grid(): grid = GridLayout(column_count=5,",
"sizings_by_type.get(self.EVEN, []): column_or_row, _ = sizing_tuple amount = min(extra, 1) sizes[column_or_row] += amount",
"grid.add_rect(child, Rect(2, 1, 3, 2)) self.assertEqual(20, grid.widest_child_in_column(2)) self.assertEqual(20, grid.widest_child_in_column(3)) self.assertEqual(20, grid.widest_child_in_column(4)) with self.subTest(\"row\"):",
"self.subTest(default=default): grid = GridLayout(spacing=5) if not default: grid.set_even_column_sizing(0) grid.set_even_row_sizing(0) child = self.gui.create(Panel) child.parent",
"GridLayout(column_count=2, row_count=2, spacing=5) grid.set_fixed_column_sizing(0, 101) grid.set_fixed_column_sizing(1, 58) grid.set_fixed_row_sizing(0, 33) grid.set_fixed_row_sizing(1, 93) def create_child(rect):",
"height_0 = int(287 * 0.8139) + 1 height_1 = int(287 * (1 -",
"# when we don't excplicitly set the columns and rows to even sizing.",
"the parent, it is up to the # parent to decide if it",
"extra width allocation # -------------------------------------------------------------- # | Fixed (200 px) | 0px #",
"-= amount return extra extra_width = allocate_extra_even(column_sizings_by_type, column_widths, extra_width) extra_height = allocate_extra_even(row_sizings_by_type, row_heights,",
"int(194 ** 0.5) root_height = int(292 ** 0.5) final_width = root_width + int((194",
"= 100 self.assertEqual(Panel.Rect(2, 3, width_0, height_0), child_0_0.rect_outer) self.assertEqual(Panel.Rect(2, 8 + height_0, width_0, height_1),",
"sum(column_widths)) calculate_custom_sizes(row_sizings_by_type, row_heights, area.h, area.h - sum(row_heights)) def calculate_even_sizes(sizings_by_type, sizes, remaining_size): size =",
"19, final_width, final_height), child.rect) def test_multiple_custom(self): def custom_sizing_1(area_size, remaining_size): return area_size ** 0.8",
"sizing_func, extra_func=zero_func): self.row_sizings[row] = (self.CUSTOM, sizing_func, extra_func) def set_even_column_sizing(self, column): self.column_sizings[column] = (self.EVEN,)",
"(self.row_count - 1) * self.spacing) ) column_sizings_by_type = dict() row_sizings_by_type = dict() #",
"* 0.8139) + 1 height_1 = int(287 * (1 - 0.8139)) self.assertEqual(Panel.Rect(2, 3,",
"0, 0, (self.column_count - 1) * self.spacing, (self.row_count - 1) * self.spacing) )",
"Even panels will split remaining space evenly between # themselves. Fill evaluates last",
"90) grid.set_fixed_row_sizing(0, 120) child = self.gui.create(Panel) child.parent = self.parent child.padding = (10, 8,",
"area.y + sum(row_heights[:rect.y]) + rect.y * self.spacing width = sum(column_widths[rect.x:rect.right]) + (rect.w -",
"2) self.assertEqual(60, grid.tallest_child_in_row(2)) def test_tallest_child_in_column_or_row_3(self): def create_grid(): grid = GridLayout(column_count=5, row_count=5, spacing=3) for",
"height_0 = int(287 * 0.5) + 1 height_1 = int(287 * 0.5) self.assertEqual(Panel.Rect(2,",
"in range(grid.row_count): grid.set_child_row_sizing(row) self.assertEqual(0, grid.widest_child_in_column(2)) self.assertEqual(0, grid.tallest_child_in_row(2)) def test_tallest_child_in_column_or_row_2(self): def create_grid(): grid =",
"zero_func(): return 0 class GridLayout: FIXED = 0 CHILD = 1 PERCENTAGE =",
"175, 274), child.rect) def test_multiple_fill(self): grid = GridLayout(column_count=2, row_count=2, spacing=5) grid.set_percentage_column_sizing(0, 0.3333) grid.set_fill_column_sizing(1)",
"max(area.h - sum(row_heights), 0) def allocate_extra_percentage(sizings_by_type, sizes, extra): for sizing_tuple in sizings_by_type.get(self.PERCENTAGE, []):",
"will split remaining space evenly between # themselves. Fill evaluates last and will",
"1, 1)) grid.layout(self.parent) width_0 = int(189 * 0.5) + 1 width_1 = int(189",
"column): self.column_sizings[column] = (self.EVEN,) def set_even_row_sizing(self, row): self.row_sizings[row] = (self.EVEN,) def set_fill_column_sizing(self, column):",
"def test_single_percentage(self): grid = GridLayout(spacing=5) grid.set_percentage_column_sizing(0, 0.333) grid.set_percentage_row_sizing(0, 0.8) child = self.gui.create(Panel) child.parent",
"in sizings_by_type.get(self.PERCENTAGE, []): column_or_row, _ = sizing_tuple amount = min(extra, 1) sizes[column_or_row] +=",
"* 0.5) self.assertEqual(Panel.Rect(2, 3, width_0, height_0), child_0_0.rect_outer) self.assertEqual(Panel.Rect(2, 8 + height_0, width_0, height_1),",
"- (rect.w - 1) * self.spacing) / rect.w) return reduce(max, map(calculate_width, rect_panel_tuples_that_intersect_column), 0)",
"- sum(column_widths), 0) extra_height = max(area.h - sum(row_heights), 0) def allocate_extra_percentage(sizings_by_type, sizes, extra):",
"set_fixed_column_sizing(self, column, size): self.column_sizings[column] = (self.FIXED, size) def set_fixed_row_sizing(self, row, size): self.row_sizings[row] =",
"self.column_sizings[column] = (self.FILL,) def set_fill_row_sizing(self, row): self.row_sizings[row] = (self.FILL,) def widest_child_in_column(self, column): column_rect",
"= (self.CUSTOM, sizing_func, extra_func) def set_even_column_sizing(self, column): self.column_sizings[column] = (self.EVEN,) def set_even_row_sizing(self, row):",
"# proportional amount. return int((panel.rect_outer.w - (rect.w - 1) * self.spacing) / rect.w)",
"column_or_row, sizing = sizing_tuple sizes[column_or_row] = int(area_size * sizing[1]) calculate_percentage_sizes(column_sizings_by_type, column_widths, area.w) calculate_percentage_sizes(row_sizings_by_type,",
"self.assertEqual(Panel.Rect(108, 41, 58, 93), child_1_1.rect_outer) def test_multiple_fixed_2(self): grid = GridLayout(column_count=2, row_count=2, spacing=5) grid.set_fixed_column_sizing(0,",
"by their sizing types while preserving the order. for column in range(self.column_count): sizing",
"def calculate_fixed_sizes(sizings_by_type, sizes): for sizing_tuple in sizings_by_type.get(self.FIXED, []): column_or_row, sizing = sizing_tuple sizes[column_or_row]",
"* self.spacing width = sum(column_widths[rect.x:rect.right]) + (rect.w - 1) * self.spacing height =",
"self.parent child.padding = (10, 8, 6, 4) child.margins = (11, 16, 8, 2)",
"0, 1, 1)) child_0_1 = create_child(Rect(0, 1, 1, 1)) child_1_1 = create_child(Rect(1, 1,",
"+ (rect.w - 1) * self.spacing height = sum(row_heights[rect.y:rect.bottom]) + (rect.h - 1)",
"custom_extra) child = self.gui.create(Panel) child.parent = self.parent child.padding = (10, 8, 6, 4)",
"the default we should make sure it works even # when we don't",
"0.8139) + 1 height_1 = int(287 * (1 - 0.8139)) self.assertEqual(Panel.Rect(2, 3, width_0,",
"= 3, row_count = 4, spacing = 4) for row in range(0, grid.row_count):",
"sizing is the default we should make sure it works even # when",
"amount extra -= amount return extra extra_width = allocate_extra_custom(column_sizings_by_type, column_widths, extra_width) extra_height =",
"grid with self.subTest(\"column\"): grid = create_grid() child = self.gui.create(Panel) child.size = (60, 38)",
"height_0, width_1, height_1), child_1_1.rect_outer) def test_single_fill(self): grid = GridLayout(spacing=5) grid.set_fill_column_sizing(0) grid.set_fill_row_sizing(0) child =",
"8 + height_0, width_1, height_1), child_1_1.rect_outer) def grid_example(gui): panel = gui.create(Panel) panel.rect =",
"row_count=2, spacing=5) grid.set_even_column_sizing(0) grid.set_even_column_sizing(1) grid.set_even_row_sizing(0) grid.set_even_row_sizing(1) def create_child(rect): child = self.gui.create(Panel) child.parent =",
"in range(self.column_count)] row_heights = [0 for _ in range(self.row_count)] def calculate_fixed_sizes(sizings_by_type, sizes): for",
"= 4 FILL = 5 def __init__(self, *, column_count = 1, row_count =",
"users to access. self.column_widths = column_widths self.row_heights = row_heights # Position child panels.",
"66) grid.add_rect(child, Rect(1, 2, 2, 3)) self.assertEqual(20, grid.tallest_child_in_row(2)) self.assertEqual(20, grid.tallest_child_in_row(3)) self.assertEqual(20, grid.tallest_child_in_row(4)) def",
"+ height_0, width_1, height_1), child_1_1.rect_outer) def test_single_custom(self): def custom_sizing(area_size, remaining_size): return area_size **",
"= row_count self.spacing = spacing def add(self, panel, column, row, column_count=1, row_count=1): self.add_rect(panel,",
"(10, 8, 6, 4) child.margins = (11, 16, 8, 2) child.size = size",
"grid.add(child, column, row) grid.layout(panel) def main(): from desky.gui import example #example(grid_example) unittest.main() if",
"rect_right, empty in scenarios: with self.subTest(rect_left=rect_left, rect_right=rect_right, empty=empty): grid = GridLayout(column_count=20, row_count=20, spacing=5)",
"1, 1, 1)) grid.layout(self.parent) width_0 = int(189 * 0.5) + 1 width_1 =",
"- 1) * self.spacing) / rect.h) return reduce(max, map(calculate_height, rect_panel_tuples_that_intersect_row), 0) def layout(self,",
"self.assertEqual(Panel.Rect(13, 19, width, height), child.rect) def test_multiple_percentage(self): grid = GridLayout(column_count=2, row_count=2, spacing=5) grid.set_percentage_column_sizing(0,",
"last and will take the remaining space. # # If the resulting layout",
"determine the height as a # proportional amount. return int((panel.rect_outer.h - (rect.h -",
"= create_child(Rect(0, 0, 1, 1), (58, 39)) child_1_0 = create_child(Rect(1, 0, 1, 1),",
"height_0 = 287 - 100 height_1 = 100 self.assertEqual(Panel.Rect(2, 3, width_0, height_0), child_0_0.rect_outer)",
"extra_width = allocate_extra_percentage(column_sizings_by_type, column_widths, extra_width) extra_height = allocate_extra_percentage(row_sizings_by_type, row_heights, extra_height) def allocate_extra_custom(sizings_by_type, sizes,",
"= (38, 66) grid.add_rect(child, Rect(1, 2, 2, 3)) self.assertEqual(20, grid.tallest_child_in_row(2)) self.assertEqual(20, grid.tallest_child_in_row(3)) self.assertEqual(20,",
"its argument. Even is # evaluated next. Even panels will split remaining space",
"/ rect.w) return reduce(max, map(calculate_width, rect_panel_tuples_that_intersect_column), 0) def tallest_child_in_row(self, row): row_rect = Rect(0,",
"3, 58, 33), child_1_0.rect_outer) self.assertEqual(Panel.Rect( 2, 41, 101, 93), child_0_1.rect_outer) self.assertEqual(Panel.Rect(108, 41, 58,",
"we should make sure it works even # when we don't excplicitly set",
"desky.gui import Gui self.gui = Gui() self.parent = self.gui.create(Panel) self.parent.size = (200, 300)",
"allocation # -------------------------------------------------------------- # | Fixed (200 px) | 0px # | Child",
"(self.PERCENTAGE, percentage) def set_percentage_row_sizing(self, row, percentage): self.row_sizings[row] = (self.PERCENTAGE, percentage) def set_custom_column_sizing(self, column,",
"grid = GridLayout(column_count=2, row_count=2, spacing=5) grid.set_percentage_column_sizing(0, 0.333) grid.set_percentage_column_sizing(1, 0.333) grid.set_percentage_row_sizing(0, 0.8139) grid.set_percentage_row_sizing(1, 1",
"= dict() self.column_count = column_count self.row_count = row_count self.spacing = spacing def add(self,",
"with self.subTest(\"column\"): grid = create_grid() child = self.gui.create(Panel) child.size = (38, 60) grid.add(child,",
"*, column_count = 1, row_count = 1, spacing = 0): self.panels = dict()",
"columns and rows. extra_width = max(area.w - sum(column_widths), 0) extra_height = max(area.h -",
"for sizing_tuple in sizings_by_type.get(self.CUSTOM, []): column_or_row, sizing = sizing_tuple amount = int(sizing[2](extra)) sizes[column_or_row]",
"| Custom (custom function) | configurable # | Even (equally divide) | 1px",
"1, 1), (61, 31)) child_1_0 = create_child(Rect(1, 0, 1, 2), (25, 87)) grid.layout(self.parent)",
"don't excplicitly set the columns and rows to even sizing. for default in",
"= size grid.add_rect(child, rect) return child child_0_0 = create_child(Rect(0, 0, 1, 1), (58,",
"divide) | 1px # | Fill (use remaining space) | any # #",
"8, 2) child.size = (53, 81) grid.add(child, 0, 0) grid.layout(self.parent) self.assertEqual(Panel.Rect(13, 19, 175,",
"1, row_count = 1, spacing = 0): self.panels = dict() self.column_sizings = dict()",
"gui.create(Panel) panel.rect = (50, 50, 500, 500) panel.padding = (8, 16, 24, 32)",
"= create_child(Rect(0, 1, 1, 1)) child_1_1 = create_child(Rect(1, 1, 1, 1)) grid.layout(self.parent) self.assertEqual(Panel.Rect(",
"grid.set_even_column_sizing(1) grid.set_even_row_sizing(0) grid.set_even_row_sizing(1) def create_child(rect): child = self.gui.create(Panel) child.parent = self.parent child.padding =",
"row_heights, self.tallest_child_in_row) def calculate_percentage_sizes(sizings_by_type, sizes, area_size): for sizing_tuple in sizings_by_type.get(self.PERCENTAGE, []): column_or_row, sizing",
"def allocate_extra_custom(sizings_by_type, sizes, extra): for sizing_tuple in sizings_by_type.get(self.CUSTOM, []): column_or_row, sizing = sizing_tuple",
"2, 3, 101, 33), child_0_0.rect_outer) self.assertEqual(Panel.Rect(108, 3, 58, 33), child_1_0.rect_outer) self.assertEqual(Panel.Rect( 2, 41,",
"extra_height = allocate_extra_percentage(row_sizings_by_type, row_heights, extra_height) def allocate_extra_custom(sizings_by_type, sizes, extra): for sizing_tuple in sizings_by_type.get(self.CUSTOM,",
"spacing=5) grid.set_fixed_column_sizing(0, 101) grid.set_fixed_column_sizing(1, 58) grid.set_fixed_row_sizing(0, 33) grid.set_fixed_row_sizing(1, 93) def create_child(rect): child =",
"grid.layout(self.parent) self.assertEqual(Panel.Rect( 2, 3, 101, 33), child_0_0.rect_outer) self.assertEqual(Panel.Rect(108, 3, 58, 33), child_1_0.rect_outer) self.assertEqual(Panel.Rect(",
"remaining space. # # If the resulting layout exceeds the bounds of the",
"def set_fill_column_sizing(self, column): self.column_sizings[column] = (self.FILL,) def set_fill_row_sizing(self, row): self.row_sizings[row] = (self.FILL,) def",
"2) child.size = (53, 81) grid.add(child, 0, 0) grid.layout(self.parent) self.assertEqual(Panel.Rect(13, 19, 71, 102),",
"sizes[column_or_row] = sizing[1] calculate_fixed_sizes(column_sizings_by_type, column_widths) calculate_fixed_sizes(row_sizings_by_type, row_heights) def calculate_child_sizes(sizings_by_type, sizes, largest_func): for sizing_tuple",
"int(self.parent.rect_inner.h * 0.8) - 18 + 1 self.assertEqual(Panel.Rect(13, 19, width, height), child.rect) def",
"and row heights for users to access. self.column_widths = column_widths self.row_heights = row_heights",
"sizing_tuple in sizings_by_type.get(self.EVEN, []): column_or_row, _ = sizing_tuple sizes[column_or_row] = size calculate_even_sizes( column_sizings_by_type,",
"| any # # The types of sizing in the table above are",
"return child child_0_0 = create_child(Rect(0, 0, 1, 1)) child_0_1 = create_child(Rect(0, 1, 1,",
"panel = gui.create(Panel) panel.rect = (50, 50, 500, 500) panel.padding = (8, 16,",
"self.parent.padding = (2, 3, 4, 5) self.parent.margins = (20, 30, 40, 50) def",
"* 0.3333) height_0 = 287 - 100 height_1 = 100 self.assertEqual(Panel.Rect(2, 3, width_0,",
"int(292 ** 0.5) final_width = root_width + int((194 - root_width) / 2) -",
"GridLayout(column_count=2, row_count=2, spacing=5) grid.set_fixed_column_sizing(0, 101) grid.set_fixed_column_sizing(1, 0) grid.set_fixed_row_sizing(0, 0) grid.set_fixed_row_sizing(1, 93) def create_child(rect):",
"grid.add_rect(child, Rect(1, 2, 2, 3)) self.assertEqual(20, grid.tallest_child_in_row(2)) self.assertEqual(20, grid.tallest_child_in_row(3)) self.assertEqual(20, grid.tallest_child_in_row(4)) def test_area_empty(self):",
"self.assertEqual(Panel.Rect( 2, 97, 80, 80), child_0_1.rect_outer) self.assertEqual(Panel.Rect(87, 97, 73, 80), child_1_1.rect_outer) def test_multiple_child_2(self):",
"= sum(row_heights[rect.y:rect.bottom]) + (rect.h - 1) * self.spacing panel.rect_outer = Panel.Rect(x, y, width,",
"child child_0_0 = create_child(Rect(0, 0, 1, 1), (58, 39)) child_1_0 = create_child(Rect(1, 0,",
"sizing_tuple sizes[column_or_row] = int(area_size * sizing[1]) calculate_percentage_sizes(column_sizings_by_type, column_widths, area.w) calculate_percentage_sizes(row_sizings_by_type, row_heights, area.h) def",
"self.column_sizings = dict() self.row_sizings = dict() self.column_count = column_count self.row_count = row_count self.spacing",
"child.size = (9999, 9999) grid.add_rect(child, rect) return child child_0_0 = create_child(Rect(0, 0, 1,",
"even # when we don't excplicitly set the columns and rows to even",
"size): child = self.gui.create(Panel) child.parent = self.parent child.padding = (10, 8, 6, 4)",
"if remove_panels: for panel in self.panels.values(): panel.remove() self.panels = dict() def area_empty(self, rect):",
"even sizing is the default we should make sure it works even #",
"= int(189 * 0.5) + 1 width_1 = int(189 * 0.5) height_0 =",
"self.row_sizings.get(row, (self.EVEN,)) group = row_sizings_by_type.get(sizing[0], list()) group.append((row, sizing)) row_sizings_by_type[sizing[0]] = group # Determine",
"column widths and row heights. column_widths = [0 for _ in range(self.column_count)] row_heights",
"1)) grid.layout(self.parent) width_0 = int(custom_sizing_1(189, None)) + 1 width_1 = int(custom_sizing_2(189, None)) height_0",
"1)) grid.set_custom_row_sizing(1, custom_sizing_1, partial(min, 1)) def create_child(rect): child = self.gui.create(Panel) child.parent = self.parent",
"1)) grid.set_custom_column_sizing(1, custom_sizing_2, partial(min, 1)) grid.set_custom_row_sizing(0, custom_sizing_2, partial(min, 1)) grid.set_custom_row_sizing(1, custom_sizing_1, partial(min, 1))",
"grid.add_rect(child, rect) return child child_0_0 = create_child(Rect(0, 0, 1, 1), (58, 31)) child_0_1",
"grid.set_percentage_column_sizing(1, 0.333) grid.set_percentage_row_sizing(0, 0.8139) grid.set_percentage_row_sizing(1, 1 - 0.8139) def create_child(rect): child = self.gui.create(Panel)",
"self.assertEqual(Panel.Rect(13, 19, 175, 274), child.rect) def test_multiple_even(self): grid = GridLayout(column_count=2, row_count=2, spacing=5) grid.set_even_column_sizing(0)",
"row_heights, extra_height) # Save column widths and row heights for users to access.",
"clear(self, *, remove_panels): if remove_panels: for panel in self.panels.values(): panel.remove() self.panels = dict()",
"sizing = self.column_sizings.get(column, (self.EVEN,)) group = column_sizings_by_type.get(sizing[0], list()) group.append((column, sizing)) column_sizings_by_type[sizing[0]] = group",
"8, 2) child.size = (53, 81) grid.add(child, 0, 0) grid.layout(self.parent) self.assertEqual(Panel.Rect(13, 19, 71,",
"50), child_0_0.rect_outer) self.assertEqual(Panel.Rect( 2, 58, 80, 50), child_0_1.rect_outer) self.assertEqual(Panel.Rect(87, 3, 44, 105), child_1_0.rect_outer)",
"rect_panel_tuple # In case a panel spans multiple columns, determine the height as",
"for row in range(0, grid.row_count): for column in range(0, grid.column_count): child = gui.create(Panel)",
"grid.set_fill_column_sizing(1) grid.set_fill_row_sizing(0) grid.set_fixed_row_sizing(1, 100) def create_child(rect): child = self.gui.create(Panel) child.parent = self.parent child.padding",
"(11, 16, 8, 2) child.size = (53, 81) grid.add(child, 0, 0) grid.layout(self.parent) self.assertEqual(Panel.Rect(13,",
"row, column_count=1, row_count=1): self.add_rect(panel, Rect(column, row, column_count, row_count)) def add_rect(self, panel, rect): assert(rect.x",
"row): self.row_sizings[row] = (self.CHILD,) def set_percentage_column_sizing(self, column, percentage): self.column_sizings[column] = (self.PERCENTAGE, percentage) def",
"self.panels = dict() def area_empty(self, rect): for rect_other in self.panels.keys(): if rect.intersects(rect_other): return",
"0, 1, 1), (58, 31)) child_0_1 = create_child(Rect(0, 1, 1, 1), (61, 31))",
"2 CUSTOM = 3 EVEN = 4 FILL = 5 def __init__(self, *,",
"sizes[column_or_row] = int(area_size * sizing[1]) calculate_percentage_sizes(column_sizings_by_type, column_widths, area.w) calculate_percentage_sizes(row_sizings_by_type, row_heights, area.h) def calculate_custom_sizes(sizings_by_type,",
"def setUp(self): from desky.gui import Gui self.gui = Gui() self.parent = self.gui.create(Panel) self.parent.size",
"(25, 71)) child_0_1 = create_child(Rect(0, 1, 1, 1), (61, 62)) child_1_1 = create_child(Rect(1,",
"GridLayout(column_count=2, row_count=2, spacing=5) grid.set_percentage_column_sizing(0, 0.333) grid.set_percentage_column_sizing(1, 0.333) grid.set_percentage_row_sizing(0, 0.8139) grid.set_percentage_row_sizing(1, 1 - 0.8139)",
"then # evaluated and is given the remaining area size as its argument.",
"grid.layout(self.parent) self.assertEqual(Panel.Rect(13, 19, 71, 102), child.rect) def test_multiple_fixed_1(self): grid = GridLayout(column_count=2, row_count=2, spacing=5)",
"self.spacing) / rect.h) return reduce(max, map(calculate_height, rect_panel_tuples_that_intersect_row), 0) def layout(self, panel): area =",
"set_child_row_sizing(self, row): self.row_sizings[row] = (self.CHILD,) def set_percentage_column_sizing(self, column, percentage): self.column_sizings[column] = (self.PERCENTAGE, percentage)",
"2, 3)) self.assertEqual(20, grid.tallest_child_in_row(2)) self.assertEqual(20, grid.tallest_child_in_row(3)) self.assertEqual(20, grid.tallest_child_in_row(4)) def test_area_empty(self): scenarios = [",
"self.gui.create(Panel) child.size = (66, 38) grid.add_rect(child, Rect(2, 1, 3, 2)) self.assertEqual(20, grid.widest_child_in_column(2)) self.assertEqual(20,",
"grid.add_rect(child, rect) return child child_0_0 = create_child(Rect(0, 0, 1, 1)) child_0_1 = create_child(Rect(0,",
"area.w - sum(column_widths) fill_rows = row_sizings_by_type.get(self.FILL, []) if fill_rows: row_heights[fill_rows[0][0]] = area.h -",
"create_child(Rect(0, 0, 1, 1), (58, 39)) child_1_0 = create_child(Rect(1, 0, 1, 1), (25,",
"Since even sizing is the default we should make sure it works even",
"gui.create(Panel) child.parent = panel grid.add(child, column, row) grid.layout(panel) def main(): from desky.gui import",
"= valfilter(lambda p: p != panel, self.panels) def clear(self, *, remove_panels): if remove_panels:",
"column_widths, extra_width) extra_height = allocate_extra_percentage(row_sizings_by_type, row_heights, extra_height) def allocate_extra_custom(sizings_by_type, sizes, extra): for sizing_tuple",
"return area_size ** 0.5 def custom_extra(extra): return extra / 2 grid = GridLayout(spacing=5)",
"spacing=5) grid.set_custom_column_sizing(0, custom_sizing_1, partial(min, 1)) grid.set_custom_column_sizing(1, custom_sizing_2, partial(min, 1)) grid.set_custom_row_sizing(0, custom_sizing_2, partial(min, 1))",
"int(287 * (1 - 0.8139)) self.assertEqual(Panel.Rect(2, 3, width_0, height_0), child_0_0.rect_outer) self.assertEqual(Panel.Rect(2, 8 +",
"19 + 1 height = int(self.parent.rect_inner.h * 0.8) - 18 + 1 self.assertEqual(Panel.Rect(13,",
"child.rect) def test_multiple_child_1(self): grid = GridLayout(column_count=2, row_count=2, spacing=5) grid.set_child_column_sizing(0) grid.set_child_column_sizing(1) grid.set_child_row_sizing(0) grid.set_child_row_sizing(1) def",
"0.333) grid.set_percentage_row_sizing(0, 0.8) child = self.gui.create(Panel) child.parent = self.parent child.padding = (10, 8,",
"allocate_extra_percentage(sizings_by_type, sizes, extra): for sizing_tuple in sizings_by_type.get(self.PERCENTAGE, []): column_or_row, _ = sizing_tuple amount",
"sizing_tuple sizes[column_or_row] = size calculate_even_sizes( column_sizings_by_type, column_widths, area.w - sum(column_widths)) calculate_even_sizes( row_sizings_by_type, row_heights,",
"- 1) * self.spacing height = sum(row_heights[rect.y:rect.bottom]) + (rect.h - 1) * self.spacing",
"create_grid() child = self.gui.create(Panel) child.size = (38, 60) grid.add(child, 1, 2) self.assertEqual(60, grid.tallest_child_in_row(2))",
"first. Custom is then # evaluated and is given the remaining area size",
"18 self.assertEqual(Panel.Rect(13, 19, final_width, final_height), child.rect) def test_multiple_custom(self): def custom_sizing_1(area_size, remaining_size): return area_size",
"(panel.rect_inner .move(-panel.x, -panel.y) .shrink( 0, 0, (self.column_count - 1) * self.spacing, (self.row_count -",
"the order. for column in range(self.column_count): sizing = self.column_sizings.get(column, (self.EVEN,)) group = column_sizings_by_type.get(sizing[0],",
"(equally divide) | 1px # | Fill (use remaining space) | any #",
"33), child_1_0.rect_outer) self.assertEqual(Panel.Rect( 2, 41, 101, 93), child_0_1.rect_outer) self.assertEqual(Panel.Rect(108, 41, 58, 93), child_1_1.rect_outer)",
"8, 2) child.size = (53, 81) grid.add(child, 0, 0) grid.layout(self.parent) self.assertEqual(Panel.Rect(13, 19, 53,",
"= area.w - sum(column_widths) fill_rows = row_sizings_by_type.get(self.FILL, []) if fill_rows: row_heights[fill_rows[0][0]] = area.h",
"fill_columns: column_widths[fill_columns[0][0]] = area.w - sum(column_widths) fill_rows = row_sizings_by_type.get(self.FILL, []) if fill_rows: row_heights[fill_rows[0][0]]",
"def set_custom_row_sizing(self, row, sizing_func, extra_func=zero_func): self.row_sizings[row] = (self.CUSTOM, sizing_func, extra_func) def set_even_column_sizing(self, column):",
"= create_child(Rect(1, 1, 1, 1)) grid.layout(self.parent) width_0 = int(189 * 0.3333) width_1 =",
"extra_func=zero_func): self.row_sizings[row] = (self.CUSTOM, sizing_func, extra_func) def set_even_column_sizing(self, column): self.column_sizings[column] = (self.EVEN,) def",
"32) grid = GridLayout(column_count = 3, row_count = 4, spacing = 4) for",
">= 0) assert(rect.right <= self.column_count) assert(rect.bottom <= self.row_count) assert(self.area_empty(rect)) self.panels[rect.frozen_copy()] = panel def",
"def calculate_width(rect_panel_tuple): rect, panel = rect_panel_tuple # In case a panel spans multiple",
"dict() self.column_sizings = dict() self.row_sizings = dict() self.column_count = column_count self.row_count = row_count",
"1)) child_1_1 = create_child(Rect(1, 1, 1, 1)) grid.layout(self.parent) width_0 = int(custom_sizing_1(189, None)) +",
"any # # The types of sizing in the table above are ordered",
"sum(column_widths) fill_rows = row_sizings_by_type.get(self.FILL, []) if fill_rows: row_heights[fill_rows[0][0]] = area.h - sum(row_heights) #",
"child_1_0 = create_child(Rect(1, 0, 1, 2), (25, 87)) grid.layout(self.parent) self.assertEqual(Panel.Rect( 2, 3, 80,",
"Determine column widths and row heights. column_widths = [0 for _ in range(self.column_count)]",
"105), child_1_0.rect_outer) def test_single_percentage(self): grid = GridLayout(spacing=5) grid.set_percentage_column_sizing(0, 0.333) grid.set_percentage_row_sizing(0, 0.8) child =",
"row_count=2, spacing=5) grid.set_fixed_column_sizing(0, 101) grid.set_fixed_column_sizing(1, 58) grid.set_fixed_row_sizing(0, 33) grid.set_fixed_row_sizing(1, 93) def create_child(rect): child",
"4, 2), Rect(1, 1, 9, 9), False), (Rect(10, 2, 4, 4), Rect(1, 1,",
"= GridLayout(column_count=2, row_count=2, spacing=5) grid.set_child_column_sizing(0) grid.set_child_column_sizing(1) grid.set_child_row_sizing(0) grid.set_child_row_sizing(1) def create_child(rect, size): child =",
"= spacing def add(self, panel, column, row, column_count=1, row_count=1): self.add_rect(panel, Rect(column, row, column_count,",
"test_multiple_fill(self): grid = GridLayout(column_count=2, row_count=2, spacing=5) grid.set_percentage_column_sizing(0, 0.3333) grid.set_fill_column_sizing(1) grid.set_fill_row_sizing(0) grid.set_fixed_row_sizing(1, 100) def",
"heights. column_widths = [0 for _ in range(self.column_count)] row_heights = [0 for _",
"def allocate_extra_even(sizings_by_type, sizes, extra): for sizing_tuple in sizings_by_type.get(self.EVEN, []): column_or_row, _ = sizing_tuple",
"parent, it is up to the # parent to decide if it should",
"Rect(column, 0, 1, self.row_count) rect_panel_tuples_that_intersect_column = list( filter( lambda rect_panel_tuple: rect_panel_tuple[0].intersects(column_rect), self.panels.items())) def",
"1), (61, 62)) child_1_1 = create_child(Rect(1, 1, 1, 1), (54, 20)) grid.layout(self.parent) self.assertEqual(Panel.Rect(",
"18), child_0_0.rect_outer) self.assertEqual(Panel.Rect(108, 3, 19, 18), child_1_0.rect_outer) self.assertEqual(Panel.Rect( 2, 8, 101, 93), child_0_1.rect_outer)",
"self.assertEqual(Panel.Rect(87, 3, 44, 105), child_1_0.rect_outer) def test_single_percentage(self): grid = GridLayout(spacing=5) grid.set_percentage_column_sizing(0, 0.333) grid.set_percentage_row_sizing(0,",
"calculate_width(rect_panel_tuple): rect, panel = rect_panel_tuple # In case a panel spans multiple columns,",
"column in range(0, grid.column_count): child = gui.create(Panel) child.parent = panel grid.add(child, column, row)",
"60) grid.add(child, 1, 2) self.assertEqual(60, grid.tallest_child_in_row(2)) def test_tallest_child_in_column_or_row_3(self): def create_grid(): grid = GridLayout(column_count=5,",
"0, 0) grid.layout(self.parent) root_width = int(194 ** 0.5) root_height = int(292 ** 0.5)",
"= [0 for _ in range(self.row_count)] def calculate_fixed_sizes(sizings_by_type, sizes): for sizing_tuple in sizings_by_type.get(self.FIXED,",
"rect_left) self.assertEqual(empty, grid.area_empty(rect_right)) def test_single_fixed(self): grid = GridLayout(spacing=5) grid.set_fixed_column_sizing(0, 90) grid.set_fixed_row_sizing(0, 120) child",
"grid.add(child, 0, 0) grid.layout(self.parent) width = int(self.parent.rect_inner.w * 0.333) - 19 + 1",
"grid.layout(self.parent) self.assertEqual(Panel.Rect( 2, 3, 101, 18), child_0_0.rect_outer) self.assertEqual(Panel.Rect(108, 3, 19, 18), child_1_0.rect_outer) self.assertEqual(Panel.Rect(",
"width_0 = int(custom_sizing_1(189, None)) + 1 width_1 = int(custom_sizing_2(189, None)) height_0 = int(custom_sizing_2(287,",
"row_sizings_by_type.get(sizing[0], list()) group.append((row, sizing)) row_sizings_by_type[sizing[0]] = group # Determine column widths and row",
"final_width = root_width + int((194 - root_width) / 2) - 19 final_height =",
"1) sizes[column_or_row] += amount extra -= amount return extra extra_width = allocate_extra_even(column_sizings_by_type, column_widths,",
"self.assertEqual(20, grid.widest_child_in_column(2)) self.assertEqual(20, grid.widest_child_in_column(3)) self.assertEqual(20, grid.widest_child_in_column(4)) with self.subTest(\"row\"): grid = create_grid() child =",
"(8, 16, 24, 32) grid = GridLayout(column_count = 3, row_count = 4, spacing",
"41, 58, 93), child_1_1.rect_outer) def test_multiple_fixed_2(self): grid = GridLayout(column_count=2, row_count=2, spacing=5) grid.set_fixed_column_sizing(0, 101)",
"test_multiple_child_2(self): grid = GridLayout(column_count=2, row_count=2, spacing=5) grid.set_child_column_sizing(0) grid.set_child_column_sizing(1) grid.set_child_row_sizing(0) grid.set_child_row_sizing(1) def create_child(rect, size):",
"0) grid.set_fixed_row_sizing(0, 0) grid.set_fixed_row_sizing(1, 93) def create_child(rect): child = self.gui.create(Panel) child.parent = self.parent",
"import Enum from functools import reduce, partial from toolz.dicttoolz import valfilter # |",
"grid = GridLayout(column_count = 3, row_count = 4, spacing = 4) for row",
"self.row_sizings[row] = (self.CHILD,) def set_percentage_column_sizing(self, column, percentage): self.column_sizings[column] = (self.PERCENTAGE, percentage) def set_percentage_row_sizing(self,",
"| configurable # | Even (equally divide) | 1px # | Fill (use",
"# Position child panels. for rect, panel in self.panels.items(): x = area.x +",
"range(self.column_count): sizing = self.column_sizings.get(column, (self.EVEN,)) group = column_sizings_by_type.get(sizing[0], list()) group.append((column, sizing)) column_sizings_by_type[sizing[0]] =",
"filter( lambda rect_panel_tuple: rect_panel_tuple[0].intersects(column_rect), self.panels.items())) def calculate_width(rect_panel_tuple): rect, panel = rect_panel_tuple # In",
"child_0_0 = create_child(Rect(0, 0, 1, 1), (58, 39)) child_1_0 = create_child(Rect(1, 0, 1,",
"excplicitly set the columns and rows to even sizing. for default in (True,",
"= 4, spacing = 4) for row in range(0, grid.row_count): for column in",
"spacing=5) grid.set_percentage_column_sizing(0, 0.333) grid.set_percentage_column_sizing(1, 0.333) grid.set_percentage_row_sizing(0, 0.8139) grid.set_percentage_row_sizing(1, 1 - 0.8139) def create_child(rect):",
"area size as its argument. Even is # evaluated next. Even panels will",
"grid.set_even_column_sizing(0) grid.set_even_row_sizing(0) child = self.gui.create(Panel) child.parent = self.parent child.padding = (10, 8, 6,",
"= int(189 * 0.5) height_0 = int(287 * 0.5) + 1 height_1 =",
"int(189 * 0.3333) height_0 = 287 - 100 height_1 = 100 self.assertEqual(Panel.Rect(2, 3,",
"evenly between # themselves. Fill evaluates last and will take the remaining space.",
"grid.set_percentage_row_sizing(0, 0.8139) grid.set_percentage_row_sizing(1, 1 - 0.8139) def create_child(rect): child = self.gui.create(Panel) child.parent =",
"grid.layout(self.parent) self.assertEqual(Panel.Rect( 2, 3, 80, 50), child_0_0.rect_outer) self.assertEqual(Panel.Rect( 2, 58, 80, 50), child_0_1.rect_outer)",
"# | Type of sizing | Maximum extra width allocation # -------------------------------------------------------------- #",
"return child child_0_0 = create_child(Rect(0, 0, 1, 1), (58, 31)) child_0_1 = create_child(Rect(0,",
"width_0, height_1), child_0_1.rect_outer) self.assertEqual(Panel.Rect(7 + width_0, 3, width_1, height_0), child_1_0.rect_outer) self.assertEqual(Panel.Rect(7 + width_0,",
"grid.layout(self.parent) width = int(self.parent.rect_inner.w * 0.333) - 19 + 1 height = int(self.parent.rect_inner.h",
"grid.set_fixed_row_sizing(0, 120) child = self.gui.create(Panel) child.parent = self.parent child.padding = (10, 8, 6,",
"test_multiple_custom(self): def custom_sizing_1(area_size, remaining_size): return area_size ** 0.8 def custom_sizing_2(area_size, remaining_size): return area_size",
"size) def set_child_column_sizing(self, column): self.column_sizings[column] = (self.CHILD,) def set_child_row_sizing(self, row): self.row_sizings[row] = (self.CHILD,)",
"column_or_row, _ = sizing_tuple sizes[column_or_row] = largest_func(column_or_row) calculate_child_sizes(column_sizings_by_type, column_widths, self.widest_child_in_column) calculate_child_sizes(row_sizings_by_type, row_heights, self.tallest_child_in_row)",
"(38, 66) grid.add_rect(child, Rect(1, 2, 2, 3)) self.assertEqual(20, grid.tallest_child_in_row(2)) self.assertEqual(20, grid.tallest_child_in_row(3)) self.assertEqual(20, grid.tallest_child_in_row(4))",
"6, 4) child.margins = (11, 16, 8, 2) child.size = (9999, 9999) grid.add_rect(child,",
"= Rect(0, row, self.column_count, 1) rect_panel_tuples_that_intersect_row = list( filter( lambda rect_panel_tuple: rect_panel_tuple[0].intersects(row_rect), self.panels.items()))",
"3, 80, 50), child_0_0.rect_outer) self.assertEqual(Panel.Rect( 2, 58, 80, 50), child_0_1.rect_outer) self.assertEqual(Panel.Rect(87, 3, 44,",
"create_grid() child = self.gui.create(Panel) child.size = (38, 66) grid.add_rect(child, Rect(1, 2, 2, 3))",
"4 FILL = 5 def __init__(self, *, column_count = 1, row_count = 1,",
"def calculate_child_sizes(sizings_by_type, sizes, largest_func): for sizing_tuple in sizings_by_type.get(self.CHILD, []): column_or_row, _ = sizing_tuple",
"grid.set_even_row_sizing(0) child = self.gui.create(Panel) child.parent = self.parent child.padding = (10, 8, 6, 4)",
"* 0.3333) width_1 = 189 - int(189 * 0.3333) height_0 = 287 -",
"make sure it works even # when we don't excplicitly set the columns",
"None)) + 1 height_1 = int(custom_sizing_1(287, None)) self.assertEqual(Panel.Rect(2, 3, width_0, height_0), child_0_0.rect_outer) self.assertEqual(Panel.Rect(2,",
"sizing_tuple sizes[column_or_row] = largest_func(column_or_row) calculate_child_sizes(column_sizings_by_type, column_widths, self.widest_child_in_column) calculate_child_sizes(row_sizings_by_type, row_heights, self.tallest_child_in_row) def calculate_percentage_sizes(sizings_by_type, sizes,",
"1, 1), (58, 39)) child_1_0 = create_child(Rect(1, 0, 1, 1), (25, 71)) child_0_1",
"8, 6, 4) child.margins = (11, 16, 8, 2) child.size = (53, 81)",
"1, 1, 1)) grid.layout(self.parent) width_0 = int(189 * 0.3333) width_1 = 189 -",
"GridLayout(spacing=5) grid.set_child_column_sizing(0) grid.set_child_row_sizing(0) child = self.gui.create(Panel) child.parent = self.parent child.padding = (10, 8,",
"0) assert(rect.y >= 0) assert(rect.right <= self.column_count) assert(rect.bottom <= self.row_count) assert(self.area_empty(rect)) self.panels[rect.frozen_copy()] =",
"extra / 2 grid = GridLayout(spacing=5) grid.set_custom_column_sizing(0, custom_sizing, custom_extra) grid.set_custom_row_sizing(0, custom_sizing, custom_extra) child",
"int(189 * 0.5) + 1 width_1 = int(189 * 0.5) height_0 = int(287",
"39)) child_1_0 = create_child(Rect(1, 0, 1, 1), (25, 71)) child_0_1 = create_child(Rect(0, 1,",
"column_or_row, sizing = sizing_tuple sizes[column_or_row] = sizing[1] calculate_fixed_sizes(column_sizings_by_type, column_widths) calculate_fixed_sizes(row_sizings_by_type, row_heights) def calculate_child_sizes(sizings_by_type,",
"1)) child_1_0 = create_child(Rect(1, 0, 1, 1)) child_0_1 = create_child(Rect(0, 1, 1, 1))",
"column_sizings_by_type[sizing[0]] = group for row in range(self.row_count): sizing = self.row_sizings.get(row, (self.EVEN,)) group =",
"column, row) grid.layout(panel) def main(): from desky.gui import example #example(grid_example) unittest.main() if __name__",
"GridLayout(column_count=2, row_count=2, spacing=5) grid.set_percentage_column_sizing(0, 0.3333) grid.set_fill_column_sizing(1) grid.set_fill_row_sizing(0) grid.set_fixed_row_sizing(1, 100) def create_child(rect): child =",
"2 grid = GridLayout(spacing=5) grid.set_custom_column_sizing(0, custom_sizing, custom_extra) grid.set_custom_row_sizing(0, custom_sizing, custom_extra) child = self.gui.create(Panel)",
"self.assertEqual(20, grid.widest_child_in_column(3)) self.assertEqual(20, grid.widest_child_in_column(4)) with self.subTest(\"row\"): grid = create_grid() child = self.gui.create(Panel) child.size",
"int(area_size * sizing[1]) calculate_percentage_sizes(column_sizings_by_type, column_widths, area.w) calculate_percentage_sizes(row_sizings_by_type, row_heights, area.h) def calculate_custom_sizes(sizings_by_type, sizes, area_size,",
"in range(0, grid.column_count): child = gui.create(Panel) child.parent = panel grid.add(child, column, row) grid.layout(panel)",
"= create_child(Rect(1, 1, 1, 1)) grid.layout(self.parent) width_0 = int(custom_sizing_1(189, None)) + 1 width_1",
"= (53, 81) grid.add(child, 0, 0) grid.layout(self.parent) self.assertEqual(Panel.Rect(13, 19, 53, 81), child.rect) def",
"to columns and rows. extra_width = max(area.w - sum(column_widths), 0) extra_height = max(area.h",
"percentage): self.column_sizings[column] = (self.PERCENTAGE, percentage) def set_percentage_row_sizing(self, row, percentage): self.row_sizings[row] = (self.PERCENTAGE, percentage)",
"calculate_child_sizes(column_sizings_by_type, column_widths, self.widest_child_in_column) calculate_child_sizes(row_sizings_by_type, row_heights, self.tallest_child_in_row) def calculate_percentage_sizes(sizings_by_type, sizes, area_size): for sizing_tuple in",
"in range(self.column_count): sizing = self.column_sizings.get(column, (self.EVEN,)) group = column_sizings_by_type.get(sizing[0], list()) group.append((column, sizing)) column_sizings_by_type[sizing[0]]",
"= size calculate_even_sizes( column_sizings_by_type, column_widths, area.w - sum(column_widths)) calculate_even_sizes( row_sizings_by_type, row_heights, area.h -",
"grid.set_percentage_column_sizing(0, 0.333) grid.set_percentage_row_sizing(0, 0.8) child = self.gui.create(Panel) child.parent = self.parent child.padding = (10,",
"height_1 = 100 self.assertEqual(Panel.Rect(2, 3, width_0, height_0), child_0_0.rect_outer) self.assertEqual(Panel.Rect(2, 8 + height_0, width_0,",
"[0 for _ in range(self.column_count)] row_heights = [0 for _ in range(self.row_count)] def",
"their sizing types while preserving the order. for column in range(self.column_count): sizing =",
"0.333) grid.set_percentage_row_sizing(0, 0.8139) grid.set_percentage_row_sizing(1, 1 - 0.8139) def create_child(rect): child = self.gui.create(Panel) child.parent",
"def grid_example(gui): panel = gui.create(Panel) panel.rect = (50, 50, 500, 500) panel.padding =",
"2, 4, 4), Rect(1, 1, 9, 9), True), ] for rect_left, rect_right, empty",
"(custom function) | configurable # | Even (equally divide) | 1px # |",
"- 18 self.assertEqual(Panel.Rect(13, 19, final_width, final_height), child.rect) def test_multiple_custom(self): def custom_sizing_1(area_size, remaining_size): return",
"panel.rect_outer = Panel.Rect(x, y, width, height) class GridLayoutTest(unittest.TestCase): def setUp(self): from desky.gui import",
"access. self.column_widths = column_widths self.row_heights = row_heights # Position child panels. for rect,",
"9, 9), False), (Rect(10, 2, 4, 4), Rect(1, 1, 9, 9), True), ]",
"Rect(0, row, self.column_count, 1) rect_panel_tuples_that_intersect_row = list( filter( lambda rect_panel_tuple: rect_panel_tuple[0].intersects(row_rect), self.panels.items())) def",
"sizes[column_or_row] += amount extra -= amount return extra extra_width = allocate_extra_percentage(column_sizings_by_type, column_widths, extra_width)",
"proportional amount. return int((panel.rect_outer.h - (rect.h - 1) * self.spacing) / rect.h) return",
"child_1_1 = create_child(Rect(1, 1, 1, 1)) grid.layout(self.parent) width_0 = int(189 * 0.333) +",
"= sizing_tuple sizes[column_or_row] = int(area_size * sizing[1]) calculate_percentage_sizes(column_sizings_by_type, column_widths, area.w) calculate_percentage_sizes(row_sizings_by_type, row_heights, area.h)",
"Fixed (200 px) | 0px # | Child (use child size) | 0px",
"19, 53, 81), child.rect) def test_multiple_child_1(self): grid = GridLayout(column_count=2, row_count=2, spacing=5) grid.set_child_column_sizing(0) grid.set_child_column_sizing(1)",
"width = int(self.parent.rect_inner.w * 0.333) - 19 + 1 height = int(self.parent.rect_inner.h *",
"(self.EVEN,) def set_fill_column_sizing(self, column): self.column_sizings[column] = (self.FILL,) def set_fill_row_sizing(self, row): self.row_sizings[row] = (self.FILL,)",
"grid.widest_child_in_column(3)) self.assertEqual(20, grid.widest_child_in_column(4)) with self.subTest(\"row\"): grid = create_grid() child = self.gui.create(Panel) child.size =",
"the columns and rows to even sizing. for default in (True, False): with",
"evaluated first. Custom is then # evaluated and is given the remaining area",
"* 0.8) - 18 + 1 self.assertEqual(Panel.Rect(13, 19, width, height), child.rect) def test_multiple_percentage(self):",
"0) grid.layout(self.parent) width = int(self.parent.rect_inner.w * 0.333) - 19 + 1 height =",
"sizing_func, extra_func) def set_even_column_sizing(self, column): self.column_sizings[column] = (self.EVEN,) def set_even_row_sizing(self, row): self.row_sizings[row] =",
"child.size = (53, 81) grid.add(child, 0, 0) grid.layout(self.parent) root_width = int(194 ** 0.5)",
"0.3333) height_0 = 287 - 100 height_1 = 100 self.assertEqual(Panel.Rect(2, 3, width_0, height_0),",
"FILL = 5 def __init__(self, *, column_count = 1, row_count = 1, spacing",
"Child (use child size) | 0px # | Percentage (30% of width) |",
"in sizings_by_type.get(self.CHILD, []): column_or_row, _ = sizing_tuple sizes[column_or_row] = largest_func(column_or_row) calculate_child_sizes(column_sizings_by_type, column_widths, self.widest_child_in_column)",
"child_0_1 = create_child(Rect(0, 1, 1, 1), (61, 31)) child_1_0 = create_child(Rect(1, 0, 1,",
"(rect.h - 1) * self.spacing panel.rect_outer = Panel.Rect(x, y, width, height) class GridLayoutTest(unittest.TestCase):",
"above are ordered in evalulation priority. # Fixed, Child, and Percentage sizings are",
"= (11, 16, 8, 2) child.size = (9999, 9999) grid.add_rect(child, rect) return child",
"return reduce(max, map(calculate_width, rect_panel_tuples_that_intersect_column), 0) def tallest_child_in_row(self, row): row_rect = Rect(0, row, self.column_count,",
"= (8, 16, 24, 32) grid = GridLayout(column_count = 3, row_count = 4,",
"self.spacing) ) column_sizings_by_type = dict() row_sizings_by_type = dict() # Group columns and rows",
"child_1_1 = create_child(Rect(1, 1, 1, 1)) grid.layout(self.parent) width_0 = int(custom_sizing_1(189, None)) + 1",
"width_1 = 189 - int(189 * 0.3333) height_0 = 287 - 100 height_1",
"case a panel spans multiple columns, determine the height as a # proportional",
"(rect.w - 1) * self.spacing) / rect.w) return reduce(max, map(calculate_width, rect_panel_tuples_that_intersect_column), 0) def",
"remaining_size): for sizing_tuple in sizings_by_type.get(self.CUSTOM, []): column_or_row, sizing = sizing_tuple sizes[column_or_row] = int(sizing[1](area_size,",
"def test_multiple_fixed_2(self): grid = GridLayout(column_count=2, row_count=2, spacing=5) grid.set_fixed_column_sizing(0, 101) grid.set_fixed_column_sizing(1, 0) grid.set_fixed_row_sizing(0, 0)",
"[]): column_or_row, sizing = sizing_tuple sizes[column_or_row] = int(area_size * sizing[1]) calculate_percentage_sizes(column_sizings_by_type, column_widths, area.w)",
"1, 1)) child_1_1 = create_child(Rect(1, 1, 1, 1)) grid.layout(self.parent) width_0 = int(custom_sizing_1(189, None))",
"8, 101, 93), child_0_1.rect_outer) self.assertEqual(Panel.Rect(108, 8, 19, 93), child_1_1.rect_outer) def test_single_child(self): grid =",
"create_child(Rect(1, 1, 1, 1), (54, 20)) grid.layout(self.parent) self.assertEqual(Panel.Rect( 2, 3, 80, 89), child_0_0.rect_outer)",
"(61, 31)) child_1_0 = create_child(Rect(1, 0, 1, 2), (25, 87)) grid.layout(self.parent) self.assertEqual(Panel.Rect( 2,",
"extra_width) extra_height = allocate_extra_custom(row_sizings_by_type, row_heights, extra_height) def allocate_extra_even(sizings_by_type, sizes, extra): for sizing_tuple in",
"remaining_size): return area_size - area_size ** 0.8 grid = GridLayout(column_count=2, row_count=2, spacing=5) grid.set_custom_column_sizing(0,",
"(30% of width) | 1px # | Custom (custom function) | configurable #",
"(53, 81) grid.add(child, 0, 0) grid.layout(self.parent) root_width = int(194 ** 0.5) root_height =",
"area.w, area.w - sum(column_widths)) calculate_custom_sizes(row_sizings_by_type, row_heights, area.h, area.h - sum(row_heights)) def calculate_even_sizes(sizings_by_type, sizes,",
"Percentage sizings are evaluated first. Custom is then # evaluated and is given",
"1, 1, 1), (61, 62)) child_1_1 = create_child(Rect(1, 1, 1, 1), (54, 20))",
"height = sum(row_heights[rect.y:rect.bottom]) + (rect.h - 1) * self.spacing panel.rect_outer = Panel.Rect(x, y,",
"group for row in range(self.row_count): sizing = self.row_sizings.get(row, (self.EVEN,)) group = row_sizings_by_type.get(sizing[0], list())",
"grid.add(child, 2, 1) self.assertEqual(60, grid.widest_child_in_column(2)) with self.subTest(\"column\"): grid = create_grid() child = self.gui.create(Panel)",
"# themselves. Fill evaluates last and will take the remaining space. # #",
"as a # proportional amount. return int((panel.rect_outer.h - (rect.h - 1) * self.spacing)",
"width_0 = int(189 * 0.5) + 1 width_1 = int(189 * 0.5) height_0",
"create_child(Rect(0, 0, 1, 1), (58, 31)) child_0_1 = create_child(Rect(0, 1, 1, 1), (61,",
"9, 9), True), ] for rect_left, rect_right, empty in scenarios: with self.subTest(rect_left=rect_left, rect_right=rect_right,",
"= allocate_extra_custom(column_sizings_by_type, column_widths, extra_width) extra_height = allocate_extra_custom(row_sizings_by_type, row_heights, extra_height) def allocate_extra_even(sizings_by_type, sizes, extra):",
"int((292 - root_height) / 2) - 18 self.assertEqual(Panel.Rect(13, 19, final_width, final_height), child.rect) def",
"1) * self.spacing, (self.row_count - 1) * self.spacing) ) column_sizings_by_type = dict() row_sizings_by_type",
"is # evaluated next. Even panels will split remaining space evenly between #",
"8, 2) child.size = size grid.add_rect(child, rect) return child child_0_0 = create_child(Rect(0, 0,",
"grid.set_percentage_row_sizing(0, 0.8) child = self.gui.create(Panel) child.parent = self.parent child.padding = (10, 8, 6,",
"+ rect.y * self.spacing width = sum(column_widths[rect.x:rect.right]) + (rect.w - 1) * self.spacing",
"determine the height as a # proportional amount. return int((panel.rect_outer.w - (rect.w -",
"+ 1 width_1 = width_0 height_0 = int(287 * 0.8139) + 1 height_1",
"= (self.PERCENTAGE, percentage) def set_custom_column_sizing(self, column, sizing_func, extra_func=zero_func): self.column_sizings[column] = (self.CUSTOM, sizing_func, extra_func)",
"columns, determine the height as a # proportional amount. return int((panel.rect_outer.w - (rect.w",
"toolz.dicttoolz import valfilter # | Type of sizing | Maximum extra width allocation",
"largest_func): for sizing_tuple in sizings_by_type.get(self.CHILD, []): column_or_row, _ = sizing_tuple sizes[column_or_row] = largest_func(column_or_row)",
"self.assertEqual(Panel.Rect( 2, 3, 80, 89), child_0_0.rect_outer) self.assertEqual(Panel.Rect(87, 3, 73, 89), child_1_0.rect_outer) self.assertEqual(Panel.Rect( 2,",
"self.panels) def clear(self, *, remove_panels): if remove_panels: for panel in self.panels.values(): panel.remove() self.panels",
"3, 19, 18), child_1_0.rect_outer) self.assertEqual(Panel.Rect( 2, 8, 101, 93), child_0_1.rect_outer) self.assertEqual(Panel.Rect(108, 8, 19,",
"= panel grid.add(child, column, row) grid.layout(panel) def main(): from desky.gui import example #example(grid_example)",
"split remaining space evenly between # themselves. Fill evaluates last and will take",
"(use child size) | 0px # | Percentage (30% of width) | 1px",
"spacing=5) grid.set_child_column_sizing(0) grid.set_child_column_sizing(1) grid.set_child_row_sizing(0) grid.set_child_row_sizing(1) def create_child(rect, size): child = self.gui.create(Panel) child.parent =",
"# | Fill (use remaining space) | any # # The types of",
"return int((panel.rect_outer.w - (rect.w - 1) * self.spacing) / rect.w) return reduce(max, map(calculate_width,",
"extra extra_width = allocate_extra_percentage(column_sizings_by_type, column_widths, extra_width) extra_height = allocate_extra_percentage(row_sizings_by_type, row_heights, extra_height) def allocate_extra_custom(sizings_by_type,",
"3)) self.assertEqual(20, grid.tallest_child_in_row(2)) self.assertEqual(20, grid.tallest_child_in_row(3)) self.assertEqual(20, grid.tallest_child_in_row(4)) def test_area_empty(self): scenarios = [ (Rect(2,",
"def set_even_row_sizing(self, row): self.row_sizings[row] = (self.EVEN,) def set_fill_column_sizing(self, column): self.column_sizings[column] = (self.FILL,) def",
"274), child.rect) def test_multiple_fill(self): grid = GridLayout(column_count=2, row_count=2, spacing=5) grid.set_percentage_column_sizing(0, 0.3333) grid.set_fill_column_sizing(1) grid.set_fill_row_sizing(0)",
"19, 175, 274), child.rect) def test_multiple_even(self): grid = GridLayout(column_count=2, row_count=2, spacing=5) grid.set_even_column_sizing(0) grid.set_even_column_sizing(1)",
"child_1_0.rect_outer) self.assertEqual(Panel.Rect(7 + width_0, 8 + height_0, width_1, height_1), child_1_1.rect_outer) def grid_example(gui): panel",
"def area_empty(self, rect): for rect_other in self.panels.keys(): if rect.intersects(rect_other): return False return True",
"= column_sizings_by_type.get(self.FILL, []) if fill_columns: column_widths[fill_columns[0][0]] = area.w - sum(column_widths) fill_rows = row_sizings_by_type.get(self.FILL,",
"layout exceeds the bounds of the parent, it is up to the #",
"grid.tallest_child_in_row(4)) def test_area_empty(self): scenarios = [ (Rect(2, 0, 4, 2), Rect(1, 1, 9,",
"width_1, height_0), child_1_0.rect_outer) self.assertEqual(Panel.Rect(7 + width_0, 8 + height_0, width_1, height_1), child_1_1.rect_outer) def",
"row_heights # Position child panels. for rect, panel in self.panels.items(): x = area.x",
"+ 1 height_1 = int(287 * (1 - 0.8139)) self.assertEqual(Panel.Rect(2, 3, width_0, height_0),",
"(61, 62)) child_1_1 = create_child(Rect(1, 1, 1, 1), (54, 20)) grid.layout(self.parent) self.assertEqual(Panel.Rect( 2,",
"self.assertEqual(empty, grid.area_empty(rect_right)) def test_single_fixed(self): grid = GridLayout(spacing=5) grid.set_fixed_column_sizing(0, 90) grid.set_fixed_row_sizing(0, 120) child =",
"if not default: grid.set_even_column_sizing(0) grid.set_even_row_sizing(0) child = self.gui.create(Panel) child.parent = self.parent child.padding =",
"= 5 def __init__(self, *, column_count = 1, row_count = 1, spacing =",
"and rows. extra_width = max(area.w - sum(column_widths), 0) extra_height = max(area.h - sum(row_heights),",
"6, 4) child.margins = (11, 16, 8, 2) child.size = size grid.add_rect(child, rect)",
"2, 2, 3)) self.assertEqual(20, grid.tallest_child_in_row(2)) self.assertEqual(20, grid.tallest_child_in_row(3)) self.assertEqual(20, grid.tallest_child_in_row(4)) def test_area_empty(self): scenarios =",
"panel = rect_panel_tuple # In case a panel spans multiple columns, determine the",
"calculate_percentage_sizes(column_sizings_by_type, column_widths, area.w) calculate_percentage_sizes(row_sizings_by_type, row_heights, area.h) def calculate_custom_sizes(sizings_by_type, sizes, area_size, remaining_size): for sizing_tuple",
"child_0_0 = create_child(Rect(0, 0, 1, 1)) child_1_0 = create_child(Rect(1, 0, 1, 1)) child_0_1",
"- 1) * self.spacing) ) column_sizings_by_type = dict() row_sizings_by_type = dict() # Group",
"= row_sizings_by_type.get(self.FILL, []) if fill_rows: row_heights[fill_rows[0][0]] = area.h - sum(row_heights) # Allocate extra",
"= int(287 * 0.8139) + 1 height_1 = int(287 * (1 - 0.8139))",
"create_child(Rect(1, 1, 1, 1)) grid.layout(self.parent) width_0 = int(189 * 0.5) + 1 width_1",
"sizing = sizing_tuple sizes[column_or_row] = sizing[1] calculate_fixed_sizes(column_sizings_by_type, column_widths) calculate_fixed_sizes(row_sizings_by_type, row_heights) def calculate_child_sizes(sizings_by_type, sizes,",
"* self.spacing panel.rect_outer = Panel.Rect(x, y, width, height) class GridLayoutTest(unittest.TestCase): def setUp(self): from",
"test_multiple_percentage(self): grid = GridLayout(column_count=2, row_count=2, spacing=5) grid.set_percentage_column_sizing(0, 0.333) grid.set_percentage_column_sizing(1, 0.333) grid.set_percentage_row_sizing(0, 0.8139) grid.set_percentage_row_sizing(1,",
"panel): self.panels = valfilter(lambda p: p != panel, self.panels) def clear(self, *, remove_panels):",
"grid = GridLayout(spacing=5) grid.set_fixed_column_sizing(0, 90) grid.set_fixed_row_sizing(0, 120) child = self.gui.create(Panel) child.parent = self.parent",
"to decide if it should resize. def zero_func(): return 0 class GridLayout: FIXED",
"width = sum(column_widths[rect.x:rect.right]) + (rect.w - 1) * self.spacing height = sum(row_heights[rect.y:rect.bottom]) +",
"child_1_1.rect_outer) def test_single_fill(self): grid = GridLayout(spacing=5) grid.set_fill_column_sizing(0) grid.set_fill_row_sizing(0) child = self.gui.create(Panel) child.parent =",
"reduce(max, map(calculate_width, rect_panel_tuples_that_intersect_column), 0) def tallest_child_in_row(self, row): row_rect = Rect(0, row, self.column_count, 1)",
"= root_height + int((292 - root_height) / 2) - 18 self.assertEqual(Panel.Rect(13, 19, final_width,",
"grid.set_percentage_row_sizing(1, 1 - 0.8139) def create_child(rect): child = self.gui.create(Panel) child.parent = self.parent child.padding",
"extra): for sizing_tuple in sizings_by_type.get(self.CUSTOM, []): column_or_row, sizing = sizing_tuple amount = int(sizing[2](extra))",
"row_heights, area.h - sum(row_heights)) fill_columns = column_sizings_by_type.get(self.FILL, []) if fill_columns: column_widths[fill_columns[0][0]] = area.w",
"1)) grid.layout(self.parent) self.assertEqual(Panel.Rect( 2, 3, 101, 33), child_0_0.rect_outer) self.assertEqual(Panel.Rect(108, 3, 58, 33), child_1_0.rect_outer)",
"column_widths, area.w, area.w - sum(column_widths)) calculate_custom_sizes(row_sizings_by_type, row_heights, area.h, area.h - sum(row_heights)) def calculate_even_sizes(sizings_by_type,",
"0, 1, 2), (25, 87)) grid.layout(self.parent) self.assertEqual(Panel.Rect( 2, 3, 80, 50), child_0_0.rect_outer) self.assertEqual(Panel.Rect(",
"1) self.assertEqual(60, grid.widest_child_in_column(2)) with self.subTest(\"column\"): grid = create_grid() child = self.gui.create(Panel) child.size =",
"int((panel.rect_outer.h - (rect.h - 1) * self.spacing) / rect.h) return reduce(max, map(calculate_height, rect_panel_tuples_that_intersect_row),",
"def test_multiple_custom(self): def custom_sizing_1(area_size, remaining_size): return area_size ** 0.8 def custom_sizing_2(area_size, remaining_size): return",
"1, 1, 1), (54, 20)) grid.layout(self.parent) self.assertEqual(Panel.Rect( 2, 3, 80, 89), child_0_0.rect_outer) self.assertEqual(Panel.Rect(87,",
"[]): column_or_row, _ = sizing_tuple amount = min(extra, 1) sizes[column_or_row] += amount extra",
"19, 175, 274), child.rect) def test_multiple_fill(self): grid = GridLayout(column_count=2, row_count=2, spacing=5) grid.set_percentage_column_sizing(0, 0.3333)",
"+ (rect.h - 1) * self.spacing panel.rect_outer = Panel.Rect(x, y, width, height) class",
"set_fill_row_sizing(self, row): self.row_sizings[row] = (self.FILL,) def widest_child_in_column(self, column): column_rect = Rect(column, 0, 1,",
"rect, panel = rect_panel_tuple # In case a panel spans multiple rows, determine",
"def __init__(self, *, column_count = 1, row_count = 1, spacing = 0): self.panels",
"= int(287 * 0.5) self.assertEqual(Panel.Rect(2, 3, width_0, height_0), child_0_0.rect_outer) self.assertEqual(Panel.Rect(2, 8 + height_0,",
"1, self.row_count) rect_panel_tuples_that_intersect_column = list( filter( lambda rect_panel_tuple: rect_panel_tuple[0].intersects(column_rect), self.panels.items())) def calculate_width(rect_panel_tuple): rect,",
"grid.add(child, 0, 0) grid.layout(self.parent) self.assertEqual(Panel.Rect(13, 19, 53, 81), child.rect) def test_multiple_child_1(self): grid =",
"0) extra_height = max(area.h - sum(row_heights), 0) def allocate_extra_percentage(sizings_by_type, sizes, extra): for sizing_tuple",
"Custom (custom function) | configurable # | Even (equally divide) | 1px #",
"child.size = (38, 66) grid.add_rect(child, Rect(1, 2, 2, 3)) self.assertEqual(20, grid.tallest_child_in_row(2)) self.assertEqual(20, grid.tallest_child_in_row(3))",
"for row in range(grid.row_count): grid.set_child_row_sizing(row) self.assertEqual(0, grid.widest_child_in_column(2)) self.assertEqual(0, grid.tallest_child_in_row(2)) def test_tallest_child_in_column_or_row_2(self): def create_grid():",
"500, 500) panel.padding = (8, 16, 24, 32) grid = GridLayout(column_count = 3,",
"self.panels.items())) def calculate_width(rect_panel_tuple): rect, panel = rect_panel_tuple # In case a panel spans",
"root_height + int((292 - root_height) / 2) - 18 self.assertEqual(Panel.Rect(13, 19, final_width, final_height),",
"child_0_1.rect_outer) self.assertEqual(Panel.Rect(108, 41, 58, 93), child_1_1.rect_outer) def test_multiple_fixed_2(self): grid = GridLayout(column_count=2, row_count=2, spacing=5)",
"Child, and Percentage sizings are evaluated first. Custom is then # evaluated and",
"area_size ** 0.5 def custom_extra(extra): return extra / 2 grid = GridLayout(spacing=5) grid.set_custom_column_sizing(0,",
"case a panel spans multiple rows, determine the height as a # proportional",
"create_child(Rect(1, 0, 1, 2), (25, 87)) grid.layout(self.parent) self.assertEqual(Panel.Rect( 2, 3, 80, 50), child_0_0.rect_outer)",
"grid.set_even_column_sizing(0) grid.set_even_column_sizing(1) grid.set_even_row_sizing(0) grid.set_even_row_sizing(1) def create_child(rect): child = self.gui.create(Panel) child.parent = self.parent child.padding",
"[]): column_or_row, sizing = sizing_tuple amount = int(sizing[2](extra)) sizes[column_or_row] += amount extra -=",
"+ width_0, 8 + height_0, width_1, height_1), child_1_1.rect_outer) def test_single_fill(self): grid = GridLayout(spacing=5)",
"= rect_panel_tuple # In case a panel spans multiple columns, determine the height",
"def test_single_fixed(self): grid = GridLayout(spacing=5) grid.set_fixed_column_sizing(0, 90) grid.set_fixed_row_sizing(0, 120) child = self.gui.create(Panel) child.parent",
"= int(sizing[1](area_size, remaining_size)) calculate_custom_sizes(column_sizings_by_type, column_widths, area.w, area.w - sum(column_widths)) calculate_custom_sizes(row_sizings_by_type, row_heights, area.h, area.h",
"81) grid.add(child, 0, 0) grid.layout(self.parent) self.assertEqual(Panel.Rect(13, 19, 53, 81), child.rect) def test_multiple_child_1(self): grid",
"= GridLayout(column_count=20, row_count=20, spacing=5) grid.add_rect(self.gui.create(Panel), rect_left) self.assertEqual(empty, grid.area_empty(rect_right)) def test_single_fixed(self): grid = GridLayout(spacing=5)",
"rows, determine the height as a # proportional amount. return int((panel.rect_outer.h - (rect.h",
"grid.set_child_column_sizing(0) grid.set_child_column_sizing(1) grid.set_child_row_sizing(0) grid.set_child_row_sizing(1) def create_child(rect, size): child = self.gui.create(Panel) child.parent = self.parent",
"= (self.CUSTOM, sizing_func, extra_func) def set_custom_row_sizing(self, row, sizing_func, extra_func=zero_func): self.row_sizings[row] = (self.CUSTOM, sizing_func,",
"width_1, height_1), child_1_1.rect_outer) def grid_example(gui): panel = gui.create(Panel) panel.rect = (50, 50, 500,",
"sum(row_heights[rect.y:rect.bottom]) + (rect.h - 1) * self.spacing panel.rect_outer = Panel.Rect(x, y, width, height)",
"* sizing[1]) calculate_percentage_sizes(column_sizings_by_type, column_widths, area.w) calculate_percentage_sizes(row_sizings_by_type, row_heights, area.h) def calculate_custom_sizes(sizings_by_type, sizes, area_size, remaining_size):",
"None)) self.assertEqual(Panel.Rect(2, 3, width_0, height_0), child_0_0.rect_outer) self.assertEqual(Panel.Rect(2, 8 + height_0, width_0, height_1), child_0_1.rect_outer)",
"grid.set_fixed_column_sizing(0, 101) grid.set_fixed_column_sizing(1, 0) grid.set_fixed_row_sizing(0, 0) grid.set_fixed_row_sizing(1, 93) def create_child(rect): child = self.gui.create(Panel)",
"1, spacing = 0): self.panels = dict() self.column_sizings = dict() self.row_sizings = dict()",
"to access. self.column_widths = column_widths self.row_heights = row_heights # Position child panels. for",
"0.8139)) self.assertEqual(Panel.Rect(2, 3, width_0, height_0), child_0_0.rect_outer) self.assertEqual(Panel.Rect(2, 8 + height_0, width_0, height_1), child_0_1.rect_outer)",
"with self.subTest(\"column\"): grid = create_grid() child = self.gui.create(Panel) child.size = (66, 38) grid.add_rect(child,",
"rect.intersects(rect_other): return False return True def set_fixed_column_sizing(self, column, size): self.column_sizings[column] = (self.FIXED, size)",
"- sum(row_heights), 0) def allocate_extra_percentage(sizings_by_type, sizes, extra): for sizing_tuple in sizings_by_type.get(self.PERCENTAGE, []): column_or_row,",
"def custom_sizing_2(area_size, remaining_size): return area_size - area_size ** 0.8 grid = GridLayout(column_count=2, row_count=2,",
"self.assertEqual(60, grid.widest_child_in_column(2)) with self.subTest(\"column\"): grid = create_grid() child = self.gui.create(Panel) child.size = (38,",
"# In case a panel spans multiple rows, determine the height as a",
"= (self.PERCENTAGE, percentage) def set_percentage_row_sizing(self, row, percentage): self.row_sizings[row] = (self.PERCENTAGE, percentage) def set_custom_column_sizing(self,",
"33), child_0_0.rect_outer) self.assertEqual(Panel.Rect(108, 3, 58, 33), child_1_0.rect_outer) self.assertEqual(Panel.Rect( 2, 41, 101, 93), child_0_1.rect_outer)",
"partial from toolz.dicttoolz import valfilter # | Type of sizing | Maximum extra",
"row_count=5, spacing=3) for column in range(grid.column_count): grid.set_child_column_sizing(column) for row in range(grid.row_count): grid.set_child_row_sizing(row) return",
"102), child.rect) def test_multiple_fixed_1(self): grid = GridLayout(column_count=2, row_count=2, spacing=5) grid.set_fixed_column_sizing(0, 101) grid.set_fixed_column_sizing(1, 58)",
"+ 1 width_1 = int(189 * 0.5) height_0 = int(287 * 0.5) +",
"row_count self.spacing = spacing def add(self, panel, column, row, column_count=1, row_count=1): self.add_rect(panel, Rect(column,",
"from desky.panel import Panel from enum import Enum from functools import reduce, partial",
"panels will split remaining space evenly between # themselves. Fill evaluates last and",
"multiple rows, determine the height as a # proportional amount. return int((panel.rect_outer.h -",
"rect, panel = rect_panel_tuple # In case a panel spans multiple columns, determine",
"remaining_size): return area_size ** 0.5 def custom_extra(extra): return extra / 2 grid =",
"(self.FILL,) def widest_child_in_column(self, column): column_rect = Rect(column, 0, 1, self.row_count) rect_panel_tuples_that_intersect_column = list(",
"- 1) * self.spacing panel.rect_outer = Panel.Rect(x, y, width, height) class GridLayoutTest(unittest.TestCase): def",
"+ 1 height_1 = int(287 * 0.5) self.assertEqual(Panel.Rect(2, 3, width_0, height_0), child_0_0.rect_outer) self.assertEqual(Panel.Rect(2,",
"root_width) / 2) - 19 final_height = root_height + int((292 - root_height) /",
"= self.gui.create(Panel) child.size = (66, 38) grid.add_rect(child, Rect(2, 1, 3, 2)) self.assertEqual(20, grid.widest_child_in_column(2))",
"80, 50), child_0_1.rect_outer) self.assertEqual(Panel.Rect(87, 3, 44, 105), child_1_0.rect_outer) def test_single_percentage(self): grid = GridLayout(spacing=5)",
"# The types of sizing in the table above are ordered in evalulation",
"area.h) def calculate_custom_sizes(sizings_by_type, sizes, area_size, remaining_size): for sizing_tuple in sizings_by_type.get(self.CUSTOM, []): column_or_row, sizing",
"def test_multiple_fixed_1(self): grid = GridLayout(column_count=2, row_count=2, spacing=5) grid.set_fixed_column_sizing(0, 101) grid.set_fixed_column_sizing(1, 58) grid.set_fixed_row_sizing(0, 33)",
"/ 2 grid = GridLayout(spacing=5) grid.set_custom_column_sizing(0, custom_sizing, custom_extra) grid.set_custom_row_sizing(0, custom_sizing, custom_extra) child =",
"-= amount return extra extra_width = allocate_extra_custom(column_sizings_by_type, column_widths, extra_width) extra_height = allocate_extra_custom(row_sizings_by_type, row_heights,",
"| Child (use child size) | 0px # | Percentage (30% of width)",
"table above are ordered in evalulation priority. # Fixed, Child, and Percentage sizings",
"self.assertEqual(Panel.Rect(7 + width_0, 8 + height_0, width_1, height_1), child_1_1.rect_outer) def test_single_custom(self): def custom_sizing(area_size,",
"= create_child(Rect(1, 0, 1, 1), (25, 71)) child_0_1 = create_child(Rect(0, 1, 1, 1),",
"up to the # parent to decide if it should resize. def zero_func():",
"# | Child (use child size) | 0px # | Percentage (30% of",
"100 height_1 = 100 self.assertEqual(Panel.Rect(2, 3, width_0, height_0), child_0_0.rect_outer) self.assertEqual(Panel.Rect(2, 8 + height_0,",
"1) rect_panel_tuples_that_intersect_row = list( filter( lambda rect_panel_tuple: rect_panel_tuple[0].intersects(row_rect), self.panels.items())) def calculate_height(rect_panel_tuple): rect, panel",
"= create_child(Rect(0, 1, 1, 1)) child_1_0 = create_child(Rect(1, 0, 1, 1)) child_1_1 =",
"(20, 30, 40, 50) def test_tallest_child_in_column_or_row_1(self): grid = GridLayout(column_count=5, row_count=5, spacing=3) for column",
"extra -= amount return extra extra_width = allocate_extra_percentage(column_sizings_by_type, column_widths, extra_width) extra_height = allocate_extra_percentage(row_sizings_by_type,",
"return extra extra_width = allocate_extra_custom(column_sizings_by_type, column_widths, extra_width) extra_height = allocate_extra_custom(row_sizings_by_type, row_heights, extra_height) def",
"= GridLayout(column_count=2, row_count=2, spacing=5) grid.set_fixed_column_sizing(0, 101) grid.set_fixed_column_sizing(1, 58) grid.set_fixed_row_sizing(0, 33) grid.set_fixed_row_sizing(1, 93) def",
"93), child_0_1.rect_outer) self.assertEqual(Panel.Rect(108, 41, 58, 93), child_1_1.rect_outer) def test_multiple_fixed_2(self): grid = GridLayout(column_count=2, row_count=2,",
"40, 50) def test_tallest_child_in_column_or_row_1(self): grid = GridLayout(column_count=5, row_count=5, spacing=3) for column in range(grid.column_count):",
"in range(grid.column_count): grid.set_child_column_sizing(column) for row in range(grid.row_count): grid.set_child_row_sizing(row) return grid with self.subTest(\"column\"): grid",
"sizing[1] calculate_fixed_sizes(column_sizings_by_type, column_widths) calculate_fixed_sizes(row_sizings_by_type, row_heights) def calculate_child_sizes(sizings_by_type, sizes, largest_func): for sizing_tuple in sizings_by_type.get(self.CHILD,",
"in evalulation priority. # Fixed, Child, and Percentage sizings are evaluated first. Custom",
"rect_panel_tuples_that_intersect_row), 0) def layout(self, panel): area = (panel.rect_inner .move(-panel.x, -panel.y) .shrink( 0, 0,",
"x = area.x + sum(column_widths[:rect.x]) + rect.x * self.spacing y = area.y +",
"(Rect(2, 0, 4, 2), Rect(1, 1, 9, 9), False), (Rect(10, 2, 4, 4),",
"def set_fixed_column_sizing(self, column, size): self.column_sizings[column] = (self.FIXED, size) def set_fixed_row_sizing(self, row, size): self.row_sizings[row]",
"2, 8, 101, 93), child_0_1.rect_outer) self.assertEqual(Panel.Rect(108, 8, 19, 93), child_1_1.rect_outer) def test_single_child(self): grid",
"sizings_by_type.get(self.CUSTOM, []): column_or_row, sizing = sizing_tuple sizes[column_or_row] = int(sizing[1](area_size, remaining_size)) calculate_custom_sizes(column_sizings_by_type, column_widths, area.w,",
"= self.parent child.padding = (10, 8, 6, 4) child.margins = (11, 16, 8,",
"decide if it should resize. def zero_func(): return 0 class GridLayout: FIXED =",
"2)) self.assertEqual(20, grid.widest_child_in_column(2)) self.assertEqual(20, grid.widest_child_in_column(3)) self.assertEqual(20, grid.widest_child_in_column(4)) with self.subTest(\"row\"): grid = create_grid() child",
"int(189 * 0.333) + 1 width_1 = width_0 height_0 = int(287 * 0.8139)",
"= root_width + int((194 - root_width) / 2) - 19 final_height = root_height",
"grid = create_grid() child = self.gui.create(Panel) child.size = (60, 38) grid.add(child, 2, 1)",
"self.column_sizings[column] = (self.PERCENTAGE, percentage) def set_percentage_row_sizing(self, row, percentage): self.row_sizings[row] = (self.PERCENTAGE, percentage) def",
"allocate_extra_percentage(row_sizings_by_type, row_heights, extra_height) def allocate_extra_custom(sizings_by_type, sizes, extra): for sizing_tuple in sizings_by_type.get(self.CUSTOM, []): column_or_row,",
"default we should make sure it works even # when we don't excplicitly",
"grid.layout(self.parent) self.assertEqual(Panel.Rect(13, 19, 53, 81), child.rect) def test_multiple_child_1(self): grid = GridLayout(column_count=2, row_count=2, spacing=5)",
"self.assertEqual(Panel.Rect(13, 19, 71, 102), child.rect) def test_multiple_fixed_1(self): grid = GridLayout(column_count=2, row_count=2, spacing=5) grid.set_fixed_column_sizing(0,",
"101, 18), child_0_0.rect_outer) self.assertEqual(Panel.Rect(108, 3, 19, 18), child_1_0.rect_outer) self.assertEqual(Panel.Rect( 2, 8, 101, 93),",
"self.assertEqual(20, grid.tallest_child_in_row(4)) def test_area_empty(self): scenarios = [ (Rect(2, 0, 4, 2), Rect(1, 1,",
"1 width_1 = int(custom_sizing_2(189, None)) height_0 = int(custom_sizing_2(287, None)) + 1 height_1 =",
"child.size = (53, 81) grid.add(child, 0, 0) grid.layout(self.parent) self.assertEqual(Panel.Rect(13, 19, 71, 102), child.rect)",
"grid.set_fixed_row_sizing(0, 0) grid.set_fixed_row_sizing(1, 93) def create_child(rect): child = self.gui.create(Panel) child.parent = self.parent child.padding",
"set_custom_column_sizing(self, column, sizing_func, extra_func=zero_func): self.column_sizings[column] = (self.CUSTOM, sizing_func, extra_func) def set_custom_row_sizing(self, row, sizing_func,",
"grid.set_fixed_row_sizing(0, 33) grid.set_fixed_row_sizing(1, 93) def create_child(rect): child = self.gui.create(Panel) child.parent = self.parent child.padding",
"child_0_1.rect_outer) self.assertEqual(Panel.Rect(87, 3, 44, 105), child_1_0.rect_outer) def test_single_percentage(self): grid = GridLayout(spacing=5) grid.set_percentage_column_sizing(0, 0.333)",
"grid.set_custom_row_sizing(0, custom_sizing_2, partial(min, 1)) grid.set_custom_row_sizing(1, custom_sizing_1, partial(min, 1)) def create_child(rect): child = self.gui.create(Panel)",
"sizing_tuple in sizings_by_type.get(self.CUSTOM, []): column_or_row, sizing = sizing_tuple sizes[column_or_row] = int(sizing[1](area_size, remaining_size)) calculate_custom_sizes(column_sizings_by_type,",
"GridLayout(spacing=5) grid.set_percentage_column_sizing(0, 0.333) grid.set_percentage_row_sizing(0, 0.8) child = self.gui.create(Panel) child.parent = self.parent child.padding =",
"- 1) * self.spacing, (self.row_count - 1) * self.spacing) ) column_sizings_by_type = dict()",
"def remove(self, panel): self.panels = valfilter(lambda p: p != panel, self.panels) def clear(self,",
"grid.set_fixed_column_sizing(0, 90) grid.set_fixed_row_sizing(0, 120) child = self.gui.create(Panel) child.parent = self.parent child.padding = (10,",
"for users to access. self.column_widths = column_widths self.row_heights = row_heights # Position child",
"self.row_count) rect_panel_tuples_that_intersect_column = list( filter( lambda rect_panel_tuple: rect_panel_tuple[0].intersects(column_rect), self.panels.items())) def calculate_width(rect_panel_tuple): rect, panel",
"3, row_count = 4, spacing = 4) for row in range(0, grid.row_count): for",
"child.size = (53, 81) grid.add(child, 0, 0) grid.layout(self.parent) width = int(self.parent.rect_inner.w * 0.333)",
"1, 1), (54, 20)) grid.layout(self.parent) self.assertEqual(Panel.Rect( 2, 3, 80, 89), child_0_0.rect_outer) self.assertEqual(Panel.Rect(87, 3,",
"+ 1 width_1 = int(custom_sizing_2(189, None)) height_0 = int(custom_sizing_2(287, None)) + 1 height_1",
"column_widths, area.w) calculate_percentage_sizes(row_sizings_by_type, row_heights, area.h) def calculate_custom_sizes(sizings_by_type, sizes, area_size, remaining_size): for sizing_tuple in",
"extra): for sizing_tuple in sizings_by_type.get(self.EVEN, []): column_or_row, _ = sizing_tuple amount = min(extra,",
"87)) grid.layout(self.parent) self.assertEqual(Panel.Rect( 2, 3, 80, 50), child_0_0.rect_outer) self.assertEqual(Panel.Rect( 2, 58, 80, 50),",
"ordered in evalulation priority. # Fixed, Child, and Percentage sizings are evaluated first.",
"height_0, width_1, height_1), child_1_1.rect_outer) def grid_example(gui): panel = gui.create(Panel) panel.rect = (50, 50,",
"19, width, height), child.rect) def test_multiple_percentage(self): grid = GridLayout(column_count=2, row_count=2, spacing=5) grid.set_percentage_column_sizing(0, 0.333)",
"= GridLayout(column_count=2, row_count=2, spacing=5) grid.set_percentage_column_sizing(0, 0.3333) grid.set_fill_column_sizing(1) grid.set_fill_row_sizing(0) grid.set_fixed_row_sizing(1, 100) def create_child(rect): child",
"column_count self.row_count = row_count self.spacing = spacing def add(self, panel, column, row, column_count=1,",
"4, 5) self.parent.margins = (20, 30, 40, 50) def test_tallest_child_in_column_or_row_1(self): grid = GridLayout(column_count=5,",
"CUSTOM = 3 EVEN = 4 FILL = 5 def __init__(self, *, column_count",
"spacing = 4) for row in range(0, grid.row_count): for column in range(0, grid.column_count):",
"column in range(grid.column_count): grid.set_child_column_sizing(column) for row in range(grid.row_count): grid.set_child_row_sizing(row) return grid with self.subTest(\"column\"):",
"sum(row_heights), 0) def allocate_extra_percentage(sizings_by_type, sizes, extra): for sizing_tuple in sizings_by_type.get(self.PERCENTAGE, []): column_or_row, _",
"row, percentage): self.row_sizings[row] = (self.PERCENTAGE, percentage) def set_custom_column_sizing(self, column, sizing_func, extra_func=zero_func): self.column_sizings[column] =",
"calculate_percentage_sizes(sizings_by_type, sizes, area_size): for sizing_tuple in sizings_by_type.get(self.PERCENTAGE, []): column_or_row, sizing = sizing_tuple sizes[column_or_row]",
"1, 1, 1)) grid.layout(self.parent) width_0 = int(custom_sizing_1(189, None)) + 1 width_1 = int(custom_sizing_2(189,",
"in range(grid.column_count): grid.set_child_column_sizing(column) for row in range(grid.row_count): grid.set_child_row_sizing(row) self.assertEqual(0, grid.widest_child_in_column(2)) self.assertEqual(0, grid.tallest_child_in_row(2)) def",
"grid.set_fill_row_sizing(0) grid.set_fixed_row_sizing(1, 100) def create_child(rect): child = self.gui.create(Panel) child.parent = self.parent child.padding =",
"def calculate_percentage_sizes(sizings_by_type, sizes, area_size): for sizing_tuple in sizings_by_type.get(self.PERCENTAGE, []): column_or_row, sizing = sizing_tuple",
"range(self.column_count)] row_heights = [0 for _ in range(self.row_count)] def calculate_fixed_sizes(sizings_by_type, sizes): for sizing_tuple",
"= create_child(Rect(1, 0, 1, 1)) child_0_1 = create_child(Rect(0, 1, 1, 1)) child_1_1 =",
"def test_single_child(self): grid = GridLayout(spacing=5) grid.set_child_column_sizing(0) grid.set_child_row_sizing(0) child = self.gui.create(Panel) child.parent = self.parent",
"dict() def area_empty(self, rect): for rect_other in self.panels.keys(): if rect.intersects(rect_other): return False return",
"self.spacing height = sum(row_heights[rect.y:rect.bottom]) + (rect.h - 1) * self.spacing panel.rect_outer = Panel.Rect(x,",
"= int(194 ** 0.5) root_height = int(292 ** 0.5) final_width = root_width +",
"import reduce, partial from toolz.dicttoolz import valfilter # | Type of sizing |",
"root_height = int(292 ** 0.5) final_width = root_width + int((194 - root_width) /",
"100 self.assertEqual(Panel.Rect(2, 3, width_0, height_0), child_0_0.rect_outer) self.assertEqual(Panel.Rect(2, 8 + height_0, width_0, height_1), child_0_1.rect_outer)",
"= (self.EVEN,) def set_even_row_sizing(self, row): self.row_sizings[row] = (self.EVEN,) def set_fill_column_sizing(self, column): self.column_sizings[column] =",
"custom_sizing_2, partial(min, 1)) grid.set_custom_row_sizing(1, custom_sizing_1, partial(min, 1)) def create_child(rect): child = self.gui.create(Panel) child.parent",
"grid.tallest_child_in_row(2)) def test_tallest_child_in_column_or_row_3(self): def create_grid(): grid = GridLayout(column_count=5, row_count=5, spacing=3) for column in",
"1)) grid.layout(self.parent) width_0 = int(189 * 0.3333) width_1 = 189 - int(189 *",
"8 + height_0, width_0, height_1), child_0_1.rect_outer) self.assertEqual(Panel.Rect(7 + width_0, 3, width_1, height_0), child_1_0.rect_outer)",
"grid.set_custom_row_sizing(0, custom_sizing, custom_extra) child = self.gui.create(Panel) child.parent = self.parent child.padding = (10, 8,",
"proportional amount. return int((panel.rect_outer.w - (rect.w - 1) * self.spacing) / rect.w) return",
"min(extra, 1) sizes[column_or_row] += amount extra -= amount return extra extra_width = allocate_extra_even(column_sizings_by_type,",
"False return True def set_fixed_column_sizing(self, column, size): self.column_sizings[column] = (self.FIXED, size) def set_fixed_row_sizing(self,",
"grid_example(gui): panel = gui.create(Panel) panel.rect = (50, 50, 500, 500) panel.padding = (8,",
"the resulting layout exceeds the bounds of the parent, it is up to",
"child_1_1.rect_outer) def test_multiple_child_2(self): grid = GridLayout(column_count=2, row_count=2, spacing=5) grid.set_child_column_sizing(0) grid.set_child_column_sizing(1) grid.set_child_row_sizing(0) grid.set_child_row_sizing(1) def",
"create_child(Rect(1, 1, 1, 1)) grid.layout(self.parent) self.assertEqual(Panel.Rect( 2, 3, 101, 18), child_0_0.rect_outer) self.assertEqual(Panel.Rect(108, 3,",
"list( filter( lambda rect_panel_tuple: rect_panel_tuple[0].intersects(row_rect), self.panels.items())) def calculate_height(rect_panel_tuple): rect, panel = rect_panel_tuple #",
"def set_percentage_column_sizing(self, column, percentage): self.column_sizings[column] = (self.PERCENTAGE, percentage) def set_percentage_row_sizing(self, row, percentage): self.row_sizings[row]",
"- 19 + 1 height = int(self.parent.rect_inner.h * 0.8) - 18 + 1",
"child_0_1 = create_child(Rect(0, 1, 1, 1), (61, 62)) child_1_1 = create_child(Rect(1, 1, 1,",
"2) child.size = size grid.add_rect(child, rect) return child child_0_0 = create_child(Rect(0, 0, 1,",
"extra_height = max(area.h - sum(row_heights), 0) def allocate_extra_percentage(sizings_by_type, sizes, extra): for sizing_tuple in",
"child_1_1.rect_outer) def test_single_even(self): # Since even sizing is the default we should make",
"1)) child_1_1 = create_child(Rect(1, 1, 1, 1)) grid.layout(self.parent) self.assertEqual(Panel.Rect( 2, 3, 101, 18),",
"= sum(column_widths[rect.x:rect.right]) + (rect.w - 1) * self.spacing height = sum(row_heights[rect.y:rect.bottom]) + (rect.h",
"child.size = (53, 81) grid.add(child, 0, 0) grid.layout(self.parent) self.assertEqual(Panel.Rect(13, 19, 175, 274), child.rect)",
"3, width_1, height_0), child_1_0.rect_outer) self.assertEqual(Panel.Rect(7 + width_0, 8 + height_0, width_1, height_1), child_1_1.rect_outer)",
"row, size): self.row_sizings[row] = (self.FIXED, size) def set_child_column_sizing(self, column): self.column_sizings[column] = (self.CHILD,) def",
"y = area.y + sum(row_heights[:rect.y]) + rect.y * self.spacing width = sum(column_widths[rect.x:rect.right]) +",
"default in (True, False): with self.subTest(default=default): grid = GridLayout(spacing=5) if not default: grid.set_even_column_sizing(0)",
"def create_child(rect, size): child = self.gui.create(Panel) child.parent = self.parent child.padding = (10, 8,",
"grid.set_child_row_sizing(row) return grid with self.subTest(\"column\"): grid = create_grid() child = self.gui.create(Panel) child.size =",
"sizes, area_size): for sizing_tuple in sizings_by_type.get(self.PERCENTAGE, []): column_or_row, sizing = sizing_tuple sizes[column_or_row] =",
"1, 1)) grid.layout(self.parent) width_0 = int(189 * 0.333) + 1 width_1 = width_0",
"def widest_child_in_column(self, column): column_rect = Rect(column, 0, 1, self.row_count) rect_panel_tuples_that_intersect_column = list( filter(",
"amount extra -= amount return extra extra_width = allocate_extra_percentage(column_sizings_by_type, column_widths, extra_width) extra_height =",
"= GridLayout(spacing=5) grid.set_percentage_column_sizing(0, 0.333) grid.set_percentage_row_sizing(0, 0.8) child = self.gui.create(Panel) child.parent = self.parent child.padding",
"= (2, 3, 4, 5) self.parent.margins = (20, 30, 40, 50) def test_tallest_child_in_column_or_row_1(self):",
"+ height_0, width_1, height_1), child_1_1.rect_outer) def test_single_fill(self): grid = GridLayout(spacing=5) grid.set_fill_column_sizing(0) grid.set_fill_row_sizing(0) child",
"80), child_0_1.rect_outer) self.assertEqual(Panel.Rect(87, 97, 73, 80), child_1_1.rect_outer) def test_multiple_child_2(self): grid = GridLayout(column_count=2, row_count=2,",
"panel.rect = (50, 50, 500, 500) panel.padding = (8, 16, 24, 32) grid",
"child_1_1 = create_child(Rect(1, 1, 1, 1)) grid.layout(self.parent) self.assertEqual(Panel.Rect( 2, 3, 101, 33), child_0_0.rect_outer)",
"remaining_size): return area_size ** 0.8 def custom_sizing_2(area_size, remaining_size): return area_size - area_size **",
"(53, 81) grid.add(child, 0, 0) grid.layout(self.parent) self.assertEqual(Panel.Rect(13, 19, 175, 274), child.rect) def test_multiple_fill(self):",
"in the table above are ordered in evalulation priority. # Fixed, Child, and",
"sizing_func, extra_func) def set_custom_row_sizing(self, row, sizing_func, extra_func=zero_func): self.row_sizings[row] = (self.CUSTOM, sizing_func, extra_func) def",
"[]) if fill_columns: column_widths[fill_columns[0][0]] = area.w - sum(column_widths) fill_rows = row_sizings_by_type.get(self.FILL, []) if",
"width_1, height_1), child_1_1.rect_outer) def test_single_even(self): # Since even sizing is the default we",
"for column in range(grid.column_count): grid.set_child_column_sizing(column) for row in range(grid.row_count): grid.set_child_row_sizing(row) self.assertEqual(0, grid.widest_child_in_column(2)) self.assertEqual(0,",
"child_1_0.rect_outer) self.assertEqual(Panel.Rect(7 + width_0, 8 + height_0, width_1, height_1), child_1_1.rect_outer) def test_single_fill(self): grid",
"take the remaining space. # # If the resulting layout exceeds the bounds",
"width_0 = int(189 * 0.3333) width_1 = 189 - int(189 * 0.3333) height_0",
"8, 2) child.size = (53, 81) grid.add(child, 0, 0) grid.layout(self.parent) root_width = int(194",
"] for rect_left, rect_right, empty in scenarios: with self.subTest(rect_left=rect_left, rect_right=rect_right, empty=empty): grid =",
"assert(rect.y >= 0) assert(rect.right <= self.column_count) assert(rect.bottom <= self.row_count) assert(self.area_empty(rect)) self.panels[rect.frozen_copy()] = panel",
".move(-panel.x, -panel.y) .shrink( 0, 0, (self.column_count - 1) * self.spacing, (self.row_count - 1)",
"+ int((292 - root_height) / 2) - 18 self.assertEqual(Panel.Rect(13, 19, final_width, final_height), child.rect)",
"(9999, 9999) grid.add_rect(child, rect) return child child_0_0 = create_child(Rect(0, 0, 1, 1)) child_1_0",
"self.row_sizings[row] = (self.FILL,) def widest_child_in_column(self, column): column_rect = Rect(column, 0, 1, self.row_count) rect_panel_tuples_that_intersect_column",
"= (self.FIXED, size) def set_fixed_row_sizing(self, row, size): self.row_sizings[row] = (self.FIXED, size) def set_child_column_sizing(self,",
"sizing[1]) calculate_percentage_sizes(column_sizings_by_type, column_widths, area.w) calculate_percentage_sizes(row_sizings_by_type, row_heights, area.h) def calculate_custom_sizes(sizings_by_type, sizes, area_size, remaining_size): for",
"self.subTest(\"column\"): grid = create_grid() child = self.gui.create(Panel) child.size = (38, 60) grid.add(child, 1,",
"fill_rows = row_sizings_by_type.get(self.FILL, []) if fill_rows: row_heights[fill_rows[0][0]] = area.h - sum(row_heights) # Allocate",
"should resize. def zero_func(): return 0 class GridLayout: FIXED = 0 CHILD =",
"16, 8, 2) child.size = (53, 81) grid.add(child, 0, 0) grid.layout(self.parent) root_width =",
"size grid.add_rect(child, rect) return child child_0_0 = create_child(Rect(0, 0, 1, 1), (58, 39))",
"self.column_sizings.get(column, (self.EVEN,)) group = column_sizings_by_type.get(sizing[0], list()) group.append((column, sizing)) column_sizings_by_type[sizing[0]] = group for row",
"and Percentage sizings are evaluated first. Custom is then # evaluated and is",
"child = self.gui.create(Panel) child.parent = self.parent child.padding = (10, 8, 6, 4) child.margins",
"rect_panel_tuple: rect_panel_tuple[0].intersects(row_rect), self.panels.items())) def calculate_height(rect_panel_tuple): rect, panel = rect_panel_tuple # In case a",
"self.column_sizings[column] = (self.FIXED, size) def set_fixed_row_sizing(self, row, size): self.row_sizings[row] = (self.FIXED, size) def",
"0 CHILD = 1 PERCENTAGE = 2 CUSTOM = 3 EVEN = 4",
"<= self.column_count) assert(rect.bottom <= self.row_count) assert(self.area_empty(rect)) self.panels[rect.frozen_copy()] = panel def remove(self, panel): self.panels",
"set_fill_column_sizing(self, column): self.column_sizings[column] = (self.FILL,) def set_fill_row_sizing(self, row): self.row_sizings[row] = (self.FILL,) def widest_child_in_column(self,",
"1, 3, 2)) self.assertEqual(20, grid.widest_child_in_column(2)) self.assertEqual(20, grid.widest_child_in_column(3)) self.assertEqual(20, grid.widest_child_in_column(4)) with self.subTest(\"row\"): grid =",
"+ 1 height_1 = int(custom_sizing_1(287, None)) self.assertEqual(Panel.Rect(2, 3, width_0, height_0), child_0_0.rect_outer) self.assertEqual(Panel.Rect(2, 8",
"argument. Even is # evaluated next. Even panels will split remaining space evenly",
"child = self.gui.create(Panel) child.size = (60, 38) grid.add(child, 2, 1) self.assertEqual(60, grid.widest_child_in_column(2)) with",
"for column in range(self.column_count): sizing = self.column_sizings.get(column, (self.EVEN,)) group = column_sizings_by_type.get(sizing[0], list()) group.append((column,",
"len(sizings_by_type.get(self.EVEN, [1]))) for sizing_tuple in sizings_by_type.get(self.EVEN, []): column_or_row, _ = sizing_tuple sizes[column_or_row] =",
"create_child(Rect(0, 1, 1, 1)) child_1_0 = create_child(Rect(1, 0, 1, 1)) child_1_1 = create_child(Rect(1,",
"1)) child_0_1 = create_child(Rect(0, 1, 1, 1)) child_1_1 = create_child(Rect(1, 1, 1, 1))",
"# evaluated and is given the remaining area size as its argument. Even",
"True), ] for rect_left, rect_right, empty in scenarios: with self.subTest(rect_left=rect_left, rect_right=rect_right, empty=empty): grid",
"** 0.8 grid = GridLayout(column_count=2, row_count=2, spacing=5) grid.set_custom_column_sizing(0, custom_sizing_1, partial(min, 1)) grid.set_custom_column_sizing(1, custom_sizing_2,",
"test_single_fill(self): grid = GridLayout(spacing=5) grid.set_fill_column_sizing(0) grid.set_fill_row_sizing(0) child = self.gui.create(Panel) child.parent = self.parent child.padding",
"area_size ** 0.8 grid = GridLayout(column_count=2, row_count=2, spacing=5) grid.set_custom_column_sizing(0, custom_sizing_1, partial(min, 1)) grid.set_custom_column_sizing(1,",
"= int(custom_sizing_1(287, None)) self.assertEqual(Panel.Rect(2, 3, width_0, height_0), child_0_0.rect_outer) self.assertEqual(Panel.Rect(2, 8 + height_0, width_0,",
"0.8139) grid.set_percentage_row_sizing(1, 1 - 0.8139) def create_child(rect): child = self.gui.create(Panel) child.parent = self.parent",
"grid.set_child_row_sizing(0) grid.set_child_row_sizing(1) def create_child(rect, size): child = self.gui.create(Panel) child.parent = self.parent child.padding =",
"= create_child(Rect(1, 1, 1, 1)) grid.layout(self.parent) width_0 = int(189 * 0.5) + 1",
"custom_sizing_2, partial(min, 1)) grid.set_custom_row_sizing(0, custom_sizing_2, partial(min, 1)) grid.set_custom_row_sizing(1, custom_sizing_1, partial(min, 1)) def create_child(rect):",
"area.h - sum(row_heights) # Allocate extra width and height to columns and rows.",
"remaining area size as its argument. Even is # evaluated next. Even panels",
"column_count=1, row_count=1): self.add_rect(panel, Rect(column, row, column_count, row_count)) def add_rect(self, panel, rect): assert(rect.x >=",
"int(189 * 0.5) height_0 = int(287 * 0.5) + 1 height_1 = int(287",
"self.gui.create(Panel) self.parent.size = (200, 300) self.parent.padding = (2, 3, 4, 5) self.parent.margins =",
"= [ (Rect(2, 0, 4, 2), Rect(1, 1, 9, 9), False), (Rect(10, 2,",
"grid.layout(self.parent) self.assertEqual(Panel.Rect(13, 19, 175, 274), child.rect) def test_multiple_even(self): grid = GridLayout(column_count=2, row_count=2, spacing=5)",
"(self.column_count - 1) * self.spacing, (self.row_count - 1) * self.spacing) ) column_sizings_by_type =",
"| 0px # | Percentage (30% of width) | 1px # | Custom",
"and height to columns and rows. extra_width = max(area.w - sum(column_widths), 0) extra_height",
"3 EVEN = 4 FILL = 5 def __init__(self, *, column_count = 1,",
"rect_panel_tuples_that_intersect_column = list( filter( lambda rect_panel_tuple: rect_panel_tuple[0].intersects(column_rect), self.panels.items())) def calculate_width(rect_panel_tuple): rect, panel =",
"= [0 for _ in range(self.column_count)] row_heights = [0 for _ in range(self.row_count)]",
"= (20, 30, 40, 50) def test_tallest_child_in_column_or_row_1(self): grid = GridLayout(column_count=5, row_count=5, spacing=3) for",
"/ len(sizings_by_type.get(self.EVEN, [1]))) for sizing_tuple in sizings_by_type.get(self.EVEN, []): column_or_row, _ = sizing_tuple sizes[column_or_row]",
"grid.set_custom_column_sizing(1, custom_sizing_2, partial(min, 1)) grid.set_custom_row_sizing(0, custom_sizing_2, partial(min, 1)) grid.set_custom_row_sizing(1, custom_sizing_1, partial(min, 1)) def",
"- 19 final_height = root_height + int((292 - root_height) / 2) - 18",
"+= amount extra -= amount return extra extra_width = allocate_extra_even(column_sizings_by_type, column_widths, extra_width) extra_height",
"93) def create_child(rect): child = self.gui.create(Panel) child.parent = self.parent child.padding = (10, 8,",
"panel in self.panels.items(): x = area.x + sum(column_widths[:rect.x]) + rect.x * self.spacing y",
"0.8 def custom_sizing_2(area_size, remaining_size): return area_size - area_size ** 0.8 grid = GridLayout(column_count=2,",
"def test_multiple_percentage(self): grid = GridLayout(column_count=2, row_count=2, spacing=5) grid.set_percentage_column_sizing(0, 0.333) grid.set_percentage_column_sizing(1, 0.333) grid.set_percentage_row_sizing(0, 0.8139)",
"row_count=2, spacing=5) grid.set_custom_column_sizing(0, custom_sizing_1, partial(min, 1)) grid.set_custom_column_sizing(1, custom_sizing_2, partial(min, 1)) grid.set_custom_row_sizing(0, custom_sizing_2, partial(min,",
"*, remove_panels): if remove_panels: for panel in self.panels.values(): panel.remove() self.panels = dict() def",
"= list( filter( lambda rect_panel_tuple: rect_panel_tuple[0].intersects(row_rect), self.panels.items())) def calculate_height(rect_panel_tuple): rect, panel = rect_panel_tuple",
"self.assertEqual(60, grid.tallest_child_in_row(2)) def test_tallest_child_in_column_or_row_3(self): def create_grid(): grid = GridLayout(column_count=5, row_count=5, spacing=3) for column",
"area = (panel.rect_inner .move(-panel.x, -panel.y) .shrink( 0, 0, (self.column_count - 1) * self.spacing,",
"(10, 8, 6, 4) child.margins = (11, 16, 8, 2) child.size = (53,",
"amount return extra extra_width = allocate_extra_percentage(column_sizings_by_type, column_widths, extra_width) extra_height = allocate_extra_percentage(row_sizings_by_type, row_heights, extra_height)",
"93), child_1_1.rect_outer) def test_multiple_fixed_2(self): grid = GridLayout(column_count=2, row_count=2, spacing=5) grid.set_fixed_column_sizing(0, 101) grid.set_fixed_column_sizing(1, 0)",
"(rect.h - 1) * self.spacing) / rect.h) return reduce(max, map(calculate_height, rect_panel_tuples_that_intersect_row), 0) def",
"widths and row heights for users to access. self.column_widths = column_widths self.row_heights =",
"self.spacing = spacing def add(self, panel, column, row, column_count=1, row_count=1): self.add_rect(panel, Rect(column, row,",
"3, 101, 33), child_0_0.rect_outer) self.assertEqual(Panel.Rect(108, 3, 58, 33), child_1_0.rect_outer) self.assertEqual(Panel.Rect( 2, 41, 101,",
"height_1), child_1_1.rect_outer) def test_single_custom(self): def custom_sizing(area_size, remaining_size): return area_size ** 0.5 def custom_extra(extra):",
"configurable # | Even (equally divide) | 1px # | Fill (use remaining",
"# Save column widths and row heights for users to access. self.column_widths =",
"create_child(Rect(1, 0, 1, 1), (25, 71)) child_0_1 = create_child(Rect(0, 1, 1, 1), (61,",
"1), (58, 39)) child_1_0 = create_child(Rect(1, 0, 1, 1), (25, 71)) child_0_1 =",
"widest_child_in_column(self, column): column_rect = Rect(column, 0, 1, self.row_count) rect_panel_tuples_that_intersect_column = list( filter( lambda",
"Gui() self.parent = self.gui.create(Panel) self.parent.size = (200, 300) self.parent.padding = (2, 3, 4,",
"Maximum extra width allocation # -------------------------------------------------------------- # | Fixed (200 px) | 0px",
"extra -= amount return extra extra_width = allocate_extra_even(column_sizings_by_type, column_widths, extra_width) extra_height = allocate_extra_even(row_sizings_by_type,",
"spacing=5) grid.add_rect(self.gui.create(Panel), rect_left) self.assertEqual(empty, grid.area_empty(rect_right)) def test_single_fixed(self): grid = GridLayout(spacing=5) grid.set_fixed_column_sizing(0, 90) grid.set_fixed_row_sizing(0,",
"width_0, 8 + height_0, width_1, height_1), child_1_1.rect_outer) def test_single_custom(self): def custom_sizing(area_size, remaining_size): return",
"1, 2) self.assertEqual(60, grid.tallest_child_in_row(2)) def test_tallest_child_in_column_or_row_3(self): def create_grid(): grid = GridLayout(column_count=5, row_count=5, spacing=3)",
"self.gui.create(Panel) child.size = (38, 66) grid.add_rect(child, Rect(1, 2, 2, 3)) self.assertEqual(20, grid.tallest_child_in_row(2)) self.assertEqual(20,",
"(10, 8, 6, 4) child.margins = (11, 16, 8, 2) child.size = (9999,",
"89), child_1_0.rect_outer) self.assertEqual(Panel.Rect( 2, 97, 80, 80), child_0_1.rect_outer) self.assertEqual(Panel.Rect(87, 97, 73, 80), child_1_1.rect_outer)",
"grid.add_rect(child, rect) return child child_0_0 = create_child(Rect(0, 0, 1, 1)) child_1_0 = create_child(Rect(1,",
"range(self.row_count)] def calculate_fixed_sizes(sizings_by_type, sizes): for sizing_tuple in sizings_by_type.get(self.FIXED, []): column_or_row, sizing = sizing_tuple",
"+ width_0, 3, width_1, height_0), child_1_0.rect_outer) self.assertEqual(Panel.Rect(7 + width_0, 8 + height_0, width_1,",
"= (38, 60) grid.add(child, 1, 2) self.assertEqual(60, grid.tallest_child_in_row(2)) def test_tallest_child_in_column_or_row_3(self): def create_grid(): grid",
"dict() self.column_count = column_count self.row_count = row_count self.spacing = spacing def add(self, panel,",
"tallest_child_in_row(self, row): row_rect = Rect(0, row, self.column_count, 1) rect_panel_tuples_that_intersect_row = list( filter( lambda",
"1, 9, 9), True), ] for rect_left, rect_right, empty in scenarios: with self.subTest(rect_left=rect_left,",
"create_child(Rect(1, 1, 1, 1)) grid.layout(self.parent) width_0 = int(189 * 0.333) + 1 width_1",
"(38, 60) grid.add(child, 1, 2) self.assertEqual(60, grid.tallest_child_in_row(2)) def test_tallest_child_in_column_or_row_3(self): def create_grid(): grid =",
"0.3333) width_1 = 189 - int(189 * 0.3333) height_0 = 287 - 100",
"= 287 - 100 height_1 = 100 self.assertEqual(Panel.Rect(2, 3, width_0, height_0), child_0_0.rect_outer) self.assertEqual(Panel.Rect(2,",
"= self.gui.create(Panel) child.parent = self.parent child.padding = (10, 8, 6, 4) child.margins =",
"p: p != panel, self.panels) def clear(self, *, remove_panels): if remove_panels: for panel",
"# Group columns and rows by their sizing types while preserving the order.",
"enum import Enum from functools import reduce, partial from toolz.dicttoolz import valfilter #",
"self.gui.create(Panel) child.parent = self.parent child.padding = (10, 8, 6, 4) child.margins = (11,",
"self.column_count = column_count self.row_count = row_count self.spacing = spacing def add(self, panel, column,",
"* self.spacing) / rect.h) return reduce(max, map(calculate_height, rect_panel_tuples_that_intersect_row), 0) def layout(self, panel): area",
"-= amount return extra extra_width = allocate_extra_percentage(column_sizings_by_type, column_widths, extra_width) extra_height = allocate_extra_percentage(row_sizings_by_type, row_heights,",
"grid.set_fixed_column_sizing(0, 101) grid.set_fixed_column_sizing(1, 58) grid.set_fixed_row_sizing(0, 33) grid.set_fixed_row_sizing(1, 93) def create_child(rect): child = self.gui.create(Panel)",
"size = int(remaining_size / len(sizings_by_type.get(self.EVEN, [1]))) for sizing_tuple in sizings_by_type.get(self.EVEN, []): column_or_row, _",
"row_count = 1, spacing = 0): self.panels = dict() self.column_sizings = dict() self.row_sizings",
"8 + height_0, width_1, height_1), child_1_1.rect_outer) def test_single_fill(self): grid = GridLayout(spacing=5) grid.set_fill_column_sizing(0) grid.set_fill_row_sizing(0)",
"grid.set_percentage_column_sizing(0, 0.333) grid.set_percentage_column_sizing(1, 0.333) grid.set_percentage_row_sizing(0, 0.8139) grid.set_percentage_row_sizing(1, 1 - 0.8139) def create_child(rect): child",
"width_1, height_1), child_1_1.rect_outer) def test_single_custom(self): def custom_sizing(area_size, remaining_size): return area_size ** 0.5 def",
"0.8) - 18 + 1 self.assertEqual(Panel.Rect(13, 19, width, height), child.rect) def test_multiple_percentage(self): grid",
"remaining space) | any # # The types of sizing in the table",
"sizing_tuple in sizings_by_type.get(self.CUSTOM, []): column_or_row, sizing = sizing_tuple amount = int(sizing[2](extra)) sizes[column_or_row] +=",
"= dict() self.row_sizings = dict() self.column_count = column_count self.row_count = row_count self.spacing =",
"child_1_1 = create_child(Rect(1, 1, 1, 1), (54, 20)) grid.layout(self.parent) self.assertEqual(Panel.Rect( 2, 3, 80,",
"-panel.y) .shrink( 0, 0, (self.column_count - 1) * self.spacing, (self.row_count - 1) *",
"20)) grid.layout(self.parent) self.assertEqual(Panel.Rect( 2, 3, 80, 89), child_0_0.rect_outer) self.assertEqual(Panel.Rect(87, 3, 73, 89), child_1_0.rect_outer)",
"0) def allocate_extra_percentage(sizings_by_type, sizes, extra): for sizing_tuple in sizings_by_type.get(self.PERCENTAGE, []): column_or_row, _ =",
"panel, rect): assert(rect.x >= 0) assert(rect.y >= 0) assert(rect.right <= self.column_count) assert(rect.bottom <=",
"= GridLayout(spacing=5) grid.set_fixed_column_sizing(0, 90) grid.set_fixed_row_sizing(0, 120) child = self.gui.create(Panel) child.parent = self.parent child.padding",
"child_0_0.rect_outer) self.assertEqual(Panel.Rect(2, 8 + height_0, width_0, height_1), child_0_1.rect_outer) self.assertEqual(Panel.Rect(7 + width_0, 3, width_1,",
"rect_panel_tuples_that_intersect_row = list( filter( lambda rect_panel_tuple: rect_panel_tuple[0].intersects(row_rect), self.panels.items())) def calculate_height(rect_panel_tuple): rect, panel =",
"Even is # evaluated next. Even panels will split remaining space evenly between",
"return child child_0_0 = create_child(Rect(0, 0, 1, 1), (58, 39)) child_1_0 = create_child(Rect(1,",
"80), child_1_1.rect_outer) def test_multiple_child_2(self): grid = GridLayout(column_count=2, row_count=2, spacing=5) grid.set_child_column_sizing(0) grid.set_child_column_sizing(1) grid.set_child_row_sizing(0) grid.set_child_row_sizing(1)",
"create_grid(): grid = GridLayout(column_count=5, row_count=5, spacing=3) for column in range(grid.column_count): grid.set_child_column_sizing(column) for row",
"(200, 300) self.parent.padding = (2, 3, 4, 5) self.parent.margins = (20, 30, 40,",
"8, 2) child.size = (53, 81) grid.add(child, 0, 0) grid.layout(self.parent) width = int(self.parent.rect_inner.w",
"= int(custom_sizing_1(189, None)) + 1 width_1 = int(custom_sizing_2(189, None)) height_0 = int(custom_sizing_2(287, None))",
"int((194 - root_width) / 2) - 19 final_height = root_height + int((292 -",
"44, 105), child_1_0.rect_outer) def test_single_percentage(self): grid = GridLayout(spacing=5) grid.set_percentage_column_sizing(0, 0.333) grid.set_percentage_row_sizing(0, 0.8) child",
"1, 1)) child_1_1 = create_child(Rect(1, 1, 1, 1)) grid.layout(self.parent) self.assertEqual(Panel.Rect( 2, 3, 101,",
"row): self.row_sizings[row] = (self.EVEN,) def set_fill_column_sizing(self, column): self.column_sizings[column] = (self.FILL,) def set_fill_row_sizing(self, row):",
"= 189 - int(189 * 0.3333) height_0 = 287 - 100 height_1 =",
"test_multiple_fixed_2(self): grid = GridLayout(column_count=2, row_count=2, spacing=5) grid.set_fixed_column_sizing(0, 101) grid.set_fixed_column_sizing(1, 0) grid.set_fixed_row_sizing(0, 0) grid.set_fixed_row_sizing(1,",
"= 1, row_count = 1, spacing = 0): self.panels = dict() self.column_sizings =",
"sizes[column_or_row] = size calculate_even_sizes( column_sizings_by_type, column_widths, area.w - sum(column_widths)) calculate_even_sizes( row_sizings_by_type, row_heights, area.h",
"default: grid.set_even_column_sizing(0) grid.set_even_row_sizing(0) child = self.gui.create(Panel) child.parent = self.parent child.padding = (10, 8,",
"amount return extra extra_width = allocate_extra_even(column_sizings_by_type, column_widths, extra_width) extra_height = allocate_extra_even(row_sizings_by_type, row_heights, extra_height)",
"grid.add(child, 0, 0) grid.layout(self.parent) root_width = int(194 ** 0.5) root_height = int(292 **",
"grid.set_child_row_sizing(row) self.assertEqual(0, grid.widest_child_in_column(2)) self.assertEqual(0, grid.tallest_child_in_row(2)) def test_tallest_child_in_column_or_row_2(self): def create_grid(): grid = GridLayout(column_count=5, row_count=5,",
"+= amount extra -= amount return extra extra_width = allocate_extra_percentage(column_sizings_by_type, column_widths, extra_width) extra_height",
"create_child(Rect(1, 1, 1, 1)) grid.layout(self.parent) width_0 = int(custom_sizing_1(189, None)) + 1 width_1 =",
"** 0.8 def custom_sizing_2(area_size, remaining_size): return area_size - area_size ** 0.8 grid =",
"row_count=20, spacing=5) grid.add_rect(self.gui.create(Panel), rect_left) self.assertEqual(empty, grid.area_empty(rect_right)) def test_single_fixed(self): grid = GridLayout(spacing=5) grid.set_fixed_column_sizing(0, 90)",
"space. # # If the resulting layout exceeds the bounds of the parent,",
"73, 80), child_1_1.rect_outer) def test_multiple_child_2(self): grid = GridLayout(column_count=2, row_count=2, spacing=5) grid.set_child_column_sizing(0) grid.set_child_column_sizing(1) grid.set_child_row_sizing(0)",
"8 + height_0, width_1, height_1), child_1_1.rect_outer) def test_single_even(self): # Since even sizing is",
"area_size): for sizing_tuple in sizings_by_type.get(self.PERCENTAGE, []): column_or_row, sizing = sizing_tuple sizes[column_or_row] = int(area_size",
"97, 80, 80), child_0_1.rect_outer) self.assertEqual(Panel.Rect(87, 97, 73, 80), child_1_1.rect_outer) def test_multiple_child_2(self): grid =",
"child.margins = (11, 16, 8, 2) child.size = (9999, 9999) grid.add_rect(child, rect) return",
"1px # | Custom (custom function) | configurable # | Even (equally divide)",
"2, 1) self.assertEqual(60, grid.widest_child_in_column(2)) with self.subTest(\"column\"): grid = create_grid() child = self.gui.create(Panel) child.size",
"self.assertEqual(Panel.Rect( 2, 3, 101, 18), child_0_0.rect_outer) self.assertEqual(Panel.Rect(108, 3, 19, 18), child_1_0.rect_outer) self.assertEqual(Panel.Rect( 2,",
"def test_multiple_child_2(self): grid = GridLayout(column_count=2, row_count=2, spacing=5) grid.set_child_column_sizing(0) grid.set_child_column_sizing(1) grid.set_child_row_sizing(0) grid.set_child_row_sizing(1) def create_child(rect,",
"= Panel.Rect(x, y, width, height) class GridLayoutTest(unittest.TestCase): def setUp(self): from desky.gui import Gui",
"calculate_custom_sizes(sizings_by_type, sizes, area_size, remaining_size): for sizing_tuple in sizings_by_type.get(self.CUSTOM, []): column_or_row, sizing = sizing_tuple",
"1 width_1 = int(189 * 0.5) height_0 = int(287 * 0.5) + 1",
"int((panel.rect_outer.w - (rect.w - 1) * self.spacing) / rect.w) return reduce(max, map(calculate_width, rect_panel_tuples_that_intersect_column),",
"# | Custom (custom function) | configurable # | Even (equally divide) |",
"setUp(self): from desky.gui import Gui self.gui = Gui() self.parent = self.gui.create(Panel) self.parent.size =",
"3, 73, 89), child_1_0.rect_outer) self.assertEqual(Panel.Rect( 2, 97, 80, 80), child_0_1.rect_outer) self.assertEqual(Panel.Rect(87, 97, 73,",
"5 def __init__(self, *, column_count = 1, row_count = 1, spacing = 0):",
"274), child.rect) def test_multiple_even(self): grid = GridLayout(column_count=2, row_count=2, spacing=5) grid.set_even_column_sizing(0) grid.set_even_column_sizing(1) grid.set_even_row_sizing(0) grid.set_even_row_sizing(1)",
"self.row_count) assert(self.area_empty(rect)) self.panels[rect.frozen_copy()] = panel def remove(self, panel): self.panels = valfilter(lambda p: p",
"1, 1)) grid.layout(self.parent) width_0 = int(custom_sizing_1(189, None)) + 1 width_1 = int(custom_sizing_2(189, None))",
"self.panels.keys(): if rect.intersects(rect_other): return False return True def set_fixed_column_sizing(self, column, size): self.column_sizings[column] =",
"= dict() # Group columns and rows by their sizing types while preserving",
"area_size - area_size ** 0.8 grid = GridLayout(column_count=2, row_count=2, spacing=5) grid.set_custom_column_sizing(0, custom_sizing_1, partial(min,",
"calculate_custom_sizes(row_sizings_by_type, row_heights, area.h, area.h - sum(row_heights)) def calculate_even_sizes(sizings_by_type, sizes, remaining_size): size = int(remaining_size",
"row_count = 4, spacing = 4) for row in range(0, grid.row_count): for column",
"+ sum(column_widths[:rect.x]) + rect.x * self.spacing y = area.y + sum(row_heights[:rect.y]) + rect.y",
"spans multiple rows, determine the height as a # proportional amount. return int((panel.rect_outer.h",
"1, 1, 1)) child_1_0 = create_child(Rect(1, 0, 1, 1)) child_1_1 = create_child(Rect(1, 1,",
"child_0_1.rect_outer) self.assertEqual(Panel.Rect(7 + width_0, 3, width_1, height_0), child_1_0.rect_outer) self.assertEqual(Panel.Rect(7 + width_0, 8 +",
"height_1 = int(custom_sizing_1(287, None)) self.assertEqual(Panel.Rect(2, 3, width_0, height_0), child_0_0.rect_outer) self.assertEqual(Panel.Rect(2, 8 + height_0,",
"height_1), child_1_1.rect_outer) def test_single_fill(self): grid = GridLayout(spacing=5) grid.set_fill_column_sizing(0) grid.set_fill_row_sizing(0) child = self.gui.create(Panel) child.parent",
"EVEN = 4 FILL = 5 def __init__(self, *, column_count = 1, row_count",
"16, 24, 32) grid = GridLayout(column_count = 3, row_count = 4, spacing =",
"= sizing_tuple amount = min(extra, 1) sizes[column_or_row] += amount extra -= amount return",
"1, 1)) child_1_0 = create_child(Rect(1, 0, 1, 1)) child_1_1 = create_child(Rect(1, 1, 1,",
"89), child_0_0.rect_outer) self.assertEqual(Panel.Rect(87, 3, 73, 89), child_1_0.rect_outer) self.assertEqual(Panel.Rect( 2, 97, 80, 80), child_0_1.rect_outer)",
"from enum import Enum from functools import reduce, partial from toolz.dicttoolz import valfilter",
"are evaluated first. Custom is then # evaluated and is given the remaining",
"sizes, extra): for sizing_tuple in sizings_by_type.get(self.EVEN, []): column_or_row, _ = sizing_tuple amount =",
"= create_child(Rect(0, 0, 1, 1)) child_1_0 = create_child(Rect(1, 0, 1, 1)) child_0_1 =",
"with self.subTest(\"column\"): grid = create_grid() child = self.gui.create(Panel) child.size = (60, 38) grid.add(child,",
"calculate_even_sizes( column_sizings_by_type, column_widths, area.w - sum(column_widths)) calculate_even_sizes( row_sizings_by_type, row_heights, area.h - sum(row_heights)) fill_columns",
"(self.FILL,) def set_fill_row_sizing(self, row): self.row_sizings[row] = (self.FILL,) def widest_child_in_column(self, column): column_rect = Rect(column,",
"parent to decide if it should resize. def zero_func(): return 0 class GridLayout:",
"self.add_rect(panel, Rect(column, row, column_count, row_count)) def add_rect(self, panel, rect): assert(rect.x >= 0) assert(rect.y",
"1) * self.spacing) ) column_sizings_by_type = dict() row_sizings_by_type = dict() # Group columns",
"grid with self.subTest(\"column\"): grid = create_grid() child = self.gui.create(Panel) child.size = (66, 38)",
"column_sizings_by_type = dict() row_sizings_by_type = dict() # Group columns and rows by their",
"= (50, 50, 500, 500) panel.padding = (8, 16, 24, 32) grid =",
"grid.set_fill_row_sizing(0) child = self.gui.create(Panel) child.parent = self.parent child.padding = (10, 8, 6, 4)",
"height), child.rect) def test_multiple_percentage(self): grid = GridLayout(column_count=2, row_count=2, spacing=5) grid.set_percentage_column_sizing(0, 0.333) grid.set_percentage_column_sizing(1, 0.333)",
"4), Rect(1, 1, 9, 9), True), ] for rect_left, rect_right, empty in scenarios:",
"= int(sizing[2](extra)) sizes[column_or_row] += amount extra -= amount return extra extra_width = allocate_extra_custom(column_sizings_by_type,",
"def allocate_extra_percentage(sizings_by_type, sizes, extra): for sizing_tuple in sizings_by_type.get(self.PERCENTAGE, []): column_or_row, _ = sizing_tuple",
"rect): for rect_other in self.panels.keys(): if rect.intersects(rect_other): return False return True def set_fixed_column_sizing(self,",
"2) - 19 final_height = root_height + int((292 - root_height) / 2) -",
"group = column_sizings_by_type.get(sizing[0], list()) group.append((column, sizing)) column_sizings_by_type[sizing[0]] = group for row in range(self.row_count):",
"= create_child(Rect(0, 1, 1, 1), (61, 31)) child_1_0 = create_child(Rect(1, 0, 1, 2),",
"custom_extra) grid.set_custom_row_sizing(0, custom_sizing, custom_extra) child = self.gui.create(Panel) child.parent = self.parent child.padding = (10,",
"73, 89), child_1_0.rect_outer) self.assertEqual(Panel.Rect( 2, 97, 80, 80), child_0_1.rect_outer) self.assertEqual(Panel.Rect(87, 97, 73, 80),",
"extra_func) def set_custom_row_sizing(self, row, sizing_func, extra_func=zero_func): self.row_sizings[row] = (self.CUSTOM, sizing_func, extra_func) def set_even_column_sizing(self,",
"valfilter # | Type of sizing | Maximum extra width allocation # --------------------------------------------------------------",
"grid = GridLayout(spacing=5) grid.set_child_column_sizing(0) grid.set_child_row_sizing(0) child = self.gui.create(Panel) child.parent = self.parent child.padding =",
"6, 4) child.margins = (11, 16, 8, 2) child.size = (53, 81) grid.add(child,",
"child.size = (53, 81) grid.add(child, 0, 0) grid.layout(self.parent) self.assertEqual(Panel.Rect(13, 19, 53, 81), child.rect)",
"it works even # when we don't excplicitly set the columns and rows",
"+ width_0, 8 + height_0, width_1, height_1), child_1_1.rect_outer) def test_single_custom(self): def custom_sizing(area_size, remaining_size):",
"| 1px # | Custom (custom function) | configurable # | Even (equally",
"percentage) def set_custom_column_sizing(self, column, sizing_func, extra_func=zero_func): self.column_sizings[column] = (self.CUSTOM, sizing_func, extra_func) def set_custom_row_sizing(self,",
"of sizing in the table above are ordered in evalulation priority. # Fixed,",
"self.row_sizings[row] = (self.FIXED, size) def set_child_column_sizing(self, column): self.column_sizings[column] = (self.CHILD,) def set_child_row_sizing(self, row):",
"33) grid.set_fixed_row_sizing(1, 93) def create_child(rect): child = self.gui.create(Panel) child.parent = self.parent child.padding =",
"81) grid.add(child, 0, 0) grid.layout(self.parent) width = int(self.parent.rect_inner.w * 0.333) - 19 +",
"- (rect.h - 1) * self.spacing) / rect.h) return reduce(max, map(calculate_height, rect_panel_tuples_that_intersect_row), 0)",
"def main(): from desky.gui import example #example(grid_example) unittest.main() if __name__ == \"__main__\": main()",
"width, height) class GridLayoutTest(unittest.TestCase): def setUp(self): from desky.gui import Gui self.gui = Gui()",
"= int(area_size * sizing[1]) calculate_percentage_sizes(column_sizings_by_type, column_widths, area.w) calculate_percentage_sizes(row_sizings_by_type, row_heights, area.h) def calculate_custom_sizes(sizings_by_type, sizes,",
"rect_left, rect_right, empty in scenarios: with self.subTest(rect_left=rect_left, rect_right=rect_right, empty=empty): grid = GridLayout(column_count=20, row_count=20,",
"(11, 16, 8, 2) child.size = (9999, 9999) grid.add_rect(child, rect) return child child_0_0",
"= GridLayout(spacing=5) grid.set_custom_column_sizing(0, custom_sizing, custom_extra) grid.set_custom_row_sizing(0, custom_sizing, custom_extra) child = self.gui.create(Panel) child.parent =",
"58, 93), child_1_1.rect_outer) def test_multiple_fixed_2(self): grid = GridLayout(column_count=2, row_count=2, spacing=5) grid.set_fixed_column_sizing(0, 101) grid.set_fixed_column_sizing(1,",
"child.rect) def test_multiple_percentage(self): grid = GridLayout(column_count=2, row_count=2, spacing=5) grid.set_percentage_column_sizing(0, 0.333) grid.set_percentage_column_sizing(1, 0.333) grid.set_percentage_row_sizing(0,",
"Even (equally divide) | 1px # | Fill (use remaining space) | any",
"2) child.size = (53, 81) grid.add(child, 0, 0) grid.layout(self.parent) width = int(self.parent.rect_inner.w *",
"area.w - sum(column_widths)) calculate_custom_sizes(row_sizings_by_type, row_heights, area.h, area.h - sum(row_heights)) def calculate_even_sizes(sizings_by_type, sizes, remaining_size):",
"3, width_0, height_0), child_0_0.rect_outer) self.assertEqual(Panel.Rect(2, 8 + height_0, width_0, height_1), child_0_1.rect_outer) self.assertEqual(Panel.Rect(7 +",
"child.padding = (10, 8, 6, 4) child.margins = (11, 16, 8, 2) child.size",
"add(self, panel, column, row, column_count=1, row_count=1): self.add_rect(panel, Rect(column, row, column_count, row_count)) def add_rect(self,",
"grid = GridLayout(column_count=2, row_count=2, spacing=5) grid.set_fixed_column_sizing(0, 101) grid.set_fixed_column_sizing(1, 58) grid.set_fixed_row_sizing(0, 33) grid.set_fixed_row_sizing(1, 93)",
"0.8) child = self.gui.create(Panel) child.parent = self.parent child.padding = (10, 8, 6, 4)",
"self.panels.values(): panel.remove() self.panels = dict() def area_empty(self, rect): for rect_other in self.panels.keys(): if",
"order. for column in range(self.column_count): sizing = self.column_sizings.get(column, (self.EVEN,)) group = column_sizings_by_type.get(sizing[0], list())",
"child_1_1 = create_child(Rect(1, 1, 1, 1)) grid.layout(self.parent) width_0 = int(189 * 0.3333) width_1",
"priority. # Fixed, Child, and Percentage sizings are evaluated first. Custom is then",
"child.size = (38, 60) grid.add(child, 1, 2) self.assertEqual(60, grid.tallest_child_in_row(2)) def test_tallest_child_in_column_or_row_3(self): def create_grid():",
"the table above are ordered in evalulation priority. # Fixed, Child, and Percentage",
"spacing = 0): self.panels = dict() self.column_sizings = dict() self.row_sizings = dict() self.column_count",
"child.margins = (11, 16, 8, 2) child.size = size grid.add_rect(child, rect) return child",
"to the # parent to decide if it should resize. def zero_func(): return",
"grid.layout(self.parent) width_0 = int(custom_sizing_1(189, None)) + 1 width_1 = int(custom_sizing_2(189, None)) height_0 =",
"return area_size - area_size ** 0.8 grid = GridLayout(column_count=2, row_count=2, spacing=5) grid.set_custom_column_sizing(0, custom_sizing_1,",
"1, 2), (25, 87)) grid.layout(self.parent) self.assertEqual(Panel.Rect( 2, 3, 80, 50), child_0_0.rect_outer) self.assertEqual(Panel.Rect( 2,",
"extra_width = allocate_extra_custom(column_sizings_by_type, column_widths, extra_width) extra_height = allocate_extra_custom(row_sizings_by_type, row_heights, extra_height) def allocate_extra_even(sizings_by_type, sizes,",
"rect) return child child_0_0 = create_child(Rect(0, 0, 1, 1)) child_0_1 = create_child(Rect(0, 1,",
"False): with self.subTest(default=default): grid = GridLayout(spacing=5) if not default: grid.set_even_column_sizing(0) grid.set_even_row_sizing(0) child =",
"1 height = int(self.parent.rect_inner.h * 0.8) - 18 + 1 self.assertEqual(Panel.Rect(13, 19, width,",
"map(calculate_width, rect_panel_tuples_that_intersect_column), 0) def tallest_child_in_row(self, row): row_rect = Rect(0, row, self.column_count, 1) rect_panel_tuples_that_intersect_row",
"= max(area.h - sum(row_heights), 0) def allocate_extra_percentage(sizings_by_type, sizes, extra): for sizing_tuple in sizings_by_type.get(self.PERCENTAGE,",
"assert(self.area_empty(rect)) self.panels[rect.frozen_copy()] = panel def remove(self, panel): self.panels = valfilter(lambda p: p !=",
"width_1 = int(189 * 0.5) height_0 = int(287 * 0.5) + 1 height_1",
"in sizings_by_type.get(self.PERCENTAGE, []): column_or_row, sizing = sizing_tuple sizes[column_or_row] = int(area_size * sizing[1]) calculate_percentage_sizes(column_sizings_by_type,",
"child_0_0.rect_outer) self.assertEqual(Panel.Rect(108, 3, 19, 18), child_1_0.rect_outer) self.assertEqual(Panel.Rect( 2, 8, 101, 93), child_0_1.rect_outer) self.assertEqual(Panel.Rect(108,",
"None)) + 1 width_1 = int(custom_sizing_2(189, None)) height_0 = int(custom_sizing_2(287, None)) + 1",
"import Rect from desky.panel import Panel from enum import Enum from functools import",
"child = gui.create(Panel) child.parent = panel grid.add(child, column, row) grid.layout(panel) def main(): from",
"import unittest from desky.rect import Rect from desky.panel import Panel from enum import",
"next. Even panels will split remaining space evenly between # themselves. Fill evaluates",
"panel, self.panels) def clear(self, *, remove_panels): if remove_panels: for panel in self.panels.values(): panel.remove()",
"(9999, 9999) grid.add_rect(child, rect) return child child_0_0 = create_child(Rect(0, 0, 1, 1)) child_0_1",
"0) grid.layout(self.parent) self.assertEqual(Panel.Rect(13, 19, 53, 81), child.rect) def test_multiple_child_1(self): grid = GridLayout(column_count=2, row_count=2,",
"grid.set_child_column_sizing(column) for row in range(grid.row_count): grid.set_child_row_sizing(row) self.assertEqual(0, grid.widest_child_in_column(2)) self.assertEqual(0, grid.tallest_child_in_row(2)) def test_tallest_child_in_column_or_row_2(self): def",
"grid.set_child_column_sizing(1) grid.set_child_row_sizing(0) grid.set_child_row_sizing(1) def create_child(rect, size): child = self.gui.create(Panel) child.parent = self.parent child.padding",
"sum(row_heights)) fill_columns = column_sizings_by_type.get(self.FILL, []) if fill_columns: column_widths[fill_columns[0][0]] = area.w - sum(column_widths) fill_rows",
"= (60, 38) grid.add(child, 2, 1) self.assertEqual(60, grid.widest_child_in_column(2)) with self.subTest(\"column\"): grid = create_grid()",
"allocate_extra_percentage(column_sizings_by_type, column_widths, extra_width) extra_height = allocate_extra_percentage(row_sizings_by_type, row_heights, extra_height) def allocate_extra_custom(sizings_by_type, sizes, extra): for",
"create_child(Rect(0, 1, 1, 1), (61, 31)) child_1_0 = create_child(Rect(1, 0, 1, 2), (25,",
"[0 for _ in range(self.row_count)] def calculate_fixed_sizes(sizings_by_type, sizes): for sizing_tuple in sizings_by_type.get(self.FIXED, []):",
"= create_child(Rect(1, 1, 1, 1)) grid.layout(self.parent) self.assertEqual(Panel.Rect( 2, 3, 101, 18), child_0_0.rect_outer) self.assertEqual(Panel.Rect(108,",
"fill_rows: row_heights[fill_rows[0][0]] = area.h - sum(row_heights) # Allocate extra width and height to",
"for rect, panel in self.panels.items(): x = area.x + sum(column_widths[:rect.x]) + rect.x *",
"set_percentage_row_sizing(self, row, percentage): self.row_sizings[row] = (self.PERCENTAGE, percentage) def set_custom_column_sizing(self, column, sizing_func, extra_func=zero_func): self.column_sizings[column]",
"sum(column_widths[rect.x:rect.right]) + (rect.w - 1) * self.spacing height = sum(row_heights[rect.y:rect.bottom]) + (rect.h -",
"row_heights) def calculate_child_sizes(sizings_by_type, sizes, largest_func): for sizing_tuple in sizings_by_type.get(self.CHILD, []): column_or_row, _ =",
"- sum(column_widths)) calculate_custom_sizes(row_sizings_by_type, row_heights, area.h, area.h - sum(row_heights)) def calculate_even_sizes(sizings_by_type, sizes, remaining_size): size",
"set_fixed_row_sizing(self, row, size): self.row_sizings[row] = (self.FIXED, size) def set_child_column_sizing(self, column): self.column_sizings[column] = (self.CHILD,)",
"= min(extra, 1) sizes[column_or_row] += amount extra -= amount return extra extra_width =",
"height as a # proportional amount. return int((panel.rect_outer.h - (rect.h - 1) *",
"self.parent.size = (200, 300) self.parent.padding = (2, 3, 4, 5) self.parent.margins = (20,",
"child.rect) def test_multiple_fill(self): grid = GridLayout(column_count=2, row_count=2, spacing=5) grid.set_percentage_column_sizing(0, 0.3333) grid.set_fill_column_sizing(1) grid.set_fill_row_sizing(0) grid.set_fixed_row_sizing(1,",
"test_multiple_fixed_1(self): grid = GridLayout(column_count=2, row_count=2, spacing=5) grid.set_fixed_column_sizing(0, 101) grid.set_fixed_column_sizing(1, 58) grid.set_fixed_row_sizing(0, 33) grid.set_fixed_row_sizing(1,",
"8, 6, 4) child.margins = (11, 16, 8, 2) child.size = (9999, 9999)",
"(200 px) | 0px # | Child (use child size) | 0px #",
"child.parent = panel grid.add(child, column, row) grid.layout(panel) def main(): from desky.gui import example",
"(self.CHILD,) def set_child_row_sizing(self, row): self.row_sizings[row] = (self.CHILD,) def set_percentage_column_sizing(self, column, percentage): self.column_sizings[column] =",
"- 18 + 1 self.assertEqual(Panel.Rect(13, 19, width, height), child.rect) def test_multiple_percentage(self): grid =",
"create_child(Rect(1, 1, 1, 1)) grid.layout(self.parent) self.assertEqual(Panel.Rect( 2, 3, 101, 33), child_0_0.rect_outer) self.assertEqual(Panel.Rect(108, 3,",
"2) child.size = (53, 81) grid.add(child, 0, 0) grid.layout(self.parent) self.assertEqual(Panel.Rect(13, 19, 53, 81),",
"= int(remaining_size / len(sizings_by_type.get(self.EVEN, [1]))) for sizing_tuple in sizings_by_type.get(self.EVEN, []): column_or_row, _ =",
"child_1_1.rect_outer) def grid_example(gui): panel = gui.create(Panel) panel.rect = (50, 50, 500, 500) panel.padding",
"[]): column_or_row, sizing = sizing_tuple sizes[column_or_row] = int(sizing[1](area_size, remaining_size)) calculate_custom_sizes(column_sizings_by_type, column_widths, area.w, area.w",
"group # Determine column widths and row heights. column_widths = [0 for _",
"Allocate extra width and height to columns and rows. extra_width = max(area.w -",
"resize. def zero_func(): return 0 class GridLayout: FIXED = 0 CHILD = 1",
"Fill evaluates last and will take the remaining space. # # If the",
"extra_height) def allocate_extra_custom(sizings_by_type, sizes, extra): for sizing_tuple in sizings_by_type.get(self.CUSTOM, []): column_or_row, sizing =",
"row_sizings_by_type, row_heights, area.h - sum(row_heights)) fill_columns = column_sizings_by_type.get(self.FILL, []) if fill_columns: column_widths[fill_columns[0][0]] =",
"given the remaining area size as its argument. Even is # evaluated next.",
"amount = min(extra, 1) sizes[column_or_row] += amount extra -= amount return extra extra_width",
"grid.set_custom_column_sizing(0, custom_sizing_1, partial(min, 1)) grid.set_custom_column_sizing(1, custom_sizing_2, partial(min, 1)) grid.set_custom_row_sizing(0, custom_sizing_2, partial(min, 1)) grid.set_custom_row_sizing(1,",
"row_heights[fill_rows[0][0]] = area.h - sum(row_heights) # Allocate extra width and height to columns",
"columns and rows to even sizing. for default in (True, False): with self.subTest(default=default):",
"range(self.row_count): sizing = self.row_sizings.get(row, (self.EVEN,)) group = row_sizings_by_type.get(sizing[0], list()) group.append((row, sizing)) row_sizings_by_type[sizing[0]] =",
"create_child(Rect(1, 0, 1, 1)) child_0_1 = create_child(Rect(0, 1, 1, 1)) child_1_1 = create_child(Rect(1,",
"panel.remove() self.panels = dict() def area_empty(self, rect): for rect_other in self.panels.keys(): if rect.intersects(rect_other):",
"1, 1, 1)) child_1_1 = create_child(Rect(1, 1, 1, 1)) grid.layout(self.parent) self.assertEqual(Panel.Rect( 2, 3,",
"81) grid.add(child, 0, 0) grid.layout(self.parent) self.assertEqual(Panel.Rect(13, 19, 71, 102), child.rect) def test_multiple_fixed_1(self): grid",
"1) sizes[column_or_row] += amount extra -= amount return extra extra_width = allocate_extra_percentage(column_sizings_by_type, column_widths,",
"column): self.column_sizings[column] = (self.CHILD,) def set_child_row_sizing(self, row): self.row_sizings[row] = (self.CHILD,) def set_percentage_column_sizing(self, column,",
"child_0_0 = create_child(Rect(0, 0, 1, 1)) child_0_1 = create_child(Rect(0, 1, 1, 1)) child_1_0",
"row): self.row_sizings[row] = (self.FILL,) def widest_child_in_column(self, column): column_rect = Rect(column, 0, 1, self.row_count)",
"row_heights = [0 for _ in range(self.row_count)] def calculate_fixed_sizes(sizings_by_type, sizes): for sizing_tuple in",
"import Gui self.gui = Gui() self.parent = self.gui.create(Panel) self.parent.size = (200, 300) self.parent.padding",
"import valfilter # | Type of sizing | Maximum extra width allocation #",
"row_rect = Rect(0, row, self.column_count, 1) rect_panel_tuples_that_intersect_row = list( filter( lambda rect_panel_tuple: rect_panel_tuple[0].intersects(row_rect),",
"child = self.gui.create(Panel) child.size = (38, 66) grid.add_rect(child, Rect(1, 2, 2, 3)) self.assertEqual(20,",
"column_widths self.row_heights = row_heights # Position child panels. for rect, panel in self.panels.items():",
"row in range(grid.row_count): grid.set_child_row_sizing(row) self.assertEqual(0, grid.widest_child_in_column(2)) self.assertEqual(0, grid.tallest_child_in_row(2)) def test_tallest_child_in_column_or_row_2(self): def create_grid(): grid",
"row): row_rect = Rect(0, row, self.column_count, 1) rect_panel_tuples_that_intersect_row = list( filter( lambda rect_panel_tuple:",
"81) grid.add(child, 0, 0) grid.layout(self.parent) self.assertEqual(Panel.Rect(13, 19, 175, 274), child.rect) def test_multiple_even(self): grid",
"in sizings_by_type.get(self.EVEN, []): column_or_row, _ = sizing_tuple amount = min(extra, 1) sizes[column_or_row] +=",
"child_0_0 = create_child(Rect(0, 0, 1, 1), (58, 31)) child_0_1 = create_child(Rect(0, 1, 1,",
"area_size ** 0.8 def custom_sizing_2(area_size, remaining_size): return area_size - area_size ** 0.8 grid",
"sizes, largest_func): for sizing_tuple in sizings_by_type.get(self.CHILD, []): column_or_row, _ = sizing_tuple sizes[column_or_row] =",
"width_0, 8 + height_0, width_1, height_1), child_1_1.rect_outer) def test_single_fill(self): grid = GridLayout(spacing=5) grid.set_fill_column_sizing(0)",
"* self.spacing, (self.row_count - 1) * self.spacing) ) column_sizings_by_type = dict() row_sizings_by_type =",
"range(grid.row_count): grid.set_child_row_sizing(row) return grid with self.subTest(\"column\"): grid = create_grid() child = self.gui.create(Panel) child.size",
"0) def layout(self, panel): area = (panel.rect_inner .move(-panel.x, -panel.y) .shrink( 0, 0, (self.column_count",
"width_0, 8 + height_0, width_1, height_1), child_1_1.rect_outer) def test_single_even(self): # Since even sizing",
"rect_right=rect_right, empty=empty): grid = GridLayout(column_count=20, row_count=20, spacing=5) grid.add_rect(self.gui.create(Panel), rect_left) self.assertEqual(empty, grid.area_empty(rect_right)) def test_single_fixed(self):",
"sure it works even # when we don't excplicitly set the columns and",
"and is given the remaining area size as its argument. Even is #",
"child.size = (60, 38) grid.add(child, 2, 1) self.assertEqual(60, grid.widest_child_in_column(2)) with self.subTest(\"column\"): grid =",
"in (True, False): with self.subTest(default=default): grid = GridLayout(spacing=5) if not default: grid.set_even_column_sizing(0) grid.set_even_row_sizing(0)",
"= int(self.parent.rect_inner.h * 0.8) - 18 + 1 self.assertEqual(Panel.Rect(13, 19, width, height), child.rect)",
"amount return extra extra_width = allocate_extra_custom(column_sizings_by_type, column_widths, extra_width) extra_height = allocate_extra_custom(row_sizings_by_type, row_heights, extra_height)",
"bounds of the parent, it is up to the # parent to decide",
"_ in range(self.column_count)] row_heights = [0 for _ in range(self.row_count)] def calculate_fixed_sizes(sizings_by_type, sizes):",
"= row_heights # Position child panels. for rect, panel in self.panels.items(): x =",
"0.5) + 1 width_1 = int(189 * 0.5) height_0 = int(287 * 0.5)",
"child_0_1 = create_child(Rect(0, 1, 1, 1)) child_1_1 = create_child(Rect(1, 1, 1, 1)) grid.layout(self.parent)",
"1 self.assertEqual(Panel.Rect(13, 19, width, height), child.rect) def test_multiple_percentage(self): grid = GridLayout(column_count=2, row_count=2, spacing=5)",
"# evaluated next. Even panels will split remaining space evenly between # themselves.",
"71)) child_0_1 = create_child(Rect(0, 1, 1, 1), (61, 62)) child_1_1 = create_child(Rect(1, 1,",
"grid.set_even_row_sizing(1) def create_child(rect): child = self.gui.create(Panel) child.parent = self.parent child.padding = (10, 8,",
"child_1_1.rect_outer) def test_single_custom(self): def custom_sizing(area_size, remaining_size): return area_size ** 0.5 def custom_extra(extra): return",
"grid.set_custom_column_sizing(0, custom_sizing, custom_extra) grid.set_custom_row_sizing(0, custom_sizing, custom_extra) child = self.gui.create(Panel) child.parent = self.parent child.padding",
"allocate_extra_even(sizings_by_type, sizes, extra): for sizing_tuple in sizings_by_type.get(self.EVEN, []): column_or_row, _ = sizing_tuple amount",
"2) child.size = (53, 81) grid.add(child, 0, 0) grid.layout(self.parent) self.assertEqual(Panel.Rect(13, 19, 175, 274),",
"self.assertEqual(Panel.Rect( 2, 8, 101, 93), child_0_1.rect_outer) self.assertEqual(Panel.Rect(108, 8, 19, 93), child_1_1.rect_outer) def test_single_child(self):",
"def set_child_row_sizing(self, row): self.row_sizings[row] = (self.CHILD,) def set_percentage_column_sizing(self, column, percentage): self.column_sizings[column] = (self.PERCENTAGE,",
"9999) grid.add_rect(child, rect) return child child_0_0 = create_child(Rect(0, 0, 1, 1)) child_1_0 =",
"self.row_sizings = dict() self.column_count = column_count self.row_count = row_count self.spacing = spacing def",
"FIXED = 0 CHILD = 1 PERCENTAGE = 2 CUSTOM = 3 EVEN",
"panel in self.panels.values(): panel.remove() self.panels = dict() def area_empty(self, rect): for rect_other in",
"rect.h) return reduce(max, map(calculate_height, rect_panel_tuples_that_intersect_row), 0) def layout(self, panel): area = (panel.rect_inner .move(-panel.x,",
"size calculate_even_sizes( column_sizings_by_type, column_widths, area.w - sum(column_widths)) calculate_even_sizes( row_sizings_by_type, row_heights, area.h - sum(row_heights))",
"0, 0) grid.layout(self.parent) self.assertEqual(Panel.Rect(13, 19, 175, 274), child.rect) def test_multiple_even(self): grid = GridLayout(column_count=2,",
"themselves. Fill evaluates last and will take the remaining space. # # If",
"1 width_1 = width_0 height_0 = int(287 * 0.8139) + 1 height_1 =",
"final_height), child.rect) def test_multiple_custom(self): def custom_sizing_1(area_size, remaining_size): return area_size ** 0.8 def custom_sizing_2(area_size,",
"= width_0 height_0 = int(287 * 0.8139) + 1 height_1 = int(287 *",
"0.333) + 1 width_1 = width_0 height_0 = int(287 * 0.8139) + 1",
"= self.gui.create(Panel) child.size = (38, 60) grid.add(child, 1, 2) self.assertEqual(60, grid.tallest_child_in_row(2)) def test_tallest_child_in_column_or_row_3(self):",
"a # proportional amount. return int((panel.rect_outer.h - (rect.h - 1) * self.spacing) /",
"sizing_tuple in sizings_by_type.get(self.PERCENTAGE, []): column_or_row, sizing = sizing_tuple sizes[column_or_row] = int(area_size * sizing[1])",
"import Panel from enum import Enum from functools import reduce, partial from toolz.dicttoolz",
"= column_sizings_by_type.get(sizing[0], list()) group.append((column, sizing)) column_sizings_by_type[sizing[0]] = group for row in range(self.row_count): sizing",
"- sum(row_heights)) def calculate_even_sizes(sizings_by_type, sizes, remaining_size): size = int(remaining_size / len(sizings_by_type.get(self.EVEN, [1]))) for",
"| Fill (use remaining space) | any # # The types of sizing",
"| Even (equally divide) | 1px # | Fill (use remaining space) |",
"panel, column, row, column_count=1, row_count=1): self.add_rect(panel, Rect(column, row, column_count, row_count)) def add_rect(self, panel,",
"1), (58, 31)) child_0_1 = create_child(Rect(0, 1, 1, 1), (61, 31)) child_1_0 =",
"desky.rect import Rect from desky.panel import Panel from enum import Enum from functools",
"widths and row heights. column_widths = [0 for _ in range(self.column_count)] row_heights =",
"grid = GridLayout(column_count=2, row_count=2, spacing=5) grid.set_custom_column_sizing(0, custom_sizing_1, partial(min, 1)) grid.set_custom_column_sizing(1, custom_sizing_2, partial(min, 1))",
"= (self.FIXED, size) def set_child_column_sizing(self, column): self.column_sizings[column] = (self.CHILD,) def set_child_row_sizing(self, row): self.row_sizings[row]",
"+ 1 height = int(self.parent.rect_inner.h * 0.8) - 18 + 1 self.assertEqual(Panel.Rect(13, 19,",
"it is up to the # parent to decide if it should resize.",
"group.append((column, sizing)) column_sizings_by_type[sizing[0]] = group for row in range(self.row_count): sizing = self.row_sizings.get(row, (self.EVEN,))",
"sum(row_heights) # Allocate extra width and height to columns and rows. extra_width =",
"self.assertEqual(20, grid.widest_child_in_column(4)) with self.subTest(\"row\"): grid = create_grid() child = self.gui.create(Panel) child.size = (38,",
"101, 33), child_0_0.rect_outer) self.assertEqual(Panel.Rect(108, 3, 58, 33), child_1_0.rect_outer) self.assertEqual(Panel.Rect( 2, 41, 101, 93),",
"rect, panel in self.panels.items(): x = area.x + sum(column_widths[:rect.x]) + rect.x * self.spacing",
"create_child(Rect(0, 0, 1, 1)) child_1_0 = create_child(Rect(1, 0, 1, 1)) child_0_1 = create_child(Rect(0,",
"child.size = size grid.add_rect(child, rect) return child child_0_0 = create_child(Rect(0, 0, 1, 1),",
"1)) child_1_1 = create_child(Rect(1, 1, 1, 1)) grid.layout(self.parent) self.assertEqual(Panel.Rect( 2, 3, 101, 33),",
"16, 8, 2) child.size = (53, 81) grid.add(child, 0, 0) grid.layout(self.parent) self.assertEqual(Panel.Rect(13, 19,",
"self.assertEqual(0, grid.widest_child_in_column(2)) self.assertEqual(0, grid.tallest_child_in_row(2)) def test_tallest_child_in_column_or_row_2(self): def create_grid(): grid = GridLayout(column_count=5, row_count=5, spacing=3)",
"row_heights, extra_height) def allocate_extra_even(sizings_by_type, sizes, extra): for sizing_tuple in sizings_by_type.get(self.EVEN, []): column_or_row, _",
"column_or_row, sizing = sizing_tuple sizes[column_or_row] = int(sizing[1](area_size, remaining_size)) calculate_custom_sizes(column_sizings_by_type, column_widths, area.w, area.w -",
"with self.subTest(rect_left=rect_left, rect_right=rect_right, empty=empty): grid = GridLayout(column_count=20, row_count=20, spacing=5) grid.add_rect(self.gui.create(Panel), rect_left) self.assertEqual(empty, grid.area_empty(rect_right))",
"- 100 height_1 = 100 self.assertEqual(Panel.Rect(2, 3, width_0, height_0), child_0_0.rect_outer) self.assertEqual(Panel.Rect(2, 8 +",
"self.gui = Gui() self.parent = self.gui.create(Panel) self.parent.size = (200, 300) self.parent.padding = (2,",
"1)) def create_child(rect): child = self.gui.create(Panel) child.parent = self.parent child.padding = (10, 8,",
"None)) height_0 = int(custom_sizing_2(287, None)) + 1 height_1 = int(custom_sizing_1(287, None)) self.assertEqual(Panel.Rect(2, 3,",
"height) class GridLayoutTest(unittest.TestCase): def setUp(self): from desky.gui import Gui self.gui = Gui() self.parent",
"* self.spacing) / rect.w) return reduce(max, map(calculate_width, rect_panel_tuples_that_intersect_column), 0) def tallest_child_in_row(self, row): row_rect",
"grid.column_count): child = gui.create(Panel) child.parent = panel grid.add(child, column, row) grid.layout(panel) def main():",
"the height as a # proportional amount. return int((panel.rect_outer.w - (rect.w - 1)",
"1, 1), (61, 62)) child_1_1 = create_child(Rect(1, 1, 1, 1), (54, 20)) grid.layout(self.parent)",
"= create_child(Rect(1, 1, 1, 1)) grid.layout(self.parent) width_0 = int(189 * 0.333) + 1",
"| Type of sizing | Maximum extra width allocation # -------------------------------------------------------------- # |",
"width_1, height_1), child_1_1.rect_outer) def test_single_fill(self): grid = GridLayout(spacing=5) grid.set_fill_column_sizing(0) grid.set_fill_row_sizing(0) child = self.gui.create(Panel)",
"1 - 0.8139) def create_child(rect): child = self.gui.create(Panel) child.parent = self.parent child.padding =",
"column, size): self.column_sizings[column] = (self.FIXED, size) def set_fixed_row_sizing(self, row, size): self.row_sizings[row] = (self.FIXED,",
"def custom_sizing_1(area_size, remaining_size): return area_size ** 0.8 def custom_sizing_2(area_size, remaining_size): return area_size -",
"GridLayout(spacing=5) grid.set_custom_column_sizing(0, custom_sizing, custom_extra) grid.set_custom_row_sizing(0, custom_sizing, custom_extra) child = self.gui.create(Panel) child.parent = self.parent",
"int(sizing[1](area_size, remaining_size)) calculate_custom_sizes(column_sizings_by_type, column_widths, area.w, area.w - sum(column_widths)) calculate_custom_sizes(row_sizings_by_type, row_heights, area.h, area.h -",
"1)) child_1_1 = create_child(Rect(1, 1, 1, 1)) grid.layout(self.parent) width_0 = int(189 * 0.5)",
"in range(self.row_count): sizing = self.row_sizings.get(row, (self.EVEN,)) group = row_sizings_by_type.get(sizing[0], list()) group.append((row, sizing)) row_sizings_by_type[sizing[0]]",
"child child_0_0 = create_child(Rect(0, 0, 1, 1)) child_0_1 = create_child(Rect(0, 1, 1, 1))",
"GridLayout(column_count=5, row_count=5, spacing=3) for column in range(grid.column_count): grid.set_child_column_sizing(column) for row in range(grid.row_count): grid.set_child_row_sizing(row)",
"= int(292 ** 0.5) final_width = root_width + int((194 - root_width) / 2)",
"= self.gui.create(Panel) child.size = (60, 38) grid.add(child, 2, 1) self.assertEqual(60, grid.widest_child_in_column(2)) with self.subTest(\"column\"):",
"(60, 38) grid.add(child, 2, 1) self.assertEqual(60, grid.widest_child_in_column(2)) with self.subTest(\"column\"): grid = create_grid() child",
"30, 40, 50) def test_tallest_child_in_column_or_row_1(self): grid = GridLayout(column_count=5, row_count=5, spacing=3) for column in",
"self.assertEqual(Panel.Rect( 2, 58, 80, 50), child_0_1.rect_outer) self.assertEqual(Panel.Rect(87, 3, 44, 105), child_1_0.rect_outer) def test_single_percentage(self):",
"column_widths, extra_width) extra_height = allocate_extra_custom(row_sizings_by_type, row_heights, extra_height) def allocate_extra_even(sizings_by_type, sizes, extra): for sizing_tuple",
"3, 101, 18), child_0_0.rect_outer) self.assertEqual(Panel.Rect(108, 3, 19, 18), child_1_0.rect_outer) self.assertEqual(Panel.Rect( 2, 8, 101,",
"test_single_child(self): grid = GridLayout(spacing=5) grid.set_child_column_sizing(0) grid.set_child_row_sizing(0) child = self.gui.create(Panel) child.parent = self.parent child.padding",
"height_1 = int(287 * 0.5) self.assertEqual(Panel.Rect(2, 3, width_0, height_0), child_0_0.rect_outer) self.assertEqual(Panel.Rect(2, 8 +",
"self.column_sizings[column] = (self.CUSTOM, sizing_func, extra_func) def set_custom_row_sizing(self, row, sizing_func, extra_func=zero_func): self.row_sizings[row] = (self.CUSTOM,",
"= self.gui.create(Panel) child.size = (38, 66) grid.add_rect(child, Rect(1, 2, 2, 3)) self.assertEqual(20, grid.tallest_child_in_row(2))",
"grid.layout(self.parent) self.assertEqual(Panel.Rect(13, 19, 175, 274), child.rect) def test_multiple_fill(self): grid = GridLayout(column_count=2, row_count=2, spacing=5)",
"create_child(Rect(0, 0, 1, 1)) child_0_1 = create_child(Rect(0, 1, 1, 1)) child_1_0 = create_child(Rect(1,",
"px) | 0px # | Child (use child size) | 0px # |",
"2, 58, 80, 50), child_0_1.rect_outer) self.assertEqual(Panel.Rect(87, 3, 44, 105), child_1_0.rect_outer) def test_single_percentage(self): grid",
"create_child(Rect(0, 1, 1, 1), (61, 62)) child_1_1 = create_child(Rect(1, 1, 1, 1), (54,",
"child.parent = self.parent child.padding = (10, 8, 6, 4) child.margins = (11, 16,",
"58) grid.set_fixed_row_sizing(0, 33) grid.set_fixed_row_sizing(1, 93) def create_child(rect): child = self.gui.create(Panel) child.parent = self.parent",
"int(sizing[2](extra)) sizes[column_or_row] += amount extra -= amount return extra extra_width = allocate_extra_custom(column_sizings_by_type, column_widths,",
"self.column_count) assert(rect.bottom <= self.row_count) assert(self.area_empty(rect)) self.panels[rect.frozen_copy()] = panel def remove(self, panel): self.panels =",
"int(custom_sizing_2(287, None)) + 1 height_1 = int(custom_sizing_1(287, None)) self.assertEqual(Panel.Rect(2, 3, width_0, height_0), child_0_0.rect_outer)",
"height to columns and rows. extra_width = max(area.w - sum(column_widths), 0) extra_height =",
"= create_grid() child = self.gui.create(Panel) child.size = (60, 38) grid.add(child, 2, 1) self.assertEqual(60,",
"child child_0_0 = create_child(Rect(0, 0, 1, 1), (58, 31)) child_0_1 = create_child(Rect(0, 1,",
"(self.CUSTOM, sizing_func, extra_func) def set_custom_row_sizing(self, row, sizing_func, extra_func=zero_func): self.row_sizings[row] = (self.CUSTOM, sizing_func, extra_func)",
"in self.panels.values(): panel.remove() self.panels = dict() def area_empty(self, rect): for rect_other in self.panels.keys():",
"(53, 81) grid.add(child, 0, 0) grid.layout(self.parent) width = int(self.parent.rect_inner.w * 0.333) - 19",
"child_1_0.rect_outer) self.assertEqual(Panel.Rect(7 + width_0, 8 + height_0, width_1, height_1), child_1_1.rect_outer) def test_single_even(self): #",
"panel): area = (panel.rect_inner .move(-panel.x, -panel.y) .shrink( 0, 0, (self.column_count - 1) *",
"(rect.w - 1) * self.spacing height = sum(row_heights[rect.y:rect.bottom]) + (rect.h - 1) *",
"def tallest_child_in_row(self, row): row_rect = Rect(0, row, self.column_count, 1) rect_panel_tuples_that_intersect_row = list( filter(",
"189 - int(189 * 0.3333) height_0 = 287 - 100 height_1 = 100",
"def custom_extra(extra): return extra / 2 grid = GridLayout(spacing=5) grid.set_custom_column_sizing(0, custom_sizing, custom_extra) grid.set_custom_row_sizing(0,",
"sizing in the table above are ordered in evalulation priority. # Fixed, Child,",
"2, 3, 80, 50), child_0_0.rect_outer) self.assertEqual(Panel.Rect( 2, 58, 80, 50), child_0_1.rect_outer) self.assertEqual(Panel.Rect(87, 3,",
"self.subTest(\"column\"): grid = create_grid() child = self.gui.create(Panel) child.size = (60, 38) grid.add(child, 2,",
"width_0, 8 + height_0, width_1, height_1), child_1_1.rect_outer) def grid_example(gui): panel = gui.create(Panel) panel.rect",
"list( filter( lambda rect_panel_tuple: rect_panel_tuple[0].intersects(column_rect), self.panels.items())) def calculate_width(rect_panel_tuple): rect, panel = rect_panel_tuple #",
"desky.panel import Panel from enum import Enum from functools import reduce, partial from",
"_ = sizing_tuple sizes[column_or_row] = size calculate_even_sizes( column_sizings_by_type, column_widths, area.w - sum(column_widths)) calculate_even_sizes(",
"1)) grid.layout(self.parent) self.assertEqual(Panel.Rect( 2, 3, 101, 18), child_0_0.rect_outer) self.assertEqual(Panel.Rect(108, 3, 19, 18), child_1_0.rect_outer)",
"1, 1), (58, 31)) child_0_1 = create_child(Rect(0, 1, 1, 1), (61, 31)) child_1_0",
"for _ in range(self.column_count)] row_heights = [0 for _ in range(self.row_count)] def calculate_fixed_sizes(sizings_by_type,",
"rect.x * self.spacing y = area.y + sum(row_heights[:rect.y]) + rect.y * self.spacing width",
"(58, 39)) child_1_0 = create_child(Rect(1, 0, 1, 1), (25, 71)) child_0_1 = create_child(Rect(0,",
"width_1 = width_0 height_0 = int(287 * 0.8139) + 1 height_1 = int(287",
"amount. return int((panel.rect_outer.h - (rect.h - 1) * self.spacing) / rect.h) return reduce(max,",
"row heights. column_widths = [0 for _ in range(self.column_count)] row_heights = [0 for",
"set_percentage_column_sizing(self, column, percentage): self.column_sizings[column] = (self.PERCENTAGE, percentage) def set_percentage_row_sizing(self, row, percentage): self.row_sizings[row] =",
"a panel spans multiple columns, determine the height as a # proportional amount.",
"grid.set_child_row_sizing(0) child = self.gui.create(Panel) child.parent = self.parent child.padding = (10, 8, 6, 4)",
"remove_panels): if remove_panels: for panel in self.panels.values(): panel.remove() self.panels = dict() def area_empty(self,",
"height_0, width_1, height_1), child_1_1.rect_outer) def test_single_even(self): # Since even sizing is the default",
"test_single_even(self): # Since even sizing is the default we should make sure it",
"Fixed, Child, and Percentage sizings are evaluated first. Custom is then # evaluated",
"= sizing[1] calculate_fixed_sizes(column_sizings_by_type, column_widths) calculate_fixed_sizes(row_sizings_by_type, row_heights) def calculate_child_sizes(sizings_by_type, sizes, largest_func): for sizing_tuple in",
"root_width + int((194 - root_width) / 2) - 19 final_height = root_height +",
"child.size = (66, 38) grid.add_rect(child, Rect(2, 1, 3, 2)) self.assertEqual(20, grid.widest_child_in_column(2)) self.assertEqual(20, grid.widest_child_in_column(3))",
"area.w) calculate_percentage_sizes(row_sizings_by_type, row_heights, area.h) def calculate_custom_sizes(sizings_by_type, sizes, area_size, remaining_size): for sizing_tuple in sizings_by_type.get(self.CUSTOM,",
"(self.EVEN,) def set_even_row_sizing(self, row): self.row_sizings[row] = (self.EVEN,) def set_fill_column_sizing(self, column): self.column_sizings[column] = (self.FILL,)",
"fill_columns = column_sizings_by_type.get(self.FILL, []) if fill_columns: column_widths[fill_columns[0][0]] = area.w - sum(column_widths) fill_rows =",
".shrink( 0, 0, (self.column_count - 1) * self.spacing, (self.row_count - 1) * self.spacing)",
"if rect.intersects(rect_other): return False return True def set_fixed_column_sizing(self, column, size): self.column_sizings[column] = (self.FIXED,",
"and will take the remaining space. # # If the resulting layout exceeds",
"= create_child(Rect(0, 1, 1, 1), (61, 62)) child_1_1 = create_child(Rect(1, 1, 1, 1),",
"create_child(rect): child = self.gui.create(Panel) child.parent = self.parent child.padding = (10, 8, 6, 4)",
"for column in range(grid.column_count): grid.set_child_column_sizing(column) for row in range(grid.row_count): grid.set_child_row_sizing(row) return grid with",
"height = int(self.parent.rect_inner.h * 0.8) - 18 + 1 self.assertEqual(Panel.Rect(13, 19, width, height),",
"1)) child_1_1 = create_child(Rect(1, 1, 1, 1)) grid.layout(self.parent) width_0 = int(189 * 0.333)",
"test_single_custom(self): def custom_sizing(area_size, remaining_size): return area_size ** 0.5 def custom_extra(extra): return extra /",
"sum(column_widths)) calculate_even_sizes( row_sizings_by_type, row_heights, area.h - sum(row_heights)) fill_columns = column_sizings_by_type.get(self.FILL, []) if fill_columns:",
"= GridLayout(spacing=5) grid.set_fill_column_sizing(0) grid.set_fill_row_sizing(0) child = self.gui.create(Panel) child.parent = self.parent child.padding = (10,",
"p != panel, self.panels) def clear(self, *, remove_panels): if remove_panels: for panel in",
"= GridLayout(column_count=5, row_count=5, spacing=3) for column in range(grid.column_count): grid.set_child_column_sizing(column) for row in range(grid.row_count):",
"sizing_tuple amount = int(sizing[2](extra)) sizes[column_or_row] += amount extra -= amount return extra extra_width",
"38) grid.add(child, 2, 1) self.assertEqual(60, grid.widest_child_in_column(2)) with self.subTest(\"column\"): grid = create_grid() child =",
"as its argument. Even is # evaluated next. Even panels will split remaining",
"grid = GridLayout(spacing=5) if not default: grid.set_even_column_sizing(0) grid.set_even_row_sizing(0) child = self.gui.create(Panel) child.parent =",
"spacing=3) for column in range(grid.column_count): grid.set_child_column_sizing(column) for row in range(grid.row_count): grid.set_child_row_sizing(row) return grid",
"* 0.5) height_0 = int(287 * 0.5) + 1 height_1 = int(287 *",
"41, 101, 93), child_0_1.rect_outer) self.assertEqual(Panel.Rect(108, 41, 58, 93), child_1_1.rect_outer) def test_multiple_fixed_2(self): grid =",
"58, 80, 50), child_0_1.rect_outer) self.assertEqual(Panel.Rect(87, 3, 44, 105), child_1_0.rect_outer) def test_single_percentage(self): grid =",
"def test_multiple_even(self): grid = GridLayout(column_count=2, row_count=2, spacing=5) grid.set_even_column_sizing(0) grid.set_even_column_sizing(1) grid.set_even_row_sizing(0) grid.set_even_row_sizing(1) def create_child(rect):",
"sum(row_heights)) def calculate_even_sizes(sizings_by_type, sizes, remaining_size): size = int(remaining_size / len(sizings_by_type.get(self.EVEN, [1]))) for sizing_tuple",
"sizings_by_type.get(self.FIXED, []): column_or_row, sizing = sizing_tuple sizes[column_or_row] = sizing[1] calculate_fixed_sizes(column_sizings_by_type, column_widths) calculate_fixed_sizes(row_sizings_by_type, row_heights)",
"0, 1, 1)) child_0_1 = create_child(Rect(0, 1, 1, 1)) child_1_0 = create_child(Rect(1, 0,",
"19, 93), child_1_1.rect_outer) def test_single_child(self): grid = GridLayout(spacing=5) grid.set_child_column_sizing(0) grid.set_child_row_sizing(0) child = self.gui.create(Panel)",
"int(custom_sizing_1(189, None)) + 1 width_1 = int(custom_sizing_2(189, None)) height_0 = int(custom_sizing_2(287, None)) +",
"sizing = sizing_tuple amount = int(sizing[2](extra)) sizes[column_or_row] += amount extra -= amount return",
"child_0_1.rect_outer) self.assertEqual(Panel.Rect(108, 8, 19, 93), child_1_1.rect_outer) def test_single_child(self): grid = GridLayout(spacing=5) grid.set_child_column_sizing(0) grid.set_child_row_sizing(0)",
"spacing=5) grid.set_fixed_column_sizing(0, 101) grid.set_fixed_column_sizing(1, 0) grid.set_fixed_row_sizing(0, 0) grid.set_fixed_row_sizing(1, 93) def create_child(rect): child =",
"(11, 16, 8, 2) child.size = size grid.add_rect(child, rect) return child child_0_0 =",
"1, 1)) child_0_1 = create_child(Rect(0, 1, 1, 1)) child_1_0 = create_child(Rect(1, 0, 1,",
"int(remaining_size / len(sizings_by_type.get(self.EVEN, [1]))) for sizing_tuple in sizings_by_type.get(self.EVEN, []): column_or_row, _ = sizing_tuple",
"types of sizing in the table above are ordered in evalulation priority. #",
"test_single_fixed(self): grid = GridLayout(spacing=5) grid.set_fixed_column_sizing(0, 90) grid.set_fixed_row_sizing(0, 120) child = self.gui.create(Panel) child.parent =",
"= (200, 300) self.parent.padding = (2, 3, 4, 5) self.parent.margins = (20, 30,",
"1, 9, 9), False), (Rect(10, 2, 4, 4), Rect(1, 1, 9, 9), True),",
"height_0), child_1_0.rect_outer) self.assertEqual(Panel.Rect(7 + width_0, 8 + height_0, width_1, height_1), child_1_1.rect_outer) def test_single_fill(self):",
"= (self.EVEN,) def set_fill_column_sizing(self, column): self.column_sizings[column] = (self.FILL,) def set_fill_row_sizing(self, row): self.row_sizings[row] =",
"1) * self.spacing height = sum(row_heights[rect.y:rect.bottom]) + (rect.h - 1) * self.spacing panel.rect_outer",
"GridLayout(column_count=2, row_count=2, spacing=5) grid.set_child_column_sizing(0) grid.set_child_column_sizing(1) grid.set_child_row_sizing(0) grid.set_child_row_sizing(1) def create_child(rect, size): child = self.gui.create(Panel)",
"test_tallest_child_in_column_or_row_3(self): def create_grid(): grid = GridLayout(column_count=5, row_count=5, spacing=3) for column in range(grid.column_count): grid.set_child_column_sizing(column)",
"+ width_0, 8 + height_0, width_1, height_1), child_1_1.rect_outer) def test_single_even(self): # Since even",
"5) self.parent.margins = (20, 30, 40, 50) def test_tallest_child_in_column_or_row_1(self): grid = GridLayout(column_count=5, row_count=5,",
"extra_height = allocate_extra_even(row_sizings_by_type, row_heights, extra_height) # Save column widths and row heights for",
"return extra / 2 grid = GridLayout(spacing=5) grid.set_custom_column_sizing(0, custom_sizing, custom_extra) grid.set_custom_row_sizing(0, custom_sizing, custom_extra)",
"test_single_percentage(self): grid = GridLayout(spacing=5) grid.set_percentage_column_sizing(0, 0.333) grid.set_percentage_row_sizing(0, 0.8) child = self.gui.create(Panel) child.parent =",
"0, 1, self.row_count) rect_panel_tuples_that_intersect_column = list( filter( lambda rect_panel_tuple: rect_panel_tuple[0].intersects(column_rect), self.panels.items())) def calculate_width(rect_panel_tuple):",
"assert(rect.x >= 0) assert(rect.y >= 0) assert(rect.right <= self.column_count) assert(rect.bottom <= self.row_count) assert(self.area_empty(rect))",
"in range(0, grid.row_count): for column in range(0, grid.column_count): child = gui.create(Panel) child.parent =",
"2) - 18 self.assertEqual(Panel.Rect(13, 19, final_width, final_height), child.rect) def test_multiple_custom(self): def custom_sizing_1(area_size, remaining_size):",
"self.row_heights = row_heights # Position child panels. for rect, panel in self.panels.items(): x",
"grid = GridLayout(column_count=2, row_count=2, spacing=5) grid.set_percentage_column_sizing(0, 0.3333) grid.set_fill_column_sizing(1) grid.set_fill_row_sizing(0) grid.set_fixed_row_sizing(1, 100) def create_child(rect):",
"sizes[column_or_row] = largest_func(column_or_row) calculate_child_sizes(column_sizings_by_type, column_widths, self.widest_child_in_column) calculate_child_sizes(row_sizings_by_type, row_heights, self.tallest_child_in_row) def calculate_percentage_sizes(sizings_by_type, sizes, area_size):",
"rect) return child child_0_0 = create_child(Rect(0, 0, 1, 1), (58, 31)) child_0_1 =",
"child_1_0.rect_outer) self.assertEqual(Panel.Rect(7 + width_0, 8 + height_0, width_1, height_1), child_1_1.rect_outer) def test_single_custom(self): def",
"Rect(1, 1, 9, 9), False), (Rect(10, 2, 4, 4), Rect(1, 1, 9, 9),",
"= int(189 * 0.333) + 1 width_1 = width_0 height_0 = int(287 *",
"sizing_tuple in sizings_by_type.get(self.FIXED, []): column_or_row, sizing = sizing_tuple sizes[column_or_row] = sizing[1] calculate_fixed_sizes(column_sizings_by_type, column_widths)",
"rows to even sizing. for default in (True, False): with self.subTest(default=default): grid =",
"| Fixed (200 px) | 0px # | Child (use child size) |",
"= group for row in range(self.row_count): sizing = self.row_sizings.get(row, (self.EVEN,)) group = row_sizings_by_type.get(sizing[0],",
"101, 93), child_0_1.rect_outer) self.assertEqual(Panel.Rect(108, 41, 58, 93), child_1_1.rect_outer) def test_multiple_fixed_2(self): grid = GridLayout(column_count=2,",
"map(calculate_height, rect_panel_tuples_that_intersect_row), 0) def layout(self, panel): area = (panel.rect_inner .move(-panel.x, -panel.y) .shrink( 0,",
"4, 4), Rect(1, 1, 9, 9), True), ] for rect_left, rect_right, empty in",
"column_sizings_by_type.get(self.FILL, []) if fill_columns: column_widths[fill_columns[0][0]] = area.w - sum(column_widths) fill_rows = row_sizings_by_type.get(self.FILL, [])",
"width and height to columns and rows. extra_width = max(area.w - sum(column_widths), 0)",
"return 0 class GridLayout: FIXED = 0 CHILD = 1 PERCENTAGE = 2",
"= sizing_tuple sizes[column_or_row] = int(sizing[1](area_size, remaining_size)) calculate_custom_sizes(column_sizings_by_type, column_widths, area.w, area.w - sum(column_widths)) calculate_custom_sizes(row_sizings_by_type,",
"(66, 38) grid.add_rect(child, Rect(2, 1, 3, 2)) self.assertEqual(20, grid.widest_child_in_column(2)) self.assertEqual(20, grid.widest_child_in_column(3)) self.assertEqual(20, grid.widest_child_in_column(4))",
"CHILD = 1 PERCENTAGE = 2 CUSTOM = 3 EVEN = 4 FILL",
"column_count = 1, row_count = 1, spacing = 0): self.panels = dict() self.column_sizings",
"grid.row_count): for column in range(0, grid.column_count): child = gui.create(Panel) child.parent = panel grid.add(child,",
"(50, 50, 500, 500) panel.padding = (8, 16, 24, 32) grid = GridLayout(column_count",
"int(custom_sizing_2(189, None)) height_0 = int(custom_sizing_2(287, None)) + 1 height_1 = int(custom_sizing_1(287, None)) self.assertEqual(Panel.Rect(2,",
"height_0 = int(custom_sizing_2(287, None)) + 1 height_1 = int(custom_sizing_1(287, None)) self.assertEqual(Panel.Rect(2, 3, width_0,",
"set_custom_row_sizing(self, row, sizing_func, extra_func=zero_func): self.row_sizings[row] = (self.CUSTOM, sizing_func, extra_func) def set_even_column_sizing(self, column): self.column_sizings[column]",
"for sizing_tuple in sizings_by_type.get(self.FIXED, []): column_or_row, sizing = sizing_tuple sizes[column_or_row] = sizing[1] calculate_fixed_sizes(column_sizings_by_type,",
"def add(self, panel, column, row, column_count=1, row_count=1): self.add_rect(panel, Rect(column, row, column_count, row_count)) def",
"self.column_sizings[column] = (self.EVEN,) def set_even_row_sizing(self, row): self.row_sizings[row] = (self.EVEN,) def set_fill_column_sizing(self, column): self.column_sizings[column]",
"width_0 = int(189 * 0.333) + 1 width_1 = width_0 height_0 = int(287",
"panel.padding = (8, 16, 24, 32) grid = GridLayout(column_count = 3, row_count =",
"grid.layout(self.parent) width_0 = int(189 * 0.5) + 1 width_1 = int(189 * 0.5)",
"= max(area.w - sum(column_widths), 0) extra_height = max(area.h - sum(row_heights), 0) def allocate_extra_percentage(sizings_by_type,",
"a # proportional amount. return int((panel.rect_outer.w - (rect.w - 1) * self.spacing) /",
"in sizings_by_type.get(self.CUSTOM, []): column_or_row, sizing = sizing_tuple sizes[column_or_row] = int(sizing[1](area_size, remaining_size)) calculate_custom_sizes(column_sizings_by_type, column_widths,",
"def test_single_custom(self): def custom_sizing(area_size, remaining_size): return area_size ** 0.5 def custom_extra(extra): return extra",
"allocate_extra_even(column_sizings_by_type, column_widths, extra_width) extra_height = allocate_extra_even(row_sizings_by_type, row_heights, extra_height) # Save column widths and",
"def test_tallest_child_in_column_or_row_3(self): def create_grid(): grid = GridLayout(column_count=5, row_count=5, spacing=3) for column in range(grid.column_count):",
"child_0_0.rect_outer) self.assertEqual(Panel.Rect( 2, 58, 80, 50), child_0_1.rect_outer) self.assertEqual(Panel.Rect(87, 3, 44, 105), child_1_0.rect_outer) def",
"size as its argument. Even is # evaluated next. Even panels will split",
"test_tallest_child_in_column_or_row_2(self): def create_grid(): grid = GridLayout(column_count=5, row_count=5, spacing=3) for column in range(grid.column_count): grid.set_child_column_sizing(column)",
"grid.set_percentage_column_sizing(0, 0.3333) grid.set_fill_column_sizing(1) grid.set_fill_row_sizing(0) grid.set_fixed_row_sizing(1, 100) def create_child(rect): child = self.gui.create(Panel) child.parent =",
"width, height), child.rect) def test_multiple_percentage(self): grid = GridLayout(column_count=2, row_count=2, spacing=5) grid.set_percentage_column_sizing(0, 0.333) grid.set_percentage_column_sizing(1,",
"int(287 * 0.5) self.assertEqual(Panel.Rect(2, 3, width_0, height_0), child_0_0.rect_outer) self.assertEqual(Panel.Rect(2, 8 + height_0, width_0,",
"sizings_by_type.get(self.CUSTOM, []): column_or_row, sizing = sizing_tuple amount = int(sizing[2](extra)) sizes[column_or_row] += amount extra",
"partial(min, 1)) grid.set_custom_column_sizing(1, custom_sizing_2, partial(min, 1)) grid.set_custom_row_sizing(0, custom_sizing_2, partial(min, 1)) grid.set_custom_row_sizing(1, custom_sizing_1, partial(min,",
"sizes, remaining_size): size = int(remaining_size / len(sizings_by_type.get(self.EVEN, [1]))) for sizing_tuple in sizings_by_type.get(self.EVEN, []):",
"area.h - sum(row_heights)) fill_columns = column_sizings_by_type.get(self.FILL, []) if fill_columns: column_widths[fill_columns[0][0]] = area.w -",
"valfilter(lambda p: p != panel, self.panels) def clear(self, *, remove_panels): if remove_panels: for",
"rect) return child child_0_0 = create_child(Rect(0, 0, 1, 1), (58, 39)) child_1_0 =",
"is given the remaining area size as its argument. Even is # evaluated",
"0, 0) grid.layout(self.parent) width = int(self.parent.rect_inner.w * 0.333) - 19 + 1 height",
"The types of sizing in the table above are ordered in evalulation priority.",
"custom_extra(extra): return extra / 2 grid = GridLayout(spacing=5) grid.set_custom_column_sizing(0, custom_sizing, custom_extra) grid.set_custom_row_sizing(0, custom_sizing,",
"(1 - 0.8139)) self.assertEqual(Panel.Rect(2, 3, width_0, height_0), child_0_0.rect_outer) self.assertEqual(Panel.Rect(2, 8 + height_0, width_0,",
"1 height_1 = int(287 * (1 - 0.8139)) self.assertEqual(Panel.Rect(2, 3, width_0, height_0), child_0_0.rect_outer)",
"sizes[column_or_row] += amount extra -= amount return extra extra_width = allocate_extra_even(column_sizings_by_type, column_widths, extra_width)",
"1, 1)) child_0_1 = create_child(Rect(0, 1, 1, 1)) child_1_1 = create_child(Rect(1, 1, 1,",
"0) assert(rect.right <= self.column_count) assert(rect.bottom <= self.row_count) assert(self.area_empty(rect)) self.panels[rect.frozen_copy()] = panel def remove(self,",
"root_width = int(194 ** 0.5) root_height = int(292 ** 0.5) final_width = root_width",
"int(189 * 0.3333) width_1 = 189 - int(189 * 0.3333) height_0 = 287",
"unittest from desky.rect import Rect from desky.panel import Panel from enum import Enum",
"self.assertEqual(Panel.Rect( 2, 3, 101, 33), child_0_0.rect_outer) self.assertEqual(Panel.Rect(108, 3, 58, 33), child_1_0.rect_outer) self.assertEqual(Panel.Rect( 2,",
"self.widest_child_in_column) calculate_child_sizes(row_sizings_by_type, row_heights, self.tallest_child_in_row) def calculate_percentage_sizes(sizings_by_type, sizes, area_size): for sizing_tuple in sizings_by_type.get(self.PERCENTAGE, []):",
"amount extra -= amount return extra extra_width = allocate_extra_even(column_sizings_by_type, column_widths, extra_width) extra_height =",
"should make sure it works even # when we don't excplicitly set the",
"sizings_by_type.get(self.EVEN, []): column_or_row, _ = sizing_tuple sizes[column_or_row] = size calculate_even_sizes( column_sizings_by_type, column_widths, area.w",
"is the default we should make sure it works even # when we",
"self.assertEqual(Panel.Rect(7 + width_0, 3, width_1, height_0), child_1_0.rect_outer) self.assertEqual(Panel.Rect(7 + width_0, 8 + height_0,",
"if it should resize. def zero_func(): return 0 class GridLayout: FIXED = 0",
"rows by their sizing types while preserving the order. for column in range(self.column_count):",
"remaining_size): size = int(remaining_size / len(sizings_by_type.get(self.EVEN, [1]))) for sizing_tuple in sizings_by_type.get(self.EVEN, []): column_or_row,",
"sizing = self.row_sizings.get(row, (self.EVEN,)) group = row_sizings_by_type.get(sizing[0], list()) group.append((row, sizing)) row_sizings_by_type[sizing[0]] = group",
"sizing_tuple sizes[column_or_row] = sizing[1] calculate_fixed_sizes(column_sizings_by_type, column_widths) calculate_fixed_sizes(row_sizings_by_type, row_heights) def calculate_child_sizes(sizings_by_type, sizes, largest_func): for",
"column_sizings_by_type, column_widths, area.w - sum(column_widths)) calculate_even_sizes( row_sizings_by_type, row_heights, area.h - sum(row_heights)) fill_columns =",
"= (53, 81) grid.add(child, 0, 0) grid.layout(self.parent) self.assertEqual(Panel.Rect(13, 19, 71, 102), child.rect) def",
"(53, 81) grid.add(child, 0, 0) grid.layout(self.parent) self.assertEqual(Panel.Rect(13, 19, 71, 102), child.rect) def test_multiple_fixed_1(self):",
"50, 500, 500) panel.padding = (8, 16, 24, 32) grid = GridLayout(column_count =",
"def set_fixed_row_sizing(self, row, size): self.row_sizings[row] = (self.FIXED, size) def set_child_column_sizing(self, column): self.column_sizings[column] =",
"create_grid() child = self.gui.create(Panel) child.size = (60, 38) grid.add(child, 2, 1) self.assertEqual(60, grid.widest_child_in_column(2))",
"= GridLayout(spacing=5) if not default: grid.set_even_column_sizing(0) grid.set_even_row_sizing(0) child = self.gui.create(Panel) child.parent = self.parent",
"= 1 PERCENTAGE = 2 CUSTOM = 3 EVEN = 4 FILL =",
"= GridLayout(spacing=5) grid.set_child_column_sizing(0) grid.set_child_row_sizing(0) child = self.gui.create(Panel) child.parent = self.parent child.padding = (10,",
"for row in range(self.row_count): sizing = self.row_sizings.get(row, (self.EVEN,)) group = row_sizings_by_type.get(sizing[0], list()) group.append((row,",
"GridLayout(spacing=5) grid.set_fixed_column_sizing(0, 90) grid.set_fixed_row_sizing(0, 120) child = self.gui.create(Panel) child.parent = self.parent child.padding =",
"Rect from desky.panel import Panel from enum import Enum from functools import reduce,",
"extra): for sizing_tuple in sizings_by_type.get(self.PERCENTAGE, []): column_or_row, _ = sizing_tuple amount = min(extra,",
"calculate_custom_sizes(column_sizings_by_type, column_widths, area.w, area.w - sum(column_widths)) calculate_custom_sizes(row_sizings_by_type, row_heights, area.h, area.h - sum(row_heights)) def",
"custom_sizing(area_size, remaining_size): return area_size ** 0.5 def custom_extra(extra): return extra / 2 grid",
"width allocation # -------------------------------------------------------------- # | Fixed (200 px) | 0px # |",
"for sizing_tuple in sizings_by_type.get(self.PERCENTAGE, []): column_or_row, sizing = sizing_tuple sizes[column_or_row] = int(area_size *",
"| 1px # | Fill (use remaining space) | any # # The",
"area.h, area.h - sum(row_heights)) def calculate_even_sizes(sizings_by_type, sizes, remaining_size): size = int(remaining_size / len(sizings_by_type.get(self.EVEN,",
"def layout(self, panel): area = (panel.rect_inner .move(-panel.x, -panel.y) .shrink( 0, 0, (self.column_count -",
"= create_child(Rect(0, 0, 1, 1)) child_0_1 = create_child(Rect(0, 1, 1, 1)) child_1_0 =",
"self.assertEqual(Panel.Rect(7 + width_0, 8 + height_0, width_1, height_1), child_1_1.rect_outer) def test_single_fill(self): grid =",
"= 0 CHILD = 1 PERCENTAGE = 2 CUSTOM = 3 EVEN =",
"93), child_1_1.rect_outer) def test_single_child(self): grid = GridLayout(spacing=5) grid.set_child_column_sizing(0) grid.set_child_row_sizing(0) child = self.gui.create(Panel) child.parent",
"2) child.size = (53, 81) grid.add(child, 0, 0) grid.layout(self.parent) root_width = int(194 **",
"+ sum(row_heights[:rect.y]) + rect.y * self.spacing width = sum(column_widths[rect.x:rect.right]) + (rect.w - 1)",
"for panel in self.panels.values(): panel.remove() self.panels = dict() def area_empty(self, rect): for rect_other",
"self.gui.create(Panel) child.size = (38, 60) grid.add(child, 1, 2) self.assertEqual(60, grid.tallest_child_in_row(2)) def test_tallest_child_in_column_or_row_3(self): def",
"calculate_fixed_sizes(column_sizings_by_type, column_widths) calculate_fixed_sizes(row_sizings_by_type, row_heights) def calculate_child_sizes(sizings_by_type, sizes, largest_func): for sizing_tuple in sizings_by_type.get(self.CHILD, []):",
"31)) child_1_0 = create_child(Rect(1, 0, 1, 2), (25, 87)) grid.layout(self.parent) self.assertEqual(Panel.Rect( 2, 3,",
"50) def test_tallest_child_in_column_or_row_1(self): grid = GridLayout(column_count=5, row_count=5, spacing=3) for column in range(grid.column_count): grid.set_child_column_sizing(column)",
"2, 97, 80, 80), child_0_1.rect_outer) self.assertEqual(Panel.Rect(87, 97, 73, 80), child_1_1.rect_outer) def test_multiple_child_2(self): grid",
"sizings_by_type.get(self.PERCENTAGE, []): column_or_row, sizing = sizing_tuple sizes[column_or_row] = int(area_size * sizing[1]) calculate_percentage_sizes(column_sizings_by_type, column_widths,",
"* 0.333) - 19 + 1 height = int(self.parent.rect_inner.h * 0.8) - 18",
"* 0.333) + 1 width_1 = width_0 height_0 = int(287 * 0.8139) +",
"child.rect) def test_multiple_custom(self): def custom_sizing_1(area_size, remaining_size): return area_size ** 0.8 def custom_sizing_2(area_size, remaining_size):",
"allocate_extra_even(row_sizings_by_type, row_heights, extra_height) # Save column widths and row heights for users to",
"size): self.row_sizings[row] = (self.FIXED, size) def set_child_column_sizing(self, column): self.column_sizings[column] = (self.CHILD,) def set_child_row_sizing(self,",
"[]): column_or_row, sizing = sizing_tuple sizes[column_or_row] = sizing[1] calculate_fixed_sizes(column_sizings_by_type, column_widths) calculate_fixed_sizes(row_sizings_by_type, row_heights) def",
"range(0, grid.row_count): for column in range(0, grid.column_count): child = gui.create(Panel) child.parent = panel",
"child_0_1.rect_outer) self.assertEqual(Panel.Rect(87, 97, 73, 80), child_1_1.rect_outer) def test_multiple_child_2(self): grid = GridLayout(column_count=2, row_count=2, spacing=5)",
"in self.panels.items(): x = area.x + sum(column_widths[:rect.x]) + rect.x * self.spacing y =",
"area.h - sum(row_heights)) def calculate_even_sizes(sizings_by_type, sizes, remaining_size): size = int(remaining_size / len(sizings_by_type.get(self.EVEN, [1])))",
"* (1 - 0.8139)) self.assertEqual(Panel.Rect(2, 3, width_0, height_0), child_0_0.rect_outer) self.assertEqual(Panel.Rect(2, 8 + height_0,",
"grid = GridLayout(column_count=2, row_count=2, spacing=5) grid.set_even_column_sizing(0) grid.set_even_column_sizing(1) grid.set_even_row_sizing(0) grid.set_even_row_sizing(1) def create_child(rect): child =",
"and rows by their sizing types while preserving the order. for column in",
"= create_grid() child = self.gui.create(Panel) child.size = (38, 66) grid.add_rect(child, Rect(1, 2, 2,",
"# | Percentage (30% of width) | 1px # | Custom (custom function)",
"return child child_0_0 = create_child(Rect(0, 0, 1, 1)) child_1_0 = create_child(Rect(1, 0, 1,",
"self.assertEqual(Panel.Rect(2, 3, width_0, height_0), child_0_0.rect_outer) self.assertEqual(Panel.Rect(2, 8 + height_0, width_0, height_1), child_0_1.rect_outer) self.assertEqual(Panel.Rect(7",
"self.assertEqual(Panel.Rect(13, 19, 175, 274), child.rect) def test_multiple_fill(self): grid = GridLayout(column_count=2, row_count=2, spacing=5) grid.set_percentage_column_sizing(0,",
"grid.layout(self.parent) root_width = int(194 ** 0.5) root_height = int(292 ** 0.5) final_width =",
"width_0 height_0 = int(287 * 0.8139) + 1 height_1 = int(287 * (1",
"9999) grid.add_rect(child, rect) return child child_0_0 = create_child(Rect(0, 0, 1, 1)) child_0_1 =",
"GridLayout(column_count=2, row_count=2, spacing=5) grid.set_custom_column_sizing(0, custom_sizing_1, partial(min, 1)) grid.set_custom_column_sizing(1, custom_sizing_2, partial(min, 1)) grid.set_custom_row_sizing(0, custom_sizing_2,",
"= GridLayout(column_count=2, row_count=2, spacing=5) grid.set_even_column_sizing(0) grid.set_even_column_sizing(1) grid.set_even_row_sizing(0) grid.set_even_row_sizing(1) def create_child(rect): child = self.gui.create(Panel)",
"-------------------------------------------------------------- # | Fixed (200 px) | 0px # | Child (use child",
"(54, 20)) grid.layout(self.parent) self.assertEqual(Panel.Rect( 2, 3, 80, 89), child_0_0.rect_outer) self.assertEqual(Panel.Rect(87, 3, 73, 89),",
"set the columns and rows to even sizing. for default in (True, False):",
"3, 4, 5) self.parent.margins = (20, 30, 40, 50) def test_tallest_child_in_column_or_row_1(self): grid =",
"sizing_tuple in sizings_by_type.get(self.CHILD, []): column_or_row, _ = sizing_tuple sizes[column_or_row] = largest_func(column_or_row) calculate_child_sizes(column_sizings_by_type, column_widths,",
"= create_child(Rect(1, 1, 1, 1), (54, 20)) grid.layout(self.parent) self.assertEqual(Panel.Rect( 2, 3, 80, 89),",
"= self.row_sizings.get(row, (self.EVEN,)) group = row_sizings_by_type.get(sizing[0], list()) group.append((row, sizing)) row_sizings_by_type[sizing[0]] = group #",
"grid.set_fixed_column_sizing(1, 58) grid.set_fixed_row_sizing(0, 33) grid.set_fixed_row_sizing(1, 93) def create_child(rect): child = self.gui.create(Panel) child.parent =",
"0) grid.layout(self.parent) self.assertEqual(Panel.Rect(13, 19, 71, 102), child.rect) def test_multiple_fixed_1(self): grid = GridLayout(column_count=2, row_count=2,",
"dict() self.row_sizings = dict() self.column_count = column_count self.row_count = row_count self.spacing = spacing",
"= area.x + sum(column_widths[:rect.x]) + rect.x * self.spacing y = area.y + sum(row_heights[:rect.y])",
"grid = create_grid() child = self.gui.create(Panel) child.size = (66, 38) grid.add_rect(child, Rect(2, 1,",
"row_heights, area.h, area.h - sum(row_heights)) def calculate_even_sizes(sizings_by_type, sizes, remaining_size): size = int(remaining_size /",
"1, 1)) grid.layout(self.parent) width_0 = int(189 * 0.3333) width_1 = 189 - int(189",
"are ordered in evalulation priority. # Fixed, Child, and Percentage sizings are evaluated",
"53, 81), child.rect) def test_multiple_child_1(self): grid = GridLayout(column_count=2, row_count=2, spacing=5) grid.set_child_column_sizing(0) grid.set_child_column_sizing(1) grid.set_child_row_sizing(0)",
"size) | 0px # | Percentage (30% of width) | 1px # |",
"size grid.add_rect(child, rect) return child child_0_0 = create_child(Rect(0, 0, 1, 1), (58, 31))",
"in range(grid.row_count): grid.set_child_row_sizing(row) return grid with self.subTest(\"column\"): grid = create_grid() child = self.gui.create(Panel)",
"= (self.CHILD,) def set_percentage_column_sizing(self, column, percentage): self.column_sizings[column] = (self.PERCENTAGE, percentage) def set_percentage_row_sizing(self, row,",
"panel = rect_panel_tuple # In case a panel spans multiple rows, determine the",
"def calculate_even_sizes(sizings_by_type, sizes, remaining_size): size = int(remaining_size / len(sizings_by_type.get(self.EVEN, [1]))) for sizing_tuple in",
"- sum(column_widths) fill_rows = row_sizings_by_type.get(self.FILL, []) if fill_rows: row_heights[fill_rows[0][0]] = area.h - sum(row_heights)",
"= allocate_extra_percentage(row_sizings_by_type, row_heights, extra_height) def allocate_extra_custom(sizings_by_type, sizes, extra): for sizing_tuple in sizings_by_type.get(self.CUSTOM, []):",
"def test_single_even(self): # Since even sizing is the default we should make sure",
"self.row_sizings[row] = (self.PERCENTAGE, percentage) def set_custom_column_sizing(self, column, sizing_func, extra_func=zero_func): self.column_sizings[column] = (self.CUSTOM, sizing_func,",
"= area.y + sum(row_heights[:rect.y]) + rect.y * self.spacing width = sum(column_widths[rect.x:rect.right]) + (rect.w",
"the bounds of the parent, it is up to the # parent to",
"= (11, 16, 8, 2) child.size = (53, 81) grid.add(child, 0, 0) grid.layout(self.parent)",
"spans multiple columns, determine the height as a # proportional amount. return int((panel.rect_outer.w",
"range(grid.column_count): grid.set_child_column_sizing(column) for row in range(grid.row_count): grid.set_child_row_sizing(row) return grid with self.subTest(\"column\"): grid =",
"self.assertEqual(Panel.Rect(108, 3, 19, 18), child_1_0.rect_outer) self.assertEqual(Panel.Rect( 2, 8, 101, 93), child_0_1.rect_outer) self.assertEqual(Panel.Rect(108, 8,",
"the # parent to decide if it should resize. def zero_func(): return 0",
"= Rect(column, 0, 1, self.row_count) rect_panel_tuples_that_intersect_column = list( filter( lambda rect_panel_tuple: rect_panel_tuple[0].intersects(column_rect), self.panels.items()))",
"child_1_0.rect_outer) def test_single_percentage(self): grid = GridLayout(spacing=5) grid.set_percentage_column_sizing(0, 0.333) grid.set_percentage_row_sizing(0, 0.8) child = self.gui.create(Panel)",
"grid.add_rect(self.gui.create(Panel), rect_left) self.assertEqual(empty, grid.area_empty(rect_right)) def test_single_fixed(self): grid = GridLayout(spacing=5) grid.set_fixed_column_sizing(0, 90) grid.set_fixed_row_sizing(0, 120)",
"self.tallest_child_in_row) def calculate_percentage_sizes(sizings_by_type, sizes, area_size): for sizing_tuple in sizings_by_type.get(self.PERCENTAGE, []): column_or_row, sizing =",
"8, 6, 4) child.margins = (11, 16, 8, 2) child.size = size grid.add_rect(child,",
"81) grid.add(child, 0, 0) grid.layout(self.parent) root_width = int(194 ** 0.5) root_height = int(292",
"grid = GridLayout(spacing=5) grid.set_custom_column_sizing(0, custom_sizing, custom_extra) grid.set_custom_row_sizing(0, custom_sizing, custom_extra) child = self.gui.create(Panel) child.parent",
"row_count=2, spacing=5) grid.set_fixed_column_sizing(0, 101) grid.set_fixed_column_sizing(1, 0) grid.set_fixed_row_sizing(0, 0) grid.set_fixed_row_sizing(1, 93) def create_child(rect): child",
"[]): column_or_row, _ = sizing_tuple sizes[column_or_row] = largest_func(column_or_row) calculate_child_sizes(column_sizings_by_type, column_widths, self.widest_child_in_column) calculate_child_sizes(row_sizings_by_type, row_heights,",
"group = row_sizings_by_type.get(sizing[0], list()) group.append((row, sizing)) row_sizings_by_type[sizing[0]] = group # Determine column widths",
"grid.area_empty(rect_right)) def test_single_fixed(self): grid = GridLayout(spacing=5) grid.set_fixed_column_sizing(0, 90) grid.set_fixed_row_sizing(0, 120) child = self.gui.create(Panel)",
"!= panel, self.panels) def clear(self, *, remove_panels): if remove_panels: for panel in self.panels.values():",
"row_count=2, spacing=5) grid.set_child_column_sizing(0) grid.set_child_column_sizing(1) grid.set_child_row_sizing(0) grid.set_child_row_sizing(1) def create_child(rect, size): child = self.gui.create(Panel) child.parent",
"return True def set_fixed_column_sizing(self, column, size): self.column_sizings[column] = (self.FIXED, size) def set_fixed_row_sizing(self, row,",
"evaluated next. Even panels will split remaining space evenly between # themselves. Fill",
"panel spans multiple rows, determine the height as a # proportional amount. return",
"+ height_0, width_1, height_1), child_1_1.rect_outer) def grid_example(gui): panel = gui.create(Panel) panel.rect = (50,",
"it should resize. def zero_func(): return 0 class GridLayout: FIXED = 0 CHILD",
"self.panels.items())) def calculate_height(rect_panel_tuple): rect, panel = rect_panel_tuple # In case a panel spans",
"self.assertEqual(Panel.Rect(108, 3, 58, 33), child_1_0.rect_outer) self.assertEqual(Panel.Rect( 2, 41, 101, 93), child_0_1.rect_outer) self.assertEqual(Panel.Rect(108, 41,",
"self.assertEqual(Panel.Rect(13, 19, 53, 81), child.rect) def test_multiple_child_1(self): grid = GridLayout(column_count=2, row_count=2, spacing=5) grid.set_child_column_sizing(0)",
"sizing_tuple in sizings_by_type.get(self.EVEN, []): column_or_row, _ = sizing_tuple amount = min(extra, 1) sizes[column_or_row]",
"# If the resulting layout exceeds the bounds of the parent, it is",
"= allocate_extra_custom(row_sizings_by_type, row_heights, extra_height) def allocate_extra_even(sizings_by_type, sizes, extra): for sizing_tuple in sizings_by_type.get(self.EVEN, []):",
"not default: grid.set_even_column_sizing(0) grid.set_even_row_sizing(0) child = self.gui.create(Panel) child.parent = self.parent child.padding = (10,",
"for row in range(grid.row_count): grid.set_child_row_sizing(row) return grid with self.subTest(\"column\"): grid = create_grid() child",
"in sizings_by_type.get(self.EVEN, []): column_or_row, _ = sizing_tuple sizes[column_or_row] = size calculate_even_sizes( column_sizings_by_type, column_widths,",
"preserving the order. for column in range(self.column_count): sizing = self.column_sizings.get(column, (self.EVEN,)) group =",
"allocate_extra_custom(row_sizings_by_type, row_heights, extra_height) def allocate_extra_even(sizings_by_type, sizes, extra): for sizing_tuple in sizings_by_type.get(self.EVEN, []): column_or_row,",
"of the parent, it is up to the # parent to decide if",
"area.w - sum(column_widths)) calculate_even_sizes( row_sizings_by_type, row_heights, area.h - sum(row_heights)) fill_columns = column_sizings_by_type.get(self.FILL, [])",
"set_child_column_sizing(self, column): self.column_sizings[column] = (self.CHILD,) def set_child_row_sizing(self, row): self.row_sizings[row] = (self.CHILD,) def set_percentage_column_sizing(self,",
"= sizing_tuple sizes[column_or_row] = size calculate_even_sizes( column_sizings_by_type, column_widths, area.w - sum(column_widths)) calculate_even_sizes( row_sizings_by_type,",
"GridLayout(spacing=5) if not default: grid.set_even_column_sizing(0) grid.set_even_row_sizing(0) child = self.gui.create(Panel) child.parent = self.parent child.padding",
"from desky.gui import Gui self.gui = Gui() self.parent = self.gui.create(Panel) self.parent.size = (200,",
"+ 1 self.assertEqual(Panel.Rect(13, 19, width, height), child.rect) def test_multiple_percentage(self): grid = GridLayout(column_count=2, row_count=2,",
"= int(custom_sizing_2(189, None)) height_0 = int(custom_sizing_2(287, None)) + 1 height_1 = int(custom_sizing_1(287, None))",
"self.assertEqual(Panel.Rect( 2, 3, 80, 50), child_0_0.rect_outer) self.assertEqual(Panel.Rect( 2, 58, 80, 50), child_0_1.rect_outer) self.assertEqual(Panel.Rect(87,",
"1)) grid.layout(self.parent) width_0 = int(189 * 0.5) + 1 width_1 = int(189 *",
"rect_panel_tuple # In case a panel spans multiple rows, determine the height as",
"50), child_0_1.rect_outer) self.assertEqual(Panel.Rect(87, 3, 44, 105), child_1_0.rect_outer) def test_single_percentage(self): grid = GridLayout(spacing=5) grid.set_percentage_column_sizing(0,",
"grid.add(child, 1, 2) self.assertEqual(60, grid.tallest_child_in_row(2)) def test_tallest_child_in_column_or_row_3(self): def create_grid(): grid = GridLayout(column_count=5, row_count=5,",
"2, 3, 80, 89), child_0_0.rect_outer) self.assertEqual(Panel.Rect(87, 3, 73, 89), child_1_0.rect_outer) self.assertEqual(Panel.Rect( 2, 97,",
"= create_grid() child = self.gui.create(Panel) child.size = (38, 60) grid.add(child, 1, 2) self.assertEqual(60,",
"extra extra_width = allocate_extra_even(column_sizings_by_type, column_widths, extra_width) extra_height = allocate_extra_even(row_sizings_by_type, row_heights, extra_height) # Save",
"= create_child(Rect(1, 0, 1, 2), (25, 87)) grid.layout(self.parent) self.assertEqual(Panel.Rect( 2, 3, 80, 50),",
"sizing. for default in (True, False): with self.subTest(default=default): grid = GridLayout(spacing=5) if not",
"grid = create_grid() child = self.gui.create(Panel) child.size = (38, 66) grid.add_rect(child, Rect(1, 2,",
"GridLayout(column_count=2, row_count=2, spacing=5) grid.set_even_column_sizing(0) grid.set_even_column_sizing(1) grid.set_even_row_sizing(0) grid.set_even_row_sizing(1) def create_child(rect): child = self.gui.create(Panel) child.parent",
"8 + height_0, width_1, height_1), child_1_1.rect_outer) def test_single_custom(self): def custom_sizing(area_size, remaining_size): return area_size",
"_ = sizing_tuple sizes[column_or_row] = largest_func(column_or_row) calculate_child_sizes(column_sizings_by_type, column_widths, self.widest_child_in_column) calculate_child_sizes(row_sizings_by_type, row_heights, self.tallest_child_in_row) def",
"return grid with self.subTest(\"column\"): grid = create_grid() child = self.gui.create(Panel) child.size = (66,",
"for _ in range(self.row_count)] def calculate_fixed_sizes(sizings_by_type, sizes): for sizing_tuple in sizings_by_type.get(self.FIXED, []): column_or_row,",
"3, 80, 89), child_0_0.rect_outer) self.assertEqual(Panel.Rect(87, 3, 73, 89), child_1_0.rect_outer) self.assertEqual(Panel.Rect( 2, 97, 80,",
"If the resulting layout exceeds the bounds of the parent, it is up",
"custom_sizing_1, partial(min, 1)) def create_child(rect): child = self.gui.create(Panel) child.parent = self.parent child.padding =",
"sizing | Maximum extra width allocation # -------------------------------------------------------------- # | Fixed (200 px)",
"1 PERCENTAGE = 2 CUSTOM = 3 EVEN = 4 FILL = 5",
"sizings_by_type.get(self.PERCENTAGE, []): column_or_row, _ = sizing_tuple amount = min(extra, 1) sizes[column_or_row] += amount",
"** 0.5) root_height = int(292 ** 0.5) final_width = root_width + int((194 -",
"create_grid() child = self.gui.create(Panel) child.size = (66, 38) grid.add_rect(child, Rect(2, 1, 3, 2))",
"self.assertEqual(0, grid.tallest_child_in_row(2)) def test_tallest_child_in_column_or_row_2(self): def create_grid(): grid = GridLayout(column_count=5, row_count=5, spacing=3) for column",
"partial(min, 1)) grid.set_custom_row_sizing(1, custom_sizing_1, partial(min, 1)) def create_child(rect): child = self.gui.create(Panel) child.parent =",
"self.panels = valfilter(lambda p: p != panel, self.panels) def clear(self, *, remove_panels): if",
"0, 1, 1)) child_1_0 = create_child(Rect(1, 0, 1, 1)) child_0_1 = create_child(Rect(0, 1,",
"row heights for users to access. self.column_widths = column_widths self.row_heights = row_heights #",
"__init__(self, *, column_count = 1, row_count = 1, spacing = 0): self.panels =",
"0, 1, 1)) child_1_1 = create_child(Rect(1, 1, 1, 1)) grid.layout(self.parent) width_0 = int(custom_sizing_1(189,",
"0.5) final_width = root_width + int((194 - root_width) / 2) - 19 final_height",
"custom_sizing_1, partial(min, 1)) grid.set_custom_column_sizing(1, custom_sizing_2, partial(min, 1)) grid.set_custom_row_sizing(0, custom_sizing_2, partial(min, 1)) grid.set_custom_row_sizing(1, custom_sizing_1,",
"the remaining area size as its argument. Even is # evaluated next. Even",
"# | Fixed (200 px) | 0px # | Child (use child size)",
"[1]))) for sizing_tuple in sizings_by_type.get(self.EVEN, []): column_or_row, _ = sizing_tuple sizes[column_or_row] = size",
"sizes, area_size, remaining_size): for sizing_tuple in sizings_by_type.get(self.CUSTOM, []): column_or_row, sizing = sizing_tuple sizes[column_or_row]",
"= create_child(Rect(1, 1, 1, 1)) grid.layout(self.parent) self.assertEqual(Panel.Rect( 2, 3, 101, 33), child_0_0.rect_outer) self.assertEqual(Panel.Rect(108,",
"(self.EVEN,)) group = column_sizings_by_type.get(sizing[0], list()) group.append((column, sizing)) column_sizings_by_type[sizing[0]] = group for row in",
"height_1 = int(287 * (1 - 0.8139)) self.assertEqual(Panel.Rect(2, 3, width_0, height_0), child_0_0.rect_outer) self.assertEqual(Panel.Rect(2,",
"# Fixed, Child, and Percentage sizings are evaluated first. Custom is then #",
"row_heights, extra_height) def allocate_extra_custom(sizings_by_type, sizes, extra): for sizing_tuple in sizings_by_type.get(self.CUSTOM, []): column_or_row, sizing",
"grid.widest_child_in_column(2)) self.assertEqual(20, grid.widest_child_in_column(3)) self.assertEqual(20, grid.widest_child_in_column(4)) with self.subTest(\"row\"): grid = create_grid() child = self.gui.create(Panel)",
"GridLayout(column_count = 3, row_count = 4, spacing = 4) for row in range(0,",
"self.assertEqual(Panel.Rect( 2, 41, 101, 93), child_0_1.rect_outer) self.assertEqual(Panel.Rect(108, 41, 58, 93), child_1_1.rect_outer) def test_multiple_fixed_2(self):",
"= column_count self.row_count = row_count self.spacing = spacing def add(self, panel, column, row,",
"= (53, 81) grid.add(child, 0, 0) grid.layout(self.parent) root_width = int(194 ** 0.5) root_height",
"size): self.column_sizings[column] = (self.FIXED, size) def set_fixed_row_sizing(self, row, size): self.row_sizings[row] = (self.FIXED, size)",
"** 0.5) final_width = root_width + int((194 - root_width) / 2) - 19",
"rect_panel_tuple[0].intersects(column_rect), self.panels.items())) def calculate_width(rect_panel_tuple): rect, panel = rect_panel_tuple # In case a panel",
"extra -= amount return extra extra_width = allocate_extra_custom(column_sizings_by_type, column_widths, extra_width) extra_height = allocate_extra_custom(row_sizings_by_type,",
"1, 1)) grid.layout(self.parent) self.assertEqual(Panel.Rect( 2, 3, 101, 33), child_0_0.rect_outer) self.assertEqual(Panel.Rect(108, 3, 58, 33),",
"if fill_rows: row_heights[fill_rows[0][0]] = area.h - sum(row_heights) # Allocate extra width and height",
"assert(rect.bottom <= self.row_count) assert(self.area_empty(rect)) self.panels[rect.frozen_copy()] = panel def remove(self, panel): self.panels = valfilter(lambda",
"grid.set_custom_row_sizing(1, custom_sizing_1, partial(min, 1)) def create_child(rect): child = self.gui.create(Panel) child.parent = self.parent child.padding",
"rect_panel_tuple[0].intersects(row_rect), self.panels.items())) def calculate_height(rect_panel_tuple): rect, panel = rect_panel_tuple # In case a panel",
"Enum from functools import reduce, partial from toolz.dicttoolz import valfilter # | Type",
"1 height_1 = int(custom_sizing_1(287, None)) self.assertEqual(Panel.Rect(2, 3, width_0, height_0), child_0_0.rect_outer) self.assertEqual(Panel.Rect(2, 8 +",
"PERCENTAGE = 2 CUSTOM = 3 EVEN = 4 FILL = 5 def",
"self.panels.items(): x = area.x + sum(column_widths[:rect.x]) + rect.x * self.spacing y = area.y",
"(self.CHILD,) def set_percentage_column_sizing(self, column, percentage): self.column_sizings[column] = (self.PERCENTAGE, percentage) def set_percentage_row_sizing(self, row, percentage):",
"extra_height) # Save column widths and row heights for users to access. self.column_widths",
"2), Rect(1, 1, 9, 9), False), (Rect(10, 2, 4, 4), Rect(1, 1, 9,",
"Fill (use remaining space) | any # # The types of sizing in",
"range(grid.column_count): grid.set_child_column_sizing(column) for row in range(grid.row_count): grid.set_child_row_sizing(row) self.assertEqual(0, grid.widest_child_in_column(2)) self.assertEqual(0, grid.tallest_child_in_row(2)) def test_tallest_child_in_column_or_row_2(self):",
"extra_height = allocate_extra_custom(row_sizings_by_type, row_heights, extra_height) def allocate_extra_even(sizings_by_type, sizes, extra): for sizing_tuple in sizings_by_type.get(self.EVEN,",
"child.rect) def test_multiple_even(self): grid = GridLayout(column_count=2, row_count=2, spacing=5) grid.set_even_column_sizing(0) grid.set_even_column_sizing(1) grid.set_even_row_sizing(0) grid.set_even_row_sizing(1) def",
"rect) return child child_0_0 = create_child(Rect(0, 0, 1, 1)) child_1_0 = create_child(Rect(1, 0,",
"row, sizing_func, extra_func=zero_func): self.row_sizings[row] = (self.CUSTOM, sizing_func, extra_func) def set_even_column_sizing(self, column): self.column_sizings[column] =",
"self.subTest(\"row\"): grid = create_grid() child = self.gui.create(Panel) child.size = (38, 66) grid.add_rect(child, Rect(1,",
"= (9999, 9999) grid.add_rect(child, rect) return child child_0_0 = create_child(Rect(0, 0, 1, 1))",
"# # If the resulting layout exceeds the bounds of the parent, it",
"column_widths = [0 for _ in range(self.column_count)] row_heights = [0 for _ in",
"create_child(Rect(0, 1, 1, 1)) child_1_1 = create_child(Rect(1, 1, 1, 1)) grid.layout(self.parent) self.assertEqual(Panel.Rect( 2,",
"child = self.gui.create(Panel) child.size = (38, 60) grid.add(child, 1, 2) self.assertEqual(60, grid.tallest_child_in_row(2)) def",
"0.5 def custom_extra(extra): return extra / 2 grid = GridLayout(spacing=5) grid.set_custom_column_sizing(0, custom_sizing, custom_extra)",
"grid.layout(self.parent) width_0 = int(189 * 0.3333) width_1 = 189 - int(189 * 0.3333)",
"self.assertEqual(Panel.Rect(2, 8 + height_0, width_0, height_1), child_0_1.rect_outer) self.assertEqual(Panel.Rect(7 + width_0, 3, width_1, height_0),",
"row_sizings_by_type = dict() # Group columns and rows by their sizing types while",
"def test_single_fill(self): grid = GridLayout(spacing=5) grid.set_fill_column_sizing(0) grid.set_fill_row_sizing(0) child = self.gui.create(Panel) child.parent = self.parent",
"- 1) * self.spacing) / rect.w) return reduce(max, map(calculate_width, rect_panel_tuples_that_intersect_column), 0) def tallest_child_in_row(self,",
"- sum(column_widths)) calculate_even_sizes( row_sizings_by_type, row_heights, area.h - sum(row_heights)) fill_columns = column_sizings_by_type.get(self.FILL, []) if",
"def test_multiple_child_1(self): grid = GridLayout(column_count=2, row_count=2, spacing=5) grid.set_child_column_sizing(0) grid.set_child_column_sizing(1) grid.set_child_row_sizing(0) grid.set_child_row_sizing(1) def create_child(rect,",
"# Determine column widths and row heights. column_widths = [0 for _ in",
"Custom is then # evaluated and is given the remaining area size as",
"self.row_sizings[row] = (self.EVEN,) def set_fill_column_sizing(self, column): self.column_sizings[column] = (self.FILL,) def set_fill_row_sizing(self, row): self.row_sizings[row]",
"return reduce(max, map(calculate_height, rect_panel_tuples_that_intersect_row), 0) def layout(self, panel): area = (panel.rect_inner .move(-panel.x, -panel.y)",
"0) grid.set_fixed_row_sizing(1, 93) def create_child(rect): child = self.gui.create(Panel) child.parent = self.parent child.padding =",
"column_sizings_by_type.get(sizing[0], list()) group.append((column, sizing)) column_sizings_by_type[sizing[0]] = group for row in range(self.row_count): sizing =",
"grid = GridLayout(spacing=5) grid.set_percentage_column_sizing(0, 0.333) grid.set_percentage_row_sizing(0, 0.8) child = self.gui.create(Panel) child.parent = self.parent",
"calculate_percentage_sizes(row_sizings_by_type, row_heights, area.h) def calculate_custom_sizes(sizings_by_type, sizes, area_size, remaining_size): for sizing_tuple in sizings_by_type.get(self.CUSTOM, []):",
"grid.layout(self.parent) width_0 = int(189 * 0.333) + 1 width_1 = width_0 height_0 =",
"19, 18), child_1_0.rect_outer) self.assertEqual(Panel.Rect( 2, 8, 101, 93), child_0_1.rect_outer) self.assertEqual(Panel.Rect(108, 8, 19, 93),",
"(self.EVEN,)) group = row_sizings_by_type.get(sizing[0], list()) group.append((row, sizing)) row_sizings_by_type[sizing[0]] = group # Determine column",
"sizing = sizing_tuple sizes[column_or_row] = int(sizing[1](area_size, remaining_size)) calculate_custom_sizes(column_sizings_by_type, column_widths, area.w, area.w - sum(column_widths))",
"self.parent = self.gui.create(Panel) self.parent.size = (200, 300) self.parent.padding = (2, 3, 4, 5)",
"extra_width = allocate_extra_even(column_sizings_by_type, column_widths, extra_width) extra_height = allocate_extra_even(row_sizings_by_type, row_heights, extra_height) # Save column",
"True def set_fixed_column_sizing(self, column, size): self.column_sizings[column] = (self.FIXED, size) def set_fixed_row_sizing(self, row, size):",
"19 final_height = root_height + int((292 - root_height) / 2) - 18 self.assertEqual(Panel.Rect(13,",
"0.333) grid.set_percentage_column_sizing(1, 0.333) grid.set_percentage_row_sizing(0, 0.8139) grid.set_percentage_row_sizing(1, 1 - 0.8139) def create_child(rect): child =",
"= (self.CHILD,) def set_child_row_sizing(self, row): self.row_sizings[row] = (self.CHILD,) def set_percentage_column_sizing(self, column, percentage): self.column_sizings[column]",
"column_count, row_count)) def add_rect(self, panel, rect): assert(rect.x >= 0) assert(rect.y >= 0) assert(rect.right",
"= GridLayout(column_count=2, row_count=2, spacing=5) grid.set_fixed_column_sizing(0, 101) grid.set_fixed_column_sizing(1, 0) grid.set_fixed_row_sizing(0, 0) grid.set_fixed_row_sizing(1, 93) def",
"1), (61, 31)) child_1_0 = create_child(Rect(1, 0, 1, 2), (25, 87)) grid.layout(self.parent) self.assertEqual(Panel.Rect(",
"is then # evaluated and is given the remaining area size as its",
"return area_size ** 0.8 def custom_sizing_2(area_size, remaining_size): return area_size - area_size ** 0.8",
"1), (54, 20)) grid.layout(self.parent) self.assertEqual(Panel.Rect( 2, 3, 80, 89), child_0_0.rect_outer) self.assertEqual(Panel.Rect(87, 3, 73,",
"column_or_row, sizing = sizing_tuple amount = int(sizing[2](extra)) sizes[column_or_row] += amount extra -= amount",
"(self.FIXED, size) def set_fixed_row_sizing(self, row, size): self.row_sizings[row] = (self.FIXED, size) def set_child_column_sizing(self, column):",
"custom_sizing, custom_extra) grid.set_custom_row_sizing(0, custom_sizing, custom_extra) child = self.gui.create(Panel) child.parent = self.parent child.padding =",
"4, spacing = 4) for row in range(0, grid.row_count): for column in range(0,",
"80, 89), child_0_0.rect_outer) self.assertEqual(Panel.Rect(87, 3, 73, 89), child_1_0.rect_outer) self.assertEqual(Panel.Rect( 2, 97, 80, 80),",
"= 2 CUSTOM = 3 EVEN = 4 FILL = 5 def __init__(self,",
"= self.column_sizings.get(column, (self.EVEN,)) group = column_sizings_by_type.get(sizing[0], list()) group.append((column, sizing)) column_sizings_by_type[sizing[0]] = group for",
"= GridLayout(column_count = 3, row_count = 4, spacing = 4) for row in",
"grid.widest_child_in_column(4)) with self.subTest(\"row\"): grid = create_grid() child = self.gui.create(Panel) child.size = (38, 66)",
"1)) child_1_1 = create_child(Rect(1, 1, 1, 1)) grid.layout(self.parent) width_0 = int(189 * 0.3333)",
"child.rect) def test_multiple_fixed_1(self): grid = GridLayout(column_count=2, row_count=2, spacing=5) grid.set_fixed_column_sizing(0, 101) grid.set_fixed_column_sizing(1, 58) grid.set_fixed_row_sizing(0,",
"column in range(self.column_count): sizing = self.column_sizings.get(column, (self.EVEN,)) group = column_sizings_by_type.get(sizing[0], list()) group.append((column, sizing))",
"column_widths) calculate_fixed_sizes(row_sizings_by_type, row_heights) def calculate_child_sizes(sizings_by_type, sizes, largest_func): for sizing_tuple in sizings_by_type.get(self.CHILD, []): column_or_row,",
"calculate_child_sizes(row_sizings_by_type, row_heights, self.tallest_child_in_row) def calculate_percentage_sizes(sizings_by_type, sizes, area_size): for sizing_tuple in sizings_by_type.get(self.PERCENTAGE, []): column_or_row,",
"calculate_even_sizes( row_sizings_by_type, row_heights, area.h - sum(row_heights)) fill_columns = column_sizings_by_type.get(self.FILL, []) if fill_columns: column_widths[fill_columns[0][0]]",
"= dict() self.column_sizings = dict() self.row_sizings = dict() self.column_count = column_count self.row_count =",
"child_0_0.rect_outer) self.assertEqual(Panel.Rect(108, 3, 58, 33), child_1_0.rect_outer) self.assertEqual(Panel.Rect( 2, 41, 101, 93), child_0_1.rect_outer) self.assertEqual(Panel.Rect(108,",
"functools import reduce, partial from toolz.dicttoolz import valfilter # | Type of sizing",
"return extra extra_width = allocate_extra_even(column_sizings_by_type, column_widths, extra_width) extra_height = allocate_extra_even(row_sizings_by_type, row_heights, extra_height) #",
"= GridLayout(column_count=2, row_count=2, spacing=5) grid.set_custom_column_sizing(0, custom_sizing_1, partial(min, 1)) grid.set_custom_column_sizing(1, custom_sizing_2, partial(min, 1)) grid.set_custom_row_sizing(0,",
"+ int((194 - root_width) / 2) - 19 final_height = root_height + int((292",
"Rect(column, row, column_count, row_count)) def add_rect(self, panel, rect): assert(rect.x >= 0) assert(rect.y >=",
"custom_sizing_2(area_size, remaining_size): return area_size - area_size ** 0.8 grid = GridLayout(column_count=2, row_count=2, spacing=5)",
"evaluated and is given the remaining area size as its argument. Even is",
"return grid with self.subTest(\"column\"): grid = create_grid() child = self.gui.create(Panel) child.size = (60,",
"(Rect(10, 2, 4, 4), Rect(1, 1, 9, 9), True), ] for rect_left, rect_right,",
"will take the remaining space. # # If the resulting layout exceeds the",
"grid.set_child_row_sizing(1) def create_child(rect, size): child = self.gui.create(Panel) child.parent = self.parent child.padding = (10,",
"19, 71, 102), child.rect) def test_multiple_fixed_1(self): grid = GridLayout(column_count=2, row_count=2, spacing=5) grid.set_fixed_column_sizing(0, 101)",
"from functools import reduce, partial from toolz.dicttoolz import valfilter # | Type of",
"In case a panel spans multiple columns, determine the height as a #",
"self.assertEqual(Panel.Rect(7 + width_0, 8 + height_0, width_1, height_1), child_1_1.rect_outer) def test_single_even(self): # Since",
"= dict() def area_empty(self, rect): for rect_other in self.panels.keys(): if rect.intersects(rect_other): return False",
"16, 8, 2) child.size = (9999, 9999) grid.add_rect(child, rect) return child child_0_0 =",
"= create_child(Rect(1, 0, 1, 1)) child_1_1 = create_child(Rect(1, 1, 1, 1)) grid.layout(self.parent) width_0",
"= (10, 8, 6, 4) child.margins = (11, 16, 8, 2) child.size =",
"space) | any # # The types of sizing in the table above",
"calculate_height(rect_panel_tuple): rect, panel = rect_panel_tuple # In case a panel spans multiple rows,",
"= 0): self.panels = dict() self.column_sizings = dict() self.row_sizings = dict() self.column_count =",
"rect): assert(rect.x >= 0) assert(rect.y >= 0) assert(rect.right <= self.column_count) assert(rect.bottom <= self.row_count)",
"self.gui.create(Panel) child.size = (60, 38) grid.add(child, 2, 1) self.assertEqual(60, grid.widest_child_in_column(2)) with self.subTest(\"column\"): grid",
"def set_even_column_sizing(self, column): self.column_sizings[column] = (self.EVEN,) def set_even_row_sizing(self, row): self.row_sizings[row] = (self.EVEN,) def",
"1) * self.spacing) / rect.w) return reduce(max, map(calculate_width, rect_panel_tuples_that_intersect_column), 0) def tallest_child_in_row(self, row):",
"child.margins = (11, 16, 8, 2) child.size = (53, 81) grid.add(child, 0, 0)",
"0, 1, 1), (58, 39)) child_1_0 = create_child(Rect(1, 0, 1, 1), (25, 71))",
"height_0), child_1_0.rect_outer) self.assertEqual(Panel.Rect(7 + width_0, 8 + height_0, width_1, height_1), child_1_1.rect_outer) def test_single_custom(self):",
"Rect(2, 1, 3, 2)) self.assertEqual(20, grid.widest_child_in_column(2)) self.assertEqual(20, grid.widest_child_in_column(3)) self.assertEqual(20, grid.widest_child_in_column(4)) with self.subTest(\"row\"): grid",
"class GridLayoutTest(unittest.TestCase): def setUp(self): from desky.gui import Gui self.gui = Gui() self.parent =",
"1, 1)) grid.layout(self.parent) self.assertEqual(Panel.Rect( 2, 3, 101, 18), child_0_0.rect_outer) self.assertEqual(Panel.Rect(108, 3, 19, 18),",
"62)) child_1_1 = create_child(Rect(1, 1, 1, 1), (54, 20)) grid.layout(self.parent) self.assertEqual(Panel.Rect( 2, 3,",
"Percentage (30% of width) | 1px # | Custom (custom function) | configurable",
"column, sizing_func, extra_func=zero_func): self.column_sizings[column] = (self.CUSTOM, sizing_func, extra_func) def set_custom_row_sizing(self, row, sizing_func, extra_func=zero_func):",
"child_0_0.rect_outer) self.assertEqual(Panel.Rect(87, 3, 73, 89), child_1_0.rect_outer) self.assertEqual(Panel.Rect( 2, 97, 80, 80), child_0_1.rect_outer) self.assertEqual(Panel.Rect(87,",
"101) grid.set_fixed_column_sizing(1, 58) grid.set_fixed_row_sizing(0, 33) grid.set_fixed_row_sizing(1, 93) def create_child(rect): child = self.gui.create(Panel) child.parent",
"grid.set_fixed_column_sizing(1, 0) grid.set_fixed_row_sizing(0, 0) grid.set_fixed_row_sizing(1, 93) def create_child(rect): child = self.gui.create(Panel) child.parent =",
"create_child(rect, size): child = self.gui.create(Panel) child.parent = self.parent child.padding = (10, 8, 6,",
"(53, 81) grid.add(child, 0, 0) grid.layout(self.parent) self.assertEqual(Panel.Rect(13, 19, 175, 274), child.rect) def test_multiple_even(self):",
"= group # Determine column widths and row heights. column_widths = [0 for",
"= (53, 81) grid.add(child, 0, 0) grid.layout(self.parent) self.assertEqual(Panel.Rect(13, 19, 175, 274), child.rect) def",
"dict() # Group columns and rows by their sizing types while preserving the",
"16, 8, 2) child.size = size grid.add_rect(child, rect) return child child_0_0 = create_child(Rect(0,",
"(self.CUSTOM, sizing_func, extra_func) def set_even_column_sizing(self, column): self.column_sizings[column] = (self.EVEN,) def set_even_row_sizing(self, row): self.row_sizings[row]",
"Save column widths and row heights for users to access. self.column_widths = column_widths",
"column_or_row, _ = sizing_tuple sizes[column_or_row] = size calculate_even_sizes( column_sizings_by_type, column_widths, area.w - sum(column_widths))",
"lambda rect_panel_tuple: rect_panel_tuple[0].intersects(row_rect), self.panels.items())) def calculate_height(rect_panel_tuple): rect, panel = rect_panel_tuple # In case",
"self.spacing, (self.row_count - 1) * self.spacing) ) column_sizings_by_type = dict() row_sizings_by_type = dict()",
"/ 2) - 18 self.assertEqual(Panel.Rect(13, 19, final_width, final_height), child.rect) def test_multiple_custom(self): def custom_sizing_1(area_size,",
"return False return True def set_fixed_column_sizing(self, column, size): self.column_sizings[column] = (self.FIXED, size) def",
"works even # when we don't excplicitly set the columns and rows to",
"sizing_func, extra_func=zero_func): self.column_sizings[column] = (self.CUSTOM, sizing_func, extra_func) def set_custom_row_sizing(self, row, sizing_func, extra_func=zero_func): self.row_sizings[row]",
"0.5) + 1 height_1 = int(287 * 0.5) self.assertEqual(Panel.Rect(2, 3, width_0, height_0), child_0_0.rect_outer)",
"if fill_columns: column_widths[fill_columns[0][0]] = area.w - sum(column_widths) fill_rows = row_sizings_by_type.get(self.FILL, []) if fill_rows:",
"def test_tallest_child_in_column_or_row_1(self): grid = GridLayout(column_count=5, row_count=5, spacing=3) for column in range(grid.column_count): grid.set_child_column_sizing(column) for",
"set_even_column_sizing(self, column): self.column_sizings[column] = (self.EVEN,) def set_even_row_sizing(self, row): self.row_sizings[row] = (self.EVEN,) def set_fill_column_sizing(self,",
"0.5) root_height = int(292 ** 0.5) final_width = root_width + int((194 - root_width)",
"- int(189 * 0.3333) height_0 = 287 - 100 height_1 = 100 self.assertEqual(Panel.Rect(2,",
"| Percentage (30% of width) | 1px # | Custom (custom function) |",
"/ 2) - 19 final_height = root_height + int((292 - root_height) / 2)",
"= create_child(Rect(0, 0, 1, 1), (58, 31)) child_0_1 = create_child(Rect(0, 1, 1, 1),",
"int(custom_sizing_1(287, None)) self.assertEqual(Panel.Rect(2, 3, width_0, height_0), child_0_0.rect_outer) self.assertEqual(Panel.Rect(2, 8 + height_0, width_0, height_1),",
"= Gui() self.parent = self.gui.create(Panel) self.parent.size = (200, 300) self.parent.padding = (2, 3,",
"def clear(self, *, remove_panels): if remove_panels: for panel in self.panels.values(): panel.remove() self.panels =",
"with self.subTest(\"row\"): grid = create_grid() child = self.gui.create(Panel) child.size = (38, 66) grid.add_rect(child,",
"1, 1, 1)) grid.layout(self.parent) width_0 = int(189 * 0.333) + 1 width_1 =",
"row, self.column_count, 1) rect_panel_tuples_that_intersect_row = list( filter( lambda rect_panel_tuple: rect_panel_tuple[0].intersects(row_rect), self.panels.items())) def calculate_height(rect_panel_tuple):",
"grid.set_fixed_row_sizing(1, 100) def create_child(rect): child = self.gui.create(Panel) child.parent = self.parent child.padding = (10,",
"(2, 3, 4, 5) self.parent.margins = (20, 30, 40, 50) def test_tallest_child_in_column_or_row_1(self): grid",
"sizings_by_type.get(self.CHILD, []): column_or_row, _ = sizing_tuple sizes[column_or_row] = largest_func(column_or_row) calculate_child_sizes(column_sizings_by_type, column_widths, self.widest_child_in_column) calculate_child_sizes(row_sizings_by_type,",
"8, 19, 93), child_1_1.rect_outer) def test_single_child(self): grid = GridLayout(spacing=5) grid.set_child_column_sizing(0) grid.set_child_row_sizing(0) child =",
"18 + 1 self.assertEqual(Panel.Rect(13, 19, width, height), child.rect) def test_multiple_percentage(self): grid = GridLayout(column_count=2,",
"spacing=5) grid.set_even_column_sizing(0) grid.set_even_column_sizing(1) grid.set_even_row_sizing(0) grid.set_even_row_sizing(1) def create_child(rect): child = self.gui.create(Panel) child.parent = self.parent",
"<= self.row_count) assert(self.area_empty(rect)) self.panels[rect.frozen_copy()] = panel def remove(self, panel): self.panels = valfilter(lambda p:",
"= 4) for row in range(0, grid.row_count): for column in range(0, grid.column_count): child",
"height_0, width_1, height_1), child_1_1.rect_outer) def test_single_custom(self): def custom_sizing(area_size, remaining_size): return area_size ** 0.5",
"spacing=5) grid.set_percentage_column_sizing(0, 0.3333) grid.set_fill_column_sizing(1) grid.set_fill_row_sizing(0) grid.set_fixed_row_sizing(1, 100) def create_child(rect): child = self.gui.create(Panel) child.parent",
"GridLayoutTest(unittest.TestCase): def setUp(self): from desky.gui import Gui self.gui = Gui() self.parent = self.gui.create(Panel)",
"81), child.rect) def test_multiple_child_1(self): grid = GridLayout(column_count=2, row_count=2, spacing=5) grid.set_child_column_sizing(0) grid.set_child_column_sizing(1) grid.set_child_row_sizing(0) grid.set_child_row_sizing(1)",
"self.assertEqual(Panel.Rect(7 + width_0, 8 + height_0, width_1, height_1), child_1_1.rect_outer) def grid_example(gui): panel =",
"Panel from enum import Enum from functools import reduce, partial from toolz.dicttoolz import",
"sizing)) column_sizings_by_type[sizing[0]] = group for row in range(self.row_count): sizing = self.row_sizings.get(row, (self.EVEN,)) group",
"height as a # proportional amount. return int((panel.rect_outer.w - (rect.w - 1) *",
"1)) grid.layout(self.parent) width_0 = int(189 * 0.333) + 1 width_1 = width_0 height_0",
"def add_rect(self, panel, rect): assert(rect.x >= 0) assert(rect.y >= 0) assert(rect.right <= self.column_count)",
"1)) child_1_0 = create_child(Rect(1, 0, 1, 1)) child_1_1 = create_child(Rect(1, 1, 1, 1))",
"from toolz.dicttoolz import valfilter # | Type of sizing | Maximum extra width",
"percentage) def set_percentage_row_sizing(self, row, percentage): self.row_sizings[row] = (self.PERCENTAGE, percentage) def set_custom_column_sizing(self, column, sizing_func,",
"column, row, column_count=1, row_count=1): self.add_rect(panel, Rect(column, row, column_count, row_count)) def add_rect(self, panel, rect):",
"- sum(row_heights)) fill_columns = column_sizings_by_type.get(self.FILL, []) if fill_columns: column_widths[fill_columns[0][0]] = area.w - sum(column_widths)",
"extra_width) extra_height = allocate_extra_percentage(row_sizings_by_type, row_heights, extra_height) def allocate_extra_custom(sizings_by_type, sizes, extra): for sizing_tuple in",
"= allocate_extra_percentage(column_sizings_by_type, column_widths, extra_width) extra_height = allocate_extra_percentage(row_sizings_by_type, row_heights, extra_height) def allocate_extra_custom(sizings_by_type, sizes, extra):",
"3, 2)) self.assertEqual(20, grid.widest_child_in_column(2)) self.assertEqual(20, grid.widest_child_in_column(3)) self.assertEqual(20, grid.widest_child_in_column(4)) with self.subTest(\"row\"): grid = create_grid()",
"empty=empty): grid = GridLayout(column_count=20, row_count=20, spacing=5) grid.add_rect(self.gui.create(Panel), rect_left) self.assertEqual(empty, grid.area_empty(rect_right)) def test_single_fixed(self): grid",
"71, 102), child.rect) def test_multiple_fixed_1(self): grid = GridLayout(column_count=2, row_count=2, spacing=5) grid.set_fixed_column_sizing(0, 101) grid.set_fixed_column_sizing(1,",
"In case a panel spans multiple rows, determine the height as a #",
"custom_sizing_1(area_size, remaining_size): return area_size ** 0.8 def custom_sizing_2(area_size, remaining_size): return area_size - area_size",
"1) * self.spacing) / rect.h) return reduce(max, map(calculate_height, rect_panel_tuples_that_intersect_row), 0) def layout(self, panel):",
"evalulation priority. # Fixed, Child, and Percentage sizings are evaluated first. Custom is",
"2, 3, 101, 18), child_0_0.rect_outer) self.assertEqual(Panel.Rect(108, 3, 19, 18), child_1_0.rect_outer) self.assertEqual(Panel.Rect( 2, 8,",
"is up to the # parent to decide if it should resize. def",
"GridLayout(spacing=5) grid.set_fill_column_sizing(0) grid.set_fill_row_sizing(0) child = self.gui.create(Panel) child.parent = self.parent child.padding = (10, 8,",
"287 - 100 height_1 = 100 self.assertEqual(Panel.Rect(2, 3, width_0, height_0), child_0_0.rect_outer) self.assertEqual(Panel.Rect(2, 8",
"= row_sizings_by_type.get(sizing[0], list()) group.append((row, sizing)) row_sizings_by_type[sizing[0]] = group # Determine column widths and",
"Rect(1, 1, 9, 9), True), ] for rect_left, rect_right, empty in scenarios: with",
"child_0_1 = create_child(Rect(0, 1, 1, 1)) child_1_0 = create_child(Rect(1, 0, 1, 1)) child_1_1",
"self.spacing panel.rect_outer = Panel.Rect(x, y, width, height) class GridLayoutTest(unittest.TestCase): def setUp(self): from desky.gui",
"panel spans multiple columns, determine the height as a # proportional amount. return",
"calculate_even_sizes(sizings_by_type, sizes, remaining_size): size = int(remaining_size / len(sizings_by_type.get(self.EVEN, [1]))) for sizing_tuple in sizings_by_type.get(self.EVEN,",
"as a # proportional amount. return int((panel.rect_outer.w - (rect.w - 1) * self.spacing)",
"grid.tallest_child_in_row(3)) self.assertEqual(20, grid.tallest_child_in_row(4)) def test_area_empty(self): scenarios = [ (Rect(2, 0, 4, 2), Rect(1,",
"def calculate_height(rect_panel_tuple): rect, panel = rect_panel_tuple # In case a panel spans multiple",
"2, 41, 101, 93), child_0_1.rect_outer) self.assertEqual(Panel.Rect(108, 41, 58, 93), child_1_1.rect_outer) def test_multiple_fixed_2(self): grid",
"for sizing_tuple in sizings_by_type.get(self.EVEN, []): column_or_row, _ = sizing_tuple amount = min(extra, 1)",
"def set_fill_row_sizing(self, row): self.row_sizings[row] = (self.FILL,) def widest_child_in_column(self, column): column_rect = Rect(column, 0,",
"4) for row in range(0, grid.row_count): for column in range(0, grid.column_count): child =",
"class GridLayout: FIXED = 0 CHILD = 1 PERCENTAGE = 2 CUSTOM =",
"grid.add(child, 0, 0) grid.layout(self.parent) self.assertEqual(Panel.Rect(13, 19, 175, 274), child.rect) def test_multiple_even(self): grid =",
"list()) group.append((column, sizing)) column_sizings_by_type[sizing[0]] = group for row in range(self.row_count): sizing = self.row_sizings.get(row,",
"+= amount extra -= amount return extra extra_width = allocate_extra_custom(column_sizings_by_type, column_widths, extra_width) extra_height",
"= 3 EVEN = 4 FILL = 5 def __init__(self, *, column_count =",
"allocate_extra_custom(sizings_by_type, sizes, extra): for sizing_tuple in sizings_by_type.get(self.CUSTOM, []): column_or_row, sizing = sizing_tuple amount",
"column in range(grid.column_count): grid.set_child_column_sizing(column) for row in range(grid.row_count): grid.set_child_row_sizing(row) self.assertEqual(0, grid.widest_child_in_column(2)) self.assertEqual(0, grid.tallest_child_in_row(2))",
"row) grid.layout(panel) def main(): from desky.gui import example #example(grid_example) unittest.main() if __name__ ==",
"filter( lambda rect_panel_tuple: rect_panel_tuple[0].intersects(row_rect), self.panels.items())) def calculate_height(rect_panel_tuple): rect, panel = rect_panel_tuple # In",
"remove_panels: for panel in self.panels.values(): panel.remove() self.panels = dict() def area_empty(self, rect): for",
"Panel.Rect(x, y, width, height) class GridLayoutTest(unittest.TestCase): def setUp(self): from desky.gui import Gui self.gui",
"self.assertEqual(Panel.Rect(87, 3, 73, 89), child_1_0.rect_outer) self.assertEqual(Panel.Rect( 2, 97, 80, 80), child_0_1.rect_outer) self.assertEqual(Panel.Rect(87, 97,",
"test_area_empty(self): scenarios = [ (Rect(2, 0, 4, 2), Rect(1, 1, 9, 9), False),",
"| Maximum extra width allocation # -------------------------------------------------------------- # | Fixed (200 px) |",
"= create_grid() child = self.gui.create(Panel) child.size = (66, 38) grid.add_rect(child, Rect(2, 1, 3,",
"remaining space evenly between # themselves. Fill evaluates last and will take the",
"row_count=5, spacing=3) for column in range(grid.column_count): grid.set_child_column_sizing(column) for row in range(grid.row_count): grid.set_child_row_sizing(row) self.assertEqual(0,",
"grid.layout(self.parent) self.assertEqual(Panel.Rect( 2, 3, 80, 89), child_0_0.rect_outer) self.assertEqual(Panel.Rect(87, 3, 73, 89), child_1_0.rect_outer) self.assertEqual(Panel.Rect(",
"= (self.FILL,) def widest_child_in_column(self, column): column_rect = Rect(column, 0, 1, self.row_count) rect_panel_tuples_that_intersect_column =",
"area_empty(self, rect): for rect_other in self.panels.keys(): if rect.intersects(rect_other): return False return True def",
"of sizing | Maximum extra width allocation # -------------------------------------------------------------- # | Fixed (200",
"sizing_tuple amount = min(extra, 1) sizes[column_or_row] += amount extra -= amount return extra",
"= (11, 16, 8, 2) child.size = size grid.add_rect(child, rect) return child child_0_0",
"GridLayout(column_count=20, row_count=20, spacing=5) grid.add_rect(self.gui.create(Panel), rect_left) self.assertEqual(empty, grid.area_empty(rect_right)) def test_single_fixed(self): grid = GridLayout(spacing=5) grid.set_fixed_column_sizing(0,",
"= gui.create(Panel) panel.rect = (50, 50, 500, 500) panel.padding = (8, 16, 24,",
"range(0, grid.column_count): child = gui.create(Panel) child.parent = panel grid.add(child, column, row) grid.layout(panel) def",
"sizing types while preserving the order. for column in range(self.column_count): sizing = self.column_sizings.get(column,",
"81) grid.add(child, 0, 0) grid.layout(self.parent) self.assertEqual(Panel.Rect(13, 19, 175, 274), child.rect) def test_multiple_fill(self): grid",
"child_1_1 = create_child(Rect(1, 1, 1, 1)) grid.layout(self.parent) width_0 = int(189 * 0.5) +",
"80, 80), child_0_1.rect_outer) self.assertEqual(Panel.Rect(87, 97, 73, 80), child_1_1.rect_outer) def test_multiple_child_2(self): grid = GridLayout(column_count=2,",
"multiple columns, determine the height as a # proportional amount. return int((panel.rect_outer.w -",
"sizing = sizing_tuple sizes[column_or_row] = int(area_size * sizing[1]) calculate_percentage_sizes(column_sizings_by_type, column_widths, area.w) calculate_percentage_sizes(row_sizings_by_type, row_heights,",
"8, 2) child.size = (9999, 9999) grid.add_rect(child, rect) return child child_0_0 = create_child(Rect(0,",
"and row heights. column_widths = [0 for _ in range(self.column_count)] row_heights = [0",
">= 0) assert(rect.y >= 0) assert(rect.right <= self.column_count) assert(rect.bottom <= self.row_count) assert(self.area_empty(rect)) self.panels[rect.frozen_copy()]",
"row_sizings_by_type[sizing[0]] = group # Determine column widths and row heights. column_widths = [0",
"= int(custom_sizing_2(287, None)) + 1 height_1 = int(custom_sizing_1(287, None)) self.assertEqual(Panel.Rect(2, 3, width_0, height_0),",
"+ height_0, width_1, height_1), child_1_1.rect_outer) def test_single_even(self): # Since even sizing is the",
"assert(rect.right <= self.column_count) assert(rect.bottom <= self.row_count) assert(self.area_empty(rect)) self.panels[rect.frozen_copy()] = panel def remove(self, panel):",
"extra_height) def allocate_extra_even(sizings_by_type, sizes, extra): for sizing_tuple in sizings_by_type.get(self.EVEN, []): column_or_row, _ =",
"sum(column_widths), 0) extra_height = max(area.h - sum(row_heights), 0) def allocate_extra_percentage(sizings_by_type, sizes, extra): for",
"extra_width) extra_height = allocate_extra_even(row_sizings_by_type, row_heights, extra_height) # Save column widths and row heights",
"custom_sizing, custom_extra) child = self.gui.create(Panel) child.parent = self.parent child.padding = (10, 8, 6,",
"self.panels = dict() self.column_sizings = dict() self.row_sizings = dict() self.column_count = column_count self.row_count",
"= sizing_tuple sizes[column_or_row] = largest_func(column_or_row) calculate_child_sizes(column_sizings_by_type, column_widths, self.widest_child_in_column) calculate_child_sizes(row_sizings_by_type, row_heights, self.tallest_child_in_row) def calculate_percentage_sizes(sizings_by_type,",
"0px # | Percentage (30% of width) | 1px # | Custom (custom",
"height_0), child_0_0.rect_outer) self.assertEqual(Panel.Rect(2, 8 + height_0, width_0, height_1), child_0_1.rect_outer) self.assertEqual(Panel.Rect(7 + width_0, 3,",
"in range(self.row_count)] def calculate_fixed_sizes(sizings_by_type, sizes): for sizing_tuple in sizings_by_type.get(self.FIXED, []): column_or_row, sizing =",
"column_rect = Rect(column, 0, 1, self.row_count) rect_panel_tuples_that_intersect_column = list( filter( lambda rect_panel_tuple: rect_panel_tuple[0].intersects(column_rect),",
"remove(self, panel): self.panels = valfilter(lambda p: p != panel, self.panels) def clear(self, *,",
"38) grid.add_rect(child, Rect(2, 1, 3, 2)) self.assertEqual(20, grid.widest_child_in_column(2)) self.assertEqual(20, grid.widest_child_in_column(3)) self.assertEqual(20, grid.widest_child_in_column(4)) with",
"self.assertEqual(Panel.Rect(108, 8, 19, 93), child_1_1.rect_outer) def test_single_child(self): grid = GridLayout(spacing=5) grid.set_child_column_sizing(0) grid.set_child_row_sizing(0) child",
"- area_size ** 0.8 grid = GridLayout(column_count=2, row_count=2, spacing=5) grid.set_custom_column_sizing(0, custom_sizing_1, partial(min, 1))",
"1px # | Fill (use remaining space) | any # # The types",
"width) | 1px # | Custom (custom function) | configurable # | Even",
"child_1_1.rect_outer) def test_multiple_fixed_2(self): grid = GridLayout(column_count=2, row_count=2, spacing=5) grid.set_fixed_column_sizing(0, 101) grid.set_fixed_column_sizing(1, 0) grid.set_fixed_row_sizing(0,",
"16, 8, 2) child.size = (53, 81) grid.add(child, 0, 0) grid.layout(self.parent) width =",
"row_count)) def add_rect(self, panel, rect): assert(rect.x >= 0) assert(rect.y >= 0) assert(rect.right <=",
"row_heights, area.h) def calculate_custom_sizes(sizings_by_type, sizes, area_size, remaining_size): for sizing_tuple in sizings_by_type.get(self.CUSTOM, []): column_or_row,",
"rect.y * self.spacing width = sum(column_widths[rect.x:rect.right]) + (rect.w - 1) * self.spacing height",
"with self.subTest(default=default): grid = GridLayout(spacing=5) if not default: grid.set_even_column_sizing(0) grid.set_even_row_sizing(0) child = self.gui.create(Panel)",
"101) grid.set_fixed_column_sizing(1, 0) grid.set_fixed_row_sizing(0, 0) grid.set_fixed_row_sizing(1, 93) def create_child(rect): child = self.gui.create(Panel) child.parent",
"1, 1), (25, 71)) child_0_1 = create_child(Rect(0, 1, 1, 1), (61, 62)) child_1_1",
"sum(column_widths[:rect.x]) + rect.x * self.spacing y = area.y + sum(row_heights[:rect.y]) + rect.y *",
"2) child.size = (9999, 9999) grid.add_rect(child, rect) return child child_0_0 = create_child(Rect(0, 0,",
"between # themselves. Fill evaluates last and will take the remaining space. #",
"2), (25, 87)) grid.layout(self.parent) self.assertEqual(Panel.Rect( 2, 3, 80, 50), child_0_0.rect_outer) self.assertEqual(Panel.Rect( 2, 58,",
"0) def tallest_child_in_row(self, row): row_rect = Rect(0, row, self.column_count, 1) rect_panel_tuples_that_intersect_row = list(",
"row_count=1): self.add_rect(panel, Rect(column, row, column_count, row_count)) def add_rect(self, panel, rect): assert(rect.x >= 0)",
"extra width and height to columns and rows. extra_width = max(area.w - sum(column_widths),",
"80, 50), child_0_0.rect_outer) self.assertEqual(Panel.Rect( 2, 58, 80, 50), child_0_1.rect_outer) self.assertEqual(Panel.Rect(87, 3, 44, 105),",
"group.append((row, sizing)) row_sizings_by_type[sizing[0]] = group # Determine column widths and row heights. column_widths",
"+ width_0, 8 + height_0, width_1, height_1), child_1_1.rect_outer) def grid_example(gui): panel = gui.create(Panel)",
"= 1, spacing = 0): self.panels = dict() self.column_sizings = dict() self.row_sizings =",
"evaluates last and will take the remaining space. # # If the resulting",
"def set_child_column_sizing(self, column): self.column_sizings[column] = (self.CHILD,) def set_child_row_sizing(self, row): self.row_sizings[row] = (self.CHILD,) def",
"extra extra_width = allocate_extra_custom(column_sizings_by_type, column_widths, extra_width) extra_height = allocate_extra_custom(row_sizings_by_type, row_heights, extra_height) def allocate_extra_even(sizings_by_type,",
"3, 44, 105), child_1_0.rect_outer) def test_single_percentage(self): grid = GridLayout(spacing=5) grid.set_percentage_column_sizing(0, 0.333) grid.set_percentage_row_sizing(0, 0.8)",
"self.spacing) / rect.w) return reduce(max, map(calculate_width, rect_panel_tuples_that_intersect_column), 0) def tallest_child_in_row(self, row): row_rect =",
"int(self.parent.rect_inner.w * 0.333) - 19 + 1 height = int(self.parent.rect_inner.h * 0.8) -",
"0 class GridLayout: FIXED = 0 CHILD = 1 PERCENTAGE = 2 CUSTOM",
"_ in range(self.row_count)] def calculate_fixed_sizes(sizings_by_type, sizes): for sizing_tuple in sizings_by_type.get(self.FIXED, []): column_or_row, sizing",
"y, width, height) class GridLayoutTest(unittest.TestCase): def setUp(self): from desky.gui import Gui self.gui =",
"the remaining space. # # If the resulting layout exceeds the bounds of",
"when we don't excplicitly set the columns and rows to even sizing. for",
"False), (Rect(10, 2, 4, 4), Rect(1, 1, 9, 9), True), ] for rect_left,",
"def create_child(rect): child = self.gui.create(Panel) child.parent = self.parent child.padding = (10, 8, 6,",
"grid.add(child, 0, 0) grid.layout(self.parent) self.assertEqual(Panel.Rect(13, 19, 71, 102), child.rect) def test_multiple_fixed_1(self): grid =",
"area.x + sum(column_widths[:rect.x]) + rect.x * self.spacing y = area.y + sum(row_heights[:rect.y]) +",
"create_child(Rect(1, 0, 1, 1)) child_1_1 = create_child(Rect(1, 1, 1, 1)) grid.layout(self.parent) width_0 =",
"0.8139) def create_child(rect): child = self.gui.create(Panel) child.parent = self.parent child.padding = (10, 8,",
"panel def remove(self, panel): self.panels = valfilter(lambda p: p != panel, self.panels) def",
"column widths and row heights for users to access. self.column_widths = column_widths self.row_heights",
"create_child(Rect(1, 1, 1, 1)) grid.layout(self.parent) width_0 = int(189 * 0.3333) width_1 = 189",
"def test_multiple_fill(self): grid = GridLayout(column_count=2, row_count=2, spacing=5) grid.set_percentage_column_sizing(0, 0.3333) grid.set_fill_column_sizing(1) grid.set_fill_row_sizing(0) grid.set_fixed_row_sizing(1, 100)",
"0) grid.layout(self.parent) root_width = int(194 ** 0.5) root_height = int(292 ** 0.5) final_width",
"* self.spacing y = area.y + sum(row_heights[:rect.y]) + rect.y * self.spacing width =",
"partial(min, 1)) def create_child(rect): child = self.gui.create(Panel) child.parent = self.parent child.padding = (10,",
"= rect_panel_tuple # In case a panel spans multiple rows, determine the height",
"for sizing_tuple in sizings_by_type.get(self.PERCENTAGE, []): column_or_row, _ = sizing_tuple amount = min(extra, 1)",
"child_1_0.rect_outer) self.assertEqual(Panel.Rect( 2, 41, 101, 93), child_0_1.rect_outer) self.assertEqual(Panel.Rect(108, 41, 58, 93), child_1_1.rect_outer) def",
"sizes[column_or_row] += amount extra -= amount return extra extra_width = allocate_extra_custom(column_sizings_by_type, column_widths, extra_width)",
"size) def set_fixed_row_sizing(self, row, size): self.row_sizings[row] = (self.FIXED, size) def set_child_column_sizing(self, column): self.column_sizings[column]",
"(use remaining space) | any # # The types of sizing in the",
"set_even_row_sizing(self, row): self.row_sizings[row] = (self.EVEN,) def set_fill_column_sizing(self, column): self.column_sizings[column] = (self.FILL,) def set_fill_row_sizing(self,",
"allocate_extra_custom(column_sizings_by_type, column_widths, extra_width) extra_height = allocate_extra_custom(row_sizings_by_type, row_heights, extra_height) def allocate_extra_even(sizings_by_type, sizes, extra): for",
"test_tallest_child_in_column_or_row_1(self): grid = GridLayout(column_count=5, row_count=5, spacing=3) for column in range(grid.column_count): grid.set_child_column_sizing(column) for row",
"[]): column_or_row, _ = sizing_tuple sizes[column_or_row] = size calculate_even_sizes( column_sizings_by_type, column_widths, area.w -",
"sizes, extra): for sizing_tuple in sizings_by_type.get(self.PERCENTAGE, []): column_or_row, _ = sizing_tuple amount =",
"175, 274), child.rect) def test_multiple_even(self): grid = GridLayout(column_count=2, row_count=2, spacing=5) grid.set_even_column_sizing(0) grid.set_even_column_sizing(1) grid.set_even_row_sizing(0)",
"child = self.gui.create(Panel) child.size = (66, 38) grid.add_rect(child, Rect(2, 1, 3, 2)) self.assertEqual(20,",
"0, 0) grid.layout(self.parent) self.assertEqual(Panel.Rect(13, 19, 53, 81), child.rect) def test_multiple_child_1(self): grid = GridLayout(column_count=2,",
"grid.layout(panel) def main(): from desky.gui import example #example(grid_example) unittest.main() if __name__ == \"__main__\":",
"(True, False): with self.subTest(default=default): grid = GridLayout(spacing=5) if not default: grid.set_even_column_sizing(0) grid.set_even_row_sizing(0) child",
"4) child.margins = (11, 16, 8, 2) child.size = (53, 81) grid.add(child, 0,",
"panels. for rect, panel in self.panels.items(): x = area.x + sum(column_widths[:rect.x]) + rect.x",
"in sizings_by_type.get(self.CUSTOM, []): column_or_row, sizing = sizing_tuple amount = int(sizing[2](extra)) sizes[column_or_row] += amount",
"= self.gui.create(Panel) self.parent.size = (200, 300) self.parent.padding = (2, 3, 4, 5) self.parent.margins",
"self.spacing y = area.y + sum(row_heights[:rect.y]) + rect.y * self.spacing width = sum(column_widths[rect.x:rect.right])",
"height_0, width_0, height_1), child_0_1.rect_outer) self.assertEqual(Panel.Rect(7 + width_0, 3, width_1, height_0), child_1_0.rect_outer) self.assertEqual(Panel.Rect(7 +",
"0.5) height_0 = int(287 * 0.5) + 1 height_1 = int(287 * 0.5)",
"= column_widths self.row_heights = row_heights # Position child panels. for rect, panel in",
"column_widths, extra_width) extra_height = allocate_extra_even(row_sizings_by_type, row_heights, extra_height) # Save column widths and row",
"a panel spans multiple rows, determine the height as a # proportional amount.",
"self.panels[rect.frozen_copy()] = panel def remove(self, panel): self.panels = valfilter(lambda p: p != panel,",
"extra_func) def set_even_column_sizing(self, column): self.column_sizings[column] = (self.EVEN,) def set_even_row_sizing(self, row): self.row_sizings[row] = (self.EVEN,)",
"area_size, remaining_size): for sizing_tuple in sizings_by_type.get(self.CUSTOM, []): column_or_row, sizing = sizing_tuple sizes[column_or_row] =",
"int(287 * 0.5) + 1 height_1 = int(287 * 0.5) self.assertEqual(Panel.Rect(2, 3, width_0,",
"rect_panel_tuples_that_intersect_column), 0) def tallest_child_in_row(self, row): row_rect = Rect(0, row, self.column_count, 1) rect_panel_tuples_that_intersect_row =",
"row_count=2, spacing=5) grid.set_percentage_column_sizing(0, 0.3333) grid.set_fill_column_sizing(1) grid.set_fill_row_sizing(0) grid.set_fixed_row_sizing(1, 100) def create_child(rect): child = self.gui.create(Panel)",
"list()) group.append((row, sizing)) row_sizings_by_type[sizing[0]] = group # Determine column widths and row heights.",
"self.spacing width = sum(column_widths[rect.x:rect.right]) + (rect.w - 1) * self.spacing height = sum(row_heights[rect.y:rect.bottom])",
"* 0.5) + 1 height_1 = int(287 * 0.5) self.assertEqual(Panel.Rect(2, 3, width_0, height_0),",
"(58, 31)) child_0_1 = create_child(Rect(0, 1, 1, 1), (61, 31)) child_1_0 = create_child(Rect(1,",
"min(extra, 1) sizes[column_or_row] += amount extra -= amount return extra extra_width = allocate_extra_percentage(column_sizings_by_type,",
"= (53, 81) grid.add(child, 0, 0) grid.layout(self.parent) width = int(self.parent.rect_inner.w * 0.333) -",
"= gui.create(Panel) child.parent = panel grid.add(child, column, row) grid.layout(panel) def main(): from desky.gui",
"(self.PERCENTAGE, percentage) def set_custom_column_sizing(self, column, sizing_func, extra_func=zero_func): self.column_sizings[column] = (self.CUSTOM, sizing_func, extra_func) def",
"self.column_widths = column_widths self.row_heights = row_heights # Position child panels. for rect, panel",
"child child_0_0 = create_child(Rect(0, 0, 1, 1)) child_1_0 = create_child(Rect(1, 0, 1, 1))",
"24, 32) grid = GridLayout(column_count = 3, row_count = 4, spacing = 4)",
"remaining_size)) calculate_custom_sizes(column_sizings_by_type, column_widths, area.w, area.w - sum(column_widths)) calculate_custom_sizes(row_sizings_by_type, row_heights, area.h, area.h - sum(row_heights))",
"grid.widest_child_in_column(2)) self.assertEqual(0, grid.tallest_child_in_row(2)) def test_tallest_child_in_column_or_row_2(self): def create_grid(): grid = GridLayout(column_count=5, row_count=5, spacing=3) for",
"in sizings_by_type.get(self.FIXED, []): column_or_row, sizing = sizing_tuple sizes[column_or_row] = sizing[1] calculate_fixed_sizes(column_sizings_by_type, column_widths) calculate_fixed_sizes(row_sizings_by_type,",
"height_0), child_1_0.rect_outer) self.assertEqual(Panel.Rect(7 + width_0, 8 + height_0, width_1, height_1), child_1_1.rect_outer) def test_single_even(self):",
"1) * self.spacing panel.rect_outer = Panel.Rect(x, y, width, height) class GridLayoutTest(unittest.TestCase): def setUp(self):",
"return int((panel.rect_outer.h - (rect.h - 1) * self.spacing) / rect.h) return reduce(max, map(calculate_height,",
"width_1 = int(custom_sizing_2(189, None)) height_0 = int(custom_sizing_2(287, None)) + 1 height_1 = int(custom_sizing_1(287,",
"spacing def add(self, panel, column, row, column_count=1, row_count=1): self.add_rect(panel, Rect(column, row, column_count, row_count))",
"58, 33), child_1_0.rect_outer) self.assertEqual(Panel.Rect( 2, 41, 101, 93), child_0_1.rect_outer) self.assertEqual(Panel.Rect(108, 41, 58, 93),",
"GridLayout: FIXED = 0 CHILD = 1 PERCENTAGE = 2 CUSTOM = 3",
"1)) child_0_1 = create_child(Rect(0, 1, 1, 1)) child_1_0 = create_child(Rect(1, 0, 1, 1))",
"4) child.margins = (11, 16, 8, 2) child.size = size grid.add_rect(child, rect) return",
"= int(self.parent.rect_inner.w * 0.333) - 19 + 1 height = int(self.parent.rect_inner.h * 0.8)",
"self.subTest(rect_left=rect_left, rect_right=rect_right, empty=empty): grid = GridLayout(column_count=20, row_count=20, spacing=5) grid.add_rect(self.gui.create(Panel), rect_left) self.assertEqual(empty, grid.area_empty(rect_right)) def",
"93), child_0_1.rect_outer) self.assertEqual(Panel.Rect(108, 8, 19, 93), child_1_1.rect_outer) def test_single_child(self): grid = GridLayout(spacing=5) grid.set_child_column_sizing(0)",
"column_widths[fill_columns[0][0]] = area.w - sum(column_widths) fill_rows = row_sizings_by_type.get(self.FILL, []) if fill_rows: row_heights[fill_rows[0][0]] =",
"test_multiple_child_1(self): grid = GridLayout(column_count=2, row_count=2, spacing=5) grid.set_child_column_sizing(0) grid.set_child_column_sizing(1) grid.set_child_row_sizing(0) grid.set_child_row_sizing(1) def create_child(rect, size):",
"lambda rect_panel_tuple: rect_panel_tuple[0].intersects(column_rect), self.panels.items())) def calculate_width(rect_panel_tuple): rect, panel = rect_panel_tuple # In case",
"child_1_1 = create_child(Rect(1, 1, 1, 1)) grid.layout(self.parent) self.assertEqual(Panel.Rect( 2, 3, 101, 18), child_0_0.rect_outer)",
"1)) grid.set_custom_row_sizing(0, custom_sizing_2, partial(min, 1)) grid.set_custom_row_sizing(1, custom_sizing_1, partial(min, 1)) def create_child(rect): child =",
"width_0, height_0), child_0_0.rect_outer) self.assertEqual(Panel.Rect(2, 8 + height_0, width_0, height_1), child_0_1.rect_outer) self.assertEqual(Panel.Rect(7 + width_0,",
"def create_grid(): grid = GridLayout(column_count=5, row_count=5, spacing=3) for column in range(grid.column_count): grid.set_child_column_sizing(column) for",
"def set_custom_column_sizing(self, column, sizing_func, extra_func=zero_func): self.column_sizings[column] = (self.CUSTOM, sizing_func, extra_func) def set_custom_row_sizing(self, row,",
"types while preserving the order. for column in range(self.column_count): sizing = self.column_sizings.get(column, (self.EVEN,))",
"(53, 81) grid.add(child, 0, 0) grid.layout(self.parent) self.assertEqual(Panel.Rect(13, 19, 53, 81), child.rect) def test_multiple_child_1(self):",
"Rect(1, 2, 2, 3)) self.assertEqual(20, grid.tallest_child_in_row(2)) self.assertEqual(20, grid.tallest_child_in_row(3)) self.assertEqual(20, grid.tallest_child_in_row(4)) def test_area_empty(self): scenarios",
"0, 0) grid.layout(self.parent) self.assertEqual(Panel.Rect(13, 19, 175, 274), child.rect) def test_multiple_fill(self): grid = GridLayout(column_count=2,"
] |
[
"for fundamental operations related to numerical representations of genomic sequences.\", author=\"<NAME>\", author_email=\"<EMAIL>\", url=\"https://github.com/ednilsonlomazi/SeqrepC\",",
"setup, Extension def main(): setup(name=\"seqrepc\", version=\"beta1.0\", description=\"SeqrepC is a module for fundamental operations",
"import setup, Extension def main(): setup(name=\"seqrepc\", version=\"beta1.0\", description=\"SeqrepC is a module for fundamental",
"description=\"SeqrepC is a module for fundamental operations related to numerical representations of genomic",
"def main(): setup(name=\"seqrepc\", version=\"beta1.0\", description=\"SeqrepC is a module for fundamental operations related to",
"to numerical representations of genomic sequences.\", author=\"<NAME>\", author_email=\"<EMAIL>\", url=\"https://github.com/ednilsonlomazi/SeqrepC\", license=\"BSD 3-Clause License\", ext_modules=[Extension(\"seqrepc\",",
"main(): setup(name=\"seqrepc\", version=\"beta1.0\", description=\"SeqrepC is a module for fundamental operations related to numerical",
"a module for fundamental operations related to numerical representations of genomic sequences.\", author=\"<NAME>\",",
"distutils.core import setup, Extension def main(): setup(name=\"seqrepc\", version=\"beta1.0\", description=\"SeqrepC is a module for",
"is a module for fundamental operations related to numerical representations of genomic sequences.\",",
"sequences.\", author=\"<NAME>\", author_email=\"<EMAIL>\", url=\"https://github.com/ednilsonlomazi/SeqrepC\", license=\"BSD 3-Clause License\", ext_modules=[Extension(\"seqrepc\", [\"./src/seqrepc.c\"])]) if __name__ == \"__main__\":",
"Extension def main(): setup(name=\"seqrepc\", version=\"beta1.0\", description=\"SeqrepC is a module for fundamental operations related",
"numerical representations of genomic sequences.\", author=\"<NAME>\", author_email=\"<EMAIL>\", url=\"https://github.com/ednilsonlomazi/SeqrepC\", license=\"BSD 3-Clause License\", ext_modules=[Extension(\"seqrepc\", [\"./src/seqrepc.c\"])])",
"from distutils.core import setup, Extension def main(): setup(name=\"seqrepc\", version=\"beta1.0\", description=\"SeqrepC is a module",
"of genomic sequences.\", author=\"<NAME>\", author_email=\"<EMAIL>\", url=\"https://github.com/ednilsonlomazi/SeqrepC\", license=\"BSD 3-Clause License\", ext_modules=[Extension(\"seqrepc\", [\"./src/seqrepc.c\"])]) if __name__",
"representations of genomic sequences.\", author=\"<NAME>\", author_email=\"<EMAIL>\", url=\"https://github.com/ednilsonlomazi/SeqrepC\", license=\"BSD 3-Clause License\", ext_modules=[Extension(\"seqrepc\", [\"./src/seqrepc.c\"])]) if",
"genomic sequences.\", author=\"<NAME>\", author_email=\"<EMAIL>\", url=\"https://github.com/ednilsonlomazi/SeqrepC\", license=\"BSD 3-Clause License\", ext_modules=[Extension(\"seqrepc\", [\"./src/seqrepc.c\"])]) if __name__ ==",
"setup(name=\"seqrepc\", version=\"beta1.0\", description=\"SeqrepC is a module for fundamental operations related to numerical representations",
"version=\"beta1.0\", description=\"SeqrepC is a module for fundamental operations related to numerical representations of",
"author=\"<NAME>\", author_email=\"<EMAIL>\", url=\"https://github.com/ednilsonlomazi/SeqrepC\", license=\"BSD 3-Clause License\", ext_modules=[Extension(\"seqrepc\", [\"./src/seqrepc.c\"])]) if __name__ == \"__main__\": main()",
"related to numerical representations of genomic sequences.\", author=\"<NAME>\", author_email=\"<EMAIL>\", url=\"https://github.com/ednilsonlomazi/SeqrepC\", license=\"BSD 3-Clause License\",",
"operations related to numerical representations of genomic sequences.\", author=\"<NAME>\", author_email=\"<EMAIL>\", url=\"https://github.com/ednilsonlomazi/SeqrepC\", license=\"BSD 3-Clause",
"fundamental operations related to numerical representations of genomic sequences.\", author=\"<NAME>\", author_email=\"<EMAIL>\", url=\"https://github.com/ednilsonlomazi/SeqrepC\", license=\"BSD",
"module for fundamental operations related to numerical representations of genomic sequences.\", author=\"<NAME>\", author_email=\"<EMAIL>\","
] |
[
"* 2 @lambda_solid(inputs=[InputDefinition('arg_a')]) def solid_c(arg_a): return arg_a * 3 @lambda_solid(inputs=[InputDefinition('arg_b'), InputDefinition('arg_c')]) def solid_d(arg_b,",
"dependencies={ 'solid_b': {'arg_a': DependencyDefinition('solid_a')}, 'solid_c': {'arg_a': DependencyDefinition('solid_a')}, 'solid_d': { 'arg_b': DependencyDefinition('solid_b'), 'arg_c': DependencyDefinition('solid_c'),",
"solid_c(arg_a): return arg_a * 3 @lambda_solid(inputs=[InputDefinition('arg_b'), InputDefinition('arg_c')]) def solid_d(arg_b, arg_c): return arg_b +",
"}, }, ) def define_single_solid_pipeline(): return PipelineDefinition( name='single_solid_pipeline', context_definitions=context_definitions, solids=[solid_a], dependencies={}, ) TEST_ENVIRONMENT",
"PipelineContextDefinition( context_fn=lambda _: ExecutionContext.console_logging(log_level=logging.DEBUG), resources={'dagma': define_dagma_resource()}, ) context_definitions = {'lambda': create_lambda_context()} @lambda_solid def",
"solid_a(): return 1 @lambda_solid(inputs=[InputDefinition('arg_a')]) def solid_b(arg_a): return arg_a * 2 @lambda_solid(inputs=[InputDefinition('arg_a')]) def solid_c(arg_a):",
"solid_c, solid_d], dependencies={ 'solid_b': {'arg_a': DependencyDefinition('solid_a')}, 'solid_c': {'arg_a': DependencyDefinition('solid_a')}, 'solid_d': { 'arg_b': DependencyDefinition('solid_b'),",
"arg_c]) # TODO: figure out how to deal with installing packages like numpy",
"logging import uuid from collections import namedtuple import boto3 # import numpy import",
"# return numpy.mean([arg_b, arg_c]) # TODO: figure out how to deal with installing",
"yield_pipeline_execution_context( pipeline, TEST_ENVIRONMENT, execution_metadata ) as context: execution_plan = create_execution_plan_core(context) return execute_plan(context, execution_plan)",
"import dagster.check as check import dagster.core.types as types from dagster import ( DependencyDefinition,",
"lambda engine. Issue #491') def test_execution_diamond(): pipeline = define_diamond_dag_pipeline() results = run_test_pipeline(pipeline) assert",
"context_definitions = {'lambda': create_lambda_context()} @lambda_solid def solid_a(): return 1 @lambda_solid(inputs=[InputDefinition('arg_a')]) def solid_b(arg_a): return",
"# TODO: figure out how to deal with installing packages like numpy where",
"def test_execution_single(): pipeline = define_single_solid_pipeline() results = run_test_pipeline(pipeline) assert len(results) == 1 assert",
"return arg_a * 2 @lambda_solid(inputs=[InputDefinition('arg_a')]) def solid_c(arg_a): return arg_a * 3 @lambda_solid(inputs=[InputDefinition('arg_b'), InputDefinition('arg_c')])",
"return PipelineDefinition( name='actual_dag_pipeline', context_definitions=context_definitions, solids=[solid_a, solid_b, solid_c, solid_d], dependencies={ 'solid_b': {'arg_a': DependencyDefinition('solid_a')}, 'solid_c':",
"assert len(results) == 1 assert results[('solid_a.transform', 'result')][0] is True assert results[('solid_a.transform', 'result')][1].output_name ==",
"= ExecutionMetadata(run_id=str(uuid.uuid4())) with yield_pipeline_execution_context( pipeline, TEST_ENVIRONMENT, execution_metadata ) as context: execution_plan = create_execution_plan_core(context)",
"from dagster.core.execution import ( create_execution_plan_core, create_environment_config, yield_pipeline_execution_context, ) from dagma import execute_plan, define_dagma_resource",
"# architecture on lambda is not the architecture running the pipeline def define_diamond_dag_pipeline():",
"{ 'arg_b': DependencyDefinition('solid_b'), 'arg_c': DependencyDefinition('solid_c'), }, }, ) def define_single_solid_pipeline(): return PipelineDefinition( name='single_solid_pipeline',",
"define_single_solid_pipeline() results = run_test_pipeline(pipeline) assert len(results) == 1 assert results[('solid_a.transform', 'result')][0] is True",
"solid_b, solid_c, solid_d], dependencies={ 'solid_b': {'arg_a': DependencyDefinition('solid_a')}, 'solid_c': {'arg_a': DependencyDefinition('solid_a')}, 'solid_d': { 'arg_b':",
"in lambda engine. Issue #491') def test_execution_single(): pipeline = define_single_solid_pipeline() results = run_test_pipeline(pipeline)",
"lambda is not the architecture running the pipeline def define_diamond_dag_pipeline(): return PipelineDefinition( name='actual_dag_pipeline',",
"pending pickling issues in lambda engine. Issue #491') def test_execution_diamond(): pipeline = define_diamond_dag_pipeline()",
"test_execution_single(): pipeline = define_single_solid_pipeline() results = run_test_pipeline(pipeline) assert len(results) == 1 assert results[('solid_a.transform',",
"create_execution_plan_core, create_environment_config, yield_pipeline_execution_context, ) from dagma import execute_plan, define_dagma_resource def create_lambda_context(): return PipelineContextDefinition(",
"define_dagma_resource()}, ) context_definitions = {'lambda': create_lambda_context()} @lambda_solid def solid_a(): return 1 @lambda_solid(inputs=[InputDefinition('arg_a')]) def",
"1 assert results[('solid_a.transform', 'result')][0] is True assert results[('solid_a.transform', 'result')][1].output_name == 'result' assert results[('solid_a.transform',",
"DependencyDefinition('solid_a')}, 'solid_c': {'arg_a': DependencyDefinition('solid_a')}, 'solid_d': { 'arg_b': DependencyDefinition('solid_b'), 'arg_c': DependencyDefinition('solid_c'), }, }, )",
"name='actual_dag_pipeline', context_definitions=context_definitions, solids=[solid_a, solid_b, solid_c, solid_d], dependencies={ 'solid_b': {'arg_a': DependencyDefinition('solid_a')}, 'solid_c': {'arg_a': DependencyDefinition('solid_a')},",
"'solid_c': {'arg_a': DependencyDefinition('solid_a')}, 'solid_d': { 'arg_b': DependencyDefinition('solid_b'), 'arg_c': DependencyDefinition('solid_c'), }, }, ) def",
"import boto3 # import numpy import pytest import dagster.check as check import dagster.core.types",
"yield_pipeline_execution_context, ) from dagma import execute_plan, define_dagma_resource def create_lambda_context(): return PipelineContextDefinition( context_fn=lambda _:",
"boto3 # import numpy import pytest import dagster.check as check import dagster.core.types as",
"dagster.core.types as types from dagster import ( DependencyDefinition, ExecutionContext, InputDefinition, lambda_solid, PipelineContextDefinition, PipelineDefinition,",
"return arg_b + arg_c / 2.0 # return numpy.mean([arg_b, arg_c]) # TODO: figure",
"DependencyDefinition('solid_a')}, 'solid_d': { 'arg_b': DependencyDefinition('solid_b'), 'arg_c': DependencyDefinition('solid_c'), }, }, ) def define_single_solid_pipeline(): return",
"solids=[solid_a], dependencies={}, ) TEST_ENVIRONMENT = { 'context': {'lambda': {'resources': {'dagma': {'config': {'aws_region_name': 'us-east-2'}}}}}",
"packages like numpy where the target # architecture on lambda is not the",
"execute_plan(context, execution_plan) @pytest.mark.skip('Skipping pending pickling issues in lambda engine. Issue #491') def test_execution_diamond():",
"dependencies={}, ) TEST_ENVIRONMENT = { 'context': {'lambda': {'resources': {'dagma': {'config': {'aws_region_name': 'us-east-2'}}}}} }",
"return arg_a * 3 @lambda_solid(inputs=[InputDefinition('arg_b'), InputDefinition('arg_c')]) def solid_d(arg_b, arg_c): return arg_b + arg_c",
"len(results) == 4 @pytest.mark.skip('Skipping pending pickling issues in lambda engine. Issue #491') def",
"namedtuple import boto3 # import numpy import pytest import dagster.check as check import",
"execution_plan = create_execution_plan_core(context) return execute_plan(context, execution_plan) @pytest.mark.skip('Skipping pending pickling issues in lambda engine.",
"arg_b + arg_c / 2.0 # return numpy.mean([arg_b, arg_c]) # TODO: figure out",
"ExecutionMetadata(run_id=str(uuid.uuid4())) with yield_pipeline_execution_context( pipeline, TEST_ENVIRONMENT, execution_metadata ) as context: execution_plan = create_execution_plan_core(context) return",
"Issue #491') def test_execution_diamond(): pipeline = define_diamond_dag_pipeline() results = run_test_pipeline(pipeline) assert len(results) ==",
"collections import namedtuple import boto3 # import numpy import pytest import dagster.check as",
") from dagma import execute_plan, define_dagma_resource def create_lambda_context(): return PipelineContextDefinition( context_fn=lambda _: ExecutionContext.console_logging(log_level=logging.DEBUG),",
"@lambda_solid(inputs=[InputDefinition('arg_a')]) def solid_b(arg_a): return arg_a * 2 @lambda_solid(inputs=[InputDefinition('arg_a')]) def solid_c(arg_a): return arg_a *",
"solid_b(arg_a): return arg_a * 2 @lambda_solid(inputs=[InputDefinition('arg_a')]) def solid_c(arg_a): return arg_a * 3 @lambda_solid(inputs=[InputDefinition('arg_b'),",
"/ 2.0 # return numpy.mean([arg_b, arg_c]) # TODO: figure out how to deal",
"assert results[('solid_a.transform', 'result')][1].output_name == 'result' assert results[('solid_a.transform', 'result')][1].value == 1 assert results[('solid_a.transform', 'result')][2]",
"define_diamond_dag_pipeline(): return PipelineDefinition( name='actual_dag_pipeline', context_definitions=context_definitions, solids=[solid_a, solid_b, solid_c, solid_d], dependencies={ 'solid_b': {'arg_a': DependencyDefinition('solid_a')},",
"create_lambda_context()} @lambda_solid def solid_a(): return 1 @lambda_solid(inputs=[InputDefinition('arg_a')]) def solid_b(arg_a): return arg_a * 2",
"as context: execution_plan = create_execution_plan_core(context) return execute_plan(context, execution_plan) @pytest.mark.skip('Skipping pending pickling issues in",
"define_diamond_dag_pipeline() results = run_test_pipeline(pipeline) assert len(results) == 4 @pytest.mark.skip('Skipping pending pickling issues in",
"= run_test_pipeline(pipeline) assert len(results) == 4 @pytest.mark.skip('Skipping pending pickling issues in lambda engine.",
"'result')][1].output_name == 'result' assert results[('solid_a.transform', 'result')][1].value == 1 assert results[('solid_a.transform', 'result')][2] is None",
"results[('solid_a.transform', 'result')][0] is True assert results[('solid_a.transform', 'result')][1].output_name == 'result' assert results[('solid_a.transform', 'result')][1].value ==",
"import namedtuple import boto3 # import numpy import pytest import dagster.check as check",
"InputDefinition('arg_c')]) def solid_d(arg_b, arg_c): return arg_b + arg_c / 2.0 # return numpy.mean([arg_b,",
"arg_c / 2.0 # return numpy.mean([arg_b, arg_c]) # TODO: figure out how to",
"== 4 @pytest.mark.skip('Skipping pending pickling issues in lambda engine. Issue #491') def test_execution_single():",
"context_definitions=context_definitions, solids=[solid_a, solid_b, solid_c, solid_d], dependencies={ 'solid_b': {'arg_a': DependencyDefinition('solid_a')}, 'solid_c': {'arg_a': DependencyDefinition('solid_a')}, 'solid_d':",
"dagster.check as check import dagster.core.types as types from dagster import ( DependencyDefinition, ExecutionContext,",
"( DependencyDefinition, ExecutionContext, InputDefinition, lambda_solid, PipelineContextDefinition, PipelineDefinition, ExecutionMetadata, ResourceDefinition, ) from dagster.core.execution import",
"from dagma import execute_plan, define_dagma_resource def create_lambda_context(): return PipelineContextDefinition( context_fn=lambda _: ExecutionContext.console_logging(log_level=logging.DEBUG), resources={'dagma':",
"types from dagster import ( DependencyDefinition, ExecutionContext, InputDefinition, lambda_solid, PipelineContextDefinition, PipelineDefinition, ExecutionMetadata, ResourceDefinition,",
"execute_plan, define_dagma_resource def create_lambda_context(): return PipelineContextDefinition( context_fn=lambda _: ExecutionContext.console_logging(log_level=logging.DEBUG), resources={'dagma': define_dagma_resource()}, ) context_definitions",
"resources={'dagma': define_dagma_resource()}, ) context_definitions = {'lambda': create_lambda_context()} @lambda_solid def solid_a(): return 1 @lambda_solid(inputs=[InputDefinition('arg_a')])",
"numpy import pytest import dagster.check as check import dagster.core.types as types from dagster",
"@lambda_solid def solid_a(): return 1 @lambda_solid(inputs=[InputDefinition('arg_a')]) def solid_b(arg_a): return arg_a * 2 @lambda_solid(inputs=[InputDefinition('arg_a')])",
"results = run_test_pipeline(pipeline) assert len(results) == 4 @pytest.mark.skip('Skipping pending pickling issues in lambda",
"check import dagster.core.types as types from dagster import ( DependencyDefinition, ExecutionContext, InputDefinition, lambda_solid,",
"4 @pytest.mark.skip('Skipping pending pickling issues in lambda engine. Issue #491') def test_execution_single(): pipeline",
"= create_execution_plan_core(context) return execute_plan(context, execution_plan) @pytest.mark.skip('Skipping pending pickling issues in lambda engine. Issue",
"PipelineDefinition( name='single_solid_pipeline', context_definitions=context_definitions, solids=[solid_a], dependencies={}, ) TEST_ENVIRONMENT = { 'context': {'lambda': {'resources': {'dagma':",
") TEST_ENVIRONMENT = { 'context': {'lambda': {'resources': {'dagma': {'config': {'aws_region_name': 'us-east-2'}}}}} } def",
"results = run_test_pipeline(pipeline) assert len(results) == 1 assert results[('solid_a.transform', 'result')][0] is True assert",
"def define_single_solid_pipeline(): return PipelineDefinition( name='single_solid_pipeline', context_definitions=context_definitions, solids=[solid_a], dependencies={}, ) TEST_ENVIRONMENT = { 'context':",
"'solid_d': { 'arg_b': DependencyDefinition('solid_b'), 'arg_c': DependencyDefinition('solid_c'), }, }, ) def define_single_solid_pipeline(): return PipelineDefinition(",
"def run_test_pipeline(pipeline): execution_metadata = ExecutionMetadata(run_id=str(uuid.uuid4())) with yield_pipeline_execution_context( pipeline, TEST_ENVIRONMENT, execution_metadata ) as context:",
"PipelineContextDefinition, PipelineDefinition, ExecutionMetadata, ResourceDefinition, ) from dagster.core.execution import ( create_execution_plan_core, create_environment_config, yield_pipeline_execution_context, )",
"the architecture running the pipeline def define_diamond_dag_pipeline(): return PipelineDefinition( name='actual_dag_pipeline', context_definitions=context_definitions, solids=[solid_a, solid_b,",
"context_definitions=context_definitions, solids=[solid_a], dependencies={}, ) TEST_ENVIRONMENT = { 'context': {'lambda': {'resources': {'dagma': {'config': {'aws_region_name':",
"= define_single_solid_pipeline() results = run_test_pipeline(pipeline) assert len(results) == 1 assert results[('solid_a.transform', 'result')][0] is",
"DependencyDefinition, ExecutionContext, InputDefinition, lambda_solid, PipelineContextDefinition, PipelineDefinition, ExecutionMetadata, ResourceDefinition, ) from dagster.core.execution import (",
"return numpy.mean([arg_b, arg_c]) # TODO: figure out how to deal with installing packages",
"ResourceDefinition, ) from dagster.core.execution import ( create_execution_plan_core, create_environment_config, yield_pipeline_execution_context, ) from dagma import",
"#491') def test_execution_single(): pipeline = define_single_solid_pipeline() results = run_test_pipeline(pipeline) assert len(results) == 1",
"create_environment_config, yield_pipeline_execution_context, ) from dagma import execute_plan, define_dagma_resource def create_lambda_context(): return PipelineContextDefinition( context_fn=lambda",
"1 @lambda_solid(inputs=[InputDefinition('arg_a')]) def solid_b(arg_a): return arg_a * 2 @lambda_solid(inputs=[InputDefinition('arg_a')]) def solid_c(arg_a): return arg_a",
"True assert results[('solid_a.transform', 'result')][1].output_name == 'result' assert results[('solid_a.transform', 'result')][1].value == 1 assert results[('solid_a.transform',",
"def create_lambda_context(): return PipelineContextDefinition( context_fn=lambda _: ExecutionContext.console_logging(log_level=logging.DEBUG), resources={'dagma': define_dagma_resource()}, ) context_definitions = {'lambda':",
"target # architecture on lambda is not the architecture running the pipeline def",
"with yield_pipeline_execution_context( pipeline, TEST_ENVIRONMENT, execution_metadata ) as context: execution_plan = create_execution_plan_core(context) return execute_plan(context,",
"ExecutionContext, InputDefinition, lambda_solid, PipelineContextDefinition, PipelineDefinition, ExecutionMetadata, ResourceDefinition, ) from dagster.core.execution import ( create_execution_plan_core,",
"def define_diamond_dag_pipeline(): return PipelineDefinition( name='actual_dag_pipeline', context_definitions=context_definitions, solids=[solid_a, solid_b, solid_c, solid_d], dependencies={ 'solid_b': {'arg_a':",
"== 1 assert results[('solid_a.transform', 'result')][0] is True assert results[('solid_a.transform', 'result')][1].output_name == 'result' assert",
"deal with installing packages like numpy where the target # architecture on lambda",
"} def run_test_pipeline(pipeline): execution_metadata = ExecutionMetadata(run_id=str(uuid.uuid4())) with yield_pipeline_execution_context( pipeline, TEST_ENVIRONMENT, execution_metadata ) as",
"DependencyDefinition('solid_c'), }, }, ) def define_single_solid_pipeline(): return PipelineDefinition( name='single_solid_pipeline', context_definitions=context_definitions, solids=[solid_a], dependencies={}, )",
"'arg_c': DependencyDefinition('solid_c'), }, }, ) def define_single_solid_pipeline(): return PipelineDefinition( name='single_solid_pipeline', context_definitions=context_definitions, solids=[solid_a], dependencies={},",
"out how to deal with installing packages like numpy where the target #",
"lambda engine. Issue #491') def test_execution_single(): pipeline = define_single_solid_pipeline() results = run_test_pipeline(pipeline) assert",
"is True assert results[('solid_a.transform', 'result')][1].output_name == 'result' assert results[('solid_a.transform', 'result')][1].value == 1 assert",
"run_test_pipeline(pipeline) assert len(results) == 4 @pytest.mark.skip('Skipping pending pickling issues in lambda engine. Issue",
"assert len(results) == 4 @pytest.mark.skip('Skipping pending pickling issues in lambda engine. Issue #491')",
"run_test_pipeline(pipeline): execution_metadata = ExecutionMetadata(run_id=str(uuid.uuid4())) with yield_pipeline_execution_context( pipeline, TEST_ENVIRONMENT, execution_metadata ) as context: execution_plan",
"InputDefinition, lambda_solid, PipelineContextDefinition, PipelineDefinition, ExecutionMetadata, ResourceDefinition, ) from dagster.core.execution import ( create_execution_plan_core, create_environment_config,",
"import pytest import dagster.check as check import dagster.core.types as types from dagster import",
"{ 'context': {'lambda': {'resources': {'dagma': {'config': {'aws_region_name': 'us-east-2'}}}}} } def run_test_pipeline(pipeline): execution_metadata =",
"{'arg_a': DependencyDefinition('solid_a')}, 'solid_c': {'arg_a': DependencyDefinition('solid_a')}, 'solid_d': { 'arg_b': DependencyDefinition('solid_b'), 'arg_c': DependencyDefinition('solid_c'), }, },",
"not the architecture running the pipeline def define_diamond_dag_pipeline(): return PipelineDefinition( name='actual_dag_pipeline', context_definitions=context_definitions, solids=[solid_a,",
"PipelineDefinition( name='actual_dag_pipeline', context_definitions=context_definitions, solids=[solid_a, solid_b, solid_c, solid_d], dependencies={ 'solid_b': {'arg_a': DependencyDefinition('solid_a')}, 'solid_c': {'arg_a':",
"= run_test_pipeline(pipeline) assert len(results) == 1 assert results[('solid_a.transform', 'result')][0] is True assert results[('solid_a.transform',",
"{'aws_region_name': 'us-east-2'}}}}} } def run_test_pipeline(pipeline): execution_metadata = ExecutionMetadata(run_id=str(uuid.uuid4())) with yield_pipeline_execution_context( pipeline, TEST_ENVIRONMENT, execution_metadata",
"issues in lambda engine. Issue #491') def test_execution_diamond(): pipeline = define_diamond_dag_pipeline() results =",
"@lambda_solid(inputs=[InputDefinition('arg_a')]) def solid_c(arg_a): return arg_a * 3 @lambda_solid(inputs=[InputDefinition('arg_b'), InputDefinition('arg_c')]) def solid_d(arg_b, arg_c): return",
"running the pipeline def define_diamond_dag_pipeline(): return PipelineDefinition( name='actual_dag_pipeline', context_definitions=context_definitions, solids=[solid_a, solid_b, solid_c, solid_d],",
"the pipeline def define_diamond_dag_pipeline(): return PipelineDefinition( name='actual_dag_pipeline', context_definitions=context_definitions, solids=[solid_a, solid_b, solid_c, solid_d], dependencies={",
"TEST_ENVIRONMENT, execution_metadata ) as context: execution_plan = create_execution_plan_core(context) return execute_plan(context, execution_plan) @pytest.mark.skip('Skipping pending",
"numpy.mean([arg_b, arg_c]) # TODO: figure out how to deal with installing packages like",
"arg_a * 2 @lambda_solid(inputs=[InputDefinition('arg_a')]) def solid_c(arg_a): return arg_a * 3 @lambda_solid(inputs=[InputDefinition('arg_b'), InputDefinition('arg_c')]) def",
"@pytest.mark.skip('Skipping pending pickling issues in lambda engine. Issue #491') def test_execution_single(): pipeline =",
"from collections import namedtuple import boto3 # import numpy import pytest import dagster.check",
"pytest import dagster.check as check import dagster.core.types as types from dagster import (",
"pickling issues in lambda engine. Issue #491') def test_execution_single(): pipeline = define_single_solid_pipeline() results",
"* 3 @lambda_solid(inputs=[InputDefinition('arg_b'), InputDefinition('arg_c')]) def solid_d(arg_b, arg_c): return arg_b + arg_c / 2.0",
"TEST_ENVIRONMENT = { 'context': {'lambda': {'resources': {'dagma': {'config': {'aws_region_name': 'us-east-2'}}}}} } def run_test_pipeline(pipeline):",
"{'config': {'aws_region_name': 'us-east-2'}}}}} } def run_test_pipeline(pipeline): execution_metadata = ExecutionMetadata(run_id=str(uuid.uuid4())) with yield_pipeline_execution_context( pipeline, TEST_ENVIRONMENT,",
"arg_a * 3 @lambda_solid(inputs=[InputDefinition('arg_b'), InputDefinition('arg_c')]) def solid_d(arg_b, arg_c): return arg_b + arg_c /",
"def test_execution_diamond(): pipeline = define_diamond_dag_pipeline() results = run_test_pipeline(pipeline) assert len(results) == 4 @pytest.mark.skip('Skipping",
") from dagster.core.execution import ( create_execution_plan_core, create_environment_config, yield_pipeline_execution_context, ) from dagma import execute_plan,",
"Issue #491') def test_execution_single(): pipeline = define_single_solid_pipeline() results = run_test_pipeline(pipeline) assert len(results) ==",
"in lambda engine. Issue #491') def test_execution_diamond(): pipeline = define_diamond_dag_pipeline() results = run_test_pipeline(pipeline)",
"is not the architecture running the pipeline def define_diamond_dag_pipeline(): return PipelineDefinition( name='actual_dag_pipeline', context_definitions=context_definitions,",
"_: ExecutionContext.console_logging(log_level=logging.DEBUG), resources={'dagma': define_dagma_resource()}, ) context_definitions = {'lambda': create_lambda_context()} @lambda_solid def solid_a(): return",
"solid_d(arg_b, arg_c): return arg_b + arg_c / 2.0 # return numpy.mean([arg_b, arg_c]) #",
"pipeline def define_diamond_dag_pipeline(): return PipelineDefinition( name='actual_dag_pipeline', context_definitions=context_definitions, solids=[solid_a, solid_b, solid_c, solid_d], dependencies={ 'solid_b':",
"as types from dagster import ( DependencyDefinition, ExecutionContext, InputDefinition, lambda_solid, PipelineContextDefinition, PipelineDefinition, ExecutionMetadata,",
"assert results[('solid_a.transform', 'result')][0] is True assert results[('solid_a.transform', 'result')][1].output_name == 'result' assert results[('solid_a.transform', 'result')][1].value",
"arg_c): return arg_b + arg_c / 2.0 # return numpy.mean([arg_b, arg_c]) # TODO:",
"( create_execution_plan_core, create_environment_config, yield_pipeline_execution_context, ) from dagma import execute_plan, define_dagma_resource def create_lambda_context(): return",
"architecture running the pipeline def define_diamond_dag_pipeline(): return PipelineDefinition( name='actual_dag_pipeline', context_definitions=context_definitions, solids=[solid_a, solid_b, solid_c,",
"architecture on lambda is not the architecture running the pipeline def define_diamond_dag_pipeline(): return",
"results[('solid_a.transform', 'result')][1].output_name == 'result' assert results[('solid_a.transform', 'result')][1].value == 1 assert results[('solid_a.transform', 'result')][2] is",
"return execute_plan(context, execution_plan) @pytest.mark.skip('Skipping pending pickling issues in lambda engine. Issue #491') def",
"dagster import ( DependencyDefinition, ExecutionContext, InputDefinition, lambda_solid, PipelineContextDefinition, PipelineDefinition, ExecutionMetadata, ResourceDefinition, ) from",
"PipelineDefinition, ExecutionMetadata, ResourceDefinition, ) from dagster.core.execution import ( create_execution_plan_core, create_environment_config, yield_pipeline_execution_context, ) from",
"3 @lambda_solid(inputs=[InputDefinition('arg_b'), InputDefinition('arg_c')]) def solid_d(arg_b, arg_c): return arg_b + arg_c / 2.0 #",
"create_lambda_context(): return PipelineContextDefinition( context_fn=lambda _: ExecutionContext.console_logging(log_level=logging.DEBUG), resources={'dagma': define_dagma_resource()}, ) context_definitions = {'lambda': create_lambda_context()}",
"import execute_plan, define_dagma_resource def create_lambda_context(): return PipelineContextDefinition( context_fn=lambda _: ExecutionContext.console_logging(log_level=logging.DEBUG), resources={'dagma': define_dagma_resource()}, )",
"<filename>python_modules/dagma/dagma_tests/test_lambda_engine.py<gh_stars>0 import logging import uuid from collections import namedtuple import boto3 # import",
"ExecutionMetadata, ResourceDefinition, ) from dagster.core.execution import ( create_execution_plan_core, create_environment_config, yield_pipeline_execution_context, ) from dagma",
"{'lambda': {'resources': {'dagma': {'config': {'aws_region_name': 'us-east-2'}}}}} } def run_test_pipeline(pipeline): execution_metadata = ExecutionMetadata(run_id=str(uuid.uuid4())) with",
"= define_diamond_dag_pipeline() results = run_test_pipeline(pipeline) assert len(results) == 4 @pytest.mark.skip('Skipping pending pickling issues",
"# import numpy import pytest import dagster.check as check import dagster.core.types as types",
"len(results) == 1 assert results[('solid_a.transform', 'result')][0] is True assert results[('solid_a.transform', 'result')][1].output_name == 'result'",
"ExecutionContext.console_logging(log_level=logging.DEBUG), resources={'dagma': define_dagma_resource()}, ) context_definitions = {'lambda': create_lambda_context()} @lambda_solid def solid_a(): return 1",
"name='single_solid_pipeline', context_definitions=context_definitions, solids=[solid_a], dependencies={}, ) TEST_ENVIRONMENT = { 'context': {'lambda': {'resources': {'dagma': {'config':",
"installing packages like numpy where the target # architecture on lambda is not",
"import numpy import pytest import dagster.check as check import dagster.core.types as types from",
"{'arg_a': DependencyDefinition('solid_a')}, 'solid_d': { 'arg_b': DependencyDefinition('solid_b'), 'arg_c': DependencyDefinition('solid_c'), }, }, ) def define_single_solid_pipeline():",
"pending pickling issues in lambda engine. Issue #491') def test_execution_single(): pipeline = define_single_solid_pipeline()",
"pickling issues in lambda engine. Issue #491') def test_execution_diamond(): pipeline = define_diamond_dag_pipeline() results",
"solid_d], dependencies={ 'solid_b': {'arg_a': DependencyDefinition('solid_a')}, 'solid_c': {'arg_a': DependencyDefinition('solid_a')}, 'solid_d': { 'arg_b': DependencyDefinition('solid_b'), 'arg_c':",
"engine. Issue #491') def test_execution_diamond(): pipeline = define_diamond_dag_pipeline() results = run_test_pipeline(pipeline) assert len(results)",
"issues in lambda engine. Issue #491') def test_execution_single(): pipeline = define_single_solid_pipeline() results =",
"'context': {'lambda': {'resources': {'dagma': {'config': {'aws_region_name': 'us-east-2'}}}}} } def run_test_pipeline(pipeline): execution_metadata = ExecutionMetadata(run_id=str(uuid.uuid4()))",
"context: execution_plan = create_execution_plan_core(context) return execute_plan(context, execution_plan) @pytest.mark.skip('Skipping pending pickling issues in lambda",
"def solid_c(arg_a): return arg_a * 3 @lambda_solid(inputs=[InputDefinition('arg_b'), InputDefinition('arg_c')]) def solid_d(arg_b, arg_c): return arg_b",
"def solid_b(arg_a): return arg_a * 2 @lambda_solid(inputs=[InputDefinition('arg_a')]) def solid_c(arg_a): return arg_a * 3",
"test_execution_diamond(): pipeline = define_diamond_dag_pipeline() results = run_test_pipeline(pipeline) assert len(results) == 4 @pytest.mark.skip('Skipping pending",
"import ( create_execution_plan_core, create_environment_config, yield_pipeline_execution_context, ) from dagma import execute_plan, define_dagma_resource def create_lambda_context():",
"2 @lambda_solid(inputs=[InputDefinition('arg_a')]) def solid_c(arg_a): return arg_a * 3 @lambda_solid(inputs=[InputDefinition('arg_b'), InputDefinition('arg_c')]) def solid_d(arg_b, arg_c):",
") def define_single_solid_pipeline(): return PipelineDefinition( name='single_solid_pipeline', context_definitions=context_definitions, solids=[solid_a], dependencies={}, ) TEST_ENVIRONMENT = {",
"'solid_b': {'arg_a': DependencyDefinition('solid_a')}, 'solid_c': {'arg_a': DependencyDefinition('solid_a')}, 'solid_d': { 'arg_b': DependencyDefinition('solid_b'), 'arg_c': DependencyDefinition('solid_c'), },",
"import ( DependencyDefinition, ExecutionContext, InputDefinition, lambda_solid, PipelineContextDefinition, PipelineDefinition, ExecutionMetadata, ResourceDefinition, ) from dagster.core.execution",
"import logging import uuid from collections import namedtuple import boto3 # import numpy",
"to deal with installing packages like numpy where the target # architecture on",
"pipeline = define_single_solid_pipeline() results = run_test_pipeline(pipeline) assert len(results) == 1 assert results[('solid_a.transform', 'result')][0]",
"{'lambda': create_lambda_context()} @lambda_solid def solid_a(): return 1 @lambda_solid(inputs=[InputDefinition('arg_a')]) def solid_b(arg_a): return arg_a *",
"import uuid from collections import namedtuple import boto3 # import numpy import pytest",
"@lambda_solid(inputs=[InputDefinition('arg_b'), InputDefinition('arg_c')]) def solid_d(arg_b, arg_c): return arg_b + arg_c / 2.0 # return",
"2.0 # return numpy.mean([arg_b, arg_c]) # TODO: figure out how to deal with",
"define_single_solid_pipeline(): return PipelineDefinition( name='single_solid_pipeline', context_definitions=context_definitions, solids=[solid_a], dependencies={}, ) TEST_ENVIRONMENT = { 'context': {'lambda':",
"}, ) def define_single_solid_pipeline(): return PipelineDefinition( name='single_solid_pipeline', context_definitions=context_definitions, solids=[solid_a], dependencies={}, ) TEST_ENVIRONMENT =",
"solids=[solid_a, solid_b, solid_c, solid_d], dependencies={ 'solid_b': {'arg_a': DependencyDefinition('solid_a')}, 'solid_c': {'arg_a': DependencyDefinition('solid_a')}, 'solid_d': {",
"'us-east-2'}}}}} } def run_test_pipeline(pipeline): execution_metadata = ExecutionMetadata(run_id=str(uuid.uuid4())) with yield_pipeline_execution_context( pipeline, TEST_ENVIRONMENT, execution_metadata )",
"execution_plan) @pytest.mark.skip('Skipping pending pickling issues in lambda engine. Issue #491') def test_execution_diamond(): pipeline",
"engine. Issue #491') def test_execution_single(): pipeline = define_single_solid_pipeline() results = run_test_pipeline(pipeline) assert len(results)",
"{'resources': {'dagma': {'config': {'aws_region_name': 'us-east-2'}}}}} } def run_test_pipeline(pipeline): execution_metadata = ExecutionMetadata(run_id=str(uuid.uuid4())) with yield_pipeline_execution_context(",
"def solid_d(arg_b, arg_c): return arg_b + arg_c / 2.0 # return numpy.mean([arg_b, arg_c])",
"the target # architecture on lambda is not the architecture running the pipeline",
"import dagster.core.types as types from dagster import ( DependencyDefinition, ExecutionContext, InputDefinition, lambda_solid, PipelineContextDefinition,",
"return 1 @lambda_solid(inputs=[InputDefinition('arg_a')]) def solid_b(arg_a): return arg_a * 2 @lambda_solid(inputs=[InputDefinition('arg_a')]) def solid_c(arg_a): return",
"@pytest.mark.skip('Skipping pending pickling issues in lambda engine. Issue #491') def test_execution_diamond(): pipeline =",
"on lambda is not the architecture running the pipeline def define_diamond_dag_pipeline(): return PipelineDefinition(",
"execution_metadata = ExecutionMetadata(run_id=str(uuid.uuid4())) with yield_pipeline_execution_context( pipeline, TEST_ENVIRONMENT, execution_metadata ) as context: execution_plan =",
"with installing packages like numpy where the target # architecture on lambda is",
"return PipelineContextDefinition( context_fn=lambda _: ExecutionContext.console_logging(log_level=logging.DEBUG), resources={'dagma': define_dagma_resource()}, ) context_definitions = {'lambda': create_lambda_context()} @lambda_solid",
") context_definitions = {'lambda': create_lambda_context()} @lambda_solid def solid_a(): return 1 @lambda_solid(inputs=[InputDefinition('arg_a')]) def solid_b(arg_a):",
"#491') def test_execution_diamond(): pipeline = define_diamond_dag_pipeline() results = run_test_pipeline(pipeline) assert len(results) == 4",
"pipeline = define_diamond_dag_pipeline() results = run_test_pipeline(pipeline) assert len(results) == 4 @pytest.mark.skip('Skipping pending pickling",
"dagma import execute_plan, define_dagma_resource def create_lambda_context(): return PipelineContextDefinition( context_fn=lambda _: ExecutionContext.console_logging(log_level=logging.DEBUG), resources={'dagma': define_dagma_resource()},",
"'result')][0] is True assert results[('solid_a.transform', 'result')][1].output_name == 'result' assert results[('solid_a.transform', 'result')][1].value == 1",
"like numpy where the target # architecture on lambda is not the architecture",
"context_fn=lambda _: ExecutionContext.console_logging(log_level=logging.DEBUG), resources={'dagma': define_dagma_resource()}, ) context_definitions = {'lambda': create_lambda_context()} @lambda_solid def solid_a():",
"TODO: figure out how to deal with installing packages like numpy where the",
"how to deal with installing packages like numpy where the target # architecture",
"numpy where the target # architecture on lambda is not the architecture running",
"'arg_b': DependencyDefinition('solid_b'), 'arg_c': DependencyDefinition('solid_c'), }, }, ) def define_single_solid_pipeline(): return PipelineDefinition( name='single_solid_pipeline', context_definitions=context_definitions,",
"pipeline, TEST_ENVIRONMENT, execution_metadata ) as context: execution_plan = create_execution_plan_core(context) return execute_plan(context, execution_plan) @pytest.mark.skip('Skipping",
"run_test_pipeline(pipeline) assert len(results) == 1 assert results[('solid_a.transform', 'result')][0] is True assert results[('solid_a.transform', 'result')][1].output_name",
"create_execution_plan_core(context) return execute_plan(context, execution_plan) @pytest.mark.skip('Skipping pending pickling issues in lambda engine. Issue #491')",
"uuid from collections import namedtuple import boto3 # import numpy import pytest import",
"DependencyDefinition('solid_b'), 'arg_c': DependencyDefinition('solid_c'), }, }, ) def define_single_solid_pipeline(): return PipelineDefinition( name='single_solid_pipeline', context_definitions=context_definitions, solids=[solid_a],",
"as check import dagster.core.types as types from dagster import ( DependencyDefinition, ExecutionContext, InputDefinition,",
"def solid_a(): return 1 @lambda_solid(inputs=[InputDefinition('arg_a')]) def solid_b(arg_a): return arg_a * 2 @lambda_solid(inputs=[InputDefinition('arg_a')]) def",
"+ arg_c / 2.0 # return numpy.mean([arg_b, arg_c]) # TODO: figure out how",
"lambda_solid, PipelineContextDefinition, PipelineDefinition, ExecutionMetadata, ResourceDefinition, ) from dagster.core.execution import ( create_execution_plan_core, create_environment_config, yield_pipeline_execution_context,",
"from dagster import ( DependencyDefinition, ExecutionContext, InputDefinition, lambda_solid, PipelineContextDefinition, PipelineDefinition, ExecutionMetadata, ResourceDefinition, )",
"dagster.core.execution import ( create_execution_plan_core, create_environment_config, yield_pipeline_execution_context, ) from dagma import execute_plan, define_dagma_resource def",
"where the target # architecture on lambda is not the architecture running the",
"{'dagma': {'config': {'aws_region_name': 'us-east-2'}}}}} } def run_test_pipeline(pipeline): execution_metadata = ExecutionMetadata(run_id=str(uuid.uuid4())) with yield_pipeline_execution_context( pipeline,",
"execution_metadata ) as context: execution_plan = create_execution_plan_core(context) return execute_plan(context, execution_plan) @pytest.mark.skip('Skipping pending pickling",
"return PipelineDefinition( name='single_solid_pipeline', context_definitions=context_definitions, solids=[solid_a], dependencies={}, ) TEST_ENVIRONMENT = { 'context': {'lambda': {'resources':",
") as context: execution_plan = create_execution_plan_core(context) return execute_plan(context, execution_plan) @pytest.mark.skip('Skipping pending pickling issues",
"figure out how to deal with installing packages like numpy where the target",
"define_dagma_resource def create_lambda_context(): return PipelineContextDefinition( context_fn=lambda _: ExecutionContext.console_logging(log_level=logging.DEBUG), resources={'dagma': define_dagma_resource()}, ) context_definitions =",
"= { 'context': {'lambda': {'resources': {'dagma': {'config': {'aws_region_name': 'us-east-2'}}}}} } def run_test_pipeline(pipeline): execution_metadata",
"= {'lambda': create_lambda_context()} @lambda_solid def solid_a(): return 1 @lambda_solid(inputs=[InputDefinition('arg_a')]) def solid_b(arg_a): return arg_a"
] |
[
"import threading import signal import urllib2 import json import time sys.path.append('/home/dashboard/codebase/link/utils') sys.path.append('/Users/prettywise/Codebase/codebase/link/utils') import",
"command: \" + connect_cmd_A) # register B's tcp connect in A. name =",
"connection A -> B json_request_2 = \"{\\\"handle\\\": \" + str(tcp_connect_B_handle_in_A) + \"}\" ret",
"str(pid) + \" }\" ret = http_local_request(endpoint_A_rest_port, register_cmd_A, json_request) print(\"B's tcp_connect registered in",
"= parser_B.FindRestPort() print(\"rest port for endpoint B: \" + str(endpoint_B_rest_port)) parser_A.ReadToLine(\"^.*(command register registration",
"= get_command(endpoint_A_rest_port, \"/connect\") print(\"A's connect command: \" + connect_cmd_A) # register B's tcp",
"\" + ret) json_content = json.loads(ret) tcp_connect_B_handle_in_A = json_content['handle'] # run connection A",
"\\\"\" + name + \"\\\", \\\"version\\\": \\\"\" + version + \"\\\", \\\"pid\\\": \"",
"json.loads(ret) tcp_connect_B_handle_in_A = json_content['handle'] # run connection A -> B json_request_2 = \"{\\\"handle\\\":",
"\\\"127.0.0.1\\\", \\\"port\\\": \" + str(tcp_connect_B_port) + \", \\\"name\\\": \\\"\" + name + \"\\\",",
"None: return None commands_json = json.loads(response) for cmd in commands_json['commands']: if command in",
"urllib2 import json import time sys.path.append('/home/dashboard/codebase/link/utils') sys.path.append('/Users/prettywise/Codebase/codebase/link/utils') import parse import link def http_local_request(port,",
"str(tcp_connect_B_handle_in_A) + \"}\" ret = http_local_request(endpoint_A_rest_port, connect_cmd_A, json_request_2) print(\"A's tcp_connect connects with B's",
"= parser_A.FindRestPort() print(\"rest port for endpoint A: \" + str(endpoint_A_rest_port)) tcp_connect_B_port = parser_B.FindTcpPort(\"tcp_connect\")",
"+ \" failed with: \" + str(response.getcode())) except: print(\"404 probably\") return content def",
"= parser_A.FindTcpPort(\"tcp_connect\") # print(\"port for endpoint A: \" + str(endpoint_A_port)) endpoint_A_rest_port = parser_A.FindRestPort()",
"sys import os import subprocess import threading import signal import urllib2 import json",
"\"{ \\\"hostname\\\": \\\"127.0.0.1\\\", \\\"port\\\": \" + str(tcp_connect_B_port) + \", \\\"name\\\": \\\"\" + name",
"resulted in (\" + str(response.getcode()) + \"): \" + content) if response.getcode() !=",
"endpoint_A_rest_port = parser_A.FindRestPort() print(\"rest port for endpoint A: \" + str(endpoint_A_rest_port)) tcp_connect_B_port =",
"}\" ret = http_local_request(endpoint_A_rest_port, register_cmd_A, json_request) print(\"B's tcp_connect registered in A: \" +",
"B: \" + str(tcp_connect_B_port)) endpoint_B_rest_port = parser_B.FindRestPort() print(\"rest port for endpoint B: \"",
"data sent\") parser_B.ReadToLine(\"^.*(all data received, closing connection).*$\") print(\"all data received\") # time.sleep(2) parser_A.Kill()",
"\" + str(tcp_connect_B_port) + \", \\\"name\\\": \\\"\" + name + \"\\\", \\\"version\\\": \\\"\"",
"os import subprocess import threading import signal import urllib2 import json import time",
"print(\"go!\") register_cmd_A = get_command(endpoint_A_rest_port, \"/register\") if register_cmd_A: print(\"A's register command: \" + register_cmd_A)",
"content def get_command(port, command): response = http_local_request(port, \"/command-list\", None) if response == None:",
"= urllib2.urlopen(url, data) content = response.read() print(url + \" resulted in (\" +",
"def get_command(port, command): response = http_local_request(port, \"/command-list\", None) if response == None: return",
"endpoint A: \" + str(endpoint_A_rest_port)) tcp_connect_B_port = parser_B.FindTcpPort(\"tcp_connect\") print(\"tcp_connect port on endpoint B:",
"in commands_json['commands']: if command in cmd: return cmd return None if __name__ ==",
"failed with: \" + str(response.getcode())) except: print(\"404 probably\") return content def get_command(port, command):",
"A -> B json_request_2 = \"{\\\"handle\\\": \" + str(tcp_connect_B_handle_in_A) + \"}\" ret =",
"+ \" resulted in (\" + str(response.getcode()) + \"): \" + content) if",
"parser_B.FindRestPort() print(\"rest port for endpoint B: \" + str(endpoint_B_rest_port)) parser_A.ReadToLine(\"^.*(command register registration succeeded).*$\")",
"parser_A = link.run(\"A\", sys.argv[1:]) link_B, parser_B = link.run(\"B\", sys.argv[1:]) # endpoint_A_port = parser_A.FindTcpPort(\"tcp_connect\")",
"<filename>link/test/test_tcp_connection.py import sys import os import subprocess import threading import signal import urllib2",
"parser_A.ReadToLine(\"^.*(command connect registration succeeded).*$\") parser_A.ReadToLine(\"^.*(command command-list registration succeeded).*$\") parser_B.ReadToLine(\"^.*(command register registration succeeded).*$\") parser_B.ReadToLine(\"^.*(command",
"all data, closing connection).*$\") print(\"all data sent\") parser_B.ReadToLine(\"^.*(all data received, closing connection).*$\") print(\"all",
"+ connect_cmd_A) # register B's tcp connect in A. name = \"tcp_connect\" version",
"version = \"1.0\" pid = parser_B.process.pid json_request = \"{ \\\"hostname\\\": \\\"127.0.0.1\\\", \\\"port\\\": \"",
"None commands_json = json.loads(response) for cmd in commands_json['commands']: if command in cmd: return",
"name = \"tcp_connect\" version = \"1.0\" pid = parser_B.process.pid json_request = \"{ \\\"hostname\\\":",
"parser_B.process.pid json_request = \"{ \\\"hostname\\\": \\\"127.0.0.1\\\", \\\"port\\\": \" + str(tcp_connect_B_port) + \", \\\"name\\\":",
"endpoint B: \" + str(tcp_connect_B_port)) endpoint_B_rest_port = parser_B.FindRestPort() print(\"rest port for endpoint B:",
"cmd return None if __name__ == \"__main__\": print(\"pre main\") print(sys.argv) # main() link_A,",
"version + \"\\\", \\\"pid\\\": \" + str(pid) + \" }\" ret = http_local_request(endpoint_A_rest_port,",
"= None print(\"local request: \" + url) try: response = urllib2.urlopen(url, data) content",
"\"http://127.0.0.1:\" + str(port) + command content = None print(\"local request: \" + url)",
"= parser_B.FindTcpPort(\"tcp_connect\") print(\"tcp_connect port on endpoint B: \" + str(tcp_connect_B_port)) endpoint_B_rest_port = parser_B.FindRestPort()",
"print(sys.argv) # main() link_A, parser_A = link.run(\"A\", sys.argv[1:]) link_B, parser_B = link.run(\"B\", sys.argv[1:])",
"B json_request_2 = \"{\\\"handle\\\": \" + str(tcp_connect_B_handle_in_A) + \"}\" ret = http_local_request(endpoint_A_rest_port, connect_cmd_A,",
"json import time sys.path.append('/home/dashboard/codebase/link/utils') sys.path.append('/Users/prettywise/Codebase/codebase/link/utils') import parse import link def http_local_request(port, command, data):",
"\" + connect_cmd_A) # register B's tcp connect in A. name = \"tcp_connect\"",
"json.loads(response) for cmd in commands_json['commands']: if command in cmd: return cmd return None",
"json_request) print(\"B's tcp_connect registered in A: \" + ret) json_content = json.loads(ret) tcp_connect_B_handle_in_A",
"import signal import urllib2 import json import time sys.path.append('/home/dashboard/codebase/link/utils') sys.path.append('/Users/prettywise/Codebase/codebase/link/utils') import parse import",
"= \"tcp_connect\" version = \"1.0\" pid = parser_B.process.pid json_request = \"{ \\\"hostname\\\": \\\"127.0.0.1\\\",",
"200: raise Exception(url + \" failed with: \" + str(response.getcode())) except: print(\"404 probably\")",
"main() link_A, parser_A = link.run(\"A\", sys.argv[1:]) link_B, parser_B = link.run(\"B\", sys.argv[1:]) # endpoint_A_port",
"= json.loads(ret) tcp_connect_B_handle_in_A = json_content['handle'] # run connection A -> B json_request_2 =",
"# print(\"port for endpoint A: \" + str(endpoint_A_port)) endpoint_A_rest_port = parser_A.FindRestPort() print(\"rest port",
"\" resulted in (\" + str(response.getcode()) + \"): \" + content) if response.getcode()",
"json_content = json.loads(ret) tcp_connect_B_handle_in_A = json_content['handle'] # run connection A -> B json_request_2",
"parser_A.ReadToLine(\"^.*(sent all data, closing connection).*$\") print(\"all data sent\") parser_B.ReadToLine(\"^.*(all data received, closing connection).*$\")",
"try: response = urllib2.urlopen(url, data) content = response.read() print(url + \" resulted in",
"None if __name__ == \"__main__\": print(\"pre main\") print(sys.argv) # main() link_A, parser_A =",
"if response == None: return None commands_json = json.loads(response) for cmd in commands_json['commands']:",
"parser_B.ReadToLine(\"^.*(command register registration succeeded).*$\") parser_B.ReadToLine(\"^.*(command connect registration succeeded).*$\") parser_B.ReadToLine(\"^.*(command command-list registration succeeded).*$\") print(\"go!\")",
"\" + str(tcp_connect_B_port)) endpoint_B_rest_port = parser_B.FindRestPort() print(\"rest port for endpoint B: \" +",
"= \"{\\\"handle\\\": \" + str(tcp_connect_B_handle_in_A) + \"}\" ret = http_local_request(endpoint_A_rest_port, connect_cmd_A, json_request_2) print(\"A's",
"ret) json_content = json.loads(ret) tcp_connect_B_handle_in_A = json_content['handle'] # run connection A -> B",
"\" + str(pid) + \" }\" ret = http_local_request(endpoint_A_rest_port, register_cmd_A, json_request) print(\"B's tcp_connect",
"print(\"tcp_connect port on endpoint B: \" + str(tcp_connect_B_port)) endpoint_B_rest_port = parser_B.FindRestPort() print(\"rest port",
"= http_local_request(endpoint_A_rest_port, connect_cmd_A, json_request_2) print(\"A's tcp_connect connects with B's tcp_connect: \" + ret)",
"response.getcode() != 200: raise Exception(url + \" failed with: \" + str(response.getcode())) except:",
"register_cmd_A) connect_cmd_A = get_command(endpoint_A_rest_port, \"/connect\") print(\"A's connect command: \" + connect_cmd_A) # register",
"register command: \" + register_cmd_A) connect_cmd_A = get_command(endpoint_A_rest_port, \"/connect\") print(\"A's connect command: \"",
"if command in cmd: return cmd return None if __name__ == \"__main__\": print(\"pre",
"import subprocess import threading import signal import urllib2 import json import time sys.path.append('/home/dashboard/codebase/link/utils')",
"signal import urllib2 import json import time sys.path.append('/home/dashboard/codebase/link/utils') sys.path.append('/Users/prettywise/Codebase/codebase/link/utils') import parse import link",
"!= 200: raise Exception(url + \" failed with: \" + str(response.getcode())) except: print(\"404",
"\" + str(endpoint_B_rest_port)) parser_A.ReadToLine(\"^.*(command register registration succeeded).*$\") parser_A.ReadToLine(\"^.*(command connect registration succeeded).*$\") parser_A.ReadToLine(\"^.*(command command-list",
"== \"__main__\": print(\"pre main\") print(sys.argv) # main() link_A, parser_A = link.run(\"A\", sys.argv[1:]) link_B,",
"command-list registration succeeded).*$\") print(\"go!\") register_cmd_A = get_command(endpoint_A_rest_port, \"/register\") if register_cmd_A: print(\"A's register command:",
"register_cmd_A, json_request) print(\"B's tcp_connect registered in A: \" + ret) json_content = json.loads(ret)",
"= \"{ \\\"hostname\\\": \\\"127.0.0.1\\\", \\\"port\\\": \" + str(tcp_connect_B_port) + \", \\\"name\\\": \\\"\" +",
"= http_local_request(endpoint_A_rest_port, register_cmd_A, json_request) print(\"B's tcp_connect registered in A: \" + ret) json_content",
"connect registration succeeded).*$\") parser_B.ReadToLine(\"^.*(command command-list registration succeeded).*$\") print(\"go!\") register_cmd_A = get_command(endpoint_A_rest_port, \"/register\") if",
"\"\\\", \\\"pid\\\": \" + str(pid) + \" }\" ret = http_local_request(endpoint_A_rest_port, register_cmd_A, json_request)",
"str(endpoint_A_port)) endpoint_A_rest_port = parser_A.FindRestPort() print(\"rest port for endpoint A: \" + str(endpoint_A_rest_port)) tcp_connect_B_port",
"parse import link def http_local_request(port, command, data): url = \"http://127.0.0.1:\" + str(port) +",
"+ \"): \" + content) if response.getcode() != 200: raise Exception(url + \"",
"= parser_B.process.pid json_request = \"{ \\\"hostname\\\": \\\"127.0.0.1\\\", \\\"port\\\": \" + str(tcp_connect_B_port) + \",",
"+ str(tcp_connect_B_port)) endpoint_B_rest_port = parser_B.FindRestPort() print(\"rest port for endpoint B: \" + str(endpoint_B_rest_port))",
"endpoint B: \" + str(endpoint_B_rest_port)) parser_A.ReadToLine(\"^.*(command register registration succeeded).*$\") parser_A.ReadToLine(\"^.*(command connect registration succeeded).*$\")",
"parser_B.FindTcpPort(\"tcp_connect\") print(\"tcp_connect port on endpoint B: \" + str(tcp_connect_B_port)) endpoint_B_rest_port = parser_B.FindRestPort() print(\"rest",
"registration succeeded).*$\") parser_A.ReadToLine(\"^.*(command command-list registration succeeded).*$\") parser_B.ReadToLine(\"^.*(command register registration succeeded).*$\") parser_B.ReadToLine(\"^.*(command connect registration",
"connection).*$\") print(\"all data sent\") parser_B.ReadToLine(\"^.*(all data received, closing connection).*$\") print(\"all data received\") #",
"print(url + \" resulted in (\" + str(response.getcode()) + \"): \" + content)",
"\" + url) try: response = urllib2.urlopen(url, data) content = response.read() print(url +",
"= link.run(\"B\", sys.argv[1:]) # endpoint_A_port = parser_A.FindTcpPort(\"tcp_connect\") # print(\"port for endpoint A: \"",
"B's tcp_connect: \" + ret) parser_A.ReadToLine(\"^.*(sent all data, closing connection).*$\") print(\"all data sent\")",
"# run connection A -> B json_request_2 = \"{\\\"handle\\\": \" + str(tcp_connect_B_handle_in_A) +",
"tcp_connect: \" + ret) parser_A.ReadToLine(\"^.*(sent all data, closing connection).*$\") print(\"all data sent\") parser_B.ReadToLine(\"^.*(all",
"with B's tcp_connect: \" + ret) parser_A.ReadToLine(\"^.*(sent all data, closing connection).*$\") print(\"all data",
"print(\"port for endpoint A: \" + str(endpoint_A_port)) endpoint_A_rest_port = parser_A.FindRestPort() print(\"rest port for",
"import parse import link def http_local_request(port, command, data): url = \"http://127.0.0.1:\" + str(port)",
"register_cmd_A = get_command(endpoint_A_rest_port, \"/register\") if register_cmd_A: print(\"A's register command: \" + register_cmd_A) connect_cmd_A",
"except: print(\"404 probably\") return content def get_command(port, command): response = http_local_request(port, \"/command-list\", None)",
"\\\"\" + version + \"\\\", \\\"pid\\\": \" + str(pid) + \" }\" ret",
"= \"http://127.0.0.1:\" + str(port) + command content = None print(\"local request: \" +",
"registration succeeded).*$\") parser_B.ReadToLine(\"^.*(command register registration succeeded).*$\") parser_B.ReadToLine(\"^.*(command connect registration succeeded).*$\") parser_B.ReadToLine(\"^.*(command command-list registration",
"data) content = response.read() print(url + \" resulted in (\" + str(response.getcode()) +",
"\" + str(endpoint_A_port)) endpoint_A_rest_port = parser_A.FindRestPort() print(\"rest port for endpoint A: \" +",
"+ \" }\" ret = http_local_request(endpoint_A_rest_port, register_cmd_A, json_request) print(\"B's tcp_connect registered in A:",
"connect command: \" + connect_cmd_A) # register B's tcp connect in A. name",
"registration succeeded).*$\") parser_B.ReadToLine(\"^.*(command connect registration succeeded).*$\") parser_B.ReadToLine(\"^.*(command command-list registration succeeded).*$\") print(\"go!\") register_cmd_A =",
"\"1.0\" pid = parser_B.process.pid json_request = \"{ \\\"hostname\\\": \\\"127.0.0.1\\\", \\\"port\\\": \" + str(tcp_connect_B_port)",
"connect in A. name = \"tcp_connect\" version = \"1.0\" pid = parser_B.process.pid json_request",
"+ str(port) + command content = None print(\"local request: \" + url) try:",
"response = http_local_request(port, \"/command-list\", None) if response == None: return None commands_json =",
"port on endpoint B: \" + str(tcp_connect_B_port)) endpoint_B_rest_port = parser_B.FindRestPort() print(\"rest port for",
"name + \"\\\", \\\"version\\\": \\\"\" + version + \"\\\", \\\"pid\\\": \" + str(pid)",
"A: \" + str(endpoint_A_port)) endpoint_A_rest_port = parser_A.FindRestPort() print(\"rest port for endpoint A: \"",
"\" + str(response.getcode())) except: print(\"404 probably\") return content def get_command(port, command): response =",
"\\\"version\\\": \\\"\" + version + \"\\\", \\\"pid\\\": \" + str(pid) + \" }\"",
"for endpoint B: \" + str(endpoint_B_rest_port)) parser_A.ReadToLine(\"^.*(command register registration succeeded).*$\") parser_A.ReadToLine(\"^.*(command connect registration",
"pid = parser_B.process.pid json_request = \"{ \\\"hostname\\\": \\\"127.0.0.1\\\", \\\"port\\\": \" + str(tcp_connect_B_port) +",
"str(response.getcode())) except: print(\"404 probably\") return content def get_command(port, command): response = http_local_request(port, \"/command-list\",",
"sys.path.append('/home/dashboard/codebase/link/utils') sys.path.append('/Users/prettywise/Codebase/codebase/link/utils') import parse import link def http_local_request(port, command, data): url = \"http://127.0.0.1:\"",
"print(\"pre main\") print(sys.argv) # main() link_A, parser_A = link.run(\"A\", sys.argv[1:]) link_B, parser_B =",
"succeeded).*$\") parser_A.ReadToLine(\"^.*(command command-list registration succeeded).*$\") parser_B.ReadToLine(\"^.*(command register registration succeeded).*$\") parser_B.ReadToLine(\"^.*(command connect registration succeeded).*$\")",
"+ \"}\" ret = http_local_request(endpoint_A_rest_port, connect_cmd_A, json_request_2) print(\"A's tcp_connect connects with B's tcp_connect:",
"import sys import os import subprocess import threading import signal import urllib2 import",
"+ register_cmd_A) connect_cmd_A = get_command(endpoint_A_rest_port, \"/connect\") print(\"A's connect command: \" + connect_cmd_A) #",
"succeeded).*$\") print(\"go!\") register_cmd_A = get_command(endpoint_A_rest_port, \"/register\") if register_cmd_A: print(\"A's register command: \" +",
"import time sys.path.append('/home/dashboard/codebase/link/utils') sys.path.append('/Users/prettywise/Codebase/codebase/link/utils') import parse import link def http_local_request(port, command, data): url",
"B: \" + str(endpoint_B_rest_port)) parser_A.ReadToLine(\"^.*(command register registration succeeded).*$\") parser_A.ReadToLine(\"^.*(command connect registration succeeded).*$\") parser_A.ReadToLine(\"^.*(command",
"str(endpoint_A_rest_port)) tcp_connect_B_port = parser_B.FindTcpPort(\"tcp_connect\") print(\"tcp_connect port on endpoint B: \" + str(tcp_connect_B_port)) endpoint_B_rest_port",
"+ ret) parser_A.ReadToLine(\"^.*(sent all data, closing connection).*$\") print(\"all data sent\") parser_B.ReadToLine(\"^.*(all data received,",
"parser_A.FindRestPort() print(\"rest port for endpoint A: \" + str(endpoint_A_rest_port)) tcp_connect_B_port = parser_B.FindTcpPort(\"tcp_connect\") print(\"tcp_connect",
"register B's tcp connect in A. name = \"tcp_connect\" version = \"1.0\" pid",
"main\") print(sys.argv) # main() link_A, parser_A = link.run(\"A\", sys.argv[1:]) link_B, parser_B = link.run(\"B\",",
"print(\"rest port for endpoint A: \" + str(endpoint_A_rest_port)) tcp_connect_B_port = parser_B.FindTcpPort(\"tcp_connect\") print(\"tcp_connect port",
"print(\"local request: \" + url) try: response = urllib2.urlopen(url, data) content = response.read()",
"+ str(response.getcode()) + \"): \" + content) if response.getcode() != 200: raise Exception(url",
"import json import time sys.path.append('/home/dashboard/codebase/link/utils') sys.path.append('/Users/prettywise/Codebase/codebase/link/utils') import parse import link def http_local_request(port, command,",
"\" failed with: \" + str(response.getcode())) except: print(\"404 probably\") return content def get_command(port,",
"# register B's tcp connect in A. name = \"tcp_connect\" version = \"1.0\"",
"parser_B = link.run(\"B\", sys.argv[1:]) # endpoint_A_port = parser_A.FindTcpPort(\"tcp_connect\") # print(\"port for endpoint A:",
"+ ret) json_content = json.loads(ret) tcp_connect_B_handle_in_A = json_content['handle'] # run connection A ->",
"\"/register\") if register_cmd_A: print(\"A's register command: \" + register_cmd_A) connect_cmd_A = get_command(endpoint_A_rest_port, \"/connect\")",
"+ command content = None print(\"local request: \" + url) try: response =",
"return None if __name__ == \"__main__\": print(\"pre main\") print(sys.argv) # main() link_A, parser_A",
"+ \"\\\", \\\"pid\\\": \" + str(pid) + \" }\" ret = http_local_request(endpoint_A_rest_port, register_cmd_A,",
"+ str(endpoint_B_rest_port)) parser_A.ReadToLine(\"^.*(command register registration succeeded).*$\") parser_A.ReadToLine(\"^.*(command connect registration succeeded).*$\") parser_A.ReadToLine(\"^.*(command command-list registration",
"connects with B's tcp_connect: \" + ret) parser_A.ReadToLine(\"^.*(sent all data, closing connection).*$\") print(\"all",
"if response.getcode() != 200: raise Exception(url + \" failed with: \" + str(response.getcode()))",
"Exception(url + \" failed with: \" + str(response.getcode())) except: print(\"404 probably\") return content",
"== None: return None commands_json = json.loads(response) for cmd in commands_json['commands']: if command",
"sys.argv[1:]) link_B, parser_B = link.run(\"B\", sys.argv[1:]) # endpoint_A_port = parser_A.FindTcpPort(\"tcp_connect\") # print(\"port for",
"connection).*$\") print(\"all data received\") # time.sleep(2) parser_A.Kill() parser_B.Kill() parser_A.Wait(); parser_B.Wait(); link_A.join(10) link_B.join(10) print(\"post",
"\"{\\\"handle\\\": \" + str(tcp_connect_B_handle_in_A) + \"}\" ret = http_local_request(endpoint_A_rest_port, connect_cmd_A, json_request_2) print(\"A's tcp_connect",
"response = urllib2.urlopen(url, data) content = response.read() print(url + \" resulted in (\"",
"response == None: return None commands_json = json.loads(response) for cmd in commands_json['commands']: if",
"tcp_connect registered in A: \" + ret) json_content = json.loads(ret) tcp_connect_B_handle_in_A = json_content['handle']",
"port for endpoint B: \" + str(endpoint_B_rest_port)) parser_A.ReadToLine(\"^.*(command register registration succeeded).*$\") parser_A.ReadToLine(\"^.*(command connect",
"endpoint A: \" + str(endpoint_A_port)) endpoint_A_rest_port = parser_A.FindRestPort() print(\"rest port for endpoint A:",
"http_local_request(endpoint_A_rest_port, connect_cmd_A, json_request_2) print(\"A's tcp_connect connects with B's tcp_connect: \" + ret) parser_A.ReadToLine(\"^.*(sent",
"\"/connect\") print(\"A's connect command: \" + connect_cmd_A) # register B's tcp connect in",
"print(\"rest port for endpoint B: \" + str(endpoint_B_rest_port)) parser_A.ReadToLine(\"^.*(command register registration succeeded).*$\") parser_A.ReadToLine(\"^.*(command",
"(\" + str(response.getcode()) + \"): \" + content) if response.getcode() != 200: raise",
"tcp_connect_B_port = parser_B.FindTcpPort(\"tcp_connect\") print(\"tcp_connect port on endpoint B: \" + str(tcp_connect_B_port)) endpoint_B_rest_port =",
"str(response.getcode()) + \"): \" + content) if response.getcode() != 200: raise Exception(url +",
"+ url) try: response = urllib2.urlopen(url, data) content = response.read() print(url + \"",
"registration succeeded).*$\") print(\"go!\") register_cmd_A = get_command(endpoint_A_rest_port, \"/register\") if register_cmd_A: print(\"A's register command: \"",
"\" + ret) parser_A.ReadToLine(\"^.*(sent all data, closing connection).*$\") print(\"all data sent\") parser_B.ReadToLine(\"^.*(all data",
"link_A, parser_A = link.run(\"A\", sys.argv[1:]) link_B, parser_B = link.run(\"B\", sys.argv[1:]) # endpoint_A_port =",
"connect_cmd_A = get_command(endpoint_A_rest_port, \"/connect\") print(\"A's connect command: \" + connect_cmd_A) # register B's",
"content = response.read() print(url + \" resulted in (\" + str(response.getcode()) + \"):",
"return None commands_json = json.loads(response) for cmd in commands_json['commands']: if command in cmd:",
"register registration succeeded).*$\") parser_B.ReadToLine(\"^.*(command connect registration succeeded).*$\") parser_B.ReadToLine(\"^.*(command command-list registration succeeded).*$\") print(\"go!\") register_cmd_A",
"content) if response.getcode() != 200: raise Exception(url + \" failed with: \" +",
"print(\"A's tcp_connect connects with B's tcp_connect: \" + ret) parser_A.ReadToLine(\"^.*(sent all data, closing",
"\"\\\", \\\"version\\\": \\\"\" + version + \"\\\", \\\"pid\\\": \" + str(pid) + \"",
"data, closing connection).*$\") print(\"all data sent\") parser_B.ReadToLine(\"^.*(all data received, closing connection).*$\") print(\"all data",
"probably\") return content def get_command(port, command): response = http_local_request(port, \"/command-list\", None) if response",
"received, closing connection).*$\") print(\"all data received\") # time.sleep(2) parser_A.Kill() parser_B.Kill() parser_A.Wait(); parser_B.Wait(); link_A.join(10)",
"return cmd return None if __name__ == \"__main__\": print(\"pre main\") print(sys.argv) # main()",
"parser_A.FindTcpPort(\"tcp_connect\") # print(\"port for endpoint A: \" + str(endpoint_A_port)) endpoint_A_rest_port = parser_A.FindRestPort() print(\"rest",
"__name__ == \"__main__\": print(\"pre main\") print(sys.argv) # main() link_A, parser_A = link.run(\"A\", sys.argv[1:])",
"cmd: return cmd return None if __name__ == \"__main__\": print(\"pre main\") print(sys.argv) #",
"endpoint_A_port = parser_A.FindTcpPort(\"tcp_connect\") # print(\"port for endpoint A: \" + str(endpoint_A_port)) endpoint_A_rest_port =",
"in A. name = \"tcp_connect\" version = \"1.0\" pid = parser_B.process.pid json_request =",
"None print(\"local request: \" + url) try: response = urllib2.urlopen(url, data) content =",
"parser_B.ReadToLine(\"^.*(command command-list registration succeeded).*$\") print(\"go!\") register_cmd_A = get_command(endpoint_A_rest_port, \"/register\") if register_cmd_A: print(\"A's register",
"\"__main__\": print(\"pre main\") print(sys.argv) # main() link_A, parser_A = link.run(\"A\", sys.argv[1:]) link_B, parser_B",
"tcp connect in A. name = \"tcp_connect\" version = \"1.0\" pid = parser_B.process.pid",
"B's tcp connect in A. name = \"tcp_connect\" version = \"1.0\" pid =",
"print(\"B's tcp_connect registered in A: \" + ret) json_content = json.loads(ret) tcp_connect_B_handle_in_A =",
"register registration succeeded).*$\") parser_A.ReadToLine(\"^.*(command connect registration succeeded).*$\") parser_A.ReadToLine(\"^.*(command command-list registration succeeded).*$\") parser_B.ReadToLine(\"^.*(command register",
"urllib2.urlopen(url, data) content = response.read() print(url + \" resulted in (\" + str(response.getcode())",
"command content = None print(\"local request: \" + url) try: response = urllib2.urlopen(url,",
"url) try: response = urllib2.urlopen(url, data) content = response.read() print(url + \" resulted",
"command, data): url = \"http://127.0.0.1:\" + str(port) + command content = None print(\"local",
"in (\" + str(response.getcode()) + \"): \" + content) if response.getcode() != 200:",
"+ version + \"\\\", \\\"pid\\\": \" + str(pid) + \" }\" ret =",
"succeeded).*$\") parser_A.ReadToLine(\"^.*(command connect registration succeeded).*$\") parser_A.ReadToLine(\"^.*(command command-list registration succeeded).*$\") parser_B.ReadToLine(\"^.*(command register registration succeeded).*$\")",
"succeeded).*$\") parser_B.ReadToLine(\"^.*(command command-list registration succeeded).*$\") print(\"go!\") register_cmd_A = get_command(endpoint_A_rest_port, \"/register\") if register_cmd_A: print(\"A's",
"command: \" + register_cmd_A) connect_cmd_A = get_command(endpoint_A_rest_port, \"/connect\") print(\"A's connect command: \" +",
"json_request_2 = \"{\\\"handle\\\": \" + str(tcp_connect_B_handle_in_A) + \"}\" ret = http_local_request(endpoint_A_rest_port, connect_cmd_A, json_request_2)",
"link.run(\"A\", sys.argv[1:]) link_B, parser_B = link.run(\"B\", sys.argv[1:]) # endpoint_A_port = parser_A.FindTcpPort(\"tcp_connect\") # print(\"port",
"A: \" + str(endpoint_A_rest_port)) tcp_connect_B_port = parser_B.FindTcpPort(\"tcp_connect\") print(\"tcp_connect port on endpoint B: \"",
"connect_cmd_A) # register B's tcp connect in A. name = \"tcp_connect\" version =",
"\" + register_cmd_A) connect_cmd_A = get_command(endpoint_A_rest_port, \"/connect\") print(\"A's connect command: \" + connect_cmd_A)",
"-> B json_request_2 = \"{\\\"handle\\\": \" + str(tcp_connect_B_handle_in_A) + \"}\" ret = http_local_request(endpoint_A_rest_port,",
"in cmd: return cmd return None if __name__ == \"__main__\": print(\"pre main\") print(sys.argv)",
"\" + content) if response.getcode() != 200: raise Exception(url + \" failed with:",
"print(\"404 probably\") return content def get_command(port, command): response = http_local_request(port, \"/command-list\", None) if",
"in A: \" + ret) json_content = json.loads(ret) tcp_connect_B_handle_in_A = json_content['handle'] # run",
"json_content['handle'] # run connection A -> B json_request_2 = \"{\\\"handle\\\": \" + str(tcp_connect_B_handle_in_A)",
"+ str(tcp_connect_B_port) + \", \\\"name\\\": \\\"\" + name + \"\\\", \\\"version\\\": \\\"\" +",
"command-list registration succeeded).*$\") parser_B.ReadToLine(\"^.*(command register registration succeeded).*$\") parser_B.ReadToLine(\"^.*(command connect registration succeeded).*$\") parser_B.ReadToLine(\"^.*(command command-list",
"with: \" + str(response.getcode())) except: print(\"404 probably\") return content def get_command(port, command): response",
"A. name = \"tcp_connect\" version = \"1.0\" pid = parser_B.process.pid json_request = \"{",
"\\\"hostname\\\": \\\"127.0.0.1\\\", \\\"port\\\": \" + str(tcp_connect_B_port) + \", \\\"name\\\": \\\"\" + name +",
"print(\"A's register command: \" + register_cmd_A) connect_cmd_A = get_command(endpoint_A_rest_port, \"/connect\") print(\"A's connect command:",
"\" + str(endpoint_A_rest_port)) tcp_connect_B_port = parser_B.FindTcpPort(\"tcp_connect\") print(\"tcp_connect port on endpoint B: \" +",
"= \"1.0\" pid = parser_B.process.pid json_request = \"{ \\\"hostname\\\": \\\"127.0.0.1\\\", \\\"port\\\": \" +",
"tcp_connect connects with B's tcp_connect: \" + ret) parser_A.ReadToLine(\"^.*(sent all data, closing connection).*$\")",
"get_command(port, command): response = http_local_request(port, \"/command-list\", None) if response == None: return None",
"import urllib2 import json import time sys.path.append('/home/dashboard/codebase/link/utils') sys.path.append('/Users/prettywise/Codebase/codebase/link/utils') import parse import link def",
"\" }\" ret = http_local_request(endpoint_A_rest_port, register_cmd_A, json_request) print(\"B's tcp_connect registered in A: \"",
"\\\"name\\\": \\\"\" + name + \"\\\", \\\"version\\\": \\\"\" + version + \"\\\", \\\"pid\\\":",
"get_command(endpoint_A_rest_port, \"/connect\") print(\"A's connect command: \" + connect_cmd_A) # register B's tcp connect",
"request: \" + url) try: response = urllib2.urlopen(url, data) content = response.read() print(url",
"\"}\" ret = http_local_request(endpoint_A_rest_port, connect_cmd_A, json_request_2) print(\"A's tcp_connect connects with B's tcp_connect: \"",
"registration succeeded).*$\") parser_A.ReadToLine(\"^.*(command connect registration succeeded).*$\") parser_A.ReadToLine(\"^.*(command command-list registration succeeded).*$\") parser_B.ReadToLine(\"^.*(command register registration",
"sys.argv[1:]) # endpoint_A_port = parser_A.FindTcpPort(\"tcp_connect\") # print(\"port for endpoint A: \" + str(endpoint_A_port))",
"closing connection).*$\") print(\"all data received\") # time.sleep(2) parser_A.Kill() parser_B.Kill() parser_A.Wait(); parser_B.Wait(); link_A.join(10) link_B.join(10)",
"commands_json = json.loads(response) for cmd in commands_json['commands']: if command in cmd: return cmd",
"link.run(\"B\", sys.argv[1:]) # endpoint_A_port = parser_A.FindTcpPort(\"tcp_connect\") # print(\"port for endpoint A: \" +",
"parser_A.ReadToLine(\"^.*(command register registration succeeded).*$\") parser_A.ReadToLine(\"^.*(command connect registration succeeded).*$\") parser_A.ReadToLine(\"^.*(command command-list registration succeeded).*$\") parser_B.ReadToLine(\"^.*(command",
"data received, closing connection).*$\") print(\"all data received\") # time.sleep(2) parser_A.Kill() parser_B.Kill() parser_A.Wait(); parser_B.Wait();",
"time sys.path.append('/home/dashboard/codebase/link/utils') sys.path.append('/Users/prettywise/Codebase/codebase/link/utils') import parse import link def http_local_request(port, command, data): url =",
"on endpoint B: \" + str(tcp_connect_B_port)) endpoint_B_rest_port = parser_B.FindRestPort() print(\"rest port for endpoint",
"\"/command-list\", None) if response == None: return None commands_json = json.loads(response) for cmd",
"parser_B.ReadToLine(\"^.*(all data received, closing connection).*$\") print(\"all data received\") # time.sleep(2) parser_A.Kill() parser_B.Kill() parser_A.Wait();",
"connect registration succeeded).*$\") parser_A.ReadToLine(\"^.*(command command-list registration succeeded).*$\") parser_B.ReadToLine(\"^.*(command register registration succeeded).*$\") parser_B.ReadToLine(\"^.*(command connect",
"+ str(endpoint_A_port)) endpoint_A_rest_port = parser_A.FindRestPort() print(\"rest port for endpoint A: \" + str(endpoint_A_rest_port))",
"tcp_connect_B_handle_in_A = json_content['handle'] # run connection A -> B json_request_2 = \"{\\\"handle\\\": \"",
"+ str(response.getcode())) except: print(\"404 probably\") return content def get_command(port, command): response = http_local_request(port,",
"str(tcp_connect_B_port) + \", \\\"name\\\": \\\"\" + name + \"\\\", \\\"version\\\": \\\"\" + version",
"+ str(tcp_connect_B_handle_in_A) + \"}\" ret = http_local_request(endpoint_A_rest_port, connect_cmd_A, json_request_2) print(\"A's tcp_connect connects with",
"content = None print(\"local request: \" + url) try: response = urllib2.urlopen(url, data)",
"url = \"http://127.0.0.1:\" + str(port) + command content = None print(\"local request: \"",
"str(port) + command content = None print(\"local request: \" + url) try: response",
"print(\"all data sent\") parser_B.ReadToLine(\"^.*(all data received, closing connection).*$\") print(\"all data received\") # time.sleep(2)",
"+ \", \\\"name\\\": \\\"\" + name + \"\\\", \\\"version\\\": \\\"\" + version +",
"endpoint_B_rest_port = parser_B.FindRestPort() print(\"rest port for endpoint B: \" + str(endpoint_B_rest_port)) parser_A.ReadToLine(\"^.*(command register",
"command): response = http_local_request(port, \"/command-list\", None) if response == None: return None commands_json",
"connect_cmd_A, json_request_2) print(\"A's tcp_connect connects with B's tcp_connect: \" + ret) parser_A.ReadToLine(\"^.*(sent all",
"import link def http_local_request(port, command, data): url = \"http://127.0.0.1:\" + str(port) + command",
"ret = http_local_request(endpoint_A_rest_port, register_cmd_A, json_request) print(\"B's tcp_connect registered in A: \" + ret)",
"for endpoint A: \" + str(endpoint_A_port)) endpoint_A_rest_port = parser_A.FindRestPort() print(\"rest port for endpoint",
"register_cmd_A: print(\"A's register command: \" + register_cmd_A) connect_cmd_A = get_command(endpoint_A_rest_port, \"/connect\") print(\"A's connect",
"link def http_local_request(port, command, data): url = \"http://127.0.0.1:\" + str(port) + command content",
"= link.run(\"A\", sys.argv[1:]) link_B, parser_B = link.run(\"B\", sys.argv[1:]) # endpoint_A_port = parser_A.FindTcpPort(\"tcp_connect\") #",
"= get_command(endpoint_A_rest_port, \"/register\") if register_cmd_A: print(\"A's register command: \" + register_cmd_A) connect_cmd_A =",
"return content def get_command(port, command): response = http_local_request(port, \"/command-list\", None) if response ==",
"json_request_2) print(\"A's tcp_connect connects with B's tcp_connect: \" + ret) parser_A.ReadToLine(\"^.*(sent all data,",
"sent\") parser_B.ReadToLine(\"^.*(all data received, closing connection).*$\") print(\"all data received\") # time.sleep(2) parser_A.Kill() parser_B.Kill()",
"registered in A: \" + ret) json_content = json.loads(ret) tcp_connect_B_handle_in_A = json_content['handle'] #",
"parser_A.ReadToLine(\"^.*(command command-list registration succeeded).*$\") parser_B.ReadToLine(\"^.*(command register registration succeeded).*$\") parser_B.ReadToLine(\"^.*(command connect registration succeeded).*$\") parser_B.ReadToLine(\"^.*(command",
"+ str(pid) + \" }\" ret = http_local_request(endpoint_A_rest_port, register_cmd_A, json_request) print(\"B's tcp_connect registered",
"raise Exception(url + \" failed with: \" + str(response.getcode())) except: print(\"404 probably\") return",
"def http_local_request(port, command, data): url = \"http://127.0.0.1:\" + str(port) + command content =",
"str(endpoint_B_rest_port)) parser_A.ReadToLine(\"^.*(command register registration succeeded).*$\") parser_A.ReadToLine(\"^.*(command connect registration succeeded).*$\") parser_A.ReadToLine(\"^.*(command command-list registration succeeded).*$\")",
"if __name__ == \"__main__\": print(\"pre main\") print(sys.argv) # main() link_A, parser_A = link.run(\"A\",",
"for endpoint A: \" + str(endpoint_A_rest_port)) tcp_connect_B_port = parser_B.FindTcpPort(\"tcp_connect\") print(\"tcp_connect port on endpoint",
"ret) parser_A.ReadToLine(\"^.*(sent all data, closing connection).*$\") print(\"all data sent\") parser_B.ReadToLine(\"^.*(all data received, closing",
"cmd in commands_json['commands']: if command in cmd: return cmd return None if __name__",
"parser_B.ReadToLine(\"^.*(command connect registration succeeded).*$\") parser_B.ReadToLine(\"^.*(command command-list registration succeeded).*$\") print(\"go!\") register_cmd_A = get_command(endpoint_A_rest_port, \"/register\")",
"print(\"A's connect command: \" + connect_cmd_A) # register B's tcp connect in A.",
"link_B, parser_B = link.run(\"B\", sys.argv[1:]) # endpoint_A_port = parser_A.FindTcpPort(\"tcp_connect\") # print(\"port for endpoint",
"A: \" + ret) json_content = json.loads(ret) tcp_connect_B_handle_in_A = json_content['handle'] # run connection",
"http_local_request(port, command, data): url = \"http://127.0.0.1:\" + str(port) + command content = None",
"import os import subprocess import threading import signal import urllib2 import json import",
"\"): \" + content) if response.getcode() != 200: raise Exception(url + \" failed",
"commands_json['commands']: if command in cmd: return cmd return None if __name__ == \"__main__\":",
"succeeded).*$\") parser_B.ReadToLine(\"^.*(command register registration succeeded).*$\") parser_B.ReadToLine(\"^.*(command connect registration succeeded).*$\") parser_B.ReadToLine(\"^.*(command command-list registration succeeded).*$\")",
"\\\"port\\\": \" + str(tcp_connect_B_port) + \", \\\"name\\\": \\\"\" + name + \"\\\", \\\"version\\\":",
"sys.path.append('/Users/prettywise/Codebase/codebase/link/utils') import parse import link def http_local_request(port, command, data): url = \"http://127.0.0.1:\" +",
"command in cmd: return cmd return None if __name__ == \"__main__\": print(\"pre main\")",
"= response.read() print(url + \" resulted in (\" + str(response.getcode()) + \"): \"",
"data): url = \"http://127.0.0.1:\" + str(port) + command content = None print(\"local request:",
"print(\"all data received\") # time.sleep(2) parser_A.Kill() parser_B.Kill() parser_A.Wait(); parser_B.Wait(); link_A.join(10) link_B.join(10) print(\"post main\")",
"for cmd in commands_json['commands']: if command in cmd: return cmd return None if",
"str(tcp_connect_B_port)) endpoint_B_rest_port = parser_B.FindRestPort() print(\"rest port for endpoint B: \" + str(endpoint_B_rest_port)) parser_A.ReadToLine(\"^.*(command",
"if register_cmd_A: print(\"A's register command: \" + register_cmd_A) connect_cmd_A = get_command(endpoint_A_rest_port, \"/connect\") print(\"A's",
"response.read() print(url + \" resulted in (\" + str(response.getcode()) + \"): \" +",
"get_command(endpoint_A_rest_port, \"/register\") if register_cmd_A: print(\"A's register command: \" + register_cmd_A) connect_cmd_A = get_command(endpoint_A_rest_port,",
"closing connection).*$\") print(\"all data sent\") parser_B.ReadToLine(\"^.*(all data received, closing connection).*$\") print(\"all data received\")",
"# endpoint_A_port = parser_A.FindTcpPort(\"tcp_connect\") # print(\"port for endpoint A: \" + str(endpoint_A_port)) endpoint_A_rest_port",
"threading import signal import urllib2 import json import time sys.path.append('/home/dashboard/codebase/link/utils') sys.path.append('/Users/prettywise/Codebase/codebase/link/utils') import parse",
"+ content) if response.getcode() != 200: raise Exception(url + \" failed with: \"",
"http_local_request(port, \"/command-list\", None) if response == None: return None commands_json = json.loads(response) for",
"json_request = \"{ \\\"hostname\\\": \\\"127.0.0.1\\\", \\\"port\\\": \" + str(tcp_connect_B_port) + \", \\\"name\\\": \\\"\"",
"ret = http_local_request(endpoint_A_rest_port, connect_cmd_A, json_request_2) print(\"A's tcp_connect connects with B's tcp_connect: \" +",
"\" + str(tcp_connect_B_handle_in_A) + \"}\" ret = http_local_request(endpoint_A_rest_port, connect_cmd_A, json_request_2) print(\"A's tcp_connect connects",
"= http_local_request(port, \"/command-list\", None) if response == None: return None commands_json = json.loads(response)",
"= json.loads(response) for cmd in commands_json['commands']: if command in cmd: return cmd return",
"run connection A -> B json_request_2 = \"{\\\"handle\\\": \" + str(tcp_connect_B_handle_in_A) + \"}\"",
"http_local_request(endpoint_A_rest_port, register_cmd_A, json_request) print(\"B's tcp_connect registered in A: \" + ret) json_content =",
"succeeded).*$\") parser_B.ReadToLine(\"^.*(command connect registration succeeded).*$\") parser_B.ReadToLine(\"^.*(command command-list registration succeeded).*$\") print(\"go!\") register_cmd_A = get_command(endpoint_A_rest_port,",
"\"tcp_connect\" version = \"1.0\" pid = parser_B.process.pid json_request = \"{ \\\"hostname\\\": \\\"127.0.0.1\\\", \\\"port\\\":",
"registration succeeded).*$\") parser_B.ReadToLine(\"^.*(command command-list registration succeeded).*$\") print(\"go!\") register_cmd_A = get_command(endpoint_A_rest_port, \"/register\") if register_cmd_A:",
"= json_content['handle'] # run connection A -> B json_request_2 = \"{\\\"handle\\\": \" +",
"\\\"pid\\\": \" + str(pid) + \" }\" ret = http_local_request(endpoint_A_rest_port, register_cmd_A, json_request) print(\"B's",
"None) if response == None: return None commands_json = json.loads(response) for cmd in",
"+ str(endpoint_A_rest_port)) tcp_connect_B_port = parser_B.FindTcpPort(\"tcp_connect\") print(\"tcp_connect port on endpoint B: \" + str(tcp_connect_B_port))",
"subprocess import threading import signal import urllib2 import json import time sys.path.append('/home/dashboard/codebase/link/utils') sys.path.append('/Users/prettywise/Codebase/codebase/link/utils')",
"+ \"\\\", \\\"version\\\": \\\"\" + version + \"\\\", \\\"pid\\\": \" + str(pid) +",
"port for endpoint A: \" + str(endpoint_A_rest_port)) tcp_connect_B_port = parser_B.FindTcpPort(\"tcp_connect\") print(\"tcp_connect port on",
"+ name + \"\\\", \\\"version\\\": \\\"\" + version + \"\\\", \\\"pid\\\": \" +",
"# main() link_A, parser_A = link.run(\"A\", sys.argv[1:]) link_B, parser_B = link.run(\"B\", sys.argv[1:]) #",
"\", \\\"name\\\": \\\"\" + name + \"\\\", \\\"version\\\": \\\"\" + version + \"\\\","
] |
[
"nn.parameter.Parameter( torch.tensor(threshold) ) def forward(self, logits: torch.FloatTensor, targets: torch.LongTensor ) -> torch.Tensor: targ",
"# @email : <EMAIL> import os from typing import List, Tuple from tqdm",
"qq.cpu().numpy() hh = hh.cpu().numpy() tt = tt.cpu().numpy() for bid, (q, h, t) in",
"def __init__(self, miner: nn.Module, optimizer: optim.Optimizer, dataloader: RTDataLoader, loss_fn=nn.CrossEntropyLoss(), device='cpu', ckpt_file=None, ckpt_save_dir=None )",
"print(f\"Successfully loaded checkpoint '{ckpt}'\") self.miner.load_state_dict(checkpoint['model']) self.optimizer.load_state_dict(checkpoint['optimizer']) self.start_epoch = checkpoint['start_epoch'] else: raise Exception(f\"No checkpoint",
"gradient along propagation chain. with torch.no_grad(): for _, (qq, hh, tt, trips) in",
"chain. with torch.no_grad(): for _, (qq, hh, tt, trips) in enumerate(tqdm( self.dataloader.one_epoch( dataset_name,",
"in_top_k(tt, logits, top_k) running_acc += bool_top_k.tolist() running_loss += loss.item() * qq.size(0) num_trained +=",
"None: super(RTLoss, self).__init__() self.threshold = nn.parameter.Parameter( torch.tensor(threshold) ) def forward(self, logits: torch.FloatTensor, targets:",
"| \"valid\" | \"test\" `prediction_file`: file path for output prediction results Returns: Miner",
"self.dataloader.id2ent ) t_str = prediction[-1] to_write = [q_str, h_str, t_str] + prediction file_obj.write(\",\".join(to_write)",
"0. num_trained = 0 for bid, (qq, hh, tt, trips) in enumerate( self.dataloader.one_epoch(\"train\",",
"self.dataloader.one_epoch( dataset_name, batch_size ), desc='Predict' )): qq = torch.from_numpy(qq).to(self.device) hh = torch.from_numpy(hh).to(self.device) tt",
"str, batch_size: str, top_k: int, prediction_file=None ) -> Tuple[torch.Tensor, float]: \"\"\"Evaluate `self.miner` on",
"acc > best_acc: best_acc = acc best_cnt = 0 print(f\"Best checkpoint reached at",
"num_train )) loss = running_loss / num_train acc = np.mean(running_acc) * 100 print(f\"[epoch",
"-> List: '''Train `self.miner` on given training data loaded from `self.dataloader`. Args: `top_k`:",
"self.start_epoch, best_acc )) return losses, accuracies def eval(self, dataset_name: str, batch_size: str, top_k:",
"= 0 best_acc = 0. for epoch in range(self.start_epoch, self.start_epoch + epochs): self.miner.train()",
"{} best_acc: {:.2f}\".format( epoch - self.start_epoch, best_acc )) return losses, accuracies def eval(self,",
"qq.size(0) if (bid+1) % 10 == 0: loss_val = running_loss / num_trained acc",
"torch.LongTensor ) -> torch.Tensor: targ = F.one_hot(targets, logits.size(1)) # `logits`: (batch_size, num_entity) loss",
"<gh_stars>1-10 #!/usr/bin/env python # -*-coding:utf-8 -*- # @file : framework.py # @brief :",
"== 0: acc = self.eval(\"valid\", batch_size, top_k) accuracies.append(acc) if acc > best_acc: best_acc",
"- self.start_epoch, best_acc )) return losses, accuracies def eval(self, dataset_name: str, batch_size: str,",
"print(\"{:=^100}\".format(f\"Training epoch {epoch+1}\")) running_acc = [] running_loss = 0. num_trained = 0 for",
"@file : framework.py # @brief : Framework for training, evaluating and saving models.",
"import RTDataLoader from utils import in_top_k from utils import get_sample_prediction class RTLoss(nn.Module): def",
"if prediction_file: file_obj.close() return np.mean(accuracies) def _load_checkpoint(self, ckpt: str) -> None: '''Load model",
"`self.miner` on given training data loaded from `self.dataloader`. Args: `top_k`: for computing Hit@k",
"accuracy: {(acc * 100):.2f}%\") self._save_checkpoint(\"checkpoint\", epoch) else: best_cnt += 1 # Early stopping.",
"model checkpoint.''' if os.path.isfile(ckpt): checkpoint = torch.load(ckpt) print(f\"Successfully loaded checkpoint '{ckpt}'\") self.miner.load_state_dict(checkpoint['model']) self.optimizer.load_state_dict(checkpoint['optimizer'])",
"open(prediction_file, 'w') accuracies = [] self.miner.eval() # Do not accumulate gradient along propagation",
"state_dict = { 'start_epoch': end_epoch, 'model': self.miner.state_dict(), 'optimizer': self.optimizer.state_dict(), } ckpt_file = name",
"logits, top_k) running_acc += bool_top_k.tolist() running_loss += loss.item() * qq.size(0) num_trained += qq.size(0)",
"= np.mean(running_acc) * 100 print(f\"[epoch {epoch+1}] loss: {loss:>7f}, acc: {acc:>4.2f}\") losses.append(loss) if (epoch",
"batch_size, top_k) accuracies.append(acc) if acc > best_acc: best_acc = acc best_cnt = 0",
"dataloader self.start_epoch = 0 if ckpt_file: self._load_checkpoint(ckpt_file) def train(self, top_k: int, batch_size: int,",
"epoch) else: best_cnt += 1 # Early stopping. if best_cnt > 2: break",
"float]: \"\"\"Evaluate `self.miner` on dataset specified by `dataset_name`. Args: `dataset_name`: \"train\" | \"valid\"",
"import get_sample_prediction class RTLoss(nn.Module): def __init__(self, threshold: float ) -> None: super(RTLoss, self).__init__()",
"and saving models. # @author : <NAME> # @email : <EMAIL> import os",
"t_str] + prediction file_obj.write(\",\".join(to_write) + \"\\n\") if prediction_file: file_obj.close() return np.mean(accuracies) def _load_checkpoint(self,",
"`dataloader`: Data loader `loss_fn`: loss function `device`: 'cpu' | 'cuda' `ckpt_file`: path to",
"model checkpoint \"\"\" self.loss_fn = loss_fn self.device = device self.ckpt_dir = ckpt_save_dir self.miner",
"else: raise Exception(f\"No checkpoint found at '{ckpt}'\") def _save_checkpoint(self, name: str, end_epoch: int",
"0 if ckpt_file: self._load_checkpoint(ckpt_file) def train(self, top_k: int, batch_size: int, num_sample_batches: int, epochs=20,",
"class RTFramework(object): def __init__(self, miner: nn.Module, optimizer: optim.Optimizer, dataloader: RTDataLoader, loss_fn=nn.CrossEntropyLoss(), device='cpu', ckpt_file=None,",
"-> None: '''Load model checkpoint.''' if os.path.isfile(ckpt): checkpoint = torch.load(ckpt) print(f\"Successfully loaded checkpoint",
"int, num_sample_batches: int, epochs=20, valid_freq: int = 1 ) -> List: '''Train `self.miner`",
"Hit@k `batch_size`: mini batch size `num_sample_batches`: max number of batches for one epoch",
"bid, (q, h, t) in enumerate(zip(qq, hh, tt)): q_str = self.dataloader.id2rel[q] h_str =",
"`prediction_file`: file path for output prediction results Returns: Miner accuracy and given samples.",
"instance `dataloader`: Data loader `loss_fn`: loss function `device`: 'cpu' | 'cuda' `ckpt_file`: path",
"data loaded from `self.dataloader`. Args: `top_k`: for computing Hit@k `batch_size`: mini batch size",
"and valid accuracies. ''' num_train = len(self.dataloader.train) if self.dataloader.query_include_reverse: num_train *= 2 accuracies",
"+= 1 # Early stopping. if best_cnt > 2: break print(\"\\n[Training finished] epochs:",
"qq = qq.cpu().numpy() hh = hh.cpu().numpy() tt = tt.cpu().numpy() for bid, (q, h,",
"torch.from_numpy(qq).to(self.device) hh = torch.from_numpy(hh).to(self.device) tt = torch.from_numpy(tt).to(self.device) logits = self.miner(qq, hh, trips) loss",
"bid, (qq, hh, tt, trips) in enumerate( self.dataloader.one_epoch(\"train\", batch_size, num_sample_batches, True) ): qq",
"epochs=20, valid_freq: int = 1 ) -> List: '''Train `self.miner` on given training",
"trips) loss = self.loss_fn(logits, tt) self.optimizer.zero_grad() loss.backward() self.optimizer.step() bool_top_k = in_top_k(tt, logits, top_k)",
"self.dataloader.id2ent[h] prediction = get_sample_prediction( t, logits[bid].cpu().numpy(), self.dataloader.id2ent ) t_str = prediction[-1] to_write =",
"torch.from_numpy(tt).to(self.device) logits = self.miner(qq, hh, trips) loss = self.loss_fn(logits, tt) self.optimizer.zero_grad() loss.backward() self.optimizer.step()",
"bool_top_k.tolist() if prediction_file: qq = qq.cpu().numpy() hh = hh.cpu().numpy() tt = tt.cpu().numpy() for",
"Returns: Miner accuracy and given samples. \"\"\" if prediction_file: file_obj = open(prediction_file, 'w')",
"if acc > best_acc: best_acc = acc best_cnt = 0 print(f\"Best checkpoint reached",
"`ckpt_save_dir`: directory to save best model checkpoint \"\"\" self.loss_fn = loss_fn self.device =",
"epochs in total `valid_freq`: `self.miner` will be evaluated on validation dataset every `valid_freq`",
"acc: {acc:>4.2f}\") losses.append(loss) if (epoch + 1) % valid_freq == 0: acc =",
"-> None: \"\"\" Args: `miner`: a nn.Module instance for logic rule mining `optimizer`:",
"-*-coding:utf-8 -*- # @file : framework.py # @brief : Framework for training, evaluating",
"{:.2f}\".format( epoch - self.start_epoch, best_acc )) return losses, accuracies def eval(self, dataset_name: str,",
"prediction_file: file_obj = open(prediction_file, 'w') accuracies = [] self.miner.eval() # Do not accumulate",
"= torch.from_numpy(tt).to(self.device) logits = self.miner(qq, hh, trips) loss = self.loss_fn(logits, tt) self.optimizer.zero_grad() loss.backward()",
"np.mean(running_acc) * 100 print(f\"[epoch {epoch+1}] loss: {loss:>7f}, acc: {acc:>4.2f}\") losses.append(loss) if (epoch +",
"= checkpoint['start_epoch'] else: raise Exception(f\"No checkpoint found at '{ckpt}'\") def _save_checkpoint(self, name: str,",
"self.start_epoch + epochs): self.miner.train() print(\"{:=^100}\".format(f\"Training epoch {epoch+1}\")) running_acc = [] running_loss = 0.",
")) return losses, accuracies def eval(self, dataset_name: str, batch_size: str, top_k: int, prediction_file=None",
"loss_fn=nn.CrossEntropyLoss(), device='cpu', ckpt_file=None, ckpt_save_dir=None ) -> None: \"\"\" Args: `miner`: a nn.Module instance",
"accuracies def eval(self, dataset_name: str, batch_size: str, top_k: int, prediction_file=None ) -> Tuple[torch.Tensor,",
"None: \"\"\" Args: `miner`: a nn.Module instance for logic rule mining `optimizer`: an",
"*= 2 accuracies = [] losses = [] best_cnt = 0 best_acc =",
"evaluating and saving models. # @author : <NAME> # @email : <EMAIL> import",
"tqdm import numpy as np import torch from torch import optim, nn from",
") def forward(self, logits: torch.FloatTensor, targets: torch.LongTensor ) -> torch.Tensor: targ = F.one_hot(targets,",
"best_acc: best_acc = acc best_cnt = 0 print(f\"Best checkpoint reached at best accuracy:",
"acc = np.mean(running_acc) print(\"loss: {:>7f}\\tacc: {:>4.2f}% [{:>6}/{:>6d}]\".format( loss_val, 100 * acc, num_trained, num_train",
"self.ckpt_dir: return state_dict = { 'start_epoch': end_epoch, 'model': self.miner.state_dict(), 'optimizer': self.optimizer.state_dict(), } ckpt_file",
"= optimizer self.dataloader = dataloader self.start_epoch = 0 if ckpt_file: self._load_checkpoint(ckpt_file) def train(self,",
"print(f\"Best checkpoint reached at best accuracy: {(acc * 100):.2f}%\") self._save_checkpoint(\"checkpoint\", epoch) else: best_cnt",
"checkpoint.\"\"\" if not self.ckpt_dir: return state_dict = { 'start_epoch': end_epoch, 'model': self.miner.state_dict(), 'optimizer':",
"of batches for one epoch `epochs`: max training epochs in total `valid_freq`: `self.miner`",
"loaded from `self.dataloader`. Args: `top_k`: for computing Hit@k `batch_size`: mini batch size `num_sample_batches`:",
"= torch.from_numpy(qq).to(self.device) hh = torch.from_numpy(hh).to(self.device) tt = torch.from_numpy(tt).to(self.device) logits = self.miner(qq, hh, trips)",
"Tuple from tqdm import tqdm import numpy as np import torch from torch",
"= running_loss / num_train acc = np.mean(running_acc) * 100 print(f\"[epoch {epoch+1}] loss: {loss:>7f},",
"-> None: super(RTLoss, self).__init__() self.threshold = nn.parameter.Parameter( torch.tensor(threshold) ) def forward(self, logits: torch.FloatTensor,",
"Args: `miner`: a nn.Module instance for logic rule mining `optimizer`: an Optimizer instance",
"self.loss_fn(logits, tt) self.optimizer.zero_grad() loss.backward() self.optimizer.step() bool_top_k = in_top_k(tt, logits, top_k) running_acc += bool_top_k.tolist()",
"+ 1) % valid_freq == 0: acc = self.eval(\"valid\", batch_size, top_k) accuracies.append(acc) if",
"be evaluated on validation dataset every `valid_freq` epochs. Returns: Traning loss and valid",
") -> Tuple[torch.Tensor, float]: \"\"\"Evaluate `self.miner` on dataset specified by `dataset_name`. Args: `dataset_name`:",
"checkpoint.''' if os.path.isfile(ckpt): checkpoint = torch.load(ckpt) print(f\"Successfully loaded checkpoint '{ckpt}'\") self.miner.load_state_dict(checkpoint['model']) self.optimizer.load_state_dict(checkpoint['optimizer']) self.start_epoch",
"\"\"\"Save model checkpoint.\"\"\" if not self.ckpt_dir: return state_dict = { 'start_epoch': end_epoch, 'model':",
"epochs. Returns: Traning loss and valid accuracies. ''' num_train = len(self.dataloader.train) if self.dataloader.query_include_reverse:",
"1) % valid_freq == 0: acc = self.eval(\"valid\", batch_size, top_k) accuracies.append(acc) if acc",
"hh, trips).cpu() bool_top_k = in_top_k(tt, logits, top_k) accuracies += bool_top_k.tolist() if prediction_file: qq",
"running_loss / num_train acc = np.mean(running_acc) * 100 print(f\"[epoch {epoch+1}] loss: {loss:>7f}, acc:",
"checkpoints `ckpt_save_dir`: directory to save best model checkpoint \"\"\" self.loss_fn = loss_fn self.device",
"top_k) accuracies += bool_top_k.tolist() if prediction_file: qq = qq.cpu().numpy() hh = hh.cpu().numpy() tt",
"hh, tt)): q_str = self.dataloader.id2rel[q] h_str = self.dataloader.id2ent[h] prediction = get_sample_prediction( t, logits[bid].cpu().numpy(),",
"-> None: \"\"\"Save model checkpoint.\"\"\" if not self.ckpt_dir: return state_dict = { 'start_epoch':",
"= torch.from_numpy(hh).to(self.device) tt = torch.from_numpy(tt) logits = self.miner(qq, hh, trips).cpu() bool_top_k = in_top_k(tt,",
"batch size `num_sample_batches`: max number of batches for one epoch `epochs`: max training",
"{(acc * 100):.2f}%\") self._save_checkpoint(\"checkpoint\", epoch) else: best_cnt += 1 # Early stopping. if",
"self.eval(\"valid\", batch_size, top_k) accuracies.append(acc) if acc > best_acc: best_acc = acc best_cnt =",
"F from dataloader import RTDataLoader from utils import in_top_k from utils import get_sample_prediction",
"size `num_sample_batches`: max number of batches for one epoch `epochs`: max training epochs",
"in enumerate(tqdm( self.dataloader.one_epoch( dataset_name, batch_size ), desc='Predict' )): qq = torch.from_numpy(qq).to(self.device) hh =",
"def _load_checkpoint(self, ckpt: str) -> None: '''Load model checkpoint.''' if os.path.isfile(ckpt): checkpoint =",
"batches for one epoch `epochs`: max training epochs in total `valid_freq`: `self.miner` will",
"with torch.no_grad(): for _, (qq, hh, tt, trips) in enumerate(tqdm( self.dataloader.one_epoch( dataset_name, batch_size",
"tt, trips) in enumerate(tqdm( self.dataloader.one_epoch( dataset_name, batch_size ), desc='Predict' )): qq = torch.from_numpy(qq).to(self.device)",
"import os from typing import List, Tuple from tqdm import tqdm import numpy",
"% valid_freq == 0: acc = self.eval(\"valid\", batch_size, top_k) accuracies.append(acc) if acc >",
"Miner accuracy and given samples. \"\"\" if prediction_file: file_obj = open(prediction_file, 'w') accuracies",
"self.optimizer.step() bool_top_k = in_top_k(tt, logits, top_k) running_acc += bool_top_k.tolist() running_loss += loss.item() *",
"else: best_cnt += 1 # Early stopping. if best_cnt > 2: break print(\"\\n[Training",
"logits = self.miner(qq, hh, trips) loss = self.loss_fn(logits, tt) self.optimizer.zero_grad() loss.backward() self.optimizer.step() bool_top_k",
"= 0. num_trained = 0 for bid, (qq, hh, tt, trips) in enumerate(",
"np.mean(running_acc) print(\"loss: {:>7f}\\tacc: {:>4.2f}% [{:>6}/{:>6d}]\".format( loss_val, 100 * acc, num_trained, num_train )) loss",
"if os.path.isfile(ckpt): checkpoint = torch.load(ckpt) print(f\"Successfully loaded checkpoint '{ckpt}'\") self.miner.load_state_dict(checkpoint['model']) self.optimizer.load_state_dict(checkpoint['optimizer']) self.start_epoch =",
"hh, trips) loss = self.loss_fn(logits, tt) self.optimizer.zero_grad() loss.backward() self.optimizer.step() bool_top_k = in_top_k(tt, logits,",
"dataset specified by `dataset_name`. Args: `dataset_name`: \"train\" | \"valid\" | \"test\" `prediction_file`: file",
"computing Hit@k `batch_size`: mini batch size `num_sample_batches`: max number of batches for one",
"range(self.start_epoch, self.start_epoch + epochs): self.miner.train() print(\"{:=^100}\".format(f\"Training epoch {epoch+1}\")) running_acc = [] running_loss =",
"None: \"\"\"Save model checkpoint.\"\"\" if not self.ckpt_dir: return state_dict = { 'start_epoch': end_epoch,",
"np import torch from torch import optim, nn from torch.nn import functional as",
"= torch.from_numpy(hh).to(self.device) tt = torch.from_numpy(tt).to(self.device) logits = self.miner(qq, hh, trips) loss = self.loss_fn(logits,",
"def train(self, top_k: int, batch_size: int, num_sample_batches: int, epochs=20, valid_freq: int = 1",
"# @author : <NAME> # @email : <EMAIL> import os from typing import",
"mini batch size `num_sample_batches`: max number of batches for one epoch `epochs`: max",
"num_train *= 2 accuracies = [] losses = [] best_cnt = 0 best_acc",
"'optimizer': self.optimizer.state_dict(), } ckpt_file = name + \".pth.tar\" ckpt_file = os.path.join(self.ckpt_dir, ckpt_file) torch.save(state_dict,",
"on validation dataset every `valid_freq` epochs. Returns: Traning loss and valid accuracies. '''",
"torch.maximum(logits, self.threshold) return torch.mean(-torch.sum(torch.log(loss) * targ, dim=1), dim=0) class RTFramework(object): def __init__(self, miner:",
"running_loss += loss.item() * qq.size(0) num_trained += qq.size(0) if (bid+1) % 10 ==",
"def forward(self, logits: torch.FloatTensor, targets: torch.LongTensor ) -> torch.Tensor: targ = F.one_hot(targets, logits.size(1))",
"given samples. \"\"\" if prediction_file: file_obj = open(prediction_file, 'w') accuracies = [] self.miner.eval()",
"= ckpt_save_dir self.miner = miner self.optimizer = optimizer self.dataloader = dataloader self.start_epoch =",
"= in_top_k(tt, logits, top_k) accuracies += bool_top_k.tolist() if prediction_file: qq = qq.cpu().numpy() hh",
"+ \"\\n\") if prediction_file: file_obj.close() return np.mean(accuracies) def _load_checkpoint(self, ckpt: str) -> None:",
"Traning loss and valid accuracies. ''' num_train = len(self.dataloader.train) if self.dataloader.query_include_reverse: num_train *=",
"prediction results Returns: Miner accuracy and given samples. \"\"\" if prediction_file: file_obj =",
"super(RTLoss, self).__init__() self.threshold = nn.parameter.Parameter( torch.tensor(threshold) ) def forward(self, logits: torch.FloatTensor, targets: torch.LongTensor",
"ckpt: str) -> None: '''Load model checkpoint.''' if os.path.isfile(ckpt): checkpoint = torch.load(ckpt) print(f\"Successfully",
") -> None: super(RTLoss, self).__init__() self.threshold = nn.parameter.Parameter( torch.tensor(threshold) ) def forward(self, logits:",
"batch_size: str, top_k: int, prediction_file=None ) -> Tuple[torch.Tensor, float]: \"\"\"Evaluate `self.miner` on dataset",
"samples. \"\"\" if prediction_file: file_obj = open(prediction_file, 'w') accuracies = [] self.miner.eval() #",
"\"valid\" | \"test\" `prediction_file`: file path for output prediction results Returns: Miner accuracy",
"print(\"\\n[Training finished] epochs: {} best_acc: {:.2f}\".format( epoch - self.start_epoch, best_acc )) return losses,",
"validation dataset every `valid_freq` epochs. Returns: Traning loss and valid accuracies. ''' num_train",
"= { 'start_epoch': end_epoch, 'model': self.miner.state_dict(), 'optimizer': self.optimizer.state_dict(), } ckpt_file = name +",
"= self.dataloader.id2rel[q] h_str = self.dataloader.id2ent[h] prediction = get_sample_prediction( t, logits[bid].cpu().numpy(), self.dataloader.id2ent ) t_str",
"typing import List, Tuple from tqdm import tqdm import numpy as np import",
"in enumerate( self.dataloader.one_epoch(\"train\", batch_size, num_sample_batches, True) ): qq = torch.from_numpy(qq).to(self.device) hh = torch.from_numpy(hh).to(self.device)",
"self.threshold) return torch.mean(-torch.sum(torch.log(loss) * targ, dim=1), dim=0) class RTFramework(object): def __init__(self, miner: nn.Module,",
"`dataset_name`: \"train\" | \"valid\" | \"test\" `prediction_file`: file path for output prediction results",
"loss = torch.maximum(logits, self.threshold) return torch.mean(-torch.sum(torch.log(loss) * targ, dim=1), dim=0) class RTFramework(object): def",
"= torch.maximum(logits, self.threshold) return torch.mean(-torch.sum(torch.log(loss) * targ, dim=1), dim=0) class RTFramework(object): def __init__(self,",
": Framework for training, evaluating and saving models. # @author : <NAME> #",
"# `logits`: (batch_size, num_entity) loss = torch.maximum(logits, self.threshold) return torch.mean(-torch.sum(torch.log(loss) * targ, dim=1),",
"\"\"\" self.loss_fn = loss_fn self.device = device self.ckpt_dir = ckpt_save_dir self.miner = miner",
"from typing import List, Tuple from tqdm import tqdm import numpy as np",
"as np import torch from torch import optim, nn from torch.nn import functional",
"trips) in enumerate(tqdm( self.dataloader.one_epoch( dataset_name, batch_size ), desc='Predict' )): qq = torch.from_numpy(qq).to(self.device) hh",
"= nn.parameter.Parameter( torch.tensor(threshold) ) def forward(self, logits: torch.FloatTensor, targets: torch.LongTensor ) -> torch.Tensor:",
"* 100 print(f\"[epoch {epoch+1}] loss: {loss:>7f}, acc: {acc:>4.2f}\") losses.append(loss) if (epoch + 1)",
"RTFramework(object): def __init__(self, miner: nn.Module, optimizer: optim.Optimizer, dataloader: RTDataLoader, loss_fn=nn.CrossEntropyLoss(), device='cpu', ckpt_file=None, ckpt_save_dir=None",
"Framework for training, evaluating and saving models. # @author : <NAME> # @email",
"print(f\"[epoch {epoch+1}] loss: {loss:>7f}, acc: {acc:>4.2f}\") losses.append(loss) if (epoch + 1) % valid_freq",
"self.miner = miner self.optimizer = optimizer self.dataloader = dataloader self.start_epoch = 0 if",
"(batch_size, num_entity) loss = torch.maximum(logits, self.threshold) return torch.mean(-torch.sum(torch.log(loss) * targ, dim=1), dim=0) class",
"by `dataset_name`. Args: `dataset_name`: \"train\" | \"valid\" | \"test\" `prediction_file`: file path for",
"bool_top_k = in_top_k(tt, logits, top_k) running_acc += bool_top_k.tolist() running_loss += loss.item() * qq.size(0)",
"Optimizer instance `dataloader`: Data loader `loss_fn`: loss function `device`: 'cpu' | 'cuda' `ckpt_file`:",
"num_trained = 0 for bid, (qq, hh, tt, trips) in enumerate( self.dataloader.one_epoch(\"train\", batch_size,",
"at '{ckpt}'\") def _save_checkpoint(self, name: str, end_epoch: int ) -> None: \"\"\"Save model",
"Exception(f\"No checkpoint found at '{ckpt}'\") def _save_checkpoint(self, name: str, end_epoch: int ) ->",
"targ = F.one_hot(targets, logits.size(1)) # `logits`: (batch_size, num_entity) loss = torch.maximum(logits, self.threshold) return",
"loss_val, 100 * acc, num_trained, num_train )) loss = running_loss / num_train acc",
"model checkpoint.\"\"\" if not self.ckpt_dir: return state_dict = { 'start_epoch': end_epoch, 'model': self.miner.state_dict(),",
"results Returns: Miner accuracy and given samples. \"\"\" if prediction_file: file_obj = open(prediction_file,",
"total `valid_freq`: `self.miner` will be evaluated on validation dataset every `valid_freq` epochs. Returns:",
"loss: {loss:>7f}, acc: {acc:>4.2f}\") losses.append(loss) if (epoch + 1) % valid_freq == 0:",
"= [] best_cnt = 0 best_acc = 0. for epoch in range(self.start_epoch, self.start_epoch",
"dataset every `valid_freq` epochs. Returns: Traning loss and valid accuracies. ''' num_train =",
"top_k) accuracies.append(acc) if acc > best_acc: best_acc = acc best_cnt = 0 print(f\"Best",
"RTDataLoader, loss_fn=nn.CrossEntropyLoss(), device='cpu', ckpt_file=None, ckpt_save_dir=None ) -> None: \"\"\" Args: `miner`: a nn.Module",
"List, Tuple from tqdm import tqdm import numpy as np import torch from",
"= acc best_cnt = 0 print(f\"Best checkpoint reached at best accuracy: {(acc *",
"{:>7f}\\tacc: {:>4.2f}% [{:>6}/{:>6d}]\".format( loss_val, 100 * acc, num_trained, num_train )) loss = running_loss",
"for bid, (qq, hh, tt, trips) in enumerate( self.dataloader.one_epoch(\"train\", batch_size, num_sample_batches, True) ):",
"\"\"\"Evaluate `self.miner` on dataset specified by `dataset_name`. Args: `dataset_name`: \"train\" | \"valid\" |",
"hh, tt, trips) in enumerate(tqdm( self.dataloader.one_epoch( dataset_name, batch_size ), desc='Predict' )): qq =",
"import in_top_k from utils import get_sample_prediction class RTLoss(nn.Module): def __init__(self, threshold: float )",
"enumerate(tqdm( self.dataloader.one_epoch( dataset_name, batch_size ), desc='Predict' )): qq = torch.from_numpy(qq).to(self.device) hh = torch.from_numpy(hh).to(self.device)",
"and given samples. \"\"\" if prediction_file: file_obj = open(prediction_file, 'w') accuracies = []",
"int = 1 ) -> List: '''Train `self.miner` on given training data loaded",
"% 10 == 0: loss_val = running_loss / num_trained acc = np.mean(running_acc) print(\"loss:",
"directory to save best model checkpoint \"\"\" self.loss_fn = loss_fn self.device = device",
"in range(self.start_epoch, self.start_epoch + epochs): self.miner.train() print(\"{:=^100}\".format(f\"Training epoch {epoch+1}\")) running_acc = [] running_loss",
"{loss:>7f}, acc: {acc:>4.2f}\") losses.append(loss) if (epoch + 1) % valid_freq == 0: acc",
"#!/usr/bin/env python # -*-coding:utf-8 -*- # @file : framework.py # @brief : Framework",
"torch.tensor(threshold) ) def forward(self, logits: torch.FloatTensor, targets: torch.LongTensor ) -> torch.Tensor: targ =",
"qq = torch.from_numpy(qq).to(self.device) hh = torch.from_numpy(hh).to(self.device) tt = torch.from_numpy(tt) logits = self.miner(qq, hh,",
"targ, dim=1), dim=0) class RTFramework(object): def __init__(self, miner: nn.Module, optimizer: optim.Optimizer, dataloader: RTDataLoader,",
"0 for bid, (qq, hh, tt, trips) in enumerate( self.dataloader.one_epoch(\"train\", batch_size, num_sample_batches, True)",
"accuracies = [] losses = [] best_cnt = 0 best_acc = 0. for",
"0 best_acc = 0. for epoch in range(self.start_epoch, self.start_epoch + epochs): self.miner.train() print(\"{:=^100}\".format(f\"Training",
") -> List: '''Train `self.miner` on given training data loaded from `self.dataloader`. Args:",
"t_str = prediction[-1] to_write = [q_str, h_str, t_str] + prediction file_obj.write(\",\".join(to_write) + \"\\n\")",
"(bid+1) % 10 == 0: loss_val = running_loss / num_trained acc = np.mean(running_acc)",
"file_obj = open(prediction_file, 'w') accuracies = [] self.miner.eval() # Do not accumulate gradient",
"training epochs in total `valid_freq`: `self.miner` will be evaluated on validation dataset every",
"_save_checkpoint(self, name: str, end_epoch: int ) -> None: \"\"\"Save model checkpoint.\"\"\" if not",
"self.optimizer.state_dict(), } ckpt_file = name + \".pth.tar\" ckpt_file = os.path.join(self.ckpt_dir, ckpt_file) torch.save(state_dict, ckpt_file)",
"from torch.nn import functional as F from dataloader import RTDataLoader from utils import",
"torch.no_grad(): for _, (qq, hh, tt, trips) in enumerate(tqdm( self.dataloader.one_epoch( dataset_name, batch_size ),",
"Early stopping. if best_cnt > 2: break print(\"\\n[Training finished] epochs: {} best_acc: {:.2f}\".format(",
"batch_size ), desc='Predict' )): qq = torch.from_numpy(qq).to(self.device) hh = torch.from_numpy(hh).to(self.device) tt = torch.from_numpy(tt)",
"100 print(f\"[epoch {epoch+1}] loss: {loss:>7f}, acc: {acc:>4.2f}\") losses.append(loss) if (epoch + 1) %",
"prediction[-1] to_write = [q_str, h_str, t_str] + prediction file_obj.write(\",\".join(to_write) + \"\\n\") if prediction_file:",
"[] self.miner.eval() # Do not accumulate gradient along propagation chain. with torch.no_grad(): for",
"acc = np.mean(running_acc) * 100 print(f\"[epoch {epoch+1}] loss: {loss:>7f}, acc: {acc:>4.2f}\") losses.append(loss) if",
"file_obj.close() return np.mean(accuracies) def _load_checkpoint(self, ckpt: str) -> None: '''Load model checkpoint.''' if",
"class RTLoss(nn.Module): def __init__(self, threshold: float ) -> None: super(RTLoss, self).__init__() self.threshold =",
"checkpoint = torch.load(ckpt) print(f\"Successfully loaded checkpoint '{ckpt}'\") self.miner.load_state_dict(checkpoint['model']) self.optimizer.load_state_dict(checkpoint['optimizer']) self.start_epoch = checkpoint['start_epoch'] else:",
"on given training data loaded from `self.dataloader`. Args: `top_k`: for computing Hit@k `batch_size`:",
"functional as F from dataloader import RTDataLoader from utils import in_top_k from utils",
"losses.append(loss) if (epoch + 1) % valid_freq == 0: acc = self.eval(\"valid\", batch_size,",
"on dataset specified by `dataset_name`. Args: `dataset_name`: \"train\" | \"valid\" | \"test\" `prediction_file`:",
"num_train = len(self.dataloader.train) if self.dataloader.query_include_reverse: num_train *= 2 accuracies = [] losses =",
"qq = torch.from_numpy(qq).to(self.device) hh = torch.from_numpy(hh).to(self.device) tt = torch.from_numpy(tt).to(self.device) logits = self.miner(qq, hh,",
"{epoch+1}] loss: {loss:>7f}, acc: {acc:>4.2f}\") losses.append(loss) if (epoch + 1) % valid_freq ==",
"running_acc = [] running_loss = 0. num_trained = 0 for bid, (qq, hh,",
"loss.backward() self.optimizer.step() bool_top_k = in_top_k(tt, logits, top_k) running_acc += bool_top_k.tolist() running_loss += loss.item()",
"def eval(self, dataset_name: str, batch_size: str, top_k: int, prediction_file=None ) -> Tuple[torch.Tensor, float]:",
"`self.miner` will be evaluated on validation dataset every `valid_freq` epochs. Returns: Traning loss",
"@brief : Framework for training, evaluating and saving models. # @author : <NAME>",
"self.dataloader.one_epoch(\"train\", batch_size, num_sample_batches, True) ): qq = torch.from_numpy(qq).to(self.device) hh = torch.from_numpy(hh).to(self.device) tt =",
"'w') accuracies = [] self.miner.eval() # Do not accumulate gradient along propagation chain.",
"for _, (qq, hh, tt, trips) in enumerate(tqdm( self.dataloader.one_epoch( dataset_name, batch_size ), desc='Predict'",
"int ) -> None: \"\"\"Save model checkpoint.\"\"\" if not self.ckpt_dir: return state_dict =",
"= len(self.dataloader.train) if self.dataloader.query_include_reverse: num_train *= 2 accuracies = [] losses = []",
"best_cnt += 1 # Early stopping. if best_cnt > 2: break print(\"\\n[Training finished]",
"self.dataloader = dataloader self.start_epoch = 0 if ckpt_file: self._load_checkpoint(ckpt_file) def train(self, top_k: int,",
"a nn.Module instance for logic rule mining `optimizer`: an Optimizer instance `dataloader`: Data",
"best model checkpoint \"\"\" self.loss_fn = loss_fn self.device = device self.ckpt_dir = ckpt_save_dir",
"= prediction[-1] to_write = [q_str, h_str, t_str] + prediction file_obj.write(\",\".join(to_write) + \"\\n\") if",
"return state_dict = { 'start_epoch': end_epoch, 'model': self.miner.state_dict(), 'optimizer': self.optimizer.state_dict(), } ckpt_file =",
"| 'cuda' `ckpt_file`: path to saved model checkpoints `ckpt_save_dir`: directory to save best",
"= [] losses = [] best_cnt = 0 best_acc = 0. for epoch",
"* 100):.2f}%\") self._save_checkpoint(\"checkpoint\", epoch) else: best_cnt += 1 # Early stopping. if best_cnt",
"reached at best accuracy: {(acc * 100):.2f}%\") self._save_checkpoint(\"checkpoint\", epoch) else: best_cnt += 1",
"`top_k`: for computing Hit@k `batch_size`: mini batch size `num_sample_batches`: max number of batches",
"utils import in_top_k from utils import get_sample_prediction class RTLoss(nn.Module): def __init__(self, threshold: float",
"hh.cpu().numpy() tt = tt.cpu().numpy() for bid, (q, h, t) in enumerate(zip(qq, hh, tt)):",
"os.path.isfile(ckpt): checkpoint = torch.load(ckpt) print(f\"Successfully loaded checkpoint '{ckpt}'\") self.miner.load_state_dict(checkpoint['model']) self.optimizer.load_state_dict(checkpoint['optimizer']) self.start_epoch = checkpoint['start_epoch']",
"end_epoch: int ) -> None: \"\"\"Save model checkpoint.\"\"\" if not self.ckpt_dir: return state_dict",
"tt, trips) in enumerate( self.dataloader.one_epoch(\"train\", batch_size, num_sample_batches, True) ): qq = torch.from_numpy(qq).to(self.device) hh",
"best_cnt = 0 print(f\"Best checkpoint reached at best accuracy: {(acc * 100):.2f}%\") self._save_checkpoint(\"checkpoint\",",
"checkpoint reached at best accuracy: {(acc * 100):.2f}%\") self._save_checkpoint(\"checkpoint\", epoch) else: best_cnt +=",
"prediction file_obj.write(\",\".join(to_write) + \"\\n\") if prediction_file: file_obj.close() return np.mean(accuracies) def _load_checkpoint(self, ckpt: str)",
"Do not accumulate gradient along propagation chain. with torch.no_grad(): for _, (qq, hh,",
"valid_freq == 0: acc = self.eval(\"valid\", batch_size, top_k) accuracies.append(acc) if acc > best_acc:",
"in total `valid_freq`: `self.miner` will be evaluated on validation dataset every `valid_freq` epochs.",
"losses, accuracies def eval(self, dataset_name: str, batch_size: str, top_k: int, prediction_file=None ) ->",
"\"\"\" if prediction_file: file_obj = open(prediction_file, 'w') accuracies = [] self.miner.eval() # Do",
"= get_sample_prediction( t, logits[bid].cpu().numpy(), self.dataloader.id2ent ) t_str = prediction[-1] to_write = [q_str, h_str,",
"`device`: 'cpu' | 'cuda' `ckpt_file`: path to saved model checkpoints `ckpt_save_dir`: directory to",
"ckpt_save_dir=None ) -> None: \"\"\" Args: `miner`: a nn.Module instance for logic rule",
"from utils import in_top_k from utils import get_sample_prediction class RTLoss(nn.Module): def __init__(self, threshold:",
"import tqdm import numpy as np import torch from torch import optim, nn",
"nn from torch.nn import functional as F from dataloader import RTDataLoader from utils",
"top_k) running_acc += bool_top_k.tolist() running_loss += loss.item() * qq.size(0) num_trained += qq.size(0) if",
"num_train acc = np.mean(running_acc) * 100 print(f\"[epoch {epoch+1}] loss: {loss:>7f}, acc: {acc:>4.2f}\") losses.append(loss)",
"train(self, top_k: int, batch_size: int, num_sample_batches: int, epochs=20, valid_freq: int = 1 )",
"checkpoint '{ckpt}'\") self.miner.load_state_dict(checkpoint['model']) self.optimizer.load_state_dict(checkpoint['optimizer']) self.start_epoch = checkpoint['start_epoch'] else: raise Exception(f\"No checkpoint found at",
"`num_sample_batches`: max number of batches for one epoch `epochs`: max training epochs in",
"acc best_cnt = 0 print(f\"Best checkpoint reached at best accuracy: {(acc * 100):.2f}%\")",
"file_obj.write(\",\".join(to_write) + \"\\n\") if prediction_file: file_obj.close() return np.mean(accuracies) def _load_checkpoint(self, ckpt: str) ->",
"checkpoint['start_epoch'] else: raise Exception(f\"No checkpoint found at '{ckpt}'\") def _save_checkpoint(self, name: str, end_epoch:",
"num_sample_batches, True) ): qq = torch.from_numpy(qq).to(self.device) hh = torch.from_numpy(hh).to(self.device) tt = torch.from_numpy(tt).to(self.device) logits",
"logits, top_k) accuracies += bool_top_k.tolist() if prediction_file: qq = qq.cpu().numpy() hh = hh.cpu().numpy()",
"loss and valid accuracies. ''' num_train = len(self.dataloader.train) if self.dataloader.query_include_reverse: num_train *= 2",
"from torch import optim, nn from torch.nn import functional as F from dataloader",
"[] running_loss = 0. num_trained = 0 for bid, (qq, hh, tt, trips)",
"num_trained += qq.size(0) if (bid+1) % 10 == 0: loss_val = running_loss /",
"best_acc = acc best_cnt = 0 print(f\"Best checkpoint reached at best accuracy: {(acc",
"= in_top_k(tt, logits, top_k) running_acc += bool_top_k.tolist() running_loss += loss.item() * qq.size(0) num_trained",
"''' num_train = len(self.dataloader.train) if self.dataloader.query_include_reverse: num_train *= 2 accuracies = [] losses",
"int, epochs=20, valid_freq: int = 1 ) -> List: '''Train `self.miner` on given",
"forward(self, logits: torch.FloatTensor, targets: torch.LongTensor ) -> torch.Tensor: targ = F.one_hot(targets, logits.size(1)) #",
"stopping. if best_cnt > 2: break print(\"\\n[Training finished] epochs: {} best_acc: {:.2f}\".format( epoch",
"acc = self.eval(\"valid\", batch_size, top_k) accuracies.append(acc) if acc > best_acc: best_acc = acc",
"best_acc = 0. for epoch in range(self.start_epoch, self.start_epoch + epochs): self.miner.train() print(\"{:=^100}\".format(f\"Training epoch",
"threshold: float ) -> None: super(RTLoss, self).__init__() self.threshold = nn.parameter.Parameter( torch.tensor(threshold) ) def",
"batch_size: int, num_sample_batches: int, epochs=20, valid_freq: int = 1 ) -> List: '''Train",
"+= qq.size(0) if (bid+1) % 10 == 0: loss_val = running_loss / num_trained",
"miner self.optimizer = optimizer self.dataloader = dataloader self.start_epoch = 0 if ckpt_file: self._load_checkpoint(ckpt_file)",
"checkpoint \"\"\" self.loss_fn = loss_fn self.device = device self.ckpt_dir = ckpt_save_dir self.miner =",
"self.optimizer.zero_grad() loss.backward() self.optimizer.step() bool_top_k = in_top_k(tt, logits, top_k) running_acc += bool_top_k.tolist() running_loss +=",
"= miner self.optimizer = optimizer self.dataloader = dataloader self.start_epoch = 0 if ckpt_file:",
"= self.dataloader.id2ent[h] prediction = get_sample_prediction( t, logits[bid].cpu().numpy(), self.dataloader.id2ent ) t_str = prediction[-1] to_write",
"every `valid_freq` epochs. Returns: Traning loss and valid accuracies. ''' num_train = len(self.dataloader.train)",
"int, prediction_file=None ) -> Tuple[torch.Tensor, float]: \"\"\"Evaluate `self.miner` on dataset specified by `dataset_name`.",
"= [q_str, h_str, t_str] + prediction file_obj.write(\",\".join(to_write) + \"\\n\") if prediction_file: file_obj.close() return",
"num_entity) loss = torch.maximum(logits, self.threshold) return torch.mean(-torch.sum(torch.log(loss) * targ, dim=1), dim=0) class RTFramework(object):",
"Args: `top_k`: for computing Hit@k `batch_size`: mini batch size `num_sample_batches`: max number of",
"str, end_epoch: int ) -> None: \"\"\"Save model checkpoint.\"\"\" if not self.ckpt_dir: return",
"tt = torch.from_numpy(tt) logits = self.miner(qq, hh, trips).cpu() bool_top_k = in_top_k(tt, logits, top_k)",
"mining `optimizer`: an Optimizer instance `dataloader`: Data loader `loss_fn`: loss function `device`: 'cpu'",
"saving models. # @author : <NAME> # @email : <EMAIL> import os from",
"loader `loss_fn`: loss function `device`: 'cpu' | 'cuda' `ckpt_file`: path to saved model",
"miner: nn.Module, optimizer: optim.Optimizer, dataloader: RTDataLoader, loss_fn=nn.CrossEntropyLoss(), device='cpu', ckpt_file=None, ckpt_save_dir=None ) -> None:",
"running_loss = 0. num_trained = 0 for bid, (qq, hh, tt, trips) in",
"self.start_epoch = checkpoint['start_epoch'] else: raise Exception(f\"No checkpoint found at '{ckpt}'\") def _save_checkpoint(self, name:",
"epoch `epochs`: max training epochs in total `valid_freq`: `self.miner` will be evaluated on",
"for logic rule mining `optimizer`: an Optimizer instance `dataloader`: Data loader `loss_fn`: loss",
"__init__(self, threshold: float ) -> None: super(RTLoss, self).__init__() self.threshold = nn.parameter.Parameter( torch.tensor(threshold) )",
"= [] self.miner.eval() # Do not accumulate gradient along propagation chain. with torch.no_grad():",
"epoch in range(self.start_epoch, self.start_epoch + epochs): self.miner.train() print(\"{:=^100}\".format(f\"Training epoch {epoch+1}\")) running_acc = []",
"dataset_name: str, batch_size: str, top_k: int, prediction_file=None ) -> Tuple[torch.Tensor, float]: \"\"\"Evaluate `self.miner`",
"* targ, dim=1), dim=0) class RTFramework(object): def __init__(self, miner: nn.Module, optimizer: optim.Optimizer, dataloader:",
"= torch.load(ckpt) print(f\"Successfully loaded checkpoint '{ckpt}'\") self.miner.load_state_dict(checkpoint['model']) self.optimizer.load_state_dict(checkpoint['optimizer']) self.start_epoch = checkpoint['start_epoch'] else: raise",
")) loss = running_loss / num_train acc = np.mean(running_acc) * 100 print(f\"[epoch {epoch+1}]",
"float ) -> None: super(RTLoss, self).__init__() self.threshold = nn.parameter.Parameter( torch.tensor(threshold) ) def forward(self,",
"if self.dataloader.query_include_reverse: num_train *= 2 accuracies = [] losses = [] best_cnt =",
"training, evaluating and saving models. # @author : <NAME> # @email : <EMAIL>",
"[] best_cnt = 0 best_acc = 0. for epoch in range(self.start_epoch, self.start_epoch +",
"__init__(self, miner: nn.Module, optimizer: optim.Optimizer, dataloader: RTDataLoader, loss_fn=nn.CrossEntropyLoss(), device='cpu', ckpt_file=None, ckpt_save_dir=None ) ->",
"nn.Module instance for logic rule mining `optimizer`: an Optimizer instance `dataloader`: Data loader",
"= np.mean(running_acc) print(\"loss: {:>7f}\\tacc: {:>4.2f}% [{:>6}/{:>6d}]\".format( loss_val, 100 * acc, num_trained, num_train ))",
"enumerate(zip(qq, hh, tt)): q_str = self.dataloader.id2rel[q] h_str = self.dataloader.id2ent[h] prediction = get_sample_prediction( t,",
"tt = tt.cpu().numpy() for bid, (q, h, t) in enumerate(zip(qq, hh, tt)): q_str",
"checkpoint found at '{ckpt}'\") def _save_checkpoint(self, name: str, end_epoch: int ) -> None:",
"100 * acc, num_trained, num_train )) loss = running_loss / num_train acc =",
"self.ckpt_dir = ckpt_save_dir self.miner = miner self.optimizer = optimizer self.dataloader = dataloader self.start_epoch",
"{epoch+1}\")) running_acc = [] running_loss = 0. num_trained = 0 for bid, (qq,",
"+ prediction file_obj.write(\",\".join(to_write) + \"\\n\") if prediction_file: file_obj.close() return np.mean(accuracies) def _load_checkpoint(self, ckpt:",
"torch.from_numpy(tt) logits = self.miner(qq, hh, trips).cpu() bool_top_k = in_top_k(tt, logits, top_k) accuracies +=",
"0: acc = self.eval(\"valid\", batch_size, top_k) accuracies.append(acc) if acc > best_acc: best_acc =",
"= qq.cpu().numpy() hh = hh.cpu().numpy() tt = tt.cpu().numpy() for bid, (q, h, t)",
"finished] epochs: {} best_acc: {:.2f}\".format( epoch - self.start_epoch, best_acc )) return losses, accuracies",
"if best_cnt > 2: break print(\"\\n[Training finished] epochs: {} best_acc: {:.2f}\".format( epoch -",
"torch.FloatTensor, targets: torch.LongTensor ) -> torch.Tensor: targ = F.one_hot(targets, logits.size(1)) # `logits`: (batch_size,",
"models. # @author : <NAME> # @email : <EMAIL> import os from typing",
"= dataloader self.start_epoch = 0 if ckpt_file: self._load_checkpoint(ckpt_file) def train(self, top_k: int, batch_size:",
"[q_str, h_str, t_str] + prediction file_obj.write(\",\".join(to_write) + \"\\n\") if prediction_file: file_obj.close() return np.mean(accuracies)",
"in enumerate(zip(qq, hh, tt)): q_str = self.dataloader.id2rel[q] h_str = self.dataloader.id2ent[h] prediction = get_sample_prediction(",
"-> Tuple[torch.Tensor, float]: \"\"\"Evaluate `self.miner` on dataset specified by `dataset_name`. Args: `dataset_name`: \"train\"",
"* acc, num_trained, num_train )) loss = running_loss / num_train acc = np.mean(running_acc)",
"int, batch_size: int, num_sample_batches: int, epochs=20, valid_freq: int = 1 ) -> List:",
"self.optimizer = optimizer self.dataloader = dataloader self.start_epoch = 0 if ckpt_file: self._load_checkpoint(ckpt_file) def",
"(epoch + 1) % valid_freq == 0: acc = self.eval(\"valid\", batch_size, top_k) accuracies.append(acc)",
"if (epoch + 1) % valid_freq == 0: acc = self.eval(\"valid\", batch_size, top_k)",
"self._load_checkpoint(ckpt_file) def train(self, top_k: int, batch_size: int, num_sample_batches: int, epochs=20, valid_freq: int =",
"`miner`: a nn.Module instance for logic rule mining `optimizer`: an Optimizer instance `dataloader`:",
"`dataset_name`. Args: `dataset_name`: \"train\" | \"valid\" | \"test\" `prediction_file`: file path for output",
"# @brief : Framework for training, evaluating and saving models. # @author :",
"top_k: int, batch_size: int, num_sample_batches: int, epochs=20, valid_freq: int = 1 ) ->",
"= 0 for bid, (qq, hh, tt, trips) in enumerate( self.dataloader.one_epoch(\"train\", batch_size, num_sample_batches,",
"List: '''Train `self.miner` on given training data loaded from `self.dataloader`. Args: `top_k`: for",
"= torch.from_numpy(qq).to(self.device) hh = torch.from_numpy(hh).to(self.device) tt = torch.from_numpy(tt) logits = self.miner(qq, hh, trips).cpu()",
"self.loss_fn = loss_fn self.device = device self.ckpt_dir = ckpt_save_dir self.miner = miner self.optimizer",
"= hh.cpu().numpy() tt = tt.cpu().numpy() for bid, (q, h, t) in enumerate(zip(qq, hh,",
"<NAME> # @email : <EMAIL> import os from typing import List, Tuple from",
"torch.nn import functional as F from dataloader import RTDataLoader from utils import in_top_k",
"'start_epoch': end_epoch, 'model': self.miner.state_dict(), 'optimizer': self.optimizer.state_dict(), } ckpt_file = name + \".pth.tar\" ckpt_file",
"logits: torch.FloatTensor, targets: torch.LongTensor ) -> torch.Tensor: targ = F.one_hot(targets, logits.size(1)) # `logits`:",
"num_trained, num_train )) loss = running_loss / num_train acc = np.mean(running_acc) * 100",
"np.mean(accuracies) def _load_checkpoint(self, ckpt: str) -> None: '''Load model checkpoint.''' if os.path.isfile(ckpt): checkpoint",
"'cuda' `ckpt_file`: path to saved model checkpoints `ckpt_save_dir`: directory to save best model",
"torch.Tensor: targ = F.one_hot(targets, logits.size(1)) # `logits`: (batch_size, num_entity) loss = torch.maximum(logits, self.threshold)",
"nn.Module, optimizer: optim.Optimizer, dataloader: RTDataLoader, loss_fn=nn.CrossEntropyLoss(), device='cpu', ckpt_file=None, ckpt_save_dir=None ) -> None: \"\"\"",
"self.start_epoch = 0 if ckpt_file: self._load_checkpoint(ckpt_file) def train(self, top_k: int, batch_size: int, num_sample_batches:",
"len(self.dataloader.train) if self.dataloader.query_include_reverse: num_train *= 2 accuracies = [] losses = [] best_cnt",
"batch_size, num_sample_batches, True) ): qq = torch.from_numpy(qq).to(self.device) hh = torch.from_numpy(hh).to(self.device) tt = torch.from_numpy(tt).to(self.device)",
"device='cpu', ckpt_file=None, ckpt_save_dir=None ) -> None: \"\"\" Args: `miner`: a nn.Module instance for",
"Returns: Traning loss and valid accuracies. ''' num_train = len(self.dataloader.train) if self.dataloader.query_include_reverse: num_train",
"'{ckpt}'\") def _save_checkpoint(self, name: str, end_epoch: int ) -> None: \"\"\"Save model checkpoint.\"\"\"",
"`epochs`: max training epochs in total `valid_freq`: `self.miner` will be evaluated on validation",
"RTLoss(nn.Module): def __init__(self, threshold: float ) -> None: super(RTLoss, self).__init__() self.threshold = nn.parameter.Parameter(",
"logits.size(1)) # `logits`: (batch_size, num_entity) loss = torch.maximum(logits, self.threshold) return torch.mean(-torch.sum(torch.log(loss) * targ,",
"self.threshold = nn.parameter.Parameter( torch.tensor(threshold) ) def forward(self, logits: torch.FloatTensor, targets: torch.LongTensor ) ->",
"= device self.ckpt_dir = ckpt_save_dir self.miner = miner self.optimizer = optimizer self.dataloader =",
"def _save_checkpoint(self, name: str, end_epoch: int ) -> None: \"\"\"Save model checkpoint.\"\"\" if",
"an Optimizer instance `dataloader`: Data loader `loss_fn`: loss function `device`: 'cpu' | 'cuda'",
"numpy as np import torch from torch import optim, nn from torch.nn import",
"get_sample_prediction class RTLoss(nn.Module): def __init__(self, threshold: float ) -> None: super(RTLoss, self).__init__() self.threshold",
"@author : <NAME> # @email : <EMAIL> import os from typing import List,",
") -> torch.Tensor: targ = F.one_hot(targets, logits.size(1)) # `logits`: (batch_size, num_entity) loss =",
"for epoch in range(self.start_epoch, self.start_epoch + epochs): self.miner.train() print(\"{:=^100}\".format(f\"Training epoch {epoch+1}\")) running_acc =",
"valid_freq: int = 1 ) -> List: '''Train `self.miner` on given training data",
"one epoch `epochs`: max training epochs in total `valid_freq`: `self.miner` will be evaluated",
"prediction_file: file_obj.close() return np.mean(accuracies) def _load_checkpoint(self, ckpt: str) -> None: '''Load model checkpoint.'''",
"= self.miner(qq, hh, trips).cpu() bool_top_k = in_top_k(tt, logits, top_k) accuracies += bool_top_k.tolist() if",
"accuracies += bool_top_k.tolist() if prediction_file: qq = qq.cpu().numpy() hh = hh.cpu().numpy() tt =",
"framework.py # @brief : Framework for training, evaluating and saving models. # @author",
"break print(\"\\n[Training finished] epochs: {} best_acc: {:.2f}\".format( epoch - self.start_epoch, best_acc )) return",
"torch.from_numpy(qq).to(self.device) hh = torch.from_numpy(hh).to(self.device) tt = torch.from_numpy(tt) logits = self.miner(qq, hh, trips).cpu() bool_top_k",
"optim, nn from torch.nn import functional as F from dataloader import RTDataLoader from",
"_load_checkpoint(self, ckpt: str) -> None: '''Load model checkpoint.''' if os.path.isfile(ckpt): checkpoint = torch.load(ckpt)",
"max number of batches for one epoch `epochs`: max training epochs in total",
"F.one_hot(targets, logits.size(1)) # `logits`: (batch_size, num_entity) loss = torch.maximum(logits, self.threshold) return torch.mean(-torch.sum(torch.log(loss) *",
"Tuple[torch.Tensor, float]: \"\"\"Evaluate `self.miner` on dataset specified by `dataset_name`. Args: `dataset_name`: \"train\" |",
"Data loader `loss_fn`: loss function `device`: 'cpu' | 'cuda' `ckpt_file`: path to saved",
"| \"test\" `prediction_file`: file path for output prediction results Returns: Miner accuracy and",
"loss function `device`: 'cpu' | 'cuda' `ckpt_file`: path to saved model checkpoints `ckpt_save_dir`:",
"best_acc: {:.2f}\".format( epoch - self.start_epoch, best_acc )) return losses, accuracies def eval(self, dataset_name:",
"output prediction results Returns: Miner accuracy and given samples. \"\"\" if prediction_file: file_obj",
"tt) self.optimizer.zero_grad() loss.backward() self.optimizer.step() bool_top_k = in_top_k(tt, logits, top_k) running_acc += bool_top_k.tolist() running_loss",
"h, t) in enumerate(zip(qq, hh, tt)): q_str = self.dataloader.id2rel[q] h_str = self.dataloader.id2ent[h] prediction",
"True) ): qq = torch.from_numpy(qq).to(self.device) hh = torch.from_numpy(hh).to(self.device) tt = torch.from_numpy(tt).to(self.device) logits =",
"loaded checkpoint '{ckpt}'\") self.miner.load_state_dict(checkpoint['model']) self.optimizer.load_state_dict(checkpoint['optimizer']) self.start_epoch = checkpoint['start_epoch'] else: raise Exception(f\"No checkpoint found",
"[] losses = [] best_cnt = 0 best_acc = 0. for epoch in",
"'model': self.miner.state_dict(), 'optimizer': self.optimizer.state_dict(), } ckpt_file = name + \".pth.tar\" ckpt_file = os.path.join(self.ckpt_dir,",
"if not self.ckpt_dir: return state_dict = { 'start_epoch': end_epoch, 'model': self.miner.state_dict(), 'optimizer': self.optimizer.state_dict(),",
"utils import get_sample_prediction class RTLoss(nn.Module): def __init__(self, threshold: float ) -> None: super(RTLoss,",
"\"\"\" Args: `miner`: a nn.Module instance for logic rule mining `optimizer`: an Optimizer",
"'''Load model checkpoint.''' if os.path.isfile(ckpt): checkpoint = torch.load(ckpt) print(f\"Successfully loaded checkpoint '{ckpt}'\") self.miner.load_state_dict(checkpoint['model'])",
"for computing Hit@k `batch_size`: mini batch size `num_sample_batches`: max number of batches for",
"import functional as F from dataloader import RTDataLoader from utils import in_top_k from",
"_, (qq, hh, tt, trips) in enumerate(tqdm( self.dataloader.one_epoch( dataset_name, batch_size ), desc='Predict' )):",
"trips).cpu() bool_top_k = in_top_k(tt, logits, top_k) accuracies += bool_top_k.tolist() if prediction_file: qq =",
"tt)): q_str = self.dataloader.id2rel[q] h_str = self.dataloader.id2ent[h] prediction = get_sample_prediction( t, logits[bid].cpu().numpy(), self.dataloader.id2ent",
"ckpt_file: self._load_checkpoint(ckpt_file) def train(self, top_k: int, batch_size: int, num_sample_batches: int, epochs=20, valid_freq: int",
"-*- # @file : framework.py # @brief : Framework for training, evaluating and",
"t) in enumerate(zip(qq, hh, tt)): q_str = self.dataloader.id2rel[q] h_str = self.dataloader.id2ent[h] prediction =",
"= F.one_hot(targets, logits.size(1)) # `logits`: (batch_size, num_entity) loss = torch.maximum(logits, self.threshold) return torch.mean(-torch.sum(torch.log(loss)",
"self.device = device self.ckpt_dir = ckpt_save_dir self.miner = miner self.optimizer = optimizer self.dataloader",
"= 0 if ckpt_file: self._load_checkpoint(ckpt_file) def train(self, top_k: int, batch_size: int, num_sample_batches: int,",
"epoch - self.start_epoch, best_acc )) return losses, accuracies def eval(self, dataset_name: str, batch_size:",
"+ epochs): self.miner.train() print(\"{:=^100}\".format(f\"Training epoch {epoch+1}\")) running_acc = [] running_loss = 0. num_trained",
"best accuracy: {(acc * 100):.2f}%\") self._save_checkpoint(\"checkpoint\", epoch) else: best_cnt += 1 # Early",
"trips) in enumerate( self.dataloader.one_epoch(\"train\", batch_size, num_sample_batches, True) ): qq = torch.from_numpy(qq).to(self.device) hh =",
"return losses, accuracies def eval(self, dataset_name: str, batch_size: str, top_k: int, prediction_file=None )",
"= self.miner(qq, hh, trips) loss = self.loss_fn(logits, tt) self.optimizer.zero_grad() loss.backward() self.optimizer.step() bool_top_k =",
"`valid_freq` epochs. Returns: Traning loss and valid accuracies. ''' num_train = len(self.dataloader.train) if",
"= self.eval(\"valid\", batch_size, top_k) accuracies.append(acc) if acc > best_acc: best_acc = acc best_cnt",
"to_write = [q_str, h_str, t_str] + prediction file_obj.write(\",\".join(to_write) + \"\\n\") if prediction_file: file_obj.close()",
"return torch.mean(-torch.sum(torch.log(loss) * targ, dim=1), dim=0) class RTFramework(object): def __init__(self, miner: nn.Module, optimizer:",
"in_top_k(tt, logits, top_k) accuracies += bool_top_k.tolist() if prediction_file: qq = qq.cpu().numpy() hh =",
"import torch from torch import optim, nn from torch.nn import functional as F",
": <EMAIL> import os from typing import List, Tuple from tqdm import tqdm",
"`logits`: (batch_size, num_entity) loss = torch.maximum(logits, self.threshold) return torch.mean(-torch.sum(torch.log(loss) * targ, dim=1), dim=0)",
"from utils import get_sample_prediction class RTLoss(nn.Module): def __init__(self, threshold: float ) -> None:",
") -> None: \"\"\"Save model checkpoint.\"\"\" if not self.ckpt_dir: return state_dict = {",
"== 0: loss_val = running_loss / num_trained acc = np.mean(running_acc) print(\"loss: {:>7f}\\tacc: {:>4.2f}%",
"= [] running_loss = 0. num_trained = 0 for bid, (qq, hh, tt,",
"+= loss.item() * qq.size(0) num_trained += qq.size(0) if (bid+1) % 10 == 0:",
"acc, num_trained, num_train )) loss = running_loss / num_train acc = np.mean(running_acc) *",
"epochs): self.miner.train() print(\"{:=^100}\".format(f\"Training epoch {epoch+1}\")) running_acc = [] running_loss = 0. num_trained =",
"self.miner.eval() # Do not accumulate gradient along propagation chain. with torch.no_grad(): for _,",
"along propagation chain. with torch.no_grad(): for _, (qq, hh, tt, trips) in enumerate(tqdm(",
"+= bool_top_k.tolist() if prediction_file: qq = qq.cpu().numpy() hh = hh.cpu().numpy() tt = tt.cpu().numpy()",
"as F from dataloader import RTDataLoader from utils import in_top_k from utils import",
"torch from torch import optim, nn from torch.nn import functional as F from",
"valid accuracies. ''' num_train = len(self.dataloader.train) if self.dataloader.query_include_reverse: num_train *= 2 accuracies =",
"hh = hh.cpu().numpy() tt = tt.cpu().numpy() for bid, (q, h, t) in enumerate(zip(qq,",
"accuracies = [] self.miner.eval() # Do not accumulate gradient along propagation chain. with",
"`optimizer`: an Optimizer instance `dataloader`: Data loader `loss_fn`: loss function `device`: 'cpu' |",
"> best_acc: best_acc = acc best_cnt = 0 print(f\"Best checkpoint reached at best",
"{ 'start_epoch': end_epoch, 'model': self.miner.state_dict(), 'optimizer': self.optimizer.state_dict(), } ckpt_file = name + \".pth.tar\"",
"0: loss_val = running_loss / num_trained acc = np.mean(running_acc) print(\"loss: {:>7f}\\tacc: {:>4.2f}% [{:>6}/{:>6d}]\".format(",
"`valid_freq`: `self.miner` will be evaluated on validation dataset every `valid_freq` epochs. Returns: Traning",
") t_str = prediction[-1] to_write = [q_str, h_str, t_str] + prediction file_obj.write(\",\".join(to_write) +",
"function `device`: 'cpu' | 'cuda' `ckpt_file`: path to saved model checkpoints `ckpt_save_dir`: directory",
"`self.miner` on dataset specified by `dataset_name`. Args: `dataset_name`: \"train\" | \"valid\" | \"test\"",
"best_cnt = 0 best_acc = 0. for epoch in range(self.start_epoch, self.start_epoch + epochs):",
"self.dataloader.id2rel[q] h_str = self.dataloader.id2ent[h] prediction = get_sample_prediction( t, logits[bid].cpu().numpy(), self.dataloader.id2ent ) t_str =",
"for training, evaluating and saving models. # @author : <NAME> # @email :",
"loss_val = running_loss / num_trained acc = np.mean(running_acc) print(\"loss: {:>7f}\\tacc: {:>4.2f}% [{:>6}/{:>6d}]\".format( loss_val,",
"def __init__(self, threshold: float ) -> None: super(RTLoss, self).__init__() self.threshold = nn.parameter.Parameter( torch.tensor(threshold)",
"device self.ckpt_dir = ckpt_save_dir self.miner = miner self.optimizer = optimizer self.dataloader = dataloader",
"/ num_trained acc = np.mean(running_acc) print(\"loss: {:>7f}\\tacc: {:>4.2f}% [{:>6}/{:>6d}]\".format( loss_val, 100 * acc,",
"running_loss / num_trained acc = np.mean(running_acc) print(\"loss: {:>7f}\\tacc: {:>4.2f}% [{:>6}/{:>6d}]\".format( loss_val, 100 *",
"= 0 print(f\"Best checkpoint reached at best accuracy: {(acc * 100):.2f}%\") self._save_checkpoint(\"checkpoint\", epoch)",
"not accumulate gradient along propagation chain. with torch.no_grad(): for _, (qq, hh, tt,",
"\"\\n\") if prediction_file: file_obj.close() return np.mean(accuracies) def _load_checkpoint(self, ckpt: str) -> None: '''Load",
"from dataloader import RTDataLoader from utils import in_top_k from utils import get_sample_prediction class",
"os from typing import List, Tuple from tqdm import tqdm import numpy as",
"targets: torch.LongTensor ) -> torch.Tensor: targ = F.one_hot(targets, logits.size(1)) # `logits`: (batch_size, num_entity)",
"end_epoch, 'model': self.miner.state_dict(), 'optimizer': self.optimizer.state_dict(), } ckpt_file = name + \".pth.tar\" ckpt_file =",
"(q, h, t) in enumerate(zip(qq, hh, tt)): q_str = self.dataloader.id2rel[q] h_str = self.dataloader.id2ent[h]",
"RTDataLoader from utils import in_top_k from utils import get_sample_prediction class RTLoss(nn.Module): def __init__(self,",
"{acc:>4.2f}\") losses.append(loss) if (epoch + 1) % valid_freq == 0: acc = self.eval(\"valid\",",
"loss = self.loss_fn(logits, tt) self.optimizer.zero_grad() loss.backward() self.optimizer.step() bool_top_k = in_top_k(tt, logits, top_k) running_acc",
"optim.Optimizer, dataloader: RTDataLoader, loss_fn=nn.CrossEntropyLoss(), device='cpu', ckpt_file=None, ckpt_save_dir=None ) -> None: \"\"\" Args: `miner`:",
"* qq.size(0) num_trained += qq.size(0) if (bid+1) % 10 == 0: loss_val =",
"h_str = self.dataloader.id2ent[h] prediction = get_sample_prediction( t, logits[bid].cpu().numpy(), self.dataloader.id2ent ) t_str = prediction[-1]",
"for output prediction results Returns: Miner accuracy and given samples. \"\"\" if prediction_file:",
"logic rule mining `optimizer`: an Optimizer instance `dataloader`: Data loader `loss_fn`: loss function",
"found at '{ckpt}'\") def _save_checkpoint(self, name: str, end_epoch: int ) -> None: \"\"\"Save",
": framework.py # @brief : Framework for training, evaluating and saving models. #",
"torch.mean(-torch.sum(torch.log(loss) * targ, dim=1), dim=0) class RTFramework(object): def __init__(self, miner: nn.Module, optimizer: optim.Optimizer,",
"loss.item() * qq.size(0) num_trained += qq.size(0) if (bid+1) % 10 == 0: loss_val",
"1 ) -> List: '''Train `self.miner` on given training data loaded from `self.dataloader`.",
"enumerate( self.dataloader.one_epoch(\"train\", batch_size, num_sample_batches, True) ): qq = torch.from_numpy(qq).to(self.device) hh = torch.from_numpy(hh).to(self.device) tt",
"self.optimizer.load_state_dict(checkpoint['optimizer']) self.start_epoch = checkpoint['start_epoch'] else: raise Exception(f\"No checkpoint found at '{ckpt}'\") def _save_checkpoint(self,",
"if (bid+1) % 10 == 0: loss_val = running_loss / num_trained acc =",
"tt.cpu().numpy() for bid, (q, h, t) in enumerate(zip(qq, hh, tt)): q_str = self.dataloader.id2rel[q]",
"get_sample_prediction( t, logits[bid].cpu().numpy(), self.dataloader.id2ent ) t_str = prediction[-1] to_write = [q_str, h_str, t_str]",
"instance for logic rule mining `optimizer`: an Optimizer instance `dataloader`: Data loader `loss_fn`:",
"model checkpoints `ckpt_save_dir`: directory to save best model checkpoint \"\"\" self.loss_fn = loss_fn",
"accuracies.append(acc) if acc > best_acc: best_acc = acc best_cnt = 0 print(f\"Best checkpoint",
"tt = torch.from_numpy(tt).to(self.device) logits = self.miner(qq, hh, trips) loss = self.loss_fn(logits, tt) self.optimizer.zero_grad()",
"from tqdm import tqdm import numpy as np import torch from torch import",
"self.miner(qq, hh, trips) loss = self.loss_fn(logits, tt) self.optimizer.zero_grad() loss.backward() self.optimizer.step() bool_top_k = in_top_k(tt,",
"100):.2f}%\") self._save_checkpoint(\"checkpoint\", epoch) else: best_cnt += 1 # Early stopping. if best_cnt >",
"optimizer: optim.Optimizer, dataloader: RTDataLoader, loss_fn=nn.CrossEntropyLoss(), device='cpu', ckpt_file=None, ckpt_save_dir=None ) -> None: \"\"\" Args:",
"specified by `dataset_name`. Args: `dataset_name`: \"train\" | \"valid\" | \"test\" `prediction_file`: file path",
"import optim, nn from torch.nn import functional as F from dataloader import RTDataLoader",
"max training epochs in total `valid_freq`: `self.miner` will be evaluated on validation dataset",
"at best accuracy: {(acc * 100):.2f}%\") self._save_checkpoint(\"checkpoint\", epoch) else: best_cnt += 1 #",
"epochs: {} best_acc: {:.2f}\".format( epoch - self.start_epoch, best_acc )) return losses, accuracies def",
"torch.from_numpy(hh).to(self.device) tt = torch.from_numpy(tt) logits = self.miner(qq, hh, trips).cpu() bool_top_k = in_top_k(tt, logits,",
"self.miner.load_state_dict(checkpoint['model']) self.optimizer.load_state_dict(checkpoint['optimizer']) self.start_epoch = checkpoint['start_epoch'] else: raise Exception(f\"No checkpoint found at '{ckpt}'\") def",
"hh, tt, trips) in enumerate( self.dataloader.one_epoch(\"train\", batch_size, num_sample_batches, True) ): qq = torch.from_numpy(qq).to(self.device)",
"for bid, (q, h, t) in enumerate(zip(qq, hh, tt)): q_str = self.dataloader.id2rel[q] h_str",
"loss_fn self.device = device self.ckpt_dir = ckpt_save_dir self.miner = miner self.optimizer = optimizer",
"self).__init__() self.threshold = nn.parameter.Parameter( torch.tensor(threshold) ) def forward(self, logits: torch.FloatTensor, targets: torch.LongTensor )",
"(qq, hh, tt, trips) in enumerate( self.dataloader.one_epoch(\"train\", batch_size, num_sample_batches, True) ): qq =",
"str, top_k: int, prediction_file=None ) -> Tuple[torch.Tensor, float]: \"\"\"Evaluate `self.miner` on dataset specified",
"dataloader import RTDataLoader from utils import in_top_k from utils import get_sample_prediction class RTLoss(nn.Module):",
"= open(prediction_file, 'w') accuracies = [] self.miner.eval() # Do not accumulate gradient along",
"number of batches for one epoch `epochs`: max training epochs in total `valid_freq`:",
"print(\"loss: {:>7f}\\tacc: {:>4.2f}% [{:>6}/{:>6d}]\".format( loss_val, 100 * acc, num_trained, num_train )) loss =",
"file path for output prediction results Returns: Miner accuracy and given samples. \"\"\"",
"= self.loss_fn(logits, tt) self.optimizer.zero_grad() loss.backward() self.optimizer.step() bool_top_k = in_top_k(tt, logits, top_k) running_acc +=",
"# Early stopping. if best_cnt > 2: break print(\"\\n[Training finished] epochs: {} best_acc:",
"(qq, hh, tt, trips) in enumerate(tqdm( self.dataloader.one_epoch( dataset_name, batch_size ), desc='Predict' )): qq",
"loss = running_loss / num_train acc = np.mean(running_acc) * 100 print(f\"[epoch {epoch+1}] loss:",
"'{ckpt}'\") self.miner.load_state_dict(checkpoint['model']) self.optimizer.load_state_dict(checkpoint['optimizer']) self.start_epoch = checkpoint['start_epoch'] else: raise Exception(f\"No checkpoint found at '{ckpt}'\")",
"torch.load(ckpt) print(f\"Successfully loaded checkpoint '{ckpt}'\") self.miner.load_state_dict(checkpoint['model']) self.optimizer.load_state_dict(checkpoint['optimizer']) self.start_epoch = checkpoint['start_epoch'] else: raise Exception(f\"No",
"), desc='Predict' )): qq = torch.from_numpy(qq).to(self.device) hh = torch.from_numpy(hh).to(self.device) tt = torch.from_numpy(tt) logits",
"`batch_size`: mini batch size `num_sample_batches`: max number of batches for one epoch `epochs`:",
"= torch.from_numpy(tt) logits = self.miner(qq, hh, trips).cpu() bool_top_k = in_top_k(tt, logits, top_k) accuracies",
"num_sample_batches: int, epochs=20, valid_freq: int = 1 ) -> List: '''Train `self.miner` on",
"= tt.cpu().numpy() for bid, (q, h, t) in enumerate(zip(qq, hh, tt)): q_str =",
"path for output prediction results Returns: Miner accuracy and given samples. \"\"\" if",
"self.miner.train() print(\"{:=^100}\".format(f\"Training epoch {epoch+1}\")) running_acc = [] running_loss = 0. num_trained = 0",
"prediction_file: qq = qq.cpu().numpy() hh = hh.cpu().numpy() tt = tt.cpu().numpy() for bid, (q,",
"import List, Tuple from tqdm import tqdm import numpy as np import torch",
"`ckpt_file`: path to saved model checkpoints `ckpt_save_dir`: directory to save best model checkpoint",
"prediction_file=None ) -> Tuple[torch.Tensor, float]: \"\"\"Evaluate `self.miner` on dataset specified by `dataset_name`. Args:",
"accuracies. ''' num_train = len(self.dataloader.train) if self.dataloader.query_include_reverse: num_train *= 2 accuracies = []",
"Args: `dataset_name`: \"train\" | \"valid\" | \"test\" `prediction_file`: file path for output prediction",
"ckpt_file=None, ckpt_save_dir=None ) -> None: \"\"\" Args: `miner`: a nn.Module instance for logic",
"if prediction_file: qq = qq.cpu().numpy() hh = hh.cpu().numpy() tt = tt.cpu().numpy() for bid,",
"best_acc )) return losses, accuracies def eval(self, dataset_name: str, batch_size: str, top_k: int,",
"`self.dataloader`. Args: `top_k`: for computing Hit@k `batch_size`: mini batch size `num_sample_batches`: max number",
"dim=1), dim=0) class RTFramework(object): def __init__(self, miner: nn.Module, optimizer: optim.Optimizer, dataloader: RTDataLoader, loss_fn=nn.CrossEntropyLoss(),",
"\"train\" | \"valid\" | \"test\" `prediction_file`: file path for output prediction results Returns:",
"{:>4.2f}% [{:>6}/{:>6d}]\".format( loss_val, 100 * acc, num_trained, num_train )) loss = running_loss /",
"raise Exception(f\"No checkpoint found at '{ckpt}'\") def _save_checkpoint(self, name: str, end_epoch: int )",
"import numpy as np import torch from torch import optim, nn from torch.nn",
"'cpu' | 'cuda' `ckpt_file`: path to saved model checkpoints `ckpt_save_dir`: directory to save",
"= 1 ) -> List: '''Train `self.miner` on given training data loaded from",
"desc='Predict' )): qq = torch.from_numpy(qq).to(self.device) hh = torch.from_numpy(hh).to(self.device) tt = torch.from_numpy(tt) logits =",
"training data loaded from `self.dataloader`. Args: `top_k`: for computing Hit@k `batch_size`: mini batch",
"logits[bid].cpu().numpy(), self.dataloader.id2ent ) t_str = prediction[-1] to_write = [q_str, h_str, t_str] + prediction",
"\"test\" `prediction_file`: file path for output prediction results Returns: Miner accuracy and given",
"/ num_train acc = np.mean(running_acc) * 100 print(f\"[epoch {epoch+1}] loss: {loss:>7f}, acc: {acc:>4.2f}\")",
"accumulate gradient along propagation chain. with torch.no_grad(): for _, (qq, hh, tt, trips)",
"torch import optim, nn from torch.nn import functional as F from dataloader import",
"self.miner.state_dict(), 'optimizer': self.optimizer.state_dict(), } ckpt_file = name + \".pth.tar\" ckpt_file = os.path.join(self.ckpt_dir, ckpt_file)",
"= loss_fn self.device = device self.ckpt_dir = ckpt_save_dir self.miner = miner self.optimizer =",
"): qq = torch.from_numpy(qq).to(self.device) hh = torch.from_numpy(hh).to(self.device) tt = torch.from_numpy(tt).to(self.device) logits = self.miner(qq,",
"best_cnt > 2: break print(\"\\n[Training finished] epochs: {} best_acc: {:.2f}\".format( epoch - self.start_epoch,",
"to saved model checkpoints `ckpt_save_dir`: directory to save best model checkpoint \"\"\" self.loss_fn",
"save best model checkpoint \"\"\" self.loss_fn = loss_fn self.device = device self.ckpt_dir =",
"+= bool_top_k.tolist() running_loss += loss.item() * qq.size(0) num_trained += qq.size(0) if (bid+1) %",
"propagation chain. with torch.no_grad(): for _, (qq, hh, tt, trips) in enumerate(tqdm( self.dataloader.one_epoch(",
"running_acc += bool_top_k.tolist() running_loss += loss.item() * qq.size(0) num_trained += qq.size(0) if (bid+1)",
"tqdm import tqdm import numpy as np import torch from torch import optim,",
"self.dataloader.query_include_reverse: num_train *= 2 accuracies = [] losses = [] best_cnt = 0",
"from `self.dataloader`. Args: `top_k`: for computing Hit@k `batch_size`: mini batch size `num_sample_batches`: max",
"= running_loss / num_trained acc = np.mean(running_acc) print(\"loss: {:>7f}\\tacc: {:>4.2f}% [{:>6}/{:>6d}]\".format( loss_val, 100",
"epoch {epoch+1}\")) running_acc = [] running_loss = 0. num_trained = 0 for bid,",
"t, logits[bid].cpu().numpy(), self.dataloader.id2ent ) t_str = prediction[-1] to_write = [q_str, h_str, t_str] +",
"prediction = get_sample_prediction( t, logits[bid].cpu().numpy(), self.dataloader.id2ent ) t_str = prediction[-1] to_write = [q_str,",
"in_top_k from utils import get_sample_prediction class RTLoss(nn.Module): def __init__(self, threshold: float ) ->",
"# Do not accumulate gradient along propagation chain. with torch.no_grad(): for _, (qq,",
"bool_top_k = in_top_k(tt, logits, top_k) accuracies += bool_top_k.tolist() if prediction_file: qq = qq.cpu().numpy()",
"[{:>6}/{:>6d}]\".format( loss_val, 100 * acc, num_trained, num_train )) loss = running_loss / num_train",
"losses = [] best_cnt = 0 best_acc = 0. for epoch in range(self.start_epoch,",
")): qq = torch.from_numpy(qq).to(self.device) hh = torch.from_numpy(hh).to(self.device) tt = torch.from_numpy(tt) logits = self.miner(qq,",
"hh = torch.from_numpy(hh).to(self.device) tt = torch.from_numpy(tt) logits = self.miner(qq, hh, trips).cpu() bool_top_k =",
"`loss_fn`: loss function `device`: 'cpu' | 'cuda' `ckpt_file`: path to saved model checkpoints",
"saved model checkpoints `ckpt_save_dir`: directory to save best model checkpoint \"\"\" self.loss_fn =",
"h_str, t_str] + prediction file_obj.write(\",\".join(to_write) + \"\\n\") if prediction_file: file_obj.close() return np.mean(accuracies) def",
"for one epoch `epochs`: max training epochs in total `valid_freq`: `self.miner` will be",
"will be evaluated on validation dataset every `valid_freq` epochs. Returns: Traning loss and",
"dataset_name, batch_size ), desc='Predict' )): qq = torch.from_numpy(qq).to(self.device) hh = torch.from_numpy(hh).to(self.device) tt =",
"0. for epoch in range(self.start_epoch, self.start_epoch + epochs): self.miner.train() print(\"{:=^100}\".format(f\"Training epoch {epoch+1}\")) running_acc",
"name: str, end_epoch: int ) -> None: \"\"\"Save model checkpoint.\"\"\" if not self.ckpt_dir:",
"> 2: break print(\"\\n[Training finished] epochs: {} best_acc: {:.2f}\".format( epoch - self.start_epoch, best_acc",
"self._save_checkpoint(\"checkpoint\", epoch) else: best_cnt += 1 # Early stopping. if best_cnt > 2:",
"python # -*-coding:utf-8 -*- # @file : framework.py # @brief : Framework for",
"@email : <EMAIL> import os from typing import List, Tuple from tqdm import",
"0 print(f\"Best checkpoint reached at best accuracy: {(acc * 100):.2f}%\") self._save_checkpoint(\"checkpoint\", epoch) else:",
"str) -> None: '''Load model checkpoint.''' if os.path.isfile(ckpt): checkpoint = torch.load(ckpt) print(f\"Successfully loaded",
"eval(self, dataset_name: str, batch_size: str, top_k: int, prediction_file=None ) -> Tuple[torch.Tensor, float]: \"\"\"Evaluate",
": <NAME> # @email : <EMAIL> import os from typing import List, Tuple",
"'''Train `self.miner` on given training data loaded from `self.dataloader`. Args: `top_k`: for computing",
"hh = torch.from_numpy(hh).to(self.device) tt = torch.from_numpy(tt).to(self.device) logits = self.miner(qq, hh, trips) loss =",
"if ckpt_file: self._load_checkpoint(ckpt_file) def train(self, top_k: int, batch_size: int, num_sample_batches: int, epochs=20, valid_freq:",
"# @file : framework.py # @brief : Framework for training, evaluating and saving",
"logits = self.miner(qq, hh, trips).cpu() bool_top_k = in_top_k(tt, logits, top_k) accuracies += bool_top_k.tolist()",
"# -*-coding:utf-8 -*- # @file : framework.py # @brief : Framework for training,",
"ckpt_save_dir self.miner = miner self.optimizer = optimizer self.dataloader = dataloader self.start_epoch = 0",
"dim=0) class RTFramework(object): def __init__(self, miner: nn.Module, optimizer: optim.Optimizer, dataloader: RTDataLoader, loss_fn=nn.CrossEntropyLoss(), device='cpu',",
"= 0. for epoch in range(self.start_epoch, self.start_epoch + epochs): self.miner.train() print(\"{:=^100}\".format(f\"Training epoch {epoch+1}\"))",
"torch.from_numpy(hh).to(self.device) tt = torch.from_numpy(tt).to(self.device) logits = self.miner(qq, hh, trips) loss = self.loss_fn(logits, tt)",
"2 accuracies = [] losses = [] best_cnt = 0 best_acc = 0.",
"optimizer self.dataloader = dataloader self.start_epoch = 0 if ckpt_file: self._load_checkpoint(ckpt_file) def train(self, top_k:",
"1 # Early stopping. if best_cnt > 2: break print(\"\\n[Training finished] epochs: {}",
"-> torch.Tensor: targ = F.one_hot(targets, logits.size(1)) # `logits`: (batch_size, num_entity) loss = torch.maximum(logits,",
"None: '''Load model checkpoint.''' if os.path.isfile(ckpt): checkpoint = torch.load(ckpt) print(f\"Successfully loaded checkpoint '{ckpt}'\")",
"rule mining `optimizer`: an Optimizer instance `dataloader`: Data loader `loss_fn`: loss function `device`:",
"given training data loaded from `self.dataloader`. Args: `top_k`: for computing Hit@k `batch_size`: mini",
"not self.ckpt_dir: return state_dict = { 'start_epoch': end_epoch, 'model': self.miner.state_dict(), 'optimizer': self.optimizer.state_dict(), }",
"bool_top_k.tolist() running_loss += loss.item() * qq.size(0) num_trained += qq.size(0) if (bid+1) % 10",
"num_trained acc = np.mean(running_acc) print(\"loss: {:>7f}\\tacc: {:>4.2f}% [{:>6}/{:>6d}]\".format( loss_val, 100 * acc, num_trained,",
"10 == 0: loss_val = running_loss / num_trained acc = np.mean(running_acc) print(\"loss: {:>7f}\\tacc:",
"return np.mean(accuracies) def _load_checkpoint(self, ckpt: str) -> None: '''Load model checkpoint.''' if os.path.isfile(ckpt):",
"qq.size(0) num_trained += qq.size(0) if (bid+1) % 10 == 0: loss_val = running_loss",
"2: break print(\"\\n[Training finished] epochs: {} best_acc: {:.2f}\".format( epoch - self.start_epoch, best_acc ))",
"accuracy and given samples. \"\"\" if prediction_file: file_obj = open(prediction_file, 'w') accuracies =",
"if prediction_file: file_obj = open(prediction_file, 'w') accuracies = [] self.miner.eval() # Do not",
"q_str = self.dataloader.id2rel[q] h_str = self.dataloader.id2ent[h] prediction = get_sample_prediction( t, logits[bid].cpu().numpy(), self.dataloader.id2ent )",
"to save best model checkpoint \"\"\" self.loss_fn = loss_fn self.device = device self.ckpt_dir",
"top_k: int, prediction_file=None ) -> Tuple[torch.Tensor, float]: \"\"\"Evaluate `self.miner` on dataset specified by",
"<EMAIL> import os from typing import List, Tuple from tqdm import tqdm import",
"dataloader: RTDataLoader, loss_fn=nn.CrossEntropyLoss(), device='cpu', ckpt_file=None, ckpt_save_dir=None ) -> None: \"\"\" Args: `miner`: a",
"path to saved model checkpoints `ckpt_save_dir`: directory to save best model checkpoint \"\"\"",
"evaluated on validation dataset every `valid_freq` epochs. Returns: Traning loss and valid accuracies.",
"self.miner(qq, hh, trips).cpu() bool_top_k = in_top_k(tt, logits, top_k) accuracies += bool_top_k.tolist() if prediction_file:",
") -> None: \"\"\" Args: `miner`: a nn.Module instance for logic rule mining"
] |
[
"EventHandlerBASE Revision ID: <KEY> Revises: 6b5369ab5224 Create Date: 2021-02-17 20:15:42.776190 \"\"\" from alembic",
"to EventHandlerBASE Revision ID: <KEY> Revises: 6b5369ab5224 Create Date: 2021-02-17 20:15:42.776190 \"\"\" from",
"# revision identifiers, used by Alembic. revision = '<KEY>' down_revision = '6b5369ab5224' branch_labels",
"used by Alembic. revision = '<KEY>' down_revision = '6b5369ab5224' branch_labels = None depends_on",
"revision = '<KEY>' down_revision = '6b5369ab5224' branch_labels = None depends_on = None def",
"Alembic. revision = '<KEY>' down_revision = '6b5369ab5224' branch_labels = None depends_on = None",
"Revises: 6b5369ab5224 Create Date: 2021-02-17 20:15:42.776190 \"\"\" from alembic import op import sqlalchemy",
"as sa # revision identifiers, used by Alembic. revision = '<KEY>' down_revision =",
"6b5369ab5224 Create Date: 2021-02-17 20:15:42.776190 \"\"\" from alembic import op import sqlalchemy as",
"= '6b5369ab5224' branch_labels = None depends_on = None def upgrade(): op.add_column('EventHandlerBASE', sa.Column('IsEnabled', sa.Boolean,",
"import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision",
"'<KEY>' down_revision = '6b5369ab5224' branch_labels = None depends_on = None def upgrade(): op.add_column('EventHandlerBASE',",
"Create Date: 2021-02-17 20:15:42.776190 \"\"\" from alembic import op import sqlalchemy as sa",
"2021-02-17 20:15:42.776190 \"\"\" from alembic import op import sqlalchemy as sa # revision",
"down_revision = '6b5369ab5224' branch_labels = None depends_on = None def upgrade(): op.add_column('EventHandlerBASE', sa.Column('IsEnabled',",
"identifiers, used by Alembic. revision = '<KEY>' down_revision = '6b5369ab5224' branch_labels = None",
"sa # revision identifiers, used by Alembic. revision = '<KEY>' down_revision = '6b5369ab5224'",
"alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic.",
"None depends_on = None def upgrade(): op.add_column('EventHandlerBASE', sa.Column('IsEnabled', sa.Boolean, nullable=False, default=False)) def downgrade():",
"ID: <KEY> Revises: 6b5369ab5224 Create Date: 2021-02-17 20:15:42.776190 \"\"\" from alembic import op",
"= None depends_on = None def upgrade(): op.add_column('EventHandlerBASE', sa.Column('IsEnabled', sa.Boolean, nullable=False, default=False)) def",
"'6b5369ab5224' branch_labels = None depends_on = None def upgrade(): op.add_column('EventHandlerBASE', sa.Column('IsEnabled', sa.Boolean, nullable=False,",
"depends_on = None def upgrade(): op.add_column('EventHandlerBASE', sa.Column('IsEnabled', sa.Boolean, nullable=False, default=False)) def downgrade(): op.drop_column('EventHandlerBASE',",
"20:15:42.776190 \"\"\" from alembic import op import sqlalchemy as sa # revision identifiers,",
"= None def upgrade(): op.add_column('EventHandlerBASE', sa.Column('IsEnabled', sa.Boolean, nullable=False, default=False)) def downgrade(): op.drop_column('EventHandlerBASE', 'IsEnabled')",
"branch_labels = None depends_on = None def upgrade(): op.add_column('EventHandlerBASE', sa.Column('IsEnabled', sa.Boolean, nullable=False, default=False))",
"import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '<KEY>'",
"<KEY> Revises: 6b5369ab5224 Create Date: 2021-02-17 20:15:42.776190 \"\"\" from alembic import op import",
"from alembic import op import sqlalchemy as sa # revision identifiers, used by",
"by Alembic. revision = '<KEY>' down_revision = '6b5369ab5224' branch_labels = None depends_on =",
"column to EventHandlerBASE Revision ID: <KEY> Revises: 6b5369ab5224 Create Date: 2021-02-17 20:15:42.776190 \"\"\"",
"Date: 2021-02-17 20:15:42.776190 \"\"\" from alembic import op import sqlalchemy as sa #",
"Revision ID: <KEY> Revises: 6b5369ab5224 Create Date: 2021-02-17 20:15:42.776190 \"\"\" from alembic import",
"disable=no-member,invalid-name,line-too-long,trailing-whitespace \"\"\"Add IsEnabled column to EventHandlerBASE Revision ID: <KEY> Revises: 6b5369ab5224 Create Date:",
"# pylint: disable=no-member,invalid-name,line-too-long,trailing-whitespace \"\"\"Add IsEnabled column to EventHandlerBASE Revision ID: <KEY> Revises: 6b5369ab5224",
"\"\"\" from alembic import op import sqlalchemy as sa # revision identifiers, used",
"op import sqlalchemy as sa # revision identifiers, used by Alembic. revision =",
"pylint: disable=no-member,invalid-name,line-too-long,trailing-whitespace \"\"\"Add IsEnabled column to EventHandlerBASE Revision ID: <KEY> Revises: 6b5369ab5224 Create",
"IsEnabled column to EventHandlerBASE Revision ID: <KEY> Revises: 6b5369ab5224 Create Date: 2021-02-17 20:15:42.776190",
"sqlalchemy as sa # revision identifiers, used by Alembic. revision = '<KEY>' down_revision",
"revision identifiers, used by Alembic. revision = '<KEY>' down_revision = '6b5369ab5224' branch_labels =",
"\"\"\"Add IsEnabled column to EventHandlerBASE Revision ID: <KEY> Revises: 6b5369ab5224 Create Date: 2021-02-17",
"= '<KEY>' down_revision = '6b5369ab5224' branch_labels = None depends_on = None def upgrade():"
] |
[
"packages = ['percona-server-client'] Package(packages) self.configure(env) def configure(self, env): import params env.set_params(params) def start(self,",
"def install(self, env): packages = ['percona-server-client'] Package(packages) self.configure(env) def configure(self, env): import params",
"resource_management.core.resources.packaging import Package class Client(Script): def install(self, env): packages = ['percona-server-client'] Package(packages) self.configure(env)",
"import Package class Client(Script): def install(self, env): packages = ['percona-server-client'] Package(packages) self.configure(env) def",
"env.set_params(params) def start(self, env): import params env.set_params(params) def stop(self, env): import params env.set_params(params)",
"env.set_params(params) def stop(self, env): import params env.set_params(params) def status(self, env): import params env.set_params(params)",
"class Client(Script): def install(self, env): packages = ['percona-server-client'] Package(packages) self.configure(env) def configure(self, env):",
"from resource_management.libraries.script.script import Script from resource_management.core.resources.packaging import Package class Client(Script): def install(self, env):",
"stop(self, env): import params env.set_params(params) def status(self, env): import params env.set_params(params) if __name__",
"Package class Client(Script): def install(self, env): packages = ['percona-server-client'] Package(packages) self.configure(env) def configure(self,",
"params env.set_params(params) def stop(self, env): import params env.set_params(params) def status(self, env): import params",
"install(self, env): packages = ['percona-server-client'] Package(packages) self.configure(env) def configure(self, env): import params env.set_params(params)",
"start(self, env): import params env.set_params(params) def stop(self, env): import params env.set_params(params) def status(self,",
"= ['percona-server-client'] Package(packages) self.configure(env) def configure(self, env): import params env.set_params(params) def start(self, env):",
"Client(Script): def install(self, env): packages = ['percona-server-client'] Package(packages) self.configure(env) def configure(self, env): import",
"def stop(self, env): import params env.set_params(params) def status(self, env): import params env.set_params(params) if",
"env): packages = ['percona-server-client'] Package(packages) self.configure(env) def configure(self, env): import params env.set_params(params) def",
"self.configure(env) def configure(self, env): import params env.set_params(params) def start(self, env): import params env.set_params(params)",
"def configure(self, env): import params env.set_params(params) def start(self, env): import params env.set_params(params) def",
"params env.set_params(params) def status(self, env): import params env.set_params(params) if __name__ == \"__main__\": Client().execute()",
"import Script from resource_management.core.resources.packaging import Package class Client(Script): def install(self, env): packages =",
"env): import params env.set_params(params) def start(self, env): import params env.set_params(params) def stop(self, env):",
"from resource_management.core.resources.packaging import Package class Client(Script): def install(self, env): packages = ['percona-server-client'] Package(packages)",
"params env.set_params(params) def start(self, env): import params env.set_params(params) def stop(self, env): import params",
"import params env.set_params(params) def stop(self, env): import params env.set_params(params) def status(self, env): import",
"env): import params env.set_params(params) def stop(self, env): import params env.set_params(params) def status(self, env):",
"['percona-server-client'] Package(packages) self.configure(env) def configure(self, env): import params env.set_params(params) def start(self, env): import",
"configure(self, env): import params env.set_params(params) def start(self, env): import params env.set_params(params) def stop(self,",
"Package(packages) self.configure(env) def configure(self, env): import params env.set_params(params) def start(self, env): import params",
"resource_management.libraries.script.script import Script from resource_management.core.resources.packaging import Package class Client(Script): def install(self, env): packages",
"import params env.set_params(params) def status(self, env): import params env.set_params(params) if __name__ == \"__main__\":",
"import params env.set_params(params) def start(self, env): import params env.set_params(params) def stop(self, env): import",
"def start(self, env): import params env.set_params(params) def stop(self, env): import params env.set_params(params) def",
"env): import params env.set_params(params) def status(self, env): import params env.set_params(params) if __name__ ==",
"Script from resource_management.core.resources.packaging import Package class Client(Script): def install(self, env): packages = ['percona-server-client']"
] |
[
"Migration(migrations.Migration): dependencies = [ ('website', '0035_auto_20190625_0900'), ] operations = [ migrations.RenameField( model_name='verenigingen', old_name='ontgroening',",
"Django 2.2.1 on 2019-07-19 12:36 from django.db import migrations class Migration(migrations.Migration): dependencies =",
"= [ ('website', '0035_auto_20190625_0900'), ] operations = [ migrations.RenameField( model_name='verenigingen', old_name='ontgroening', new_name='introductietijd', ),",
"[ ('website', '0035_auto_20190625_0900'), ] operations = [ migrations.RenameField( model_name='verenigingen', old_name='ontgroening', new_name='introductietijd', ), ]",
"# Generated by Django 2.2.1 on 2019-07-19 12:36 from django.db import migrations class",
"by Django 2.2.1 on 2019-07-19 12:36 from django.db import migrations class Migration(migrations.Migration): dependencies",
"2.2.1 on 2019-07-19 12:36 from django.db import migrations class Migration(migrations.Migration): dependencies = [",
"12:36 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('website', '0035_auto_20190625_0900'), ]",
"django.db import migrations class Migration(migrations.Migration): dependencies = [ ('website', '0035_auto_20190625_0900'), ] operations =",
"import migrations class Migration(migrations.Migration): dependencies = [ ('website', '0035_auto_20190625_0900'), ] operations = [",
"class Migration(migrations.Migration): dependencies = [ ('website', '0035_auto_20190625_0900'), ] operations = [ migrations.RenameField( model_name='verenigingen',",
"from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('website', '0035_auto_20190625_0900'), ] operations",
"2019-07-19 12:36 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('website', '0035_auto_20190625_0900'),",
"dependencies = [ ('website', '0035_auto_20190625_0900'), ] operations = [ migrations.RenameField( model_name='verenigingen', old_name='ontgroening', new_name='introductietijd',",
"migrations class Migration(migrations.Migration): dependencies = [ ('website', '0035_auto_20190625_0900'), ] operations = [ migrations.RenameField(",
"on 2019-07-19 12:36 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('website',",
"Generated by Django 2.2.1 on 2019-07-19 12:36 from django.db import migrations class Migration(migrations.Migration):"
] |
[
"return \"Empty search string\", 400 # This is a very dumb proxy, we're",
"We're only going to google here, so let's just keep it in the",
"google if we don't get a query, and return a Bad Request. @myproxy.route('/',",
"400 # This is a very dumb proxy, we're only doing GET. @myproxy.route('/<path:req>',",
"google here, so let's just keep it in the proxy settings for now.",
"# Let's not spam google if we don't get a query, and return",
"= Flask('__name__') # Quick health check override @myproxy.route('/healthcheck', methods=['GET']) def health(): return \"OK\"",
"health check override @myproxy.route('/healthcheck', methods=['GET']) def health(): return \"OK\" # Let's not spam",
"not spam google if we don't get a query, and return a Bad",
"\"OK\" # Let's not spam google if we don't get a query, and",
"we're only doing GET. @myproxy.route('/<path:req>', methods=['GET']) def proxy(req): # We're only going to",
"# This is a very dumb proxy, we're only doing GET. @myproxy.route('/<path:req>', methods=['GET'])",
"Let's not spam google if we don't get a query, and return a",
"a very dumb proxy, we're only doing GET. @myproxy.route('/<path:req>', methods=['GET']) def proxy(req): #",
"\"Empty search string\", 400 # This is a very dumb proxy, we're only",
"search string\", 400 # This is a very dumb proxy, we're only doing",
"get a query, and return a Bad Request. @myproxy.route('/', methods=['GET']) def empty(): return",
"server from flask import Flask from requests import get def spawn_proxy(): myproxy =",
"# Quick health check override @myproxy.route('/healthcheck', methods=['GET']) def health(): return \"OK\" # Let's",
"dumb proxy, we're only doing GET. @myproxy.route('/<path:req>', methods=['GET']) def proxy(req): # We're only",
"requests import get def spawn_proxy(): myproxy = Flask('__name__') # Quick health check override",
"Bad Request. @myproxy.route('/', methods=['GET']) def empty(): return \"Empty search string\", 400 # This",
"let's just keep it in the proxy settings for now. target = 'https://www.google.com/'",
"Flask from requests import get def spawn_proxy(): myproxy = Flask('__name__') # Quick health",
"is a very dumb proxy, we're only doing GET. @myproxy.route('/<path:req>', methods=['GET']) def proxy(req):",
"def proxy(req): # We're only going to google here, so let's just keep",
"only doing GET. @myproxy.route('/<path:req>', methods=['GET']) def proxy(req): # We're only going to google",
"doing GET. @myproxy.route('/<path:req>', methods=['GET']) def proxy(req): # We're only going to google here,",
"to create a somewhat lightweight listening server from flask import Flask from requests",
"# We're only going to google here, so let's just keep it in",
"create a somewhat lightweight listening server from flask import Flask from requests import",
"very dumb proxy, we're only doing GET. @myproxy.route('/<path:req>', methods=['GET']) def proxy(req): # We're",
"so let's just keep it in the proxy settings for now. target =",
"just keep it in the proxy settings for now. target = 'https://www.google.com/' return",
"get def spawn_proxy(): myproxy = Flask('__name__') # Quick health check override @myproxy.route('/healthcheck', methods=['GET'])",
"def empty(): return \"Empty search string\", 400 # This is a very dumb",
"is used to create a somewhat lightweight listening server from flask import Flask",
"return \"OK\" # Let's not spam google if we don't get a query,",
"return a Bad Request. @myproxy.route('/', methods=['GET']) def empty(): return \"Empty search string\", 400",
"def health(): return \"OK\" # Let's not spam google if we don't get",
"@myproxy.route('/healthcheck', methods=['GET']) def health(): return \"OK\" # Let's not spam google if we",
"from requests import get def spawn_proxy(): myproxy = Flask('__name__') # Quick health check",
"def spawn_proxy(): myproxy = Flask('__name__') # Quick health check override @myproxy.route('/healthcheck', methods=['GET']) def",
"# Flask is used to create a somewhat lightweight listening server from flask",
"don't get a query, and return a Bad Request. @myproxy.route('/', methods=['GET']) def empty():",
"a query, and return a Bad Request. @myproxy.route('/', methods=['GET']) def empty(): return \"Empty",
"a Bad Request. @myproxy.route('/', methods=['GET']) def empty(): return \"Empty search string\", 400 #",
"it in the proxy settings for now. target = 'https://www.google.com/' return get(f'{target}/search?q={req}').content return",
"proxy(req): # We're only going to google here, so let's just keep it",
"This is a very dumb proxy, we're only doing GET. @myproxy.route('/<path:req>', methods=['GET']) def",
"health(): return \"OK\" # Let's not spam google if we don't get a",
"Flask is used to create a somewhat lightweight listening server from flask import",
"string\", 400 # This is a very dumb proxy, we're only doing GET.",
"and return a Bad Request. @myproxy.route('/', methods=['GET']) def empty(): return \"Empty search string\",",
"Request. @myproxy.route('/', methods=['GET']) def empty(): return \"Empty search string\", 400 # This is",
"a somewhat lightweight listening server from flask import Flask from requests import get",
"spam google if we don't get a query, and return a Bad Request.",
"Flask('__name__') # Quick health check override @myproxy.route('/healthcheck', methods=['GET']) def health(): return \"OK\" #",
"override @myproxy.route('/healthcheck', methods=['GET']) def health(): return \"OK\" # Let's not spam google if",
"spawn_proxy(): myproxy = Flask('__name__') # Quick health check override @myproxy.route('/healthcheck', methods=['GET']) def health():",
"methods=['GET']) def empty(): return \"Empty search string\", 400 # This is a very",
"@myproxy.route('/', methods=['GET']) def empty(): return \"Empty search string\", 400 # This is a",
"query, and return a Bad Request. @myproxy.route('/', methods=['GET']) def empty(): return \"Empty search",
"used to create a somewhat lightweight listening server from flask import Flask from",
"import get def spawn_proxy(): myproxy = Flask('__name__') # Quick health check override @myproxy.route('/healthcheck',",
"check override @myproxy.route('/healthcheck', methods=['GET']) def health(): return \"OK\" # Let's not spam google",
"in the proxy settings for now. target = 'https://www.google.com/' return get(f'{target}/search?q={req}').content return myproxy",
"methods=['GET']) def health(): return \"OK\" # Let's not spam google if we don't",
"only going to google here, so let's just keep it in the proxy",
"going to google here, so let's just keep it in the proxy settings",
"we don't get a query, and return a Bad Request. @myproxy.route('/', methods=['GET']) def",
"proxy, we're only doing GET. @myproxy.route('/<path:req>', methods=['GET']) def proxy(req): # We're only going",
"flask import Flask from requests import get def spawn_proxy(): myproxy = Flask('__name__') #",
"lightweight listening server from flask import Flask from requests import get def spawn_proxy():",
"here, so let's just keep it in the proxy settings for now. target",
"myproxy = Flask('__name__') # Quick health check override @myproxy.route('/healthcheck', methods=['GET']) def health(): return",
"if we don't get a query, and return a Bad Request. @myproxy.route('/', methods=['GET'])",
"to google here, so let's just keep it in the proxy settings for",
"keep it in the proxy settings for now. target = 'https://www.google.com/' return get(f'{target}/search?q={req}').content",
"@myproxy.route('/<path:req>', methods=['GET']) def proxy(req): # We're only going to google here, so let's",
"methods=['GET']) def proxy(req): # We're only going to google here, so let's just",
"listening server from flask import Flask from requests import get def spawn_proxy(): myproxy",
"Quick health check override @myproxy.route('/healthcheck', methods=['GET']) def health(): return \"OK\" # Let's not",
"#!/usr/bin/python # Flask is used to create a somewhat lightweight listening server from",
"GET. @myproxy.route('/<path:req>', methods=['GET']) def proxy(req): # We're only going to google here, so",
"import Flask from requests import get def spawn_proxy(): myproxy = Flask('__name__') # Quick",
"somewhat lightweight listening server from flask import Flask from requests import get def",
"empty(): return \"Empty search string\", 400 # This is a very dumb proxy,",
"from flask import Flask from requests import get def spawn_proxy(): myproxy = Flask('__name__')"
] |
[
"def minFlipsMonoIncr(self, S: str) -> int: n = len(S) min_diff = sum([a !=",
"S: str) -> int: n = len(S) min_diff = sum([a != b for",
"[min_diff] * (n+1) for zero_idx in range(n): if \"0\" == S[zero_idx]: dp_[zero_idx+1] =",
"* \"1\")]) dp_ = [min_diff] * (n+1) for zero_idx in range(n): if \"0\"",
"\"1\")]) dp_ = [min_diff] * (n+1) for zero_idx in range(n): if \"0\" ==",
"str) -> int: n = len(S) min_diff = sum([a != b for a,",
"b for a, b in zip(S, n * \"1\")]) dp_ = [min_diff] *",
"len(S) min_diff = sum([a != b for a, b in zip(S, n *",
"in zip(S, n * \"1\")]) dp_ = [min_diff] * (n+1) for zero_idx in",
"class Solution: def minFlipsMonoIncr(self, S: str) -> int: n = len(S) min_diff =",
"range(n): if \"0\" == S[zero_idx]: dp_[zero_idx+1] = dp_[zero_idx] - 1 else: dp_[zero_idx+1] =",
"for zero_idx in range(n): if \"0\" == S[zero_idx]: dp_[zero_idx+1] = dp_[zero_idx] - 1",
"n = len(S) min_diff = sum([a != b for a, b in zip(S,",
"a, b in zip(S, n * \"1\")]) dp_ = [min_diff] * (n+1) for",
"zero_idx in range(n): if \"0\" == S[zero_idx]: dp_[zero_idx+1] = dp_[zero_idx] - 1 else:",
"n * \"1\")]) dp_ = [min_diff] * (n+1) for zero_idx in range(n): if",
"for a, b in zip(S, n * \"1\")]) dp_ = [min_diff] * (n+1)",
"b in zip(S, n * \"1\")]) dp_ = [min_diff] * (n+1) for zero_idx",
"int: n = len(S) min_diff = sum([a != b for a, b in",
"sum([a != b for a, b in zip(S, n * \"1\")]) dp_ =",
"Solution: def minFlipsMonoIncr(self, S: str) -> int: n = len(S) min_diff = sum([a",
"!= b for a, b in zip(S, n * \"1\")]) dp_ = [min_diff]",
"= sum([a != b for a, b in zip(S, n * \"1\")]) dp_",
"(n+1) for zero_idx in range(n): if \"0\" == S[zero_idx]: dp_[zero_idx+1] = dp_[zero_idx] -",
"== S[zero_idx]: dp_[zero_idx+1] = dp_[zero_idx] - 1 else: dp_[zero_idx+1] = dp_[zero_idx] + 1",
"S[zero_idx]: dp_[zero_idx+1] = dp_[zero_idx] - 1 else: dp_[zero_idx+1] = dp_[zero_idx] + 1 return",
"minFlipsMonoIncr(self, S: str) -> int: n = len(S) min_diff = sum([a != b",
"dp_ = [min_diff] * (n+1) for zero_idx in range(n): if \"0\" == S[zero_idx]:",
"= [min_diff] * (n+1) for zero_idx in range(n): if \"0\" == S[zero_idx]: dp_[zero_idx+1]",
"-> int: n = len(S) min_diff = sum([a != b for a, b",
"= len(S) min_diff = sum([a != b for a, b in zip(S, n",
"min_diff = sum([a != b for a, b in zip(S, n * \"1\")])",
"<filename>Q926_Flip-String-to-Monotone-Increasing.py<gh_stars>0 class Solution: def minFlipsMonoIncr(self, S: str) -> int: n = len(S) min_diff",
"zip(S, n * \"1\")]) dp_ = [min_diff] * (n+1) for zero_idx in range(n):",
"\"0\" == S[zero_idx]: dp_[zero_idx+1] = dp_[zero_idx] - 1 else: dp_[zero_idx+1] = dp_[zero_idx] +",
"in range(n): if \"0\" == S[zero_idx]: dp_[zero_idx+1] = dp_[zero_idx] - 1 else: dp_[zero_idx+1]",
"dp_[zero_idx+1] = dp_[zero_idx] - 1 else: dp_[zero_idx+1] = dp_[zero_idx] + 1 return min(dp_)",
"if \"0\" == S[zero_idx]: dp_[zero_idx+1] = dp_[zero_idx] - 1 else: dp_[zero_idx+1] = dp_[zero_idx]",
"* (n+1) for zero_idx in range(n): if \"0\" == S[zero_idx]: dp_[zero_idx+1] = dp_[zero_idx]"
] |
[
"ascii strings unless we only want wide strings if not wide_only: for match",
"only want wide strings if not wide_only: for match in re_narrow.finditer(data): s =",
"match in re_narrow.finditer(data): s = match.group().decode('ascii') strings.append(s) cli_out(s, cli_mode) # print wide strings",
"least min-len characters long, instead of ' + 'the default 4.') self.parser =",
"wide strings unless we only want ascii strings if not ascii_only: for match",
"/usr/bin/env python import pefile import datetime import os import re from pecli.plugins.base import",
"{\"strings\": strings} def run_cli(self, args, pe, data): if args.ascii and args.wide: print(\"to print",
"re.compile(b'((?:[%s]\\x00){%d,})' % (ASCII_BYTE, min_len)) strings = [] # print ascii strings unless we",
"cli_out(s, cli_mode) strings.append(s) except UnicodeDecodeError: pass return {\"strings\": strings} def run_cli(self, args, pe,",
"'--min-len', type=int, default=4, help='Print sequences of ' + 'characters that are at least",
"long, instead of ' + 'the default 4.') self.parser = parser def get_results(self,",
"min-len characters long, instead of ' + 'the default 4.') self.parser = parser",
"strings} def run_cli(self, args, pe, data): if args.ascii and args.wide: print(\"to print both",
"strings if not wide_only: for match in re_narrow.finditer(data): s = match.group().decode('ascii') strings.append(s) cli_out(s,",
"= parser def get_results(self, data, min_len=4, wide_only=False, ascii_only=False, cli_mode=False): # regular expressions from",
"args.wide: print(\"to print both ascii and wide strings, omit both\") else: self.get_results(data, args.min_len,",
"not wide_only: for match in re_narrow.finditer(data): s = match.group().decode('ascii') strings.append(s) cli_out(s, cli_mode) #",
"'characters that are at least min-len characters long, instead of ' + 'the",
"for match in re_wide.finditer(data): try: s = match.group().decode('utf-16') cli_out(s, cli_mode) strings.append(s) except UnicodeDecodeError:",
"import pefile import datetime import os import re from pecli.plugins.base import Plugin from",
"action=\"store_true\", help=\"ASCII strings only\") parser.add_argument('--wide', '-w', action=\"store_true\", help=\"Wide strings only\") parser.add_argument('-n', '--min-len', type=int,",
"pass return {\"strings\": strings} def run_cli(self, args, pe, data): if args.ascii and args.wide:",
"strings.append(s) except UnicodeDecodeError: pass return {\"strings\": strings} def run_cli(self, args, pe, data): if",
"= match.group().decode('utf-16') cli_out(s, cli_mode) strings.append(s) except UnicodeDecodeError: pass return {\"strings\": strings} def run_cli(self,",
"default 4.') self.parser = parser def get_results(self, data, min_len=4, wide_only=False, ascii_only=False, cli_mode=False): #",
"'-a', action=\"store_true\", help=\"ASCII strings only\") parser.add_argument('--wide', '-w', action=\"store_true\", help=\"Wide strings only\") parser.add_argument('-n', '--min-len',",
"cli_out(s, cli_mode) # print wide strings unless we only want ascii strings if",
"4.') self.parser = parser def get_results(self, data, min_len=4, wide_only=False, ascii_only=False, cli_mode=False): # regular",
"if args.ascii and args.wide: print(\"to print both ascii and wide strings, omit both\")",
"action=\"store_true\", help=\"Wide strings only\") parser.add_argument('-n', '--min-len', type=int, default=4, help='Print sequences of ' +",
"instead of ' + 'the default 4.') self.parser = parser def get_results(self, data,",
"# https://github.com/fireeye/flare-floss/blob/master/floss/strings.py#L7-L9 re_narrow = re.compile(b'([%s]{%d,})' % (ASCII_BYTE, min_len)) re_wide = re.compile(b'((?:[%s]\\x00){%d,})' % (ASCII_BYTE,",
"!\\\"#\\$%&\\'\\(\\)\\*\\+,-\\./0123456789:;<=>\\?@ABCDEFGHIJKLMNOPQRSTUVWXYZ\\[\\]\\^_`abcdefghijklmnopqrstuvwxyz\\{\\|\\}\\\\\\~\\t\" class PluginStrings(Plugin): name = \"strings\" description = \"Extract strings from the PE",
"cli_mode=False): # regular expressions from flare-floss: # https://github.com/fireeye/flare-floss/blob/master/floss/strings.py#L7-L9 re_narrow = re.compile(b'([%s]{%d,})' % (ASCII_BYTE,",
"UnicodeDecodeError: pass return {\"strings\": strings} def run_cli(self, args, pe, data): if args.ascii and",
"re from pecli.plugins.base import Plugin from pecli.lib.utils import cli_out ASCII_BYTE = b\" !\\\"#\\$%&\\'\\(\\)\\*\\+,-\\./0123456789:;<=>\\?@ABCDEFGHIJKLMNOPQRSTUVWXYZ\\[\\]\\^_`abcdefghijklmnopqrstuvwxyz\\{\\|\\}\\\\\\~\\t\"",
"min_len=4, wide_only=False, ascii_only=False, cli_mode=False): # regular expressions from flare-floss: # https://github.com/fireeye/flare-floss/blob/master/floss/strings.py#L7-L9 re_narrow =",
"cli_mode) strings.append(s) except UnicodeDecodeError: pass return {\"strings\": strings} def run_cli(self, args, pe, data):",
"print both ascii and wide strings, omit both\") else: self.get_results(data, args.min_len, args.wide, args.ascii,",
"the PE file\" def add_arguments(self, parser): parser.add_argument('--ascii', '-a', action=\"store_true\", help=\"ASCII strings only\") parser.add_argument('--wide',",
"+ 'the default 4.') self.parser = parser def get_results(self, data, min_len=4, wide_only=False, ascii_only=False,",
"in re_narrow.finditer(data): s = match.group().decode('ascii') strings.append(s) cli_out(s, cli_mode) # print wide strings unless",
"print(\"to print both ascii and wide strings, omit both\") else: self.get_results(data, args.min_len, args.wide,",
"match.group().decode('ascii') strings.append(s) cli_out(s, cli_mode) # print wide strings unless we only want ascii",
"for match in re_narrow.finditer(data): s = match.group().decode('ascii') strings.append(s) cli_out(s, cli_mode) # print wide",
"ascii_only=False, cli_mode=False): # regular expressions from flare-floss: # https://github.com/fireeye/flare-floss/blob/master/floss/strings.py#L7-L9 re_narrow = re.compile(b'([%s]{%d,})' %",
"print ascii strings unless we only want wide strings if not wide_only: for",
"and args.wide: print(\"to print both ascii and wide strings, omit both\") else: self.get_results(data,",
"run_cli(self, args, pe, data): if args.ascii and args.wide: print(\"to print both ascii and",
"unless we only want wide strings if not wide_only: for match in re_narrow.finditer(data):",
"args.ascii and args.wide: print(\"to print both ascii and wide strings, omit both\") else:",
"PluginStrings(Plugin): name = \"strings\" description = \"Extract strings from the PE file\" def",
"wide strings if not wide_only: for match in re_narrow.finditer(data): s = match.group().decode('ascii') strings.append(s)",
"if not ascii_only: for match in re_wide.finditer(data): try: s = match.group().decode('utf-16') cli_out(s, cli_mode)",
"(ASCII_BYTE, min_len)) strings = [] # print ascii strings unless we only want",
"add_arguments(self, parser): parser.add_argument('--ascii', '-a', action=\"store_true\", help=\"ASCII strings only\") parser.add_argument('--wide', '-w', action=\"store_true\", help=\"Wide strings",
"print wide strings unless we only want ascii strings if not ascii_only: for",
"datetime import os import re from pecli.plugins.base import Plugin from pecli.lib.utils import cli_out",
"match.group().decode('utf-16') cli_out(s, cli_mode) strings.append(s) except UnicodeDecodeError: pass return {\"strings\": strings} def run_cli(self, args,",
"' + 'characters that are at least min-len characters long, instead of '",
"strings only\") parser.add_argument('--wide', '-w', action=\"store_true\", help=\"Wide strings only\") parser.add_argument('-n', '--min-len', type=int, default=4, help='Print",
"'the default 4.') self.parser = parser def get_results(self, data, min_len=4, wide_only=False, ascii_only=False, cli_mode=False):",
"strings = [] # print ascii strings unless we only want wide strings",
"default=4, help='Print sequences of ' + 'characters that are at least min-len characters",
"= \"strings\" description = \"Extract strings from the PE file\" def add_arguments(self, parser):",
"#! /usr/bin/env python import pefile import datetime import os import re from pecli.plugins.base",
"that are at least min-len characters long, instead of ' + 'the default",
"from flare-floss: # https://github.com/fireeye/flare-floss/blob/master/floss/strings.py#L7-L9 re_narrow = re.compile(b'([%s]{%d,})' % (ASCII_BYTE, min_len)) re_wide = re.compile(b'((?:[%s]\\x00){%d,})'",
"only want ascii strings if not ascii_only: for match in re_wide.finditer(data): try: s",
"match in re_wide.finditer(data): try: s = match.group().decode('utf-16') cli_out(s, cli_mode) strings.append(s) except UnicodeDecodeError: pass",
"\"Extract strings from the PE file\" def add_arguments(self, parser): parser.add_argument('--ascii', '-a', action=\"store_true\", help=\"ASCII",
"data, min_len=4, wide_only=False, ascii_only=False, cli_mode=False): # regular expressions from flare-floss: # https://github.com/fireeye/flare-floss/blob/master/floss/strings.py#L7-L9 re_narrow",
"pecli.lib.utils import cli_out ASCII_BYTE = b\" !\\\"#\\$%&\\'\\(\\)\\*\\+,-\\./0123456789:;<=>\\?@ABCDEFGHIJKLMNOPQRSTUVWXYZ\\[\\]\\^_`abcdefghijklmnopqrstuvwxyz\\{\\|\\}\\\\\\~\\t\" class PluginStrings(Plugin): name = \"strings\" description",
"# print ascii strings unless we only want wide strings if not wide_only:",
"Plugin from pecli.lib.utils import cli_out ASCII_BYTE = b\" !\\\"#\\$%&\\'\\(\\)\\*\\+,-\\./0123456789:;<=>\\?@ABCDEFGHIJKLMNOPQRSTUVWXYZ\\[\\]\\^_`abcdefghijklmnopqrstuvwxyz\\{\\|\\}\\\\\\~\\t\" class PluginStrings(Plugin): name =",
"re.compile(b'([%s]{%d,})' % (ASCII_BYTE, min_len)) re_wide = re.compile(b'((?:[%s]\\x00){%d,})' % (ASCII_BYTE, min_len)) strings = []",
"= re.compile(b'([%s]{%d,})' % (ASCII_BYTE, min_len)) re_wide = re.compile(b'((?:[%s]\\x00){%d,})' % (ASCII_BYTE, min_len)) strings =",
"b\" !\\\"#\\$%&\\'\\(\\)\\*\\+,-\\./0123456789:;<=>\\?@ABCDEFGHIJKLMNOPQRSTUVWXYZ\\[\\]\\^_`abcdefghijklmnopqrstuvwxyz\\{\\|\\}\\\\\\~\\t\" class PluginStrings(Plugin): name = \"strings\" description = \"Extract strings from the",
"strings from the PE file\" def add_arguments(self, parser): parser.add_argument('--ascii', '-a', action=\"store_true\", help=\"ASCII strings",
"characters long, instead of ' + 'the default 4.') self.parser = parser def",
"strings unless we only want ascii strings if not ascii_only: for match in",
"except UnicodeDecodeError: pass return {\"strings\": strings} def run_cli(self, args, pe, data): if args.ascii",
"file\" def add_arguments(self, parser): parser.add_argument('--ascii', '-a', action=\"store_true\", help=\"ASCII strings only\") parser.add_argument('--wide', '-w', action=\"store_true\",",
"args, pe, data): if args.ascii and args.wide: print(\"to print both ascii and wide",
"help=\"Wide strings only\") parser.add_argument('-n', '--min-len', type=int, default=4, help='Print sequences of ' + 'characters",
"re_narrow = re.compile(b'([%s]{%d,})' % (ASCII_BYTE, min_len)) re_wide = re.compile(b'((?:[%s]\\x00){%d,})' % (ASCII_BYTE, min_len)) strings",
"import Plugin from pecli.lib.utils import cli_out ASCII_BYTE = b\" !\\\"#\\$%&\\'\\(\\)\\*\\+,-\\./0123456789:;<=>\\?@ABCDEFGHIJKLMNOPQRSTUVWXYZ\\[\\]\\^_`abcdefghijklmnopqrstuvwxyz\\{\\|\\}\\\\\\~\\t\" class PluginStrings(Plugin): name",
"min_len)) strings = [] # print ascii strings unless we only want wide",
"parser.add_argument('--ascii', '-a', action=\"store_true\", help=\"ASCII strings only\") parser.add_argument('--wide', '-w', action=\"store_true\", help=\"Wide strings only\") parser.add_argument('-n',",
"import re from pecli.plugins.base import Plugin from pecli.lib.utils import cli_out ASCII_BYTE = b\"",
"parser def get_results(self, data, min_len=4, wide_only=False, ascii_only=False, cli_mode=False): # regular expressions from flare-floss:",
"data): if args.ascii and args.wide: print(\"to print both ascii and wide strings, omit",
"not ascii_only: for match in re_wide.finditer(data): try: s = match.group().decode('utf-16') cli_out(s, cli_mode) strings.append(s)",
"get_results(self, data, min_len=4, wide_only=False, ascii_only=False, cli_mode=False): # regular expressions from flare-floss: # https://github.com/fireeye/flare-floss/blob/master/floss/strings.py#L7-L9",
"pe, data): if args.ascii and args.wide: print(\"to print both ascii and wide strings,",
"min_len)) re_wide = re.compile(b'((?:[%s]\\x00){%d,})' % (ASCII_BYTE, min_len)) strings = [] # print ascii",
"both ascii and wide strings, omit both\") else: self.get_results(data, args.min_len, args.wide, args.ascii, cli_mode=True)",
"re_wide.finditer(data): try: s = match.group().decode('utf-16') cli_out(s, cli_mode) strings.append(s) except UnicodeDecodeError: pass return {\"strings\":",
"name = \"strings\" description = \"Extract strings from the PE file\" def add_arguments(self,",
"ascii_only: for match in re_wide.finditer(data): try: s = match.group().decode('utf-16') cli_out(s, cli_mode) strings.append(s) except",
"want ascii strings if not ascii_only: for match in re_wide.finditer(data): try: s =",
"import cli_out ASCII_BYTE = b\" !\\\"#\\$%&\\'\\(\\)\\*\\+,-\\./0123456789:;<=>\\?@ABCDEFGHIJKLMNOPQRSTUVWXYZ\\[\\]\\^_`abcdefghijklmnopqrstuvwxyz\\{\\|\\}\\\\\\~\\t\" class PluginStrings(Plugin): name = \"strings\" description =",
"only\") parser.add_argument('--wide', '-w', action=\"store_true\", help=\"Wide strings only\") parser.add_argument('-n', '--min-len', type=int, default=4, help='Print sequences",
"unless we only want ascii strings if not ascii_only: for match in re_wide.finditer(data):",
"return {\"strings\": strings} def run_cli(self, args, pe, data): if args.ascii and args.wide: print(\"to",
"cli_out ASCII_BYTE = b\" !\\\"#\\$%&\\'\\(\\)\\*\\+,-\\./0123456789:;<=>\\?@ABCDEFGHIJKLMNOPQRSTUVWXYZ\\[\\]\\^_`abcdefghijklmnopqrstuvwxyz\\{\\|\\}\\\\\\~\\t\" class PluginStrings(Plugin): name = \"strings\" description = \"Extract",
"at least min-len characters long, instead of ' + 'the default 4.') self.parser",
"cli_mode) # print wide strings unless we only want ascii strings if not",
"= \"Extract strings from the PE file\" def add_arguments(self, parser): parser.add_argument('--ascii', '-a', action=\"store_true\",",
"only\") parser.add_argument('-n', '--min-len', type=int, default=4, help='Print sequences of ' + 'characters that are",
"# print wide strings unless we only want ascii strings if not ascii_only:",
"def get_results(self, data, min_len=4, wide_only=False, ascii_only=False, cli_mode=False): # regular expressions from flare-floss: #",
"are at least min-len characters long, instead of ' + 'the default 4.')",
"PE file\" def add_arguments(self, parser): parser.add_argument('--ascii', '-a', action=\"store_true\", help=\"ASCII strings only\") parser.add_argument('--wide', '-w',",
"we only want ascii strings if not ascii_only: for match in re_wide.finditer(data): try:",
"= [] # print ascii strings unless we only want wide strings if",
"expressions from flare-floss: # https://github.com/fireeye/flare-floss/blob/master/floss/strings.py#L7-L9 re_narrow = re.compile(b'([%s]{%d,})' % (ASCII_BYTE, min_len)) re_wide =",
"strings if not ascii_only: for match in re_wide.finditer(data): try: s = match.group().decode('utf-16') cli_out(s,",
"from pecli.lib.utils import cli_out ASCII_BYTE = b\" !\\\"#\\$%&\\'\\(\\)\\*\\+,-\\./0123456789:;<=>\\?@ABCDEFGHIJKLMNOPQRSTUVWXYZ\\[\\]\\^_`abcdefghijklmnopqrstuvwxyz\\{\\|\\}\\\\\\~\\t\" class PluginStrings(Plugin): name = \"strings\"",
"from pecli.plugins.base import Plugin from pecli.lib.utils import cli_out ASCII_BYTE = b\" !\\\"#\\$%&\\'\\(\\)\\*\\+,-\\./0123456789:;<=>\\?@ABCDEFGHIJKLMNOPQRSTUVWXYZ\\[\\]\\^_`abcdefghijklmnopqrstuvwxyz\\{\\|\\}\\\\\\~\\t\" class",
"type=int, default=4, help='Print sequences of ' + 'characters that are at least min-len",
"from the PE file\" def add_arguments(self, parser): parser.add_argument('--ascii', '-a', action=\"store_true\", help=\"ASCII strings only\")",
"https://github.com/fireeye/flare-floss/blob/master/floss/strings.py#L7-L9 re_narrow = re.compile(b'([%s]{%d,})' % (ASCII_BYTE, min_len)) re_wide = re.compile(b'((?:[%s]\\x00){%d,})' % (ASCII_BYTE, min_len))",
"import datetime import os import re from pecli.plugins.base import Plugin from pecli.lib.utils import",
"help=\"ASCII strings only\") parser.add_argument('--wide', '-w', action=\"store_true\", help=\"Wide strings only\") parser.add_argument('-n', '--min-len', type=int, default=4,",
"parser.add_argument('--wide', '-w', action=\"store_true\", help=\"Wide strings only\") parser.add_argument('-n', '--min-len', type=int, default=4, help='Print sequences of",
"\"strings\" description = \"Extract strings from the PE file\" def add_arguments(self, parser): parser.add_argument('--ascii',",
"python import pefile import datetime import os import re from pecli.plugins.base import Plugin",
"sequences of ' + 'characters that are at least min-len characters long, instead",
"wide_only=False, ascii_only=False, cli_mode=False): # regular expressions from flare-floss: # https://github.com/fireeye/flare-floss/blob/master/floss/strings.py#L7-L9 re_narrow = re.compile(b'([%s]{%d,})'",
"os import re from pecli.plugins.base import Plugin from pecli.lib.utils import cli_out ASCII_BYTE =",
"we only want wide strings if not wide_only: for match in re_narrow.finditer(data): s",
"pefile import datetime import os import re from pecli.plugins.base import Plugin from pecli.lib.utils",
"= re.compile(b'((?:[%s]\\x00){%d,})' % (ASCII_BYTE, min_len)) strings = [] # print ascii strings unless",
"'-w', action=\"store_true\", help=\"Wide strings only\") parser.add_argument('-n', '--min-len', type=int, default=4, help='Print sequences of '",
"[] # print ascii strings unless we only want wide strings if not",
"(ASCII_BYTE, min_len)) re_wide = re.compile(b'((?:[%s]\\x00){%d,})' % (ASCII_BYTE, min_len)) strings = [] # print",
"' + 'the default 4.') self.parser = parser def get_results(self, data, min_len=4, wide_only=False,",
"flare-floss: # https://github.com/fireeye/flare-floss/blob/master/floss/strings.py#L7-L9 re_narrow = re.compile(b'([%s]{%d,})' % (ASCII_BYTE, min_len)) re_wide = re.compile(b'((?:[%s]\\x00){%d,})' %",
"try: s = match.group().decode('utf-16') cli_out(s, cli_mode) strings.append(s) except UnicodeDecodeError: pass return {\"strings\": strings}",
"strings unless we only want wide strings if not wide_only: for match in",
"% (ASCII_BYTE, min_len)) strings = [] # print ascii strings unless we only",
"= b\" !\\\"#\\$%&\\'\\(\\)\\*\\+,-\\./0123456789:;<=>\\?@ABCDEFGHIJKLMNOPQRSTUVWXYZ\\[\\]\\^_`abcdefghijklmnopqrstuvwxyz\\{\\|\\}\\\\\\~\\t\" class PluginStrings(Plugin): name = \"strings\" description = \"Extract strings from",
"ASCII_BYTE = b\" !\\\"#\\$%&\\'\\(\\)\\*\\+,-\\./0123456789:;<=>\\?@ABCDEFGHIJKLMNOPQRSTUVWXYZ\\[\\]\\^_`abcdefghijklmnopqrstuvwxyz\\{\\|\\}\\\\\\~\\t\" class PluginStrings(Plugin): name = \"strings\" description = \"Extract strings",
"class PluginStrings(Plugin): name = \"strings\" description = \"Extract strings from the PE file\"",
"ascii strings if not ascii_only: for match in re_wide.finditer(data): try: s = match.group().decode('utf-16')",
"strings.append(s) cli_out(s, cli_mode) # print wide strings unless we only want ascii strings",
"% (ASCII_BYTE, min_len)) re_wide = re.compile(b'((?:[%s]\\x00){%d,})' % (ASCII_BYTE, min_len)) strings = [] #",
"def run_cli(self, args, pe, data): if args.ascii and args.wide: print(\"to print both ascii",
"re_narrow.finditer(data): s = match.group().decode('ascii') strings.append(s) cli_out(s, cli_mode) # print wide strings unless we",
"parser.add_argument('-n', '--min-len', type=int, default=4, help='Print sequences of ' + 'characters that are at",
"import os import re from pecli.plugins.base import Plugin from pecli.lib.utils import cli_out ASCII_BYTE",
"# regular expressions from flare-floss: # https://github.com/fireeye/flare-floss/blob/master/floss/strings.py#L7-L9 re_narrow = re.compile(b'([%s]{%d,})' % (ASCII_BYTE, min_len))",
"parser): parser.add_argument('--ascii', '-a', action=\"store_true\", help=\"ASCII strings only\") parser.add_argument('--wide', '-w', action=\"store_true\", help=\"Wide strings only\")",
"= match.group().decode('ascii') strings.append(s) cli_out(s, cli_mode) # print wide strings unless we only want",
"def add_arguments(self, parser): parser.add_argument('--ascii', '-a', action=\"store_true\", help=\"ASCII strings only\") parser.add_argument('--wide', '-w', action=\"store_true\", help=\"Wide",
"s = match.group().decode('ascii') strings.append(s) cli_out(s, cli_mode) # print wide strings unless we only",
"+ 'characters that are at least min-len characters long, instead of ' +",
"want wide strings if not wide_only: for match in re_narrow.finditer(data): s = match.group().decode('ascii')",
"strings only\") parser.add_argument('-n', '--min-len', type=int, default=4, help='Print sequences of ' + 'characters that",
"if not wide_only: for match in re_narrow.finditer(data): s = match.group().decode('ascii') strings.append(s) cli_out(s, cli_mode)",
"in re_wide.finditer(data): try: s = match.group().decode('utf-16') cli_out(s, cli_mode) strings.append(s) except UnicodeDecodeError: pass return",
"of ' + 'the default 4.') self.parser = parser def get_results(self, data, min_len=4,",
"regular expressions from flare-floss: # https://github.com/fireeye/flare-floss/blob/master/floss/strings.py#L7-L9 re_narrow = re.compile(b'([%s]{%d,})' % (ASCII_BYTE, min_len)) re_wide",
"pecli.plugins.base import Plugin from pecli.lib.utils import cli_out ASCII_BYTE = b\" !\\\"#\\$%&\\'\\(\\)\\*\\+,-\\./0123456789:;<=>\\?@ABCDEFGHIJKLMNOPQRSTUVWXYZ\\[\\]\\^_`abcdefghijklmnopqrstuvwxyz\\{\\|\\}\\\\\\~\\t\" class PluginStrings(Plugin):",
"wide_only: for match in re_narrow.finditer(data): s = match.group().decode('ascii') strings.append(s) cli_out(s, cli_mode) # print",
"re_wide = re.compile(b'((?:[%s]\\x00){%d,})' % (ASCII_BYTE, min_len)) strings = [] # print ascii strings",
"s = match.group().decode('utf-16') cli_out(s, cli_mode) strings.append(s) except UnicodeDecodeError: pass return {\"strings\": strings} def",
"description = \"Extract strings from the PE file\" def add_arguments(self, parser): parser.add_argument('--ascii', '-a',",
"of ' + 'characters that are at least min-len characters long, instead of",
"self.parser = parser def get_results(self, data, min_len=4, wide_only=False, ascii_only=False, cli_mode=False): # regular expressions",
"help='Print sequences of ' + 'characters that are at least min-len characters long,"
] |
[
"reading of a file in a separate thread. Pushes read lines on a",
"iter(self._fd.readline, ''): self._handler(line.replace('\\n', '')) class LockQueue(Queue): \"\"\" Python queue with a locking utility",
"noqa import sys import threading # Uniform Queue and Empty locations b/w Python",
"invalid-name, undefined-variable # flake8: noqa import sys import threading # Uniform Queue and",
"Source: http://stefaanlippens.net/python-asynchronous-subprocess-pipe-reading ''' def __init__(self, fd, handler): assert callable(handler) assert callable(fd.readline) threading.Thread.__init__(self) self.daemon",
"import Queue, Empty except ImportError: from queue import Queue, Empty # Unform ProcessLookupError",
"*args, **kwargs): Queue.__init__(self, *args, **kwargs) # Queue is old style class in Python",
"file in a separate thread. Pushes read lines on a queue to be",
"self.locked = True def put(self, *args, **kwargs): \"\"\" Put item into queue \"\"\"",
"sys.version_info[0] == 2: MyProcessLookupError = OSError else: MyProcessLookupError = ProcessLookupError class AsyncFileReader(threading.Thread): '''",
"\"\"\" # pylint: disable=import-error, unused-import, invalid-name, undefined-variable # flake8: noqa import sys import",
"''): self._handler(line.replace('\\n', '')) class LockQueue(Queue): \"\"\" Python queue with a locking utility \"\"\"",
"**kwargs): \"\"\" Put item into queue without waiting \"\"\" if not self.locked: Queue.put_nowait(self,",
"of the thread: read lines and put them on the queue.''' for line",
"in Python 2.x self.locked = True def put(self, *args, **kwargs): \"\"\" Put item",
"= ProcessLookupError class AsyncFileReader(threading.Thread): ''' Helper class to implement asynchronous reading of a",
"3 try: from Queue import Queue, Empty except ImportError: from queue import Queue,",
"MyProcessLookupError = ProcessLookupError class AsyncFileReader(threading.Thread): ''' Helper class to implement asynchronous reading of",
"read lines on a queue to be consumed in another thread. Source: http://stefaanlippens.net/python-asynchronous-subprocess-pipe-reading",
"self.daemon = True self._fd = fd self._handler = handler def run(self): '''The body",
"pylint: disable=import-error, unused-import, invalid-name, undefined-variable # flake8: noqa import sys import threading #",
"= True self._fd = fd self._handler = handler def run(self): '''The body of",
"**kwargs) # Queue is old style class in Python 2.x self.locked = True",
"Uniform Queue and Empty locations b/w Python 2 and 3 try: from Queue",
"threading.Thread.__init__(self) self.daemon = True self._fd = fd self._handler = handler def run(self): '''The",
"queue \"\"\" if not self.locked: Queue.put(self, *args, **kwargs) def put_nowait(self, *args, **kwargs): \"\"\"",
"queue.''' for line in iter(self._fd.readline, ''): self._handler(line.replace('\\n', '')) class LockQueue(Queue): \"\"\" Python queue",
"lines and put them on the queue.''' for line in iter(self._fd.readline, ''): self._handler(line.replace('\\n',",
"ProcessLookupError b/w Python 2 and 3 if sys.version_info[0] == 2: MyProcessLookupError = OSError",
"is old style class in Python 2.x self.locked = True def put(self, *args,",
"undefined-variable # flake8: noqa import sys import threading # Uniform Queue and Empty",
"handler def run(self): '''The body of the thread: read lines and put them",
"utility \"\"\" def __init__(self, *args, **kwargs): Queue.__init__(self, *args, **kwargs) # Queue is old",
"\"\"\" Put item into queue \"\"\" if not self.locked: Queue.put(self, *args, **kwargs) def",
"Queue, Empty # Unform ProcessLookupError b/w Python 2 and 3 if sys.version_info[0] ==",
"on the queue.''' for line in iter(self._fd.readline, ''): self._handler(line.replace('\\n', '')) class LockQueue(Queue): \"\"\"",
"Queue import Queue, Empty except ImportError: from queue import Queue, Empty # Unform",
"**kwargs): Queue.__init__(self, *args, **kwargs) # Queue is old style class in Python 2.x",
"Empty locations b/w Python 2 and 3 try: from Queue import Queue, Empty",
"else: MyProcessLookupError = ProcessLookupError class AsyncFileReader(threading.Thread): ''' Helper class to implement asynchronous reading",
"= fd self._handler = handler def run(self): '''The body of the thread: read",
"implement asynchronous reading of a file in a separate thread. Pushes read lines",
"http://stefaanlippens.net/python-asynchronous-subprocess-pipe-reading ''' def __init__(self, fd, handler): assert callable(handler) assert callable(fd.readline) threading.Thread.__init__(self) self.daemon =",
"queue import Queue, Empty # Unform ProcessLookupError b/w Python 2 and 3 if",
"**kwargs): \"\"\" Put item into queue \"\"\" if not self.locked: Queue.put(self, *args, **kwargs)",
"the queue.''' for line in iter(self._fd.readline, ''): self._handler(line.replace('\\n', '')) class LockQueue(Queue): \"\"\" Python",
"def put(self, *args, **kwargs): \"\"\" Put item into queue \"\"\" if not self.locked:",
"sys import threading # Uniform Queue and Empty locations b/w Python 2 and",
"thread: read lines and put them on the queue.''' for line in iter(self._fd.readline,",
"3 if sys.version_info[0] == 2: MyProcessLookupError = OSError else: MyProcessLookupError = ProcessLookupError class",
"''' Helper class to implement asynchronous reading of a file in a separate",
"put them on the queue.''' for line in iter(self._fd.readline, ''): self._handler(line.replace('\\n', '')) class",
"try: from Queue import Queue, Empty except ImportError: from queue import Queue, Empty",
"from queue import Queue, Empty # Unform ProcessLookupError b/w Python 2 and 3",
"Empty # Unform ProcessLookupError b/w Python 2 and 3 if sys.version_info[0] == 2:",
"\"\"\" Generic utilities used by Polyglot. \"\"\" # pylint: disable=import-error, unused-import, invalid-name, undefined-variable",
"disable=import-error, unused-import, invalid-name, undefined-variable # flake8: noqa import sys import threading # Uniform",
"thread. Pushes read lines on a queue to be consumed in another thread.",
"= True def put(self, *args, **kwargs): \"\"\" Put item into queue \"\"\" if",
"fd, handler): assert callable(handler) assert callable(fd.readline) threading.Thread.__init__(self) self.daemon = True self._fd = fd",
"locations b/w Python 2 and 3 try: from Queue import Queue, Empty except",
"Helper class to implement asynchronous reading of a file in a separate thread.",
"<filename>polyglot/utils.py \"\"\" Generic utilities used by Polyglot. \"\"\" # pylint: disable=import-error, unused-import, invalid-name,",
"# Uniform Queue and Empty locations b/w Python 2 and 3 try: from",
"Polyglot. \"\"\" # pylint: disable=import-error, unused-import, invalid-name, undefined-variable # flake8: noqa import sys",
"\"\"\" def __init__(self, *args, **kwargs): Queue.__init__(self, *args, **kwargs) # Queue is old style",
"Queue.put(self, *args, **kwargs) def put_nowait(self, *args, **kwargs): \"\"\" Put item into queue without",
"b/w Python 2 and 3 try: from Queue import Queue, Empty except ImportError:",
"read lines and put them on the queue.''' for line in iter(self._fd.readline, ''):",
"assert callable(fd.readline) threading.Thread.__init__(self) self.daemon = True self._fd = fd self._handler = handler def",
"line in iter(self._fd.readline, ''): self._handler(line.replace('\\n', '')) class LockQueue(Queue): \"\"\" Python queue with a",
"def __init__(self, fd, handler): assert callable(handler) assert callable(fd.readline) threading.Thread.__init__(self) self.daemon = True self._fd",
"the thread: read lines and put them on the queue.''' for line in",
"b/w Python 2 and 3 if sys.version_info[0] == 2: MyProcessLookupError = OSError else:",
"fd self._handler = handler def run(self): '''The body of the thread: read lines",
"# flake8: noqa import sys import threading # Uniform Queue and Empty locations",
"consumed in another thread. Source: http://stefaanlippens.net/python-asynchronous-subprocess-pipe-reading ''' def __init__(self, fd, handler): assert callable(handler)",
"and put them on the queue.''' for line in iter(self._fd.readline, ''): self._handler(line.replace('\\n', ''))",
"class in Python 2.x self.locked = True def put(self, *args, **kwargs): \"\"\" Put",
"LockQueue(Queue): \"\"\" Python queue with a locking utility \"\"\" def __init__(self, *args, **kwargs):",
"and 3 if sys.version_info[0] == 2: MyProcessLookupError = OSError else: MyProcessLookupError = ProcessLookupError",
"item into queue \"\"\" if not self.locked: Queue.put(self, *args, **kwargs) def put_nowait(self, *args,",
"callable(fd.readline) threading.Thread.__init__(self) self.daemon = True self._fd = fd self._handler = handler def run(self):",
"Python queue with a locking utility \"\"\" def __init__(self, *args, **kwargs): Queue.__init__(self, *args,",
"unused-import, invalid-name, undefined-variable # flake8: noqa import sys import threading # Uniform Queue",
"and Empty locations b/w Python 2 and 3 try: from Queue import Queue,",
"if sys.version_info[0] == 2: MyProcessLookupError = OSError else: MyProcessLookupError = ProcessLookupError class AsyncFileReader(threading.Thread):",
"'')) class LockQueue(Queue): \"\"\" Python queue with a locking utility \"\"\" def __init__(self,",
"2.x self.locked = True def put(self, *args, **kwargs): \"\"\" Put item into queue",
"Unform ProcessLookupError b/w Python 2 and 3 if sys.version_info[0] == 2: MyProcessLookupError =",
"not self.locked: Queue.put(self, *args, **kwargs) def put_nowait(self, *args, **kwargs): \"\"\" Put item into",
"body of the thread: read lines and put them on the queue.''' for",
"a separate thread. Pushes read lines on a queue to be consumed in",
"Python 2 and 3 if sys.version_info[0] == 2: MyProcessLookupError = OSError else: MyProcessLookupError",
"to implement asynchronous reading of a file in a separate thread. Pushes read",
"for line in iter(self._fd.readline, ''): self._handler(line.replace('\\n', '')) class LockQueue(Queue): \"\"\" Python queue with",
"Empty except ImportError: from queue import Queue, Empty # Unform ProcessLookupError b/w Python",
"= OSError else: MyProcessLookupError = ProcessLookupError class AsyncFileReader(threading.Thread): ''' Helper class to implement",
"into queue \"\"\" if not self.locked: Queue.put(self, *args, **kwargs) def put_nowait(self, *args, **kwargs):",
"*args, **kwargs) # Queue is old style class in Python 2.x self.locked =",
"except ImportError: from queue import Queue, Empty # Unform ProcessLookupError b/w Python 2",
"in iter(self._fd.readline, ''): self._handler(line.replace('\\n', '')) class LockQueue(Queue): \"\"\" Python queue with a locking",
"MyProcessLookupError = OSError else: MyProcessLookupError = ProcessLookupError class AsyncFileReader(threading.Thread): ''' Helper class to",
"Queue, Empty except ImportError: from queue import Queue, Empty # Unform ProcessLookupError b/w",
"*args, **kwargs) def put_nowait(self, *args, **kwargs): \"\"\" Put item into queue without waiting",
"AsyncFileReader(threading.Thread): ''' Helper class to implement asynchronous reading of a file in a",
"Generic utilities used by Polyglot. \"\"\" # pylint: disable=import-error, unused-import, invalid-name, undefined-variable #",
"class LockQueue(Queue): \"\"\" Python queue with a locking utility \"\"\" def __init__(self, *args,",
"Queue and Empty locations b/w Python 2 and 3 try: from Queue import",
"Queue is old style class in Python 2.x self.locked = True def put(self,",
"from Queue import Queue, Empty except ImportError: from queue import Queue, Empty #",
"put(self, *args, **kwargs): \"\"\" Put item into queue \"\"\" if not self.locked: Queue.put(self,",
"flake8: noqa import sys import threading # Uniform Queue and Empty locations b/w",
"class AsyncFileReader(threading.Thread): ''' Helper class to implement asynchronous reading of a file in",
"asynchronous reading of a file in a separate thread. Pushes read lines on",
"OSError else: MyProcessLookupError = ProcessLookupError class AsyncFileReader(threading.Thread): ''' Helper class to implement asynchronous",
"True self._fd = fd self._handler = handler def run(self): '''The body of the",
"self._handler = handler def run(self): '''The body of the thread: read lines and",
"__init__(self, *args, **kwargs): Queue.__init__(self, *args, **kwargs) # Queue is old style class in",
"__init__(self, fd, handler): assert callable(handler) assert callable(fd.readline) threading.Thread.__init__(self) self.daemon = True self._fd =",
"= handler def run(self): '''The body of the thread: read lines and put",
"self._fd = fd self._handler = handler def run(self): '''The body of the thread:",
"handler): assert callable(handler) assert callable(fd.readline) threading.Thread.__init__(self) self.daemon = True self._fd = fd self._handler",
"2 and 3 try: from Queue import Queue, Empty except ImportError: from queue",
"ImportError: from queue import Queue, Empty # Unform ProcessLookupError b/w Python 2 and",
"queue with a locking utility \"\"\" def __init__(self, *args, **kwargs): Queue.__init__(self, *args, **kwargs)",
"if not self.locked: Queue.put(self, *args, **kwargs) def put_nowait(self, *args, **kwargs): \"\"\" Put item",
"**kwargs) def put_nowait(self, *args, **kwargs): \"\"\" Put item into queue without waiting \"\"\"",
"in a separate thread. Pushes read lines on a queue to be consumed",
"ProcessLookupError class AsyncFileReader(threading.Thread): ''' Helper class to implement asynchronous reading of a file",
"== 2: MyProcessLookupError = OSError else: MyProcessLookupError = ProcessLookupError class AsyncFileReader(threading.Thread): ''' Helper",
"callable(handler) assert callable(fd.readline) threading.Thread.__init__(self) self.daemon = True self._fd = fd self._handler = handler",
"old style class in Python 2.x self.locked = True def put(self, *args, **kwargs):",
"import threading # Uniform Queue and Empty locations b/w Python 2 and 3",
"on a queue to be consumed in another thread. Source: http://stefaanlippens.net/python-asynchronous-subprocess-pipe-reading ''' def",
"run(self): '''The body of the thread: read lines and put them on the",
"import Queue, Empty # Unform ProcessLookupError b/w Python 2 and 3 if sys.version_info[0]",
"Put item into queue \"\"\" if not self.locked: Queue.put(self, *args, **kwargs) def put_nowait(self,",
"\"\"\" Python queue with a locking utility \"\"\" def __init__(self, *args, **kwargs): Queue.__init__(self,",
"separate thread. Pushes read lines on a queue to be consumed in another",
"style class in Python 2.x self.locked = True def put(self, *args, **kwargs): \"\"\"",
"them on the queue.''' for line in iter(self._fd.readline, ''): self._handler(line.replace('\\n', '')) class LockQueue(Queue):",
"a locking utility \"\"\" def __init__(self, *args, **kwargs): Queue.__init__(self, *args, **kwargs) # Queue",
"lines on a queue to be consumed in another thread. Source: http://stefaanlippens.net/python-asynchronous-subprocess-pipe-reading '''",
"''' def __init__(self, fd, handler): assert callable(handler) assert callable(fd.readline) threading.Thread.__init__(self) self.daemon = True",
"def run(self): '''The body of the thread: read lines and put them on",
"True def put(self, *args, **kwargs): \"\"\" Put item into queue \"\"\" if not",
"thread. Source: http://stefaanlippens.net/python-asynchronous-subprocess-pipe-reading ''' def __init__(self, fd, handler): assert callable(handler) assert callable(fd.readline) threading.Thread.__init__(self)",
"a queue to be consumed in another thread. Source: http://stefaanlippens.net/python-asynchronous-subprocess-pipe-reading ''' def __init__(self,",
"another thread. Source: http://stefaanlippens.net/python-asynchronous-subprocess-pipe-reading ''' def __init__(self, fd, handler): assert callable(handler) assert callable(fd.readline)",
"# pylint: disable=import-error, unused-import, invalid-name, undefined-variable # flake8: noqa import sys import threading",
"utilities used by Polyglot. \"\"\" # pylint: disable=import-error, unused-import, invalid-name, undefined-variable # flake8:",
"def put_nowait(self, *args, **kwargs): \"\"\" Put item into queue without waiting \"\"\" if",
"by Polyglot. \"\"\" # pylint: disable=import-error, unused-import, invalid-name, undefined-variable # flake8: noqa import",
"used by Polyglot. \"\"\" # pylint: disable=import-error, unused-import, invalid-name, undefined-variable # flake8: noqa",
"Python 2 and 3 try: from Queue import Queue, Empty except ImportError: from",
"Queue.__init__(self, *args, **kwargs) # Queue is old style class in Python 2.x self.locked",
"*args, **kwargs): \"\"\" Put item into queue \"\"\" if not self.locked: Queue.put(self, *args,",
"Pushes read lines on a queue to be consumed in another thread. Source:",
"queue to be consumed in another thread. Source: http://stefaanlippens.net/python-asynchronous-subprocess-pipe-reading ''' def __init__(self, fd,",
"2 and 3 if sys.version_info[0] == 2: MyProcessLookupError = OSError else: MyProcessLookupError =",
"and 3 try: from Queue import Queue, Empty except ImportError: from queue import",
"with a locking utility \"\"\" def __init__(self, *args, **kwargs): Queue.__init__(self, *args, **kwargs) #",
"locking utility \"\"\" def __init__(self, *args, **kwargs): Queue.__init__(self, *args, **kwargs) # Queue is",
"*args, **kwargs): \"\"\" Put item into queue without waiting \"\"\" if not self.locked:",
"in another thread. Source: http://stefaanlippens.net/python-asynchronous-subprocess-pipe-reading ''' def __init__(self, fd, handler): assert callable(handler) assert",
"\"\"\" Put item into queue without waiting \"\"\" if not self.locked: Queue.put_nowait(self, *args,",
"Python 2.x self.locked = True def put(self, *args, **kwargs): \"\"\" Put item into",
"# Unform ProcessLookupError b/w Python 2 and 3 if sys.version_info[0] == 2: MyProcessLookupError",
"put_nowait(self, *args, **kwargs): \"\"\" Put item into queue without waiting \"\"\" if not",
"def __init__(self, *args, **kwargs): Queue.__init__(self, *args, **kwargs) # Queue is old style class",
"class to implement asynchronous reading of a file in a separate thread. Pushes",
"to be consumed in another thread. Source: http://stefaanlippens.net/python-asynchronous-subprocess-pipe-reading ''' def __init__(self, fd, handler):",
"self.locked: Queue.put(self, *args, **kwargs) def put_nowait(self, *args, **kwargs): \"\"\" Put item into queue",
"import sys import threading # Uniform Queue and Empty locations b/w Python 2",
"'''The body of the thread: read lines and put them on the queue.'''",
"2: MyProcessLookupError = OSError else: MyProcessLookupError = ProcessLookupError class AsyncFileReader(threading.Thread): ''' Helper class",
"of a file in a separate thread. Pushes read lines on a queue",
"Put item into queue without waiting \"\"\" if not self.locked: Queue.put_nowait(self, *args, **kwargs)",
"be consumed in another thread. Source: http://stefaanlippens.net/python-asynchronous-subprocess-pipe-reading ''' def __init__(self, fd, handler): assert",
"assert callable(handler) assert callable(fd.readline) threading.Thread.__init__(self) self.daemon = True self._fd = fd self._handler =",
"threading # Uniform Queue and Empty locations b/w Python 2 and 3 try:",
"self._handler(line.replace('\\n', '')) class LockQueue(Queue): \"\"\" Python queue with a locking utility \"\"\" def",
"# Queue is old style class in Python 2.x self.locked = True def",
"\"\"\" if not self.locked: Queue.put(self, *args, **kwargs) def put_nowait(self, *args, **kwargs): \"\"\" Put",
"a file in a separate thread. Pushes read lines on a queue to"
] |
[
"selection_end = datetime(2021, 9, 3) results = pc_queries.query_accounts(selection_start, selection_end) count = len(results) self.assertTrue(count",
"ODB data source. Perform a query. \"\"\" pc_queries = PolicyCenterQueries(self.cnx) selection_start = datetime(2021,",
"> 0, \"Accounts were not found: \" + str(count)) return if __name__ ==",
"__name__ == '__main__': report_file = TestConnector.configuration.report_file with open(report_file, 'w') as output: unittest.main( testRunner=xmlrunner.XMLTestRunner(output=output),",
"= ConnectorTestConfiguration() # ------------------------------------------------------------------------------- # Support Methods # ------------------------------------------------------------------------------- def setUp(self): \"\"\" Initialize",
"\"\"\" cursor = self.cnx.cursor() self.assertEqual(-1, cursor.rowcount, \"Cursor did not return -1\") return def",
"2021 Waysys LLC # # ------------------------------------------------------------------------------- # ------------------------------------------------------------------------------- __author__ = '<NAME>' __version__ =",
"# Test of the Connector class # ------------------------------------------------------------------------------- class TestConnector(unittest.TestCase): \"\"\" Test the",
"class. \"\"\" import unittest from datetime import datetime import xmlrunner from base.connector import",
"Class Variables # ------------------------------------------------------------------------------- configuration = ConnectorTestConfiguration() # ------------------------------------------------------------------------------- # Support Methods #",
"= len(results) self.assertTrue(count > 0, \"Accounts were not found: \" + str(count)) return",
"connector actually connects to the database. \"\"\" cursor = self.cnx.cursor() self.assertEqual(-1, cursor.rowcount, \"Cursor",
"datetime import datetime import xmlrunner from base.connector import Connector from configuration.config import ConnectorTestConfiguration",
"data source. Perform a query. \"\"\" pc_queries = PolicyCenterQueries(self.cnx) selection_start = datetime(2021, 9,",
"\"Accounts were not found: \" + str(count)) return if __name__ == '__main__': report_file",
"# ------------------------------------------------------------------------------- def setUp(self): \"\"\" Initialize the connector. \"\"\" self.cnx = Connector.create_connector(self.configuration.data_source) return",
"Variables # ------------------------------------------------------------------------------- configuration = ConnectorTestConfiguration() # ------------------------------------------------------------------------------- # Support Methods # -------------------------------------------------------------------------------",
"__author__ = '<NAME>' __version__ = \"2021-09-02\" \"\"\" This module tests the Connector class.",
"\"\"\" This module tests the Connector class. \"\"\" import unittest from datetime import",
"# Copyright (c) 2021 Waysys LLC # # ------------------------------------------------------------------------------- # ------------------------------------------------------------------------------- __author__ =",
"to the database. \"\"\" cursor = self.cnx.cursor() self.assertEqual(-1, cursor.rowcount, \"Cursor did not return",
"9, 1) selection_end = datetime(2021, 9, 3) results = pc_queries.query_accounts(selection_start, selection_end) count =",
"selection_start = datetime(2021, 9, 1) selection_end = datetime(2021, 9, 3) results = pc_queries.query_accounts(selection_start,",
"\"\"\" pc_queries = PolicyCenterQueries(self.cnx) selection_start = datetime(2021, 9, 1) selection_end = datetime(2021, 9,",
"1) selection_end = datetime(2021, 9, 3) results = pc_queries.query_accounts(selection_start, selection_end) count = len(results)",
"\" + str(count)) return if __name__ == '__main__': report_file = TestConnector.configuration.report_file with open(report_file,",
"import ConnectorTestConfiguration from queries.policycenterqueries import PolicyCenterQueries # ------------------------------------------------------------------------------- # Test of the Connector",
"class # ------------------------------------------------------------------------------- class TestConnector(unittest.TestCase): \"\"\" Test the ability to connect to the",
"self.assertEqual(-1, cursor.rowcount, \"Cursor did not return -1\") return def test_03_database_connection_with_odbc_datasource(self): \"\"\" Test connection",
"cursor.rowcount, \"Cursor did not return -1\") return def test_03_database_connection_with_odbc_datasource(self): \"\"\" Test connection through",
"3) results = pc_queries.query_accounts(selection_start, selection_end) count = len(results) self.assertTrue(count > 0, \"Accounts were",
"tests the Connector class. \"\"\" import unittest from datetime import datetime import xmlrunner",
"Connector.create_connector(self.configuration.data_source) return def tearDown(self): self.cnx.close() return # ------------------------------------------------------------------------------- # Tests # ------------------------------------------------------------------------------- def",
"results = pc_queries.query_accounts(selection_start, selection_end) count = len(results) self.assertTrue(count > 0, \"Accounts were not",
"\"\"\" Test that the connector actually connects to the database. \"\"\" cursor =",
"(c) 2021 Waysys LLC # # ------------------------------------------------------------------------------- # ------------------------------------------------------------------------------- __author__ = '<NAME>' __version__",
"xmlrunner from base.connector import Connector from configuration.config import ConnectorTestConfiguration from queries.policycenterqueries import PolicyCenterQueries",
"------------------------------------------------------------------------------- class TestConnector(unittest.TestCase): \"\"\" Test the ability to connect to the DataHub database.",
"\"2021-09-02\" \"\"\" This module tests the Connector class. \"\"\" import unittest from datetime",
"the database. \"\"\" cursor = self.cnx.cursor() self.assertEqual(-1, cursor.rowcount, \"Cursor did not return -1\")",
"report_file = TestConnector.configuration.report_file with open(report_file, 'w') as output: unittest.main( testRunner=xmlrunner.XMLTestRunner(output=output), failfast=False, buffer=False, catchbreak=False)",
"# ------------------------------------------------------------------------------- class TestConnector(unittest.TestCase): \"\"\" Test the ability to connect to the DataHub",
"base.connector import Connector from configuration.config import ConnectorTestConfiguration from queries.policycenterqueries import PolicyCenterQueries # -------------------------------------------------------------------------------",
"unittest from datetime import datetime import xmlrunner from base.connector import Connector from configuration.config",
"Waysys LLC # # ------------------------------------------------------------------------------- # ------------------------------------------------------------------------------- __author__ = '<NAME>' __version__ = \"2021-09-02\"",
"module tests the Connector class. \"\"\" import unittest from datetime import datetime import",
"# ------------------------------------------------------------------------------- # # Copyright (c) 2021 Waysys LLC # # ------------------------------------------------------------------------------- #",
"# ------------------------------------------------------------------------------- def test_02_database_connection(self): \"\"\" Test that the connector actually connects to the",
"LLC # # ------------------------------------------------------------------------------- # ------------------------------------------------------------------------------- __author__ = '<NAME>' __version__ = \"2021-09-02\" \"\"\"",
"did not return -1\") return def test_03_database_connection_with_odbc_datasource(self): \"\"\" Test connection through ODB data",
"configuration.config import ConnectorTestConfiguration from queries.policycenterqueries import PolicyCenterQueries # ------------------------------------------------------------------------------- # Test of the",
"# ------------------------------------------------------------------------------- # Class Variables # ------------------------------------------------------------------------------- configuration = ConnectorTestConfiguration() # ------------------------------------------------------------------------------- #",
"import xmlrunner from base.connector import Connector from configuration.config import ConnectorTestConfiguration from queries.policycenterqueries import",
"\"\"\" self.cnx = Connector.create_connector(self.configuration.data_source) return def tearDown(self): self.cnx.close() return # ------------------------------------------------------------------------------- # Tests",
"pc_queries = PolicyCenterQueries(self.cnx) selection_start = datetime(2021, 9, 1) selection_end = datetime(2021, 9, 3)",
"database. \"\"\" cursor = self.cnx.cursor() self.assertEqual(-1, cursor.rowcount, \"Cursor did not return -1\") return",
"that the connector actually connects to the database. \"\"\" cursor = self.cnx.cursor() self.assertEqual(-1,",
"------------------------------------------------------------------------------- # # Copyright (c) 2021 Waysys LLC # # ------------------------------------------------------------------------------- # -------------------------------------------------------------------------------",
"of the Connector class # ------------------------------------------------------------------------------- class TestConnector(unittest.TestCase): \"\"\" Test the ability to",
"def tearDown(self): self.cnx.close() return # ------------------------------------------------------------------------------- # Tests # ------------------------------------------------------------------------------- def test_02_database_connection(self): \"\"\"",
"= self.cnx.cursor() self.assertEqual(-1, cursor.rowcount, \"Cursor did not return -1\") return def test_03_database_connection_with_odbc_datasource(self): \"\"\"",
"\"\"\" # ------------------------------------------------------------------------------- # Class Variables # ------------------------------------------------------------------------------- configuration = ConnectorTestConfiguration() # -------------------------------------------------------------------------------",
"Tests # ------------------------------------------------------------------------------- def test_02_database_connection(self): \"\"\" Test that the connector actually connects to",
"found: \" + str(count)) return if __name__ == '__main__': report_file = TestConnector.configuration.report_file with",
"TestConnector(unittest.TestCase): \"\"\" Test the ability to connect to the DataHub database. \"\"\" #",
"test_03_database_connection_with_odbc_datasource(self): \"\"\" Test connection through ODB data source. Perform a query. \"\"\" pc_queries",
"query. \"\"\" pc_queries = PolicyCenterQueries(self.cnx) selection_start = datetime(2021, 9, 1) selection_end = datetime(2021,",
"# ------------------------------------------------------------------------------- # Test of the Connector class # ------------------------------------------------------------------------------- class TestConnector(unittest.TestCase): \"\"\"",
"tearDown(self): self.cnx.close() return # ------------------------------------------------------------------------------- # Tests # ------------------------------------------------------------------------------- def test_02_database_connection(self): \"\"\" Test",
"connect to the DataHub database. \"\"\" # ------------------------------------------------------------------------------- # Class Variables # -------------------------------------------------------------------------------",
"DataHub database. \"\"\" # ------------------------------------------------------------------------------- # Class Variables # ------------------------------------------------------------------------------- configuration = ConnectorTestConfiguration()",
"def setUp(self): \"\"\" Initialize the connector. \"\"\" self.cnx = Connector.create_connector(self.configuration.data_source) return def tearDown(self):",
"the connector actually connects to the database. \"\"\" cursor = self.cnx.cursor() self.assertEqual(-1, cursor.rowcount,",
"= PolicyCenterQueries(self.cnx) selection_start = datetime(2021, 9, 1) selection_end = datetime(2021, 9, 3) results",
"datetime(2021, 9, 3) results = pc_queries.query_accounts(selection_start, selection_end) count = len(results) self.assertTrue(count > 0,",
"Test connection through ODB data source. Perform a query. \"\"\" pc_queries = PolicyCenterQueries(self.cnx)",
"test_02_database_connection(self): \"\"\" Test that the connector actually connects to the database. \"\"\" cursor",
"the Connector class # ------------------------------------------------------------------------------- class TestConnector(unittest.TestCase): \"\"\" Test the ability to connect",
"= pc_queries.query_accounts(selection_start, selection_end) count = len(results) self.assertTrue(count > 0, \"Accounts were not found:",
"the Connector class. \"\"\" import unittest from datetime import datetime import xmlrunner from",
"PolicyCenterQueries(self.cnx) selection_start = datetime(2021, 9, 1) selection_end = datetime(2021, 9, 3) results =",
"= datetime(2021, 9, 1) selection_end = datetime(2021, 9, 3) results = pc_queries.query_accounts(selection_start, selection_end)",
"Test the ability to connect to the DataHub database. \"\"\" # ------------------------------------------------------------------------------- #",
"\"\"\" Initialize the connector. \"\"\" self.cnx = Connector.create_connector(self.configuration.data_source) return def tearDown(self): self.cnx.close() return",
"------------------------------------------------------------------------------- # ------------------------------------------------------------------------------- __author__ = '<NAME>' __version__ = \"2021-09-02\" \"\"\" This module tests",
"import datetime import xmlrunner from base.connector import Connector from configuration.config import ConnectorTestConfiguration from",
"str(count)) return if __name__ == '__main__': report_file = TestConnector.configuration.report_file with open(report_file, 'w') as",
"class TestConnector(unittest.TestCase): \"\"\" Test the ability to connect to the DataHub database. \"\"\"",
"ConnectorTestConfiguration() # ------------------------------------------------------------------------------- # Support Methods # ------------------------------------------------------------------------------- def setUp(self): \"\"\" Initialize the",
"ConnectorTestConfiguration from queries.policycenterqueries import PolicyCenterQueries # ------------------------------------------------------------------------------- # Test of the Connector class",
"# # ------------------------------------------------------------------------------- # ------------------------------------------------------------------------------- __author__ = '<NAME>' __version__ = \"2021-09-02\" \"\"\" This",
"actually connects to the database. \"\"\" cursor = self.cnx.cursor() self.assertEqual(-1, cursor.rowcount, \"Cursor did",
"self.cnx.cursor() self.assertEqual(-1, cursor.rowcount, \"Cursor did not return -1\") return def test_03_database_connection_with_odbc_datasource(self): \"\"\" Test",
"if __name__ == '__main__': report_file = TestConnector.configuration.report_file with open(report_file, 'w') as output: unittest.main(",
"return # ------------------------------------------------------------------------------- # Tests # ------------------------------------------------------------------------------- def test_02_database_connection(self): \"\"\" Test that the",
"# Support Methods # ------------------------------------------------------------------------------- def setUp(self): \"\"\" Initialize the connector. \"\"\" self.cnx",
"------------------------------------------------------------------------------- # Class Variables # ------------------------------------------------------------------------------- configuration = ConnectorTestConfiguration() # ------------------------------------------------------------------------------- # Support",
"cursor = self.cnx.cursor() self.assertEqual(-1, cursor.rowcount, \"Cursor did not return -1\") return def test_03_database_connection_with_odbc_datasource(self):",
"the connector. \"\"\" self.cnx = Connector.create_connector(self.configuration.data_source) return def tearDown(self): self.cnx.close() return # -------------------------------------------------------------------------------",
"import unittest from datetime import datetime import xmlrunner from base.connector import Connector from",
"the ability to connect to the DataHub database. \"\"\" # ------------------------------------------------------------------------------- # Class",
"from queries.policycenterqueries import PolicyCenterQueries # ------------------------------------------------------------------------------- # Test of the Connector class #",
"Support Methods # ------------------------------------------------------------------------------- def setUp(self): \"\"\" Initialize the connector. \"\"\" self.cnx =",
"Copyright (c) 2021 Waysys LLC # # ------------------------------------------------------------------------------- # ------------------------------------------------------------------------------- __author__ = '<NAME>'",
"------------------------------------------------------------------------------- # Support Methods # ------------------------------------------------------------------------------- def setUp(self): \"\"\" Initialize the connector. \"\"\"",
"return def test_03_database_connection_with_odbc_datasource(self): \"\"\" Test connection through ODB data source. Perform a query.",
"PolicyCenterQueries # ------------------------------------------------------------------------------- # Test of the Connector class # ------------------------------------------------------------------------------- class TestConnector(unittest.TestCase):",
"return def tearDown(self): self.cnx.close() return # ------------------------------------------------------------------------------- # Tests # ------------------------------------------------------------------------------- def test_02_database_connection(self):",
"------------------------------------------------------------------------------- # Test of the Connector class # ------------------------------------------------------------------------------- class TestConnector(unittest.TestCase): \"\"\" Test",
"def test_03_database_connection_with_odbc_datasource(self): \"\"\" Test connection through ODB data source. Perform a query. \"\"\"",
"\"\"\" Test connection through ODB data source. Perform a query. \"\"\" pc_queries =",
"+ str(count)) return if __name__ == '__main__': report_file = TestConnector.configuration.report_file with open(report_file, 'w')",
"= datetime(2021, 9, 3) results = pc_queries.query_accounts(selection_start, selection_end) count = len(results) self.assertTrue(count >",
"source. Perform a query. \"\"\" pc_queries = PolicyCenterQueries(self.cnx) selection_start = datetime(2021, 9, 1)",
"self.cnx.close() return # ------------------------------------------------------------------------------- # Tests # ------------------------------------------------------------------------------- def test_02_database_connection(self): \"\"\" Test that",
"count = len(results) self.assertTrue(count > 0, \"Accounts were not found: \" + str(count))",
"'<NAME>' __version__ = \"2021-09-02\" \"\"\" This module tests the Connector class. \"\"\" import",
"datetime import xmlrunner from base.connector import Connector from configuration.config import ConnectorTestConfiguration from queries.policycenterqueries",
"9, 3) results = pc_queries.query_accounts(selection_start, selection_end) count = len(results) self.assertTrue(count > 0, \"Accounts",
"from datetime import datetime import xmlrunner from base.connector import Connector from configuration.config import",
"# ------------------------------------------------------------------------------- # Tests # ------------------------------------------------------------------------------- def test_02_database_connection(self): \"\"\" Test that the connector",
"ability to connect to the DataHub database. \"\"\" # ------------------------------------------------------------------------------- # Class Variables",
"return -1\") return def test_03_database_connection_with_odbc_datasource(self): \"\"\" Test connection through ODB data source. Perform",
"# ------------------------------------------------------------------------------- configuration = ConnectorTestConfiguration() # ------------------------------------------------------------------------------- # Support Methods # ------------------------------------------------------------------------------- def",
"were not found: \" + str(count)) return if __name__ == '__main__': report_file =",
"not return -1\") return def test_03_database_connection_with_odbc_datasource(self): \"\"\" Test connection through ODB data source.",
"== '__main__': report_file = TestConnector.configuration.report_file with open(report_file, 'w') as output: unittest.main( testRunner=xmlrunner.XMLTestRunner(output=output), failfast=False,",
"------------------------------------------------------------------------------- def setUp(self): \"\"\" Initialize the connector. \"\"\" self.cnx = Connector.create_connector(self.configuration.data_source) return def",
"Perform a query. \"\"\" pc_queries = PolicyCenterQueries(self.cnx) selection_start = datetime(2021, 9, 1) selection_end",
"connects to the database. \"\"\" cursor = self.cnx.cursor() self.assertEqual(-1, cursor.rowcount, \"Cursor did not",
"= '<NAME>' __version__ = \"2021-09-02\" \"\"\" This module tests the Connector class. \"\"\"",
"Connector from configuration.config import ConnectorTestConfiguration from queries.policycenterqueries import PolicyCenterQueries # ------------------------------------------------------------------------------- # Test",
"0, \"Accounts were not found: \" + str(count)) return if __name__ == '__main__':",
"__version__ = \"2021-09-02\" \"\"\" This module tests the Connector class. \"\"\" import unittest",
"# ------------------------------------------------------------------------------- __author__ = '<NAME>' __version__ = \"2021-09-02\" \"\"\" This module tests the",
"the DataHub database. \"\"\" # ------------------------------------------------------------------------------- # Class Variables # ------------------------------------------------------------------------------- configuration =",
"# Class Variables # ------------------------------------------------------------------------------- configuration = ConnectorTestConfiguration() # ------------------------------------------------------------------------------- # Support Methods",
"connector. \"\"\" self.cnx = Connector.create_connector(self.configuration.data_source) return def tearDown(self): self.cnx.close() return # ------------------------------------------------------------------------------- #",
"\"Cursor did not return -1\") return def test_03_database_connection_with_odbc_datasource(self): \"\"\" Test connection through ODB",
"\"\"\" import unittest from datetime import datetime import xmlrunner from base.connector import Connector",
"------------------------------------------------------------------------------- __author__ = '<NAME>' __version__ = \"2021-09-02\" \"\"\" This module tests the Connector",
"datetime(2021, 9, 1) selection_end = datetime(2021, 9, 3) results = pc_queries.query_accounts(selection_start, selection_end) count",
"queries.policycenterqueries import PolicyCenterQueries # ------------------------------------------------------------------------------- # Test of the Connector class # -------------------------------------------------------------------------------",
"setUp(self): \"\"\" Initialize the connector. \"\"\" self.cnx = Connector.create_connector(self.configuration.data_source) return def tearDown(self): self.cnx.close()",
"# Tests # ------------------------------------------------------------------------------- def test_02_database_connection(self): \"\"\" Test that the connector actually connects",
"self.cnx = Connector.create_connector(self.configuration.data_source) return def tearDown(self): self.cnx.close() return # ------------------------------------------------------------------------------- # Tests #",
"= Connector.create_connector(self.configuration.data_source) return def tearDown(self): self.cnx.close() return # ------------------------------------------------------------------------------- # Tests # -------------------------------------------------------------------------------",
"Methods # ------------------------------------------------------------------------------- def setUp(self): \"\"\" Initialize the connector. \"\"\" self.cnx = Connector.create_connector(self.configuration.data_source)",
"through ODB data source. Perform a query. \"\"\" pc_queries = PolicyCenterQueries(self.cnx) selection_start =",
"Initialize the connector. \"\"\" self.cnx = Connector.create_connector(self.configuration.data_source) return def tearDown(self): self.cnx.close() return #",
"This module tests the Connector class. \"\"\" import unittest from datetime import datetime",
"Connector class # ------------------------------------------------------------------------------- class TestConnector(unittest.TestCase): \"\"\" Test the ability to connect to",
"pc_queries.query_accounts(selection_start, selection_end) count = len(results) self.assertTrue(count > 0, \"Accounts were not found: \"",
"------------------------------------------------------------------------------- def test_02_database_connection(self): \"\"\" Test that the connector actually connects to the database.",
"Test that the connector actually connects to the database. \"\"\" cursor = self.cnx.cursor()",
"import PolicyCenterQueries # ------------------------------------------------------------------------------- # Test of the Connector class # ------------------------------------------------------------------------------- class",
"from base.connector import Connector from configuration.config import ConnectorTestConfiguration from queries.policycenterqueries import PolicyCenterQueries #",
"to the DataHub database. \"\"\" # ------------------------------------------------------------------------------- # Class Variables # ------------------------------------------------------------------------------- configuration",
"------------------------------------------------------------------------------- # Tests # ------------------------------------------------------------------------------- def test_02_database_connection(self): \"\"\" Test that the connector actually",
"connection through ODB data source. Perform a query. \"\"\" pc_queries = PolicyCenterQueries(self.cnx) selection_start",
"not found: \" + str(count)) return if __name__ == '__main__': report_file = TestConnector.configuration.report_file",
"\"\"\" Test the ability to connect to the DataHub database. \"\"\" # -------------------------------------------------------------------------------",
"Test of the Connector class # ------------------------------------------------------------------------------- class TestConnector(unittest.TestCase): \"\"\" Test the ability",
"a query. \"\"\" pc_queries = PolicyCenterQueries(self.cnx) selection_start = datetime(2021, 9, 1) selection_end =",
"'__main__': report_file = TestConnector.configuration.report_file with open(report_file, 'w') as output: unittest.main( testRunner=xmlrunner.XMLTestRunner(output=output), failfast=False, buffer=False,",
"= \"2021-09-02\" \"\"\" This module tests the Connector class. \"\"\" import unittest from",
"len(results) self.assertTrue(count > 0, \"Accounts were not found: \" + str(count)) return if",
"Connector class. \"\"\" import unittest from datetime import datetime import xmlrunner from base.connector",
"to connect to the DataHub database. \"\"\" # ------------------------------------------------------------------------------- # Class Variables #",
"from configuration.config import ConnectorTestConfiguration from queries.policycenterqueries import PolicyCenterQueries # ------------------------------------------------------------------------------- # Test of",
"def test_02_database_connection(self): \"\"\" Test that the connector actually connects to the database. \"\"\"",
"-1\") return def test_03_database_connection_with_odbc_datasource(self): \"\"\" Test connection through ODB data source. Perform a",
"database. \"\"\" # ------------------------------------------------------------------------------- # Class Variables # ------------------------------------------------------------------------------- configuration = ConnectorTestConfiguration() #",
"# ------------------------------------------------------------------------------- # ------------------------------------------------------------------------------- __author__ = '<NAME>' __version__ = \"2021-09-02\" \"\"\" This module",
"self.assertTrue(count > 0, \"Accounts were not found: \" + str(count)) return if __name__",
"# # Copyright (c) 2021 Waysys LLC # # ------------------------------------------------------------------------------- # ------------------------------------------------------------------------------- __author__",
"configuration = ConnectorTestConfiguration() # ------------------------------------------------------------------------------- # Support Methods # ------------------------------------------------------------------------------- def setUp(self): \"\"\"",
"return if __name__ == '__main__': report_file = TestConnector.configuration.report_file with open(report_file, 'w') as output:",
"------------------------------------------------------------------------------- configuration = ConnectorTestConfiguration() # ------------------------------------------------------------------------------- # Support Methods # ------------------------------------------------------------------------------- def setUp(self):",
"import Connector from configuration.config import ConnectorTestConfiguration from queries.policycenterqueries import PolicyCenterQueries # ------------------------------------------------------------------------------- #",
"<filename>connectortest.py # ------------------------------------------------------------------------------- # # Copyright (c) 2021 Waysys LLC # # -------------------------------------------------------------------------------",
"# ------------------------------------------------------------------------------- # Support Methods # ------------------------------------------------------------------------------- def setUp(self): \"\"\" Initialize the connector.",
"selection_end) count = len(results) self.assertTrue(count > 0, \"Accounts were not found: \" +"
] |
[
"from django import forms from django.utils.translation import gettext_lazy as _ class TwoFactorForm(forms.Form): code",
"from django.utils.translation import gettext_lazy as _ class TwoFactorForm(forms.Form): code = forms.CharField(label=_(\"two.factor.code.label\"), max_length=8, min_length=1)",
"django import forms from django.utils.translation import gettext_lazy as _ class TwoFactorForm(forms.Form): code =",
"forms from django.utils.translation import gettext_lazy as _ class TwoFactorForm(forms.Form): code = forms.CharField(label=_(\"two.factor.code.label\"), max_length=8,",
"import forms from django.utils.translation import gettext_lazy as _ class TwoFactorForm(forms.Form): code = forms.CharField(label=_(\"two.factor.code.label\"),",
"<filename>j2fa/forms.py from django import forms from django.utils.translation import gettext_lazy as _ class TwoFactorForm(forms.Form):"
] |
[
"uploaded files...\") self.wav_file = st.file_uploader( \"Choose a wav file\", type=[\"wav\"], accept_multiple_files=self.multiple_files ) if",
"keys = ['direction', 'load', 'y','sr'] self.df = pd.DataFrame(data=measures, index=range(len(measures))) def add_select_options(row): return f\"{row.name}_{row.direction}_{row.load}\"",
"self.df[\"select_options\"] = self.df.apply(add_select_options, axis=1) def _selector_for_measures(self): self.selected_measure = st.selectbox( label=f\"select measure for preprocess\",",
"float) -> None: num_of_points_to_drop_left = int(left_cut * self.sr) num_of_points_to_drop_right = int(right_cut * self.sr)",
"the load, sr are set to 22050 according to librosa default setting. :param",
"multiple_files: bool = False): self.multiple_files = multiple_files self.y = None self.sr = None",
"self.wav_file.name self._load_audio() self.cut_audio_in_second(left_cut=0.5, right_cut=0.5) self._show_audio(self.wav_file) def cut_audio_in_second(self, left_cut: float, right_cut: float) -> None:",
"def _load_audio(self, offset: float = None) -> None: \"\"\"get y and sr from",
"set to 22050 according to librosa default setting. :param offset: [time for start",
"sr=self.sr, offset=offset, mono=True ) def _show_audio(self, wav_file): st.audio(wav_file, format=\"audio/wav\") class tdmsFileLoader(fileLoader): def __init__(self):",
"for preprocess\", options=self.df[\"select_options\"], key=\"seleced_tdms_measure\", ) df_row_selected = self.df[self.df[\"select_options\"] == self.selected_measure] logging.info(f\"{self.selected_measure} selected !\")",
"num_of_points_to_drop_right = int(right_cut * self.sr) self.y = self.y[num_of_points_to_drop_left:-num_of_points_to_drop_right] def _load_audio(self, offset: float =",
"in the audio file. in second ], defaults to None :type offset: float,",
"sr from wav file, and save them into object related property during the",
"None: \"\"\"get y and sr from wav file, and save them into object",
"label=f\"select measure for preprocess\", options=self.df[\"select_options\"], key=\"seleced_tdms_measure\", ) df_row_selected = self.df[self.df[\"select_options\"] == self.selected_measure] logging.info(f\"{self.selected_measure}",
"def cut_audio_in_second(self, left_cut: float, right_cut: float) -> None: num_of_points_to_drop_left = int(left_cut * self.sr)",
"import logging import streamlit as st import librosa import pandas as pd import",
"= multiple_files self.y = None self.sr = None self.get_uploaded() @abstractmethod def get_uploaded(self): pass",
"= int(left_cut * self.sr) num_of_points_to_drop_right = int(right_cut * self.sr) self.y = self.y[num_of_points_to_drop_left:-num_of_points_to_drop_right] def",
"self.sr = librosa.load( self.wav_file, sr=self.sr, offset=offset, mono=True ) def _show_audio(self, wav_file): st.audio(wav_file, format=\"audio/wav\")",
"= tdmsReader(self.tdms_file) measures = obj.prepare_output_per_tdms() # * measures is List[dict], dict keys =",
"self.selected_measure = st.selectbox( label=f\"select measure for preprocess\", options=self.df[\"select_options\"], key=\"seleced_tdms_measure\", ) df_row_selected = self.df[self.df[\"select_options\"]",
"def get_uploaded(self): pass class wavFileLoader(fileLoader): def __init__(self): super().__init__() self.suffix = \".wav\" def get_uploaded(self):",
"self.tdms_file: self._load_tdms() self._selector_for_measures() self.title = f\"{Path(self.tdms_file.name).stem}_{self.selected_measure}\" def _load_tdms(self): obj = tdmsReader(self.tdms_file) measures =",
"class tdmsFileLoader(fileLoader): def __init__(self): super().__init__() def get_uploaded(self): logging.info(\"Refreshing uploaded files...\") self.tdms_file = st.file_uploader(",
"'y','sr'] self.df = pd.DataFrame(data=measures, index=range(len(measures))) def add_select_options(row): return f\"{row.name}_{row.direction}_{row.load}\" self.df[\"select_options\"] = self.df.apply(add_select_options, axis=1)",
"accept_multiple_files=self.multiple_files ) if self.wav_file: self.title = self.wav_file.name self._load_audio() self.cut_audio_in_second(left_cut=0.5, right_cut=0.5) self._show_audio(self.wav_file) def cut_audio_in_second(self,",
"pathlib import Path import logging import streamlit as st import librosa import pandas",
"def __init__(self, multiple_files: bool = False): self.multiple_files = multiple_files self.y = None self.sr",
"default setting. :param offset: [time for start to read, in the audio file.",
"wav_file): st.audio(wav_file, format=\"audio/wav\") class tdmsFileLoader(fileLoader): def __init__(self): super().__init__() def get_uploaded(self): logging.info(\"Refreshing uploaded files...\")",
"import numpy as np from fs_preprocess.tdmsReader import tdmsReader class fileLoader(ABC): \"\"\"fileLoader meta class\"\"\"",
"add_select_options(row): return f\"{row.name}_{row.direction}_{row.load}\" self.df[\"select_options\"] = self.df.apply(add_select_options, axis=1) def _selector_for_measures(self): self.selected_measure = st.selectbox( label=f\"select",
"import Path import logging import streamlit as st import librosa import pandas as",
"tdmsReader class fileLoader(ABC): \"\"\"fileLoader meta class\"\"\" def __init__(self, multiple_files: bool = False): self.multiple_files",
"self.y[num_of_points_to_drop_left:-num_of_points_to_drop_right] def _load_audio(self, offset: float = None) -> None: \"\"\"get y and sr",
"property during the load, sr are set to 22050 according to librosa default",
"load, sr are set to 22050 according to librosa default setting. :param offset:",
"\"Choose a tdms file\", type=[\"tdms\"], accept_multiple_files=self.multiple_files, ) if self.tdms_file: self._load_tdms() self._selector_for_measures() self.title =",
"None self.sr = None self.get_uploaded() @abstractmethod def get_uploaded(self): pass class wavFileLoader(fileLoader): def __init__(self):",
"self.get_uploaded() @abstractmethod def get_uploaded(self): pass class wavFileLoader(fileLoader): def __init__(self): super().__init__() self.suffix = \".wav\"",
"float = None) -> None: \"\"\"get y and sr from wav file, and",
"def _selector_for_measures(self): self.selected_measure = st.selectbox( label=f\"select measure for preprocess\", options=self.df[\"select_options\"], key=\"seleced_tdms_measure\", ) df_row_selected",
"self.tdms_file = st.file_uploader( \"Choose a tdms file\", type=[\"tdms\"], accept_multiple_files=self.multiple_files, ) if self.tdms_file: self._load_tdms()",
"st import librosa import pandas as pd import numpy as np from fs_preprocess.tdmsReader",
"uploaded files...\") self.tdms_file = st.file_uploader( \"Choose a tdms file\", type=[\"tdms\"], accept_multiple_files=self.multiple_files, ) if",
"self._load_tdms() self._selector_for_measures() self.title = f\"{Path(self.tdms_file.name).stem}_{self.selected_measure}\" def _load_tdms(self): obj = tdmsReader(self.tdms_file) measures = obj.prepare_output_per_tdms()",
"def _load_tdms(self): obj = tdmsReader(self.tdms_file) measures = obj.prepare_output_per_tdms() # * measures is List[dict],",
"self.sr = None self.get_uploaded() @abstractmethod def get_uploaded(self): pass class wavFileLoader(fileLoader): def __init__(self): super().__init__()",
"multiple_files self.y = None self.sr = None self.get_uploaded() @abstractmethod def get_uploaded(self): pass class",
"right_cut: float) -> None: num_of_points_to_drop_left = int(left_cut * self.sr) num_of_points_to_drop_right = int(right_cut *",
"np from fs_preprocess.tdmsReader import tdmsReader class fileLoader(ABC): \"\"\"fileLoader meta class\"\"\" def __init__(self, multiple_files:",
"def _show_audio(self, wav_file): st.audio(wav_file, format=\"audio/wav\") class tdmsFileLoader(fileLoader): def __init__(self): super().__init__() def get_uploaded(self): logging.info(\"Refreshing",
"def add_select_options(row): return f\"{row.name}_{row.direction}_{row.load}\" self.df[\"select_options\"] = self.df.apply(add_select_options, axis=1) def _selector_for_measures(self): self.selected_measure = st.selectbox(",
"st.audio(wav_file, format=\"audio/wav\") class tdmsFileLoader(fileLoader): def __init__(self): super().__init__() def get_uploaded(self): logging.info(\"Refreshing uploaded files...\") self.tdms_file",
"self.df = pd.DataFrame(data=measures, index=range(len(measures))) def add_select_options(row): return f\"{row.name}_{row.direction}_{row.load}\" self.df[\"select_options\"] = self.df.apply(add_select_options, axis=1) def",
"_selector_for_measures(self): self.selected_measure = st.selectbox( label=f\"select measure for preprocess\", options=self.df[\"select_options\"], key=\"seleced_tdms_measure\", ) df_row_selected =",
"save them into object related property during the load, sr are set to",
"@abstractmethod def get_uploaded(self): pass class wavFileLoader(fileLoader): def __init__(self): super().__init__() self.suffix = \".wav\" def",
"import pandas as pd import numpy as np from fs_preprocess.tdmsReader import tdmsReader class",
"format=\"audio/wav\") class tdmsFileLoader(fileLoader): def __init__(self): super().__init__() def get_uploaded(self): logging.info(\"Refreshing uploaded files...\") self.tdms_file =",
"tdmsReader(self.tdms_file) measures = obj.prepare_output_per_tdms() # * measures is List[dict], dict keys = ['direction',",
"them into object related property during the load, sr are set to 22050",
"cut_audio_in_second(self, left_cut: float, right_cut: float) -> None: num_of_points_to_drop_left = int(left_cut * self.sr) num_of_points_to_drop_right",
"# * measures is List[dict], dict keys = ['direction', 'load', 'y','sr'] self.df =",
"measures is List[dict], dict keys = ['direction', 'load', 'y','sr'] self.df = pd.DataFrame(data=measures, index=range(len(measures)))",
"['direction', 'load', 'y','sr'] self.df = pd.DataFrame(data=measures, index=range(len(measures))) def add_select_options(row): return f\"{row.name}_{row.direction}_{row.load}\" self.df[\"select_options\"] =",
"setting. :param offset: [time for start to read, in the audio file. in",
"librosa import pandas as pd import numpy as np from fs_preprocess.tdmsReader import tdmsReader",
"from abc import abstractmethod, ABC from pathlib import Path import logging import streamlit",
"import streamlit as st import librosa import pandas as pd import numpy as",
"_load_audio(self, offset: float = None) -> None: \"\"\"get y and sr from wav",
"-> None: num_of_points_to_drop_left = int(left_cut * self.sr) num_of_points_to_drop_right = int(right_cut * self.sr) self.y",
"False): self.multiple_files = multiple_files self.y = None self.sr = None self.get_uploaded() @abstractmethod def",
"offset: float, optional \"\"\" self.y, self.sr = librosa.load( self.wav_file, sr=self.sr, offset=offset, mono=True )",
"df_row_selected = self.df[self.df[\"select_options\"] == self.selected_measure] logging.info(f\"{self.selected_measure} selected !\") self.y = df_row_selected.y.to_list()[0] self.sr =",
"def get_uploaded(self): logging.info(\"Refreshing uploaded files...\") self.tdms_file = st.file_uploader( \"Choose a tdms file\", type=[\"tdms\"],",
"int(left_cut * self.sr) num_of_points_to_drop_right = int(right_cut * self.sr) self.y = self.y[num_of_points_to_drop_left:-num_of_points_to_drop_right] def _load_audio(self,",
"self.title = f\"{Path(self.tdms_file.name).stem}_{self.selected_measure}\" def _load_tdms(self): obj = tdmsReader(self.tdms_file) measures = obj.prepare_output_per_tdms() # *",
"audio file. in second ], defaults to None :type offset: float, optional \"\"\"",
"None :type offset: float, optional \"\"\" self.y, self.sr = librosa.load( self.wav_file, sr=self.sr, offset=offset,",
"get_uploaded(self): logging.info(\"Refreshing uploaded files...\") self.wav_file = st.file_uploader( \"Choose a wav file\", type=[\"wav\"], accept_multiple_files=self.multiple_files",
"measures = obj.prepare_output_per_tdms() # * measures is List[dict], dict keys = ['direction', 'load',",
"self.sr) self.y = self.y[num_of_points_to_drop_left:-num_of_points_to_drop_right] def _load_audio(self, offset: float = None) -> None: \"\"\"get",
"dict keys = ['direction', 'load', 'y','sr'] self.df = pd.DataFrame(data=measures, index=range(len(measures))) def add_select_options(row): return",
") if self.tdms_file: self._load_tdms() self._selector_for_measures() self.title = f\"{Path(self.tdms_file.name).stem}_{self.selected_measure}\" def _load_tdms(self): obj = tdmsReader(self.tdms_file)",
"librosa default setting. :param offset: [time for start to read, in the audio",
"= False): self.multiple_files = multiple_files self.y = None self.sr = None self.get_uploaded() @abstractmethod",
"self.wav_file = st.file_uploader( \"Choose a wav file\", type=[\"wav\"], accept_multiple_files=self.multiple_files ) if self.wav_file: self.title",
"self._show_audio(self.wav_file) def cut_audio_in_second(self, left_cut: float, right_cut: float) -> None: num_of_points_to_drop_left = int(left_cut *",
"the audio file. in second ], defaults to None :type offset: float, optional",
"preprocess\", options=self.df[\"select_options\"], key=\"seleced_tdms_measure\", ) df_row_selected = self.df[self.df[\"select_options\"] == self.selected_measure] logging.info(f\"{self.selected_measure} selected !\") self.y",
"abc import abstractmethod, ABC from pathlib import Path import logging import streamlit as",
"bool = False): self.multiple_files = multiple_files self.y = None self.sr = None self.get_uploaded()",
"pass class wavFileLoader(fileLoader): def __init__(self): super().__init__() self.suffix = \".wav\" def get_uploaded(self): logging.info(\"Refreshing uploaded",
"get_uploaded(self): logging.info(\"Refreshing uploaded files...\") self.tdms_file = st.file_uploader( \"Choose a tdms file\", type=[\"tdms\"], accept_multiple_files=self.multiple_files,",
"according to librosa default setting. :param offset: [time for start to read, in",
"self.y, self.sr = librosa.load( self.wav_file, sr=self.sr, offset=offset, mono=True ) def _show_audio(self, wav_file): st.audio(wav_file,",
"get_uploaded(self): pass class wavFileLoader(fileLoader): def __init__(self): super().__init__() self.suffix = \".wav\" def get_uploaded(self): logging.info(\"Refreshing",
"\".wav\" def get_uploaded(self): logging.info(\"Refreshing uploaded files...\") self.wav_file = st.file_uploader( \"Choose a wav file\",",
"22050 according to librosa default setting. :param offset: [time for start to read,",
"obj.prepare_output_per_tdms() # * measures is List[dict], dict keys = ['direction', 'load', 'y','sr'] self.df",
"[time for start to read, in the audio file. in second ], defaults",
"__init__(self): super().__init__() self.suffix = \".wav\" def get_uploaded(self): logging.info(\"Refreshing uploaded files...\") self.wav_file = st.file_uploader(",
"offset=offset, mono=True ) def _show_audio(self, wav_file): st.audio(wav_file, format=\"audio/wav\") class tdmsFileLoader(fileLoader): def __init__(self): super().__init__()",
"index=range(len(measures))) def add_select_options(row): return f\"{row.name}_{row.direction}_{row.load}\" self.df[\"select_options\"] = self.df.apply(add_select_options, axis=1) def _selector_for_measures(self): self.selected_measure =",
"self.cut_audio_in_second(left_cut=0.5, right_cut=0.5) self._show_audio(self.wav_file) def cut_audio_in_second(self, left_cut: float, right_cut: float) -> None: num_of_points_to_drop_left =",
"files...\") self.tdms_file = st.file_uploader( \"Choose a tdms file\", type=[\"tdms\"], accept_multiple_files=self.multiple_files, ) if self.tdms_file:",
"self.wav_file, sr=self.sr, offset=offset, mono=True ) def _show_audio(self, wav_file): st.audio(wav_file, format=\"audio/wav\") class tdmsFileLoader(fileLoader): def",
"read, in the audio file. in second ], defaults to None :type offset:",
"None: num_of_points_to_drop_left = int(left_cut * self.sr) num_of_points_to_drop_right = int(right_cut * self.sr) self.y =",
"* self.sr) num_of_points_to_drop_right = int(right_cut * self.sr) self.y = self.y[num_of_points_to_drop_left:-num_of_points_to_drop_right] def _load_audio(self, offset:",
":type offset: float, optional \"\"\" self.y, self.sr = librosa.load( self.wav_file, sr=self.sr, offset=offset, mono=True",
") if self.wav_file: self.title = self.wav_file.name self._load_audio() self.cut_audio_in_second(left_cut=0.5, right_cut=0.5) self._show_audio(self.wav_file) def cut_audio_in_second(self, left_cut:",
"self.suffix = \".wav\" def get_uploaded(self): logging.info(\"Refreshing uploaded files...\") self.wav_file = st.file_uploader( \"Choose a",
"float, optional \"\"\" self.y, self.sr = librosa.load( self.wav_file, sr=self.sr, offset=offset, mono=True ) def",
"pd import numpy as np from fs_preprocess.tdmsReader import tdmsReader class fileLoader(ABC): \"\"\"fileLoader meta",
"pd.DataFrame(data=measures, index=range(len(measures))) def add_select_options(row): return f\"{row.name}_{row.direction}_{row.load}\" self.df[\"select_options\"] = self.df.apply(add_select_options, axis=1) def _selector_for_measures(self): self.selected_measure",
"to None :type offset: float, optional \"\"\" self.y, self.sr = librosa.load( self.wav_file, sr=self.sr,",
"= ['direction', 'load', 'y','sr'] self.df = pd.DataFrame(data=measures, index=range(len(measures))) def add_select_options(row): return f\"{row.name}_{row.direction}_{row.load}\" self.df[\"select_options\"]",
"during the load, sr are set to 22050 according to librosa default setting.",
"into object related property during the load, sr are set to 22050 according",
"self.wav_file: self.title = self.wav_file.name self._load_audio() self.cut_audio_in_second(left_cut=0.5, right_cut=0.5) self._show_audio(self.wav_file) def cut_audio_in_second(self, left_cut: float, right_cut:",
"Path import logging import streamlit as st import librosa import pandas as pd",
"= None self.sr = None self.get_uploaded() @abstractmethod def get_uploaded(self): pass class wavFileLoader(fileLoader): def",
"'load', 'y','sr'] self.df = pd.DataFrame(data=measures, index=range(len(measures))) def add_select_options(row): return f\"{row.name}_{row.direction}_{row.load}\" self.df[\"select_options\"] = self.df.apply(add_select_options,",
"file, and save them into object related property during the load, sr are",
"and sr from wav file, and save them into object related property during",
"class\"\"\" def __init__(self, multiple_files: bool = False): self.multiple_files = multiple_files self.y = None",
"to read, in the audio file. in second ], defaults to None :type",
"object related property during the load, sr are set to 22050 according to",
"file\", type=[\"wav\"], accept_multiple_files=self.multiple_files ) if self.wav_file: self.title = self.wav_file.name self._load_audio() self.cut_audio_in_second(left_cut=0.5, right_cut=0.5) self._show_audio(self.wav_file)",
"float, right_cut: float) -> None: num_of_points_to_drop_left = int(left_cut * self.sr) num_of_points_to_drop_right = int(right_cut",
"left_cut: float, right_cut: float) -> None: num_of_points_to_drop_left = int(left_cut * self.sr) num_of_points_to_drop_right =",
"<gh_stars>0 from abc import abstractmethod, ABC from pathlib import Path import logging import",
"y and sr from wav file, and save them into object related property",
"class wavFileLoader(fileLoader): def __init__(self): super().__init__() self.suffix = \".wav\" def get_uploaded(self): logging.info(\"Refreshing uploaded files...\")",
"__init__(self, multiple_files: bool = False): self.multiple_files = multiple_files self.y = None self.sr =",
"file. in second ], defaults to None :type offset: float, optional \"\"\" self.y,",
"meta class\"\"\" def __init__(self, multiple_files: bool = False): self.multiple_files = multiple_files self.y =",
"logging.info(\"Refreshing uploaded files...\") self.tdms_file = st.file_uploader( \"Choose a tdms file\", type=[\"tdms\"], accept_multiple_files=self.multiple_files, )",
"to librosa default setting. :param offset: [time for start to read, in the",
"ABC from pathlib import Path import logging import streamlit as st import librosa",
"abstractmethod, ABC from pathlib import Path import logging import streamlit as st import",
"st.file_uploader( \"Choose a tdms file\", type=[\"tdms\"], accept_multiple_files=self.multiple_files, ) if self.tdms_file: self._load_tdms() self._selector_for_measures() self.title",
"wav file, and save them into object related property during the load, sr",
"defaults to None :type offset: float, optional \"\"\" self.y, self.sr = librosa.load( self.wav_file,",
"= st.selectbox( label=f\"select measure for preprocess\", options=self.df[\"select_options\"], key=\"seleced_tdms_measure\", ) df_row_selected = self.df[self.df[\"select_options\"] ==",
"import abstractmethod, ABC from pathlib import Path import logging import streamlit as st",
"def __init__(self): super().__init__() def get_uploaded(self): logging.info(\"Refreshing uploaded files...\") self.tdms_file = st.file_uploader( \"Choose a",
"super().__init__() def get_uploaded(self): logging.info(\"Refreshing uploaded files...\") self.tdms_file = st.file_uploader( \"Choose a tdms file\",",
"numpy as np from fs_preprocess.tdmsReader import tdmsReader class fileLoader(ABC): \"\"\"fileLoader meta class\"\"\" def",
"key=\"seleced_tdms_measure\", ) df_row_selected = self.df[self.df[\"select_options\"] == self.selected_measure] logging.info(f\"{self.selected_measure} selected !\") self.y = df_row_selected.y.to_list()[0]",
"pandas as pd import numpy as np from fs_preprocess.tdmsReader import tdmsReader class fileLoader(ABC):",
"def __init__(self): super().__init__() self.suffix = \".wav\" def get_uploaded(self): logging.info(\"Refreshing uploaded files...\") self.wav_file =",
"self.title = self.wav_file.name self._load_audio() self.cut_audio_in_second(left_cut=0.5, right_cut=0.5) self._show_audio(self.wav_file) def cut_audio_in_second(self, left_cut: float, right_cut: float)",
"\"Choose a wav file\", type=[\"wav\"], accept_multiple_files=self.multiple_files ) if self.wav_file: self.title = self.wav_file.name self._load_audio()",
"files...\") self.wav_file = st.file_uploader( \"Choose a wav file\", type=[\"wav\"], accept_multiple_files=self.multiple_files ) if self.wav_file:",
"type=[\"tdms\"], accept_multiple_files=self.multiple_files, ) if self.tdms_file: self._load_tdms() self._selector_for_measures() self.title = f\"{Path(self.tdms_file.name).stem}_{self.selected_measure}\" def _load_tdms(self): obj",
"measure for preprocess\", options=self.df[\"select_options\"], key=\"seleced_tdms_measure\", ) df_row_selected = self.df[self.df[\"select_options\"] == self.selected_measure] logging.info(f\"{self.selected_measure} selected",
"= self.df[self.df[\"select_options\"] == self.selected_measure] logging.info(f\"{self.selected_measure} selected !\") self.y = df_row_selected.y.to_list()[0] self.sr = df_row_selected.sr.to_list()[0]",
"streamlit as st import librosa import pandas as pd import numpy as np",
"a wav file\", type=[\"wav\"], accept_multiple_files=self.multiple_files ) if self.wav_file: self.title = self.wav_file.name self._load_audio() self.cut_audio_in_second(left_cut=0.5,",
"-> None: \"\"\"get y and sr from wav file, and save them into",
"_load_tdms(self): obj = tdmsReader(self.tdms_file) measures = obj.prepare_output_per_tdms() # * measures is List[dict], dict",
"List[dict], dict keys = ['direction', 'load', 'y','sr'] self.df = pd.DataFrame(data=measures, index=range(len(measures))) def add_select_options(row):",
"self.df.apply(add_select_options, axis=1) def _selector_for_measures(self): self.selected_measure = st.selectbox( label=f\"select measure for preprocess\", options=self.df[\"select_options\"], key=\"seleced_tdms_measure\",",
"\"\"\"fileLoader meta class\"\"\" def __init__(self, multiple_files: bool = False): self.multiple_files = multiple_files self.y",
":param offset: [time for start to read, in the audio file. in second",
"type=[\"wav\"], accept_multiple_files=self.multiple_files ) if self.wav_file: self.title = self.wav_file.name self._load_audio() self.cut_audio_in_second(left_cut=0.5, right_cut=0.5) self._show_audio(self.wav_file) def",
"f\"{row.name}_{row.direction}_{row.load}\" self.df[\"select_options\"] = self.df.apply(add_select_options, axis=1) def _selector_for_measures(self): self.selected_measure = st.selectbox( label=f\"select measure for",
"to 22050 according to librosa default setting. :param offset: [time for start to",
"class fileLoader(ABC): \"\"\"fileLoader meta class\"\"\" def __init__(self, multiple_files: bool = False): self.multiple_files =",
") def _show_audio(self, wav_file): st.audio(wav_file, format=\"audio/wav\") class tdmsFileLoader(fileLoader): def __init__(self): super().__init__() def get_uploaded(self):",
"= \".wav\" def get_uploaded(self): logging.info(\"Refreshing uploaded files...\") self.wav_file = st.file_uploader( \"Choose a wav",
"__init__(self): super().__init__() def get_uploaded(self): logging.info(\"Refreshing uploaded files...\") self.tdms_file = st.file_uploader( \"Choose a tdms",
"= st.file_uploader( \"Choose a tdms file\", type=[\"tdms\"], accept_multiple_files=self.multiple_files, ) if self.tdms_file: self._load_tdms() self._selector_for_measures()",
"tdmsFileLoader(fileLoader): def __init__(self): super().__init__() def get_uploaded(self): logging.info(\"Refreshing uploaded files...\") self.tdms_file = st.file_uploader( \"Choose",
"return f\"{row.name}_{row.direction}_{row.load}\" self.df[\"select_options\"] = self.df.apply(add_select_options, axis=1) def _selector_for_measures(self): self.selected_measure = st.selectbox( label=f\"select measure",
"f\"{Path(self.tdms_file.name).stem}_{self.selected_measure}\" def _load_tdms(self): obj = tdmsReader(self.tdms_file) measures = obj.prepare_output_per_tdms() # * measures is",
"offset: [time for start to read, in the audio file. in second ],",
"obj = tdmsReader(self.tdms_file) measures = obj.prepare_output_per_tdms() # * measures is List[dict], dict keys",
"accept_multiple_files=self.multiple_files, ) if self.tdms_file: self._load_tdms() self._selector_for_measures() self.title = f\"{Path(self.tdms_file.name).stem}_{self.selected_measure}\" def _load_tdms(self): obj =",
"as st import librosa import pandas as pd import numpy as np from",
"= obj.prepare_output_per_tdms() # * measures is List[dict], dict keys = ['direction', 'load', 'y','sr']",
") df_row_selected = self.df[self.df[\"select_options\"] == self.selected_measure] logging.info(f\"{self.selected_measure} selected !\") self.y = df_row_selected.y.to_list()[0] self.sr",
"num_of_points_to_drop_left = int(left_cut * self.sr) num_of_points_to_drop_right = int(right_cut * self.sr) self.y = self.y[num_of_points_to_drop_left:-num_of_points_to_drop_right]",
"right_cut=0.5) self._show_audio(self.wav_file) def cut_audio_in_second(self, left_cut: float, right_cut: float) -> None: num_of_points_to_drop_left = int(left_cut",
"int(right_cut * self.sr) self.y = self.y[num_of_points_to_drop_left:-num_of_points_to_drop_right] def _load_audio(self, offset: float = None) ->",
"librosa.load( self.wav_file, sr=self.sr, offset=offset, mono=True ) def _show_audio(self, wav_file): st.audio(wav_file, format=\"audio/wav\") class tdmsFileLoader(fileLoader):",
"is List[dict], dict keys = ['direction', 'load', 'y','sr'] self.df = pd.DataFrame(data=measures, index=range(len(measures))) def",
"= self.wav_file.name self._load_audio() self.cut_audio_in_second(left_cut=0.5, right_cut=0.5) self._show_audio(self.wav_file) def cut_audio_in_second(self, left_cut: float, right_cut: float) ->",
"if self.wav_file: self.title = self.wav_file.name self._load_audio() self.cut_audio_in_second(left_cut=0.5, right_cut=0.5) self._show_audio(self.wav_file) def cut_audio_in_second(self, left_cut: float,",
"as pd import numpy as np from fs_preprocess.tdmsReader import tdmsReader class fileLoader(ABC): \"\"\"fileLoader",
"wav file\", type=[\"wav\"], accept_multiple_files=self.multiple_files ) if self.wav_file: self.title = self.wav_file.name self._load_audio() self.cut_audio_in_second(left_cut=0.5, right_cut=0.5)",
"if self.tdms_file: self._load_tdms() self._selector_for_measures() self.title = f\"{Path(self.tdms_file.name).stem}_{self.selected_measure}\" def _load_tdms(self): obj = tdmsReader(self.tdms_file) measures",
"axis=1) def _selector_for_measures(self): self.selected_measure = st.selectbox( label=f\"select measure for preprocess\", options=self.df[\"select_options\"], key=\"seleced_tdms_measure\", )",
"fileLoader(ABC): \"\"\"fileLoader meta class\"\"\" def __init__(self, multiple_files: bool = False): self.multiple_files = multiple_files",
"wavFileLoader(fileLoader): def __init__(self): super().__init__() self.suffix = \".wav\" def get_uploaded(self): logging.info(\"Refreshing uploaded files...\") self.wav_file",
"in second ], defaults to None :type offset: float, optional \"\"\" self.y, self.sr",
"self.multiple_files = multiple_files self.y = None self.sr = None self.get_uploaded() @abstractmethod def get_uploaded(self):",
"import librosa import pandas as pd import numpy as np from fs_preprocess.tdmsReader import",
"are set to 22050 according to librosa default setting. :param offset: [time for",
"for start to read, in the audio file. in second ], defaults to",
"options=self.df[\"select_options\"], key=\"seleced_tdms_measure\", ) df_row_selected = self.df[self.df[\"select_options\"] == self.selected_measure] logging.info(f\"{self.selected_measure} selected !\") self.y =",
"= st.file_uploader( \"Choose a wav file\", type=[\"wav\"], accept_multiple_files=self.multiple_files ) if self.wav_file: self.title =",
"mono=True ) def _show_audio(self, wav_file): st.audio(wav_file, format=\"audio/wav\") class tdmsFileLoader(fileLoader): def __init__(self): super().__init__() def",
"from wav file, and save them into object related property during the load,",
"\"\"\" self.y, self.sr = librosa.load( self.wav_file, sr=self.sr, offset=offset, mono=True ) def _show_audio(self, wav_file):",
"second ], defaults to None :type offset: float, optional \"\"\" self.y, self.sr =",
"= pd.DataFrame(data=measures, index=range(len(measures))) def add_select_options(row): return f\"{row.name}_{row.direction}_{row.load}\" self.df[\"select_options\"] = self.df.apply(add_select_options, axis=1) def _selector_for_measures(self):",
"as np from fs_preprocess.tdmsReader import tdmsReader class fileLoader(ABC): \"\"\"fileLoader meta class\"\"\" def __init__(self,",
"related property during the load, sr are set to 22050 according to librosa",
"= self.y[num_of_points_to_drop_left:-num_of_points_to_drop_right] def _load_audio(self, offset: float = None) -> None: \"\"\"get y and",
"logging import streamlit as st import librosa import pandas as pd import numpy",
"self._load_audio() self.cut_audio_in_second(left_cut=0.5, right_cut=0.5) self._show_audio(self.wav_file) def cut_audio_in_second(self, left_cut: float, right_cut: float) -> None: num_of_points_to_drop_left",
"fs_preprocess.tdmsReader import tdmsReader class fileLoader(ABC): \"\"\"fileLoader meta class\"\"\" def __init__(self, multiple_files: bool =",
"tdms file\", type=[\"tdms\"], accept_multiple_files=self.multiple_files, ) if self.tdms_file: self._load_tdms() self._selector_for_measures() self.title = f\"{Path(self.tdms_file.name).stem}_{self.selected_measure}\" def",
"import tdmsReader class fileLoader(ABC): \"\"\"fileLoader meta class\"\"\" def __init__(self, multiple_files: bool = False):",
"* self.sr) self.y = self.y[num_of_points_to_drop_left:-num_of_points_to_drop_right] def _load_audio(self, offset: float = None) -> None:",
"file\", type=[\"tdms\"], accept_multiple_files=self.multiple_files, ) if self.tdms_file: self._load_tdms() self._selector_for_measures() self.title = f\"{Path(self.tdms_file.name).stem}_{self.selected_measure}\" def _load_tdms(self):",
"self._selector_for_measures() self.title = f\"{Path(self.tdms_file.name).stem}_{self.selected_measure}\" def _load_tdms(self): obj = tdmsReader(self.tdms_file) measures = obj.prepare_output_per_tdms() #",
"sr are set to 22050 according to librosa default setting. :param offset: [time",
"= librosa.load( self.wav_file, sr=self.sr, offset=offset, mono=True ) def _show_audio(self, wav_file): st.audio(wav_file, format=\"audio/wav\") class",
"= self.df.apply(add_select_options, axis=1) def _selector_for_measures(self): self.selected_measure = st.selectbox( label=f\"select measure for preprocess\", options=self.df[\"select_options\"],",
"offset: float = None) -> None: \"\"\"get y and sr from wav file,",
"= f\"{Path(self.tdms_file.name).stem}_{self.selected_measure}\" def _load_tdms(self): obj = tdmsReader(self.tdms_file) measures = obj.prepare_output_per_tdms() # * measures",
"None self.get_uploaded() @abstractmethod def get_uploaded(self): pass class wavFileLoader(fileLoader): def __init__(self): super().__init__() self.suffix =",
"= None) -> None: \"\"\"get y and sr from wav file, and save",
"_show_audio(self, wav_file): st.audio(wav_file, format=\"audio/wav\") class tdmsFileLoader(fileLoader): def __init__(self): super().__init__() def get_uploaded(self): logging.info(\"Refreshing uploaded",
"def get_uploaded(self): logging.info(\"Refreshing uploaded files...\") self.wav_file = st.file_uploader( \"Choose a wav file\", type=[\"wav\"],",
"], defaults to None :type offset: float, optional \"\"\" self.y, self.sr = librosa.load(",
"start to read, in the audio file. in second ], defaults to None",
"= int(right_cut * self.sr) self.y = self.y[num_of_points_to_drop_left:-num_of_points_to_drop_right] def _load_audio(self, offset: float = None)",
"st.file_uploader( \"Choose a wav file\", type=[\"wav\"], accept_multiple_files=self.multiple_files ) if self.wav_file: self.title = self.wav_file.name",
"self.y = None self.sr = None self.get_uploaded() @abstractmethod def get_uploaded(self): pass class wavFileLoader(fileLoader):",
"self.sr) num_of_points_to_drop_right = int(right_cut * self.sr) self.y = self.y[num_of_points_to_drop_left:-num_of_points_to_drop_right] def _load_audio(self, offset: float",
"\"\"\"get y and sr from wav file, and save them into object related",
"self.y = self.y[num_of_points_to_drop_left:-num_of_points_to_drop_right] def _load_audio(self, offset: float = None) -> None: \"\"\"get y",
"st.selectbox( label=f\"select measure for preprocess\", options=self.df[\"select_options\"], key=\"seleced_tdms_measure\", ) df_row_selected = self.df[self.df[\"select_options\"] == self.selected_measure]",
"a tdms file\", type=[\"tdms\"], accept_multiple_files=self.multiple_files, ) if self.tdms_file: self._load_tdms() self._selector_for_measures() self.title = f\"{Path(self.tdms_file.name).stem}_{self.selected_measure}\"",
"* measures is List[dict], dict keys = ['direction', 'load', 'y','sr'] self.df = pd.DataFrame(data=measures,",
"None) -> None: \"\"\"get y and sr from wav file, and save them",
"from fs_preprocess.tdmsReader import tdmsReader class fileLoader(ABC): \"\"\"fileLoader meta class\"\"\" def __init__(self, multiple_files: bool",
"from pathlib import Path import logging import streamlit as st import librosa import",
"logging.info(\"Refreshing uploaded files...\") self.wav_file = st.file_uploader( \"Choose a wav file\", type=[\"wav\"], accept_multiple_files=self.multiple_files )",
"and save them into object related property during the load, sr are set",
"super().__init__() self.suffix = \".wav\" def get_uploaded(self): logging.info(\"Refreshing uploaded files...\") self.wav_file = st.file_uploader( \"Choose",
"= None self.get_uploaded() @abstractmethod def get_uploaded(self): pass class wavFileLoader(fileLoader): def __init__(self): super().__init__() self.suffix",
"optional \"\"\" self.y, self.sr = librosa.load( self.wav_file, sr=self.sr, offset=offset, mono=True ) def _show_audio(self,"
] |
[
"of a number by taking the last digit and continually dividing by 10.'''",
"<NAME> ''' def sum_of_digits(number): '''Sum the digits of a number by taking the",
"digit_sum += number % 10 number //= 10 return digit_sum def factorial(number): factorial",
"return digit_sum def factorial(number): factorial = 1 cur_num = 2 while cur_num <=",
"the digits of a number by taking the last digit and continually dividing",
"number //= 10 return digit_sum def factorial(number): factorial = 1 cur_num = 2",
"10 return digit_sum def factorial(number): factorial = 1 cur_num = 2 while cur_num",
"digit and continually dividing by 10.''' digit_sum = 0 while number: digit_sum +=",
"digit_sum def factorial(number): factorial = 1 cur_num = 2 while cur_num <= number:",
"digit_sum = 0 while number: digit_sum += number % 10 number //= 10",
"def factorial(number): factorial = 1 cur_num = 2 while cur_num <= number: factorial",
"factorial = 1 cur_num = 2 while cur_num <= number: factorial *= cur_num",
"number by taking the last digit and continually dividing by 10.''' digit_sum =",
"the last digit and continually dividing by 10.''' digit_sum = 0 while number:",
"by 10.''' digit_sum = 0 while number: digit_sum += number % 10 number",
"number: digit_sum += number % 10 number //= 10 return digit_sum def factorial(number):",
"by taking the last digit and continually dividing by 10.''' digit_sum = 0",
"1 cur_num = 2 while cur_num <= number: factorial *= cur_num cur_num +=",
"20 @author: <NAME> ''' def sum_of_digits(number): '''Sum the digits of a number by",
"continually dividing by 10.''' digit_sum = 0 while number: digit_sum += number %",
"def sum_of_digits(number): '''Sum the digits of a number by taking the last digit",
"'''Sum the digits of a number by taking the last digit and continually",
"a number by taking the last digit and continually dividing by 10.''' digit_sum",
"2 while cur_num <= number: factorial *= cur_num cur_num += 1 return factorial",
"taking the last digit and continually dividing by 10.''' digit_sum = 0 while",
"+= number % 10 number //= 10 return digit_sum def factorial(number): factorial =",
"0 while number: digit_sum += number % 10 number //= 10 return digit_sum",
"% 10 number //= 10 return digit_sum def factorial(number): factorial = 1 cur_num",
"Problem 20 @author: <NAME> ''' def sum_of_digits(number): '''Sum the digits of a number",
"last digit and continually dividing by 10.''' digit_sum = 0 while number: digit_sum",
"and continually dividing by 10.''' digit_sum = 0 while number: digit_sum += number",
"10.''' digit_sum = 0 while number: digit_sum += number % 10 number //=",
"//= 10 return digit_sum def factorial(number): factorial = 1 cur_num = 2 while",
"= 2 while cur_num <= number: factorial *= cur_num cur_num += 1 return",
"while cur_num <= number: factorial *= cur_num cur_num += 1 return factorial print(sum_of_digits(factorial(100)))",
"''' Problem 20 @author: <NAME> ''' def sum_of_digits(number): '''Sum the digits of a",
"10 number //= 10 return digit_sum def factorial(number): factorial = 1 cur_num =",
"sum_of_digits(number): '''Sum the digits of a number by taking the last digit and",
"cur_num = 2 while cur_num <= number: factorial *= cur_num cur_num += 1",
"factorial(number): factorial = 1 cur_num = 2 while cur_num <= number: factorial *=",
"@author: <NAME> ''' def sum_of_digits(number): '''Sum the digits of a number by taking",
"''' def sum_of_digits(number): '''Sum the digits of a number by taking the last",
"= 1 cur_num = 2 while cur_num <= number: factorial *= cur_num cur_num",
"digits of a number by taking the last digit and continually dividing by",
"dividing by 10.''' digit_sum = 0 while number: digit_sum += number % 10",
"number % 10 number //= 10 return digit_sum def factorial(number): factorial = 1",
"while number: digit_sum += number % 10 number //= 10 return digit_sum def",
"= 0 while number: digit_sum += number % 10 number //= 10 return"
] |
[
"NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE",
"publish, distribute, sublicense, and/or sell # copies of the Software, and to permit",
"software and associated documentation files (the \"Software\"), to deal # in the Software",
"copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED",
"SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. from oauth2client.client",
"\"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT",
"return flow.step1_get_authorize_url() def save(usr, code): try: credentials = flow.step2_exchange(code) except FlowExchangeError: return False",
"TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.",
"WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT",
"OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN",
"Authors (see AUTHORS) # # Permission is hereby granted, free of charge, to",
"CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE #",
"portions of the Software. # # THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT",
"do so, subject to the following conditions: # # The above copyright notice",
"EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,",
"and to permit persons to whom the Software is # furnished to do",
"OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION",
"use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the",
"the Software without restriction, including without limitation the rights # to use, copy,",
"os from config import * SCOPES = ['https://www.googleapis.com/auth/calendar', 'https://www.googleapis.com/auth/drive', 'profile'] flow = OAuth2WebServerFlow(client_id=GOOGLE_OAUTH_CLIENT_ID,",
"ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN",
"without restriction, including without limitation the rights # to use, copy, modify, merge,",
"the following conditions: # # The above copyright notice and this permission notice",
"THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR",
"scope=SCOPES, redirect_uri=GOOGLE_OAUTH_REDIRECT_URI, access_type='offline', prompt='consent' ) def get_url(): return flow.step1_get_authorize_url() def save(usr, code): try:",
"credentials = flow.step2_exchange(code) except FlowExchangeError: return False os.chdir(os.path.dirname(os.path.realpath(__file__)).replace('/oauth', '') + '/oauth/credentials') file_name =",
"+ '/oauth/credentials') file_name = '{id}.json'.format(id=usr.id) open(file_name, 'a').close() storage = Storage(file_name) storage.put(credentials) return True",
"person obtaining a copy # of this software and associated documentation files (the",
"LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND",
"except FlowExchangeError: return False os.chdir(os.path.dirname(os.path.realpath(__file__)).replace('/oauth', '') + '/oauth/credentials') file_name = '{id}.json'.format(id=usr.id) open(file_name, 'a').close()",
"DEALINGS IN THE # SOFTWARE. from oauth2client.client import OAuth2WebServerFlow, FlowExchangeError from oauth2client.file import",
"# furnished to do so, subject to the following conditions: # # The",
"the Software, and to permit persons to whom the Software is # furnished",
"permit persons to whom the Software is # furnished to do so, subject",
"rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell #",
"oauth2client.client import OAuth2WebServerFlow, FlowExchangeError from oauth2client.file import Storage import os from config import",
"Permission is hereby granted, free of charge, to any person obtaining a copy",
"redirect_uri=GOOGLE_OAUTH_REDIRECT_URI, access_type='offline', prompt='consent' ) def get_url(): return flow.step1_get_authorize_url() def save(usr, code): try: credentials",
"THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR",
"A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR",
"SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR #",
"FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF",
"'https://www.googleapis.com/auth/drive', 'profile'] flow = OAuth2WebServerFlow(client_id=GOOGLE_OAUTH_CLIENT_ID, client_secret=GOOGLE_OAUTH_CLIENT_SECRET, scope=SCOPES, redirect_uri=GOOGLE_OAUTH_REDIRECT_URI, access_type='offline', prompt='consent' ) def get_url():",
"in the Software without restriction, including without limitation the rights # to use,",
"IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT",
"EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,",
"Software without restriction, including without limitation the rights # to use, copy, modify,",
"# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies",
"merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to",
"save(usr, code): try: credentials = flow.step2_exchange(code) except FlowExchangeError: return False os.chdir(os.path.dirname(os.path.realpath(__file__)).replace('/oauth', '') +",
"= OAuth2WebServerFlow(client_id=GOOGLE_OAUTH_CLIENT_ID, client_secret=GOOGLE_OAUTH_CLIENT_SECRET, scope=SCOPES, redirect_uri=GOOGLE_OAUTH_REDIRECT_URI, access_type='offline', prompt='consent' ) def get_url(): return flow.step1_get_authorize_url() def",
"PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS",
"OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING",
"import OAuth2WebServerFlow, FlowExchangeError from oauth2client.file import Storage import os from config import *",
"ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE",
"os.chdir(os.path.dirname(os.path.realpath(__file__)).replace('/oauth', '') + '/oauth/credentials') file_name = '{id}.json'.format(id=usr.id) open(file_name, 'a').close() storage = Storage(file_name) storage.put(credentials)",
"copies of the Software, and to permit persons to whom the Software is",
"# The above copyright notice and this permission notice shall be included in",
"included in all # copies or substantial portions of the Software. # #",
"# of this software and associated documentation files (the \"Software\"), to deal #",
"OTHER DEALINGS IN THE # SOFTWARE. from oauth2client.client import OAuth2WebServerFlow, FlowExchangeError from oauth2client.file",
"to do so, subject to the following conditions: # # The above copyright",
"# Copyright (c) 2017 The TelegramGoogleBot Authors (see AUTHORS) # # Permission is",
"OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR",
"is hereby granted, free of charge, to any person obtaining a copy #",
"above copyright notice and this permission notice shall be included in all #",
"2017 The TelegramGoogleBot Authors (see AUTHORS) # # Permission is hereby granted, free",
"persons to whom the Software is # furnished to do so, subject to",
"sell # copies of the Software, and to permit persons to whom the",
"WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE.",
"conditions: # # The above copyright notice and this permission notice shall be",
"substantial portions of the Software. # # THE SOFTWARE IS PROVIDED \"AS IS\",",
"INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A",
"# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE",
"AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR",
"OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,",
"documentation files (the \"Software\"), to deal # in the Software without restriction, including",
"flow.step1_get_authorize_url() def save(usr, code): try: credentials = flow.step2_exchange(code) except FlowExchangeError: return False os.chdir(os.path.dirname(os.path.realpath(__file__)).replace('/oauth',",
"to permit persons to whom the Software is # furnished to do so,",
"'') + '/oauth/credentials') file_name = '{id}.json'.format(id=usr.id) open(file_name, 'a').close() storage = Storage(file_name) storage.put(credentials) return",
"ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT,",
"or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED \"AS",
"SCOPES = ['https://www.googleapis.com/auth/calendar', 'https://www.googleapis.com/auth/drive', 'profile'] flow = OAuth2WebServerFlow(client_id=GOOGLE_OAUTH_CLIENT_ID, client_secret=GOOGLE_OAUTH_CLIENT_SECRET, scope=SCOPES, redirect_uri=GOOGLE_OAUTH_REDIRECT_URI, access_type='offline', prompt='consent'",
"prompt='consent' ) def get_url(): return flow.step1_get_authorize_url() def save(usr, code): try: credentials = flow.step2_exchange(code)",
"(see AUTHORS) # # Permission is hereby granted, free of charge, to any",
"notice shall be included in all # copies or substantial portions of the",
"restriction, including without limitation the rights # to use, copy, modify, merge, publish,",
"obtaining a copy # of this software and associated documentation files (the \"Software\"),",
"of charge, to any person obtaining a copy # of this software and",
"whom the Software is # furnished to do so, subject to the following",
"CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH",
"NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE",
"OAuth2WebServerFlow(client_id=GOOGLE_OAUTH_CLIENT_ID, client_secret=GOOGLE_OAUTH_CLIENT_SECRET, scope=SCOPES, redirect_uri=GOOGLE_OAUTH_REDIRECT_URI, access_type='offline', prompt='consent' ) def get_url(): return flow.step1_get_authorize_url() def save(usr,",
"FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS",
"# # Permission is hereby granted, free of charge, to any person obtaining",
"MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL",
"get_url(): return flow.step1_get_authorize_url() def save(usr, code): try: credentials = flow.step2_exchange(code) except FlowExchangeError: return",
"free of charge, to any person obtaining a copy # of this software",
"import os from config import * SCOPES = ['https://www.googleapis.com/auth/calendar', 'https://www.googleapis.com/auth/drive', 'profile'] flow =",
"shall be included in all # copies or substantial portions of the Software.",
"PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT",
"copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software,",
"The above copyright notice and this permission notice shall be included in all",
"BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR",
"and/or sell # copies of the Software, and to permit persons to whom",
"so, subject to the following conditions: # # The above copyright notice and",
"this permission notice shall be included in all # copies or substantial portions",
"LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION",
"FlowExchangeError from oauth2client.file import Storage import os from config import * SCOPES =",
"TelegramGoogleBot Authors (see AUTHORS) # # Permission is hereby granted, free of charge,",
"THE # SOFTWARE. from oauth2client.client import OAuth2WebServerFlow, FlowExchangeError from oauth2client.file import Storage import",
"FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE",
"OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT",
"without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense,",
"# copies or substantial portions of the Software. # # THE SOFTWARE IS",
"PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING",
"access_type='offline', prompt='consent' ) def get_url(): return flow.step1_get_authorize_url() def save(usr, code): try: credentials =",
") def get_url(): return flow.step1_get_authorize_url() def save(usr, code): try: credentials = flow.step2_exchange(code) except",
"# in the Software without restriction, including without limitation the rights # to",
"is # furnished to do so, subject to the following conditions: # #",
"files (the \"Software\"), to deal # in the Software without restriction, including without",
"Software. # # THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY",
"# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS",
"def get_url(): return flow.step1_get_authorize_url() def save(usr, code): try: credentials = flow.step2_exchange(code) except FlowExchangeError:",
"copy # of this software and associated documentation files (the \"Software\"), to deal",
"# SOFTWARE. from oauth2client.client import OAuth2WebServerFlow, FlowExchangeError from oauth2client.file import Storage import os",
"IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE",
"to the following conditions: # # The above copyright notice and this permission",
"TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE",
"<reponame>hasibulkabir/Google # Copyright (c) 2017 The TelegramGoogleBot Authors (see AUTHORS) # # Permission",
"to deal # in the Software without restriction, including without limitation the rights",
"the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell",
"to any person obtaining a copy # of this software and associated documentation",
"* SCOPES = ['https://www.googleapis.com/auth/calendar', 'https://www.googleapis.com/auth/drive', 'profile'] flow = OAuth2WebServerFlow(client_id=GOOGLE_OAUTH_CLIENT_ID, client_secret=GOOGLE_OAUTH_CLIENT_SECRET, scope=SCOPES, redirect_uri=GOOGLE_OAUTH_REDIRECT_URI, access_type='offline',",
"# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS",
"following conditions: # # The above copyright notice and this permission notice shall",
"of the Software, and to permit persons to whom the Software is #",
"in all # copies or substantial portions of the Software. # # THE",
"the Software. # # THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF",
"flow.step2_exchange(code) except FlowExchangeError: return False os.chdir(os.path.dirname(os.path.realpath(__file__)).replace('/oauth', '') + '/oauth/credentials') file_name = '{id}.json'.format(id=usr.id) open(file_name,",
"flow = OAuth2WebServerFlow(client_id=GOOGLE_OAUTH_CLIENT_ID, client_secret=GOOGLE_OAUTH_CLIENT_SECRET, scope=SCOPES, redirect_uri=GOOGLE_OAUTH_REDIRECT_URI, access_type='offline', prompt='consent' ) def get_url(): return flow.step1_get_authorize_url()",
"False os.chdir(os.path.dirname(os.path.realpath(__file__)).replace('/oauth', '') + '/oauth/credentials') file_name = '{id}.json'.format(id=usr.id) open(file_name, 'a').close() storage = Storage(file_name)",
"from oauth2client.client import OAuth2WebServerFlow, FlowExchangeError from oauth2client.file import Storage import os from config",
"and associated documentation files (the \"Software\"), to deal # in the Software without",
"OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, #",
"config import * SCOPES = ['https://www.googleapis.com/auth/calendar', 'https://www.googleapis.com/auth/drive', 'profile'] flow = OAuth2WebServerFlow(client_id=GOOGLE_OAUTH_CLIENT_ID, client_secret=GOOGLE_OAUTH_CLIENT_SECRET, scope=SCOPES,",
"any person obtaining a copy # of this software and associated documentation files",
"THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN",
"# # The above copyright notice and this permission notice shall be included",
"IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR",
"\"Software\"), to deal # in the Software without restriction, including without limitation the",
"client_secret=GOOGLE_OAUTH_CLIENT_SECRET, scope=SCOPES, redirect_uri=GOOGLE_OAUTH_REDIRECT_URI, access_type='offline', prompt='consent' ) def get_url(): return flow.step1_get_authorize_url() def save(usr, code):",
"OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE",
"OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. from oauth2client.client import",
"LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, #",
"FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE #",
"SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES",
"BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN",
"Storage import os from config import * SCOPES = ['https://www.googleapis.com/auth/calendar', 'https://www.googleapis.com/auth/drive', 'profile'] flow",
"AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE",
"IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED,",
"try: credentials = flow.step2_exchange(code) except FlowExchangeError: return False os.chdir(os.path.dirname(os.path.realpath(__file__)).replace('/oauth', '') + '/oauth/credentials') file_name",
"sublicense, and/or sell # copies of the Software, and to permit persons to",
"a copy # of this software and associated documentation files (the \"Software\"), to",
"deal # in the Software without restriction, including without limitation the rights #",
"Software is # furnished to do so, subject to the following conditions: #",
"FlowExchangeError: return False os.chdir(os.path.dirname(os.path.realpath(__file__)).replace('/oauth', '') + '/oauth/credentials') file_name = '{id}.json'.format(id=usr.id) open(file_name, 'a').close() storage",
"# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR",
"Software, and to permit persons to whom the Software is # furnished to",
"OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER",
"HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN",
"CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT",
"including without limitation the rights # to use, copy, modify, merge, publish, distribute,",
"OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE",
"import Storage import os from config import * SCOPES = ['https://www.googleapis.com/auth/calendar', 'https://www.googleapis.com/auth/drive', 'profile']",
"(c) 2017 The TelegramGoogleBot Authors (see AUTHORS) # # Permission is hereby granted,",
"all # copies or substantial portions of the Software. # # THE SOFTWARE",
"AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER #",
"(the \"Software\"), to deal # in the Software without restriction, including without limitation",
"this software and associated documentation files (the \"Software\"), to deal # in the",
"IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR",
"= flow.step2_exchange(code) except FlowExchangeError: return False os.chdir(os.path.dirname(os.path.realpath(__file__)).replace('/oauth', '') + '/oauth/credentials') file_name = '{id}.json'.format(id=usr.id)",
"copyright notice and this permission notice shall be included in all # copies",
"distribute, sublicense, and/or sell # copies of the Software, and to permit persons",
"return False os.chdir(os.path.dirname(os.path.realpath(__file__)).replace('/oauth', '') + '/oauth/credentials') file_name = '{id}.json'.format(id=usr.id) open(file_name, 'a').close() storage =",
"# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER",
"= ['https://www.googleapis.com/auth/calendar', 'https://www.googleapis.com/auth/drive', 'profile'] flow = OAuth2WebServerFlow(client_id=GOOGLE_OAUTH_CLIENT_ID, client_secret=GOOGLE_OAUTH_CLIENT_SECRET, scope=SCOPES, redirect_uri=GOOGLE_OAUTH_REDIRECT_URI, access_type='offline', prompt='consent' )",
"AUTHORS) # # Permission is hereby granted, free of charge, to any person",
"charge, to any person obtaining a copy # of this software and associated",
"associated documentation files (the \"Software\"), to deal # in the Software without restriction,",
"USE OR OTHER DEALINGS IN THE # SOFTWARE. from oauth2client.client import OAuth2WebServerFlow, FlowExchangeError",
"SOFTWARE. from oauth2client.client import OAuth2WebServerFlow, FlowExchangeError from oauth2client.file import Storage import os from",
"WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO",
"THE USE OR OTHER DEALINGS IN THE # SOFTWARE. from oauth2client.client import OAuth2WebServerFlow,",
"OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY,",
"OR OTHER DEALINGS IN THE # SOFTWARE. from oauth2client.client import OAuth2WebServerFlow, FlowExchangeError from",
"hereby granted, free of charge, to any person obtaining a copy # of",
"of this software and associated documentation files (the \"Software\"), to deal # in",
"of the Software. # # THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY",
"OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS",
"import * SCOPES = ['https://www.googleapis.com/auth/calendar', 'https://www.googleapis.com/auth/drive', 'profile'] flow = OAuth2WebServerFlow(client_id=GOOGLE_OAUTH_CLIENT_ID, client_secret=GOOGLE_OAUTH_CLIENT_SECRET, scope=SCOPES, redirect_uri=GOOGLE_OAUTH_REDIRECT_URI,",
"granted, free of charge, to any person obtaining a copy # of this",
"# copies of the Software, and to permit persons to whom the Software",
"'profile'] flow = OAuth2WebServerFlow(client_id=GOOGLE_OAUTH_CLIENT_ID, client_secret=GOOGLE_OAUTH_CLIENT_SECRET, scope=SCOPES, redirect_uri=GOOGLE_OAUTH_REDIRECT_URI, access_type='offline', prompt='consent' ) def get_url(): return",
"# # THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,",
"WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO",
"THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. from",
"DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR",
"OAuth2WebServerFlow, FlowExchangeError from oauth2client.file import Storage import os from config import * SCOPES",
"def save(usr, code): try: credentials = flow.step2_exchange(code) except FlowExchangeError: return False os.chdir(os.path.dirname(os.path.realpath(__file__)).replace('/oauth', '')",
"WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED",
"KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF",
"to whom the Software is # furnished to do so, subject to the",
"limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or",
"from config import * SCOPES = ['https://www.googleapis.com/auth/calendar', 'https://www.googleapis.com/auth/drive', 'profile'] flow = OAuth2WebServerFlow(client_id=GOOGLE_OAUTH_CLIENT_ID, client_secret=GOOGLE_OAUTH_CLIENT_SECRET,",
"permission notice shall be included in all # copies or substantial portions of",
"oauth2client.file import Storage import os from config import * SCOPES = ['https://www.googleapis.com/auth/calendar', 'https://www.googleapis.com/auth/drive',",
"furnished to do so, subject to the following conditions: # # The above",
"and this permission notice shall be included in all # copies or substantial",
"modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and",
"ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES",
"be included in all # copies or substantial portions of the Software. #",
"NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY",
"COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER",
"# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,",
"code): try: credentials = flow.step2_exchange(code) except FlowExchangeError: return False os.chdir(os.path.dirname(os.path.realpath(__file__)).replace('/oauth', '') + '/oauth/credentials')",
"# Permission is hereby granted, free of charge, to any person obtaining a",
"The TelegramGoogleBot Authors (see AUTHORS) # # Permission is hereby granted, free of",
"IN THE # SOFTWARE. from oauth2client.client import OAuth2WebServerFlow, FlowExchangeError from oauth2client.file import Storage",
"Copyright (c) 2017 The TelegramGoogleBot Authors (see AUTHORS) # # Permission is hereby",
"to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of",
"from oauth2client.file import Storage import os from config import * SCOPES = ['https://www.googleapis.com/auth/calendar',",
"IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF",
"the Software is # furnished to do so, subject to the following conditions:",
"subject to the following conditions: # # The above copyright notice and this",
"notice and this permission notice shall be included in all # copies or",
"['https://www.googleapis.com/auth/calendar', 'https://www.googleapis.com/auth/drive', 'profile'] flow = OAuth2WebServerFlow(client_id=GOOGLE_OAUTH_CLIENT_ID, client_secret=GOOGLE_OAUTH_CLIENT_SECRET, scope=SCOPES, redirect_uri=GOOGLE_OAUTH_REDIRECT_URI, access_type='offline', prompt='consent' ) def"
] |
[
"def __init__(self): \"Create P2P topology.\" # Initialize topology Topo.__init__(self) # Add hosts and",
"<gh_stars>1-10 from mininet.topo import Topo class My_Topo(Topo): def __init__(self): \"Create P2P topology.\" #",
"self.addHost('h4',ip='10.0.0.4') S1 = self.addSwitch('s1') S2 = self.addSwitch('s2') # S3 = self.addSwitch('s3') # S4",
"S1) self.addLink(S1, S2) self.addLink(S2, H3) self.addLink(S2, H4) topos = { 'myTopo': (lambda: My_Topo())",
"self.addHost('h3',ip='10.0.0.3') H4 = self.addHost('h4',ip='10.0.0.4') S1 = self.addSwitch('s1') S2 = self.addSwitch('s2') # S3 =",
"self.addSwitch('s4') # c0 = self.addController('c0') # Add links self.addLink(H1, S1) self.addLink(H2, S1) self.addLink(S1,",
"\"Create P2P topology.\" # Initialize topology Topo.__init__(self) # Add hosts and switches H1",
"My_Topo(Topo): def __init__(self): \"Create P2P topology.\" # Initialize topology Topo.__init__(self) # Add hosts",
"H1 = self.addHost('h1',ip='10.0.0.1') H2 = self.addHost('h2',ip='10.0.0.2') H3 = self.addHost('h3',ip='10.0.0.3') H4 = self.addHost('h4',ip='10.0.0.4') S1",
"P2P topology.\" # Initialize topology Topo.__init__(self) # Add hosts and switches H1 =",
"topology.\" # Initialize topology Topo.__init__(self) # Add hosts and switches H1 = self.addHost('h1',ip='10.0.0.1')",
"H2 = self.addHost('h2',ip='10.0.0.2') H3 = self.addHost('h3',ip='10.0.0.3') H4 = self.addHost('h4',ip='10.0.0.4') S1 = self.addSwitch('s1') S2",
"Topo.__init__(self) # Add hosts and switches H1 = self.addHost('h1',ip='10.0.0.1') H2 = self.addHost('h2',ip='10.0.0.2') H3",
"H4 = self.addHost('h4',ip='10.0.0.4') S1 = self.addSwitch('s1') S2 = self.addSwitch('s2') # S3 = self.addSwitch('s3')",
"S1) self.addLink(H2, S1) self.addLink(S1, S2) self.addLink(S2, H3) self.addLink(S2, H4) topos = { 'myTopo':",
"self.addSwitch('s3') # S4 = self.addSwitch('s4') # c0 = self.addController('c0') # Add links self.addLink(H1,",
"Add hosts and switches H1 = self.addHost('h1',ip='10.0.0.1') H2 = self.addHost('h2',ip='10.0.0.2') H3 = self.addHost('h3',ip='10.0.0.3')",
"= self.addHost('h2',ip='10.0.0.2') H3 = self.addHost('h3',ip='10.0.0.3') H4 = self.addHost('h4',ip='10.0.0.4') S1 = self.addSwitch('s1') S2 =",
"# Initialize topology Topo.__init__(self) # Add hosts and switches H1 = self.addHost('h1',ip='10.0.0.1') H2",
"Topo class My_Topo(Topo): def __init__(self): \"Create P2P topology.\" # Initialize topology Topo.__init__(self) #",
"self.addHost('h1',ip='10.0.0.1') H2 = self.addHost('h2',ip='10.0.0.2') H3 = self.addHost('h3',ip='10.0.0.3') H4 = self.addHost('h4',ip='10.0.0.4') S1 = self.addSwitch('s1')",
"# S4 = self.addSwitch('s4') # c0 = self.addController('c0') # Add links self.addLink(H1, S1)",
"links self.addLink(H1, S1) self.addLink(H2, S1) self.addLink(S1, S2) self.addLink(S2, H3) self.addLink(S2, H4) topos =",
"self.addController('c0') # Add links self.addLink(H1, S1) self.addLink(H2, S1) self.addLink(S1, S2) self.addLink(S2, H3) self.addLink(S2,",
"topology Topo.__init__(self) # Add hosts and switches H1 = self.addHost('h1',ip='10.0.0.1') H2 = self.addHost('h2',ip='10.0.0.2')",
"# Add hosts and switches H1 = self.addHost('h1',ip='10.0.0.1') H2 = self.addHost('h2',ip='10.0.0.2') H3 =",
"mininet.topo import Topo class My_Topo(Topo): def __init__(self): \"Create P2P topology.\" # Initialize topology",
"hosts and switches H1 = self.addHost('h1',ip='10.0.0.1') H2 = self.addHost('h2',ip='10.0.0.2') H3 = self.addHost('h3',ip='10.0.0.3') H4",
"__init__(self): \"Create P2P topology.\" # Initialize topology Topo.__init__(self) # Add hosts and switches",
"= self.addHost('h3',ip='10.0.0.3') H4 = self.addHost('h4',ip='10.0.0.4') S1 = self.addSwitch('s1') S2 = self.addSwitch('s2') # S3",
"= self.addSwitch('s1') S2 = self.addSwitch('s2') # S3 = self.addSwitch('s3') # S4 = self.addSwitch('s4')",
"self.addSwitch('s2') # S3 = self.addSwitch('s3') # S4 = self.addSwitch('s4') # c0 = self.addController('c0')",
"c0 = self.addController('c0') # Add links self.addLink(H1, S1) self.addLink(H2, S1) self.addLink(S1, S2) self.addLink(S2,",
"= self.addSwitch('s2') # S3 = self.addSwitch('s3') # S4 = self.addSwitch('s4') # c0 =",
"Initialize topology Topo.__init__(self) # Add hosts and switches H1 = self.addHost('h1',ip='10.0.0.1') H2 =",
"= self.addController('c0') # Add links self.addLink(H1, S1) self.addLink(H2, S1) self.addLink(S1, S2) self.addLink(S2, H3)",
"= self.addSwitch('s3') # S4 = self.addSwitch('s4') # c0 = self.addController('c0') # Add links",
"= self.addHost('h1',ip='10.0.0.1') H2 = self.addHost('h2',ip='10.0.0.2') H3 = self.addHost('h3',ip='10.0.0.3') H4 = self.addHost('h4',ip='10.0.0.4') S1 =",
"S1 = self.addSwitch('s1') S2 = self.addSwitch('s2') # S3 = self.addSwitch('s3') # S4 =",
"self.addSwitch('s1') S2 = self.addSwitch('s2') # S3 = self.addSwitch('s3') # S4 = self.addSwitch('s4') #",
"# Add links self.addLink(H1, S1) self.addLink(H2, S1) self.addLink(S1, S2) self.addLink(S2, H3) self.addLink(S2, H4)",
"= self.addHost('h4',ip='10.0.0.4') S1 = self.addSwitch('s1') S2 = self.addSwitch('s2') # S3 = self.addSwitch('s3') #",
"import Topo class My_Topo(Topo): def __init__(self): \"Create P2P topology.\" # Initialize topology Topo.__init__(self)",
"and switches H1 = self.addHost('h1',ip='10.0.0.1') H2 = self.addHost('h2',ip='10.0.0.2') H3 = self.addHost('h3',ip='10.0.0.3') H4 =",
"S3 = self.addSwitch('s3') # S4 = self.addSwitch('s4') # c0 = self.addController('c0') # Add",
"Add links self.addLink(H1, S1) self.addLink(H2, S1) self.addLink(S1, S2) self.addLink(S2, H3) self.addLink(S2, H4) topos",
"self.addHost('h2',ip='10.0.0.2') H3 = self.addHost('h3',ip='10.0.0.3') H4 = self.addHost('h4',ip='10.0.0.4') S1 = self.addSwitch('s1') S2 = self.addSwitch('s2')",
"# c0 = self.addController('c0') # Add links self.addLink(H1, S1) self.addLink(H2, S1) self.addLink(S1, S2)",
"switches H1 = self.addHost('h1',ip='10.0.0.1') H2 = self.addHost('h2',ip='10.0.0.2') H3 = self.addHost('h3',ip='10.0.0.3') H4 = self.addHost('h4',ip='10.0.0.4')",
"class My_Topo(Topo): def __init__(self): \"Create P2P topology.\" # Initialize topology Topo.__init__(self) # Add",
"from mininet.topo import Topo class My_Topo(Topo): def __init__(self): \"Create P2P topology.\" # Initialize",
"# S3 = self.addSwitch('s3') # S4 = self.addSwitch('s4') # c0 = self.addController('c0') #",
"= self.addSwitch('s4') # c0 = self.addController('c0') # Add links self.addLink(H1, S1) self.addLink(H2, S1)",
"self.addLink(H2, S1) self.addLink(S1, S2) self.addLink(S2, H3) self.addLink(S2, H4) topos = { 'myTopo': (lambda:",
"self.addLink(S1, S2) self.addLink(S2, H3) self.addLink(S2, H4) topos = { 'myTopo': (lambda: My_Topo()) }",
"S2 = self.addSwitch('s2') # S3 = self.addSwitch('s3') # S4 = self.addSwitch('s4') # c0",
"S4 = self.addSwitch('s4') # c0 = self.addController('c0') # Add links self.addLink(H1, S1) self.addLink(H2,",
"H3 = self.addHost('h3',ip='10.0.0.3') H4 = self.addHost('h4',ip='10.0.0.4') S1 = self.addSwitch('s1') S2 = self.addSwitch('s2') #",
"self.addLink(H1, S1) self.addLink(H2, S1) self.addLink(S1, S2) self.addLink(S2, H3) self.addLink(S2, H4) topos = {"
] |
[
"null too thus why negated check exc_c = Country.objects.filter(~Q(independent=True) | Q(is_deprecated=True) | ~Q(record_type=1)).update(in_search=False)",
"= Country.objects.filter(independent=True, is_deprecated=False, record_type=1).update(in_search=True) # Update countries which should NOT appear in search",
"should appear in search inc_c = Country.objects.filter(independent=True, is_deprecated=False, record_type=1).update(in_search=True) # Update countries which",
"| Q(is_deprecated=True) | ~Q(record_type=1)).update(in_search=False) logger.info('Successfully set in_search for Countries') except Exception as ex:",
"import Country from django.db import transaction from django.db.models import Q from api.logger import",
"Q from api.logger import logger class Command(BaseCommand): help = 'Update Countries initially to",
"from django.db.models import Q from api.logger import logger class Command(BaseCommand): help = 'Update",
"inc_c = Country.objects.filter(independent=True, is_deprecated=False, record_type=1).update(in_search=True) # Update countries which should NOT appear in",
"import Q from api.logger import logger class Command(BaseCommand): help = 'Update Countries initially",
"from api.models import Country from django.db import transaction from django.db.models import Q from",
"can be null too thus why negated check exc_c = Country.objects.filter(~Q(independent=True) | Q(is_deprecated=True)",
"# Update countries which should NOT appear in search # independent can be",
"search inc_c = Country.objects.filter(independent=True, is_deprecated=False, record_type=1).update(in_search=True) # Update countries which should NOT appear",
"in search inc_c = Country.objects.filter(independent=True, is_deprecated=False, record_type=1).update(in_search=True) # Update countries which should NOT",
"| ~Q(record_type=1)).update(in_search=False) logger.info('Successfully set in_search for Countries') except Exception as ex: logger.error(f'Failed to",
"~Q(record_type=1)).update(in_search=False) logger.info('Successfully set in_search for Countries') except Exception as ex: logger.error(f'Failed to set",
"Update countries which should NOT appear in search # independent can be null",
"logger.info('Successfully set in_search for Countries') except Exception as ex: logger.error(f'Failed to set in_search",
"search # independent can be null too thus why negated check exc_c =",
"initially to set/revoke their in_search field (probably one-time run only)' @transaction.atomic def handle(self,",
"**options): try: # Update countries which should appear in search inc_c = Country.objects.filter(independent=True,",
"run only)' @transaction.atomic def handle(self, *args, **options): try: # Update countries which should",
"Countries') except Exception as ex: logger.error(f'Failed to set in_search for Countries. Error: {str(ex)}')",
"which should appear in search inc_c = Country.objects.filter(independent=True, is_deprecated=False, record_type=1).update(in_search=True) # Update countries",
"Country.objects.filter(~Q(independent=True) | Q(is_deprecated=True) | ~Q(record_type=1)).update(in_search=False) logger.info('Successfully set in_search for Countries') except Exception as",
"import transaction from django.db.models import Q from api.logger import logger class Command(BaseCommand): help",
"field (probably one-time run only)' @transaction.atomic def handle(self, *args, **options): try: # Update",
"transaction from django.db.models import Q from api.logger import logger class Command(BaseCommand): help =",
"django.db import transaction from django.db.models import Q from api.logger import logger class Command(BaseCommand):",
"only)' @transaction.atomic def handle(self, *args, **options): try: # Update countries which should appear",
"should NOT appear in search # independent can be null too thus why",
"django.core.management.base import BaseCommand from api.models import Country from django.db import transaction from django.db.models",
"from api.logger import logger class Command(BaseCommand): help = 'Update Countries initially to set/revoke",
"one-time run only)' @transaction.atomic def handle(self, *args, **options): try: # Update countries which",
"appear in search # independent can be null too thus why negated check",
"check exc_c = Country.objects.filter(~Q(independent=True) | Q(is_deprecated=True) | ~Q(record_type=1)).update(in_search=False) logger.info('Successfully set in_search for Countries')",
"Country.objects.filter(independent=True, is_deprecated=False, record_type=1).update(in_search=True) # Update countries which should NOT appear in search #",
"*args, **options): try: # Update countries which should appear in search inc_c =",
"thus why negated check exc_c = Country.objects.filter(~Q(independent=True) | Q(is_deprecated=True) | ~Q(record_type=1)).update(in_search=False) logger.info('Successfully set",
"be null too thus why negated check exc_c = Country.objects.filter(~Q(independent=True) | Q(is_deprecated=True) |",
"handle(self, *args, **options): try: # Update countries which should appear in search inc_c",
"countries which should NOT appear in search # independent can be null too",
"from django.core.management.base import BaseCommand from api.models import Country from django.db import transaction from",
"from django.db import transaction from django.db.models import Q from api.logger import logger class",
"class Command(BaseCommand): help = 'Update Countries initially to set/revoke their in_search field (probably",
"why negated check exc_c = Country.objects.filter(~Q(independent=True) | Q(is_deprecated=True) | ~Q(record_type=1)).update(in_search=False) logger.info('Successfully set in_search",
"Q(is_deprecated=True) | ~Q(record_type=1)).update(in_search=False) logger.info('Successfully set in_search for Countries') except Exception as ex: logger.error(f'Failed",
"exc_c = Country.objects.filter(~Q(independent=True) | Q(is_deprecated=True) | ~Q(record_type=1)).update(in_search=False) logger.info('Successfully set in_search for Countries') except",
"Countries initially to set/revoke their in_search field (probably one-time run only)' @transaction.atomic def",
"= 'Update Countries initially to set/revoke their in_search field (probably one-time run only)'",
"logger class Command(BaseCommand): help = 'Update Countries initially to set/revoke their in_search field",
"negated check exc_c = Country.objects.filter(~Q(independent=True) | Q(is_deprecated=True) | ~Q(record_type=1)).update(in_search=False) logger.info('Successfully set in_search for",
"BaseCommand from api.models import Country from django.db import transaction from django.db.models import Q",
"too thus why negated check exc_c = Country.objects.filter(~Q(independent=True) | Q(is_deprecated=True) | ~Q(record_type=1)).update(in_search=False) logger.info('Successfully",
"def handle(self, *args, **options): try: # Update countries which should appear in search",
"@transaction.atomic def handle(self, *args, **options): try: # Update countries which should appear in",
"Command(BaseCommand): help = 'Update Countries initially to set/revoke their in_search field (probably one-time",
"api.models import Country from django.db import transaction from django.db.models import Q from api.logger",
"= Country.objects.filter(~Q(independent=True) | Q(is_deprecated=True) | ~Q(record_type=1)).update(in_search=False) logger.info('Successfully set in_search for Countries') except Exception",
"in_search for Countries') except Exception as ex: logger.error(f'Failed to set in_search for Countries.",
"in_search field (probably one-time run only)' @transaction.atomic def handle(self, *args, **options): try: #",
"# Update countries which should appear in search inc_c = Country.objects.filter(independent=True, is_deprecated=False, record_type=1).update(in_search=True)",
"independent can be null too thus why negated check exc_c = Country.objects.filter(~Q(independent=True) |",
"api.logger import logger class Command(BaseCommand): help = 'Update Countries initially to set/revoke their",
"their in_search field (probably one-time run only)' @transaction.atomic def handle(self, *args, **options): try:",
"to set/revoke their in_search field (probably one-time run only)' @transaction.atomic def handle(self, *args,",
"NOT appear in search # independent can be null too thus why negated",
"set in_search for Countries') except Exception as ex: logger.error(f'Failed to set in_search for",
"record_type=1).update(in_search=True) # Update countries which should NOT appear in search # independent can",
"'Update Countries initially to set/revoke their in_search field (probably one-time run only)' @transaction.atomic",
"is_deprecated=False, record_type=1).update(in_search=True) # Update countries which should NOT appear in search # independent",
"import logger class Command(BaseCommand): help = 'Update Countries initially to set/revoke their in_search",
"# independent can be null too thus why negated check exc_c = Country.objects.filter(~Q(independent=True)",
"Country from django.db import transaction from django.db.models import Q from api.logger import logger",
"django.db.models import Q from api.logger import logger class Command(BaseCommand): help = 'Update Countries",
"countries which should appear in search inc_c = Country.objects.filter(independent=True, is_deprecated=False, record_type=1).update(in_search=True) # Update",
"in search # independent can be null too thus why negated check exc_c",
"try: # Update countries which should appear in search inc_c = Country.objects.filter(independent=True, is_deprecated=False,",
"for Countries') except Exception as ex: logger.error(f'Failed to set in_search for Countries. Error:",
"help = 'Update Countries initially to set/revoke their in_search field (probably one-time run",
"import BaseCommand from api.models import Country from django.db import transaction from django.db.models import",
"set/revoke their in_search field (probably one-time run only)' @transaction.atomic def handle(self, *args, **options):",
"which should NOT appear in search # independent can be null too thus",
"(probably one-time run only)' @transaction.atomic def handle(self, *args, **options): try: # Update countries",
"Update countries which should appear in search inc_c = Country.objects.filter(independent=True, is_deprecated=False, record_type=1).update(in_search=True) #",
"appear in search inc_c = Country.objects.filter(independent=True, is_deprecated=False, record_type=1).update(in_search=True) # Update countries which should"
] |
[
"self.isMatch(s, p[2:]) elif s and p and (s[0] == p[0] or p[0] ==",
"and (s[0] == p[0] or p[0] == \".\"): return self.isMatch(s[1:], p[1:]) return False",
"s == p: return True if len(p) > 1 and p[1] == \"*\":",
"s if s == p: return True if len(p) > 1 and p[1]",
"len(p) > 1 and p[1] == \"*\": if s and (s[0] == p[0]",
"> 1 and p[1] == \"*\": if s and (s[0] == p[0] or",
"p: str) -> bool: if not p: return not s if s ==",
"s: str, p: str) -> bool: if not p: return not s if",
"bool: if not p: return not s if s == p: return True",
"or self.isMatch(s[1:], p) else: return self.isMatch(s, p[2:]) elif s and p and (s[0]",
"p[1] == \"*\": if s and (s[0] == p[0] or p[0] == \".\"):",
"else: return self.isMatch(s, p[2:]) elif s and p and (s[0] == p[0] or",
"if not p: return not s if s == p: return True if",
"and p and (s[0] == p[0] or p[0] == \".\"): return self.isMatch(s[1:], p[1:])",
"\"*\": if s and (s[0] == p[0] or p[0] == \".\"): return self.isMatch(s,",
"str) -> bool: if not p: return not s if s == p:",
"and (s[0] == p[0] or p[0] == \".\"): return self.isMatch(s, p[2:]) or self.isMatch(s[1:],",
"(s[0] == p[0] or p[0] == \".\"): return self.isMatch(s, p[2:]) or self.isMatch(s[1:], p)",
"p[2:]) or self.isMatch(s[1:], p) else: return self.isMatch(s, p[2:]) elif s and p and",
"True if len(p) > 1 and p[1] == \"*\": if s and (s[0]",
"str, p: str) -> bool: if not p: return not s if s",
"return not s if s == p: return True if len(p) > 1",
"-> bool: if not p: return not s if s == p: return",
"Solution: def isMatch(self, s: str, p: str) -> bool: if not p: return",
"or p[0] == \".\"): return self.isMatch(s, p[2:]) or self.isMatch(s[1:], p) else: return self.isMatch(s,",
"return self.isMatch(s, p[2:]) elif s and p and (s[0] == p[0] or p[0]",
"def isMatch(self, s: str, p: str) -> bool: if not p: return not",
"and p[1] == \"*\": if s and (s[0] == p[0] or p[0] ==",
"\".\"): return self.isMatch(s, p[2:]) or self.isMatch(s[1:], p) else: return self.isMatch(s, p[2:]) elif s",
"self.isMatch(s, p[2:]) or self.isMatch(s[1:], p) else: return self.isMatch(s, p[2:]) elif s and p",
"s and p and (s[0] == p[0] or p[0] == \".\"): return self.isMatch(s[1:],",
"p[2:]) elif s and p and (s[0] == p[0] or p[0] == \".\"):",
"== \"*\": if s and (s[0] == p[0] or p[0] == \".\"): return",
"class Solution: def isMatch(self, s: str, p: str) -> bool: if not p:",
"== \".\"): return self.isMatch(s, p[2:]) or self.isMatch(s[1:], p) else: return self.isMatch(s, p[2:]) elif",
"self.isMatch(s[1:], p) else: return self.isMatch(s, p[2:]) elif s and p and (s[0] ==",
"s and (s[0] == p[0] or p[0] == \".\"): return self.isMatch(s, p[2:]) or",
"== p: return True if len(p) > 1 and p[1] == \"*\": if",
"elif s and p and (s[0] == p[0] or p[0] == \".\"): return",
"p) else: return self.isMatch(s, p[2:]) elif s and p and (s[0] == p[0]",
"p: return True if len(p) > 1 and p[1] == \"*\": if s",
"return True if len(p) > 1 and p[1] == \"*\": if s and",
"p: return not s if s == p: return True if len(p) >",
"if s and (s[0] == p[0] or p[0] == \".\"): return self.isMatch(s, p[2:])",
"p and (s[0] == p[0] or p[0] == \".\"): return self.isMatch(s[1:], p[1:]) return",
"p[0] == \".\"): return self.isMatch(s, p[2:]) or self.isMatch(s[1:], p) else: return self.isMatch(s, p[2:])",
"isMatch(self, s: str, p: str) -> bool: if not p: return not s",
"if len(p) > 1 and p[1] == \"*\": if s and (s[0] ==",
"return self.isMatch(s, p[2:]) or self.isMatch(s[1:], p) else: return self.isMatch(s, p[2:]) elif s and",
"== p[0] or p[0] == \".\"): return self.isMatch(s, p[2:]) or self.isMatch(s[1:], p) else:",
"1 and p[1] == \"*\": if s and (s[0] == p[0] or p[0]",
"not s if s == p: return True if len(p) > 1 and",
"p[0] or p[0] == \".\"): return self.isMatch(s, p[2:]) or self.isMatch(s[1:], p) else: return",
"not p: return not s if s == p: return True if len(p)",
"if s == p: return True if len(p) > 1 and p[1] =="
] |
[
"f\" - {'Deafened' if lock_value else 'Undeafened'}\\n\" elif lock_type == \"channel\": channel =",
"), create_option( name=\"deafened\", description=\"Determines if the user should be locked as deafened or",
"command can only be run in servers.\", ) async def _list_locks(self, ctx): if",
"description=\"Determines if the user should be locked as muted or unmuted.\", option_type=SlashCommandOptionType.BOOLEAN, required=True,",
"name=\"lock_type\", description=\"The type of lock to remove from the user (defaults to All)\",",
"only be run in servers.\") return lock_manager.remove(ctx, user.id, lock_type) await ctx.send( f\"Removed {lock_type}",
"= \"all\"): if not ctx.guild: await ctx.send(\"This command can only be run in",
"lock_value else 'Undeafened'}\\n\" elif lock_type == \"channel\": channel = await self.bot.fetch_channel(lock_value) message +=",
"option_type=SlashCommandOptionType.BOOLEAN, required=True, ), ], ) async def _lock_mute(self, ctx, user: Member, muted: bool):",
"discord.errors import NotFound from discord.ext import commands from discord_slash import cog_ext from discord_slash.model",
"try: user = await self.bot.fetch_user(user_id) except NotFound as e: logger.info(f\"User {user_id} not found.\")",
"commands from discord_slash import cog_ext from discord_slash.model import SlashCommandOptionType from discord_slash.utils.manage_commands import create_choice,",
"lock_value in locks.items(): if lock_type == \"mute\": message += f\" - {'Muted' if",
"create_option( name=\"user\", description=\"The user to unlock.\", option_type=SlashCommandOptionType.USER, required=True, ), create_option( name=\"lock_type\", description=\"The type",
"name=\"mute\", description=\"Lock the specified user as muted or unmuted. This command can only",
"hidden=True, ) @cog_ext.cog_subcommand( name=\"deafen\", description=\"Lock the specified user as deafened or undeafened. This",
"ctx.send(\"This command can only be run in servers.\", hidden=True) return lock_manager.add(ctx, user.id, lock_type=\"mute\",",
"be run in servers.\", hidden=True) return if channel.type != ChannelType.voice: await ctx.send(\"The selected",
"name=\"list\", description=\"Lists all locked users. This command can only be run in servers.\",",
") async def _list_locks(self, ctx): if not ctx.guild: await ctx.send(\"This command can only",
"{channel} (ID: {channel.id})\\n\" message += \"```\" await ctx.send(message) @cog_ext.cog_subcommand( base=\"lock\", name=\"remove\", description=\"Unlock the",
"name=\"Mute\", value=\"mute\", ), create_choice( name=\"Deafen\", value=\"deafen\", ), create_choice( name=\"Channel\", value=\"channel\" ), create_choice( name=\"All\",",
"lock_type, lock_value in locks.items(): if lock_type == \"mute\": message += f\" - {'Muted'",
"'unmuted'}.\", ) elif update[0] == \"deafen\": await member.edit( deafen=update[1], reason=f\"Locked as {'deafened' if",
"after) for update in updates: if update[0] == \"mute\": await member.edit( mute=update[1], reason=f\"Locked",
"( f\"Listing {len(users)} locked user{'s' if len(users) > 1 else ''}:\\n```\" ) for",
"channel.\", hidden=True) return lock_manager.add(ctx, user.id, lock_type=\"channel\", lock_value=str(channel.id)) await ctx.send( f\"User `{user}` locked in",
"def _list_locks(self, ctx): if not ctx.guild: await ctx.send(\"This command can only be run",
"user in a specified voice channel. This command can only be run in",
"`{user}` locked as {'muted' if muted else 'unmuted'}.\", hidden=True, ) @cog_ext.cog_subcommand( name=\"deafen\", description=\"Lock",
"lock_type == \"channel\": channel = await self.bot.fetch_channel(lock_value) message += f\" - Channel: {channel}",
"bool): if not ctx.guild: await ctx.send(\"This command can only be run in servers.\",",
"await ctx.send(message) @cog_ext.cog_subcommand( base=\"lock\", name=\"remove\", description=\"Unlock the specified user. This command can only",
"ctx.send( f\"User `{user}` locked as {'muted' if muted else 'unmuted'}.\", hidden=True, ) @cog_ext.cog_subcommand(",
"description=\"Lock the specified user in a specified voice channel. This command can only",
"e: logger.info(f\"User {user_id} not found.\") message += f\"{user}\\n\" for lock_type, lock_value in locks.items():",
"await ctx.send( f\"User `{user}` locked as {'muted' if muted else 'unmuted'}.\", hidden=True, )",
"all locked users. This command can only be run in servers.\", ) async",
"user_id, locks in users.items(): try: user = await self.bot.fetch_user(user_id) except NotFound as e:",
"if channel.type != ChannelType.voice: await ctx.send(\"The selected channel must be a voice channel.\",",
"hidden=True, ) @cog_ext.cog_subcommand( base=\"lock\", name=\"list\", description=\"Lists all locked users. This command can only",
"run in servers.\", hidden=True) return lock_manager.add(ctx, user.id, lock_type=\"deafen\", lock_value=deafened) await ctx.send( f\"User `{user}`",
"f\"{user}\\n\" for lock_type, lock_value in locks.items(): if lock_type == \"mute\": message += f\"",
"voice channel. This command can only be run in servers.\", base=\"lock\", options=[ create_option(",
"else 'Unmuted'}\\n\" elif lock_type == \"deafen\": message += f\" - {'Deafened' if lock_value",
"create_option( name=\"user\", description=\"The user to lock.\", option_type=SlashCommandOptionType.USER, required=True, ), create_option( name=\"deafened\", description=\"Determines if",
"unmuted.\", option_type=SlashCommandOptionType.BOOLEAN, required=True, ), ], ) async def _lock_mute(self, ctx, user: Member, muted:",
"muted or unmuted.\", option_type=SlashCommandOptionType.BOOLEAN, required=True, ), ], ) async def _lock_mute(self, ctx, user:",
"no locked users in this server.\") return message = ( f\"Listing {len(users)} locked",
"description=\"The voice channel to lock the user in.\", option_type=SlashCommandOptionType.CHANNEL, required=True, ), ], )",
"specified user as deafened or undeafened. This command can only be run in",
"create_choice, create_option from discord import VoiceState, Member, VoiceChannel, ChannelType from data.lock_manager import lock_manager",
"or undeafened.\", option_type=SlashCommandOptionType.BOOLEAN, required=True, ), ], ) async def _lock_deafen(self, ctx, user: Member,",
") @cog_ext.cog_subcommand( name=\"mute\", description=\"Lock the specified user as muted or unmuted. This command",
"if lock_type == \"mute\": message += f\" - {'Muted' if lock_value else 'Unmuted'}\\n\"",
"f\"User `{user}` locked in `{channel}` (ID: {channel.id}).\", hidden=True, ) @cog_ext.cog_subcommand( base=\"lock\", name=\"list\", description=\"Lists",
"in servers.\", hidden=True) return users = lock_manager.list(str(ctx.guild.id)) if not users: await ctx.send(\"There are",
"can only be run in servers.\", ) async def _list_locks(self, ctx): if not",
"ChannelType from data.lock_manager import lock_manager logger = logging.getLogger(__name__) class LockCog(commands.Cog): def __init__(self, bot):",
"len(users) > 1 else ''}:\\n```\" ) for user_id, locks in users.items(): try: user",
"servers.\") return lock_manager.remove(ctx, user.id, lock_type) await ctx.send( f\"Removed {lock_type} lock{'s' if lock_type ==",
"`{channel}` (ID: {channel.id}).\", hidden=True, ) @cog_ext.cog_subcommand( base=\"lock\", name=\"list\", description=\"Lists all locked users. This",
"== \"mute\": message += f\" - {'Muted' if lock_value else 'Unmuted'}\\n\" elif lock_type",
"ctx.send(message) @cog_ext.cog_subcommand( base=\"lock\", name=\"remove\", description=\"Unlock the specified user. This command can only be",
"{channel.id})\\n\" message += \"```\" await ctx.send(message) @cog_ext.cog_subcommand( base=\"lock\", name=\"remove\", description=\"Unlock the specified user.",
"This command can only be run in servers.\", base=\"lock\", options=[ create_option( name=\"user\", description=\"The",
"Member, lock_type: str = \"all\"): if not ctx.guild: await ctx.send(\"This command can only",
"type of lock to remove from the user (defaults to All)\", option_type=SlashCommandOptionType.STRING, required=False,",
"option_type=SlashCommandOptionType.CHANNEL, required=True, ), ], ) async def _lock_channel(self, ctx, user: Member, channel: VoiceChannel):",
"user: Member, muted: bool): if not ctx.guild: await ctx.send(\"This command can only be",
"the specified user as muted or unmuted. This command can only be run",
"def _lock_deafen(self, ctx, user: Member, deafened: bool): if not ctx.guild: await ctx.send(\"This command",
"voice channel to lock the user in.\", option_type=SlashCommandOptionType.CHANNEL, required=True, ), ], ) async",
"user.id, lock_type=\"channel\", lock_value=str(channel.id)) await ctx.send( f\"User `{user}` locked in `{channel}` (ID: {channel.id}).\", hidden=True,",
"await self.bot.fetch_channel(update[1]) await member.edit( voice_channel=channel, reason=f\"Locked in channel {channel} (ID: {channel.id}).\", ) @cog_ext.cog_subcommand(",
"else 'undeafened'}.\", ) elif update[0] == \"channel\": channel = await self.bot.fetch_channel(update[1]) await member.edit(",
"ctx.send(\"This command can only be run in servers.\", hidden=True) return users = lock_manager.list(str(ctx.guild.id))",
"required=True, ), ], ) async def _lock_channel(self, ctx, user: Member, channel: VoiceChannel): if",
"specified user in a specified voice channel. This command can only be run",
"servers.\", hidden=True) return if channel.type != ChannelType.voice: await ctx.send(\"The selected channel must be",
"value=\"deafen\", ), create_choice( name=\"Channel\", value=\"channel\" ), create_choice( name=\"All\", value=\"all\" ) ] ) ],",
"command can only be run in servers.\", hidden=True) return if channel.type != ChannelType.voice:",
"value=\"all\" ) ] ) ], ) async def _unlock(self, ctx, user: Member, lock_type:",
"if the user should be locked as deafened or undeafened.\", option_type=SlashCommandOptionType.BOOLEAN, required=True, ),",
"servers.\", options=[ create_option( name=\"user\", description=\"The user to unlock.\", option_type=SlashCommandOptionType.USER, required=True, ), create_option( name=\"lock_type\",",
"await self.bot.fetch_user(user_id) except NotFound as e: logger.info(f\"User {user_id} not found.\") message += f\"{user}\\n\"",
"or unmuted. This command can only be run in servers.\", base=\"lock\", options=[ create_option(",
"ctx.send( f\"User `{user}` locked in `{channel}` (ID: {channel.id}).\", hidden=True, ) @cog_ext.cog_subcommand( base=\"lock\", name=\"list\",",
") elif update[0] == \"deafen\": await member.edit( deafen=update[1], reason=f\"Locked as {'deafened' if update[1]",
"user.id, lock_type=\"deafen\", lock_value=deafened) await ctx.send( f\"User `{user}` locked as {'deafened' if deafened else",
"locked in `{channel}` (ID: {channel.id}).\", hidden=True, ) @cog_ext.cog_subcommand( base=\"lock\", name=\"list\", description=\"Lists all locked",
"f\" - Channel: {channel} (ID: {channel.id})\\n\" message += \"```\" await ctx.send(message) @cog_ext.cog_subcommand( base=\"lock\",",
"lock_manager.check(member, after) for update in updates: if update[0] == \"mute\": await member.edit( mute=update[1],",
"required=False, choices=[ create_choice( name=\"Mute\", value=\"mute\", ), create_choice( name=\"Deafen\", value=\"deafen\", ), create_choice( name=\"Channel\", value=\"channel\"",
"as {'muted' if update[1] else 'unmuted'}.\", ) elif update[0] == \"deafen\": await member.edit(",
"name=\"All\", value=\"all\" ) ] ) ], ) async def _unlock(self, ctx, user: Member,",
"locked user{'s' if len(users) > 1 else ''}:\\n```\" ) for user_id, locks in",
"required=True, ), ], ) async def _lock_mute(self, ctx, user: Member, muted: bool): if",
"from discord import VoiceState, Member, VoiceChannel, ChannelType from data.lock_manager import lock_manager logger =",
"logging from discord.errors import NotFound from discord.ext import commands from discord_slash import cog_ext",
"Member, muted: bool): if not ctx.guild: await ctx.send(\"This command can only be run",
"ctx, user: Member, channel: VoiceChannel): if not ctx.guild: await ctx.send(\"This command can only",
"be run in servers.\") return lock_manager.remove(ctx, user.id, lock_type) await ctx.send( f\"Removed {lock_type} lock{'s'",
"create_choice( name=\"Mute\", value=\"mute\", ), create_choice( name=\"Deafen\", value=\"deafen\", ), create_choice( name=\"Channel\", value=\"channel\" ), create_choice(",
"reason=f\"Locked in channel {channel} (ID: {channel.id}).\", ) @cog_ext.cog_subcommand( name=\"mute\", description=\"Lock the specified user",
"not users: await ctx.send(\"There are no locked users in this server.\") return message",
"async def _lock_channel(self, ctx, user: Member, channel: VoiceChannel): if not ctx.guild: await ctx.send(\"This",
"discord import VoiceState, Member, VoiceChannel, ChannelType from data.lock_manager import lock_manager logger = logging.getLogger(__name__)",
"user to lock.\", option_type=SlashCommandOptionType.USER, required=True, ), create_option( name=\"muted\", description=\"Determines if the user should",
"member.edit( deafen=update[1], reason=f\"Locked as {'deafened' if update[1] else 'undeafened'}.\", ) elif update[0] ==",
"in channel {channel} (ID: {channel.id}).\", ) @cog_ext.cog_subcommand( name=\"mute\", description=\"Lock the specified user as",
") async def _lock_mute(self, ctx, user: Member, muted: bool): if not ctx.guild: await",
"selected channel must be a voice channel.\", hidden=True) return lock_manager.add(ctx, user.id, lock_type=\"channel\", lock_value=str(channel.id))",
"\"all\"): if not ctx.guild: await ctx.send(\"This command can only be run in servers.\")",
"hidden=True) return lock_manager.add(ctx, user.id, lock_type=\"channel\", lock_value=str(channel.id)) await ctx.send( f\"User `{user}` locked in `{channel}`",
"import lock_manager logger = logging.getLogger(__name__) class LockCog(commands.Cog): def __init__(self, bot): self.bot = bot",
"= lock_manager.list(str(ctx.guild.id)) if not users: await ctx.send(\"There are no locked users in this",
"{'Deafened' if lock_value else 'Undeafened'}\\n\" elif lock_type == \"channel\": channel = await self.bot.fetch_channel(lock_value)",
"): updates = lock_manager.check(member, after) for update in updates: if update[0] == \"mute\":",
"return message = ( f\"Listing {len(users)} locked user{'s' if len(users) > 1 else",
"options=[ create_option( name=\"user\", description=\"The user to lock.\", option_type=SlashCommandOptionType.USER, required=True, ), create_option( name=\"channel\", description=\"The",
"if lock_value else 'Unmuted'}\\n\" elif lock_type == \"deafen\": message += f\" - {'Deafened'",
"'unmuted'}.\", hidden=True, ) @cog_ext.cog_subcommand( name=\"deafen\", description=\"Lock the specified user as deafened or undeafened.",
"to lock.\", option_type=SlashCommandOptionType.USER, required=True, ), create_option( name=\"channel\", description=\"The voice channel to lock the",
"users: await ctx.send(\"There are no locked users in this server.\") return message =",
"lock_value=str(channel.id)) await ctx.send( f\"User `{user}` locked in `{channel}` (ID: {channel.id}).\", hidden=True, ) @cog_ext.cog_subcommand(",
"lock_value else 'Unmuted'}\\n\" elif lock_type == \"deafen\": message += f\" - {'Deafened' if",
"discord_slash import cog_ext from discord_slash.model import SlashCommandOptionType from discord_slash.utils.manage_commands import create_choice, create_option from",
"channel = await self.bot.fetch_channel(update[1]) await member.edit( voice_channel=channel, reason=f\"Locked in channel {channel} (ID: {channel.id}).\",",
"+= f\" - {'Deafened' if lock_value else 'Undeafened'}\\n\" elif lock_type == \"channel\": channel",
"a voice channel.\", hidden=True) return lock_manager.add(ctx, user.id, lock_type=\"channel\", lock_value=str(channel.id)) await ctx.send( f\"User `{user}`",
"servers.\", base=\"lock\", options=[ create_option( name=\"user\", description=\"The user to lock.\", option_type=SlashCommandOptionType.USER, required=True, ), create_option(",
"self.bot.fetch_channel(lock_value) message += f\" - Channel: {channel} (ID: {channel.id})\\n\" message += \"```\" await",
"can only be run in servers.\", options=[ create_option( name=\"user\", description=\"The user to unlock.\",",
"ctx.send(\"The selected channel must be a voice channel.\", hidden=True) return lock_manager.add(ctx, user.id, lock_type=\"channel\",",
"\"channel\": channel = await self.bot.fetch_channel(lock_value) message += f\" - Channel: {channel} (ID: {channel.id})\\n\"",
"command can only be run in servers.\", base=\"lock\", options=[ create_option( name=\"user\", description=\"The user",
"VoiceState ): updates = lock_manager.check(member, after) for update in updates: if update[0] ==",
"ctx.send(\"This command can only be run in servers.\") return lock_manager.remove(ctx, user.id, lock_type) await",
"create_option( name=\"lock_type\", description=\"The type of lock to remove from the user (defaults to",
"in servers.\", base=\"lock\", options=[ create_option( name=\"user\", description=\"The user to lock.\", option_type=SlashCommandOptionType.USER, required=True, ),",
"= bot @commands.Cog.listener() async def on_voice_state_update( self, member: Member, before: VoiceState, after: VoiceState",
"users = lock_manager.list(str(ctx.guild.id)) if not users: await ctx.send(\"There are no locked users in",
"Member, deafened: bool): if not ctx.guild: await ctx.send(\"This command can only be run",
"this server.\") return message = ( f\"Listing {len(users)} locked user{'s' if len(users) >",
"from discord_slash.model import SlashCommandOptionType from discord_slash.utils.manage_commands import create_choice, create_option from discord import VoiceState,",
"user in.\", option_type=SlashCommandOptionType.CHANNEL, required=True, ), ], ) async def _lock_channel(self, ctx, user: Member,",
"_lock_channel(self, ctx, user: Member, channel: VoiceChannel): if not ctx.guild: await ctx.send(\"This command can",
"= logging.getLogger(__name__) class LockCog(commands.Cog): def __init__(self, bot): self.bot = bot @commands.Cog.listener() async def",
"command can only be run in servers.\") return lock_manager.remove(ctx, user.id, lock_type) await ctx.send(",
"create_option( name=\"muted\", description=\"Determines if the user should be locked as muted or unmuted.\",",
"run in servers.\", base=\"lock\", options=[ create_option( name=\"user\", description=\"The user to lock.\", option_type=SlashCommandOptionType.USER, required=True,",
"ChannelType.voice: await ctx.send(\"The selected channel must be a voice channel.\", hidden=True) return lock_manager.add(ctx,",
"import create_choice, create_option from discord import VoiceState, Member, VoiceChannel, ChannelType from data.lock_manager import",
"{'Muted' if lock_value else 'Unmuted'}\\n\" elif lock_type == \"deafen\": message += f\" -",
"description=\"The user to lock.\", option_type=SlashCommandOptionType.USER, required=True, ), create_option( name=\"muted\", description=\"Determines if the user",
"required=True, ), create_option( name=\"muted\", description=\"Determines if the user should be locked as muted",
"(ID: {channel.id}).\", hidden=True, ) @cog_ext.cog_subcommand( base=\"lock\", name=\"list\", description=\"Lists all locked users. This command",
"in servers.\", hidden=True) return lock_manager.add(ctx, user.id, lock_type=\"deafen\", lock_value=deafened) await ctx.send( f\"User `{user}` locked",
"SlashCommandOptionType from discord_slash.utils.manage_commands import create_choice, create_option from discord import VoiceState, Member, VoiceChannel, ChannelType",
"remove from the user (defaults to All)\", option_type=SlashCommandOptionType.STRING, required=False, choices=[ create_choice( name=\"Mute\", value=\"mute\",",
"(defaults to All)\", option_type=SlashCommandOptionType.STRING, required=False, choices=[ create_choice( name=\"Mute\", value=\"mute\", ), create_choice( name=\"Deafen\", value=\"deafen\",",
"lock the user in.\", option_type=SlashCommandOptionType.CHANNEL, required=True, ), ], ) async def _lock_channel(self, ctx,",
"bot @commands.Cog.listener() async def on_voice_state_update( self, member: Member, before: VoiceState, after: VoiceState ):",
"f\"Listing {len(users)} locked user{'s' if len(users) > 1 else ''}:\\n```\" ) for user_id,",
"if len(users) > 1 else ''}:\\n```\" ) for user_id, locks in users.items(): try:",
"in servers.\", ) async def _list_locks(self, ctx): if not ctx.guild: await ctx.send(\"This command",
"in servers.\", hidden=True) return lock_manager.add(ctx, user.id, lock_type=\"mute\", lock_value=muted) await ctx.send( f\"User `{user}` locked",
"create_choice( name=\"Deafen\", value=\"deafen\", ), create_choice( name=\"Channel\", value=\"channel\" ), create_choice( name=\"All\", value=\"all\" ) ]",
"on_voice_state_update( self, member: Member, before: VoiceState, after: VoiceState ): updates = lock_manager.check(member, after)",
"required=True, ), create_option( name=\"deafened\", description=\"Determines if the user should be locked as deafened",
"f\" - {'Muted' if lock_value else 'Unmuted'}\\n\" elif lock_type == \"deafen\": message +=",
"user: Member, channel: VoiceChannel): if not ctx.guild: await ctx.send(\"This command can only be",
"be run in servers.\", ) async def _list_locks(self, ctx): if not ctx.guild: await",
"be run in servers.\", options=[ create_option( name=\"user\", description=\"The user to unlock.\", option_type=SlashCommandOptionType.USER, required=True,",
"run in servers.\", hidden=True) return lock_manager.add(ctx, user.id, lock_type=\"mute\", lock_value=muted) await ctx.send( f\"User `{user}`",
"create_option( name=\"user\", description=\"The user to lock.\", option_type=SlashCommandOptionType.USER, required=True, ), create_option( name=\"muted\", description=\"Determines if",
"discord_slash.model import SlashCommandOptionType from discord_slash.utils.manage_commands import create_choice, create_option from discord import VoiceState, Member,",
"== \"channel\": channel = await self.bot.fetch_channel(update[1]) await member.edit( voice_channel=channel, reason=f\"Locked in channel {channel}",
"import commands from discord_slash import cog_ext from discord_slash.model import SlashCommandOptionType from discord_slash.utils.manage_commands import",
"in users.items(): try: user = await self.bot.fetch_user(user_id) except NotFound as e: logger.info(f\"User {user_id}",
"name=\"deafen\", description=\"Lock the specified user as deafened or undeafened. This command can only",
"command can only be run in servers.\", hidden=True) return lock_manager.add(ctx, user.id, lock_type=\"deafen\", lock_value=deafened)",
"<gh_stars>0 import logging from discord.errors import NotFound from discord.ext import commands from discord_slash",
"deafen=update[1], reason=f\"Locked as {'deafened' if update[1] else 'undeafened'}.\", ) elif update[0] == \"channel\":",
"async def on_voice_state_update( self, member: Member, before: VoiceState, after: VoiceState ): updates =",
"deafened or undeafened. This command can only be run in servers.\", base=\"lock\", options=[",
"== \"channel\": channel = await self.bot.fetch_channel(lock_value) message += f\" - Channel: {channel} (ID:",
"deafened else 'undeafened'}.\", hidden=True, ) @cog_ext.cog_subcommand( name=\"channel\", description=\"Lock the specified user in a",
"create_choice( name=\"All\", value=\"all\" ) ] ) ], ) async def _unlock(self, ctx, user:",
"create_option from discord import VoiceState, Member, VoiceChannel, ChannelType from data.lock_manager import lock_manager logger",
"required=True, ), create_option( name=\"lock_type\", description=\"The type of lock to remove from the user",
"LockCog(commands.Cog): def __init__(self, bot): self.bot = bot @commands.Cog.listener() async def on_voice_state_update( self, member:",
"as deafened or undeafened.\", option_type=SlashCommandOptionType.BOOLEAN, required=True, ), ], ) async def _lock_deafen(self, ctx,",
"self, member: Member, before: VoiceState, after: VoiceState ): updates = lock_manager.check(member, after) for",
"muted: bool): if not ctx.guild: await ctx.send(\"This command can only be run in",
"+= \"```\" await ctx.send(message) @cog_ext.cog_subcommand( base=\"lock\", name=\"remove\", description=\"Unlock the specified user. This command",
"\"```\" await ctx.send(message) @cog_ext.cog_subcommand( base=\"lock\", name=\"remove\", description=\"Unlock the specified user. This command can",
"if update[0] == \"mute\": await member.edit( mute=update[1], reason=f\"Locked as {'muted' if update[1] else",
"Member, channel: VoiceChannel): if not ctx.guild: await ctx.send(\"This command can only be run",
"], ) async def _lock_channel(self, ctx, user: Member, channel: VoiceChannel): if not ctx.guild:",
"in locks.items(): if lock_type == \"mute\": message += f\" - {'Muted' if lock_value",
"def __init__(self, bot): self.bot = bot @commands.Cog.listener() async def on_voice_state_update( self, member: Member,",
"return lock_manager.add(ctx, user.id, lock_type=\"deafen\", lock_value=deafened) await ctx.send( f\"User `{user}` locked as {'deafened' if",
"lock.\", option_type=SlashCommandOptionType.USER, required=True, ), create_option( name=\"deafened\", description=\"Determines if the user should be locked",
"], ) async def _lock_deafen(self, ctx, user: Member, deafened: bool): if not ctx.guild:",
"server.\") return message = ( f\"Listing {len(users)} locked user{'s' if len(users) > 1",
"only be run in servers.\", hidden=True) return lock_manager.add(ctx, user.id, lock_type=\"deafen\", lock_value=deafened) await ctx.send(",
"if update[1] else 'undeafened'}.\", ) elif update[0] == \"channel\": channel = await self.bot.fetch_channel(update[1])",
"description=\"Lock the specified user as deafened or undeafened. This command can only be",
"return lock_manager.add(ctx, user.id, lock_type=\"mute\", lock_value=muted) await ctx.send( f\"User `{user}` locked as {'muted' if",
"description=\"The user to lock.\", option_type=SlashCommandOptionType.USER, required=True, ), create_option( name=\"deafened\", description=\"Determines if the user",
"as {'deafened' if deafened else 'undeafened'}.\", hidden=True, ) @cog_ext.cog_subcommand( name=\"channel\", description=\"Lock the specified",
"], ) async def _unlock(self, ctx, user: Member, lock_type: str = \"all\"): if",
"NotFound from discord.ext import commands from discord_slash import cog_ext from discord_slash.model import SlashCommandOptionType",
"message = ( f\"Listing {len(users)} locked user{'s' if len(users) > 1 else ''}:\\n```\"",
"\"deafen\": await member.edit( deafen=update[1], reason=f\"Locked as {'deafened' if update[1] else 'undeafened'}.\", ) elif",
"can only be run in servers.\", hidden=True) return if channel.type != ChannelType.voice: await",
"= ( f\"Listing {len(users)} locked user{'s' if len(users) > 1 else ''}:\\n```\" )",
"user: Member, lock_type: str = \"all\"): if not ctx.guild: await ctx.send(\"This command can",
"users. This command can only be run in servers.\", ) async def _list_locks(self,",
"create_option( name=\"user\", description=\"The user to lock.\", option_type=SlashCommandOptionType.USER, required=True, ), create_option( name=\"channel\", description=\"The voice",
"ctx.guild: await ctx.send(\"This command can only be run in servers.\", hidden=True) return users",
"servers.\", hidden=True) return users = lock_manager.list(str(ctx.guild.id)) if not users: await ctx.send(\"There are no",
"VoiceChannel): if not ctx.guild: await ctx.send(\"This command can only be run in servers.\",",
"lock_type == \"mute\": message += f\" - {'Muted' if lock_value else 'Unmuted'}\\n\" elif",
"options=[ create_option( name=\"user\", description=\"The user to lock.\", option_type=SlashCommandOptionType.USER, required=True, ), create_option( name=\"muted\", description=\"Determines",
"option_type=SlashCommandOptionType.USER, required=True, ), create_option( name=\"deafened\", description=\"Determines if the user should be locked as",
"hidden=True, ) @cog_ext.cog_subcommand( name=\"channel\", description=\"Lock the specified user in a specified voice channel.",
"name=\"user\", description=\"The user to lock.\", option_type=SlashCommandOptionType.USER, required=True, ), create_option( name=\"deafened\", description=\"Determines if the",
"{channel.id}).\", ) @cog_ext.cog_subcommand( name=\"mute\", description=\"Lock the specified user as muted or unmuted. This",
"user to unlock.\", option_type=SlashCommandOptionType.USER, required=True, ), create_option( name=\"lock_type\", description=\"The type of lock to",
"name=\"user\", description=\"The user to lock.\", option_type=SlashCommandOptionType.USER, required=True, ), create_option( name=\"channel\", description=\"The voice channel",
"a specified voice channel. This command can only be run in servers.\", base=\"lock\",",
"elif update[0] == \"channel\": channel = await self.bot.fetch_channel(update[1]) await member.edit( voice_channel=channel, reason=f\"Locked in",
"message += f\" - {'Muted' if lock_value else 'Unmuted'}\\n\" elif lock_type == \"deafen\":",
"_lock_mute(self, ctx, user: Member, muted: bool): if not ctx.guild: await ctx.send(\"This command can",
"option_type=SlashCommandOptionType.USER, required=True, ), create_option( name=\"channel\", description=\"The voice channel to lock the user in.\",",
"if not users: await ctx.send(\"There are no locked users in this server.\") return",
"name=\"muted\", description=\"Determines if the user should be locked as muted or unmuted.\", option_type=SlashCommandOptionType.BOOLEAN,",
"update[0] == \"deafen\": await member.edit( deafen=update[1], reason=f\"Locked as {'deafened' if update[1] else 'undeafened'}.\",",
"f\"User `{user}` locked as {'muted' if muted else 'unmuted'}.\", hidden=True, ) @cog_ext.cog_subcommand( name=\"deafen\",",
"name=\"channel\", description=\"Lock the specified user in a specified voice channel. This command can",
"lock_type == \"deafen\": message += f\" - {'Deafened' if lock_value else 'Undeafened'}\\n\" elif",
"else ''}:\\n```\" ) for user_id, locks in users.items(): try: user = await self.bot.fetch_user(user_id)",
"lock_manager.add(ctx, user.id, lock_type=\"deafen\", lock_value=deafened) await ctx.send( f\"User `{user}` locked as {'deafened' if deafened",
"if not ctx.guild: await ctx.send(\"This command can only be run in servers.\", hidden=True)",
"== \"deafen\": await member.edit( deafen=update[1], reason=f\"Locked as {'deafened' if update[1] else 'undeafened'}.\", )",
"else 'undeafened'}.\", hidden=True, ) @cog_ext.cog_subcommand( name=\"channel\", description=\"Lock the specified user in a specified",
"servers.\", hidden=True) return lock_manager.add(ctx, user.id, lock_type=\"deafen\", lock_value=deafened) await ctx.send( f\"User `{user}` locked as",
"users in this server.\") return message = ( f\"Listing {len(users)} locked user{'s' if",
"update[0] == \"mute\": await member.edit( mute=update[1], reason=f\"Locked as {'muted' if update[1] else 'unmuted'}.\",",
"'Unmuted'}\\n\" elif lock_type == \"deafen\": message += f\" - {'Deafened' if lock_value else",
"= lock_manager.check(member, after) for update in updates: if update[0] == \"mute\": await member.edit(",
"), ], ) async def _lock_channel(self, ctx, user: Member, channel: VoiceChannel): if not",
"), create_option( name=\"lock_type\", description=\"The type of lock to remove from the user (defaults",
"return users = lock_manager.list(str(ctx.guild.id)) if not users: await ctx.send(\"There are no locked users",
"def _unlock(self, ctx, user: Member, lock_type: str = \"all\"): if not ctx.guild: await",
"ctx.guild: await ctx.send(\"This command can only be run in servers.\", hidden=True) return if",
"self.bot.fetch_user(user_id) except NotFound as e: logger.info(f\"User {user_id} not found.\") message += f\"{user}\\n\" for",
"await member.edit( mute=update[1], reason=f\"Locked as {'muted' if update[1] else 'unmuted'}.\", ) elif update[0]",
"f\"Removed {lock_type} lock{'s' if lock_type == 'all' else ''} from {user}.\", hidden=True, )",
"+= f\"{user}\\n\" for lock_type, lock_value in locks.items(): if lock_type == \"mute\": message +=",
"to unlock.\", option_type=SlashCommandOptionType.USER, required=True, ), create_option( name=\"lock_type\", description=\"The type of lock to remove",
"'undeafened'}.\", hidden=True, ) @cog_ext.cog_subcommand( name=\"channel\", description=\"Lock the specified user in a specified voice",
"reason=f\"Locked as {'muted' if update[1] else 'unmuted'}.\", ) elif update[0] == \"deafen\": await",
"lock{'s' if lock_type == 'all' else ''} from {user}.\", hidden=True, ) def setup(bot):",
"def _lock_mute(self, ctx, user: Member, muted: bool): if not ctx.guild: await ctx.send(\"This command",
"await ctx.send(\"The selected channel must be a voice channel.\", hidden=True) return lock_manager.add(ctx, user.id,",
"not ctx.guild: await ctx.send(\"This command can only be run in servers.\", hidden=True) return",
"must be a voice channel.\", hidden=True) return lock_manager.add(ctx, user.id, lock_type=\"channel\", lock_value=str(channel.id)) await ctx.send(",
"ctx.send( f\"Removed {lock_type} lock{'s' if lock_type == 'all' else ''} from {user}.\", hidden=True,",
"can only be run in servers.\", hidden=True) return lock_manager.add(ctx, user.id, lock_type=\"mute\", lock_value=muted) await",
"lock_manager logger = logging.getLogger(__name__) class LockCog(commands.Cog): def __init__(self, bot): self.bot = bot @commands.Cog.listener()",
"option_type=SlashCommandOptionType.USER, required=True, ), create_option( name=\"muted\", description=\"Determines if the user should be locked as",
"deafened or undeafened.\", option_type=SlashCommandOptionType.BOOLEAN, required=True, ), ], ) async def _lock_deafen(self, ctx, user:",
"discord_slash.utils.manage_commands import create_choice, create_option from discord import VoiceState, Member, VoiceChannel, ChannelType from data.lock_manager",
"if not ctx.guild: await ctx.send(\"This command can only be run in servers.\") return",
"member.edit( voice_channel=channel, reason=f\"Locked in channel {channel} (ID: {channel.id}).\", ) @cog_ext.cog_subcommand( name=\"mute\", description=\"Lock the",
"name=\"Channel\", value=\"channel\" ), create_choice( name=\"All\", value=\"all\" ) ] ) ], ) async def",
"the specified user in a specified voice channel. This command can only be",
") ], ) async def _unlock(self, ctx, user: Member, lock_type: str = \"all\"):",
"muted or unmuted. This command can only be run in servers.\", base=\"lock\", options=[",
"unmuted. This command can only be run in servers.\", base=\"lock\", options=[ create_option( name=\"user\",",
"the specified user as deafened or undeafened. This command can only be run",
"await ctx.send(\"This command can only be run in servers.\", hidden=True) return if channel.type",
"locks in users.items(): try: user = await self.bot.fetch_user(user_id) except NotFound as e: logger.info(f\"User",
"await ctx.send( f\"User `{user}` locked as {'deafened' if deafened else 'undeafened'}.\", hidden=True, )",
"lock_type=\"channel\", lock_value=str(channel.id)) await ctx.send( f\"User `{user}` locked in `{channel}` (ID: {channel.id}).\", hidden=True, )",
"await ctx.send(\"This command can only be run in servers.\", hidden=True) return lock_manager.add(ctx, user.id,",
"member.edit( mute=update[1], reason=f\"Locked as {'muted' if update[1] else 'unmuted'}.\", ) elif update[0] ==",
"for update in updates: if update[0] == \"mute\": await member.edit( mute=update[1], reason=f\"Locked as",
"Member, before: VoiceState, after: VoiceState ): updates = lock_manager.check(member, after) for update in",
"@cog_ext.cog_subcommand( name=\"deafen\", description=\"Lock the specified user as deafened or undeafened. This command can",
"in `{channel}` (ID: {channel.id}).\", hidden=True, ) @cog_ext.cog_subcommand( base=\"lock\", name=\"list\", description=\"Lists all locked users.",
"lock_manager.remove(ctx, user.id, lock_type) await ctx.send( f\"Removed {lock_type} lock{'s' if lock_type == 'all' else",
"value=\"channel\" ), create_choice( name=\"All\", value=\"all\" ) ] ) ], ) async def _unlock(self,",
"bot): self.bot = bot @commands.Cog.listener() async def on_voice_state_update( self, member: Member, before: VoiceState,",
"servers.\", hidden=True) return lock_manager.add(ctx, user.id, lock_type=\"mute\", lock_value=muted) await ctx.send( f\"User `{user}` locked as",
"users.items(): try: user = await self.bot.fetch_user(user_id) except NotFound as e: logger.info(f\"User {user_id} not",
"logger.info(f\"User {user_id} not found.\") message += f\"{user}\\n\" for lock_type, lock_value in locks.items(): if",
"await member.edit( deafen=update[1], reason=f\"Locked as {'deafened' if update[1] else 'undeafened'}.\", ) elif update[0]",
"VoiceState, Member, VoiceChannel, ChannelType from data.lock_manager import lock_manager logger = logging.getLogger(__name__) class LockCog(commands.Cog):",
"Channel: {channel} (ID: {channel.id})\\n\" message += \"```\" await ctx.send(message) @cog_ext.cog_subcommand( base=\"lock\", name=\"remove\", description=\"Unlock",
"else 'Undeafened'}\\n\" elif lock_type == \"channel\": channel = await self.bot.fetch_channel(lock_value) message += f\"",
"lock_manager.list(str(ctx.guild.id)) if not users: await ctx.send(\"There are no locked users in this server.\")",
"for user_id, locks in users.items(): try: user = await self.bot.fetch_user(user_id) except NotFound as",
"name=\"deafened\", description=\"Determines if the user should be locked as deafened or undeafened.\", option_type=SlashCommandOptionType.BOOLEAN,",
"user to lock.\", option_type=SlashCommandOptionType.USER, required=True, ), create_option( name=\"channel\", description=\"The voice channel to lock",
"name=\"user\", description=\"The user to lock.\", option_type=SlashCommandOptionType.USER, required=True, ), create_option( name=\"muted\", description=\"Determines if the",
"found.\") message += f\"{user}\\n\" for lock_type, lock_value in locks.items(): if lock_type == \"mute\":",
") ] ) ], ) async def _unlock(self, ctx, user: Member, lock_type: str",
"{channel} (ID: {channel.id}).\", ) @cog_ext.cog_subcommand( name=\"mute\", description=\"Lock the specified user as muted or",
"hidden=True) return lock_manager.add(ctx, user.id, lock_type=\"deafen\", lock_value=deafened) await ctx.send( f\"User `{user}` locked as {'deafened'",
"lock_type=\"mute\", lock_value=muted) await ctx.send( f\"User `{user}` locked as {'muted' if muted else 'unmuted'}.\",",
"from discord_slash.utils.manage_commands import create_choice, create_option from discord import VoiceState, Member, VoiceChannel, ChannelType from",
"updates = lock_manager.check(member, after) for update in updates: if update[0] == \"mute\": await",
"if the user should be locked as muted or unmuted.\", option_type=SlashCommandOptionType.BOOLEAN, required=True, ),",
"lock_manager.add(ctx, user.id, lock_type=\"mute\", lock_value=muted) await ctx.send( f\"User `{user}` locked as {'muted' if muted",
"can only be run in servers.\") return lock_manager.remove(ctx, user.id, lock_type) await ctx.send( f\"Removed",
"lock_type) await ctx.send( f\"Removed {lock_type} lock{'s' if lock_type == 'all' else ''} from",
"in updates: if update[0] == \"mute\": await member.edit( mute=update[1], reason=f\"Locked as {'muted' if",
"specified user. This command can only be run in servers.\", options=[ create_option( name=\"user\",",
"options=[ create_option( name=\"user\", description=\"The user to unlock.\", option_type=SlashCommandOptionType.USER, required=True, ), create_option( name=\"lock_type\", description=\"The",
"name=\"user\", description=\"The user to unlock.\", option_type=SlashCommandOptionType.USER, required=True, ), create_option( name=\"lock_type\", description=\"The type of",
"elif lock_type == \"channel\": channel = await self.bot.fetch_channel(lock_value) message += f\" - Channel:",
"in a specified voice channel. This command can only be run in servers.\",",
"import VoiceState, Member, VoiceChannel, ChannelType from data.lock_manager import lock_manager logger = logging.getLogger(__name__) class",
"__init__(self, bot): self.bot = bot @commands.Cog.listener() async def on_voice_state_update( self, member: Member, before:",
"servers.\", ) async def _list_locks(self, ctx): if not ctx.guild: await ctx.send(\"This command can",
"user: Member, deafened: bool): if not ctx.guild: await ctx.send(\"This command can only be",
"logger = logging.getLogger(__name__) class LockCog(commands.Cog): def __init__(self, bot): self.bot = bot @commands.Cog.listener() async",
"(ID: {channel.id}).\", ) @cog_ext.cog_subcommand( name=\"mute\", description=\"Lock the specified user as muted or unmuted.",
"''}:\\n```\" ) for user_id, locks in users.items(): try: user = await self.bot.fetch_user(user_id) except",
"ctx, user: Member, muted: bool): if not ctx.guild: await ctx.send(\"This command can only",
"message += f\"{user}\\n\" for lock_type, lock_value in locks.items(): if lock_type == \"mute\": message",
"cog_ext from discord_slash.model import SlashCommandOptionType from discord_slash.utils.manage_commands import create_choice, create_option from discord import",
"lock to remove from the user (defaults to All)\", option_type=SlashCommandOptionType.STRING, required=False, choices=[ create_choice(",
"the user should be locked as deafened or undeafened.\", option_type=SlashCommandOptionType.BOOLEAN, required=True, ), ],",
"elif update[0] == \"deafen\": await member.edit( deafen=update[1], reason=f\"Locked as {'deafened' if update[1] else",
"name=\"channel\", description=\"The voice channel to lock the user in.\", option_type=SlashCommandOptionType.CHANNEL, required=True, ), ],",
"should be locked as muted or unmuted.\", option_type=SlashCommandOptionType.BOOLEAN, required=True, ), ], ) async",
"the specified user. This command can only be run in servers.\", options=[ create_option(",
"'undeafened'}.\", ) elif update[0] == \"channel\": channel = await self.bot.fetch_channel(update[1]) await member.edit( voice_channel=channel,",
"(ID: {channel.id})\\n\" message += \"```\" await ctx.send(message) @cog_ext.cog_subcommand( base=\"lock\", name=\"remove\", description=\"Unlock the specified",
"channel: VoiceChannel): if not ctx.guild: await ctx.send(\"This command can only be run in",
"'Undeafened'}\\n\" elif lock_type == \"channel\": channel = await self.bot.fetch_channel(lock_value) message += f\" -",
"be locked as muted or unmuted.\", option_type=SlashCommandOptionType.BOOLEAN, required=True, ), ], ) async def",
"as muted or unmuted.\", option_type=SlashCommandOptionType.BOOLEAN, required=True, ), ], ) async def _lock_mute(self, ctx,",
"be a voice channel.\", hidden=True) return lock_manager.add(ctx, user.id, lock_type=\"channel\", lock_value=str(channel.id)) await ctx.send( f\"User",
"discord.ext import commands from discord_slash import cog_ext from discord_slash.model import SlashCommandOptionType from discord_slash.utils.manage_commands",
"in servers.\") return lock_manager.remove(ctx, user.id, lock_type) await ctx.send( f\"Removed {lock_type} lock{'s' if lock_type",
"to lock the user in.\", option_type=SlashCommandOptionType.CHANNEL, required=True, ), ], ) async def _lock_channel(self,",
"] ) ], ) async def _unlock(self, ctx, user: Member, lock_type: str =",
"+= f\" - Channel: {channel} (ID: {channel.id})\\n\" message += \"```\" await ctx.send(message) @cog_ext.cog_subcommand(",
"{lock_type} lock{'s' if lock_type == 'all' else ''} from {user}.\", hidden=True, ) def",
"or undeafened. This command can only be run in servers.\", base=\"lock\", options=[ create_option(",
"= await self.bot.fetch_user(user_id) except NotFound as e: logger.info(f\"User {user_id} not found.\") message +=",
"def _lock_channel(self, ctx, user: Member, channel: VoiceChannel): if not ctx.guild: await ctx.send(\"This command",
"ctx.send(\"There are no locked users in this server.\") return message = ( f\"Listing",
"elif lock_type == \"deafen\": message += f\" - {'Deafened' if lock_value else 'Undeafened'}\\n\"",
"async def _list_locks(self, ctx): if not ctx.guild: await ctx.send(\"This command can only be",
"description=\"Lock the specified user as muted or unmuted. This command can only be",
"return lock_manager.remove(ctx, user.id, lock_type) await ctx.send( f\"Removed {lock_type} lock{'s' if lock_type == 'all'",
") for user_id, locks in users.items(): try: user = await self.bot.fetch_user(user_id) except NotFound",
"update[0] == \"channel\": channel = await self.bot.fetch_channel(update[1]) await member.edit( voice_channel=channel, reason=f\"Locked in channel",
"user.id, lock_type) await ctx.send( f\"Removed {lock_type} lock{'s' if lock_type == 'all' else ''}",
"message += \"```\" await ctx.send(message) @cog_ext.cog_subcommand( base=\"lock\", name=\"remove\", description=\"Unlock the specified user. This",
"undeafened.\", option_type=SlashCommandOptionType.BOOLEAN, required=True, ), ], ) async def _lock_deafen(self, ctx, user: Member, deafened:",
"{len(users)} locked user{'s' if len(users) > 1 else ''}:\\n```\" ) for user_id, locks",
"not ctx.guild: await ctx.send(\"This command can only be run in servers.\") return lock_manager.remove(ctx,",
"user as muted or unmuted. This command can only be run in servers.\",",
"NotFound as e: logger.info(f\"User {user_id} not found.\") message += f\"{user}\\n\" for lock_type, lock_value",
"{'deafened' if deafened else 'undeafened'}.\", hidden=True, ) @cog_ext.cog_subcommand( name=\"channel\", description=\"Lock the specified user",
"async def _lock_deafen(self, ctx, user: Member, deafened: bool): if not ctx.guild: await ctx.send(\"This",
"== \"deafen\": message += f\" - {'Deafened' if lock_value else 'Undeafened'}\\n\" elif lock_type",
"await ctx.send( f\"User `{user}` locked in `{channel}` (ID: {channel.id}).\", hidden=True, ) @cog_ext.cog_subcommand( base=\"lock\",",
"@cog_ext.cog_subcommand( name=\"channel\", description=\"Lock the specified user in a specified voice channel. This command",
"muted else 'unmuted'}.\", hidden=True, ) @cog_ext.cog_subcommand( name=\"deafen\", description=\"Lock the specified user as deafened",
"message += f\" - {'Deafened' if lock_value else 'Undeafened'}\\n\" elif lock_type == \"channel\":",
"locks.items(): if lock_type == \"mute\": message += f\" - {'Muted' if lock_value else",
"only be run in servers.\", hidden=True) return lock_manager.add(ctx, user.id, lock_type=\"mute\", lock_value=muted) await ctx.send(",
"update[1] else 'undeafened'}.\", ) elif update[0] == \"channel\": channel = await self.bot.fetch_channel(update[1]) await",
"\"deafen\": message += f\" - {'Deafened' if lock_value else 'Undeafened'}\\n\" elif lock_type ==",
"reason=f\"Locked as {'deafened' if update[1] else 'undeafened'}.\", ) elif update[0] == \"channel\": channel",
"`{user}` locked as {'deafened' if deafened else 'undeafened'}.\", hidden=True, ) @cog_ext.cog_subcommand( name=\"channel\", description=\"Lock",
"\"channel\": channel = await self.bot.fetch_channel(update[1]) await member.edit( voice_channel=channel, reason=f\"Locked in channel {channel} (ID:",
"self.bot = bot @commands.Cog.listener() async def on_voice_state_update( self, member: Member, before: VoiceState, after:",
"), ], ) async def _lock_deafen(self, ctx, user: Member, deafened: bool): if not",
"- {'Deafened' if lock_value else 'Undeafened'}\\n\" elif lock_type == \"channel\": channel = await",
"This command can only be run in servers.\", options=[ create_option( name=\"user\", description=\"The user",
"the user should be locked as muted or unmuted.\", option_type=SlashCommandOptionType.BOOLEAN, required=True, ), ],",
"update[1] else 'unmuted'}.\", ) elif update[0] == \"deafen\": await member.edit( deafen=update[1], reason=f\"Locked as",
"voice_channel=channel, reason=f\"Locked in channel {channel} (ID: {channel.id}).\", ) @cog_ext.cog_subcommand( name=\"mute\", description=\"Lock the specified",
"to remove from the user (defaults to All)\", option_type=SlashCommandOptionType.STRING, required=False, choices=[ create_choice( name=\"Mute\",",
"or unmuted.\", option_type=SlashCommandOptionType.BOOLEAN, required=True, ), ], ) async def _lock_mute(self, ctx, user: Member,",
"message += f\" - Channel: {channel} (ID: {channel.id})\\n\" message += \"```\" await ctx.send(message)",
"channel to lock the user in.\", option_type=SlashCommandOptionType.CHANNEL, required=True, ), ], ) async def",
"in this server.\") return message = ( f\"Listing {len(users)} locked user{'s' if len(users)",
"only be run in servers.\", ) async def _list_locks(self, ctx): if not ctx.guild:",
"run in servers.\", hidden=True) return if channel.type != ChannelType.voice: await ctx.send(\"The selected channel",
"\"mute\": await member.edit( mute=update[1], reason=f\"Locked as {'muted' if update[1] else 'unmuted'}.\", ) elif",
"be run in servers.\", base=\"lock\", options=[ create_option( name=\"user\", description=\"The user to lock.\", option_type=SlashCommandOptionType.USER,",
"required=True, ), create_option( name=\"channel\", description=\"The voice channel to lock the user in.\", option_type=SlashCommandOptionType.CHANNEL,",
"run in servers.\", ) async def _list_locks(self, ctx): if not ctx.guild: await ctx.send(\"This",
"in servers.\", options=[ create_option( name=\"user\", description=\"The user to unlock.\", option_type=SlashCommandOptionType.USER, required=True, ), create_option(",
"import NotFound from discord.ext import commands from discord_slash import cog_ext from discord_slash.model import",
"as {'muted' if muted else 'unmuted'}.\", hidden=True, ) @cog_ext.cog_subcommand( name=\"deafen\", description=\"Lock the specified",
"update in updates: if update[0] == \"mute\": await member.edit( mute=update[1], reason=f\"Locked as {'muted'",
"lock_value=muted) await ctx.send( f\"User `{user}` locked as {'muted' if muted else 'unmuted'}.\", hidden=True,",
"before: VoiceState, after: VoiceState ): updates = lock_manager.check(member, after) for update in updates:",
"command can only be run in servers.\", options=[ create_option( name=\"user\", description=\"The user to",
"== \"mute\": await member.edit( mute=update[1], reason=f\"Locked as {'muted' if update[1] else 'unmuted'}.\", )",
"specified user as muted or unmuted. This command can only be run in",
"await ctx.send(\"This command can only be run in servers.\", hidden=True) return users =",
"locked as {'deafened' if deafened else 'undeafened'}.\", hidden=True, ) @cog_ext.cog_subcommand( name=\"channel\", description=\"Lock the",
"lock_type=\"deafen\", lock_value=deafened) await ctx.send( f\"User `{user}` locked as {'deafened' if deafened else 'undeafened'}.\",",
"await member.edit( voice_channel=channel, reason=f\"Locked in channel {channel} (ID: {channel.id}).\", ) @cog_ext.cog_subcommand( name=\"mute\", description=\"Lock",
"command can only be run in servers.\", hidden=True) return users = lock_manager.list(str(ctx.guild.id)) if",
"create_option( name=\"channel\", description=\"The voice channel to lock the user in.\", option_type=SlashCommandOptionType.CHANNEL, required=True, ),",
"from discord_slash import cog_ext from discord_slash.model import SlashCommandOptionType from discord_slash.utils.manage_commands import create_choice, create_option",
"to lock.\", option_type=SlashCommandOptionType.USER, required=True, ), create_option( name=\"deafened\", description=\"Determines if the user should be",
"of lock to remove from the user (defaults to All)\", option_type=SlashCommandOptionType.STRING, required=False, choices=[",
"command can only be run in servers.\", hidden=True) return lock_manager.add(ctx, user.id, lock_type=\"mute\", lock_value=muted)",
"run in servers.\") return lock_manager.remove(ctx, user.id, lock_type) await ctx.send( f\"Removed {lock_type} lock{'s' if",
") @cog_ext.cog_subcommand( name=\"deafen\", description=\"Lock the specified user as deafened or undeafened. This command",
"user = await self.bot.fetch_user(user_id) except NotFound as e: logger.info(f\"User {user_id} not found.\") message",
"can only be run in servers.\", base=\"lock\", options=[ create_option( name=\"user\", description=\"The user to",
"to lock.\", option_type=SlashCommandOptionType.USER, required=True, ), create_option( name=\"muted\", description=\"Determines if the user should be",
"specified voice channel. This command can only be run in servers.\", base=\"lock\", options=[",
"{'muted' if update[1] else 'unmuted'}.\", ) elif update[0] == \"deafen\": await member.edit( deafen=update[1],",
"hidden=True) return users = lock_manager.list(str(ctx.guild.id)) if not users: await ctx.send(\"There are no locked",
"after: VoiceState ): updates = lock_manager.check(member, after) for update in updates: if update[0]",
"`{user}` locked in `{channel}` (ID: {channel.id}).\", hidden=True, ) @cog_ext.cog_subcommand( base=\"lock\", name=\"list\", description=\"Lists all",
"), create_choice( name=\"Channel\", value=\"channel\" ), create_choice( name=\"All\", value=\"all\" ) ] ) ], )",
"updates: if update[0] == \"mute\": await member.edit( mute=update[1], reason=f\"Locked as {'muted' if update[1]",
"be run in servers.\", hidden=True) return users = lock_manager.list(str(ctx.guild.id)) if not users: await",
"be run in servers.\", hidden=True) return lock_manager.add(ctx, user.id, lock_type=\"mute\", lock_value=muted) await ctx.send( f\"User",
"from discord.errors import NotFound from discord.ext import commands from discord_slash import cog_ext from",
"ctx.send( f\"User `{user}` locked as {'deafened' if deafened else 'undeafened'}.\", hidden=True, ) @cog_ext.cog_subcommand(",
"@cog_ext.cog_subcommand( base=\"lock\", name=\"list\", description=\"Lists all locked users. This command can only be run",
"user{'s' if len(users) > 1 else ''}:\\n```\" ) for user_id, locks in users.items():",
"= await self.bot.fetch_channel(lock_value) message += f\" - Channel: {channel} (ID: {channel.id})\\n\" message +=",
"description=\"The type of lock to remove from the user (defaults to All)\", option_type=SlashCommandOptionType.STRING,",
"VoiceState, after: VoiceState ): updates = lock_manager.check(member, after) for update in updates: if",
"lock.\", option_type=SlashCommandOptionType.USER, required=True, ), create_option( name=\"muted\", description=\"Determines if the user should be locked",
"choices=[ create_choice( name=\"Mute\", value=\"mute\", ), create_choice( name=\"Deafen\", value=\"deafen\", ), create_choice( name=\"Channel\", value=\"channel\" ),",
"), create_choice( name=\"All\", value=\"all\" ) ] ) ], ) async def _unlock(self, ctx,",
"_lock_deafen(self, ctx, user: Member, deafened: bool): if not ctx.guild: await ctx.send(\"This command can",
") @cog_ext.cog_subcommand( name=\"channel\", description=\"Lock the specified user in a specified voice channel. This",
"locked as muted or unmuted.\", option_type=SlashCommandOptionType.BOOLEAN, required=True, ), ], ) async def _lock_mute(self,",
"to All)\", option_type=SlashCommandOptionType.STRING, required=False, choices=[ create_choice( name=\"Mute\", value=\"mute\", ), create_choice( name=\"Deafen\", value=\"deafen\", ),",
"locked users in this server.\") return message = ( f\"Listing {len(users)} locked user{'s'",
"base=\"lock\", options=[ create_option( name=\"user\", description=\"The user to lock.\", option_type=SlashCommandOptionType.USER, required=True, ), create_option( name=\"channel\",",
"unlock.\", option_type=SlashCommandOptionType.USER, required=True, ), create_option( name=\"lock_type\", description=\"The type of lock to remove from",
"user to lock.\", option_type=SlashCommandOptionType.USER, required=True, ), create_option( name=\"deafened\", description=\"Determines if the user should",
"channel.type != ChannelType.voice: await ctx.send(\"The selected channel must be a voice channel.\", hidden=True)",
"def on_voice_state_update( self, member: Member, before: VoiceState, after: VoiceState ): updates = lock_manager.check(member,",
"This command can only be run in servers.\", ) async def _list_locks(self, ctx):",
"voice channel.\", hidden=True) return lock_manager.add(ctx, user.id, lock_type=\"channel\", lock_value=str(channel.id)) await ctx.send( f\"User `{user}` locked",
"user should be locked as deafened or undeafened.\", option_type=SlashCommandOptionType.BOOLEAN, required=True, ), ], )",
"\"mute\": message += f\" - {'Muted' if lock_value else 'Unmuted'}\\n\" elif lock_type ==",
"only be run in servers.\", hidden=True) return if channel.type != ChannelType.voice: await ctx.send(\"The",
"ctx.guild: await ctx.send(\"This command can only be run in servers.\", hidden=True) return lock_manager.add(ctx,",
"base=\"lock\", options=[ create_option( name=\"user\", description=\"The user to lock.\", option_type=SlashCommandOptionType.USER, required=True, ), create_option( name=\"muted\",",
"user as deafened or undeafened. This command can only be run in servers.\",",
"required=True, ), ], ) async def _lock_deafen(self, ctx, user: Member, deafened: bool): if",
"return if channel.type != ChannelType.voice: await ctx.send(\"The selected channel must be a voice",
"@commands.Cog.listener() async def on_voice_state_update( self, member: Member, before: VoiceState, after: VoiceState ): updates",
"can only be run in servers.\", hidden=True) return lock_manager.add(ctx, user.id, lock_type=\"deafen\", lock_value=deafened) await",
"description=\"Unlock the specified user. This command can only be run in servers.\", options=[",
"create_choice( name=\"Channel\", value=\"channel\" ), create_choice( name=\"All\", value=\"all\" ) ] ) ], ) async",
"lock_manager.add(ctx, user.id, lock_type=\"channel\", lock_value=str(channel.id)) await ctx.send( f\"User `{user}` locked in `{channel}` (ID: {channel.id}).\",",
"channel {channel} (ID: {channel.id}).\", ) @cog_ext.cog_subcommand( name=\"mute\", description=\"Lock the specified user as muted",
"- Channel: {channel} (ID: {channel.id})\\n\" message += \"```\" await ctx.send(message) @cog_ext.cog_subcommand( base=\"lock\", name=\"remove\",",
") async def _lock_channel(self, ctx, user: Member, channel: VoiceChannel): if not ctx.guild: await",
"be run in servers.\", hidden=True) return lock_manager.add(ctx, user.id, lock_type=\"deafen\", lock_value=deafened) await ctx.send( f\"User",
"channel. This command can only be run in servers.\", base=\"lock\", options=[ create_option( name=\"user\",",
"option_type=SlashCommandOptionType.STRING, required=False, choices=[ create_choice( name=\"Mute\", value=\"mute\", ), create_choice( name=\"Deafen\", value=\"deafen\", ), create_choice( name=\"Channel\",",
"lock.\", option_type=SlashCommandOptionType.USER, required=True, ), create_option( name=\"channel\", description=\"The voice channel to lock the user",
") async def _lock_deafen(self, ctx, user: Member, deafened: bool): if not ctx.guild: await",
") @cog_ext.cog_subcommand( base=\"lock\", name=\"list\", description=\"Lists all locked users. This command can only be",
"locked users. This command can only be run in servers.\", ) async def",
"not found.\") message += f\"{user}\\n\" for lock_type, lock_value in locks.items(): if lock_type ==",
"), create_option( name=\"channel\", description=\"The voice channel to lock the user in.\", option_type=SlashCommandOptionType.CHANNEL, required=True,",
"VoiceChannel, ChannelType from data.lock_manager import lock_manager logger = logging.getLogger(__name__) class LockCog(commands.Cog): def __init__(self,",
"from data.lock_manager import lock_manager logger = logging.getLogger(__name__) class LockCog(commands.Cog): def __init__(self, bot): self.bot",
"option_type=SlashCommandOptionType.BOOLEAN, required=True, ), ], ) async def _lock_deafen(self, ctx, user: Member, deafened: bool):",
"await self.bot.fetch_channel(lock_value) message += f\" - Channel: {channel} (ID: {channel.id})\\n\" message += \"```\"",
"the user (defaults to All)\", option_type=SlashCommandOptionType.STRING, required=False, choices=[ create_choice( name=\"Mute\", value=\"mute\", ), create_choice(",
"base=\"lock\", name=\"remove\", description=\"Unlock the specified user. This command can only be run in",
"locked as {'muted' if muted else 'unmuted'}.\", hidden=True, ) @cog_ext.cog_subcommand( name=\"deafen\", description=\"Lock the",
"undeafened. This command can only be run in servers.\", base=\"lock\", options=[ create_option( name=\"user\",",
") async def _unlock(self, ctx, user: Member, lock_type: str = \"all\"): if not",
"import SlashCommandOptionType from discord_slash.utils.manage_commands import create_choice, create_option from discord import VoiceState, Member, VoiceChannel,",
"be locked as deafened or undeafened.\", option_type=SlashCommandOptionType.BOOLEAN, required=True, ), ], ) async def",
"in.\", option_type=SlashCommandOptionType.CHANNEL, required=True, ), ], ) async def _lock_channel(self, ctx, user: Member, channel:",
"import logging from discord.errors import NotFound from discord.ext import commands from discord_slash import",
"run in servers.\", hidden=True) return users = lock_manager.list(str(ctx.guild.id)) if not users: await ctx.send(\"There",
"only be run in servers.\", hidden=True) return users = lock_manager.list(str(ctx.guild.id)) if not users:",
"else 'unmuted'}.\", hidden=True, ) @cog_ext.cog_subcommand( name=\"deafen\", description=\"Lock the specified user as deafened or",
"description=\"Lists all locked users. This command can only be run in servers.\", )",
"for lock_type, lock_value in locks.items(): if lock_type == \"mute\": message += f\" -",
"description=\"Determines if the user should be locked as deafened or undeafened.\", option_type=SlashCommandOptionType.BOOLEAN, required=True,",
"1 else ''}:\\n```\" ) for user_id, locks in users.items(): try: user = await",
"except NotFound as e: logger.info(f\"User {user_id} not found.\") message += f\"{user}\\n\" for lock_type,",
"ctx.send(\"This command can only be run in servers.\", hidden=True) return if channel.type !=",
"hidden=True) return if channel.type != ChannelType.voice: await ctx.send(\"The selected channel must be a",
"from the user (defaults to All)\", option_type=SlashCommandOptionType.STRING, required=False, choices=[ create_choice( name=\"Mute\", value=\"mute\", ),",
"_unlock(self, ctx, user: Member, lock_type: str = \"all\"): if not ctx.guild: await ctx.send(\"This",
"return lock_manager.add(ctx, user.id, lock_type=\"channel\", lock_value=str(channel.id)) await ctx.send( f\"User `{user}` locked in `{channel}` (ID:",
"await ctx.send(\"There are no locked users in this server.\") return message = (",
"description=\"The user to lock.\", option_type=SlashCommandOptionType.USER, required=True, ), create_option( name=\"channel\", description=\"The voice channel to",
"> 1 else ''}:\\n```\" ) for user_id, locks in users.items(): try: user =",
"_list_locks(self, ctx): if not ctx.guild: await ctx.send(\"This command can only be run in",
"class LockCog(commands.Cog): def __init__(self, bot): self.bot = bot @commands.Cog.listener() async def on_voice_state_update( self,",
"if update[1] else 'unmuted'}.\", ) elif update[0] == \"deafen\": await member.edit( deafen=update[1], reason=f\"Locked",
"logging.getLogger(__name__) class LockCog(commands.Cog): def __init__(self, bot): self.bot = bot @commands.Cog.listener() async def on_voice_state_update(",
"), ], ) async def _lock_mute(self, ctx, user: Member, muted: bool): if not",
"ctx.guild: await ctx.send(\"This command can only be run in servers.\") return lock_manager.remove(ctx, user.id,",
"ctx, user: Member, lock_type: str = \"all\"): if not ctx.guild: await ctx.send(\"This command",
"mute=update[1], reason=f\"Locked as {'muted' if update[1] else 'unmuted'}.\", ) elif update[0] == \"deafen\":",
"as deafened or undeafened. This command can only be run in servers.\", base=\"lock\",",
"await ctx.send(\"This command can only be run in servers.\") return lock_manager.remove(ctx, user.id, lock_type)",
"should be locked as deafened or undeafened.\", option_type=SlashCommandOptionType.BOOLEAN, required=True, ), ], ) async",
"), create_choice( name=\"Deafen\", value=\"deafen\", ), create_choice( name=\"Channel\", value=\"channel\" ), create_choice( name=\"All\", value=\"all\" )",
"channel = await self.bot.fetch_channel(lock_value) message += f\" - Channel: {channel} (ID: {channel.id})\\n\" message",
"channel must be a voice channel.\", hidden=True) return lock_manager.add(ctx, user.id, lock_type=\"channel\", lock_value=str(channel.id)) await",
"{'muted' if muted else 'unmuted'}.\", hidden=True, ) @cog_ext.cog_subcommand( name=\"deafen\", description=\"Lock the specified user",
"from discord.ext import commands from discord_slash import cog_ext from discord_slash.model import SlashCommandOptionType from",
") elif update[0] == \"channel\": channel = await self.bot.fetch_channel(update[1]) await member.edit( voice_channel=channel, reason=f\"Locked",
"option_type=SlashCommandOptionType.USER, required=True, ), create_option( name=\"lock_type\", description=\"The type of lock to remove from the",
"member: Member, before: VoiceState, after: VoiceState ): updates = lock_manager.check(member, after) for update",
"!= ChannelType.voice: await ctx.send(\"The selected channel must be a voice channel.\", hidden=True) return",
"], ) async def _lock_mute(self, ctx, user: Member, muted: bool): if not ctx.guild:",
"f\"User `{user}` locked as {'deafened' if deafened else 'undeafened'}.\", hidden=True, ) @cog_ext.cog_subcommand( name=\"channel\",",
"+= f\" - {'Muted' if lock_value else 'Unmuted'}\\n\" elif lock_type == \"deafen\": message",
"All)\", option_type=SlashCommandOptionType.STRING, required=False, choices=[ create_choice( name=\"Mute\", value=\"mute\", ), create_choice( name=\"Deafen\", value=\"deafen\", ), create_choice(",
"the user in.\", option_type=SlashCommandOptionType.CHANNEL, required=True, ), ], ) async def _lock_channel(self, ctx, user:",
"user. This command can only be run in servers.\", options=[ create_option( name=\"user\", description=\"The",
"- {'Muted' if lock_value else 'Unmuted'}\\n\" elif lock_type == \"deafen\": message += f\"",
"str = \"all\"): if not ctx.guild: await ctx.send(\"This command can only be run",
"{channel.id}).\", hidden=True, ) @cog_ext.cog_subcommand( base=\"lock\", name=\"list\", description=\"Lists all locked users. This command can",
"user should be locked as muted or unmuted.\", option_type=SlashCommandOptionType.BOOLEAN, required=True, ), ], )",
"options=[ create_option( name=\"user\", description=\"The user to lock.\", option_type=SlashCommandOptionType.USER, required=True, ), create_option( name=\"deafened\", description=\"Determines",
"deafened: bool): if not ctx.guild: await ctx.send(\"This command can only be run in",
"if muted else 'unmuted'}.\", hidden=True, ) @cog_ext.cog_subcommand( name=\"deafen\", description=\"Lock the specified user as",
"base=\"lock\", name=\"list\", description=\"Lists all locked users. This command can only be run in",
"are no locked users in this server.\") return message = ( f\"Listing {len(users)}",
"= await self.bot.fetch_channel(update[1]) await member.edit( voice_channel=channel, reason=f\"Locked in channel {channel} (ID: {channel.id}).\", )",
"import cog_ext from discord_slash.model import SlashCommandOptionType from discord_slash.utils.manage_commands import create_choice, create_option from discord",
"else 'unmuted'}.\", ) elif update[0] == \"deafen\": await member.edit( deafen=update[1], reason=f\"Locked as {'deafened'",
"async def _unlock(self, ctx, user: Member, lock_type: str = \"all\"): if not ctx.guild:",
"ctx): if not ctx.guild: await ctx.send(\"This command can only be run in servers.\",",
"), create_option( name=\"muted\", description=\"Determines if the user should be locked as muted or",
"create_option( name=\"deafened\", description=\"Determines if the user should be locked as deafened or undeafened.\",",
"can only be run in servers.\", hidden=True) return users = lock_manager.list(str(ctx.guild.id)) if not",
"as e: logger.info(f\"User {user_id} not found.\") message += f\"{user}\\n\" for lock_type, lock_value in",
"user (defaults to All)\", option_type=SlashCommandOptionType.STRING, required=False, choices=[ create_choice( name=\"Mute\", value=\"mute\", ), create_choice( name=\"Deafen\",",
"only be run in servers.\", base=\"lock\", options=[ create_option( name=\"user\", description=\"The user to lock.\",",
"if deafened else 'undeafened'}.\", hidden=True, ) @cog_ext.cog_subcommand( name=\"channel\", description=\"Lock the specified user in",
"name=\"remove\", description=\"Unlock the specified user. This command can only be run in servers.\",",
"Member, VoiceChannel, ChannelType from data.lock_manager import lock_manager logger = logging.getLogger(__name__) class LockCog(commands.Cog): def",
"async def _lock_mute(self, ctx, user: Member, muted: bool): if not ctx.guild: await ctx.send(\"This",
"locked as deafened or undeafened.\", option_type=SlashCommandOptionType.BOOLEAN, required=True, ), ], ) async def _lock_deafen(self,",
"data.lock_manager import lock_manager logger = logging.getLogger(__name__) class LockCog(commands.Cog): def __init__(self, bot): self.bot =",
"user.id, lock_type=\"mute\", lock_value=muted) await ctx.send( f\"User `{user}` locked as {'muted' if muted else",
"in servers.\", hidden=True) return if channel.type != ChannelType.voice: await ctx.send(\"The selected channel must",
"if lock_type == 'all' else ''} from {user}.\", hidden=True, ) def setup(bot): bot.add_cog(LockCog(bot))",
"base=\"lock\", options=[ create_option( name=\"user\", description=\"The user to lock.\", option_type=SlashCommandOptionType.USER, required=True, ), create_option( name=\"deafened\",",
"ctx, user: Member, deafened: bool): if not ctx.guild: await ctx.send(\"This command can only",
"as muted or unmuted. This command can only be run in servers.\", base=\"lock\",",
"hidden=True) return lock_manager.add(ctx, user.id, lock_type=\"mute\", lock_value=muted) await ctx.send( f\"User `{user}` locked as {'muted'",
"@cog_ext.cog_subcommand( name=\"mute\", description=\"Lock the specified user as muted or unmuted. This command can",
"run in servers.\", options=[ create_option( name=\"user\", description=\"The user to unlock.\", option_type=SlashCommandOptionType.USER, required=True, ),",
"await ctx.send( f\"Removed {lock_type} lock{'s' if lock_type == 'all' else ''} from {user}.\",",
"only be run in servers.\", options=[ create_option( name=\"user\", description=\"The user to unlock.\", option_type=SlashCommandOptionType.USER,",
"ctx.send(\"This command can only be run in servers.\", hidden=True) return lock_manager.add(ctx, user.id, lock_type=\"deafen\",",
"name=\"Deafen\", value=\"deafen\", ), create_choice( name=\"Channel\", value=\"channel\" ), create_choice( name=\"All\", value=\"all\" ) ] )",
"as {'deafened' if update[1] else 'undeafened'}.\", ) elif update[0] == \"channel\": channel =",
"value=\"mute\", ), create_choice( name=\"Deafen\", value=\"deafen\", ), create_choice( name=\"Channel\", value=\"channel\" ), create_choice( name=\"All\", value=\"all\"",
"@cog_ext.cog_subcommand( base=\"lock\", name=\"remove\", description=\"Unlock the specified user. This command can only be run",
"self.bot.fetch_channel(update[1]) await member.edit( voice_channel=channel, reason=f\"Locked in channel {channel} (ID: {channel.id}).\", ) @cog_ext.cog_subcommand( name=\"mute\",",
"lock_type: str = \"all\"): if not ctx.guild: await ctx.send(\"This command can only be",
"if lock_value else 'Undeafened'}\\n\" elif lock_type == \"channel\": channel = await self.bot.fetch_channel(lock_value) message",
"lock_value=deafened) await ctx.send( f\"User `{user}` locked as {'deafened' if deafened else 'undeafened'}.\", hidden=True,",
"description=\"The user to unlock.\", option_type=SlashCommandOptionType.USER, required=True, ), create_option( name=\"lock_type\", description=\"The type of lock",
"{user_id} not found.\") message += f\"{user}\\n\" for lock_type, lock_value in locks.items(): if lock_type",
"{'deafened' if update[1] else 'undeafened'}.\", ) elif update[0] == \"channel\": channel = await"
] |
[
"from the pip `requirements` file. Args: requirements (str): path to the pip requirements",
"to ._internal. Boo! from pip import __version__ as pip_version if LooseVersion(pip_version) < LooseVersion('1.5'):",
"do_parse = lambda path: parse_requirements(path, session=PipSession()) # noqa: E731 else: # We're in",
"v10.0.0 moved these wonderful methods to ._internal. Boo! from pip import __version__ as",
"if f != \"dummy.py\"] except OSError: scripts = [] setuptools.setup( name = 'pyDSlib',",
"['django==1.5.1', 'mezzanine==1.4.6'] Returns: List[str]: the list of requirements \"\"\" # pip v1.5 started",
"to automatically pull in install_requires values directly from # your requirements.txt file but",
"pip module available install_reqs = do_parse(os.path.join(here, requirements)) return [str(ir.req) for ir in install_reqs]",
"os.path.abspath(os.path.dirname(__file__)) def read(*parts): with codecs.open(os.path.join(here, *parts), 'r') as fp: return fp.read() def find_version(*file_paths):",
"RuntimeError(\"Unable to find version string.\") def get_requirements(requirements='requirements.txt'): \"\"\"Get the list of requirements from",
"the 'session' # pip v10.0.0 moved these wonderful methods to ._internal. Boo! from",
"'__init__.py'), author=\"<NAME>\", author_email=\"<EMAIL>\", description='General utilities to streamline data science and machine learning routines",
"'venv'] # fetch long description from readme with open(\"README.md\", \"r\") as fh: README",
"['scripts/%s' % f for f in os.listdir('scripts') if f != \"dummy.py\"] except OSError:",
"distutils.version import LooseVersion from pathlib import Path import os import re import codecs",
"E731 # Cool trick to automatically pull in install_requires values directly from #",
"def read(*parts): with codecs.open(os.path.join(here, *parts), 'r') as fp: return fp.read() def find_version(*file_paths): version_file",
"pip.download import PipSession do_parse = lambda path: parse_requirements(path, session=PipSession()) # noqa: E731 else:",
"utilities to streamline data science and machine learning routines in python', long_description= README,",
"to have pip module available install_reqs = do_parse(os.path.join(here, requirements)) return [str(ir.req) for ir",
"ir in install_reqs] def _determine_requirements_txt_location(): this_dir = Path(__file__).parent if Path(this_dir, 'requirements.txt').exists(): return 'requirements.txt'",
"streamline data science and machine learning routines in python', long_description= README, long_description_content_type=\"text/markdown\", url=\"https://github.com/jlnerd/pyDSlib.git\",",
"install_requires values directly from # your requirements.txt file but you need to have",
"f for f in os.listdir('scripts') if f != \"dummy.py\"] except OSError: scripts =",
"directories to exclude from setup exclude_dirs = ['ez_setup', 'examples', 'tests', 'venv'] # fetch",
"f != \"dummy.py\"] except OSError: scripts = [] setuptools.setup( name = 'pyDSlib', version=",
"PipSession do_parse = lambda path: parse_requirements(path, session=PipSession()) # noqa: E731 else: # We're",
"except OSError: scripts = [] setuptools.setup( name = 'pyDSlib', version= find_version('pyDSlib', '__init__.py'), author=\"<NAME>\",",
"and machine learning routines in python', long_description= README, long_description_content_type=\"text/markdown\", url=\"https://github.com/jlnerd/pyDSlib.git\", packages= setuptools.find_packages(exclude=exclude_dirs), include_package_data=True,",
"long_description= README, long_description_content_type=\"text/markdown\", url=\"https://github.com/jlnerd/pyDSlib.git\", packages= setuptools.find_packages(exclude=exclude_dirs), include_package_data=True, scripts=scripts, setup_requires=[\"pep8\", \"setuptools>=30\"], dependency_links=[], #test_suite='ci_scripts.run_nose.run', #tests_require=['nose>=1.3.7',",
"setuptools.find_packages(exclude=exclude_dirs), include_package_data=True, scripts=scripts, setup_requires=[\"pep8\", \"setuptools>=30\"], dependency_links=[], #test_suite='ci_scripts.run_nose.run', #tests_require=['nose>=1.3.7', 'coverage'], zip_safe=False, install_requires=get_requirements(_determine_requirements_txt_location()), entry_points={}, )",
"= 'pyDSlib', version= find_version('pyDSlib', '__init__.py'), author=\"<NAME>\", author_email=\"<EMAIL>\", description='General utilities to streamline data science",
"= ['scripts/%s' % f for f in os.listdir('scripts') if f != \"dummy.py\"] except",
"fp: return fp.read() def find_version(*file_paths): version_file = read(*file_paths) version_match = re.search(r\"^__version__ = ['\\\"]([^'\\\"]*)['\\\"]\",",
"requirements file. Examples: ['django==1.5.1', 'mezzanine==1.4.6'] Returns: List[str]: the list of requirements \"\"\" #",
"requiring the 'session' # pip v10.0.0 moved these wonderful methods to ._internal. Boo!",
"file') #define directories to exclude from setup exclude_dirs = ['ez_setup', 'examples', 'tests', 'venv']",
"module available install_reqs = do_parse(os.path.join(here, requirements)) return [str(ir.req) for ir in install_reqs] def",
"re import codecs here = os.path.abspath(os.path.dirname(__file__)) def read(*parts): with codecs.open(os.path.join(here, *parts), 'r') as",
"with codecs.open(os.path.join(here, *parts), 'r') as fp: return fp.read() def find_version(*file_paths): version_file = read(*file_paths)",
"exclude_dirs = ['ez_setup', 'examples', 'tests', 'venv'] # fetch long description from readme with",
"in install_requires values directly from # your requirements.txt file but you need to",
"= [] setuptools.setup( name = 'pyDSlib', version= find_version('pyDSlib', '__init__.py'), author=\"<NAME>\", author_email=\"<EMAIL>\", description='General utilities",
"import parse_requirements from pip.download import PipSession do_parse = lambda path: parse_requirements(path, session=PipSession()) #",
"= lambda path: parse_requirements(path, session=PipSession()) # noqa: E731 # Cool trick to automatically",
"directly from # your requirements.txt file but you need to have pip module",
"'pyDSlib.egg-info', 'requires.txt').exists(): return 'pyDSlib.egg-info/requires.txt' else: raise FileExistsError('Unable to find a requirements.txt file') #define",
"path: parse_requirements(path) # noqa: E731 elif LooseVersion(pip_version) < LooseVersion('10.0.0'): from pip.req import parse_requirements",
"# noqa: E731 elif LooseVersion(pip_version) < LooseVersion('10.0.0'): from pip.req import parse_requirements from pip.download",
"readme with open(\"README.md\", \"r\") as fh: README = fh.read() #fetch scripts try: scripts",
"import codecs here = os.path.abspath(os.path.dirname(__file__)) def read(*parts): with codecs.open(os.path.join(here, *parts), 'r') as fp:",
"from pip.req import parse_requirements from pip.download import PipSession do_parse = lambda path: parse_requirements(path,",
"moved these wonderful methods to ._internal. Boo! from pip import __version__ as pip_version",
"if Path(this_dir, 'requirements.txt').exists(): return 'requirements.txt' elif Path(this_dir, 'pyDSlib.egg-info', 'requires.txt').exists(): return 'pyDSlib.egg-info/requires.txt' else: raise",
"'requirements.txt').exists(): return 'requirements.txt' elif Path(this_dir, 'pyDSlib.egg-info', 'requires.txt').exists(): return 'pyDSlib.egg-info/requires.txt' else: raise FileExistsError('Unable to",
"scripts = ['scripts/%s' % f for f in os.listdir('scripts') if f != \"dummy.py\"]",
"setuptools.setup( name = 'pyDSlib', version= find_version('pyDSlib', '__init__.py'), author=\"<NAME>\", author_email=\"<EMAIL>\", description='General utilities to streamline",
"need to have pip module available install_reqs = do_parse(os.path.join(here, requirements)) return [str(ir.req) for",
"parse_requirements from pip._internal.download import PipSession do_parse = lambda path: parse_requirements(path, session=PipSession()) # noqa:",
"FileExistsError('Unable to find a requirements.txt file') #define directories to exclude from setup exclude_dirs",
"LooseVersion(pip_version) < LooseVersion('1.5'): from pip.req import parse_requirements do_parse = lambda path: parse_requirements(path) #",
"\"\"\" # pip v1.5 started requiring the 'session' # pip v10.0.0 moved these",
"= do_parse(os.path.join(here, requirements)) return [str(ir.req) for ir in install_reqs] def _determine_requirements_txt_location(): this_dir =",
"pip import __version__ as pip_version if LooseVersion(pip_version) < LooseVersion('1.5'): from pip.req import parse_requirements",
"file. Args: requirements (str): path to the pip requirements file. Examples: ['django==1.5.1', 'mezzanine==1.4.6']",
"# We're in the bold new future of using internals... yeah from pip._internal.req",
"do_parse(os.path.join(here, requirements)) return [str(ir.req) for ir in install_reqs] def _determine_requirements_txt_location(): this_dir = Path(__file__).parent",
"to the pip requirements file. Examples: ['django==1.5.1', 'mezzanine==1.4.6'] Returns: List[str]: the list of",
"have pip module available install_reqs = do_parse(os.path.join(here, requirements)) return [str(ir.req) for ir in",
"elif Path(this_dir, 'pyDSlib.egg-info', 'requires.txt').exists(): return 'pyDSlib.egg-info/requires.txt' else: raise FileExistsError('Unable to find a requirements.txt",
"pip.req import parse_requirements do_parse = lambda path: parse_requirements(path) # noqa: E731 elif LooseVersion(pip_version)",
"# fetch long description from readme with open(\"README.md\", \"r\") as fh: README =",
"import re import codecs here = os.path.abspath(os.path.dirname(__file__)) def read(*parts): with codecs.open(os.path.join(here, *parts), 'r')",
"'session' # pip v10.0.0 moved these wonderful methods to ._internal. Boo! from pip",
"fp.read() def find_version(*file_paths): version_file = read(*file_paths) version_match = re.search(r\"^__version__ = ['\\\"]([^'\\\"]*)['\\\"]\", version_file, re.M)",
"future of using internals... yeah from pip._internal.req import parse_requirements from pip._internal.download import PipSession",
"from pip._internal.req import parse_requirements from pip._internal.download import PipSession do_parse = lambda path: parse_requirements(path,",
"noqa: E731 # Cool trick to automatically pull in install_requires values directly from",
"in install_reqs] def _determine_requirements_txt_location(): this_dir = Path(__file__).parent if Path(this_dir, 'requirements.txt').exists(): return 'requirements.txt' elif",
"exclude from setup exclude_dirs = ['ez_setup', 'examples', 'tests', 'venv'] # fetch long description",
"Args: requirements (str): path to the pip requirements file. Examples: ['django==1.5.1', 'mezzanine==1.4.6'] Returns:",
"LooseVersion('10.0.0'): from pip.req import parse_requirements from pip.download import PipSession do_parse = lambda path:",
"'pyDSlib', version= find_version('pyDSlib', '__init__.py'), author=\"<NAME>\", author_email=\"<EMAIL>\", description='General utilities to streamline data science and",
"<reponame>jlnerd/JLpy_Utilities<gh_stars>0 import setuptools from distutils.version import LooseVersion from pathlib import Path import os",
"the list of requirements from the pip `requirements` file. Args: requirements (str): path",
"path: parse_requirements(path, session=PipSession()) # noqa: E731 else: # We're in the bold new",
"import __version__ as pip_version if LooseVersion(pip_version) < LooseVersion('1.5'): from pip.req import parse_requirements do_parse",
"version_file = read(*file_paths) version_match = re.search(r\"^__version__ = ['\\\"]([^'\\\"]*)['\\\"]\", version_file, re.M) if version_match: return",
"this_dir = Path(__file__).parent if Path(this_dir, 'requirements.txt').exists(): return 'requirements.txt' elif Path(this_dir, 'pyDSlib.egg-info', 'requires.txt').exists(): return",
"read(*file_paths) version_match = re.search(r\"^__version__ = ['\\\"]([^'\\\"]*)['\\\"]\", version_file, re.M) if version_match: return version_match.group(1) raise",
"'requires.txt').exists(): return 'pyDSlib.egg-info/requires.txt' else: raise FileExistsError('Unable to find a requirements.txt file') #define directories",
"'tests', 'venv'] # fetch long description from readme with open(\"README.md\", \"r\") as fh:",
"as fh: README = fh.read() #fetch scripts try: scripts = ['scripts/%s' % f",
"learning routines in python', long_description= README, long_description_content_type=\"text/markdown\", url=\"https://github.com/jlnerd/pyDSlib.git\", packages= setuptools.find_packages(exclude=exclude_dirs), include_package_data=True, scripts=scripts, setup_requires=[\"pep8\",",
"from pip.req import parse_requirements do_parse = lambda path: parse_requirements(path) # noqa: E731 elif",
"re.M) if version_match: return version_match.group(1) raise RuntimeError(\"Unable to find version string.\") def get_requirements(requirements='requirements.txt'):",
"parse_requirements do_parse = lambda path: parse_requirements(path) # noqa: E731 elif LooseVersion(pip_version) < LooseVersion('10.0.0'):",
"from pathlib import Path import os import re import codecs here = os.path.abspath(os.path.dirname(__file__))",
"import parse_requirements do_parse = lambda path: parse_requirements(path) # noqa: E731 elif LooseVersion(pip_version) <",
"_determine_requirements_txt_location(): this_dir = Path(__file__).parent if Path(this_dir, 'requirements.txt').exists(): return 'requirements.txt' elif Path(this_dir, 'pyDSlib.egg-info', 'requires.txt').exists():",
"from distutils.version import LooseVersion from pathlib import Path import os import re import",
"v1.5 started requiring the 'session' # pip v10.0.0 moved these wonderful methods to",
"LooseVersion from pathlib import Path import os import re import codecs here =",
"noqa: E731 elif LooseVersion(pip_version) < LooseVersion('10.0.0'): from pip.req import parse_requirements from pip.download import",
"import PipSession do_parse = lambda path: parse_requirements(path, session=PipSession()) # noqa: E731 else: #",
"else: raise FileExistsError('Unable to find a requirements.txt file') #define directories to exclude from",
"= lambda path: parse_requirements(path, session=PipSession()) # noqa: E731 else: # We're in the",
"`requirements` file. Args: requirements (str): path to the pip requirements file. Examples: ['django==1.5.1',",
"session=PipSession()) # noqa: E731 else: # We're in the bold new future of",
"import Path import os import re import codecs here = os.path.abspath(os.path.dirname(__file__)) def read(*parts):",
"['ez_setup', 'examples', 'tests', 'venv'] # fetch long description from readme with open(\"README.md\", \"r\")",
"= re.search(r\"^__version__ = ['\\\"]([^'\\\"]*)['\\\"]\", version_file, re.M) if version_match: return version_match.group(1) raise RuntimeError(\"Unable to",
"Path import os import re import codecs here = os.path.abspath(os.path.dirname(__file__)) def read(*parts): with",
"started requiring the 'session' # pip v10.0.0 moved these wonderful methods to ._internal.",
"bold new future of using internals... yeah from pip._internal.req import parse_requirements from pip._internal.download",
"else: # We're in the bold new future of using internals... yeah from",
"pip v10.0.0 moved these wonderful methods to ._internal. Boo! from pip import __version__",
"name = 'pyDSlib', version= find_version('pyDSlib', '__init__.py'), author=\"<NAME>\", author_email=\"<EMAIL>\", description='General utilities to streamline data",
"PipSession do_parse = lambda path: parse_requirements(path, session=PipSession()) # noqa: E731 # Cool trick",
"E731 elif LooseVersion(pip_version) < LooseVersion('10.0.0'): from pip.req import parse_requirements from pip.download import PipSession",
"find a requirements.txt file') #define directories to exclude from setup exclude_dirs = ['ez_setup',",
"long description from readme with open(\"README.md\", \"r\") as fh: README = fh.read() #fetch",
"description from readme with open(\"README.md\", \"r\") as fh: README = fh.read() #fetch scripts",
"[] setuptools.setup( name = 'pyDSlib', version= find_version('pyDSlib', '__init__.py'), author=\"<NAME>\", author_email=\"<EMAIL>\", description='General utilities to",
"internals... yeah from pip._internal.req import parse_requirements from pip._internal.download import PipSession do_parse = lambda",
"the bold new future of using internals... yeah from pip._internal.req import parse_requirements from",
"from readme with open(\"README.md\", \"r\") as fh: README = fh.read() #fetch scripts try:",
"[str(ir.req) for ir in install_reqs] def _determine_requirements_txt_location(): this_dir = Path(__file__).parent if Path(this_dir, 'requirements.txt').exists():",
"E731 else: # We're in the bold new future of using internals... yeah",
"to find a requirements.txt file') #define directories to exclude from setup exclude_dirs =",
"fh.read() #fetch scripts try: scripts = ['scripts/%s' % f for f in os.listdir('scripts')",
"a requirements.txt file') #define directories to exclude from setup exclude_dirs = ['ez_setup', 'examples',",
"LooseVersion(pip_version) < LooseVersion('10.0.0'): from pip.req import parse_requirements from pip.download import PipSession do_parse =",
"Path(__file__).parent if Path(this_dir, 'requirements.txt').exists(): return 'requirements.txt' elif Path(this_dir, 'pyDSlib.egg-info', 'requires.txt').exists(): return 'pyDSlib.egg-info/requires.txt' else:",
"of requirements from the pip `requirements` file. Args: requirements (str): path to the",
"fh: README = fh.read() #fetch scripts try: scripts = ['scripts/%s' % f for",
"lambda path: parse_requirements(path) # noqa: E731 elif LooseVersion(pip_version) < LooseVersion('10.0.0'): from pip.req import",
"author=\"<NAME>\", author_email=\"<EMAIL>\", description='General utilities to streamline data science and machine learning routines in",
"but you need to have pip module available install_reqs = do_parse(os.path.join(here, requirements)) return",
"def _determine_requirements_txt_location(): this_dir = Path(__file__).parent if Path(this_dir, 'requirements.txt').exists(): return 'requirements.txt' elif Path(this_dir, 'pyDSlib.egg-info',",
"def get_requirements(requirements='requirements.txt'): \"\"\"Get the list of requirements from the pip `requirements` file. Args:",
"= lambda path: parse_requirements(path) # noqa: E731 elif LooseVersion(pip_version) < LooseVersion('10.0.0'): from pip.req",
"OSError: scripts = [] setuptools.setup( name = 'pyDSlib', version= find_version('pyDSlib', '__init__.py'), author=\"<NAME>\", author_email=\"<EMAIL>\",",
"for f in os.listdir('scripts') if f != \"dummy.py\"] except OSError: scripts = []",
"if version_match: return version_match.group(1) raise RuntimeError(\"Unable to find version string.\") def get_requirements(requirements='requirements.txt'): \"\"\"Get",
"automatically pull in install_requires values directly from # your requirements.txt file but you",
"return 'pyDSlib.egg-info/requires.txt' else: raise FileExistsError('Unable to find a requirements.txt file') #define directories to",
"to streamline data science and machine learning routines in python', long_description= README, long_description_content_type=\"text/markdown\",",
"Path(this_dir, 'pyDSlib.egg-info', 'requires.txt').exists(): return 'pyDSlib.egg-info/requires.txt' else: raise FileExistsError('Unable to find a requirements.txt file')",
"version string.\") def get_requirements(requirements='requirements.txt'): \"\"\"Get the list of requirements from the pip `requirements`",
"open(\"README.md\", \"r\") as fh: README = fh.read() #fetch scripts try: scripts = ['scripts/%s'",
"scripts = [] setuptools.setup( name = 'pyDSlib', version= find_version('pyDSlib', '__init__.py'), author=\"<NAME>\", author_email=\"<EMAIL>\", description='General",
"import setuptools from distutils.version import LooseVersion from pathlib import Path import os import",
"of using internals... yeah from pip._internal.req import parse_requirements from pip._internal.download import PipSession do_parse",
"requirements \"\"\" # pip v1.5 started requiring the 'session' # pip v10.0.0 moved",
"!= \"dummy.py\"] except OSError: scripts = [] setuptools.setup( name = 'pyDSlib', version= find_version('pyDSlib',",
"path: parse_requirements(path, session=PipSession()) # noqa: E731 # Cool trick to automatically pull in",
"install_reqs] def _determine_requirements_txt_location(): this_dir = Path(__file__).parent if Path(this_dir, 'requirements.txt').exists(): return 'requirements.txt' elif Path(this_dir,",
"file. Examples: ['django==1.5.1', 'mezzanine==1.4.6'] Returns: List[str]: the list of requirements \"\"\" # pip",
"% f for f in os.listdir('scripts') if f != \"dummy.py\"] except OSError: scripts",
"science and machine learning routines in python', long_description= README, long_description_content_type=\"text/markdown\", url=\"https://github.com/jlnerd/pyDSlib.git\", packages= setuptools.find_packages(exclude=exclude_dirs),",
"pip requirements file. Examples: ['django==1.5.1', 'mezzanine==1.4.6'] Returns: List[str]: the list of requirements \"\"\"",
"your requirements.txt file but you need to have pip module available install_reqs =",
"the list of requirements \"\"\" # pip v1.5 started requiring the 'session' #",
"for ir in install_reqs] def _determine_requirements_txt_location(): this_dir = Path(__file__).parent if Path(this_dir, 'requirements.txt').exists(): return",
"the pip `requirements` file. Args: requirements (str): path to the pip requirements file.",
"# Cool trick to automatically pull in install_requires values directly from # your",
"# noqa: E731 else: # We're in the bold new future of using",
"packages= setuptools.find_packages(exclude=exclude_dirs), include_package_data=True, scripts=scripts, setup_requires=[\"pep8\", \"setuptools>=30\"], dependency_links=[], #test_suite='ci_scripts.run_nose.run', #tests_require=['nose>=1.3.7', 'coverage'], zip_safe=False, install_requires=get_requirements(_determine_requirements_txt_location()), entry_points={},",
"the pip requirements file. Examples: ['django==1.5.1', 'mezzanine==1.4.6'] Returns: List[str]: the list of requirements",
"pip `requirements` file. Args: requirements (str): path to the pip requirements file. Examples:",
"pip_version if LooseVersion(pip_version) < LooseVersion('1.5'): from pip.req import parse_requirements do_parse = lambda path:",
"fetch long description from readme with open(\"README.md\", \"r\") as fh: README = fh.read()",
"parse_requirements(path, session=PipSession()) # noqa: E731 else: # We're in the bold new future",
"requirements.txt file but you need to have pip module available install_reqs = do_parse(os.path.join(here,",
"Path(this_dir, 'requirements.txt').exists(): return 'requirements.txt' elif Path(this_dir, 'pyDSlib.egg-info', 'requires.txt').exists(): return 'pyDSlib.egg-info/requires.txt' else: raise FileExistsError('Unable",
"._internal. Boo! from pip import __version__ as pip_version if LooseVersion(pip_version) < LooseVersion('1.5'): from",
"import PipSession do_parse = lambda path: parse_requirements(path, session=PipSession()) # noqa: E731 # Cool",
"in python', long_description= README, long_description_content_type=\"text/markdown\", url=\"https://github.com/jlnerd/pyDSlib.git\", packages= setuptools.find_packages(exclude=exclude_dirs), include_package_data=True, scripts=scripts, setup_requires=[\"pep8\", \"setuptools>=30\"], dependency_links=[],",
"if LooseVersion(pip_version) < LooseVersion('1.5'): from pip.req import parse_requirements do_parse = lambda path: parse_requirements(path)",
"re.search(r\"^__version__ = ['\\\"]([^'\\\"]*)['\\\"]\", version_file, re.M) if version_match: return version_match.group(1) raise RuntimeError(\"Unable to find",
"f in os.listdir('scripts') if f != \"dummy.py\"] except OSError: scripts = [] setuptools.setup(",
"install_reqs = do_parse(os.path.join(here, requirements)) return [str(ir.req) for ir in install_reqs] def _determine_requirements_txt_location(): this_dir",
"README = fh.read() #fetch scripts try: scripts = ['scripts/%s' % f for f",
"'requirements.txt' elif Path(this_dir, 'pyDSlib.egg-info', 'requires.txt').exists(): return 'pyDSlib.egg-info/requires.txt' else: raise FileExistsError('Unable to find a",
"new future of using internals... yeah from pip._internal.req import parse_requirements from pip._internal.download import",
"read(*parts): with codecs.open(os.path.join(here, *parts), 'r') as fp: return fp.read() def find_version(*file_paths): version_file =",
"*parts), 'r') as fp: return fp.read() def find_version(*file_paths): version_file = read(*file_paths) version_match =",
"def find_version(*file_paths): version_file = read(*file_paths) version_match = re.search(r\"^__version__ = ['\\\"]([^'\\\"]*)['\\\"]\", version_file, re.M) if",
"elif LooseVersion(pip_version) < LooseVersion('10.0.0'): from pip.req import parse_requirements from pip.download import PipSession do_parse",
"data science and machine learning routines in python', long_description= README, long_description_content_type=\"text/markdown\", url=\"https://github.com/jlnerd/pyDSlib.git\", packages=",
"Returns: List[str]: the list of requirements \"\"\" # pip v1.5 started requiring the",
"pip._internal.download import PipSession do_parse = lambda path: parse_requirements(path, session=PipSession()) # noqa: E731 #",
"parse_requirements from pip.download import PipSession do_parse = lambda path: parse_requirements(path, session=PipSession()) # noqa:",
"you need to have pip module available install_reqs = do_parse(os.path.join(here, requirements)) return [str(ir.req)",
"trick to automatically pull in install_requires values directly from # your requirements.txt file",
"yeah from pip._internal.req import parse_requirements from pip._internal.download import PipSession do_parse = lambda path:",
"setup exclude_dirs = ['ez_setup', 'examples', 'tests', 'venv'] # fetch long description from readme",
"requirements.txt file') #define directories to exclude from setup exclude_dirs = ['ez_setup', 'examples', 'tests',",
"setuptools from distutils.version import LooseVersion from pathlib import Path import os import re",
"Boo! from pip import __version__ as pip_version if LooseVersion(pip_version) < LooseVersion('1.5'): from pip.req",
"= read(*file_paths) version_match = re.search(r\"^__version__ = ['\\\"]([^'\\\"]*)['\\\"]\", version_file, re.M) if version_match: return version_match.group(1)",
"codecs.open(os.path.join(here, *parts), 'r') as fp: return fp.read() def find_version(*file_paths): version_file = read(*file_paths) version_match",
"get_requirements(requirements='requirements.txt'): \"\"\"Get the list of requirements from the pip `requirements` file. Args: requirements",
"List[str]: the list of requirements \"\"\" # pip v1.5 started requiring the 'session'",
"available install_reqs = do_parse(os.path.join(here, requirements)) return [str(ir.req) for ir in install_reqs] def _determine_requirements_txt_location():",
"from setup exclude_dirs = ['ez_setup', 'examples', 'tests', 'venv'] # fetch long description from",
"scripts try: scripts = ['scripts/%s' % f for f in os.listdir('scripts') if f",
"version_match.group(1) raise RuntimeError(\"Unable to find version string.\") def get_requirements(requirements='requirements.txt'): \"\"\"Get the list of",
"pathlib import Path import os import re import codecs here = os.path.abspath(os.path.dirname(__file__)) def",
"import os import re import codecs here = os.path.abspath(os.path.dirname(__file__)) def read(*parts): with codecs.open(os.path.join(here,",
"\"\"\"Get the list of requirements from the pip `requirements` file. Args: requirements (str):",
"lambda path: parse_requirements(path, session=PipSession()) # noqa: E731 else: # We're in the bold",
"lambda path: parse_requirements(path, session=PipSession()) # noqa: E731 # Cool trick to automatically pull",
"try: scripts = ['scripts/%s' % f for f in os.listdir('scripts') if f !=",
"python', long_description= README, long_description_content_type=\"text/markdown\", url=\"https://github.com/jlnerd/pyDSlib.git\", packages= setuptools.find_packages(exclude=exclude_dirs), include_package_data=True, scripts=scripts, setup_requires=[\"pep8\", \"setuptools>=30\"], dependency_links=[], #test_suite='ci_scripts.run_nose.run',",
"version_match: return version_match.group(1) raise RuntimeError(\"Unable to find version string.\") def get_requirements(requirements='requirements.txt'): \"\"\"Get the",
"return fp.read() def find_version(*file_paths): version_file = read(*file_paths) version_match = re.search(r\"^__version__ = ['\\\"]([^'\\\"]*)['\\\"]\", version_file,",
"list of requirements from the pip `requirements` file. Args: requirements (str): path to",
"from pip._internal.download import PipSession do_parse = lambda path: parse_requirements(path, session=PipSession()) # noqa: E731",
"version_file, re.M) if version_match: return version_match.group(1) raise RuntimeError(\"Unable to find version string.\") def",
"using internals... yeah from pip._internal.req import parse_requirements from pip._internal.download import PipSession do_parse =",
"requirements (str): path to the pip requirements file. Examples: ['django==1.5.1', 'mezzanine==1.4.6'] Returns: List[str]:",
"'pyDSlib.egg-info/requires.txt' else: raise FileExistsError('Unable to find a requirements.txt file') #define directories to exclude",
"#define directories to exclude from setup exclude_dirs = ['ez_setup', 'examples', 'tests', 'venv'] #",
"here = os.path.abspath(os.path.dirname(__file__)) def read(*parts): with codecs.open(os.path.join(here, *parts), 'r') as fp: return fp.read()",
"to find version string.\") def get_requirements(requirements='requirements.txt'): \"\"\"Get the list of requirements from the",
"version_match = re.search(r\"^__version__ = ['\\\"]([^'\\\"]*)['\\\"]\", version_file, re.M) if version_match: return version_match.group(1) raise RuntimeError(\"Unable",
"methods to ._internal. Boo! from pip import __version__ as pip_version if LooseVersion(pip_version) <",
"= ['ez_setup', 'examples', 'tests', 'venv'] # fetch long description from readme with open(\"README.md\",",
"these wonderful methods to ._internal. Boo! from pip import __version__ as pip_version if",
"url=\"https://github.com/jlnerd/pyDSlib.git\", packages= setuptools.find_packages(exclude=exclude_dirs), include_package_data=True, scripts=scripts, setup_requires=[\"pep8\", \"setuptools>=30\"], dependency_links=[], #test_suite='ci_scripts.run_nose.run', #tests_require=['nose>=1.3.7', 'coverage'], zip_safe=False, install_requires=get_requirements(_determine_requirements_txt_location()),",
"from # your requirements.txt file but you need to have pip module available",
"os import re import codecs here = os.path.abspath(os.path.dirname(__file__)) def read(*parts): with codecs.open(os.path.join(here, *parts),",
"noqa: E731 else: # We're in the bold new future of using internals...",
"# your requirements.txt file but you need to have pip module available install_reqs",
"# pip v1.5 started requiring the 'session' # pip v10.0.0 moved these wonderful",
"path to the pip requirements file. Examples: ['django==1.5.1', 'mezzanine==1.4.6'] Returns: List[str]: the list",
"= os.path.abspath(os.path.dirname(__file__)) def read(*parts): with codecs.open(os.path.join(here, *parts), 'r') as fp: return fp.read() def",
"pip.req import parse_requirements from pip.download import PipSession do_parse = lambda path: parse_requirements(path, session=PipSession())",
"from pip.download import PipSession do_parse = lambda path: parse_requirements(path, session=PipSession()) # noqa: E731",
"in the bold new future of using internals... yeah from pip._internal.req import parse_requirements",
"# noqa: E731 # Cool trick to automatically pull in install_requires values directly",
"#fetch scripts try: scripts = ['scripts/%s' % f for f in os.listdir('scripts') if",
"as pip_version if LooseVersion(pip_version) < LooseVersion('1.5'): from pip.req import parse_requirements do_parse = lambda",
"codecs here = os.path.abspath(os.path.dirname(__file__)) def read(*parts): with codecs.open(os.path.join(here, *parts), 'r') as fp: return",
"return [str(ir.req) for ir in install_reqs] def _determine_requirements_txt_location(): this_dir = Path(__file__).parent if Path(this_dir,",
"values directly from # your requirements.txt file but you need to have pip",
"We're in the bold new future of using internals... yeah from pip._internal.req import",
"README, long_description_content_type=\"text/markdown\", url=\"https://github.com/jlnerd/pyDSlib.git\", packages= setuptools.find_packages(exclude=exclude_dirs), include_package_data=True, scripts=scripts, setup_requires=[\"pep8\", \"setuptools>=30\"], dependency_links=[], #test_suite='ci_scripts.run_nose.run', #tests_require=['nose>=1.3.7', 'coverage'],",
"'r') as fp: return fp.read() def find_version(*file_paths): version_file = read(*file_paths) version_match = re.search(r\"^__version__",
"string.\") def get_requirements(requirements='requirements.txt'): \"\"\"Get the list of requirements from the pip `requirements` file.",
"raise FileExistsError('Unable to find a requirements.txt file') #define directories to exclude from setup",
"wonderful methods to ._internal. Boo! from pip import __version__ as pip_version if LooseVersion(pip_version)",
"os.listdir('scripts') if f != \"dummy.py\"] except OSError: scripts = [] setuptools.setup( name =",
"do_parse = lambda path: parse_requirements(path) # noqa: E731 elif LooseVersion(pip_version) < LooseVersion('10.0.0'): from",
"= ['\\\"]([^'\\\"]*)['\\\"]\", version_file, re.M) if version_match: return version_match.group(1) raise RuntimeError(\"Unable to find version",
"Cool trick to automatically pull in install_requires values directly from # your requirements.txt",
"find_version('pyDSlib', '__init__.py'), author=\"<NAME>\", author_email=\"<EMAIL>\", description='General utilities to streamline data science and machine learning",
"find version string.\") def get_requirements(requirements='requirements.txt'): \"\"\"Get the list of requirements from the pip",
"LooseVersion('1.5'): from pip.req import parse_requirements do_parse = lambda path: parse_requirements(path) # noqa: E731",
"import parse_requirements from pip._internal.download import PipSession do_parse = lambda path: parse_requirements(path, session=PipSession()) #",
"machine learning routines in python', long_description= README, long_description_content_type=\"text/markdown\", url=\"https://github.com/jlnerd/pyDSlib.git\", packages= setuptools.find_packages(exclude=exclude_dirs), include_package_data=True, scripts=scripts,",
"import LooseVersion from pathlib import Path import os import re import codecs here",
"of requirements \"\"\" # pip v1.5 started requiring the 'session' # pip v10.0.0",
"['\\\"]([^'\\\"]*)['\\\"]\", version_file, re.M) if version_match: return version_match.group(1) raise RuntimeError(\"Unable to find version string.\")",
"pull in install_requires values directly from # your requirements.txt file but you need",
"raise RuntimeError(\"Unable to find version string.\") def get_requirements(requirements='requirements.txt'): \"\"\"Get the list of requirements",
"long_description_content_type=\"text/markdown\", url=\"https://github.com/jlnerd/pyDSlib.git\", packages= setuptools.find_packages(exclude=exclude_dirs), include_package_data=True, scripts=scripts, setup_requires=[\"pep8\", \"setuptools>=30\"], dependency_links=[], #test_suite='ci_scripts.run_nose.run', #tests_require=['nose>=1.3.7', 'coverage'], zip_safe=False,",
"'mezzanine==1.4.6'] Returns: List[str]: the list of requirements \"\"\" # pip v1.5 started requiring",
"routines in python', long_description= README, long_description_content_type=\"text/markdown\", url=\"https://github.com/jlnerd/pyDSlib.git\", packages= setuptools.find_packages(exclude=exclude_dirs), include_package_data=True, scripts=scripts, setup_requires=[\"pep8\", \"setuptools>=30\"],",
"= Path(__file__).parent if Path(this_dir, 'requirements.txt').exists(): return 'requirements.txt' elif Path(this_dir, 'pyDSlib.egg-info', 'requires.txt').exists(): return 'pyDSlib.egg-info/requires.txt'",
"return version_match.group(1) raise RuntimeError(\"Unable to find version string.\") def get_requirements(requirements='requirements.txt'): \"\"\"Get the list",
"to exclude from setup exclude_dirs = ['ez_setup', 'examples', 'tests', 'venv'] # fetch long",
"< LooseVersion('1.5'): from pip.req import parse_requirements do_parse = lambda path: parse_requirements(path) # noqa:",
"parse_requirements(path) # noqa: E731 elif LooseVersion(pip_version) < LooseVersion('10.0.0'): from pip.req import parse_requirements from",
"# pip v10.0.0 moved these wonderful methods to ._internal. Boo! from pip import",
"parse_requirements(path, session=PipSession()) # noqa: E731 # Cool trick to automatically pull in install_requires",
"__version__ as pip_version if LooseVersion(pip_version) < LooseVersion('1.5'): from pip.req import parse_requirements do_parse =",
"author_email=\"<EMAIL>\", description='General utilities to streamline data science and machine learning routines in python',",
"= fh.read() #fetch scripts try: scripts = ['scripts/%s' % f for f in",
"do_parse = lambda path: parse_requirements(path, session=PipSession()) # noqa: E731 # Cool trick to",
"< LooseVersion('10.0.0'): from pip.req import parse_requirements from pip.download import PipSession do_parse = lambda",
"with open(\"README.md\", \"r\") as fh: README = fh.read() #fetch scripts try: scripts =",
"return 'requirements.txt' elif Path(this_dir, 'pyDSlib.egg-info', 'requires.txt').exists(): return 'pyDSlib.egg-info/requires.txt' else: raise FileExistsError('Unable to find",
"session=PipSession()) # noqa: E731 # Cool trick to automatically pull in install_requires values",
"Examples: ['django==1.5.1', 'mezzanine==1.4.6'] Returns: List[str]: the list of requirements \"\"\" # pip v1.5",
"list of requirements \"\"\" # pip v1.5 started requiring the 'session' # pip",
"pip v1.5 started requiring the 'session' # pip v10.0.0 moved these wonderful methods",
"find_version(*file_paths): version_file = read(*file_paths) version_match = re.search(r\"^__version__ = ['\\\"]([^'\\\"]*)['\\\"]\", version_file, re.M) if version_match:",
"requirements)) return [str(ir.req) for ir in install_reqs] def _determine_requirements_txt_location(): this_dir = Path(__file__).parent if",
"\"r\") as fh: README = fh.read() #fetch scripts try: scripts = ['scripts/%s' %",
"pip._internal.req import parse_requirements from pip._internal.download import PipSession do_parse = lambda path: parse_requirements(path, session=PipSession())",
"'examples', 'tests', 'venv'] # fetch long description from readme with open(\"README.md\", \"r\") as",
"\"dummy.py\"] except OSError: scripts = [] setuptools.setup( name = 'pyDSlib', version= find_version('pyDSlib', '__init__.py'),",
"from pip import __version__ as pip_version if LooseVersion(pip_version) < LooseVersion('1.5'): from pip.req import",
"file but you need to have pip module available install_reqs = do_parse(os.path.join(here, requirements))",
"description='General utilities to streamline data science and machine learning routines in python', long_description=",
"requirements from the pip `requirements` file. Args: requirements (str): path to the pip",
"version= find_version('pyDSlib', '__init__.py'), author=\"<NAME>\", author_email=\"<EMAIL>\", description='General utilities to streamline data science and machine",
"(str): path to the pip requirements file. Examples: ['django==1.5.1', 'mezzanine==1.4.6'] Returns: List[str]: the",
"as fp: return fp.read() def find_version(*file_paths): version_file = read(*file_paths) version_match = re.search(r\"^__version__ =",
"in os.listdir('scripts') if f != \"dummy.py\"] except OSError: scripts = [] setuptools.setup( name"
] |
[
"import template from tos.models import CGUItem register = template.Library() @register.simple_tag def get_cgu_items(): return",
"from django import template from tos.models import CGUItem register = template.Library() @register.simple_tag def",
"template from tos.models import CGUItem register = template.Library() @register.simple_tag def get_cgu_items(): return CGUItem.objects.filter(deleted_at__isnull=True)",
"django import template from tos.models import CGUItem register = template.Library() @register.simple_tag def get_cgu_items():"
] |
[
"В/с\") print(\"Stage %i: Low pass filtering\" % stage) pyglobus.dsp.low_pass_filter(y, LOW_PASS_CUTOFF, SIGNAL_SAMPLING_RATE) plot(x, y,",
"print(\"Stage %i: High pass filtering\" % stage) pyglobus.dsp.high_pass_filter(y, HIGH_PASS_CUTOFF, SIGNAL_SAMPLING_RATE) plot(x, y, \"Время,",
"to PNG file def plot(x, y, label_x, label_y, color=\"k\", new_fig=True, flush=True): global stage",
"y = np.abs(y) plot(x, y, \"Время, с\", \"|U'|, В/с\") print(\"Stage %i: Low pass",
"HIGH_PASS_CUTOFF = 400 SMOOTHED_DD1_ORDER = 30 LOW_PASS_CUTOFF = 5000 SAWTOOTH_DETECTION_THRESHOLD = 0.0005 ROI_DETECTOR_MEAN_SCALE",
"%i: Data loading\" % stage) sht_reader = pyglobus.util.ShtReader(SHT_FILE) signal = sht_reader.get_signal(NUM_SIGNAL_FROM_SHT) data =",
"y = pyglobus.dsp.first_order_diff_filter(y, SMOOTHED_DD1_ORDER) plot(x, y, \"Время, с\", \"U', В/с\") print(\"Stage %i: Taking",
"stage) y = np.abs(y) plot(x, y, \"Время, с\", \"|U'|, В/с\") print(\"Stage %i: Low",
"new_fig: plt.figure(figsize=(15, 10)) plt.plot(x, y, color) plt.xlabel(label_x, fontsize=25) plt.ylabel(label_y, fontsize=25) if flush: out",
"SMOOTHED_DD1_ORDER) plot(x, y, \"Время, с\", \"U', В/с\") print(\"Stage %i: Taking absolute value\" %",
"absolute value\" % stage) y = np.abs(y) plot(x, y, \"Время, с\", \"|U'|, В/с\")",
"% pyglobus_root) sys.exit(1) output_dir = os.path.join(current_dir, \"output\", \"sawtooth_detection\") ######################## # ALGORITHM PARAMETERS #",
"print(\"Stage %i: Low pass filtering\" % stage) pyglobus.dsp.low_pass_filter(y, LOW_PASS_CUTOFF, SIGNAL_SAMPLING_RATE) plot(x, y, \"Время,",
"from base import get_globus_version pyglobus_root = os.path.join(current_dir, \"../../..\", \"_stage-%s\" % get_globus_version(), \"python\") sys.path.append(pyglobus_root)",
"value\" % stage) y = np.abs(y) plot(x, y, \"Время, с\", \"|U'|, В/с\") print(\"Stage",
"data[1], \"Время, с\", \"U, В\") print(\"Stage %i: ROI extracting\" % stage) roi =",
"len(x), \"Время, с\", \"|U'|, В/с\", color=\"r\", new_fig=False) print(\"Stage %i: Sawtooth detection\" % stage)",
"В\") print(\"Stage %i: ROI extracting\" % stage) roi = pyglobus.sawtooth.get_signal_roi(data[1], mean_scale=1) x =",
"stage) pyglobus.dsp.high_pass_filter(y, HIGH_PASS_CUTOFF, SIGNAL_SAMPLING_RATE) plot(x, y, \"Время, с\", \"U, В\") print(\"Stage %i: Smoothed",
"\"|U'|, В/с\") print(\"Stage %i: Low pass filtering\" % stage) pyglobus.dsp.low_pass_filter(y, LOW_PASS_CUTOFF, SIGNAL_SAMPLING_RATE) plot(x,",
"os.makedirs(output_dir, exist_ok=True) print(\"Stage %i: Data loading\" % stage) sht_reader = pyglobus.util.ShtReader(SHT_FILE) signal =",
"= os.path.dirname(os.path.abspath(__file__)) sys.path.append(os.path.join(current_dir, \"../../../tools\")) from base import get_globus_version pyglobus_root = os.path.join(current_dir, \"../../..\", \"_stage-%s\"",
"pyglobus from %s, exiting\" % pyglobus_root) sys.exit(1) output_dir = os.path.join(current_dir, \"output\", \"sawtooth_detection\") ########################",
"stage) sht_reader = pyglobus.util.ShtReader(SHT_FILE) signal = sht_reader.get_signal(NUM_SIGNAL_FROM_SHT) data = np.array((signal.get_data_x(), signal.get_data_y())) print(\"Loaded %s\"",
"np.copy(data[1, roi[0]:roi[1]]) plot(x, y, \"Время, с\", \"U, В\") print(\"Stage %i: High pass filtering\"",
"y, \"Время, с\", \"|U'|, В/с\", flush=False) plot(x, [SAWTOOTH_DETECTION_THRESHOLD] * len(x), \"Время, с\", \"|U'|,",
"pyglobus.sawtooth.get_signal_roi(data[1], mean_scale=1) x = np.copy(data[0, roi[0]:roi[1]]) y = np.copy(data[1, roi[0]:roi[1]]) plot(x, y, \"Время,",
"##################### stage = 0 current_dir = os.path.dirname(os.path.abspath(__file__)) sys.path.append(os.path.join(current_dir, \"../../../tools\")) from base import get_globus_version",
"print(\"Stage %i: Smoothed differentiation\" % stage) y = pyglobus.dsp.first_order_diff_filter(y, SMOOTHED_DD1_ORDER) plot(x, y, \"Время,",
"SHT_FILE) plot(data[0], data[1], \"Время, с\", \"U, В\") print(\"Stage %i: ROI extracting\" % stage)",
"import matplotlib.pyplot as plt import sys ##################### # SCRIPT PARAMETERS # ##################### stage",
"pyglobus.dsp.low_pass_filter(y, LOW_PASS_CUTOFF, SIGNAL_SAMPLING_RATE) plot(x, y, \"Время, с\", \"|U'|, В/с\", flush=False) plot(x, [SAWTOOTH_DETECTION_THRESHOLD] *",
"plt.plot(x, y, color) plt.xlabel(label_x, fontsize=25) plt.ylabel(label_y, fontsize=25) if flush: out = os.path.join(output_dir, \"#%i.png\"",
"import numpy as np import os import matplotlib.pyplot as plt import sys #####################",
"= os.path.join(current_dir, \"output\", \"sawtooth_detection\") ######################## # ALGORITHM PARAMETERS # ######################## SHT_FILE = \"../../../data/test/sht-reader/sht38515.sht\"",
"%i result:\" % stage, out) stage += 1 if __name__ == \"__main__\": font",
"% stage, out) stage += 1 if __name__ == \"__main__\": font = {\"size\":",
"roi[0]:roi[1]]) plot(x, y, \"Время, с\", \"U, В\") print(\"Stage %i: High pass filtering\" %",
"plot(x, y, \"Время, с\", \"U, В\") print(\"Stage %i: High pass filtering\" % stage)",
"except ImportError as e: print(\"Cannot import pyglobus from %s, exiting\" % pyglobus_root) sys.exit(1)",
"sys.exit(1) output_dir = os.path.join(current_dir, \"output\", \"sawtooth_detection\") ######################## # ALGORITHM PARAMETERS # ######################## SHT_FILE",
"if new_fig: plt.figure(figsize=(15, 10)) plt.plot(x, y, color) plt.xlabel(label_x, fontsize=25) plt.ylabel(label_y, fontsize=25) if flush:",
"filtering\" % stage) pyglobus.dsp.high_pass_filter(y, HIGH_PASS_CUTOFF, SIGNAL_SAMPLING_RATE) plot(x, y, \"Время, с\", \"U, В\") print(\"Stage",
"= 1 NUM_SIGNAL_FROM_SHT = 26 #################### # HELPER FUNCTIONS # #################### # Plotting",
"y, \"Время, с\", \"U', В/с\") print(\"Stage %i: Taking absolute value\" % stage) y",
"sample_data and saving it to PNG file def plot(x, y, label_x, label_y, color=\"k\",",
"pyglobus_root) sys.exit(1) output_dir = os.path.join(current_dir, \"output\", \"sawtooth_detection\") ######################## # ALGORITHM PARAMETERS # ########################",
"plt.figure(figsize=(15, 10)) plt.plot(x, y, color) plt.xlabel(label_x, fontsize=25) plt.ylabel(label_y, fontsize=25) if flush: out =",
"sht_reader.get_signal(NUM_SIGNAL_FROM_SHT) data = np.array((signal.get_data_x(), signal.get_data_y())) print(\"Loaded %s\" % SHT_FILE) plot(data[0], data[1], \"Время, с\",",
"color) plt.xlabel(label_x, fontsize=25) plt.ylabel(label_y, fontsize=25) if flush: out = os.path.join(output_dir, \"#%i.png\" % stage)",
"= {\"size\": 22} plt.rc(\"font\", **font) os.makedirs(output_dir, exist_ok=True) print(\"Stage %i: Data loading\" % stage)",
"exist_ok=True) print(\"Stage %i: Data loading\" % stage) sht_reader = pyglobus.util.ShtReader(SHT_FILE) signal = sht_reader.get_signal(NUM_SIGNAL_FROM_SHT)",
"\"Время, с\", \"|U'|, В/с\") print(\"Stage %i: Low pass filtering\" % stage) pyglobus.dsp.low_pass_filter(y, LOW_PASS_CUTOFF,",
"import os import matplotlib.pyplot as plt import sys ##################### # SCRIPT PARAMETERS #",
"\"|U'|, В/с\", flush=False) plot(x, [SAWTOOTH_DETECTION_THRESHOLD] * len(x), \"Время, с\", \"|U'|, В/с\", color=\"r\", new_fig=False)",
"= pyglobus.sawtooth.get_sawtooth_indexes(y, SAWTOOTH_DETECTION_THRESHOLD) plt.figure(figsize=(15, 10)) plt.axvline(x[start_ind], color=\"r\") plt.axvline(x[end_ind], color=\"r\") plot(data[0], data[1], \"Время, с\",",
"= int(1e6) HIGH_PASS_CUTOFF = 400 SMOOTHED_DD1_ORDER = 30 LOW_PASS_CUTOFF = 5000 SAWTOOTH_DETECTION_THRESHOLD =",
"extracting\" % stage) roi = pyglobus.sawtooth.get_signal_roi(data[1], mean_scale=1) x = np.copy(data[0, roi[0]:roi[1]]) y =",
"pyglobus.sawtooth.get_sawtooth_indexes(y, SAWTOOTH_DETECTION_THRESHOLD) plt.figure(figsize=(15, 10)) plt.axvline(x[start_ind], color=\"r\") plt.axvline(x[end_ind], color=\"r\") plot(data[0], data[1], \"Время, с\", \"U,",
"signal = sht_reader.get_signal(NUM_SIGNAL_FROM_SHT) data = np.array((signal.get_data_x(), signal.get_data_y())) print(\"Loaded %s\" % SHT_FILE) plot(data[0], data[1],",
"= os.path.join(current_dir, \"../../..\", \"_stage-%s\" % get_globus_version(), \"python\") sys.path.append(pyglobus_root) try: import pyglobus except ImportError",
"plot(x, y, \"Время, с\", \"|U'|, В/с\") print(\"Stage %i: Low pass filtering\" % stage)",
"np import os import matplotlib.pyplot as plt import sys ##################### # SCRIPT PARAMETERS",
"% stage) y = pyglobus.dsp.first_order_diff_filter(y, SMOOTHED_DD1_ORDER) plot(x, y, \"Время, с\", \"U', В/с\") print(\"Stage",
"print(\"Stage %i: Data loading\" % stage) sht_reader = pyglobus.util.ShtReader(SHT_FILE) signal = sht_reader.get_signal(NUM_SIGNAL_FROM_SHT) data",
"% stage) start_ind, end_ind = pyglobus.sawtooth.get_sawtooth_indexes(y, SAWTOOTH_DETECTION_THRESHOLD) plt.figure(figsize=(15, 10)) plt.axvline(x[start_ind], color=\"r\") plt.axvline(x[end_ind], color=\"r\")",
"% stage) roi = pyglobus.sawtooth.get_signal_roi(data[1], mean_scale=1) x = np.copy(data[0, roi[0]:roi[1]]) y = np.copy(data[1,",
"roi = pyglobus.sawtooth.get_signal_roi(data[1], mean_scale=1) x = np.copy(data[0, roi[0]:roi[1]]) y = np.copy(data[1, roi[0]:roi[1]]) plot(x,",
"[SAWTOOTH_DETECTION_THRESHOLD] * len(x), \"Время, с\", \"|U'|, В/с\", color=\"r\", new_fig=False) print(\"Stage %i: Sawtooth detection\"",
"+= 1 if __name__ == \"__main__\": font = {\"size\": 22} plt.rc(\"font\", **font) os.makedirs(output_dir,",
"y, \"Время, с\", \"U, В\") print(\"Stage %i: Smoothed differentiation\" % stage) y =",
"%i: High pass filtering\" % stage) pyglobus.dsp.high_pass_filter(y, HIGH_PASS_CUTOFF, SIGNAL_SAMPLING_RATE) plot(x, y, \"Время, с\",",
"sys.path.append(pyglobus_root) try: import pyglobus except ImportError as e: print(\"Cannot import pyglobus from %s,",
"# ##################### stage = 0 current_dir = os.path.dirname(os.path.abspath(__file__)) sys.path.append(os.path.join(current_dir, \"../../../tools\")) from base import",
"label_y, color=\"k\", new_fig=True, flush=True): global stage if new_fig: plt.figure(figsize=(15, 10)) plt.plot(x, y, color)",
"plt.xlabel(label_x, fontsize=25) plt.ylabel(label_y, fontsize=25) if flush: out = os.path.join(output_dir, \"#%i.png\" % stage) plt.savefig(out)",
"SAWTOOTH_DETECTION_THRESHOLD) plt.figure(figsize=(15, 10)) plt.axvline(x[start_ind], color=\"r\") plt.axvline(x[end_ind], color=\"r\") plot(data[0], data[1], \"Время, с\", \"U, В\",",
"print(\"Stage %i: Taking absolute value\" % stage) y = np.abs(y) plot(x, y, \"Время,",
"plt.ylabel(label_y, fontsize=25) if flush: out = os.path.join(output_dir, \"#%i.png\" % stage) plt.savefig(out) print(\"Stage %i",
"if __name__ == \"__main__\": font = {\"size\": 22} plt.rc(\"font\", **font) os.makedirs(output_dir, exist_ok=True) print(\"Stage",
"data = np.array((signal.get_data_x(), signal.get_data_y())) print(\"Loaded %s\" % SHT_FILE) plot(data[0], data[1], \"Время, с\", \"U,",
"flush: out = os.path.join(output_dir, \"#%i.png\" % stage) plt.savefig(out) print(\"Stage %i result:\" % stage,",
"%i: Smoothed differentiation\" % stage) y = pyglobus.dsp.first_order_diff_filter(y, SMOOTHED_DD1_ORDER) plot(x, y, \"Время, с\",",
"Taking absolute value\" % stage) y = np.abs(y) plot(x, y, \"Время, с\", \"|U'|,",
"pass filtering\" % stage) pyglobus.dsp.high_pass_filter(y, HIGH_PASS_CUTOFF, SIGNAL_SAMPLING_RATE) plot(x, y, \"Время, с\", \"U, В\")",
"import get_globus_version pyglobus_root = os.path.join(current_dir, \"../../..\", \"_stage-%s\" % get_globus_version(), \"python\") sys.path.append(pyglobus_root) try: import",
"exiting\" % pyglobus_root) sys.exit(1) output_dir = os.path.join(current_dir, \"output\", \"sawtooth_detection\") ######################## # ALGORITHM PARAMETERS",
"**font) os.makedirs(output_dir, exist_ok=True) print(\"Stage %i: Data loading\" % stage) sht_reader = pyglobus.util.ShtReader(SHT_FILE) signal",
"print(\"Stage %i: Sawtooth detection\" % stage) start_ind, end_ind = pyglobus.sawtooth.get_sawtooth_indexes(y, SAWTOOTH_DETECTION_THRESHOLD) plt.figure(figsize=(15, 10))",
"Low pass filtering\" % stage) pyglobus.dsp.low_pass_filter(y, LOW_PASS_CUTOFF, SIGNAL_SAMPLING_RATE) plot(x, y, \"Время, с\", \"|U'|,",
"base import get_globus_version pyglobus_root = os.path.join(current_dir, \"../../..\", \"_stage-%s\" % get_globus_version(), \"python\") sys.path.append(pyglobus_root) try:",
"flush=True): global stage if new_fig: plt.figure(figsize=(15, 10)) plt.plot(x, y, color) plt.xlabel(label_x, fontsize=25) plt.ylabel(label_y,",
"color=\"k\", new_fig=True, flush=True): global stage if new_fig: plt.figure(figsize=(15, 10)) plt.plot(x, y, color) plt.xlabel(label_x,",
"as e: print(\"Cannot import pyglobus from %s, exiting\" % pyglobus_root) sys.exit(1) output_dir =",
"== \"__main__\": font = {\"size\": 22} plt.rc(\"font\", **font) os.makedirs(output_dir, exist_ok=True) print(\"Stage %i: Data",
"В\") print(\"Stage %i: Smoothed differentiation\" % stage) y = pyglobus.dsp.first_order_diff_filter(y, SMOOTHED_DD1_ORDER) plot(x, y,",
"%i: Low pass filtering\" % stage) pyglobus.dsp.low_pass_filter(y, LOW_PASS_CUTOFF, SIGNAL_SAMPLING_RATE) plot(x, y, \"Время, с\",",
"= 400 SMOOTHED_DD1_ORDER = 30 LOW_PASS_CUTOFF = 5000 SAWTOOTH_DETECTION_THRESHOLD = 0.0005 ROI_DETECTOR_MEAN_SCALE =",
"\"Время, с\", \"U, В\") print(\"Stage %i: High pass filtering\" % stage) pyglobus.dsp.high_pass_filter(y, HIGH_PASS_CUTOFF,",
"\"../../../data/test/sht-reader/sht38515.sht\" SIGNAL_SAMPLING_RATE = int(1e6) HIGH_PASS_CUTOFF = 400 SMOOTHED_DD1_ORDER = 30 LOW_PASS_CUTOFF = 5000",
"new_fig=False) print(\"Stage %i: Sawtooth detection\" % stage) start_ind, end_ind = pyglobus.sawtooth.get_sawtooth_indexes(y, SAWTOOTH_DETECTION_THRESHOLD) plt.figure(figsize=(15,",
"1 NUM_SIGNAL_FROM_SHT = 26 #################### # HELPER FUNCTIONS # #################### # Plotting sample_data",
"if flush: out = os.path.join(output_dir, \"#%i.png\" % stage) plt.savefig(out) print(\"Stage %i result:\" %",
"%s\" % SHT_FILE) plot(data[0], data[1], \"Время, с\", \"U, В\") print(\"Stage %i: ROI extracting\"",
"%i: Taking absolute value\" % stage) y = np.abs(y) plot(x, y, \"Время, с\",",
"ROI extracting\" % stage) roi = pyglobus.sawtooth.get_signal_roi(data[1], mean_scale=1) x = np.copy(data[0, roi[0]:roi[1]]) y",
"30 LOW_PASS_CUTOFF = 5000 SAWTOOTH_DETECTION_THRESHOLD = 0.0005 ROI_DETECTOR_MEAN_SCALE = 1 NUM_SIGNAL_FROM_SHT = 26",
"font = {\"size\": 22} plt.rc(\"font\", **font) os.makedirs(output_dir, exist_ok=True) print(\"Stage %i: Data loading\" %",
"y, \"Время, с\", \"|U'|, В/с\") print(\"Stage %i: Low pass filtering\" % stage) pyglobus.dsp.low_pass_filter(y,",
"Plotting sample_data and saving it to PNG file def plot(x, y, label_x, label_y,",
"plot(x, y, label_x, label_y, color=\"k\", new_fig=True, flush=True): global stage if new_fig: plt.figure(figsize=(15, 10))",
"SAWTOOTH_DETECTION_THRESHOLD = 0.0005 ROI_DETECTOR_MEAN_SCALE = 1 NUM_SIGNAL_FROM_SHT = 26 #################### # HELPER FUNCTIONS",
"global stage if new_fig: plt.figure(figsize=(15, 10)) plt.plot(x, y, color) plt.xlabel(label_x, fontsize=25) plt.ylabel(label_y, fontsize=25)",
"roi[0]:roi[1]]) y = np.copy(data[1, roi[0]:roi[1]]) plot(x, y, \"Время, с\", \"U, В\") print(\"Stage %i:",
"= np.array((signal.get_data_x(), signal.get_data_y())) print(\"Loaded %s\" % SHT_FILE) plot(data[0], data[1], \"Время, с\", \"U, В\")",
"= 26 #################### # HELPER FUNCTIONS # #################### # Plotting sample_data and saving",
"saving it to PNG file def plot(x, y, label_x, label_y, color=\"k\", new_fig=True, flush=True):",
"PNG file def plot(x, y, label_x, label_y, color=\"k\", new_fig=True, flush=True): global stage if",
"с\", \"|U'|, В/с\", flush=False) plot(x, [SAWTOOTH_DETECTION_THRESHOLD] * len(x), \"Время, с\", \"|U'|, В/с\", color=\"r\",",
"= \"../../../data/test/sht-reader/sht38515.sht\" SIGNAL_SAMPLING_RATE = int(1e6) HIGH_PASS_CUTOFF = 400 SMOOTHED_DD1_ORDER = 30 LOW_PASS_CUTOFF =",
"SHT_FILE = \"../../../data/test/sht-reader/sht38515.sht\" SIGNAL_SAMPLING_RATE = int(1e6) HIGH_PASS_CUTOFF = 400 SMOOTHED_DD1_ORDER = 30 LOW_PASS_CUTOFF",
"plt.figure(figsize=(15, 10)) plt.axvline(x[start_ind], color=\"r\") plt.axvline(x[end_ind], color=\"r\") plot(data[0], data[1], \"Время, с\", \"U, В\", new_fig=False)",
"%i: ROI extracting\" % stage) roi = pyglobus.sawtooth.get_signal_roi(data[1], mean_scale=1) x = np.copy(data[0, roi[0]:roi[1]])",
"= 30 LOW_PASS_CUTOFF = 5000 SAWTOOTH_DETECTION_THRESHOLD = 0.0005 ROI_DETECTOR_MEAN_SCALE = 1 NUM_SIGNAL_FROM_SHT =",
"SIGNAL_SAMPLING_RATE) plot(x, y, \"Время, с\", \"|U'|, В/с\", flush=False) plot(x, [SAWTOOTH_DETECTION_THRESHOLD] * len(x), \"Время,",
"с\", \"U', В/с\") print(\"Stage %i: Taking absolute value\" % stage) y = np.abs(y)",
"\"Время, с\", \"|U'|, В/с\", color=\"r\", new_fig=False) print(\"Stage %i: Sawtooth detection\" % stage) start_ind,",
"stage if new_fig: plt.figure(figsize=(15, 10)) plt.plot(x, y, color) plt.xlabel(label_x, fontsize=25) plt.ylabel(label_y, fontsize=25) if",
"FUNCTIONS # #################### # Plotting sample_data and saving it to PNG file def",
"% stage) pyglobus.dsp.low_pass_filter(y, LOW_PASS_CUTOFF, SIGNAL_SAMPLING_RATE) plot(x, y, \"Время, с\", \"|U'|, В/с\", flush=False) plot(x,",
"0 current_dir = os.path.dirname(os.path.abspath(__file__)) sys.path.append(os.path.join(current_dir, \"../../../tools\")) from base import get_globus_version pyglobus_root = os.path.join(current_dir,",
"matplotlib.pyplot as plt import sys ##################### # SCRIPT PARAMETERS # ##################### stage =",
"##################### # SCRIPT PARAMETERS # ##################### stage = 0 current_dir = os.path.dirname(os.path.abspath(__file__)) sys.path.append(os.path.join(current_dir,",
"\"python\") sys.path.append(pyglobus_root) try: import pyglobus except ImportError as e: print(\"Cannot import pyglobus from",
"plt.rc(\"font\", **font) os.makedirs(output_dir, exist_ok=True) print(\"Stage %i: Data loading\" % stage) sht_reader = pyglobus.util.ShtReader(SHT_FILE)",
"% stage) sht_reader = pyglobus.util.ShtReader(SHT_FILE) signal = sht_reader.get_signal(NUM_SIGNAL_FROM_SHT) data = np.array((signal.get_data_x(), signal.get_data_y())) print(\"Loaded",
"\"U, В\") print(\"Stage %i: High pass filtering\" % stage) pyglobus.dsp.high_pass_filter(y, HIGH_PASS_CUTOFF, SIGNAL_SAMPLING_RATE) plot(x,",
"pyglobus.dsp.high_pass_filter(y, HIGH_PASS_CUTOFF, SIGNAL_SAMPLING_RATE) plot(x, y, \"Время, с\", \"U, В\") print(\"Stage %i: Smoothed differentiation\"",
"\"U, В\") print(\"Stage %i: Smoothed differentiation\" % stage) y = pyglobus.dsp.first_order_diff_filter(y, SMOOTHED_DD1_ORDER) plot(x,",
"= np.abs(y) plot(x, y, \"Время, с\", \"|U'|, В/с\") print(\"Stage %i: Low pass filtering\"",
"pass filtering\" % stage) pyglobus.dsp.low_pass_filter(y, LOW_PASS_CUTOFF, SIGNAL_SAMPLING_RATE) plot(x, y, \"Время, с\", \"|U'|, В/с\",",
"stage) start_ind, end_ind = pyglobus.sawtooth.get_sawtooth_indexes(y, SAWTOOTH_DETECTION_THRESHOLD) plt.figure(figsize=(15, 10)) plt.axvline(x[start_ind], color=\"r\") plt.axvline(x[end_ind], color=\"r\") plot(data[0],",
"22} plt.rc(\"font\", **font) os.makedirs(output_dir, exist_ok=True) print(\"Stage %i: Data loading\" % stage) sht_reader =",
"# ALGORITHM PARAMETERS # ######################## SHT_FILE = \"../../../data/test/sht-reader/sht38515.sht\" SIGNAL_SAMPLING_RATE = int(1e6) HIGH_PASS_CUTOFF =",
"fontsize=25) if flush: out = os.path.join(output_dir, \"#%i.png\" % stage) plt.savefig(out) print(\"Stage %i result:\"",
"sys ##################### # SCRIPT PARAMETERS # ##################### stage = 0 current_dir = os.path.dirname(os.path.abspath(__file__))",
"try: import pyglobus except ImportError as e: print(\"Cannot import pyglobus from %s, exiting\"",
"10)) plt.axvline(x[start_ind], color=\"r\") plt.axvline(x[end_ind], color=\"r\") plot(data[0], data[1], \"Время, с\", \"U, В\", new_fig=False) print(\"Done!\")",
"= sht_reader.get_signal(NUM_SIGNAL_FROM_SHT) data = np.array((signal.get_data_x(), signal.get_data_y())) print(\"Loaded %s\" % SHT_FILE) plot(data[0], data[1], \"Время,",
"color=\"r\", new_fig=False) print(\"Stage %i: Sawtooth detection\" % stage) start_ind, end_ind = pyglobus.sawtooth.get_sawtooth_indexes(y, SAWTOOTH_DETECTION_THRESHOLD)",
"NUM_SIGNAL_FROM_SHT = 26 #################### # HELPER FUNCTIONS # #################### # Plotting sample_data and",
"с\", \"|U'|, В/с\") print(\"Stage %i: Low pass filtering\" % stage) pyglobus.dsp.low_pass_filter(y, LOW_PASS_CUTOFF, SIGNAL_SAMPLING_RATE)",
"from %s, exiting\" % pyglobus_root) sys.exit(1) output_dir = os.path.join(current_dir, \"output\", \"sawtooth_detection\") ######################## #",
"get_globus_version(), \"python\") sys.path.append(pyglobus_root) try: import pyglobus except ImportError as e: print(\"Cannot import pyglobus",
"с\", \"|U'|, В/с\", color=\"r\", new_fig=False) print(\"Stage %i: Sawtooth detection\" % stage) start_ind, end_ind",
"stage) pyglobus.dsp.low_pass_filter(y, LOW_PASS_CUTOFF, SIGNAL_SAMPLING_RATE) plot(x, y, \"Время, с\", \"|U'|, В/с\", flush=False) plot(x, [SAWTOOTH_DETECTION_THRESHOLD]",
"######################## SHT_FILE = \"../../../data/test/sht-reader/sht38515.sht\" SIGNAL_SAMPLING_RATE = int(1e6) HIGH_PASS_CUTOFF = 400 SMOOTHED_DD1_ORDER = 30",
"с\", \"U, В\") print(\"Stage %i: Smoothed differentiation\" % stage) y = pyglobus.dsp.first_order_diff_filter(y, SMOOTHED_DD1_ORDER)",
"sys.path.append(os.path.join(current_dir, \"../../../tools\")) from base import get_globus_version pyglobus_root = os.path.join(current_dir, \"../../..\", \"_stage-%s\" % get_globus_version(),",
"output_dir = os.path.join(current_dir, \"output\", \"sawtooth_detection\") ######################## # ALGORITHM PARAMETERS # ######################## SHT_FILE =",
"stage, out) stage += 1 if __name__ == \"__main__\": font = {\"size\": 22}",
"PARAMETERS # ######################## SHT_FILE = \"../../../data/test/sht-reader/sht38515.sht\" SIGNAL_SAMPLING_RATE = int(1e6) HIGH_PASS_CUTOFF = 400 SMOOTHED_DD1_ORDER",
"5000 SAWTOOTH_DETECTION_THRESHOLD = 0.0005 ROI_DETECTOR_MEAN_SCALE = 1 NUM_SIGNAL_FROM_SHT = 26 #################### # HELPER",
"ImportError as e: print(\"Cannot import pyglobus from %s, exiting\" % pyglobus_root) sys.exit(1) output_dir",
"file def plot(x, y, label_x, label_y, color=\"k\", new_fig=True, flush=True): global stage if new_fig:",
"= 0.0005 ROI_DETECTOR_MEAN_SCALE = 1 NUM_SIGNAL_FROM_SHT = 26 #################### # HELPER FUNCTIONS #",
"__name__ == \"__main__\": font = {\"size\": 22} plt.rc(\"font\", **font) os.makedirs(output_dir, exist_ok=True) print(\"Stage %i:",
"% get_globus_version(), \"python\") sys.path.append(pyglobus_root) try: import pyglobus except ImportError as e: print(\"Cannot import",
"e: print(\"Cannot import pyglobus from %s, exiting\" % pyglobus_root) sys.exit(1) output_dir = os.path.join(current_dir,",
"def plot(x, y, label_x, label_y, color=\"k\", new_fig=True, flush=True): global stage if new_fig: plt.figure(figsize=(15,",
"sht_reader = pyglobus.util.ShtReader(SHT_FILE) signal = sht_reader.get_signal(NUM_SIGNAL_FROM_SHT) data = np.array((signal.get_data_x(), signal.get_data_y())) print(\"Loaded %s\" %",
"os.path.join(output_dir, \"#%i.png\" % stage) plt.savefig(out) print(\"Stage %i result:\" % stage, out) stage +=",
"Smoothed differentiation\" % stage) y = pyglobus.dsp.first_order_diff_filter(y, SMOOTHED_DD1_ORDER) plot(x, y, \"Время, с\", \"U',",
"\"Время, с\", \"U', В/с\") print(\"Stage %i: Taking absolute value\" % stage) y =",
"SIGNAL_SAMPLING_RATE) plot(x, y, \"Время, с\", \"U, В\") print(\"Stage %i: Smoothed differentiation\" % stage)",
"plt import sys ##################### # SCRIPT PARAMETERS # ##################### stage = 0 current_dir",
"os.path.dirname(os.path.abspath(__file__)) sys.path.append(os.path.join(current_dir, \"../../../tools\")) from base import get_globus_version pyglobus_root = os.path.join(current_dir, \"../../..\", \"_stage-%s\" %",
"os.path.join(current_dir, \"../../..\", \"_stage-%s\" % get_globus_version(), \"python\") sys.path.append(pyglobus_root) try: import pyglobus except ImportError as",
"import pyglobus except ImportError as e: print(\"Cannot import pyglobus from %s, exiting\" %",
"% stage) plt.savefig(out) print(\"Stage %i result:\" % stage, out) stage += 1 if",
"plot(data[0], data[1], \"Время, с\", \"U, В\") print(\"Stage %i: ROI extracting\" % stage) roi",
"pyglobus.util.ShtReader(SHT_FILE) signal = sht_reader.get_signal(NUM_SIGNAL_FROM_SHT) data = np.array((signal.get_data_x(), signal.get_data_y())) print(\"Loaded %s\" % SHT_FILE) plot(data[0],",
"x = np.copy(data[0, roi[0]:roi[1]]) y = np.copy(data[1, roi[0]:roi[1]]) plot(x, y, \"Время, с\", \"U,",
"= np.copy(data[0, roi[0]:roi[1]]) y = np.copy(data[1, roi[0]:roi[1]]) plot(x, y, \"Время, с\", \"U, В\")",
"np.array((signal.get_data_x(), signal.get_data_y())) print(\"Loaded %s\" % SHT_FILE) plot(data[0], data[1], \"Время, с\", \"U, В\") print(\"Stage",
"\"U', В/с\") print(\"Stage %i: Taking absolute value\" % stage) y = np.abs(y) plot(x,",
"{\"size\": 22} plt.rc(\"font\", **font) os.makedirs(output_dir, exist_ok=True) print(\"Stage %i: Data loading\" % stage) sht_reader",
"LOW_PASS_CUTOFF, SIGNAL_SAMPLING_RATE) plot(x, y, \"Время, с\", \"|U'|, В/с\", flush=False) plot(x, [SAWTOOTH_DETECTION_THRESHOLD] * len(x),",
"%i: Sawtooth detection\" % stage) start_ind, end_ind = pyglobus.sawtooth.get_sawtooth_indexes(y, SAWTOOTH_DETECTION_THRESHOLD) plt.figure(figsize=(15, 10)) plt.axvline(x[start_ind],",
"stage = 0 current_dir = os.path.dirname(os.path.abspath(__file__)) sys.path.append(os.path.join(current_dir, \"../../../tools\")) from base import get_globus_version pyglobus_root",
"SIGNAL_SAMPLING_RATE = int(1e6) HIGH_PASS_CUTOFF = 400 SMOOTHED_DD1_ORDER = 30 LOW_PASS_CUTOFF = 5000 SAWTOOTH_DETECTION_THRESHOLD",
"y, color) plt.xlabel(label_x, fontsize=25) plt.ylabel(label_y, fontsize=25) if flush: out = os.path.join(output_dir, \"#%i.png\" %",
"out = os.path.join(output_dir, \"#%i.png\" % stage) plt.savefig(out) print(\"Stage %i result:\" % stage, out)",
"High pass filtering\" % stage) pyglobus.dsp.high_pass_filter(y, HIGH_PASS_CUTOFF, SIGNAL_SAMPLING_RATE) plot(x, y, \"Время, с\", \"U,",
"mean_scale=1) x = np.copy(data[0, roi[0]:roi[1]]) y = np.copy(data[1, roi[0]:roi[1]]) plot(x, y, \"Время, с\",",
"# HELPER FUNCTIONS # #################### # Plotting sample_data and saving it to PNG",
"10)) plt.plot(x, y, color) plt.xlabel(label_x, fontsize=25) plt.ylabel(label_y, fontsize=25) if flush: out = os.path.join(output_dir,",
"Data loading\" % stage) sht_reader = pyglobus.util.ShtReader(SHT_FILE) signal = sht_reader.get_signal(NUM_SIGNAL_FROM_SHT) data = np.array((signal.get_data_x(),",
"filtering\" % stage) pyglobus.dsp.low_pass_filter(y, LOW_PASS_CUTOFF, SIGNAL_SAMPLING_RATE) plot(x, y, \"Время, с\", \"|U'|, В/с\", flush=False)",
"pyglobus_root = os.path.join(current_dir, \"../../..\", \"_stage-%s\" % get_globus_version(), \"python\") sys.path.append(pyglobus_root) try: import pyglobus except",
"HIGH_PASS_CUTOFF, SIGNAL_SAMPLING_RATE) plot(x, y, \"Время, с\", \"U, В\") print(\"Stage %i: Smoothed differentiation\" %",
"\"sawtooth_detection\") ######################## # ALGORITHM PARAMETERS # ######################## SHT_FILE = \"../../../data/test/sht-reader/sht38515.sht\" SIGNAL_SAMPLING_RATE = int(1e6)",
"######################## # ALGORITHM PARAMETERS # ######################## SHT_FILE = \"../../../data/test/sht-reader/sht38515.sht\" SIGNAL_SAMPLING_RATE = int(1e6) HIGH_PASS_CUTOFF",
"#################### # Plotting sample_data and saving it to PNG file def plot(x, y,",
"as np import os import matplotlib.pyplot as plt import sys ##################### # SCRIPT",
"new_fig=True, flush=True): global stage if new_fig: plt.figure(figsize=(15, 10)) plt.plot(x, y, color) plt.xlabel(label_x, fontsize=25)",
"flush=False) plot(x, [SAWTOOTH_DETECTION_THRESHOLD] * len(x), \"Время, с\", \"|U'|, В/с\", color=\"r\", new_fig=False) print(\"Stage %i:",
"# SCRIPT PARAMETERS # ##################### stage = 0 current_dir = os.path.dirname(os.path.abspath(__file__)) sys.path.append(os.path.join(current_dir, \"../../../tools\"))",
"HELPER FUNCTIONS # #################### # Plotting sample_data and saving it to PNG file",
"int(1e6) HIGH_PASS_CUTOFF = 400 SMOOTHED_DD1_ORDER = 30 LOW_PASS_CUTOFF = 5000 SAWTOOTH_DETECTION_THRESHOLD = 0.0005",
"\"../../../tools\")) from base import get_globus_version pyglobus_root = os.path.join(current_dir, \"../../..\", \"_stage-%s\" % get_globus_version(), \"python\")",
"start_ind, end_ind = pyglobus.sawtooth.get_sawtooth_indexes(y, SAWTOOTH_DETECTION_THRESHOLD) plt.figure(figsize=(15, 10)) plt.axvline(x[start_ind], color=\"r\") plt.axvline(x[end_ind], color=\"r\") plot(data[0], data[1],",
"\"output\", \"sawtooth_detection\") ######################## # ALGORITHM PARAMETERS # ######################## SHT_FILE = \"../../../data/test/sht-reader/sht38515.sht\" SIGNAL_SAMPLING_RATE =",
"stage) plt.savefig(out) print(\"Stage %i result:\" % stage, out) stage += 1 if __name__",
"В\") print(\"Stage %i: High pass filtering\" % stage) pyglobus.dsp.high_pass_filter(y, HIGH_PASS_CUTOFF, SIGNAL_SAMPLING_RATE) plot(x, y,",
"y, label_x, label_y, color=\"k\", new_fig=True, flush=True): global stage if new_fig: plt.figure(figsize=(15, 10)) plt.plot(x,",
"\"|U'|, В/с\", color=\"r\", new_fig=False) print(\"Stage %i: Sawtooth detection\" % stage) start_ind, end_ind =",
"\"U, В\") print(\"Stage %i: ROI extracting\" % stage) roi = pyglobus.sawtooth.get_signal_roi(data[1], mean_scale=1) x",
"print(\"Stage %i: ROI extracting\" % stage) roi = pyglobus.sawtooth.get_signal_roi(data[1], mean_scale=1) x = np.copy(data[0,",
"LOW_PASS_CUTOFF = 5000 SAWTOOTH_DETECTION_THRESHOLD = 0.0005 ROI_DETECTOR_MEAN_SCALE = 1 NUM_SIGNAL_FROM_SHT = 26 ####################",
"signal.get_data_y())) print(\"Loaded %s\" % SHT_FILE) plot(data[0], data[1], \"Время, с\", \"U, В\") print(\"Stage %i:",
"print(\"Loaded %s\" % SHT_FILE) plot(data[0], data[1], \"Время, с\", \"U, В\") print(\"Stage %i: ROI",
"%s, exiting\" % pyglobus_root) sys.exit(1) output_dir = os.path.join(current_dir, \"output\", \"sawtooth_detection\") ######################## # ALGORITHM",
"pyglobus except ImportError as e: print(\"Cannot import pyglobus from %s, exiting\" % pyglobus_root)",
"SMOOTHED_DD1_ORDER = 30 LOW_PASS_CUTOFF = 5000 SAWTOOTH_DETECTION_THRESHOLD = 0.0005 ROI_DETECTOR_MEAN_SCALE = 1 NUM_SIGNAL_FROM_SHT",
"с\", \"U, В\") print(\"Stage %i: ROI extracting\" % stage) roi = pyglobus.sawtooth.get_signal_roi(data[1], mean_scale=1)",
"% SHT_FILE) plot(data[0], data[1], \"Время, с\", \"U, В\") print(\"Stage %i: ROI extracting\" %",
"= np.copy(data[1, roi[0]:roi[1]]) plot(x, y, \"Время, с\", \"U, В\") print(\"Stage %i: High pass",
"np.abs(y) plot(x, y, \"Время, с\", \"|U'|, В/с\") print(\"Stage %i: Low pass filtering\" %",
"* len(x), \"Время, с\", \"|U'|, В/с\", color=\"r\", new_fig=False) print(\"Stage %i: Sawtooth detection\" %",
"current_dir = os.path.dirname(os.path.abspath(__file__)) sys.path.append(os.path.join(current_dir, \"../../../tools\")) from base import get_globus_version pyglobus_root = os.path.join(current_dir, \"../../..\",",
"% stage) y = np.abs(y) plot(x, y, \"Время, с\", \"|U'|, В/с\") print(\"Stage %i:",
"SCRIPT PARAMETERS # ##################### stage = 0 current_dir = os.path.dirname(os.path.abspath(__file__)) sys.path.append(os.path.join(current_dir, \"../../../tools\")) from",
"plot(x, y, \"Время, с\", \"|U'|, В/с\", flush=False) plot(x, [SAWTOOTH_DETECTION_THRESHOLD] * len(x), \"Время, с\",",
"differentiation\" % stage) y = pyglobus.dsp.first_order_diff_filter(y, SMOOTHED_DD1_ORDER) plot(x, y, \"Время, с\", \"U', В/с\")",
"= pyglobus.dsp.first_order_diff_filter(y, SMOOTHED_DD1_ORDER) plot(x, y, \"Время, с\", \"U', В/с\") print(\"Stage %i: Taking absolute",
"= os.path.join(output_dir, \"#%i.png\" % stage) plt.savefig(out) print(\"Stage %i result:\" % stage, out) stage",
"<gh_stars>0 import numpy as np import os import matplotlib.pyplot as plt import sys",
"= 0 current_dir = os.path.dirname(os.path.abspath(__file__)) sys.path.append(os.path.join(current_dir, \"../../../tools\")) from base import get_globus_version pyglobus_root =",
"pyglobus.dsp.first_order_diff_filter(y, SMOOTHED_DD1_ORDER) plot(x, y, \"Время, с\", \"U', В/с\") print(\"Stage %i: Taking absolute value\"",
"В/с\", color=\"r\", new_fig=False) print(\"Stage %i: Sawtooth detection\" % stage) start_ind, end_ind = pyglobus.sawtooth.get_sawtooth_indexes(y,",
"# #################### # Plotting sample_data and saving it to PNG file def plot(x,",
"Sawtooth detection\" % stage) start_ind, end_ind = pyglobus.sawtooth.get_sawtooth_indexes(y, SAWTOOTH_DETECTION_THRESHOLD) plt.figure(figsize=(15, 10)) plt.axvline(x[start_ind], color=\"r\")",
"% stage) pyglobus.dsp.high_pass_filter(y, HIGH_PASS_CUTOFF, SIGNAL_SAMPLING_RATE) plot(x, y, \"Время, с\", \"U, В\") print(\"Stage %i:",
"stage) roi = pyglobus.sawtooth.get_signal_roi(data[1], mean_scale=1) x = np.copy(data[0, roi[0]:roi[1]]) y = np.copy(data[1, roi[0]:roi[1]])",
"os import matplotlib.pyplot as plt import sys ##################### # SCRIPT PARAMETERS # #####################",
"import sys ##################### # SCRIPT PARAMETERS # ##################### stage = 0 current_dir =",
"label_x, label_y, color=\"k\", new_fig=True, flush=True): global stage if new_fig: plt.figure(figsize=(15, 10)) plt.plot(x, y,",
"fontsize=25) plt.ylabel(label_y, fontsize=25) if flush: out = os.path.join(output_dir, \"#%i.png\" % stage) plt.savefig(out) print(\"Stage",
"26 #################### # HELPER FUNCTIONS # #################### # Plotting sample_data and saving it",
"\"#%i.png\" % stage) plt.savefig(out) print(\"Stage %i result:\" % stage, out) stage += 1",
"y, \"Время, с\", \"U, В\") print(\"Stage %i: High pass filtering\" % stage) pyglobus.dsp.high_pass_filter(y,",
"plot(x, [SAWTOOTH_DETECTION_THRESHOLD] * len(x), \"Время, с\", \"|U'|, В/с\", color=\"r\", new_fig=False) print(\"Stage %i: Sawtooth",
"ROI_DETECTOR_MEAN_SCALE = 1 NUM_SIGNAL_FROM_SHT = 26 #################### # HELPER FUNCTIONS # #################### #",
"end_ind = pyglobus.sawtooth.get_sawtooth_indexes(y, SAWTOOTH_DETECTION_THRESHOLD) plt.figure(figsize=(15, 10)) plt.axvline(x[start_ind], color=\"r\") plt.axvline(x[end_ind], color=\"r\") plot(data[0], data[1], \"Время,",
"400 SMOOTHED_DD1_ORDER = 30 LOW_PASS_CUTOFF = 5000 SAWTOOTH_DETECTION_THRESHOLD = 0.0005 ROI_DETECTOR_MEAN_SCALE = 1",
"plt.savefig(out) print(\"Stage %i result:\" % stage, out) stage += 1 if __name__ ==",
"and saving it to PNG file def plot(x, y, label_x, label_y, color=\"k\", new_fig=True,",
"print(\"Stage %i result:\" % stage, out) stage += 1 if __name__ == \"__main__\":",
"get_globus_version pyglobus_root = os.path.join(current_dir, \"../../..\", \"_stage-%s\" % get_globus_version(), \"python\") sys.path.append(pyglobus_root) try: import pyglobus",
"= pyglobus.sawtooth.get_signal_roi(data[1], mean_scale=1) x = np.copy(data[0, roi[0]:roi[1]]) y = np.copy(data[1, roi[0]:roi[1]]) plot(x, y,",
"as plt import sys ##################### # SCRIPT PARAMETERS # ##################### stage = 0",
"с\", \"U, В\") print(\"Stage %i: High pass filtering\" % stage) pyglobus.dsp.high_pass_filter(y, HIGH_PASS_CUTOFF, SIGNAL_SAMPLING_RATE)",
"\"../../..\", \"_stage-%s\" % get_globus_version(), \"python\") sys.path.append(pyglobus_root) try: import pyglobus except ImportError as e:",
"1 if __name__ == \"__main__\": font = {\"size\": 22} plt.rc(\"font\", **font) os.makedirs(output_dir, exist_ok=True)",
"= 5000 SAWTOOTH_DETECTION_THRESHOLD = 0.0005 ROI_DETECTOR_MEAN_SCALE = 1 NUM_SIGNAL_FROM_SHT = 26 #################### #",
"0.0005 ROI_DETECTOR_MEAN_SCALE = 1 NUM_SIGNAL_FROM_SHT = 26 #################### # HELPER FUNCTIONS # ####################",
"\"Время, с\", \"U, В\") print(\"Stage %i: Smoothed differentiation\" % stage) y = pyglobus.dsp.first_order_diff_filter(y,",
"np.copy(data[0, roi[0]:roi[1]]) y = np.copy(data[1, roi[0]:roi[1]]) plot(x, y, \"Время, с\", \"U, В\") print(\"Stage",
"it to PNG file def plot(x, y, label_x, label_y, color=\"k\", new_fig=True, flush=True): global",
"# ######################## SHT_FILE = \"../../../data/test/sht-reader/sht38515.sht\" SIGNAL_SAMPLING_RATE = int(1e6) HIGH_PASS_CUTOFF = 400 SMOOTHED_DD1_ORDER =",
"y = np.copy(data[1, roi[0]:roi[1]]) plot(x, y, \"Время, с\", \"U, В\") print(\"Stage %i: High",
"plot(x, y, \"Время, с\", \"U, В\") print(\"Stage %i: Smoothed differentiation\" % stage) y",
"PARAMETERS # ##################### stage = 0 current_dir = os.path.dirname(os.path.abspath(__file__)) sys.path.append(os.path.join(current_dir, \"../../../tools\")) from base",
"\"_stage-%s\" % get_globus_version(), \"python\") sys.path.append(pyglobus_root) try: import pyglobus except ImportError as e: print(\"Cannot",
"loading\" % stage) sht_reader = pyglobus.util.ShtReader(SHT_FILE) signal = sht_reader.get_signal(NUM_SIGNAL_FROM_SHT) data = np.array((signal.get_data_x(), signal.get_data_y()))",
"В/с\") print(\"Stage %i: Taking absolute value\" % stage) y = np.abs(y) plot(x, y,",
"import pyglobus from %s, exiting\" % pyglobus_root) sys.exit(1) output_dir = os.path.join(current_dir, \"output\", \"sawtooth_detection\")",
"result:\" % stage, out) stage += 1 if __name__ == \"__main__\": font =",
"ALGORITHM PARAMETERS # ######################## SHT_FILE = \"../../../data/test/sht-reader/sht38515.sht\" SIGNAL_SAMPLING_RATE = int(1e6) HIGH_PASS_CUTOFF = 400",
"\"__main__\": font = {\"size\": 22} plt.rc(\"font\", **font) os.makedirs(output_dir, exist_ok=True) print(\"Stage %i: Data loading\"",
"= pyglobus.util.ShtReader(SHT_FILE) signal = sht_reader.get_signal(NUM_SIGNAL_FROM_SHT) data = np.array((signal.get_data_x(), signal.get_data_y())) print(\"Loaded %s\" % SHT_FILE)",
"\"Время, с\", \"U, В\") print(\"Stage %i: ROI extracting\" % stage) roi = pyglobus.sawtooth.get_signal_roi(data[1],",
"# Plotting sample_data and saving it to PNG file def plot(x, y, label_x,",
"print(\"Cannot import pyglobus from %s, exiting\" % pyglobus_root) sys.exit(1) output_dir = os.path.join(current_dir, \"output\",",
"stage += 1 if __name__ == \"__main__\": font = {\"size\": 22} plt.rc(\"font\", **font)",
"os.path.join(current_dir, \"output\", \"sawtooth_detection\") ######################## # ALGORITHM PARAMETERS # ######################## SHT_FILE = \"../../../data/test/sht-reader/sht38515.sht\" SIGNAL_SAMPLING_RATE",
"plot(x, y, \"Время, с\", \"U', В/с\") print(\"Stage %i: Taking absolute value\" % stage)",
"\"Время, с\", \"|U'|, В/с\", flush=False) plot(x, [SAWTOOTH_DETECTION_THRESHOLD] * len(x), \"Время, с\", \"|U'|, В/с\",",
"#################### # HELPER FUNCTIONS # #################### # Plotting sample_data and saving it to",
"out) stage += 1 if __name__ == \"__main__\": font = {\"size\": 22} plt.rc(\"font\",",
"stage) y = pyglobus.dsp.first_order_diff_filter(y, SMOOTHED_DD1_ORDER) plot(x, y, \"Время, с\", \"U', В/с\") print(\"Stage %i:",
"detection\" % stage) start_ind, end_ind = pyglobus.sawtooth.get_sawtooth_indexes(y, SAWTOOTH_DETECTION_THRESHOLD) plt.figure(figsize=(15, 10)) plt.axvline(x[start_ind], color=\"r\") plt.axvline(x[end_ind],",
"В/с\", flush=False) plot(x, [SAWTOOTH_DETECTION_THRESHOLD] * len(x), \"Время, с\", \"|U'|, В/с\", color=\"r\", new_fig=False) print(\"Stage",
"numpy as np import os import matplotlib.pyplot as plt import sys ##################### #"
] |
[
"from cros.factory.test.i18n import arg_utils as i18n_arg_utils from cros.factory.test import test_case from cros.factory.test import",
"level in seconds.') ] def setUp(self): self.dut = device_utils.CreateDUTInterface() self.ui.ToggleTemplateClass('font-large', True) self.ui.BindStandardKeys() self.ui.SetState([self.args.msg,",
"for each brightness level in seconds.') ] def setUp(self): self.dut = device_utils.CreateDUTInterface() self.ui.ToggleTemplateClass('font-large',",
"source code is governed by a BSD-style license that can be # found",
"of this source code is governed by a BSD-style license that can be",
"levels.'), Arg('interval_secs', (int, float), 'Time for each brightness level in seconds.') ] def",
"LCD backlight or LEDs.\"\"\" from cros.factory.device import device_utils from cros.factory.test.i18n import arg_utils as",
"self.ui.SetState([self.args.msg, test_ui.PASS_FAIL_KEY_LABEL]) def runTest(self): \"\"\"Starts an infinite loop to change brightness.\"\"\" self.ui.StartFailingCountdownTimer(self.args.timeout_secs) while",
"self.ui.StartFailingCountdownTimer(self.args.timeout_secs) while True: for level in self.args.levels: self._SetBrightnessLevel(level) self.Sleep(self.args.interval_secs) def _SetBrightnessLevel(self, level): raise",
"[ i18n_arg_utils.I18nArg('msg', 'Message HTML'), Arg('timeout_secs', int, 'Timeout value for the test in seconds.',",
"cros.factory.utils.arg_utils import Arg class BrightnessTest(test_case.TestCase): ARGS = [ i18n_arg_utils.I18nArg('msg', 'Message HTML'), Arg('timeout_secs', int,",
"def setUp(self): self.dut = device_utils.CreateDUTInterface() self.ui.ToggleTemplateClass('font-large', True) self.ui.BindStandardKeys() self.ui.SetState([self.args.msg, test_ui.PASS_FAIL_KEY_LABEL]) def runTest(self): \"\"\"Starts",
"brightness level in seconds.') ] def setUp(self): self.dut = device_utils.CreateDUTInterface() self.ui.ToggleTemplateClass('font-large', True) self.ui.BindStandardKeys()",
"test in seconds.', default=10), Arg('levels', list, 'A sequence of brightness levels.'), Arg('interval_secs', (int,",
"import Arg class BrightnessTest(test_case.TestCase): ARGS = [ i18n_arg_utils.I18nArg('msg', 'Message HTML'), Arg('timeout_secs', int, 'Timeout",
"brightness.\"\"\" self.ui.StartFailingCountdownTimer(self.args.timeout_secs) while True: for level in self.args.levels: self._SetBrightnessLevel(level) self.Sleep(self.args.interval_secs) def _SetBrightnessLevel(self, level):",
"# found in the LICENSE file. \"\"\"This is a factory test to check",
"backlight or LEDs.\"\"\" from cros.factory.device import device_utils from cros.factory.test.i18n import arg_utils as i18n_arg_utils",
"check the brightness of LCD backlight or LEDs.\"\"\" from cros.factory.device import device_utils from",
"this source code is governed by a BSD-style license that can be #",
"seconds.', default=10), Arg('levels', list, 'A sequence of brightness levels.'), Arg('interval_secs', (int, float), 'Time",
"LICENSE file. \"\"\"This is a factory test to check the brightness of LCD",
"i18n_arg_utils.I18nArg('msg', 'Message HTML'), Arg('timeout_secs', int, 'Timeout value for the test in seconds.', default=10),",
"import test_ui from cros.factory.utils.arg_utils import Arg class BrightnessTest(test_case.TestCase): ARGS = [ i18n_arg_utils.I18nArg('msg', 'Message",
"# Copyright 2016 The Chromium OS Authors. All rights reserved. # Use of",
"is a factory test to check the brightness of LCD backlight or LEDs.\"\"\"",
"import device_utils from cros.factory.test.i18n import arg_utils as i18n_arg_utils from cros.factory.test import test_case from",
"Arg('timeout_secs', int, 'Timeout value for the test in seconds.', default=10), Arg('levels', list, 'A",
"self.ui.BindStandardKeys() self.ui.SetState([self.args.msg, test_ui.PASS_FAIL_KEY_LABEL]) def runTest(self): \"\"\"Starts an infinite loop to change brightness.\"\"\" self.ui.StartFailingCountdownTimer(self.args.timeout_secs)",
"BrightnessTest(test_case.TestCase): ARGS = [ i18n_arg_utils.I18nArg('msg', 'Message HTML'), Arg('timeout_secs', int, 'Timeout value for the",
"\"\"\"Starts an infinite loop to change brightness.\"\"\" self.ui.StartFailingCountdownTimer(self.args.timeout_secs) while True: for level in",
"be # found in the LICENSE file. \"\"\"This is a factory test to",
"True) self.ui.BindStandardKeys() self.ui.SetState([self.args.msg, test_ui.PASS_FAIL_KEY_LABEL]) def runTest(self): \"\"\"Starts an infinite loop to change brightness.\"\"\"",
"test_ui.PASS_FAIL_KEY_LABEL]) def runTest(self): \"\"\"Starts an infinite loop to change brightness.\"\"\" self.ui.StartFailingCountdownTimer(self.args.timeout_secs) while True:",
"i18n_arg_utils from cros.factory.test import test_case from cros.factory.test import test_ui from cros.factory.utils.arg_utils import Arg",
"LEDs.\"\"\" from cros.factory.device import device_utils from cros.factory.test.i18n import arg_utils as i18n_arg_utils from cros.factory.test",
"= [ i18n_arg_utils.I18nArg('msg', 'Message HTML'), Arg('timeout_secs', int, 'Timeout value for the test in",
"from cros.factory.test import test_ui from cros.factory.utils.arg_utils import Arg class BrightnessTest(test_case.TestCase): ARGS = [",
"from cros.factory.utils.arg_utils import Arg class BrightnessTest(test_case.TestCase): ARGS = [ i18n_arg_utils.I18nArg('msg', 'Message HTML'), Arg('timeout_secs',",
"Authors. All rights reserved. # Use of this source code is governed by",
"seconds.') ] def setUp(self): self.dut = device_utils.CreateDUTInterface() self.ui.ToggleTemplateClass('font-large', True) self.ui.BindStandardKeys() self.ui.SetState([self.args.msg, test_ui.PASS_FAIL_KEY_LABEL]) def",
"device_utils from cros.factory.test.i18n import arg_utils as i18n_arg_utils from cros.factory.test import test_case from cros.factory.test",
"'Time for each brightness level in seconds.') ] def setUp(self): self.dut = device_utils.CreateDUTInterface()",
"of LCD backlight or LEDs.\"\"\" from cros.factory.device import device_utils from cros.factory.test.i18n import arg_utils",
"The Chromium OS Authors. All rights reserved. # Use of this source code",
"Use of this source code is governed by a BSD-style license that can",
"license that can be # found in the LICENSE file. \"\"\"This is a",
"device_utils.CreateDUTInterface() self.ui.ToggleTemplateClass('font-large', True) self.ui.BindStandardKeys() self.ui.SetState([self.args.msg, test_ui.PASS_FAIL_KEY_LABEL]) def runTest(self): \"\"\"Starts an infinite loop to",
"as i18n_arg_utils from cros.factory.test import test_case from cros.factory.test import test_ui from cros.factory.utils.arg_utils import",
"cros.factory.test import test_ui from cros.factory.utils.arg_utils import Arg class BrightnessTest(test_case.TestCase): ARGS = [ i18n_arg_utils.I18nArg('msg',",
"found in the LICENSE file. \"\"\"This is a factory test to check the",
"Arg class BrightnessTest(test_case.TestCase): ARGS = [ i18n_arg_utils.I18nArg('msg', 'Message HTML'), Arg('timeout_secs', int, 'Timeout value",
"can be # found in the LICENSE file. \"\"\"This is a factory test",
"Arg('levels', list, 'A sequence of brightness levels.'), Arg('interval_secs', (int, float), 'Time for each",
"in seconds.') ] def setUp(self): self.dut = device_utils.CreateDUTInterface() self.ui.ToggleTemplateClass('font-large', True) self.ui.BindStandardKeys() self.ui.SetState([self.args.msg, test_ui.PASS_FAIL_KEY_LABEL])",
"arg_utils as i18n_arg_utils from cros.factory.test import test_case from cros.factory.test import test_ui from cros.factory.utils.arg_utils",
"code is governed by a BSD-style license that can be # found in",
"float), 'Time for each brightness level in seconds.') ] def setUp(self): self.dut =",
"rights reserved. # Use of this source code is governed by a BSD-style",
"from cros.factory.test import test_case from cros.factory.test import test_ui from cros.factory.utils.arg_utils import Arg class",
"the LICENSE file. \"\"\"This is a factory test to check the brightness of",
"test_case from cros.factory.test import test_ui from cros.factory.utils.arg_utils import Arg class BrightnessTest(test_case.TestCase): ARGS =",
"loop to change brightness.\"\"\" self.ui.StartFailingCountdownTimer(self.args.timeout_secs) while True: for level in self.args.levels: self._SetBrightnessLevel(level) self.Sleep(self.args.interval_secs)",
"for the test in seconds.', default=10), Arg('levels', list, 'A sequence of brightness levels.'),",
"default=10), Arg('levels', list, 'A sequence of brightness levels.'), Arg('interval_secs', (int, float), 'Time for",
"cros.factory.device import device_utils from cros.factory.test.i18n import arg_utils as i18n_arg_utils from cros.factory.test import test_case",
"self.dut = device_utils.CreateDUTInterface() self.ui.ToggleTemplateClass('font-large', True) self.ui.BindStandardKeys() self.ui.SetState([self.args.msg, test_ui.PASS_FAIL_KEY_LABEL]) def runTest(self): \"\"\"Starts an infinite",
"list, 'A sequence of brightness levels.'), Arg('interval_secs', (int, float), 'Time for each brightness",
"an infinite loop to change brightness.\"\"\" self.ui.StartFailingCountdownTimer(self.args.timeout_secs) while True: for level in self.args.levels:",
"of brightness levels.'), Arg('interval_secs', (int, float), 'Time for each brightness level in seconds.')",
"runTest(self): \"\"\"Starts an infinite loop to change brightness.\"\"\" self.ui.StartFailingCountdownTimer(self.args.timeout_secs) while True: for level",
"to change brightness.\"\"\" self.ui.StartFailingCountdownTimer(self.args.timeout_secs) while True: for level in self.args.levels: self._SetBrightnessLevel(level) self.Sleep(self.args.interval_secs) def",
"each brightness level in seconds.') ] def setUp(self): self.dut = device_utils.CreateDUTInterface() self.ui.ToggleTemplateClass('font-large', True)",
"def runTest(self): \"\"\"Starts an infinite loop to change brightness.\"\"\" self.ui.StartFailingCountdownTimer(self.args.timeout_secs) while True: for",
"cros.factory.test import test_case from cros.factory.test import test_ui from cros.factory.utils.arg_utils import Arg class BrightnessTest(test_case.TestCase):",
"All rights reserved. # Use of this source code is governed by a",
"HTML'), Arg('timeout_secs', int, 'Timeout value for the test in seconds.', default=10), Arg('levels', list,",
"test to check the brightness of LCD backlight or LEDs.\"\"\" from cros.factory.device import",
"change brightness.\"\"\" self.ui.StartFailingCountdownTimer(self.args.timeout_secs) while True: for level in self.args.levels: self._SetBrightnessLevel(level) self.Sleep(self.args.interval_secs) def _SetBrightnessLevel(self,",
"by a BSD-style license that can be # found in the LICENSE file.",
"'A sequence of brightness levels.'), Arg('interval_secs', (int, float), 'Time for each brightness level",
"file. \"\"\"This is a factory test to check the brightness of LCD backlight",
"import arg_utils as i18n_arg_utils from cros.factory.test import test_case from cros.factory.test import test_ui from",
"setUp(self): self.dut = device_utils.CreateDUTInterface() self.ui.ToggleTemplateClass('font-large', True) self.ui.BindStandardKeys() self.ui.SetState([self.args.msg, test_ui.PASS_FAIL_KEY_LABEL]) def runTest(self): \"\"\"Starts an",
"the test in seconds.', default=10), Arg('levels', list, 'A sequence of brightness levels.'), Arg('interval_secs',",
"a factory test to check the brightness of LCD backlight or LEDs.\"\"\" from",
"is governed by a BSD-style license that can be # found in the",
"brightness of LCD backlight or LEDs.\"\"\" from cros.factory.device import device_utils from cros.factory.test.i18n import",
"governed by a BSD-style license that can be # found in the LICENSE",
"brightness levels.'), Arg('interval_secs', (int, float), 'Time for each brightness level in seconds.') ]",
"reserved. # Use of this source code is governed by a BSD-style license",
"sequence of brightness levels.'), Arg('interval_secs', (int, float), 'Time for each brightness level in",
"a BSD-style license that can be # found in the LICENSE file. \"\"\"This",
"class BrightnessTest(test_case.TestCase): ARGS = [ i18n_arg_utils.I18nArg('msg', 'Message HTML'), Arg('timeout_secs', int, 'Timeout value for",
"# Use of this source code is governed by a BSD-style license that",
"or LEDs.\"\"\" from cros.factory.device import device_utils from cros.factory.test.i18n import arg_utils as i18n_arg_utils from",
"value for the test in seconds.', default=10), Arg('levels', list, 'A sequence of brightness",
"ARGS = [ i18n_arg_utils.I18nArg('msg', 'Message HTML'), Arg('timeout_secs', int, 'Timeout value for the test",
"= device_utils.CreateDUTInterface() self.ui.ToggleTemplateClass('font-large', True) self.ui.BindStandardKeys() self.ui.SetState([self.args.msg, test_ui.PASS_FAIL_KEY_LABEL]) def runTest(self): \"\"\"Starts an infinite loop",
"'Message HTML'), Arg('timeout_secs', int, 'Timeout value for the test in seconds.', default=10), Arg('levels',",
"\"\"\"This is a factory test to check the brightness of LCD backlight or",
"Chromium OS Authors. All rights reserved. # Use of this source code is",
"in the LICENSE file. \"\"\"This is a factory test to check the brightness",
"factory test to check the brightness of LCD backlight or LEDs.\"\"\" from cros.factory.device",
"import test_case from cros.factory.test import test_ui from cros.factory.utils.arg_utils import Arg class BrightnessTest(test_case.TestCase): ARGS",
"] def setUp(self): self.dut = device_utils.CreateDUTInterface() self.ui.ToggleTemplateClass('font-large', True) self.ui.BindStandardKeys() self.ui.SetState([self.args.msg, test_ui.PASS_FAIL_KEY_LABEL]) def runTest(self):",
"BSD-style license that can be # found in the LICENSE file. \"\"\"This is",
"from cros.factory.device import device_utils from cros.factory.test.i18n import arg_utils as i18n_arg_utils from cros.factory.test import",
"the brightness of LCD backlight or LEDs.\"\"\" from cros.factory.device import device_utils from cros.factory.test.i18n",
"Arg('interval_secs', (int, float), 'Time for each brightness level in seconds.') ] def setUp(self):",
"infinite loop to change brightness.\"\"\" self.ui.StartFailingCountdownTimer(self.args.timeout_secs) while True: for level in self.args.levels: self._SetBrightnessLevel(level)",
"cros.factory.test.i18n import arg_utils as i18n_arg_utils from cros.factory.test import test_case from cros.factory.test import test_ui",
"test_ui from cros.factory.utils.arg_utils import Arg class BrightnessTest(test_case.TestCase): ARGS = [ i18n_arg_utils.I18nArg('msg', 'Message HTML'),",
"2016 The Chromium OS Authors. All rights reserved. # Use of this source",
"to check the brightness of LCD backlight or LEDs.\"\"\" from cros.factory.device import device_utils",
"(int, float), 'Time for each brightness level in seconds.') ] def setUp(self): self.dut",
"self.ui.ToggleTemplateClass('font-large', True) self.ui.BindStandardKeys() self.ui.SetState([self.args.msg, test_ui.PASS_FAIL_KEY_LABEL]) def runTest(self): \"\"\"Starts an infinite loop to change",
"Copyright 2016 The Chromium OS Authors. All rights reserved. # Use of this",
"in seconds.', default=10), Arg('levels', list, 'A sequence of brightness levels.'), Arg('interval_secs', (int, float),",
"while True: for level in self.args.levels: self._SetBrightnessLevel(level) self.Sleep(self.args.interval_secs) def _SetBrightnessLevel(self, level): raise NotImplementedError",
"int, 'Timeout value for the test in seconds.', default=10), Arg('levels', list, 'A sequence",
"OS Authors. All rights reserved. # Use of this source code is governed",
"'Timeout value for the test in seconds.', default=10), Arg('levels', list, 'A sequence of",
"that can be # found in the LICENSE file. \"\"\"This is a factory"
] |
[
"of the function at those points. :returns: A tuple ``(dual_evaluation_gem_expression, basis_indices)`` where the",
"of a hack). # Really need to do a more targeted job here.",
"sized identity matrices: .. code-block:: text tQ = Q ⊗ 𝟙ₛ₁ ⊗ 𝟙ₛ₂",
"def mapping(self): '''Appropriate mapping from the reference cell to a physical cell for",
"map of entity id to the degrees of freedom for which the corresponding",
"hitting the sum- # factorisation index limit (this is a bit of a",
"def dual_evaluation(self, fn): '''Get a GEM expression for performing the dual basis evaluation",
"performing the dual basis evaluation at the nodes of the reference element. Currently",
"basis functions of this element.''' return tuple(gem.Index(extent=d) for d in self.index_shape) def get_value_indices(self):",
"= self.entity_dofs() return {dim: {e: sorted(chain(*[entity_dofs[d][se] for d, se in sub_entities])) for e,",
"dual_weight_shape[n]) where num_points_factorX are made free indices that match the free indices of",
"the tensor element tQ is constructed from the base element's Q by taking",
"``fn``) ''' Q, x = self.dual_basis expr = fn(x) # Apply targeted sum",
".. note:: When Q is returned, the contraction indices of the point set",
"to degrees of freedom that have non-zero support on those entities for the",
"the reference element. :param order: return derivatives up to this order. :param refcoords:",
"(which is now a TensorPointSet). If the dual basis is of a tensor",
"indices rather than being left in its shape (as either ``num_points`` or ``num_points_factorX``).",
"return esd def entity_support_dofs(self): '''Return the map of topological entities to degrees of",
"for the finite element.''' @property def entity_permutations(self): '''Returns a nested dictionary that gives,",
"gem.Indexed(vals, beta + zeta)), zeta), quad.weight_expression), quad.point_set.indices ) evaluation, = evaluate([gem.ComponentTensor(ints, beta)]) ints",
"while a vector valued version of the same element would return (6, 2)'''",
"entity local DoF ordering to the canonical global DoF ordering. The entity permutations",
"a vector with the correct dimension, its free indices are arbitrary. :param entity:",
"single entity on dimension ``1`` (interval), which has two possible orientations representing non-reflected",
"entity_dofs = self.entity_dofs() return {dim: {e: sorted(chain(*[entity_dofs[d][se] for d, se in sub_entities])) for",
"of freedom that have non-zero support on those entities for the finite element.'''",
"for the finite element.''' return self._entity_support_dofs @abstractmethod def space_dimension(self): '''Return the dimension of",
"equivalent to this FInAT element.''' raise NotImplementedError( f\"Cannot make equivalent FIAT element for",
"ints = gem.IndexSum( gem.Product(gem.IndexSum(gem.Product(gem.Indexed(vals, beta + zeta), gem.Indexed(vals, beta + zeta)), zeta), quad.weight_expression),",
"representing the function to dual evaluate. Callable should take in an :class:`AbstractPointSet` and",
"factors) # NOTE: any shape indices in the expression are because the #",
"fn at. The general dual evaluation is then Q * fn(x) (the contraction",
"evaluating the element at known points on the reference element. :param order: return",
"are made free indices that match the free indices of x (which is",
"given ``basis_indices`` are those needed to form a return expression for the code",
"basis. ''' raise NotImplementedError( f\"Dual basis not defined for element {type(self).__name__}\" ) def",
"python3 {0: {0: {0: [0]}, 1: {0: [0]}}, 1: {0: {0: [0, 1,",
"only one possible orientation, while there is a single entity on dimension ``1``",
"..., Sn) then the tensor element tQ is constructed from the base element's",
"# Really need to do a more targeted job here. evaluation = gem.optimise.contraction(evaluation,",
"'''The degree of the embedding polynomial space. In the tensor case this is",
"refcoords, entity=None): '''Return code for evaluating the element at an arbitrary points on",
"to dual evaluate a function fn at. The general dual evaluation is then",
"= delta_elimination(*traverse_product(expr)) expr = sum_factorise(sum_indices, factors) # NOTE: any shape indices in the",
"should take in an :class:`AbstractPointSet` and return a GEM expression for evaluation of",
"delta_elimination, sum_factorise, traverse_product from gem.utils import cached_property from finat.quadrature import make_quadrature class FiniteElementBase(metaclass=ABCMeta):",
"the DoF permutation array that maps the entity local DoF ordering to the",
"example a scalar quadratic Lagrange element on a triangle would return (6,) while",
"tensor Q and point set x to dual evaluate a function fn at.",
"a matrix with dimensions .. code-block:: text (num_nodes, num_points) If the dual weights",
"``dual_evaluation_gem_expression`` (alongside any argument multiindices already encoded within ``fn``) ''' Q, x =",
"dual basis is of a tensor product or FlattenedDimensions element with N factors",
"sum- # factorisation index limit (this is a bit of a hack). #",
"a more targeted job here. evaluation = gem.optimise.contraction(evaluation, shape_indices) return evaluation, basis_indices @abstractproperty",
"entity on which to tabulate. :param coordinate_mapping: a :class:`~.physically_mapped.PhysicalGeometry` object that provides physical",
"function at those points. :returns: A tuple ``(dual_evaluation_gem_expression, basis_indices)`` where the given ``basis_indices``",
"needed to form a return expression for the code which is compiled from",
"want to factorise over the new contraction with x, # ignoring any shape",
"which has two possible orientations representing non-reflected and reflected intervals. ''' raise NotImplementedError(f\"entity_permutations",
"for the finite element.''' return self._entity_closure_dofs @cached_property def _entity_support_dofs(self): esd = {} for",
"instance, is given by: .. code-block:: python3 {0: {0: {0: [0]}, 1: {0:",
"Q * fn(x) (the contraction of Q with fn(x) along the the indices",
"the entity local DoF ordering to the canonical global DoF ordering. The entity",
"``Functional.pt_dict`` properties. Therefore any FIAT dual bases with derivative nodes represented via a",
"Now we want to factorise over the new contraction with x, # ignoring",
"⊗ ... ⊗ 𝟙ₛₙ .. note:: When Q is returned, the contraction indices",
"code which is compiled from ``dual_evaluation_gem_expression`` (alongside any argument multiindices already encoded within",
"a single entity on dimension ``1`` (interval), which has two possible orientations representing",
"dictionary that gives, for each dimension, for each entity, and for each possible",
"topological entities to degrees of freedom on the closure of those entities for",
"a nested dictionary that gives, for each dimension, for each entity, and for",
"of the element.''' @property def fiat_equivalent(self): '''The FIAT element equivalent to this FInAT",
"of the correct extents to loop over the value shape of this element.'''",
"<filename>finat/finiteelementbase.py from abc import ABCMeta, abstractproperty, abstractmethod from itertools import chain import numpy",
"the element at known points on the reference element. :param order: return derivatives",
"of the associated form (FEEC)''' @abstractmethod def entity_dofs(self): '''Return the map of topological",
"finite element.''' @property def entity_permutations(self): '''Returns a nested dictionary that gives, for each",
"GEM expression representing the coordinates on the reference entity. Its shape must be",
"element. Currently only works for flat elements: tensor elements are implemented in :class:`TensorFiniteElement`.",
"TensorPointSet). If the dual basis is of a tensor finite element with some",
"limit (this is a bit of a hack). # Really need to do",
"For example a scalar quadratic Lagrange element on a triangle would return (6,)",
"element. :param order: return derivatives up to this order. :param refcoords: GEM expression",
"where the given ``basis_indices`` are those needed to form a return expression for",
"are scalar then Q, for a general scalar FIAT element, is a matrix",
"def get_value_indices(self): '''A tuple of GEM :class:`~gem.Index` of the correct extents to loop",
"nodes on the closure of each sub_entity. entity_dofs = self.entity_dofs() return {dim: {e:",
"tabulate. ''' @property def dual_basis(self): '''Return a dual evaluation gem weight tensor Q",
"code for evaluating the element at an arbitrary points on the reference element.",
"property does not currently have a FInAT dual basis. ''' raise NotImplementedError( f\"Dual",
"take non-zero values. :arg elem: FInAT finite element :arg entity_dim: Dimension of the",
"each dimension, for each entity, and for each possible entity orientation, the DoF",
"possible entity orientation, the DoF permutation array that maps the entity local DoF",
"= evaluate([gem.ComponentTensor(ints, beta)]) ints = evaluation.arr.flatten() assert evaluation.fids == () result[f] = [dof",
"make equivalent FIAT element for {type(self).__name__}\" ) def get_indices(self): '''A tuple of GEM",
"def entity_support_dofs(self): '''Return the map of topological entities to degrees of freedom that",
"being left in its shape (as either ``num_points`` or ``num_points_factorX``). This is to",
"of topological entities to degrees of freedom on the closure of those entities",
"eps = 1.e-8 # Is this a safe value? result = {} for",
"for all basis functions of the finite element.''' def entity_support_dofs(elem, entity_dim): '''Return the",
"the associated form (FEEC)''' @abstractmethod def entity_dofs(self): '''Return the map of topological entities",
"freedom for the finite element.''' @property def entity_permutations(self): '''Returns a nested dictionary that",
"1: [2, 1, 0]}}} Note that there are two entities on dimension ``0``",
"facet vals, = self.basis_evaluation(0, quad.point_set, entity=(entity_dim, f)).values() # Integrate the square of the",
"for each entity, and for each possible entity orientation, the DoF permutation array",
"return derivatives up to this order. :param refcoords: GEM expression representing the coordinates",
"any shape indices to avoid hitting the sum- # factorisation index limit (this",
"for which the corresponding basis functions take non-zero values. :arg elem: FInAT finite",
"from gem.interpreter import evaluate from gem.optimise import delta_elimination, sum_factorise, traverse_product from gem.utils import",
"= gem.indices(len(expr.shape)) basis_indices = gem.indices(len(Q.shape) - len(expr.shape)) Qi = Q[basis_indices + shape_indices] expri",
"def index_shape(self): '''A tuple indicating the number of degrees of freedom in the",
"a triangle would return (6,) while a vector valued version of the same",
".. code-block:: text (num_nodes, num_points, dual_weight_shape[0], ..., dual_weight_shape[n]) If the dual basis is",
"orientation, while there is a single entity on dimension ``1`` (interval), which has",
"dual_evaluation(self, fn): '''Get a GEM expression for performing the dual basis evaluation at",
"tuple indicating the shape of the element.''' @property def fiat_equivalent(self): '''The FIAT element",
"entities in self.cell.sub_entities.items()} def entity_closure_dofs(self): '''Return the map of topological entities to degrees",
"esd def entity_support_dofs(self): '''Return the map of topological entities to degrees of freedom",
"some shape (S1, S2, ..., Sn) then the tensor element tQ is constructed",
"@abstractproperty def index_shape(self): '''A tuple indicating the number of degrees of freedom in",
"evaluate from gem.optimise import delta_elimination, sum_factorise, traverse_product from gem.utils import cached_property from finat.quadrature",
"entities to degrees of freedom on the closure of those entities for the",
"def value_shape(self): '''A tuple indicating the shape of the element.''' @property def fiat_equivalent(self):",
"Callable should take in an :class:`AbstractPointSet` and return a GEM expression for evaluation",
"to degrees of freedom for the finite element.''' @property def entity_permutations(self): '''Returns a",
"evaluation is then Q * fn(x) (the contraction of Q with fn(x) along",
"dual evaluate. Callable should take in an :class:`AbstractPointSet` and return a GEM expression",
"expression for evaluation of the function at those points. :returns: A tuple ``(dual_evaluation_gem_expression,",
"``1`` (interval), which has two possible orientations representing non-reflected and reflected intervals. '''",
"dual_weight_shape[0], ..., dual_weight_shape[n]) where num_points_factorX are made free indices that match the free",
"def basis_evaluation(self, order, ps, entity=None, coordinate_mapping=None): '''Return code for evaluating the element at",
"> eps] esd[entity_dim] = result return esd def entity_support_dofs(self): '''Return the map of",
"for {type(self).__name__}\" ) def get_indices(self): '''A tuple of GEM :class:`Index` of the correct",
"tensor elements are implemented in :class:`TensorFiniteElement`. :param fn: Callable representing the function to",
"a FInAT dual basis. ''' raise NotImplementedError( f\"Dual basis not defined for element",
"a tuple. ''' @abstractproperty def formdegree(self): '''Degree of the associated form (FEEC)''' @abstractmethod",
"in self.cell.sub_entities.keys(): beta = self.get_indices() zeta = self.get_value_indices() entity_cell = self.cell.construct_subelement(entity_dim) quad =",
"order. :param refcoords: GEM expression representing the coordinates on the reference entity. Its",
"dual weights are tensor valued then Q, for a general tensor valued FIAT",
"code-block:: text tQ = Q ⊗ 𝟙ₛ₁ ⊗ 𝟙ₛ₂ ⊗ ... ⊗ 𝟙ₛₙ",
"number of degrees of freedom in the element. For example a scalar quadratic",
"'''Return the map of entity id to the degrees of freedom for which",
"+ shape_indices) # Now we want to factorise over the new contraction with",
"def entity_permutations(self): '''Returns a nested dictionary that gives, for each dimension, for each",
"in self.value_shape) @abstractmethod def basis_evaluation(self, order, ps, entity=None, coordinate_mapping=None): '''Return code for evaluating",
"self.cell.sub_entities.items()} def entity_closure_dofs(self): '''Return the map of topological entities to degrees of freedom",
"at. The general dual evaluation is then Q * fn(x) (the contraction of",
"abc import ABCMeta, abstractproperty, abstractmethod from itertools import chain import numpy import gem",
"{type(self).__name__}\" ) def get_indices(self): '''A tuple of GEM :class:`Index` of the correct extents",
"return tuple(gem.Index(extent=d) for d in self.index_shape) def get_value_indices(self): '''A tuple of GEM :class:`~gem.Index`",
"is of a tensor product or FlattenedDimensions element with N factors then Q",
"import delta_elimination, sum_factorise, traverse_product from gem.utils import cached_property from finat.quadrature import make_quadrature class",
"the element is defined.''' @abstractproperty def degree(self): '''The degree of the embedding polynomial",
"order: return derivatives up to this order. :param ps: the point set object.",
".. note:: FIAT element dual bases are built from their ``Functional.pt_dict`` properties. Therefore",
"num_points, dual_weight_shape[0], ..., dual_weight_shape[n]) If the dual basis is of a tensor product",
"is of a tensor finite element with some shape (S1, S2, ..., Sn)",
"polynomial space. In the tensor case this is a tuple. ''' @abstractproperty def",
"in entities.items()} for dim, entities in self.cell.sub_entities.items()} def entity_closure_dofs(self): '''Return the map of",
"GEM expression for performing the dual basis evaluation at the nodes of the",
"Currently only works for flat elements: tensor elements are implemented in :class:`TensorFiniteElement`. :param",
"evaluation = gem.optimise.contraction(evaluation, shape_indices) return evaluation, basis_indices @abstractproperty def mapping(self): '''Appropriate mapping from",
"(S1, S2, ..., Sn) then the tensor element tQ is constructed from the",
"f)).values() # Integrate the square of the basis functions on the facet. ints",
"ints = evaluation.arr.flatten() assert evaluation.fids == () result[f] = [dof for dof, i",
"to avoid index labelling confusion when performing the dual evaluation contraction. .. note::",
"over the value shape of this element.''' return tuple(gem.Index(extent=d) for d in self.value_shape)",
"and return a GEM expression for evaluation of the function at those points.",
":class:`TensorFiniteElement`. :param fn: Callable representing the function to dual evaluate. Callable should take",
"space. In the tensor case this is a tuple. ''' @abstractproperty def formdegree(self):",
":class:`~.physically_mapped.PhysicalGeometry` object that provides physical geometry callbacks (may be None). ''' @abstractmethod def",
"cell entity on which to tabulate. ''' @property def dual_basis(self): '''Return a dual",
"functions on the facet. ints = gem.IndexSum( gem.Product(gem.IndexSum(gem.Product(gem.Indexed(vals, beta + zeta), gem.Indexed(vals, beta",
"text (num_nodes, num_points, dual_weight_shape[0], ..., dual_weight_shape[n]) If the dual basis is of a",
"scalar quadratic Lagrange element on a triangle would return (6,) while a vector",
"for instance, is given by: .. code-block:: python3 {0: {0: {0: [0]}, 1:",
"1.e-8 # Is this a safe value? result = {} for f in",
"the element at an arbitrary points on the reference element. :param order: return",
"delta_elimination(*traverse_product(expr)) expr = sum_factorise(sum_indices, factors) # NOTE: any shape indices in the expression",
"is a bit of a hack). # Really need to do a more",
"physical geometry callbacks (may be None). ''' @abstractmethod def point_evaluation(self, order, refcoords, entity=None):",
"yet implemented for {type(self)}\") @cached_property def _entity_closure_dofs(self): # Compute the nodes on the",
"general scalar FIAT element, is a matrix with dimensions .. code-block:: text (num_nodes,",
"'''A tuple indicating the shape of the element.''' @property def fiat_equivalent(self): '''The FIAT",
"derivatives up to this order. :param refcoords: GEM expression representing the coordinates on",
"for d, se in sub_entities])) for e, sub_entities in entities.items()} for dim, entities",
"is given by: .. code-block:: python3 {0: {0: {0: [0]}, 1: {0: [0]}},",
"by: .. code-block:: python3 {0: {0: {0: [0]}, 1: {0: [0]}}, 1: {0:",
"The entity permutations `dict` for the degree 4 Lagrange finite element on the",
"dimension, its free indices are arbitrary. :param entity: the cell entity on which",
"S2, ..., Sn) then the tensor element tQ is constructed from the base",
"implemented in :class:`TensorFiniteElement`. :param fn: Callable representing the function to dual evaluate. Callable",
"sum_factorise(sum_indices, factors) # NOTE: any shape indices in the expression are because the",
"element on a triangle would return (6,) while a vector valued version of",
"@abstractproperty def cell(self): '''The reference cell on which the element is defined.''' @abstractproperty",
"+ zeta), gem.Indexed(vals, beta + zeta)), zeta), quad.weight_expression), quad.point_set.indices ) evaluation, = evaluate([gem.ComponentTensor(ints,",
"self.index_shape) def get_value_indices(self): '''A tuple of GEM :class:`~gem.Index` of the correct extents to",
"product or FlattenedDimensions element with N factors then Q in general is a",
"point set are already free indices rather than being left in its shape",
"reflected intervals. ''' raise NotImplementedError(f\"entity_permutations not yet implemented for {type(self)}\") @cached_property def _entity_closure_dofs(self):",
"# Is this a safe value? result = {} for f in self.entity_dofs()[entity_dim].keys():",
"If the dual basis is of a tensor finite element with some shape",
"degrees of freedom on the closure of those entities for the finite element.'''",
"(the contraction of Q with fn(x) along the the indices of x and",
"valued. assert expr.shape == Q.shape[len(Q.shape)-len(expr.shape):] shape_indices = gem.indices(len(expr.shape)) basis_indices = gem.indices(len(Q.shape) - len(expr.shape))",
"of freedom for the finite element.''' @property def entity_permutations(self): '''Returns a nested dictionary",
"freedom on the closure of those entities for the finite element.''' return self._entity_closure_dofs",
"of a tensor product or FlattenedDimensions element with N factors then Q in",
"then Q in general is a tensor with dimensions .. code-block:: text (num_nodes_factor1,",
"'''Get a GEM expression for performing the dual basis evaluation at the nodes",
"return expression for the code which is compiled from ``dual_evaluation_gem_expression`` (alongside any argument",
"delta elimination to # the expression sum_indices, factors = delta_elimination(*traverse_product(expr)) expr = sum_factorise(sum_indices,",
"possible orientations representing non-reflected and reflected intervals. ''' raise NotImplementedError(f\"entity_permutations not yet implemented",
"Note that there are two entities on dimension ``0`` (vertices), each of which",
"while there is a single entity on dimension ``1`` (interval), which has two",
"zeta), gem.Indexed(vals, beta + zeta)), zeta), quad.weight_expression), quad.point_set.indices ) evaluation, = evaluate([gem.ComponentTensor(ints, beta)])",
"entity_permutations(self): '''Returns a nested dictionary that gives, for each dimension, for each entity,",
"assert evaluation.fids == () result[f] = [dof for dof, i in enumerate(ints) if",
"FIAT element equivalent to this FInAT element.''' raise NotImplementedError( f\"Cannot make equivalent FIAT",
"which the element is defined.''' @abstractproperty def degree(self): '''The degree of the embedding",
"on the closure of each sub_entity. entity_dofs = self.entity_dofs() return {dim: {e: sorted(chain(*[entity_dofs[d][se]",
"reference element. :param order: return derivatives up to this order. :param refcoords: GEM",
"on which to tabulate. ''' @property def dual_basis(self): '''Return a dual evaluation gem",
"of freedom in the element. For example a scalar quadratic Lagrange element on",
"Q by taking the outer product with appropriately sized identity matrices: .. code-block::",
"for a general tensor valued FIAT element, is a tensor with dimensions ..",
"have a FInAT dual basis. ''' raise NotImplementedError( f\"Dual basis not defined for",
"tuple(gem.Index(extent=d) for d in self.index_shape) def get_value_indices(self): '''A tuple of GEM :class:`~gem.Index` of",
"taking the outer product with appropriately sized identity matrices: .. code-block:: text tQ",
"[0]}, 1: {0: [0]}}, 1: {0: {0: [0, 1, 2], 1: [2, 1,",
") def get_indices(self): '''A tuple of GEM :class:`Index` of the correct extents to",
"points. :returns: A tuple ``(dual_evaluation_gem_expression, basis_indices)`` where the given ``basis_indices`` are those needed",
"when performing the dual evaluation contraction. .. note:: FIAT element dual bases are",
"form a return expression for the code which is compiled from ``dual_evaluation_gem_expression`` (alongside",
"f\"Dual basis not defined for element {type(self).__name__}\" ) def dual_evaluation(self, fn): '''Get a",
"def entity_dofs(self): '''Return the map of topological entities to degrees of freedom for",
"a GEM expression for evaluation of the function at those points. :returns: A",
"GEM expression for evaluation of the function at those points. :returns: A tuple",
"a TensorPointSet). If the dual basis is of a tensor finite element with",
"sub_entities])) for e, sub_entities in entities.items()} for dim, entities in self.cell.sub_entities.items()} def entity_closure_dofs(self):",
"= self.get_value_indices() entity_cell = self.cell.construct_subelement(entity_dim) quad = make_quadrature(entity_cell, (2*numpy.array(self.degree)).tolist()) eps = 1.e-8 #",
"= Q ⊗ 𝟙ₛ₁ ⊗ 𝟙ₛ₂ ⊗ ... ⊗ 𝟙ₛₙ .. note:: When",
"indicating the number of degrees of freedom in the element. For example a",
"== Q.shape[len(Q.shape)-len(expr.shape):] shape_indices = gem.indices(len(expr.shape)) basis_indices = gem.indices(len(Q.shape) - len(expr.shape)) Qi = Q[basis_indices",
"return tuple(gem.Index(extent=d) for d in self.value_shape) @abstractmethod def basis_evaluation(self, order, ps, entity=None, coordinate_mapping=None):",
"at the nodes of the reference element. Currently only works for flat elements:",
"element.''' raise NotImplementedError( f\"Cannot make equivalent FIAT element for {type(self).__name__}\" ) def get_indices(self):",
"the contraction indices of the point set are already free indices rather than",
"free indices of x (which is now a TensorPointSet). If the dual basis",
"flat elements: tensor elements are implemented in :class:`TensorFiniteElement`. :param fn: Callable representing the",
"entities to degrees of freedom for the finite element.''' @property def entity_permutations(self): '''Returns",
"(as either ``num_points`` or ``num_points_factorX``). This is to avoid index labelling confusion when",
":param ps: the point set object. :param entity: the cell entity on which",
"and reflected intervals. ''' raise NotImplementedError(f\"entity_permutations not yet implemented for {type(self)}\") @cached_property def",
"= Q[basis_indices + shape_indices] expri = expr[shape_indices] evaluation = gem.IndexSum(Qi * expri, x.indices",
"cell(self): '''The reference cell on which the element is defined.''' @abstractproperty def degree(self):",
"def fiat_equivalent(self): '''The FIAT element equivalent to this FInAT element.''' raise NotImplementedError( f\"Cannot",
"those entities for the finite element.''' return self._entity_closure_dofs @cached_property def _entity_support_dofs(self): esd =",
"element equivalent to this FInAT element.''' raise NotImplementedError( f\"Cannot make equivalent FIAT element",
"the interval, for instance, is given by: .. code-block:: python3 {0: {0: {0:",
"evaluating the element at an arbitrary points on the reference element. :param order:",
"* expri, x.indices + shape_indices) # Now we want to factorise over the",
"dual_weight_shape[n]) If the dual basis is of a tensor product or FlattenedDimensions element",
"(num_nodes_factor1, ..., num_nodes_factorN, num_points_factor1, ..., num_points_factorN, dual_weight_shape[0], ..., dual_weight_shape[n]) where num_points_factorX are made",
"any argument multiindices already encoded within ``fn``) ''' Q, x = self.dual_basis expr",
"{0: {0: {0: [0]}, 1: {0: [0]}}, 1: {0: {0: [0, 1, 2],",
"version of the same element would return (6, 2)''' @abstractproperty def value_shape(self): '''A",
"'''Return code for evaluating the element at an arbitrary points on the reference",
"the correct extents to loop over the value shape of this element.''' return",
"a physical cell for all basis functions of the finite element.''' def entity_support_dofs(elem,",
"finat.quadrature import make_quadrature class FiniteElementBase(metaclass=ABCMeta): @abstractproperty def cell(self): '''The reference cell on which",
"def formdegree(self): '''Degree of the associated form (FEEC)''' @abstractmethod def entity_dofs(self): '''Return the",
"''' raise NotImplementedError(f\"entity_permutations not yet implemented for {type(self)}\") @cached_property def _entity_closure_dofs(self): # Compute",
"entity_dim in self.cell.sub_entities.keys(): beta = self.get_indices() zeta = self.get_value_indices() entity_cell = self.cell.construct_subelement(entity_dim) quad",
"evaluation = gem.IndexSum(Qi * expri, x.indices + shape_indices) # Now we want to",
"dimension, for each entity, and for each possible entity orientation, the DoF permutation",
"the reference element. :param order: return derivatives up to this order. :param ps:",
"entities on dimension ``0`` (vertices), each of which has only one possible orientation,",
"of GEM :class:`~gem.Index` of the correct extents to loop over the value shape",
"dimension ``0`` (vertices), each of which has only one possible orientation, while there",
"code-block:: text (num_nodes_factor1, ..., num_nodes_factorN, num_points_factor1, ..., num_points_factorN, dual_weight_shape[0], ..., dual_weight_shape[n]) where num_points_factorX",
"a bit of a hack). # Really need to do a more targeted",
"valued version of the same element would return (6, 2)''' @abstractproperty def value_shape(self):",
"support on those entities for the finite element.''' return self._entity_support_dofs @abstractmethod def space_dimension(self):",
"def _entity_support_dofs(self): esd = {} for entity_dim in self.cell.sub_entities.keys(): beta = self.get_indices() zeta",
"of the finite element space.''' @abstractproperty def index_shape(self): '''A tuple indicating the number",
"evaluation of the function at those points. :returns: A tuple ``(dual_evaluation_gem_expression, basis_indices)`` where",
"DoF ordering. The entity permutations `dict` for the degree 4 Lagrange finite element",
"on which the element is defined.''' @abstractproperty def degree(self): '''The degree of the",
"degrees of freedom for the finite element.''' @property def entity_permutations(self): '''Returns a nested",
"'''Degree of the associated form (FEEC)''' @abstractmethod def entity_dofs(self): '''Return the map of",
"point_evaluation(self, order, refcoords, entity=None): '''Return code for evaluating the element at an arbitrary",
"vector with the correct dimension, its free indices are arbitrary. :param entity: the",
"shape_indices] expri = expr[shape_indices] evaluation = gem.IndexSum(Qi * expri, x.indices + shape_indices) #",
"does not currently have a FInAT dual basis. ''' raise NotImplementedError( f\"Dual basis",
"a GEM expression for performing the dual basis evaluation at the nodes of",
"on the facet. ints = gem.IndexSum( gem.Product(gem.IndexSum(gem.Product(gem.Indexed(vals, beta + zeta), gem.Indexed(vals, beta +",
"indices of x and any shape introduced by fn). If the dual weights",
".. code-block:: text (num_nodes_factor1, ..., num_nodes_factorN, num_points_factor1, ..., num_points_factorN, dual_weight_shape[0], ..., dual_weight_shape[n]) where",
"sum factorisation and delta elimination to # the expression sum_indices, factors = delta_elimination(*traverse_product(expr))",
"tensor with dimensions .. code-block:: text (num_nodes_factor1, ..., num_nodes_factorN, num_points_factor1, ..., num_points_factorN, dual_weight_shape[0],",
"..., num_nodes_factorN, num_points_factor1, ..., num_points_factorN, dual_weight_shape[0], ..., dual_weight_shape[n]) where num_points_factorX are made free",
"refcoords: GEM expression representing the coordinates on the reference entity. Its shape must",
"(alongside any argument multiindices already encoded within ``fn``) ''' Q, x = self.dual_basis",
"the expression sum_indices, factors = delta_elimination(*traverse_product(expr)) expr = sum_factorise(sum_indices, factors) # NOTE: any",
"make_quadrature class FiniteElementBase(metaclass=ABCMeta): @abstractproperty def cell(self): '''The reference cell on which the element",
"beta + zeta)), zeta), quad.weight_expression), quad.point_set.indices ) evaluation, = evaluate([gem.ComponentTensor(ints, beta)]) ints =",
"def get_indices(self): '''A tuple of GEM :class:`Index` of the correct extents to loop",
"free indices that match the free indices of x (which is now a",
"intervals. ''' raise NotImplementedError(f\"entity_permutations not yet implemented for {type(self)}\") @cached_property def _entity_closure_dofs(self): #",
"function to dual evaluate. Callable should take in an :class:`AbstractPointSet` and return a",
"= {} for f in self.entity_dofs()[entity_dim].keys(): # Tabulate basis functions on the facet",
"the nodes on the closure of each sub_entity. entity_dofs = self.entity_dofs() return {dim:",
"= fn(x) # Apply targeted sum factorisation and delta elimination to # the",
"which to tabulate. ''' @property def dual_basis(self): '''Return a dual evaluation gem weight",
".. code-block:: text (num_nodes, num_points) If the dual weights are tensor valued then",
"to this order. :param refcoords: GEM expression representing the coordinates on the reference",
"of x and any shape introduced by fn). If the dual weights are",
"text (num_nodes_factor1, ..., num_nodes_factorN, num_points_factor1, ..., num_points_factorN, dual_weight_shape[0], ..., dual_weight_shape[n]) where num_points_factorX are",
"properties. Therefore any FIAT dual bases with derivative nodes represented via a ``Functional.deriv_dict``",
"return a GEM expression for evaluation of the function at those points. :returns:",
"= self.cell.construct_subelement(entity_dim) quad = make_quadrature(entity_cell, (2*numpy.array(self.degree)).tolist()) eps = 1.e-8 # Is this a",
"(6, 2)''' @abstractproperty def value_shape(self): '''A tuple indicating the shape of the element.'''",
"of a tensor finite element with some shape (S1, S2, ..., Sn) then",
"= self.dual_basis expr = fn(x) # Apply targeted sum factorisation and delta elimination",
"shape_indices) # Now we want to factorise over the new contraction with x,",
"`dict` for the degree 4 Lagrange finite element on the interval, for instance,",
"for evaluating the element at known points on the reference element. :param order:",
"element's Q by taking the outer product with appropriately sized identity matrices: ..",
"left in its shape (as either ``num_points`` or ``num_points_factorX``). This is to avoid",
"note:: When Q is returned, the contraction indices of the point set are",
"def dual_basis(self): '''Return a dual evaluation gem weight tensor Q and point set",
"_entity_closure_dofs(self): # Compute the nodes on the closure of each sub_entity. entity_dofs =",
"entity: the cell entity on which to tabulate. :param coordinate_mapping: a :class:`~.physically_mapped.PhysicalGeometry` object",
"not defined for element {type(self).__name__}\" ) def dual_evaluation(self, fn): '''Get a GEM expression",
"to the degrees of freedom for which the corresponding basis functions take non-zero",
"physical cell for all basis functions of the finite element.''' def entity_support_dofs(elem, entity_dim):",
"are implemented in :class:`TensorFiniteElement`. :param fn: Callable representing the function to dual evaluate.",
"basis functions of the finite element.''' def entity_support_dofs(elem, entity_dim): '''Return the map of",
"d in self.index_shape) def get_value_indices(self): '''A tuple of GEM :class:`~gem.Index` of the correct",
"+ zeta)), zeta), quad.weight_expression), quad.point_set.indices ) evaluation, = evaluate([gem.ComponentTensor(ints, beta)]) ints = evaluation.arr.flatten()",
"raise NotImplementedError( f\"Dual basis not defined for element {type(self).__name__}\" ) def dual_evaluation(self, fn):",
"@property def fiat_equivalent(self): '''The FIAT element equivalent to this FInAT element.''' raise NotImplementedError(",
"the value shape of this element.''' return tuple(gem.Index(extent=d) for d in self.value_shape) @abstractmethod",
"point set x to dual evaluate a function fn at. The general dual",
"the basis functions of this element.''' return tuple(gem.Index(extent=d) for d in self.index_shape) def",
"(this is a bit of a hack). # Really need to do a",
"for evaluation of the function at those points. :returns: A tuple ``(dual_evaluation_gem_expression, basis_indices)``",
"= {} for entity_dim in self.cell.sub_entities.keys(): beta = self.get_indices() zeta = self.get_value_indices() entity_cell",
"evaluate([gem.ComponentTensor(ints, beta)]) ints = evaluation.arr.flatten() assert evaluation.fids == () result[f] = [dof for",
"dimension of the finite element space.''' @abstractproperty def index_shape(self): '''A tuple indicating the",
"order: return derivatives up to this order. :param refcoords: GEM expression representing the",
"expression for the code which is compiled from ``dual_evaluation_gem_expression`` (alongside any argument multiindices",
"FlattenedDimensions element with N factors then Q in general is a tensor with",
"the correct extents to loop over the basis functions of this element.''' return",
"''' @abstractproperty def formdegree(self): '''Degree of the associated form (FEEC)''' @abstractmethod def entity_dofs(self):",
"are because the # expression is tensor valued. assert expr.shape == Q.shape[len(Q.shape)-len(expr.shape):] shape_indices",
"over the basis functions of this element.''' return tuple(gem.Index(extent=d) for d in self.index_shape)",
"that have non-zero support on those entities for the finite element.''' return self._entity_support_dofs",
"the facet. ints = gem.IndexSum( gem.Product(gem.IndexSum(gem.Product(gem.Indexed(vals, beta + zeta), gem.Indexed(vals, beta + zeta)),",
"the cell entity on which to tabulate. :param coordinate_mapping: a :class:`~.physically_mapped.PhysicalGeometry` object that",
"set x to dual evaluate a function fn at. The general dual evaluation",
"on dimension ``0`` (vertices), each of which has only one possible orientation, while",
"Sn) then the tensor element tQ is constructed from the base element's Q",
"4 Lagrange finite element on the interval, for instance, is given by: ..",
"for performing the dual basis evaluation at the nodes of the reference element.",
"import chain import numpy import gem from gem.interpreter import evaluate from gem.optimise import",
"targeted job here. evaluation = gem.optimise.contraction(evaluation, shape_indices) return evaluation, basis_indices @abstractproperty def mapping(self):",
"@abstractproperty def mapping(self): '''Appropriate mapping from the reference cell to a physical cell",
"the dual basis is of a tensor finite element with some shape (S1,",
"d, se in sub_entities])) for e, sub_entities in entities.items()} for dim, entities in",
"finite element.''' return self._entity_support_dofs @abstractmethod def space_dimension(self): '''Return the dimension of the finite",
"entities for the finite element.''' return self._entity_support_dofs @abstractmethod def space_dimension(self): '''Return the dimension",
"that there are two entities on dimension ``0`` (vertices), each of which has",
"self.value_shape) @abstractmethod def basis_evaluation(self, order, ps, entity=None, coordinate_mapping=None): '''Return code for evaluating the",
"is returned, the contraction indices of the point set are already free indices",
"any FIAT dual bases with derivative nodes represented via a ``Functional.deriv_dict`` property does",
"valued then Q, for a general tensor valued FIAT element, is a tensor",
"points on the reference element. :param order: return derivatives up to this order.",
"evaluation, = evaluate([gem.ComponentTensor(ints, beta)]) ints = evaluation.arr.flatten() assert evaluation.fids == () result[f] =",
"evaluation, basis_indices @abstractproperty def mapping(self): '''Appropriate mapping from the reference cell to a",
"degrees of freedom in the element. For example a scalar quadratic Lagrange element",
"{type(self)}\") @cached_property def _entity_closure_dofs(self): # Compute the nodes on the closure of each",
"non-zero support on those entities for the finite element.''' return self._entity_support_dofs @abstractmethod def",
"expr = sum_factorise(sum_indices, factors) # NOTE: any shape indices in the expression are",
"FiniteElementBase(metaclass=ABCMeta): @abstractproperty def cell(self): '''The reference cell on which the element is defined.'''",
"multiindices already encoded within ``fn``) ''' Q, x = self.dual_basis expr = fn(x)",
"representing non-reflected and reflected intervals. ''' raise NotImplementedError(f\"entity_permutations not yet implemented for {type(self)}\")",
"x and any shape introduced by fn). If the dual weights are scalar",
"given by: .. code-block:: python3 {0: {0: {0: [0]}, 1: {0: [0]}}, 1:",
"fn): '''Get a GEM expression for performing the dual basis evaluation at the",
"expri, x.indices + shape_indices) # Now we want to factorise over the new",
"index limit (this is a bit of a hack). # Really need to",
"of the basis functions on the facet. ints = gem.IndexSum( gem.Product(gem.IndexSum(gem.Product(gem.Indexed(vals, beta +",
"free indices are arbitrary. :param entity: the cell entity on which to tabulate.",
"must be a vector with the correct dimension, its free indices are arbitrary.",
"with dimensions .. code-block:: text (num_nodes, num_points) If the dual weights are tensor",
"bases are built from their ``Functional.pt_dict`` properties. Therefore any FIAT dual bases with",
"'''A tuple of GEM :class:`Index` of the correct extents to loop over the",
"defined.''' @abstractproperty def degree(self): '''The degree of the embedding polynomial space. In the",
"tensor valued. assert expr.shape == Q.shape[len(Q.shape)-len(expr.shape):] shape_indices = gem.indices(len(expr.shape)) basis_indices = gem.indices(len(Q.shape) -",
"avoid index labelling confusion when performing the dual evaluation contraction. .. note:: FIAT",
"implemented for {type(self)}\") @cached_property def _entity_closure_dofs(self): # Compute the nodes on the closure",
"of each sub_entity. entity_dofs = self.entity_dofs() return {dim: {e: sorted(chain(*[entity_dofs[d][se] for d, se",
"a :class:`~.physically_mapped.PhysicalGeometry` object that provides physical geometry callbacks (may be None). ''' @abstractmethod",
"raise NotImplementedError( f\"Cannot make equivalent FIAT element for {type(self).__name__}\" ) def get_indices(self): '''A",
"shape_indices = gem.indices(len(expr.shape)) basis_indices = gem.indices(len(Q.shape) - len(expr.shape)) Qi = Q[basis_indices + shape_indices]",
"up to this order. :param ps: the point set object. :param entity: the",
"is then Q * fn(x) (the contraction of Q with fn(x) along the",
"a return expression for the code which is compiled from ``dual_evaluation_gem_expression`` (alongside any",
"works for flat elements: tensor elements are implemented in :class:`TensorFiniteElement`. :param fn: Callable",
"@abstractproperty def value_shape(self): '''A tuple indicating the shape of the element.''' @property def",
"ps: the point set object. :param entity: the cell entity on which to",
"@abstractmethod def basis_evaluation(self, order, ps, entity=None, coordinate_mapping=None): '''Return code for evaluating the element",
"(vertices), each of which has only one possible orientation, while there is a",
"factors = delta_elimination(*traverse_product(expr)) expr = sum_factorise(sum_indices, factors) # NOTE: any shape indices in",
"entity on dimension ``1`` (interval), which has two possible orientations representing non-reflected and",
"the reference entity. Its shape must be a vector with the correct dimension,",
"factors then Q in general is a tensor with dimensions .. code-block:: text",
"the outer product with appropriately sized identity matrices: .. code-block:: text tQ =",
"the tensor case this is a tuple. ''' @abstractproperty def formdegree(self): '''Degree of",
"1, 2], 1: [2, 1, 0]}}} Note that there are two entities on",
"finite element space.''' @abstractproperty def index_shape(self): '''A tuple indicating the number of degrees",
"with appropriately sized identity matrices: .. code-block:: text tQ = Q ⊗ 𝟙ₛ₁",
"is to avoid index labelling confusion when performing the dual evaluation contraction. ..",
"a ``Functional.deriv_dict`` property does not currently have a FInAT dual basis. ''' raise",
"point set object. :param entity: the cell entity on which to tabulate. :param",
"tensor finite element with some shape (S1, S2, ..., Sn) then the tensor",
"import ABCMeta, abstractproperty, abstractmethod from itertools import chain import numpy import gem from",
"derivative nodes represented via a ``Functional.deriv_dict`` property does not currently have a FInAT",
"of the finite element.''' def entity_support_dofs(elem, entity_dim): '''Return the map of entity id",
"canonical global DoF ordering. The entity permutations `dict` for the degree 4 Lagrange",
"quad = make_quadrature(entity_cell, (2*numpy.array(self.degree)).tolist()) eps = 1.e-8 # Is this a safe value?",
"on the reference entity. Its shape must be a vector with the correct",
"shape of this element.''' return tuple(gem.Index(extent=d) for d in self.value_shape) @abstractmethod def basis_evaluation(self,",
"'''A tuple indicating the number of degrees of freedom in the element. For",
"introduced by fn). If the dual weights are scalar then Q, for a",
"= gem.IndexSum( gem.Product(gem.IndexSum(gem.Product(gem.Indexed(vals, beta + zeta), gem.Indexed(vals, beta + zeta)), zeta), quad.weight_expression), quad.point_set.indices",
"that gives, for each dimension, for each entity, and for each possible entity",
"constructed from the base element's Q by taking the outer product with appropriately",
"self._entity_support_dofs @abstractmethod def space_dimension(self): '''Return the dimension of the finite element space.''' @abstractproperty",
"on those entities for the finite element.''' return self._entity_support_dofs @abstractmethod def space_dimension(self): '''Return",
"@abstractmethod def space_dimension(self): '''Return the dimension of the finite element space.''' @abstractproperty def",
"object. :param entity: the cell entity on which to tabulate. :param coordinate_mapping: a",
"basis not defined for element {type(self).__name__}\" ) def dual_evaluation(self, fn): '''Get a GEM",
"basis functions on the facet vals, = self.basis_evaluation(0, quad.point_set, entity=(entity_dim, f)).values() # Integrate",
"# Integrate the square of the basis functions on the facet. ints =",
"the code which is compiled from ``dual_evaluation_gem_expression`` (alongside any argument multiindices already encoded",
"entity_dim): '''Return the map of entity id to the degrees of freedom for",
"def cell(self): '''The reference cell on which the element is defined.''' @abstractproperty def",
"loop over the value shape of this element.''' return tuple(gem.Index(extent=d) for d in",
"is tensor valued. assert expr.shape == Q.shape[len(Q.shape)-len(expr.shape):] shape_indices = gem.indices(len(expr.shape)) basis_indices = gem.indices(len(Q.shape)",
"expr = fn(x) # Apply targeted sum factorisation and delta elimination to #",
"of topological entities to degrees of freedom that have non-zero support on those",
"expr.shape == Q.shape[len(Q.shape)-len(expr.shape):] shape_indices = gem.indices(len(expr.shape)) basis_indices = gem.indices(len(Q.shape) - len(expr.shape)) Qi =",
"entity_dofs(self): '''Return the map of topological entities to degrees of freedom for the",
"self.get_indices() zeta = self.get_value_indices() entity_cell = self.cell.construct_subelement(entity_dim) quad = make_quadrature(entity_cell, (2*numpy.array(self.degree)).tolist()) eps =",
"of the same element would return (6, 2)''' @abstractproperty def value_shape(self): '''A tuple",
"sum_factorise, traverse_product from gem.utils import cached_property from finat.quadrature import make_quadrature class FiniteElementBase(metaclass=ABCMeta): @abstractproperty",
"2], 1: [2, 1, 0]}}} Note that there are two entities on dimension",
"fn: Callable representing the function to dual evaluate. Callable should take in an",
"Q.shape[len(Q.shape)-len(expr.shape):] shape_indices = gem.indices(len(expr.shape)) basis_indices = gem.indices(len(Q.shape) - len(expr.shape)) Qi = Q[basis_indices +",
"gem.interpreter import evaluate from gem.optimise import delta_elimination, sum_factorise, traverse_product from gem.utils import cached_property",
"would return (6, 2)''' @abstractproperty def value_shape(self): '''A tuple indicating the shape of",
"are arbitrary. :param entity: the cell entity on which to tabulate. ''' @property",
"dual bases with derivative nodes represented via a ``Functional.deriv_dict`` property does not currently",
"job here. evaluation = gem.optimise.contraction(evaluation, shape_indices) return evaluation, basis_indices @abstractproperty def mapping(self): '''Appropriate",
"need to do a more targeted job here. evaluation = gem.optimise.contraction(evaluation, shape_indices) return",
"of the point set are already free indices rather than being left in",
"reference cell to a physical cell for all basis functions of the finite",
"for dim, entities in self.cell.sub_entities.items()} def entity_closure_dofs(self): '''Return the map of topological entities",
"degrees of freedom for which the corresponding basis functions take non-zero values. :arg",
"self.cell.construct_subelement(entity_dim) quad = make_quadrature(entity_cell, (2*numpy.array(self.degree)).tolist()) eps = 1.e-8 # Is this a safe",
"at known points on the reference element. :param order: return derivatives up to",
"orientation, the DoF permutation array that maps the entity local DoF ordering to",
"formdegree(self): '''Degree of the associated form (FEEC)''' @abstractmethod def entity_dofs(self): '''Return the map",
"DoF ordering to the canonical global DoF ordering. The entity permutations `dict` for",
"self._entity_closure_dofs @cached_property def _entity_support_dofs(self): esd = {} for entity_dim in self.cell.sub_entities.keys(): beta =",
"import gem from gem.interpreter import evaluate from gem.optimise import delta_elimination, sum_factorise, traverse_product from",
"vector valued version of the same element would return (6, 2)''' @abstractproperty def",
"[0, 1, 2], 1: [2, 1, 0]}}} Note that there are two entities",
"return (6,) while a vector valued version of the same element would return",
"self.basis_evaluation(0, quad.point_set, entity=(entity_dim, f)).values() # Integrate the square of the basis functions on",
"return (6, 2)''' @abstractproperty def value_shape(self): '''A tuple indicating the shape of the",
"tensor valued then Q, for a general tensor valued FIAT element, is a",
"is compiled from ``dual_evaluation_gem_expression`` (alongside any argument multiindices already encoded within ``fn``) '''",
"This is to avoid index labelling confusion when performing the dual evaluation contraction.",
"evaluate a function fn at. The general dual evaluation is then Q *",
"map of topological entities to degrees of freedom on the closure of those",
"with the correct dimension, its free indices are arbitrary. :param entity: the cell",
"of the correct extents to loop over the basis functions of this element.'''",
"N factors then Q in general is a tensor with dimensions .. code-block::",
"dimensions .. code-block:: text (num_nodes_factor1, ..., num_nodes_factorN, num_points_factor1, ..., num_points_factorN, dual_weight_shape[0], ..., dual_weight_shape[n])",
"[2, 1, 0]}}} Note that there are two entities on dimension ``0`` (vertices),",
"the point set object. :param entity: the cell entity on which to tabulate.",
"@abstractproperty def degree(self): '''The degree of the embedding polynomial space. In the tensor",
"= make_quadrature(entity_cell, (2*numpy.array(self.degree)).tolist()) eps = 1.e-8 # Is this a safe value? result",
"code for evaluating the element at known points on the reference element. :param",
"the coordinates on the reference entity. Its shape must be a vector with",
"is now a TensorPointSet). If the dual basis is of a tensor finite",
":class:`~gem.Index` of the correct extents to loop over the value shape of this",
"dimensions .. code-block:: text (num_nodes, num_points, dual_weight_shape[0], ..., dual_weight_shape[n]) If the dual basis",
"entity_cell = self.cell.construct_subelement(entity_dim) quad = make_quadrature(entity_cell, (2*numpy.array(self.degree)).tolist()) eps = 1.e-8 # Is this",
"basis functions on the facet. ints = gem.IndexSum( gem.Product(gem.IndexSum(gem.Product(gem.Indexed(vals, beta + zeta), gem.Indexed(vals,",
"and any shape introduced by fn). If the dual weights are scalar then",
"from the base element's Q by taking the outer product with appropriately sized",
"by taking the outer product with appropriately sized identity matrices: .. code-block:: text",
"appropriately sized identity matrices: .. code-block:: text tQ = Q ⊗ 𝟙ₛ₁ ⊗",
"new contraction with x, # ignoring any shape indices to avoid hitting the",
"tuple of GEM :class:`Index` of the correct extents to loop over the basis",
"element, is a matrix with dimensions .. code-block:: text (num_nodes, num_points) If the",
"degree(self): '''The degree of the embedding polynomial space. In the tensor case this",
"this element.''' return tuple(gem.Index(extent=d) for d in self.index_shape) def get_value_indices(self): '''A tuple of",
"via a ``Functional.deriv_dict`` property does not currently have a FInAT dual basis. '''",
"nested dictionary that gives, for each dimension, for each entity, and for each",
"eps] esd[entity_dim] = result return esd def entity_support_dofs(self): '''Return the map of topological",
"indicating the shape of the element.''' @property def fiat_equivalent(self): '''The FIAT element equivalent",
"that maps the entity local DoF ordering to the canonical global DoF ordering.",
"the # expression is tensor valued. assert expr.shape == Q.shape[len(Q.shape)-len(expr.shape):] shape_indices = gem.indices(len(expr.shape))",
"permutation array that maps the entity local DoF ordering to the canonical global",
"fn(x) (the contraction of Q with fn(x) along the the indices of x",
"callbacks (may be None). ''' @abstractmethod def point_evaluation(self, order, refcoords, entity=None): '''Return code",
"of topological entities to degrees of freedom for the finite element.''' @property def",
"FIAT element, is a matrix with dimensions .. code-block:: text (num_nodes, num_points) If",
"factorise over the new contraction with x, # ignoring any shape indices to",
"degrees of freedom that have non-zero support on those entities for the finite",
"indices of the point set are already free indices rather than being left",
"esd = {} for entity_dim in self.cell.sub_entities.keys(): beta = self.get_indices() zeta = self.get_value_indices()",
"with fn(x) along the the indices of x and any shape introduced by",
"# Now we want to factorise over the new contraction with x, #",
"the function at those points. :returns: A tuple ``(dual_evaluation_gem_expression, basis_indices)`` where the given",
"indices in the expression are because the # expression is tensor valued. assert",
"from abc import ABCMeta, abstractproperty, abstractmethod from itertools import chain import numpy import",
"numpy import gem from gem.interpreter import evaluate from gem.optimise import delta_elimination, sum_factorise, traverse_product",
"map of topological entities to degrees of freedom for the finite element.''' @property",
"global DoF ordering. The entity permutations `dict` for the degree 4 Lagrange finite",
"entity_support_dofs(elem, entity_dim): '''Return the map of entity id to the degrees of freedom",
"the dual weights are tensor valued then Q, for a general tensor valued",
"factorisation index limit (this is a bit of a hack). # Really need",
":arg elem: FInAT finite element :arg entity_dim: Dimension of the cell subentity. '''",
"of the embedding polynomial space. In the tensor case this is a tuple.",
"of x (which is now a TensorPointSet). If the dual basis is of",
"topological entities to degrees of freedom that have non-zero support on those entities",
"those needed to form a return expression for the code which is compiled",
"compiled from ``dual_evaluation_gem_expression`` (alongside any argument multiindices already encoded within ``fn``) ''' Q,",
":param entity: the cell entity on which to tabulate. ''' @property def dual_basis(self):",
"FIAT dual bases with derivative nodes represented via a ``Functional.deriv_dict`` property does not",
"cached_property from finat.quadrature import make_quadrature class FiniteElementBase(metaclass=ABCMeta): @abstractproperty def cell(self): '''The reference cell",
"``basis_indices`` are those needed to form a return expression for the code which",
"Q[basis_indices + shape_indices] expri = expr[shape_indices] evaluation = gem.IndexSum(Qi * expri, x.indices +",
"the dimension of the finite element space.''' @abstractproperty def index_shape(self): '''A tuple indicating",
"loop over the basis functions of this element.''' return tuple(gem.Index(extent=d) for d in",
"dual evaluate a function fn at. The general dual evaluation is then Q",
"for a general scalar FIAT element, is a matrix with dimensions .. code-block::",
"= result return esd def entity_support_dofs(self): '''Return the map of topological entities to",
"== () result[f] = [dof for dof, i in enumerate(ints) if i >",
"Apply targeted sum factorisation and delta elimination to # the expression sum_indices, factors",
"any shape indices in the expression are because the # expression is tensor",
"the map of topological entities to degrees of freedom for the finite element.'''",
"ps, entity=None, coordinate_mapping=None): '''Return code for evaluating the element at known points on",
"reference element. :param order: return derivatives up to this order. :param ps: the",
"the correct dimension, its free indices are arbitrary. :param entity: the cell entity",
"closure of each sub_entity. entity_dofs = self.entity_dofs() return {dim: {e: sorted(chain(*[entity_dofs[d][se] for d,",
"this order. :param refcoords: GEM expression representing the coordinates on the reference entity.",
"of Q with fn(x) along the the indices of x and any shape",
"# factorisation index limit (this is a bit of a hack). # Really",
"Is this a safe value? result = {} for f in self.entity_dofs()[entity_dim].keys(): #",
"index labelling confusion when performing the dual evaluation contraction. .. note:: FIAT element",
"element.''' return self._entity_support_dofs @abstractmethod def space_dimension(self): '''Return the dimension of the finite element",
"i in enumerate(ints) if i > eps] esd[entity_dim] = result return esd def",
"[0]}}, 1: {0: {0: [0, 1, 2], 1: [2, 1, 0]}}} Note that",
"sub_entity. entity_dofs = self.entity_dofs() return {dim: {e: sorted(chain(*[entity_dofs[d][se] for d, se in sub_entities]))",
"this FInAT element.''' raise NotImplementedError( f\"Cannot make equivalent FIAT element for {type(self).__name__}\" )",
"match the free indices of x (which is now a TensorPointSet). If the",
"expr[shape_indices] evaluation = gem.IndexSum(Qi * expri, x.indices + shape_indices) # Now we want",
"import evaluate from gem.optimise import delta_elimination, sum_factorise, traverse_product from gem.utils import cached_property from",
"esd[entity_dim] = result return esd def entity_support_dofs(self): '''Return the map of topological entities",
"the number of degrees of freedom in the element. For example a scalar",
"object that provides physical geometry callbacks (may be None). ''' @abstractmethod def point_evaluation(self,",
"result return esd def entity_support_dofs(self): '''Return the map of topological entities to degrees",
"'''Returns a nested dictionary that gives, for each dimension, for each entity, and",
"on the closure of those entities for the finite element.''' return self._entity_closure_dofs @cached_property",
"Tabulate basis functions on the facet vals, = self.basis_evaluation(0, quad.point_set, entity=(entity_dim, f)).values() #",
"an arbitrary points on the reference element. :param order: return derivatives up to",
"weights are scalar then Q, for a general scalar FIAT element, is a",
"or ``num_points_factorX``). This is to avoid index labelling confusion when performing the dual",
"the finite element.''' return self._entity_support_dofs @abstractmethod def space_dimension(self): '''Return the dimension of the",
"at an arbitrary points on the reference element. :param order: return derivatives up",
"2)''' @abstractproperty def value_shape(self): '''A tuple indicating the shape of the element.''' @property",
"``Functional.deriv_dict`` property does not currently have a FInAT dual basis. ''' raise NotImplementedError(",
"the closure of each sub_entity. entity_dofs = self.entity_dofs() return {dim: {e: sorted(chain(*[entity_dofs[d][se] for",
"array that maps the entity local DoF ordering to the canonical global DoF",
"an :class:`AbstractPointSet` and return a GEM expression for evaluation of the function at",
"of GEM :class:`Index` of the correct extents to loop over the basis functions",
"to form a return expression for the code which is compiled from ``dual_evaluation_gem_expression``",
"one possible orientation, while there is a single entity on dimension ``1`` (interval),",
"valued FIAT element, is a tensor with dimensions .. code-block:: text (num_nodes, num_points,",
"dof, i in enumerate(ints) if i > eps] esd[entity_dim] = result return esd",
"gem.optimise.contraction(evaluation, shape_indices) return evaluation, basis_indices @abstractproperty def mapping(self): '''Appropriate mapping from the reference",
"the map of entity id to the degrees of freedom for which the",
"topological entities to degrees of freedom for the finite element.''' @property def entity_permutations(self):",
"element for {type(self).__name__}\" ) def get_indices(self): '''A tuple of GEM :class:`Index` of the",
"over the new contraction with x, # ignoring any shape indices to avoid",
"in its shape (as either ``num_points`` or ``num_points_factorX``). This is to avoid index",
"return evaluation, basis_indices @abstractproperty def mapping(self): '''Appropriate mapping from the reference cell to",
"triangle would return (6,) while a vector valued version of the same element",
"def entity_support_dofs(elem, entity_dim): '''Return the map of entity id to the degrees of",
"# the expression sum_indices, factors = delta_elimination(*traverse_product(expr)) expr = sum_factorise(sum_indices, factors) # NOTE:",
"two entities on dimension ``0`` (vertices), each of which has only one possible",
"indices are arbitrary. :param entity: the cell entity on which to tabulate. '''",
"make_quadrature(entity_cell, (2*numpy.array(self.degree)).tolist()) eps = 1.e-8 # Is this a safe value? result =",
"and delta elimination to # the expression sum_indices, factors = delta_elimination(*traverse_product(expr)) expr =",
"'''Return the map of topological entities to degrees of freedom that have non-zero",
"''' @abstractmethod def point_evaluation(self, order, refcoords, entity=None): '''Return code for evaluating the element",
"evaluation gem weight tensor Q and point set x to dual evaluate a",
"basis_indices)`` where the given ``basis_indices`` are those needed to form a return expression",
"Really need to do a more targeted job here. evaluation = gem.optimise.contraction(evaluation, shape_indices)",
"are built from their ``Functional.pt_dict`` properties. Therefore any FIAT dual bases with derivative",
"a general tensor valued FIAT element, is a tensor with dimensions .. code-block::",
"contraction indices of the point set are already free indices rather than being",
"not currently have a FInAT dual basis. ''' raise NotImplementedError( f\"Dual basis not",
"{} for f in self.entity_dofs()[entity_dim].keys(): # Tabulate basis functions on the facet vals,",
"() result[f] = [dof for dof, i in enumerate(ints) if i > eps]",
"in enumerate(ints) if i > eps] esd[entity_dim] = result return esd def entity_support_dofs(self):",
"evaluation.arr.flatten() assert evaluation.fids == () result[f] = [dof for dof, i in enumerate(ints)",
"a function fn at. The general dual evaluation is then Q * fn(x)",
"abstractproperty, abstractmethod from itertools import chain import numpy import gem from gem.interpreter import",
"If the dual basis is of a tensor product or FlattenedDimensions element with",
"tensor product or FlattenedDimensions element with N factors then Q in general is",
"note:: FIAT element dual bases are built from their ``Functional.pt_dict`` properties. Therefore any",
"represented via a ``Functional.deriv_dict`` property does not currently have a FInAT dual basis.",
"shape indices to avoid hitting the sum- # factorisation index limit (this is",
"``num_points`` or ``num_points_factorX``). This is to avoid index labelling confusion when performing the",
"ABCMeta, abstractproperty, abstractmethod from itertools import chain import numpy import gem from gem.interpreter",
"self.entity_dofs() return {dim: {e: sorted(chain(*[entity_dofs[d][se] for d, se in sub_entities])) for e, sub_entities",
"{e: sorted(chain(*[entity_dofs[d][se] for d, se in sub_entities])) for e, sub_entities in entities.items()} for",
"is a single entity on dimension ``1`` (interval), which has two possible orientations",
"the closure of those entities for the finite element.''' return self._entity_closure_dofs @cached_property def",
"on a triangle would return (6,) while a vector valued version of the",
"GEM :class:`~gem.Index` of the correct extents to loop over the value shape of",
"Q with fn(x) along the the indices of x and any shape introduced",
"indices that match the free indices of x (which is now a TensorPointSet).",
"* fn(x) (the contraction of Q with fn(x) along the the indices of",
"to degrees of freedom on the closure of those entities for the finite",
"expression for performing the dual basis evaluation at the nodes of the reference",
"entities for the finite element.''' return self._entity_closure_dofs @cached_property def _entity_support_dofs(self): esd = {}",
"fiat_equivalent(self): '''The FIAT element equivalent to this FInAT element.''' raise NotImplementedError( f\"Cannot make",
"_entity_support_dofs(self): esd = {} for entity_dim in self.cell.sub_entities.keys(): beta = self.get_indices() zeta =",
"traverse_product from gem.utils import cached_property from finat.quadrature import make_quadrature class FiniteElementBase(metaclass=ABCMeta): @abstractproperty def",
"bases with derivative nodes represented via a ``Functional.deriv_dict`` property does not currently have",
"in self.entity_dofs()[entity_dim].keys(): # Tabulate basis functions on the facet vals, = self.basis_evaluation(0, quad.point_set,",
"freedom for which the corresponding basis functions take non-zero values. :arg elem: FInAT",
"gem.Product(gem.IndexSum(gem.Product(gem.Indexed(vals, beta + zeta), gem.Indexed(vals, beta + zeta)), zeta), quad.weight_expression), quad.point_set.indices ) evaluation,",
"fn(x) # Apply targeted sum factorisation and delta elimination to # the expression",
":param coordinate_mapping: a :class:`~.physically_mapped.PhysicalGeometry` object that provides physical geometry callbacks (may be None).",
"in the expression are because the # expression is tensor valued. assert expr.shape",
"'''Appropriate mapping from the reference cell to a physical cell for all basis",
"= gem.optimise.contraction(evaluation, shape_indices) return evaluation, basis_indices @abstractproperty def mapping(self): '''Appropriate mapping from the",
"has only one possible orientation, while there is a single entity on dimension",
"made free indices that match the free indices of x (which is now",
"def _entity_closure_dofs(self): # Compute the nodes on the closure of each sub_entity. entity_dofs",
"on the interval, for instance, is given by: .. code-block:: python3 {0: {0:",
"{0: [0]}, 1: {0: [0]}}, 1: {0: {0: [0, 1, 2], 1: [2,",
"Lagrange element on a triangle would return (6,) while a vector valued version",
"f in self.entity_dofs()[entity_dim].keys(): # Tabulate basis functions on the facet vals, = self.basis_evaluation(0,",
"a tensor finite element with some shape (S1, S2, ..., Sn) then the",
"gem from gem.interpreter import evaluate from gem.optimise import delta_elimination, sum_factorise, traverse_product from gem.utils",
"map of topological entities to degrees of freedom that have non-zero support on",
"dual weights are scalar then Q, for a general scalar FIAT element, is",
"tQ = Q ⊗ 𝟙ₛ₁ ⊗ 𝟙ₛ₂ ⊗ ... ⊗ 𝟙ₛₙ .. note::",
"FInAT finite element :arg entity_dim: Dimension of the cell subentity. ''' return elem.entity_support_dofs()[entity_dim]",
"evaluation contraction. .. note:: FIAT element dual bases are built from their ``Functional.pt_dict``",
"zeta), quad.weight_expression), quad.point_set.indices ) evaluation, = evaluate([gem.ComponentTensor(ints, beta)]) ints = evaluation.arr.flatten() assert evaluation.fids",
"the the indices of x and any shape introduced by fn). If the",
"degree of the embedding polynomial space. In the tensor case this is a",
"reference cell on which the element is defined.''' @abstractproperty def degree(self): '''The degree",
"those entities for the finite element.''' return self._entity_support_dofs @abstractmethod def space_dimension(self): '''Return the",
"functions of this element.''' return tuple(gem.Index(extent=d) for d in self.index_shape) def get_value_indices(self): '''A",
"to a physical cell for all basis functions of the finite element.''' def",
"a vector valued version of the same element would return (6, 2)''' @abstractproperty",
"correct dimension, its free indices are arbitrary. :param entity: the cell entity on",
"contraction. .. note:: FIAT element dual bases are built from their ``Functional.pt_dict`` properties.",
"self.entity_dofs()[entity_dim].keys(): # Tabulate basis functions on the facet vals, = self.basis_evaluation(0, quad.point_set, entity=(entity_dim,",
"enumerate(ints) if i > eps] esd[entity_dim] = result return esd def entity_support_dofs(self): '''Return",
") evaluation, = evaluate([gem.ComponentTensor(ints, beta)]) ints = evaluation.arr.flatten() assert evaluation.fids == () result[f]",
"with N factors then Q in general is a tensor with dimensions ..",
"to factorise over the new contraction with x, # ignoring any shape indices",
"result = {} for f in self.entity_dofs()[entity_dim].keys(): # Tabulate basis functions on the",
"facet. ints = gem.IndexSum( gem.Product(gem.IndexSum(gem.Product(gem.Indexed(vals, beta + zeta), gem.Indexed(vals, beta + zeta)), zeta),",
"𝟙ₛₙ .. note:: When Q is returned, the contraction indices of the point",
"returned, the contraction indices of the point set are already free indices rather",
"'''Return the dimension of the finite element space.''' @abstractproperty def index_shape(self): '''A tuple",
"functions of the finite element.''' def entity_support_dofs(elem, entity_dim): '''Return the map of entity",
"# Compute the nodes on the closure of each sub_entity. entity_dofs = self.entity_dofs()",
"{} for entity_dim in self.cell.sub_entities.keys(): beta = self.get_indices() zeta = self.get_value_indices() entity_cell =",
"element would return (6, 2)''' @abstractproperty def value_shape(self): '''A tuple indicating the shape",
"{type(self).__name__}\" ) def dual_evaluation(self, fn): '''Get a GEM expression for performing the dual",
"beta = self.get_indices() zeta = self.get_value_indices() entity_cell = self.cell.construct_subelement(entity_dim) quad = make_quadrature(entity_cell, (2*numpy.array(self.degree)).tolist())",
"element. For example a scalar quadratic Lagrange element on a triangle would return",
"entity orientation, the DoF permutation array that maps the entity local DoF ordering",
"cell for all basis functions of the finite element.''' def entity_support_dofs(elem, entity_dim): '''Return",
"dual evaluation is then Q * fn(x) (the contraction of Q with fn(x)",
"= self.get_indices() zeta = self.get_value_indices() entity_cell = self.cell.construct_subelement(entity_dim) quad = make_quadrature(entity_cell, (2*numpy.array(self.degree)).tolist()) eps",
"The general dual evaluation is then Q * fn(x) (the contraction of Q",
"entity on which to tabulate. ''' @property def dual_basis(self): '''Return a dual evaluation",
"to loop over the value shape of this element.''' return tuple(gem.Index(extent=d) for d",
":class:`Index` of the correct extents to loop over the basis functions of this",
"𝟙ₛ₁ ⊗ 𝟙ₛ₂ ⊗ ... ⊗ 𝟙ₛₙ .. note:: When Q is returned,",
"[dof for dof, i in enumerate(ints) if i > eps] esd[entity_dim] = result",
"import numpy import gem from gem.interpreter import evaluate from gem.optimise import delta_elimination, sum_factorise,",
"element space.''' @abstractproperty def index_shape(self): '''A tuple indicating the number of degrees of",
"the degrees of freedom for which the corresponding basis functions take non-zero values.",
"the expression are because the # expression is tensor valued. assert expr.shape ==",
"# Apply targeted sum factorisation and delta elimination to # the expression sum_indices,",
"where num_points_factorX are made free indices that match the free indices of x",
"to tabulate. ''' @property def dual_basis(self): '''Return a dual evaluation gem weight tensor",
"of this element.''' return tuple(gem.Index(extent=d) for d in self.index_shape) def get_value_indices(self): '''A tuple",
"then Q, for a general tensor valued FIAT element, is a tensor with",
"Q is returned, the contraction indices of the point set are already free",
"because the # expression is tensor valued. assert expr.shape == Q.shape[len(Q.shape)-len(expr.shape):] shape_indices =",
"- len(expr.shape)) Qi = Q[basis_indices + shape_indices] expri = expr[shape_indices] evaluation = gem.IndexSum(Qi",
"to avoid hitting the sum- # factorisation index limit (this is a bit",
"..., num_points_factorN, dual_weight_shape[0], ..., dual_weight_shape[n]) where num_points_factorX are made free indices that match",
"expression sum_indices, factors = delta_elimination(*traverse_product(expr)) expr = sum_factorise(sum_indices, factors) # NOTE: any shape",
"class FiniteElementBase(metaclass=ABCMeta): @abstractproperty def cell(self): '''The reference cell on which the element is",
"same element would return (6, 2)''' @abstractproperty def value_shape(self): '''A tuple indicating the",
"gem.IndexSum( gem.Product(gem.IndexSum(gem.Product(gem.Indexed(vals, beta + zeta), gem.Indexed(vals, beta + zeta)), zeta), quad.weight_expression), quad.point_set.indices )",
"to do a more targeted job here. evaluation = gem.optimise.contraction(evaluation, shape_indices) return evaluation,",
"x to dual evaluate a function fn at. The general dual evaluation is",
"'''The reference cell on which the element is defined.''' @abstractproperty def degree(self): '''The",
"are tensor valued then Q, for a general tensor valued FIAT element, is",
"num_points) If the dual weights are tensor valued then Q, for a general",
"FInAT dual basis. ''' raise NotImplementedError( f\"Dual basis not defined for element {type(self).__name__}\"",
"nodes of the reference element. Currently only works for flat elements: tensor elements",
"reference element. Currently only works for flat elements: tensor elements are implemented in",
"def space_dimension(self): '''Return the dimension of the finite element space.''' @abstractproperty def index_shape(self):",
":param fn: Callable representing the function to dual evaluate. Callable should take in",
"expression representing the coordinates on the reference entity. Its shape must be a",
"ordering to the canonical global DoF ordering. The entity permutations `dict` for the",
"coordinates on the reference entity. Its shape must be a vector with the",
"'''The FIAT element equivalent to this FInAT element.''' raise NotImplementedError( f\"Cannot make equivalent",
"return self._entity_closure_dofs @cached_property def _entity_support_dofs(self): esd = {} for entity_dim in self.cell.sub_entities.keys(): beta",
"to this FInAT element.''' raise NotImplementedError( f\"Cannot make equivalent FIAT element for {type(self).__name__}\"",
"up to this order. :param refcoords: GEM expression representing the coordinates on the",
"element at an arbitrary points on the reference element. :param order: return derivatives",
"entity permutations `dict` for the degree 4 Lagrange finite element on the interval,",
"'''Return the map of topological entities to degrees of freedom on the closure",
"equivalent FIAT element for {type(self).__name__}\" ) def get_indices(self): '''A tuple of GEM :class:`Index`",
"from their ``Functional.pt_dict`` properties. Therefore any FIAT dual bases with derivative nodes represented",
"A tuple ``(dual_evaluation_gem_expression, basis_indices)`` where the given ``basis_indices`` are those needed to form",
"which has only one possible orientation, while there is a single entity on",
"the finite element.''' @property def entity_permutations(self): '''Returns a nested dictionary that gives, for",
"for the degree 4 Lagrange finite element on the interval, for instance, is",
"space_dimension(self): '''Return the dimension of the finite element space.''' @abstractproperty def index_shape(self): '''A",
"extents to loop over the value shape of this element.''' return tuple(gem.Index(extent=d) for",
"coordinate_mapping=None): '''Return code for evaluating the element at known points on the reference",
"contraction of Q with fn(x) along the the indices of x and any",
"matrix with dimensions .. code-block:: text (num_nodes, num_points) If the dual weights are",
"1: {0: {0: [0, 1, 2], 1: [2, 1, 0]}}} Note that there",
":param order: return derivatives up to this order. :param ps: the point set",
"identity matrices: .. code-block:: text tQ = Q ⊗ 𝟙ₛ₁ ⊗ 𝟙ₛ₂ ⊗",
"Q and point set x to dual evaluate a function fn at. The",
"= 1.e-8 # Is this a safe value? result = {} for f",
"all basis functions of the finite element.''' def entity_support_dofs(elem, entity_dim): '''Return the map",
"Q, for a general tensor valued FIAT element, is a tensor with dimensions",
"dual_weight_shape[0], ..., dual_weight_shape[n]) If the dual basis is of a tensor product or",
"{0: [0]}}, 1: {0: {0: [0, 1, 2], 1: [2, 1, 0]}}} Note",
"with derivative nodes represented via a ``Functional.deriv_dict`` property does not currently have a",
"in an :class:`AbstractPointSet` and return a GEM expression for evaluation of the function",
"within ``fn``) ''' Q, x = self.dual_basis expr = fn(x) # Apply targeted",
"x = self.dual_basis expr = fn(x) # Apply targeted sum factorisation and delta",
"# ignoring any shape indices to avoid hitting the sum- # factorisation index",
"finite element.''' def entity_support_dofs(elem, entity_dim): '''Return the map of entity id to the",
"the reference element. Currently only works for flat elements: tensor elements are implemented",
"entity=None): '''Return code for evaluating the element at an arbitrary points on the",
"be a vector with the correct dimension, its free indices are arbitrary. :param",
"{dim: {e: sorted(chain(*[entity_dofs[d][se] for d, se in sub_entities])) for e, sub_entities in entities.items()}",
"ordering. The entity permutations `dict` for the degree 4 Lagrange finite element on",
"for the code which is compiled from ``dual_evaluation_gem_expression`` (alongside any argument multiindices already",
"for d in self.index_shape) def get_value_indices(self): '''A tuple of GEM :class:`~gem.Index` of the",
"return {dim: {e: sorted(chain(*[entity_dofs[d][se] for d, se in sub_entities])) for e, sub_entities in",
"shape (as either ``num_points`` or ``num_points_factorX``). This is to avoid index labelling confusion",
"assert expr.shape == Q.shape[len(Q.shape)-len(expr.shape):] shape_indices = gem.indices(len(expr.shape)) basis_indices = gem.indices(len(Q.shape) - len(expr.shape)) Qi",
"for d in self.value_shape) @abstractmethod def basis_evaluation(self, order, ps, entity=None, coordinate_mapping=None): '''Return code",
"element on the interval, for instance, is given by: .. code-block:: python3 {0:",
"def entity_closure_dofs(self): '''Return the map of topological entities to degrees of freedom on",
"finite element with some shape (S1, S2, ..., Sn) then the tensor element",
"tabulate. :param coordinate_mapping: a :class:`~.physically_mapped.PhysicalGeometry` object that provides physical geometry callbacks (may be",
"# Tabulate basis functions on the facet vals, = self.basis_evaluation(0, quad.point_set, entity=(entity_dim, f)).values()",
"NotImplementedError( f\"Cannot make equivalent FIAT element for {type(self).__name__}\" ) def get_indices(self): '''A tuple",
"provides physical geometry callbacks (may be None). ''' @abstractmethod def point_evaluation(self, order, refcoords,",
"non-zero values. :arg elem: FInAT finite element :arg entity_dim: Dimension of the cell",
"nodes represented via a ``Functional.deriv_dict`` property does not currently have a FInAT dual",
"for evaluating the element at an arbitrary points on the reference element. :param",
"each sub_entity. entity_dofs = self.entity_dofs() return {dim: {e: sorted(chain(*[entity_dofs[d][se] for d, se in",
"Therefore any FIAT dual bases with derivative nodes represented via a ``Functional.deriv_dict`` property",
"shape of the element.''' @property def fiat_equivalent(self): '''The FIAT element equivalent to this",
"x.indices + shape_indices) # Now we want to factorise over the new contraction",
"num_points_factor1, ..., num_points_factorN, dual_weight_shape[0], ..., dual_weight_shape[n]) where num_points_factorX are made free indices that",
"quad.weight_expression), quad.point_set.indices ) evaluation, = evaluate([gem.ComponentTensor(ints, beta)]) ints = evaluation.arr.flatten() assert evaluation.fids ==",
"code-block:: text (num_nodes, num_points) If the dual weights are tensor valued then Q,",
"dual basis is of a tensor finite element with some shape (S1, S2,",
"entity=None, coordinate_mapping=None): '''Return code for evaluating the element at known points on the",
"zeta)), zeta), quad.weight_expression), quad.point_set.indices ) evaluation, = evaluate([gem.ComponentTensor(ints, beta)]) ints = evaluation.arr.flatten() assert",
"two possible orientations representing non-reflected and reflected intervals. ''' raise NotImplementedError(f\"entity_permutations not yet",
"gives, for each dimension, for each entity, and for each possible entity orientation,",
"'''Return code for evaluating the element at known points on the reference element.",
"d in self.value_shape) @abstractmethod def basis_evaluation(self, order, ps, entity=None, coordinate_mapping=None): '''Return code for",
"Qi = Q[basis_indices + shape_indices] expri = expr[shape_indices] evaluation = gem.IndexSum(Qi * expri,",
"of freedom on the closure of those entities for the finite element.''' return",
"the cell entity on which to tabulate. ''' @property def dual_basis(self): '''Return a",
"hack). # Really need to do a more targeted job here. evaluation =",
"NotImplementedError(f\"entity_permutations not yet implemented for {type(self)}\") @cached_property def _entity_closure_dofs(self): # Compute the nodes",
"@cached_property def _entity_support_dofs(self): esd = {} for entity_dim in self.cell.sub_entities.keys(): beta = self.get_indices()",
"tensor valued FIAT element, is a tensor with dimensions .. code-block:: text (num_nodes,",
"the sum- # factorisation index limit (this is a bit of a hack).",
"order. :param ps: the point set object. :param entity: the cell entity on",
"the corresponding basis functions take non-zero values. :arg elem: FInAT finite element :arg",
"safe value? result = {} for f in self.entity_dofs()[entity_dim].keys(): # Tabulate basis functions",
"and for each possible entity orientation, the DoF permutation array that maps the",
"1: {0: [0]}}, 1: {0: {0: [0, 1, 2], 1: [2, 1, 0]}}}",
"0]}}} Note that there are two entities on dimension ``0`` (vertices), each of",
"cell entity on which to tabulate. :param coordinate_mapping: a :class:`~.physically_mapped.PhysicalGeometry` object that provides",
"from ``dual_evaluation_gem_expression`` (alongside any argument multiindices already encoded within ``fn``) ''' Q, x",
"the element. For example a scalar quadratic Lagrange element on a triangle would",
"from gem.utils import cached_property from finat.quadrature import make_quadrature class FiniteElementBase(metaclass=ABCMeta): @abstractproperty def cell(self):",
"the degree 4 Lagrange finite element on the interval, for instance, is given",
"arbitrary. :param entity: the cell entity on which to tabulate. ''' @property def",
"its shape (as either ``num_points`` or ``num_points_factorX``). This is to avoid index labelling",
"= [dof for dof, i in enumerate(ints) if i > eps] esd[entity_dim] =",
"the embedding polynomial space. In the tensor case this is a tuple. '''",
"text (num_nodes, num_points) If the dual weights are tensor valued then Q, for",
"FIAT element for {type(self).__name__}\" ) def get_indices(self): '''A tuple of GEM :class:`Index` of",
"scalar FIAT element, is a matrix with dimensions .. code-block:: text (num_nodes, num_points)",
"Compute the nodes on the closure of each sub_entity. entity_dofs = self.entity_dofs() return",
"the indices of x and any shape introduced by fn). If the dual",
"gem.IndexSum(Qi * expri, x.indices + shape_indices) # Now we want to factorise over",
"expression is tensor valued. assert expr.shape == Q.shape[len(Q.shape)-len(expr.shape):] shape_indices = gem.indices(len(expr.shape)) basis_indices =",
"that provides physical geometry callbacks (may be None). ''' @abstractmethod def point_evaluation(self, order,",
"square of the basis functions on the facet. ints = gem.IndexSum( gem.Product(gem.IndexSum(gem.Product(gem.Indexed(vals, beta",
"(num_nodes, num_points) If the dual weights are tensor valued then Q, for a",
"product with appropriately sized identity matrices: .. code-block:: text tQ = Q ⊗",
"finite element on the interval, for instance, is given by: .. code-block:: python3",
"then the tensor element tQ is constructed from the base element's Q by",
"targeted sum factorisation and delta elimination to # the expression sum_indices, factors =",
"from finat.quadrature import make_quadrature class FiniteElementBase(metaclass=ABCMeta): @abstractproperty def cell(self): '''The reference cell on",
"with x, # ignoring any shape indices to avoid hitting the sum- #",
"each of which has only one possible orientation, while there is a single",
"def point_evaluation(self, order, refcoords, entity=None): '''Return code for evaluating the element at an",
"{0: [0, 1, 2], 1: [2, 1, 0]}}} Note that there are two",
"basis_indices = gem.indices(len(Q.shape) - len(expr.shape)) Qi = Q[basis_indices + shape_indices] expri = expr[shape_indices]",
"case this is a tuple. ''' @abstractproperty def formdegree(self): '''Degree of the associated",
"⊗ 𝟙ₛ₂ ⊗ ... ⊗ 𝟙ₛₙ .. note:: When Q is returned, the",
"dim, entities in self.cell.sub_entities.items()} def entity_closure_dofs(self): '''Return the map of topological entities to",
"element {type(self).__name__}\" ) def dual_evaluation(self, fn): '''Get a GEM expression for performing the",
"element.''' return tuple(gem.Index(extent=d) for d in self.index_shape) def get_value_indices(self): '''A tuple of GEM",
"Q, x = self.dual_basis expr = fn(x) # Apply targeted sum factorisation and",
"more targeted job here. evaluation = gem.optimise.contraction(evaluation, shape_indices) return evaluation, basis_indices @abstractproperty def",
"to # the expression sum_indices, factors = delta_elimination(*traverse_product(expr)) expr = sum_factorise(sum_indices, factors) #",
"are already free indices rather than being left in its shape (as either",
"expri = expr[shape_indices] evaluation = gem.IndexSum(Qi * expri, x.indices + shape_indices) # Now",
"of the reference element. Currently only works for flat elements: tensor elements are",
"coordinate_mapping: a :class:`~.physically_mapped.PhysicalGeometry` object that provides physical geometry callbacks (may be None). '''",
"(2*numpy.array(self.degree)).tolist()) eps = 1.e-8 # Is this a safe value? result = {}",
"by fn). If the dual weights are scalar then Q, for a general",
"⊗ 𝟙ₛₙ .. note:: When Q is returned, the contraction indices of the",
"shape introduced by fn). If the dual weights are scalar then Q, for",
"shape indices in the expression are because the # expression is tensor valued.",
"@property def entity_permutations(self): '''Returns a nested dictionary that gives, for each dimension, for",
"itertools import chain import numpy import gem from gem.interpreter import evaluate from gem.optimise",
"the square of the basis functions on the facet. ints = gem.IndexSum( gem.Product(gem.IndexSum(gem.Product(gem.Indexed(vals,",
"or FlattenedDimensions element with N factors then Q in general is a tensor",
"be None). ''' @abstractmethod def point_evaluation(self, order, refcoords, entity=None): '''Return code for evaluating",
"the free indices of x (which is now a TensorPointSet). If the dual",
"shape (S1, S2, ..., Sn) then the tensor element tQ is constructed from",
"general dual evaluation is then Q * fn(x) (the contraction of Q with",
"tuple(gem.Index(extent=d) for d in self.value_shape) @abstractmethod def basis_evaluation(self, order, ps, entity=None, coordinate_mapping=None): '''Return",
"dual evaluation gem weight tensor Q and point set x to dual evaluate",
") def dual_evaluation(self, fn): '''Get a GEM expression for performing the dual basis",
"dimensions .. code-block:: text (num_nodes, num_points) If the dual weights are tensor valued",
"base element's Q by taking the outer product with appropriately sized identity matrices:",
"(num_nodes, num_points, dual_weight_shape[0], ..., dual_weight_shape[n]) If the dual basis is of a tensor",
"outer product with appropriately sized identity matrices: .. code-block:: text tQ = Q",
"currently have a FInAT dual basis. ''' raise NotImplementedError( f\"Dual basis not defined",
"reference entity. Its shape must be a vector with the correct dimension, its",
"in self.index_shape) def get_value_indices(self): '''A tuple of GEM :class:`~gem.Index` of the correct extents",
"entity, and for each possible entity orientation, the DoF permutation array that maps",
"1, 0]}}} Note that there are two entities on dimension ``0`` (vertices), each",
"``0`` (vertices), each of which has only one possible orientation, while there is",
"chain import numpy import gem from gem.interpreter import evaluate from gem.optimise import delta_elimination,",
"there is a single entity on dimension ``1`` (interval), which has two possible",
"basis evaluation at the nodes of the reference element. Currently only works for",
":param order: return derivatives up to this order. :param refcoords: GEM expression representing",
"evaluation at the nodes of the reference element. Currently only works for flat",
"the reference cell to a physical cell for all basis functions of the",
":param entity: the cell entity on which to tabulate. :param coordinate_mapping: a :class:`~.physically_mapped.PhysicalGeometry`",
"tuple of GEM :class:`~gem.Index` of the correct extents to loop over the value",
"return self._entity_support_dofs @abstractmethod def space_dimension(self): '''Return the dimension of the finite element space.'''",
"'''Return a dual evaluation gem weight tensor Q and point set x to",
"extents to loop over the basis functions of this element.''' return tuple(gem.Index(extent=d) for",
"element tQ is constructed from the base element's Q by taking the outer",
"is a tensor with dimensions .. code-block:: text (num_nodes, num_points, dual_weight_shape[0], ..., dual_weight_shape[n])",
"already free indices rather than being left in its shape (as either ``num_points``",
"scalar then Q, for a general scalar FIAT element, is a matrix with",
"local DoF ordering to the canonical global DoF ordering. The entity permutations `dict`",
"import make_quadrature class FiniteElementBase(metaclass=ABCMeta): @abstractproperty def cell(self): '''The reference cell on which the",
"for each possible entity orientation, the DoF permutation array that maps the entity",
"evaluation.fids == () result[f] = [dof for dof, i in enumerate(ints) if i",
"NOTE: any shape indices in the expression are because the # expression is",
"(interval), which has two possible orientations representing non-reflected and reflected intervals. ''' raise",
"here. evaluation = gem.optimise.contraction(evaluation, shape_indices) return evaluation, basis_indices @abstractproperty def mapping(self): '''Appropriate mapping",
"function fn at. The general dual evaluation is then Q * fn(x) (the",
"get_value_indices(self): '''A tuple of GEM :class:`~gem.Index` of the correct extents to loop over",
"in sub_entities])) for e, sub_entities in entities.items()} for dim, entities in self.cell.sub_entities.items()} def",
"the dual weights are scalar then Q, for a general scalar FIAT element,",
"with dimensions .. code-block:: text (num_nodes, num_points, dual_weight_shape[0], ..., dual_weight_shape[n]) If the dual",
"element is defined.''' @abstractproperty def degree(self): '''The degree of the embedding polynomial space.",
"then Q, for a general scalar FIAT element, is a matrix with dimensions",
"x (which is now a TensorPointSet). If the dual basis is of a",
"elimination to # the expression sum_indices, factors = delta_elimination(*traverse_product(expr)) expr = sum_factorise(sum_indices, factors)",
"each entity, and for each possible entity orientation, the DoF permutation array that",
"a tensor product or FlattenedDimensions element with N factors then Q in general",
"that match the free indices of x (which is now a TensorPointSet). If",
"gem weight tensor Q and point set x to dual evaluate a function",
"and point set x to dual evaluate a function fn at. The general",
"set object. :param entity: the cell entity on which to tabulate. :param coordinate_mapping:",
"num_nodes_factorN, num_points_factor1, ..., num_points_factorN, dual_weight_shape[0], ..., dual_weight_shape[n]) where num_points_factorX are made free indices",
"code-block:: python3 {0: {0: {0: [0]}, 1: {0: [0]}}, 1: {0: {0: [0,",
"the finite element space.''' @abstractproperty def index_shape(self): '''A tuple indicating the number of",
"contraction with x, # ignoring any shape indices to avoid hitting the sum-",
"FIAT element dual bases are built from their ``Functional.pt_dict`` properties. Therefore any FIAT",
"interval, for instance, is given by: .. code-block:: python3 {0: {0: {0: [0]},",
"non-reflected and reflected intervals. ''' raise NotImplementedError(f\"entity_permutations not yet implemented for {type(self)}\") @cached_property",
"import cached_property from finat.quadrature import make_quadrature class FiniteElementBase(metaclass=ABCMeta): @abstractproperty def cell(self): '''The reference",
"def degree(self): '''The degree of the embedding polynomial space. In the tensor case",
"to this order. :param ps: the point set object. :param entity: the cell",
"a general scalar FIAT element, is a matrix with dimensions .. code-block:: text",
"{0: {0: [0]}, 1: {0: [0]}}, 1: {0: {0: [0, 1, 2], 1:",
"in self.cell.sub_entities.items()} def entity_closure_dofs(self): '''Return the map of topological entities to degrees of",
"gem.indices(len(expr.shape)) basis_indices = gem.indices(len(Q.shape) - len(expr.shape)) Qi = Q[basis_indices + shape_indices] expri =",
"functions on the facet vals, = self.basis_evaluation(0, quad.point_set, entity=(entity_dim, f)).values() # Integrate the",
".. code-block:: python3 {0: {0: {0: [0]}, 1: {0: [0]}}, 1: {0: {0:",
"the function to dual evaluate. Callable should take in an :class:`AbstractPointSet` and return",
"shape_indices) return evaluation, basis_indices @abstractproperty def mapping(self): '''Appropriate mapping from the reference cell",
"entity: the cell entity on which to tabulate. ''' @property def dual_basis(self): '''Return",
"entity_closure_dofs(self): '''Return the map of topological entities to degrees of freedom on the",
"permutations `dict` for the degree 4 Lagrange finite element on the interval, for",
"with dimensions .. code-block:: text (num_nodes_factor1, ..., num_nodes_factorN, num_points_factor1, ..., num_points_factorN, dual_weight_shape[0], ...,",
"geometry callbacks (may be None). ''' @abstractmethod def point_evaluation(self, order, refcoords, entity=None): '''Return",
"the dual evaluation contraction. .. note:: FIAT element dual bases are built from",
"correct extents to loop over the basis functions of this element.''' return tuple(gem.Index(extent=d)",
"dual basis. ''' raise NotImplementedError( f\"Dual basis not defined for element {type(self).__name__}\" )",
"along the the indices of x and any shape introduced by fn). If",
"the map of topological entities to degrees of freedom on the closure of",
"degree 4 Lagrange finite element on the interval, for instance, is given by:",
"elements: tensor elements are implemented in :class:`TensorFiniteElement`. :param fn: Callable representing the function",
"= gem.indices(len(Q.shape) - len(expr.shape)) Qi = Q[basis_indices + shape_indices] expri = expr[shape_indices] evaluation",
"labelling confusion when performing the dual evaluation contraction. .. note:: FIAT element dual",
"raise NotImplementedError(f\"entity_permutations not yet implemented for {type(self)}\") @cached_property def _entity_closure_dofs(self): # Compute the",
"freedom that have non-zero support on those entities for the finite element.''' return",
"Callable representing the function to dual evaluate. Callable should take in an :class:`AbstractPointSet`",
"from itertools import chain import numpy import gem from gem.interpreter import evaluate from",
"form (FEEC)''' @abstractmethod def entity_dofs(self): '''Return the map of topological entities to degrees",
"order, ps, entity=None, coordinate_mapping=None): '''Return code for evaluating the element at known points",
"(may be None). ''' @abstractmethod def point_evaluation(self, order, refcoords, entity=None): '''Return code for",
"in general is a tensor with dimensions .. code-block:: text (num_nodes_factor1, ..., num_nodes_factorN,",
"len(expr.shape)) Qi = Q[basis_indices + shape_indices] expri = expr[shape_indices] evaluation = gem.IndexSum(Qi *",
"in the element. For example a scalar quadratic Lagrange element on a triangle",
"None). ''' @abstractmethod def point_evaluation(self, order, refcoords, entity=None): '''Return code for evaluating the",
"quadratic Lagrange element on a triangle would return (6,) while a vector valued",
"element.''' @property def entity_permutations(self): '''Returns a nested dictionary that gives, for each dimension,",
"''' @property def dual_basis(self): '''Return a dual evaluation gem weight tensor Q and",
"rather than being left in its shape (as either ``num_points`` or ``num_points_factorX``). This",
"factorisation and delta elimination to # the expression sum_indices, factors = delta_elimination(*traverse_product(expr)) expr",
"gem.utils import cached_property from finat.quadrature import make_quadrature class FiniteElementBase(metaclass=ABCMeta): @abstractproperty def cell(self): '''The",
"tQ is constructed from the base element's Q by taking the outer product",
"the basis functions on the facet. ints = gem.IndexSum( gem.Product(gem.IndexSum(gem.Product(gem.Indexed(vals, beta + zeta),",
"result[f] = [dof for dof, i in enumerate(ints) if i > eps] esd[entity_dim]",
"⊗ 𝟙ₛ₁ ⊗ 𝟙ₛ₂ ⊗ ... ⊗ 𝟙ₛₙ .. note:: When Q is",
"those points. :returns: A tuple ``(dual_evaluation_gem_expression, basis_indices)`` where the given ``basis_indices`` are those",
"basis_evaluation(self, order, ps, entity=None, coordinate_mapping=None): '''Return code for evaluating the element at known",
"for flat elements: tensor elements are implemented in :class:`TensorFiniteElement`. :param fn: Callable representing",
"dual basis evaluation at the nodes of the reference element. Currently only works",
"NotImplementedError( f\"Dual basis not defined for element {type(self).__name__}\" ) def dual_evaluation(self, fn): '''Get",
"cell on which the element is defined.''' @abstractproperty def degree(self): '''The degree of",
"is constructed from the base element's Q by taking the outer product with",
"``num_points_factorX``). This is to avoid index labelling confusion when performing the dual evaluation",
"element with some shape (S1, S2, ..., Sn) then the tensor element tQ",
"defined for element {type(self).__name__}\" ) def dual_evaluation(self, fn): '''Get a GEM expression for",
"tensor case this is a tuple. ''' @abstractproperty def formdegree(self): '''Degree of the",
"@cached_property def _entity_closure_dofs(self): # Compute the nodes on the closure of each sub_entity.",
"Q in general is a tensor with dimensions .. code-block:: text (num_nodes_factor1, ...,",
"= expr[shape_indices] evaluation = gem.IndexSum(Qi * expri, x.indices + shape_indices) # Now we",
"their ``Functional.pt_dict`` properties. Therefore any FIAT dual bases with derivative nodes represented via",
"for {type(self)}\") @cached_property def _entity_closure_dofs(self): # Compute the nodes on the closure of",
"get_indices(self): '''A tuple of GEM :class:`Index` of the correct extents to loop over",
"element.''' return self._entity_closure_dofs @cached_property def _entity_support_dofs(self): esd = {} for entity_dim in self.cell.sub_entities.keys():",
"# expression is tensor valued. assert expr.shape == Q.shape[len(Q.shape)-len(expr.shape):] shape_indices = gem.indices(len(expr.shape)) basis_indices",
"to tabulate. :param coordinate_mapping: a :class:`~.physically_mapped.PhysicalGeometry` object that provides physical geometry callbacks (may",
"element with N factors then Q in general is a tensor with dimensions",
"tensor element tQ is constructed from the base element's Q by taking the",
"for entity_dim in self.cell.sub_entities.keys(): beta = self.get_indices() zeta = self.get_value_indices() entity_cell = self.cell.construct_subelement(entity_dim)",
"freedom in the element. For example a scalar quadratic Lagrange element on a",
"the element.''' @property def fiat_equivalent(self): '''The FIAT element equivalent to this FInAT element.'''",
"with some shape (S1, S2, ..., Sn) then the tensor element tQ is",
"return derivatives up to this order. :param ps: the point set object. :param",
"weights are tensor valued then Q, for a general tensor valued FIAT element,",
"evaluate. Callable should take in an :class:`AbstractPointSet` and return a GEM expression for",
"dual evaluation contraction. .. note:: FIAT element dual bases are built from their",
"Its shape must be a vector with the correct dimension, its free indices",
"on dimension ``1`` (interval), which has two possible orientations representing non-reflected and reflected",
"basis is of a tensor product or FlattenedDimensions element with N factors then",
"free indices rather than being left in its shape (as either ``num_points`` or",
"embedding polynomial space. In the tensor case this is a tuple. ''' @abstractproperty",
"basis_indices @abstractproperty def mapping(self): '''Appropriate mapping from the reference cell to a physical",
"element.''' @property def fiat_equivalent(self): '''The FIAT element equivalent to this FInAT element.''' raise",
"the dual basis is of a tensor product or FlattenedDimensions element with N",
"general is a tensor with dimensions .. code-block:: text (num_nodes_factor1, ..., num_nodes_factorN, num_points_factor1,",
"is a tensor with dimensions .. code-block:: text (num_nodes_factor1, ..., num_nodes_factorN, num_points_factor1, ...,",
"have non-zero support on those entities for the finite element.''' return self._entity_support_dofs @abstractmethod",
"Q ⊗ 𝟙ₛ₁ ⊗ 𝟙ₛ₂ ⊗ ... ⊗ 𝟙ₛₙ .. note:: When Q",
"the same element would return (6, 2)''' @abstractproperty def value_shape(self): '''A tuple indicating",
"is defined.''' @abstractproperty def degree(self): '''The degree of the embedding polynomial space. In",
"element.''' def entity_support_dofs(elem, entity_dim): '''Return the map of entity id to the degrees",
"entity id to the degrees of freedom for which the corresponding basis functions",
"general tensor valued FIAT element, is a tensor with dimensions .. code-block:: text",
"num_points_factorX are made free indices that match the free indices of x (which",
".. code-block:: text tQ = Q ⊗ 𝟙ₛ₁ ⊗ 𝟙ₛ₂ ⊗ ... ⊗",
"has two possible orientations representing non-reflected and reflected intervals. ''' raise NotImplementedError(f\"entity_permutations not",
"𝟙ₛ₂ ⊗ ... ⊗ 𝟙ₛₙ .. note:: When Q is returned, the contraction",
"(6,) while a vector valued version of the same element would return (6,",
"which the corresponding basis functions take non-zero values. :arg elem: FInAT finite element",
"for dof, i in enumerate(ints) if i > eps] esd[entity_dim] = result return",
"vals, = self.basis_evaluation(0, quad.point_set, entity=(entity_dim, f)).values() # Integrate the square of the basis",
"indices to avoid hitting the sum- # factorisation index limit (this is a",
":returns: A tuple ``(dual_evaluation_gem_expression, basis_indices)`` where the given ``basis_indices`` are those needed to",
"element dual bases are built from their ``Functional.pt_dict`` properties. Therefore any FIAT dual",
"cell to a physical cell for all basis functions of the finite element.'''",
"a tensor with dimensions .. code-block:: text (num_nodes_factor1, ..., num_nodes_factorN, num_points_factor1, ..., num_points_factorN,",
"functions take non-zero values. :arg elem: FInAT finite element :arg entity_dim: Dimension of",
"GEM :class:`Index` of the correct extents to loop over the basis functions of",
"matrices: .. code-block:: text tQ = Q ⊗ 𝟙ₛ₁ ⊗ 𝟙ₛ₂ ⊗ ...",
"element, is a tensor with dimensions .. code-block:: text (num_nodes, num_points, dual_weight_shape[0], ...,",
"derivatives up to this order. :param ps: the point set object. :param entity:",
"tuple indicating the number of degrees of freedom in the element. For example",
"to dual evaluate. Callable should take in an :class:`AbstractPointSet` and return a GEM",
"encoded within ``fn``) ''' Q, x = self.dual_basis expr = fn(x) # Apply",
"basis functions take non-zero values. :arg elem: FInAT finite element :arg entity_dim: Dimension",
"sub_entities in entities.items()} for dim, entities in self.cell.sub_entities.items()} def entity_closure_dofs(self): '''Return the map",
"closure of those entities for the finite element.''' return self._entity_closure_dofs @cached_property def _entity_support_dofs(self):",
"indices of x (which is now a TensorPointSet). If the dual basis is",
"a safe value? result = {} for f in self.entity_dofs()[entity_dim].keys(): # Tabulate basis",
"finite element.''' return self._entity_closure_dofs @cached_property def _entity_support_dofs(self): esd = {} for entity_dim in",
"this element.''' return tuple(gem.Index(extent=d) for d in self.value_shape) @abstractmethod def basis_evaluation(self, order, ps,",
"If the dual weights are scalar then Q, for a general scalar FIAT",
"element. :param order: return derivatives up to this order. :param ps: the point",
"confusion when performing the dual evaluation contraction. .. note:: FIAT element dual bases",
"each possible entity orientation, the DoF permutation array that maps the entity local",
"the point set are already free indices rather than being left in its",
"which is compiled from ``dual_evaluation_gem_expression`` (alongside any argument multiindices already encoded within ``fn``)",
"the finite element.''' return self._entity_closure_dofs @cached_property def _entity_support_dofs(self): esd = {} for entity_dim",
"space.''' @abstractproperty def index_shape(self): '''A tuple indicating the number of degrees of freedom",
"@property def dual_basis(self): '''Return a dual evaluation gem weight tensor Q and point",
"sum_indices, factors = delta_elimination(*traverse_product(expr)) expr = sum_factorise(sum_indices, factors) # NOTE: any shape indices",
"@abstractmethod def point_evaluation(self, order, refcoords, entity=None): '''Return code for evaluating the element at",
"weight tensor Q and point set x to dual evaluate a function fn",
"basis is of a tensor finite element with some shape (S1, S2, ...,",
"dual bases are built from their ``Functional.pt_dict`` properties. Therefore any FIAT dual bases",
"tuple ``(dual_evaluation_gem_expression, basis_indices)`` where the given ``basis_indices`` are those needed to form a",
"Q, for a general scalar FIAT element, is a matrix with dimensions ..",
"elem: FInAT finite element :arg entity_dim: Dimension of the cell subentity. ''' return",
"(FEEC)''' @abstractmethod def entity_dofs(self): '''Return the map of topological entities to degrees of",
"f\"Cannot make equivalent FIAT element for {type(self).__name__}\" ) def get_indices(self): '''A tuple of",
"element.''' return tuple(gem.Index(extent=d) for d in self.value_shape) @abstractmethod def basis_evaluation(self, order, ps, entity=None,",
"= evaluation.arr.flatten() assert evaluation.fids == () result[f] = [dof for dof, i in",
"entity=(entity_dim, f)).values() # Integrate the square of the basis functions on the facet.",
"+ shape_indices] expri = expr[shape_indices] evaluation = gem.IndexSum(Qi * expri, x.indices + shape_indices)",
"In the tensor case this is a tuple. ''' @abstractproperty def formdegree(self): '''Degree",
"do a more targeted job here. evaluation = gem.optimise.contraction(evaluation, shape_indices) return evaluation, basis_indices",
"the nodes of the reference element. Currently only works for flat elements: tensor",
"gem.optimise import delta_elimination, sum_factorise, traverse_product from gem.utils import cached_property from finat.quadrature import make_quadrature",
"e, sub_entities in entities.items()} for dim, entities in self.cell.sub_entities.items()} def entity_closure_dofs(self): '''Return the",
"ignoring any shape indices to avoid hitting the sum- # factorisation index limit",
"to loop over the basis functions of this element.''' return tuple(gem.Index(extent=d) for d",
"avoid hitting the sum- # factorisation index limit (this is a bit of",
"if i > eps] esd[entity_dim] = result return esd def entity_support_dofs(self): '''Return the",
"of entity id to the degrees of freedom for which the corresponding basis",
"are two entities on dimension ``0`` (vertices), each of which has only one",
"num_points_factorN, dual_weight_shape[0], ..., dual_weight_shape[n]) where num_points_factorX are made free indices that match the",
"at those points. :returns: A tuple ``(dual_evaluation_gem_expression, basis_indices)`` where the given ``basis_indices`` are",
"When Q is returned, the contraction indices of the point set are already",
"= self.basis_evaluation(0, quad.point_set, entity=(entity_dim, f)).values() # Integrate the square of the basis functions",
"of which has only one possible orientation, while there is a single entity",
"the given ``basis_indices`` are those needed to form a return expression for the",
"fn(x) along the the indices of x and any shape introduced by fn).",
"the new contraction with x, # ignoring any shape indices to avoid hitting",
"tensor with dimensions .. code-block:: text (num_nodes, num_points, dual_weight_shape[0], ..., dual_weight_shape[n]) If the",
"from the reference cell to a physical cell for all basis functions of",
"already encoded within ``fn``) ''' Q, x = self.dual_basis expr = fn(x) #",
"on which to tabulate. :param coordinate_mapping: a :class:`~.physically_mapped.PhysicalGeometry` object that provides physical geometry",
"its free indices are arbitrary. :param entity: the cell entity on which to",
"are those needed to form a return expression for the code which is",
"fn). If the dual weights are scalar then Q, for a general scalar",
"FIAT element, is a tensor with dimensions .. code-block:: text (num_nodes, num_points, dual_weight_shape[0],",
"gem.indices(len(Q.shape) - len(expr.shape)) Qi = Q[basis_indices + shape_indices] expri = expr[shape_indices] evaluation =",
"this a safe value? result = {} for f in self.entity_dofs()[entity_dim].keys(): # Tabulate",
"is a tuple. ''' @abstractproperty def formdegree(self): '''Degree of the associated form (FEEC)'''",
"Integrate the square of the basis functions on the facet. ints = gem.IndexSum(",
"a hack). # Really need to do a more targeted job here. evaluation",
"Lagrange finite element on the interval, for instance, is given by: .. code-block::",
"the finite element.''' def entity_support_dofs(elem, entity_dim): '''Return the map of entity id to",
"now a TensorPointSet). If the dual basis is of a tensor finite element",
"argument multiindices already encoded within ``fn``) ''' Q, x = self.dual_basis expr =",
"of degrees of freedom in the element. For example a scalar quadratic Lagrange",
"..., dual_weight_shape[n]) where num_points_factorX are made free indices that match the free indices",
"text tQ = Q ⊗ 𝟙ₛ₁ ⊗ 𝟙ₛ₂ ⊗ ... ⊗ 𝟙ₛₙ ..",
"orientations representing non-reflected and reflected intervals. ''' raise NotImplementedError(f\"entity_permutations not yet implemented for",
"only works for flat elements: tensor elements are implemented in :class:`TensorFiniteElement`. :param fn:",
"possible orientation, while there is a single entity on dimension ``1`` (interval), which",
"a dual evaluation gem weight tensor Q and point set x to dual",
"of this element.''' return tuple(gem.Index(extent=d) for d in self.value_shape) @abstractmethod def basis_evaluation(self, order,",
"If the dual weights are tensor valued then Q, for a general tensor",
"take in an :class:`AbstractPointSet` and return a GEM expression for evaluation of the",
"i > eps] esd[entity_dim] = result return esd def entity_support_dofs(self): '''Return the map",
":class:`AbstractPointSet` and return a GEM expression for evaluation of the function at those",
"either ``num_points`` or ``num_points_factorX``). This is to avoid index labelling confusion when performing",
"on the reference element. :param order: return derivatives up to this order. :param",
"elements are implemented in :class:`TensorFiniteElement`. :param fn: Callable representing the function to dual",
"x, # ignoring any shape indices to avoid hitting the sum- # factorisation",
"for each dimension, for each entity, and for each possible entity orientation, the",
"mapping from the reference cell to a physical cell for all basis functions",
"associated form (FEEC)''' @abstractmethod def entity_dofs(self): '''Return the map of topological entities to",
"... ⊗ 𝟙ₛₙ .. note:: When Q is returned, the contraction indices of",
"shape must be a vector with the correct dimension, its free indices are",
"entities.items()} for dim, entities in self.cell.sub_entities.items()} def entity_closure_dofs(self): '''Return the map of topological",
"code-block:: text (num_nodes, num_points, dual_weight_shape[0], ..., dual_weight_shape[n]) If the dual basis is of",
"entity. Its shape must be a vector with the correct dimension, its free",
"this is a tuple. ''' @abstractproperty def formdegree(self): '''Degree of the associated form",
"= gem.IndexSum(Qi * expri, x.indices + shape_indices) # Now we want to factorise",
"mapping(self): '''Appropriate mapping from the reference cell to a physical cell for all",
"quad.point_set, entity=(entity_dim, f)).values() # Integrate the square of the basis functions on the",
"there are two entities on dimension ``0`` (vertices), each of which has only",
"not yet implemented for {type(self)}\") @cached_property def _entity_closure_dofs(self): # Compute the nodes on",
"maps the entity local DoF ordering to the canonical global DoF ordering. The",
"performing the dual evaluation contraction. .. note:: FIAT element dual bases are built",
"we want to factorise over the new contraction with x, # ignoring any",
"abstractmethod from itertools import chain import numpy import gem from gem.interpreter import evaluate",
":param refcoords: GEM expression representing the coordinates on the reference entity. Its shape",
"# NOTE: any shape indices in the expression are because the # expression",
"would return (6,) while a vector valued version of the same element would",
"sorted(chain(*[entity_dofs[d][se] for d, se in sub_entities])) for e, sub_entities in entities.items()} for dim,",
"self.cell.sub_entities.keys(): beta = self.get_indices() zeta = self.get_value_indices() entity_cell = self.cell.construct_subelement(entity_dim) quad = make_quadrature(entity_cell,",
"= sum_factorise(sum_indices, factors) # NOTE: any shape indices in the expression are because",
"the canonical global DoF ordering. The entity permutations `dict` for the degree 4",
"dimension ``1`` (interval), which has two possible orientations representing non-reflected and reflected intervals.",
"a scalar quadratic Lagrange element on a triangle would return (6,) while a",
"values. :arg elem: FInAT finite element :arg entity_dim: Dimension of the cell subentity.",
"on the facet vals, = self.basis_evaluation(0, quad.point_set, entity=(entity_dim, f)).values() # Integrate the square",
"from gem.optimise import delta_elimination, sum_factorise, traverse_product from gem.utils import cached_property from finat.quadrature import",
"correct extents to loop over the value shape of this element.''' return tuple(gem.Index(extent=d)",
"any shape introduced by fn). If the dual weights are scalar then Q,",
"'''A tuple of GEM :class:`~gem.Index` of the correct extents to loop over the",
"arbitrary points on the reference element. :param order: return derivatives up to this",
"which to tabulate. :param coordinate_mapping: a :class:`~.physically_mapped.PhysicalGeometry` object that provides physical geometry callbacks",
"in :class:`TensorFiniteElement`. :param fn: Callable representing the function to dual evaluate. Callable should",
"se in sub_entities])) for e, sub_entities in entities.items()} for dim, entities in self.cell.sub_entities.items()}",
"dual_basis(self): '''Return a dual evaluation gem weight tensor Q and point set x",
"id to the degrees of freedom for which the corresponding basis functions take",
"corresponding basis functions take non-zero values. :arg elem: FInAT finite element :arg entity_dim:",
"the base element's Q by taking the outer product with appropriately sized identity",
"the map of topological entities to degrees of freedom that have non-zero support",
"of those entities for the finite element.''' return self._entity_closure_dofs @cached_property def _entity_support_dofs(self): esd",
"self.dual_basis expr = fn(x) # Apply targeted sum factorisation and delta elimination to",
"a tensor with dimensions .. code-block:: text (num_nodes, num_points, dual_weight_shape[0], ..., dual_weight_shape[n]) If",
"is a matrix with dimensions .. code-block:: text (num_nodes, num_points) If the dual",
"@abstractmethod def entity_dofs(self): '''Return the map of topological entities to degrees of freedom",
"''' raise NotImplementedError( f\"Dual basis not defined for element {type(self).__name__}\" ) def dual_evaluation(self,",
"this order. :param ps: the point set object. :param entity: the cell entity",
"for f in self.entity_dofs()[entity_dim].keys(): # Tabulate basis functions on the facet vals, =",
"value shape of this element.''' return tuple(gem.Index(extent=d) for d in self.value_shape) @abstractmethod def",
"..., dual_weight_shape[n]) If the dual basis is of a tensor product or FlattenedDimensions",
"bit of a hack). # Really need to do a more targeted job",
"self.get_value_indices() entity_cell = self.cell.construct_subelement(entity_dim) quad = make_quadrature(entity_cell, (2*numpy.array(self.degree)).tolist()) eps = 1.e-8 # Is",
"FInAT element.''' raise NotImplementedError( f\"Cannot make equivalent FIAT element for {type(self).__name__}\" ) def",
"the dual basis evaluation at the nodes of the reference element. Currently only",
"entities to degrees of freedom that have non-zero support on those entities for",
"{0: {0: [0, 1, 2], 1: [2, 1, 0]}}} Note that there are",
"element at known points on the reference element. :param order: return derivatives up",
"@abstractproperty def formdegree(self): '''Degree of the associated form (FEEC)''' @abstractmethod def entity_dofs(self): '''Return",
"to the canonical global DoF ordering. The entity permutations `dict` for the degree",
"for e, sub_entities in entities.items()} for dim, entities in self.cell.sub_entities.items()} def entity_closure_dofs(self): '''Return",
"zeta = self.get_value_indices() entity_cell = self.cell.construct_subelement(entity_dim) quad = make_quadrature(entity_cell, (2*numpy.array(self.degree)).tolist()) eps = 1.e-8",
"``(dual_evaluation_gem_expression, basis_indices)`` where the given ``basis_indices`` are those needed to form a return",
"quad.point_set.indices ) evaluation, = evaluate([gem.ComponentTensor(ints, beta)]) ints = evaluation.arr.flatten() assert evaluation.fids == ()",
"beta + zeta), gem.Indexed(vals, beta + zeta)), zeta), quad.weight_expression), quad.point_set.indices ) evaluation, =",
"the facet vals, = self.basis_evaluation(0, quad.point_set, entity=(entity_dim, f)).values() # Integrate the square of",
"the shape of the element.''' @property def fiat_equivalent(self): '''The FIAT element equivalent to",
"of freedom for which the corresponding basis functions take non-zero values. :arg elem:",
"than being left in its shape (as either ``num_points`` or ``num_points_factorX``). This is",
"known points on the reference element. :param order: return derivatives up to this",
"'''Return the map of topological entities to degrees of freedom for the finite",
"beta)]) ints = evaluation.arr.flatten() assert evaluation.fids == () result[f] = [dof for dof,",
"representing the coordinates on the reference entity. Its shape must be a vector",
"built from their ``Functional.pt_dict`` properties. Therefore any FIAT dual bases with derivative nodes",
"DoF permutation array that maps the entity local DoF ordering to the canonical",
"''' Q, x = self.dual_basis expr = fn(x) # Apply targeted sum factorisation",
"value_shape(self): '''A tuple indicating the shape of the element.''' @property def fiat_equivalent(self): '''The",
"expression are because the # expression is tensor valued. assert expr.shape == Q.shape[len(Q.shape)-len(expr.shape):]",
"for element {type(self).__name__}\" ) def dual_evaluation(self, fn): '''Get a GEM expression for performing",
"order, refcoords, entity=None): '''Return code for evaluating the element at an arbitrary points",
"set are already free indices rather than being left in its shape (as",
"then Q * fn(x) (the contraction of Q with fn(x) along the the",
"entity_support_dofs(self): '''Return the map of topological entities to degrees of freedom that have",
"index_shape(self): '''A tuple indicating the number of degrees of freedom in the element.",
"value? result = {} for f in self.entity_dofs()[entity_dim].keys(): # Tabulate basis functions on",
"tuple. ''' @abstractproperty def formdegree(self): '''Degree of the associated form (FEEC)''' @abstractmethod def"
] |
[
"the state of the worker queues active = 0 overloaded = 0 empty",
"state of the worker queues active = 0 overloaded = 0 empty =",
"inactive.append(worker) # take an action if necessary if len(empty) > 1 and overloaded",
"import AbstractSelfAdaptingStrategy class SimpleSelfAdaptingStrategy(AbstractSelfAdaptingStrategy): \"\"\"Represents a simple SA controller for activation/deactivation of queues",
"the beginning, make only the first worker active for worker in workers: worker.set_attribute(\"active\",",
"False) # put idle worker to sleep elif inactive and overloaded > 0:",
"1 else: inactive.append(worker) # take an action if necessary if len(empty) > 1",
"elif worker.jobs_count() > 1: overloaded += 1 else: inactive.append(worker) # take an action",
"inactive work queues for worker in workers: if worker.get_attribute(\"active\"): active += 1 if",
"1 if worker.jobs_count() == 0: empty.append(worker) elif worker.jobs_count() > 1: overloaded += 1",
"# At the beginning, make only the first worker active for worker in",
"def do_adapt(self, ts, dispatcher, workers, job=None): # analyse the state of the worker",
"idle. \"\"\" def init(self, ts, dispatcher, workers): # At the beginning, make only",
"Activates suspended worker queues when the system gets staturated, deactivates queues that are",
"empty work queues inactive = [] # inactive work queues for worker in",
"deactivates queues that are idle. \"\"\" def init(self, ts, dispatcher, workers): # At",
"queues that are idle. \"\"\" def init(self, ts, dispatcher, workers): # At the",
"and empty: empty[0].set_attribute(\"active\", False) # put idle worker to sleep elif inactive and",
"workers: worker.set_attribute(\"active\", False) workers[0].set_attribute(\"active\", True) def do_adapt(self, ts, dispatcher, workers, job=None): # analyse",
"queues inactive = [] # inactive work queues for worker in workers: if",
"the worker queues active = 0 overloaded = 0 empty = [] #",
"active for worker in workers: worker.set_attribute(\"active\", False) workers[0].set_attribute(\"active\", True) def do_adapt(self, ts, dispatcher,",
"work queues inactive = [] # inactive work queues for worker in workers:",
"queues active = 0 overloaded = 0 empty = [] # active yet",
"# active yet empty work queues inactive = [] # inactive work queues",
"if len(empty) > 1 and overloaded == 0 and empty: empty[0].set_attribute(\"active\", False) #",
"worker active for worker in workers: worker.set_attribute(\"active\", False) workers[0].set_attribute(\"active\", True) def do_adapt(self, ts,",
"> 1 and overloaded == 0 and empty: empty[0].set_attribute(\"active\", False) # put idle",
"do_adapt(self, ts, dispatcher, workers, job=None): # analyse the state of the worker queues",
"suspended worker queues when the system gets staturated, deactivates queues that are idle.",
"empty[0].set_attribute(\"active\", False) # put idle worker to sleep elif inactive and overloaded >",
"# inactive work queues for worker in workers: if worker.get_attribute(\"active\"): active += 1",
"and overloaded == 0 and empty: empty[0].set_attribute(\"active\", False) # put idle worker to",
"== 0 and empty: empty[0].set_attribute(\"active\", False) # put idle worker to sleep elif",
"workers[0].set_attribute(\"active\", True) def do_adapt(self, ts, dispatcher, workers, job=None): # analyse the state of",
"empty.append(worker) elif worker.jobs_count() > 1: overloaded += 1 else: inactive.append(worker) # take an",
"worker.set_attribute(\"active\", False) workers[0].set_attribute(\"active\", True) def do_adapt(self, ts, dispatcher, workers, job=None): # analyse the",
"worker to sleep elif inactive and overloaded > 0: inactive[0].set_attribute(\"active\", True) # wake",
"are idle. \"\"\" def init(self, ts, dispatcher, workers): # At the beginning, make",
"if necessary if len(empty) > 1 and overloaded == 0 and empty: empty[0].set_attribute(\"active\",",
"overloaded = 0 empty = [] # active yet empty work queues inactive",
"queues for worker in workers: if worker.get_attribute(\"active\"): active += 1 if worker.jobs_count() ==",
"if worker.jobs_count() == 0: empty.append(worker) elif worker.jobs_count() > 1: overloaded += 1 else:",
"class SimpleSelfAdaptingStrategy(AbstractSelfAdaptingStrategy): \"\"\"Represents a simple SA controller for activation/deactivation of queues based on",
"simple SA controller for activation/deactivation of queues based on current workload. Activates suspended",
"At the beginning, make only the first worker active for worker in workers:",
"# analyse the state of the worker queues active = 0 overloaded =",
"SimpleSelfAdaptingStrategy(AbstractSelfAdaptingStrategy): \"\"\"Represents a simple SA controller for activation/deactivation of queues based on current",
"else: inactive.append(worker) # take an action if necessary if len(empty) > 1 and",
"for worker in workers: if worker.get_attribute(\"active\"): active += 1 if worker.jobs_count() == 0:",
"interfaces import AbstractSelfAdaptingStrategy class SimpleSelfAdaptingStrategy(AbstractSelfAdaptingStrategy): \"\"\"Represents a simple SA controller for activation/deactivation of",
"for worker in workers: worker.set_attribute(\"active\", False) workers[0].set_attribute(\"active\", True) def do_adapt(self, ts, dispatcher, workers,",
"put idle worker to sleep elif inactive and overloaded > 0: inactive[0].set_attribute(\"active\", True)",
"if worker.get_attribute(\"active\"): active += 1 if worker.jobs_count() == 0: empty.append(worker) elif worker.jobs_count() >",
"only the first worker active for worker in workers: worker.set_attribute(\"active\", False) workers[0].set_attribute(\"active\", True)",
"1: overloaded += 1 else: inactive.append(worker) # take an action if necessary if",
"overloaded == 0 and empty: empty[0].set_attribute(\"active\", False) # put idle worker to sleep",
"a simple SA controller for activation/deactivation of queues based on current workload. Activates",
"ts, dispatcher, workers): # At the beginning, make only the first worker active",
"take an action if necessary if len(empty) > 1 and overloaded == 0",
"def init(self, ts, dispatcher, workers): # At the beginning, make only the first",
"job=None): # analyse the state of the worker queues active = 0 overloaded",
"necessary if len(empty) > 1 and overloaded == 0 and empty: empty[0].set_attribute(\"active\", False)",
"queues when the system gets staturated, deactivates queues that are idle. \"\"\" def",
"\"\"\" def init(self, ts, dispatcher, workers): # At the beginning, make only the",
"True) def do_adapt(self, ts, dispatcher, workers, job=None): # analyse the state of the",
"== 0: empty.append(worker) elif worker.jobs_count() > 1: overloaded += 1 else: inactive.append(worker) #",
"> 1: overloaded += 1 else: inactive.append(worker) # take an action if necessary",
"make only the first worker active for worker in workers: worker.set_attribute(\"active\", False) workers[0].set_attribute(\"active\",",
"= [] # active yet empty work queues inactive = [] # inactive",
"dispatcher, workers): # At the beginning, make only the first worker active for",
"gets staturated, deactivates queues that are idle. \"\"\" def init(self, ts, dispatcher, workers):",
"of the worker queues active = 0 overloaded = 0 empty = []",
"current workload. Activates suspended worker queues when the system gets staturated, deactivates queues",
"in workers: worker.set_attribute(\"active\", False) workers[0].set_attribute(\"active\", True) def do_adapt(self, ts, dispatcher, workers, job=None): #",
"empty: empty[0].set_attribute(\"active\", False) # put idle worker to sleep elif inactive and overloaded",
"0 and empty: empty[0].set_attribute(\"active\", False) # put idle worker to sleep elif inactive",
"worker.get_attribute(\"active\"): active += 1 if worker.jobs_count() == 0: empty.append(worker) elif worker.jobs_count() > 1:",
"an action if necessary if len(empty) > 1 and overloaded == 0 and",
"0 overloaded = 0 empty = [] # active yet empty work queues",
"the system gets staturated, deactivates queues that are idle. \"\"\" def init(self, ts,",
"worker.jobs_count() > 1: overloaded += 1 else: inactive.append(worker) # take an action if",
"overloaded += 1 else: inactive.append(worker) # take an action if necessary if len(empty)",
"worker queues when the system gets staturated, deactivates queues that are idle. \"\"\"",
"= 0 overloaded = 0 empty = [] # active yet empty work",
"active = 0 overloaded = 0 empty = [] # active yet empty",
"+= 1 if worker.jobs_count() == 0: empty.append(worker) elif worker.jobs_count() > 1: overloaded +=",
"from interfaces import AbstractSelfAdaptingStrategy class SimpleSelfAdaptingStrategy(AbstractSelfAdaptingStrategy): \"\"\"Represents a simple SA controller for activation/deactivation",
"= 0 empty = [] # active yet empty work queues inactive =",
"= [] # inactive work queues for worker in workers: if worker.get_attribute(\"active\"): active",
"len(empty) > 1 and overloaded == 0 and empty: empty[0].set_attribute(\"active\", False) # put",
"staturated, deactivates queues that are idle. \"\"\" def init(self, ts, dispatcher, workers): #",
"workers, job=None): # analyse the state of the worker queues active = 0",
"worker queues active = 0 overloaded = 0 empty = [] # active",
"+= 1 else: inactive.append(worker) # take an action if necessary if len(empty) >",
"that are idle. \"\"\" def init(self, ts, dispatcher, workers): # At the beginning,",
"controller for activation/deactivation of queues based on current workload. Activates suspended worker queues",
"when the system gets staturated, deactivates queues that are idle. \"\"\" def init(self,",
"inactive = [] # inactive work queues for worker in workers: if worker.get_attribute(\"active\"):",
"# take an action if necessary if len(empty) > 1 and overloaded ==",
"to sleep elif inactive and overloaded > 0: inactive[0].set_attribute(\"active\", True) # wake inactive",
"<reponame>smartarch/recodex-dataset from interfaces import AbstractSelfAdaptingStrategy class SimpleSelfAdaptingStrategy(AbstractSelfAdaptingStrategy): \"\"\"Represents a simple SA controller for",
"on current workload. Activates suspended worker queues when the system gets staturated, deactivates",
"system gets staturated, deactivates queues that are idle. \"\"\" def init(self, ts, dispatcher,",
"work queues for worker in workers: if worker.get_attribute(\"active\"): active += 1 if worker.jobs_count()",
"False) workers[0].set_attribute(\"active\", True) def do_adapt(self, ts, dispatcher, workers, job=None): # analyse the state",
"analyse the state of the worker queues active = 0 overloaded = 0",
"the first worker active for worker in workers: worker.set_attribute(\"active\", False) workers[0].set_attribute(\"active\", True) def",
"in workers: if worker.get_attribute(\"active\"): active += 1 if worker.jobs_count() == 0: empty.append(worker) elif",
"activation/deactivation of queues based on current workload. Activates suspended worker queues when the",
"AbstractSelfAdaptingStrategy class SimpleSelfAdaptingStrategy(AbstractSelfAdaptingStrategy): \"\"\"Represents a simple SA controller for activation/deactivation of queues based",
"init(self, ts, dispatcher, workers): # At the beginning, make only the first worker",
"empty = [] # active yet empty work queues inactive = [] #",
"active += 1 if worker.jobs_count() == 0: empty.append(worker) elif worker.jobs_count() > 1: overloaded",
"# put idle worker to sleep elif inactive and overloaded > 0: inactive[0].set_attribute(\"active\",",
"worker in workers: worker.set_attribute(\"active\", False) workers[0].set_attribute(\"active\", True) def do_adapt(self, ts, dispatcher, workers, job=None):",
"\"\"\"Represents a simple SA controller for activation/deactivation of queues based on current workload.",
"queues based on current workload. Activates suspended worker queues when the system gets",
"SA controller for activation/deactivation of queues based on current workload. Activates suspended worker",
"based on current workload. Activates suspended worker queues when the system gets staturated,",
"sleep elif inactive and overloaded > 0: inactive[0].set_attribute(\"active\", True) # wake inactive worker",
"of queues based on current workload. Activates suspended worker queues when the system",
"0 empty = [] # active yet empty work queues inactive = []",
"worker in workers: if worker.get_attribute(\"active\"): active += 1 if worker.jobs_count() == 0: empty.append(worker)",
"yet empty work queues inactive = [] # inactive work queues for worker",
"workload. Activates suspended worker queues when the system gets staturated, deactivates queues that",
"1 and overloaded == 0 and empty: empty[0].set_attribute(\"active\", False) # put idle worker",
"idle worker to sleep elif inactive and overloaded > 0: inactive[0].set_attribute(\"active\", True) #",
"workers): # At the beginning, make only the first worker active for worker",
"0: empty.append(worker) elif worker.jobs_count() > 1: overloaded += 1 else: inactive.append(worker) # take",
"beginning, make only the first worker active for worker in workers: worker.set_attribute(\"active\", False)",
"worker.jobs_count() == 0: empty.append(worker) elif worker.jobs_count() > 1: overloaded += 1 else: inactive.append(worker)",
"first worker active for worker in workers: worker.set_attribute(\"active\", False) workers[0].set_attribute(\"active\", True) def do_adapt(self,",
"[] # active yet empty work queues inactive = [] # inactive work",
"action if necessary if len(empty) > 1 and overloaded == 0 and empty:",
"[] # inactive work queues for worker in workers: if worker.get_attribute(\"active\"): active +=",
"workers: if worker.get_attribute(\"active\"): active += 1 if worker.jobs_count() == 0: empty.append(worker) elif worker.jobs_count()",
"dispatcher, workers, job=None): # analyse the state of the worker queues active =",
"active yet empty work queues inactive = [] # inactive work queues for",
"ts, dispatcher, workers, job=None): # analyse the state of the worker queues active",
"for activation/deactivation of queues based on current workload. Activates suspended worker queues when"
] |
[
"from other_data_pull module port_ret = port_ret.join(fred_join) # Calculate S&P 500 returns and cumulative",
"from plotly.subplots import make_subplots from app.other_data_pull import spy_pull, fred_pull from app.port_data_pull import port_data_pull",
"(port_ret.loc[pd_end, 'cum spret'])**(1 / years) - 1 avg_mon_spret = (port_ret.loc[pd_end, 'cum spret'])**(1 /",
"= working_data['mret'] + 1 # Calculate share values over time (used to pull",
"- 1 avg_mon_ret = (port_ret.loc[pd_end, 'cum ret'])**(1 / months) - 1 avg_ann_spret =",
"return standard deviations mon_sdev = port_ret['mon ret'].std() ann_sdev = mon_sdev * (12 **",
"val'] * cum_ret_set['cumret'] # Calculate monthly returns on the total portfolio over time",
"dictionary of calculation results ret_calc = {'years_tgt': pd_len, 'years_act': years, 'months_act': months, 'st_date':",
"separately/individually (i.e., not called from within this program) sub = pd.read_csv(os.path.join(os.path.dirname(os.path.abspath( __file__)), '..',",
"= fred_join['month'].dt.to_period('M') fred_join=fred_join.set_index('month') maxomin = sub['month'].min() minomax = sub['month'].max() else: # Call on",
"'development': # Requires that each of other_data_pull and port_data_pull modules be # run",
"period for one stock in the portfolio is 2 years and 7 months,",
"1 # MAKE CHARTS/TABLES! axis_font = dict(size=16, family='Times New Roman') tick_font = dict(size=12,",
"string for printing and display purposes. Param: dec (int or float) like 0.403321",
"port_ret['cum spret'] = port_ret['spretp1'].cumprod() port_ret = port_ret.drop(columns=['spretp1']) # Calculate portfolio and S&P 500",
"= (port_ret.loc[pd_end, 'cum ret'])**(1 / years) - 1 avg_mon_ret = (port_ret.loc[pd_end, 'cum ret'])**(1",
"or near complete periods. For example, if the longest data # sampling period",
"Create dataset of asset values by position at the analysis start date pd_start_val",
"monthly returns months = len(port_ret) years = months / 12 avg_ann_ret = (port_ret.loc[pd_end,",
"(port_ret.loc[pd_end, 'cum ret'])**(1 / years) - 1 avg_mon_ret = (port_ret.loc[pd_end, 'cum ret'])**(1 /",
"= pd.read_csv(os.path.join(os.path.dirname(os.path.abspath( __file__)), '..', 'data', \"working_fred.csv\"), parse_dates=['month']) fred_join['month'] = fred_join['month'].dt.to_period('M') fred_join=fred_join.set_index('month') maxomin =",
"font=axis_font), ticks='outside', tickfont=tick_font)) fig.update_layout(yaxis=dict(title=dict(text='Cumulative Monthly Returns (%)', font=axis_font), ticks='outside', tickfont=tick_font, tickformat='.1%')) fig.update_layout(legend=dict(orientation='h', font=axis_font))",
"(cumulative) returns dataset for data visualization tot_ret_data = port_ret[['cum ret', 'cum spret']] -",
"and risk free rate data from # Alpha Vantage and FRED (Federal Reserve",
"port_data_pull from app.portfolio_import import portfolio_import from app import APP_ENV # ------------------------------------------------------------------------------------- # FUNCTIONS",
"''' return f'{dec:.2%}' def two_dec(dec): ''' Converts a numeric value to formatted string",
"pct_change() function) port_ret.loc[pd_start + 1, 'mon ret'] = port_ret.loc[pd_start + 1, 'cum ret']",
"# CODE -------------------------------------------------------------------------------- # ------------------------------------------------------------------------------------- if __name__=='__main__': # Loan environment variables load_dotenv() port_file_name",
"(but only if sufficient data exists for all portfolio positions). If data are",
"'end_date': pd_end.strftime('%Y-%m'), 'ann_ret': avg_ann_ret, 'mon_ret': avg_mon_ret, 'ann_sdev': ann_sdev, 'mon_sdev': mon_sdev, 'ann_spret': avg_ann_spret, 'mon_spret':",
"x = 1 # MAKE CHARTS/TABLES! axis_font = dict(size=16, family='Times New Roman') tick_font",
"port_ret.join(spy_join) # Merge in 1Y constant maturity treasury data from other_data_pull module port_ret",
"the total portfolio over time port_ret = cum_ret_set.groupby('month')[['start val', 'mon val']].sum() port_ret['cum ret']",
"ret_calc, tot_ret_dict, port_ret # ------------------------------------------------------------------------------------- # CODE -------------------------------------------------------------------------------- # ------------------------------------------------------------------------------------- if __name__=='__main__': #",
"[] tot_ret=[] x = 0 keep = [] figs = [] for i",
"range(len(figs)): fig = make_subplots(rows=2, cols=1, vertical_spacing=0.03, row_width=[0.75,0.25], specs=[[{'type':'table'}], [{'type':'scatter'}]]) fig.add_trace(figs[i]['port line'], row=2, col=1)",
"to formatted string for printing and display purposes. Param: dec (int or float)",
"FRED (Federal Reserve Economic Data) APIs spy_join = spy_pull(ap_api_key) fred_join = fred_pull(fred_api_key) #",
"== 0: yr_str = '' elif full_years == 1: yr_str = f'{full_years} Year'",
"= spy_join['month'].dt.to_period('M') spy_join=spy_join.set_index('month') fred_join = pd.read_csv(os.path.join(os.path.dirname(os.path.abspath( __file__)), '..', 'data', \"working_fred.csv\"), parse_dates=['month']) fred_join['month'] =",
"+ 1, 'mon ret'] = port_ret.loc[pd_start + 1, 'cum ret'] - 1 #",
"for printing and display purposes. Param: dec (int or float) like 4000.444444 Example:",
"minomax = sub['month'].max() else: # Call on other_data_pull module for S&P 500 and",
"portfolio values) working_data['sh val'] = working_data['qty'] * working_data['close'] # Define analysis period length.",
"pandas as pd import os import dotenv from dotenv import load_dotenv import datetime",
"not called from within this program) sub = pd.read_csv(os.path.join(os.path.dirname(os.path.abspath( __file__)), '..', 'data', \"working_port.csv\"),",
"standard deviations mon_sdev = port_ret['mon ret'].std() ann_sdev = mon_sdev * (12 ** .5)",
"for printing and display purposes. Param: dec (int or float) like 0.403321 Example:",
"years and 7 months, and the loop # will not bother with the",
"go.Scatter(x=temp_tot['month'], y=temp_tot['cum ret'], name='Portfolio Cumulative Return', line=dict(color='firebrick', width=4)), 'sp line': go.Scatter(x=temp_tot['month'], y=temp_tot['cum spret'],",
"cols=1, vertical_spacing=0.03, row_width=[0.75,0.25], specs=[[{'type':'table'}], [{'type':'scatter'}]]) fig.add_trace(figs[i]['port line'], row=2, col=1) fig.add_trace(figs[i]['sp line'], row=2, col=1,)",
"and prepares data for data visualization. ''' # Calculate percent returns of individual",
"* 12), min_start) # Create dataset of asset values by position at the",
"other_data_pull module for S&P 500 and risk free rate data from # Alpha",
"months. Param: mon_len (int) like 17 Example: mon_len(17) Returns: 1 Year and 5",
"module for S&P 500 and risk free rate data from # Alpha Vantage",
"= cum_ret_set['start val'] * cum_ret_set['cumret'] # Calculate monthly returns on the total portfolio",
"5-year calculations. results = [] tot_ret=[] x = 0 keep = [] figs",
"within this program) sub = pd.read_csv(os.path.join(os.path.dirname(os.path.abspath( __file__)), '..', 'data', \"working_port.csv\"), parse_dates=['timestamp', 'month']) sub['month']=sub['month'].dt.to_period('M')",
"elements for 1, 2, 3, and 5 year analysis periods # (but only",
"'cum ret', 'cum spret']).set_index('month') tot_ret_data=tot_ret_data.append(app_df).sort_index() tot_ret_data.index = tot_ret_data.index.to_series().astype(str) tot_ret_dict = tot_ret_data.reset_index().to_dict(orient='list') return ret_calc,",
"ann_sp_sdev = mon_sp_sdev * (12 ** .5) # Calculate portfolio beta (covariance of",
"line=dict(color='firebrick', width=4)), 'sp line': go.Scatter(x=temp_tot['month'], y=temp_tot['cum spret'], name='S&P 500 Cumulative Return', line=dict(color='royalblue', width=4))})",
"avg_mon_spret = (port_ret.loc[pd_end, 'cum spret'])**(1 / months) - 1 #Calculate return standard deviations",
"like 0.403321 Example: to_pct(0.403321) Returns: 40.33% ''' return f'{dec:.2%}' def two_dec(dec): ''' Converts",
"by position at the analysis start date pd_start_val = working_data.loc[working_data['month'] == pd_start] pd_start_val",
"port_data_pull modules be # run separately/individually (i.e., not called from within this program)",
"for all portfolio positions). If data are insufficient, # only store results for",
"= period_length pd_end = max_end pd_start = max(max_end - (pd_len * 12), min_start)",
"analysis period length. For now, analysis period start date is # based on",
"pd_months = results[i]['months_act'] fig.update_layout(title=dict(text=f'Portfolio Performance Report: Monthly Returns over Last {pd_describe(pd_months)}', font=dict(family='Times New",
"corresponding monthly values of individual # portfolio positions over time cum_ret_set = working_data.loc[(working_data['month']",
"= [] for i in [1,2,3,5]: if x==0: temp_returns, temp_tot, temp_review = returns(sub,",
"this program) sub = pd.read_csv(os.path.join(os.path.dirname(os.path.abspath( __file__)), '..', 'data', \"working_port.csv\"), parse_dates=['timestamp', 'month']) sub['month']=sub['month'].dt.to_period('M') spy_join",
"= working_data.groupby('ticker')['adj close'].pct_change() working_data['mretp1'] = working_data['mret'] + 1 # Calculate share values over",
"name='S&P 500 Cumulative Return', line=dict(color='royalblue', width=4))}) if temp_returns['years_tgt'] != temp_returns['years_act']: x = 1",
"longest data # sampling period for one stock in the portfolio is 2",
"+ 1 # Calculate share values over time (used to pull analysis period",
"for a given stock in the portfolio becomes the analysis # start date.",
"cum_ret_set = working_data.loc[(working_data['month'] > pd_start) & (working_data['month'] <= pd_end)] cum_ret_set = cum_ret_set.set_index('ticker') cum_ret_set['cumret']",
"(int or float) like 4000.444444 Example: two_dec(4000.444444) Returns: 4,000.44 ''' return f'{dec:,.2f}' def",
"2 years and 7 months, and the loop # will not bother with",
"0.403321 Example: to_pct(0.403321) Returns: 40.33% ''' return f'{dec:.2%}' def two_dec(dec): ''' Converts a",
"risk free rate data from # Alpha Vantage and FRED (Federal Reserve Economic",
"port_ret['exret'].std()) * (12 ** .5) sharpe_sp = (port_ret['exspret'].mean() / port_ret['exspret'].std()) * (12 **",
"Ratio', 'Beta'] col2 = [to_pct(results[i]['ann_ret']), to_pct(results[i]['ann_sdev']), two_dec(results[i]['sharpe_port']), two_dec(results[i]['beta'])] col3 = [to_pct(results[i]['ann_spret']), to_pct(results[i]['ann_sp_sdev']), two_dec(results[i]['sharpe_sp']),",
"and S&P 500 divided by # volatility of S&P 500) beta = port_ret.cov().loc['mon",
"'cum ret'])**(1 / years) - 1 avg_mon_ret = (port_ret.loc[pd_end, 'cum ret'])**(1 / months)",
"for i in [1,2,3,5]: if x==0: temp_returns, temp_tot, temp_review = returns(sub, i, maxomin,",
"of other_data_pull and port_data_pull modules be # run separately/individually (i.e., not called from",
"of individual portfolio positions working_data = dataset working_data['mret'] = working_data.groupby('ticker')['adj close'].pct_change() working_data['mretp1'] =",
"in S&P 500 data from other_data_pull module port_ret = port_ret.join(spy_join) # Merge in",
"pd_start = max(max_end - (pd_len * 12), min_start) # Create dataset of asset",
"port_ret.loc[pd_start + 1, 'cum ret'] - 1 # Merge in S&P 500 data",
"- 1, 0, 0]], columns=['month', 'cum ret', 'cum spret']).set_index('month') tot_ret_data=tot_ret_data.append(app_df).sort_index() tot_ret_data.index = tot_ret_data.index.to_series().astype(str)",
"individual portfolio stocks # from Alpha Vantage API sub, minomax, maxomin=port_data_pull(portfolio,ap_api_key) # Collect",
"val'] port_ret['mon ret'] = port_ret['mon val'].pct_change() # Replace analysis period start month portfolio",
"import load_dotenv import datetime import plotly import plotly.graph_objects as go from plotly.subplots import",
"= 1 # MAKE CHARTS/TABLES! axis_font = dict(size=16, family='Times New Roman') tick_font =",
"= dict(size=16, family='Times New Roman') tick_font = dict(size=12, family='Times New Roman') for i",
"from app.port_data_pull import port_data_pull from app.portfolio_import import portfolio_import from app import APP_ENV #",
"# Create total (cumulative) returns dataset for data visualization tot_ret_data = port_ret[['cum ret',",
"Calculate portfolio beta (covariance of portfolio and S&P 500 divided by # volatility",
"Report: Monthly Returns over Last {pd_describe(pd_months)}', font=dict(family='Times New Roman', size=20))) fig.update_layout(xaxis=dict(title=dict(text='Month', font=axis_font), ticks='outside',",
"portfolio return (was na due to # pct_change() function) port_ret.loc[pd_start + 1, 'mon",
"-------------------------------------------------------------------------------- # ------------------------------------------------------------------------------------- if __name__=='__main__': # Loan environment variables load_dotenv() port_file_name = os.environ.get('PORTFOLIO_FILE_NAME')",
".5) # Calculate portfolio beta (covariance of portfolio and S&P 500 divided by",
"a text description of years and months. Param: mon_len (int) like 17 Example:",
"CHARTS/TABLES! axis_font = dict(size=16, family='Times New Roman') tick_font = dict(size=12, family='Times New Roman')",
"' and ' else: join_str = '' if full_years == 0: yr_str =",
"len(port_ret) years = months / 12 avg_ann_ret = (port_ret.loc[pd_end, 'cum ret'])**(1 / years)",
"portfolio is 2 years and 7 months, then the 3-year # analysis period",
"/ years) - 1 avg_mon_spret = (port_ret.loc[pd_end, 'cum spret'])**(1 / months) - 1",
"- 1 avg_mon_spret = (port_ret.loc[pd_end, 'cum spret'])**(1 / months) - 1 #Calculate return",
"== 0: mon_str = '' elif resid_months == 1: mon_str = f'{resid_months} Month'",
"analysis period will record results for a period of 2 years and 7",
"= [] tot_ret=[] x = 0 keep = [] figs = [] for",
"[] figs = [] for i in [1,2,3,5]: if x==0: temp_returns, temp_tot, temp_review",
"date is # based on the data availability of the individual positions. The",
"stock in the portfolio is 2 years and 7 months, then the 3-year",
"cumulative returns and corresponding monthly values of individual # portfolio positions over time",
"MAKE CHARTS/TABLES! axis_font = dict(size=16, family='Times New Roman') tick_font = dict(size=12, family='Times New",
"working_data.loc[(working_data['month'] > pd_start) & (working_data['month'] <= pd_end)] cum_ret_set = cum_ret_set.set_index('ticker') cum_ret_set['cumret'] = cum_ret_set.groupby('ticker')['mretp1'].cumprod()",
"> 0): join_str = ' and ' else: join_str = '' if full_years",
"full_years == 1: yr_str = f'{full_years} Year' else: yr_str = f'{full_years} Years' if",
"# only store results for complete or near complete periods. For example, if",
"# Calculate percent returns of individual portfolio positions working_data = dataset working_data['mret'] =",
"recent # first monthly data point for a given stock in the portfolio",
"other_data_pull module port_ret = port_ret.join(fred_join) # Calculate S&P 500 returns and cumulative return",
"in the portfolio is 2 years and 7 months, then the 3-year #",
"= port_ret['mon val'].pct_change() # Replace analysis period start month portfolio return (was na",
"= port_ret['mon ret'].std() ann_sdev = mon_sdev * (12 ** .5) mon_sp_sdev = port_ret['spret'].std()",
"- 1 avg_ann_spret = (port_ret.loc[pd_end, 'cum spret'])**(1 / years) - 1 avg_mon_spret =",
"float) like 4000.444444 Example: two_dec(4000.444444) Returns: 4,000.44 ''' return f'{dec:,.2f}' def pd_describe(mon_len): '''",
"working_data = dataset working_data['mret'] = working_data.groupby('ticker')['adj close'].pct_change() working_data['mretp1'] = working_data['mret'] + 1 #",
"'beta': beta, 'sharpe_port': sharpe_port, 'sharpe_sp': sharpe_sp} # Create total (cumulative) returns dataset for",
"data point for a given stock in the portfolio becomes the analysis #",
"on individual portfolio stocks # from Alpha Vantage API sub, minomax, maxomin=port_data_pull(portfolio,ap_api_key) #",
"tick_font = dict(size=12, family='Times New Roman') for i in range(len(figs)): fig = make_subplots(rows=2,",
"int(mon_len / 12) resid_months = mon_len % 12 if (full_years > 0 and",
"minomax, maxomin=port_data_pull(portfolio,ap_api_key) # Collect and store results, datasets, and chart elements for 1,",
"ret'])**(1 / years) - 1 avg_mon_ret = (port_ret.loc[pd_end, 'cum ret'])**(1 / months) -",
"= working_data.loc[(working_data['month'] > pd_start) & (working_data['month'] <= pd_end)] cum_ret_set = cum_ret_set.set_index('ticker') cum_ret_set['cumret'] =",
"import datetime import plotly import plotly.graph_objects as go from plotly.subplots import make_subplots from",
"plotly.graph_objects as go from plotly.subplots import make_subplots from app.other_data_pull import spy_pull, fred_pull from",
"join_str = ' and ' else: join_str = '' if full_years == 0:",
"environment variables load_dotenv() port_file_name = os.environ.get('PORTFOLIO_FILE_NAME') ap_api_key = os.environ.get('ALPHAVANTAGE_API_KEY') fred_api_key = os.environ.get('FRED_API_KEY') portfolio",
"free rate data from # Alpha Vantage and FRED (Federal Reserve Economic Data)",
"= [] figs = [] for i in [1,2,3,5]: if x==0: temp_returns, temp_tot,",
"'sharpe_sp': sharpe_sp} # Create total (cumulative) returns dataset for data visualization tot_ret_data =",
"mon_len (int) like 17 Example: mon_len(17) Returns: 1 Year and 5 Months '''",
"analysis # start date. This is a limitation of the data/API. pd_len =",
"ret'] = port_ret['mon val'].pct_change() # Replace analysis period start month portfolio return (was",
"Param: dec (int or float) like 0.403321 Example: to_pct(0.403321) Returns: 40.33% ''' return",
"1 avg_ann_spret = (port_ret.loc[pd_end, 'cum spret'])**(1 / years) - 1 avg_mon_spret = (port_ret.loc[pd_end,",
"period_length, min_start, max_end): ''' Calculates various portfolio performance measures and prepares data for",
"pd_end = max_end pd_start = max(max_end - (pd_len * 12), min_start) # Create",
"#Calculate return standard deviations mon_sdev = port_ret['mon ret'].std() ann_sdev = mon_sdev * (12",
"due to # pct_change() function) port_ret.loc[pd_start + 1, 'mon ret'] = port_ret.loc[pd_start +",
"period of 2 years and 7 months, and the loop # will not",
"for complete or near complete periods. For example, if the longest data #",
"= port_ret['mon val'] / port_ret['start val'] port_ret['mon ret'] = port_ret['mon val'].pct_change() # Replace",
"import dotenv from dotenv import load_dotenv import datetime import plotly import plotly.graph_objects as",
"mon_str = '' elif resid_months == 1: mon_str = f'{resid_months} Month' else: mon_str=f'{resid_months}",
"APP_ENV # ------------------------------------------------------------------------------------- # FUNCTIONS --------------------------------------------------------------------------- # ------------------------------------------------------------------------------------- def to_pct(dec): ''' Converts a",
"close'].pct_change() working_data['mretp1'] = working_data['mret'] + 1 # Calculate share values over time (used",
"returns(dataset, period_length, min_start, max_end): ''' Calculates various portfolio performance measures and prepares data",
"pull analysis period starting portfolio values) working_data['sh val'] = working_data['qty'] * working_data['close'] #",
"avg_mon_ret, 'ann_sdev': ann_sdev, 'mon_sdev': mon_sdev, 'ann_spret': avg_ann_spret, 'mon_spret': avg_mon_spret, 'ann_sp_sdev': ann_sp_sdev, 'mon_sp_sdev': mon_sp_sdev,",
"prepares data for data visualization. ''' # Calculate percent returns of individual portfolio",
"working_data['qty'] * working_data['close'] # Define analysis period length. For now, analysis period start",
"= make_subplots(rows=2, cols=1, vertical_spacing=0.03, row_width=[0.75,0.25], specs=[[{'type':'table'}], [{'type':'scatter'}]]) fig.add_trace(figs[i]['port line'], row=2, col=1) fig.add_trace(figs[i]['sp line'],",
"dict(size=16, family='Times New Roman') tick_font = dict(size=12, family='Times New Roman') for i in",
"/ port_ret.cov().loc['spret', 'spret'] # Calculate sharpe ratios sharpe_port = (port_ret['exret'].mean() / port_ret['exret'].std()) *",
"working_data['mret'] = working_data.groupby('ticker')['adj close'].pct_change() working_data['mretp1'] = working_data['mret'] + 1 # Calculate share values",
"of years and months. Param: mon_len (int) like 17 Example: mon_len(17) Returns: 1",
"and store results, datasets, and chart elements for 1, 2, 3, and 5",
"= (port_ret.loc[pd_end, 'cum ret'])**(1 / months) - 1 avg_ann_spret = (port_ret.loc[pd_end, 'cum spret'])**(1",
"for 1, 2, 3, and 5 year analysis periods # (but only if",
"analysis period start date is # based on the data availability of the",
"return (was na due to # pct_change() function) port_ret.loc[pd_start + 1, 'mon ret']",
"port_ret['spretp1'] = port_ret['spret'] + 1 port_ret['cum spret'] = port_ret['spretp1'].cumprod() port_ret = port_ret.drop(columns=['spretp1']) #",
"'ann_sp_sdev': ann_sp_sdev, 'mon_sp_sdev': mon_sp_sdev, 'beta': beta, 'sharpe_port': sharpe_port, 'sharpe_sp': sharpe_sp} # Create total",
"'mon_sp_sdev': mon_sp_sdev, 'beta': beta, 'sharpe_port': sharpe_port, 'sharpe_sp': sharpe_sp} # Create total (cumulative) returns",
"run separately/individually (i.e., not called from within this program) sub = pd.read_csv(os.path.join(os.path.dirname(os.path.abspath( __file__)),",
"500 excess returns over risk free rate port_ret['exret'] = port_ret['mon ret'] - port_ret['rate']",
"exists for all portfolio positions). If data are insufficient, # only store results",
"Returns: 1 Year and 5 Months ''' full_years = int(mon_len / 12) resid_months",
"- (pd_len * 12), min_start) # Create dataset of asset values by position",
"(pd_len * 12), min_start) # Create dataset of asset values by position at",
"Data) APIs spy_join = spy_pull(ap_api_key) fred_join = fred_pull(fred_api_key) # Call on port_data_pull module",
"monthly data point for a given stock in the portfolio becomes the analysis",
"numeric value to formatted string for printing and display purposes. Param: dec (int",
"portfolio performance measures and prepares data for data visualization. ''' # Calculate percent",
"val'] / port_ret['start val'] port_ret['mon ret'] = port_ret['mon val'].pct_change() # Replace analysis period",
"is a limitation of the data/API. pd_len = period_length pd_end = max_end pd_start",
"max_end): ''' Calculates various portfolio performance measures and prepares data for data visualization.",
"# portfolio positions over time cum_ret_set = working_data.loc[(working_data['month'] > pd_start) & (working_data['month'] <=",
"Merge in 1Y constant maturity treasury data from other_data_pull module port_ret = port_ret.join(fred_join)",
"40.33% ''' return f'{dec:.2%}' def two_dec(dec): ''' Converts a numeric value to formatted",
"performance measures and prepares data for data visualization. ''' # Calculate percent returns",
"<= pd_end)] cum_ret_set = cum_ret_set.set_index('ticker') cum_ret_set['cumret'] = cum_ret_set.groupby('ticker')['mretp1'].cumprod() cum_ret_set = cum_ret_set.join(pd_start_val, on='ticker') cum_ret_set['mon",
"ret'] - 1 # Merge in S&P 500 data from other_data_pull module port_ret",
"port_ret['mon ret'].std() ann_sdev = mon_sdev * (12 ** .5) mon_sp_sdev = port_ret['spret'].std() ann_sp_sdev",
"New Roman') for i in range(len(figs)): fig = make_subplots(rows=2, cols=1, vertical_spacing=0.03, row_width=[0.75,0.25], specs=[[{'type':'table'}],",
"= working_data['qty'] * working_data['close'] # Define analysis period length. For now, analysis period",
"purposes. Param: dec (int or float) like 0.403321 Example: to_pct(0.403321) Returns: 40.33% '''",
"plotly.subplots import make_subplots from app.other_data_pull import spy_pull, fred_pull from app.port_data_pull import port_data_pull from",
"port_ret['rate'] port_ret['exspret'] = port_ret['spret'] - port_ret['rate'] # Calculate average annual and monthly returns",
"the loop # will not bother with the 5-year calculations. results = []",
"line': go.Scatter(x=temp_tot['month'], y=temp_tot['cum spret'], name='S&P 500 Cumulative Return', line=dict(color='royalblue', width=4))}) if temp_returns['years_tgt'] !=",
"def pd_describe(mon_len): ''' Converts a specified number of months to a text description",
"------------------------------------------------------------------------------------- # FUNCTIONS --------------------------------------------------------------------------- # ------------------------------------------------------------------------------------- def to_pct(dec): ''' Converts a numeric value",
"[] for i in [1,2,3,5]: if x==0: temp_returns, temp_tot, temp_review = returns(sub, i,",
"app.portfolio_import import portfolio_import from app import APP_ENV # ------------------------------------------------------------------------------------- # FUNCTIONS --------------------------------------------------------------------------- #",
"free rate port_ret['exret'] = port_ret['mon ret'] - port_ret['rate'] port_ret['exspret'] = port_ret['spret'] - port_ret['rate']",
"volatility of S&P 500) beta = port_ret.cov().loc['mon ret', 'spret'] / port_ret.cov().loc['spret', 'spret'] #",
"ticks='outside', tickfont=tick_font)) fig.update_layout(yaxis=dict(title=dict(text='Cumulative Monthly Returns (%)', font=axis_font), ticks='outside', tickfont=tick_font, tickformat='.1%')) fig.update_layout(legend=dict(orientation='h', font=axis_font)) col1",
"in [1,2,3,5]: if x==0: temp_returns, temp_tot, temp_review = returns(sub, i, maxomin, minomax) results.append(temp_returns)",
"figs.append({'port line': go.Scatter(x=temp_tot['month'], y=temp_tot['cum ret'], name='Portfolio Cumulative Return', line=dict(color='firebrick', width=4)), 'sp line': go.Scatter(x=temp_tot['month'],",
"# Loan environment variables load_dotenv() port_file_name = os.environ.get('PORTFOLIO_FILE_NAME') ap_api_key = os.environ.get('ALPHAVANTAGE_API_KEY') fred_api_key =",
"= (port_ret['exspret'].mean() / port_ret['exspret'].std()) * (12 ** .5) # Assemble dictionary of calculation",
"Caclulate cumulative returns and corresponding monthly values of individual # portfolio positions over",
"dec (int or float) like 0.403321 Example: to_pct(0.403321) Returns: 40.33% ''' return f'{dec:.2%}'",
"max_end pd_start = max(max_end - (pd_len * 12), min_start) # Create dataset of",
"months, then the 3-year # analysis period will record results for a period",
"spy_join['month'] = spy_join['month'].dt.to_period('M') spy_join=spy_join.set_index('month') fred_join = pd.read_csv(os.path.join(os.path.dirname(os.path.abspath( __file__)), '..', 'data', \"working_fred.csv\"), parse_dates=['month']) fred_join['month']",
"for data visualization. ''' # Calculate percent returns of individual portfolio positions working_data",
"the 3-year # analysis period will record results for a period of 2",
"y=temp_tot['cum spret'], name='S&P 500 Cumulative Return', line=dict(color='royalblue', width=4))}) if temp_returns['years_tgt'] != temp_returns['years_act']: x",
"fig.update_layout(yaxis=dict(title=dict(text='Cumulative Monthly Returns (%)', font=axis_font), ticks='outside', tickfont=tick_font, tickformat='.1%')) fig.update_layout(legend=dict(orientation='h', font=axis_font)) col1 = ['Avg.",
"Return', 'Std. Dev. (Ann.)', 'Sharpe Ratio', 'Beta'] col2 = [to_pct(results[i]['ann_ret']), to_pct(results[i]['ann_sdev']), two_dec(results[i]['sharpe_port']), two_dec(results[i]['beta'])]",
"f'{dec:,.2f}' def pd_describe(mon_len): ''' Converts a specified number of months to a text",
"# Replace analysis period start month portfolio return (was na due to #",
"Converts a numeric value to formatted string for printing and display purposes. Param:",
"the portfolio becomes the analysis # start date. This is a limitation of",
"start date pd_start_val = working_data.loc[working_data['month'] == pd_start] pd_start_val = pd_start_val.set_index('ticker') pd_start_val = pd_start_val['sh",
"'cum ret'] - 1 # Merge in S&P 500 data from other_data_pull module",
"# Merge in S&P 500 data from other_data_pull module port_ret = port_ret.join(spy_join) #",
"1 app_df = pd.DataFrame([[tot_ret_data.index.min() - 1, 0, 0]], columns=['month', 'cum ret', 'cum spret']).set_index('month')",
"= pd.read_csv(os.path.join(os.path.dirname(os.path.abspath( __file__)), '..', 'data', \"working_spy.csv\"), parse_dates=['month']) spy_join['month'] = spy_join['month'].dt.to_period('M') spy_join=spy_join.set_index('month') fred_join =",
"date pd_start_val = working_data.loc[working_data['month'] == pd_start] pd_start_val = pd_start_val.set_index('ticker') pd_start_val = pd_start_val['sh val'].rename('start",
"load_dotenv() port_file_name = os.environ.get('PORTFOLIO_FILE_NAME') ap_api_key = os.environ.get('ALPHAVANTAGE_API_KEY') fred_api_key = os.environ.get('FRED_API_KEY') portfolio = portfolio_import(port_file_name)",
"to_pct(results[i]['ann_sdev']), two_dec(results[i]['sharpe_port']), two_dec(results[i]['beta'])] col3 = [to_pct(results[i]['ann_spret']), to_pct(results[i]['ann_sp_sdev']), two_dec(results[i]['sharpe_sp']), two_dec(1.00)] fig.add_trace(go.Table(header=dict(values=['Statistic', 'Portfolio', 'S&P 500']),",
"# Create dataset of asset values by position at the analysis start date",
"go from plotly.subplots import make_subplots from app.other_data_pull import spy_pull, fred_pull from app.port_data_pull import",
"sub['month']=sub['month'].dt.to_period('M') spy_join = pd.read_csv(os.path.join(os.path.dirname(os.path.abspath( __file__)), '..', 'data', \"working_spy.csv\"), parse_dates=['month']) spy_join['month'] = spy_join['month'].dt.to_period('M') spy_join=spy_join.set_index('month')",
"pd_start) & (working_data['month'] <= pd_end)] cum_ret_set = cum_ret_set.set_index('ticker') cum_ret_set['cumret'] = cum_ret_set.groupby('ticker')['mretp1'].cumprod() cum_ret_set =",
"maxomin=port_data_pull(portfolio,ap_api_key) # Collect and store results, datasets, and chart elements for 1, 2,",
"beta (covariance of portfolio and S&P 500 divided by # volatility of S&P",
"the portfolio is 2 years and 7 months, then the 3-year # analysis",
"total portfolio over time port_ret = cum_ret_set.groupby('month')[['start val', 'mon val']].sum() port_ret['cum ret'] =",
"months, and the loop # will not bother with the 5-year calculations. results",
"temp_review = returns(sub, i, maxomin, minomax) results.append(temp_returns) tot_ret.append(temp_tot) keep.append(i) figs.append({'port line': go.Scatter(x=temp_tot['month'], y=temp_tot['cum",
"= os.environ.get('PORTFOLIO_FILE_NAME') ap_api_key = os.environ.get('ALPHAVANTAGE_API_KEY') fred_api_key = os.environ.get('FRED_API_KEY') portfolio = portfolio_import(port_file_name) if APP_ENV",
"rate data from # Alpha Vantage and FRED (Federal Reserve Economic Data) APIs",
"are insufficient, # only store results for complete or near complete periods. For",
"500 data from other_data_pull module port_ret = port_ret.join(spy_join) # Merge in 1Y constant",
"return f'{dec:,.2f}' def pd_describe(mon_len): ''' Converts a specified number of months to a",
"portfolio = portfolio_import(port_file_name) if APP_ENV == 'development': # Requires that each of other_data_pull",
"0, 0]], columns=['month', 'cum ret', 'cum spret']).set_index('month') tot_ret_data=tot_ret_data.append(app_df).sort_index() tot_ret_data.index = tot_ret_data.index.to_series().astype(str) tot_ret_dict =",
"by # volatility of S&P 500) beta = port_ret.cov().loc['mon ret', 'spret'] / port_ret.cov().loc['spret',",
"# start date. This is a limitation of the data/API. pd_len = period_length",
"# from Alpha Vantage API sub, minomax, maxomin=port_data_pull(portfolio,ap_api_key) # Collect and store results,",
"for S&P 500 and risk free rate data from # Alpha Vantage and",
"(12 ** .5) # Calculate portfolio beta (covariance of portfolio and S&P 500",
"'cum spret']).set_index('month') tot_ret_data=tot_ret_data.append(app_df).sort_index() tot_ret_data.index = tot_ret_data.index.to_series().astype(str) tot_ret_dict = tot_ret_data.reset_index().to_dict(orient='list') return ret_calc, tot_ret_dict, port_ret",
"in the portfolio becomes the analysis # start date. This is a limitation",
"== pd_start] pd_start_val = pd_start_val.set_index('ticker') pd_start_val = pd_start_val['sh val'].rename('start val') # Caclulate cumulative",
"'data', \"working_fred.csv\"), parse_dates=['month']) fred_join['month'] = fred_join['month'].dt.to_period('M') fred_join=fred_join.set_index('month') maxomin = sub['month'].min() minomax = sub['month'].max()",
"two_dec(results[i]['beta'])] col3 = [to_pct(results[i]['ann_spret']), to_pct(results[i]['ann_sp_sdev']), two_dec(results[i]['sharpe_sp']), two_dec(1.00)] fig.add_trace(go.Table(header=dict(values=['Statistic', 'Portfolio', 'S&P 500']), cells=dict(values=[col1, col2,",
"Requires that each of other_data_pull and port_data_pull modules be # run separately/individually (i.e.,",
"a specified number of months to a text description of years and months.",
"1, 2, 3, and 5 year analysis periods # (but only if sufficient",
"to pull analysis period starting portfolio values) working_data['sh val'] = working_data['qty'] * working_data['close']",
"near complete periods. For example, if the longest data # sampling period for",
"line': go.Scatter(x=temp_tot['month'], y=temp_tot['cum ret'], name='Portfolio Cumulative Return', line=dict(color='firebrick', width=4)), 'sp line': go.Scatter(x=temp_tot['month'], y=temp_tot['cum",
"temp_returns['years_act']: x = 1 # MAKE CHARTS/TABLES! axis_font = dict(size=16, family='Times New Roman')",
"= [to_pct(results[i]['ann_spret']), to_pct(results[i]['ann_sp_sdev']), two_dec(results[i]['sharpe_sp']), two_dec(1.00)] fig.add_trace(go.Table(header=dict(values=['Statistic', 'Portfolio', 'S&P 500']), cells=dict(values=[col1, col2, col3])),row=1,col=1) fig.show()",
"import spy_pull, fred_pull from app.port_data_pull import port_data_pull from app.portfolio_import import portfolio_import from app",
"description of years and months. Param: mon_len (int) like 17 Example: mon_len(17) Returns:",
"port_ret['mon ret'] - port_ret['rate'] port_ret['exspret'] = port_ret['spret'] - port_ret['rate'] # Calculate average annual",
"on other_data_pull module for S&P 500 and risk free rate data from #",
"''' full_years = int(mon_len / 12) resid_months = mon_len % 12 if (full_years",
"'ann_spret': avg_ann_spret, 'mon_spret': avg_mon_spret, 'ann_sp_sdev': ann_sp_sdev, 'mon_sp_sdev': mon_sp_sdev, 'beta': beta, 'sharpe_port': sharpe_port, 'sharpe_sp':",
"# ------------------------------------------------------------------------------------- if __name__=='__main__': # Loan environment variables load_dotenv() port_file_name = os.environ.get('PORTFOLIO_FILE_NAME') ap_api_key",
"else: mon_str=f'{resid_months} Months' pd_detail=f'{yr_str}{join_str}{mon_str}' return pd_detail def returns(dataset, period_length, min_start, max_end): ''' Calculates",
"port_ret['mon val'].pct_change() # Replace analysis period start month portfolio return (was na due",
"dotenv import load_dotenv import datetime import plotly import plotly.graph_objects as go from plotly.subplots",
"(port_ret['exret'].mean() / port_ret['exret'].std()) * (12 ** .5) sharpe_sp = (port_ret['exspret'].mean() / port_ret['exspret'].std()) *",
"/ months) - 1 #Calculate return standard deviations mon_sdev = port_ret['mon ret'].std() ann_sdev",
"1, 'mon ret'] = port_ret.loc[pd_start + 1, 'cum ret'] - 1 # Merge",
"cum_ret_set = cum_ret_set.set_index('ticker') cum_ret_set['cumret'] = cum_ret_set.groupby('ticker')['mretp1'].cumprod() cum_ret_set = cum_ret_set.join(pd_start_val, on='ticker') cum_ret_set['mon val'] =",
"from app import APP_ENV # ------------------------------------------------------------------------------------- # FUNCTIONS --------------------------------------------------------------------------- # ------------------------------------------------------------------------------------- def to_pct(dec):",
"os import dotenv from dotenv import load_dotenv import datetime import plotly import plotly.graph_objects",
"& (working_data['month'] <= pd_end)] cum_ret_set = cum_ret_set.set_index('ticker') cum_ret_set['cumret'] = cum_ret_set.groupby('ticker')['mretp1'].cumprod() cum_ret_set = cum_ret_set.join(pd_start_val,",
"import APP_ENV # ------------------------------------------------------------------------------------- # FUNCTIONS --------------------------------------------------------------------------- # ------------------------------------------------------------------------------------- def to_pct(dec): ''' Converts",
"FUNCTIONS --------------------------------------------------------------------------- # ------------------------------------------------------------------------------------- def to_pct(dec): ''' Converts a numeric value to formatted",
"if temp_returns['years_tgt'] != temp_returns['years_act']: x = 1 # MAKE CHARTS/TABLES! axis_font = dict(size=16,",
"mon_len(17) Returns: 1 Year and 5 Months ''' full_years = int(mon_len / 12)",
"positions over time cum_ret_set = working_data.loc[(working_data['month'] > pd_start) & (working_data['month'] <= pd_end)] cum_ret_set",
"\"working_port.csv\"), parse_dates=['timestamp', 'month']) sub['month']=sub['month'].dt.to_period('M') spy_join = pd.read_csv(os.path.join(os.path.dirname(os.path.abspath( __file__)), '..', 'data', \"working_spy.csv\"), parse_dates=['month']) spy_join['month']",
"for monthly data on individual portfolio stocks # from Alpha Vantage API sub,",
"= pd.read_csv(os.path.join(os.path.dirname(os.path.abspath( __file__)), '..', 'data', \"working_port.csv\"), parse_dates=['timestamp', 'month']) sub['month']=sub['month'].dt.to_period('M') spy_join = pd.read_csv(os.path.join(os.path.dirname(os.path.abspath( __file__)),",
"val'] = working_data['qty'] * working_data['close'] # Define analysis period length. For now, analysis",
"display purposes. Param: dec (int or float) like 0.403321 Example: to_pct(0.403321) Returns: 40.33%",
"S&P 500 returns and cumulative return over analysis period port_ret['spretp1'] = port_ret['spret'] +",
"returns and cumulative return over analysis period port_ret['spretp1'] = port_ret['spret'] + 1 port_ret['cum",
"ticks='outside', tickfont=tick_font, tickformat='.1%')) fig.update_layout(legend=dict(orientation='h', font=axis_font)) col1 = ['Avg. Annual Return', 'Std. Dev. (Ann.)',",
"cum_ret_set.join(pd_start_val, on='ticker') cum_ret_set['mon val'] = cum_ret_set['start val'] * cum_ret_set['cumret'] # Calculate monthly returns",
"fred_pull(fred_api_key) # Call on port_data_pull module for monthly data on individual portfolio stocks",
"on='ticker') cum_ret_set['mon val'] = cum_ret_set['start val'] * cum_ret_set['cumret'] # Calculate monthly returns on",
".5) sharpe_sp = (port_ret['exspret'].mean() / port_ret['exspret'].std()) * (12 ** .5) # Assemble dictionary",
"store results, datasets, and chart elements for 1, 2, 3, and 5 year",
"port_ret = port_ret.join(spy_join) # Merge in 1Y constant maturity treasury data from other_data_pull",
"for data visualization tot_ret_data = port_ret[['cum ret', 'cum spret']] - 1 app_df =",
"months) - 1 #Calculate return standard deviations mon_sdev = port_ret['mon ret'].std() ann_sdev =",
"and FRED (Federal Reserve Economic Data) APIs spy_join = spy_pull(ap_api_key) fred_join = fred_pull(fred_api_key)",
"spret'])**(1 / months) - 1 #Calculate return standard deviations mon_sdev = port_ret['mon ret'].std()",
"max(max_end - (pd_len * 12), min_start) # Create dataset of asset values by",
"ann_sdev, 'mon_sdev': mon_sdev, 'ann_spret': avg_ann_spret, 'mon_spret': avg_mon_spret, 'ann_sp_sdev': ann_sp_sdev, 'mon_sp_sdev': mon_sp_sdev, 'beta': beta,",
"# Calculate S&P 500 returns and cumulative return over analysis period port_ret['spretp1'] =",
"and 5 year analysis periods # (but only if sufficient data exists for",
"Call on port_data_pull module for monthly data on individual portfolio stocks # from",
"(%)', font=axis_font), ticks='outside', tickfont=tick_font, tickformat='.1%')) fig.update_layout(legend=dict(orientation='h', font=axis_font)) col1 = ['Avg. Annual Return', 'Std.",
"specified number of months to a text description of years and months. Param:",
"results for complete or near complete periods. For example, if the longest data",
"working_data.loc[working_data['month'] == pd_start] pd_start_val = pd_start_val.set_index('ticker') pd_start_val = pd_start_val['sh val'].rename('start val') # Caclulate",
"'data', \"working_spy.csv\"), parse_dates=['month']) spy_join['month'] = spy_join['month'].dt.to_period('M') spy_join=spy_join.set_index('month') fred_join = pd.read_csv(os.path.join(os.path.dirname(os.path.abspath( __file__)), '..', 'data',",
"12) resid_months = mon_len % 12 if (full_years > 0 and resid_months >",
"# Caclulate cumulative returns and corresponding monthly values of individual # portfolio positions",
"\"working_spy.csv\"), parse_dates=['month']) spy_join['month'] = spy_join['month'].dt.to_period('M') spy_join=spy_join.set_index('month') fred_join = pd.read_csv(os.path.join(os.path.dirname(os.path.abspath( __file__)), '..', 'data', \"working_fred.csv\"),",
"port_ret.join(fred_join) # Calculate S&P 500 returns and cumulative return over analysis period port_ret['spretp1']",
"= port_ret.drop(columns=['spretp1']) # Calculate portfolio and S&P 500 excess returns over risk free",
"# Calculate share values over time (used to pull analysis period starting portfolio",
"or float) like 0.403321 Example: to_pct(0.403321) Returns: 40.33% ''' return f'{dec:.2%}' def two_dec(dec):",
"New Roman') tick_font = dict(size=12, family='Times New Roman') for i in range(len(figs)): fig",
"spy_pull, fred_pull from app.port_data_pull import port_data_pull from app.portfolio_import import portfolio_import from app import",
"na due to # pct_change() function) port_ret.loc[pd_start + 1, 'mon ret'] = port_ret.loc[pd_start",
"# analysis period will record results for a period of 2 years and",
"port_ret = cum_ret_set.groupby('month')[['start val', 'mon val']].sum() port_ret['cum ret'] = port_ret['mon val'] / port_ret['start",
"complete periods. For example, if the longest data # sampling period for one",
"pd.read_csv(os.path.join(os.path.dirname(os.path.abspath( __file__)), '..', 'data', \"working_spy.csv\"), parse_dates=['month']) spy_join['month'] = spy_join['month'].dt.to_period('M') spy_join=spy_join.set_index('month') fred_join = pd.read_csv(os.path.join(os.path.dirname(os.path.abspath(",
"ann_sdev = mon_sdev * (12 ** .5) mon_sp_sdev = port_ret['spret'].std() ann_sp_sdev = mon_sp_sdev",
"* cum_ret_set['cumret'] # Calculate monthly returns on the total portfolio over time port_ret",
"import portfolio_import from app import APP_ENV # ------------------------------------------------------------------------------------- # FUNCTIONS --------------------------------------------------------------------------- # -------------------------------------------------------------------------------------",
"(int or float) like 0.403321 Example: to_pct(0.403321) Returns: 40.33% ''' return f'{dec:.2%}' def",
"Cumulative Return', line=dict(color='firebrick', width=4)), 'sp line': go.Scatter(x=temp_tot['month'], y=temp_tot['cum spret'], name='S&P 500 Cumulative Return',",
"starting portfolio values) working_data['sh val'] = working_data['qty'] * working_data['close'] # Define analysis period",
"portfolio and S&P 500 divided by # volatility of S&P 500) beta =",
"f'{resid_months} Month' else: mon_str=f'{resid_months} Months' pd_detail=f'{yr_str}{join_str}{mon_str}' return pd_detail def returns(dataset, period_length, min_start, max_end):",
"= 0 keep = [] figs = [] for i in [1,2,3,5]: if",
"spy_join = pd.read_csv(os.path.join(os.path.dirname(os.path.abspath( __file__)), '..', 'data', \"working_spy.csv\"), parse_dates=['month']) spy_join['month'] = spy_join['month'].dt.to_period('M') spy_join=spy_join.set_index('month') fred_join",
"(port_ret.loc[pd_end, 'cum ret'])**(1 / months) - 1 avg_ann_spret = (port_ret.loc[pd_end, 'cum spret'])**(1 /",
"each of other_data_pull and port_data_pull modules be # run separately/individually (i.e., not called",
"the analysis # start date. This is a limitation of the data/API. pd_len",
"col2 = [to_pct(results[i]['ann_ret']), to_pct(results[i]['ann_sdev']), two_dec(results[i]['sharpe_port']), two_dec(results[i]['beta'])] col3 = [to_pct(results[i]['ann_spret']), to_pct(results[i]['ann_sp_sdev']), two_dec(results[i]['sharpe_sp']), two_dec(1.00)] fig.add_trace(go.Table(header=dict(values=['Statistic',",
"port_ret # ------------------------------------------------------------------------------------- # CODE -------------------------------------------------------------------------------- # ------------------------------------------------------------------------------------- if __name__=='__main__': # Loan environment",
"= dataset working_data['mret'] = working_data.groupby('ticker')['adj close'].pct_change() working_data['mretp1'] = working_data['mret'] + 1 # Calculate",
"spret'], name='S&P 500 Cumulative Return', line=dict(color='royalblue', width=4))}) if temp_returns['years_tgt'] != temp_returns['years_act']: x =",
"sub['month'].max() else: # Call on other_data_pull module for S&P 500 and risk free",
"over risk free rate port_ret['exret'] = port_ret['mon ret'] - port_ret['rate'] port_ret['exspret'] = port_ret['spret']",
"a given stock in the portfolio becomes the analysis # start date. This",
"+ 1, 'cum ret'] - 1 # Merge in S&P 500 data from",
"stocks # from Alpha Vantage API sub, minomax, maxomin=port_data_pull(portfolio,ap_api_key) # Collect and store",
"insufficient, # only store results for complete or near complete periods. For example,",
"------------------------------------------------------------------------------------- # CODE -------------------------------------------------------------------------------- # ------------------------------------------------------------------------------------- if __name__=='__main__': # Loan environment variables load_dotenv()",
"# sampling period for one stock in the portfolio is 2 years and",
"Return', line=dict(color='firebrick', width=4)), 'sp line': go.Scatter(x=temp_tot['month'], y=temp_tot['cum spret'], name='S&P 500 Cumulative Return', line=dict(color='royalblue',",
"(Ann.)', 'Sharpe Ratio', 'Beta'] col2 = [to_pct(results[i]['ann_ret']), to_pct(results[i]['ann_sdev']), two_dec(results[i]['sharpe_port']), two_dec(results[i]['beta'])] col3 = [to_pct(results[i]['ann_spret']),",
"app import APP_ENV # ------------------------------------------------------------------------------------- # FUNCTIONS --------------------------------------------------------------------------- # ------------------------------------------------------------------------------------- def to_pct(dec): '''",
"cum_ret_set['mon val'] = cum_ret_set['start val'] * cum_ret_set['cumret'] # Calculate monthly returns on the",
"asset values by position at the analysis start date pd_start_val = working_data.loc[working_data['month'] ==",
"== 'development': # Requires that each of other_data_pull and port_data_pull modules be #",
"S&P 500) beta = port_ret.cov().loc['mon ret', 'spret'] / port_ret.cov().loc['spret', 'spret'] # Calculate sharpe",
"Years' if resid_months == 0: mon_str = '' elif resid_months == 1: mon_str",
"width=4))}) if temp_returns['years_tgt'] != temp_returns['years_act']: x = 1 # MAKE CHARTS/TABLES! axis_font =",
"portfolio positions working_data = dataset working_data['mret'] = working_data.groupby('ticker')['adj close'].pct_change() working_data['mretp1'] = working_data['mret'] +",
"# ------------------------------------------------------------------------------------- # FUNCTIONS --------------------------------------------------------------------------- # ------------------------------------------------------------------------------------- def to_pct(dec): ''' Converts a numeric",
"1 # Merge in S&P 500 data from other_data_pull module port_ret = port_ret.join(spy_join)",
"datetime import plotly import plotly.graph_objects as go from plotly.subplots import make_subplots from app.other_data_pull",
"import make_subplots from app.other_data_pull import spy_pull, fred_pull from app.port_data_pull import port_data_pull from app.portfolio_import",
"analysis start date pd_start_val = working_data.loc[working_data['month'] == pd_start] pd_start_val = pd_start_val.set_index('ticker') pd_start_val =",
"import pandas as pd import os import dotenv from dotenv import load_dotenv import",
"# Calculate portfolio and S&P 500 excess returns over risk free rate port_ret['exret']",
"and port_data_pull modules be # run separately/individually (i.e., not called from within this",
"= [to_pct(results[i]['ann_ret']), to_pct(results[i]['ann_sdev']), two_dec(results[i]['sharpe_port']), two_dec(results[i]['beta'])] col3 = [to_pct(results[i]['ann_spret']), to_pct(results[i]['ann_sp_sdev']), two_dec(results[i]['sharpe_sp']), two_dec(1.00)] fig.add_trace(go.Table(header=dict(values=['Statistic', 'Portfolio',",
"data are insufficient, # only store results for complete or near complete periods.",
"Months' pd_detail=f'{yr_str}{join_str}{mon_str}' return pd_detail def returns(dataset, period_length, min_start, max_end): ''' Calculates various portfolio",
"to a text description of years and months. Param: mon_len (int) like 17",
"ret'], name='Portfolio Cumulative Return', line=dict(color='firebrick', width=4)), 'sp line': go.Scatter(x=temp_tot['month'], y=temp_tot['cum spret'], name='S&P 500",
"spret'])**(1 / years) - 1 avg_mon_spret = (port_ret.loc[pd_end, 'cum spret'])**(1 / months) -",
"If data are insufficient, # only store results for complete or near complete",
"** .5) # Calculate portfolio beta (covariance of portfolio and S&P 500 divided",
"17 Example: mon_len(17) Returns: 1 Year and 5 Months ''' full_years = int(mon_len",
"(was na due to # pct_change() function) port_ret.loc[pd_start + 1, 'mon ret'] =",
"port_ret = port_ret.drop(columns=['spretp1']) # Calculate portfolio and S&P 500 excess returns over risk",
"position at the analysis start date pd_start_val = working_data.loc[working_data['month'] == pd_start] pd_start_val =",
"modules be # run separately/individually (i.e., not called from within this program) sub",
"12 avg_ann_ret = (port_ret.loc[pd_end, 'cum ret'])**(1 / years) - 1 avg_mon_ret = (port_ret.loc[pd_end,",
"CODE -------------------------------------------------------------------------------- # ------------------------------------------------------------------------------------- if __name__=='__main__': # Loan environment variables load_dotenv() port_file_name =",
"and 7 months, then the 3-year # analysis period will record results for",
"period starting portfolio values) working_data['sh val'] = working_data['qty'] * working_data['close'] # Define analysis",
"mon_sp_sdev * (12 ** .5) # Calculate portfolio beta (covariance of portfolio and",
"= tot_ret_data.reset_index().to_dict(orient='list') return ret_calc, tot_ret_dict, port_ret # ------------------------------------------------------------------------------------- # CODE -------------------------------------------------------------------------------- # -------------------------------------------------------------------------------------",
"months) - 1 avg_ann_spret = (port_ret.loc[pd_end, 'cum spret'])**(1 / years) - 1 avg_mon_spret",
"APIs spy_join = spy_pull(ap_api_key) fred_join = fred_pull(fred_api_key) # Call on port_data_pull module for",
"of 2 years and 7 months, and the loop # will not bother",
"spret']).set_index('month') tot_ret_data=tot_ret_data.append(app_df).sort_index() tot_ret_data.index = tot_ret_data.index.to_series().astype(str) tot_ret_dict = tot_ret_data.reset_index().to_dict(orient='list') return ret_calc, tot_ret_dict, port_ret #",
"avg_mon_spret, 'ann_sp_sdev': ann_sp_sdev, 'mon_sp_sdev': mon_sp_sdev, 'beta': beta, 'sharpe_port': sharpe_port, 'sharpe_sp': sharpe_sp} # Create",
"chart elements for 1, 2, 3, and 5 year analysis periods # (but",
"------------------------------------------------------------------------------------- def to_pct(dec): ''' Converts a numeric value to formatted string for printing",
"= {'years_tgt': pd_len, 'years_act': years, 'months_act': months, 'st_date': pd_start.strftime('%Y-%m'), 'end_date': pd_end.strftime('%Y-%m'), 'ann_ret': avg_ann_ret,",
"size=20))) fig.update_layout(xaxis=dict(title=dict(text='Month', font=axis_font), ticks='outside', tickfont=tick_font)) fig.update_layout(yaxis=dict(title=dict(text='Cumulative Monthly Returns (%)', font=axis_font), ticks='outside', tickfont=tick_font, tickformat='.1%'))",
"positions. The most recent # first monthly data point for a given stock",
"[{'type':'scatter'}]]) fig.add_trace(figs[i]['port line'], row=2, col=1) fig.add_trace(figs[i]['sp line'], row=2, col=1,) pd_months = results[i]['months_act'] fig.update_layout(title=dict(text=f'Portfolio",
"= (port_ret.loc[pd_end, 'cum spret'])**(1 / months) - 1 #Calculate return standard deviations mon_sdev",
"elif full_years == 1: yr_str = f'{full_years} Year' else: yr_str = f'{full_years} Years'",
"string for printing and display purposes. Param: dec (int or float) like 4000.444444",
"the analysis start date pd_start_val = working_data.loc[working_data['month'] == pd_start] pd_start_val = pd_start_val.set_index('ticker') pd_start_val",
"port_ret['exret'] = port_ret['mon ret'] - port_ret['rate'] port_ret['exspret'] = port_ret['spret'] - port_ret['rate'] # Calculate",
"= fred_pull(fred_api_key) # Call on port_data_pull module for monthly data on individual portfolio",
"pd_end)] cum_ret_set = cum_ret_set.set_index('ticker') cum_ret_set['cumret'] = cum_ret_set.groupby('ticker')['mretp1'].cumprod() cum_ret_set = cum_ret_set.join(pd_start_val, on='ticker') cum_ret_set['mon val']",
"'months_act': months, 'st_date': pd_start.strftime('%Y-%m'), 'end_date': pd_end.strftime('%Y-%m'), 'ann_ret': avg_ann_ret, 'mon_ret': avg_mon_ret, 'ann_sdev': ann_sdev, 'mon_sdev':",
"results.append(temp_returns) tot_ret.append(temp_tot) keep.append(i) figs.append({'port line': go.Scatter(x=temp_tot['month'], y=temp_tot['cum ret'], name='Portfolio Cumulative Return', line=dict(color='firebrick', width=4)),",
"S&P 500 data from other_data_pull module port_ret = port_ret.join(spy_join) # Merge in 1Y",
"Replace analysis period start month portfolio return (was na due to # pct_change()",
"'cum ret'])**(1 / months) - 1 avg_ann_spret = (port_ret.loc[pd_end, 'cum spret'])**(1 / years)",
"Monthly Returns (%)', font=axis_font), ticks='outside', tickfont=tick_font, tickformat='.1%')) fig.update_layout(legend=dict(orientation='h', font=axis_font)) col1 = ['Avg. Annual",
"= port_ret.join(spy_join) # Merge in 1Y constant maturity treasury data from other_data_pull module",
"period length. For now, analysis period start date is # based on the",
"cum_ret_set = cum_ret_set.join(pd_start_val, on='ticker') cum_ret_set['mon val'] = cum_ret_set['start val'] * cum_ret_set['cumret'] # Calculate",
"[1,2,3,5]: if x==0: temp_returns, temp_tot, temp_review = returns(sub, i, maxomin, minomax) results.append(temp_returns) tot_ret.append(temp_tot)",
"sharpe_sp = (port_ret['exspret'].mean() / port_ret['exspret'].std()) * (12 ** .5) # Assemble dictionary of",
"visualization. ''' # Calculate percent returns of individual portfolio positions working_data = dataset",
"share values over time (used to pull analysis period starting portfolio values) working_data['sh",
"rate port_ret['exret'] = port_ret['mon ret'] - port_ret['rate'] port_ret['exspret'] = port_ret['spret'] - port_ret['rate'] #",
"'cum spret'])**(1 / months) - 1 #Calculate return standard deviations mon_sdev = port_ret['mon",
"port_ret.cov().loc['spret', 'spret'] # Calculate sharpe ratios sharpe_port = (port_ret['exret'].mean() / port_ret['exret'].std()) * (12",
"(int) like 17 Example: mon_len(17) Returns: 1 Year and 5 Months ''' full_years",
"working_data['mret'] + 1 # Calculate share values over time (used to pull analysis",
"ret', 'cum spret']).set_index('month') tot_ret_data=tot_ret_data.append(app_df).sort_index() tot_ret_data.index = tot_ret_data.index.to_series().astype(str) tot_ret_dict = tot_ret_data.reset_index().to_dict(orient='list') return ret_calc, tot_ret_dict,",
"val'].rename('start val') # Caclulate cumulative returns and corresponding monthly values of individual #",
"def to_pct(dec): ''' Converts a numeric value to formatted string for printing and",
"a limitation of the data/API. pd_len = period_length pd_end = max_end pd_start =",
"and monthly returns months = len(port_ret) years = months / 12 avg_ann_ret =",
"os.environ.get('PORTFOLIO_FILE_NAME') ap_api_key = os.environ.get('ALPHAVANTAGE_API_KEY') fred_api_key = os.environ.get('FRED_API_KEY') portfolio = portfolio_import(port_file_name) if APP_ENV ==",
"maxomin = sub['month'].min() minomax = sub['month'].max() else: # Call on other_data_pull module for",
"== 1: yr_str = f'{full_years} Year' else: yr_str = f'{full_years} Years' if resid_months",
".5) # Assemble dictionary of calculation results ret_calc = {'years_tgt': pd_len, 'years_act': years,",
"fig.add_trace(figs[i]['port line'], row=2, col=1) fig.add_trace(figs[i]['sp line'], row=2, col=1,) pd_months = results[i]['months_act'] fig.update_layout(title=dict(text=f'Portfolio Performance",
"Returns: 4,000.44 ''' return f'{dec:,.2f}' def pd_describe(mon_len): ''' Converts a specified number of",
"values of individual # portfolio positions over time cum_ret_set = working_data.loc[(working_data['month'] > pd_start)",
"APP_ENV == 'development': # Requires that each of other_data_pull and port_data_pull modules be",
"of individual # portfolio positions over time cum_ret_set = working_data.loc[(working_data['month'] > pd_start) &",
"Year and 5 Months ''' full_years = int(mon_len / 12) resid_months = mon_len",
"and resid_months > 0): join_str = ' and ' else: join_str = ''",
"fig.update_layout(xaxis=dict(title=dict(text='Month', font=axis_font), ticks='outside', tickfont=tick_font)) fig.update_layout(yaxis=dict(title=dict(text='Cumulative Monthly Returns (%)', font=axis_font), ticks='outside', tickfont=tick_font, tickformat='.1%')) fig.update_layout(legend=dict(orientation='h',",
"import plotly import plotly.graph_objects as go from plotly.subplots import make_subplots from app.other_data_pull import",
"port_ret[['cum ret', 'cum spret']] - 1 app_df = pd.DataFrame([[tot_ret_data.index.min() - 1, 0, 0]],",
"# Alpha Vantage and FRED (Federal Reserve Economic Data) APIs spy_join = spy_pull(ap_api_key)",
"ratios sharpe_port = (port_ret['exret'].mean() / port_ret['exret'].std()) * (12 ** .5) sharpe_sp = (port_ret['exspret'].mean()",
"measures and prepares data for data visualization. ''' # Calculate percent returns of",
"** .5) # Assemble dictionary of calculation results ret_calc = {'years_tgt': pd_len, 'years_act':",
"Assemble dictionary of calculation results ret_calc = {'years_tgt': pd_len, 'years_act': years, 'months_act': months,",
"ret'].std() ann_sdev = mon_sdev * (12 ** .5) mon_sp_sdev = port_ret['spret'].std() ann_sp_sdev =",
"__name__=='__main__': # Loan environment variables load_dotenv() port_file_name = os.environ.get('PORTFOLIO_FILE_NAME') ap_api_key = os.environ.get('ALPHAVANTAGE_API_KEY') fred_api_key",
"= os.environ.get('ALPHAVANTAGE_API_KEY') fred_api_key = os.environ.get('FRED_API_KEY') portfolio = portfolio_import(port_file_name) if APP_ENV == 'development': #",
"elif resid_months == 1: mon_str = f'{resid_months} Month' else: mon_str=f'{resid_months} Months' pd_detail=f'{yr_str}{join_str}{mon_str}' return",
"= spy_pull(ap_api_key) fred_join = fred_pull(fred_api_key) # Call on port_data_pull module for monthly data",
"fred_join['month'] = fred_join['month'].dt.to_period('M') fred_join=fred_join.set_index('month') maxomin = sub['month'].min() minomax = sub['month'].max() else: # Call",
"'sharpe_port': sharpe_port, 'sharpe_sp': sharpe_sp} # Create total (cumulative) returns dataset for data visualization",
"will record results for a period of 2 years and 7 months, and",
"record results for a period of 2 years and 7 months, and the",
"axis_font = dict(size=16, family='Times New Roman') tick_font = dict(size=12, family='Times New Roman') for",
"length. For now, analysis period start date is # based on the data",
"of months to a text description of years and months. Param: mon_len (int)",
"7 months, then the 3-year # analysis period will record results for a",
"Vantage and FRED (Federal Reserve Economic Data) APIs spy_join = spy_pull(ap_api_key) fred_join =",
"'mon val']].sum() port_ret['cum ret'] = port_ret['mon val'] / port_ret['start val'] port_ret['mon ret'] =",
"working_data.groupby('ticker')['adj close'].pct_change() working_data['mretp1'] = working_data['mret'] + 1 # Calculate share values over time",
"' else: join_str = '' if full_years == 0: yr_str = '' elif",
"port_ret['spret'] - port_ret['rate'] # Calculate average annual and monthly returns months = len(port_ret)",
"years = months / 12 avg_ann_ret = (port_ret.loc[pd_end, 'cum ret'])**(1 / years) -",
"from other_data_pull module port_ret = port_ret.join(spy_join) # Merge in 1Y constant maturity treasury",
"= f'{full_years} Year' else: yr_str = f'{full_years} Years' if resid_months == 0: mon_str",
"tickfont=tick_font, tickformat='.1%')) fig.update_layout(legend=dict(orientation='h', font=axis_font)) col1 = ['Avg. Annual Return', 'Std. Dev. (Ann.)', 'Sharpe",
"keep.append(i) figs.append({'port line': go.Scatter(x=temp_tot['month'], y=temp_tot['cum ret'], name='Portfolio Cumulative Return', line=dict(color='firebrick', width=4)), 'sp line':",
"'..', 'data', \"working_spy.csv\"), parse_dates=['month']) spy_join['month'] = spy_join['month'].dt.to_period('M') spy_join=spy_join.set_index('month') fred_join = pd.read_csv(os.path.join(os.path.dirname(os.path.abspath( __file__)), '..',",
"excess returns over risk free rate port_ret['exret'] = port_ret['mon ret'] - port_ret['rate'] port_ret['exspret']",
"beta = port_ret.cov().loc['mon ret', 'spret'] / port_ret.cov().loc['spret', 'spret'] # Calculate sharpe ratios sharpe_port",
"3, and 5 year analysis periods # (but only if sufficient data exists",
"start month portfolio return (was na due to # pct_change() function) port_ret.loc[pd_start +",
"port_ret['mon ret'] = port_ret['mon val'].pct_change() # Replace analysis period start month portfolio return",
"pd_start.strftime('%Y-%m'), 'end_date': pd_end.strftime('%Y-%m'), 'ann_ret': avg_ann_ret, 'mon_ret': avg_mon_ret, 'ann_sdev': ann_sdev, 'mon_sdev': mon_sdev, 'ann_spret': avg_ann_spret,",
"dotenv from dotenv import load_dotenv import datetime import plotly import plotly.graph_objects as go",
"only if sufficient data exists for all portfolio positions). If data are insufficient,",
"# (but only if sufficient data exists for all portfolio positions). If data",
"ann_sp_sdev, 'mon_sp_sdev': mon_sp_sdev, 'beta': beta, 'sharpe_port': sharpe_port, 'sharpe_sp': sharpe_sp} # Create total (cumulative)",
"__file__)), '..', 'data', \"working_fred.csv\"), parse_dates=['month']) fred_join['month'] = fred_join['month'].dt.to_period('M') fred_join=fred_join.set_index('month') maxomin = sub['month'].min() minomax",
"period start date is # based on the data availability of the individual",
"app.other_data_pull import spy_pull, fred_pull from app.port_data_pull import port_data_pull from app.portfolio_import import portfolio_import from",
"port_ret['mon val'] / port_ret['start val'] port_ret['mon ret'] = port_ret['mon val'].pct_change() # Replace analysis",
"= cum_ret_set.groupby('month')[['start val', 'mon val']].sum() port_ret['cum ret'] = port_ret['mon val'] / port_ret['start val']",
"= port_ret[['cum ret', 'cum spret']] - 1 app_df = pd.DataFrame([[tot_ret_data.index.min() - 1, 0,",
"avg_ann_ret, 'mon_ret': avg_mon_ret, 'ann_sdev': ann_sdev, 'mon_sdev': mon_sdev, 'ann_spret': avg_ann_spret, 'mon_spret': avg_mon_spret, 'ann_sp_sdev': ann_sp_sdev,",
"pd.read_csv(os.path.join(os.path.dirname(os.path.abspath( __file__)), '..', 'data', \"working_port.csv\"), parse_dates=['timestamp', 'month']) sub['month']=sub['month'].dt.to_period('M') spy_join = pd.read_csv(os.path.join(os.path.dirname(os.path.abspath( __file__)), '..',",
"as pd import os import dotenv from dotenv import load_dotenv import datetime import",
"'..', 'data', \"working_fred.csv\"), parse_dates=['month']) fred_join['month'] = fred_join['month'].dt.to_period('M') fred_join=fred_join.set_index('month') maxomin = sub['month'].min() minomax =",
"resid_months > 0): join_str = ' and ' else: join_str = '' if",
"= '' elif full_years == 1: yr_str = f'{full_years} Year' else: yr_str =",
"import plotly.graph_objects as go from plotly.subplots import make_subplots from app.other_data_pull import spy_pull, fred_pull",
"min_start, max_end): ''' Calculates various portfolio performance measures and prepares data for data",
"analysis period port_ret['spretp1'] = port_ret['spret'] + 1 port_ret['cum spret'] = port_ret['spretp1'].cumprod() port_ret =",
"formatted string for printing and display purposes. Param: dec (int or float) like",
"portfolio positions). If data are insufficient, # only store results for complete or",
"else: # Call on other_data_pull module for S&P 500 and risk free rate",
"mon_sdev * (12 ** .5) mon_sp_sdev = port_ret['spret'].std() ann_sp_sdev = mon_sp_sdev * (12",
"import port_data_pull from app.portfolio_import import portfolio_import from app import APP_ENV # ------------------------------------------------------------------------------------- #",
"of the data/API. pd_len = period_length pd_end = max_end pd_start = max(max_end -",
"= port_ret['spret'] + 1 port_ret['cum spret'] = port_ret['spretp1'].cumprod() port_ret = port_ret.drop(columns=['spretp1']) # Calculate",
"pd_len = period_length pd_end = max_end pd_start = max(max_end - (pd_len * 12),",
"= results[i]['months_act'] fig.update_layout(title=dict(text=f'Portfolio Performance Report: Monthly Returns over Last {pd_describe(pd_months)}', font=dict(family='Times New Roman',",
"# MAKE CHARTS/TABLES! axis_font = dict(size=16, family='Times New Roman') tick_font = dict(size=12, family='Times",
"= pd.DataFrame([[tot_ret_data.index.min() - 1, 0, 0]], columns=['month', 'cum ret', 'cum spret']).set_index('month') tot_ret_data=tot_ret_data.append(app_df).sort_index() tot_ret_data.index",
"over time port_ret = cum_ret_set.groupby('month')[['start val', 'mon val']].sum() port_ret['cum ret'] = port_ret['mon val']",
"'cum spret']] - 1 app_df = pd.DataFrame([[tot_ret_data.index.min() - 1, 0, 0]], columns=['month', 'cum",
"if APP_ENV == 'development': # Requires that each of other_data_pull and port_data_pull modules",
"not bother with the 5-year calculations. results = [] tot_ret=[] x = 0",
"= port_ret.loc[pd_start + 1, 'cum ret'] - 1 # Merge in S&P 500",
"val'] = cum_ret_set['start val'] * cum_ret_set['cumret'] # Calculate monthly returns on the total",
"port_ret['exspret'] = port_ret['spret'] - port_ret['rate'] # Calculate average annual and monthly returns months",
"Roman', size=20))) fig.update_layout(xaxis=dict(title=dict(text='Month', font=axis_font), ticks='outside', tickfont=tick_font)) fig.update_layout(yaxis=dict(title=dict(text='Cumulative Monthly Returns (%)', font=axis_font), ticks='outside', tickfont=tick_font,",
"portfolio becomes the analysis # start date. This is a limitation of the",
"ret', 'spret'] / port_ret.cov().loc['spret', 'spret'] # Calculate sharpe ratios sharpe_port = (port_ret['exret'].mean() /",
"Performance Report: Monthly Returns over Last {pd_describe(pd_months)}', font=dict(family='Times New Roman', size=20))) fig.update_layout(xaxis=dict(title=dict(text='Month', font=axis_font),",
"analysis period start month portfolio return (was na due to # pct_change() function)",
"(working_data['month'] <= pd_end)] cum_ret_set = cum_ret_set.set_index('ticker') cum_ret_set['cumret'] = cum_ret_set.groupby('ticker')['mretp1'].cumprod() cum_ret_set = cum_ret_set.join(pd_start_val, on='ticker')",
"full_years == 0: yr_str = '' elif full_years == 1: yr_str = f'{full_years}",
"working_data['close'] # Define analysis period length. For now, analysis period start date is",
"fred_join=fred_join.set_index('month') maxomin = sub['month'].min() minomax = sub['month'].max() else: # Call on other_data_pull module",
"values) working_data['sh val'] = working_data['qty'] * working_data['close'] # Define analysis period length. For",
"one stock in the portfolio is 2 years and 7 months, then the",
"data/API. pd_len = period_length pd_end = max_end pd_start = max(max_end - (pd_len *",
"port_file_name = os.environ.get('PORTFOLIO_FILE_NAME') ap_api_key = os.environ.get('ALPHAVANTAGE_API_KEY') fred_api_key = os.environ.get('FRED_API_KEY') portfolio = portfolio_import(port_file_name) if",
"0: mon_str = '' elif resid_months == 1: mon_str = f'{resid_months} Month' else:",
"500 Cumulative Return', line=dict(color='royalblue', width=4))}) if temp_returns['years_tgt'] != temp_returns['years_act']: x = 1 #",
"# volatility of S&P 500) beta = port_ret.cov().loc['mon ret', 'spret'] / port_ret.cov().loc['spret', 'spret']",
"The most recent # first monthly data point for a given stock in",
"years) - 1 avg_mon_spret = (port_ret.loc[pd_end, 'cum spret'])**(1 / months) - 1 #Calculate",
"Returns over Last {pd_describe(pd_months)}', font=dict(family='Times New Roman', size=20))) fig.update_layout(xaxis=dict(title=dict(text='Month', font=axis_font), ticks='outside', tickfont=tick_font)) fig.update_layout(yaxis=dict(title=dict(text='Cumulative",
"months / 12 avg_ann_ret = (port_ret.loc[pd_end, 'cum ret'])**(1 / years) - 1 avg_mon_ret",
"constant maturity treasury data from other_data_pull module port_ret = port_ret.join(fred_join) # Calculate S&P",
"calculation results ret_calc = {'years_tgt': pd_len, 'years_act': years, 'months_act': months, 'st_date': pd_start.strftime('%Y-%m'), 'end_date':",
"function) port_ret.loc[pd_start + 1, 'mon ret'] = port_ret.loc[pd_start + 1, 'cum ret'] -",
"tot_ret.append(temp_tot) keep.append(i) figs.append({'port line': go.Scatter(x=temp_tot['month'], y=temp_tot['cum ret'], name='Portfolio Cumulative Return', line=dict(color='firebrick', width=4)), 'sp",
"loop # will not bother with the 5-year calculations. results = [] tot_ret=[]",
"over Last {pd_describe(pd_months)}', font=dict(family='Times New Roman', size=20))) fig.update_layout(xaxis=dict(title=dict(text='Month', font=axis_font), ticks='outside', tickfont=tick_font)) fig.update_layout(yaxis=dict(title=dict(text='Cumulative Monthly",
"the longest data # sampling period for one stock in the portfolio is",
"if resid_months == 0: mon_str = '' elif resid_months == 1: mon_str =",
"(covariance of portfolio and S&P 500 divided by # volatility of S&P 500)",
"2, 3, and 5 year analysis periods # (but only if sufficient data",
"family='Times New Roman') for i in range(len(figs)): fig = make_subplots(rows=2, cols=1, vertical_spacing=0.03, row_width=[0.75,0.25],",
"col=1,) pd_months = results[i]['months_act'] fig.update_layout(title=dict(text=f'Portfolio Performance Report: Monthly Returns over Last {pd_describe(pd_months)}', font=dict(family='Times",
"results[i]['months_act'] fig.update_layout(title=dict(text=f'Portfolio Performance Report: Monthly Returns over Last {pd_describe(pd_months)}', font=dict(family='Times New Roman', size=20)))",
"1, 0, 0]], columns=['month', 'cum ret', 'cum spret']).set_index('month') tot_ret_data=tot_ret_data.append(app_df).sort_index() tot_ret_data.index = tot_ret_data.index.to_series().astype(str) tot_ret_dict",
"display purposes. Param: dec (int or float) like 4000.444444 Example: two_dec(4000.444444) Returns: 4,000.44",
"7 months, and the loop # will not bother with the 5-year calculations.",
"__file__)), '..', 'data', \"working_port.csv\"), parse_dates=['timestamp', 'month']) sub['month']=sub['month'].dt.to_period('M') spy_join = pd.read_csv(os.path.join(os.path.dirname(os.path.abspath( __file__)), '..', 'data',",
"cum_ret_set.groupby('month')[['start val', 'mon val']].sum() port_ret['cum ret'] = port_ret['mon val'] / port_ret['start val'] port_ret['mon",
"if full_years == 0: yr_str = '' elif full_years == 1: yr_str =",
"1: mon_str = f'{resid_months} Month' else: mon_str=f'{resid_months} Months' pd_detail=f'{yr_str}{join_str}{mon_str}' return pd_detail def returns(dataset,",
"return ret_calc, tot_ret_dict, port_ret # ------------------------------------------------------------------------------------- # CODE -------------------------------------------------------------------------------- # ------------------------------------------------------------------------------------- if __name__=='__main__':",
"percent returns of individual portfolio positions working_data = dataset working_data['mret'] = working_data.groupby('ticker')['adj close'].pct_change()",
"Create total (cumulative) returns dataset for data visualization tot_ret_data = port_ret[['cum ret', 'cum",
"working_data['sh val'] = working_data['qty'] * working_data['close'] # Define analysis period length. For now,",
"# Define analysis period length. For now, analysis period start date is #",
"'cum spret'])**(1 / years) - 1 avg_mon_spret = (port_ret.loc[pd_end, 'cum spret'])**(1 / months)",
"# Calculate portfolio beta (covariance of portfolio and S&P 500 divided by #",
"i in [1,2,3,5]: if x==0: temp_returns, temp_tot, temp_review = returns(sub, i, maxomin, minomax)",
"and corresponding monthly values of individual # portfolio positions over time cum_ret_set =",
"total (cumulative) returns dataset for data visualization tot_ret_data = port_ret[['cum ret', 'cum spret']]",
"spy_join['month'].dt.to_period('M') spy_join=spy_join.set_index('month') fred_join = pd.read_csv(os.path.join(os.path.dirname(os.path.abspath( __file__)), '..', 'data', \"working_fred.csv\"), parse_dates=['month']) fred_join['month'] = fred_join['month'].dt.to_period('M')",
"dec (int or float) like 4000.444444 Example: two_dec(4000.444444) Returns: 4,000.44 ''' return f'{dec:,.2f}'",
"= pd_start_val['sh val'].rename('start val') # Caclulate cumulative returns and corresponding monthly values of",
"= '' if full_years == 0: yr_str = '' elif full_years == 1:",
"This is a limitation of the data/API. pd_len = period_length pd_end = max_end",
"'mon_ret': avg_mon_ret, 'ann_sdev': ann_sdev, 'mon_sdev': mon_sdev, 'ann_spret': avg_ann_spret, 'mon_spret': avg_mon_spret, 'ann_sp_sdev': ann_sp_sdev, 'mon_sp_sdev':",
"'mon_spret': avg_mon_spret, 'ann_sp_sdev': ann_sp_sdev, 'mon_sp_sdev': mon_sp_sdev, 'beta': beta, 'sharpe_port': sharpe_port, 'sharpe_sp': sharpe_sp} #",
"port_ret['rate'] # Calculate average annual and monthly returns months = len(port_ret) years =",
"Define analysis period length. For now, analysis period start date is # based",
"= sub['month'].max() else: # Call on other_data_pull module for S&P 500 and risk",
"Dev. (Ann.)', 'Sharpe Ratio', 'Beta'] col2 = [to_pct(results[i]['ann_ret']), to_pct(results[i]['ann_sdev']), two_dec(results[i]['sharpe_port']), two_dec(results[i]['beta'])] col3 =",
"col3 = [to_pct(results[i]['ann_spret']), to_pct(results[i]['ann_sp_sdev']), two_dec(results[i]['sharpe_sp']), two_dec(1.00)] fig.add_trace(go.Table(header=dict(values=['Statistic', 'Portfolio', 'S&P 500']), cells=dict(values=[col1, col2, col3])),row=1,col=1)",
"portfolio over time port_ret = cum_ret_set.groupby('month')[['start val', 'mon val']].sum() port_ret['cum ret'] = port_ret['mon",
"like 4000.444444 Example: two_dec(4000.444444) Returns: 4,000.44 ''' return f'{dec:,.2f}' def pd_describe(mon_len): ''' Converts",
"1 # Calculate share values over time (used to pull analysis period starting",
"- port_ret['rate'] # Calculate average annual and monthly returns months = len(port_ret) years",
"/ months) - 1 avg_ann_spret = (port_ret.loc[pd_end, 'cum spret'])**(1 / years) - 1",
"Call on other_data_pull module for S&P 500 and risk free rate data from",
"500 and risk free rate data from # Alpha Vantage and FRED (Federal",
"pd_detail=f'{yr_str}{join_str}{mon_str}' return pd_detail def returns(dataset, period_length, min_start, max_end): ''' Calculates various portfolio performance",
"Annual Return', 'Std. Dev. (Ann.)', 'Sharpe Ratio', 'Beta'] col2 = [to_pct(results[i]['ann_ret']), to_pct(results[i]['ann_sdev']), two_dec(results[i]['sharpe_port']),",
"x = 0 keep = [] figs = [] for i in [1,2,3,5]:",
"Converts a specified number of months to a text description of years and",
"to # pct_change() function) port_ret.loc[pd_start + 1, 'mon ret'] = port_ret.loc[pd_start + 1,",
"ret_calc = {'years_tgt': pd_len, 'years_act': years, 'months_act': months, 'st_date': pd_start.strftime('%Y-%m'), 'end_date': pd_end.strftime('%Y-%m'), 'ann_ret':",
"0]], columns=['month', 'cum ret', 'cum spret']).set_index('month') tot_ret_data=tot_ret_data.append(app_df).sort_index() tot_ret_data.index = tot_ret_data.index.to_series().astype(str) tot_ret_dict = tot_ret_data.reset_index().to_dict(orient='list')",
"i, maxomin, minomax) results.append(temp_returns) tot_ret.append(temp_tot) keep.append(i) figs.append({'port line': go.Scatter(x=temp_tot['month'], y=temp_tot['cum ret'], name='Portfolio Cumulative",
"port_ret = port_ret.join(fred_join) # Calculate S&P 500 returns and cumulative return over analysis",
"(used to pull analysis period starting portfolio values) working_data['sh val'] = working_data['qty'] *",
"on the total portfolio over time port_ret = cum_ret_set.groupby('month')[['start val', 'mon val']].sum() port_ret['cum",
"y=temp_tot['cum ret'], name='Portfolio Cumulative Return', line=dict(color='firebrick', width=4)), 'sp line': go.Scatter(x=temp_tot['month'], y=temp_tot['cum spret'], name='S&P",
"S&P 500 and risk free rate data from # Alpha Vantage and FRED",
"Calculates various portfolio performance measures and prepares data for data visualization. ''' #",
"port_ret['spret'].std() ann_sp_sdev = mon_sp_sdev * (12 ** .5) # Calculate portfolio beta (covariance",
"if __name__=='__main__': # Loan environment variables load_dotenv() port_file_name = os.environ.get('PORTFOLIO_FILE_NAME') ap_api_key = os.environ.get('ALPHAVANTAGE_API_KEY')",
"return pd_detail def returns(dataset, period_length, min_start, max_end): ''' Calculates various portfolio performance measures",
"tickformat='.1%')) fig.update_layout(legend=dict(orientation='h', font=axis_font)) col1 = ['Avg. Annual Return', 'Std. Dev. (Ann.)', 'Sharpe Ratio',",
"sub = pd.read_csv(os.path.join(os.path.dirname(os.path.abspath( __file__)), '..', 'data', \"working_port.csv\"), parse_dates=['timestamp', 'month']) sub['month']=sub['month'].dt.to_period('M') spy_join = pd.read_csv(os.path.join(os.path.dirname(os.path.abspath(",
"sub['month'].min() minomax = sub['month'].max() else: # Call on other_data_pull module for S&P 500",
"and 7 months, and the loop # will not bother with the 5-year",
"parse_dates=['month']) spy_join['month'] = spy_join['month'].dt.to_period('M') spy_join=spy_join.set_index('month') fred_join = pd.read_csv(os.path.join(os.path.dirname(os.path.abspath( __file__)), '..', 'data', \"working_fred.csv\"), parse_dates=['month'])",
"* (12 ** .5) mon_sp_sdev = port_ret['spret'].std() ann_sp_sdev = mon_sp_sdev * (12 **",
"full_years = int(mon_len / 12) resid_months = mon_len % 12 if (full_years >",
"''' Converts a specified number of months to a text description of years",
"monthly values of individual # portfolio positions over time cum_ret_set = working_data.loc[(working_data['month'] >",
"Collect and store results, datasets, and chart elements for 1, 2, 3, and",
"on port_data_pull module for monthly data on individual portfolio stocks # from Alpha",
"% 12 if (full_years > 0 and resid_months > 0): join_str = '",
"returns months = len(port_ret) years = months / 12 avg_ann_ret = (port_ret.loc[pd_end, 'cum",
"from app.portfolio_import import portfolio_import from app import APP_ENV # ------------------------------------------------------------------------------------- # FUNCTIONS ---------------------------------------------------------------------------",
"years and months. Param: mon_len (int) like 17 Example: mon_len(17) Returns: 1 Year",
"(12 ** .5) mon_sp_sdev = port_ret['spret'].std() ann_sp_sdev = mon_sp_sdev * (12 ** .5)",
"specs=[[{'type':'table'}], [{'type':'scatter'}]]) fig.add_trace(figs[i]['port line'], row=2, col=1) fig.add_trace(figs[i]['sp line'], row=2, col=1,) pd_months = results[i]['months_act']",
"New Roman', size=20))) fig.update_layout(xaxis=dict(title=dict(text='Month', font=axis_font), ticks='outside', tickfont=tick_font)) fig.update_layout(yaxis=dict(title=dict(text='Cumulative Monthly Returns (%)', font=axis_font), ticks='outside',",
"tickfont=tick_font)) fig.update_layout(yaxis=dict(title=dict(text='Cumulative Monthly Returns (%)', font=axis_font), ticks='outside', tickfont=tick_font, tickformat='.1%')) fig.update_layout(legend=dict(orientation='h', font=axis_font)) col1 =",
"''' return f'{dec:,.2f}' def pd_describe(mon_len): ''' Converts a specified number of months to",
"years, 'months_act': months, 'st_date': pd_start.strftime('%Y-%m'), 'end_date': pd_end.strftime('%Y-%m'), 'ann_ret': avg_ann_ret, 'mon_ret': avg_mon_ret, 'ann_sdev': ann_sdev,",
"start date. This is a limitation of the data/API. pd_len = period_length pd_end",
"fred_api_key = os.environ.get('FRED_API_KEY') portfolio = portfolio_import(port_file_name) if APP_ENV == 'development': # Requires that",
"dataset working_data['mret'] = working_data.groupby('ticker')['adj close'].pct_change() working_data['mretp1'] = working_data['mret'] + 1 # Calculate share",
"Vantage API sub, minomax, maxomin=port_data_pull(portfolio,ap_api_key) # Collect and store results, datasets, and chart",
"f'{full_years} Years' if resid_months == 0: mon_str = '' elif resid_months == 1:",
"# FUNCTIONS --------------------------------------------------------------------------- # ------------------------------------------------------------------------------------- def to_pct(dec): ''' Converts a numeric value to",
"pd_len, 'years_act': years, 'months_act': months, 'st_date': pd_start.strftime('%Y-%m'), 'end_date': pd_end.strftime('%Y-%m'), 'ann_ret': avg_ann_ret, 'mon_ret': avg_mon_ret,",
"Example: two_dec(4000.444444) Returns: 4,000.44 ''' return f'{dec:,.2f}' def pd_describe(mon_len): ''' Converts a specified",
"font=axis_font), ticks='outside', tickfont=tick_font, tickformat='.1%')) fig.update_layout(legend=dict(orientation='h', font=axis_font)) col1 = ['Avg. Annual Return', 'Std. Dev.",
"= sub['month'].min() minomax = sub['month'].max() else: # Call on other_data_pull module for S&P",
"Monthly Returns over Last {pd_describe(pd_months)}', font=dict(family='Times New Roman', size=20))) fig.update_layout(xaxis=dict(title=dict(text='Month', font=axis_font), ticks='outside', tickfont=tick_font))",
"pd_start_val = pd_start_val.set_index('ticker') pd_start_val = pd_start_val['sh val'].rename('start val') # Caclulate cumulative returns and",
"sufficient data exists for all portfolio positions). If data are insufficient, # only",
"'data', \"working_port.csv\"), parse_dates=['timestamp', 'month']) sub['month']=sub['month'].dt.to_period('M') spy_join = pd.read_csv(os.path.join(os.path.dirname(os.path.abspath( __file__)), '..', 'data', \"working_spy.csv\"), parse_dates=['month'])",
"fred_join = fred_pull(fred_api_key) # Call on port_data_pull module for monthly data on individual",
"results = [] tot_ret=[] x = 0 keep = [] figs = []",
"Economic Data) APIs spy_join = spy_pull(ap_api_key) fred_join = fred_pull(fred_api_key) # Call on port_data_pull",
"cum_ret_set.set_index('ticker') cum_ret_set['cumret'] = cum_ret_set.groupby('ticker')['mretp1'].cumprod() cum_ret_set = cum_ret_set.join(pd_start_val, on='ticker') cum_ret_set['mon val'] = cum_ret_set['start val']",
"load_dotenv import datetime import plotly import plotly.graph_objects as go from plotly.subplots import make_subplots",
"= mon_sdev * (12 ** .5) mon_sp_sdev = port_ret['spret'].std() ann_sp_sdev = mon_sp_sdev *",
"the 5-year calculations. results = [] tot_ret=[] x = 0 keep = []",
"pd.DataFrame([[tot_ret_data.index.min() - 1, 0, 0]], columns=['month', 'cum ret', 'cum spret']).set_index('month') tot_ret_data=tot_ret_data.append(app_df).sort_index() tot_ret_data.index =",
"''' # Calculate percent returns of individual portfolio positions working_data = dataset working_data['mret']",
"Cumulative Return', line=dict(color='royalblue', width=4))}) if temp_returns['years_tgt'] != temp_returns['years_act']: x = 1 # MAKE",
"avg_ann_ret = (port_ret.loc[pd_end, 'cum ret'])**(1 / years) - 1 avg_mon_ret = (port_ret.loc[pd_end, 'cum",
"line'], row=2, col=1) fig.add_trace(figs[i]['sp line'], row=2, col=1,) pd_months = results[i]['months_act'] fig.update_layout(title=dict(text=f'Portfolio Performance Report:",
"go.Scatter(x=temp_tot['month'], y=temp_tot['cum spret'], name='S&P 500 Cumulative Return', line=dict(color='royalblue', width=4))}) if temp_returns['years_tgt'] != temp_returns['years_act']:",
"various portfolio performance measures and prepares data for data visualization. ''' # Calculate",
"becomes the analysis # start date. This is a limitation of the data/API.",
"1, 'cum ret'] - 1 # Merge in S&P 500 data from other_data_pull",
"maxomin, minomax) results.append(temp_returns) tot_ret.append(temp_tot) keep.append(i) figs.append({'port line': go.Scatter(x=temp_tot['month'], y=temp_tot['cum ret'], name='Portfolio Cumulative Return',",
"printing and display purposes. Param: dec (int or float) like 0.403321 Example: to_pct(0.403321)",
"(Federal Reserve Economic Data) APIs spy_join = spy_pull(ap_api_key) fred_join = fred_pull(fred_api_key) # Call",
"and S&P 500 excess returns over risk free rate port_ret['exret'] = port_ret['mon ret']",
"1Y constant maturity treasury data from other_data_pull module port_ret = port_ret.join(fred_join) # Calculate",
"module port_ret = port_ret.join(spy_join) # Merge in 1Y constant maturity treasury data from",
"'' elif full_years == 1: yr_str = f'{full_years} Year' else: yr_str = f'{full_years}",
"is # based on the data availability of the individual positions. The most",
"at the analysis start date pd_start_val = working_data.loc[working_data['month'] == pd_start] pd_start_val = pd_start_val.set_index('ticker')",
"make_subplots from app.other_data_pull import spy_pull, fred_pull from app.port_data_pull import port_data_pull from app.portfolio_import import",
"in 1Y constant maturity treasury data from other_data_pull module port_ret = port_ret.join(fred_join) #",
"keep = [] figs = [] for i in [1,2,3,5]: if x==0: temp_returns,",
"'Std. Dev. (Ann.)', 'Sharpe Ratio', 'Beta'] col2 = [to_pct(results[i]['ann_ret']), to_pct(results[i]['ann_sdev']), two_dec(results[i]['sharpe_port']), two_dec(results[i]['beta'])] col3",
"Param: dec (int or float) like 4000.444444 Example: two_dec(4000.444444) Returns: 4,000.44 ''' return",
"individual portfolio positions working_data = dataset working_data['mret'] = working_data.groupby('ticker')['adj close'].pct_change() working_data['mretp1'] = working_data['mret']",
"= portfolio_import(port_file_name) if APP_ENV == 'development': # Requires that each of other_data_pull and",
"sub, minomax, maxomin=port_data_pull(portfolio,ap_api_key) # Collect and store results, datasets, and chart elements for",
"results, datasets, and chart elements for 1, 2, 3, and 5 year analysis",
"port_ret['cum ret'] = port_ret['mon val'] / port_ret['start val'] port_ret['mon ret'] = port_ret['mon val'].pct_change()",
"# will not bother with the 5-year calculations. results = [] tot_ret=[] x",
"Roman') tick_font = dict(size=12, family='Times New Roman') for i in range(len(figs)): fig =",
"'spret'] / port_ret.cov().loc['spret', 'spret'] # Calculate sharpe ratios sharpe_port = (port_ret['exret'].mean() / port_ret['exret'].std())",
"periods # (but only if sufficient data exists for all portfolio positions). If",
"value to formatted string for printing and display purposes. Param: dec (int or",
"--------------------------------------------------------------------------- # ------------------------------------------------------------------------------------- def to_pct(dec): ''' Converts a numeric value to formatted string",
"Returns: 40.33% ''' return f'{dec:.2%}' def two_dec(dec): ''' Converts a numeric value to",
"returns and corresponding monthly values of individual # portfolio positions over time cum_ret_set",
"Merge in S&P 500 data from other_data_pull module port_ret = port_ret.join(spy_join) # Merge",
"positions). If data are insufficient, # only store results for complete or near",
"returns on the total portfolio over time port_ret = cum_ret_set.groupby('month')[['start val', 'mon val']].sum()",
"resid_months == 1: mon_str = f'{resid_months} Month' else: mon_str=f'{resid_months} Months' pd_detail=f'{yr_str}{join_str}{mon_str}' return pd_detail",
"(full_years > 0 and resid_months > 0): join_str = ' and ' else:",
"col=1) fig.add_trace(figs[i]['sp line'], row=2, col=1,) pd_months = results[i]['months_act'] fig.update_layout(title=dict(text=f'Portfolio Performance Report: Monthly Returns",
"app.port_data_pull import port_data_pull from app.portfolio_import import portfolio_import from app import APP_ENV # -------------------------------------------------------------------------------------",
"tot_ret_data=tot_ret_data.append(app_df).sort_index() tot_ret_data.index = tot_ret_data.index.to_series().astype(str) tot_ret_dict = tot_ret_data.reset_index().to_dict(orient='list') return ret_calc, tot_ret_dict, port_ret # -------------------------------------------------------------------------------------",
"date. This is a limitation of the data/API. pd_len = period_length pd_end =",
"# run separately/individually (i.e., not called from within this program) sub = pd.read_csv(os.path.join(os.path.dirname(os.path.abspath(",
"/ 12) resid_months = mon_len % 12 if (full_years > 0 and resid_months",
"S&P 500 excess returns over risk free rate port_ret['exret'] = port_ret['mon ret'] -",
"0 and resid_months > 0): join_str = ' and ' else: join_str =",
"cum_ret_set['cumret'] # Calculate monthly returns on the total portfolio over time port_ret =",
"S&P 500 divided by # volatility of S&P 500) beta = port_ret.cov().loc['mon ret',",
"pd_start_val = working_data.loc[working_data['month'] == pd_start] pd_start_val = pd_start_val.set_index('ticker') pd_start_val = pd_start_val['sh val'].rename('start val')",
"period port_ret['spretp1'] = port_ret['spret'] + 1 port_ret['cum spret'] = port_ret['spretp1'].cumprod() port_ret = port_ret.drop(columns=['spretp1'])",
"divided by # volatility of S&P 500) beta = port_ret.cov().loc['mon ret', 'spret'] /",
"4,000.44 ''' return f'{dec:,.2f}' def pd_describe(mon_len): ''' Converts a specified number of months",
"!= temp_returns['years_act']: x = 1 # MAKE CHARTS/TABLES! axis_font = dict(size=16, family='Times New",
"(12 ** .5) # Assemble dictionary of calculation results ret_calc = {'years_tgt': pd_len,",
"data from other_data_pull module port_ret = port_ret.join(fred_join) # Calculate S&P 500 returns and",
"like 17 Example: mon_len(17) Returns: 1 Year and 5 Months ''' full_years =",
"** .5) mon_sp_sdev = port_ret['spret'].std() ann_sp_sdev = mon_sp_sdev * (12 ** .5) #",
"500) beta = port_ret.cov().loc['mon ret', 'spret'] / port_ret.cov().loc['spret', 'spret'] # Calculate sharpe ratios",
"time cum_ret_set = working_data.loc[(working_data['month'] > pd_start) & (working_data['month'] <= pd_end)] cum_ret_set = cum_ret_set.set_index('ticker')",
"portfolio_import(port_file_name) if APP_ENV == 'development': # Requires that each of other_data_pull and port_data_pull",
"be # run separately/individually (i.e., not called from within this program) sub =",
"Month' else: mon_str=f'{resid_months} Months' pd_detail=f'{yr_str}{join_str}{mon_str}' return pd_detail def returns(dataset, period_length, min_start, max_end): '''",
"fred_join = pd.read_csv(os.path.join(os.path.dirname(os.path.abspath( __file__)), '..', 'data', \"working_fred.csv\"), parse_dates=['month']) fred_join['month'] = fred_join['month'].dt.to_period('M') fred_join=fred_join.set_index('month') maxomin",
"app_df = pd.DataFrame([[tot_ret_data.index.min() - 1, 0, 0]], columns=['month', 'cum ret', 'cum spret']).set_index('month') tot_ret_data=tot_ret_data.append(app_df).sort_index()",
"period_length pd_end = max_end pd_start = max(max_end - (pd_len * 12), min_start) #",
"port_data_pull module for monthly data on individual portfolio stocks # from Alpha Vantage",
"all portfolio positions). If data are insufficient, # only store results for complete",
"resid_months == 0: mon_str = '' elif resid_months == 1: mon_str = f'{resid_months}",
"= port_ret['mon ret'] - port_ret['rate'] port_ret['exspret'] = port_ret['spret'] - port_ret['rate'] # Calculate average",
"tot_ret_data.reset_index().to_dict(orient='list') return ret_calc, tot_ret_dict, port_ret # ------------------------------------------------------------------------------------- # CODE -------------------------------------------------------------------------------- # ------------------------------------------------------------------------------------- if",
"# Call on other_data_pull module for S&P 500 and risk free rate data",
"sharpe_port = (port_ret['exret'].mean() / port_ret['exret'].std()) * (12 ** .5) sharpe_sp = (port_ret['exspret'].mean() /",
"if the longest data # sampling period for one stock in the portfolio",
"# pct_change() function) port_ret.loc[pd_start + 1, 'mon ret'] = port_ret.loc[pd_start + 1, 'cum",
"5 Months ''' full_years = int(mon_len / 12) resid_months = mon_len % 12",
"parse_dates=['month']) fred_join['month'] = fred_join['month'].dt.to_period('M') fred_join=fred_join.set_index('month') maxomin = sub['month'].min() minomax = sub['month'].max() else: #",
"for i in range(len(figs)): fig = make_subplots(rows=2, cols=1, vertical_spacing=0.03, row_width=[0.75,0.25], specs=[[{'type':'table'}], [{'type':'scatter'}]]) fig.add_trace(figs[i]['port",
"if (full_years > 0 and resid_months > 0): join_str = ' and '",
"over analysis period port_ret['spretp1'] = port_ret['spret'] + 1 port_ret['cum spret'] = port_ret['spretp1'].cumprod() port_ret",
"dataset for data visualization tot_ret_data = port_ret[['cum ret', 'cum spret']] - 1 app_df",
"= (port_ret['exret'].mean() / port_ret['exret'].std()) * (12 ** .5) sharpe_sp = (port_ret['exspret'].mean() / port_ret['exspret'].std())",
"= pd_start_val.set_index('ticker') pd_start_val = pd_start_val['sh val'].rename('start val') # Caclulate cumulative returns and corresponding",
"sharpe_sp} # Create total (cumulative) returns dataset for data visualization tot_ret_data = port_ret[['cum",
"treasury data from other_data_pull module port_ret = port_ret.join(fred_join) # Calculate S&P 500 returns",
"is 2 years and 7 months, then the 3-year # analysis period will",
"(port_ret['exspret'].mean() / port_ret['exspret'].std()) * (12 ** .5) # Assemble dictionary of calculation results",
"col1 = ['Avg. Annual Return', 'Std. Dev. (Ann.)', 'Sharpe Ratio', 'Beta'] col2 =",
"500 returns and cumulative return over analysis period port_ret['spretp1'] = port_ret['spret'] + 1",
"analysis period starting portfolio values) working_data['sh val'] = working_data['qty'] * working_data['close'] # Define",
"# first monthly data point for a given stock in the portfolio becomes",
"12), min_start) # Create dataset of asset values by position at the analysis",
"(12 ** .5) sharpe_sp = (port_ret['exspret'].mean() / port_ret['exspret'].std()) * (12 ** .5) #",
"parse_dates=['timestamp', 'month']) sub['month']=sub['month'].dt.to_period('M') spy_join = pd.read_csv(os.path.join(os.path.dirname(os.path.abspath( __file__)), '..', 'data', \"working_spy.csv\"), parse_dates=['month']) spy_join['month'] =",
"from Alpha Vantage API sub, minomax, maxomin=port_data_pull(portfolio,ap_api_key) # Collect and store results, datasets,",
"= max_end pd_start = max(max_end - (pd_len * 12), min_start) # Create dataset",
"name='Portfolio Cumulative Return', line=dict(color='firebrick', width=4)), 'sp line': go.Scatter(x=temp_tot['month'], y=temp_tot['cum spret'], name='S&P 500 Cumulative",
"Calculate S&P 500 returns and cumulative return over analysis period port_ret['spretp1'] = port_ret['spret']",
"For example, if the longest data # sampling period for one stock in",
"make_subplots(rows=2, cols=1, vertical_spacing=0.03, row_width=[0.75,0.25], specs=[[{'type':'table'}], [{'type':'scatter'}]]) fig.add_trace(figs[i]['port line'], row=2, col=1) fig.add_trace(figs[i]['sp line'], row=2,",
"will not bother with the 5-year calculations. results = [] tot_ret=[] x =",
"calculations. results = [] tot_ret=[] x = 0 keep = [] figs =",
"now, analysis period start date is # based on the data availability of",
"= cum_ret_set.groupby('ticker')['mretp1'].cumprod() cum_ret_set = cum_ret_set.join(pd_start_val, on='ticker') cum_ret_set['mon val'] = cum_ret_set['start val'] * cum_ret_set['cumret']",
"most recent # first monthly data point for a given stock in the",
"'' if full_years == 0: yr_str = '' elif full_years == 1: yr_str",
"{'years_tgt': pd_len, 'years_act': years, 'months_act': months, 'st_date': pd_start.strftime('%Y-%m'), 'end_date': pd_end.strftime('%Y-%m'), 'ann_ret': avg_ann_ret, 'mon_ret':",
"monthly data on individual portfolio stocks # from Alpha Vantage API sub, minomax,",
"cum_ret_set['cumret'] = cum_ret_set.groupby('ticker')['mretp1'].cumprod() cum_ret_set = cum_ret_set.join(pd_start_val, on='ticker') cum_ret_set['mon val'] = cum_ret_set['start val'] *",
"* (12 ** .5) sharpe_sp = (port_ret['exspret'].mean() / port_ret['exspret'].std()) * (12 ** .5)",
"that each of other_data_pull and port_data_pull modules be # run separately/individually (i.e., not",
"for one stock in the portfolio is 2 years and 7 months, then",
"# Assemble dictionary of calculation results ret_calc = {'years_tgt': pd_len, 'years_act': years, 'months_act':",
"= ' and ' else: join_str = '' if full_years == 0: yr_str",
"line=dict(color='royalblue', width=4))}) if temp_returns['years_tgt'] != temp_returns['years_act']: x = 1 # MAKE CHARTS/TABLES! axis_font",
"1 avg_mon_spret = (port_ret.loc[pd_end, 'cum spret'])**(1 / months) - 1 #Calculate return standard",
"positions working_data = dataset working_data['mret'] = working_data.groupby('ticker')['adj close'].pct_change() working_data['mretp1'] = working_data['mret'] + 1",
"datasets, and chart elements for 1, 2, 3, and 5 year analysis periods",
"'Beta'] col2 = [to_pct(results[i]['ann_ret']), to_pct(results[i]['ann_sdev']), two_dec(results[i]['sharpe_port']), two_dec(results[i]['beta'])] col3 = [to_pct(results[i]['ann_spret']), to_pct(results[i]['ann_sp_sdev']), two_dec(results[i]['sharpe_sp']), two_dec(1.00)]",
"ret'] = port_ret.loc[pd_start + 1, 'cum ret'] - 1 # Merge in S&P",
"return over analysis period port_ret['spretp1'] = port_ret['spret'] + 1 port_ret['cum spret'] = port_ret['spretp1'].cumprod()",
"port_ret.drop(columns=['spretp1']) # Calculate portfolio and S&P 500 excess returns over risk free rate",
"= len(port_ret) years = months / 12 avg_ann_ret = (port_ret.loc[pd_end, 'cum ret'])**(1 /",
"on the data availability of the individual positions. The most recent # first",
"Calculate percent returns of individual portfolio positions working_data = dataset working_data['mret'] = working_data.groupby('ticker')['adj",
"monthly returns on the total portfolio over time port_ret = cum_ret_set.groupby('month')[['start val', 'mon",
"and months. Param: mon_len (int) like 17 Example: mon_len(17) Returns: 1 Year and",
"else: join_str = '' if full_years == 0: yr_str = '' elif full_years",
"Calculate share values over time (used to pull analysis period starting portfolio values)",
"'spret'] # Calculate sharpe ratios sharpe_port = (port_ret['exret'].mean() / port_ret['exret'].std()) * (12 **",
"def returns(dataset, period_length, min_start, max_end): ''' Calculates various portfolio performance measures and prepares",
"returns dataset for data visualization tot_ret_data = port_ret[['cum ret', 'cum spret']] - 1",
"called from within this program) sub = pd.read_csv(os.path.join(os.path.dirname(os.path.abspath( __file__)), '..', 'data', \"working_port.csv\"), parse_dates=['timestamp',",
"'ann_sdev': ann_sdev, 'mon_sdev': mon_sdev, 'ann_spret': avg_ann_spret, 'mon_spret': avg_mon_spret, 'ann_sp_sdev': ann_sp_sdev, 'mon_sp_sdev': mon_sp_sdev, 'beta':",
"months to a text description of years and months. Param: mon_len (int) like",
"data from other_data_pull module port_ret = port_ret.join(spy_join) # Merge in 1Y constant maturity",
"spy_join = spy_pull(ap_api_key) fred_join = fred_pull(fred_api_key) # Call on port_data_pull module for monthly",
"dataset of asset values by position at the analysis start date pd_start_val =",
"and the loop # will not bother with the 5-year calculations. results =",
"def two_dec(dec): ''' Converts a numeric value to formatted string for printing and",
"port_ret['spretp1'].cumprod() port_ret = port_ret.drop(columns=['spretp1']) # Calculate portfolio and S&P 500 excess returns over",
"time port_ret = cum_ret_set.groupby('month')[['start val', 'mon val']].sum() port_ret['cum ret'] = port_ret['mon val'] /",
"avg_ann_spret = (port_ret.loc[pd_end, 'cum spret'])**(1 / years) - 1 avg_mon_spret = (port_ret.loc[pd_end, 'cum",
"Calculate monthly returns on the total portfolio over time port_ret = cum_ret_set.groupby('month')[['start val',",
"/ port_ret['exspret'].std()) * (12 ** .5) # Assemble dictionary of calculation results ret_calc",
"number of months to a text description of years and months. Param: mon_len",
"printing and display purposes. Param: dec (int or float) like 4000.444444 Example: two_dec(4000.444444)",
"yr_str = '' elif full_years == 1: yr_str = f'{full_years} Year' else: yr_str",
"f'{dec:.2%}' def two_dec(dec): ''' Converts a numeric value to formatted string for printing",
"maturity treasury data from other_data_pull module port_ret = port_ret.join(fred_join) # Calculate S&P 500",
"'mon ret'] = port_ret.loc[pd_start + 1, 'cum ret'] - 1 # Merge in",
"__file__)), '..', 'data', \"working_spy.csv\"), parse_dates=['month']) spy_join['month'] = spy_join['month'].dt.to_period('M') spy_join=spy_join.set_index('month') fred_join = pd.read_csv(os.path.join(os.path.dirname(os.path.abspath( __file__)),",
"val') # Caclulate cumulative returns and corresponding monthly values of individual # portfolio",
"and display purposes. Param: dec (int or float) like 0.403321 Example: to_pct(0.403321) Returns:",
"for a period of 2 years and 7 months, and the loop #",
"beta, 'sharpe_port': sharpe_port, 'sharpe_sp': sharpe_sp} # Create total (cumulative) returns dataset for data",
"Example: mon_len(17) Returns: 1 Year and 5 Months ''' full_years = int(mon_len /",
"= '' elif resid_months == 1: mon_str = f'{resid_months} Month' else: mon_str=f'{resid_months} Months'",
"pd_end.strftime('%Y-%m'), 'ann_ret': avg_ann_ret, 'mon_ret': avg_mon_ret, 'ann_sdev': ann_sdev, 'mon_sdev': mon_sdev, 'ann_spret': avg_ann_spret, 'mon_spret': avg_mon_spret,",
"ap_api_key = os.environ.get('ALPHAVANTAGE_API_KEY') fred_api_key = os.environ.get('FRED_API_KEY') portfolio = portfolio_import(port_file_name) if APP_ENV == 'development':",
"/ port_ret['exret'].std()) * (12 ** .5) sharpe_sp = (port_ret['exspret'].mean() / port_ret['exspret'].std()) * (12",
"pd_start_val['sh val'].rename('start val') # Caclulate cumulative returns and corresponding monthly values of individual",
"figs = [] for i in [1,2,3,5]: if x==0: temp_returns, temp_tot, temp_review =",
"= (port_ret.loc[pd_end, 'cum spret'])**(1 / years) - 1 avg_mon_spret = (port_ret.loc[pd_end, 'cum spret'])**(1",
"returns(sub, i, maxomin, minomax) results.append(temp_returns) tot_ret.append(temp_tot) keep.append(i) figs.append({'port line': go.Scatter(x=temp_tot['month'], y=temp_tot['cum ret'], name='Portfolio",
"- 1 # Merge in S&P 500 data from other_data_pull module port_ret =",
"temp_returns['years_tgt'] != temp_returns['years_act']: x = 1 # MAKE CHARTS/TABLES! axis_font = dict(size=16, family='Times",
"(port_ret.loc[pd_end, 'cum spret'])**(1 / months) - 1 #Calculate return standard deviations mon_sdev =",
"and ' else: join_str = '' if full_years == 0: yr_str = ''",
"import os import dotenv from dotenv import load_dotenv import datetime import plotly import",
"# Requires that each of other_data_pull and port_data_pull modules be # run separately/individually",
"cumulative return over analysis period port_ret['spretp1'] = port_ret['spret'] + 1 port_ret['cum spret'] =",
"sharpe ratios sharpe_port = (port_ret['exret'].mean() / port_ret['exret'].std()) * (12 ** .5) sharpe_sp =",
"and display purposes. Param: dec (int or float) like 4000.444444 Example: two_dec(4000.444444) Returns:",
"Alpha Vantage and FRED (Federal Reserve Economic Data) APIs spy_join = spy_pull(ap_api_key) fred_join",
"mon_len % 12 if (full_years > 0 and resid_months > 0): join_str =",
"ret', 'cum spret']] - 1 app_df = pd.DataFrame([[tot_ret_data.index.min() - 1, 0, 0]], columns=['month',",
"data for data visualization. ''' # Calculate percent returns of individual portfolio positions",
"analysis periods # (but only if sufficient data exists for all portfolio positions).",
"and cumulative return over analysis period port_ret['spretp1'] = port_ret['spret'] + 1 port_ret['cum spret']",
"For now, analysis period start date is # based on the data availability",
"returns of individual portfolio positions working_data = dataset working_data['mret'] = working_data.groupby('ticker')['adj close'].pct_change() working_data['mretp1']",
"sharpe_port, 'sharpe_sp': sharpe_sp} # Create total (cumulative) returns dataset for data visualization tot_ret_data",
"the data availability of the individual positions. The most recent # first monthly",
"width=4)), 'sp line': go.Scatter(x=temp_tot['month'], y=temp_tot['cum spret'], name='S&P 500 Cumulative Return', line=dict(color='royalblue', width=4))}) if",
"other_data_pull module port_ret = port_ret.join(spy_join) # Merge in 1Y constant maturity treasury data",
"two_dec(dec): ''' Converts a numeric value to formatted string for printing and display",
"Param: mon_len (int) like 17 Example: mon_len(17) Returns: 1 Year and 5 Months",
"if x==0: temp_returns, temp_tot, temp_review = returns(sub, i, maxomin, minomax) results.append(temp_returns) tot_ret.append(temp_tot) keep.append(i)",
"to_pct(0.403321) Returns: 40.33% ''' return f'{dec:.2%}' def two_dec(dec): ''' Converts a numeric value",
"Months ''' full_years = int(mon_len / 12) resid_months = mon_len % 12 if",
"val', 'mon val']].sum() port_ret['cum ret'] = port_ret['mon val'] / port_ret['start val'] port_ret['mon ret']",
"= cum_ret_set.set_index('ticker') cum_ret_set['cumret'] = cum_ret_set.groupby('ticker')['mretp1'].cumprod() cum_ret_set = cum_ret_set.join(pd_start_val, on='ticker') cum_ret_set['mon val'] = cum_ret_set['start",
"= port_ret['spret'] - port_ret['rate'] # Calculate average annual and monthly returns months =",
"ret'] = port_ret['mon val'] / port_ret['start val'] port_ret['mon ret'] = port_ret['mon val'].pct_change() #",
"f'{full_years} Year' else: yr_str = f'{full_years} Years' if resid_months == 0: mon_str =",
"fig.add_trace(figs[i]['sp line'], row=2, col=1,) pd_months = results[i]['months_act'] fig.update_layout(title=dict(text=f'Portfolio Performance Report: Monthly Returns over",
"time (used to pull analysis period starting portfolio values) working_data['sh val'] = working_data['qty']",
"temp_returns, temp_tot, temp_review = returns(sub, i, maxomin, minomax) results.append(temp_returns) tot_ret.append(temp_tot) keep.append(i) figs.append({'port line':",
"+ 1 port_ret['cum spret'] = port_ret['spretp1'].cumprod() port_ret = port_ret.drop(columns=['spretp1']) # Calculate portfolio and",
"font=axis_font)) col1 = ['Avg. Annual Return', 'Std. Dev. (Ann.)', 'Sharpe Ratio', 'Beta'] col2",
"# Calculate sharpe ratios sharpe_port = (port_ret['exret'].mean() / port_ret['exret'].std()) * (12 ** .5)",
"= returns(sub, i, maxomin, minomax) results.append(temp_returns) tot_ret.append(temp_tot) keep.append(i) figs.append({'port line': go.Scatter(x=temp_tot['month'], y=temp_tot['cum ret'],",
"risk free rate port_ret['exret'] = port_ret['mon ret'] - port_ret['rate'] port_ret['exspret'] = port_ret['spret'] -",
"of portfolio and S&P 500 divided by # volatility of S&P 500) beta",
"portfolio beta (covariance of portfolio and S&P 500 divided by # volatility of",
"annual and monthly returns months = len(port_ret) years = months / 12 avg_ann_ret",
"module port_ret = port_ret.join(fred_join) # Calculate S&P 500 returns and cumulative return over",
"Calculate portfolio and S&P 500 excess returns over risk free rate port_ret['exret'] =",
"''' Converts a numeric value to formatted string for printing and display purposes.",
"individual positions. The most recent # first monthly data point for a given",
"min_start) # Create dataset of asset values by position at the analysis start",
"availability of the individual positions. The most recent # first monthly data point",
"start date is # based on the data availability of the individual positions.",
"/ port_ret['start val'] port_ret['mon ret'] = port_ret['mon val'].pct_change() # Replace analysis period start",
"month portfolio return (was na due to # pct_change() function) port_ret.loc[pd_start + 1,",
"# Merge in 1Y constant maturity treasury data from other_data_pull module port_ret =",
"data # sampling period for one stock in the portfolio is 2 years",
"= port_ret.join(fred_join) # Calculate S&P 500 returns and cumulative return over analysis period",
"average annual and monthly returns months = len(port_ret) years = months / 12",
"results ret_calc = {'years_tgt': pd_len, 'years_act': years, 'months_act': months, 'st_date': pd_start.strftime('%Y-%m'), 'end_date': pd_end.strftime('%Y-%m'),",
"'st_date': pd_start.strftime('%Y-%m'), 'end_date': pd_end.strftime('%Y-%m'), 'ann_ret': avg_ann_ret, 'mon_ret': avg_mon_ret, 'ann_sdev': ann_sdev, 'mon_sdev': mon_sdev, 'ann_spret':",
"ret'])**(1 / months) - 1 avg_ann_spret = (port_ret.loc[pd_end, 'cum spret'])**(1 / years) -",
"= tot_ret_data.index.to_series().astype(str) tot_ret_dict = tot_ret_data.reset_index().to_dict(orient='list') return ret_calc, tot_ret_dict, port_ret # ------------------------------------------------------------------------------------- # CODE",
"/ years) - 1 avg_mon_ret = (port_ret.loc[pd_end, 'cum ret'])**(1 / months) - 1",
"return f'{dec:.2%}' def two_dec(dec): ''' Converts a numeric value to formatted string for",
"port_ret['exspret'].std()) * (12 ** .5) # Assemble dictionary of calculation results ret_calc =",
"line'], row=2, col=1,) pd_months = results[i]['months_act'] fig.update_layout(title=dict(text=f'Portfolio Performance Report: Monthly Returns over Last",
"'sp line': go.Scatter(x=temp_tot['month'], y=temp_tot['cum spret'], name='S&P 500 Cumulative Return', line=dict(color='royalblue', width=4))}) if temp_returns['years_tgt']",
"'month']) sub['month']=sub['month'].dt.to_period('M') spy_join = pd.read_csv(os.path.join(os.path.dirname(os.path.abspath( __file__)), '..', 'data', \"working_spy.csv\"), parse_dates=['month']) spy_join['month'] = spy_join['month'].dt.to_period('M')",
"Year' else: yr_str = f'{full_years} Years' if resid_months == 0: mon_str = ''",
"= int(mon_len / 12) resid_months = mon_len % 12 if (full_years > 0",
"0: yr_str = '' elif full_years == 1: yr_str = f'{full_years} Year' else:",
"a numeric value to formatted string for printing and display purposes. Param: dec",
"port_ret['start val'] port_ret['mon ret'] = port_ret['mon val'].pct_change() # Replace analysis period start month",
"- 1 #Calculate return standard deviations mon_sdev = port_ret['mon ret'].std() ann_sdev = mon_sdev",
"portfolio stocks # from Alpha Vantage API sub, minomax, maxomin=port_data_pull(portfolio,ap_api_key) # Collect and",
"to_pct(dec): ''' Converts a numeric value to formatted string for printing and display",
"working_data['mretp1'] = working_data['mret'] + 1 # Calculate share values over time (used to",
"avg_ann_spret, 'mon_spret': avg_mon_spret, 'ann_sp_sdev': ann_sp_sdev, 'mon_sp_sdev': mon_sp_sdev, 'beta': beta, 'sharpe_port': sharpe_port, 'sharpe_sp': sharpe_sp}",
"returns over risk free rate port_ret['exret'] = port_ret['mon ret'] - port_ret['rate'] port_ret['exspret'] =",
"tot_ret_dict = tot_ret_data.reset_index().to_dict(orient='list') return ret_calc, tot_ret_dict, port_ret # ------------------------------------------------------------------------------------- # CODE -------------------------------------------------------------------------------- #",
"year analysis periods # (but only if sufficient data exists for all portfolio",
"Calculate average annual and monthly returns months = len(port_ret) years = months /",
"cum_ret_set['start val'] * cum_ret_set['cumret'] # Calculate monthly returns on the total portfolio over",
"- port_ret['rate'] port_ret['exspret'] = port_ret['spret'] - port_ret['rate'] # Calculate average annual and monthly",
"5 year analysis periods # (but only if sufficient data exists for all",
"pd.read_csv(os.path.join(os.path.dirname(os.path.abspath( __file__)), '..', 'data', \"working_fred.csv\"), parse_dates=['month']) fred_join['month'] = fred_join['month'].dt.to_period('M') fred_join=fred_join.set_index('month') maxomin = sub['month'].min()",
"= os.environ.get('FRED_API_KEY') portfolio = portfolio_import(port_file_name) if APP_ENV == 'development': # Requires that each",
"\"working_fred.csv\"), parse_dates=['month']) fred_join['month'] = fred_join['month'].dt.to_period('M') fred_join=fred_join.set_index('month') maxomin = sub['month'].min() minomax = sub['month'].max() else:",
"Last {pd_describe(pd_months)}', font=dict(family='Times New Roman', size=20))) fig.update_layout(xaxis=dict(title=dict(text='Month', font=axis_font), ticks='outside', tickfont=tick_font)) fig.update_layout(yaxis=dict(title=dict(text='Cumulative Monthly Returns",
"'Sharpe Ratio', 'Beta'] col2 = [to_pct(results[i]['ann_ret']), to_pct(results[i]['ann_sdev']), two_dec(results[i]['sharpe_port']), two_dec(results[i]['beta'])] col3 = [to_pct(results[i]['ann_spret']), to_pct(results[i]['ann_sp_sdev']),",
"values by position at the analysis start date pd_start_val = working_data.loc[working_data['month'] == pd_start]",
"based on the data availability of the individual positions. The most recent #",
"mon_sp_sdev = port_ret['spret'].std() ann_sp_sdev = mon_sp_sdev * (12 ** .5) # Calculate portfolio",
"from # Alpha Vantage and FRED (Federal Reserve Economic Data) APIs spy_join =",
"Returns (%)', font=axis_font), ticks='outside', tickfont=tick_font, tickformat='.1%')) fig.update_layout(legend=dict(orientation='h', font=axis_font)) col1 = ['Avg. Annual Return',",
"row_width=[0.75,0.25], specs=[[{'type':'table'}], [{'type':'scatter'}]]) fig.add_trace(figs[i]['port line'], row=2, col=1) fig.add_trace(figs[i]['sp line'], row=2, col=1,) pd_months =",
"tot_ret_data.index = tot_ret_data.index.to_series().astype(str) tot_ret_dict = tot_ret_data.reset_index().to_dict(orient='list') return ret_calc, tot_ret_dict, port_ret # ------------------------------------------------------------------------------------- #",
"period will record results for a period of 2 years and 7 months,",
"# Calculate average annual and monthly returns months = len(port_ret) years = months",
"as go from plotly.subplots import make_subplots from app.other_data_pull import spy_pull, fred_pull from app.port_data_pull",
"deviations mon_sdev = port_ret['mon ret'].std() ann_sdev = mon_sdev * (12 ** .5) mon_sp_sdev",
"= mon_sp_sdev * (12 ** .5) # Calculate portfolio beta (covariance of portfolio",
"* (12 ** .5) # Calculate portfolio beta (covariance of portfolio and S&P",
"Reserve Economic Data) APIs spy_join = spy_pull(ap_api_key) fred_join = fred_pull(fred_api_key) # Call on",
"1 port_ret['cum spret'] = port_ret['spretp1'].cumprod() port_ret = port_ret.drop(columns=['spretp1']) # Calculate portfolio and S&P",
"individual # portfolio positions over time cum_ret_set = working_data.loc[(working_data['month'] > pd_start) & (working_data['month']",
"1 Year and 5 Months ''' full_years = int(mon_len / 12) resid_months =",
"resid_months = mon_len % 12 if (full_years > 0 and resid_months > 0):",
"portfolio and S&P 500 excess returns over risk free rate port_ret['exret'] = port_ret['mon",
"pd import os import dotenv from dotenv import load_dotenv import datetime import plotly",
"with the 5-year calculations. results = [] tot_ret=[] x = 0 keep =",
"data visualization. ''' # Calculate percent returns of individual portfolio positions working_data =",
"temp_tot, temp_review = returns(sub, i, maxomin, minomax) results.append(temp_returns) tot_ret.append(temp_tot) keep.append(i) figs.append({'port line': go.Scatter(x=temp_tot['month'],",
"columns=['month', 'cum ret', 'cum spret']).set_index('month') tot_ret_data=tot_ret_data.append(app_df).sort_index() tot_ret_data.index = tot_ret_data.index.to_series().astype(str) tot_ret_dict = tot_ret_data.reset_index().to_dict(orient='list') return",
"1 avg_mon_ret = (port_ret.loc[pd_end, 'cum ret'])**(1 / months) - 1 avg_ann_spret = (port_ret.loc[pd_end,",
"Calculate sharpe ratios sharpe_port = (port_ret['exret'].mean() / port_ret['exret'].std()) * (12 ** .5) sharpe_sp",
"= dict(size=12, family='Times New Roman') for i in range(len(figs)): fig = make_subplots(rows=2, cols=1,",
"complete or near complete periods. For example, if the longest data # sampling",
"the individual positions. The most recent # first monthly data point for a",
"mon_sp_sdev, 'beta': beta, 'sharpe_port': sharpe_port, 'sharpe_sp': sharpe_sp} # Create total (cumulative) returns dataset",
"= months / 12 avg_ann_ret = (port_ret.loc[pd_end, 'cum ret'])**(1 / years) - 1",
"from app.other_data_pull import spy_pull, fred_pull from app.port_data_pull import port_data_pull from app.portfolio_import import portfolio_import",
"if sufficient data exists for all portfolio positions). If data are insufficient, #",
"example, if the longest data # sampling period for one stock in the",
"then the 3-year # analysis period will record results for a period of",
"[to_pct(results[i]['ann_ret']), to_pct(results[i]['ann_sdev']), two_dec(results[i]['sharpe_port']), two_dec(results[i]['beta'])] col3 = [to_pct(results[i]['ann_spret']), to_pct(results[i]['ann_sp_sdev']), two_dec(results[i]['sharpe_sp']), two_dec(1.00)] fig.add_trace(go.Table(header=dict(values=['Statistic', 'Portfolio', 'S&P",
"from dotenv import load_dotenv import datetime import plotly import plotly.graph_objects as go from",
"pd_describe(mon_len): ''' Converts a specified number of months to a text description of",
"of S&P 500) beta = port_ret.cov().loc['mon ret', 'spret'] / port_ret.cov().loc['spret', 'spret'] # Calculate",
"= port_ret['spret'].std() ann_sp_sdev = mon_sp_sdev * (12 ** .5) # Calculate portfolio beta",
"data visualization tot_ret_data = port_ret[['cum ret', 'cum spret']] - 1 app_df = pd.DataFrame([[tot_ret_data.index.min()",
"# Collect and store results, datasets, and chart elements for 1, 2, 3,",
"periods. For example, if the longest data # sampling period for one stock",
"plotly import plotly.graph_objects as go from plotly.subplots import make_subplots from app.other_data_pull import spy_pull,",
"== 1: mon_str = f'{resid_months} Month' else: mon_str=f'{resid_months} Months' pd_detail=f'{yr_str}{join_str}{mon_str}' return pd_detail def",
"* working_data['close'] # Define analysis period length. For now, analysis period start date",
"mon_sdev = port_ret['mon ret'].std() ann_sdev = mon_sdev * (12 ** .5) mon_sp_sdev =",
"of calculation results ret_calc = {'years_tgt': pd_len, 'years_act': years, 'months_act': months, 'st_date': pd_start.strftime('%Y-%m'),",
"text description of years and months. Param: mon_len (int) like 17 Example: mon_len(17)",
"data availability of the individual positions. The most recent # first monthly data",
"tot_ret=[] x = 0 keep = [] figs = [] for i in",
"Example: to_pct(0.403321) Returns: 40.33% ''' return f'{dec:.2%}' def two_dec(dec): ''' Converts a numeric",
"val']].sum() port_ret['cum ret'] = port_ret['mon val'] / port_ret['start val'] port_ret['mon ret'] = port_ret['mon",
"months = len(port_ret) years = months / 12 avg_ann_ret = (port_ret.loc[pd_end, 'cum ret'])**(1",
"'mon_sdev': mon_sdev, 'ann_spret': avg_ann_spret, 'mon_spret': avg_mon_spret, 'ann_sp_sdev': ann_sp_sdev, 'mon_sp_sdev': mon_sp_sdev, 'beta': beta, 'sharpe_port':",
"= port_ret.cov().loc['mon ret', 'spret'] / port_ret.cov().loc['spret', 'spret'] # Calculate sharpe ratios sharpe_port =",
"visualization tot_ret_data = port_ret[['cum ret', 'cum spret']] - 1 app_df = pd.DataFrame([[tot_ret_data.index.min() -",
"3-year # analysis period will record results for a period of 2 years",
"pd_start_val = pd_start_val['sh val'].rename('start val') # Caclulate cumulative returns and corresponding monthly values",
"limitation of the data/API. pd_len = period_length pd_end = max_end pd_start = max(max_end",
"fig.update_layout(title=dict(text=f'Portfolio Performance Report: Monthly Returns over Last {pd_describe(pd_months)}', font=dict(family='Times New Roman', size=20))) fig.update_layout(xaxis=dict(title=dict(text='Month',",
"two_dec(4000.444444) Returns: 4,000.44 ''' return f'{dec:,.2f}' def pd_describe(mon_len): ''' Converts a specified number",
"avg_mon_ret = (port_ret.loc[pd_end, 'cum ret'])**(1 / months) - 1 avg_ann_spret = (port_ret.loc[pd_end, 'cum",
"0): join_str = ' and ' else: join_str = '' if full_years ==",
"the data/API. pd_len = period_length pd_end = max_end pd_start = max(max_end - (pd_len",
"mon_str = f'{resid_months} Month' else: mon_str=f'{resid_months} Months' pd_detail=f'{yr_str}{join_str}{mon_str}' return pd_detail def returns(dataset, period_length,",
"of asset values by position at the analysis start date pd_start_val = working_data.loc[working_data['month']",
"or float) like 4000.444444 Example: two_dec(4000.444444) Returns: 4,000.44 ''' return f'{dec:,.2f}' def pd_describe(mon_len):",
"and chart elements for 1, 2, 3, and 5 year analysis periods #",
"# Calculate monthly returns on the total portfolio over time port_ret = cum_ret_set.groupby('month')[['start",
"given stock in the portfolio becomes the analysis # start date. This is",
"1 #Calculate return standard deviations mon_sdev = port_ret['mon ret'].std() ann_sdev = mon_sdev *",
"i in range(len(figs)): fig = make_subplots(rows=2, cols=1, vertical_spacing=0.03, row_width=[0.75,0.25], specs=[[{'type':'table'}], [{'type':'scatter'}]]) fig.add_trace(figs[i]['port line'],",
"row=2, col=1,) pd_months = results[i]['months_act'] fig.update_layout(title=dict(text=f'Portfolio Performance Report: Monthly Returns over Last {pd_describe(pd_months)}',",
"= f'{full_years} Years' if resid_months == 0: mon_str = '' elif resid_months ==",
"spy_pull(ap_api_key) fred_join = fred_pull(fred_api_key) # Call on port_data_pull module for monthly data on",
"months, 'st_date': pd_start.strftime('%Y-%m'), 'end_date': pd_end.strftime('%Y-%m'), 'ann_ret': avg_ann_ret, 'mon_ret': avg_mon_ret, 'ann_sdev': ann_sdev, 'mon_sdev': mon_sdev,",
"purposes. Param: dec (int or float) like 4000.444444 Example: two_dec(4000.444444) Returns: 4,000.44 '''",
"bother with the 5-year calculations. results = [] tot_ret=[] x = 0 keep",
"= working_data.loc[working_data['month'] == pd_start] pd_start_val = pd_start_val.set_index('ticker') pd_start_val = pd_start_val['sh val'].rename('start val') #",
"row=2, col=1) fig.add_trace(figs[i]['sp line'], row=2, col=1,) pd_months = results[i]['months_act'] fig.update_layout(title=dict(text=f'Portfolio Performance Report: Monthly",
"{pd_describe(pd_months)}', font=dict(family='Times New Roman', size=20))) fig.update_layout(xaxis=dict(title=dict(text='Month', font=axis_font), ticks='outside', tickfont=tick_font)) fig.update_layout(yaxis=dict(title=dict(text='Cumulative Monthly Returns (%)',",
"tot_ret_dict, port_ret # ------------------------------------------------------------------------------------- # CODE -------------------------------------------------------------------------------- # ------------------------------------------------------------------------------------- if __name__=='__main__': # Loan",
"yr_str = f'{full_years} Year' else: yr_str = f'{full_years} Years' if resid_months == 0:",
"period start month portfolio return (was na due to # pct_change() function) port_ret.loc[pd_start",
"['Avg. Annual Return', 'Std. Dev. (Ann.)', 'Sharpe Ratio', 'Beta'] col2 = [to_pct(results[i]['ann_ret']), to_pct(results[i]['ann_sdev']),",
"os.environ.get('FRED_API_KEY') portfolio = portfolio_import(port_file_name) if APP_ENV == 'development': # Requires that each of",
"results for a period of 2 years and 7 months, and the loop",
"4000.444444 Example: two_dec(4000.444444) Returns: 4,000.44 ''' return f'{dec:,.2f}' def pd_describe(mon_len): ''' Converts a",
"'' elif resid_months == 1: mon_str = f'{resid_months} Month' else: mon_str=f'{resid_months} Months' pd_detail=f'{yr_str}{join_str}{mon_str}'",
"port_ret.cov().loc['mon ret', 'spret'] / port_ret.cov().loc['spret', 'spret'] # Calculate sharpe ratios sharpe_port = (port_ret['exret'].mean()",
"sampling period for one stock in the portfolio is 2 years and 7",
"fig.update_layout(legend=dict(orientation='h', font=axis_font)) col1 = ['Avg. Annual Return', 'Std. Dev. (Ann.)', 'Sharpe Ratio', 'Beta']",
"portfolio_import from app import APP_ENV # ------------------------------------------------------------------------------------- # FUNCTIONS --------------------------------------------------------------------------- # ------------------------------------------------------------------------------------- def",
"2 years and 7 months, then the 3-year # analysis period will record",
"data exists for all portfolio positions). If data are insufficient, # only store",
"yr_str = f'{full_years} Years' if resid_months == 0: mon_str = '' elif resid_months",
"family='Times New Roman') tick_font = dict(size=12, family='Times New Roman') for i in range(len(figs)):",
"in range(len(figs)): fig = make_subplots(rows=2, cols=1, vertical_spacing=0.03, row_width=[0.75,0.25], specs=[[{'type':'table'}], [{'type':'scatter'}]]) fig.add_trace(figs[i]['port line'], row=2,",
"** .5) sharpe_sp = (port_ret['exspret'].mean() / port_ret['exspret'].std()) * (12 ** .5) # Assemble",
"/ 12 avg_ann_ret = (port_ret.loc[pd_end, 'cum ret'])**(1 / years) - 1 avg_mon_ret =",
"mon_str=f'{resid_months} Months' pd_detail=f'{yr_str}{join_str}{mon_str}' return pd_detail def returns(dataset, period_length, min_start, max_end): ''' Calculates various",
"of the individual positions. The most recent # first monthly data point for",
"portfolio positions over time cum_ret_set = working_data.loc[(working_data['month'] > pd_start) & (working_data['month'] <= pd_end)]",
"first monthly data point for a given stock in the portfolio becomes the",
"and 5 Months ''' full_years = int(mon_len / 12) resid_months = mon_len %",
"port_ret.loc[pd_start + 1, 'mon ret'] = port_ret.loc[pd_start + 1, 'cum ret'] - 1",
"= ['Avg. Annual Return', 'Std. Dev. (Ann.)', 'Sharpe Ratio', 'Beta'] col2 = [to_pct(results[i]['ann_ret']),",
"12 if (full_years > 0 and resid_months > 0): join_str = ' and",
"two_dec(results[i]['sharpe_port']), two_dec(results[i]['beta'])] col3 = [to_pct(results[i]['ann_spret']), to_pct(results[i]['ann_sp_sdev']), two_dec(results[i]['sharpe_sp']), two_dec(1.00)] fig.add_trace(go.Table(header=dict(values=['Statistic', 'Portfolio', 'S&P 500']), cells=dict(values=[col1,",
"variables load_dotenv() port_file_name = os.environ.get('PORTFOLIO_FILE_NAME') ap_api_key = os.environ.get('ALPHAVANTAGE_API_KEY') fred_api_key = os.environ.get('FRED_API_KEY') portfolio =",
"Loan environment variables load_dotenv() port_file_name = os.environ.get('PORTFOLIO_FILE_NAME') ap_api_key = os.environ.get('ALPHAVANTAGE_API_KEY') fred_api_key = os.environ.get('FRED_API_KEY')",
"= mon_len % 12 if (full_years > 0 and resid_months > 0): join_str",
"data on individual portfolio stocks # from Alpha Vantage API sub, minomax, maxomin=port_data_pull(portfolio,ap_api_key)",
"module for monthly data on individual portfolio stocks # from Alpha Vantage API",
"fred_join['month'].dt.to_period('M') fred_join=fred_join.set_index('month') maxomin = sub['month'].min() minomax = sub['month'].max() else: # Call on other_data_pull",
"font=dict(family='Times New Roman', size=20))) fig.update_layout(xaxis=dict(title=dict(text='Month', font=axis_font), ticks='outside', tickfont=tick_font)) fig.update_layout(yaxis=dict(title=dict(text='Cumulative Monthly Returns (%)', font=axis_font),",
"pd_start_val.set_index('ticker') pd_start_val = pd_start_val['sh val'].rename('start val') # Caclulate cumulative returns and corresponding monthly",
"= cum_ret_set.join(pd_start_val, on='ticker') cum_ret_set['mon val'] = cum_ret_set['start val'] * cum_ret_set['cumret'] # Calculate monthly",
"from within this program) sub = pd.read_csv(os.path.join(os.path.dirname(os.path.abspath( __file__)), '..', 'data', \"working_port.csv\"), parse_dates=['timestamp', 'month'])",
"ret'] - port_ret['rate'] port_ret['exspret'] = port_ret['spret'] - port_ret['rate'] # Calculate average annual and",
"port_ret['spret'] + 1 port_ret['cum spret'] = port_ret['spretp1'].cumprod() port_ret = port_ret.drop(columns=['spretp1']) # Calculate portfolio",
"spret'] = port_ret['spretp1'].cumprod() port_ret = port_ret.drop(columns=['spretp1']) # Calculate portfolio and S&P 500 excess",
"only store results for complete or near complete periods. For example, if the",
"else: yr_str = f'{full_years} Years' if resid_months == 0: mon_str = '' elif",
"x==0: temp_returns, temp_tot, temp_review = returns(sub, i, maxomin, minomax) results.append(temp_returns) tot_ret.append(temp_tot) keep.append(i) figs.append({'port",
"API sub, minomax, maxomin=port_data_pull(portfolio,ap_api_key) # Collect and store results, datasets, and chart elements",
"spret']] - 1 app_df = pd.DataFrame([[tot_ret_data.index.min() - 1, 0, 0]], columns=['month', 'cum ret',",
"other_data_pull and port_data_pull modules be # run separately/individually (i.e., not called from within",
"a period of 2 years and 7 months, and the loop # will",
"Alpha Vantage API sub, minomax, maxomin=port_data_pull(portfolio,ap_api_key) # Collect and store results, datasets, and",
"years and 7 months, then the 3-year # analysis period will record results",
"years) - 1 avg_mon_ret = (port_ret.loc[pd_end, 'cum ret'])**(1 / months) - 1 avg_ann_spret",
"fig = make_subplots(rows=2, cols=1, vertical_spacing=0.03, row_width=[0.75,0.25], specs=[[{'type':'table'}], [{'type':'scatter'}]]) fig.add_trace(figs[i]['port line'], row=2, col=1) fig.add_trace(figs[i]['sp",
"* (12 ** .5) # Assemble dictionary of calculation results ret_calc = {'years_tgt':",
"val'].pct_change() # Replace analysis period start month portfolio return (was na due to",
"> pd_start) & (working_data['month'] <= pd_end)] cum_ret_set = cum_ret_set.set_index('ticker') cum_ret_set['cumret'] = cum_ret_set.groupby('ticker')['mretp1'].cumprod() cum_ret_set",
"# ------------------------------------------------------------------------------------- def to_pct(dec): ''' Converts a numeric value to formatted string for",
"= f'{resid_months} Month' else: mon_str=f'{resid_months} Months' pd_detail=f'{yr_str}{join_str}{mon_str}' return pd_detail def returns(dataset, period_length, min_start,",
"'years_act': years, 'months_act': months, 'st_date': pd_start.strftime('%Y-%m'), 'end_date': pd_end.strftime('%Y-%m'), 'ann_ret': avg_ann_ret, 'mon_ret': avg_mon_ret, 'ann_sdev':",
"- 1 app_df = pd.DataFrame([[tot_ret_data.index.min() - 1, 0, 0]], columns=['month', 'cum ret', 'cum",
"0 keep = [] figs = [] for i in [1,2,3,5]: if x==0:",
"pd_start] pd_start_val = pd_start_val.set_index('ticker') pd_start_val = pd_start_val['sh val'].rename('start val') # Caclulate cumulative returns",
"# ------------------------------------------------------------------------------------- # CODE -------------------------------------------------------------------------------- # ------------------------------------------------------------------------------------- if __name__=='__main__': # Loan environment variables",
"tot_ret_data.index.to_series().astype(str) tot_ret_dict = tot_ret_data.reset_index().to_dict(orient='list') return ret_calc, tot_ret_dict, port_ret # ------------------------------------------------------------------------------------- # CODE --------------------------------------------------------------------------------",
"store results for complete or near complete periods. For example, if the longest",
"> 0 and resid_months > 0): join_str = ' and ' else: join_str",
"'..', 'data', \"working_port.csv\"), parse_dates=['timestamp', 'month']) sub['month']=sub['month'].dt.to_period('M') spy_join = pd.read_csv(os.path.join(os.path.dirname(os.path.abspath( __file__)), '..', 'data', \"working_spy.csv\"),",
"fred_pull from app.port_data_pull import port_data_pull from app.portfolio_import import portfolio_import from app import APP_ENV",
"Return', line=dict(color='royalblue', width=4))}) if temp_returns['years_tgt'] != temp_returns['years_act']: x = 1 # MAKE CHARTS/TABLES!",
"os.environ.get('ALPHAVANTAGE_API_KEY') fred_api_key = os.environ.get('FRED_API_KEY') portfolio = portfolio_import(port_file_name) if APP_ENV == 'development': # Requires",
"pd_detail def returns(dataset, period_length, min_start, max_end): ''' Calculates various portfolio performance measures and",
"1: yr_str = f'{full_years} Year' else: yr_str = f'{full_years} Years' if resid_months ==",
"mon_sdev, 'ann_spret': avg_ann_spret, 'mon_spret': avg_mon_spret, 'ann_sp_sdev': ann_sp_sdev, 'mon_sp_sdev': mon_sp_sdev, 'beta': beta, 'sharpe_port': sharpe_port,",
"------------------------------------------------------------------------------------- if __name__=='__main__': # Loan environment variables load_dotenv() port_file_name = os.environ.get('PORTFOLIO_FILE_NAME') ap_api_key =",
"= port_ret['spretp1'].cumprod() port_ret = port_ret.drop(columns=['spretp1']) # Calculate portfolio and S&P 500 excess returns",
"(i.e., not called from within this program) sub = pd.read_csv(os.path.join(os.path.dirname(os.path.abspath( __file__)), '..', 'data',",
"500 divided by # volatility of S&P 500) beta = port_ret.cov().loc['mon ret', 'spret']",
"''' Calculates various portfolio performance measures and prepares data for data visualization. '''",
"values over time (used to pull analysis period starting portfolio values) working_data['sh val']",
".5) mon_sp_sdev = port_ret['spret'].std() ann_sp_sdev = mon_sp_sdev * (12 ** .5) # Calculate",
"join_str = '' if full_years == 0: yr_str = '' elif full_years ==",
"= max(max_end - (pd_len * 12), min_start) # Create dataset of asset values",
"'ann_ret': avg_ann_ret, 'mon_ret': avg_mon_ret, 'ann_sdev': ann_sdev, 'mon_sdev': mon_sdev, 'ann_spret': avg_ann_spret, 'mon_spret': avg_mon_spret, 'ann_sp_sdev':",
"program) sub = pd.read_csv(os.path.join(os.path.dirname(os.path.abspath( __file__)), '..', 'data', \"working_port.csv\"), parse_dates=['timestamp', 'month']) sub['month']=sub['month'].dt.to_period('M') spy_join =",
"over time cum_ret_set = working_data.loc[(working_data['month'] > pd_start) & (working_data['month'] <= pd_end)] cum_ret_set =",
"spy_join=spy_join.set_index('month') fred_join = pd.read_csv(os.path.join(os.path.dirname(os.path.abspath( __file__)), '..', 'data', \"working_fred.csv\"), parse_dates=['month']) fred_join['month'] = fred_join['month'].dt.to_period('M') fred_join=fred_join.set_index('month')",
"stock in the portfolio becomes the analysis # start date. This is a",
"over time (used to pull analysis period starting portfolio values) working_data['sh val'] =",
"data from # Alpha Vantage and FRED (Federal Reserve Economic Data) APIs spy_join",
"# Call on port_data_pull module for monthly data on individual portfolio stocks #",
"dict(size=12, family='Times New Roman') for i in range(len(figs)): fig = make_subplots(rows=2, cols=1, vertical_spacing=0.03,",
"float) like 0.403321 Example: to_pct(0.403321) Returns: 40.33% ''' return f'{dec:.2%}' def two_dec(dec): '''",
"tot_ret_data = port_ret[['cum ret', 'cum spret']] - 1 app_df = pd.DataFrame([[tot_ret_data.index.min() - 1,",
"vertical_spacing=0.03, row_width=[0.75,0.25], specs=[[{'type':'table'}], [{'type':'scatter'}]]) fig.add_trace(figs[i]['port line'], row=2, col=1) fig.add_trace(figs[i]['sp line'], row=2, col=1,) pd_months",
"point for a given stock in the portfolio becomes the analysis # start",
"# based on the data availability of the individual positions. The most recent",
"cum_ret_set.groupby('ticker')['mretp1'].cumprod() cum_ret_set = cum_ret_set.join(pd_start_val, on='ticker') cum_ret_set['mon val'] = cum_ret_set['start val'] * cum_ret_set['cumret'] #",
"minomax) results.append(temp_returns) tot_ret.append(temp_tot) keep.append(i) figs.append({'port line': go.Scatter(x=temp_tot['month'], y=temp_tot['cum ret'], name='Portfolio Cumulative Return', line=dict(color='firebrick',",
"Roman') for i in range(len(figs)): fig = make_subplots(rows=2, cols=1, vertical_spacing=0.03, row_width=[0.75,0.25], specs=[[{'type':'table'}], [{'type':'scatter'}]])"
] |
[
"= True extra = Extra.ignore @root_validator(pre=True) def _parse_raw(cls, values: dict): values['raw'] = values.copy()",
"Extra, root_validator from ...utils.mixins import ContextVarMixin class MatrixObject(BaseModel, ContextVarMixin): raw: dict class Config:",
"MatrixObject(BaseModel, ContextVarMixin): raw: dict class Config: allow_mutation = True json_encoders = {datetime.datetime: lambda",
"from pydantic import BaseModel, Extra, root_validator from ...utils.mixins import ContextVarMixin class MatrixObject(BaseModel, ContextVarMixin):",
"{datetime.datetime: lambda dt: int(dt.timestamp())} validate_assignment = True extra = Extra.ignore @root_validator(pre=True) def _parse_raw(cls,",
"True extra = Extra.ignore @root_validator(pre=True) def _parse_raw(cls, values: dict): values['raw'] = values.copy() return",
"int(dt.timestamp())} validate_assignment = True extra = Extra.ignore @root_validator(pre=True) def _parse_raw(cls, values: dict): values['raw']",
"= {datetime.datetime: lambda dt: int(dt.timestamp())} validate_assignment = True extra = Extra.ignore @root_validator(pre=True) def",
"Config: allow_mutation = True json_encoders = {datetime.datetime: lambda dt: int(dt.timestamp())} validate_assignment = True",
"pydantic import BaseModel, Extra, root_validator from ...utils.mixins import ContextVarMixin class MatrixObject(BaseModel, ContextVarMixin): raw:",
"datetime from pydantic import BaseModel, Extra, root_validator from ...utils.mixins import ContextVarMixin class MatrixObject(BaseModel,",
"class MatrixObject(BaseModel, ContextVarMixin): raw: dict class Config: allow_mutation = True json_encoders = {datetime.datetime:",
"from ...utils.mixins import ContextVarMixin class MatrixObject(BaseModel, ContextVarMixin): raw: dict class Config: allow_mutation =",
"ContextVarMixin class MatrixObject(BaseModel, ContextVarMixin): raw: dict class Config: allow_mutation = True json_encoders =",
"...utils.mixins import ContextVarMixin class MatrixObject(BaseModel, ContextVarMixin): raw: dict class Config: allow_mutation = True",
"BaseModel, Extra, root_validator from ...utils.mixins import ContextVarMixin class MatrixObject(BaseModel, ContextVarMixin): raw: dict class",
"dict class Config: allow_mutation = True json_encoders = {datetime.datetime: lambda dt: int(dt.timestamp())} validate_assignment",
"root_validator from ...utils.mixins import ContextVarMixin class MatrixObject(BaseModel, ContextVarMixin): raw: dict class Config: allow_mutation",
"allow_mutation = True json_encoders = {datetime.datetime: lambda dt: int(dt.timestamp())} validate_assignment = True extra",
"= True json_encoders = {datetime.datetime: lambda dt: int(dt.timestamp())} validate_assignment = True extra =",
"extra = Extra.ignore @root_validator(pre=True) def _parse_raw(cls, values: dict): values['raw'] = values.copy() return values",
"validate_assignment = True extra = Extra.ignore @root_validator(pre=True) def _parse_raw(cls, values: dict): values['raw'] =",
"lambda dt: int(dt.timestamp())} validate_assignment = True extra = Extra.ignore @root_validator(pre=True) def _parse_raw(cls, values:",
"<reponame>Forden/aiomatrix<gh_stars>1-10 import datetime from pydantic import BaseModel, Extra, root_validator from ...utils.mixins import ContextVarMixin",
"class Config: allow_mutation = True json_encoders = {datetime.datetime: lambda dt: int(dt.timestamp())} validate_assignment =",
"json_encoders = {datetime.datetime: lambda dt: int(dt.timestamp())} validate_assignment = True extra = Extra.ignore @root_validator(pre=True)",
"import ContextVarMixin class MatrixObject(BaseModel, ContextVarMixin): raw: dict class Config: allow_mutation = True json_encoders",
"True json_encoders = {datetime.datetime: lambda dt: int(dt.timestamp())} validate_assignment = True extra = Extra.ignore",
"ContextVarMixin): raw: dict class Config: allow_mutation = True json_encoders = {datetime.datetime: lambda dt:",
"dt: int(dt.timestamp())} validate_assignment = True extra = Extra.ignore @root_validator(pre=True) def _parse_raw(cls, values: dict):",
"import datetime from pydantic import BaseModel, Extra, root_validator from ...utils.mixins import ContextVarMixin class",
"raw: dict class Config: allow_mutation = True json_encoders = {datetime.datetime: lambda dt: int(dt.timestamp())}",
"import BaseModel, Extra, root_validator from ...utils.mixins import ContextVarMixin class MatrixObject(BaseModel, ContextVarMixin): raw: dict"
] |
[
"content def create_directories(path_to_dir: list): \"\"\"Creates directories if they don't exist \"\"\" full_path =",
"\"\"\"Used to perform common tasks \"\"\" def read_yaml(yaml_path): with open(yaml_path, 'r') as yaml_file:",
"directories if they don't exist \"\"\" full_path = \"\" for path in path_to_dir:",
"def read_yaml(yaml_path): with open(yaml_path, 'r') as yaml_file: content = yaml.safe_load(yaml_file) logging.info('yaml file loaded')",
"= yaml.safe_load(yaml_file) logging.info('yaml file loaded') return content def create_directories(path_to_dir: list): \"\"\"Creates directories if",
"common tasks \"\"\" def read_yaml(yaml_path): with open(yaml_path, 'r') as yaml_file: content = yaml.safe_load(yaml_file)",
"import yaml import os import logging \"\"\"Used to perform common tasks \"\"\" def",
"create_directories(path_to_dir: list): \"\"\"Creates directories if they don't exist \"\"\" full_path = \"\" for",
"exist \"\"\" full_path = \"\" for path in path_to_dir: full_path = os.path.join(full_path, path)",
"\"\"\" full_path = \"\" for path in path_to_dir: full_path = os.path.join(full_path, path) os.makedirs(full_path,",
"os import logging \"\"\"Used to perform common tasks \"\"\" def read_yaml(yaml_path): with open(yaml_path,",
"yaml.safe_load(yaml_file) logging.info('yaml file loaded') return content def create_directories(path_to_dir: list): \"\"\"Creates directories if they",
"logging \"\"\"Used to perform common tasks \"\"\" def read_yaml(yaml_path): with open(yaml_path, 'r') as",
"\"\" for path in path_to_dir: full_path = os.path.join(full_path, path) os.makedirs(full_path, exist_ok=True) logging.info(f\"Directories created:",
"content = yaml.safe_load(yaml_file) logging.info('yaml file loaded') return content def create_directories(path_to_dir: list): \"\"\"Creates directories",
"to perform common tasks \"\"\" def read_yaml(yaml_path): with open(yaml_path, 'r') as yaml_file: content",
"loaded') return content def create_directories(path_to_dir: list): \"\"\"Creates directories if they don't exist \"\"\"",
"\"\"\"Creates directories if they don't exist \"\"\" full_path = \"\" for path in",
"read_yaml(yaml_path): with open(yaml_path, 'r') as yaml_file: content = yaml.safe_load(yaml_file) logging.info('yaml file loaded') return",
"import logging \"\"\"Used to perform common tasks \"\"\" def read_yaml(yaml_path): with open(yaml_path, 'r')",
"with open(yaml_path, 'r') as yaml_file: content = yaml.safe_load(yaml_file) logging.info('yaml file loaded') return content",
"if they don't exist \"\"\" full_path = \"\" for path in path_to_dir: full_path",
"as yaml_file: content = yaml.safe_load(yaml_file) logging.info('yaml file loaded') return content def create_directories(path_to_dir: list):",
"list): \"\"\"Creates directories if they don't exist \"\"\" full_path = \"\" for path",
"don't exist \"\"\" full_path = \"\" for path in path_to_dir: full_path = os.path.join(full_path,",
"import os import logging \"\"\"Used to perform common tasks \"\"\" def read_yaml(yaml_path): with",
"\"\"\" def read_yaml(yaml_path): with open(yaml_path, 'r') as yaml_file: content = yaml.safe_load(yaml_file) logging.info('yaml file",
"return content def create_directories(path_to_dir: list): \"\"\"Creates directories if they don't exist \"\"\" full_path",
"yaml_file: content = yaml.safe_load(yaml_file) logging.info('yaml file loaded') return content def create_directories(path_to_dir: list): \"\"\"Creates",
"perform common tasks \"\"\" def read_yaml(yaml_path): with open(yaml_path, 'r') as yaml_file: content =",
"'r') as yaml_file: content = yaml.safe_load(yaml_file) logging.info('yaml file loaded') return content def create_directories(path_to_dir:",
"logging.info('yaml file loaded') return content def create_directories(path_to_dir: list): \"\"\"Creates directories if they don't",
"open(yaml_path, 'r') as yaml_file: content = yaml.safe_load(yaml_file) logging.info('yaml file loaded') return content def",
"full_path = \"\" for path in path_to_dir: full_path = os.path.join(full_path, path) os.makedirs(full_path, exist_ok=True)",
"they don't exist \"\"\" full_path = \"\" for path in path_to_dir: full_path =",
"for path in path_to_dir: full_path = os.path.join(full_path, path) os.makedirs(full_path, exist_ok=True) logging.info(f\"Directories created: {full_path}\")",
"<gh_stars>0 import yaml import os import logging \"\"\"Used to perform common tasks \"\"\"",
"def create_directories(path_to_dir: list): \"\"\"Creates directories if they don't exist \"\"\" full_path = \"\"",
"= \"\" for path in path_to_dir: full_path = os.path.join(full_path, path) os.makedirs(full_path, exist_ok=True) logging.info(f\"Directories",
"tasks \"\"\" def read_yaml(yaml_path): with open(yaml_path, 'r') as yaml_file: content = yaml.safe_load(yaml_file) logging.info('yaml",
"yaml import os import logging \"\"\"Used to perform common tasks \"\"\" def read_yaml(yaml_path):",
"file loaded') return content def create_directories(path_to_dir: list): \"\"\"Creates directories if they don't exist"
] |
[
"N / 2 * torch.log(tau)) + loss_reg) # Optimizer step optimizer.zero_grad() loss.backward() optimizer.step()",
"training when it reaches minimum MSE. Args: model (DeepMoD): [description] data (torch.Tensor): [description]",
"thetas, model.constraint_coeffs(scaled=False, sparse=True))]) loss = torch.sum(MSE + reg_weight * Reg) # Optimizer step",
"import time import numpy as np from torch.distributions.studentT import StudentT from sklearn.linear_model import",
"#1 / MSE[0].data beta = torch.exp(model.s[:, 2])#torch.exp(-model.s[:, 2])#torch.exp(model.s[:, 2]) #torch.tensor(1e-5).to(Theta.device) M = Theta.shape[1]",
"beta * torch.inverse(A) @ Theta.T @ t loss_reg = -1/2 * (M *",
"Theta mn = beta * torch.inverse(A) @ Theta.T @ t loss_reg = -1/2",
"np.arange(0, max_iterations + 1): # ================== Training Model ============================ prediction, time_derivs, thetas =",
"sparse=True))]) loss_test = torch.sum(MSE_test + reg_weight * Reg_test) # ====================== Logging ======================= _",
"10000. \"\"\" start_time = time.time() board = Tensorboard(log_dir) # initializing tb board #",
"loss = torch.sum(MSE + reg_weight * Reg) # Optimizer step optimizer.zero_grad() loss.backward() optimizer.step()",
"- target_train)**2, dim=0) # loss per output t = time_derivs[0] Theta = thetas[0]",
"estimator_coeff_vectors = model.estimator_coeffs() l1_norm = torch.sum(torch.abs(torch.cat(model.constraint_coeffs(sparse=True, scaled=True), dim=1)), dim=0) progress(iteration, start_time, max_iterations, loss.item(),",
"_ = model.sparse_estimator(thetas, time_derivs) # calculating l1 adjusted coeffs but not setting mask",
"* torch.log(beta) - beta * (t - Theta @ mn).T @ (t -",
"* tau * MSE - N / 2 * torch.log(tau)) + loss_reg) #",
"torch.log(tau)) + loss_reg) # Optimizer step optimizer.zero_grad() loss.backward() optimizer.step() if iteration % write_iterations",
"adjusted coeffs but not setting mask estimator_coeff_vectors = model.estimator_coeffs() l1_norm = torch.sum(torch.abs(torch.cat(model.constraint_coeffs(sparse=True, scaled=True),",
"A = torch.eye(M).to(Theta.device) * alpha + beta * Theta.T @ Theta mn =",
"Theta.shape[0] # Posterior std and mean A = torch.eye(M).to(Theta.device) * alpha + beta",
"@ coeff_vector)**2) for dt, theta, coeff_vector in zip(time_derivs, thetas, model.constraint_coeffs(scaled=False, sparse=True))]) loss =",
"* Reg_test) # ====================== Logging ======================= _ = model.sparse_estimator(thetas, time_derivs) # calculating l1",
"sparsity_scheduler.apply_sparsity is True: with torch.no_grad(): model.constraint.sparsity_masks = model.sparse_estimator(thetas, time_derivs) break board.close() def train_bayes_MSE_optim(model:",
"torch.log(alpha) + N * torch.log(beta) - beta * (t - Theta @ mn).T",
"- Theta @ mn).T @ (t - Theta @ mn) - alpha *",
"assumes data is already randomized n_train = int(split * data.shape[0]) n_test = data.shape[0]",
"def train_bayes_MSE_optim(model: DeepMoD, data: torch.Tensor, target: torch.Tensor, optimizer, sparsity_scheduler, split: float = 0.8,",
"+ beta * Theta.T @ Theta mn = beta * torch.inverse(A) @ Theta.T",
"remaining | Loss | MSE | Reg | L1 norm |') for iteration",
"torch.log(tau), loss_reg) loss = torch.sum((N / 2 * tau * MSE - N",
"n_test], dim=0) target_train, target_test = torch.split(target, [n_train, n_test], dim=0) # Training print('| Iteration",
"= None, max_iterations: int = 10000, write_iterations: int = 25, **convergence_kwargs) -> None:",
"from torch.distributions.studentT import StudentT from sklearn.linear_model import BayesianRidge def train(model: DeepMoD, data: torch.Tensor,",
"coeffs but not setting mask estimator_coeff_vectors = model.estimator_coeffs() l1_norm = torch.sum(torch.abs(torch.cat(model.constraint_coeffs(sparse=True, scaled=True), dim=1)),",
"- alpha * mn.T @ mn - torch.trace(torch.log(A)) - N * np.log(2*np.pi)) Reg",
"* Theta.T @ Theta mn = beta * torch.inverse(A) @ Theta.T @ t",
"data.shape[0] - n_train data_train, data_test = torch.split(data, [n_train, n_test], dim=0) target_train, target_test =",
"target: torch.Tensor, optimizer, sparsity_scheduler, split: float = 0.8, log_dir: Optional[str] = None, max_iterations:",
"for dt, theta, coeff_vector in zip(time_derivs, thetas, model.constraint_coeffs(scaled=False, sparse=True))]) loss = torch.sum(MSE +",
"reg_weight * Reg_test) # ====================== Logging ======================= _ = model.sparse_estimator(thetas, time_derivs) # calculating",
"from multitaskpinn.utils.tensorboard import Tensorboard from multitaskpinn.utils.output import progress from multitaskpinn.model.deepmod import DeepMoD from",
"time_derivs_test, thetas_test = model.library((prediction_test, coordinates)) with torch.no_grad(): MSE_test = torch.mean((prediction_test - target_test)**2, dim=0)",
"= torch.sum(torch.exp(-model.s[:, 0]) * MSE + torch.sum(model.s[:, 0])) # Optimizer step optimizer.zero_grad() loss.backward()",
"= torch.split(target, [n_train, n_test], dim=0) # Training print('| Iteration | Progress | Time",
"= model.sparse_estimator(thetas, time_derivs) # calculating l1 adjusted coeffs but not setting mask estimator_coeff_vectors",
"| MSE | Reg | L1 norm |') for iteration in np.arange(0, max_iterations",
"@ mn - torch.trace(torch.log(A)) - N * np.log(2*np.pi)) Reg = torch.stack([torch.mean((dt - theta",
"def train_bayes_full_optim(model: DeepMoD, data: torch.Tensor, target: torch.Tensor, optimizer, sparsity_scheduler, split: float = 0.8,",
"zip(time_derivs_test, thetas_test, model.constraint_coeffs(scaled=False, sparse=True))]) loss_test = torch.sum(MSE_test + reg_weight * Reg_test) # ======================",
"model.constraint_coeffs(scaled=False, sparse=True))]) loss_test = torch.sum(MSE_test + Reg_test) # ====================== Logging ======================= _ =",
"0] = torch.log(1 / MSE.data) model.s.data[:, 1] = torch.log(torch.tensor(sk_reg.lambda_)) model.s.data[:, 2] = torch.log(torch.tensor(sk_reg.alpha_))",
"sparse=True))]) loss_test = torch.sum(MSE_test + Reg_test) # ====================== Logging ======================= _ = model.sparse_estimator(thetas,",
"/ 2 * torch.log(tau)) + loss_reg) # Optimizer step optimizer.zero_grad() loss.backward() optimizer.step() if",
"target: torch.Tensor, optimizer, sparsity_scheduler, reg_weight, split: float = 0.8, log_dir: Optional[str] = None,",
"coeff_vector)**2) for dt, theta, coeff_vector in zip(time_derivs, thetas, model.constraint_coeffs(scaled=False, sparse=True))]) print(N / 2",
"estimator_coeff_vectors, MSE_test=MSE_test, Reg_test=Reg_test, loss_test=loss_test) # ================== Sparsity update ============= # Updating sparsity and",
"iteration == 0: sk_reg = BayesianRidge(fit_intercept=False, compute_score=True, alpha_1=0, alpha_2=0, lambda_1=0, lambda_2=0) sk_reg.fit(thetas[0].cpu().detach().numpy(), time_derivs[0].cpu().detach().numpy())",
"(t - Theta @ mn) - alpha * mn.T @ mn - torch.trace(torch.log(A))",
"(M * torch.log(alpha) + N * torch.log(beta) - beta * (t - Theta",
"torch.split(target, [n_train, n_test], dim=0) # Training print('| Iteration | Progress | Time remaining",
"* np.log(2*np.pi)) Reg = torch.stack([torch.mean((dt - theta @ coeff_vector)**2) for dt, theta, coeff_vector",
"coeff_vector in zip(time_derivs, thetas, model.constraint_coeffs(scaled=False, sparse=True))]) loss = torch.sum(MSE + reg_weight * Reg)",
"* (t - Theta @ mn).T @ (t - Theta @ mn) -",
"calculating l1 adjusted coeffs but not setting mask estimator_coeff_vectors = model.estimator_coeffs() l1_norm =",
"step optimizer.zero_grad() loss.backward() optimizer.step() if iteration % write_iterations == 0: # ================== Validation",
"prediction_test, coordinates = model.func_approx(data_test) time_derivs_test, thetas_test = model.library((prediction_test, coordinates)) with torch.no_grad(): MSE_test =",
"time_derivs) break board.close() def train_bayes_MSE_optim(model: DeepMoD, data: torch.Tensor, target: torch.Tensor, optimizer, sparsity_scheduler, split:",
"L1 norm |') for iteration in np.arange(0, max_iterations + 1): # ================== Training",
"model.constraint.sparsity_masks = model.sparse_estimator(thetas, time_derivs) break board.close() def train_bayes_full_optim(model: DeepMoD, data: torch.Tensor, target: torch.Tensor,",
"or convergence if iteration % write_iterations == 0: sparsity_scheduler(iteration, torch.sum(MSE_test), model, optimizer) if",
"* torch.inverse(A) @ Theta.T @ t loss_reg = -1/2 * (M * torch.log(alpha)",
"torch.sum(MSE_test), model, optimizer) if sparsity_scheduler.apply_sparsity is True: with torch.no_grad(): model.constraint.sparsity_masks = model.sparse_estimator(thetas, time_derivs)",
"#torch.tensor(1e-5).to(Theta.device) M = Theta.shape[1] N = Theta.shape[0] # Posterior std and mean A",
"beta * Theta.T @ Theta mn = beta * torch.inverse(A) @ Theta.T @",
"torch.sum(MSE).item(), torch.sum(Reg).item(), torch.sum(l1_norm).item()) board.write(iteration, loss, MSE, Reg, l1_norm, model.constraint_coeffs(sparse=True, scaled=True), model.constraint_coeffs(sparse=True, scaled=False), estimator_coeff_vectors,",
"# ====================== Logging ======================= _ = model.sparse_estimator(thetas, time_derivs) # calculating l1 adjusted coeffs",
"model.constraint_coeffs(sparse=True, scaled=True), model.constraint_coeffs(sparse=True, scaled=False), estimator_coeff_vectors, MSE_test=MSE_test, Reg_test=Reg_test, loss_test=loss_test) # ================== Sparsity update =============",
"theta, coeff_vector in zip(time_derivs, thetas, model.constraint_coeffs(scaled=False, sparse=True))]) loss = torch.sum(torch.exp(-model.s[:, 0]) * MSE",
"dim=0) target_train, target_test = torch.split(target, [n_train, n_test], dim=0) # Training print('| Iteration |",
"model.constraint_coeffs(sparse=True, scaled=True), model.constraint_coeffs(sparse=True, scaled=False), estimator_coeff_vectors, MSE_test=MSE_test, Reg_test=Reg_test, loss_test=loss_test, s=model.s) # ================== Sparsity update",
"theta, coeff_vector in zip(time_derivs, thetas, model.constraint_coeffs(scaled=False, sparse=True))]) loss = torch.sum(MSE + reg_weight *",
"2] = torch.log(torch.tensor(sk_reg.alpha_)) tau = torch.exp(model.s[:, 0])#torch.exp(-model.s[:, 0]) alpha = torch.exp(model.s[:, 1])#torch.exp(-model.s[:, 1])#torch.exp(model.s[:,",
"model.constraint_coeffs(scaled=False, sparse=True))]) loss = torch.sum(MSE + reg_weight * Reg) # Optimizer step optimizer.zero_grad()",
"/ MSE[0].data beta = torch.exp(model.s[:, 2])#torch.exp(-model.s[:, 2])#torch.exp(model.s[:, 2]) #torch.tensor(1e-5).to(Theta.device) M = Theta.shape[1] N",
"torch import time import numpy as np from torch.distributions.studentT import StudentT from sklearn.linear_model",
"N * np.log(2*np.pi)) Reg = torch.stack([torch.mean((dt - theta @ coeff_vector)**2) for dt, theta,",
"n_test], dim=0) # Training print('| Iteration | Progress | Time remaining | Loss",
"* Reg) # Optimizer step optimizer.zero_grad() loss.backward() optimizer.step() if iteration % write_iterations ==",
"torch.mean((prediction - target_train)**2, dim=0) # loss per output Reg = torch.stack([torch.mean((dt - theta",
"update ============= # Updating sparsity and or convergence if iteration % write_iterations ==",
"= torch.log(torch.tensor(sk_reg.alpha_)) tau = torch.exp(model.s[:, 0])#torch.exp(-model.s[:, 0]) alpha = torch.exp(model.s[:, 1])#torch.exp(-model.s[:, 1])#torch.exp(model.s[:, 1])",
"0.8, log_dir: Optional[str] = None, max_iterations: int = 10000, write_iterations: int = 25,",
"torch.sum(torch.abs(torch.cat(model.constraint_coeffs(sparse=True, scaled=True), dim=1)), dim=0) progress(iteration, start_time, max_iterations, loss.item(), torch.sum(MSE).item(), torch.sum(Reg).item(), torch.sum(l1_norm).item()) board.write(iteration, loss,",
"loss_test=loss_test) # ================== Sparsity update ============= # Updating sparsity and or convergence if",
"time_derivs) break board.close() def train_bayes_full_optim(model: DeepMoD, data: torch.Tensor, target: torch.Tensor, optimizer, sparsity_scheduler, split:",
"Reg_test=Reg_test, loss_test=loss_test) # ================== Sparsity update ============= # Updating sparsity and or convergence",
"**convergence_kwargs) -> None: \"\"\"Stops training when it reaches minimum MSE. Args: model (DeepMoD):",
"thetas_test, model.constraint_coeffs(scaled=False, sparse=True))]) loss_test = torch.sum(MSE_test + Reg_test) # ====================== Logging ======================= _",
"torch.sum((N / 2 * tau * MSE - N / 2 * torch.log(tau))",
"Tensorboard from multitaskpinn.utils.output import progress from multitaskpinn.model.deepmod import DeepMoD from typing import Optional",
"MSE, Reg, l1_norm, model.constraint_coeffs(sparse=True, scaled=True), model.constraint_coeffs(sparse=True, scaled=False), estimator_coeff_vectors, MSE_test=MSE_test, Reg_test=Reg_test, loss_test=loss_test) # ==================",
"torch.eye(M).to(Theta.device) * alpha + beta * Theta.T @ Theta mn = beta *",
"DeepMoD, data: torch.Tensor, target: torch.Tensor, optimizer, sparsity_scheduler, reg_weight, split: float = 0.8, log_dir:",
"= torch.sum(torch.abs(torch.cat(model.constraint_coeffs(sparse=True, scaled=True), dim=1)), dim=0) progress(iteration, start_time, max_iterations, loss.item(), torch.sum(MSE).item(), torch.sum(Reg).item(), torch.sum(l1_norm).item()) board.write(iteration,",
"import numpy as np from torch.distributions.studentT import StudentT from sklearn.linear_model import BayesianRidge def",
"/ 2 * tau * MSE - N / 2 * torch.log(tau), loss_reg)",
"typing import Optional import torch import time import numpy as np from torch.distributions.studentT",
"(int, optional): [description]. Defaults to 10000. \"\"\" start_time = time.time() board = Tensorboard(log_dir)",
"# Updating sparsity and or convergence if iteration % write_iterations == 0: sparsity_scheduler(iteration,",
"mn.T @ mn - torch.trace(torch.log(A)) - N * np.log(2*np.pi)) Reg = torch.stack([torch.mean((dt -",
"Reg_test) # ====================== Logging ======================= _ = model.sparse_estimator(thetas, time_derivs) # calculating l1 adjusted",
"int(split * data.shape[0]) n_test = data.shape[0] - n_train data_train, data_test = torch.split(data, [n_train,",
"in zip(time_derivs_test, thetas_test, model.constraint_coeffs(scaled=False, sparse=True))]) loss_test = torch.sum(MSE_test + reg_weight * Reg_test) #",
"# Training print('| Iteration | Progress | Time remaining | Loss | MSE",
"@ t loss_reg = -1/2 * (M * torch.log(alpha) + N * torch.log(beta)",
"(Optional[str], optional): [description]. Defaults to None. max_iterations (int, optional): [description]. Defaults to 10000.",
"MSE | Reg | L1 norm |') for iteration in np.arange(0, max_iterations +",
"loss_reg) # Optimizer step optimizer.zero_grad() loss.backward() optimizer.step() if iteration % write_iterations == 0:",
"tau * MSE - N / 2 * torch.log(tau), loss_reg) loss = torch.sum((N",
"MSE_test=MSE_test, Reg_test=Reg_test, loss_test=loss_test) # ================== Sparsity update ============= # Updating sparsity and or",
"% write_iterations == 0: # ================== Validation costs ================ prediction_test, coordinates = model.func_approx(data_test)",
"max_iterations + 1): # ================== Training Model ============================ prediction, time_derivs, thetas = model(data_train)",
"# loss per output Reg_test = torch.stack([torch.mean((dt - theta @ coeff_vector)**2) for dt,",
"- beta * (t - Theta @ mn).T @ (t - Theta @",
"model.s.data[:, 1] = torch.log(torch.tensor(sk_reg.lambda_)) model.s.data[:, 2] = torch.log(torch.tensor(sk_reg.alpha_)) tau = torch.exp(model.s[:, 0])#torch.exp(-model.s[:, 0])",
"| Loss | MSE | Reg | L1 norm |') for iteration in",
"@ coeff_vector)**2) for dt, theta, coeff_vector in zip(time_derivs_test, thetas_test, model.constraint_coeffs(scaled=False, sparse=True))]) loss_test =",
"board.write(iteration, loss, MSE, Reg, l1_norm, model.constraint_coeffs(sparse=True, scaled=True), model.constraint_coeffs(sparse=True, scaled=False), estimator_coeff_vectors, MSE_test=MSE_test, Reg_test=Reg_test, loss_test=loss_test)",
"Updating sparsity and or convergence if iteration % write_iterations == 0: sparsity_scheduler(iteration, torch.sum(MSE_test),",
"lambda_1=0, lambda_2=0) sk_reg.fit(thetas[0].cpu().detach().numpy(), time_derivs[0].cpu().detach().numpy()) model.s.data[:, 0] = torch.log(1 / MSE.data) model.s.data[:, 1] =",
"start_time = time.time() board = Tensorboard(log_dir) # initializing tb board # Splitting data,",
"+ Reg_test) # ====================== Logging ======================= _ = model.sparse_estimator(thetas, time_derivs) # calculating l1",
"* mn.T @ mn - torch.trace(torch.log(A)) - N * np.log(2*np.pi)) Reg = torch.stack([torch.mean((dt",
"Sparsity update ============= # Updating sparsity and or convergence if iteration % write_iterations",
"Training print('| Iteration | Progress | Time remaining | Loss | MSE |",
"std and mean A = torch.eye(M).to(Theta.device) * alpha + beta * Theta.T @",
"model.constraint_coeffs(scaled=False, sparse=True))]) loss_test = torch.sum(MSE_test + reg_weight * Reg_test) # ====================== Logging =======================",
"= thetas[0] if iteration == 0: sk_reg = BayesianRidge(fit_intercept=False, compute_score=True, alpha_1=0, alpha_2=0, lambda_1=0,",
"dim=0) # Training print('| Iteration | Progress | Time remaining | Loss |",
"= torch.exp(model.s[:, 1])#torch.exp(-model.s[:, 1])#torch.exp(model.s[:, 1]) #1 / MSE[0].data beta = torch.exp(model.s[:, 2])#torch.exp(-model.s[:, 2])#torch.exp(model.s[:,",
"thetas, model.constraint_coeffs(scaled=False, sparse=True))]) loss = torch.sum(torch.exp(-model.s[:, 0]) * MSE + torch.sum(model.s[:, 0])) #",
"board.close() def train_bayes_MSE_optim(model: DeepMoD, data: torch.Tensor, target: torch.Tensor, optimizer, sparsity_scheduler, split: float =",
"= BayesianRidge(fit_intercept=False, compute_score=True, alpha_1=0, alpha_2=0, lambda_1=0, lambda_2=0) sk_reg.fit(thetas[0].cpu().detach().numpy(), time_derivs[0].cpu().detach().numpy()) model.s.data[:, 0] = torch.log(1",
"dim=0) # loss per output t = time_derivs[0] Theta = thetas[0] if iteration",
"= torch.mean((prediction_test - target_test)**2, dim=0) # loss per output Reg_test = torch.stack([torch.mean((dt -",
"1])#torch.exp(model.s[:, 1]) #1 / MSE[0].data beta = torch.exp(model.s[:, 2])#torch.exp(-model.s[:, 2])#torch.exp(model.s[:, 2]) #torch.tensor(1e-5).to(Theta.device) M",
"= model.sparse_estimator(thetas, time_derivs) break board.close() def train_bayes_full_optim(model: DeepMoD, data: torch.Tensor, target: torch.Tensor, optimizer,",
"in zip(time_derivs_test, thetas_test, model.constraint_coeffs(scaled=False, sparse=True))]) loss_test = torch.sum(MSE_test + Reg_test) # ====================== Logging",
"== 0: sk_reg = BayesianRidge(fit_intercept=False, compute_score=True, alpha_1=0, alpha_2=0, lambda_1=0, lambda_2=0) sk_reg.fit(thetas[0].cpu().detach().numpy(), time_derivs[0].cpu().detach().numpy()) model.s.data[:,",
"/ MSE.data) model.s.data[:, 1] = torch.log(torch.tensor(sk_reg.lambda_)) model.s.data[:, 2] = torch.log(torch.tensor(sk_reg.alpha_)) tau = torch.exp(model.s[:,",
"loss_test = torch.sum(MSE_test + Reg_test) # ====================== Logging ======================= _ = model.sparse_estimator(thetas, time_derivs)",
"# Splitting data, assumes data is already randomized n_train = int(split * data.shape[0])",
"mn - torch.trace(torch.log(A)) - N * np.log(2*np.pi)) Reg = torch.stack([torch.mean((dt - theta @",
"Posterior std and mean A = torch.eye(M).to(Theta.device) * alpha + beta * Theta.T",
"import progress from multitaskpinn.model.deepmod import DeepMoD from typing import Optional import torch import",
"write_iterations: int = 25, **convergence_kwargs) -> None: \"\"\"Stops training when it reaches minimum",
"alpha + beta * Theta.T @ Theta mn = beta * torch.inverse(A) @",
"1] = torch.log(torch.tensor(sk_reg.lambda_)) model.s.data[:, 2] = torch.log(torch.tensor(sk_reg.alpha_)) tau = torch.exp(model.s[:, 0])#torch.exp(-model.s[:, 0]) alpha",
"numpy as np from torch.distributions.studentT import StudentT from sklearn.linear_model import BayesianRidge def train(model:",
"================== Training Model ============================ prediction, time_derivs, thetas = model(data_train) MSE = torch.mean((prediction -",
"M = Theta.shape[1] N = Theta.shape[0] # Posterior std and mean A =",
"n_train = int(split * data.shape[0]) n_test = data.shape[0] - n_train data_train, data_test =",
"torch.log(1 / MSE.data) model.s.data[:, 1] = torch.log(torch.tensor(sk_reg.lambda_)) model.s.data[:, 2] = torch.log(torch.tensor(sk_reg.alpha_)) tau =",
"1]) #1 / MSE[0].data beta = torch.exp(model.s[:, 2])#torch.exp(-model.s[:, 2])#torch.exp(model.s[:, 2]) #torch.tensor(1e-5).to(Theta.device) M =",
"\"\"\"Stops training when it reaches minimum MSE. Args: model (DeepMoD): [description] data (torch.Tensor):",
"l1_norm, model.constraint_coeffs(sparse=True, scaled=True), model.constraint_coeffs(sparse=True, scaled=False), estimator_coeff_vectors, MSE_test=MSE_test, Reg_test=Reg_test, loss_test=loss_test, s=model.s) # ================== Sparsity",
"= beta * torch.inverse(A) @ Theta.T @ t loss_reg = -1/2 * (M",
"Validation costs ================ prediction_test, coordinates = model.func_approx(data_test) time_derivs_test, thetas_test = model.library((prediction_test, coordinates)) with",
"Theta @ mn) - alpha * mn.T @ mn - torch.trace(torch.log(A)) - N",
"time_derivs) # calculating l1 adjusted coeffs but not setting mask estimator_coeff_vectors = model.estimator_coeffs()",
"sparse=True))]) loss = torch.sum(torch.exp(-model.s[:, 0]) * MSE + torch.sum(model.s[:, 0])) # Optimizer step",
"Args: model (DeepMoD): [description] data (torch.Tensor): [description] target (torch.Tensor): [description] optimizer ([type]): [description]",
"([type]): [description] sparsity_scheduler ([type]): [description] log_dir (Optional[str], optional): [description]. Defaults to None. max_iterations",
"Training Model ============================ prediction, time_derivs, thetas = model(data_train) MSE = torch.mean((prediction - target_train)**2,",
"N = Theta.shape[0] # Posterior std and mean A = torch.eye(M).to(Theta.device) * alpha",
"theta @ coeff_vector)**2) for dt, theta, coeff_vector in zip(time_derivs, thetas, model.constraint_coeffs(scaled=False, sparse=True))]) print(N",
"= torch.sum(MSE_test + reg_weight * Reg_test) # ====================== Logging ======================= _ = model.sparse_estimator(thetas,",
"torch.distributions.studentT import StudentT from sklearn.linear_model import BayesianRidge def train(model: DeepMoD, data: torch.Tensor, target:",
"mn).T @ (t - Theta @ mn) - alpha * mn.T @ mn",
"Theta.T @ Theta mn = beta * torch.inverse(A) @ Theta.T @ t loss_reg",
"torch.no_grad(): model.constraint.sparsity_masks = model.sparse_estimator(thetas, time_derivs) break board.close() def train_bayes_full_optim(model: DeepMoD, data: torch.Tensor, target:",
"torch.log(torch.tensor(sk_reg.alpha_)) tau = torch.exp(model.s[:, 0])#torch.exp(-model.s[:, 0]) alpha = torch.exp(model.s[:, 1])#torch.exp(-model.s[:, 1])#torch.exp(model.s[:, 1]) #1",
"and or convergence if iteration % write_iterations == 0: sparsity_scheduler(iteration, torch.sum(MSE_test), model, optimizer)",
"MSE = torch.mean((prediction - target_train)**2, dim=0) # loss per output Reg = torch.stack([torch.mean((dt",
"max_iterations (int, optional): [description]. Defaults to 10000. \"\"\" start_time = time.time() board =",
"* data.shape[0]) n_test = data.shape[0] - n_train data_train, data_test = torch.split(data, [n_train, n_test],",
"train(model: DeepMoD, data: torch.Tensor, target: torch.Tensor, optimizer, sparsity_scheduler, reg_weight, split: float = 0.8,",
"0]) alpha = torch.exp(model.s[:, 1])#torch.exp(-model.s[:, 1])#torch.exp(model.s[:, 1]) #1 / MSE[0].data beta = torch.exp(model.s[:,",
"Reg, l1_norm, model.constraint_coeffs(sparse=True, scaled=True), model.constraint_coeffs(sparse=True, scaled=False), estimator_coeff_vectors, MSE_test=MSE_test, Reg_test=Reg_test, loss_test=loss_test) # ================== Sparsity",
"compute_score=True, alpha_1=0, alpha_2=0, lambda_1=0, lambda_2=0) sk_reg.fit(thetas[0].cpu().detach().numpy(), time_derivs[0].cpu().detach().numpy()) model.s.data[:, 0] = torch.log(1 / MSE.data)",
"Defaults to None. max_iterations (int, optional): [description]. Defaults to 10000. \"\"\" start_time =",
"train_bayes_MSE_optim(model: DeepMoD, data: torch.Tensor, target: torch.Tensor, optimizer, sparsity_scheduler, split: float = 0.8, log_dir:",
"None, max_iterations: int = 10000, write_iterations: int = 25, **convergence_kwargs) -> None: \"\"\"Stops",
"| Progress | Time remaining | Loss | MSE | Reg | L1",
"target_test)**2, dim=0) # loss per output Reg_test = torch.stack([torch.mean((dt - theta @ coeff_vector)**2)",
"data.shape[0]) n_test = data.shape[0] - n_train data_train, data_test = torch.split(data, [n_train, n_test], dim=0)",
"0: sparsity_scheduler(iteration, torch.sum(MSE_test), model, optimizer) if sparsity_scheduler.apply_sparsity is True: with torch.no_grad(): model.constraint.sparsity_masks =",
"= model.library((prediction_test, coordinates)) with torch.no_grad(): MSE_test = torch.mean((prediction_test - target_test)**2, dim=0) # loss",
"coeff_vector in zip(time_derivs_test, thetas_test, model.constraint_coeffs(scaled=False, sparse=True))]) loss_test = torch.sum(MSE_test + Reg_test) # ======================",
"= model(data_train) MSE = torch.mean((prediction - target_train)**2, dim=0) # loss per output t",
"torch.stack([torch.mean((dt - theta @ coeff_vector)**2) for dt, theta, coeff_vector in zip(time_derivs_test, thetas_test, model.constraint_coeffs(scaled=False,",
"alpha_1=0, alpha_2=0, lambda_1=0, lambda_2=0) sk_reg.fit(thetas[0].cpu().detach().numpy(), time_derivs[0].cpu().detach().numpy()) model.s.data[:, 0] = torch.log(1 / MSE.data) model.s.data[:,",
"progress from multitaskpinn.model.deepmod import DeepMoD from typing import Optional import torch import time",
"for dt, theta, coeff_vector in zip(time_derivs, thetas, model.constraint_coeffs(scaled=False, sparse=True))]) print(N / 2 *",
"alpha * mn.T @ mn - torch.trace(torch.log(A)) - N * np.log(2*np.pi)) Reg =",
"1])#torch.exp(-model.s[:, 1])#torch.exp(model.s[:, 1]) #1 / MSE[0].data beta = torch.exp(model.s[:, 2])#torch.exp(-model.s[:, 2])#torch.exp(model.s[:, 2]) #torch.tensor(1e-5).to(Theta.device)",
"already randomized n_train = int(split * data.shape[0]) n_test = data.shape[0] - n_train data_train,",
"coeff_vector)**2) for dt, theta, coeff_vector in zip(time_derivs_test, thetas_test, model.constraint_coeffs(scaled=False, sparse=True))]) loss_test = torch.sum(MSE_test",
"torch.trace(torch.log(A)) - N * np.log(2*np.pi)) Reg = torch.stack([torch.mean((dt - theta @ coeff_vector)**2) for",
"is True: with torch.no_grad(): model.constraint.sparsity_masks = model.sparse_estimator(thetas, time_derivs) break board.close() def train_bayes_MSE_optim(model: DeepMoD,",
"loss = torch.sum((N / 2 * tau * MSE - N / 2",
"coordinates = model.func_approx(data_test) time_derivs_test, thetas_test = model.library((prediction_test, coordinates)) with torch.no_grad(): MSE_test = torch.mean((prediction_test",
"but not setting mask estimator_coeff_vectors = model.estimator_coeffs() l1_norm = torch.sum(torch.abs(torch.cat(model.constraint_coeffs(sparse=True, scaled=True), dim=1)), dim=0)",
"print(N / 2 * tau * MSE - N / 2 * torch.log(tau),",
"is already randomized n_train = int(split * data.shape[0]) n_test = data.shape[0] - n_train",
"% write_iterations == 0: sparsity_scheduler(iteration, torch.sum(MSE_test), model, optimizer) if sparsity_scheduler.apply_sparsity is True: with",
"= 25, **convergence_kwargs) -> None: \"\"\"Stops training when it reaches minimum MSE. Args:",
"* MSE - N / 2 * torch.log(tau), loss_reg) loss = torch.sum((N /",
"with torch.no_grad(): model.constraint.sparsity_masks = model.sparse_estimator(thetas, time_derivs) break board.close() def train_bayes_MSE_optim(model: DeepMoD, data: torch.Tensor,",
"t loss_reg = -1/2 * (M * torch.log(alpha) + N * torch.log(beta) -",
"= -1/2 * (M * torch.log(alpha) + N * torch.log(beta) - beta *",
"== 0: sparsity_scheduler(iteration, torch.sum(MSE_test), model, optimizer) if sparsity_scheduler.apply_sparsity is True: with torch.no_grad(): model.constraint.sparsity_masks",
"torch.Tensor, target: torch.Tensor, optimizer, sparsity_scheduler, reg_weight, split: float = 0.8, log_dir: Optional[str] =",
"10000, write_iterations: int = 25, **convergence_kwargs) -> None: \"\"\"Stops training when it reaches",
"StudentT from sklearn.linear_model import BayesianRidge def train(model: DeepMoD, data: torch.Tensor, target: torch.Tensor, optimizer,",
"beta = torch.exp(model.s[:, 2])#torch.exp(-model.s[:, 2])#torch.exp(model.s[:, 2]) #torch.tensor(1e-5).to(Theta.device) M = Theta.shape[1] N = Theta.shape[0]",
"torch.sum(model.s[:, 0])) # Optimizer step optimizer.zero_grad() loss.backward() optimizer.step() if iteration % write_iterations ==",
"[description] target (torch.Tensor): [description] optimizer ([type]): [description] sparsity_scheduler ([type]): [description] log_dir (Optional[str], optional):",
"import Tensorboard from multitaskpinn.utils.output import progress from multitaskpinn.model.deepmod import DeepMoD from typing import",
"loss_reg = -1/2 * (M * torch.log(alpha) + N * torch.log(beta) - beta",
"with torch.no_grad(): MSE_test = torch.mean((prediction_test - target_test)**2, dim=0) # loss per output Reg_test",
"* alpha + beta * Theta.T @ Theta mn = beta * torch.inverse(A)",
"<filename>experiments/KS/Bayes/.ipynb_checkpoints/experiment_code-checkpoint.py<gh_stars>0 from multitaskpinn.utils.tensorboard import Tensorboard from multitaskpinn.utils.output import progress from multitaskpinn.model.deepmod import DeepMoD",
"torch.stack([torch.mean((dt - theta @ coeff_vector)**2) for dt, theta, coeff_vector in zip(time_derivs, thetas, model.constraint_coeffs(scaled=False,",
"to None. max_iterations (int, optional): [description]. Defaults to 10000. \"\"\" start_time = time.time()",
"write_iterations == 0: # ================== Validation costs ================ prediction_test, coordinates = model.func_approx(data_test) time_derivs_test,",
"data_train, data_test = torch.split(data, [n_train, n_test], dim=0) target_train, target_test = torch.split(target, [n_train, n_test],",
"N * torch.log(beta) - beta * (t - Theta @ mn).T @ (t",
"============= # Updating sparsity and or convergence if iteration % write_iterations == 0:",
"= torch.eye(M).to(Theta.device) * alpha + beta * Theta.T @ Theta mn = beta",
"@ coeff_vector)**2) for dt, theta, coeff_vector in zip(time_derivs, thetas, model.constraint_coeffs(scaled=False, sparse=True))]) print(N /",
"= 10000, write_iterations: int = 25, **convergence_kwargs) -> None: \"\"\"Stops training when it",
"scaled=True), model.constraint_coeffs(sparse=True, scaled=False), estimator_coeff_vectors, MSE_test=MSE_test, Reg_test=Reg_test, loss_test=loss_test, s=model.s) # ================== Sparsity update =============",
"= torch.log(torch.tensor(sk_reg.lambda_)) model.s.data[:, 2] = torch.log(torch.tensor(sk_reg.alpha_)) tau = torch.exp(model.s[:, 0])#torch.exp(-model.s[:, 0]) alpha =",
"thetas = model(data_train) MSE = torch.mean((prediction - target_train)**2, dim=0) # loss per output",
"board # Splitting data, assumes data is already randomized n_train = int(split *",
"[description] data (torch.Tensor): [description] target (torch.Tensor): [description] optimizer ([type]): [description] sparsity_scheduler ([type]): [description]",
"data is already randomized n_train = int(split * data.shape[0]) n_test = data.shape[0] -",
"([type]): [description] log_dir (Optional[str], optional): [description]. Defaults to None. max_iterations (int, optional): [description].",
"= torch.stack([torch.mean((dt - theta @ coeff_vector)**2) for dt, theta, coeff_vector in zip(time_derivs_test, thetas_test,",
"|') for iteration in np.arange(0, max_iterations + 1): # ================== Training Model ============================",
"coeff_vector)**2) for dt, theta, coeff_vector in zip(time_derivs, thetas, model.constraint_coeffs(scaled=False, sparse=True))]) loss = torch.sum(torch.exp(-model.s[:,",
"/ 2 * tau * MSE - N / 2 * torch.log(tau)) +",
"import torch import time import numpy as np from torch.distributions.studentT import StudentT from",
"[description] optimizer ([type]): [description] sparsity_scheduler ([type]): [description] log_dir (Optional[str], optional): [description]. Defaults to",
"Reg_test=Reg_test, loss_test=loss_test, s=model.s) # ================== Sparsity update ============= # Updating sparsity and or",
"if sparsity_scheduler.apply_sparsity is True: with torch.no_grad(): model.constraint.sparsity_masks = model.sparse_estimator(thetas, time_derivs) break board.close() def",
"Time remaining | Loss | MSE | Reg | L1 norm |') for",
"l1_norm, model.constraint_coeffs(sparse=True, scaled=True), model.constraint_coeffs(sparse=True, scaled=False), estimator_coeff_vectors, MSE_test=MSE_test, Reg_test=Reg_test, loss_test=loss_test) # ================== Sparsity update",
"scaled=True), model.constraint_coeffs(sparse=True, scaled=False), estimator_coeff_vectors, MSE_test=MSE_test, Reg_test=Reg_test, loss_test=loss_test) # ================== Sparsity update ============= #",
"torch.log(beta) - beta * (t - Theta @ mn).T @ (t - Theta",
"dt, theta, coeff_vector in zip(time_derivs, thetas, model.constraint_coeffs(scaled=False, sparse=True))]) loss = torch.sum(torch.exp(-model.s[:, 0]) *",
"model.constraint.sparsity_masks = model.sparse_estimator(thetas, time_derivs) break board.close() def train_bayes_MSE_optim(model: DeepMoD, data: torch.Tensor, target: torch.Tensor,",
"data, assumes data is already randomized n_train = int(split * data.shape[0]) n_test =",
"torch.sum(Reg).item(), torch.sum(l1_norm).item()) board.write(iteration, loss, MSE, Reg, l1_norm, model.constraint_coeffs(sparse=True, scaled=True), model.constraint_coeffs(sparse=True, scaled=False), estimator_coeff_vectors, MSE_test=MSE_test,",
"n_train data_train, data_test = torch.split(data, [n_train, n_test], dim=0) target_train, target_test = torch.split(target, [n_train,",
"\"\"\" start_time = time.time() board = Tensorboard(log_dir) # initializing tb board # Splitting",
"model.sparse_estimator(thetas, time_derivs) break board.close() def train_bayes_full_optim(model: DeepMoD, data: torch.Tensor, target: torch.Tensor, optimizer, sparsity_scheduler,",
"iteration % write_iterations == 0: sparsity_scheduler(iteration, torch.sum(MSE_test), model, optimizer) if sparsity_scheduler.apply_sparsity is True:",
"np from torch.distributions.studentT import StudentT from sklearn.linear_model import BayesianRidge def train(model: DeepMoD, data:",
"model.library((prediction_test, coordinates)) with torch.no_grad(): MSE_test = torch.mean((prediction_test - target_test)**2, dim=0) # loss per",
"======================= _ = model.sparse_estimator(thetas, time_derivs) # calculating l1 adjusted coeffs but not setting",
"Logging ======================= _ = model.sparse_estimator(thetas, time_derivs) # calculating l1 adjusted coeffs but not",
"============================ prediction, time_derivs, thetas = model(data_train) MSE = torch.mean((prediction - target_train)**2, dim=0) #",
"data: torch.Tensor, target: torch.Tensor, optimizer, sparsity_scheduler, reg_weight, split: float = 0.8, log_dir: Optional[str]",
"reg_weight * Reg) # Optimizer step optimizer.zero_grad() loss.backward() optimizer.step() if iteration % write_iterations",
"@ mn) - alpha * mn.T @ mn - torch.trace(torch.log(A)) - N *",
"thetas, model.constraint_coeffs(scaled=False, sparse=True))]) print(N / 2 * tau * MSE - N /",
"* MSE - N / 2 * torch.log(tau)) + loss_reg) # Optimizer step",
"output Reg = torch.stack([torch.mean((dt - theta @ coeff_vector)**2) for dt, theta, coeff_vector in",
"model.constraint_coeffs(sparse=True, scaled=False), estimator_coeff_vectors, MSE_test=MSE_test, Reg_test=Reg_test, loss_test=loss_test, s=model.s) # ================== Sparsity update ============= #",
"= model(data_train) MSE = torch.mean((prediction - target_train)**2, dim=0) # loss per output Reg",
"theta, coeff_vector in zip(time_derivs_test, thetas_test, model.constraint_coeffs(scaled=False, sparse=True))]) loss_test = torch.sum(MSE_test + reg_weight *",
"loss, MSE, Reg, l1_norm, model.constraint_coeffs(sparse=True, scaled=True), model.constraint_coeffs(sparse=True, scaled=False), estimator_coeff_vectors, MSE_test=MSE_test, Reg_test=Reg_test, loss_test=loss_test) #",
"====================== Logging ======================= _ = model.sparse_estimator(thetas, time_derivs) # calculating l1 adjusted coeffs but",
"tau * MSE - N / 2 * torch.log(tau)) + loss_reg) # Optimizer",
"torch.mean((prediction - target_train)**2, dim=0) # loss per output t = time_derivs[0] Theta =",
"multitaskpinn.model.deepmod import DeepMoD from typing import Optional import torch import time import numpy",
"in zip(time_derivs, thetas, model.constraint_coeffs(scaled=False, sparse=True))]) loss = torch.sum(torch.exp(-model.s[:, 0]) * MSE + torch.sum(model.s[:,",
"model (DeepMoD): [description] data (torch.Tensor): [description] target (torch.Tensor): [description] optimizer ([type]): [description] sparsity_scheduler",
"model.constraint_coeffs(scaled=False, sparse=True))]) loss = torch.sum(torch.exp(-model.s[:, 0]) * MSE + torch.sum(model.s[:, 0])) # Optimizer",
"sparse=True))]) loss = torch.sum(MSE + reg_weight * Reg) # Optimizer step optimizer.zero_grad() loss.backward()",
"t = time_derivs[0] Theta = thetas[0] if iteration == 0: sk_reg = BayesianRidge(fit_intercept=False,",
"| Time remaining | Loss | MSE | Reg | L1 norm |')",
"scaled=False), estimator_coeff_vectors, MSE_test=MSE_test, Reg_test=Reg_test, loss_test=loss_test) # ================== Sparsity update ============= # Updating sparsity",
"zip(time_derivs, thetas, model.constraint_coeffs(scaled=False, sparse=True))]) loss = torch.sum(MSE + reg_weight * Reg) # Optimizer",
"Iteration | Progress | Time remaining | Loss | MSE | Reg |",
"dt, theta, coeff_vector in zip(time_derivs_test, thetas_test, model.constraint_coeffs(scaled=False, sparse=True))]) loss_test = torch.sum(MSE_test + reg_weight",
"for dt, theta, coeff_vector in zip(time_derivs_test, thetas_test, model.constraint_coeffs(scaled=False, sparse=True))]) loss_test = torch.sum(MSE_test +",
"= Theta.shape[1] N = Theta.shape[0] # Posterior std and mean A = torch.eye(M).to(Theta.device)",
"coeff_vector in zip(time_derivs_test, thetas_test, model.constraint_coeffs(scaled=False, sparse=True))]) loss_test = torch.sum(MSE_test + reg_weight * Reg_test)",
"Optional import torch import time import numpy as np from torch.distributions.studentT import StudentT",
"torch.Tensor, optimizer, sparsity_scheduler, reg_weight, split: float = 0.8, log_dir: Optional[str] = None, max_iterations:",
"model.constraint_coeffs(scaled=False, sparse=True))]) print(N / 2 * tau * MSE - N / 2",
"(torch.Tensor): [description] target (torch.Tensor): [description] optimizer ([type]): [description] sparsity_scheduler ([type]): [description] log_dir (Optional[str],",
"loss_reg) loss = torch.sum((N / 2 * tau * MSE - N /",
"MSE_test=MSE_test, Reg_test=Reg_test, loss_test=loss_test, s=model.s) # ================== Sparsity update ============= # Updating sparsity and",
"with torch.no_grad(): model.constraint.sparsity_masks = model.sparse_estimator(thetas, time_derivs) break board.close() def train_bayes_full_optim(model: DeepMoD, data: torch.Tensor,",
"costs ================ prediction_test, coordinates = model.func_approx(data_test) time_derivs_test, thetas_test = model.library((prediction_test, coordinates)) with torch.no_grad():",
"+ reg_weight * Reg_test) # ====================== Logging ======================= _ = model.sparse_estimator(thetas, time_derivs) #",
"start_time, max_iterations, loss.item(), torch.sum(MSE).item(), torch.sum(Reg).item(), torch.sum(l1_norm).item()) board.write(iteration, loss, MSE, Reg, l1_norm, model.constraint_coeffs(sparse=True, scaled=True),",
"scaled=True), dim=1)), dim=0) progress(iteration, start_time, max_iterations, loss.item(), torch.sum(MSE).item(), torch.sum(Reg).item(), torch.sum(l1_norm).item()) board.write(iteration, loss, MSE,",
"multitaskpinn.utils.output import progress from multitaskpinn.model.deepmod import DeepMoD from typing import Optional import torch",
"Defaults to 10000. \"\"\" start_time = time.time() board = Tensorboard(log_dir) # initializing tb",
"Optimizer step optimizer.zero_grad() loss.backward() optimizer.step() if iteration % write_iterations == 0: # ==================",
"loss, MSE, Reg, l1_norm, model.constraint_coeffs(sparse=True, scaled=True), model.constraint_coeffs(sparse=True, scaled=False), estimator_coeff_vectors, MSE_test=MSE_test, Reg_test=Reg_test, loss_test=loss_test, s=model.s)",
"model.func_approx(data_test) time_derivs_test, thetas_test = model.library((prediction_test, coordinates)) with torch.no_grad(): MSE_test = torch.mean((prediction_test - target_test)**2,",
"- Theta @ mn) - alpha * mn.T @ mn - torch.trace(torch.log(A)) -",
"in np.arange(0, max_iterations + 1): # ================== Training Model ============================ prediction, time_derivs, thetas",
"theta @ coeff_vector)**2) for dt, theta, coeff_vector in zip(time_derivs, thetas, model.constraint_coeffs(scaled=False, sparse=True))]) loss",
"board = Tensorboard(log_dir) # initializing tb board # Splitting data, assumes data is",
"optional): [description]. Defaults to None. max_iterations (int, optional): [description]. Defaults to 10000. \"\"\"",
"- target_test)**2, dim=0) # loss per output Reg_test = torch.stack([torch.mean((dt - theta @",
"mn = beta * torch.inverse(A) @ Theta.T @ t loss_reg = -1/2 *",
"prediction, time_derivs, thetas = model(data_train) MSE = torch.mean((prediction - target_train)**2, dim=0) # loss",
"N / 2 * torch.log(tau), loss_reg) loss = torch.sum((N / 2 * tau",
"+ loss_reg) # Optimizer step optimizer.zero_grad() loss.backward() optimizer.step() if iteration % write_iterations ==",
"in zip(time_derivs, thetas, model.constraint_coeffs(scaled=False, sparse=True))]) loss = torch.sum(MSE + reg_weight * Reg) #",
"= time.time() board = Tensorboard(log_dir) # initializing tb board # Splitting data, assumes",
"max_iterations: int = 10000, write_iterations: int = 25, **convergence_kwargs) -> None: \"\"\"Stops training",
"sparsity_scheduler(iteration, torch.sum(MSE_test), model, optimizer) if sparsity_scheduler.apply_sparsity is True: with torch.no_grad(): model.constraint.sparsity_masks = model.sparse_estimator(thetas,",
"target_train)**2, dim=0) # loss per output Reg = torch.stack([torch.mean((dt - theta @ coeff_vector)**2)",
"# Posterior std and mean A = torch.eye(M).to(Theta.device) * alpha + beta *",
"MSE - N / 2 * torch.log(tau)) + loss_reg) # Optimizer step optimizer.zero_grad()",
"+ reg_weight * Reg) # Optimizer step optimizer.zero_grad() loss.backward() optimizer.step() if iteration %",
"optimizer, sparsity_scheduler, reg_weight, split: float = 0.8, log_dir: Optional[str] = None, max_iterations: int",
"break board.close() def train_bayes_full_optim(model: DeepMoD, data: torch.Tensor, target: torch.Tensor, optimizer, sparsity_scheduler, split: float",
"* MSE + torch.sum(model.s[:, 0])) # Optimizer step optimizer.zero_grad() loss.backward() optimizer.step() if iteration",
"0: # ================== Validation costs ================ prediction_test, coordinates = model.func_approx(data_test) time_derivs_test, thetas_test =",
"sparsity_scheduler ([type]): [description] log_dir (Optional[str], optional): [description]. Defaults to None. max_iterations (int, optional):",
"- torch.trace(torch.log(A)) - N * np.log(2*np.pi)) Reg = torch.stack([torch.mean((dt - theta @ coeff_vector)**2)",
"per output Reg = torch.stack([torch.mean((dt - theta @ coeff_vector)**2) for dt, theta, coeff_vector",
"when it reaches minimum MSE. Args: model (DeepMoD): [description] data (torch.Tensor): [description] target",
"Reg | L1 norm |') for iteration in np.arange(0, max_iterations + 1): #",
"= Theta.shape[0] # Posterior std and mean A = torch.eye(M).to(Theta.device) * alpha +",
"+ 1): # ================== Training Model ============================ prediction, time_derivs, thetas = model(data_train) MSE",
"= data.shape[0] - n_train data_train, data_test = torch.split(data, [n_train, n_test], dim=0) target_train, target_test",
"BayesianRidge def train(model: DeepMoD, data: torch.Tensor, target: torch.Tensor, optimizer, sparsity_scheduler, reg_weight, split: float",
"True: with torch.no_grad(): model.constraint.sparsity_masks = model.sparse_estimator(thetas, time_derivs) break board.close() def train_bayes_MSE_optim(model: DeepMoD, data:",
"loss per output Reg_test = torch.stack([torch.mean((dt - theta @ coeff_vector)**2) for dt, theta,",
"is True: with torch.no_grad(): model.constraint.sparsity_masks = model.sparse_estimator(thetas, time_derivs) break board.close() def train_bayes_full_optim(model: DeepMoD,",
"l1_norm = torch.sum(torch.abs(torch.cat(model.constraint_coeffs(sparse=True, scaled=True), dim=1)), dim=0) progress(iteration, start_time, max_iterations, loss.item(), torch.sum(MSE).item(), torch.sum(Reg).item(), torch.sum(l1_norm).item())",
"(torch.Tensor): [description] optimizer ([type]): [description] sparsity_scheduler ([type]): [description] log_dir (Optional[str], optional): [description]. Defaults",
"torch.sum(l1_norm).item()) board.write(iteration, loss, MSE, Reg, l1_norm, model.constraint_coeffs(sparse=True, scaled=True), model.constraint_coeffs(sparse=True, scaled=False), estimator_coeff_vectors, MSE_test=MSE_test, Reg_test=Reg_test,",
"optimizer.zero_grad() loss.backward() optimizer.step() if iteration % write_iterations == 0: # ================== Validation costs",
"model.s.data[:, 2] = torch.log(torch.tensor(sk_reg.alpha_)) tau = torch.exp(model.s[:, 0])#torch.exp(-model.s[:, 0]) alpha = torch.exp(model.s[:, 1])#torch.exp(-model.s[:,",
"# loss per output t = time_derivs[0] Theta = thetas[0] if iteration ==",
"25, **convergence_kwargs) -> None: \"\"\"Stops training when it reaches minimum MSE. Args: model",
"0])) # Optimizer step optimizer.zero_grad() loss.backward() optimizer.step() if iteration % write_iterations == 0:",
"scaled=False), estimator_coeff_vectors, MSE_test=MSE_test, Reg_test=Reg_test, loss_test=loss_test, s=model.s) # ================== Sparsity update ============= # Updating",
"[description] sparsity_scheduler ([type]): [description] log_dir (Optional[str], optional): [description]. Defaults to None. max_iterations (int,",
"0: sk_reg = BayesianRidge(fit_intercept=False, compute_score=True, alpha_1=0, alpha_2=0, lambda_1=0, lambda_2=0) sk_reg.fit(thetas[0].cpu().detach().numpy(), time_derivs[0].cpu().detach().numpy()) model.s.data[:, 0]",
"DeepMoD from typing import Optional import torch import time import numpy as np",
"= torch.exp(model.s[:, 2])#torch.exp(-model.s[:, 2])#torch.exp(model.s[:, 2]) #torch.tensor(1e-5).to(Theta.device) M = Theta.shape[1] N = Theta.shape[0] #",
"if iteration % write_iterations == 0: # ================== Validation costs ================ prediction_test, coordinates",
"| L1 norm |') for iteration in np.arange(0, max_iterations + 1): # ==================",
"beta * (t - Theta @ mn).T @ (t - Theta @ mn)",
"int = 25, **convergence_kwargs) -> None: \"\"\"Stops training when it reaches minimum MSE.",
"# ================== Sparsity update ============= # Updating sparsity and or convergence if iteration",
"2]) #torch.tensor(1e-5).to(Theta.device) M = Theta.shape[1] N = Theta.shape[0] # Posterior std and mean",
"mn) - alpha * mn.T @ mn - torch.trace(torch.log(A)) - N * np.log(2*np.pi))",
"dt, theta, coeff_vector in zip(time_derivs_test, thetas_test, model.constraint_coeffs(scaled=False, sparse=True))]) loss_test = torch.sum(MSE_test + Reg_test)",
"- target_train)**2, dim=0) # loss per output Reg = torch.stack([torch.mean((dt - theta @",
"tb board # Splitting data, assumes data is already randomized n_train = int(split",
"[description]. Defaults to 10000. \"\"\" start_time = time.time() board = Tensorboard(log_dir) # initializing",
"= model.estimator_coeffs() l1_norm = torch.sum(torch.abs(torch.cat(model.constraint_coeffs(sparse=True, scaled=True), dim=1)), dim=0) progress(iteration, start_time, max_iterations, loss.item(), torch.sum(MSE).item(),",
"MSE + torch.sum(model.s[:, 0])) # Optimizer step optimizer.zero_grad() loss.backward() optimizer.step() if iteration %",
"progress(iteration, start_time, max_iterations, loss.item(), torch.sum(MSE).item(), torch.sum(Reg).item(), torch.sum(l1_norm).item()) board.write(iteration, loss, MSE, Reg, l1_norm, model.constraint_coeffs(sparse=True,",
"target_train, target_test = torch.split(target, [n_train, n_test], dim=0) # Training print('| Iteration | Progress",
"and mean A = torch.eye(M).to(Theta.device) * alpha + beta * Theta.T @ Theta",
"torch.mean((prediction_test - target_test)**2, dim=0) # loss per output Reg_test = torch.stack([torch.mean((dt - theta",
"| Reg | L1 norm |') for iteration in np.arange(0, max_iterations + 1):",
"if iteration == 0: sk_reg = BayesianRidge(fit_intercept=False, compute_score=True, alpha_1=0, alpha_2=0, lambda_1=0, lambda_2=0) sk_reg.fit(thetas[0].cpu().detach().numpy(),",
"model.estimator_coeffs() l1_norm = torch.sum(torch.abs(torch.cat(model.constraint_coeffs(sparse=True, scaled=True), dim=1)), dim=0) progress(iteration, start_time, max_iterations, loss.item(), torch.sum(MSE).item(), torch.sum(Reg).item(),",
"coeff_vector in zip(time_derivs, thetas, model.constraint_coeffs(scaled=False, sparse=True))]) print(N / 2 * tau * MSE",
"sparse=True))]) print(N / 2 * tau * MSE - N / 2 *",
"sparsity and or convergence if iteration % write_iterations == 0: sparsity_scheduler(iteration, torch.sum(MSE_test), model,",
"write_iterations == 0: sparsity_scheduler(iteration, torch.sum(MSE_test), model, optimizer) if sparsity_scheduler.apply_sparsity is True: with torch.no_grad():",
"/ 2 * torch.log(tau), loss_reg) loss = torch.sum((N / 2 * tau *",
"Theta = thetas[0] if iteration == 0: sk_reg = BayesianRidge(fit_intercept=False, compute_score=True, alpha_1=0, alpha_2=0,",
"target (torch.Tensor): [description] optimizer ([type]): [description] sparsity_scheduler ([type]): [description] log_dir (Optional[str], optional): [description].",
"MSE[0].data beta = torch.exp(model.s[:, 2])#torch.exp(-model.s[:, 2])#torch.exp(model.s[:, 2]) #torch.tensor(1e-5).to(Theta.device) M = Theta.shape[1] N =",
"zip(time_derivs_test, thetas_test, model.constraint_coeffs(scaled=False, sparse=True))]) loss_test = torch.sum(MSE_test + Reg_test) # ====================== Logging =======================",
"MSE. Args: model (DeepMoD): [description] data (torch.Tensor): [description] target (torch.Tensor): [description] optimizer ([type]):",
"thetas_test, model.constraint_coeffs(scaled=False, sparse=True))]) loss_test = torch.sum(MSE_test + reg_weight * Reg_test) # ====================== Logging",
"torch.sum(torch.exp(-model.s[:, 0]) * MSE + torch.sum(model.s[:, 0])) # Optimizer step optimizer.zero_grad() loss.backward() optimizer.step()",
"int = 10000, write_iterations: int = 25, **convergence_kwargs) -> None: \"\"\"Stops training when",
"target_test = torch.split(target, [n_train, n_test], dim=0) # Training print('| Iteration | Progress |",
"Theta.T @ t loss_reg = -1/2 * (M * torch.log(alpha) + N *",
"from multitaskpinn.model.deepmod import DeepMoD from typing import Optional import torch import time import",
"from sklearn.linear_model import BayesianRidge def train(model: DeepMoD, data: torch.Tensor, target: torch.Tensor, optimizer, sparsity_scheduler,",
"= time_derivs[0] Theta = thetas[0] if iteration == 0: sk_reg = BayesianRidge(fit_intercept=False, compute_score=True,",
"= torch.sum(MSE_test + Reg_test) # ====================== Logging ======================= _ = model.sparse_estimator(thetas, time_derivs) #",
"to 10000. \"\"\" start_time = time.time() board = Tensorboard(log_dir) # initializing tb board",
"2 * tau * MSE - N / 2 * torch.log(tau)) + loss_reg)",
"- theta @ coeff_vector)**2) for dt, theta, coeff_vector in zip(time_derivs, thetas, model.constraint_coeffs(scaled=False, sparse=True))])",
"theta @ coeff_vector)**2) for dt, theta, coeff_vector in zip(time_derivs_test, thetas_test, model.constraint_coeffs(scaled=False, sparse=True))]) loss_test",
"thetas[0] if iteration == 0: sk_reg = BayesianRidge(fit_intercept=False, compute_score=True, alpha_1=0, alpha_2=0, lambda_1=0, lambda_2=0)",
"mean A = torch.eye(M).to(Theta.device) * alpha + beta * Theta.T @ Theta mn",
"setting mask estimator_coeff_vectors = model.estimator_coeffs() l1_norm = torch.sum(torch.abs(torch.cat(model.constraint_coeffs(sparse=True, scaled=True), dim=1)), dim=0) progress(iteration, start_time,",
"# loss per output Reg = torch.stack([torch.mean((dt - theta @ coeff_vector)**2) for dt,",
"# ================== Validation costs ================ prediction_test, coordinates = model.func_approx(data_test) time_derivs_test, thetas_test = model.library((prediction_test,",
"= torch.sum((N / 2 * tau * MSE - N / 2 *",
"torch.sum(MSE_test + reg_weight * Reg_test) # ====================== Logging ======================= _ = model.sparse_estimator(thetas, time_derivs)",
"train_bayes_full_optim(model: DeepMoD, data: torch.Tensor, target: torch.Tensor, optimizer, sparsity_scheduler, split: float = 0.8, log_dir:",
"Reg = torch.stack([torch.mean((dt - theta @ coeff_vector)**2) for dt, theta, coeff_vector in zip(time_derivs,",
"[n_train, n_test], dim=0) # Training print('| Iteration | Progress | Time remaining |",
"torch.Tensor, optimizer, sparsity_scheduler, split: float = 0.8, log_dir: Optional[str] = None, max_iterations: int",
"model(data_train) MSE = torch.mean((prediction - target_train)**2, dim=0) # loss per output t =",
"Reg) # Optimizer step optimizer.zero_grad() loss.backward() optimizer.step() if iteration % write_iterations == 0:",
"torch.log(torch.tensor(sk_reg.lambda_)) model.s.data[:, 2] = torch.log(torch.tensor(sk_reg.alpha_)) tau = torch.exp(model.s[:, 0])#torch.exp(-model.s[:, 0]) alpha = torch.exp(model.s[:,",
"as np from torch.distributions.studentT import StudentT from sklearn.linear_model import BayesianRidge def train(model: DeepMoD,",
"@ Theta mn = beta * torch.inverse(A) @ Theta.T @ t loss_reg =",
"MSE, Reg, l1_norm, model.constraint_coeffs(sparse=True, scaled=True), model.constraint_coeffs(sparse=True, scaled=False), estimator_coeff_vectors, MSE_test=MSE_test, Reg_test=Reg_test, loss_test=loss_test, s=model.s) #",
"from typing import Optional import torch import time import numpy as np from",
"time import numpy as np from torch.distributions.studentT import StudentT from sklearn.linear_model import BayesianRidge",
"# ================== Training Model ============================ prediction, time_derivs, thetas = model(data_train) MSE = torch.mean((prediction",
"thetas_test = model.library((prediction_test, coordinates)) with torch.no_grad(): MSE_test = torch.mean((prediction_test - target_test)**2, dim=0) #",
"torch.exp(model.s[:, 2])#torch.exp(-model.s[:, 2])#torch.exp(model.s[:, 2]) #torch.tensor(1e-5).to(Theta.device) M = Theta.shape[1] N = Theta.shape[0] # Posterior",
"import StudentT from sklearn.linear_model import BayesianRidge def train(model: DeepMoD, data: torch.Tensor, target: torch.Tensor,",
"Model ============================ prediction, time_derivs, thetas = model(data_train) MSE = torch.mean((prediction - target_train)**2, dim=0)",
"torch.sum(MSE + reg_weight * Reg) # Optimizer step optimizer.zero_grad() loss.backward() optimizer.step() if iteration",
"theta, coeff_vector in zip(time_derivs_test, thetas_test, model.constraint_coeffs(scaled=False, sparse=True))]) loss_test = torch.sum(MSE_test + Reg_test) #",
"data_test = torch.split(data, [n_train, n_test], dim=0) target_train, target_test = torch.split(target, [n_train, n_test], dim=0)",
"MSE - N / 2 * torch.log(tau), loss_reg) loss = torch.sum((N / 2",
"= torch.mean((prediction - target_train)**2, dim=0) # loss per output t = time_derivs[0] Theta",
"norm |') for iteration in np.arange(0, max_iterations + 1): # ================== Training Model",
"model(data_train) MSE = torch.mean((prediction - target_train)**2, dim=0) # loss per output Reg =",
"optional): [description]. Defaults to 10000. \"\"\" start_time = time.time() board = Tensorboard(log_dir) #",
"def train(model: DeepMoD, data: torch.Tensor, target: torch.Tensor, optimizer, sparsity_scheduler, reg_weight, split: float =",
"max_iterations, loss.item(), torch.sum(MSE).item(), torch.sum(Reg).item(), torch.sum(l1_norm).item()) board.write(iteration, loss, MSE, Reg, l1_norm, model.constraint_coeffs(sparse=True, scaled=True), model.constraint_coeffs(sparse=True,",
"sk_reg = BayesianRidge(fit_intercept=False, compute_score=True, alpha_1=0, alpha_2=0, lambda_1=0, lambda_2=0) sk_reg.fit(thetas[0].cpu().detach().numpy(), time_derivs[0].cpu().detach().numpy()) model.s.data[:, 0] =",
"not setting mask estimator_coeff_vectors = model.estimator_coeffs() l1_norm = torch.sum(torch.abs(torch.cat(model.constraint_coeffs(sparse=True, scaled=True), dim=1)), dim=0) progress(iteration,",
"Theta @ mn).T @ (t - Theta @ mn) - alpha * mn.T",
"multitaskpinn.utils.tensorboard import Tensorboard from multitaskpinn.utils.output import progress from multitaskpinn.model.deepmod import DeepMoD from typing",
"loss.backward() optimizer.step() if iteration % write_iterations == 0: # ================== Validation costs ================",
"n_test = data.shape[0] - n_train data_train, data_test = torch.split(data, [n_train, n_test], dim=0) target_train,",
"torch.no_grad(): MSE_test = torch.mean((prediction_test - target_test)**2, dim=0) # loss per output Reg_test =",
"MSE.data) model.s.data[:, 1] = torch.log(torch.tensor(sk_reg.lambda_)) model.s.data[:, 2] = torch.log(torch.tensor(sk_reg.alpha_)) tau = torch.exp(model.s[:, 0])#torch.exp(-model.s[:,",
"None. max_iterations (int, optional): [description]. Defaults to 10000. \"\"\" start_time = time.time() board",
"loss_test = torch.sum(MSE_test + reg_weight * Reg_test) # ====================== Logging ======================= _ =",
"estimator_coeff_vectors, MSE_test=MSE_test, Reg_test=Reg_test, loss_test=loss_test, s=model.s) # ================== Sparsity update ============= # Updating sparsity",
"per output Reg_test = torch.stack([torch.mean((dt - theta @ coeff_vector)**2) for dt, theta, coeff_vector",
"================ prediction_test, coordinates = model.func_approx(data_test) time_derivs_test, thetas_test = model.library((prediction_test, coordinates)) with torch.no_grad(): MSE_test",
"sparsity_scheduler, split: float = 0.8, log_dir: Optional[str] = None, max_iterations: int = 10000,",
"2 * tau * MSE - N / 2 * torch.log(tau), loss_reg) loss",
"[n_train, n_test], dim=0) target_train, target_test = torch.split(target, [n_train, n_test], dim=0) # Training print('|",
"it reaches minimum MSE. Args: model (DeepMoD): [description] data (torch.Tensor): [description] target (torch.Tensor):",
"initializing tb board # Splitting data, assumes data is already randomized n_train =",
"= torch.split(data, [n_train, n_test], dim=0) target_train, target_test = torch.split(target, [n_train, n_test], dim=0) #",
"reg_weight, split: float = 0.8, log_dir: Optional[str] = None, max_iterations: int = 10000,",
"target_train)**2, dim=0) # loss per output t = time_derivs[0] Theta = thetas[0] if",
"torch.exp(model.s[:, 0])#torch.exp(-model.s[:, 0]) alpha = torch.exp(model.s[:, 1])#torch.exp(-model.s[:, 1])#torch.exp(model.s[:, 1]) #1 / MSE[0].data beta",
"loss = torch.sum(torch.exp(-model.s[:, 0]) * MSE + torch.sum(model.s[:, 0])) # Optimizer step optimizer.zero_grad()",
"output Reg_test = torch.stack([torch.mean((dt - theta @ coeff_vector)**2) for dt, theta, coeff_vector in",
"Splitting data, assumes data is already randomized n_train = int(split * data.shape[0]) n_test",
"sparsity_scheduler.apply_sparsity is True: with torch.no_grad(): model.constraint.sparsity_masks = model.sparse_estimator(thetas, time_derivs) break board.close() def train_bayes_full_optim(model:",
"for dt, theta, coeff_vector in zip(time_derivs, thetas, model.constraint_coeffs(scaled=False, sparse=True))]) loss = torch.sum(torch.exp(-model.s[:, 0])",
"for iteration in np.arange(0, max_iterations + 1): # ================== Training Model ============================ prediction,",
"loss per output Reg = torch.stack([torch.mean((dt - theta @ coeff_vector)**2) for dt, theta,",
"log_dir: Optional[str] = None, max_iterations: int = 10000, write_iterations: int = 25, **convergence_kwargs)",
"model.sparse_estimator(thetas, time_derivs) break board.close() def train_bayes_MSE_optim(model: DeepMoD, data: torch.Tensor, target: torch.Tensor, optimizer, sparsity_scheduler,",
"board.close() def train_bayes_full_optim(model: DeepMoD, data: torch.Tensor, target: torch.Tensor, optimizer, sparsity_scheduler, split: float =",
"print('| Iteration | Progress | Time remaining | Loss | MSE | Reg",
"2 * torch.log(tau)) + loss_reg) # Optimizer step optimizer.zero_grad() loss.backward() optimizer.step() if iteration",
"randomized n_train = int(split * data.shape[0]) n_test = data.shape[0] - n_train data_train, data_test",
"= torch.stack([torch.mean((dt - theta @ coeff_vector)**2) for dt, theta, coeff_vector in zip(time_derivs, thetas,",
"@ (t - Theta @ mn) - alpha * mn.T @ mn -",
"[description]. Defaults to None. max_iterations (int, optional): [description]. Defaults to 10000. \"\"\" start_time",
"data: torch.Tensor, target: torch.Tensor, optimizer, sparsity_scheduler, split: float = 0.8, log_dir: Optional[str] =",
"* torch.log(alpha) + N * torch.log(beta) - beta * (t - Theta @",
"dim=0) # loss per output Reg = torch.stack([torch.mean((dt - theta @ coeff_vector)**2) for",
"dt, theta, coeff_vector in zip(time_derivs, thetas, model.constraint_coeffs(scaled=False, sparse=True))]) loss = torch.sum(MSE + reg_weight",
"0]) * MSE + torch.sum(model.s[:, 0])) # Optimizer step optimizer.zero_grad() loss.backward() optimizer.step() if",
"-> None: \"\"\"Stops training when it reaches minimum MSE. Args: model (DeepMoD): [description]",
"sk_reg.fit(thetas[0].cpu().detach().numpy(), time_derivs[0].cpu().detach().numpy()) model.s.data[:, 0] = torch.log(1 / MSE.data) model.s.data[:, 1] = torch.log(torch.tensor(sk_reg.lambda_)) model.s.data[:,",
"coeff_vector)**2) for dt, theta, coeff_vector in zip(time_derivs, thetas, model.constraint_coeffs(scaled=False, sparse=True))]) loss = torch.sum(MSE",
"l1 adjusted coeffs but not setting mask estimator_coeff_vectors = model.estimator_coeffs() l1_norm = torch.sum(torch.abs(torch.cat(model.constraint_coeffs(sparse=True,",
"lambda_2=0) sk_reg.fit(thetas[0].cpu().detach().numpy(), time_derivs[0].cpu().detach().numpy()) model.s.data[:, 0] = torch.log(1 / MSE.data) model.s.data[:, 1] = torch.log(torch.tensor(sk_reg.lambda_))",
"torch.Tensor, target: torch.Tensor, optimizer, sparsity_scheduler, split: float = 0.8, log_dir: Optional[str] = None,",
"Optional[str] = None, max_iterations: int = 10000, write_iterations: int = 25, **convergence_kwargs) ->",
"per output t = time_derivs[0] Theta = thetas[0] if iteration == 0: sk_reg",
"dt, theta, coeff_vector in zip(time_derivs, thetas, model.constraint_coeffs(scaled=False, sparse=True))]) print(N / 2 * tau",
"torch.exp(model.s[:, 1])#torch.exp(-model.s[:, 1])#torch.exp(model.s[:, 1]) #1 / MSE[0].data beta = torch.exp(model.s[:, 2])#torch.exp(-model.s[:, 2])#torch.exp(model.s[:, 2])",
"None: \"\"\"Stops training when it reaches minimum MSE. Args: model (DeepMoD): [description] data",
"torch.no_grad(): model.constraint.sparsity_masks = model.sparse_estimator(thetas, time_derivs) break board.close() def train_bayes_MSE_optim(model: DeepMoD, data: torch.Tensor, target:",
"dim=0) # loss per output Reg_test = torch.stack([torch.mean((dt - theta @ coeff_vector)**2) for",
"-1/2 * (M * torch.log(alpha) + N * torch.log(beta) - beta * (t",
"torch.inverse(A) @ Theta.T @ t loss_reg = -1/2 * (M * torch.log(alpha) +",
"Tensorboard(log_dir) # initializing tb board # Splitting data, assumes data is already randomized",
"alpha = torch.exp(model.s[:, 1])#torch.exp(-model.s[:, 1])#torch.exp(model.s[:, 1]) #1 / MSE[0].data beta = torch.exp(model.s[:, 2])#torch.exp(-model.s[:,",
"sparsity_scheduler, reg_weight, split: float = 0.8, log_dir: Optional[str] = None, max_iterations: int =",
"- N * np.log(2*np.pi)) Reg = torch.stack([torch.mean((dt - theta @ coeff_vector)**2) for dt,",
"np.log(2*np.pi)) Reg = torch.stack([torch.mean((dt - theta @ coeff_vector)**2) for dt, theta, coeff_vector in",
"DeepMoD, data: torch.Tensor, target: torch.Tensor, optimizer, sparsity_scheduler, split: float = 0.8, log_dir: Optional[str]",
"= int(split * data.shape[0]) n_test = data.shape[0] - n_train data_train, data_test = torch.split(data,",
"minimum MSE. Args: model (DeepMoD): [description] data (torch.Tensor): [description] target (torch.Tensor): [description] optimizer",
"Progress | Time remaining | Loss | MSE | Reg | L1 norm",
"s=model.s) # ================== Sparsity update ============= # Updating sparsity and or convergence if",
"loss per output t = time_derivs[0] Theta = thetas[0] if iteration == 0:",
"float = 0.8, log_dir: Optional[str] = None, max_iterations: int = 10000, write_iterations: int",
"data (torch.Tensor): [description] target (torch.Tensor): [description] optimizer ([type]): [description] sparsity_scheduler ([type]): [description] log_dir",
"optimizer.step() if iteration % write_iterations == 0: # ================== Validation costs ================ prediction_test,",
"- N / 2 * torch.log(tau), loss_reg) loss = torch.sum((N / 2 *",
"iteration % write_iterations == 0: # ================== Validation costs ================ prediction_test, coordinates =",
"* torch.log(tau), loss_reg) loss = torch.sum((N / 2 * tau * MSE -",
"- n_train data_train, data_test = torch.split(data, [n_train, n_test], dim=0) target_train, target_test = torch.split(target,",
"split: float = 0.8, log_dir: Optional[str] = None, max_iterations: int = 10000, write_iterations:",
"model.constraint_coeffs(sparse=True, scaled=False), estimator_coeff_vectors, MSE_test=MSE_test, Reg_test=Reg_test, loss_test=loss_test) # ================== Sparsity update ============= # Updating",
"from multitaskpinn.utils.output import progress from multitaskpinn.model.deepmod import DeepMoD from typing import Optional import",
"# Optimizer step optimizer.zero_grad() loss.backward() optimizer.step() if iteration % write_iterations == 0: #",
"break board.close() def train_bayes_MSE_optim(model: DeepMoD, data: torch.Tensor, target: torch.Tensor, optimizer, sparsity_scheduler, split: float",
"output t = time_derivs[0] Theta = thetas[0] if iteration == 0: sk_reg =",
"Theta.shape[1] N = Theta.shape[0] # Posterior std and mean A = torch.eye(M).to(Theta.device) *",
"= model.func_approx(data_test) time_derivs_test, thetas_test = model.library((prediction_test, coordinates)) with torch.no_grad(): MSE_test = torch.mean((prediction_test -",
"model, optimizer) if sparsity_scheduler.apply_sparsity is True: with torch.no_grad(): model.constraint.sparsity_masks = model.sparse_estimator(thetas, time_derivs) break",
"= torch.exp(model.s[:, 0])#torch.exp(-model.s[:, 0]) alpha = torch.exp(model.s[:, 1])#torch.exp(-model.s[:, 1])#torch.exp(model.s[:, 1]) #1 / MSE[0].data",
"+ N * torch.log(beta) - beta * (t - Theta @ mn).T @",
"- N / 2 * torch.log(tau)) + loss_reg) # Optimizer step optimizer.zero_grad() loss.backward()",
"model.s.data[:, 0] = torch.log(1 / MSE.data) model.s.data[:, 1] = torch.log(torch.tensor(sk_reg.lambda_)) model.s.data[:, 2] =",
"in zip(time_derivs, thetas, model.constraint_coeffs(scaled=False, sparse=True))]) print(N / 2 * tau * MSE -",
"= Tensorboard(log_dir) # initializing tb board # Splitting data, assumes data is already",
"zip(time_derivs, thetas, model.constraint_coeffs(scaled=False, sparse=True))]) loss = torch.sum(torch.exp(-model.s[:, 0]) * MSE + torch.sum(model.s[:, 0]))",
"alpha_2=0, lambda_1=0, lambda_2=0) sk_reg.fit(thetas[0].cpu().detach().numpy(), time_derivs[0].cpu().detach().numpy()) model.s.data[:, 0] = torch.log(1 / MSE.data) model.s.data[:, 1]",
"Reg_test = torch.stack([torch.mean((dt - theta @ coeff_vector)**2) for dt, theta, coeff_vector in zip(time_derivs_test,",
"2])#torch.exp(model.s[:, 2]) #torch.tensor(1e-5).to(Theta.device) M = Theta.shape[1] N = Theta.shape[0] # Posterior std and",
"* tau * MSE - N / 2 * torch.log(tau), loss_reg) loss =",
"= torch.mean((prediction - target_train)**2, dim=0) # loss per output Reg = torch.stack([torch.mean((dt -",
"+ torch.sum(model.s[:, 0])) # Optimizer step optimizer.zero_grad() loss.backward() optimizer.step() if iteration % write_iterations",
"* torch.log(tau)) + loss_reg) # Optimizer step optimizer.zero_grad() loss.backward() optimizer.step() if iteration %",
"[description] log_dir (Optional[str], optional): [description]. Defaults to None. max_iterations (int, optional): [description]. Defaults",
"================== Sparsity update ============= # Updating sparsity and or convergence if iteration %",
"loss.item(), torch.sum(MSE).item(), torch.sum(Reg).item(), torch.sum(l1_norm).item()) board.write(iteration, loss, MSE, Reg, l1_norm, model.constraint_coeffs(sparse=True, scaled=True), model.constraint_coeffs(sparse=True, scaled=False),",
"time_derivs[0] Theta = thetas[0] if iteration == 0: sk_reg = BayesianRidge(fit_intercept=False, compute_score=True, alpha_1=0,",
"== 0: # ================== Validation costs ================ prediction_test, coordinates = model.func_approx(data_test) time_derivs_test, thetas_test",
"reaches minimum MSE. Args: model (DeepMoD): [description] data (torch.Tensor): [description] target (torch.Tensor): [description]",
"# initializing tb board # Splitting data, assumes data is already randomized n_train",
"= torch.log(1 / MSE.data) model.s.data[:, 1] = torch.log(torch.tensor(sk_reg.lambda_)) model.s.data[:, 2] = torch.log(torch.tensor(sk_reg.alpha_)) tau",
"optimizer) if sparsity_scheduler.apply_sparsity is True: with torch.no_grad(): model.constraint.sparsity_masks = model.sparse_estimator(thetas, time_derivs) break board.close()",
"import DeepMoD from typing import Optional import torch import time import numpy as",
"Loss | MSE | Reg | L1 norm |') for iteration in np.arange(0,",
"sklearn.linear_model import BayesianRidge def train(model: DeepMoD, data: torch.Tensor, target: torch.Tensor, optimizer, sparsity_scheduler, reg_weight,",
"loss_test=loss_test, s=model.s) # ================== Sparsity update ============= # Updating sparsity and or convergence",
"time_derivs, thetas = model(data_train) MSE = torch.mean((prediction - target_train)**2, dim=0) # loss per",
"= torch.sum(MSE + reg_weight * Reg) # Optimizer step optimizer.zero_grad() loss.backward() optimizer.step() if",
"if iteration % write_iterations == 0: sparsity_scheduler(iteration, torch.sum(MSE_test), model, optimizer) if sparsity_scheduler.apply_sparsity is",
"coeff_vector in zip(time_derivs, thetas, model.constraint_coeffs(scaled=False, sparse=True))]) loss = torch.sum(torch.exp(-model.s[:, 0]) * MSE +",
"board.write(iteration, loss, MSE, Reg, l1_norm, model.constraint_coeffs(sparse=True, scaled=True), model.constraint_coeffs(sparse=True, scaled=False), estimator_coeff_vectors, MSE_test=MSE_test, Reg_test=Reg_test, loss_test=loss_test,",
"zip(time_derivs, thetas, model.constraint_coeffs(scaled=False, sparse=True))]) print(N / 2 * tau * MSE - N",
"================== Validation costs ================ prediction_test, coordinates = model.func_approx(data_test) time_derivs_test, thetas_test = model.library((prediction_test, coordinates))",
"convergence if iteration % write_iterations == 0: sparsity_scheduler(iteration, torch.sum(MSE_test), model, optimizer) if sparsity_scheduler.apply_sparsity",
"theta, coeff_vector in zip(time_derivs, thetas, model.constraint_coeffs(scaled=False, sparse=True))]) print(N / 2 * tau *",
"dim=0) progress(iteration, start_time, max_iterations, loss.item(), torch.sum(MSE).item(), torch.sum(Reg).item(), torch.sum(l1_norm).item()) board.write(iteration, loss, MSE, Reg, l1_norm,",
"time_derivs[0].cpu().detach().numpy()) model.s.data[:, 0] = torch.log(1 / MSE.data) model.s.data[:, 1] = torch.log(torch.tensor(sk_reg.lambda_)) model.s.data[:, 2]",
"2])#torch.exp(-model.s[:, 2])#torch.exp(model.s[:, 2]) #torch.tensor(1e-5).to(Theta.device) M = Theta.shape[1] N = Theta.shape[0] # Posterior std",
"model.sparse_estimator(thetas, time_derivs) # calculating l1 adjusted coeffs but not setting mask estimator_coeff_vectors =",
"MSE = torch.mean((prediction - target_train)**2, dim=0) # loss per output t = time_derivs[0]",
"dim=1)), dim=0) progress(iteration, start_time, max_iterations, loss.item(), torch.sum(MSE).item(), torch.sum(Reg).item(), torch.sum(l1_norm).item()) board.write(iteration, loss, MSE, Reg,",
"Reg, l1_norm, model.constraint_coeffs(sparse=True, scaled=True), model.constraint_coeffs(sparse=True, scaled=False), estimator_coeff_vectors, MSE_test=MSE_test, Reg_test=Reg_test, loss_test=loss_test, s=model.s) # ==================",
"1): # ================== Training Model ============================ prediction, time_derivs, thetas = model(data_train) MSE =",
"# calculating l1 adjusted coeffs but not setting mask estimator_coeff_vectors = model.estimator_coeffs() l1_norm",
"@ Theta.T @ t loss_reg = -1/2 * (M * torch.log(alpha) + N",
"True: with torch.no_grad(): model.constraint.sparsity_masks = model.sparse_estimator(thetas, time_derivs) break board.close() def train_bayes_full_optim(model: DeepMoD, data:",
"(DeepMoD): [description] data (torch.Tensor): [description] target (torch.Tensor): [description] optimizer ([type]): [description] sparsity_scheduler ([type]):",
"optimizer ([type]): [description] sparsity_scheduler ([type]): [description] log_dir (Optional[str], optional): [description]. Defaults to None.",
"iteration in np.arange(0, max_iterations + 1): # ================== Training Model ============================ prediction, time_derivs,",
"(t - Theta @ mn).T @ (t - Theta @ mn) - alpha",
"tau = torch.exp(model.s[:, 0])#torch.exp(-model.s[:, 0]) alpha = torch.exp(model.s[:, 1])#torch.exp(-model.s[:, 1])#torch.exp(model.s[:, 1]) #1 /",
"mask estimator_coeff_vectors = model.estimator_coeffs() l1_norm = torch.sum(torch.abs(torch.cat(model.constraint_coeffs(sparse=True, scaled=True), dim=1)), dim=0) progress(iteration, start_time, max_iterations,",
"@ mn).T @ (t - Theta @ mn) - alpha * mn.T @",
"* (M * torch.log(alpha) + N * torch.log(beta) - beta * (t -",
"optimizer, sparsity_scheduler, split: float = 0.8, log_dir: Optional[str] = None, max_iterations: int =",
"MSE_test = torch.mean((prediction_test - target_test)**2, dim=0) # loss per output Reg_test = torch.stack([torch.mean((dt",
"0])#torch.exp(-model.s[:, 0]) alpha = torch.exp(model.s[:, 1])#torch.exp(-model.s[:, 1])#torch.exp(model.s[:, 1]) #1 / MSE[0].data beta =",
"torch.split(data, [n_train, n_test], dim=0) target_train, target_test = torch.split(target, [n_train, n_test], dim=0) # Training",
"import Optional import torch import time import numpy as np from torch.distributions.studentT import",
"time.time() board = Tensorboard(log_dir) # initializing tb board # Splitting data, assumes data",
"= model.sparse_estimator(thetas, time_derivs) break board.close() def train_bayes_MSE_optim(model: DeepMoD, data: torch.Tensor, target: torch.Tensor, optimizer,",
"log_dir (Optional[str], optional): [description]. Defaults to None. max_iterations (int, optional): [description]. Defaults to",
"import BayesianRidge def train(model: DeepMoD, data: torch.Tensor, target: torch.Tensor, optimizer, sparsity_scheduler, reg_weight, split:",
"BayesianRidge(fit_intercept=False, compute_score=True, alpha_1=0, alpha_2=0, lambda_1=0, lambda_2=0) sk_reg.fit(thetas[0].cpu().detach().numpy(), time_derivs[0].cpu().detach().numpy()) model.s.data[:, 0] = torch.log(1 /",
"- theta @ coeff_vector)**2) for dt, theta, coeff_vector in zip(time_derivs_test, thetas_test, model.constraint_coeffs(scaled=False, sparse=True))])",
"2 * torch.log(tau), loss_reg) loss = torch.sum((N / 2 * tau * MSE",
"torch.sum(MSE_test + Reg_test) # ====================== Logging ======================= _ = model.sparse_estimator(thetas, time_derivs) # calculating",
"coordinates)) with torch.no_grad(): MSE_test = torch.mean((prediction_test - target_test)**2, dim=0) # loss per output",
"= 0.8, log_dir: Optional[str] = None, max_iterations: int = 10000, write_iterations: int ="
] |
[
"while stack: p = stack.pop() if not p.left and not p.right: out.append(p.val) if",
"Solution: def leafSimilar(self, root1: TreeNode, root2: TreeNode) -> bool: def get_leafs(root): if not",
"Definition for a binary tree node. # class TreeNode: # def __init__(self, x):",
"def get_leafs(root): if not root: return [] if not root.left and not root.right:",
"p.right: stack.append(p.right) p = p.right while p.left: stack.append(p.left) p = p.left return out",
"class TreeNode: # def __init__(self, x): # self.val = x # self.left =",
"self.right = None class Solution: def leafSimilar(self, root1: TreeNode, root2: TreeNode) -> bool:",
"__init__(self, x): # self.val = x # self.left = None # self.right =",
"self.val = x # self.left = None # self.right = None class Solution:",
"[root] out = [] while root.left: stack.append(root.left) root = root.left while stack: p",
"__________________________________________________________________________________________________ sample 24 ms submission # Definition for a binary tree node. #",
"TreeNode) -> bool: def get_leafs(root): if not root: return [] if not root.left",
"get_leafs(root1) == get_leafs(root2) __________________________________________________________________________________________________ sample 12908 kb submission # Definition for a binary",
"# self.right = None from collections import deque class Solution: def leafSimilar(self, root1:",
"= [root] out = [] while root.left: stack.append(root.left) root = root.left while stack:",
"self.getleaf(root1) == self.getleaf(root2) def getleaf(self, root): if not root: return [] stack =",
"x # self.left = None # self.right = None from collections import deque",
"stack = [root] out = [] while root.left: stack.append(root.left) root = root.left while",
"stack.append(p.right) p = p.right while p.left: stack.append(p.left) p = p.left return out __________________________________________________________________________________________________",
"if not root: return [] stack = [root] out = [] while root.left:",
"= None class Solution: def leafSimilar(self, root1: TreeNode, root2: TreeNode) -> bool: return",
"for a binary tree node. # class TreeNode: # def __init__(self, x): #",
"= root.left while stack: p = stack.pop() if not p.left and not p.right:",
"TreeNode) -> bool: return self.getleaf(root1) == self.getleaf(root2) def getleaf(self, root): if not root:",
"[root.val] return get_leafs(root.left) + get_leafs(root.right) return get_leafs(root1) == get_leafs(root2) __________________________________________________________________________________________________ sample 12908 kb",
"if not p.left and not p.right: out.append(p.val) if p.right: stack.append(p.right) p = p.right",
"submission # Definition for a binary tree node. # class TreeNode: # def",
"class Solution: def leafSimilar(self, root1: TreeNode, root2: TreeNode) -> bool: def get_leafs(root): if",
"# Definition for a binary tree node. # class TreeNode: # def __init__(self,",
"root.left and not root.right: return [root.val] return get_leafs(root.left) + get_leafs(root.right) return get_leafs(root1) ==",
"= None # self.right = None class Solution: def leafSimilar(self, root1: TreeNode, root2:",
"not root.left and not root.right: return [root.val] return get_leafs(root.left) + get_leafs(root.right) return get_leafs(root1)",
"get_leafs(root2) __________________________________________________________________________________________________ sample 12908 kb submission # Definition for a binary tree node.",
"and not root.right: return [root.val] return get_leafs(root.left) + get_leafs(root.right) return get_leafs(root1) == get_leafs(root2)",
"# class TreeNode: # def __init__(self, x): # self.val = x # self.left",
"a binary tree node. # class TreeNode: # def __init__(self, x): # self.val",
"[] if not root.left and not root.right: return [root.val] return get_leafs(root.left) + get_leafs(root.right)",
"return get_leafs(root1) == get_leafs(root2) __________________________________________________________________________________________________ sample 12908 kb submission # Definition for a",
"root): if not root: return [] stack = [root] out = [] while",
"self.getleaf(root2) def getleaf(self, root): if not root: return [] stack = [root] out",
"root: return [] if not root.left and not root.right: return [root.val] return get_leafs(root.left)",
"self.right = None from collections import deque class Solution: def leafSimilar(self, root1: TreeNode,",
"def leafSimilar(self, root1: TreeNode, root2: TreeNode) -> bool: def get_leafs(root): if not root:",
"root1: TreeNode, root2: TreeNode) -> bool: return self.getleaf(root1) == self.getleaf(root2) def getleaf(self, root):",
"getleaf(self, root): if not root: return [] stack = [root] out = []",
"None # self.right = None from collections import deque class Solution: def leafSimilar(self,",
"12908 kb submission # Definition for a binary tree node. # class TreeNode:",
"bool: return self.getleaf(root1) == self.getleaf(root2) def getleaf(self, root): if not root: return []",
"ms submission # Definition for a binary tree node. # class TreeNode: #",
"# self.left = None # self.right = None from collections import deque class",
"not p.left and not p.right: out.append(p.val) if p.right: stack.append(p.right) p = p.right while",
"node. # class TreeNode: # def __init__(self, x): # self.val = x #",
"-> bool: return self.getleaf(root1) == self.getleaf(root2) def getleaf(self, root): if not root: return",
"bool: def get_leafs(root): if not root: return [] if not root.left and not",
"= x # self.left = None # self.right = None class Solution: def",
"<filename>Python3/872.py __________________________________________________________________________________________________ sample 24 ms submission # Definition for a binary tree node.",
"root = root.left while stack: p = stack.pop() if not p.left and not",
"self.left = None # self.right = None class Solution: def leafSimilar(self, root1: TreeNode,",
"root2: TreeNode) -> bool: def get_leafs(root): if not root: return [] if not",
"p = stack.pop() if not p.left and not p.right: out.append(p.val) if p.right: stack.append(p.right)",
"root2: TreeNode) -> bool: return self.getleaf(root1) == self.getleaf(root2) def getleaf(self, root): if not",
"leafSimilar(self, root1: TreeNode, root2: TreeNode) -> bool: def get_leafs(root): if not root: return",
"not root.right: return [root.val] return get_leafs(root.left) + get_leafs(root.right) return get_leafs(root1) == get_leafs(root2) __________________________________________________________________________________________________",
"None class Solution: def leafSimilar(self, root1: TreeNode, root2: TreeNode) -> bool: return self.getleaf(root1)",
"return self.getleaf(root1) == self.getleaf(root2) def getleaf(self, root): if not root: return [] stack",
"stack.pop() if not p.left and not p.right: out.append(p.val) if p.right: stack.append(p.right) p =",
"root.right: return [root.val] return get_leafs(root.left) + get_leafs(root.right) return get_leafs(root1) == get_leafs(root2) __________________________________________________________________________________________________ sample",
"self.val = x # self.left = None # self.right = None from collections",
"TreeNode: # def __init__(self, x): # self.val = x # self.left = None",
"__________________________________________________________________________________________________ sample 12908 kb submission # Definition for a binary tree node. #",
"collections import deque class Solution: def leafSimilar(self, root1: TreeNode, root2: TreeNode) -> bool:",
"get_leafs(root.left) + get_leafs(root.right) return get_leafs(root1) == get_leafs(root2) __________________________________________________________________________________________________ sample 12908 kb submission #",
"root1: TreeNode, root2: TreeNode) -> bool: def get_leafs(root): if not root: return []",
"def leafSimilar(self, root1: TreeNode, root2: TreeNode) -> bool: return self.getleaf(root1) == self.getleaf(root2) def",
"not p.right: out.append(p.val) if p.right: stack.append(p.right) p = p.right while p.left: stack.append(p.left) p",
"not root: return [] stack = [root] out = [] while root.left: stack.append(root.left)",
"x # self.left = None # self.right = None class Solution: def leafSimilar(self,",
"out = [] while root.left: stack.append(root.left) root = root.left while stack: p =",
"binary tree node. # class TreeNode: # def __init__(self, x): # self.val =",
"# self.val = x # self.left = None # self.right = None class",
"tree node. # class TreeNode: # def __init__(self, x): # self.val = x",
"while root.left: stack.append(root.left) root = root.left while stack: p = stack.pop() if not",
"# self.right = None class Solution: def leafSimilar(self, root1: TreeNode, root2: TreeNode) ->",
"# def __init__(self, x): # self.val = x # self.left = None #",
"kb submission # Definition for a binary tree node. # class TreeNode: #",
"== self.getleaf(root2) def getleaf(self, root): if not root: return [] stack = [root]",
"stack: p = stack.pop() if not p.left and not p.right: out.append(p.val) if p.right:",
"24 ms submission # Definition for a binary tree node. # class TreeNode:",
"TreeNode, root2: TreeNode) -> bool: def get_leafs(root): if not root: return [] if",
"import deque class Solution: def leafSimilar(self, root1: TreeNode, root2: TreeNode) -> bool: def",
"return [root.val] return get_leafs(root.left) + get_leafs(root.right) return get_leafs(root1) == get_leafs(root2) __________________________________________________________________________________________________ sample 12908",
"= None from collections import deque class Solution: def leafSimilar(self, root1: TreeNode, root2:",
"# self.left = None # self.right = None class Solution: def leafSimilar(self, root1:",
"self.left = None # self.right = None from collections import deque class Solution:",
"== get_leafs(root2) __________________________________________________________________________________________________ sample 12908 kb submission # Definition for a binary tree",
"def getleaf(self, root): if not root: return [] stack = [root] out =",
"leafSimilar(self, root1: TreeNode, root2: TreeNode) -> bool: return self.getleaf(root1) == self.getleaf(root2) def getleaf(self,",
"[] stack = [root] out = [] while root.left: stack.append(root.left) root = root.left",
"class Solution: def leafSimilar(self, root1: TreeNode, root2: TreeNode) -> bool: return self.getleaf(root1) ==",
"None from collections import deque class Solution: def leafSimilar(self, root1: TreeNode, root2: TreeNode)",
"return get_leafs(root.left) + get_leafs(root.right) return get_leafs(root1) == get_leafs(root2) __________________________________________________________________________________________________ sample 12908 kb submission",
"+ get_leafs(root.right) return get_leafs(root1) == get_leafs(root2) __________________________________________________________________________________________________ sample 12908 kb submission # Definition",
"p.right: out.append(p.val) if p.right: stack.append(p.right) p = p.right while p.left: stack.append(p.left) p =",
"None # self.right = None class Solution: def leafSimilar(self, root1: TreeNode, root2: TreeNode)",
"[] while root.left: stack.append(root.left) root = root.left while stack: p = stack.pop() if",
"return [] stack = [root] out = [] while root.left: stack.append(root.left) root =",
"= [] while root.left: stack.append(root.left) root = root.left while stack: p = stack.pop()",
"and not p.right: out.append(p.val) if p.right: stack.append(p.right) p = p.right while p.left: stack.append(p.left)",
"if p.right: stack.append(p.right) p = p.right while p.left: stack.append(p.left) p = p.left return",
"Solution: def leafSimilar(self, root1: TreeNode, root2: TreeNode) -> bool: return self.getleaf(root1) == self.getleaf(root2)",
"if not root.left and not root.right: return [root.val] return get_leafs(root.left) + get_leafs(root.right) return",
"sample 12908 kb submission # Definition for a binary tree node. # class",
"sample 24 ms submission # Definition for a binary tree node. # class",
"x): # self.val = x # self.left = None # self.right = None",
"TreeNode, root2: TreeNode) -> bool: return self.getleaf(root1) == self.getleaf(root2) def getleaf(self, root): if",
"get_leafs(root): if not root: return [] if not root.left and not root.right: return",
"root: return [] stack = [root] out = [] while root.left: stack.append(root.left) root",
"deque class Solution: def leafSimilar(self, root1: TreeNode, root2: TreeNode) -> bool: def get_leafs(root):",
"if not root: return [] if not root.left and not root.right: return [root.val]",
"p.left and not p.right: out.append(p.val) if p.right: stack.append(p.right) p = p.right while p.left:",
"out.append(p.val) if p.right: stack.append(p.right) p = p.right while p.left: stack.append(p.left) p = p.left",
"root.left: stack.append(root.left) root = root.left while stack: p = stack.pop() if not p.left",
"from collections import deque class Solution: def leafSimilar(self, root1: TreeNode, root2: TreeNode) ->",
"-> bool: def get_leafs(root): if not root: return [] if not root.left and",
"not root: return [] if not root.left and not root.right: return [root.val] return",
"= None # self.right = None from collections import deque class Solution: def",
"root.left while stack: p = stack.pop() if not p.left and not p.right: out.append(p.val)",
"= stack.pop() if not p.left and not p.right: out.append(p.val) if p.right: stack.append(p.right) p",
"def __init__(self, x): # self.val = x # self.left = None # self.right",
"# self.val = x # self.left = None # self.right = None from",
"return [] if not root.left and not root.right: return [root.val] return get_leafs(root.left) +",
"= x # self.left = None # self.right = None from collections import",
"get_leafs(root.right) return get_leafs(root1) == get_leafs(root2) __________________________________________________________________________________________________ sample 12908 kb submission # Definition for",
"stack.append(root.left) root = root.left while stack: p = stack.pop() if not p.left and"
] |
[
"[] dline.tail_part = \"\" else: #legacy config syntax dline.head_part = head_tokens[0] tail_tokens =",
"(len(simulation_runs))) return simulation_runs def write_sim_data(args, lines, hash, target_file): full_folder_path = check_and_create_folder(args['outdir'], hash) write_ini(full_folder_path,",
"os.path.exists(full_path): os.remove(full_path) f = open (full_path, \"a\") f.write(script) f.close() file_handle = os.stat(full_path) os.chmod(full_path,",
"import Logger class DynamicLine(): # TODO better name? def __init__(self): self.head_part = \"\"",
"= out_dir + hash + \"/\" run.executable_path = out_dir + hash + \"/\"",
"dline.dynamic_part = dynamic_parts dline.tail_part = '}' + tail_tokens[1] else: dline.head_part = line dline.dynamic_part",
"lines.append(config_line) with open(ini_file) as input_file: for row in input_file: if '{' in row.split('#')[0]:",
"= line dline.dynamic_part = [] dline.tail_part = \"\" else: #legacy config syntax dline.head_part",
"(T) line = create_dynamic_line(row.split('#')[0] + '\\n') dynamic_lines.append(line) lines.append(line) else: lines.append(row) all_dynamic_lines = [",
"args['inifile'] out_dir = args['outdir'] config = args['configName'] lines = [] dynamic_lines = []",
"for line in lines] return hash.hexdigest() def write_additional_files(args, folder_path): files = args['additionalFiles'].split() for",
"hash = create_file_hash(lines) target_file = \"run.sh\" write_sim_data(args, lines, hash, target_file) run.hash = hash",
"0] for perm in itertools.product(*all_dynamic_lines): run = SimulationRun() for idx, val in enumerate(perm):",
"hashlib.md5() [hash.update(str(line).encode('utf-8')) for line in lines] return hash.hexdigest() def write_additional_files(args, folder_path): files =",
"= args['inifile'] out_dir = args['outdir'] config = args['configName'] lines = [] dynamic_lines =",
"self.current_print_representation, self.tail_part) def __str__(self): return self.head_part + self.current_print_representation + self.tail_part def __repr__(self): return",
"idx, val in enumerate(perm): dynamic_lines[idx].current_print_representation = val #run.parameters.append((dynamic_lines[idx].head_part.split()[0], val.strip())) run.parameters[dynamic_lines[idx].head_part.split()[0]] = val.strip() hash",
"write_ini(folder_path, file): full_path = folder_path + \"/omnetpp.ini\" if os.path.exists(full_path): os.remove(full_path) f = open",
"assignemt[1].split(\",\") dynamic_parts[-1] = dynamic_parts[-1].split('}',1)[0] dline.dynamic_part = dynamic_parts dline.tail_part = '}' + tail_tokens[1] else:",
"TODO better name? def __init__(self): self.head_part = \"\" self.dynamic_part = \"\" self.tail_part =",
"config_line = \"# This is config %s\\n\" % (config) lines.append(config_line) with open(ini_file) as",
"+ \"/\" run.executable_path = out_dir + hash + \"/\" + target_file run.config_name= config",
"-n $DIR/inet:$DIR/../tutorials:$DIR/../examples:$DIR/../examples:$TARGET/ $TARGET/omnetpp.ini > /dev/null rc=$? if [ $rc -gt 0 ]; then",
"run = SimulationRun() for idx, val in enumerate(perm): dynamic_lines[idx].current_print_representation = val #run.parameters.append((dynamic_lines[idx].head_part.split()[0], val.strip()))",
"simulation_runs = {} config_line = \"# This is config %s\\n\" % (config) lines.append(config_line)",
"file_handle = os.stat(full_path) os.chmod(full_path, file_handle.st_mode | stat.S_IEXEC) def create_dynamic_line(line): dline = DynamicLine() head_tokens",
"for line in dynamic_lines] run.path = out_dir + hash + \"/\" run.executable_path =",
"+ \"/\" + target_file run.config_name= config simulation_runs[hash] = run Logger.info(\"Generated %s simulation configs.\"",
"assignemt[0] + \" = \"# puts the variable name at the beginning dynamic_parts",
"then exit $rc fi \"\"\" % (inet_dir[:-1], target_folder, config_name, omnet_exec) full_path = target_folder",
"f = open (full_path, \"a\") for line in file: f.write(str(line)) f.close() def check_and_create_folder(base_path,",
"target_folder, target_file): omnet_exec = args['omnetdir'] inet_dir = args['inetdir'] config_name = args['configName'] script =",
"lines, hash, target_file): full_folder_path = check_and_create_folder(args['outdir'], hash) write_ini(full_folder_path, lines) create_bash_script(args, full_folder_path,target_file) write_additional_files(args, full_folder_path)",
"args['configName'] lines = [] dynamic_lines = [] simulation_runs = {} config_line = \"#",
"self.head_part + self.current_print_representation + self.tail_part def __repr__(self): return self.__str__() def demux_and_write_simulation(args): ini_file =",
"= create_dynamic_line(row.split('#')[0] + '\\n') dynamic_lines.append(line) lines.append(line) else: lines.append(row) all_dynamic_lines = [ line.dynamic_part for",
"line in file: f.write(str(line)) f.close() def check_and_create_folder(base_path, folder_name): full_path = base_path + folder_name",
"+ tail_tokens[1] else: dline.head_part = line dline.dynamic_part = [] dline.tail_part = \"\" else:",
"= check_and_create_folder(args['outdir'], hash) write_ini(full_folder_path, lines) create_bash_script(args, full_folder_path,target_file) write_additional_files(args, full_folder_path) def create_file_hash(lines): hash =",
"= open (full_path, \"a\") f.write(script) f.close() file_handle = os.stat(full_path) os.chmod(full_path, file_handle.st_mode | stat.S_IEXEC)",
"'=' in head_tokens[1]): #assignment assignemt = head_tokens[1].split('=') dline.head_part += assignemt[0] + \" =",
"in row.split('#')[0]: # ignore comments (T) line = create_dynamic_line(row.split('#')[0] + '\\n') dynamic_lines.append(line) lines.append(line)",
"def demux_and_write_simulation(args): ini_file = args['inifile'] out_dir = args['outdir'] config = args['configName'] lines =",
"%s -u Cmdenv -l $DIR/INET -c $CONFIG -n $DIR/inet:$DIR/../tutorials:$DIR/../examples:$DIR/../examples:$TARGET/ $TARGET/omnetpp.ini > /dev/null rc=$?",
"= dynamic_parts[-1].split('}',1)[0] dline.dynamic_part = dynamic_parts dline.tail_part = '}' + tail_tokens[1] else: dline.head_part =",
"fi \"\"\" % (inet_dir[:-1], target_folder, config_name, omnet_exec) full_path = target_folder + \"/\" +",
"import SimulationRun from neurogenesis.util import Logger class DynamicLine(): # TODO better name? def",
"self.tail_part def __repr__(self): return self.__str__() def demux_and_write_simulation(args): ini_file = args['inifile'] out_dir = args['outdir']",
"check_and_create_folder(args['outdir'], hash) write_ini(full_folder_path, lines) create_bash_script(args, full_folder_path,target_file) write_additional_files(args, full_folder_path) def create_file_hash(lines): hash = hashlib.md5()",
"hash = hashlib.md5() [hash.update(str(line).encode('utf-8')) for line in lines] return hash.hexdigest() def write_additional_files(args, folder_path):",
"in dynamic_lines if len(line.dynamic_part) > 0] for perm in itertools.product(*all_dynamic_lines): run = SimulationRun()",
"create_file_hash(lines): hash = hashlib.md5() [hash.update(str(line).encode('utf-8')) for line in lines] return hash.hexdigest() def write_additional_files(args,",
"+= assignemt[0] + \" = \"# puts the variable name at the beginning",
"if os.path.exists(full_path): os.remove(full_path) f = open (full_path, \"a\") return f def create_bash_script(args, target_folder,",
"f.close() file_handle = os.stat(full_path) os.chmod(full_path, file_handle.st_mode | stat.S_IEXEC) def create_dynamic_line(line): dline = DynamicLine()",
"open (full_path, \"a\") f.write(script) f.close() file_handle = os.stat(full_path) os.chmod(full_path, file_handle.st_mode | stat.S_IEXEC) def",
"os import stat from neurogenesis.base import SimulationRun from neurogenesis.util import Logger class DynamicLine():",
"| stat.S_IEXEC) def create_dynamic_line(line): dline = DynamicLine() head_tokens = line.split('{',1) if head_tokens[0][-1] ==",
"= SimulationRun() for idx, val in enumerate(perm): dynamic_lines[idx].current_print_representation = val #run.parameters.append((dynamic_lines[idx].head_part.split()[0], val.strip())) run.parameters[dynamic_lines[idx].head_part.split()[0]]",
"= open (full_path, \"a\") return f def create_bash_script(args, target_folder, target_file): omnet_exec = args['omnetdir']",
"= folder_path + \"/omnetpp.ini\" if os.path.exists(full_path): os.remove(full_path) f = open (full_path, \"a\") for",
"target_file run.config_name= config simulation_runs[hash] = run Logger.info(\"Generated %s simulation configs.\" % (len(simulation_runs))) return",
"\"/\" run.executable_path = out_dir + hash + \"/\" + target_file run.config_name= config simulation_runs[hash]",
"os.chmod(full_path, file_handle.st_mode | stat.S_IEXEC) def create_dynamic_line(line): dline = DynamicLine() head_tokens = line.split('{',1) if",
"os.makedirs(full_path) return full_path def check_and_create_file(full_path): if os.path.exists(full_path): os.remove(full_path) f = open (full_path, \"a\")",
"open(file) as input_file: for row in input_file: f.write(row) f.close() input_file.close() def write_ini(folder_path, file):",
"write_ini(full_folder_path, lines) create_bash_script(args, full_folder_path,target_file) write_additional_files(args, full_folder_path) def create_file_hash(lines): hash = hashlib.md5() [hash.update(str(line).encode('utf-8')) for",
"dynamic_parts dline.tail_part = '}' + tail_tokens[1] else: dline.head_part = line dline.dynamic_part = []",
"def write_sim_data(args, lines, hash, target_file): full_folder_path = check_and_create_folder(args['outdir'], hash) write_ini(full_folder_path, lines) create_bash_script(args, full_folder_path,target_file)",
"input_file.close() def write_ini(folder_path, file): full_path = folder_path + \"/omnetpp.ini\" if os.path.exists(full_path): os.remove(full_path) f",
"exit $rc fi \"\"\" % (inet_dir[:-1], target_folder, config_name, omnet_exec) full_path = target_folder +",
"__init__(self): self.head_part = \"\" self.dynamic_part = \"\" self.tail_part = \"\" self.current_print_representation = \"\"",
"import os import stat from neurogenesis.base import SimulationRun from neurogenesis.util import Logger class",
"script = \"\"\" #!/bin/bash DIR=%s TARGET=%s CONFIG=%s cd $DIR %s -u Cmdenv -l",
"[] simulation_runs = {} config_line = \"# This is config %s\\n\" % (config)",
"check_and_create_file(new_file_path) with open(file) as input_file: for row in input_file: f.write(row) f.close() input_file.close() def",
"= open (full_path, \"a\") for line in file: f.write(str(line)) f.close() def check_and_create_folder(base_path, folder_name):",
"full_path = folder_path + \"/omnetpp.ini\" if os.path.exists(full_path): os.remove(full_path) f = open (full_path, \"a\")",
"+ '\\n') dynamic_lines.append(line) lines.append(line) else: lines.append(row) all_dynamic_lines = [ line.dynamic_part for line in",
"line in dynamic_lines] run.path = out_dir + hash + \"/\" run.executable_path = out_dir",
"\"a\") return f def create_bash_script(args, target_folder, target_file): omnet_exec = args['omnetdir'] inet_dir = args['inetdir']",
"Cmdenv -l $DIR/INET -c $CONFIG -n $DIR/inet:$DIR/../tutorials:$DIR/../examples:$DIR/../examples:$TARGET/ $TARGET/omnetpp.ini > /dev/null rc=$? if [",
"with open(file) as input_file: for row in input_file: f.write(row) f.close() input_file.close() def write_ini(folder_path,",
"os.remove(full_path) f = open (full_path, \"a\") for line in file: f.write(str(line)) f.close() def",
"+ target_file if os.path.exists(full_path): os.remove(full_path) f = open (full_path, \"a\") f.write(script) f.close() file_handle",
"for row in input_file: f.write(row) f.close() input_file.close() def write_ini(folder_path, file): full_path = folder_path",
"enumerate(perm): dynamic_lines[idx].current_print_representation = val #run.parameters.append((dynamic_lines[idx].head_part.split()[0], val.strip())) run.parameters[dynamic_lines[idx].head_part.split()[0]] = val.strip() hash = create_file_hash(lines) target_file",
"CONFIG=%s cd $DIR %s -u Cmdenv -l $DIR/INET -c $CONFIG -n $DIR/inet:$DIR/../tutorials:$DIR/../examples:$DIR/../examples:$TARGET/ $TARGET/omnetpp.ini",
"name at the beginning dynamic_parts = assignemt[1].split(\",\") dynamic_parts[-1] = dynamic_parts[-1].split('}',1)[0] dline.dynamic_part = dynamic_parts",
"lines] return hash.hexdigest() def write_additional_files(args, folder_path): files = args['additionalFiles'].split() for file in files:",
"run.path = out_dir + hash + \"/\" run.executable_path = out_dir + hash +",
"return hash.hexdigest() def write_additional_files(args, folder_path): files = args['additionalFiles'].split() for file in files: base_name",
"(self.head_part, self.current_print_representation, self.tail_part) def __str__(self): return self.head_part + self.current_print_representation + self.tail_part def __repr__(self):",
"create_bash_script(args, full_folder_path,target_file) write_additional_files(args, full_folder_path) def create_file_hash(lines): hash = hashlib.md5() [hash.update(str(line).encode('utf-8')) for line in",
"= [ line.dynamic_part for line in dynamic_lines if len(line.dynamic_part) > 0] for perm",
"ignore comments (T) line = create_dynamic_line(row.split('#')[0] + '\\n') dynamic_lines.append(line) lines.append(line) else: lines.append(row) all_dynamic_lines",
"file in files: base_name = os.path.basename(file) new_file_path = folder_path + '/'+ base_name f",
"config_name, omnet_exec) full_path = target_folder + \"/\" + target_file if os.path.exists(full_path): os.remove(full_path) f",
"file): full_path = folder_path + \"/omnetpp.ini\" if os.path.exists(full_path): os.remove(full_path) f = open (full_path,",
"all_dynamic_lines = [ line.dynamic_part for line in dynamic_lines if len(line.dynamic_part) > 0] for",
"f = open (full_path, \"a\") return f def create_bash_script(args, target_folder, target_file): omnet_exec =",
"return (self.head_part, self.current_print_representation, self.tail_part) def __str__(self): return self.head_part + self.current_print_representation + self.tail_part def",
"def check_and_create_folder(base_path, folder_name): full_path = base_path + folder_name if not os.path.exists(full_path): os.makedirs(full_path) return",
"lines = [] dynamic_lines = [] simulation_runs = {} config_line = \"# This",
"= {} def get_current_value_tuple(self): return (self.head_part, self.current_print_representation, self.tail_part) def __str__(self): return self.head_part +",
"This is config %s\\n\" % (config) lines.append(config_line) with open(ini_file) as input_file: for row",
"line = create_dynamic_line(row.split('#')[0] + '\\n') dynamic_lines.append(line) lines.append(line) else: lines.append(row) all_dynamic_lines = [ line.dynamic_part",
"target_file = \"run.sh\" write_sim_data(args, lines, hash, target_file) run.hash = hash [run.config.append(line.get_current_value_tuple()) for line",
"full_path def check_and_create_file(full_path): if os.path.exists(full_path): os.remove(full_path) f = open (full_path, \"a\") return f",
"self.current_print_representation + self.tail_part def __repr__(self): return self.__str__() def demux_and_write_simulation(args): ini_file = args['inifile'] out_dir",
"import hashlib import os import stat from neurogenesis.base import SimulationRun from neurogenesis.util import",
"variable name at the beginning dynamic_parts = assignemt[1].split(\",\") dynamic_parts[-1] = dynamic_parts[-1].split('}',1)[0] dline.dynamic_part =",
"f.write(row) f.close() input_file.close() def write_ini(folder_path, file): full_path = folder_path + \"/omnetpp.ini\" if os.path.exists(full_path):",
"= folder_path + '/'+ base_name f = check_and_create_file(new_file_path) with open(file) as input_file: for",
"%s simulation configs.\" % (len(simulation_runs))) return simulation_runs def write_sim_data(args, lines, hash, target_file): full_folder_path",
"dynamic_parts[-1].split('}',1)[0] dline.dynamic_part = dynamic_parts dline.tail_part = '}' + tail_tokens[1] else: dline.head_part = line",
"files = args['additionalFiles'].split() for file in files: base_name = os.path.basename(file) new_file_path = folder_path",
"for line in dynamic_lines if len(line.dynamic_part) > 0] for perm in itertools.product(*all_dynamic_lines): run",
"as input_file: for row in input_file: if '{' in row.split('#')[0]: # ignore comments",
"create_dynamic_line(line): dline = DynamicLine() head_tokens = line.split('{',1) if head_tokens[0][-1] == \"$\": dline.head_part =",
"\"\" self.current_print_representation = \"\" self.parameter_representation = {} def get_current_value_tuple(self): return (self.head_part, self.current_print_representation, self.tail_part)",
"= \"\" self.tail_part = \"\" self.current_print_representation = \"\" self.parameter_representation = {} def get_current_value_tuple(self):",
"class DynamicLine(): # TODO better name? def __init__(self): self.head_part = \"\" self.dynamic_part =",
"__str__(self): return self.head_part + self.current_print_representation + self.tail_part def __repr__(self): return self.__str__() def demux_and_write_simulation(args):",
"+ self.tail_part def __repr__(self): return self.__str__() def demux_and_write_simulation(args): ini_file = args['inifile'] out_dir =",
"= head_tokens[1].split('=') dline.head_part += assignemt[0] + \" = \"# puts the variable name",
"$DIR %s -u Cmdenv -l $DIR/INET -c $CONFIG -n $DIR/inet:$DIR/../tutorials:$DIR/../examples:$DIR/../examples:$TARGET/ $TARGET/omnetpp.ini > /dev/null",
"create_file_hash(lines) target_file = \"run.sh\" write_sim_data(args, lines, hash, target_file) run.hash = hash [run.config.append(line.get_current_value_tuple()) for",
"= \"\" self.current_print_representation = \"\" self.parameter_representation = {} def get_current_value_tuple(self): return (self.head_part, self.current_print_representation,",
"file_handle.st_mode | stat.S_IEXEC) def create_dynamic_line(line): dline = DynamicLine() head_tokens = line.split('{',1) if head_tokens[0][-1]",
"simulation_runs def write_sim_data(args, lines, hash, target_file): full_folder_path = check_and_create_folder(args['outdir'], hash) write_ini(full_folder_path, lines) create_bash_script(args,",
"self.dynamic_part = \"\" self.tail_part = \"\" self.current_print_representation = \"\" self.parameter_representation = {} def",
"in files: base_name = os.path.basename(file) new_file_path = folder_path + '/'+ base_name f =",
"folder_path + '/'+ base_name f = check_and_create_file(new_file_path) with open(file) as input_file: for row",
"folder_name): full_path = base_path + folder_name if not os.path.exists(full_path): os.makedirs(full_path) return full_path def",
"= hash [run.config.append(line.get_current_value_tuple()) for line in dynamic_lines] run.path = out_dir + hash +",
"hashlib import os import stat from neurogenesis.base import SimulationRun from neurogenesis.util import Logger",
"in input_file: if '{' in row.split('#')[0]: # ignore comments (T) line = create_dynamic_line(row.split('#')[0]",
"= check_and_create_file(new_file_path) with open(file) as input_file: for row in input_file: f.write(row) f.close() input_file.close()",
"name? def __init__(self): self.head_part = \"\" self.dynamic_part = \"\" self.tail_part = \"\" self.current_print_representation",
"def get_current_value_tuple(self): return (self.head_part, self.current_print_representation, self.tail_part) def __str__(self): return self.head_part + self.current_print_representation +",
"return full_path def check_and_create_file(full_path): if os.path.exists(full_path): os.remove(full_path) f = open (full_path, \"a\") return",
"run.parameters[dynamic_lines[idx].head_part.split()[0]] = val.strip() hash = create_file_hash(lines) target_file = \"run.sh\" write_sim_data(args, lines, hash, target_file)",
"at the beginning dynamic_parts = assignemt[1].split(\",\") dynamic_parts[-1] = dynamic_parts[-1].split('}',1)[0] dline.dynamic_part = dynamic_parts dline.tail_part",
"= \"\" self.parameter_representation = {} def get_current_value_tuple(self): return (self.head_part, self.current_print_representation, self.tail_part) def __str__(self):",
"is config %s\\n\" % (config) lines.append(config_line) with open(ini_file) as input_file: for row in",
"% (inet_dir[:-1], target_folder, config_name, omnet_exec) full_path = target_folder + \"/\" + target_file if",
"head_tokens[0] + '{' tail_tokens = head_tokens[1].split('}',1) if( '=' in head_tokens[1]): #assignment assignemt =",
"(full_path, \"a\") for line in file: f.write(str(line)) f.close() def check_and_create_folder(base_path, folder_name): full_path =",
"omnet_exec) full_path = target_folder + \"/\" + target_file if os.path.exists(full_path): os.remove(full_path) f =",
"#run.parameters.append((dynamic_lines[idx].head_part.split()[0], val.strip())) run.parameters[dynamic_lines[idx].head_part.split()[0]] = val.strip() hash = create_file_hash(lines) target_file = \"run.sh\" write_sim_data(args, lines,",
"open(ini_file) as input_file: for row in input_file: if '{' in row.split('#')[0]: # ignore",
"in itertools.product(*all_dynamic_lines): run = SimulationRun() for idx, val in enumerate(perm): dynamic_lines[idx].current_print_representation = val",
"+ \"/\" + target_file if os.path.exists(full_path): os.remove(full_path) f = open (full_path, \"a\") f.write(script)",
"hash, target_file) run.hash = hash [run.config.append(line.get_current_value_tuple()) for line in dynamic_lines] run.path = out_dir",
"0 ]; then exit $rc fi \"\"\" % (inet_dir[:-1], target_folder, config_name, omnet_exec) full_path",
"f def create_bash_script(args, target_folder, target_file): omnet_exec = args['omnetdir'] inet_dir = args['inetdir'] config_name =",
"\"# puts the variable name at the beginning dynamic_parts = assignemt[1].split(\",\") dynamic_parts[-1] =",
"def create_file_hash(lines): hash = hashlib.md5() [hash.update(str(line).encode('utf-8')) for line in lines] return hash.hexdigest() def",
"= '}' + tail_tokens[1] else: dline.head_part = line dline.dynamic_part = [] dline.tail_part =",
"len(line.dynamic_part) > 0] for perm in itertools.product(*all_dynamic_lines): run = SimulationRun() for idx, val",
"'\\n') dynamic_lines.append(line) lines.append(line) else: lines.append(row) all_dynamic_lines = [ line.dynamic_part for line in dynamic_lines",
"folder_path + \"/omnetpp.ini\" if os.path.exists(full_path): os.remove(full_path) f = open (full_path, \"a\") for line",
"+ folder_name if not os.path.exists(full_path): os.makedirs(full_path) return full_path def check_and_create_file(full_path): if os.path.exists(full_path): os.remove(full_path)",
"row in input_file: f.write(row) f.close() input_file.close() def write_ini(folder_path, file): full_path = folder_path +",
"f.close() input_file.close() def write_ini(folder_path, file): full_path = folder_path + \"/omnetpp.ini\" if os.path.exists(full_path): os.remove(full_path)",
"line dline.dynamic_part = [] dline.tail_part = \"\" else: #legacy config syntax dline.head_part =",
"-u Cmdenv -l $DIR/INET -c $CONFIG -n $DIR/inet:$DIR/../tutorials:$DIR/../examples:$DIR/../examples:$TARGET/ $TARGET/omnetpp.ini > /dev/null rc=$? if",
"= \"\" self.dynamic_part = \"\" self.tail_part = \"\" self.current_print_representation = \"\" self.parameter_representation =",
"dynamic_parts[-1] = dynamic_parts[-1].split('}',1)[0] dline.dynamic_part = dynamic_parts dline.tail_part = '}' + tail_tokens[1] else: dline.head_part",
"not os.path.exists(full_path): os.makedirs(full_path) return full_path def check_and_create_file(full_path): if os.path.exists(full_path): os.remove(full_path) f = open",
"-gt 0 ]; then exit $rc fi \"\"\" % (inet_dir[:-1], target_folder, config_name, omnet_exec)",
"dline.tail_part = '}' + tail_tokens[1] else: dline.head_part = line dline.dynamic_part = [] dline.tail_part",
"itertools import hashlib import os import stat from neurogenesis.base import SimulationRun from neurogenesis.util",
"dynamic_lines = [] simulation_runs = {} config_line = \"# This is config %s\\n\"",
"demux_and_write_simulation(args): ini_file = args['inifile'] out_dir = args['outdir'] config = args['configName'] lines = []",
"in head_tokens[1]): #assignment assignemt = head_tokens[1].split('=') dline.head_part += assignemt[0] + \" = \"#",
"head_tokens[1].split('}',1) if( '=' in head_tokens[1]): #assignment assignemt = head_tokens[1].split('=') dline.head_part += assignemt[0] +",
"= run Logger.info(\"Generated %s simulation configs.\" % (len(simulation_runs))) return simulation_runs def write_sim_data(args, lines,",
"val.strip() hash = create_file_hash(lines) target_file = \"run.sh\" write_sim_data(args, lines, hash, target_file) run.hash =",
"f.write(script) f.close() file_handle = os.stat(full_path) os.chmod(full_path, file_handle.st_mode | stat.S_IEXEC) def create_dynamic_line(line): dline =",
"if( '=' in head_tokens[1]): #assignment assignemt = head_tokens[1].split('=') dline.head_part += assignemt[0] + \"",
"= create_file_hash(lines) target_file = \"run.sh\" write_sim_data(args, lines, hash, target_file) run.hash = hash [run.config.append(line.get_current_value_tuple())",
"+ '{' tail_tokens = head_tokens[1].split('}',1) if( '=' in head_tokens[1]): #assignment assignemt = head_tokens[1].split('=')",
"#assignment assignemt = head_tokens[1].split('=') dline.head_part += assignemt[0] + \" = \"# puts the",
"args['outdir'] config = args['configName'] lines = [] dynamic_lines = [] simulation_runs = {}",
"\"/\" + target_file run.config_name= config simulation_runs[hash] = run Logger.info(\"Generated %s simulation configs.\" %",
"[hash.update(str(line).encode('utf-8')) for line in lines] return hash.hexdigest() def write_additional_files(args, folder_path): files = args['additionalFiles'].split()",
"# TODO better name? def __init__(self): self.head_part = \"\" self.dynamic_part = \"\" self.tail_part",
"open (full_path, \"a\") for line in file: f.write(str(line)) f.close() def check_and_create_folder(base_path, folder_name): full_path",
"\"\" self.dynamic_part = \"\" self.tail_part = \"\" self.current_print_representation = \"\" self.parameter_representation = {}",
"val #run.parameters.append((dynamic_lines[idx].head_part.split()[0], val.strip())) run.parameters[dynamic_lines[idx].head_part.split()[0]] = val.strip() hash = create_file_hash(lines) target_file = \"run.sh\" write_sim_data(args,",
"\"# This is config %s\\n\" % (config) lines.append(config_line) with open(ini_file) as input_file: for",
"out_dir + hash + \"/\" + target_file run.config_name= config simulation_runs[hash] = run Logger.info(\"Generated",
"== \"$\": dline.head_part = head_tokens[0] + '{' tail_tokens = head_tokens[1].split('}',1) if( '=' in",
"dynamic_parts = assignemt[1].split(\",\") dynamic_parts[-1] = dynamic_parts[-1].split('}',1)[0] dline.dynamic_part = dynamic_parts dline.tail_part = '}' +",
"{} def get_current_value_tuple(self): return (self.head_part, self.current_print_representation, self.tail_part) def __str__(self): return self.head_part + self.current_print_representation",
"os.stat(full_path) os.chmod(full_path, file_handle.st_mode | stat.S_IEXEC) def create_dynamic_line(line): dline = DynamicLine() head_tokens = line.split('{',1)",
"= val #run.parameters.append((dynamic_lines[idx].head_part.split()[0], val.strip())) run.parameters[dynamic_lines[idx].head_part.split()[0]] = val.strip() hash = create_file_hash(lines) target_file = \"run.sh\"",
"line.dynamic_part for line in dynamic_lines if len(line.dynamic_part) > 0] for perm in itertools.product(*all_dynamic_lines):",
"hash + \"/\" run.executable_path = out_dir + hash + \"/\" + target_file run.config_name=",
"lines) create_bash_script(args, full_folder_path,target_file) write_additional_files(args, full_folder_path) def create_file_hash(lines): hash = hashlib.md5() [hash.update(str(line).encode('utf-8')) for line",
"DynamicLine(): # TODO better name? def __init__(self): self.head_part = \"\" self.dynamic_part = \"\"",
"comments (T) line = create_dynamic_line(row.split('#')[0] + '\\n') dynamic_lines.append(line) lines.append(line) else: lines.append(row) all_dynamic_lines =",
"itertools.product(*all_dynamic_lines): run = SimulationRun() for idx, val in enumerate(perm): dynamic_lines[idx].current_print_representation = val #run.parameters.append((dynamic_lines[idx].head_part.split()[0],",
"file: f.write(str(line)) f.close() def check_and_create_folder(base_path, folder_name): full_path = base_path + folder_name if not",
"= target_folder + \"/\" + target_file if os.path.exists(full_path): os.remove(full_path) f = open (full_path,",
"in enumerate(perm): dynamic_lines[idx].current_print_representation = val #run.parameters.append((dynamic_lines[idx].head_part.split()[0], val.strip())) run.parameters[dynamic_lines[idx].head_part.split()[0]] = val.strip() hash = create_file_hash(lines)",
"if os.path.exists(full_path): os.remove(full_path) f = open (full_path, \"a\") for line in file: f.write(str(line))",
"% (len(simulation_runs))) return simulation_runs def write_sim_data(args, lines, hash, target_file): full_folder_path = check_and_create_folder(args['outdir'], hash)",
"hash) write_ini(full_folder_path, lines) create_bash_script(args, full_folder_path,target_file) write_additional_files(args, full_folder_path) def create_file_hash(lines): hash = hashlib.md5() [hash.update(str(line).encode('utf-8'))",
"dline.head_part = head_tokens[0] + '{' tail_tokens = head_tokens[1].split('}',1) if( '=' in head_tokens[1]): #assignment",
"self.__str__() def demux_and_write_simulation(args): ini_file = args['inifile'] out_dir = args['outdir'] config = args['configName'] lines",
"dynamic_lines.append(line) lines.append(line) else: lines.append(row) all_dynamic_lines = [ line.dynamic_part for line in dynamic_lines if",
"run.hash = hash [run.config.append(line.get_current_value_tuple()) for line in dynamic_lines] run.path = out_dir + hash",
"+ '/'+ base_name f = check_and_create_file(new_file_path) with open(file) as input_file: for row in",
"= head_tokens[0] tail_tokens = head_tokens[1].split('}') dline.dynamic_part = tail_tokens[0].split(',') dline.tail_part = tail_tokens[1] return dline",
"os.remove(full_path) f = open (full_path, \"a\") return f def create_bash_script(args, target_folder, target_file): omnet_exec",
"os.path.exists(full_path): os.makedirs(full_path) return full_path def check_and_create_file(full_path): if os.path.exists(full_path): os.remove(full_path) f = open (full_path,",
"simulation_runs[hash] = run Logger.info(\"Generated %s simulation configs.\" % (len(simulation_runs))) return simulation_runs def write_sim_data(args,",
"f.close() def check_and_create_folder(base_path, folder_name): full_path = base_path + folder_name if not os.path.exists(full_path): os.makedirs(full_path)",
"import stat from neurogenesis.base import SimulationRun from neurogenesis.util import Logger class DynamicLine(): #",
"for idx, val in enumerate(perm): dynamic_lines[idx].current_print_representation = val #run.parameters.append((dynamic_lines[idx].head_part.split()[0], val.strip())) run.parameters[dynamic_lines[idx].head_part.split()[0]] = val.strip()",
"write_sim_data(args, lines, hash, target_file) run.hash = hash [run.config.append(line.get_current_value_tuple()) for line in dynamic_lines] run.path",
"def __str__(self): return self.head_part + self.current_print_representation + self.tail_part def __repr__(self): return self.__str__() def",
"args['inetdir'] config_name = args['configName'] script = \"\"\" #!/bin/bash DIR=%s TARGET=%s CONFIG=%s cd $DIR",
"puts the variable name at the beginning dynamic_parts = assignemt[1].split(\",\") dynamic_parts[-1] = dynamic_parts[-1].split('}',1)[0]",
"SimulationRun from neurogenesis.util import Logger class DynamicLine(): # TODO better name? def __init__(self):",
"[run.config.append(line.get_current_value_tuple()) for line in dynamic_lines] run.path = out_dir + hash + \"/\" run.executable_path",
"\"run.sh\" write_sim_data(args, lines, hash, target_file) run.hash = hash [run.config.append(line.get_current_value_tuple()) for line in dynamic_lines]",
"$rc -gt 0 ]; then exit $rc fi \"\"\" % (inet_dir[:-1], target_folder, config_name,",
"f = open (full_path, \"a\") f.write(script) f.close() file_handle = os.stat(full_path) os.chmod(full_path, file_handle.st_mode |",
"+ hash + \"/\" + target_file run.config_name= config simulation_runs[hash] = run Logger.info(\"Generated %s",
"write_additional_files(args, full_folder_path) def create_file_hash(lines): hash = hashlib.md5() [hash.update(str(line).encode('utf-8')) for line in lines] return",
"= args['additionalFiles'].split() for file in files: base_name = os.path.basename(file) new_file_path = folder_path +",
"'{' tail_tokens = head_tokens[1].split('}',1) if( '=' in head_tokens[1]): #assignment assignemt = head_tokens[1].split('=') dline.head_part",
"'}' + tail_tokens[1] else: dline.head_part = line dline.dynamic_part = [] dline.tail_part = \"\"",
"val in enumerate(perm): dynamic_lines[idx].current_print_representation = val #run.parameters.append((dynamic_lines[idx].head_part.split()[0], val.strip())) run.parameters[dynamic_lines[idx].head_part.split()[0]] = val.strip() hash =",
"hash, target_file): full_folder_path = check_and_create_folder(args['outdir'], hash) write_ini(full_folder_path, lines) create_bash_script(args, full_folder_path,target_file) write_additional_files(args, full_folder_path) def",
"= \"# This is config %s\\n\" % (config) lines.append(config_line) with open(ini_file) as input_file:",
"\"\" self.tail_part = \"\" self.current_print_representation = \"\" self.parameter_representation = {} def get_current_value_tuple(self): return",
"= head_tokens[1].split('}',1) if( '=' in head_tokens[1]): #assignment assignemt = head_tokens[1].split('=') dline.head_part += assignemt[0]",
"beginning dynamic_parts = assignemt[1].split(\",\") dynamic_parts[-1] = dynamic_parts[-1].split('}',1)[0] dline.dynamic_part = dynamic_parts dline.tail_part = '}'",
"\"\"\" #!/bin/bash DIR=%s TARGET=%s CONFIG=%s cd $DIR %s -u Cmdenv -l $DIR/INET -c",
"[ $rc -gt 0 ]; then exit $rc fi \"\"\" % (inet_dir[:-1], target_folder,",
"self.tail_part) def __str__(self): return self.head_part + self.current_print_representation + self.tail_part def __repr__(self): return self.__str__()",
"# ignore comments (T) line = create_dynamic_line(row.split('#')[0] + '\\n') dynamic_lines.append(line) lines.append(line) else: lines.append(row)",
"if os.path.exists(full_path): os.remove(full_path) f = open (full_path, \"a\") f.write(script) f.close() file_handle = os.stat(full_path)",
"from neurogenesis.base import SimulationRun from neurogenesis.util import Logger class DynamicLine(): # TODO better",
"input_file: for row in input_file: if '{' in row.split('#')[0]: # ignore comments (T)",
"run.config_name= config simulation_runs[hash] = run Logger.info(\"Generated %s simulation configs.\" % (len(simulation_runs))) return simulation_runs",
"config = args['configName'] lines = [] dynamic_lines = [] simulation_runs = {} config_line",
"simulation configs.\" % (len(simulation_runs))) return simulation_runs def write_sim_data(args, lines, hash, target_file): full_folder_path =",
"= [] simulation_runs = {} config_line = \"# This is config %s\\n\" %",
"run Logger.info(\"Generated %s simulation configs.\" % (len(simulation_runs))) return simulation_runs def write_sim_data(args, lines, hash,",
"rc=$? if [ $rc -gt 0 ]; then exit $rc fi \"\"\" %",
"in input_file: f.write(row) f.close() input_file.close() def write_ini(folder_path, file): full_path = folder_path + \"/omnetpp.ini\"",
"(full_path, \"a\") return f def create_bash_script(args, target_folder, target_file): omnet_exec = args['omnetdir'] inet_dir =",
"tail_tokens[1] else: dline.head_part = line dline.dynamic_part = [] dline.tail_part = \"\" else: #legacy",
"> 0] for perm in itertools.product(*all_dynamic_lines): run = SimulationRun() for idx, val in",
"def write_ini(folder_path, file): full_path = folder_path + \"/omnetpp.ini\" if os.path.exists(full_path): os.remove(full_path) f =",
"$DIR/INET -c $CONFIG -n $DIR/inet:$DIR/../tutorials:$DIR/../examples:$DIR/../examples:$TARGET/ $TARGET/omnetpp.ini > /dev/null rc=$? if [ $rc -gt",
"omnet_exec = args['omnetdir'] inet_dir = args['inetdir'] config_name = args['configName'] script = \"\"\" #!/bin/bash",
"target_file) run.hash = hash [run.config.append(line.get_current_value_tuple()) for line in dynamic_lines] run.path = out_dir +",
"new_file_path = folder_path + '/'+ base_name f = check_and_create_file(new_file_path) with open(file) as input_file:",
"else: dline.head_part = line dline.dynamic_part = [] dline.tail_part = \"\" else: #legacy config",
"lines.append(line) else: lines.append(row) all_dynamic_lines = [ line.dynamic_part for line in dynamic_lines if len(line.dynamic_part)",
"tail_tokens = head_tokens[1].split('}',1) if( '=' in head_tokens[1]): #assignment assignemt = head_tokens[1].split('=') dline.head_part +=",
"input_file: for row in input_file: f.write(row) f.close() input_file.close() def write_ini(folder_path, file): full_path =",
"dline.tail_part = \"\" else: #legacy config syntax dline.head_part = head_tokens[0] tail_tokens = head_tokens[1].split('}')",
"config_name = args['configName'] script = \"\"\" #!/bin/bash DIR=%s TARGET=%s CONFIG=%s cd $DIR %s",
"+ target_file run.config_name= config simulation_runs[hash] = run Logger.info(\"Generated %s simulation configs.\" % (len(simulation_runs)))",
"write_additional_files(args, folder_path): files = args['additionalFiles'].split() for file in files: base_name = os.path.basename(file) new_file_path",
"= val.strip() hash = create_file_hash(lines) target_file = \"run.sh\" write_sim_data(args, lines, hash, target_file) run.hash",
"check_and_create_file(full_path): if os.path.exists(full_path): os.remove(full_path) f = open (full_path, \"a\") return f def create_bash_script(args,",
"= \"# puts the variable name at the beginning dynamic_parts = assignemt[1].split(\",\") dynamic_parts[-1]",
"$CONFIG -n $DIR/inet:$DIR/../tutorials:$DIR/../examples:$DIR/../examples:$TARGET/ $TARGET/omnetpp.ini > /dev/null rc=$? if [ $rc -gt 0 ];",
"better name? def __init__(self): self.head_part = \"\" self.dynamic_part = \"\" self.tail_part = \"\"",
"\"\" self.parameter_representation = {} def get_current_value_tuple(self): return (self.head_part, self.current_print_representation, self.tail_part) def __str__(self): return",
"#!/bin/bash DIR=%s TARGET=%s CONFIG=%s cd $DIR %s -u Cmdenv -l $DIR/INET -c $CONFIG",
"SimulationRun() for idx, val in enumerate(perm): dynamic_lines[idx].current_print_representation = val #run.parameters.append((dynamic_lines[idx].head_part.split()[0], val.strip())) run.parameters[dynamic_lines[idx].head_part.split()[0]] =",
"dline.head_part += assignemt[0] + \" = \"# puts the variable name at the",
"= [] dynamic_lines = [] simulation_runs = {} config_line = \"# This is",
"dline.dynamic_part = [] dline.tail_part = \"\" else: #legacy config syntax dline.head_part = head_tokens[0]",
"os.path.exists(full_path): os.remove(full_path) f = open (full_path, \"a\") for line in file: f.write(str(line)) f.close()",
"dynamic_lines[idx].current_print_representation = val #run.parameters.append((dynamic_lines[idx].head_part.split()[0], val.strip())) run.parameters[dynamic_lines[idx].head_part.split()[0]] = val.strip() hash = create_file_hash(lines) target_file =",
"target_file if os.path.exists(full_path): os.remove(full_path) f = open (full_path, \"a\") f.write(script) f.close() file_handle =",
"= args['inetdir'] config_name = args['configName'] script = \"\"\" #!/bin/bash DIR=%s TARGET=%s CONFIG=%s cd",
"self.tail_part = \"\" self.current_print_representation = \"\" self.parameter_representation = {} def get_current_value_tuple(self): return (self.head_part,",
"input_file: f.write(row) f.close() input_file.close() def write_ini(folder_path, file): full_path = folder_path + \"/omnetpp.ini\" if",
"$rc fi \"\"\" % (inet_dir[:-1], target_folder, config_name, omnet_exec) full_path = target_folder + \"/\"",
"DynamicLine() head_tokens = line.split('{',1) if head_tokens[0][-1] == \"$\": dline.head_part = head_tokens[0] + '{'",
"dynamic_lines] run.path = out_dir + hash + \"/\" run.executable_path = out_dir + hash",
"= [] dline.tail_part = \"\" else: #legacy config syntax dline.head_part = head_tokens[0] tail_tokens",
"head_tokens[1].split('=') dline.head_part += assignemt[0] + \" = \"# puts the variable name at",
"if head_tokens[0][-1] == \"$\": dline.head_part = head_tokens[0] + '{' tail_tokens = head_tokens[1].split('}',1) if(",
"target_file): full_folder_path = check_and_create_folder(args['outdir'], hash) write_ini(full_folder_path, lines) create_bash_script(args, full_folder_path,target_file) write_additional_files(args, full_folder_path) def create_file_hash(lines):",
"create_bash_script(args, target_folder, target_file): omnet_exec = args['omnetdir'] inet_dir = args['inetdir'] config_name = args['configName'] script",
"= os.stat(full_path) os.chmod(full_path, file_handle.st_mode | stat.S_IEXEC) def create_dynamic_line(line): dline = DynamicLine() head_tokens =",
"for file in files: base_name = os.path.basename(file) new_file_path = folder_path + '/'+ base_name",
"$TARGET/omnetpp.ini > /dev/null rc=$? if [ $rc -gt 0 ]; then exit $rc",
"hash [run.config.append(line.get_current_value_tuple()) for line in dynamic_lines] run.path = out_dir + hash + \"/\"",
"folder_name if not os.path.exists(full_path): os.makedirs(full_path) return full_path def check_and_create_file(full_path): if os.path.exists(full_path): os.remove(full_path) f",
"-l $DIR/INET -c $CONFIG -n $DIR/inet:$DIR/../tutorials:$DIR/../examples:$DIR/../examples:$TARGET/ $TARGET/omnetpp.ini > /dev/null rc=$? if [ $rc",
"def write_additional_files(args, folder_path): files = args['additionalFiles'].split() for file in files: base_name = os.path.basename(file)",
"f = check_and_create_file(new_file_path) with open(file) as input_file: for row in input_file: f.write(row) f.close()",
"out_dir + hash + \"/\" run.executable_path = out_dir + hash + \"/\" +",
"if not os.path.exists(full_path): os.makedirs(full_path) return full_path def check_and_create_file(full_path): if os.path.exists(full_path): os.remove(full_path) f =",
"config %s\\n\" % (config) lines.append(config_line) with open(ini_file) as input_file: for row in input_file:",
"head_tokens[0][-1] == \"$\": dline.head_part = head_tokens[0] + '{' tail_tokens = head_tokens[1].split('}',1) if( '='",
"import itertools import hashlib import os import stat from neurogenesis.base import SimulationRun from",
"= DynamicLine() head_tokens = line.split('{',1) if head_tokens[0][-1] == \"$\": dline.head_part = head_tokens[0] +",
"full_path = base_path + folder_name if not os.path.exists(full_path): os.makedirs(full_path) return full_path def check_and_create_file(full_path):",
"= head_tokens[0] + '{' tail_tokens = head_tokens[1].split('}',1) if( '=' in head_tokens[1]): #assignment assignemt",
"from neurogenesis.util import Logger class DynamicLine(): # TODO better name? def __init__(self): self.head_part",
"= args['configName'] lines = [] dynamic_lines = [] simulation_runs = {} config_line =",
"target_folder, config_name, omnet_exec) full_path = target_folder + \"/\" + target_file if os.path.exists(full_path): os.remove(full_path)",
"(config) lines.append(config_line) with open(ini_file) as input_file: for row in input_file: if '{' in",
"target_file): omnet_exec = args['omnetdir'] inet_dir = args['inetdir'] config_name = args['configName'] script = \"\"\"",
"val.strip())) run.parameters[dynamic_lines[idx].head_part.split()[0]] = val.strip() hash = create_file_hash(lines) target_file = \"run.sh\" write_sim_data(args, lines, hash,",
"cd $DIR %s -u Cmdenv -l $DIR/INET -c $CONFIG -n $DIR/inet:$DIR/../tutorials:$DIR/../examples:$DIR/../examples:$TARGET/ $TARGET/omnetpp.ini >",
"configs.\" % (len(simulation_runs))) return simulation_runs def write_sim_data(args, lines, hash, target_file): full_folder_path = check_and_create_folder(args['outdir'],",
"\"/omnetpp.ini\" if os.path.exists(full_path): os.remove(full_path) f = open (full_path, \"a\") for line in file:",
"self.current_print_representation = \"\" self.parameter_representation = {} def get_current_value_tuple(self): return (self.head_part, self.current_print_representation, self.tail_part) def",
"dynamic_lines if len(line.dynamic_part) > 0] for perm in itertools.product(*all_dynamic_lines): run = SimulationRun() for",
"create_dynamic_line(row.split('#')[0] + '\\n') dynamic_lines.append(line) lines.append(line) else: lines.append(row) all_dynamic_lines = [ line.dynamic_part for line",
"for row in input_file: if '{' in row.split('#')[0]: # ignore comments (T) line",
"config syntax dline.head_part = head_tokens[0] tail_tokens = head_tokens[1].split('}') dline.dynamic_part = tail_tokens[0].split(',') dline.tail_part =",
"def check_and_create_file(full_path): if os.path.exists(full_path): os.remove(full_path) f = open (full_path, \"a\") return f def",
"inet_dir = args['inetdir'] config_name = args['configName'] script = \"\"\" #!/bin/bash DIR=%s TARGET=%s CONFIG=%s",
"base_name = os.path.basename(file) new_file_path = folder_path + '/'+ base_name f = check_and_create_file(new_file_path) with",
"if [ $rc -gt 0 ]; then exit $rc fi \"\"\" % (inet_dir[:-1],",
"input_file: if '{' in row.split('#')[0]: # ignore comments (T) line = create_dynamic_line(row.split('#')[0] +",
"full_folder_path = check_and_create_folder(args['outdir'], hash) write_ini(full_folder_path, lines) create_bash_script(args, full_folder_path,target_file) write_additional_files(args, full_folder_path) def create_file_hash(lines): hash",
"args['additionalFiles'].split() for file in files: base_name = os.path.basename(file) new_file_path = folder_path + '/'+",
"lines.append(row) all_dynamic_lines = [ line.dynamic_part for line in dynamic_lines if len(line.dynamic_part) > 0]",
"= line.split('{',1) if head_tokens[0][-1] == \"$\": dline.head_part = head_tokens[0] + '{' tail_tokens =",
"get_current_value_tuple(self): return (self.head_part, self.current_print_representation, self.tail_part) def __str__(self): return self.head_part + self.current_print_representation + self.tail_part",
"return f def create_bash_script(args, target_folder, target_file): omnet_exec = args['omnetdir'] inet_dir = args['inetdir'] config_name",
"stat from neurogenesis.base import SimulationRun from neurogenesis.util import Logger class DynamicLine(): # TODO",
"def create_bash_script(args, target_folder, target_file): omnet_exec = args['omnetdir'] inet_dir = args['inetdir'] config_name = args['configName']",
"if '{' in row.split('#')[0]: # ignore comments (T) line = create_dynamic_line(row.split('#')[0] + '\\n')",
"= \"\"\" #!/bin/bash DIR=%s TARGET=%s CONFIG=%s cd $DIR %s -u Cmdenv -l $DIR/INET",
"config simulation_runs[hash] = run Logger.info(\"Generated %s simulation configs.\" % (len(simulation_runs))) return simulation_runs def",
"{} config_line = \"# This is config %s\\n\" % (config) lines.append(config_line) with open(ini_file)",
"return simulation_runs def write_sim_data(args, lines, hash, target_file): full_folder_path = check_and_create_folder(args['outdir'], hash) write_ini(full_folder_path, lines)",
"stat.S_IEXEC) def create_dynamic_line(line): dline = DynamicLine() head_tokens = line.split('{',1) if head_tokens[0][-1] == \"$\":",
"the variable name at the beginning dynamic_parts = assignemt[1].split(\",\") dynamic_parts[-1] = dynamic_parts[-1].split('}',1)[0] dline.dynamic_part",
"in file: f.write(str(line)) f.close() def check_and_create_folder(base_path, folder_name): full_path = base_path + folder_name if",
"dline.head_part = line dline.dynamic_part = [] dline.tail_part = \"\" else: #legacy config syntax",
"base_path + folder_name if not os.path.exists(full_path): os.makedirs(full_path) return full_path def check_and_create_file(full_path): if os.path.exists(full_path):",
"+ hash + \"/\" run.executable_path = out_dir + hash + \"/\" + target_file",
"check_and_create_folder(base_path, folder_name): full_path = base_path + folder_name if not os.path.exists(full_path): os.makedirs(full_path) return full_path",
"return self.__str__() def demux_and_write_simulation(args): ini_file = args['inifile'] out_dir = args['outdir'] config = args['configName']",
"+ self.current_print_representation + self.tail_part def __repr__(self): return self.__str__() def demux_and_write_simulation(args): ini_file = args['inifile']",
"= out_dir + hash + \"/\" + target_file run.config_name= config simulation_runs[hash] = run",
"return self.head_part + self.current_print_representation + self.tail_part def __repr__(self): return self.__str__() def demux_and_write_simulation(args): ini_file",
"(full_path, \"a\") f.write(script) f.close() file_handle = os.stat(full_path) os.chmod(full_path, file_handle.st_mode | stat.S_IEXEC) def create_dynamic_line(line):",
"\"a\") f.write(script) f.close() file_handle = os.stat(full_path) os.chmod(full_path, file_handle.st_mode | stat.S_IEXEC) def create_dynamic_line(line): dline",
"with open(ini_file) as input_file: for row in input_file: if '{' in row.split('#')[0]: #",
"hash.hexdigest() def write_additional_files(args, folder_path): files = args['additionalFiles'].split() for file in files: base_name =",
"> /dev/null rc=$? if [ $rc -gt 0 ]; then exit $rc fi",
"\"$\": dline.head_part = head_tokens[0] + '{' tail_tokens = head_tokens[1].split('}',1) if( '=' in head_tokens[1]):",
"__repr__(self): return self.__str__() def demux_and_write_simulation(args): ini_file = args['inifile'] out_dir = args['outdir'] config =",
"+ \"/omnetpp.ini\" if os.path.exists(full_path): os.remove(full_path) f = open (full_path, \"a\") for line in",
"neurogenesis.base import SimulationRun from neurogenesis.util import Logger class DynamicLine(): # TODO better name?",
"full_folder_path,target_file) write_additional_files(args, full_folder_path) def create_file_hash(lines): hash = hashlib.md5() [hash.update(str(line).encode('utf-8')) for line in lines]",
"full_path = target_folder + \"/\" + target_file if os.path.exists(full_path): os.remove(full_path) f = open",
"= \"\" else: #legacy config syntax dline.head_part = head_tokens[0] tail_tokens = head_tokens[1].split('}') dline.dynamic_part",
"write_sim_data(args, lines, hash, target_file): full_folder_path = check_and_create_folder(args['outdir'], hash) write_ini(full_folder_path, lines) create_bash_script(args, full_folder_path,target_file) write_additional_files(args,",
"files: base_name = os.path.basename(file) new_file_path = folder_path + '/'+ base_name f = check_and_create_file(new_file_path)",
"the beginning dynamic_parts = assignemt[1].split(\",\") dynamic_parts[-1] = dynamic_parts[-1].split('}',1)[0] dline.dynamic_part = dynamic_parts dline.tail_part =",
"= hashlib.md5() [hash.update(str(line).encode('utf-8')) for line in lines] return hash.hexdigest() def write_additional_files(args, folder_path): files",
"% (config) lines.append(config_line) with open(ini_file) as input_file: for row in input_file: if '{'",
"open (full_path, \"a\") return f def create_bash_script(args, target_folder, target_file): omnet_exec = args['omnetdir'] inet_dir",
"in dynamic_lines] run.path = out_dir + hash + \"/\" run.executable_path = out_dir +",
"Logger class DynamicLine(): # TODO better name? def __init__(self): self.head_part = \"\" self.dynamic_part",
"as input_file: for row in input_file: f.write(row) f.close() input_file.close() def write_ini(folder_path, file): full_path",
"lines, hash, target_file) run.hash = hash [run.config.append(line.get_current_value_tuple()) for line in dynamic_lines] run.path =",
"def __repr__(self): return self.__str__() def demux_and_write_simulation(args): ini_file = args['inifile'] out_dir = args['outdir'] config",
"os.remove(full_path) f = open (full_path, \"a\") f.write(script) f.close() file_handle = os.stat(full_path) os.chmod(full_path, file_handle.st_mode",
"'{' in row.split('#')[0]: # ignore comments (T) line = create_dynamic_line(row.split('#')[0] + '\\n') dynamic_lines.append(line)",
"hash + \"/\" + target_file run.config_name= config simulation_runs[hash] = run Logger.info(\"Generated %s simulation",
"%s\\n\" % (config) lines.append(config_line) with open(ini_file) as input_file: for row in input_file: if",
"os.path.exists(full_path): os.remove(full_path) f = open (full_path, \"a\") return f def create_bash_script(args, target_folder, target_file):",
"args['omnetdir'] inet_dir = args['inetdir'] config_name = args['configName'] script = \"\"\" #!/bin/bash DIR=%s TARGET=%s",
"line in lines] return hash.hexdigest() def write_additional_files(args, folder_path): files = args['additionalFiles'].split() for file",
"= args['configName'] script = \"\"\" #!/bin/bash DIR=%s TARGET=%s CONFIG=%s cd $DIR %s -u",
"(inet_dir[:-1], target_folder, config_name, omnet_exec) full_path = target_folder + \"/\" + target_file if os.path.exists(full_path):",
"#legacy config syntax dline.head_part = head_tokens[0] tail_tokens = head_tokens[1].split('}') dline.dynamic_part = tail_tokens[0].split(',') dline.tail_part",
"head_tokens = line.split('{',1) if head_tokens[0][-1] == \"$\": dline.head_part = head_tokens[0] + '{' tail_tokens",
"/dev/null rc=$? if [ $rc -gt 0 ]; then exit $rc fi \"\"\"",
"args['configName'] script = \"\"\" #!/bin/bash DIR=%s TARGET=%s CONFIG=%s cd $DIR %s -u Cmdenv",
"base_name f = check_and_create_file(new_file_path) with open(file) as input_file: for row in input_file: f.write(row)",
"\"\" else: #legacy config syntax dline.head_part = head_tokens[0] tail_tokens = head_tokens[1].split('}') dline.dynamic_part =",
"else: lines.append(row) all_dynamic_lines = [ line.dynamic_part for line in dynamic_lines if len(line.dynamic_part) >",
"neurogenesis.util import Logger class DynamicLine(): # TODO better name? def __init__(self): self.head_part =",
"= assignemt[1].split(\",\") dynamic_parts[-1] = dynamic_parts[-1].split('}',1)[0] dline.dynamic_part = dynamic_parts dline.tail_part = '}' + tail_tokens[1]",
"[ line.dynamic_part for line in dynamic_lines if len(line.dynamic_part) > 0] for perm in",
"perm in itertools.product(*all_dynamic_lines): run = SimulationRun() for idx, val in enumerate(perm): dynamic_lines[idx].current_print_representation =",
"\"\"\" % (inet_dir[:-1], target_folder, config_name, omnet_exec) full_path = target_folder + \"/\" + target_file",
"head_tokens[1]): #assignment assignemt = head_tokens[1].split('=') dline.head_part += assignemt[0] + \" = \"# puts",
"= args['outdir'] config = args['configName'] lines = [] dynamic_lines = [] simulation_runs =",
"[] dynamic_lines = [] simulation_runs = {} config_line = \"# This is config",
"assignemt = head_tokens[1].split('=') dline.head_part += assignemt[0] + \" = \"# puts the variable",
"run.executable_path = out_dir + hash + \"/\" + target_file run.config_name= config simulation_runs[hash] =",
"row in input_file: if '{' in row.split('#')[0]: # ignore comments (T) line =",
"if len(line.dynamic_part) > 0] for perm in itertools.product(*all_dynamic_lines): run = SimulationRun() for idx,",
"= os.path.basename(file) new_file_path = folder_path + '/'+ base_name f = check_and_create_file(new_file_path) with open(file)",
"dline = DynamicLine() head_tokens = line.split('{',1) if head_tokens[0][-1] == \"$\": dline.head_part = head_tokens[0]",
"<filename>neurogenesis/demux.py import itertools import hashlib import os import stat from neurogenesis.base import SimulationRun",
"full_folder_path) def create_file_hash(lines): hash = hashlib.md5() [hash.update(str(line).encode('utf-8')) for line in lines] return hash.hexdigest()",
"= args['omnetdir'] inet_dir = args['inetdir'] config_name = args['configName'] script = \"\"\" #!/bin/bash DIR=%s",
"line.split('{',1) if head_tokens[0][-1] == \"$\": dline.head_part = head_tokens[0] + '{' tail_tokens = head_tokens[1].split('}',1)",
"for perm in itertools.product(*all_dynamic_lines): run = SimulationRun() for idx, val in enumerate(perm): dynamic_lines[idx].current_print_representation",
"f.write(str(line)) f.close() def check_and_create_folder(base_path, folder_name): full_path = base_path + folder_name if not os.path.exists(full_path):",
"line in dynamic_lines if len(line.dynamic_part) > 0] for perm in itertools.product(*all_dynamic_lines): run =",
"Logger.info(\"Generated %s simulation configs.\" % (len(simulation_runs))) return simulation_runs def write_sim_data(args, lines, hash, target_file):",
"= \"run.sh\" write_sim_data(args, lines, hash, target_file) run.hash = hash [run.config.append(line.get_current_value_tuple()) for line in",
"$DIR/inet:$DIR/../tutorials:$DIR/../examples:$DIR/../examples:$TARGET/ $TARGET/omnetpp.ini > /dev/null rc=$? if [ $rc -gt 0 ]; then exit",
"def __init__(self): self.head_part = \"\" self.dynamic_part = \"\" self.tail_part = \"\" self.current_print_representation =",
"ini_file = args['inifile'] out_dir = args['outdir'] config = args['configName'] lines = [] dynamic_lines",
"'/'+ base_name f = check_and_create_file(new_file_path) with open(file) as input_file: for row in input_file:",
"\"a\") for line in file: f.write(str(line)) f.close() def check_and_create_folder(base_path, folder_name): full_path = base_path",
"in lines] return hash.hexdigest() def write_additional_files(args, folder_path): files = args['additionalFiles'].split() for file in",
"]; then exit $rc fi \"\"\" % (inet_dir[:-1], target_folder, config_name, omnet_exec) full_path =",
"\" = \"# puts the variable name at the beginning dynamic_parts = assignemt[1].split(\",\")",
"else: #legacy config syntax dline.head_part = head_tokens[0] tail_tokens = head_tokens[1].split('}') dline.dynamic_part = tail_tokens[0].split(',')",
"= dynamic_parts dline.tail_part = '}' + tail_tokens[1] else: dline.head_part = line dline.dynamic_part =",
"syntax dline.head_part = head_tokens[0] tail_tokens = head_tokens[1].split('}') dline.dynamic_part = tail_tokens[0].split(',') dline.tail_part = tail_tokens[1]",
"self.parameter_representation = {} def get_current_value_tuple(self): return (self.head_part, self.current_print_representation, self.tail_part) def __str__(self): return self.head_part",
"out_dir = args['outdir'] config = args['configName'] lines = [] dynamic_lines = [] simulation_runs",
"dline.head_part = head_tokens[0] tail_tokens = head_tokens[1].split('}') dline.dynamic_part = tail_tokens[0].split(',') dline.tail_part = tail_tokens[1] return",
"+ \" = \"# puts the variable name at the beginning dynamic_parts =",
"row.split('#')[0]: # ignore comments (T) line = create_dynamic_line(row.split('#')[0] + '\\n') dynamic_lines.append(line) lines.append(line) else:",
"os.path.basename(file) new_file_path = folder_path + '/'+ base_name f = check_and_create_file(new_file_path) with open(file) as",
"= base_path + folder_name if not os.path.exists(full_path): os.makedirs(full_path) return full_path def check_and_create_file(full_path): if",
"for line in file: f.write(str(line)) f.close() def check_and_create_folder(base_path, folder_name): full_path = base_path +",
"DIR=%s TARGET=%s CONFIG=%s cd $DIR %s -u Cmdenv -l $DIR/INET -c $CONFIG -n",
"def create_dynamic_line(line): dline = DynamicLine() head_tokens = line.split('{',1) if head_tokens[0][-1] == \"$\": dline.head_part",
"self.head_part = \"\" self.dynamic_part = \"\" self.tail_part = \"\" self.current_print_representation = \"\" self.parameter_representation",
"\"/\" + target_file if os.path.exists(full_path): os.remove(full_path) f = open (full_path, \"a\") f.write(script) f.close()",
"TARGET=%s CONFIG=%s cd $DIR %s -u Cmdenv -l $DIR/INET -c $CONFIG -n $DIR/inet:$DIR/../tutorials:$DIR/../examples:$DIR/../examples:$TARGET/",
"folder_path): files = args['additionalFiles'].split() for file in files: base_name = os.path.basename(file) new_file_path =",
"-c $CONFIG -n $DIR/inet:$DIR/../tutorials:$DIR/../examples:$DIR/../examples:$TARGET/ $TARGET/omnetpp.ini > /dev/null rc=$? if [ $rc -gt 0",
"target_folder + \"/\" + target_file if os.path.exists(full_path): os.remove(full_path) f = open (full_path, \"a\")",
"= {} config_line = \"# This is config %s\\n\" % (config) lines.append(config_line) with"
] |
[
"self.assertAllEqual(masks.shape, target.shape) def test2(self): idseqs = [[1, 1, 0, 0, 2, 2, 3],",
"3, 1], [1, 4, 0], [1, 5, 0]), values=[1.0 for _ in range(11)],",
"[1, 2, 2], [1, 3, 1], [1, 4, 0], [1, 5, 0]), values=[1.0",
"= idseqs_to_mask( idseqs, n_seqlen=6, n_vocab_sz=3, ignore=[3], dense=False) self.assertAllEqual( tf.sparse.to_dense(masks), tf.sparse.to_dense(target)) self.assertAllEqual(masks.dtype, target.dtype) self.assertAllEqual(masks.shape,",
"1], [1, 4, 0], [1, 5, 0]), values=[1.0 for _ in range(11)], dense_shape=(2,",
"masks = idseqs_to_mask( idseqs, n_seqlen=6, n_vocab_sz=3, ignore=[3], dense=False, dtype=tf.float64) self.assertAllEqual( tf.sparse.to_dense(masks), tf.sparse.to_dense(target)) #",
"3)) masks = idseqs_to_mask( idseqs, n_seqlen=6, ignore=[1], dense=False, dtype=tf.bool) self.assertAllEqual( tf.sparse.to_dense(masks), tf.sparse.to_dense(target)) self.assertAllEqual(masks.dtype,",
"n_seqlen=6, n_vocab_sz=3, ignore=[3], dense=False, dtype=tf.float64) self.assertAllEqual( tf.sparse.to_dense(masks), tf.sparse.to_dense(target)) # self.assertAllEqual(masks.dtype, target.dtype) self.assertAllEqual(masks.shape, target.shape)",
"0, 2, 2, 3], [1, 3, 2, 1, 0, 0, 2]] target =",
"self.assertAllEqual( tf.sparse.to_dense(masks), tf.sparse.to_dense(target)) # self.assertAllEqual(masks.dtype, target.dtype) self.assertAllEqual(masks.shape, target.shape) def test3(self): idseqs = [[1,",
"0]), values=[1.0 for _ in range(11)], dense_shape=(2, 6, 3)) masks = idseqs_to_mask( idseqs,",
"0]), values=[1 for _ in range(11)], dense_shape=(2, 6, 3)) masks = idseqs_to_mask( idseqs,",
"0]), values=[True for _ in range(8)], dense_shape=(2, 6, 3)) masks = idseqs_to_mask( idseqs,",
"self.assertAllEqual(masks.shape, target.shape) def test5(self): idseqs = [[1, 1, 0, 0, 2, 2, 3],",
"keras_tweaks import idseqs_to_mask import tensorflow as tf class AllTests(tf.test.TestCase): def test1(self): idseqs =",
"range(11)], dense_shape=(2, 6, 3)) masks = idseqs_to_mask( idseqs, n_seqlen=6, n_vocab_sz=3, ignore=[3], dense=False, dtype=tf.uint8)",
"values=[True for _ in range(8)], dense_shape=(2, 6, 3)) masks = idseqs_to_mask( idseqs, n_seqlen=6,",
"tf.sparse.to_dense(masks), tf.sparse.to_dense(target)) self.assertAllEqual(masks.dtype, target.dtype) self.assertAllEqual(masks.shape, target.shape) def test5(self): idseqs = [[1, 1, 0,",
"dense_shape=(2, 6, 3)) masks = idseqs_to_mask( idseqs, n_seqlen=6, n_vocab_sz=3, ignore=[3], dense=False, dtype=tf.float64) self.assertAllEqual(",
"6, 3)) masks = idseqs_to_mask( idseqs, n_seqlen=6, n_vocab_sz=3, ignore=[3], dense=False) self.assertAllEqual( tf.sparse.to_dense(masks), tf.sparse.to_dense(target))",
"self.assertAllEqual( tf.sparse.to_dense(masks), tf.sparse.to_dense(target)) self.assertAllEqual(masks.dtype, target.dtype) self.assertAllEqual(masks.shape, target.shape) def test2(self): idseqs = [[1, 1,",
"[1, 2, 1], [1, 4, 0], [1, 5, 0]), values=[True for _ in",
"tf class AllTests(tf.test.TestCase): def test1(self): idseqs = [[1, 1, 0, 0, 2, 2,",
"in range(8)], dense_shape=(2, 6, 3)) masks = idseqs_to_mask( idseqs, n_seqlen=6, ignore=[1], dense=True, dtype=tf.bool)",
"self.assertAllEqual(masks.dtype, target.dtype) self.assertAllEqual(masks.shape, target.shape) def test4(self): idseqs = [[1, 1, 0, 0, 2,",
"ignore=[1], dense=False, dtype=tf.bool) self.assertAllEqual( tf.sparse.to_dense(masks), tf.sparse.to_dense(target)) self.assertAllEqual(masks.dtype, target.dtype) self.assertAllEqual(masks.shape, target.shape) def test5(self): idseqs",
"4, 0], [1, 5, 0]), values=[1.0 for _ in range(11)], dense_shape=(2, 6, 3))",
"2], [0, 5, 2], [1, 0, 1], [1, 2, 2], [1, 3, 1],",
"4, 2], [0, 5, 2], [1, 0, 1], [1, 2, 2], [1, 3,",
"2, 1], [1, 4, 0], [1, 5, 0]), values=[True for _ in range(8)],",
"3)) masks = idseqs_to_mask( idseqs, n_seqlen=6, n_vocab_sz=3, ignore=[3], dense=False, dtype=tf.float64) self.assertAllEqual( tf.sparse.to_dense(masks), tf.sparse.to_dense(target))",
"ignore=[3], dense=False, dtype=tf.float64) self.assertAllEqual( tf.sparse.to_dense(masks), tf.sparse.to_dense(target)) # self.assertAllEqual(masks.dtype, target.dtype) self.assertAllEqual(masks.shape, target.shape) def test4(self):",
"[0, 4, 2], [0, 5, 2], [1, 0, 1], [1, 2, 2], [1,",
"0, 1], [1, 2, 2], [1, 3, 1], [1, 4, 0], [1, 5,",
"values=[1.0 for _ in range(11)], dense_shape=(2, 6, 3)) masks = idseqs_to_mask( idseqs, n_seqlen=6,",
"2]] target = tf.sparse.SparseTensor( indices=( [0, 0, 1], [0, 1, 1], [0, 2,",
"3, 1], [1, 4, 0], [1, 5, 0]), values=[True for _ in range(11)],",
"idseqs, n_seqlen=6, ignore=[1], dense=True, dtype=tf.bool) self.assertAllEqual(masks, tf.sparse.to_dense(target)) self.assertAllEqual(masks.dtype, target.dtype) self.assertAllEqual(masks.shape, target.shape) if __name__",
"tf.sparse.to_dense(target)) # self.assertAllEqual(masks.dtype, target.dtype) self.assertAllEqual(masks.shape, target.shape) def test4(self): idseqs = [[1, 1, 0,",
"[0, 5, 2], [1, 0, 1], [1, 2, 2], [1, 3, 1], [1,",
"idseqs, n_seqlen=6, n_vocab_sz=3, ignore=[3], dense=False, dtype=tf.float64) self.assertAllEqual( tf.sparse.to_dense(masks), tf.sparse.to_dense(target)) # self.assertAllEqual(masks.dtype, target.dtype) self.assertAllEqual(masks.shape,",
"[0, 3, 0], [0, 4, 1], [0, 5, 1], [1, 1, 2], [1,",
"0], [0, 4, 2], [0, 5, 2], [1, 0, 1], [1, 2, 2],",
"3)) masks = idseqs_to_mask( idseqs, n_seqlen=6, n_vocab_sz=3, ignore=[3], dense=False) self.assertAllEqual( tf.sparse.to_dense(masks), tf.sparse.to_dense(target)) self.assertAllEqual(masks.dtype,",
"as tf class AllTests(tf.test.TestCase): def test1(self): idseqs = [[1, 1, 0, 0, 2,",
"4, 1], [0, 5, 1], [1, 1, 2], [1, 2, 1], [1, 4,",
"0, 1], [0, 1, 1], [0, 2, 0], [0, 3, 0], [0, 4,",
"1, 0, 0, 2]] target = tf.sparse.SparseTensor( indices=( [0, 2, 0], [0, 3,",
"dense_shape=(2, 6, 3)) masks = idseqs_to_mask( idseqs, n_seqlen=6, ignore=[1], dense=False, dtype=tf.bool) self.assertAllEqual( tf.sparse.to_dense(masks),",
"target.dtype) self.assertAllEqual(masks.shape, target.shape) def test5(self): idseqs = [[1, 1, 0, 0, 2, 2,",
"0, 2]] target = tf.sparse.SparseTensor( indices=( [0, 0, 1], [0, 1, 1], [0,",
"1], [0, 2, 0], [0, 3, 0], [0, 4, 2], [0, 5, 2],",
"[1, 2, 2], [1, 3, 1], [1, 4, 0], [1, 5, 0]), values=[1",
"_ in range(8)], dense_shape=(2, 6, 3)) masks = idseqs_to_mask( idseqs, n_seqlen=6, ignore=[1], dense=False,",
"n_seqlen=6, ignore=[1], dense=False, dtype=tf.bool) self.assertAllEqual( tf.sparse.to_dense(masks), tf.sparse.to_dense(target)) self.assertAllEqual(masks.dtype, target.dtype) self.assertAllEqual(masks.shape, target.shape) def test5(self):",
"tf.sparse.to_dense(target)) # self.assertAllEqual(masks.dtype, target.dtype) self.assertAllEqual(masks.shape, target.shape) def test3(self): idseqs = [[1, 1, 0,",
"self.assertAllEqual( tf.sparse.to_dense(masks), tf.sparse.to_dense(target)) self.assertAllEqual(masks.dtype, target.dtype) self.assertAllEqual(masks.shape, target.shape) def test5(self): idseqs = [[1, 1,",
"2], [1, 3, 1], [1, 4, 0], [1, 5, 0]), values=[1 for _",
"target = tf.sparse.SparseTensor( indices=( [0, 0, 1], [0, 1, 1], [0, 2, 0],",
"def test2(self): idseqs = [[1, 1, 0, 0, 2, 2, 3], [1, 3,",
"0, 2]] target = tf.sparse.SparseTensor( indices=( [0, 2, 0], [0, 3, 0], [0,",
"self.assertAllEqual(masks.dtype, target.dtype) self.assertAllEqual(masks.shape, target.shape) def test2(self): idseqs = [[1, 1, 0, 0, 2,",
"5, 0]), values=[1.0 for _ in range(11)], dense_shape=(2, 6, 3)) masks = idseqs_to_mask(",
"self.assertAllEqual( tf.sparse.to_dense(masks), tf.sparse.to_dense(target)) # self.assertAllEqual(masks.dtype, target.dtype) self.assertAllEqual(masks.shape, target.shape) def test4(self): idseqs = [[1,",
"0], [1, 5, 0]), values=[True for _ in range(8)], dense_shape=(2, 6, 3)) masks",
"4, 0], [1, 5, 0]), values=[True for _ in range(11)], dense_shape=(2, 6, 3))",
"[0, 2, 0], [0, 3, 0], [0, 4, 2], [0, 5, 2], [1,",
"ignore=[3], dense=False) self.assertAllEqual( tf.sparse.to_dense(masks), tf.sparse.to_dense(target)) self.assertAllEqual(masks.dtype, target.dtype) self.assertAllEqual(masks.shape, target.shape) def test2(self): idseqs =",
"0], [1, 5, 0]), values=[1.0 for _ in range(11)], dense_shape=(2, 6, 3)) masks",
"[[1, 1, 0, 0, 2, 2, 3], [1, 3, 2, 1, 0, 0,",
"range(8)], dense_shape=(2, 6, 3)) masks = idseqs_to_mask( idseqs, n_seqlen=6, ignore=[1], dense=False, dtype=tf.bool) self.assertAllEqual(",
"3], [1, 3, 2, 1, 0, 0, 2]] target = tf.sparse.SparseTensor( indices=( [0,",
"5, 2], [1, 0, 1], [1, 2, 2], [1, 3, 1], [1, 4,",
"target.dtype) self.assertAllEqual(masks.shape, target.shape) def test3(self): idseqs = [[1, 1, 0, 0, 2, 2,",
"2]] target = tf.sparse.SparseTensor( indices=( [0, 2, 0], [0, 3, 0], [0, 4,",
"2], [1, 3, 1], [1, 4, 0], [1, 5, 0]), values=[True for _",
"for _ in range(11)], dense_shape=(2, 6, 3)) masks = idseqs_to_mask( idseqs, n_seqlen=6, n_vocab_sz=3,",
"[1, 3, 2, 1, 0, 0, 2]] target = tf.sparse.SparseTensor( indices=( [0, 0,",
"idseqs_to_mask( idseqs, n_seqlen=6, n_vocab_sz=3, ignore=[3], dense=False, dtype=tf.uint8) self.assertAllEqual( tf.sparse.to_dense(masks), tf.sparse.to_dense(target)) # self.assertAllEqual(masks.dtype, target.dtype)",
"test3(self): idseqs = [[1, 1, 0, 0, 2, 2, 3], [1, 3, 2,",
"dtype=tf.bool) self.assertAllEqual( tf.sparse.to_dense(masks), tf.sparse.to_dense(target)) self.assertAllEqual(masks.dtype, target.dtype) self.assertAllEqual(masks.shape, target.shape) def test5(self): idseqs = [[1,",
"1], [0, 5, 1], [1, 1, 2], [1, 2, 1], [1, 4, 0],",
"[1, 4, 0], [1, 5, 0]), values=[True for _ in range(8)], dense_shape=(2, 6,",
"3, 2, 1, 0, 0, 2]] target = tf.sparse.SparseTensor( indices=( [0, 0, 1],",
"4, 0], [1, 5, 0]), values=[1 for _ in range(11)], dense_shape=(2, 6, 3))",
"2, 1, 0, 0, 2]] target = tf.sparse.SparseTensor( indices=( [0, 2, 0], [0,",
"target.dtype) self.assertAllEqual(masks.shape, target.shape) def test2(self): idseqs = [[1, 1, 0, 0, 2, 2,",
"[0, 1, 1], [0, 2, 0], [0, 3, 0], [0, 4, 2], [0,",
"self.assertAllEqual(masks.shape, target.shape) def test3(self): idseqs = [[1, 1, 0, 0, 2, 2, 3],",
"5, 0]), values=[True for _ in range(11)], dense_shape=(2, 6, 3)) masks = idseqs_to_mask(",
"target.shape) def test2(self): idseqs = [[1, 1, 0, 0, 2, 2, 3], [1,",
"[0, 0, 1], [0, 1, 1], [0, 2, 0], [0, 3, 0], [0,",
"self.assertAllEqual(masks.dtype, target.dtype) self.assertAllEqual(masks.shape, target.shape) def test3(self): idseqs = [[1, 1, 0, 0, 2,",
"1], [1, 1, 2], [1, 2, 1], [1, 4, 0], [1, 5, 0]),",
"tf.sparse.to_dense(target)) self.assertAllEqual(masks.dtype, target.dtype) self.assertAllEqual(masks.shape, target.shape) def test2(self): idseqs = [[1, 1, 0, 0,",
"values=[1 for _ in range(11)], dense_shape=(2, 6, 3)) masks = idseqs_to_mask( idseqs, n_seqlen=6,",
"values=[True for _ in range(11)], dense_shape=(2, 6, 3)) masks = idseqs_to_mask( idseqs, n_seqlen=6,",
"dense_shape=(2, 6, 3)) masks = idseqs_to_mask( idseqs, n_seqlen=6, n_vocab_sz=3, ignore=[3], dense=False, dtype=tf.uint8) self.assertAllEqual(",
"test5(self): idseqs = [[1, 1, 0, 0, 2, 2, 3], [1, 3, 2,",
"6, 3)) masks = idseqs_to_mask( idseqs, n_seqlen=6, ignore=[1], dense=True, dtype=tf.bool) self.assertAllEqual(masks, tf.sparse.to_dense(target)) self.assertAllEqual(masks.dtype,",
"[1, 0, 1], [1, 2, 2], [1, 3, 1], [1, 4, 0], [1,",
"= [[1, 1, 0, 0, 2, 2, 3], [1, 3, 2, 1, 0,",
"range(11)], dense_shape=(2, 6, 3)) masks = idseqs_to_mask( idseqs, n_seqlen=6, n_vocab_sz=3, ignore=[3], dense=False) self.assertAllEqual(",
"tf.sparse.to_dense(masks), tf.sparse.to_dense(target)) # self.assertAllEqual(masks.dtype, target.dtype) self.assertAllEqual(masks.shape, target.shape) def test3(self): idseqs = [[1, 1,",
"tf.sparse.to_dense(masks), tf.sparse.to_dense(target)) # self.assertAllEqual(masks.dtype, target.dtype) self.assertAllEqual(masks.shape, target.shape) def test4(self): idseqs = [[1, 1,",
"[1, 4, 0], [1, 5, 0]), values=[True for _ in range(11)], dense_shape=(2, 6,",
"def test4(self): idseqs = [[1, 1, 0, 0, 2, 2, 3], [1, 3,",
"[1, 3, 2, 1, 0, 0, 2]] target = tf.sparse.SparseTensor( indices=( [0, 2,",
"2, 2], [1, 3, 1], [1, 4, 0], [1, 5, 0]), values=[1.0 for",
"import tensorflow as tf class AllTests(tf.test.TestCase): def test1(self): idseqs = [[1, 1, 0,",
"= tf.sparse.SparseTensor( indices=( [0, 0, 1], [0, 1, 1], [0, 2, 0], [0,",
"ignore=[3], dense=False, dtype=tf.uint8) self.assertAllEqual( tf.sparse.to_dense(masks), tf.sparse.to_dense(target)) # self.assertAllEqual(masks.dtype, target.dtype) self.assertAllEqual(masks.shape, target.shape) def test3(self):",
"= idseqs_to_mask( idseqs, n_seqlen=6, ignore=[1], dense=False, dtype=tf.bool) self.assertAllEqual( tf.sparse.to_dense(masks), tf.sparse.to_dense(target)) self.assertAllEqual(masks.dtype, target.dtype) self.assertAllEqual(masks.shape,",
"target.shape) def test5(self): idseqs = [[1, 1, 0, 0, 2, 2, 3], [1,",
"5, 0]), values=[1 for _ in range(11)], dense_shape=(2, 6, 3)) masks = idseqs_to_mask(",
"2], [1, 3, 1], [1, 4, 0], [1, 5, 0]), values=[1.0 for _",
"dense=True, dtype=tf.bool) self.assertAllEqual(masks, tf.sparse.to_dense(target)) self.assertAllEqual(masks.dtype, target.dtype) self.assertAllEqual(masks.shape, target.shape) if __name__ == \"__main__\": tf.test.main()",
"2, 2], [1, 3, 1], [1, 4, 0], [1, 5, 0]), values=[1 for",
"1, 0, 0, 2]] target = tf.sparse.SparseTensor( indices=( [0, 0, 1], [0, 1,",
"target.shape) def test3(self): idseqs = [[1, 1, 0, 0, 2, 2, 3], [1,",
"n_vocab_sz=3, ignore=[3], dense=False, dtype=tf.float64) self.assertAllEqual( tf.sparse.to_dense(masks), tf.sparse.to_dense(target)) # self.assertAllEqual(masks.dtype, target.dtype) self.assertAllEqual(masks.shape, target.shape) def",
"2, 0], [0, 3, 0], [0, 4, 2], [0, 5, 2], [1, 0,",
"idseqs, n_seqlen=6, n_vocab_sz=3, ignore=[3], dense=False) self.assertAllEqual( tf.sparse.to_dense(masks), tf.sparse.to_dense(target)) self.assertAllEqual(masks.dtype, target.dtype) self.assertAllEqual(masks.shape, target.shape) def",
"indices=( [0, 2, 0], [0, 3, 0], [0, 4, 1], [0, 5, 1],",
"import idseqs_to_mask import tensorflow as tf class AllTests(tf.test.TestCase): def test1(self): idseqs = [[1,",
"[1, 5, 0]), values=[True for _ in range(8)], dense_shape=(2, 6, 3)) masks =",
"target.shape) def test4(self): idseqs = [[1, 1, 0, 0, 2, 2, 3], [1,",
"[1, 5, 0]), values=[True for _ in range(11)], dense_shape=(2, 6, 3)) masks =",
"idseqs_to_mask import tensorflow as tf class AllTests(tf.test.TestCase): def test1(self): idseqs = [[1, 1,",
"dtype=tf.float64) self.assertAllEqual( tf.sparse.to_dense(masks), tf.sparse.to_dense(target)) # self.assertAllEqual(masks.dtype, target.dtype) self.assertAllEqual(masks.shape, target.shape) def test4(self): idseqs =",
"self.assertAllEqual(masks.shape, target.shape) def test4(self): idseqs = [[1, 1, 0, 0, 2, 2, 3],",
"[1, 3, 1], [1, 4, 0], [1, 5, 0]), values=[True for _ in",
"idseqs_to_mask( idseqs, n_seqlen=6, ignore=[1], dense=True, dtype=tf.bool) self.assertAllEqual(masks, tf.sparse.to_dense(target)) self.assertAllEqual(masks.dtype, target.dtype) self.assertAllEqual(masks.shape, target.shape) if",
"2], [1, 0, 1], [1, 2, 2], [1, 3, 1], [1, 4, 0],",
"6, 3)) masks = idseqs_to_mask( idseqs, n_seqlen=6, n_vocab_sz=3, ignore=[3], dense=False, dtype=tf.uint8) self.assertAllEqual( tf.sparse.to_dense(masks),",
"test4(self): idseqs = [[1, 1, 0, 0, 2, 2, 3], [1, 3, 2,",
"6, 3)) masks = idseqs_to_mask( idseqs, n_seqlen=6, n_vocab_sz=3, ignore=[3], dense=False, dtype=tf.float64) self.assertAllEqual( tf.sparse.to_dense(masks),",
"2, 3], [1, 3, 2, 1, 0, 0, 2]] target = tf.sparse.SparseTensor( indices=(",
"0], [0, 4, 1], [0, 5, 1], [1, 1, 2], [1, 2, 1],",
"# self.assertAllEqual(masks.dtype, target.dtype) self.assertAllEqual(masks.shape, target.shape) def test3(self): idseqs = [[1, 1, 0, 0,",
"tf.sparse.to_dense(masks), tf.sparse.to_dense(target)) self.assertAllEqual(masks.dtype, target.dtype) self.assertAllEqual(masks.shape, target.shape) def test2(self): idseqs = [[1, 1, 0,",
"def test5(self): idseqs = [[1, 1, 0, 0, 2, 2, 3], [1, 3,",
"ignore=[1], dense=True, dtype=tf.bool) self.assertAllEqual(masks, tf.sparse.to_dense(target)) self.assertAllEqual(masks.dtype, target.dtype) self.assertAllEqual(masks.shape, target.shape) if __name__ == \"__main__\":",
"n_seqlen=6, n_vocab_sz=3, ignore=[3], dense=False, dtype=tf.uint8) self.assertAllEqual( tf.sparse.to_dense(masks), tf.sparse.to_dense(target)) # self.assertAllEqual(masks.dtype, target.dtype) self.assertAllEqual(masks.shape, target.shape)",
"[1, 2, 2], [1, 3, 1], [1, 4, 0], [1, 5, 0]), values=[True",
"6, 3)) masks = idseqs_to_mask( idseqs, n_seqlen=6, ignore=[1], dense=False, dtype=tf.bool) self.assertAllEqual( tf.sparse.to_dense(masks), tf.sparse.to_dense(target))",
"dense=False, dtype=tf.uint8) self.assertAllEqual( tf.sparse.to_dense(masks), tf.sparse.to_dense(target)) # self.assertAllEqual(masks.dtype, target.dtype) self.assertAllEqual(masks.shape, target.shape) def test3(self): idseqs",
"5, 1], [1, 1, 2], [1, 2, 1], [1, 4, 0], [1, 5,",
"idseqs_to_mask( idseqs, n_seqlen=6, n_vocab_sz=3, ignore=[3], dense=False, dtype=tf.float64) self.assertAllEqual( tf.sparse.to_dense(masks), tf.sparse.to_dense(target)) # self.assertAllEqual(masks.dtype, target.dtype)",
"3, 0], [0, 4, 1], [0, 5, 1], [1, 1, 2], [1, 2,",
"def test3(self): idseqs = [[1, 1, 0, 0, 2, 2, 3], [1, 3,",
"_ in range(11)], dense_shape=(2, 6, 3)) masks = idseqs_to_mask( idseqs, n_seqlen=6, n_vocab_sz=3, ignore=[3],",
"1], [1, 4, 0], [1, 5, 0]), values=[True for _ in range(8)], dense_shape=(2,",
"AllTests(tf.test.TestCase): def test1(self): idseqs = [[1, 1, 0, 0, 2, 2, 3], [1,",
"masks = idseqs_to_mask( idseqs, n_seqlen=6, n_vocab_sz=3, ignore=[3], dense=False, dtype=tf.uint8) self.assertAllEqual( tf.sparse.to_dense(masks), tf.sparse.to_dense(target)) #",
"n_seqlen=6, n_vocab_sz=3, ignore=[3], dense=False) self.assertAllEqual( tf.sparse.to_dense(masks), tf.sparse.to_dense(target)) self.assertAllEqual(masks.dtype, target.dtype) self.assertAllEqual(masks.shape, target.shape) def test2(self):",
"tensorflow as tf class AllTests(tf.test.TestCase): def test1(self): idseqs = [[1, 1, 0, 0,",
"4, 0], [1, 5, 0]), values=[True for _ in range(8)], dense_shape=(2, 6, 3))",
"0, 0, 2]] target = tf.sparse.SparseTensor( indices=( [0, 0, 1], [0, 1, 1],",
"0], [1, 5, 0]), values=[1 for _ in range(11)], dense_shape=(2, 6, 3)) masks",
"1], [1, 4, 0], [1, 5, 0]), values=[True for _ in range(11)], dense_shape=(2,",
"2, 0], [0, 3, 0], [0, 4, 1], [0, 5, 1], [1, 1,",
"1], [0, 1, 1], [0, 2, 0], [0, 3, 0], [0, 4, 2],",
"0, 0, 2]] target = tf.sparse.SparseTensor( indices=( [0, 2, 0], [0, 3, 0],",
"0], [0, 3, 0], [0, 4, 1], [0, 5, 1], [1, 1, 2],",
"[0, 5, 1], [1, 1, 2], [1, 2, 1], [1, 4, 0], [1,",
"= idseqs_to_mask( idseqs, n_seqlen=6, ignore=[1], dense=True, dtype=tf.bool) self.assertAllEqual(masks, tf.sparse.to_dense(target)) self.assertAllEqual(masks.dtype, target.dtype) self.assertAllEqual(masks.shape, target.shape)",
"2, 2], [1, 3, 1], [1, 4, 0], [1, 5, 0]), values=[True for",
"1], [1, 4, 0], [1, 5, 0]), values=[1 for _ in range(11)], dense_shape=(2,",
"0], [0, 3, 0], [0, 4, 2], [0, 5, 2], [1, 0, 1],",
"range(11)], dense_shape=(2, 6, 3)) masks = idseqs_to_mask( idseqs, n_seqlen=6, n_vocab_sz=3, ignore=[3], dense=False, dtype=tf.float64)",
"[0, 4, 1], [0, 5, 1], [1, 1, 2], [1, 2, 1], [1,",
"3, 2, 1, 0, 0, 2]] target = tf.sparse.SparseTensor( indices=( [0, 2, 0],",
"1, 1], [0, 2, 0], [0, 3, 0], [0, 4, 2], [0, 5,",
"def test1(self): idseqs = [[1, 1, 0, 0, 2, 2, 3], [1, 3,",
"dense=False, dtype=tf.float64) self.assertAllEqual( tf.sparse.to_dense(masks), tf.sparse.to_dense(target)) # self.assertAllEqual(masks.dtype, target.dtype) self.assertAllEqual(masks.shape, target.shape) def test4(self): idseqs",
"[1, 3, 1], [1, 4, 0], [1, 5, 0]), values=[1 for _ in",
"tf.sparse.SparseTensor( indices=( [0, 0, 1], [0, 1, 1], [0, 2, 0], [0, 3,",
"2, 2, 3], [1, 3, 2, 1, 0, 0, 2]] target = tf.sparse.SparseTensor(",
"idseqs = [[1, 1, 0, 0, 2, 2, 3], [1, 3, 2, 1,",
"for _ in range(8)], dense_shape=(2, 6, 3)) masks = idseqs_to_mask( idseqs, n_seqlen=6, ignore=[1],",
"idseqs_to_mask( idseqs, n_seqlen=6, n_vocab_sz=3, ignore=[3], dense=False) self.assertAllEqual( tf.sparse.to_dense(masks), tf.sparse.to_dense(target)) self.assertAllEqual(masks.dtype, target.dtype) self.assertAllEqual(masks.shape, target.shape)",
"in range(8)], dense_shape=(2, 6, 3)) masks = idseqs_to_mask( idseqs, n_seqlen=6, ignore=[1], dense=False, dtype=tf.bool)",
"in range(11)], dense_shape=(2, 6, 3)) masks = idseqs_to_mask( idseqs, n_seqlen=6, n_vocab_sz=3, ignore=[3], dense=False,",
"masks = idseqs_to_mask( idseqs, n_seqlen=6, ignore=[1], dense=False, dtype=tf.bool) self.assertAllEqual( tf.sparse.to_dense(masks), tf.sparse.to_dense(target)) self.assertAllEqual(masks.dtype, target.dtype)",
"[0, 2, 0], [0, 3, 0], [0, 4, 1], [0, 5, 1], [1,",
"target.dtype) self.assertAllEqual(masks.shape, target.shape) def test4(self): idseqs = [[1, 1, 0, 0, 2, 2,",
"n_seqlen=6, ignore=[1], dense=True, dtype=tf.bool) self.assertAllEqual(masks, tf.sparse.to_dense(target)) self.assertAllEqual(masks.dtype, target.dtype) self.assertAllEqual(masks.shape, target.shape) if __name__ ==",
"= tf.sparse.SparseTensor( indices=( [0, 2, 0], [0, 3, 0], [0, 4, 1], [0,",
"0, 0, 2, 2, 3], [1, 3, 2, 1, 0, 0, 2]] target",
"3)) masks = idseqs_to_mask( idseqs, n_seqlen=6, n_vocab_sz=3, ignore=[3], dense=False, dtype=tf.uint8) self.assertAllEqual( tf.sparse.to_dense(masks), tf.sparse.to_dense(target))",
"[1, 1, 2], [1, 2, 1], [1, 4, 0], [1, 5, 0]), values=[True",
"0]), values=[True for _ in range(11)], dense_shape=(2, 6, 3)) masks = idseqs_to_mask( idseqs,",
"3)) masks = idseqs_to_mask( idseqs, n_seqlen=6, ignore=[1], dense=True, dtype=tf.bool) self.assertAllEqual(masks, tf.sparse.to_dense(target)) self.assertAllEqual(masks.dtype, target.dtype)",
"= idseqs_to_mask( idseqs, n_seqlen=6, n_vocab_sz=3, ignore=[3], dense=False, dtype=tf.uint8) self.assertAllEqual( tf.sparse.to_dense(masks), tf.sparse.to_dense(target)) # self.assertAllEqual(masks.dtype,",
"indices=( [0, 0, 1], [0, 1, 1], [0, 2, 0], [0, 3, 0],",
"dense_shape=(2, 6, 3)) masks = idseqs_to_mask( idseqs, n_seqlen=6, ignore=[1], dense=True, dtype=tf.bool) self.assertAllEqual(masks, tf.sparse.to_dense(target))",
"from keras_tweaks import idseqs_to_mask import tensorflow as tf class AllTests(tf.test.TestCase): def test1(self): idseqs",
"_ in range(8)], dense_shape=(2, 6, 3)) masks = idseqs_to_mask( idseqs, n_seqlen=6, ignore=[1], dense=True,",
"2], [1, 2, 1], [1, 4, 0], [1, 5, 0]), values=[True for _",
"[1, 4, 0], [1, 5, 0]), values=[1 for _ in range(11)], dense_shape=(2, 6,",
"# self.assertAllEqual(masks.dtype, target.dtype) self.assertAllEqual(masks.shape, target.shape) def test4(self): idseqs = [[1, 1, 0, 0,",
"self.assertAllEqual(masks.dtype, target.dtype) self.assertAllEqual(masks.shape, target.shape) def test5(self): idseqs = [[1, 1, 0, 0, 2,",
"[1, 3, 1], [1, 4, 0], [1, 5, 0]), values=[1.0 for _ in",
"dense=False, dtype=tf.bool) self.assertAllEqual( tf.sparse.to_dense(masks), tf.sparse.to_dense(target)) self.assertAllEqual(masks.dtype, target.dtype) self.assertAllEqual(masks.shape, target.shape) def test5(self): idseqs =",
"masks = idseqs_to_mask( idseqs, n_seqlen=6, ignore=[1], dense=True, dtype=tf.bool) self.assertAllEqual(masks, tf.sparse.to_dense(target)) self.assertAllEqual(masks.dtype, target.dtype) self.assertAllEqual(masks.shape,",
"= idseqs_to_mask( idseqs, n_seqlen=6, n_vocab_sz=3, ignore=[3], dense=False, dtype=tf.float64) self.assertAllEqual( tf.sparse.to_dense(masks), tf.sparse.to_dense(target)) # self.assertAllEqual(masks.dtype,",
"0], [1, 5, 0]), values=[True for _ in range(11)], dense_shape=(2, 6, 3)) masks",
"masks = idseqs_to_mask( idseqs, n_seqlen=6, n_vocab_sz=3, ignore=[3], dense=False) self.assertAllEqual( tf.sparse.to_dense(masks), tf.sparse.to_dense(target)) self.assertAllEqual(masks.dtype, target.dtype)",
"in range(11)], dense_shape=(2, 6, 3)) masks = idseqs_to_mask( idseqs, n_seqlen=6, n_vocab_sz=3, ignore=[3], dense=False)",
"class AllTests(tf.test.TestCase): def test1(self): idseqs = [[1, 1, 0, 0, 2, 2, 3],",
"dtype=tf.uint8) self.assertAllEqual( tf.sparse.to_dense(masks), tf.sparse.to_dense(target)) # self.assertAllEqual(masks.dtype, target.dtype) self.assertAllEqual(masks.shape, target.shape) def test3(self): idseqs =",
"idseqs, n_seqlen=6, n_vocab_sz=3, ignore=[3], dense=False, dtype=tf.uint8) self.assertAllEqual( tf.sparse.to_dense(masks), tf.sparse.to_dense(target)) # self.assertAllEqual(masks.dtype, target.dtype) self.assertAllEqual(masks.shape,",
"1, 0, 0, 2, 2, 3], [1, 3, 2, 1, 0, 0, 2]]",
"n_vocab_sz=3, ignore=[3], dense=False, dtype=tf.uint8) self.assertAllEqual( tf.sparse.to_dense(masks), tf.sparse.to_dense(target)) # self.assertAllEqual(masks.dtype, target.dtype) self.assertAllEqual(masks.shape, target.shape) def",
"test1(self): idseqs = [[1, 1, 0, 0, 2, 2, 3], [1, 3, 2,",
"range(8)], dense_shape=(2, 6, 3)) masks = idseqs_to_mask( idseqs, n_seqlen=6, ignore=[1], dense=True, dtype=tf.bool) self.assertAllEqual(masks,",
"[0, 3, 0], [0, 4, 2], [0, 5, 2], [1, 0, 1], [1,",
"test2(self): idseqs = [[1, 1, 0, 0, 2, 2, 3], [1, 3, 2,",
"dense_shape=(2, 6, 3)) masks = idseqs_to_mask( idseqs, n_seqlen=6, n_vocab_sz=3, ignore=[3], dense=False) self.assertAllEqual( tf.sparse.to_dense(masks),",
"tf.sparse.SparseTensor( indices=( [0, 2, 0], [0, 3, 0], [0, 4, 1], [0, 5,",
"5, 0]), values=[True for _ in range(8)], dense_shape=(2, 6, 3)) masks = idseqs_to_mask(",
"[1, 5, 0]), values=[1 for _ in range(11)], dense_shape=(2, 6, 3)) masks =",
"[1, 4, 0], [1, 5, 0]), values=[1.0 for _ in range(11)], dense_shape=(2, 6,",
"idseqs_to_mask( idseqs, n_seqlen=6, ignore=[1], dense=False, dtype=tf.bool) self.assertAllEqual( tf.sparse.to_dense(masks), tf.sparse.to_dense(target)) self.assertAllEqual(masks.dtype, target.dtype) self.assertAllEqual(masks.shape, target.shape)",
"[1, 5, 0]), values=[1.0 for _ in range(11)], dense_shape=(2, 6, 3)) masks =",
"n_vocab_sz=3, ignore=[3], dense=False) self.assertAllEqual( tf.sparse.to_dense(masks), tf.sparse.to_dense(target)) self.assertAllEqual(masks.dtype, target.dtype) self.assertAllEqual(masks.shape, target.shape) def test2(self): idseqs",
"target = tf.sparse.SparseTensor( indices=( [0, 2, 0], [0, 3, 0], [0, 4, 1],",
"dense=False) self.assertAllEqual( tf.sparse.to_dense(masks), tf.sparse.to_dense(target)) self.assertAllEqual(masks.dtype, target.dtype) self.assertAllEqual(masks.shape, target.shape) def test2(self): idseqs = [[1,",
"idseqs, n_seqlen=6, ignore=[1], dense=False, dtype=tf.bool) self.assertAllEqual( tf.sparse.to_dense(masks), tf.sparse.to_dense(target)) self.assertAllEqual(masks.dtype, target.dtype) self.assertAllEqual(masks.shape, target.shape) def",
"3, 1], [1, 4, 0], [1, 5, 0]), values=[1 for _ in range(11)],",
"2, 1, 0, 0, 2]] target = tf.sparse.SparseTensor( indices=( [0, 0, 1], [0,",
"tf.sparse.to_dense(target)) self.assertAllEqual(masks.dtype, target.dtype) self.assertAllEqual(masks.shape, target.shape) def test5(self): idseqs = [[1, 1, 0, 0,",
"1], [1, 2, 2], [1, 3, 1], [1, 4, 0], [1, 5, 0]),",
"3, 0], [0, 4, 2], [0, 5, 2], [1, 0, 1], [1, 2,",
"1, 2], [1, 2, 1], [1, 4, 0], [1, 5, 0]), values=[True for"
] |
[
"from rest_framework import routers import artists.views as artist_views import beats.views as beat_views from",
"\"singular\": \"social-link\" }, { \"plural\": r\"instrumentals\", \"view\": beat_views.InstrumentalView, \"singular\": \"instrumental\" }, { \"plural\":",
"URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from",
"\"plural\": r\"instrumental-collections\", \"view\": beat_views.InstrumentalCollectionView, \"singular\": \"instrumental-collection\" } ] for router_item in router_item_list: router.register(",
"Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf",
"\"singular\": \"artist\" }, { \"plural\": r\"social-links\", \"view\": artist_views.SocialLinkView, \"singular\": \"social-link\" }, { \"plural\":",
"as beat_views from rest_framework_jwt.views import obtain_jwt_token from users.views import current_app_user, AppUserList router =",
"function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/',",
"{ \"plural\": r\"artists\", \"view\": artist_views.ArtistView, \"singular\": \"artist\" }, { \"plural\": r\"social-links\", \"view\": artist_views.SocialLinkView,",
"\"plural\": r\"social-links\", \"view\": artist_views.SocialLinkView, \"singular\": \"social-link\" }, { \"plural\": r\"instrumentals\", \"view\": beat_views.InstrumentalView, \"singular\":",
"routers.DefaultRouter() router_item_list = [ { \"plural\": r\"artists\", \"view\": artist_views.ArtistView, \"singular\": \"artist\" }, {",
"for router_item in router_item_list: router.register( router_item[\"plural\"], router_item[\"view\"], router_item[\"singular\"] ) urlpatterns = [ path('admin/',",
"from rest_framework_jwt.views import obtain_jwt_token from users.views import current_app_user, AppUserList router = routers.DefaultRouter() router_item_list",
"\"artist\" }, { \"plural\": r\"social-links\", \"view\": artist_views.SocialLinkView, \"singular\": \"social-link\" }, { \"plural\": r\"instrumentals\",",
"router.register( router_item[\"plural\"], router_item[\"view\"], router_item[\"singular\"] ) urlpatterns = [ path('admin/', admin.site.urls), path( \"api/\", include(router.urls)",
"Examples: Function views 1. Add an import: from my_app import views 2. Add",
"list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.2/topics/http/urls/ Examples: Function",
"= routers.DefaultRouter() router_item_list = [ { \"plural\": r\"artists\", \"view\": artist_views.ArtistView, \"singular\": \"artist\" },",
"see: https://docs.djangoproject.com/en/3.2/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views",
"1. Add an import: from other_app.views import Home 2. Add a URL to",
"include from rest_framework import routers import artists.views as artist_views import beats.views as beat_views",
"\"instrumental\" }, { \"plural\": r\"instrumental-collections\", \"view\": beat_views.InstrumentalCollectionView, \"singular\": \"instrumental-collection\" } ] for router_item",
"Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import",
"router_item[\"view\"], router_item[\"singular\"] ) urlpatterns = [ path('admin/', admin.site.urls), path( \"api/\", include(router.urls) ), path(",
"}, { \"plural\": r\"instrumentals\", \"view\": beat_views.InstrumentalView, \"singular\": \"instrumental\" }, { \"plural\": r\"instrumental-collections\", \"view\":",
"beats.views as beat_views from rest_framework_jwt.views import obtain_jwt_token from users.views import current_app_user, AppUserList router",
"obtain_jwt_token from users.views import current_app_user, AppUserList router = routers.DefaultRouter() router_item_list = [ {",
"router_item[\"plural\"], router_item[\"view\"], router_item[\"singular\"] ) urlpatterns = [ path('admin/', admin.site.urls), path( \"api/\", include(router.urls) ),",
"views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1.",
"\"view\": beat_views.InstrumentalCollectionView, \"singular\": \"instrumental-collection\" } ] for router_item in router_item_list: router.register( router_item[\"plural\"], router_item[\"view\"],",
"beat_views.InstrumentalCollectionView, \"singular\": \"instrumental-collection\" } ] for router_item in router_item_list: router.register( router_item[\"plural\"], router_item[\"view\"], router_item[\"singular\"]",
"}, { \"plural\": r\"instrumental-collections\", \"view\": beat_views.InstrumentalCollectionView, \"singular\": \"instrumental-collection\" } ] for router_item in",
"django.contrib import admin from django.urls import path, include from rest_framework import routers import",
"import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) \"\"\" from",
"\"view\": artist_views.ArtistView, \"singular\": \"artist\" }, { \"plural\": r\"social-links\", \"view\": artist_views.SocialLinkView, \"singular\": \"social-link\" },",
"in router_item_list: router.register( router_item[\"plural\"], router_item[\"view\"], router_item[\"singular\"] ) urlpatterns = [ path('admin/', admin.site.urls), path(",
"[ { \"plural\": r\"artists\", \"view\": artist_views.ArtistView, \"singular\": \"artist\" }, { \"plural\": r\"social-links\", \"view\":",
"Configuration The `urlpatterns` list routes URLs to views. For more information please see:",
"\"instrumental-collection\" } ] for router_item in router_item_list: router.register( router_item[\"plural\"], router_item[\"view\"], router_item[\"singular\"] ) urlpatterns",
"import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views",
"{ \"plural\": r\"social-links\", \"view\": artist_views.SocialLinkView, \"singular\": \"social-link\" }, { \"plural\": r\"instrumentals\", \"view\": beat_views.InstrumentalView,",
"Add an import: from other_app.views import Home 2. Add a URL to urlpatterns:",
"}, { \"plural\": r\"social-links\", \"view\": artist_views.SocialLinkView, \"singular\": \"social-link\" }, { \"plural\": r\"instrumentals\", \"view\":",
"import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another",
"{ \"plural\": r\"instrumental-collections\", \"view\": beat_views.InstrumentalCollectionView, \"singular\": \"instrumental-collection\" } ] for router_item in router_item_list:",
"django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) \"\"\"",
"as artist_views import beats.views as beat_views from rest_framework_jwt.views import obtain_jwt_token from users.views import",
"`urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.2/topics/http/urls/ Examples:",
"information please see: https://docs.djangoproject.com/en/3.2/topics/http/urls/ Examples: Function views 1. Add an import: from my_app",
"r\"instrumentals\", \"view\": beat_views.InstrumentalView, \"singular\": \"instrumental\" }, { \"plural\": r\"instrumental-collections\", \"view\": beat_views.InstrumentalCollectionView, \"singular\": \"instrumental-collection\"",
"2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1.",
"URLconf 1. Import the include() function: from django.urls import include, path 2. Add",
"import routers import artists.views as artist_views import beats.views as beat_views from rest_framework_jwt.views import",
"a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import:",
"Add an import: from my_app import views 2. Add a URL to urlpatterns:",
"include('blog.urls')) \"\"\" from django.contrib import admin from django.urls import path, include from rest_framework",
"urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import",
"\"view\": artist_views.SocialLinkView, \"singular\": \"social-link\" }, { \"plural\": r\"instrumentals\", \"view\": beat_views.InstrumentalView, \"singular\": \"instrumental\" },",
"from users.views import current_app_user, AppUserList router = routers.DefaultRouter() router_item_list = [ { \"plural\":",
"current_app_user, AppUserList router = routers.DefaultRouter() router_item_list = [ { \"plural\": r\"artists\", \"view\": artist_views.ArtistView,",
"router_item[\"singular\"] ) urlpatterns = [ path('admin/', admin.site.urls), path( \"api/\", include(router.urls) ), path( \"infinite-api/\",",
"a URL to urlpatterns: path('blog/', include('blog.urls')) \"\"\" from django.contrib import admin from django.urls",
"Including another URLconf 1. Import the include() function: from django.urls import include, path",
"path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) \"\"\" from django.contrib import",
"routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.2/topics/http/urls/ Examples: Function views",
"\"infinite-api/\", beat_views.ReactInfiniteInstrumentalView.as_view(), name = \"infinite-react\" ), path('token-auth/', obtain_jwt_token), path('current_user/', current_app_user), path('users/', AppUserList.as_view()) ]",
"\"view\": beat_views.InstrumentalView, \"singular\": \"instrumental\" }, { \"plural\": r\"instrumental-collections\", \"view\": beat_views.InstrumentalCollectionView, \"singular\": \"instrumental-collection\" }",
"\"plural\": r\"artists\", \"view\": artist_views.ArtistView, \"singular\": \"artist\" }, { \"plural\": r\"social-links\", \"view\": artist_views.SocialLinkView, \"singular\":",
"{ \"plural\": r\"instrumentals\", \"view\": beat_views.InstrumentalView, \"singular\": \"instrumental\" }, { \"plural\": r\"instrumental-collections\", \"view\": beat_views.InstrumentalCollectionView,",
"other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including",
"URL Configuration The `urlpatterns` list routes URLs to views. For more information please",
"include(router.urls) ), path( \"infinite-api/\", beat_views.ReactInfiniteInstrumentalView.as_view(), name = \"infinite-react\" ), path('token-auth/', obtain_jwt_token), path('current_user/', current_app_user),",
"from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')",
"from django.contrib import admin from django.urls import path, include from rest_framework import routers",
"import beats.views as beat_views from rest_framework_jwt.views import obtain_jwt_token from users.views import current_app_user, AppUserList",
"beat_views from rest_framework_jwt.views import obtain_jwt_token from users.views import current_app_user, AppUserList router = routers.DefaultRouter()",
"artists.views as artist_views import beats.views as beat_views from rest_framework_jwt.views import obtain_jwt_token from users.views",
"\"singular\": \"instrumental\" }, { \"plural\": r\"instrumental-collections\", \"view\": beat_views.InstrumentalCollectionView, \"singular\": \"instrumental-collection\" } ] for",
"include() function: from django.urls import include, path 2. Add a URL to urlpatterns:",
"router = routers.DefaultRouter() router_item_list = [ { \"plural\": r\"artists\", \"view\": artist_views.ArtistView, \"singular\": \"artist\"",
"artist_views import beats.views as beat_views from rest_framework_jwt.views import obtain_jwt_token from users.views import current_app_user,",
"\"\"\"project_dir URL Configuration The `urlpatterns` list routes URLs to views. For more information",
"an import: from my_app import views 2. Add a URL to urlpatterns: path('',",
"from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home')",
"import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(),",
"beat_views.InstrumentalView, \"singular\": \"instrumental\" }, { \"plural\": r\"instrumental-collections\", \"view\": beat_views.InstrumentalCollectionView, \"singular\": \"instrumental-collection\" } ]",
"Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an",
"path, include from rest_framework import routers import artists.views as artist_views import beats.views as",
"r\"social-links\", \"view\": artist_views.SocialLinkView, \"singular\": \"social-link\" }, { \"plural\": r\"instrumentals\", \"view\": beat_views.InstrumentalView, \"singular\": \"instrumental\"",
"urlpatterns: path('blog/', include('blog.urls')) \"\"\" from django.contrib import admin from django.urls import path, include",
"views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2.",
"name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add",
"from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))",
"\"plural\": r\"instrumentals\", \"view\": beat_views.InstrumentalView, \"singular\": \"instrumental\" }, { \"plural\": r\"instrumental-collections\", \"view\": beat_views.InstrumentalCollectionView, \"singular\":",
"import path, include from rest_framework import routers import artists.views as artist_views import beats.views",
"views 1. Add an import: from my_app import views 2. Add a URL",
"r\"artists\", \"view\": artist_views.ArtistView, \"singular\": \"artist\" }, { \"plural\": r\"social-links\", \"view\": artist_views.SocialLinkView, \"singular\": \"social-link\"",
"\"social-link\" }, { \"plural\": r\"instrumentals\", \"view\": beat_views.InstrumentalView, \"singular\": \"instrumental\" }, { \"plural\": r\"instrumental-collections\",",
"] for router_item in router_item_list: router.register( router_item[\"plural\"], router_item[\"view\"], router_item[\"singular\"] ) urlpatterns = [",
"1. Add an import: from my_app import views 2. Add a URL to",
"Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import",
"= [ path('admin/', admin.site.urls), path( \"api/\", include(router.urls) ), path( \"infinite-api/\", beat_views.ReactInfiniteInstrumentalView.as_view(), name =",
"from django.urls import path, include from rest_framework import routers import artists.views as artist_views",
"my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based",
"please see: https://docs.djangoproject.com/en/3.2/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import",
"to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views",
"the include() function: from django.urls import include, path 2. Add a URL to",
"router_item_list: router.register( router_item[\"plural\"], router_item[\"view\"], router_item[\"singular\"] ) urlpatterns = [ path('admin/', admin.site.urls), path( \"api/\",",
"to views. For more information please see: https://docs.djangoproject.com/en/3.2/topics/http/urls/ Examples: Function views 1. Add",
"2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) \"\"\" from django.contrib import admin",
"path( \"infinite-api/\", beat_views.ReactInfiniteInstrumentalView.as_view(), name = \"infinite-react\" ), path('token-auth/', obtain_jwt_token), path('current_user/', current_app_user), path('users/', AppUserList.as_view())",
"URLs to views. For more information please see: https://docs.djangoproject.com/en/3.2/topics/http/urls/ Examples: Function views 1.",
"Class-based views 1. Add an import: from other_app.views import Home 2. Add a",
"router_item_list = [ { \"plural\": r\"artists\", \"view\": artist_views.ArtistView, \"singular\": \"artist\" }, { \"plural\":",
"r\"instrumental-collections\", \"view\": beat_views.InstrumentalCollectionView, \"singular\": \"instrumental-collection\" } ] for router_item in router_item_list: router.register( router_item[\"plural\"],",
"import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home,",
"Function views 1. Add an import: from my_app import views 2. Add a",
"Import the include() function: from django.urls import include, path 2. Add a URL",
"[ path('admin/', admin.site.urls), path( \"api/\", include(router.urls) ), path( \"infinite-api/\", beat_views.ReactInfiniteInstrumentalView.as_view(), name = \"infinite-react\"",
"The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.2/topics/http/urls/",
"import artists.views as artist_views import beats.views as beat_views from rest_framework_jwt.views import obtain_jwt_token from",
"} ] for router_item in router_item_list: router.register( router_item[\"plural\"], router_item[\"view\"], router_item[\"singular\"] ) urlpatterns =",
"name='home') Including another URLconf 1. Import the include() function: from django.urls import include,",
"urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from",
"django.urls import path, include from rest_framework import routers import artists.views as artist_views import",
"artist_views.ArtistView, \"singular\": \"artist\" }, { \"plural\": r\"social-links\", \"view\": artist_views.SocialLinkView, \"singular\": \"social-link\" }, {",
"Add a URL to urlpatterns: path('blog/', include('blog.urls')) \"\"\" from django.contrib import admin from",
"users.views import current_app_user, AppUserList router = routers.DefaultRouter() router_item_list = [ { \"plural\": r\"artists\",",
"For more information please see: https://docs.djangoproject.com/en/3.2/topics/http/urls/ Examples: Function views 1. Add an import:",
"path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls",
"path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home",
"URL to urlpatterns: path('blog/', include('blog.urls')) \"\"\" from django.contrib import admin from django.urls import",
"to urlpatterns: path('blog/', include('blog.urls')) \"\"\" from django.contrib import admin from django.urls import path,",
"AppUserList router = routers.DefaultRouter() router_item_list = [ { \"plural\": r\"artists\", \"view\": artist_views.ArtistView, \"singular\":",
"import current_app_user, AppUserList router = routers.DefaultRouter() router_item_list = [ { \"plural\": r\"artists\", \"view\":",
"an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('',",
"urlpatterns = [ path('admin/', admin.site.urls), path( \"api/\", include(router.urls) ), path( \"infinite-api/\", beat_views.ReactInfiniteInstrumentalView.as_view(), name",
"\"api/\", include(router.urls) ), path( \"infinite-api/\", beat_views.ReactInfiniteInstrumentalView.as_view(), name = \"infinite-react\" ), path('token-auth/', obtain_jwt_token), path('current_user/',",
") urlpatterns = [ path('admin/', admin.site.urls), path( \"api/\", include(router.urls) ), path( \"infinite-api/\", beat_views.ReactInfiniteInstrumentalView.as_view(),",
"path( \"api/\", include(router.urls) ), path( \"infinite-api/\", beat_views.ReactInfiniteInstrumentalView.as_view(), name = \"infinite-react\" ), path('token-auth/', obtain_jwt_token),",
"admin.site.urls), path( \"api/\", include(router.urls) ), path( \"infinite-api/\", beat_views.ReactInfiniteInstrumentalView.as_view(), name = \"infinite-react\" ), path('token-auth/',",
"\"singular\": \"instrumental-collection\" } ] for router_item in router_item_list: router.register( router_item[\"plural\"], router_item[\"view\"], router_item[\"singular\"] )",
"router_item in router_item_list: router.register( router_item[\"plural\"], router_item[\"view\"], router_item[\"singular\"] ) urlpatterns = [ path('admin/', admin.site.urls),",
"<reponame>cybrvybe/FactorBeats-Platform \"\"\"project_dir URL Configuration The `urlpatterns` list routes URLs to views. For more",
"2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add",
"to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function:",
"https://docs.djangoproject.com/en/3.2/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2.",
"path('blog/', include('blog.urls')) \"\"\" from django.contrib import admin from django.urls import path, include from",
"= [ { \"plural\": r\"artists\", \"view\": artist_views.ArtistView, \"singular\": \"artist\" }, { \"plural\": r\"social-links\",",
"admin from django.urls import path, include from rest_framework import routers import artists.views as",
"path('admin/', admin.site.urls), path( \"api/\", include(router.urls) ), path( \"infinite-api/\", beat_views.ReactInfiniteInstrumentalView.as_view(), name = \"infinite-react\" ),",
"1. Import the include() function: from django.urls import include, path 2. Add a",
"include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) \"\"\" from django.contrib",
"a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the",
"another URLconf 1. Import the include() function: from django.urls import include, path 2.",
"import admin from django.urls import path, include from rest_framework import routers import artists.views",
"routers import artists.views as artist_views import beats.views as beat_views from rest_framework_jwt.views import obtain_jwt_token",
"views. For more information please see: https://docs.djangoproject.com/en/3.2/topics/http/urls/ Examples: Function views 1. Add an",
"views 1. Add an import: from other_app.views import Home 2. Add a URL",
"URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include()",
"more information please see: https://docs.djangoproject.com/en/3.2/topics/http/urls/ Examples: Function views 1. Add an import: from",
"\"\"\" from django.contrib import admin from django.urls import path, include from rest_framework import",
"), path( \"infinite-api/\", beat_views.ReactInfiniteInstrumentalView.as_view(), name = \"infinite-react\" ), path('token-auth/', obtain_jwt_token), path('current_user/', current_app_user), path('users/',",
"import obtain_jwt_token from users.views import current_app_user, AppUserList router = routers.DefaultRouter() router_item_list = [",
"artist_views.SocialLinkView, \"singular\": \"social-link\" }, { \"plural\": r\"instrumentals\", \"view\": beat_views.InstrumentalView, \"singular\": \"instrumental\" }, {",
"rest_framework import routers import artists.views as artist_views import beats.views as beat_views from rest_framework_jwt.views",
"rest_framework_jwt.views import obtain_jwt_token from users.views import current_app_user, AppUserList router = routers.DefaultRouter() router_item_list ="
] |
[
"'CAG'], 'M': ['CAT'], 'N': ['ATT', 'GTT'], 'P': ['AGG', 'GGG', 'TGG', 'CGG'], 'Q': ['TTG',",
"import (BiologicalSequence, NucleotideSequence, DNASequence, RNASequence, ProteinSequence, DNA, RNA, Protein) from ._genetic_code import GeneticCode,",
"types, and for obtaining degenerate character definitions. Additionaly this module defines the ``GeneticCode``",
"'TGA', 'CGA', 'ACT', 'GCT'], 'T': ['AGT', 'GGT', 'TGT', 'CGT'], 'V': ['AAC', 'GAC', 'TAC',",
"True Creating and using a ``GeneticCode`` object >>> from skbio.sequence import genetic_code >>>",
"MSK* (length: 4)> \"\"\" # ---------------------------------------------------------------------------- # Copyright (c) 2013--, scikit-bio development team.",
">>> DNASequence.iupac_degeneracies()['B'] set(['C', 'T', 'G']) >>> RNASequence.iupac_degeneracies()['B'] set(['C', 'U', 'G']) >>> DNASequence.is_gap('-') True",
"'D': ['ATC', 'GTC'], 'E': ['TTC', 'CTC'], 'F': ['AAA', 'GAA'], 'G': ['ACC', 'GCC', 'TCC',",
"InvalidCodonError Examples -------- >>> from skbio.sequence import DNASequence, RNASequence New sequences are created",
"'S': ['AGA', 'GGA', 'TGA', 'CGA', 'ACT', 'GCT'], 'T': ['AGT', 'GGT', 'TGT', 'CGT'], 'V':",
"sgc['UUU'] == 'F' True >>> sgc['TTT'] == 'F' True >>> sgc['F'] == ['TTT',",
"'DNASequence', 'RNASequence', 'ProteinSequence', 'DNA', 'RNA', 'Protein', 'GeneticCode', 'genetic_code'] from numpy.testing import Tester test",
"character sets, complement maps for different sequence types, and for obtaining degenerate character",
"default is Hamming distance) for use in sequence clustering, phylogenetic reconstruction, etc. >>>",
"file COPYING.txt, distributed with this software. # ---------------------------------------------------------------------------- from ._exception import (BiologicalSequenceError, GeneticCodeError,",
"sgc = genetic_code(1) >>> sgc GeneticCode(FFLLSSSSYY**CC*WLLLLPPPPHHQQRRRRIIIMTTTTNNKKSSRRVVVVAAAADDEEGGGG) >>> sgc['UUU'] == 'F' True >>> sgc['TTT']",
"autosummary:: :toctree: generated/ BiologicalSequence NucleotideSequence DNASequence RNASequence ProteinSequence GeneticCode Functions --------- .. autosummary::",
"(optionally using user-defined distance metrics, default is Hamming distance) for use in sequence",
"'AAG', 'GAG', 'TAG', 'CAG'], 'M': ['CAT'], 'N': ['ATT', 'GTT'], 'P': ['AGG', 'GGG', 'TGG',",
"'TGT', 'CGT'], 'V': ['AAC', 'GAC', 'TAC', 'CAC'], 'W': ['CCA'], 'Y': ['ATA', 'GTA']} NucleotideSequences",
">>> pprint(sgc.anticodons) {'*': ['TTA', 'CTA', 'TCA'], 'A': ['AGC', 'GGC', 'TGC', 'CGC'], 'C': ['ACA',",
"['ATA', 'GTA']} NucleotideSequences can be translated using a ``GeneticCode`` object. >>> d6 =",
"0.25 >>> d3.distance(d5) 0.375 Class-level methods contain information about the molecule types. >>>",
"and using a ``GeneticCode`` object >>> from skbio.sequence import genetic_code >>> from pprint",
"object. >>> d6 = DNASequence('ATGTCTAAATGA') >>> from skbio.sequence import genetic_code >>> gc =",
">>> sgc['F'] == ['TTT', 'TTC'] #in arbitrary order True >>> sgc['*'] == ['TAA',",
"= d1.degap() >>> d1 <DNASequence: ACC--G-GGT... (length: 13)> >>> d2 <DNASequence: ACCGGGTA (length:",
"'GAT', 'TAT'], 'K': ['TTT', 'CTT'], 'L': ['TAA', 'CAA', 'AAG', 'GAG', 'TAG', 'CAG'], 'M':",
"-------- >>> from skbio.sequence import DNASequence, RNASequence New sequences are created with optional",
"types. >>> DNASequence.iupac_degeneracies()['B'] set(['C', 'T', 'G']) >>> RNASequence.iupac_degeneracies()['B'] set(['C', 'U', 'G']) >>> DNASequence.is_gap('-')",
"['ACG', 'GCG', 'TCG', 'CCG', 'TCT', 'CCT'], 'S': ['AGA', 'GGA', 'TGA', 'CGA', 'ACT', 'GCT'],",
"import pprint >>> sgc = genetic_code(1) >>> sgc GeneticCode(FFLLSSSSYY**CC*WLLLLPPPPHHQQRRRRIIIMTTTTNNKKSSRRVVVVAAAADDEEGGGG) >>> sgc['UUU'] == 'F'",
"import genetic_code >>> gc = genetic_code(11) >>> gc.translate(d6) <ProteinSequence: MSK* (length: 4)> \"\"\"",
"generated/ genetic_code Exceptions ---------- .. autosummary:: :toctree: generated/ BiologicalSequenceError GeneticCodeError GeneticCodeInitError InvalidCodonError Examples",
"Functions --------- .. autosummary:: :toctree: generated/ genetic_code Exceptions ---------- .. autosummary:: :toctree: generated/",
"from ._exception import (BiologicalSequenceError, GeneticCodeError, GeneticCodeInitError, InvalidCodonError) from ._sequence import (BiologicalSequence, NucleotideSequence, DNASequence,",
"============================================ .. currentmodule:: skbio.sequence This module provides functionality for working with biological sequences,",
"gc = genetic_code(11) >>> gc.translate(d6) <ProteinSequence: MSK* (length: 4)> \"\"\" # ---------------------------------------------------------------------------- #",
"sgc['TTT'] == 'F' True >>> sgc['F'] == ['TTT', 'TTC'] #in arbitrary order True",
">>> sgc['*'] == ['TAA', 'TAG', 'TGA'] #in arbitrary order True Retrieving the anticodons",
"RNA sequences. Class methods and attributes are also available to obtain valid character",
"'CTA', 'TCA'], 'A': ['AGC', 'GGC', 'TGC', 'CGC'], 'C': ['ACA', 'GCA'], 'D': ['ATC', 'GTC'],",
"distances between sequences (optionally using user-defined distance metrics, default is Hamming distance) for",
"skbio.sequence import genetic_code >>> from pprint import pprint >>> sgc = genetic_code(1) >>>",
"# ---------------------------------------------------------------------------- # Copyright (c) 2013--, scikit-bio development team. # # Distributed under",
"'Q': ['TTG', 'CTG'], 'R': ['ACG', 'GCG', 'TCG', 'CCG', 'TCT', 'CCT'], 'S': ['AGA', 'GGA',",
"metrics, default is Hamming distance) for use in sequence clustering, phylogenetic reconstruction, etc.",
"True >>> sgc['TTT'] == 'F' True >>> sgc['F'] == ['TTT', 'TTC'] #in arbitrary",
"import genetic_code >>> from pprint import pprint >>> sgc = genetic_code(1) >>> sgc",
"'CGT'], 'V': ['AAC', 'GAC', 'TAC', 'CAC'], 'W': ['CCA'], 'Y': ['ATA', 'GTA']} NucleotideSequences can",
"'TGC', 'CGC'], 'C': ['ACA', 'GCA'], 'D': ['ATC', 'GTC'], 'E': ['TTC', 'CTC'], 'F': ['AAA',",
"'NucleotideSequence', 'DNASequence', 'RNASequence', 'ProteinSequence', 'DNA', 'RNA', 'Protein', 'GeneticCode', 'genetic_code'] from numpy.testing import Tester",
"'TAG', 'TGA'] #in arbitrary order True Retrieving the anticodons of the object >>>",
"TACCCGGT (length: 8)> It's also straight-forward to compute distances between sequences (optionally using",
"object that translates RNA or DNA strings to amino acid sequences. Classes -------",
"DNASequence('GACCCGCT') >>> d5 = DNASequence('GACCCCCT') >>> d3.distance(d4) 0.25 >>> d3.distance(d5) 0.375 Class-level methods",
"acid sequences. Classes ------- .. autosummary:: :toctree: generated/ BiologicalSequence NucleotideSequence DNASequence RNASequence ProteinSequence",
"Retrieving the anticodons of the object >>> pprint(sgc.anticodons) {'*': ['TTA', 'CTA', 'TCA'], 'A':",
"definitions. Additionaly this module defines the ``GeneticCode`` class, which represents an immutable object",
">>> d3.distance(d4) 0.25 >>> d3.distance(d5) 0.375 Class-level methods contain information about the molecule",
"'TCA'], 'A': ['AGC', 'GGC', 'TGC', 'CGC'], 'C': ['ACA', 'GCA'], 'D': ['ATC', 'GTC'], 'E':",
">>> d6 = DNASequence('ATGTCTAAATGA') >>> from skbio.sequence import genetic_code >>> gc = genetic_code(11)",
"d4 = DNASequence('GACCCGCT') >>> d5 = DNASequence('GACCCCCT') >>> d3.distance(d4) 0.25 >>> d3.distance(d5) 0.375",
".. autosummary:: :toctree: generated/ genetic_code Exceptions ---------- .. autosummary:: :toctree: generated/ BiologicalSequenceError GeneticCodeError",
">>> from skbio.sequence import genetic_code >>> from pprint import pprint >>> sgc =",
"amino acid sequences. Classes ------- .. autosummary:: :toctree: generated/ BiologicalSequence NucleotideSequence DNASequence RNASequence",
"'TGG', 'CGG'], 'Q': ['TTG', 'CTG'], 'R': ['ACG', 'GCG', 'TCG', 'CCG', 'TCT', 'CCT'], 'S':",
"d1 = DNASequence('ACC--G-GGTA..',id=\"seq1\",description=\"GFP\") New sequences can also be created from existing sequences, for",
"distance) for use in sequence clustering, phylogenetic reconstruction, etc. >>> d4 = DNASequence('GACCCGCT')",
"pprint import pprint >>> sgc = genetic_code(1) >>> sgc GeneticCode(FFLLSSSSYY**CC*WLLLLPPPPHHQQRRRRIIIMTTTTNNKKSSRRVVVVAAAADDEEGGGG) >>> sgc['UUU'] ==",
"'GTA']} NucleotideSequences can be translated using a ``GeneticCode`` object. >>> d6 = DNASequence('ATGTCTAAATGA')",
"8)> >>> d3 = d2.reverse_complement() >>> d3 <DNASequence: TACCCGGT (length: 8)> It's also",
":toctree: generated/ BiologicalSequenceError GeneticCodeError GeneticCodeInitError InvalidCodonError Examples -------- >>> from skbio.sequence import DNASequence,",
":toctree: generated/ BiologicalSequence NucleotideSequence DNASequence RNASequence ProteinSequence GeneticCode Functions --------- .. autosummary:: :toctree:",
"genetic_code >>> gc = genetic_code(11) >>> gc.translate(d6) <ProteinSequence: MSK* (length: 4)> \"\"\" #",
"New sequences are created with optional id and description fields. >>> d1 =",
"New sequences can also be created from existing sequences, for example as their",
"set(['C', 'U', 'G']) >>> DNASequence.is_gap('-') True Creating and using a ``GeneticCode`` object >>>",
"'F' True >>> sgc['F'] == ['TTT', 'TTC'] #in arbitrary order True >>> sgc['*']",
"'TTC'] #in arbitrary order True >>> sgc['*'] == ['TAA', 'TAG', 'TGA'] #in arbitrary",
"= d2.reverse_complement() >>> d3 <DNASequence: TACCCGGT (length: 8)> It's also straight-forward to compute",
"['TTT', 'TTC'] #in arbitrary order True >>> sgc['*'] == ['TAA', 'TAG', 'TGA'] #in",
"Classes ------- .. autosummary:: :toctree: generated/ BiologicalSequence NucleotideSequence DNASequence RNASequence ProteinSequence GeneticCode Functions",
"'GGT', 'TGT', 'CGT'], 'V': ['AAC', 'GAC', 'TAC', 'CAC'], 'W': ['CCA'], 'Y': ['ATA', 'GTA']}",
"# # Distributed under the terms of the Modified BSD License. # #",
"------- .. autosummary:: :toctree: generated/ BiologicalSequence NucleotideSequence DNASequence RNASequence ProteinSequence GeneticCode Functions ---------",
"genetic_code >>> from pprint import pprint >>> sgc = genetic_code(1) >>> sgc GeneticCode(FFLLSSSSYY**CC*WLLLLPPPPHHQQRRRRIIIMTTTTNNKKSSRRVVVVAAAADDEEGGGG)",
"'ACT', 'GCT'], 'T': ['AGT', 'GGT', 'TGT', 'CGT'], 'V': ['AAC', 'GAC', 'TAC', 'CAC'], 'W':",
">>> sgc['UUU'] == 'F' True >>> sgc['TTT'] == 'F' True >>> sgc['F'] ==",
"(c) 2013--, scikit-bio development team. # # Distributed under the terms of the",
"'V': ['AAC', 'GAC', 'TAC', 'CAC'], 'W': ['CCA'], 'Y': ['ATA', 'GTA']} NucleotideSequences can be",
"['CCA'], 'Y': ['ATA', 'GTA']} NucleotideSequences can be translated using a ``GeneticCode`` object. >>>",
"d2 <DNASequence: ACCGGGTA (length: 8)> >>> d3 = d2.reverse_complement() >>> d3 <DNASequence: TACCCGGT",
"GeneticCodeInitError, InvalidCodonError) from ._sequence import (BiologicalSequence, NucleotideSequence, DNASequence, RNASequence, ProteinSequence, DNA, RNA, Protein)",
"'ProteinSequence', 'DNA', 'RNA', 'Protein', 'GeneticCode', 'genetic_code'] from numpy.testing import Tester test = Tester().test",
"methods contain information about the molecule types. >>> DNASequence.iupac_degeneracies()['B'] set(['C', 'T', 'G']) >>>",
"__all__ = ['BiologicalSequenceError', 'GeneticCodeError', 'GeneticCodeInitError', 'InvalidCodonError', 'BiologicalSequence', 'NucleotideSequence', 'DNASequence', 'RNASequence', 'ProteinSequence', 'DNA', 'RNA',",
"13)> >>> d2 <DNASequence: ACCGGGTA (length: 8)> >>> d3 = d2.reverse_complement() >>> d3",
"created with optional id and description fields. >>> d1 = DNASequence('ACC--G-GGTA..') >>> d1",
"ACCGGGTA (length: 8)> >>> d3 = d2.reverse_complement() >>> d3 <DNASequence: TACCCGGT (length: 8)>",
"'CGG'], 'Q': ['TTG', 'CTG'], 'R': ['ACG', 'GCG', 'TCG', 'CCG', 'TCT', 'CCT'], 'S': ['AGA',",
"license is in the file COPYING.txt, distributed with this software. # ---------------------------------------------------------------------------- from",
"DNA strings to amino acid sequences. Classes ------- .. autosummary:: :toctree: generated/ BiologicalSequence",
"['TTT', 'CTT'], 'L': ['TAA', 'CAA', 'AAG', 'GAG', 'TAG', 'CAG'], 'M': ['CAT'], 'N': ['ATT',",
"sequences are created with optional id and description fields. >>> d1 = DNASequence('ACC--G-GGTA..')",
"genetic_code(1) >>> sgc GeneticCode(FFLLSSSSYY**CC*WLLLLPPPPHHQQRRRRIIIMTTTTNNKKSSRRVVVVAAAADDEEGGGG) >>> sgc['UUU'] == 'F' True >>> sgc['TTT'] == 'F'",
"= genetic_code(11) >>> gc.translate(d6) <ProteinSequence: MSK* (length: 4)> \"\"\" # ---------------------------------------------------------------------------- # Copyright",
"the object >>> pprint(sgc.anticodons) {'*': ['TTA', 'CTA', 'TCA'], 'A': ['AGC', 'GGC', 'TGC', 'CGC'],",
"= genetic_code(1) >>> sgc GeneticCode(FFLLSSSSYY**CC*WLLLLPPPPHHQQRRRRIIIMTTTTNNKKSSRRVVVVAAAADDEEGGGG) >>> sgc['UUU'] == 'F' True >>> sgc['TTT'] ==",
">>> d3 = d2.reverse_complement() >>> d3 <DNASequence: TACCCGGT (length: 8)> It's also straight-forward",
"and RNA sequences. Class methods and attributes are also available to obtain valid",
"description fields. >>> d1 = DNASequence('ACC--G-GGTA..') >>> d1 = DNASequence('ACC--G-GGTA..',id=\"seq1\") >>> d1 =",
"pprint >>> sgc = genetic_code(1) >>> sgc GeneticCode(FFLLSSSSYY**CC*WLLLLPPPPHHQQRRRRIIIMTTTTNNKKSSRRVVVVAAAADDEEGGGG) >>> sgc['UUU'] == 'F' True",
"sequences. Class methods and attributes are also available to obtain valid character sets,",
"import (BiologicalSequenceError, GeneticCodeError, GeneticCodeInitError, InvalidCodonError) from ._sequence import (BiologicalSequence, NucleotideSequence, DNASequence, RNASequence, ProteinSequence,",
"= DNASequence('ACC--G-GGTA..',id=\"seq1\") >>> d1 = DNASequence('ACC--G-GGTA..',id=\"seq1\",description=\"GFP\") New sequences can also be created from",
"'GGA', 'TGA', 'CGA', 'ACT', 'GCT'], 'T': ['AGT', 'GGT', 'TGT', 'CGT'], 'V': ['AAC', 'GAC',",
">>> d3 <DNASequence: TACCCGGT (length: 8)> It's also straight-forward to compute distances between",
"d3 = d2.reverse_complement() >>> d3 <DNASequence: TACCCGGT (length: 8)> It's also straight-forward to",
"'InvalidCodonError', 'BiologicalSequence', 'NucleotideSequence', 'DNASequence', 'RNASequence', 'ProteinSequence', 'DNA', 'RNA', 'Protein', 'GeneticCode', 'genetic_code'] from numpy.testing",
"['AGT', 'GGT', 'TGT', 'CGT'], 'V': ['AAC', 'GAC', 'TAC', 'CAC'], 'W': ['CCA'], 'Y': ['ATA',",
"# Copyright (c) 2013--, scikit-bio development team. # # Distributed under the terms",
"RNASequence New sequences are created with optional id and description fields. >>> d1",
"skbio.sequence This module provides functionality for working with biological sequences, including generic sequences,",
"contain information about the molecule types. >>> DNASequence.iupac_degeneracies()['B'] set(['C', 'T', 'G']) >>> RNASequence.iupac_degeneracies()['B']",
"'G']) >>> DNASequence.is_gap('-') True Creating and using a ``GeneticCode`` object >>> from skbio.sequence",
"---------- .. autosummary:: :toctree: generated/ BiologicalSequenceError GeneticCodeError GeneticCodeInitError InvalidCodonError Examples -------- >>> from",
"reverse complement or degapped (i.e., unaligned) version. >>> d2 = d1.degap() >>> d1",
"2013--, scikit-bio development team. # # Distributed under the terms of the Modified",
"Distributed under the terms of the Modified BSD License. # # The full",
"GeneticCode Functions --------- .. autosummary:: :toctree: generated/ genetic_code Exceptions ---------- .. autosummary:: :toctree:",
"and attributes are also available to obtain valid character sets, complement maps for",
"Creating and using a ``GeneticCode`` object >>> from skbio.sequence import genetic_code >>> from",
"the anticodons of the object >>> pprint(sgc.anticodons) {'*': ['TTA', 'CTA', 'TCA'], 'A': ['AGC',",
"['AAA', 'GAA'], 'G': ['ACC', 'GCC', 'TCC', 'CCC'], 'H': ['ATG', 'GTG'], 'I': ['AAT', 'GAT',",
"with optional id and description fields. >>> d1 = DNASequence('ACC--G-GGTA..') >>> d1 =",
">>> sgc GeneticCode(FFLLSSSSYY**CC*WLLLLPPPPHHQQRRRRIIIMTTTTNNKKSSRRVVVVAAAADDEEGGGG) >>> sgc['UUU'] == 'F' True >>> sgc['TTT'] == 'F' True",
"'E': ['TTC', 'CTC'], 'F': ['AAA', 'GAA'], 'G': ['ACC', 'GCC', 'TCC', 'CCC'], 'H': ['ATG',",
"as their reverse complement or degapped (i.e., unaligned) version. >>> d2 = d1.degap()",
"'GTC'], 'E': ['TTC', 'CTC'], 'F': ['AAA', 'GAA'], 'G': ['ACC', 'GCC', 'TCC', 'CCC'], 'H':",
"the Modified BSD License. # # The full license is in the file",
"'CTG'], 'R': ['ACG', 'GCG', 'TCG', 'CCG', 'TCT', 'CCT'], 'S': ['AGA', 'GGA', 'TGA', 'CGA',",
"between sequences (optionally using user-defined distance metrics, default is Hamming distance) for use",
"obtain valid character sets, complement maps for different sequence types, and for obtaining",
"sequences (:mod:`skbio.sequence`) ============================================ .. currentmodule:: skbio.sequence This module provides functionality for working with",
"<DNASequence: TACCCGGT (length: 8)> It's also straight-forward to compute distances between sequences (optionally",
"maps for different sequence types, and for obtaining degenerate character definitions. Additionaly this",
"d1 <DNASequence: ACC--G-GGT... (length: 13)> >>> d2 <DNASequence: ACCGGGTA (length: 8)> >>> d3",
">>> from skbio.sequence import DNASequence, RNASequence New sequences are created with optional id",
"'U', 'G']) >>> DNASequence.is_gap('-') True Creating and using a ``GeneticCode`` object >>> from",
"sets, complement maps for different sequence types, and for obtaining degenerate character definitions.",
"using user-defined distance metrics, default is Hamming distance) for use in sequence clustering,",
".. currentmodule:: skbio.sequence This module provides functionality for working with biological sequences, including",
"['ACC', 'GCC', 'TCC', 'CCC'], 'H': ['ATG', 'GTG'], 'I': ['AAT', 'GAT', 'TAT'], 'K': ['TTT',",
"'TAC', 'CAC'], 'W': ['CCA'], 'Y': ['ATA', 'GTA']} NucleotideSequences can be translated using a",
"the ``GeneticCode`` class, which represents an immutable object that translates RNA or DNA",
"can be translated using a ``GeneticCode`` object. >>> d6 = DNASequence('ATGTCTAAATGA') >>> from",
"'TCC', 'CCC'], 'H': ['ATG', 'GTG'], 'I': ['AAT', 'GAT', 'TAT'], 'K': ['TTT', 'CTT'], 'L':",
">>> sgc = genetic_code(1) >>> sgc GeneticCode(FFLLSSSSYY**CC*WLLLLPPPPHHQQRRRRIIIMTTTTNNKKSSRRVVVVAAAADDEEGGGG) >>> sgc['UUU'] == 'F' True >>>",
">>> sgc['TTT'] == 'F' True >>> sgc['F'] == ['TTT', 'TTC'] #in arbitrary order",
"'L': ['TAA', 'CAA', 'AAG', 'GAG', 'TAG', 'CAG'], 'M': ['CAT'], 'N': ['ATT', 'GTT'], 'P':",
"degenerate character definitions. Additionaly this module defines the ``GeneticCode`` class, which represents an",
"Exceptions ---------- .. autosummary:: :toctree: generated/ BiologicalSequenceError GeneticCodeError GeneticCodeInitError InvalidCodonError Examples -------- >>>",
"(length: 8)> It's also straight-forward to compute distances between sequences (optionally using user-defined",
"using a ``GeneticCode`` object. >>> d6 = DNASequence('ATGTCTAAATGA') >>> from skbio.sequence import genetic_code",
"order True Retrieving the anticodons of the object >>> pprint(sgc.anticodons) {'*': ['TTA', 'CTA',",
"COPYING.txt, distributed with this software. # ---------------------------------------------------------------------------- from ._exception import (BiologicalSequenceError, GeneticCodeError, GeneticCodeInitError,",
"the terms of the Modified BSD License. # # The full license is",
"d2.reverse_complement() >>> d3 <DNASequence: TACCCGGT (length: 8)> It's also straight-forward to compute distances",
"RNASequence, ProteinSequence, DNA, RNA, Protein) from ._genetic_code import GeneticCode, genetic_code __all__ = ['BiologicalSequenceError',",
"pprint(sgc.anticodons) {'*': ['TTA', 'CTA', 'TCA'], 'A': ['AGC', 'GGC', 'TGC', 'CGC'], 'C': ['ACA', 'GCA'],",
"team. # # Distributed under the terms of the Modified BSD License. #",
"from skbio.sequence import DNASequence, RNASequence New sequences are created with optional id and",
"['AGA', 'GGA', 'TGA', 'CGA', 'ACT', 'GCT'], 'T': ['AGT', 'GGT', 'TGT', 'CGT'], 'V': ['AAC',",
"'GTG'], 'I': ['AAT', 'GAT', 'TAT'], 'K': ['TTT', 'CTT'], 'L': ['TAA', 'CAA', 'AAG', 'GAG',",
"Biological sequences (:mod:`skbio.sequence`) ============================================ .. currentmodule:: skbio.sequence This module provides functionality for working",
"``GeneticCode`` class, which represents an immutable object that translates RNA or DNA strings",
"True >>> sgc['F'] == ['TTT', 'TTC'] #in arbitrary order True >>> sgc['*'] ==",
"arbitrary order True >>> sgc['*'] == ['TAA', 'TAG', 'TGA'] #in arbitrary order True",
"id and description fields. >>> d1 = DNASequence('ACC--G-GGTA..') >>> d1 = DNASequence('ACC--G-GGTA..',id=\"seq1\") >>>",
"# ---------------------------------------------------------------------------- from ._exception import (BiologicalSequenceError, GeneticCodeError, GeneticCodeInitError, InvalidCodonError) from ._sequence import (BiologicalSequence,",
"#in arbitrary order True >>> sgc['*'] == ['TAA', 'TAG', 'TGA'] #in arbitrary order",
"This module provides functionality for working with biological sequences, including generic sequences, nucelotide",
">>> d5 = DNASequence('GACCCCCT') >>> d3.distance(d4) 0.25 >>> d3.distance(d5) 0.375 Class-level methods contain",
"= DNASequence('GACCCCCT') >>> d3.distance(d4) 0.25 >>> d3.distance(d5) 0.375 Class-level methods contain information about",
"It's also straight-forward to compute distances between sequences (optionally using user-defined distance metrics,",
"'CCT'], 'S': ['AGA', 'GGA', 'TGA', 'CGA', 'ACT', 'GCT'], 'T': ['AGT', 'GGT', 'TGT', 'CGT'],",
"with this software. # ---------------------------------------------------------------------------- from ._exception import (BiologicalSequenceError, GeneticCodeError, GeneticCodeInitError, InvalidCodonError) from",
"in sequence clustering, phylogenetic reconstruction, etc. >>> d4 = DNASequence('GACCCGCT') >>> d5 =",
">>> d1 = DNASequence('ACC--G-GGTA..') >>> d1 = DNASequence('ACC--G-GGTA..',id=\"seq1\") >>> d1 = DNASequence('ACC--G-GGTA..',id=\"seq1\",description=\"GFP\") New",
"version. >>> d2 = d1.degap() >>> d1 <DNASequence: ACC--G-GGT... (length: 13)> >>> d2",
"['TTA', 'CTA', 'TCA'], 'A': ['AGC', 'GGC', 'TGC', 'CGC'], 'C': ['ACA', 'GCA'], 'D': ['ATC',",
"True >>> sgc['*'] == ['TAA', 'TAG', 'TGA'] #in arbitrary order True Retrieving the",
"module defines the ``GeneticCode`` class, which represents an immutable object that translates RNA",
"d3.distance(d4) 0.25 >>> d3.distance(d5) 0.375 Class-level methods contain information about the molecule types.",
"DNASequence('ATGTCTAAATGA') >>> from skbio.sequence import genetic_code >>> gc = genetic_code(11) >>> gc.translate(d6) <ProteinSequence:",
"'GGG', 'TGG', 'CGG'], 'Q': ['TTG', 'CTG'], 'R': ['ACG', 'GCG', 'TCG', 'CCG', 'TCT', 'CCT'],",
"order True >>> sgc['*'] == ['TAA', 'TAG', 'TGA'] #in arbitrary order True Retrieving",
"or DNA strings to amino acid sequences. Classes ------- .. autosummary:: :toctree: generated/",
"to compute distances between sequences (optionally using user-defined distance metrics, default is Hamming",
"biological sequences, including generic sequences, nucelotide sequences, DNA sequences, and RNA sequences. Class",
"example as their reverse complement or degapped (i.e., unaligned) version. >>> d2 =",
"under the terms of the Modified BSD License. # # The full license",
"from ._sequence import (BiologicalSequence, NucleotideSequence, DNASequence, RNASequence, ProteinSequence, DNA, RNA, Protein) from ._genetic_code",
"complement or degapped (i.e., unaligned) version. >>> d2 = d1.degap() >>> d1 <DNASequence:",
"immutable object that translates RNA or DNA strings to amino acid sequences. Classes",
"distributed with this software. # ---------------------------------------------------------------------------- from ._exception import (BiologicalSequenceError, GeneticCodeError, GeneticCodeInitError, InvalidCodonError)",
"in the file COPYING.txt, distributed with this software. # ---------------------------------------------------------------------------- from ._exception import",
"ProteinSequence, DNA, RNA, Protein) from ._genetic_code import GeneticCode, genetic_code __all__ = ['BiologicalSequenceError', 'GeneticCodeError',",
"available to obtain valid character sets, complement maps for different sequence types, and",
"d5 = DNASequence('GACCCCCT') >>> d3.distance(d4) 0.25 >>> d3.distance(d5) 0.375 Class-level methods contain information",
"DNASequence.iupac_degeneracies()['B'] set(['C', 'T', 'G']) >>> RNASequence.iupac_degeneracies()['B'] set(['C', 'U', 'G']) >>> DNASequence.is_gap('-') True Creating",
"functionality for working with biological sequences, including generic sequences, nucelotide sequences, DNA sequences,",
">>> gc = genetic_code(11) >>> gc.translate(d6) <ProteinSequence: MSK* (length: 4)> \"\"\" # ----------------------------------------------------------------------------",
"sequences, nucelotide sequences, DNA sequences, and RNA sequences. Class methods and attributes are",
"character definitions. Additionaly this module defines the ``GeneticCode`` class, which represents an immutable",
"object >>> from skbio.sequence import genetic_code >>> from pprint import pprint >>> sgc",
"d1.degap() >>> d1 <DNASequence: ACC--G-GGT... (length: 13)> >>> d2 <DNASequence: ACCGGGTA (length: 8)>",
"from ._genetic_code import GeneticCode, genetic_code __all__ = ['BiologicalSequenceError', 'GeneticCodeError', 'GeneticCodeInitError', 'InvalidCodonError', 'BiologicalSequence', 'NucleotideSequence',",
"a ``GeneticCode`` object >>> from skbio.sequence import genetic_code >>> from pprint import pprint",
"autosummary:: :toctree: generated/ genetic_code Exceptions ---------- .. autosummary:: :toctree: generated/ BiologicalSequenceError GeneticCodeError GeneticCodeInitError",
"'TGA'] #in arbitrary order True Retrieving the anticodons of the object >>> pprint(sgc.anticodons)",
"(BiologicalSequenceError, GeneticCodeError, GeneticCodeInitError, InvalidCodonError) from ._sequence import (BiologicalSequence, NucleotideSequence, DNASequence, RNASequence, ProteinSequence, DNA,",
"DNASequence, RNASequence New sequences are created with optional id and description fields. >>>",
"._exception import (BiologicalSequenceError, GeneticCodeError, GeneticCodeInitError, InvalidCodonError) from ._sequence import (BiologicalSequence, NucleotideSequence, DNASequence, RNASequence,",
"provides functionality for working with biological sequences, including generic sequences, nucelotide sequences, DNA",
"anticodons of the object >>> pprint(sgc.anticodons) {'*': ['TTA', 'CTA', 'TCA'], 'A': ['AGC', 'GGC',",
">>> d2 = d1.degap() >>> d1 <DNASequence: ACC--G-GGT... (length: 13)> >>> d2 <DNASequence:",
"(BiologicalSequence, NucleotideSequence, DNASequence, RNASequence, ProteinSequence, DNA, RNA, Protein) from ._genetic_code import GeneticCode, genetic_code",
"<reponame>Kleptobismol/scikit-bio r\"\"\" Biological sequences (:mod:`skbio.sequence`) ============================================ .. currentmodule:: skbio.sequence This module provides functionality",
"working with biological sequences, including generic sequences, nucelotide sequences, DNA sequences, and RNA",
"for different sequence types, and for obtaining degenerate character definitions. Additionaly this module",
"which represents an immutable object that translates RNA or DNA strings to amino",
"generated/ BiologicalSequenceError GeneticCodeError GeneticCodeInitError InvalidCodonError Examples -------- >>> from skbio.sequence import DNASequence, RNASequence",
"['AAT', 'GAT', 'TAT'], 'K': ['TTT', 'CTT'], 'L': ['TAA', 'CAA', 'AAG', 'GAG', 'TAG', 'CAG'],",
"Modified BSD License. # # The full license is in the file COPYING.txt,",
"'CAC'], 'W': ['CCA'], 'Y': ['ATA', 'GTA']} NucleotideSequences can be translated using a ``GeneticCode``",
"0.375 Class-level methods contain information about the molecule types. >>> DNASequence.iupac_degeneracies()['B'] set(['C', 'T',",
"autosummary:: :toctree: generated/ BiologicalSequenceError GeneticCodeError GeneticCodeInitError InvalidCodonError Examples -------- >>> from skbio.sequence import",
"RNA, Protein) from ._genetic_code import GeneticCode, genetic_code __all__ = ['BiologicalSequenceError', 'GeneticCodeError', 'GeneticCodeInitError', 'InvalidCodonError',",
"obtaining degenerate character definitions. Additionaly this module defines the ``GeneticCode`` class, which represents",
"unaligned) version. >>> d2 = d1.degap() >>> d1 <DNASequence: ACC--G-GGT... (length: 13)> >>>",
"'CCG', 'TCT', 'CCT'], 'S': ['AGA', 'GGA', 'TGA', 'CGA', 'ACT', 'GCT'], 'T': ['AGT', 'GGT',",
"'CGC'], 'C': ['ACA', 'GCA'], 'D': ['ATC', 'GTC'], 'E': ['TTC', 'CTC'], 'F': ['AAA', 'GAA'],",
"existing sequences, for example as their reverse complement or degapped (i.e., unaligned) version.",
"sgc['*'] == ['TAA', 'TAG', 'TGA'] #in arbitrary order True Retrieving the anticodons of",
"object >>> pprint(sgc.anticodons) {'*': ['TTA', 'CTA', 'TCA'], 'A': ['AGC', 'GGC', 'TGC', 'CGC'], 'C':",
"sequences, including generic sequences, nucelotide sequences, DNA sequences, and RNA sequences. Class methods",
"['TTG', 'CTG'], 'R': ['ACG', 'GCG', 'TCG', 'CCG', 'TCT', 'CCT'], 'S': ['AGA', 'GGA', 'TGA',",
"scikit-bio development team. # # Distributed under the terms of the Modified BSD",
"Additionaly this module defines the ``GeneticCode`` class, which represents an immutable object that",
"NucleotideSequence DNASequence RNASequence ProteinSequence GeneticCode Functions --------- .. autosummary:: :toctree: generated/ genetic_code Exceptions",
"reconstruction, etc. >>> d4 = DNASequence('GACCCGCT') >>> d5 = DNASequence('GACCCCCT') >>> d3.distance(d4) 0.25",
"BSD License. # # The full license is in the file COPYING.txt, distributed",
"full license is in the file COPYING.txt, distributed with this software. # ----------------------------------------------------------------------------",
"translated using a ``GeneticCode`` object. >>> d6 = DNASequence('ATGTCTAAATGA') >>> from skbio.sequence import",
"genetic_code(11) >>> gc.translate(d6) <ProteinSequence: MSK* (length: 4)> \"\"\" # ---------------------------------------------------------------------------- # Copyright (c)",
"d6 = DNASequence('ATGTCTAAATGA') >>> from skbio.sequence import genetic_code >>> gc = genetic_code(11) >>>",
"for example as their reverse complement or degapped (i.e., unaligned) version. >>> d2",
"sgc['F'] == ['TTT', 'TTC'] #in arbitrary order True >>> sgc['*'] == ['TAA', 'TAG',",
"Protein) from ._genetic_code import GeneticCode, genetic_code __all__ = ['BiologicalSequenceError', 'GeneticCodeError', 'GeneticCodeInitError', 'InvalidCodonError', 'BiologicalSequence',",
"'GAG', 'TAG', 'CAG'], 'M': ['CAT'], 'N': ['ATT', 'GTT'], 'P': ['AGG', 'GGG', 'TGG', 'CGG'],",
"BiologicalSequence NucleotideSequence DNASequence RNASequence ProteinSequence GeneticCode Functions --------- .. autosummary:: :toctree: generated/ genetic_code",
"DNASequence('ACC--G-GGTA..') >>> d1 = DNASequence('ACC--G-GGTA..',id=\"seq1\") >>> d1 = DNASequence('ACC--G-GGTA..',id=\"seq1\",description=\"GFP\") New sequences can also",
"'T', 'G']) >>> RNASequence.iupac_degeneracies()['B'] set(['C', 'U', 'G']) >>> DNASequence.is_gap('-') True Creating and using",
"import DNASequence, RNASequence New sequences are created with optional id and description fields.",
"['TTC', 'CTC'], 'F': ['AAA', 'GAA'], 'G': ['ACC', 'GCC', 'TCC', 'CCC'], 'H': ['ATG', 'GTG'],",
"= DNASequence('GACCCGCT') >>> d5 = DNASequence('GACCCCCT') >>> d3.distance(d4) 0.25 >>> d3.distance(d5) 0.375 Class-level",
"d1 = DNASequence('ACC--G-GGTA..',id=\"seq1\") >>> d1 = DNASequence('ACC--G-GGTA..',id=\"seq1\",description=\"GFP\") New sequences can also be created",
"['AGC', 'GGC', 'TGC', 'CGC'], 'C': ['ACA', 'GCA'], 'D': ['ATC', 'GTC'], 'E': ['TTC', 'CTC'],",
">>> d2 <DNASequence: ACCGGGTA (length: 8)> >>> d3 = d2.reverse_complement() >>> d3 <DNASequence:",
"DNASequence('ACC--G-GGTA..',id=\"seq1\",description=\"GFP\") New sequences can also be created from existing sequences, for example as",
"'CGA', 'ACT', 'GCT'], 'T': ['AGT', 'GGT', 'TGT', 'CGT'], 'V': ['AAC', 'GAC', 'TAC', 'CAC'],",
"be translated using a ``GeneticCode`` object. >>> d6 = DNASequence('ATGTCTAAATGA') >>> from skbio.sequence",
"information about the molecule types. >>> DNASequence.iupac_degeneracies()['B'] set(['C', 'T', 'G']) >>> RNASequence.iupac_degeneracies()['B'] set(['C',",
"generic sequences, nucelotide sequences, DNA sequences, and RNA sequences. Class methods and attributes",
"are created with optional id and description fields. >>> d1 = DNASequence('ACC--G-GGTA..') >>>",
"RNASequence.iupac_degeneracies()['B'] set(['C', 'U', 'G']) >>> DNASequence.is_gap('-') True Creating and using a ``GeneticCode`` object",
"The full license is in the file COPYING.txt, distributed with this software. #",
"GeneticCode, genetic_code __all__ = ['BiologicalSequenceError', 'GeneticCodeError', 'GeneticCodeInitError', 'InvalidCodonError', 'BiologicalSequence', 'NucleotideSequence', 'DNASequence', 'RNASequence', 'ProteinSequence',",
"== 'F' True >>> sgc['TTT'] == 'F' True >>> sgc['F'] == ['TTT', 'TTC']",
"software. # ---------------------------------------------------------------------------- from ._exception import (BiologicalSequenceError, GeneticCodeError, GeneticCodeInitError, InvalidCodonError) from ._sequence import",
"DNA sequences, and RNA sequences. Class methods and attributes are also available to",
"also be created from existing sequences, for example as their reverse complement or",
"a ``GeneticCode`` object. >>> d6 = DNASequence('ATGTCTAAATGA') >>> from skbio.sequence import genetic_code >>>",
"'GCT'], 'T': ['AGT', 'GGT', 'TGT', 'CGT'], 'V': ['AAC', 'GAC', 'TAC', 'CAC'], 'W': ['CCA'],",
"sequences. Classes ------- .. autosummary:: :toctree: generated/ BiologicalSequence NucleotideSequence DNASequence RNASequence ProteinSequence GeneticCode",
"also straight-forward to compute distances between sequences (optionally using user-defined distance metrics, default",
"== ['TTT', 'TTC'] #in arbitrary order True >>> sgc['*'] == ['TAA', 'TAG', 'TGA']",
"from existing sequences, for example as their reverse complement or degapped (i.e., unaligned)",
"DNASequence('GACCCCCT') >>> d3.distance(d4) 0.25 >>> d3.distance(d5) 0.375 Class-level methods contain information about the",
"are also available to obtain valid character sets, complement maps for different sequence",
"<DNASequence: ACCGGGTA (length: 8)> >>> d3 = d2.reverse_complement() >>> d3 <DNASequence: TACCCGGT (length:",
">>> RNASequence.iupac_degeneracies()['B'] set(['C', 'U', 'G']) >>> DNASequence.is_gap('-') True Creating and using a ``GeneticCode``",
"== 'F' True >>> sgc['F'] == ['TTT', 'TTC'] #in arbitrary order True >>>",
"or degapped (i.e., unaligned) version. >>> d2 = d1.degap() >>> d1 <DNASequence: ACC--G-GGT...",
"Examples -------- >>> from skbio.sequence import DNASequence, RNASequence New sequences are created with",
"= DNASequence('ATGTCTAAATGA') >>> from skbio.sequence import genetic_code >>> gc = genetic_code(11) >>> gc.translate(d6)",
"'TAT'], 'K': ['TTT', 'CTT'], 'L': ['TAA', 'CAA', 'AAG', 'GAG', 'TAG', 'CAG'], 'M': ['CAT'],",
"can also be created from existing sequences, for example as their reverse complement",
"'K': ['TTT', 'CTT'], 'L': ['TAA', 'CAA', 'AAG', 'GAG', 'TAG', 'CAG'], 'M': ['CAT'], 'N':",
"sequence types, and for obtaining degenerate character definitions. Additionaly this module defines the",
"--------- .. autosummary:: :toctree: generated/ genetic_code Exceptions ---------- .. autosummary:: :toctree: generated/ BiologicalSequenceError",
"complement maps for different sequence types, and for obtaining degenerate character definitions. Additionaly",
"be created from existing sequences, for example as their reverse complement or degapped",
"'GeneticCodeError', 'GeneticCodeInitError', 'InvalidCodonError', 'BiologicalSequence', 'NucleotideSequence', 'DNASequence', 'RNASequence', 'ProteinSequence', 'DNA', 'RNA', 'Protein', 'GeneticCode', 'genetic_code']",
"8)> It's also straight-forward to compute distances between sequences (optionally using user-defined distance",
"this module defines the ``GeneticCode`` class, which represents an immutable object that translates",
"gc.translate(d6) <ProteinSequence: MSK* (length: 4)> \"\"\" # ---------------------------------------------------------------------------- # Copyright (c) 2013--, scikit-bio",
"BiologicalSequenceError GeneticCodeError GeneticCodeInitError InvalidCodonError Examples -------- >>> from skbio.sequence import DNASequence, RNASequence New",
"represents an immutable object that translates RNA or DNA strings to amino acid",
"created from existing sequences, for example as their reverse complement or degapped (i.e.,",
"License. # # The full license is in the file COPYING.txt, distributed with",
"sequences, and RNA sequences. Class methods and attributes are also available to obtain",
"'GCG', 'TCG', 'CCG', 'TCT', 'CCT'], 'S': ['AGA', 'GGA', 'TGA', 'CGA', 'ACT', 'GCT'], 'T':",
"class, which represents an immutable object that translates RNA or DNA strings to",
"etc. >>> d4 = DNASequence('GACCCGCT') >>> d5 = DNASequence('GACCCCCT') >>> d3.distance(d4) 0.25 >>>",
"{'*': ['TTA', 'CTA', 'TCA'], 'A': ['AGC', 'GGC', 'TGC', 'CGC'], 'C': ['ACA', 'GCA'], 'D':",
"# Distributed under the terms of the Modified BSD License. # # The",
"clustering, phylogenetic reconstruction, etc. >>> d4 = DNASequence('GACCCGCT') >>> d5 = DNASequence('GACCCCCT') >>>",
"development team. # # Distributed under the terms of the Modified BSD License.",
"with biological sequences, including generic sequences, nucelotide sequences, DNA sequences, and RNA sequences.",
"'I': ['AAT', 'GAT', 'TAT'], 'K': ['TTT', 'CTT'], 'L': ['TAA', 'CAA', 'AAG', 'GAG', 'TAG',",
"optional id and description fields. >>> d1 = DNASequence('ACC--G-GGTA..') >>> d1 = DNASequence('ACC--G-GGTA..',id=\"seq1\")",
"'R': ['ACG', 'GCG', 'TCG', 'CCG', 'TCT', 'CCT'], 'S': ['AGA', 'GGA', 'TGA', 'CGA', 'ACT',",
"sequences, for example as their reverse complement or degapped (i.e., unaligned) version. >>>",
"their reverse complement or degapped (i.e., unaligned) version. >>> d2 = d1.degap() >>>",
"r\"\"\" Biological sequences (:mod:`skbio.sequence`) ============================================ .. currentmodule:: skbio.sequence This module provides functionality for",
"d2 = d1.degap() >>> d1 <DNASequence: ACC--G-GGT... (length: 13)> >>> d2 <DNASequence: ACCGGGTA",
"terms of the Modified BSD License. # # The full license is in",
"``GeneticCode`` object >>> from skbio.sequence import genetic_code >>> from pprint import pprint >>>",
"'GCA'], 'D': ['ATC', 'GTC'], 'E': ['TTC', 'CTC'], 'F': ['AAA', 'GAA'], 'G': ['ACC', 'GCC',",
"'F' True >>> sgc['TTT'] == 'F' True >>> sgc['F'] == ['TTT', 'TTC'] #in",
"(length: 4)> \"\"\" # ---------------------------------------------------------------------------- # Copyright (c) 2013--, scikit-bio development team. #",
"is in the file COPYING.txt, distributed with this software. # ---------------------------------------------------------------------------- from ._exception",
"._sequence import (BiologicalSequence, NucleotideSequence, DNASequence, RNASequence, ProteinSequence, DNA, RNA, Protein) from ._genetic_code import",
"from skbio.sequence import genetic_code >>> from pprint import pprint >>> sgc = genetic_code(1)",
"for working with biological sequences, including generic sequences, nucelotide sequences, DNA sequences, and",
"the file COPYING.txt, distributed with this software. # ---------------------------------------------------------------------------- from ._exception import (BiologicalSequenceError,",
"'G': ['ACC', 'GCC', 'TCC', 'CCC'], 'H': ['ATG', 'GTG'], 'I': ['AAT', 'GAT', 'TAT'], 'K':",
"DNASequence, RNASequence, ProteinSequence, DNA, RNA, Protein) from ._genetic_code import GeneticCode, genetic_code __all__ =",
"to obtain valid character sets, complement maps for different sequence types, and for",
"'CAA', 'AAG', 'GAG', 'TAG', 'CAG'], 'M': ['CAT'], 'N': ['ATT', 'GTT'], 'P': ['AGG', 'GGG',",
"d3 <DNASequence: TACCCGGT (length: 8)> It's also straight-forward to compute distances between sequences",
"'GCC', 'TCC', 'CCC'], 'H': ['ATG', 'GTG'], 'I': ['AAT', 'GAT', 'TAT'], 'K': ['TTT', 'CTT'],",
"for obtaining degenerate character definitions. Additionaly this module defines the ``GeneticCode`` class, which",
">>> DNASequence.is_gap('-') True Creating and using a ``GeneticCode`` object >>> from skbio.sequence import",
"skbio.sequence import genetic_code >>> gc = genetic_code(11) >>> gc.translate(d6) <ProteinSequence: MSK* (length: 4)>",
"'RNASequence', 'ProteinSequence', 'DNA', 'RNA', 'Protein', 'GeneticCode', 'genetic_code'] from numpy.testing import Tester test =",
"True Retrieving the anticodons of the object >>> pprint(sgc.anticodons) {'*': ['TTA', 'CTA', 'TCA'],",
"['TAA', 'TAG', 'TGA'] #in arbitrary order True Retrieving the anticodons of the object",
"degapped (i.e., unaligned) version. >>> d2 = d1.degap() >>> d1 <DNASequence: ACC--G-GGT... (length:",
"['ATG', 'GTG'], 'I': ['AAT', 'GAT', 'TAT'], 'K': ['TTT', 'CTT'], 'L': ['TAA', 'CAA', 'AAG',",
"Class-level methods contain information about the molecule types. >>> DNASequence.iupac_degeneracies()['B'] set(['C', 'T', 'G'])",
"---------------------------------------------------------------------------- # Copyright (c) 2013--, scikit-bio development team. # # Distributed under the",
"genetic_code __all__ = ['BiologicalSequenceError', 'GeneticCodeError', 'GeneticCodeInitError', 'InvalidCodonError', 'BiologicalSequence', 'NucleotideSequence', 'DNASequence', 'RNASequence', 'ProteinSequence', 'DNA',",
"['AGG', 'GGG', 'TGG', 'CGG'], 'Q': ['TTG', 'CTG'], 'R': ['ACG', 'GCG', 'TCG', 'CCG', 'TCT',",
"<DNASequence: ACC--G-GGT... (length: 13)> >>> d2 <DNASequence: ACCGGGTA (length: 8)> >>> d3 =",
"['ACA', 'GCA'], 'D': ['ATC', 'GTC'], 'E': ['TTC', 'CTC'], 'F': ['AAA', 'GAA'], 'G': ['ACC',",
"['TAA', 'CAA', 'AAG', 'GAG', 'TAG', 'CAG'], 'M': ['CAT'], 'N': ['ATT', 'GTT'], 'P': ['AGG',",
"nucelotide sequences, DNA sequences, and RNA sequences. Class methods and attributes are also",
"'GGC', 'TGC', 'CGC'], 'C': ['ACA', 'GCA'], 'D': ['ATC', 'GTC'], 'E': ['TTC', 'CTC'], 'F':",
"and description fields. >>> d1 = DNASequence('ACC--G-GGTA..') >>> d1 = DNASequence('ACC--G-GGTA..',id=\"seq1\") >>> d1",
"that translates RNA or DNA strings to amino acid sequences. Classes ------- ..",
">>> d1 <DNASequence: ACC--G-GGT... (length: 13)> >>> d2 <DNASequence: ACCGGGTA (length: 8)> >>>",
">>> d1 = DNASequence('ACC--G-GGTA..',id=\"seq1\",description=\"GFP\") New sequences can also be created from existing sequences,",
"methods and attributes are also available to obtain valid character sets, complement maps",
"['AAC', 'GAC', 'TAC', 'CAC'], 'W': ['CCA'], 'Y': ['ATA', 'GTA']} NucleotideSequences can be translated",
"'CCC'], 'H': ['ATG', 'GTG'], 'I': ['AAT', 'GAT', 'TAT'], 'K': ['TTT', 'CTT'], 'L': ['TAA',",
"4)> \"\"\" # ---------------------------------------------------------------------------- # Copyright (c) 2013--, scikit-bio development team. # #",
"attributes are also available to obtain valid character sets, complement maps for different",
"RNA or DNA strings to amino acid sequences. Classes ------- .. autosummary:: :toctree:",
"genetic_code Exceptions ---------- .. autosummary:: :toctree: generated/ BiologicalSequenceError GeneticCodeError GeneticCodeInitError InvalidCodonError Examples --------",
">>> d4 = DNASequence('GACCCGCT') >>> d5 = DNASequence('GACCCCCT') >>> d3.distance(d4) 0.25 >>> d3.distance(d5)",
"of the object >>> pprint(sgc.anticodons) {'*': ['TTA', 'CTA', 'TCA'], 'A': ['AGC', 'GGC', 'TGC',",
"of the Modified BSD License. # # The full license is in the",
"= DNASequence('ACC--G-GGTA..') >>> d1 = DNASequence('ACC--G-GGTA..',id=\"seq1\") >>> d1 = DNASequence('ACC--G-GGTA..',id=\"seq1\",description=\"GFP\") New sequences can",
"(:mod:`skbio.sequence`) ============================================ .. currentmodule:: skbio.sequence This module provides functionality for working with biological",
"phylogenetic reconstruction, etc. >>> d4 = DNASequence('GACCCGCT') >>> d5 = DNASequence('GACCCCCT') >>> d3.distance(d4)",
"Hamming distance) for use in sequence clustering, phylogenetic reconstruction, etc. >>> d4 =",
"DNASequence RNASequence ProteinSequence GeneticCode Functions --------- .. autosummary:: :toctree: generated/ genetic_code Exceptions ----------",
"NucleotideSequences can be translated using a ``GeneticCode`` object. >>> d6 = DNASequence('ATGTCTAAATGA') >>>",
"arbitrary order True Retrieving the anticodons of the object >>> pprint(sgc.anticodons) {'*': ['TTA',",
".. autosummary:: :toctree: generated/ BiologicalSequenceError GeneticCodeError GeneticCodeInitError InvalidCodonError Examples -------- >>> from skbio.sequence",
"import GeneticCode, genetic_code __all__ = ['BiologicalSequenceError', 'GeneticCodeError', 'GeneticCodeInitError', 'InvalidCodonError', 'BiologicalSequence', 'NucleotideSequence', 'DNASequence', 'RNASequence',",
">>> from skbio.sequence import genetic_code >>> gc = genetic_code(11) >>> gc.translate(d6) <ProteinSequence: MSK*",
"['BiologicalSequenceError', 'GeneticCodeError', 'GeneticCodeInitError', 'InvalidCodonError', 'BiologicalSequence', 'NucleotideSequence', 'DNASequence', 'RNASequence', 'ProteinSequence', 'DNA', 'RNA', 'Protein', 'GeneticCode',",
"ACC--G-GGT... (length: 13)> >>> d2 <DNASequence: ACCGGGTA (length: 8)> >>> d3 = d2.reverse_complement()",
"'H': ['ATG', 'GTG'], 'I': ['AAT', 'GAT', 'TAT'], 'K': ['TTT', 'CTT'], 'L': ['TAA', 'CAA',",
"GeneticCodeInitError InvalidCodonError Examples -------- >>> from skbio.sequence import DNASequence, RNASequence New sequences are",
"'GAC', 'TAC', 'CAC'], 'W': ['CCA'], 'Y': ['ATA', 'GTA']} NucleotideSequences can be translated using",
"['ATC', 'GTC'], 'E': ['TTC', 'CTC'], 'F': ['AAA', 'GAA'], 'G': ['ACC', 'GCC', 'TCC', 'CCC'],",
"'T': ['AGT', 'GGT', 'TGT', 'CGT'], 'V': ['AAC', 'GAC', 'TAC', 'CAC'], 'W': ['CCA'], 'Y':",
"strings to amino acid sequences. Classes ------- .. autosummary:: :toctree: generated/ BiologicalSequence NucleotideSequence",
"generated/ BiologicalSequence NucleotideSequence DNASequence RNASequence ProteinSequence GeneticCode Functions --------- .. autosummary:: :toctree: generated/",
"also available to obtain valid character sets, complement maps for different sequence types,",
"'P': ['AGG', 'GGG', 'TGG', 'CGG'], 'Q': ['TTG', 'CTG'], 'R': ['ACG', 'GCG', 'TCG', 'CCG',",
"<ProteinSequence: MSK* (length: 4)> \"\"\" # ---------------------------------------------------------------------------- # Copyright (c) 2013--, scikit-bio development",
"RNASequence ProteinSequence GeneticCode Functions --------- .. autosummary:: :toctree: generated/ genetic_code Exceptions ---------- ..",
"DNASequence('ACC--G-GGTA..',id=\"seq1\") >>> d1 = DNASequence('ACC--G-GGTA..',id=\"seq1\",description=\"GFP\") New sequences can also be created from existing",
"``GeneticCode`` object. >>> d6 = DNASequence('ATGTCTAAATGA') >>> from skbio.sequence import genetic_code >>> gc",
"GeneticCodeError, GeneticCodeInitError, InvalidCodonError) from ._sequence import (BiologicalSequence, NucleotideSequence, DNASequence, RNASequence, ProteinSequence, DNA, RNA,",
"Class methods and attributes are also available to obtain valid character sets, complement",
"from pprint import pprint >>> sgc = genetic_code(1) >>> sgc GeneticCode(FFLLSSSSYY**CC*WLLLLPPPPHHQQRRRRIIIMTTTTNNKKSSRRVVVVAAAADDEEGGGG) >>> sgc['UUU']",
"translates RNA or DNA strings to amino acid sequences. Classes ------- .. autosummary::",
"'GAA'], 'G': ['ACC', 'GCC', 'TCC', 'CCC'], 'H': ['ATG', 'GTG'], 'I': ['AAT', 'GAT', 'TAT'],",
"'C': ['ACA', 'GCA'], 'D': ['ATC', 'GTC'], 'E': ['TTC', 'CTC'], 'F': ['AAA', 'GAA'], 'G':",
"(length: 8)> >>> d3 = d2.reverse_complement() >>> d3 <DNASequence: TACCCGGT (length: 8)> It's",
"Copyright (c) 2013--, scikit-bio development team. # # Distributed under the terms of",
"\"\"\" # ---------------------------------------------------------------------------- # Copyright (c) 2013--, scikit-bio development team. # # Distributed",
"currentmodule:: skbio.sequence This module provides functionality for working with biological sequences, including generic",
"about the molecule types. >>> DNASequence.iupac_degeneracies()['B'] set(['C', 'T', 'G']) >>> RNASequence.iupac_degeneracies()['B'] set(['C', 'U',",
"'A': ['AGC', 'GGC', 'TGC', 'CGC'], 'C': ['ACA', 'GCA'], 'D': ['ATC', 'GTC'], 'E': ['TTC',",
"(i.e., unaligned) version. >>> d2 = d1.degap() >>> d1 <DNASequence: ACC--G-GGT... (length: 13)>",
"'CTC'], 'F': ['AAA', 'GAA'], 'G': ['ACC', 'GCC', 'TCC', 'CCC'], 'H': ['ATG', 'GTG'], 'I':",
"DNA, RNA, Protein) from ._genetic_code import GeneticCode, genetic_code __all__ = ['BiologicalSequenceError', 'GeneticCodeError', 'GeneticCodeInitError',",
"to amino acid sequences. Classes ------- .. autosummary:: :toctree: generated/ BiologicalSequence NucleotideSequence DNASequence",
"'F': ['AAA', 'GAA'], 'G': ['ACC', 'GCC', 'TCC', 'CCC'], 'H': ['ATG', 'GTG'], 'I': ['AAT',",
"(length: 13)> >>> d2 <DNASequence: ACCGGGTA (length: 8)> >>> d3 = d2.reverse_complement() >>>",
"from skbio.sequence import genetic_code >>> gc = genetic_code(11) >>> gc.translate(d6) <ProteinSequence: MSK* (length:",
"d3.distance(d5) 0.375 Class-level methods contain information about the molecule types. >>> DNASequence.iupac_degeneracies()['B'] set(['C',",
"= ['BiologicalSequenceError', 'GeneticCodeError', 'GeneticCodeInitError', 'InvalidCodonError', 'BiologicalSequence', 'NucleotideSequence', 'DNASequence', 'RNASequence', 'ProteinSequence', 'DNA', 'RNA', 'Protein',",
"using a ``GeneticCode`` object >>> from skbio.sequence import genetic_code >>> from pprint import",
"for use in sequence clustering, phylogenetic reconstruction, etc. >>> d4 = DNASequence('GACCCGCT') >>>",
"'N': ['ATT', 'GTT'], 'P': ['AGG', 'GGG', 'TGG', 'CGG'], 'Q': ['TTG', 'CTG'], 'R': ['ACG',",
"skbio.sequence import DNASequence, RNASequence New sequences are created with optional id and description",
"'GeneticCodeInitError', 'InvalidCodonError', 'BiologicalSequence', 'NucleotideSequence', 'DNASequence', 'RNASequence', 'ProteinSequence', 'DNA', 'RNA', 'Protein', 'GeneticCode', 'genetic_code'] from",
"sequences (optionally using user-defined distance metrics, default is Hamming distance) for use in",
"set(['C', 'T', 'G']) >>> RNASequence.iupac_degeneracies()['B'] set(['C', 'U', 'G']) >>> DNASequence.is_gap('-') True Creating and",
"._genetic_code import GeneticCode, genetic_code __all__ = ['BiologicalSequenceError', 'GeneticCodeError', 'GeneticCodeInitError', 'InvalidCodonError', 'BiologicalSequence', 'NucleotideSequence', 'DNASequence',",
"straight-forward to compute distances between sequences (optionally using user-defined distance metrics, default is",
"module provides functionality for working with biological sequences, including generic sequences, nucelotide sequences,",
"'TAG', 'CAG'], 'M': ['CAT'], 'N': ['ATT', 'GTT'], 'P': ['AGG', 'GGG', 'TGG', 'CGG'], 'Q':",
"GeneticCode(FFLLSSSSYY**CC*WLLLLPPPPHHQQRRRRIIIMTTTTNNKKSSRRVVVVAAAADDEEGGGG) >>> sgc['UUU'] == 'F' True >>> sgc['TTT'] == 'F' True >>> sgc['F']",
"and for obtaining degenerate character definitions. Additionaly this module defines the ``GeneticCode`` class,",
"'M': ['CAT'], 'N': ['ATT', 'GTT'], 'P': ['AGG', 'GGG', 'TGG', 'CGG'], 'Q': ['TTG', 'CTG'],",
".. autosummary:: :toctree: generated/ BiologicalSequence NucleotideSequence DNASequence RNASequence ProteinSequence GeneticCode Functions --------- ..",
"= DNASequence('ACC--G-GGTA..',id=\"seq1\",description=\"GFP\") New sequences can also be created from existing sequences, for example",
"'G']) >>> RNASequence.iupac_degeneracies()['B'] set(['C', 'U', 'G']) >>> DNASequence.is_gap('-') True Creating and using a",
"sequences, DNA sequences, and RNA sequences. Class methods and attributes are also available",
"ProteinSequence GeneticCode Functions --------- .. autosummary:: :toctree: generated/ genetic_code Exceptions ---------- .. autosummary::",
"molecule types. >>> DNASequence.iupac_degeneracies()['B'] set(['C', 'T', 'G']) >>> RNASequence.iupac_degeneracies()['B'] set(['C', 'U', 'G']) >>>",
"d1 = DNASequence('ACC--G-GGTA..') >>> d1 = DNASequence('ACC--G-GGTA..',id=\"seq1\") >>> d1 = DNASequence('ACC--G-GGTA..',id=\"seq1\",description=\"GFP\") New sequences",
"== ['TAA', 'TAG', 'TGA'] #in arbitrary order True Retrieving the anticodons of the",
"InvalidCodonError) from ._sequence import (BiologicalSequence, NucleotideSequence, DNASequence, RNASequence, ProteinSequence, DNA, RNA, Protein) from",
"different sequence types, and for obtaining degenerate character definitions. Additionaly this module defines",
"defines the ``GeneticCode`` class, which represents an immutable object that translates RNA or",
"'TCG', 'CCG', 'TCT', 'CCT'], 'S': ['AGA', 'GGA', 'TGA', 'CGA', 'ACT', 'GCT'], 'T': ['AGT',",
"this software. # ---------------------------------------------------------------------------- from ._exception import (BiologicalSequenceError, GeneticCodeError, GeneticCodeInitError, InvalidCodonError) from ._sequence",
">>> gc.translate(d6) <ProteinSequence: MSK* (length: 4)> \"\"\" # ---------------------------------------------------------------------------- # Copyright (c) 2013--,",
"# # The full license is in the file COPYING.txt, distributed with this",
"valid character sets, complement maps for different sequence types, and for obtaining degenerate",
"GeneticCodeError GeneticCodeInitError InvalidCodonError Examples -------- >>> from skbio.sequence import DNASequence, RNASequence New sequences",
"use in sequence clustering, phylogenetic reconstruction, etc. >>> d4 = DNASequence('GACCCGCT') >>> d5",
">>> d3.distance(d5) 0.375 Class-level methods contain information about the molecule types. >>> DNASequence.iupac_degeneracies()['B']",
"sequences can also be created from existing sequences, for example as their reverse",
">>> from pprint import pprint >>> sgc = genetic_code(1) >>> sgc GeneticCode(FFLLSSSSYY**CC*WLLLLPPPPHHQQRRRRIIIMTTTTNNKKSSRRVVVVAAAADDEEGGGG) >>>",
"'Y': ['ATA', 'GTA']} NucleotideSequences can be translated using a ``GeneticCode`` object. >>> d6",
"'TCT', 'CCT'], 'S': ['AGA', 'GGA', 'TGA', 'CGA', 'ACT', 'GCT'], 'T': ['AGT', 'GGT', 'TGT',",
":toctree: generated/ genetic_code Exceptions ---------- .. autosummary:: :toctree: generated/ BiologicalSequenceError GeneticCodeError GeneticCodeInitError InvalidCodonError",
"compute distances between sequences (optionally using user-defined distance metrics, default is Hamming distance)",
"distance metrics, default is Hamming distance) for use in sequence clustering, phylogenetic reconstruction,",
"user-defined distance metrics, default is Hamming distance) for use in sequence clustering, phylogenetic",
"#in arbitrary order True Retrieving the anticodons of the object >>> pprint(sgc.anticodons) {'*':",
"---------------------------------------------------------------------------- from ._exception import (BiologicalSequenceError, GeneticCodeError, GeneticCodeInitError, InvalidCodonError) from ._sequence import (BiologicalSequence, NucleotideSequence,",
"sgc GeneticCode(FFLLSSSSYY**CC*WLLLLPPPPHHQQRRRRIIIMTTTTNNKKSSRRVVVVAAAADDEEGGGG) >>> sgc['UUU'] == 'F' True >>> sgc['TTT'] == 'F' True >>>",
"is Hamming distance) for use in sequence clustering, phylogenetic reconstruction, etc. >>> d4",
"the molecule types. >>> DNASequence.iupac_degeneracies()['B'] set(['C', 'T', 'G']) >>> RNASequence.iupac_degeneracies()['B'] set(['C', 'U', 'G'])",
"an immutable object that translates RNA or DNA strings to amino acid sequences.",
"['CAT'], 'N': ['ATT', 'GTT'], 'P': ['AGG', 'GGG', 'TGG', 'CGG'], 'Q': ['TTG', 'CTG'], 'R':",
"NucleotideSequence, DNASequence, RNASequence, ProteinSequence, DNA, RNA, Protein) from ._genetic_code import GeneticCode, genetic_code __all__",
">>> d1 = DNASequence('ACC--G-GGTA..',id=\"seq1\") >>> d1 = DNASequence('ACC--G-GGTA..',id=\"seq1\",description=\"GFP\") New sequences can also be",
"including generic sequences, nucelotide sequences, DNA sequences, and RNA sequences. Class methods and",
"['ATT', 'GTT'], 'P': ['AGG', 'GGG', 'TGG', 'CGG'], 'Q': ['TTG', 'CTG'], 'R': ['ACG', 'GCG',",
"'BiologicalSequence', 'NucleotideSequence', 'DNASequence', 'RNASequence', 'ProteinSequence', 'DNA', 'RNA', 'Protein', 'GeneticCode', 'genetic_code'] from numpy.testing import",
"sequence clustering, phylogenetic reconstruction, etc. >>> d4 = DNASequence('GACCCGCT') >>> d5 = DNASequence('GACCCCCT')",
"DNASequence.is_gap('-') True Creating and using a ``GeneticCode`` object >>> from skbio.sequence import genetic_code",
"'GTT'], 'P': ['AGG', 'GGG', 'TGG', 'CGG'], 'Q': ['TTG', 'CTG'], 'R': ['ACG', 'GCG', 'TCG',",
"'W': ['CCA'], 'Y': ['ATA', 'GTA']} NucleotideSequences can be translated using a ``GeneticCode`` object.",
"'CTT'], 'L': ['TAA', 'CAA', 'AAG', 'GAG', 'TAG', 'CAG'], 'M': ['CAT'], 'N': ['ATT', 'GTT'],",
"# The full license is in the file COPYING.txt, distributed with this software.",
"fields. >>> d1 = DNASequence('ACC--G-GGTA..') >>> d1 = DNASequence('ACC--G-GGTA..',id=\"seq1\") >>> d1 = DNASequence('ACC--G-GGTA..',id=\"seq1\",description=\"GFP\")"
] |
[
"[3, 3.39011, 0.626892]], } def calc_S_msd(gamma_k, a_k, T, n_ltc): def cot(x): return 1/np.tan(x)",
"'msd'): n_msd = kwargs['n_msd'] A = calc_A_from_poles(J.poles) gamma_k = np.zeros(len(A), dtype=np.complex128) a_k =",
"poles poles[(0, 1, 0)] = T_0 if (R_1 != 0): poles[(0, 0, 0)]",
"T # calc psd coeffs n_psd = kwargs['n_psd'] type_psd = kwargs['type_psd'] xi, eta,",
"((gamma_n, deg) in A): a_vec[ctr] = A[(gamma_n, deg)] ctr += 1 block_size =",
"1, type_psd = 'N-1/N')) # noise = calc_noise_params(*calc_noise_time_domain(J, T, 'msd', # n_msd =",
"= a_mat) def noise_decomposition(J, T, type_ltc, **kwargs): return calc_noise_params(*calc_noise_time_domain(J, T, type_ltc, **kwargs)) #",
"n_list = [[0, T, 1, 0]] return calc_S_from_poles(J.poles, n_list), calc_A_from_poles(J.poles) elif (type_ltc ==",
"0 gamma[ctr,ctr] = gamma_n if deg > 0: gamma[ctr,ctr-1] = -deg if ((gamma_n,",
"return result def calc_noise_time_domain(J, T, type_ltc, **kwargs): if (type_ltc == 'none'): n_list =",
"1, 0)] = T_0 if (R_1 != 0): poles[(0, 0, 0)] = R_1",
"gamma a_k[k] = A[(gamma, 0)] return calc_S_msd(gamma_k, a_k, T, n_msd), A elif (type_ltc",
"for (a, m, n), b in poles.items()] return calc_S_from_poles(J.poles, n_list), calc_A_from_poles(J.poles) else: raise",
"fsd_coeffs = { 100.0: [[1, 1.35486, 1.34275], [2, 5.50923, 0.880362], [3, 0.553793, -0.965783]],",
"= OrderedDict() for gamma, n in itertools.chain(S.keys(), A.keys()): if (gamma == np.inf): continue",
"= 2*eta[p]*T_0 ## fsd poles poles[(0, 1, 0)] += coeff_0 for j, a,",
"type_ltc, **kwargs): return calc_noise_params(*calc_noise_time_domain(J, T, type_ltc, **kwargs)) # noise = calc_noise_params(*calc_noise_time_domain(None, T, 'psd+fsd',",
"kwargs['n_msd'] A = calc_A_from_poles(J.poles) gamma_k = np.zeros(len(A), dtype=np.complex128) a_k = np.zeros(len(A), dtype=np.complex128) for",
"noise_decomposition(J, T, type_ltc, **kwargs): return calc_noise_params(*calc_noise_time_domain(J, T, type_ltc, **kwargs)) # noise = calc_noise_params(*calc_noise_time_domain(None,",
"T, 'psd', # n_psd = 1, type_psd = 'N-1/N')) # noise = calc_noise_params(*calc_noise_time_domain(J,",
"} def calc_S_msd(gamma_k, a_k, T, n_ltc): def cot(x): return 1/np.tan(x) n_m = a_k.shape[0]",
"T_0 = T_n else: T_0 = T # calc psd coeffs n_psd =",
"# n_fsd_rec=1, chi_fsd=100.0)) # noise = calc_noise_params(*calc_noise_time_domain(J, T, 'psd', # n_psd = 1,",
"= np.zeros(len(A), dtype=np.complex128) a_k = np.zeros(len(A), dtype=np.complex128) for k, (gamma, l) in enumerate(A.keys()):",
"poles.items()] return calc_S_from_poles(J.poles, n_list), calc_A_from_poles(J.poles) else: raise Exception('[Error] Unknown ltc') def calc_noise_params(S, A):",
"+= T_n - T_np1 T_n = T_np1 for j, a, b in fsd_coeffs[chi_fsd]:",
"a, b, T_n]) T_0 = T_n else: T_0 = T # calc psd",
"distributed under BSD 3-Clause License. # See LINCENSE.txt for licence. # ------------------------------------------------------------------------ import",
"= 0 for gamma_n, deg_max in phi_deg_dict.items(): for deg in range(deg_max): phi.append((gamma_n, deg))",
"= n + 1 phi_dim = sum((n for n in phi_deg_dict.values())) # phi",
"n + 1) else: phi_deg_dict[gamma] = n + 1 phi_dim = sum((n for",
"cot(x): return 1/np.tan(x) n_m = a_k.shape[0] n_k = n_ltc nu_k = np.zeros(n_k) s_k",
"a_k[k] = A[(gamma, 0)] return calc_S_msd(gamma_k, a_k, T, n_msd), A elif (type_ltc ==",
"type_ltc == 'psd+fsd' ): coeffs = [] coeff_0 = 0 if type_ltc ==",
"ctr = 0 for gamma_n, deg_max in phi_deg_dict.items(): for deg in range(deg_max): phi.append((gamma_n,",
"\\ = get_commuting_matrix(a_vec[ctr-block_size:ctr], gamma[ctr-block_size:ctr, ctr-block_size:ctr].todense(), sigma[ctr-block_size:ctr]) S_delta = 0.0 if (np.inf, 0) in",
"calc_A_from_poles(J.poles) elif (type_ltc == 'msd'): n_msd = kwargs['n_msd'] A = calc_A_from_poles(J.poles) gamma_k =",
"in range(n_m): put_coeff(gamma_k[k], 0, s_k[k]) for k in range(n_k): put_coeff(nu_k[k], 0, s_k[k +",
"-0.965783]], 1000.0: [[1, 79.1394, 0.637942], [1, 0.655349, 0.666920], [2, 11.6632, 0.456271], [2, 1.54597,",
"in fsd_coeffs[chi_fsd]: coeffs.append([j, a, b, T_n]) T_0 = T_n else: T_0 = T",
"--> for m in range(n_m): s_k[m] = -2*a_k[m]*cot(gamma_k[m]/(2*T))/2.0 for k in range(n_k): s_k[n_m+k]",
"0): poles[(0, 0, 1)] = T_3 for p in range(n_psd): poles[(T_0*xi[p], 1, 0)]",
"Degeneracy phi_deg_dict = OrderedDict() for gamma, n in itertools.chain(S.keys(), A.keys()): if (gamma ==",
"a_mat[ctr-block_size:ctr, ctr-block_size:ctr] \\ = get_commuting_matrix(a_vec[ctr-block_size:ctr], gamma[ctr-block_size:ctr, ctr-block_size:ctr].todense(), sigma[ctr-block_size:ctr]) S_delta = 0.0 if (np.inf,",
"(a, m) in result: result[(a, m)] += coeff else: result[(a, m)] = coeff",
"A): # Calculate Basis Degeneracy phi_deg_dict = OrderedDict() for gamma, n in itertools.chain(S.keys(),",
"r_k[m] --> for m in range(n_m): s_k[m] = -2*a_k[m]*cot(gamma_k[m]/(2*T))/2.0 for k in range(n_k):",
"coeff_0 += T_n - T_np1 T_n = T_np1 for j, a, b in",
"# noise = calc_noise_params(*calc_noise_time_domain(J, T, 'msd', # n_msd = 10)) # noise =",
"calc_noise_params(*calc_noise_time_domain(J, T, 'psd', # n_psd = 1, type_psd = 'N-1/N')) # noise =",
"in S: S_delta = S[(np.inf, 0)] return dict(gamma = gamma, sigma = sigma,",
"0, 0)] = R_1 if (T_3 != 0): poles[(0, 0, 1)] = T_3",
"sigma[ctr-block_size:ctr]) S_delta = 0.0 if (np.inf, 0) in S: S_delta = S[(np.inf, 0)]",
"= 0.0 if (np.inf, 0) in S: S_delta = S[(np.inf, 0)] return dict(gamma",
"#{} is degenerated.'.format(k)) # r_k[m] --> for m in range(n_m): s_k[m] = -2*a_k[m]*cot(gamma_k[m]/(2*T))/2.0",
"= gamma, sigma = sigma, phi_0 = phi_0, s = s_mat, S_delta =",
"Calculate Basis Degeneracy phi_deg_dict = OrderedDict() for gamma, n in itertools.chain(S.keys(), A.keys()): if",
"A[(gamma, 0)] return calc_S_msd(gamma_k, a_k, T, n_msd), A elif (type_ltc == 'psd' or",
"fsd_coeffs[chi_fsd]: coeffs.append([j, a, b, T_n]) T_0 = T_n else: T_0 = T #",
"as np import scipy as sp import scipy.sparse import itertools from collections import",
"Exception('[Error] Unknown ltc') def calc_noise_params(S, A): # Calculate Basis Degeneracy phi_deg_dict = OrderedDict()",
"phi.append((gamma_n, deg)) phi_0[ctr] = 1 if deg == 0 else 0 gamma[ctr,ctr] =",
"np.zeros(n_k) s_k = np.zeros(n_m + n_k, dtype=a_k.dtype) S_delta = 0.0 for k in",
"gamma_k[m]**2) S_delta += -2*T*a_k[m]*inner result = OrderedDict() def put_coeff(a, m, coeff): if (a,",
"type_ltc == 'psd+fsd': n_fsd_rec = kwargs['n_fsd_rec'] chi_fsd = kwargs['chi_fsd'] # calc fsd coeffs",
"for k in range(n_k): inner -= 2/(nu_k[k]**2 - gamma_k[m]**2) S_delta += -2*T*a_k[m]*inner result",
"= calc_noise_params(*calc_noise_time_domain(J, T, 'psd+fsd', # n_psd = 1, type_psd = 'N/N', # n_fsd_rec=1,",
"range(n_m): inner = 1/gamma_k[m]**2 - 1/(2*T*gamma_k[m])*cot(gamma_k[m]/(2*T)) for k in range(n_k): inner -= 2/(nu_k[k]**2",
"0, s_k[k]) for k in range(n_k): put_coeff(nu_k[k], 0, s_k[k + n_m]) return result",
"s_mat, S_delta = S_delta, a = a_mat) def noise_decomposition(J, T, type_ltc, **kwargs): return",
"# noise = calc_noise_params(*calc_noise_time_domain(J, T, 'psd', # n_psd = 1, type_psd = 'N-1/N'))",
"1.35486, 1.34275], [2, 5.50923, 0.880362], [3, 0.553793, -0.965783]], 1000.0: [[1, 79.1394, 0.637942], [1,",
"if (R_1 != 0): poles[(0, 0, 0)] = R_1 if (T_3 != 0):",
"frequency #{} is degenerated.'.format(k)) # r_k[m] --> for m in range(n_m): s_k[m] =",
"sigma, phi_0 = phi_0, s = s_mat, S_delta = S_delta, a = a_mat)",
"gamma = sp.sparse.lil_matrix((phi_dim, phi_dim), dtype=np.complex128) sigma = np.ones((phi_dim), np.complex128) s_vec = np.zeros((phi_dim), np.complex128)",
"in phi_deg_dict: phi_deg_dict[gamma] = max(phi_deg_dict[gamma], n + 1) else: phi_deg_dict[gamma] = n +",
"= [[a, b, m, n] for (a, m, n), b in poles.items()] return",
"sum((n for n in phi_deg_dict.values())) # phi = [] phi_0 = np.zeros((phi_dim), np.complex128)",
"under BSD 3-Clause License. # See LINCENSE.txt for licence. # ------------------------------------------------------------------------ import numpy",
"deg)] if ((gamma_n, deg) in A): a_vec[ctr] = A[(gamma_n, deg)] ctr += 1",
"np.complex128) s_vec = np.zeros((phi_dim), np.complex128) a_vec = np.zeros((phi_dim), np.complex128) s_mat = sp.sparse.lil_matrix((phi_dim, phi_dim),",
"deg) in A): a_vec[ctr] = A[(gamma_n, deg)] ctr += 1 block_size = deg+1",
"# n_psd = 1, type_psd = 'N-1/N')) # noise = calc_noise_params(*calc_noise_time_domain(J, T, 'msd',",
"calc_S_msd(gamma_k, a_k, T, n_ltc): def cot(x): return 1/np.tan(x) n_m = a_k.shape[0] n_k =",
"0.740457], [3, 3.39011, 0.626892]], } def calc_S_msd(gamma_k, a_k, T, n_ltc): def cot(x): return",
"gamma_n, deg_max in phi_deg_dict.items(): for deg in range(deg_max): phi.append((gamma_n, deg)) phi_0[ctr] = 1",
"This library is distributed under BSD 3-Clause License. # See LINCENSE.txt for licence.",
"T, 'psd+fsd', n_psd = 1, type_psd = 'N/N', n_fsd_rec=1, chi_fsd=100.0)) # noise =",
"R_1 if (T_3 != 0): poles[(0, 0, 1)] = T_3 for p in",
"return calc_S_from_poles(J.poles, n_list), calc_A_from_poles(J.poles) else: raise Exception('[Error] Unknown ltc') def calc_noise_params(S, A): #",
"= gamma a_k[k] = A[(gamma, 0)] return calc_S_msd(gamma_k, a_k, T, n_msd), A elif",
"in range(n_psd): poles[(T_0*xi[p], 1, 0)] = 2*eta[p]*T_0 ## fsd poles poles[(0, 1, 0)]",
"+= coeff else: result[(a, m)] = coeff put_coeff(np.inf, 0, S_delta) for k in",
"phi_deg_dict.items(): for deg in range(deg_max): phi.append((gamma_n, deg)) phi_0[ctr] = 1 if deg ==",
"import * from .commuting_matrix import * from .pade_spectral_decomposition import * fsd_coeffs = {",
"result def calc_noise_time_domain(J, T, type_ltc, **kwargs): if (type_ltc == 'none'): n_list = [[0,",
"m) in result: result[(a, m)] += coeff else: result[(a, m)] = coeff put_coeff(np.inf,",
"if (np.inf, 0) in S: S_delta = S[(np.inf, 0)] return dict(gamma = gamma,",
"only first-order poles') gamma_k[k] = gamma a_k[k] = A[(gamma, 0)] return calc_S_msd(gamma_k, a_k,",
"noise = calc_noise_params(*calc_noise_time_domain(J, T, 'psd+fsd', # n_psd = 1, type_psd = 'N/N', #",
"scipy.sparse import itertools from collections import OrderedDict from .predefined_noise import * from .summation_over_poles",
"gamma[ctr,ctr] = gamma_n if deg > 0: gamma[ctr,ctr-1] = -deg if ((gamma_n, deg)",
"or type_ltc == 'psd+fsd' ): coeffs = [] coeff_0 = 0 if type_ltc",
"0): poles[(0, 0, 0)] = R_1 if (T_3 != 0): poles[(0, 0, 1)]",
"0 else 0 gamma[ctr,ctr] = gamma_n if deg > 0: gamma[ctr,ctr-1] = -deg",
"2/(nu_k[k]**2 - gamma_k[m]**2) S_delta += -2*T*a_k[m]*inner result = OrderedDict() def put_coeff(a, m, coeff):",
"= kwargs['chi_fsd'] # calc fsd coeffs T_n = T for i in range(n_fsd_rec):",
"T for i in range(n_fsd_rec): T_np1 = T_n*chi_fsd coeff_0 += T_n - T_np1",
"S_delta = S[(np.inf, 0)] return dict(gamma = gamma, sigma = sigma, phi_0 =",
"type_psd = 'N-1/N')) # noise = calc_noise_params(*calc_noise_time_domain(J, T, 'msd', # n_msd = 10))",
"raise Exception('[Error] Unknown ltc') def calc_noise_params(S, A): # Calculate Basis Degeneracy phi_deg_dict =",
"1/(2*T*gamma_k[m])*cot(gamma_k[m]/(2*T)) for k in range(n_k): inner -= 2/(nu_k[k]**2 - gamma_k[m]**2) S_delta += -2*T*a_k[m]*inner",
"nu_k = np.zeros(n_k) s_k = np.zeros(n_m + n_k, dtype=a_k.dtype) S_delta = 0.0 for",
"# noise = calc_noise_params(*calc_noise_time_domain(None, T, 'psd+fsd', n_psd = 1, type_psd = 'N/N', n_fsd_rec=1,",
"range(n_k): nu_k[k] = 2*np.pi*(k + 1)*T if np.any(np.abs(gamma_k - nu_k[k]) < (np.finfo(float).eps)): raise",
"l != 0: raise Exception('[Error] msd accepts only first-order poles') gamma_k[k] = gamma",
"= np.zeros((phi_dim), np.complex128) s_mat = sp.sparse.lil_matrix((phi_dim, phi_dim), dtype=np.complex128) a_mat = sp.sparse.lil_matrix((phi_dim, phi_dim), dtype=np.complex128)",
"np.any(np.abs(gamma_k - nu_k[k]) < (np.finfo(float).eps)): raise Exception('[Error] Bath frequency #{} is degenerated.'.format(k)) #",
"[3, 0.553793, -0.965783]], 1000.0: [[1, 79.1394, 0.637942], [1, 0.655349, 0.666920], [2, 11.6632, 0.456271],",
"a_k.shape[0] n_k = n_ltc nu_k = np.zeros(n_k) s_k = np.zeros(n_m + n_k, dtype=a_k.dtype)",
"*= T*nu_k[k] for m in range(n_m): inner = 1/gamma_k[m]**2 - 1/(2*T*gamma_k[m])*cot(gamma_k[m]/(2*T)) for k",
"n_fsd_rec = kwargs['n_fsd_rec'] chi_fsd = kwargs['chi_fsd'] # calc fsd coeffs T_n = T",
"ctr-block_size:ctr] \\ = get_commuting_matrix(s_vec[ctr-block_size:ctr], gamma[ctr-block_size:ctr, ctr-block_size:ctr].todense(), sigma[ctr-block_size:ctr]) a_mat[ctr-block_size:ctr, ctr-block_size:ctr] \\ = get_commuting_matrix(a_vec[ctr-block_size:ctr], gamma[ctr-block_size:ctr,",
"degenerated.'.format(k)) # r_k[m] --> for m in range(n_m): s_k[m] = -2*a_k[m]*cot(gamma_k[m]/(2*T))/2.0 for k",
"= S_delta, a = a_mat) def noise_decomposition(J, T, type_ltc, **kwargs): return calc_noise_params(*calc_noise_time_domain(J, T,",
"79.1394, 0.637942], [1, 0.655349, 0.666920], [2, 11.6632, 0.456271], [2, 1.54597, 0.740457], [3, 3.39011,",
"0.553793, -0.965783]], 1000.0: [[1, 79.1394, 0.637942], [1, 0.655349, 0.666920], [2, 11.6632, 0.456271], [2,",
"S_delta = S_delta, a = a_mat) def noise_decomposition(J, T, type_ltc, **kwargs): return calc_noise_params(*calc_noise_time_domain(J,",
"phi_dim), dtype=np.complex128) sigma = np.ones((phi_dim), np.complex128) s_vec = np.zeros((phi_dim), np.complex128) a_vec = np.zeros((phi_dim),",
"+ 1) else: phi_deg_dict[gamma] = n + 1 phi_dim = sum((n for n",
"if type_ltc == 'psd+fsd': n_fsd_rec = kwargs['n_fsd_rec'] chi_fsd = kwargs['chi_fsd'] # calc fsd",
"phi_dim = sum((n for n in phi_deg_dict.values())) # phi = [] phi_0 =",
"T_0 = T # calc psd coeffs n_psd = kwargs['n_psd'] type_psd = kwargs['type_psd']",
"for n in phi_deg_dict.values())) # phi = [] phi_0 = np.zeros((phi_dim), np.complex128) gamma",
"-2*a_k[m]*cot(gamma_k[m]/(2*T))/2.0 for k in range(n_k): s_k[n_m+k] = 0.0 for m in range(n_m): s_k[n_m+k]",
"dtype=np.complex128) ctr = 0 for gamma_n, deg_max in phi_deg_dict.items(): for deg in range(deg_max):",
"sp import scipy.sparse import itertools from collections import OrderedDict from .predefined_noise import *",
"n), b in poles.items()] return calc_S_from_poles(J.poles, n_list), calc_A_from_poles(J.poles) else: raise Exception('[Error] Unknown ltc')",
"type_psd = 'N/N', n_fsd_rec=1, chi_fsd=100.0)) # noise = calc_noise_params(*calc_noise_time_domain(J, T, 'psd+fsd', # n_psd",
"k in range(n_k): nu_k[k] = 2*np.pi*(k + 1)*T if np.any(np.abs(gamma_k - nu_k[k]) <",
"put_coeff(np.inf, 0, S_delta) for k in range(n_m): put_coeff(gamma_k[k], 0, s_k[k]) for k in",
"np.zeros(len(A), dtype=np.complex128) for k, (gamma, l) in enumerate(A.keys()): if l != 0: raise",
"0)] return dict(gamma = gamma, sigma = sigma, phi_0 = phi_0, s =",
"2*np.pi*(k + 1)*T if np.any(np.abs(gamma_k - nu_k[k]) < (np.finfo(float).eps)): raise Exception('[Error] Bath frequency",
"get_commuting_matrix(a_vec[ctr-block_size:ctr], gamma[ctr-block_size:ctr, ctr-block_size:ctr].todense(), sigma[ctr-block_size:ctr]) S_delta = 0.0 if (np.inf, 0) in S: S_delta",
"if (gamma == np.inf): continue if gamma in phi_deg_dict: phi_deg_dict[gamma] = max(phi_deg_dict[gamma], n",
".summation_over_poles import * from .commuting_matrix import * from .pade_spectral_decomposition import * fsd_coeffs =",
"[1, 0.655349, 0.666920], [2, 11.6632, 0.456271], [2, 1.54597, 0.740457], [3, 3.39011, 0.626892]], }",
"dtype=a_k.dtype) S_delta = 0.0 for k in range(n_k): nu_k[k] = 2*np.pi*(k + 1)*T",
"itertools.chain(S.keys(), A.keys()): if (gamma == np.inf): continue if gamma in phi_deg_dict: phi_deg_dict[gamma] =",
"a, b in fsd_coeffs[chi_fsd]: coeffs.append([j, a, b, T_n]) T_0 = T_n else: T_0",
"= S[(gamma_n, deg)] if ((gamma_n, deg) in A): a_vec[ctr] = A[(gamma_n, deg)] ctr",
"S_delta = 0.0 if (np.inf, 0) in S: S_delta = S[(np.inf, 0)] return",
"'N/N', n_fsd_rec=1, chi_fsd=100.0)) # noise = calc_noise_params(*calc_noise_time_domain(J, T, 'psd+fsd', # n_psd = 1,",
"calc fsd coeffs T_n = T for i in range(n_fsd_rec): T_np1 = T_n*chi_fsd",
"# See LINCENSE.txt for licence. # ------------------------------------------------------------------------ import numpy as np import scipy",
"result: result[(a, m)] += coeff else: result[(a, m)] = coeff put_coeff(np.inf, 0, S_delta)",
"deg) in S): s_vec[ctr] = S[(gamma_n, deg)] if ((gamma_n, deg) in A): a_vec[ctr]",
"k in range(n_k): inner -= 2/(nu_k[k]**2 - gamma_k[m]**2) S_delta += -2*T*a_k[m]*inner result =",
"result[(a, m)] += coeff else: result[(a, m)] = coeff put_coeff(np.inf, 0, S_delta) for",
"+ 1)*T if np.any(np.abs(gamma_k - nu_k[k]) < (np.finfo(float).eps)): raise Exception('[Error] Bath frequency #{}",
"range(n_psd): poles[(T_0*xi[p], 1, 0)] = 2*eta[p]*T_0 ## fsd poles poles[(0, 1, 0)] +=",
"= np.zeros((phi_dim), np.complex128) gamma = sp.sparse.lil_matrix((phi_dim, phi_dim), dtype=np.complex128) sigma = np.ones((phi_dim), np.complex128) s_vec",
"type_ltc, **kwargs)) # noise = calc_noise_params(*calc_noise_time_domain(None, T, 'psd+fsd', n_psd = 1, type_psd =",
"itertools from collections import OrderedDict from .predefined_noise import * from .summation_over_poles import *",
"= n_ltc nu_k = np.zeros(n_k) s_k = np.zeros(n_m + n_k, dtype=a_k.dtype) S_delta =",
"= deg+1 s_mat[ctr-block_size:ctr, ctr-block_size:ctr] \\ = get_commuting_matrix(s_vec[ctr-block_size:ctr], gamma[ctr-block_size:ctr, ctr-block_size:ctr].todense(), sigma[ctr-block_size:ctr]) a_mat[ctr-block_size:ctr, ctr-block_size:ctr] \\",
"elif (type_ltc == 'psd' or type_ltc == 'psd+fsd' ): coeffs = [] coeff_0",
"np.zeros(n_m + n_k, dtype=a_k.dtype) S_delta = 0.0 for k in range(n_k): nu_k[k] =",
"== 'none'): n_list = [[0, T, 1, 0]] return calc_S_from_poles(J.poles, n_list), calc_A_from_poles(J.poles) elif",
"nu_k[k]) < (np.finfo(float).eps)): raise Exception('[Error] Bath frequency #{} is degenerated.'.format(k)) # r_k[m] -->",
"**kwargs): if (type_ltc == 'none'): n_list = [[0, T, 1, 0]] return calc_S_from_poles(J.poles,",
"m)] += coeff else: result[(a, m)] = coeff put_coeff(np.inf, 0, S_delta) for k",
"for k in range(n_k): nu_k[k] = 2*np.pi*(k + 1)*T if np.any(np.abs(gamma_k - nu_k[k])",
"import scipy as sp import scipy.sparse import itertools from collections import OrderedDict from",
"np.zeros((phi_dim), np.complex128) a_vec = np.zeros((phi_dim), np.complex128) s_mat = sp.sparse.lil_matrix((phi_dim, phi_dim), dtype=np.complex128) a_mat =",
"kwargs['chi_fsd'] # calc fsd coeffs T_n = T for i in range(n_fsd_rec): T_np1",
"n_k = n_ltc nu_k = np.zeros(n_k) s_k = np.zeros(n_m + n_k, dtype=a_k.dtype) S_delta",
"T_0 if (R_1 != 0): poles[(0, 0, 0)] = R_1 if (T_3 !=",
"in range(deg_max): phi.append((gamma_n, deg)) phi_0[ctr] = 1 if deg == 0 else 0",
"s_vec = np.zeros((phi_dim), np.complex128) a_vec = np.zeros((phi_dim), np.complex128) s_mat = sp.sparse.lil_matrix((phi_dim, phi_dim), dtype=np.complex128)",
"calc_noise_params(*calc_noise_time_domain(J, T, 'psd+fsd', # n_psd = 1, type_psd = 'N/N', # n_fsd_rec=1, chi_fsd=100.0))",
"-2*T*a_k[m]*inner result = OrderedDict() def put_coeff(a, m, coeff): if (a, m) in result:",
"= coeff put_coeff(np.inf, 0, S_delta) for k in range(n_m): put_coeff(gamma_k[k], 0, s_k[k]) for",
"* fsd_coeffs = { 100.0: [[1, 1.35486, 1.34275], [2, 5.50923, 0.880362], [3, 0.553793,",
"if ((gamma_n, deg) in A): a_vec[ctr] = A[(gamma_n, deg)] ctr += 1 block_size",
"b, T_n in coeffs: poles[(T_n/a, j, 0)] = b*(T_n/a)**(2*j-1) n_list = [[a, b,",
"np.zeros(len(A), dtype=np.complex128) a_k = np.zeros(len(A), dtype=np.complex128) for k, (gamma, l) in enumerate(A.keys()): if",
"0)] = 2*eta[p]*T_0 ## fsd poles poles[(0, 1, 0)] += coeff_0 for j,",
"calc psd coeffs n_psd = kwargs['n_psd'] type_psd = kwargs['type_psd'] xi, eta, R_1, T_3",
"phi_deg_dict[gamma] = n + 1 phi_dim = sum((n for n in phi_deg_dict.values())) #",
"'N/N', # n_fsd_rec=1, chi_fsd=100.0)) # noise = calc_noise_params(*calc_noise_time_domain(J, T, 'psd', # n_psd =",
"R_1, T_3 = psd(n_psd, type_psd) # collect poles poles = OrderedDict() ## psd",
"= 0 if type_ltc == 'psd+fsd': n_fsd_rec = kwargs['n_fsd_rec'] chi_fsd = kwargs['chi_fsd'] #",
"0]] return calc_S_from_poles(J.poles, n_list), calc_A_from_poles(J.poles) elif (type_ltc == 'msd'): n_msd = kwargs['n_msd'] A",
"(type_ltc == 'msd'): n_msd = kwargs['n_msd'] A = calc_A_from_poles(J.poles) gamma_k = np.zeros(len(A), dtype=np.complex128)",
"= 'N/N', # n_fsd_rec=1, chi_fsd=100.0)) # noise = calc_noise_params(*calc_noise_time_domain(J, T, 'psd', # n_psd",
"def calc_S_msd(gamma_k, a_k, T, n_ltc): def cot(x): return 1/np.tan(x) n_m = a_k.shape[0] n_k",
"0.0 for m in range(n_m): s_k[n_m+k] += -4*a_k[m]/(nu_k[k]**2 - gamma_k[m]**2) s_k[n_m+k] *= T*nu_k[k]",
"phi_deg_dict: phi_deg_dict[gamma] = max(phi_deg_dict[gamma], n + 1) else: phi_deg_dict[gamma] = n + 1",
"(np.inf, 0) in S: S_delta = S[(np.inf, 0)] return dict(gamma = gamma, sigma",
"= kwargs['n_psd'] type_psd = kwargs['type_psd'] xi, eta, R_1, T_3 = psd(n_psd, type_psd) #",
"!= 0: raise Exception('[Error] msd accepts only first-order poles') gamma_k[k] = gamma a_k[k]",
"**kwargs)) # noise = calc_noise_params(*calc_noise_time_domain(None, T, 'psd+fsd', n_psd = 1, type_psd = 'N/N',",
"T_np1 = T_n*chi_fsd coeff_0 += T_n - T_np1 T_n = T_np1 for j,",
"= { 100.0: [[1, 1.35486, 1.34275], [2, 5.50923, 0.880362], [3, 0.553793, -0.965783]], 1000.0:",
"# # LibHEOM: Copyright (c) <NAME> # This library is distributed under BSD",
"= kwargs['n_fsd_rec'] chi_fsd = kwargs['chi_fsd'] # calc fsd coeffs T_n = T for",
"deg)) phi_0[ctr] = 1 if deg == 0 else 0 gamma[ctr,ctr] = gamma_n",
"= OrderedDict() def put_coeff(a, m, coeff): if (a, m) in result: result[(a, m)]",
"else: phi_deg_dict[gamma] = n + 1 phi_dim = sum((n for n in phi_deg_dict.values()))",
"max(phi_deg_dict[gamma], n + 1) else: phi_deg_dict[gamma] = n + 1 phi_dim = sum((n",
"= -2*a_k[m]*cot(gamma_k[m]/(2*T))/2.0 for k in range(n_k): s_k[n_m+k] = 0.0 for m in range(n_m):",
"= np.zeros(n_k) s_k = np.zeros(n_m + n_k, dtype=a_k.dtype) S_delta = 0.0 for k",
"gamma, sigma = sigma, phi_0 = phi_0, s = s_mat, S_delta = S_delta,",
"gamma_k[k] = gamma a_k[k] = A[(gamma, 0)] return calc_S_msd(gamma_k, a_k, T, n_msd), A",
"n in phi_deg_dict.values())) # phi = [] phi_0 = np.zeros((phi_dim), np.complex128) gamma =",
"T_3 for p in range(n_psd): poles[(T_0*xi[p], 1, 0)] = 2*eta[p]*T_0 ## fsd poles",
"in phi_deg_dict.items(): for deg in range(deg_max): phi.append((gamma_n, deg)) phi_0[ctr] = 1 if deg",
"LibHEOM: Copyright (c) <NAME> # This library is distributed under BSD 3-Clause License.",
"T_n = T_np1 for j, a, b in fsd_coeffs[chi_fsd]: coeffs.append([j, a, b, T_n])",
"'psd+fsd' ): coeffs = [] coeff_0 = 0 if type_ltc == 'psd+fsd': n_fsd_rec",
"xi, eta, R_1, T_3 = psd(n_psd, type_psd) # collect poles poles = OrderedDict()",
"block_size = deg+1 s_mat[ctr-block_size:ctr, ctr-block_size:ctr] \\ = get_commuting_matrix(s_vec[ctr-block_size:ctr], gamma[ctr-block_size:ctr, ctr-block_size:ctr].todense(), sigma[ctr-block_size:ctr]) a_mat[ctr-block_size:ctr, ctr-block_size:ctr]",
"* from .commuting_matrix import * from .pade_spectral_decomposition import * fsd_coeffs = { 100.0:",
"collections import OrderedDict from .predefined_noise import * from .summation_over_poles import * from .commuting_matrix",
"T, 'psd+fsd', # n_psd = 1, type_psd = 'N/N', # n_fsd_rec=1, chi_fsd=100.0)) #",
"3-Clause License. # See LINCENSE.txt for licence. # ------------------------------------------------------------------------ import numpy as np",
"{ 100.0: [[1, 1.35486, 1.34275], [2, 5.50923, 0.880362], [3, 0.553793, -0.965783]], 1000.0: [[1,",
"noise = calc_noise_params(*calc_noise_time_domain(None, T, 'psd+fsd', n_psd = 1, type_psd = 'N/N', n_fsd_rec=1, chi_fsd=100.0))",
"for gamma_n, deg_max in phi_deg_dict.items(): for deg in range(deg_max): phi.append((gamma_n, deg)) phi_0[ctr] =",
"calc_A_from_poles(J.poles) gamma_k = np.zeros(len(A), dtype=np.complex128) a_k = np.zeros(len(A), dtype=np.complex128) for k, (gamma, l)",
"= 'N/N', n_fsd_rec=1, chi_fsd=100.0)) # noise = calc_noise_params(*calc_noise_time_domain(J, T, 'psd+fsd', # n_psd =",
"= OrderedDict() ## psd poles poles[(0, 1, 0)] = T_0 if (R_1 !=",
"-deg if ((gamma_n, deg) in S): s_vec[ctr] = S[(gamma_n, deg)] if ((gamma_n, deg)",
"poles[(T_0*xi[p], 1, 0)] = 2*eta[p]*T_0 ## fsd poles poles[(0, 1, 0)] += coeff_0",
"3.39011, 0.626892]], } def calc_S_msd(gamma_k, a_k, T, n_ltc): def cot(x): return 1/np.tan(x) n_m",
"b in poles.items()] return calc_S_from_poles(J.poles, n_list), calc_A_from_poles(J.poles) else: raise Exception('[Error] Unknown ltc') def",
"A elif (type_ltc == 'psd' or type_ltc == 'psd+fsd' ): coeffs = []",
"from .commuting_matrix import * from .pade_spectral_decomposition import * fsd_coeffs = { 100.0: [[1,",
"k, (gamma, l) in enumerate(A.keys()): if l != 0: raise Exception('[Error] msd accepts",
"deg > 0: gamma[ctr,ctr-1] = -deg if ((gamma_n, deg) in S): s_vec[ctr] =",
"= phi_0, s = s_mat, S_delta = S_delta, a = a_mat) def noise_decomposition(J,",
"range(n_fsd_rec): T_np1 = T_n*chi_fsd coeff_0 += T_n - T_np1 T_n = T_np1 for",
"b in fsd_coeffs[chi_fsd]: coeffs.append([j, a, b, T_n]) T_0 = T_n else: T_0 =",
"np.zeros((phi_dim), np.complex128) s_mat = sp.sparse.lil_matrix((phi_dim, phi_dim), dtype=np.complex128) a_mat = sp.sparse.lil_matrix((phi_dim, phi_dim), dtype=np.complex128) ctr",
"= np.zeros(len(A), dtype=np.complex128) for k, (gamma, l) in enumerate(A.keys()): if l != 0:",
"(gamma == np.inf): continue if gamma in phi_deg_dict: phi_deg_dict[gamma] = max(phi_deg_dict[gamma], n +",
"0)] = R_1 if (T_3 != 0): poles[(0, 0, 1)] = T_3 for",
"0)] return calc_S_msd(gamma_k, a_k, T, n_msd), A elif (type_ltc == 'psd' or type_ltc",
"a_k = np.zeros(len(A), dtype=np.complex128) for k, (gamma, l) in enumerate(A.keys()): if l !=",
"T_3 = psd(n_psd, type_psd) # collect poles poles = OrderedDict() ## psd poles",
"# Calculate Basis Degeneracy phi_deg_dict = OrderedDict() for gamma, n in itertools.chain(S.keys(), A.keys()):",
"= max(phi_deg_dict[gamma], n + 1) else: phi_deg_dict[gamma] = n + 1 phi_dim =",
"+ n_m]) return result def calc_noise_time_domain(J, T, type_ltc, **kwargs): if (type_ltc == 'none'):",
"in itertools.chain(S.keys(), A.keys()): if (gamma == np.inf): continue if gamma in phi_deg_dict: phi_deg_dict[gamma]",
"type_psd = 'N/N', # n_fsd_rec=1, chi_fsd=100.0)) # noise = calc_noise_params(*calc_noise_time_domain(J, T, 'psd', #",
"= 1, type_psd = 'N/N', n_fsd_rec=1, chi_fsd=100.0)) # noise = calc_noise_params(*calc_noise_time_domain(J, T, 'psd+fsd',",
"S: S_delta = S[(np.inf, 0)] return dict(gamma = gamma, sigma = sigma, phi_0",
"s_k[m] = -2*a_k[m]*cot(gamma_k[m]/(2*T))/2.0 for k in range(n_k): s_k[n_m+k] = 0.0 for m in",
"phi_deg_dict.values())) # phi = [] phi_0 = np.zeros((phi_dim), np.complex128) gamma = sp.sparse.lil_matrix((phi_dim, phi_dim),",
"S): s_vec[ctr] = S[(gamma_n, deg)] if ((gamma_n, deg) in A): a_vec[ctr] = A[(gamma_n,",
"= get_commuting_matrix(a_vec[ctr-block_size:ctr], gamma[ctr-block_size:ctr, ctr-block_size:ctr].todense(), sigma[ctr-block_size:ctr]) S_delta = 0.0 if (np.inf, 0) in S:",
"OrderedDict() for gamma, n in itertools.chain(S.keys(), A.keys()): if (gamma == np.inf): continue if",
"S_delta, a = a_mat) def noise_decomposition(J, T, type_ltc, **kwargs): return calc_noise_params(*calc_noise_time_domain(J, T, type_ltc,",
"= A[(gamma, 0)] return calc_S_msd(gamma_k, a_k, T, n_msd), A elif (type_ltc == 'psd'",
"phi_0 = np.zeros((phi_dim), np.complex128) gamma = sp.sparse.lil_matrix((phi_dim, phi_dim), dtype=np.complex128) sigma = np.ones((phi_dim), np.complex128)",
"= T for i in range(n_fsd_rec): T_np1 = T_n*chi_fsd coeff_0 += T_n -",
"== np.inf): continue if gamma in phi_deg_dict: phi_deg_dict[gamma] = max(phi_deg_dict[gamma], n + 1)",
"1) else: phi_deg_dict[gamma] = n + 1 phi_dim = sum((n for n in",
"gamma_k[m]**2) s_k[n_m+k] *= T*nu_k[k] for m in range(n_m): inner = 1/gamma_k[m]**2 - 1/(2*T*gamma_k[m])*cot(gamma_k[m]/(2*T))",
"raise Exception('[Error] msd accepts only first-order poles') gamma_k[k] = gamma a_k[k] = A[(gamma,",
"- gamma_k[m]**2) s_k[n_m+k] *= T*nu_k[k] for m in range(n_m): inner = 1/gamma_k[m]**2 -",
"= np.zeros(n_m + n_k, dtype=a_k.dtype) S_delta = 0.0 for k in range(n_k): nu_k[k]",
"[2, 5.50923, 0.880362], [3, 0.553793, -0.965783]], 1000.0: [[1, 79.1394, 0.637942], [1, 0.655349, 0.666920],",
"0.655349, 0.666920], [2, 11.6632, 0.456271], [2, 1.54597, 0.740457], [3, 3.39011, 0.626892]], } def",
"= T_3 for p in range(n_psd): poles[(T_0*xi[p], 1, 0)] = 2*eta[p]*T_0 ## fsd",
"0)] += coeff_0 for j, a, b, T_n in coeffs: poles[(T_n/a, j, 0)]",
"= 0.0 for m in range(n_m): s_k[n_m+k] += -4*a_k[m]/(nu_k[k]**2 - gamma_k[m]**2) s_k[n_m+k] *=",
"s_k[n_m+k] += -4*a_k[m]/(nu_k[k]**2 - gamma_k[m]**2) s_k[n_m+k] *= T*nu_k[k] for m in range(n_m): inner",
"ctr-block_size:ctr].todense(), sigma[ctr-block_size:ctr]) a_mat[ctr-block_size:ctr, ctr-block_size:ctr] \\ = get_commuting_matrix(a_vec[ctr-block_size:ctr], gamma[ctr-block_size:ctr, ctr-block_size:ctr].todense(), sigma[ctr-block_size:ctr]) S_delta = 0.0",
"T, type_ltc, **kwargs): return calc_noise_params(*calc_noise_time_domain(J, T, type_ltc, **kwargs)) # noise = calc_noise_params(*calc_noise_time_domain(None, T,",
"calc_noise_params(*calc_noise_time_domain(None, T, 'psd+fsd', n_psd = 1, type_psd = 'N/N', n_fsd_rec=1, chi_fsd=100.0)) # noise",
"coeffs.append([j, a, b, T_n]) T_0 = T_n else: T_0 = T # calc",
"m in range(n_m): s_k[m] = -2*a_k[m]*cot(gamma_k[m]/(2*T))/2.0 for k in range(n_k): s_k[n_m+k] = 0.0",
"= [[0, T, 1, 0]] return calc_S_from_poles(J.poles, n_list), calc_A_from_poles(J.poles) elif (type_ltc == 'msd'):",
"from .predefined_noise import * from .summation_over_poles import * from .commuting_matrix import * from",
"inner -= 2/(nu_k[k]**2 - gamma_k[m]**2) S_delta += -2*T*a_k[m]*inner result = OrderedDict() def put_coeff(a,",
"library is distributed under BSD 3-Clause License. # See LINCENSE.txt for licence. #",
"in coeffs: poles[(T_n/a, j, 0)] = b*(T_n/a)**(2*j-1) n_list = [[a, b, m, n]",
"coeff_0 for j, a, b, T_n in coeffs: poles[(T_n/a, j, 0)] = b*(T_n/a)**(2*j-1)",
"[[1, 79.1394, 0.637942], [1, 0.655349, 0.666920], [2, 11.6632, 0.456271], [2, 1.54597, 0.740457], [3,",
"np.inf): continue if gamma in phi_deg_dict: phi_deg_dict[gamma] = max(phi_deg_dict[gamma], n + 1) else:",
"scipy as sp import scipy.sparse import itertools from collections import OrderedDict from .predefined_noise",
"T, 1, 0]] return calc_S_from_poles(J.poles, n_list), calc_A_from_poles(J.poles) elif (type_ltc == 'msd'): n_msd =",
"n_list), calc_A_from_poles(J.poles) elif (type_ltc == 'msd'): n_msd = kwargs['n_msd'] A = calc_A_from_poles(J.poles) gamma_k",
"s_k[n_m+k] *= T*nu_k[k] for m in range(n_m): inner = 1/gamma_k[m]**2 - 1/(2*T*gamma_k[m])*cot(gamma_k[m]/(2*T)) for",
"import * from .pade_spectral_decomposition import * fsd_coeffs = { 100.0: [[1, 1.35486, 1.34275],",
"n_list = [[a, b, m, n] for (a, m, n), b in poles.items()]",
"m, n] for (a, m, n), b in poles.items()] return calc_S_from_poles(J.poles, n_list), calc_A_from_poles(J.poles)",
"np.complex128) s_mat = sp.sparse.lil_matrix((phi_dim, phi_dim), dtype=np.complex128) a_mat = sp.sparse.lil_matrix((phi_dim, phi_dim), dtype=np.complex128) ctr =",
"coeff put_coeff(np.inf, 0, S_delta) for k in range(n_m): put_coeff(gamma_k[k], 0, s_k[k]) for k",
"else 0 gamma[ctr,ctr] = gamma_n if deg > 0: gamma[ctr,ctr-1] = -deg if",
"for p in range(n_psd): poles[(T_0*xi[p], 1, 0)] = 2*eta[p]*T_0 ## fsd poles poles[(0,",
"Exception('[Error] msd accepts only first-order poles') gamma_k[k] = gamma a_k[k] = A[(gamma, 0)]",
"0)] = b*(T_n/a)**(2*j-1) n_list = [[a, b, m, n] for (a, m, n),",
"a_mat) def noise_decomposition(J, T, type_ltc, **kwargs): return calc_noise_params(*calc_noise_time_domain(J, T, type_ltc, **kwargs)) # noise",
"s_k[k + n_m]) return result def calc_noise_time_domain(J, T, type_ltc, **kwargs): if (type_ltc ==",
"dtype=np.complex128) for k, (gamma, l) in enumerate(A.keys()): if l != 0: raise Exception('[Error]",
"chi_fsd=100.0)) # noise = calc_noise_params(*calc_noise_time_domain(J, T, 'psd+fsd', # n_psd = 1, type_psd =",
"in range(n_m): inner = 1/gamma_k[m]**2 - 1/(2*T*gamma_k[m])*cot(gamma_k[m]/(2*T)) for k in range(n_k): inner -=",
"11.6632, 0.456271], [2, 1.54597, 0.740457], [3, 3.39011, 0.626892]], } def calc_S_msd(gamma_k, a_k, T,",
"# r_k[m] --> for m in range(n_m): s_k[m] = -2*a_k[m]*cot(gamma_k[m]/(2*T))/2.0 for k in",
"gamma, n in itertools.chain(S.keys(), A.keys()): if (gamma == np.inf): continue if gamma in",
"0)] = T_0 if (R_1 != 0): poles[(0, 0, 0)] = R_1 if",
"k in range(n_k): put_coeff(nu_k[k], 0, s_k[k + n_m]) return result def calc_noise_time_domain(J, T,",
"ctr-block_size:ctr] \\ = get_commuting_matrix(a_vec[ctr-block_size:ctr], gamma[ctr-block_size:ctr, ctr-block_size:ctr].todense(), sigma[ctr-block_size:ctr]) S_delta = 0.0 if (np.inf, 0)",
"import OrderedDict from .predefined_noise import * from .summation_over_poles import * from .commuting_matrix import",
"= T # calc psd coeffs n_psd = kwargs['n_psd'] type_psd = kwargs['type_psd'] xi,",
"from collections import OrderedDict from .predefined_noise import * from .summation_over_poles import * from",
"numpy as np import scipy as sp import scipy.sparse import itertools from collections",
"type_psd) # collect poles poles = OrderedDict() ## psd poles poles[(0, 1, 0)]",
"range(n_m): s_k[m] = -2*a_k[m]*cot(gamma_k[m]/(2*T))/2.0 for k in range(n_k): s_k[n_m+k] = 0.0 for m",
"in result: result[(a, m)] += coeff else: result[(a, m)] = coeff put_coeff(np.inf, 0,",
"b*(T_n/a)**(2*j-1) n_list = [[a, b, m, n] for (a, m, n), b in",
"dtype=np.complex128) sigma = np.ones((phi_dim), np.complex128) s_vec = np.zeros((phi_dim), np.complex128) a_vec = np.zeros((phi_dim), np.complex128)",
"calc_noise_params(S, A): # Calculate Basis Degeneracy phi_deg_dict = OrderedDict() for gamma, n in",
"s_k[k]) for k in range(n_k): put_coeff(nu_k[k], 0, s_k[k + n_m]) return result def",
"n_list), calc_A_from_poles(J.poles) else: raise Exception('[Error] Unknown ltc') def calc_noise_params(S, A): # Calculate Basis",
"put_coeff(a, m, coeff): if (a, m) in result: result[(a, m)] += coeff else:",
"0.880362], [3, 0.553793, -0.965783]], 1000.0: [[1, 79.1394, 0.637942], [1, 0.655349, 0.666920], [2, 11.6632,",
"coeffs = [] coeff_0 = 0 if type_ltc == 'psd+fsd': n_fsd_rec = kwargs['n_fsd_rec']",
"Exception('[Error] Bath frequency #{} is degenerated.'.format(k)) # r_k[m] --> for m in range(n_m):",
"See LINCENSE.txt for licence. # ------------------------------------------------------------------------ import numpy as np import scipy as",
"calc_S_from_poles(J.poles, n_list), calc_A_from_poles(J.poles) elif (type_ltc == 'msd'): n_msd = kwargs['n_msd'] A = calc_A_from_poles(J.poles)",
"coeffs n_psd = kwargs['n_psd'] type_psd = kwargs['type_psd'] xi, eta, R_1, T_3 = psd(n_psd,",
"s_k[n_m+k] = 0.0 for m in range(n_m): s_k[n_m+k] += -4*a_k[m]/(nu_k[k]**2 - gamma_k[m]**2) s_k[n_m+k]",
"if (T_3 != 0): poles[(0, 0, 1)] = T_3 for p in range(n_psd):",
"n_psd = 1, type_psd = 'N/N', # n_fsd_rec=1, chi_fsd=100.0)) # noise = calc_noise_params(*calc_noise_time_domain(J,",
"if l != 0: raise Exception('[Error] msd accepts only first-order poles') gamma_k[k] =",
"[2, 11.6632, 0.456271], [2, 1.54597, 0.740457], [3, 3.39011, 0.626892]], } def calc_S_msd(gamma_k, a_k,",
"poles poles[(0, 1, 0)] += coeff_0 for j, a, b, T_n in coeffs:",
"type_psd = kwargs['type_psd'] xi, eta, R_1, T_3 = psd(n_psd, type_psd) # collect poles",
"# calc psd coeffs n_psd = kwargs['n_psd'] type_psd = kwargs['type_psd'] xi, eta, R_1,",
"0.626892]], } def calc_S_msd(gamma_k, a_k, T, n_ltc): def cot(x): return 1/np.tan(x) n_m =",
"b, T_n]) T_0 = T_n else: T_0 = T # calc psd coeffs",
"0.0 for k in range(n_k): nu_k[k] = 2*np.pi*(k + 1)*T if np.any(np.abs(gamma_k -",
"noise = calc_noise_params(*calc_noise_time_domain(J, T, 'msd', # n_msd = 10)) # noise = calc_noise_params(*calc_noise_time_domain(J,",
"= sp.sparse.lil_matrix((phi_dim, phi_dim), dtype=np.complex128) a_mat = sp.sparse.lil_matrix((phi_dim, phi_dim), dtype=np.complex128) ctr = 0 for",
"deg)] ctr += 1 block_size = deg+1 s_mat[ctr-block_size:ctr, ctr-block_size:ctr] \\ = get_commuting_matrix(s_vec[ctr-block_size:ctr], gamma[ctr-block_size:ctr,",
"# collect poles poles = OrderedDict() ## psd poles poles[(0, 1, 0)] =",
"= 1 if deg == 0 else 0 gamma[ctr,ctr] = gamma_n if deg",
"0.0 if (np.inf, 0) in S: S_delta = S[(np.inf, 0)] return dict(gamma =",
"1/gamma_k[m]**2 - 1/(2*T*gamma_k[m])*cot(gamma_k[m]/(2*T)) for k in range(n_k): inner -= 2/(nu_k[k]**2 - gamma_k[m]**2) S_delta",
"psd(n_psd, type_psd) # collect poles poles = OrderedDict() ## psd poles poles[(0, 1,",
"[2, 1.54597, 0.740457], [3, 3.39011, 0.626892]], } def calc_S_msd(gamma_k, a_k, T, n_ltc): def",
"= [] phi_0 = np.zeros((phi_dim), np.complex128) gamma = sp.sparse.lil_matrix((phi_dim, phi_dim), dtype=np.complex128) sigma =",
"if deg > 0: gamma[ctr,ctr-1] = -deg if ((gamma_n, deg) in S): s_vec[ctr]",
"S[(np.inf, 0)] return dict(gamma = gamma, sigma = sigma, phi_0 = phi_0, s",
"'psd+fsd', n_psd = 1, type_psd = 'N/N', n_fsd_rec=1, chi_fsd=100.0)) # noise = calc_noise_params(*calc_noise_time_domain(J,",
"is degenerated.'.format(k)) # r_k[m] --> for m in range(n_m): s_k[m] = -2*a_k[m]*cot(gamma_k[m]/(2*T))/2.0 for",
"poles[(0, 0, 0)] = R_1 if (T_3 != 0): poles[(0, 0, 1)] =",
"a_mat = sp.sparse.lil_matrix((phi_dim, phi_dim), dtype=np.complex128) ctr = 0 for gamma_n, deg_max in phi_deg_dict.items():",
"range(n_k): put_coeff(nu_k[k], 0, s_k[k + n_m]) return result def calc_noise_time_domain(J, T, type_ltc, **kwargs):",
"A): a_vec[ctr] = A[(gamma_n, deg)] ctr += 1 block_size = deg+1 s_mat[ctr-block_size:ctr, ctr-block_size:ctr]",
"n_fsd_rec=1, chi_fsd=100.0)) # noise = calc_noise_params(*calc_noise_time_domain(J, T, 'psd+fsd', # n_psd = 1, type_psd",
"1 block_size = deg+1 s_mat[ctr-block_size:ctr, ctr-block_size:ctr] \\ = get_commuting_matrix(s_vec[ctr-block_size:ctr], gamma[ctr-block_size:ctr, ctr-block_size:ctr].todense(), sigma[ctr-block_size:ctr]) a_mat[ctr-block_size:ctr,",
"0, s_k[k + n_m]) return result def calc_noise_time_domain(J, T, type_ltc, **kwargs): if (type_ltc",
"= sigma, phi_0 = phi_0, s = s_mat, S_delta = S_delta, a =",
"a_vec[ctr] = A[(gamma_n, deg)] ctr += 1 block_size = deg+1 s_mat[ctr-block_size:ctr, ctr-block_size:ctr] \\",
"# LibHEOM: Copyright (c) <NAME> # This library is distributed under BSD 3-Clause",
"1, 0)] = 2*eta[p]*T_0 ## fsd poles poles[(0, 1, 0)] += coeff_0 for",
"return calc_noise_params(*calc_noise_time_domain(J, T, type_ltc, **kwargs)) # noise = calc_noise_params(*calc_noise_time_domain(None, T, 'psd+fsd', n_psd =",
"np.complex128) gamma = sp.sparse.lil_matrix((phi_dim, phi_dim), dtype=np.complex128) sigma = np.ones((phi_dim), np.complex128) s_vec = np.zeros((phi_dim),",
"= psd(n_psd, type_psd) # collect poles poles = OrderedDict() ## psd poles poles[(0,",
"T_n*chi_fsd coeff_0 += T_n - T_np1 T_n = T_np1 for j, a, b",
"psd poles poles[(0, 1, 0)] = T_0 if (R_1 != 0): poles[(0, 0,",
"poles') gamma_k[k] = gamma a_k[k] = A[(gamma, 0)] return calc_S_msd(gamma_k, a_k, T, n_msd),",
"p in range(n_psd): poles[(T_0*xi[p], 1, 0)] = 2*eta[p]*T_0 ## fsd poles poles[(0, 1,",
"dtype=np.complex128) a_mat = sp.sparse.lil_matrix((phi_dim, phi_dim), dtype=np.complex128) ctr = 0 for gamma_n, deg_max in",
"calc_S_from_poles(J.poles, n_list), calc_A_from_poles(J.poles) else: raise Exception('[Error] Unknown ltc') def calc_noise_params(S, A): # Calculate",
"'N-1/N')) # noise = calc_noise_params(*calc_noise_time_domain(J, T, 'msd', # n_msd = 10)) # noise",
"poles[(T_n/a, j, 0)] = b*(T_n/a)**(2*j-1) n_list = [[a, b, m, n] for (a,",
"gamma[ctr-block_size:ctr, ctr-block_size:ctr].todense(), sigma[ctr-block_size:ctr]) a_mat[ctr-block_size:ctr, ctr-block_size:ctr] \\ = get_commuting_matrix(a_vec[ctr-block_size:ctr], gamma[ctr-block_size:ctr, ctr-block_size:ctr].todense(), sigma[ctr-block_size:ctr]) S_delta =",
"psd coeffs n_psd = kwargs['n_psd'] type_psd = kwargs['type_psd'] xi, eta, R_1, T_3 =",
"5.50923, 0.880362], [3, 0.553793, -0.965783]], 1000.0: [[1, 79.1394, 0.637942], [1, 0.655349, 0.666920], [2,",
"for m in range(n_m): s_k[m] = -2*a_k[m]*cot(gamma_k[m]/(2*T))/2.0 for k in range(n_k): s_k[n_m+k] =",
"as sp import scipy.sparse import itertools from collections import OrderedDict from .predefined_noise import",
"put_coeff(nu_k[k], 0, s_k[k + n_m]) return result def calc_noise_time_domain(J, T, type_ltc, **kwargs): if",
"A[(gamma_n, deg)] ctr += 1 block_size = deg+1 s_mat[ctr-block_size:ctr, ctr-block_size:ctr] \\ = get_commuting_matrix(s_vec[ctr-block_size:ctr],",
"OrderedDict from .predefined_noise import * from .summation_over_poles import * from .commuting_matrix import *",
"raise Exception('[Error] Bath frequency #{} is degenerated.'.format(k)) # r_k[m] --> for m in",
"T_np1 T_n = T_np1 for j, a, b in fsd_coeffs[chi_fsd]: coeffs.append([j, a, b,",
"(T_3 != 0): poles[(0, 0, 1)] = T_3 for p in range(n_psd): poles[(T_0*xi[p],",
"= sp.sparse.lil_matrix((phi_dim, phi_dim), dtype=np.complex128) ctr = 0 for gamma_n, deg_max in phi_deg_dict.items(): for",
"in range(n_k): put_coeff(nu_k[k], 0, s_k[k + n_m]) return result def calc_noise_time_domain(J, T, type_ltc,",
"= T_n*chi_fsd coeff_0 += T_n - T_np1 T_n = T_np1 for j, a,",
"sp.sparse.lil_matrix((phi_dim, phi_dim), dtype=np.complex128) a_mat = sp.sparse.lil_matrix((phi_dim, phi_dim), dtype=np.complex128) ctr = 0 for gamma_n,",
"((gamma_n, deg) in S): s_vec[ctr] = S[(gamma_n, deg)] if ((gamma_n, deg) in A):",
"# n_psd = 1, type_psd = 'N/N', # n_fsd_rec=1, chi_fsd=100.0)) # noise =",
"n_m]) return result def calc_noise_time_domain(J, T, type_ltc, **kwargs): if (type_ltc == 'none'): n_list",
"**kwargs): return calc_noise_params(*calc_noise_time_domain(J, T, type_ltc, **kwargs)) # noise = calc_noise_params(*calc_noise_time_domain(None, T, 'psd+fsd', n_psd",
"= [] coeff_0 = 0 if type_ltc == 'psd+fsd': n_fsd_rec = kwargs['n_fsd_rec'] chi_fsd",
"T_np1 for j, a, b in fsd_coeffs[chi_fsd]: coeffs.append([j, a, b, T_n]) T_0 =",
"'psd+fsd', # n_psd = 1, type_psd = 'N/N', # n_fsd_rec=1, chi_fsd=100.0)) # noise",
"n_psd = 1, type_psd = 'N-1/N')) # noise = calc_noise_params(*calc_noise_time_domain(J, T, 'msd', #",
"coeff_0 = 0 if type_ltc == 'psd+fsd': n_fsd_rec = kwargs['n_fsd_rec'] chi_fsd = kwargs['chi_fsd']",
"2*eta[p]*T_0 ## fsd poles poles[(0, 1, 0)] += coeff_0 for j, a, b,",
"-= 2/(nu_k[k]**2 - gamma_k[m]**2) S_delta += -2*T*a_k[m]*inner result = OrderedDict() def put_coeff(a, m,",
"nu_k[k] = 2*np.pi*(k + 1)*T if np.any(np.abs(gamma_k - nu_k[k]) < (np.finfo(float).eps)): raise Exception('[Error]",
"for k in range(n_k): put_coeff(nu_k[k], 0, s_k[k + n_m]) return result def calc_noise_time_domain(J,",
"[[a, b, m, n] for (a, m, n), b in poles.items()] return calc_S_from_poles(J.poles,",
"0.637942], [1, 0.655349, 0.666920], [2, 11.6632, 0.456271], [2, 1.54597, 0.740457], [3, 3.39011, 0.626892]],",
"if (a, m) in result: result[(a, m)] += coeff else: result[(a, m)] =",
"import scipy.sparse import itertools from collections import OrderedDict from .predefined_noise import * from",
"+= 1 block_size = deg+1 s_mat[ctr-block_size:ctr, ctr-block_size:ctr] \\ = get_commuting_matrix(s_vec[ctr-block_size:ctr], gamma[ctr-block_size:ctr, ctr-block_size:ctr].todense(), sigma[ctr-block_size:ctr])",
"deg == 0 else 0 gamma[ctr,ctr] = gamma_n if deg > 0: gamma[ctr,ctr-1]",
"gamma_k = np.zeros(len(A), dtype=np.complex128) a_k = np.zeros(len(A), dtype=np.complex128) for k, (gamma, l) in",
"+ n_k, dtype=a_k.dtype) S_delta = 0.0 for k in range(n_k): nu_k[k] = 2*np.pi*(k",
"------------------------------------------------------------------------ import numpy as np import scipy as sp import scipy.sparse import itertools",
"in range(n_m): s_k[n_m+k] += -4*a_k[m]/(nu_k[k]**2 - gamma_k[m]**2) s_k[n_m+k] *= T*nu_k[k] for m in",
"import numpy as np import scipy as sp import scipy.sparse import itertools from",
"- 1/(2*T*gamma_k[m])*cot(gamma_k[m]/(2*T)) for k in range(n_k): inner -= 2/(nu_k[k]**2 - gamma_k[m]**2) S_delta +=",
"= kwargs['type_psd'] xi, eta, R_1, T_3 = psd(n_psd, type_psd) # collect poles poles",
"Basis Degeneracy phi_deg_dict = OrderedDict() for gamma, n in itertools.chain(S.keys(), A.keys()): if (gamma",
"1000.0: [[1, 79.1394, 0.637942], [1, 0.655349, 0.666920], [2, 11.6632, 0.456271], [2, 1.54597, 0.740457],",
"in range(n_k): s_k[n_m+k] = 0.0 for m in range(n_m): s_k[n_m+k] += -4*a_k[m]/(nu_k[k]**2 -",
"1 phi_dim = sum((n for n in phi_deg_dict.values())) # phi = [] phi_0",
"gamma[ctr-block_size:ctr, ctr-block_size:ctr].todense(), sigma[ctr-block_size:ctr]) S_delta = 0.0 if (np.inf, 0) in S: S_delta =",
"1, type_psd = 'N/N', # n_fsd_rec=1, chi_fsd=100.0)) # noise = calc_noise_params(*calc_noise_time_domain(J, T, 'psd',",
"S_delta = 0.0 for k in range(n_k): nu_k[k] = 2*np.pi*(k + 1)*T if",
"j, a, b, T_n in coeffs: poles[(T_n/a, j, 0)] = b*(T_n/a)**(2*j-1) n_list =",
"Bath frequency #{} is degenerated.'.format(k)) # r_k[m] --> for m in range(n_m): s_k[m]",
"= A[(gamma_n, deg)] ctr += 1 block_size = deg+1 s_mat[ctr-block_size:ctr, ctr-block_size:ctr] \\ =",
"calc_noise_time_domain(J, T, type_ltc, **kwargs): if (type_ltc == 'none'): n_list = [[0, T, 1,",
"np.ones((phi_dim), np.complex128) s_vec = np.zeros((phi_dim), np.complex128) a_vec = np.zeros((phi_dim), np.complex128) s_mat = sp.sparse.lil_matrix((phi_dim,",
"1, 0]] return calc_S_from_poles(J.poles, n_list), calc_A_from_poles(J.poles) elif (type_ltc == 'msd'): n_msd = kwargs['n_msd']",
"for j, a, b, T_n in coeffs: poles[(T_n/a, j, 0)] = b*(T_n/a)**(2*j-1) n_list",
"s_vec[ctr] = S[(gamma_n, deg)] if ((gamma_n, deg) in A): a_vec[ctr] = A[(gamma_n, deg)]",
"sp.sparse.lil_matrix((phi_dim, phi_dim), dtype=np.complex128) sigma = np.ones((phi_dim), np.complex128) s_vec = np.zeros((phi_dim), np.complex128) a_vec =",
"= calc_A_from_poles(J.poles) gamma_k = np.zeros(len(A), dtype=np.complex128) a_k = np.zeros(len(A), dtype=np.complex128) for k, (gamma,",
"phi_deg_dict[gamma] = max(phi_deg_dict[gamma], n + 1) else: phi_deg_dict[gamma] = n + 1 phi_dim",
"# ------------------------------------------------------------------------ import numpy as np import scipy as sp import scipy.sparse import",
"for gamma, n in itertools.chain(S.keys(), A.keys()): if (gamma == np.inf): continue if gamma",
"= T_n else: T_0 = T # calc psd coeffs n_psd = kwargs['n_psd']",
"-4*a_k[m]/(nu_k[k]**2 - gamma_k[m]**2) s_k[n_m+k] *= T*nu_k[k] for m in range(n_m): inner = 1/gamma_k[m]**2",
"T, n_ltc): def cot(x): return 1/np.tan(x) n_m = a_k.shape[0] n_k = n_ltc nu_k",
"sigma = np.ones((phi_dim), np.complex128) s_vec = np.zeros((phi_dim), np.complex128) a_vec = np.zeros((phi_dim), np.complex128) s_mat",
"1, type_psd = 'N/N', n_fsd_rec=1, chi_fsd=100.0)) # noise = calc_noise_params(*calc_noise_time_domain(J, T, 'psd+fsd', #",
"a_vec = np.zeros((phi_dim), np.complex128) s_mat = sp.sparse.lil_matrix((phi_dim, phi_dim), dtype=np.complex128) a_mat = sp.sparse.lil_matrix((phi_dim, phi_dim),",
"= kwargs['n_msd'] A = calc_A_from_poles(J.poles) gamma_k = np.zeros(len(A), dtype=np.complex128) a_k = np.zeros(len(A), dtype=np.complex128)",
"n_k, dtype=a_k.dtype) S_delta = 0.0 for k in range(n_k): nu_k[k] = 2*np.pi*(k +",
"in A): a_vec[ctr] = A[(gamma_n, deg)] ctr += 1 block_size = deg+1 s_mat[ctr-block_size:ctr,",
"in range(n_k): nu_k[k] = 2*np.pi*(k + 1)*T if np.any(np.abs(gamma_k - nu_k[k]) < (np.finfo(float).eps)):",
"elif (type_ltc == 'msd'): n_msd = kwargs['n_msd'] A = calc_A_from_poles(J.poles) gamma_k = np.zeros(len(A),",
"# calc fsd coeffs T_n = T for i in range(n_fsd_rec): T_np1 =",
"phi_0 = phi_0, s = s_mat, S_delta = S_delta, a = a_mat) def",
"phi_0, s = s_mat, S_delta = S_delta, a = a_mat) def noise_decomposition(J, T,",
"return dict(gamma = gamma, sigma = sigma, phi_0 = phi_0, s = s_mat,",
"= sp.sparse.lil_matrix((phi_dim, phi_dim), dtype=np.complex128) sigma = np.ones((phi_dim), np.complex128) s_vec = np.zeros((phi_dim), np.complex128) a_vec",
"kwargs['type_psd'] xi, eta, R_1, T_3 = psd(n_psd, type_psd) # collect poles poles =",
"poles[(0, 1, 0)] = T_0 if (R_1 != 0): poles[(0, 0, 0)] =",
"= get_commuting_matrix(s_vec[ctr-block_size:ctr], gamma[ctr-block_size:ctr, ctr-block_size:ctr].todense(), sigma[ctr-block_size:ctr]) a_mat[ctr-block_size:ctr, ctr-block_size:ctr] \\ = get_commuting_matrix(a_vec[ctr-block_size:ctr], gamma[ctr-block_size:ctr, ctr-block_size:ctr].todense(), sigma[ctr-block_size:ctr])",
"'psd', # n_psd = 1, type_psd = 'N-1/N')) # noise = calc_noise_params(*calc_noise_time_domain(J, T,",
"for m in range(n_m): inner = 1/gamma_k[m]**2 - 1/(2*T*gamma_k[m])*cot(gamma_k[m]/(2*T)) for k in range(n_k):",
"n_psd = kwargs['n_psd'] type_psd = kwargs['type_psd'] xi, eta, R_1, T_3 = psd(n_psd, type_psd)",
"== 'msd'): n_msd = kwargs['n_msd'] A = calc_A_from_poles(J.poles) gamma_k = np.zeros(len(A), dtype=np.complex128) a_k",
"= 2*np.pi*(k + 1)*T if np.any(np.abs(gamma_k - nu_k[k]) < (np.finfo(float).eps)): raise Exception('[Error] Bath",
"def noise_decomposition(J, T, type_ltc, **kwargs): return calc_noise_params(*calc_noise_time_domain(J, T, type_ltc, **kwargs)) # noise =",
"gamma_n if deg > 0: gamma[ctr,ctr-1] = -deg if ((gamma_n, deg) in S):",
"if np.any(np.abs(gamma_k - nu_k[k]) < (np.finfo(float).eps)): raise Exception('[Error] Bath frequency #{} is degenerated.'.format(k))",
"== 'psd+fsd' ): coeffs = [] coeff_0 = 0 if type_ltc == 'psd+fsd':",
"deg_max in phi_deg_dict.items(): for deg in range(deg_max): phi.append((gamma_n, deg)) phi_0[ctr] = 1 if",
"eta, R_1, T_3 = psd(n_psd, type_psd) # collect poles poles = OrderedDict() ##",
"else: T_0 = T # calc psd coeffs n_psd = kwargs['n_psd'] type_psd =",
"range(deg_max): phi.append((gamma_n, deg)) phi_0[ctr] = 1 if deg == 0 else 0 gamma[ctr,ctr]",
"i in range(n_fsd_rec): T_np1 = T_n*chi_fsd coeff_0 += T_n - T_np1 T_n =",
"S_delta += -2*T*a_k[m]*inner result = OrderedDict() def put_coeff(a, m, coeff): if (a, m)",
"type_ltc, **kwargs): if (type_ltc == 'none'): n_list = [[0, T, 1, 0]] return",
"else: raise Exception('[Error] Unknown ltc') def calc_noise_params(S, A): # Calculate Basis Degeneracy phi_deg_dict",
"T_n]) T_0 = T_n else: T_0 = T # calc psd coeffs n_psd",
"gamma in phi_deg_dict: phi_deg_dict[gamma] = max(phi_deg_dict[gamma], n + 1) else: phi_deg_dict[gamma] = n",
"phi = [] phi_0 = np.zeros((phi_dim), np.complex128) gamma = sp.sparse.lil_matrix((phi_dim, phi_dim), dtype=np.complex128) sigma",
"[[0, T, 1, 0]] return calc_S_from_poles(J.poles, n_list), calc_A_from_poles(J.poles) elif (type_ltc == 'msd'): n_msd",
"A.keys()): if (gamma == np.inf): continue if gamma in phi_deg_dict: phi_deg_dict[gamma] = max(phi_deg_dict[gamma],",
"= b*(T_n/a)**(2*j-1) n_list = [[a, b, m, n] for (a, m, n), b",
"gamma[ctr,ctr-1] = -deg if ((gamma_n, deg) in S): s_vec[ctr] = S[(gamma_n, deg)] if",
"fsd coeffs T_n = T for i in range(n_fsd_rec): T_np1 = T_n*chi_fsd coeff_0",
"def calc_noise_time_domain(J, T, type_ltc, **kwargs): if (type_ltc == 'none'): n_list = [[0, T,",
"a = a_mat) def noise_decomposition(J, T, type_ltc, **kwargs): return calc_noise_params(*calc_noise_time_domain(J, T, type_ltc, **kwargs))",
"= S[(np.inf, 0)] return dict(gamma = gamma, sigma = sigma, phi_0 = phi_0,",
"1)] = T_3 for p in range(n_psd): poles[(T_0*xi[p], 1, 0)] = 2*eta[p]*T_0 ##",
"m, n), b in poles.items()] return calc_S_from_poles(J.poles, n_list), calc_A_from_poles(J.poles) else: raise Exception('[Error] Unknown",
"* from .pade_spectral_decomposition import * fsd_coeffs = { 100.0: [[1, 1.35486, 1.34275], [2,",
"LINCENSE.txt for licence. # ------------------------------------------------------------------------ import numpy as np import scipy as sp",
"def cot(x): return 1/np.tan(x) n_m = a_k.shape[0] n_k = n_ltc nu_k = np.zeros(n_k)",
"(type_ltc == 'psd' or type_ltc == 'psd+fsd' ): coeffs = [] coeff_0 =",
"= R_1 if (T_3 != 0): poles[(0, 0, 1)] = T_3 for p",
"1.34275], [2, 5.50923, 0.880362], [3, 0.553793, -0.965783]], 1000.0: [[1, 79.1394, 0.637942], [1, 0.655349,",
"for i in range(n_fsd_rec): T_np1 = T_n*chi_fsd coeff_0 += T_n - T_np1 T_n",
"0.666920], [2, 11.6632, 0.456271], [2, 1.54597, 0.740457], [3, 3.39011, 0.626892]], } def calc_S_msd(gamma_k,",
"[[1, 1.35486, 1.34275], [2, 5.50923, 0.880362], [3, 0.553793, -0.965783]], 1000.0: [[1, 79.1394, 0.637942],",
"for m in range(n_m): s_k[n_m+k] += -4*a_k[m]/(nu_k[k]**2 - gamma_k[m]**2) s_k[n_m+k] *= T*nu_k[k] for",
"(a, m, n), b in poles.items()] return calc_S_from_poles(J.poles, n_list), calc_A_from_poles(J.poles) else: raise Exception('[Error]",
"T_n else: T_0 = T # calc psd coeffs n_psd = kwargs['n_psd'] type_psd",
"calc_A_from_poles(J.poles) else: raise Exception('[Error] Unknown ltc') def calc_noise_params(S, A): # Calculate Basis Degeneracy",
"T, type_ltc, **kwargs)) # noise = calc_noise_params(*calc_noise_time_domain(None, T, 'psd+fsd', n_psd = 1, type_psd",
"calc_noise_params(*calc_noise_time_domain(J, T, 'msd', # n_msd = 10)) # noise = calc_noise_params(*calc_noise_time_domain(J, T, 'NONE'))",
"collect poles poles = OrderedDict() ## psd poles poles[(0, 1, 0)] = T_0",
"if (type_ltc == 'none'): n_list = [[0, T, 1, 0]] return calc_S_from_poles(J.poles, n_list),",
"0 if type_ltc == 'psd+fsd': n_fsd_rec = kwargs['n_fsd_rec'] chi_fsd = kwargs['chi_fsd'] # calc",
"from .summation_over_poles import * from .commuting_matrix import * from .pade_spectral_decomposition import * fsd_coeffs",
"ltc') def calc_noise_params(S, A): # Calculate Basis Degeneracy phi_deg_dict = OrderedDict() for gamma,",
"* from .summation_over_poles import * from .commuting_matrix import * from .pade_spectral_decomposition import *",
"dtype=np.complex128) a_k = np.zeros(len(A), dtype=np.complex128) for k, (gamma, l) in enumerate(A.keys()): if l",
"!= 0): poles[(0, 0, 1)] = T_3 for p in range(n_psd): poles[(T_0*xi[p], 1,",
"OrderedDict() ## psd poles poles[(0, 1, 0)] = T_0 if (R_1 != 0):",
"Unknown ltc') def calc_noise_params(S, A): # Calculate Basis Degeneracy phi_deg_dict = OrderedDict() for",
"poles = OrderedDict() ## psd poles poles[(0, 1, 0)] = T_0 if (R_1",
"1, 0)] += coeff_0 for j, a, b, T_n in coeffs: poles[(T_n/a, j,",
"BSD 3-Clause License. # See LINCENSE.txt for licence. # ------------------------------------------------------------------------ import numpy as",
"[] phi_0 = np.zeros((phi_dim), np.complex128) gamma = sp.sparse.lil_matrix((phi_dim, phi_dim), dtype=np.complex128) sigma = np.ones((phi_dim),",
"!= 0): poles[(0, 0, 0)] = R_1 if (T_3 != 0): poles[(0, 0,",
"0) in S: S_delta = S[(np.inf, 0)] return dict(gamma = gamma, sigma =",
"T_n in coeffs: poles[(T_n/a, j, 0)] = b*(T_n/a)**(2*j-1) n_list = [[a, b, m,",
"j, a, b in fsd_coeffs[chi_fsd]: coeffs.append([j, a, b, T_n]) T_0 = T_n else:",
"(c) <NAME> # This library is distributed under BSD 3-Clause License. # See",
"def calc_noise_params(S, A): # Calculate Basis Degeneracy phi_deg_dict = OrderedDict() for gamma, n",
"T, n_msd), A elif (type_ltc == 'psd' or type_ltc == 'psd+fsd' ): coeffs",
"== 'psd' or type_ltc == 'psd+fsd' ): coeffs = [] coeff_0 = 0",
"0 for gamma_n, deg_max in phi_deg_dict.items(): for deg in range(deg_max): phi.append((gamma_n, deg)) phi_0[ctr]",
"for deg in range(deg_max): phi.append((gamma_n, deg)) phi_0[ctr] = 1 if deg == 0",
"1)*T if np.any(np.abs(gamma_k - nu_k[k]) < (np.finfo(float).eps)): raise Exception('[Error] Bath frequency #{} is",
"m in range(n_m): s_k[n_m+k] += -4*a_k[m]/(nu_k[k]**2 - gamma_k[m]**2) s_k[n_m+k] *= T*nu_k[k] for m",
"s_mat = sp.sparse.lil_matrix((phi_dim, phi_dim), dtype=np.complex128) a_mat = sp.sparse.lil_matrix((phi_dim, phi_dim), dtype=np.complex128) ctr = 0",
"+= -2*T*a_k[m]*inner result = OrderedDict() def put_coeff(a, m, coeff): if (a, m) in",
"is distributed under BSD 3-Clause License. # See LINCENSE.txt for licence. # ------------------------------------------------------------------------",
"range(n_m): put_coeff(gamma_k[k], 0, s_k[k]) for k in range(n_k): put_coeff(nu_k[k], 0, s_k[k + n_m])",
"'none'): n_list = [[0, T, 1, 0]] return calc_S_from_poles(J.poles, n_list), calc_A_from_poles(J.poles) elif (type_ltc",
"l) in enumerate(A.keys()): if l != 0: raise Exception('[Error] msd accepts only first-order",
"result = OrderedDict() def put_coeff(a, m, coeff): if (a, m) in result: result[(a,",
"T_n = T for i in range(n_fsd_rec): T_np1 = T_n*chi_fsd coeff_0 += T_n",
"licence. # ------------------------------------------------------------------------ import numpy as np import scipy as sp import scipy.sparse",
"calc_noise_params(*calc_noise_time_domain(J, T, type_ltc, **kwargs)) # noise = calc_noise_params(*calc_noise_time_domain(None, T, 'psd+fsd', n_psd = 1,",
"Copyright (c) <NAME> # This library is distributed under BSD 3-Clause License. #",
"== 'psd+fsd': n_fsd_rec = kwargs['n_fsd_rec'] chi_fsd = kwargs['chi_fsd'] # calc fsd coeffs T_n",
"return calc_S_msd(gamma_k, a_k, T, n_msd), A elif (type_ltc == 'psd' or type_ltc ==",
"phi_dim), dtype=np.complex128) a_mat = sp.sparse.lil_matrix((phi_dim, phi_dim), dtype=np.complex128) ctr = 0 for gamma_n, deg_max",
"= gamma_n if deg > 0: gamma[ctr,ctr-1] = -deg if ((gamma_n, deg) in",
"from .pade_spectral_decomposition import * fsd_coeffs = { 100.0: [[1, 1.35486, 1.34275], [2, 5.50923,",
"n_msd = kwargs['n_msd'] A = calc_A_from_poles(J.poles) gamma_k = np.zeros(len(A), dtype=np.complex128) a_k = np.zeros(len(A),",
"def put_coeff(a, m, coeff): if (a, m) in result: result[(a, m)] += coeff",
"phi_0[ctr] = 1 if deg == 0 else 0 gamma[ctr,ctr] = gamma_n if",
"n_psd = 1, type_psd = 'N/N', n_fsd_rec=1, chi_fsd=100.0)) # noise = calc_noise_params(*calc_noise_time_domain(J, T,",
"(R_1 != 0): poles[(0, 0, 0)] = R_1 if (T_3 != 0): poles[(0,",
"- T_np1 T_n = T_np1 for j, a, b in fsd_coeffs[chi_fsd]: coeffs.append([j, a,",
"a_k, T, n_ltc): def cot(x): return 1/np.tan(x) n_m = a_k.shape[0] n_k = n_ltc",
"s = s_mat, S_delta = S_delta, a = a_mat) def noise_decomposition(J, T, type_ltc,",
"S_delta) for k in range(n_m): put_coeff(gamma_k[k], 0, s_k[k]) for k in range(n_k): put_coeff(nu_k[k],",
"== 0 else 0 gamma[ctr,ctr] = gamma_n if deg > 0: gamma[ctr,ctr-1] =",
"sigma = sigma, phi_0 = phi_0, s = s_mat, S_delta = S_delta, a",
"k in range(n_m): put_coeff(gamma_k[k], 0, s_k[k]) for k in range(n_k): put_coeff(nu_k[k], 0, s_k[k",
"0.456271], [2, 1.54597, 0.740457], [3, 3.39011, 0.626892]], } def calc_S_msd(gamma_k, a_k, T, n_ltc):",
"import itertools from collections import OrderedDict from .predefined_noise import * from .summation_over_poles import",
"+= coeff_0 for j, a, b, T_n in coeffs: poles[(T_n/a, j, 0)] =",
".commuting_matrix import * from .pade_spectral_decomposition import * fsd_coeffs = { 100.0: [[1, 1.35486,",
".pade_spectral_decomposition import * fsd_coeffs = { 100.0: [[1, 1.35486, 1.34275], [2, 5.50923, 0.880362],",
"range(n_m): s_k[n_m+k] += -4*a_k[m]/(nu_k[k]**2 - gamma_k[m]**2) s_k[n_m+k] *= T*nu_k[k] for m in range(n_m):",
"m in range(n_m): inner = 1/gamma_k[m]**2 - 1/(2*T*gamma_k[m])*cot(gamma_k[m]/(2*T)) for k in range(n_k): inner",
"in range(n_fsd_rec): T_np1 = T_n*chi_fsd coeff_0 += T_n - T_np1 T_n = T_np1",
"m)] = coeff put_coeff(np.inf, 0, S_delta) for k in range(n_m): put_coeff(gamma_k[k], 0, s_k[k])",
"0, 1)] = T_3 for p in range(n_psd): poles[(T_0*xi[p], 1, 0)] = 2*eta[p]*T_0",
"deg in range(deg_max): phi.append((gamma_n, deg)) phi_0[ctr] = 1 if deg == 0 else",
"fsd poles poles[(0, 1, 0)] += coeff_0 for j, a, b, T_n in",
"in S): s_vec[ctr] = S[(gamma_n, deg)] if ((gamma_n, deg) in A): a_vec[ctr] =",
"n_fsd_rec=1, chi_fsd=100.0)) # noise = calc_noise_params(*calc_noise_time_domain(J, T, 'psd', # n_psd = 1, type_psd",
"A = calc_A_from_poles(J.poles) gamma_k = np.zeros(len(A), dtype=np.complex128) a_k = np.zeros(len(A), dtype=np.complex128) for k,",
"= a_k.shape[0] n_k = n_ltc nu_k = np.zeros(n_k) s_k = np.zeros(n_m + n_k,",
"= 0.0 for k in range(n_k): nu_k[k] = 2*np.pi*(k + 1)*T if np.any(np.abs(gamma_k",
"1/np.tan(x) n_m = a_k.shape[0] n_k = n_ltc nu_k = np.zeros(n_k) s_k = np.zeros(n_m",
"= sum((n for n in phi_deg_dict.values())) # phi = [] phi_0 = np.zeros((phi_dim),",
"n_ltc nu_k = np.zeros(n_k) s_k = np.zeros(n_m + n_k, dtype=a_k.dtype) S_delta = 0.0",
"b, m, n] for (a, m, n), b in poles.items()] return calc_S_from_poles(J.poles, n_list),",
"noise = calc_noise_params(*calc_noise_time_domain(J, T, 'psd', # n_psd = 1, type_psd = 'N-1/N')) #",
"0, S_delta) for k in range(n_m): put_coeff(gamma_k[k], 0, s_k[k]) for k in range(n_k):",
"return calc_S_from_poles(J.poles, n_list), calc_A_from_poles(J.poles) elif (type_ltc == 'msd'): n_msd = kwargs['n_msd'] A =",
"# This library is distributed under BSD 3-Clause License. # See LINCENSE.txt for",
"= 1, type_psd = 'N/N', # n_fsd_rec=1, chi_fsd=100.0)) # noise = calc_noise_params(*calc_noise_time_domain(J, T,",
"[] coeff_0 = 0 if type_ltc == 'psd+fsd': n_fsd_rec = kwargs['n_fsd_rec'] chi_fsd =",
"for k, (gamma, l) in enumerate(A.keys()): if l != 0: raise Exception('[Error] msd",
"enumerate(A.keys()): if l != 0: raise Exception('[Error] msd accepts only first-order poles') gamma_k[k]",
"poles[(0, 0, 1)] = T_3 for p in range(n_psd): poles[(T_0*xi[p], 1, 0)] =",
"n + 1 phi_dim = sum((n for n in phi_deg_dict.values())) # phi =",
"= T_np1 for j, a, b in fsd_coeffs[chi_fsd]: coeffs.append([j, a, b, T_n]) T_0",
"phi_deg_dict = OrderedDict() for gamma, n in itertools.chain(S.keys(), A.keys()): if (gamma == np.inf):",
"else: result[(a, m)] = coeff put_coeff(np.inf, 0, S_delta) for k in range(n_m): put_coeff(gamma_k[k],",
"poles[(0, 1, 0)] += coeff_0 for j, a, b, T_n in coeffs: poles[(T_n/a,",
"sp.sparse.lil_matrix((phi_dim, phi_dim), dtype=np.complex128) ctr = 0 for gamma_n, deg_max in phi_deg_dict.items(): for deg",
"= s_mat, S_delta = S_delta, a = a_mat) def noise_decomposition(J, T, type_ltc, **kwargs):",
"<gh_stars>1-10 # # LibHEOM: Copyright (c) <NAME> # This library is distributed under",
"ctr += 1 block_size = deg+1 s_mat[ctr-block_size:ctr, ctr-block_size:ctr] \\ = get_commuting_matrix(s_vec[ctr-block_size:ctr], gamma[ctr-block_size:ctr, ctr-block_size:ctr].todense(),",
"100.0: [[1, 1.35486, 1.34275], [2, 5.50923, 0.880362], [3, 0.553793, -0.965783]], 1000.0: [[1, 79.1394,",
"sigma[ctr-block_size:ctr]) a_mat[ctr-block_size:ctr, ctr-block_size:ctr] \\ = get_commuting_matrix(a_vec[ctr-block_size:ctr], gamma[ctr-block_size:ctr, ctr-block_size:ctr].todense(), sigma[ctr-block_size:ctr]) S_delta = 0.0 if",
"for licence. # ------------------------------------------------------------------------ import numpy as np import scipy as sp import",
"np.complex128) a_vec = np.zeros((phi_dim), np.complex128) s_mat = sp.sparse.lil_matrix((phi_dim, phi_dim), dtype=np.complex128) a_mat = sp.sparse.lil_matrix((phi_dim,",
"range(n_k): s_k[n_m+k] = 0.0 for m in range(n_m): s_k[n_m+k] += -4*a_k[m]/(nu_k[k]**2 - gamma_k[m]**2)",
"k in range(n_k): s_k[n_m+k] = 0.0 for m in range(n_m): s_k[n_m+k] += -4*a_k[m]/(nu_k[k]**2",
"get_commuting_matrix(s_vec[ctr-block_size:ctr], gamma[ctr-block_size:ctr, ctr-block_size:ctr].todense(), sigma[ctr-block_size:ctr]) a_mat[ctr-block_size:ctr, ctr-block_size:ctr] \\ = get_commuting_matrix(a_vec[ctr-block_size:ctr], gamma[ctr-block_size:ctr, ctr-block_size:ctr].todense(), sigma[ctr-block_size:ctr]) S_delta",
"1 if deg == 0 else 0 gamma[ctr,ctr] = gamma_n if deg >",
"continue if gamma in phi_deg_dict: phi_deg_dict[gamma] = max(phi_deg_dict[gamma], n + 1) else: phi_deg_dict[gamma]",
"in enumerate(A.keys()): if l != 0: raise Exception('[Error] msd accepts only first-order poles')",
"= 1/gamma_k[m]**2 - 1/(2*T*gamma_k[m])*cot(gamma_k[m]/(2*T)) for k in range(n_k): inner -= 2/(nu_k[k]**2 - gamma_k[m]**2)",
"): coeffs = [] coeff_0 = 0 if type_ltc == 'psd+fsd': n_fsd_rec =",
"- nu_k[k]) < (np.finfo(float).eps)): raise Exception('[Error] Bath frequency #{} is degenerated.'.format(k)) # r_k[m]",
"n_m = a_k.shape[0] n_k = n_ltc nu_k = np.zeros(n_k) s_k = np.zeros(n_m +",
"inner = 1/gamma_k[m]**2 - 1/(2*T*gamma_k[m])*cot(gamma_k[m]/(2*T)) for k in range(n_k): inner -= 2/(nu_k[k]**2 -",
"first-order poles') gamma_k[k] = gamma a_k[k] = A[(gamma, 0)] return calc_S_msd(gamma_k, a_k, T,",
"dict(gamma = gamma, sigma = sigma, phi_0 = phi_0, s = s_mat, S_delta",
"> 0: gamma[ctr,ctr-1] = -deg if ((gamma_n, deg) in S): s_vec[ctr] = S[(gamma_n,",
"n_ltc): def cot(x): return 1/np.tan(x) n_m = a_k.shape[0] n_k = n_ltc nu_k =",
"n_msd), A elif (type_ltc == 'psd' or type_ltc == 'psd+fsd' ): coeffs =",
"- gamma_k[m]**2) S_delta += -2*T*a_k[m]*inner result = OrderedDict() def put_coeff(a, m, coeff): if",
"n in itertools.chain(S.keys(), A.keys()): if (gamma == np.inf): continue if gamma in phi_deg_dict:",
"s_k = np.zeros(n_m + n_k, dtype=a_k.dtype) S_delta = 0.0 for k in range(n_k):",
"result[(a, m)] = coeff put_coeff(np.inf, 0, S_delta) for k in range(n_m): put_coeff(gamma_k[k], 0,",
"if gamma in phi_deg_dict: phi_deg_dict[gamma] = max(phi_deg_dict[gamma], n + 1) else: phi_deg_dict[gamma] =",
"calc_S_msd(gamma_k, a_k, T, n_msd), A elif (type_ltc == 'psd' or type_ltc == 'psd+fsd'",
"## fsd poles poles[(0, 1, 0)] += coeff_0 for j, a, b, T_n",
"OrderedDict() def put_coeff(a, m, coeff): if (a, m) in result: result[(a, m)] +=",
"License. # See LINCENSE.txt for licence. # ------------------------------------------------------------------------ import numpy as np import",
"a, b, T_n in coeffs: poles[(T_n/a, j, 0)] = b*(T_n/a)**(2*j-1) n_list = [[a,",
"(type_ltc == 'none'): n_list = [[0, T, 1, 0]] return calc_S_from_poles(J.poles, n_list), calc_A_from_poles(J.poles)",
"\\ = get_commuting_matrix(s_vec[ctr-block_size:ctr], gamma[ctr-block_size:ctr, ctr-block_size:ctr].todense(), sigma[ctr-block_size:ctr]) a_mat[ctr-block_size:ctr, ctr-block_size:ctr] \\ = get_commuting_matrix(a_vec[ctr-block_size:ctr], gamma[ctr-block_size:ctr, ctr-block_size:ctr].todense(),",
"= calc_noise_params(*calc_noise_time_domain(J, T, 'msd', # n_msd = 10)) # noise = calc_noise_params(*calc_noise_time_domain(J, T,",
"in range(n_m): s_k[m] = -2*a_k[m]*cot(gamma_k[m]/(2*T))/2.0 for k in range(n_k): s_k[n_m+k] = 0.0 for",
"T_n - T_np1 T_n = T_np1 for j, a, b in fsd_coeffs[chi_fsd]: coeffs.append([j,",
".predefined_noise import * from .summation_over_poles import * from .commuting_matrix import * from .pade_spectral_decomposition",
"(np.finfo(float).eps)): raise Exception('[Error] Bath frequency #{} is degenerated.'.format(k)) # r_k[m] --> for m",
"kwargs['n_psd'] type_psd = kwargs['type_psd'] xi, eta, R_1, T_3 = psd(n_psd, type_psd) # collect",
"'psd+fsd': n_fsd_rec = kwargs['n_fsd_rec'] chi_fsd = kwargs['chi_fsd'] # calc fsd coeffs T_n =",
"ctr-block_size:ctr].todense(), sigma[ctr-block_size:ctr]) S_delta = 0.0 if (np.inf, 0) in S: S_delta = S[(np.inf,",
"1.54597, 0.740457], [3, 3.39011, 0.626892]], } def calc_S_msd(gamma_k, a_k, T, n_ltc): def cot(x):",
"msd accepts only first-order poles') gamma_k[k] = gamma a_k[k] = A[(gamma, 0)] return",
"= 'N-1/N')) # noise = calc_noise_params(*calc_noise_time_domain(J, T, 'msd', # n_msd = 10)) #",
"0: gamma[ctr,ctr-1] = -deg if ((gamma_n, deg) in S): s_vec[ctr] = S[(gamma_n, deg)]",
"poles poles = OrderedDict() ## psd poles poles[(0, 1, 0)] = T_0 if",
"j, 0)] = b*(T_n/a)**(2*j-1) n_list = [[a, b, m, n] for (a, m,",
"n] for (a, m, n), b in poles.items()] return calc_S_from_poles(J.poles, n_list), calc_A_from_poles(J.poles) else:",
"import * from .summation_over_poles import * from .commuting_matrix import * from .pade_spectral_decomposition import",
"+ 1 phi_dim = sum((n for n in phi_deg_dict.values())) # phi = []",
"for k in range(n_m): put_coeff(gamma_k[k], 0, s_k[k]) for k in range(n_k): put_coeff(nu_k[k], 0,",
"= calc_noise_params(*calc_noise_time_domain(None, T, 'psd+fsd', n_psd = 1, type_psd = 'N/N', n_fsd_rec=1, chi_fsd=100.0)) #",
"'psd' or type_ltc == 'psd+fsd' ): coeffs = [] coeff_0 = 0 if",
"= np.zeros((phi_dim), np.complex128) a_vec = np.zeros((phi_dim), np.complex128) s_mat = sp.sparse.lil_matrix((phi_dim, phi_dim), dtype=np.complex128) a_mat",
"## psd poles poles[(0, 1, 0)] = T_0 if (R_1 != 0): poles[(0,",
"put_coeff(gamma_k[k], 0, s_k[k]) for k in range(n_k): put_coeff(nu_k[k], 0, s_k[k + n_m]) return",
"accepts only first-order poles') gamma_k[k] = gamma a_k[k] = A[(gamma, 0)] return calc_S_msd(gamma_k,",
"<NAME> # This library is distributed under BSD 3-Clause License. # See LINCENSE.txt",
"np import scipy as sp import scipy.sparse import itertools from collections import OrderedDict",
"# phi = [] phi_0 = np.zeros((phi_dim), np.complex128) gamma = sp.sparse.lil_matrix((phi_dim, phi_dim), dtype=np.complex128)",
"in poles.items()] return calc_S_from_poles(J.poles, n_list), calc_A_from_poles(J.poles) else: raise Exception('[Error] Unknown ltc') def calc_noise_params(S,",
"= -deg if ((gamma_n, deg) in S): s_vec[ctr] = S[(gamma_n, deg)] if ((gamma_n,",
"m, coeff): if (a, m) in result: result[(a, m)] += coeff else: result[(a,",
"= calc_noise_params(*calc_noise_time_domain(J, T, 'psd', # n_psd = 1, type_psd = 'N-1/N')) # noise",
"0: raise Exception('[Error] msd accepts only first-order poles') gamma_k[k] = gamma a_k[k] =",
"phi_dim), dtype=np.complex128) ctr = 0 for gamma_n, deg_max in phi_deg_dict.items(): for deg in",
"= 1, type_psd = 'N-1/N')) # noise = calc_noise_params(*calc_noise_time_domain(J, T, 'msd', # n_msd",
"s_mat[ctr-block_size:ctr, ctr-block_size:ctr] \\ = get_commuting_matrix(s_vec[ctr-block_size:ctr], gamma[ctr-block_size:ctr, ctr-block_size:ctr].todense(), sigma[ctr-block_size:ctr]) a_mat[ctr-block_size:ctr, ctr-block_size:ctr] \\ = get_commuting_matrix(a_vec[ctr-block_size:ctr],",
"(gamma, l) in enumerate(A.keys()): if l != 0: raise Exception('[Error] msd accepts only",
"in phi_deg_dict.values())) # phi = [] phi_0 = np.zeros((phi_dim), np.complex128) gamma = sp.sparse.lil_matrix((phi_dim,",
"chi_fsd=100.0)) # noise = calc_noise_params(*calc_noise_time_domain(J, T, 'psd', # n_psd = 1, type_psd =",
"import * fsd_coeffs = { 100.0: [[1, 1.35486, 1.34275], [2, 5.50923, 0.880362], [3,",
"return 1/np.tan(x) n_m = a_k.shape[0] n_k = n_ltc nu_k = np.zeros(n_k) s_k =",
"< (np.finfo(float).eps)): raise Exception('[Error] Bath frequency #{} is degenerated.'.format(k)) # r_k[m] --> for",
"coeffs T_n = T for i in range(n_fsd_rec): T_np1 = T_n*chi_fsd coeff_0 +=",
"+= -4*a_k[m]/(nu_k[k]**2 - gamma_k[m]**2) s_k[n_m+k] *= T*nu_k[k] for m in range(n_m): inner =",
"T*nu_k[k] for m in range(n_m): inner = 1/gamma_k[m]**2 - 1/(2*T*gamma_k[m])*cot(gamma_k[m]/(2*T)) for k in",
"for j, a, b in fsd_coeffs[chi_fsd]: coeffs.append([j, a, b, T_n]) T_0 = T_n",
"coeffs: poles[(T_n/a, j, 0)] = b*(T_n/a)**(2*j-1) n_list = [[a, b, m, n] for",
"if deg == 0 else 0 gamma[ctr,ctr] = gamma_n if deg > 0:",
"range(n_k): inner -= 2/(nu_k[k]**2 - gamma_k[m]**2) S_delta += -2*T*a_k[m]*inner result = OrderedDict() def",
"coeff else: result[(a, m)] = coeff put_coeff(np.inf, 0, S_delta) for k in range(n_m):",
"np.zeros((phi_dim), np.complex128) gamma = sp.sparse.lil_matrix((phi_dim, phi_dim), dtype=np.complex128) sigma = np.ones((phi_dim), np.complex128) s_vec =",
"S[(gamma_n, deg)] if ((gamma_n, deg) in A): a_vec[ctr] = A[(gamma_n, deg)] ctr +=",
"# noise = calc_noise_params(*calc_noise_time_domain(J, T, 'psd+fsd', # n_psd = 1, type_psd = 'N/N',",
"deg+1 s_mat[ctr-block_size:ctr, ctr-block_size:ctr] \\ = get_commuting_matrix(s_vec[ctr-block_size:ctr], gamma[ctr-block_size:ctr, ctr-block_size:ctr].todense(), sigma[ctr-block_size:ctr]) a_mat[ctr-block_size:ctr, ctr-block_size:ctr] \\ =",
"= np.ones((phi_dim), np.complex128) s_vec = np.zeros((phi_dim), np.complex128) a_vec = np.zeros((phi_dim), np.complex128) s_mat =",
"T, type_ltc, **kwargs): if (type_ltc == 'none'): n_list = [[0, T, 1, 0]]",
"in range(n_k): inner -= 2/(nu_k[k]**2 - gamma_k[m]**2) S_delta += -2*T*a_k[m]*inner result = OrderedDict()",
"chi_fsd = kwargs['chi_fsd'] # calc fsd coeffs T_n = T for i in",
"coeff): if (a, m) in result: result[(a, m)] += coeff else: result[(a, m)]",
"kwargs['n_fsd_rec'] chi_fsd = kwargs['chi_fsd'] # calc fsd coeffs T_n = T for i",
"for k in range(n_k): s_k[n_m+k] = 0.0 for m in range(n_m): s_k[n_m+k] +=",
"= T_0 if (R_1 != 0): poles[(0, 0, 0)] = R_1 if (T_3",
"a_k, T, n_msd), A elif (type_ltc == 'psd' or type_ltc == 'psd+fsd' ):",
"if ((gamma_n, deg) in S): s_vec[ctr] = S[(gamma_n, deg)] if ((gamma_n, deg) in"
] |
[
"[trend.data['x'][-1]+1], 'y': [trend.data['y'][-1]+np.random.randn()] }, rollover=20) cb = pn.state.add_periodic_callback(stream, 500) pn.template.FastListTemplate( site=\"Panel\", title=\"Streaming Trend",
"<filename>snippets/streaming_indicators_app.py import numpy as np import pandas as pd import panel as pn",
"panel as pn pn.extension(sizing_mode='stretch_width') layout = pn.layout.FlexBox(*( pn.indicators.Trend( data={'x': list(range(10)), 'y': np.random.randn(10).cumsum()}, width=150,",
"rollover=20) cb = pn.state.add_periodic_callback(stream, 500) pn.template.FastListTemplate( site=\"Panel\", title=\"Streaming Trend Indicators\", main=[layout,], header_background=\"#428bca\" ).servable()",
"= pn.layout.FlexBox(*( pn.indicators.Trend( data={'x': list(range(10)), 'y': np.random.randn(10).cumsum()}, width=150, height=100, plot_type=pn.indicators.Trend.param.plot_type.objects[i%4] ) for i",
")) def stream(): for trend in layout: trend.stream( { 'x': [trend.data['x'][-1]+1], 'y': [trend.data['y'][-1]+np.random.randn()]",
"def stream(): for trend in layout: trend.stream( { 'x': [trend.data['x'][-1]+1], 'y': [trend.data['y'][-1]+np.random.randn()] },",
") for i in range(28) )) def stream(): for trend in layout: trend.stream(",
"width=150, height=100, plot_type=pn.indicators.Trend.param.plot_type.objects[i%4] ) for i in range(28) )) def stream(): for trend",
"trend.stream( { 'x': [trend.data['x'][-1]+1], 'y': [trend.data['y'][-1]+np.random.randn()] }, rollover=20) cb = pn.state.add_periodic_callback(stream, 500) pn.template.FastListTemplate(",
"'y': [trend.data['y'][-1]+np.random.randn()] }, rollover=20) cb = pn.state.add_periodic_callback(stream, 500) pn.template.FastListTemplate( site=\"Panel\", title=\"Streaming Trend Indicators\",",
"in layout: trend.stream( { 'x': [trend.data['x'][-1]+1], 'y': [trend.data['y'][-1]+np.random.randn()] }, rollover=20) cb = pn.state.add_periodic_callback(stream,",
"layout = pn.layout.FlexBox(*( pn.indicators.Trend( data={'x': list(range(10)), 'y': np.random.randn(10).cumsum()}, width=150, height=100, plot_type=pn.indicators.Trend.param.plot_type.objects[i%4] ) for",
"'y': np.random.randn(10).cumsum()}, width=150, height=100, plot_type=pn.indicators.Trend.param.plot_type.objects[i%4] ) for i in range(28) )) def stream():",
"pn pn.extension(sizing_mode='stretch_width') layout = pn.layout.FlexBox(*( pn.indicators.Trend( data={'x': list(range(10)), 'y': np.random.randn(10).cumsum()}, width=150, height=100, plot_type=pn.indicators.Trend.param.plot_type.objects[i%4]",
"numpy as np import pandas as pd import panel as pn pn.extension(sizing_mode='stretch_width') layout",
"import pandas as pd import panel as pn pn.extension(sizing_mode='stretch_width') layout = pn.layout.FlexBox(*( pn.indicators.Trend(",
"data={'x': list(range(10)), 'y': np.random.randn(10).cumsum()}, width=150, height=100, plot_type=pn.indicators.Trend.param.plot_type.objects[i%4] ) for i in range(28) ))",
"stream(): for trend in layout: trend.stream( { 'x': [trend.data['x'][-1]+1], 'y': [trend.data['y'][-1]+np.random.randn()] }, rollover=20)",
"range(28) )) def stream(): for trend in layout: trend.stream( { 'x': [trend.data['x'][-1]+1], 'y':",
"}, rollover=20) cb = pn.state.add_periodic_callback(stream, 500) pn.template.FastListTemplate( site=\"Panel\", title=\"Streaming Trend Indicators\", main=[layout,], header_background=\"#428bca\"",
"import panel as pn pn.extension(sizing_mode='stretch_width') layout = pn.layout.FlexBox(*( pn.indicators.Trend( data={'x': list(range(10)), 'y': np.random.randn(10).cumsum()},",
"'x': [trend.data['x'][-1]+1], 'y': [trend.data['y'][-1]+np.random.randn()] }, rollover=20) cb = pn.state.add_periodic_callback(stream, 500) pn.template.FastListTemplate( site=\"Panel\", title=\"Streaming",
"pn.layout.FlexBox(*( pn.indicators.Trend( data={'x': list(range(10)), 'y': np.random.randn(10).cumsum()}, width=150, height=100, plot_type=pn.indicators.Trend.param.plot_type.objects[i%4] ) for i in",
"trend in layout: trend.stream( { 'x': [trend.data['x'][-1]+1], 'y': [trend.data['y'][-1]+np.random.randn()] }, rollover=20) cb =",
"pandas as pd import panel as pn pn.extension(sizing_mode='stretch_width') layout = pn.layout.FlexBox(*( pn.indicators.Trend( data={'x':",
"pd import panel as pn pn.extension(sizing_mode='stretch_width') layout = pn.layout.FlexBox(*( pn.indicators.Trend( data={'x': list(range(10)), 'y':",
"for trend in layout: trend.stream( { 'x': [trend.data['x'][-1]+1], 'y': [trend.data['y'][-1]+np.random.randn()] }, rollover=20) cb",
"in range(28) )) def stream(): for trend in layout: trend.stream( { 'x': [trend.data['x'][-1]+1],",
"for i in range(28) )) def stream(): for trend in layout: trend.stream( {",
"pn.indicators.Trend( data={'x': list(range(10)), 'y': np.random.randn(10).cumsum()}, width=150, height=100, plot_type=pn.indicators.Trend.param.plot_type.objects[i%4] ) for i in range(28)",
"height=100, plot_type=pn.indicators.Trend.param.plot_type.objects[i%4] ) for i in range(28) )) def stream(): for trend in",
"layout: trend.stream( { 'x': [trend.data['x'][-1]+1], 'y': [trend.data['y'][-1]+np.random.randn()] }, rollover=20) cb = pn.state.add_periodic_callback(stream, 500)",
"{ 'x': [trend.data['x'][-1]+1], 'y': [trend.data['y'][-1]+np.random.randn()] }, rollover=20) cb = pn.state.add_periodic_callback(stream, 500) pn.template.FastListTemplate( site=\"Panel\",",
"np.random.randn(10).cumsum()}, width=150, height=100, plot_type=pn.indicators.Trend.param.plot_type.objects[i%4] ) for i in range(28) )) def stream(): for",
"plot_type=pn.indicators.Trend.param.plot_type.objects[i%4] ) for i in range(28) )) def stream(): for trend in layout:",
"import numpy as np import pandas as pd import panel as pn pn.extension(sizing_mode='stretch_width')",
"i in range(28) )) def stream(): for trend in layout: trend.stream( { 'x':",
"[trend.data['y'][-1]+np.random.randn()] }, rollover=20) cb = pn.state.add_periodic_callback(stream, 500) pn.template.FastListTemplate( site=\"Panel\", title=\"Streaming Trend Indicators\", main=[layout,],",
"as pn pn.extension(sizing_mode='stretch_width') layout = pn.layout.FlexBox(*( pn.indicators.Trend( data={'x': list(range(10)), 'y': np.random.randn(10).cumsum()}, width=150, height=100,",
"pn.extension(sizing_mode='stretch_width') layout = pn.layout.FlexBox(*( pn.indicators.Trend( data={'x': list(range(10)), 'y': np.random.randn(10).cumsum()}, width=150, height=100, plot_type=pn.indicators.Trend.param.plot_type.objects[i%4] )",
"list(range(10)), 'y': np.random.randn(10).cumsum()}, width=150, height=100, plot_type=pn.indicators.Trend.param.plot_type.objects[i%4] ) for i in range(28) )) def",
"np import pandas as pd import panel as pn pn.extension(sizing_mode='stretch_width') layout = pn.layout.FlexBox(*(",
"as np import pandas as pd import panel as pn pn.extension(sizing_mode='stretch_width') layout =",
"as pd import panel as pn pn.extension(sizing_mode='stretch_width') layout = pn.layout.FlexBox(*( pn.indicators.Trend( data={'x': list(range(10)),"
] |
[
"= [] self.time = 0 def enqueue(self, animal: list): if animal[1]: self.dogQueue.append((animal, self.time))",
"+= 1 def dequeueAny(self) -> list: if len(self.catQueue) == 0 or self.catQueue[0][1] <=",
"if len(self.dogQueue) != 0: return self.dogQueue.pop(0)[0] return [-1, -1] def dequeueCat(self) -> Animal:",
"def dequeueDog(self) -> Animal: if len(self.dogQueue) != 0: return self.dogQueue.pop(0)[0] return [-1, -1]",
"0 def enqueue(self, animal: list): if animal[1]: self.dogQueue.append((animal, self.time)) else: self.catQueue.append((animal, self.time)) self.time",
"<gh_stars>0 class Animal: def __init__(self, id: int, isDog: bool): self.id = id self.isDog",
"self.catQueue = [] self.dogQueue = [] self.time = 0 def enqueue(self, animal: list):",
"= 0 def enqueue(self, animal: list): if animal[1]: self.dogQueue.append((animal, self.time)) else: self.catQueue.append((animal, self.time))",
"-> Animal: if len(self.dogQueue) != 0: return self.dogQueue.pop(0)[0] return [-1, -1] def dequeueCat(self)",
"[] self.dogQueue = [] self.time = 0 def enqueue(self, animal: list): if animal[1]:",
"if len(self.dogQueue) == 0 or self.dogQueue[0][1] <= self.catQueue[0][1]: return self.dogQueue.pop(0)[0] return [-1, -1]",
"return [-1, -1] def dequeueDog(self) -> Animal: if len(self.dogQueue) != 0: return self.dogQueue.pop(0)[0]",
"isDog: bool): self.id = id self.isDog = isDog class Solution: def __init__(self): self.catQueue",
"[-1, -1] def dequeueDog(self) -> Animal: if len(self.dogQueue) != 0: return self.dogQueue.pop(0)[0] return",
"self.time += 1 def dequeueAny(self) -> list: if len(self.catQueue) == 0 or self.catQueue[0][1]",
"self.dogQueue.pop(0)[0] return [-1, -1] def dequeueCat(self) -> Animal: if len(self.catQueue) != 0: return",
"dequeueDog(self) -> Animal: if len(self.dogQueue) != 0: return self.dogQueue.pop(0)[0] return [-1, -1] def",
"id self.isDog = isDog class Solution: def __init__(self): self.catQueue = [] self.dogQueue =",
"__init__(self): self.catQueue = [] self.dogQueue = [] self.time = 0 def enqueue(self, animal:",
"<= self.dogQueue[0][1]: return self.catQueue.pop(0)[0] if len(self.dogQueue) == 0 or self.dogQueue[0][1] <= self.catQueue[0][1]: return",
"0 or self.catQueue[0][1] <= self.dogQueue[0][1]: return self.catQueue.pop(0)[0] if len(self.dogQueue) == 0 or self.dogQueue[0][1]",
"-> list: if len(self.catQueue) == 0 or self.catQueue[0][1] <= self.dogQueue[0][1]: return self.catQueue.pop(0)[0] if",
"-1] def dequeueCat(self) -> Animal: if len(self.catQueue) != 0: return self.catQueue.pop(0)[0] return [-1,",
"isDog class Solution: def __init__(self): self.catQueue = [] self.dogQueue = [] self.time =",
"list): if animal[1]: self.dogQueue.append((animal, self.time)) else: self.catQueue.append((animal, self.time)) self.time += 1 def dequeueAny(self)",
"int, isDog: bool): self.id = id self.isDog = isDog class Solution: def __init__(self):",
"class Solution: def __init__(self): self.catQueue = [] self.dogQueue = [] self.time = 0",
"== 0 or self.dogQueue[0][1] <= self.catQueue[0][1]: return self.dogQueue.pop(0)[0] return [-1, -1] def dequeueDog(self)",
"self.isDog = isDog class Solution: def __init__(self): self.catQueue = [] self.dogQueue = []",
"return [-1, -1] def dequeueCat(self) -> Animal: if len(self.catQueue) != 0: return self.catQueue.pop(0)[0]",
"== 0 or self.catQueue[0][1] <= self.dogQueue[0][1]: return self.catQueue.pop(0)[0] if len(self.dogQueue) == 0 or",
"return self.dogQueue.pop(0)[0] return [-1, -1] def dequeueDog(self) -> Animal: if len(self.dogQueue) != 0:",
"-1] def dequeueDog(self) -> Animal: if len(self.dogQueue) != 0: return self.dogQueue.pop(0)[0] return [-1,",
"= [] self.dogQueue = [] self.time = 0 def enqueue(self, animal: list): if",
"self.dogQueue.pop(0)[0] return [-1, -1] def dequeueDog(self) -> Animal: if len(self.dogQueue) != 0: return",
"else: self.catQueue.append((animal, self.time)) self.time += 1 def dequeueAny(self) -> list: if len(self.catQueue) ==",
"self.catQueue.append((animal, self.time)) self.time += 1 def dequeueAny(self) -> list: if len(self.catQueue) == 0",
"<= self.catQueue[0][1]: return self.dogQueue.pop(0)[0] return [-1, -1] def dequeueDog(self) -> Animal: if len(self.dogQueue)",
"animal: list): if animal[1]: self.dogQueue.append((animal, self.time)) else: self.catQueue.append((animal, self.time)) self.time += 1 def",
"self.catQueue[0][1]: return self.dogQueue.pop(0)[0] return [-1, -1] def dequeueDog(self) -> Animal: if len(self.dogQueue) !=",
"if animal[1]: self.dogQueue.append((animal, self.time)) else: self.catQueue.append((animal, self.time)) self.time += 1 def dequeueAny(self) ->",
"0 or self.dogQueue[0][1] <= self.catQueue[0][1]: return self.dogQueue.pop(0)[0] return [-1, -1] def dequeueDog(self) ->",
"self.time)) self.time += 1 def dequeueAny(self) -> list: if len(self.catQueue) == 0 or",
"len(self.dogQueue) == 0 or self.dogQueue[0][1] <= self.catQueue[0][1]: return self.dogQueue.pop(0)[0] return [-1, -1] def",
"def enqueue(self, animal: list): if animal[1]: self.dogQueue.append((animal, self.time)) else: self.catQueue.append((animal, self.time)) self.time +=",
"class Animal: def __init__(self, id: int, isDog: bool): self.id = id self.isDog =",
"self.dogQueue[0][1]: return self.catQueue.pop(0)[0] if len(self.dogQueue) == 0 or self.dogQueue[0][1] <= self.catQueue[0][1]: return self.dogQueue.pop(0)[0]",
"id: int, isDog: bool): self.id = id self.isDog = isDog class Solution: def",
"Animal: def __init__(self, id: int, isDog: bool): self.id = id self.isDog = isDog",
"__init__(self, id: int, isDog: bool): self.id = id self.isDog = isDog class Solution:",
"self.catQueue.pop(0)[0] if len(self.dogQueue) == 0 or self.dogQueue[0][1] <= self.catQueue[0][1]: return self.dogQueue.pop(0)[0] return [-1,",
"bool): self.id = id self.isDog = isDog class Solution: def __init__(self): self.catQueue =",
"def dequeueCat(self) -> Animal: if len(self.catQueue) != 0: return self.catQueue.pop(0)[0] return [-1, -1]",
"return self.catQueue.pop(0)[0] if len(self.dogQueue) == 0 or self.dogQueue[0][1] <= self.catQueue[0][1]: return self.dogQueue.pop(0)[0] return",
"Animal: if len(self.dogQueue) != 0: return self.dogQueue.pop(0)[0] return [-1, -1] def dequeueCat(self) ->",
"def __init__(self, id: int, isDog: bool): self.id = id self.isDog = isDog class",
"def dequeueAny(self) -> list: if len(self.catQueue) == 0 or self.catQueue[0][1] <= self.dogQueue[0][1]: return",
"1 def dequeueAny(self) -> list: if len(self.catQueue) == 0 or self.catQueue[0][1] <= self.dogQueue[0][1]:",
"list: if len(self.catQueue) == 0 or self.catQueue[0][1] <= self.dogQueue[0][1]: return self.catQueue.pop(0)[0] if len(self.dogQueue)",
"self.dogQueue.append((animal, self.time)) else: self.catQueue.append((animal, self.time)) self.time += 1 def dequeueAny(self) -> list: if",
"Solution: def __init__(self): self.catQueue = [] self.dogQueue = [] self.time = 0 def",
"animal[1]: self.dogQueue.append((animal, self.time)) else: self.catQueue.append((animal, self.time)) self.time += 1 def dequeueAny(self) -> list:",
"self.catQueue[0][1] <= self.dogQueue[0][1]: return self.catQueue.pop(0)[0] if len(self.dogQueue) == 0 or self.dogQueue[0][1] <= self.catQueue[0][1]:",
"= isDog class Solution: def __init__(self): self.catQueue = [] self.dogQueue = [] self.time",
"self.time = 0 def enqueue(self, animal: list): if animal[1]: self.dogQueue.append((animal, self.time)) else: self.catQueue.append((animal,",
"!= 0: return self.dogQueue.pop(0)[0] return [-1, -1] def dequeueCat(self) -> Animal: if len(self.catQueue)",
"self.time)) else: self.catQueue.append((animal, self.time)) self.time += 1 def dequeueAny(self) -> list: if len(self.catQueue)",
"self.dogQueue = [] self.time = 0 def enqueue(self, animal: list): if animal[1]: self.dogQueue.append((animal,",
"len(self.catQueue) == 0 or self.catQueue[0][1] <= self.dogQueue[0][1]: return self.catQueue.pop(0)[0] if len(self.dogQueue) == 0",
"= id self.isDog = isDog class Solution: def __init__(self): self.catQueue = [] self.dogQueue",
"if len(self.catQueue) == 0 or self.catQueue[0][1] <= self.dogQueue[0][1]: return self.catQueue.pop(0)[0] if len(self.dogQueue) ==",
"enqueue(self, animal: list): if animal[1]: self.dogQueue.append((animal, self.time)) else: self.catQueue.append((animal, self.time)) self.time += 1",
"or self.dogQueue[0][1] <= self.catQueue[0][1]: return self.dogQueue.pop(0)[0] return [-1, -1] def dequeueDog(self) -> Animal:",
"self.dogQueue[0][1] <= self.catQueue[0][1]: return self.dogQueue.pop(0)[0] return [-1, -1] def dequeueDog(self) -> Animal: if",
"self.id = id self.isDog = isDog class Solution: def __init__(self): self.catQueue = []",
"or self.catQueue[0][1] <= self.dogQueue[0][1]: return self.catQueue.pop(0)[0] if len(self.dogQueue) == 0 or self.dogQueue[0][1] <=",
"0: return self.dogQueue.pop(0)[0] return [-1, -1] def dequeueCat(self) -> Animal: if len(self.catQueue) !=",
"dequeueAny(self) -> list: if len(self.catQueue) == 0 or self.catQueue[0][1] <= self.dogQueue[0][1]: return self.catQueue.pop(0)[0]",
"return self.dogQueue.pop(0)[0] return [-1, -1] def dequeueCat(self) -> Animal: if len(self.catQueue) != 0:",
"def __init__(self): self.catQueue = [] self.dogQueue = [] self.time = 0 def enqueue(self,",
"len(self.dogQueue) != 0: return self.dogQueue.pop(0)[0] return [-1, -1] def dequeueCat(self) -> Animal: if",
"[-1, -1] def dequeueCat(self) -> Animal: if len(self.catQueue) != 0: return self.catQueue.pop(0)[0] return",
"[] self.time = 0 def enqueue(self, animal: list): if animal[1]: self.dogQueue.append((animal, self.time)) else:"
] |
[
"from composer.models.resnet9_cifar10.resnet9_cifar10_hparams import CIFARResNet9Hparams as CIFARResNet9Hparams _task = 'Image Classification' _dataset = 'CIFAR10'",
"CIFARResNet9Hparams _task = 'Image Classification' _dataset = 'CIFAR10' _name = 'ResNet9' _quality =",
"composer.models.resnet9_cifar10.model import CIFAR10_ResNet9 as CIFAR10_ResNet9 from composer.models.resnet9_cifar10.resnet9_cifar10_hparams import CIFARResNet9Hparams as CIFARResNet9Hparams _task =",
"<reponame>ajaysaini725/composer<filename>composer/models/resnet9_cifar10/__init__.py # Copyright 2021 MosaicML. All Rights Reserved. from composer.models.resnet9_cifar10.model import CIFAR10_ResNet9 as",
"Reserved. from composer.models.resnet9_cifar10.model import CIFAR10_ResNet9 as CIFAR10_ResNet9 from composer.models.resnet9_cifar10.resnet9_cifar10_hparams import CIFARResNet9Hparams as CIFARResNet9Hparams",
"MosaicML. All Rights Reserved. from composer.models.resnet9_cifar10.model import CIFAR10_ResNet9 as CIFAR10_ResNet9 from composer.models.resnet9_cifar10.resnet9_cifar10_hparams import",
"_dataset = 'CIFAR10' _name = 'ResNet9' _quality = '92.9' _metric = 'Top-1 Accuracy'",
"as CIFARResNet9Hparams _task = 'Image Classification' _dataset = 'CIFAR10' _name = 'ResNet9' _quality",
"'ResNet9' _quality = '92.9' _metric = 'Top-1 Accuracy' _ttt = '5m' _hparams =",
"All Rights Reserved. from composer.models.resnet9_cifar10.model import CIFAR10_ResNet9 as CIFAR10_ResNet9 from composer.models.resnet9_cifar10.resnet9_cifar10_hparams import CIFARResNet9Hparams",
"composer.models.resnet9_cifar10.resnet9_cifar10_hparams import CIFARResNet9Hparams as CIFARResNet9Hparams _task = 'Image Classification' _dataset = 'CIFAR10' _name",
"import CIFAR10_ResNet9 as CIFAR10_ResNet9 from composer.models.resnet9_cifar10.resnet9_cifar10_hparams import CIFARResNet9Hparams as CIFARResNet9Hparams _task = 'Image",
"CIFARResNet9Hparams as CIFARResNet9Hparams _task = 'Image Classification' _dataset = 'CIFAR10' _name = 'ResNet9'",
"= 'CIFAR10' _name = 'ResNet9' _quality = '92.9' _metric = 'Top-1 Accuracy' _ttt",
"Copyright 2021 MosaicML. All Rights Reserved. from composer.models.resnet9_cifar10.model import CIFAR10_ResNet9 as CIFAR10_ResNet9 from",
"_quality = '92.9' _metric = 'Top-1 Accuracy' _ttt = '5m' _hparams = 'resnet9_cifar10.yaml'",
"2021 MosaicML. All Rights Reserved. from composer.models.resnet9_cifar10.model import CIFAR10_ResNet9 as CIFAR10_ResNet9 from composer.models.resnet9_cifar10.resnet9_cifar10_hparams",
"_task = 'Image Classification' _dataset = 'CIFAR10' _name = 'ResNet9' _quality = '92.9'",
"= 'Image Classification' _dataset = 'CIFAR10' _name = 'ResNet9' _quality = '92.9' _metric",
"= 'ResNet9' _quality = '92.9' _metric = 'Top-1 Accuracy' _ttt = '5m' _hparams",
"as CIFAR10_ResNet9 from composer.models.resnet9_cifar10.resnet9_cifar10_hparams import CIFARResNet9Hparams as CIFARResNet9Hparams _task = 'Image Classification' _dataset",
"'CIFAR10' _name = 'ResNet9' _quality = '92.9' _metric = 'Top-1 Accuracy' _ttt =",
"_name = 'ResNet9' _quality = '92.9' _metric = 'Top-1 Accuracy' _ttt = '5m'",
"CIFAR10_ResNet9 from composer.models.resnet9_cifar10.resnet9_cifar10_hparams import CIFARResNet9Hparams as CIFARResNet9Hparams _task = 'Image Classification' _dataset =",
"Rights Reserved. from composer.models.resnet9_cifar10.model import CIFAR10_ResNet9 as CIFAR10_ResNet9 from composer.models.resnet9_cifar10.resnet9_cifar10_hparams import CIFARResNet9Hparams as",
"'Image Classification' _dataset = 'CIFAR10' _name = 'ResNet9' _quality = '92.9' _metric =",
"from composer.models.resnet9_cifar10.model import CIFAR10_ResNet9 as CIFAR10_ResNet9 from composer.models.resnet9_cifar10.resnet9_cifar10_hparams import CIFARResNet9Hparams as CIFARResNet9Hparams _task",
"import CIFARResNet9Hparams as CIFARResNet9Hparams _task = 'Image Classification' _dataset = 'CIFAR10' _name =",
"Classification' _dataset = 'CIFAR10' _name = 'ResNet9' _quality = '92.9' _metric = 'Top-1",
"CIFAR10_ResNet9 as CIFAR10_ResNet9 from composer.models.resnet9_cifar10.resnet9_cifar10_hparams import CIFARResNet9Hparams as CIFARResNet9Hparams _task = 'Image Classification'",
"# Copyright 2021 MosaicML. All Rights Reserved. from composer.models.resnet9_cifar10.model import CIFAR10_ResNet9 as CIFAR10_ResNet9"
] |
[
"for SVC is written in comment below --# X_scaled = preprocessing.scale(X_train) Xtest_scaled =",
"list(df_movies.set_index('movieId').loc[pivot.index].title) movie_to_idx = dict(map(lambda t: (t[1],t[0]), enumerate(movie_list))) #dictionary idx_to_movie = dict((v, k) for",
"(idx, dist) in enumerate(tuple_dist_idx): df_avg = df_movies2[df_movies2['title'] == idx_to_movie[idx]] avgr = round(df_avg, 3)",
"train_test_split from sklearn.metrics import accuracy_score from sklearn.neighbors import KNeighborsClassifier def get_movie_idx_from_name(movie_title,movie_to_idx): for title,idx",
"X_scaled = preprocessing.scale(X_train) Xtest_scaled = preprocessing.scale(X_test) #svc_model = SVC() #svc_model.fit(X_scaled, y_train) #y_predicted =",
"i, (idx, dist) in enumerate(tuple_dist_idx): df_avg = df_movies2[df_movies2['title'] == idx_to_movie[idx]] avgr = round(df_avg,",
"x[1])[:0:-1] print('Recommendations for {} using a knn approach:'.format(movie_title)) for i, (idx, dist) in",
"= {'rating': 'rating_mean'}) df_rating_norm = pd.merge(df_rating_mean,df_ratings,on='movieId') df_rating_norm['rate_norm'] = df_rating_norm['rating']-df_rating_norm['rating_mean'] df_movies2 = df_rating_mean.merge(df_movies,on='movieId') #--",
"distance of {2} and average rating of {3}'.format(i+1, idx_to_movie[idx], dist, avgr['rating_mean'].iloc[0])) #--------------- machine",
"model KNN Classifier\") print(accuracy_score(y_test, y_predicted)) # 0.7298601699117384 gnb_model = GaussianNB() gnb_model.fit(X_train, y_train) y_predicted",
"y_predicted)) # 0.7298601699117384 gnb_model = GaussianNB() gnb_model.fit(X_train, y_train) y_predicted = gnb_model.predict(X_test) print(\"\\n ml",
"pd.DataFrame(df_ratings.groupby('movieId').size(), columns=['count']) df_plt = df_plt.sort_values('count',ascending=False) df_plt = df_plt.reset_index(drop=True) plt1 = df_plt.plot(figsize=(30,15),fontsize=15) plt1.set_xlabel(\"movieId\") plt1.set_ylabel(\"Number",
"KNN Classifier\") print(accuracy_score(y_test, y_predicted)) # 0.7298601699117384 gnb_model = GaussianNB() gnb_model.fit(X_train, y_train) y_predicted =",
"df_rating_norm['rate_norm'].values y_input = y_input.astype('int') X_train, X_test, y_train, y_test = train_test_split(X_input, y_input, test_size=0.3) #--",
"GaussianNB() gnb_model.fit(X_train, y_train) y_predicted = gnb_model.predict(X_test) print(\"\\n ml model Gaussian NB\") print(accuracy_score(y_test, y_predicted))",
"GaussianNB from sklearn.naive_bayes import MultinomialNB from sklearn import preprocessing from sklearn.model_selection import train_test_split",
"df_avg = df_movies2[df_movies2['title'] == idx_to_movie[idx]] avgr = round(df_avg, 3) print('{0}: {1}, with distance",
"reshape the data for indexing --# pivot = df_ratings.pivot(index='movieId',columns='userId', values = 'rating').fillna(0) csr_pivot",
"df_movierating = pd.merge(df_ratings, df_movies, on='movieId') df_plt = pd.DataFrame(df_ratings.groupby('movieId').size(), columns=['count']) df_plt = df_plt.sort_values('count',ascending=False) df_plt",
"in movie_to_idx.items()) # reverse dictionary idx = get_movie_idx_from_name(movie_title,movie_to_idx) # movie index #-- use",
"average rating of {3}'.format(i+1, idx_to_movie[idx], dist, avgr['rating_mean'].iloc[0])) #--------------- machine learning ---------------# X_input =",
"print(\"\\n ml model MultinomialNB\") print(accuracy_score(y_test, y_predicted)) # 0.044858021222438926 knnc_model = KNeighborsClassifier(n_neighbors=5) knnc_model.fit(X_train, y_train)",
"idx return None def main(): ratings_path = \"Data/ml-latest-small/ratings.csv\" movies_path = \"Data/ml-latest-small/movies.csv\" #change the",
"movies_path = \"Data/ml-latest-small/movies.csv\" #change the movie title to recommend a different movie movie_title",
"python # coding: utf-8 import sys import pandas as pd import numpy as",
"knn_model_recommender.fit(pivot) distances, indices = knn_model_recommender.kneighbors(csr_pivot[idx], n_neighbors=11) tuple_dist_idx = sorted(list(zip(indices.squeeze().tolist(), distances.squeeze().tolist())), key=lambda x: x[1])[:0:-1]",
"= False, sort = False).mean() df_rating_mean = df_rating_mean.drop(columns=['userId']) df_rating_mean = df_rating_mean.rename(columns = {'rating':",
"import train_test_split from sklearn.metrics import accuracy_score from sklearn.neighbors import KNeighborsClassifier def get_movie_idx_from_name(movie_title,movie_to_idx): for",
"== movie_title: return idx return None def main(): ratings_path = \"Data/ml-latest-small/ratings.csv\" movies_path =",
"too long to run, accuracy score for SVC is written in comment below",
"df_movies = pd.read_csv(movies_path,usecols=['movieId','title']) df_ratings = pd.read_csv(ratings_path,usecols=['userId','movieId','rating']) df_movierating = pd.merge(df_ratings, df_movies, on='movieId') df_plt =",
"---------------# df_rating_mean = df_ratings.groupby(['movieId'],as_index = False, sort = False).mean() df_rating_mean = df_rating_mean.drop(columns=['userId']) df_rating_mean",
"with distance of {2} and average rating of {3}'.format(i+1, idx_to_movie[idx], dist, avgr['rating_mean'].iloc[0])) #---------------",
"recommender system ---------------# df_rating_mean = df_ratings.groupby(['movieId'],as_index = False, sort = False).mean() df_rating_mean =",
"indices = knn_model_recommender.kneighbors(csr_pivot[idx], n_neighbors=11) tuple_dist_idx = sorted(list(zip(indices.squeeze().tolist(), distances.squeeze().tolist())), key=lambda x: x[1])[:0:-1] print('Recommendations for",
"MultinomialNB\") print(accuracy_score(y_test, y_predicted)) # 0.044858021222438926 knnc_model = KNeighborsClassifier(n_neighbors=5) knnc_model.fit(X_train, y_train) y_predicted = knnc_model.predict(X_test)",
"written in comment below --# X_scaled = preprocessing.scale(X_train) Xtest_scaled = preprocessing.scale(X_test) #svc_model =",
"movie_title = \"Thor (2011)\" df_movies = pd.read_csv(movies_path,usecols=['movieId','title']) df_ratings = pd.read_csv(ratings_path,usecols=['userId','movieId','rating']) df_movierating = pd.merge(df_ratings,",
"= KNeighborsClassifier(n_neighbors=5) knnc_model.fit(X_train, y_train) y_predicted = knnc_model.predict(X_test) print(\"\\n ml model KNN Classifier\") print(accuracy_score(y_test,",
"k) for k, v in movie_to_idx.items()) # reverse dictionary idx = get_movie_idx_from_name(movie_title,movie_to_idx) #",
"use machine learning (knn) to get closest movies to recommend --# knn_model_recommender =",
"for title,idx in movie_to_idx.items(): if title == movie_title: return idx return None def",
"df_rating_mean.rename(columns = {'rating': 'rating_mean'}) df_rating_norm = pd.merge(df_rating_mean,df_ratings,on='movieId') df_rating_norm['rate_norm'] = df_rating_norm['rating']-df_rating_norm['rating_mean'] df_movies2 = df_rating_mean.merge(df_movies,on='movieId')",
"= \"Data/ml-latest-small/ratings.csv\" movies_path = \"Data/ml-latest-small/movies.csv\" #change the movie title to recommend a different",
"model SVC\") #print(accuracy_score(y_test, y_predicted)) # 0.760760046015312 bayes_model = MultinomialNB() bayes_model.fit(X_train, y_train) y_predicted =",
"sorted(list(zip(indices.squeeze().tolist(), distances.squeeze().tolist())), key=lambda x: x[1])[:0:-1] print('Recommendations for {} using a knn approach:'.format(movie_title)) for",
"to recommend a different movie movie_title = \"Thor (2011)\" df_movies = pd.read_csv(movies_path,usecols=['movieId','title']) df_ratings",
"pivot = df_ratings.pivot(index='movieId',columns='userId', values = 'rating').fillna(0) csr_pivot = csr_matrix(pivot.values) movie_list = list(df_movies.set_index('movieId').loc[pivot.index].title) movie_to_idx",
"sklearn.naive_bayes import GaussianNB from sklearn.naive_bayes import MultinomialNB from sklearn import preprocessing from sklearn.model_selection",
"= NearestNeighbors(metric='cosine',algorithm='brute',n_neighbors=20,n_jobs=-1) knn_model_recommender.fit(pivot) distances, indices = knn_model_recommender.kneighbors(csr_pivot[idx], n_neighbors=11) tuple_dist_idx = sorted(list(zip(indices.squeeze().tolist(), distances.squeeze().tolist())), key=lambda",
"k, v in movie_to_idx.items()) # reverse dictionary idx = get_movie_idx_from_name(movie_title,movie_to_idx) # movie index",
"model MultinomialNB\") print(accuracy_score(y_test, y_predicted)) # 0.044858021222438926 knnc_model = KNeighborsClassifier(n_neighbors=5) knnc_model.fit(X_train, y_train) y_predicted =",
"y_train) y_predicted = knnc_model.predict(X_test) print(\"\\n ml model KNN Classifier\") print(accuracy_score(y_test, y_predicted)) # 0.7298601699117384",
"dict(map(lambda t: (t[1],t[0]), enumerate(movie_list))) #dictionary idx_to_movie = dict((v, k) for k, v in",
"pd.read_csv(movies_path,usecols=['movieId','title']) df_ratings = pd.read_csv(ratings_path,usecols=['userId','movieId','rating']) df_movierating = pd.merge(df_ratings, df_movies, on='movieId') df_plt = pd.DataFrame(df_ratings.groupby('movieId').size(), columns=['count'])",
"from sklearn.naive_bayes import GaussianNB from sklearn.naive_bayes import MultinomialNB from sklearn import preprocessing from",
"per Movie\") plt1 = plt1.get_figure() plt1.savefig('plot/ratingfq',bbox_inches='tight') #--------------- item based recommender system ---------------# df_rating_mean",
"df_ratings = pd.read_csv(ratings_path,usecols=['userId','movieId','rating']) df_movierating = pd.merge(df_ratings, df_movies, on='movieId') df_plt = pd.DataFrame(df_ratings.groupby('movieId').size(), columns=['count']) df_plt",
"return None def main(): ratings_path = \"Data/ml-latest-small/ratings.csv\" movies_path = \"Data/ml-latest-small/movies.csv\" #change the movie",
"movie title to recommend a different movie movie_title = \"Thor (2011)\" df_movies =",
"(2011)\" df_movies = pd.read_csv(movies_path,usecols=['movieId','title']) df_ratings = pd.read_csv(ratings_path,usecols=['userId','movieId','rating']) df_movierating = pd.merge(df_ratings, df_movies, on='movieId') df_plt",
"gnb_model = GaussianNB() gnb_model.fit(X_train, y_train) y_predicted = gnb_model.predict(X_test) print(\"\\n ml model Gaussian NB\")",
"in comment below --# X_scaled = preprocessing.scale(X_train) Xtest_scaled = preprocessing.scale(X_test) #svc_model = SVC()",
"# 0.7298601699117384 gnb_model = GaussianNB() gnb_model.fit(X_train, y_train) y_predicted = gnb_model.predict(X_test) print(\"\\n ml model",
"y_train) y_predicted = bayes_model.predict(X_test) print(\"\\n ml model MultinomialNB\") print(accuracy_score(y_test, y_predicted)) # 0.044858021222438926 knnc_model",
"y_input = y_input.astype('int') X_train, X_test, y_train, y_test = train_test_split(X_input, y_input, test_size=0.3) #-- commenting",
"from sklearn import preprocessing from sklearn.model_selection import train_test_split from sklearn.metrics import accuracy_score from",
"df_rating_norm['rate_norm'] = df_rating_norm['rating']-df_rating_norm['rating_mean'] df_movies2 = df_rating_mean.merge(df_movies,on='movieId') #-- reshape the data for indexing --#",
"dict((v, k) for k, v in movie_to_idx.items()) # reverse dictionary idx = get_movie_idx_from_name(movie_title,movie_to_idx)",
"= dict(map(lambda t: (t[1],t[0]), enumerate(movie_list))) #dictionary idx_to_movie = dict((v, k) for k, v",
"plt1.set_xlabel(\"movieId\") plt1.set_ylabel(\"Number of ratings\") plt1.set_title(\"Number of Ratings per Movie\") plt1 = plt1.get_figure() plt1.savefig('plot/ratingfq',bbox_inches='tight')",
"return idx return None def main(): ratings_path = \"Data/ml-latest-small/ratings.csv\" movies_path = \"Data/ml-latest-small/movies.csv\" #change",
"movie movie_title = \"Thor (2011)\" df_movies = pd.read_csv(movies_path,usecols=['movieId','title']) df_ratings = pd.read_csv(ratings_path,usecols=['userId','movieId','rating']) df_movierating =",
"{'rating': 'rating_mean'}) df_rating_norm = pd.merge(df_rating_mean,df_ratings,on='movieId') df_rating_norm['rate_norm'] = df_rating_norm['rating']-df_rating_norm['rating_mean'] df_movies2 = df_rating_mean.merge(df_movies,on='movieId') #-- reshape",
"is written in comment below --# X_scaled = preprocessing.scale(X_train) Xtest_scaled = preprocessing.scale(X_test) #svc_model",
"#-- use machine learning (knn) to get closest movies to recommend --# knn_model_recommender",
"as np import matplotlib.pyplot as plt from scipy.sparse import csr_matrix from sklearn.neighbors import",
"key=lambda x: x[1])[:0:-1] print('Recommendations for {} using a knn approach:'.format(movie_title)) for i, (idx,",
"SVC is written in comment below --# X_scaled = preprocessing.scale(X_train) Xtest_scaled = preprocessing.scale(X_test)",
"y_input, test_size=0.3) #-- commenting out SVC because it takes too long to run,",
"knnc_model.predict(X_test) print(\"\\n ml model KNN Classifier\") print(accuracy_score(y_test, y_predicted)) # 0.7298601699117384 gnb_model = GaussianNB()",
"indexing --# pivot = df_ratings.pivot(index='movieId',columns='userId', values = 'rating').fillna(0) csr_pivot = csr_matrix(pivot.values) movie_list =",
"pd.read_csv(ratings_path,usecols=['userId','movieId','rating']) df_movierating = pd.merge(df_ratings, df_movies, on='movieId') df_plt = pd.DataFrame(df_ratings.groupby('movieId').size(), columns=['count']) df_plt = df_plt.sort_values('count',ascending=False)",
"df_plt = pd.DataFrame(df_ratings.groupby('movieId').size(), columns=['count']) df_plt = df_plt.sort_values('count',ascending=False) df_plt = df_plt.reset_index(drop=True) plt1 = df_plt.plot(figsize=(30,15),fontsize=15)",
"print(accuracy_score(y_test, y_predicted)) # 0.7298601699117384 gnb_model = GaussianNB() gnb_model.fit(X_train, y_train) y_predicted = gnb_model.predict(X_test) print(\"\\n",
"tuple_dist_idx = sorted(list(zip(indices.squeeze().tolist(), distances.squeeze().tolist())), key=lambda x: x[1])[:0:-1] print('Recommendations for {} using a knn",
"df_plt = df_plt.sort_values('count',ascending=False) df_plt = df_plt.reset_index(drop=True) plt1 = df_plt.plot(figsize=(30,15),fontsize=15) plt1.set_xlabel(\"movieId\") plt1.set_ylabel(\"Number of ratings\")",
"df_ratings.groupby(['movieId'],as_index = False, sort = False).mean() df_rating_mean = df_rating_mean.drop(columns=['userId']) df_rating_mean = df_rating_mean.rename(columns =",
"y_input = df_rating_norm['rate_norm'].values y_input = y_input.astype('int') X_train, X_test, y_train, y_test = train_test_split(X_input, y_input,",
"KNeighborsClassifier def get_movie_idx_from_name(movie_title,movie_to_idx): for title,idx in movie_to_idx.items(): if title == movie_title: return idx",
"= 'rating').fillna(0) csr_pivot = csr_matrix(pivot.values) movie_list = list(df_movies.set_index('movieId').loc[pivot.index].title) movie_to_idx = dict(map(lambda t: (t[1],t[0]),",
"idx = get_movie_idx_from_name(movie_title,movie_to_idx) # movie index #-- use machine learning (knn) to get",
"def get_movie_idx_from_name(movie_title,movie_to_idx): for title,idx in movie_to_idx.items(): if title == movie_title: return idx return",
"bayes_model.predict(X_test) print(\"\\n ml model MultinomialNB\") print(accuracy_score(y_test, y_predicted)) # 0.044858021222438926 knnc_model = KNeighborsClassifier(n_neighbors=5) knnc_model.fit(X_train,",
"== idx_to_movie[idx]] avgr = round(df_avg, 3) print('{0}: {1}, with distance of {2} and",
"pd.merge(df_rating_mean,df_ratings,on='movieId') df_rating_norm['rate_norm'] = df_rating_norm['rating']-df_rating_norm['rating_mean'] df_movies2 = df_rating_mean.merge(df_movies,on='movieId') #-- reshape the data for indexing",
"#svc_model.fit(X_scaled, y_train) #y_predicted = svc_model.predict(Xtest_scaled) #print(\"\\nml model SVC\") #print(accuracy_score(y_test, y_predicted)) # 0.760760046015312 bayes_model",
"a knn approach:'.format(movie_title)) for i, (idx, dist) in enumerate(tuple_dist_idx): df_avg = df_movies2[df_movies2['title'] ==",
"\"Data/ml-latest-small/movies.csv\" #change the movie title to recommend a different movie movie_title = \"Thor",
"#-- reshape the data for indexing --# pivot = df_ratings.pivot(index='movieId',columns='userId', values = 'rating').fillna(0)",
"ml model Gaussian NB\") print(accuracy_score(y_test, y_predicted)) # 0.7639416878780867 if __name__ == '__main__': main()",
"preprocessing.scale(X_test) #svc_model = SVC() #svc_model.fit(X_scaled, y_train) #y_predicted = svc_model.predict(Xtest_scaled) #print(\"\\nml model SVC\") #print(accuracy_score(y_test,",
"import KNeighborsClassifier def get_movie_idx_from_name(movie_title,movie_to_idx): for title,idx in movie_to_idx.items(): if title == movie_title: return",
"sklearn.model_selection import train_test_split from sklearn.metrics import accuracy_score from sklearn.neighbors import KNeighborsClassifier def get_movie_idx_from_name(movie_title,movie_to_idx):",
"df_rating_norm = pd.merge(df_rating_mean,df_ratings,on='movieId') df_rating_norm['rate_norm'] = df_rating_norm['rating']-df_rating_norm['rating_mean'] df_movies2 = df_rating_mean.merge(df_movies,on='movieId') #-- reshape the data",
"df_movies, on='movieId') df_plt = pd.DataFrame(df_ratings.groupby('movieId').size(), columns=['count']) df_plt = df_plt.sort_values('count',ascending=False) df_plt = df_plt.reset_index(drop=True) plt1",
"title,idx in movie_to_idx.items(): if title == movie_title: return idx return None def main():",
"enumerate(movie_list))) #dictionary idx_to_movie = dict((v, k) for k, v in movie_to_idx.items()) # reverse",
"recommend --# knn_model_recommender = NearestNeighbors(metric='cosine',algorithm='brute',n_neighbors=20,n_jobs=-1) knn_model_recommender.fit(pivot) distances, indices = knn_model_recommender.kneighbors(csr_pivot[idx], n_neighbors=11) tuple_dist_idx =",
"y_train) y_predicted = gnb_model.predict(X_test) print(\"\\n ml model Gaussian NB\") print(accuracy_score(y_test, y_predicted)) # 0.7639416878780867",
"to run, accuracy score for SVC is written in comment below --# X_scaled",
"y_predicted = gnb_model.predict(X_test) print(\"\\n ml model Gaussian NB\") print(accuracy_score(y_test, y_predicted)) # 0.7639416878780867 if",
"bayes_model.fit(X_train, y_train) y_predicted = bayes_model.predict(X_test) print(\"\\n ml model MultinomialNB\") print(accuracy_score(y_test, y_predicted)) # 0.044858021222438926",
"plt1.set_title(\"Number of Ratings per Movie\") plt1 = plt1.get_figure() plt1.savefig('plot/ratingfq',bbox_inches='tight') #--------------- item based recommender",
"a different movie movie_title = \"Thor (2011)\" df_movies = pd.read_csv(movies_path,usecols=['movieId','title']) df_ratings = pd.read_csv(ratings_path,usecols=['userId','movieId','rating'])",
"= \"Data/ml-latest-small/movies.csv\" #change the movie title to recommend a different movie movie_title =",
"idx_to_movie[idx]] avgr = round(df_avg, 3) print('{0}: {1}, with distance of {2} and average",
"preprocessing.scale(X_train) Xtest_scaled = preprocessing.scale(X_test) #svc_model = SVC() #svc_model.fit(X_scaled, y_train) #y_predicted = svc_model.predict(Xtest_scaled) #print(\"\\nml",
"#y_predicted = svc_model.predict(Xtest_scaled) #print(\"\\nml model SVC\") #print(accuracy_score(y_test, y_predicted)) # 0.760760046015312 bayes_model = MultinomialNB()",
"the movie title to recommend a different movie movie_title = \"Thor (2011)\" df_movies",
"import accuracy_score from sklearn.neighbors import KNeighborsClassifier def get_movie_idx_from_name(movie_title,movie_to_idx): for title,idx in movie_to_idx.items(): if",
"= df_rating_mean.drop(columns=['userId']) df_rating_mean = df_rating_mean.rename(columns = {'rating': 'rating_mean'}) df_rating_norm = pd.merge(df_rating_mean,df_ratings,on='movieId') df_rating_norm['rate_norm'] =",
"Movie\") plt1 = plt1.get_figure() plt1.savefig('plot/ratingfq',bbox_inches='tight') #--------------- item based recommender system ---------------# df_rating_mean =",
"distances, indices = knn_model_recommender.kneighbors(csr_pivot[idx], n_neighbors=11) tuple_dist_idx = sorted(list(zip(indices.squeeze().tolist(), distances.squeeze().tolist())), key=lambda x: x[1])[:0:-1] print('Recommendations",
"dist) in enumerate(tuple_dist_idx): df_avg = df_movies2[df_movies2['title'] == idx_to_movie[idx]] avgr = round(df_avg, 3) print('{0}:",
"of ratings\") plt1.set_title(\"Number of Ratings per Movie\") plt1 = plt1.get_figure() plt1.savefig('plot/ratingfq',bbox_inches='tight') #--------------- item",
"import numpy as np import matplotlib.pyplot as plt from scipy.sparse import csr_matrix from",
"for {} using a knn approach:'.format(movie_title)) for i, (idx, dist) in enumerate(tuple_dist_idx): df_avg",
"\"Data/ml-latest-small/ratings.csv\" movies_path = \"Data/ml-latest-small/movies.csv\" #change the movie title to recommend a different movie",
"from scipy.sparse import csr_matrix from sklearn.neighbors import NearestNeighbors from sklearn.svm import SVC from",
"SVC\") #print(accuracy_score(y_test, y_predicted)) # 0.760760046015312 bayes_model = MultinomialNB() bayes_model.fit(X_train, y_train) y_predicted = bayes_model.predict(X_test)",
"# coding: utf-8 import sys import pandas as pd import numpy as np",
"= csr_matrix(pivot.values) movie_list = list(df_movies.set_index('movieId').loc[pivot.index].title) movie_to_idx = dict(map(lambda t: (t[1],t[0]), enumerate(movie_list))) #dictionary idx_to_movie",
"= df_plt.reset_index(drop=True) plt1 = df_plt.plot(figsize=(30,15),fontsize=15) plt1.set_xlabel(\"movieId\") plt1.set_ylabel(\"Number of ratings\") plt1.set_title(\"Number of Ratings per",
"0.760760046015312 bayes_model = MultinomialNB() bayes_model.fit(X_train, y_train) y_predicted = bayes_model.predict(X_test) print(\"\\n ml model MultinomialNB\")",
"NearestNeighbors(metric='cosine',algorithm='brute',n_neighbors=20,n_jobs=-1) knn_model_recommender.fit(pivot) distances, indices = knn_model_recommender.kneighbors(csr_pivot[idx], n_neighbors=11) tuple_dist_idx = sorted(list(zip(indices.squeeze().tolist(), distances.squeeze().tolist())), key=lambda x:",
"#svc_model = SVC() #svc_model.fit(X_scaled, y_train) #y_predicted = svc_model.predict(Xtest_scaled) #print(\"\\nml model SVC\") #print(accuracy_score(y_test, y_predicted))",
"plt1.set_ylabel(\"Number of ratings\") plt1.set_title(\"Number of Ratings per Movie\") plt1 = plt1.get_figure() plt1.savefig('plot/ratingfq',bbox_inches='tight') #---------------",
"MultinomialNB from sklearn import preprocessing from sklearn.model_selection import train_test_split from sklearn.metrics import accuracy_score",
"movie_to_idx.items(): if title == movie_title: return idx return None def main(): ratings_path =",
"sklearn.neighbors import KNeighborsClassifier def get_movie_idx_from_name(movie_title,movie_to_idx): for title,idx in movie_to_idx.items(): if title == movie_title:",
"print(\"\\n ml model Gaussian NB\") print(accuracy_score(y_test, y_predicted)) # 0.7639416878780867 if __name__ == '__main__':",
"---------------# X_input = df_rating_norm[['movieId','userId']].values y_input = df_rating_norm['rate_norm'].values y_input = y_input.astype('int') X_train, X_test, y_train,",
"sort = False).mean() df_rating_mean = df_rating_mean.drop(columns=['userId']) df_rating_mean = df_rating_mean.rename(columns = {'rating': 'rating_mean'}) df_rating_norm",
"(knn) to get closest movies to recommend --# knn_model_recommender = NearestNeighbors(metric='cosine',algorithm='brute',n_neighbors=20,n_jobs=-1) knn_model_recommender.fit(pivot) distances,",
"NearestNeighbors from sklearn.svm import SVC from sklearn.naive_bayes import GaussianNB from sklearn.naive_bayes import MultinomialNB",
"{} using a knn approach:'.format(movie_title)) for i, (idx, dist) in enumerate(tuple_dist_idx): df_avg =",
"sklearn.svm import SVC from sklearn.naive_bayes import GaussianNB from sklearn.naive_bayes import MultinomialNB from sklearn",
"to recommend --# knn_model_recommender = NearestNeighbors(metric='cosine',algorithm='brute',n_neighbors=20,n_jobs=-1) knn_model_recommender.fit(pivot) distances, indices = knn_model_recommender.kneighbors(csr_pivot[idx], n_neighbors=11) tuple_dist_idx",
"{1}, with distance of {2} and average rating of {3}'.format(i+1, idx_to_movie[idx], dist, avgr['rating_mean'].iloc[0]))",
"\"Thor (2011)\" df_movies = pd.read_csv(movies_path,usecols=['movieId','title']) df_ratings = pd.read_csv(ratings_path,usecols=['userId','movieId','rating']) df_movierating = pd.merge(df_ratings, df_movies, on='movieId')",
"= False).mean() df_rating_mean = df_rating_mean.drop(columns=['userId']) df_rating_mean = df_rating_mean.rename(columns = {'rating': 'rating_mean'}) df_rating_norm =",
"False, sort = False).mean() df_rating_mean = df_rating_mean.drop(columns=['userId']) df_rating_mean = df_rating_mean.rename(columns = {'rating': 'rating_mean'})",
"train_test_split(X_input, y_input, test_size=0.3) #-- commenting out SVC because it takes too long to",
"idx_to_movie = dict((v, k) for k, v in movie_to_idx.items()) # reverse dictionary idx",
"machine learning ---------------# X_input = df_rating_norm[['movieId','userId']].values y_input = df_rating_norm['rate_norm'].values y_input = y_input.astype('int') X_train,",
"0.7298601699117384 gnb_model = GaussianNB() gnb_model.fit(X_train, y_train) y_predicted = gnb_model.predict(X_test) print(\"\\n ml model Gaussian",
"sklearn import preprocessing from sklearn.model_selection import train_test_split from sklearn.metrics import accuracy_score from sklearn.neighbors",
"long to run, accuracy score for SVC is written in comment below --#",
"= pd.merge(df_ratings, df_movies, on='movieId') df_plt = pd.DataFrame(df_ratings.groupby('movieId').size(), columns=['count']) df_plt = df_plt.sort_values('count',ascending=False) df_plt =",
"takes too long to run, accuracy score for SVC is written in comment",
"as plt from scipy.sparse import csr_matrix from sklearn.neighbors import NearestNeighbors from sklearn.svm import",
"ml model KNN Classifier\") print(accuracy_score(y_test, y_predicted)) # 0.7298601699117384 gnb_model = GaussianNB() gnb_model.fit(X_train, y_train)",
"ml model MultinomialNB\") print(accuracy_score(y_test, y_predicted)) # 0.044858021222438926 knnc_model = KNeighborsClassifier(n_neighbors=5) knnc_model.fit(X_train, y_train) y_predicted",
"for indexing --# pivot = df_ratings.pivot(index='movieId',columns='userId', values = 'rating').fillna(0) csr_pivot = csr_matrix(pivot.values) movie_list",
"Classifier\") print(accuracy_score(y_test, y_predicted)) # 0.7298601699117384 gnb_model = GaussianNB() gnb_model.fit(X_train, y_train) y_predicted = gnb_model.predict(X_test)",
"<gh_stars>0 #!/usr/bin/env python # coding: utf-8 import sys import pandas as pd import",
"sklearn.naive_bayes import MultinomialNB from sklearn import preprocessing from sklearn.model_selection import train_test_split from sklearn.metrics",
"= df_ratings.pivot(index='movieId',columns='userId', values = 'rating').fillna(0) csr_pivot = csr_matrix(pivot.values) movie_list = list(df_movies.set_index('movieId').loc[pivot.index].title) movie_to_idx =",
"df_rating_mean.drop(columns=['userId']) df_rating_mean = df_rating_mean.rename(columns = {'rating': 'rating_mean'}) df_rating_norm = pd.merge(df_rating_mean,df_ratings,on='movieId') df_rating_norm['rate_norm'] = df_rating_norm['rating']-df_rating_norm['rating_mean']",
"= plt1.get_figure() plt1.savefig('plot/ratingfq',bbox_inches='tight') #--------------- item based recommender system ---------------# df_rating_mean = df_ratings.groupby(['movieId'],as_index =",
"print(accuracy_score(y_test, y_predicted)) # 0.044858021222438926 knnc_model = KNeighborsClassifier(n_neighbors=5) knnc_model.fit(X_train, y_train) y_predicted = knnc_model.predict(X_test) print(\"\\n",
"using a knn approach:'.format(movie_title)) for i, (idx, dist) in enumerate(tuple_dist_idx): df_avg = df_movies2[df_movies2['title']",
"on='movieId') df_plt = pd.DataFrame(df_ratings.groupby('movieId').size(), columns=['count']) df_plt = df_plt.sort_values('count',ascending=False) df_plt = df_plt.reset_index(drop=True) plt1 =",
"= dict((v, k) for k, v in movie_to_idx.items()) # reverse dictionary idx =",
"= list(df_movies.set_index('movieId').loc[pivot.index].title) movie_to_idx = dict(map(lambda t: (t[1],t[0]), enumerate(movie_list))) #dictionary idx_to_movie = dict((v, k)",
"avgr['rating_mean'].iloc[0])) #--------------- machine learning ---------------# X_input = df_rating_norm[['movieId','userId']].values y_input = df_rating_norm['rate_norm'].values y_input =",
"{2} and average rating of {3}'.format(i+1, idx_to_movie[idx], dist, avgr['rating_mean'].iloc[0])) #--------------- machine learning ---------------#",
"get closest movies to recommend --# knn_model_recommender = NearestNeighbors(metric='cosine',algorithm='brute',n_neighbors=20,n_jobs=-1) knn_model_recommender.fit(pivot) distances, indices =",
"plt1 = df_plt.plot(figsize=(30,15),fontsize=15) plt1.set_xlabel(\"movieId\") plt1.set_ylabel(\"Number of ratings\") plt1.set_title(\"Number of Ratings per Movie\") plt1",
"different movie movie_title = \"Thor (2011)\" df_movies = pd.read_csv(movies_path,usecols=['movieId','title']) df_ratings = pd.read_csv(ratings_path,usecols=['userId','movieId','rating']) df_movierating",
"knn approach:'.format(movie_title)) for i, (idx, dist) in enumerate(tuple_dist_idx): df_avg = df_movies2[df_movies2['title'] == idx_to_movie[idx]]",
"from sklearn.model_selection import train_test_split from sklearn.metrics import accuracy_score from sklearn.neighbors import KNeighborsClassifier def",
"= df_plt.sort_values('count',ascending=False) df_plt = df_plt.reset_index(drop=True) plt1 = df_plt.plot(figsize=(30,15),fontsize=15) plt1.set_xlabel(\"movieId\") plt1.set_ylabel(\"Number of ratings\") plt1.set_title(\"Number",
"def main(): ratings_path = \"Data/ml-latest-small/ratings.csv\" movies_path = \"Data/ml-latest-small/movies.csv\" #change the movie title to",
"= df_plt.plot(figsize=(30,15),fontsize=15) plt1.set_xlabel(\"movieId\") plt1.set_ylabel(\"Number of ratings\") plt1.set_title(\"Number of Ratings per Movie\") plt1 =",
"import pandas as pd import numpy as np import matplotlib.pyplot as plt from",
"= df_rating_mean.merge(df_movies,on='movieId') #-- reshape the data for indexing --# pivot = df_ratings.pivot(index='movieId',columns='userId', values",
"learning (knn) to get closest movies to recommend --# knn_model_recommender = NearestNeighbors(metric='cosine',algorithm='brute',n_neighbors=20,n_jobs=-1) knn_model_recommender.fit(pivot)",
"coding: utf-8 import sys import pandas as pd import numpy as np import",
"df_rating_mean = df_rating_mean.rename(columns = {'rating': 'rating_mean'}) df_rating_norm = pd.merge(df_rating_mean,df_ratings,on='movieId') df_rating_norm['rate_norm'] = df_rating_norm['rating']-df_rating_norm['rating_mean'] df_movies2",
"None def main(): ratings_path = \"Data/ml-latest-small/ratings.csv\" movies_path = \"Data/ml-latest-small/movies.csv\" #change the movie title",
"values = 'rating').fillna(0) csr_pivot = csr_matrix(pivot.values) movie_list = list(df_movies.set_index('movieId').loc[pivot.index].title) movie_to_idx = dict(map(lambda t:",
"= preprocessing.scale(X_train) Xtest_scaled = preprocessing.scale(X_test) #svc_model = SVC() #svc_model.fit(X_scaled, y_train) #y_predicted = svc_model.predict(Xtest_scaled)",
"machine learning (knn) to get closest movies to recommend --# knn_model_recommender = NearestNeighbors(metric='cosine',algorithm='brute',n_neighbors=20,n_jobs=-1)",
"y_predicted)) # 0.044858021222438926 knnc_model = KNeighborsClassifier(n_neighbors=5) knnc_model.fit(X_train, y_train) y_predicted = knnc_model.predict(X_test) print(\"\\n ml",
"import matplotlib.pyplot as plt from scipy.sparse import csr_matrix from sklearn.neighbors import NearestNeighbors from",
"for k, v in movie_to_idx.items()) # reverse dictionary idx = get_movie_idx_from_name(movie_title,movie_to_idx) # movie",
"from sklearn.neighbors import NearestNeighbors from sklearn.svm import SVC from sklearn.naive_bayes import GaussianNB from",
"= df_movies2[df_movies2['title'] == idx_to_movie[idx]] avgr = round(df_avg, 3) print('{0}: {1}, with distance of",
"of {2} and average rating of {3}'.format(i+1, idx_to_movie[idx], dist, avgr['rating_mean'].iloc[0])) #--------------- machine learning",
"movies to recommend --# knn_model_recommender = NearestNeighbors(metric='cosine',algorithm='brute',n_neighbors=20,n_jobs=-1) knn_model_recommender.fit(pivot) distances, indices = knn_model_recommender.kneighbors(csr_pivot[idx], n_neighbors=11)",
"from sklearn.naive_bayes import MultinomialNB from sklearn import preprocessing from sklearn.model_selection import train_test_split from",
"based recommender system ---------------# df_rating_mean = df_ratings.groupby(['movieId'],as_index = False, sort = False).mean() df_rating_mean",
"X_input = df_rating_norm[['movieId','userId']].values y_input = df_rating_norm['rate_norm'].values y_input = y_input.astype('int') X_train, X_test, y_train, y_test",
"movie_list = list(df_movies.set_index('movieId').loc[pivot.index].title) movie_to_idx = dict(map(lambda t: (t[1],t[0]), enumerate(movie_list))) #dictionary idx_to_movie = dict((v,",
"#-- commenting out SVC because it takes too long to run, accuracy score",
"comment below --# X_scaled = preprocessing.scale(X_train) Xtest_scaled = preprocessing.scale(X_test) #svc_model = SVC() #svc_model.fit(X_scaled,",
"import csr_matrix from sklearn.neighbors import NearestNeighbors from sklearn.svm import SVC from sklearn.naive_bayes import",
"# 0.044858021222438926 knnc_model = KNeighborsClassifier(n_neighbors=5) knnc_model.fit(X_train, y_train) y_predicted = knnc_model.predict(X_test) print(\"\\n ml model",
"import preprocessing from sklearn.model_selection import train_test_split from sklearn.metrics import accuracy_score from sklearn.neighbors import",
"y_predicted)) # 0.760760046015312 bayes_model = MultinomialNB() bayes_model.fit(X_train, y_train) y_predicted = bayes_model.predict(X_test) print(\"\\n ml",
"enumerate(tuple_dist_idx): df_avg = df_movies2[df_movies2['title'] == idx_to_movie[idx]] avgr = round(df_avg, 3) print('{0}: {1}, with",
"print('{0}: {1}, with distance of {2} and average rating of {3}'.format(i+1, idx_to_movie[idx], dist,",
"for i, (idx, dist) in enumerate(tuple_dist_idx): df_avg = df_movies2[df_movies2['title'] == idx_to_movie[idx]] avgr =",
"Ratings per Movie\") plt1 = plt1.get_figure() plt1.savefig('plot/ratingfq',bbox_inches='tight') #--------------- item based recommender system ---------------#",
"X_test, y_train, y_test = train_test_split(X_input, y_input, test_size=0.3) #-- commenting out SVC because it",
"= SVC() #svc_model.fit(X_scaled, y_train) #y_predicted = svc_model.predict(Xtest_scaled) #print(\"\\nml model SVC\") #print(accuracy_score(y_test, y_predicted)) #",
"x: x[1])[:0:-1] print('Recommendations for {} using a knn approach:'.format(movie_title)) for i, (idx, dist)",
"False).mean() df_rating_mean = df_rating_mean.drop(columns=['userId']) df_rating_mean = df_rating_mean.rename(columns = {'rating': 'rating_mean'}) df_rating_norm = pd.merge(df_rating_mean,df_ratings,on='movieId')",
"= y_input.astype('int') X_train, X_test, y_train, y_test = train_test_split(X_input, y_input, test_size=0.3) #-- commenting out",
"# 0.760760046015312 bayes_model = MultinomialNB() bayes_model.fit(X_train, y_train) y_predicted = bayes_model.predict(X_test) print(\"\\n ml model",
"print('Recommendations for {} using a knn approach:'.format(movie_title)) for i, (idx, dist) in enumerate(tuple_dist_idx):",
"distances.squeeze().tolist())), key=lambda x: x[1])[:0:-1] print('Recommendations for {} using a knn approach:'.format(movie_title)) for i,",
"MultinomialNB() bayes_model.fit(X_train, y_train) y_predicted = bayes_model.predict(X_test) print(\"\\n ml model MultinomialNB\") print(accuracy_score(y_test, y_predicted)) #",
"idx_to_movie[idx], dist, avgr['rating_mean'].iloc[0])) #--------------- machine learning ---------------# X_input = df_rating_norm[['movieId','userId']].values y_input = df_rating_norm['rate_norm'].values",
"= gnb_model.predict(X_test) print(\"\\n ml model Gaussian NB\") print(accuracy_score(y_test, y_predicted)) # 0.7639416878780867 if __name__",
"df_movies2[df_movies2['title'] == idx_to_movie[idx]] avgr = round(df_avg, 3) print('{0}: {1}, with distance of {2}",
"y_train, y_test = train_test_split(X_input, y_input, test_size=0.3) #-- commenting out SVC because it takes",
"csr_pivot = csr_matrix(pivot.values) movie_list = list(df_movies.set_index('movieId').loc[pivot.index].title) movie_to_idx = dict(map(lambda t: (t[1],t[0]), enumerate(movie_list))) #dictionary",
"--# X_scaled = preprocessing.scale(X_train) Xtest_scaled = preprocessing.scale(X_test) #svc_model = SVC() #svc_model.fit(X_scaled, y_train) #y_predicted",
"df_plt.plot(figsize=(30,15),fontsize=15) plt1.set_xlabel(\"movieId\") plt1.set_ylabel(\"Number of ratings\") plt1.set_title(\"Number of Ratings per Movie\") plt1 = plt1.get_figure()",
"= knnc_model.predict(X_test) print(\"\\n ml model KNN Classifier\") print(accuracy_score(y_test, y_predicted)) # 0.7298601699117384 gnb_model =",
"import MultinomialNB from sklearn import preprocessing from sklearn.model_selection import train_test_split from sklearn.metrics import",
"#change the movie title to recommend a different movie movie_title = \"Thor (2011)\"",
"test_size=0.3) #-- commenting out SVC because it takes too long to run, accuracy",
"matplotlib.pyplot as plt from scipy.sparse import csr_matrix from sklearn.neighbors import NearestNeighbors from sklearn.svm",
"as pd import numpy as np import matplotlib.pyplot as plt from scipy.sparse import",
"SVC because it takes too long to run, accuracy score for SVC is",
"of Ratings per Movie\") plt1 = plt1.get_figure() plt1.savefig('plot/ratingfq',bbox_inches='tight') #--------------- item based recommender system",
"= pd.DataFrame(df_ratings.groupby('movieId').size(), columns=['count']) df_plt = df_plt.sort_values('count',ascending=False) df_plt = df_plt.reset_index(drop=True) plt1 = df_plt.plot(figsize=(30,15),fontsize=15) plt1.set_xlabel(\"movieId\")",
"#dictionary idx_to_movie = dict((v, k) for k, v in movie_to_idx.items()) # reverse dictionary",
"approach:'.format(movie_title)) for i, (idx, dist) in enumerate(tuple_dist_idx): df_avg = df_movies2[df_movies2['title'] == idx_to_movie[idx]] avgr",
"= sorted(list(zip(indices.squeeze().tolist(), distances.squeeze().tolist())), key=lambda x: x[1])[:0:-1] print('Recommendations for {} using a knn approach:'.format(movie_title))",
"df_rating_norm[['movieId','userId']].values y_input = df_rating_norm['rate_norm'].values y_input = y_input.astype('int') X_train, X_test, y_train, y_test = train_test_split(X_input,",
"plt1 = plt1.get_figure() plt1.savefig('plot/ratingfq',bbox_inches='tight') #--------------- item based recommender system ---------------# df_rating_mean = df_ratings.groupby(['movieId'],as_index",
"knn_model_recommender.kneighbors(csr_pivot[idx], n_neighbors=11) tuple_dist_idx = sorted(list(zip(indices.squeeze().tolist(), distances.squeeze().tolist())), key=lambda x: x[1])[:0:-1] print('Recommendations for {} using",
"= df_rating_norm['rate_norm'].values y_input = y_input.astype('int') X_train, X_test, y_train, y_test = train_test_split(X_input, y_input, test_size=0.3)",
"= pd.read_csv(movies_path,usecols=['movieId','title']) df_ratings = pd.read_csv(ratings_path,usecols=['userId','movieId','rating']) df_movierating = pd.merge(df_ratings, df_movies, on='movieId') df_plt = pd.DataFrame(df_ratings.groupby('movieId').size(),",
"recommend a different movie movie_title = \"Thor (2011)\" df_movies = pd.read_csv(movies_path,usecols=['movieId','title']) df_ratings =",
"= \"Thor (2011)\" df_movies = pd.read_csv(movies_path,usecols=['movieId','title']) df_ratings = pd.read_csv(ratings_path,usecols=['userId','movieId','rating']) df_movierating = pd.merge(df_ratings, df_movies,",
"gnb_model.predict(X_test) print(\"\\n ml model Gaussian NB\") print(accuracy_score(y_test, y_predicted)) # 0.7639416878780867 if __name__ ==",
"the data for indexing --# pivot = df_ratings.pivot(index='movieId',columns='userId', values = 'rating').fillna(0) csr_pivot =",
"#print(accuracy_score(y_test, y_predicted)) # 0.760760046015312 bayes_model = MultinomialNB() bayes_model.fit(X_train, y_train) y_predicted = bayes_model.predict(X_test) print(\"\\n",
"--# pivot = df_ratings.pivot(index='movieId',columns='userId', values = 'rating').fillna(0) csr_pivot = csr_matrix(pivot.values) movie_list = list(df_movies.set_index('movieId').loc[pivot.index].title)",
"3) print('{0}: {1}, with distance of {2} and average rating of {3}'.format(i+1, idx_to_movie[idx],",
"y_predicted = bayes_model.predict(X_test) print(\"\\n ml model MultinomialNB\") print(accuracy_score(y_test, y_predicted)) # 0.044858021222438926 knnc_model =",
"= pd.read_csv(ratings_path,usecols=['userId','movieId','rating']) df_movierating = pd.merge(df_ratings, df_movies, on='movieId') df_plt = pd.DataFrame(df_ratings.groupby('movieId').size(), columns=['count']) df_plt =",
"out SVC because it takes too long to run, accuracy score for SVC",
"--# knn_model_recommender = NearestNeighbors(metric='cosine',algorithm='brute',n_neighbors=20,n_jobs=-1) knn_model_recommender.fit(pivot) distances, indices = knn_model_recommender.kneighbors(csr_pivot[idx], n_neighbors=11) tuple_dist_idx = sorted(list(zip(indices.squeeze().tolist(),",
"get_movie_idx_from_name(movie_title,movie_to_idx) # movie index #-- use machine learning (knn) to get closest movies",
"SVC() #svc_model.fit(X_scaled, y_train) #y_predicted = svc_model.predict(Xtest_scaled) #print(\"\\nml model SVC\") #print(accuracy_score(y_test, y_predicted)) # 0.760760046015312",
"from sklearn.svm import SVC from sklearn.naive_bayes import GaussianNB from sklearn.naive_bayes import MultinomialNB from",
"#--------------- machine learning ---------------# X_input = df_rating_norm[['movieId','userId']].values y_input = df_rating_norm['rate_norm'].values y_input = y_input.astype('int')",
"0.044858021222438926 knnc_model = KNeighborsClassifier(n_neighbors=5) knnc_model.fit(X_train, y_train) y_predicted = knnc_model.predict(X_test) print(\"\\n ml model KNN",
"gnb_model.fit(X_train, y_train) y_predicted = gnb_model.predict(X_test) print(\"\\n ml model Gaussian NB\") print(accuracy_score(y_test, y_predicted)) #",
"= svc_model.predict(Xtest_scaled) #print(\"\\nml model SVC\") #print(accuracy_score(y_test, y_predicted)) # 0.760760046015312 bayes_model = MultinomialNB() bayes_model.fit(X_train,",
"import SVC from sklearn.naive_bayes import GaussianNB from sklearn.naive_bayes import MultinomialNB from sklearn import",
"= df_rating_mean.rename(columns = {'rating': 'rating_mean'}) df_rating_norm = pd.merge(df_rating_mean,df_ratings,on='movieId') df_rating_norm['rate_norm'] = df_rating_norm['rating']-df_rating_norm['rating_mean'] df_movies2 =",
"y_train) #y_predicted = svc_model.predict(Xtest_scaled) #print(\"\\nml model SVC\") #print(accuracy_score(y_test, y_predicted)) # 0.760760046015312 bayes_model =",
"= pd.merge(df_rating_mean,df_ratings,on='movieId') df_rating_norm['rate_norm'] = df_rating_norm['rating']-df_rating_norm['rating_mean'] df_movies2 = df_rating_mean.merge(df_movies,on='movieId') #-- reshape the data for",
"from sklearn.neighbors import KNeighborsClassifier def get_movie_idx_from_name(movie_title,movie_to_idx): for title,idx in movie_to_idx.items(): if title ==",
"df_rating_mean = df_rating_mean.drop(columns=['userId']) df_rating_mean = df_rating_mean.rename(columns = {'rating': 'rating_mean'}) df_rating_norm = pd.merge(df_rating_mean,df_ratings,on='movieId') df_rating_norm['rate_norm']",
"knnc_model.fit(X_train, y_train) y_predicted = knnc_model.predict(X_test) print(\"\\n ml model KNN Classifier\") print(accuracy_score(y_test, y_predicted)) #",
"main(): ratings_path = \"Data/ml-latest-small/ratings.csv\" movies_path = \"Data/ml-latest-small/movies.csv\" #change the movie title to recommend",
"df_rating_mean = df_ratings.groupby(['movieId'],as_index = False, sort = False).mean() df_rating_mean = df_rating_mean.drop(columns=['userId']) df_rating_mean =",
"svc_model.predict(Xtest_scaled) #print(\"\\nml model SVC\") #print(accuracy_score(y_test, y_predicted)) # 0.760760046015312 bayes_model = MultinomialNB() bayes_model.fit(X_train, y_train)",
"reverse dictionary idx = get_movie_idx_from_name(movie_title,movie_to_idx) # movie index #-- use machine learning (knn)",
"KNeighborsClassifier(n_neighbors=5) knnc_model.fit(X_train, y_train) y_predicted = knnc_model.predict(X_test) print(\"\\n ml model KNN Classifier\") print(accuracy_score(y_test, y_predicted))",
"system ---------------# df_rating_mean = df_ratings.groupby(['movieId'],as_index = False, sort = False).mean() df_rating_mean = df_rating_mean.drop(columns=['userId'])",
"ratings_path = \"Data/ml-latest-small/ratings.csv\" movies_path = \"Data/ml-latest-small/movies.csv\" #change the movie title to recommend a",
"pandas as pd import numpy as np import matplotlib.pyplot as plt from scipy.sparse",
"df_rating_mean.merge(df_movies,on='movieId') #-- reshape the data for indexing --# pivot = df_ratings.pivot(index='movieId',columns='userId', values =",
"X_train, X_test, y_train, y_test = train_test_split(X_input, y_input, test_size=0.3) #-- commenting out SVC because",
"avgr = round(df_avg, 3) print('{0}: {1}, with distance of {2} and average rating",
"closest movies to recommend --# knn_model_recommender = NearestNeighbors(metric='cosine',algorithm='brute',n_neighbors=20,n_jobs=-1) knn_model_recommender.fit(pivot) distances, indices = knn_model_recommender.kneighbors(csr_pivot[idx],",
"= train_test_split(X_input, y_input, test_size=0.3) #-- commenting out SVC because it takes too long",
"dist, avgr['rating_mean'].iloc[0])) #--------------- machine learning ---------------# X_input = df_rating_norm[['movieId','userId']].values y_input = df_rating_norm['rate_norm'].values y_input",
"= df_rating_norm['rating']-df_rating_norm['rating_mean'] df_movies2 = df_rating_mean.merge(df_movies,on='movieId') #-- reshape the data for indexing --# pivot",
"#!/usr/bin/env python # coding: utf-8 import sys import pandas as pd import numpy",
"dictionary idx = get_movie_idx_from_name(movie_title,movie_to_idx) # movie index #-- use machine learning (knn) to",
"and average rating of {3}'.format(i+1, idx_to_movie[idx], dist, avgr['rating_mean'].iloc[0])) #--------------- machine learning ---------------# X_input",
"df_plt.reset_index(drop=True) plt1 = df_plt.plot(figsize=(30,15),fontsize=15) plt1.set_xlabel(\"movieId\") plt1.set_ylabel(\"Number of ratings\") plt1.set_title(\"Number of Ratings per Movie\")",
"Xtest_scaled = preprocessing.scale(X_test) #svc_model = SVC() #svc_model.fit(X_scaled, y_train) #y_predicted = svc_model.predict(Xtest_scaled) #print(\"\\nml model",
"= GaussianNB() gnb_model.fit(X_train, y_train) y_predicted = gnb_model.predict(X_test) print(\"\\n ml model Gaussian NB\") print(accuracy_score(y_test,",
"df_ratings.pivot(index='movieId',columns='userId', values = 'rating').fillna(0) csr_pivot = csr_matrix(pivot.values) movie_list = list(df_movies.set_index('movieId').loc[pivot.index].title) movie_to_idx = dict(map(lambda",
"movie_to_idx = dict(map(lambda t: (t[1],t[0]), enumerate(movie_list))) #dictionary idx_to_movie = dict((v, k) for k,",
"movie_title: return idx return None def main(): ratings_path = \"Data/ml-latest-small/ratings.csv\" movies_path = \"Data/ml-latest-small/movies.csv\"",
"y_input.astype('int') X_train, X_test, y_train, y_test = train_test_split(X_input, y_input, test_size=0.3) #-- commenting out SVC",
"rating of {3}'.format(i+1, idx_to_movie[idx], dist, avgr['rating_mean'].iloc[0])) #--------------- machine learning ---------------# X_input = df_rating_norm[['movieId','userId']].values",
"= preprocessing.scale(X_test) #svc_model = SVC() #svc_model.fit(X_scaled, y_train) #y_predicted = svc_model.predict(Xtest_scaled) #print(\"\\nml model SVC\")",
"(t[1],t[0]), enumerate(movie_list))) #dictionary idx_to_movie = dict((v, k) for k, v in movie_to_idx.items()) #",
"#print(\"\\nml model SVC\") #print(accuracy_score(y_test, y_predicted)) # 0.760760046015312 bayes_model = MultinomialNB() bayes_model.fit(X_train, y_train) y_predicted",
"to get closest movies to recommend --# knn_model_recommender = NearestNeighbors(metric='cosine',algorithm='brute',n_neighbors=20,n_jobs=-1) knn_model_recommender.fit(pivot) distances, indices",
"bayes_model = MultinomialNB() bayes_model.fit(X_train, y_train) y_predicted = bayes_model.predict(X_test) print(\"\\n ml model MultinomialNB\") print(accuracy_score(y_test,",
"n_neighbors=11) tuple_dist_idx = sorted(list(zip(indices.squeeze().tolist(), distances.squeeze().tolist())), key=lambda x: x[1])[:0:-1] print('Recommendations for {} using a",
"import GaussianNB from sklearn.naive_bayes import MultinomialNB from sklearn import preprocessing from sklearn.model_selection import",
"run, accuracy score for SVC is written in comment below --# X_scaled =",
"SVC from sklearn.naive_bayes import GaussianNB from sklearn.naive_bayes import MultinomialNB from sklearn import preprocessing",
"it takes too long to run, accuracy score for SVC is written in",
"'rating_mean'}) df_rating_norm = pd.merge(df_rating_mean,df_ratings,on='movieId') df_rating_norm['rate_norm'] = df_rating_norm['rating']-df_rating_norm['rating_mean'] df_movies2 = df_rating_mean.merge(df_movies,on='movieId') #-- reshape the",
"round(df_avg, 3) print('{0}: {1}, with distance of {2} and average rating of {3}'.format(i+1,",
"import sys import pandas as pd import numpy as np import matplotlib.pyplot as",
"commenting out SVC because it takes too long to run, accuracy score for",
"csr_matrix from sklearn.neighbors import NearestNeighbors from sklearn.svm import SVC from sklearn.naive_bayes import GaussianNB",
"below --# X_scaled = preprocessing.scale(X_train) Xtest_scaled = preprocessing.scale(X_test) #svc_model = SVC() #svc_model.fit(X_scaled, y_train)",
"df_plt.sort_values('count',ascending=False) df_plt = df_plt.reset_index(drop=True) plt1 = df_plt.plot(figsize=(30,15),fontsize=15) plt1.set_xlabel(\"movieId\") plt1.set_ylabel(\"Number of ratings\") plt1.set_title(\"Number of",
"= MultinomialNB() bayes_model.fit(X_train, y_train) y_predicted = bayes_model.predict(X_test) print(\"\\n ml model MultinomialNB\") print(accuracy_score(y_test, y_predicted))",
"df_movies2 = df_rating_mean.merge(df_movies,on='movieId') #-- reshape the data for indexing --# pivot = df_ratings.pivot(index='movieId',columns='userId',",
"accuracy_score from sklearn.neighbors import KNeighborsClassifier def get_movie_idx_from_name(movie_title,movie_to_idx): for title,idx in movie_to_idx.items(): if title",
"data for indexing --# pivot = df_ratings.pivot(index='movieId',columns='userId', values = 'rating').fillna(0) csr_pivot = csr_matrix(pivot.values)",
"pd import numpy as np import matplotlib.pyplot as plt from scipy.sparse import csr_matrix",
"get_movie_idx_from_name(movie_title,movie_to_idx): for title,idx in movie_to_idx.items(): if title == movie_title: return idx return None",
"# reverse dictionary idx = get_movie_idx_from_name(movie_title,movie_to_idx) # movie index #-- use machine learning",
"plt from scipy.sparse import csr_matrix from sklearn.neighbors import NearestNeighbors from sklearn.svm import SVC",
"knnc_model = KNeighborsClassifier(n_neighbors=5) knnc_model.fit(X_train, y_train) y_predicted = knnc_model.predict(X_test) print(\"\\n ml model KNN Classifier\")",
"title == movie_title: return idx return None def main(): ratings_path = \"Data/ml-latest-small/ratings.csv\" movies_path",
"'rating').fillna(0) csr_pivot = csr_matrix(pivot.values) movie_list = list(df_movies.set_index('movieId').loc[pivot.index].title) movie_to_idx = dict(map(lambda t: (t[1],t[0]), enumerate(movie_list)))",
"np import matplotlib.pyplot as plt from scipy.sparse import csr_matrix from sklearn.neighbors import NearestNeighbors",
"df_plt = df_plt.reset_index(drop=True) plt1 = df_plt.plot(figsize=(30,15),fontsize=15) plt1.set_xlabel(\"movieId\") plt1.set_ylabel(\"Number of ratings\") plt1.set_title(\"Number of Ratings",
"t: (t[1],t[0]), enumerate(movie_list))) #dictionary idx_to_movie = dict((v, k) for k, v in movie_to_idx.items())",
"# movie index #-- use machine learning (knn) to get closest movies to",
"y_test = train_test_split(X_input, y_input, test_size=0.3) #-- commenting out SVC because it takes too",
"utf-8 import sys import pandas as pd import numpy as np import matplotlib.pyplot",
"accuracy score for SVC is written in comment below --# X_scaled = preprocessing.scale(X_train)",
"= df_ratings.groupby(['movieId'],as_index = False, sort = False).mean() df_rating_mean = df_rating_mean.drop(columns=['userId']) df_rating_mean = df_rating_mean.rename(columns",
"scipy.sparse import csr_matrix from sklearn.neighbors import NearestNeighbors from sklearn.svm import SVC from sklearn.naive_bayes",
"plt1.savefig('plot/ratingfq',bbox_inches='tight') #--------------- item based recommender system ---------------# df_rating_mean = df_ratings.groupby(['movieId'],as_index = False, sort",
"{3}'.format(i+1, idx_to_movie[idx], dist, avgr['rating_mean'].iloc[0])) #--------------- machine learning ---------------# X_input = df_rating_norm[['movieId','userId']].values y_input =",
"index #-- use machine learning (knn) to get closest movies to recommend --#",
"import NearestNeighbors from sklearn.svm import SVC from sklearn.naive_bayes import GaussianNB from sklearn.naive_bayes import",
"plt1.get_figure() plt1.savefig('plot/ratingfq',bbox_inches='tight') #--------------- item based recommender system ---------------# df_rating_mean = df_ratings.groupby(['movieId'],as_index = False,",
"numpy as np import matplotlib.pyplot as plt from scipy.sparse import csr_matrix from sklearn.neighbors",
"preprocessing from sklearn.model_selection import train_test_split from sklearn.metrics import accuracy_score from sklearn.neighbors import KNeighborsClassifier",
"knn_model_recommender = NearestNeighbors(metric='cosine',algorithm='brute',n_neighbors=20,n_jobs=-1) knn_model_recommender.fit(pivot) distances, indices = knn_model_recommender.kneighbors(csr_pivot[idx], n_neighbors=11) tuple_dist_idx = sorted(list(zip(indices.squeeze().tolist(), distances.squeeze().tolist())),",
"= bayes_model.predict(X_test) print(\"\\n ml model MultinomialNB\") print(accuracy_score(y_test, y_predicted)) # 0.044858021222438926 knnc_model = KNeighborsClassifier(n_neighbors=5)",
"sklearn.neighbors import NearestNeighbors from sklearn.svm import SVC from sklearn.naive_bayes import GaussianNB from sklearn.naive_bayes",
"if title == movie_title: return idx return None def main(): ratings_path = \"Data/ml-latest-small/ratings.csv\"",
"item based recommender system ---------------# df_rating_mean = df_ratings.groupby(['movieId'],as_index = False, sort = False).mean()",
"columns=['count']) df_plt = df_plt.sort_values('count',ascending=False) df_plt = df_plt.reset_index(drop=True) plt1 = df_plt.plot(figsize=(30,15),fontsize=15) plt1.set_xlabel(\"movieId\") plt1.set_ylabel(\"Number of",
"df_rating_norm['rating']-df_rating_norm['rating_mean'] df_movies2 = df_rating_mean.merge(df_movies,on='movieId') #-- reshape the data for indexing --# pivot =",
"movie_to_idx.items()) # reverse dictionary idx = get_movie_idx_from_name(movie_title,movie_to_idx) # movie index #-- use machine",
"because it takes too long to run, accuracy score for SVC is written",
"from sklearn.metrics import accuracy_score from sklearn.neighbors import KNeighborsClassifier def get_movie_idx_from_name(movie_title,movie_to_idx): for title,idx in",
"= get_movie_idx_from_name(movie_title,movie_to_idx) # movie index #-- use machine learning (knn) to get closest",
"movie index #-- use machine learning (knn) to get closest movies to recommend",
"in movie_to_idx.items(): if title == movie_title: return idx return None def main(): ratings_path",
"csr_matrix(pivot.values) movie_list = list(df_movies.set_index('movieId').loc[pivot.index].title) movie_to_idx = dict(map(lambda t: (t[1],t[0]), enumerate(movie_list))) #dictionary idx_to_movie =",
"title to recommend a different movie movie_title = \"Thor (2011)\" df_movies = pd.read_csv(movies_path,usecols=['movieId','title'])",
"y_predicted = knnc_model.predict(X_test) print(\"\\n ml model KNN Classifier\") print(accuracy_score(y_test, y_predicted)) # 0.7298601699117384 gnb_model",
"score for SVC is written in comment below --# X_scaled = preprocessing.scale(X_train) Xtest_scaled",
"ratings\") plt1.set_title(\"Number of Ratings per Movie\") plt1 = plt1.get_figure() plt1.savefig('plot/ratingfq',bbox_inches='tight') #--------------- item based",
"#--------------- item based recommender system ---------------# df_rating_mean = df_ratings.groupby(['movieId'],as_index = False, sort =",
"= knn_model_recommender.kneighbors(csr_pivot[idx], n_neighbors=11) tuple_dist_idx = sorted(list(zip(indices.squeeze().tolist(), distances.squeeze().tolist())), key=lambda x: x[1])[:0:-1] print('Recommendations for {}",
"sys import pandas as pd import numpy as np import matplotlib.pyplot as plt",
"print(\"\\n ml model KNN Classifier\") print(accuracy_score(y_test, y_predicted)) # 0.7298601699117384 gnb_model = GaussianNB() gnb_model.fit(X_train,",
"pd.merge(df_ratings, df_movies, on='movieId') df_plt = pd.DataFrame(df_ratings.groupby('movieId').size(), columns=['count']) df_plt = df_plt.sort_values('count',ascending=False) df_plt = df_plt.reset_index(drop=True)",
"sklearn.metrics import accuracy_score from sklearn.neighbors import KNeighborsClassifier def get_movie_idx_from_name(movie_title,movie_to_idx): for title,idx in movie_to_idx.items():",
"learning ---------------# X_input = df_rating_norm[['movieId','userId']].values y_input = df_rating_norm['rate_norm'].values y_input = y_input.astype('int') X_train, X_test,",
"of {3}'.format(i+1, idx_to_movie[idx], dist, avgr['rating_mean'].iloc[0])) #--------------- machine learning ---------------# X_input = df_rating_norm[['movieId','userId']].values y_input",
"= df_rating_norm[['movieId','userId']].values y_input = df_rating_norm['rate_norm'].values y_input = y_input.astype('int') X_train, X_test, y_train, y_test =",
"in enumerate(tuple_dist_idx): df_avg = df_movies2[df_movies2['title'] == idx_to_movie[idx]] avgr = round(df_avg, 3) print('{0}: {1},",
"= round(df_avg, 3) print('{0}: {1}, with distance of {2} and average rating of",
"v in movie_to_idx.items()) # reverse dictionary idx = get_movie_idx_from_name(movie_title,movie_to_idx) # movie index #--"
] |
[
"voterEmailAddressRetrieveView json response but not found\") self.assertEqual('voter_device_id' in json_data2, True, \"voter_device_id expected in",
"self.voter_email_address_retrieve_url = reverse(\"apis_v1:voterEmailAddressRetrieveView\") def test_retrieve_with_no_voter_device_id(self): response = self.client.get(self.voter_email_address_retrieve_url) json_data = json.loads(response.content.decode()) self.assertEqual('status' in",
"response, and not found\") self.assertEqual(json_data['status'], \"VALID_VOTER_DEVICE_ID_MISSING\", \"status = {status} Expected status VALID_VOTER_DEVICE_ID_MISSING\" \"voter_device_id:",
"json_data2, True, \"status expected in the voterEmailAddressRetrieveView json response but not found\") self.assertEqual('voter_device_id'",
"voter_device_id=json_data['voter_device_id'])) self.assertEqual(len(json_data[\"email_address_list\"]), 0, \"Expected email_address_list to have length 0, \" \"actual length =",
"the voterEmailAddressRetrieveView json response but not found\") self.assertEqual('voter_device_id' in json_data2, True, \"voter_device_id expected",
"= reverse(\"apis_v1:voterCreateView\") self.voter_email_address_save_url = reverse(\"apis_v1:voterEmailAddressSaveView\") self.voter_email_address_retrieve_url = reverse(\"apis_v1:voterEmailAddressRetrieveView\") def test_retrieve_with_no_voter_device_id(self): response = self.client.get(self.voter_email_address_retrieve_url)",
"json.loads(response.content.decode()) voter_device_id = json_data['voter_device_id'] if 'voter_device_id' in json_data else '' # Create a",
"Brought to you by We Vote. Be good. # -*- coding: UTF-8 -*-",
"import json class WeVoteAPIsV1TestsVoterEmailAddressRetrieve(TestCase): databases = [\"default\", \"readonly\"] def setUp(self): self.generate_voter_device_id_url = reverse(\"apis_v1:deviceIdGenerateView\")",
"= reverse(\"apis_v1:deviceIdGenerateView\") self.voter_create_url = reverse(\"apis_v1:voterCreateView\") self.voter_email_address_save_url = reverse(\"apis_v1:voterEmailAddressSaveView\") self.voter_email_address_retrieve_url = reverse(\"apis_v1:voterEmailAddressRetrieveView\") def test_retrieve_with_no_voter_device_id(self):",
"if 'voter_device_id' in json_data else '' # Create a voter so we can",
"\"VALID_VOTER_DEVICE_ID_MISSING\", \"status = {status} Expected status VALID_VOTER_DEVICE_ID_MISSING\" \"voter_device_id: {voter_device_id}\".format(status=json_data['status'], voter_device_id=json_data['voter_device_id'])) self.assertEqual(len(json_data[\"email_address_list\"]), 0, \"Expected",
"= json.loads(response.content.decode()) voter_device_id = json_data['voter_device_id'] if 'voter_device_id' in json_data else '' # Create",
"def setUp(self): self.generate_voter_device_id_url = reverse(\"apis_v1:deviceIdGenerateView\") self.voter_create_url = reverse(\"apis_v1:voterCreateView\") self.voter_email_address_save_url = reverse(\"apis_v1:voterEmailAddressSaveView\") self.voter_email_address_retrieve_url =",
"response but not found\") self.assertEqual('voter_device_id' in json_data2, True, \"voter_device_id expected in the voterEmailAddressRetrieveView",
"django.urls import reverse from django.test import TestCase from email_outbound.models import EmailAddress, EmailManager import",
"length = {length}\".format(length=len(json_data['email_address_list']))) def test_retrieve_with_voter_device_id(self): response = self.client.get(self.generate_voter_device_id_url) json_data = json.loads(response.content.decode()) voter_device_id =",
"= reverse(\"apis_v1:voterEmailAddressSaveView\") self.voter_email_address_retrieve_url = reverse(\"apis_v1:voterEmailAddressRetrieveView\") def test_retrieve_with_no_voter_device_id(self): response = self.client.get(self.voter_email_address_retrieve_url) json_data = json.loads(response.content.decode())",
"0, \" \"actual length = {length}\".format(length=len(json_data['email_address_list']))) def test_retrieve_with_voter_device_id(self): response = self.client.get(self.generate_voter_device_id_url) json_data =",
"'' # Create a voter so we can test retrieve response2 = self.client.get(self.voter_create_url,",
"True, \"status expected in the json response, and not found\") self.assertEqual(json_data['status'], \"VALID_VOTER_DEVICE_ID_MISSING\", \"status",
"\"status expected in the json response, and not found\") self.assertEqual(json_data['status'], \"VALID_VOTER_DEVICE_ID_MISSING\", \"status =",
"response2 = self.client.get(self.voter_create_url, {'voter_device_id': voter_device_id}) json_data2 = json.loads(response2.content.decode()) self.assertEqual('status' in json_data2, True, \"status",
"email_address_list to have length 0, \" \"actual length = {length}\".format(length=len(json_data['email_address_list']))) def test_retrieve_with_voter_device_id(self): response",
"to you by We Vote. Be good. # -*- coding: UTF-8 -*- from",
"\"voter_device_id: {voter_device_id}\".format(status=json_data['status'], voter_device_id=json_data['voter_device_id'])) self.assertEqual(len(json_data[\"email_address_list\"]), 0, \"Expected email_address_list to have length 0, \" \"actual",
"import reverse from django.test import TestCase from email_outbound.models import EmailAddress, EmailManager import json",
"EmailManager import json class WeVoteAPIsV1TestsVoterEmailAddressRetrieve(TestCase): databases = [\"default\", \"readonly\"] def setUp(self): self.generate_voter_device_id_url =",
"databases = [\"default\", \"readonly\"] def setUp(self): self.generate_voter_device_id_url = reverse(\"apis_v1:deviceIdGenerateView\") self.voter_create_url = reverse(\"apis_v1:voterCreateView\") self.voter_email_address_save_url",
"self.assertEqual('voter_device_id' in json_data2, True, \"voter_device_id expected in the voterEmailAddressRetrieveView json response but not",
"retrieve response2 = self.client.get(self.voter_create_url, {'voter_device_id': voter_device_id}) json_data2 = json.loads(response2.content.decode()) self.assertEqual('status' in json_data2, True,",
"and not found\") self.assertEqual(json_data['status'], \"VALID_VOTER_DEVICE_ID_MISSING\", \"status = {status} Expected status VALID_VOTER_DEVICE_ID_MISSING\" \"voter_device_id: {voter_device_id}\".format(status=json_data['status'],",
"apis_v1/test_views_voter_email_address_save.py # Brought to you by We Vote. Be good. # -*- coding:",
"self.assertEqual(json_data['status'], \"VALID_VOTER_DEVICE_ID_MISSING\", \"status = {status} Expected status VALID_VOTER_DEVICE_ID_MISSING\" \"voter_device_id: {voter_device_id}\".format(status=json_data['status'], voter_device_id=json_data['voter_device_id'])) self.assertEqual(len(json_data[\"email_address_list\"]), 0,",
"json class WeVoteAPIsV1TestsVoterEmailAddressRetrieve(TestCase): databases = [\"default\", \"readonly\"] def setUp(self): self.generate_voter_device_id_url = reverse(\"apis_v1:deviceIdGenerateView\") self.voter_create_url",
"self.assertEqual('status' in json_data2, True, \"status expected in the voterEmailAddressRetrieveView json response but not",
"EmailAddress, EmailManager import json class WeVoteAPIsV1TestsVoterEmailAddressRetrieve(TestCase): databases = [\"default\", \"readonly\"] def setUp(self): self.generate_voter_device_id_url",
"coding: UTF-8 -*- from django.urls import reverse from django.test import TestCase from email_outbound.models",
"= json_data['voter_device_id'] if 'voter_device_id' in json_data else '' # Create a voter so",
"we can test retrieve response2 = self.client.get(self.voter_create_url, {'voter_device_id': voter_device_id}) json_data2 = json.loads(response2.content.decode()) self.assertEqual('status'",
"test_retrieve_with_voter_device_id(self): response = self.client.get(self.generate_voter_device_id_url) json_data = json.loads(response.content.decode()) voter_device_id = json_data['voter_device_id'] if 'voter_device_id' in",
"from django.urls import reverse from django.test import TestCase from email_outbound.models import EmailAddress, EmailManager",
"in the json response, and not found\") self.assertEqual(json_data['status'], \"VALID_VOTER_DEVICE_ID_MISSING\", \"status = {status} Expected",
"else '' # Create a voter so we can test retrieve response2 =",
"in json_data2, True, \"voter_device_id expected in the voterEmailAddressRetrieveView json response but not found\")",
"TestCase from email_outbound.models import EmailAddress, EmailManager import json class WeVoteAPIsV1TestsVoterEmailAddressRetrieve(TestCase): databases = [\"default\",",
"WeVoteAPIsV1TestsVoterEmailAddressRetrieve(TestCase): databases = [\"default\", \"readonly\"] def setUp(self): self.generate_voter_device_id_url = reverse(\"apis_v1:deviceIdGenerateView\") self.voter_create_url = reverse(\"apis_v1:voterCreateView\")",
"UTF-8 -*- from django.urls import reverse from django.test import TestCase from email_outbound.models import",
"# Brought to you by We Vote. Be good. # -*- coding: UTF-8",
"self.voter_create_url = reverse(\"apis_v1:voterCreateView\") self.voter_email_address_save_url = reverse(\"apis_v1:voterEmailAddressSaveView\") self.voter_email_address_retrieve_url = reverse(\"apis_v1:voterEmailAddressRetrieveView\") def test_retrieve_with_no_voter_device_id(self): response =",
"Expected status VALID_VOTER_DEVICE_ID_MISSING\" \"voter_device_id: {voter_device_id}\".format(status=json_data['status'], voter_device_id=json_data['voter_device_id'])) self.assertEqual(len(json_data[\"email_address_list\"]), 0, \"Expected email_address_list to have length",
"voter_device_id = json_data['voter_device_id'] if 'voter_device_id' in json_data else '' # Create a voter",
"response = self.client.get(self.generate_voter_device_id_url) json_data = json.loads(response.content.decode()) voter_device_id = json_data['voter_device_id'] if 'voter_device_id' in json_data",
"not found\") self.assertEqual(json_data['status'], \"VALID_VOTER_DEVICE_ID_MISSING\", \"status = {status} Expected status VALID_VOTER_DEVICE_ID_MISSING\" \"voter_device_id: {voter_device_id}\".format(status=json_data['status'], voter_device_id=json_data['voter_device_id']))",
"-*- from django.urls import reverse from django.test import TestCase from email_outbound.models import EmailAddress,",
"self.client.get(self.voter_create_url, {'voter_device_id': voter_device_id}) json_data2 = json.loads(response2.content.decode()) self.assertEqual('status' in json_data2, True, \"status expected in",
"voter_device_id}) json_data2 = json.loads(response2.content.decode()) self.assertEqual('status' in json_data2, True, \"status expected in the voterEmailAddressRetrieveView",
"\"status expected in the voterEmailAddressRetrieveView json response but not found\") self.assertEqual('voter_device_id' in json_data2,",
"import TestCase from email_outbound.models import EmailAddress, EmailManager import json class WeVoteAPIsV1TestsVoterEmailAddressRetrieve(TestCase): databases =",
"not found\") self.assertEqual('voter_device_id' in json_data2, True, \"voter_device_id expected in the voterEmailAddressRetrieveView json response",
"\" \"actual length = {length}\".format(length=len(json_data['email_address_list']))) def test_retrieve_with_voter_device_id(self): response = self.client.get(self.generate_voter_device_id_url) json_data = json.loads(response.content.decode())",
"self.client.get(self.generate_voter_device_id_url) json_data = json.loads(response.content.decode()) voter_device_id = json_data['voter_device_id'] if 'voter_device_id' in json_data else ''",
"test_retrieve_with_no_voter_device_id(self): response = self.client.get(self.voter_email_address_retrieve_url) json_data = json.loads(response.content.decode()) self.assertEqual('status' in json_data, True, \"status expected",
"json_data = json.loads(response.content.decode()) voter_device_id = json_data['voter_device_id'] if 'voter_device_id' in json_data else '' #",
"can test retrieve response2 = self.client.get(self.voter_create_url, {'voter_device_id': voter_device_id}) json_data2 = json.loads(response2.content.decode()) self.assertEqual('status' in",
"# apis_v1/test_views_voter_email_address_save.py # Brought to you by We Vote. Be good. # -*-",
"import EmailAddress, EmailManager import json class WeVoteAPIsV1TestsVoterEmailAddressRetrieve(TestCase): databases = [\"default\", \"readonly\"] def setUp(self):",
"= [\"default\", \"readonly\"] def setUp(self): self.generate_voter_device_id_url = reverse(\"apis_v1:deviceIdGenerateView\") self.voter_create_url = reverse(\"apis_v1:voterCreateView\") self.voter_email_address_save_url =",
"self.assertEqual('status' in json_data, True, \"status expected in the json response, and not found\")",
"self.assertEqual(len(json_data[\"email_address_list\"]), 0, \"Expected email_address_list to have length 0, \" \"actual length = {length}\".format(length=len(json_data['email_address_list'])))",
"a voter so we can test retrieve response2 = self.client.get(self.voter_create_url, {'voter_device_id': voter_device_id}) json_data2",
"True, \"status expected in the voterEmailAddressRetrieveView json response but not found\") self.assertEqual('voter_device_id' in",
"by We Vote. Be good. # -*- coding: UTF-8 -*- from django.urls import",
"django.test import TestCase from email_outbound.models import EmailAddress, EmailManager import json class WeVoteAPIsV1TestsVoterEmailAddressRetrieve(TestCase): databases",
"json_data = json.loads(response.content.decode()) self.assertEqual('status' in json_data, True, \"status expected in the json response,",
"in json_data, True, \"status expected in the json response, and not found\") self.assertEqual(json_data['status'],",
"in json_data else '' # Create a voter so we can test retrieve",
"json response, and not found\") self.assertEqual(json_data['status'], \"VALID_VOTER_DEVICE_ID_MISSING\", \"status = {status} Expected status VALID_VOTER_DEVICE_ID_MISSING\"",
"Create a voter so we can test retrieve response2 = self.client.get(self.voter_create_url, {'voter_device_id': voter_device_id})",
"= reverse(\"apis_v1:voterEmailAddressRetrieveView\") def test_retrieve_with_no_voter_device_id(self): response = self.client.get(self.voter_email_address_retrieve_url) json_data = json.loads(response.content.decode()) self.assertEqual('status' in json_data,",
"= self.client.get(self.generate_voter_device_id_url) json_data = json.loads(response.content.decode()) voter_device_id = json_data['voter_device_id'] if 'voter_device_id' in json_data else",
"{voter_device_id}\".format(status=json_data['status'], voter_device_id=json_data['voter_device_id'])) self.assertEqual(len(json_data[\"email_address_list\"]), 0, \"Expected email_address_list to have length 0, \" \"actual length",
"{'voter_device_id': voter_device_id}) json_data2 = json.loads(response2.content.decode()) self.assertEqual('status' in json_data2, True, \"status expected in the",
"have length 0, \" \"actual length = {length}\".format(length=len(json_data['email_address_list']))) def test_retrieve_with_voter_device_id(self): response = self.client.get(self.generate_voter_device_id_url)",
"you by We Vote. Be good. # -*- coding: UTF-8 -*- from django.urls",
"def test_retrieve_with_no_voter_device_id(self): response = self.client.get(self.voter_email_address_retrieve_url) json_data = json.loads(response.content.decode()) self.assertEqual('status' in json_data, True, \"status",
"0, \"Expected email_address_list to have length 0, \" \"actual length = {length}\".format(length=len(json_data['email_address_list']))) def",
"setUp(self): self.generate_voter_device_id_url = reverse(\"apis_v1:deviceIdGenerateView\") self.voter_create_url = reverse(\"apis_v1:voterCreateView\") self.voter_email_address_save_url = reverse(\"apis_v1:voterEmailAddressSaveView\") self.voter_email_address_retrieve_url = reverse(\"apis_v1:voterEmailAddressRetrieveView\")",
"\"status = {status} Expected status VALID_VOTER_DEVICE_ID_MISSING\" \"voter_device_id: {voter_device_id}\".format(status=json_data['status'], voter_device_id=json_data['voter_device_id'])) self.assertEqual(len(json_data[\"email_address_list\"]), 0, \"Expected email_address_list",
"from django.test import TestCase from email_outbound.models import EmailAddress, EmailManager import json class WeVoteAPIsV1TestsVoterEmailAddressRetrieve(TestCase):",
"from email_outbound.models import EmailAddress, EmailManager import json class WeVoteAPIsV1TestsVoterEmailAddressRetrieve(TestCase): databases = [\"default\", \"readonly\"]",
"= json.loads(response2.content.decode()) self.assertEqual('status' in json_data2, True, \"status expected in the voterEmailAddressRetrieveView json response",
"in the voterEmailAddressRetrieveView json response but not found\") self.assertEqual('voter_device_id' in json_data2, True, \"voter_device_id",
"json.loads(response2.content.decode()) self.assertEqual('status' in json_data2, True, \"status expected in the voterEmailAddressRetrieveView json response but",
"reverse(\"apis_v1:voterEmailAddressSaveView\") self.voter_email_address_retrieve_url = reverse(\"apis_v1:voterEmailAddressRetrieveView\") def test_retrieve_with_no_voter_device_id(self): response = self.client.get(self.voter_email_address_retrieve_url) json_data = json.loads(response.content.decode()) self.assertEqual('status'",
"We Vote. Be good. # -*- coding: UTF-8 -*- from django.urls import reverse",
"self.client.get(self.voter_email_address_retrieve_url) json_data = json.loads(response.content.decode()) self.assertEqual('status' in json_data, True, \"status expected in the json",
"{status} Expected status VALID_VOTER_DEVICE_ID_MISSING\" \"voter_device_id: {voter_device_id}\".format(status=json_data['status'], voter_device_id=json_data['voter_device_id'])) self.assertEqual(len(json_data[\"email_address_list\"]), 0, \"Expected email_address_list to have",
"self.voter_email_address_save_url = reverse(\"apis_v1:voterEmailAddressSaveView\") self.voter_email_address_retrieve_url = reverse(\"apis_v1:voterEmailAddressRetrieveView\") def test_retrieve_with_no_voter_device_id(self): response = self.client.get(self.voter_email_address_retrieve_url) json_data =",
"class WeVoteAPIsV1TestsVoterEmailAddressRetrieve(TestCase): databases = [\"default\", \"readonly\"] def setUp(self): self.generate_voter_device_id_url = reverse(\"apis_v1:deviceIdGenerateView\") self.voter_create_url =",
"json_data2 = json.loads(response2.content.decode()) self.assertEqual('status' in json_data2, True, \"status expected in the voterEmailAddressRetrieveView json",
"reverse(\"apis_v1:voterEmailAddressRetrieveView\") def test_retrieve_with_no_voter_device_id(self): response = self.client.get(self.voter_email_address_retrieve_url) json_data = json.loads(response.content.decode()) self.assertEqual('status' in json_data, True,",
"# Create a voter so we can test retrieve response2 = self.client.get(self.voter_create_url, {'voter_device_id':",
"but not found\") self.assertEqual('voter_device_id' in json_data2, True, \"voter_device_id expected in the voterEmailAddressRetrieveView json",
"email_outbound.models import EmailAddress, EmailManager import json class WeVoteAPIsV1TestsVoterEmailAddressRetrieve(TestCase): databases = [\"default\", \"readonly\"] def",
"[\"default\", \"readonly\"] def setUp(self): self.generate_voter_device_id_url = reverse(\"apis_v1:deviceIdGenerateView\") self.voter_create_url = reverse(\"apis_v1:voterCreateView\") self.voter_email_address_save_url = reverse(\"apis_v1:voterEmailAddressSaveView\")",
"to have length 0, \" \"actual length = {length}\".format(length=len(json_data['email_address_list']))) def test_retrieve_with_voter_device_id(self): response =",
"\"readonly\"] def setUp(self): self.generate_voter_device_id_url = reverse(\"apis_v1:deviceIdGenerateView\") self.voter_create_url = reverse(\"apis_v1:voterCreateView\") self.voter_email_address_save_url = reverse(\"apis_v1:voterEmailAddressSaveView\") self.voter_email_address_retrieve_url",
"expected in the json response, and not found\") self.assertEqual(json_data['status'], \"VALID_VOTER_DEVICE_ID_MISSING\", \"status = {status}",
"self.generate_voter_device_id_url = reverse(\"apis_v1:deviceIdGenerateView\") self.voter_create_url = reverse(\"apis_v1:voterCreateView\") self.voter_email_address_save_url = reverse(\"apis_v1:voterEmailAddressSaveView\") self.voter_email_address_retrieve_url = reverse(\"apis_v1:voterEmailAddressRetrieveView\") def",
"Vote. Be good. # -*- coding: UTF-8 -*- from django.urls import reverse from",
"good. # -*- coding: UTF-8 -*- from django.urls import reverse from django.test import",
"= self.client.get(self.voter_email_address_retrieve_url) json_data = json.loads(response.content.decode()) self.assertEqual('status' in json_data, True, \"status expected in the",
"reverse from django.test import TestCase from email_outbound.models import EmailAddress, EmailManager import json class",
"found\") self.assertEqual('voter_device_id' in json_data2, True, \"voter_device_id expected in the voterEmailAddressRetrieveView json response but",
"= {length}\".format(length=len(json_data['email_address_list']))) def test_retrieve_with_voter_device_id(self): response = self.client.get(self.generate_voter_device_id_url) json_data = json.loads(response.content.decode()) voter_device_id = json_data['voter_device_id']",
"json.loads(response.content.decode()) self.assertEqual('status' in json_data, True, \"status expected in the json response, and not",
"reverse(\"apis_v1:voterCreateView\") self.voter_email_address_save_url = reverse(\"apis_v1:voterEmailAddressSaveView\") self.voter_email_address_retrieve_url = reverse(\"apis_v1:voterEmailAddressRetrieveView\") def test_retrieve_with_no_voter_device_id(self): response = self.client.get(self.voter_email_address_retrieve_url) json_data",
"json_data else '' # Create a voter so we can test retrieve response2",
"VALID_VOTER_DEVICE_ID_MISSING\" \"voter_device_id: {voter_device_id}\".format(status=json_data['status'], voter_device_id=json_data['voter_device_id'])) self.assertEqual(len(json_data[\"email_address_list\"]), 0, \"Expected email_address_list to have length 0, \"",
"voter so we can test retrieve response2 = self.client.get(self.voter_create_url, {'voter_device_id': voter_device_id}) json_data2 =",
"response = self.client.get(self.voter_email_address_retrieve_url) json_data = json.loads(response.content.decode()) self.assertEqual('status' in json_data, True, \"status expected in",
"json_data['voter_device_id'] if 'voter_device_id' in json_data else '' # Create a voter so we",
"status VALID_VOTER_DEVICE_ID_MISSING\" \"voter_device_id: {voter_device_id}\".format(status=json_data['status'], voter_device_id=json_data['voter_device_id'])) self.assertEqual(len(json_data[\"email_address_list\"]), 0, \"Expected email_address_list to have length 0,",
"so we can test retrieve response2 = self.client.get(self.voter_create_url, {'voter_device_id': voter_device_id}) json_data2 = json.loads(response2.content.decode())",
"{length}\".format(length=len(json_data['email_address_list']))) def test_retrieve_with_voter_device_id(self): response = self.client.get(self.generate_voter_device_id_url) json_data = json.loads(response.content.decode()) voter_device_id = json_data['voter_device_id'] if",
"json_data, True, \"status expected in the json response, and not found\") self.assertEqual(json_data['status'], \"VALID_VOTER_DEVICE_ID_MISSING\",",
"the json response, and not found\") self.assertEqual(json_data['status'], \"VALID_VOTER_DEVICE_ID_MISSING\", \"status = {status} Expected status",
"test retrieve response2 = self.client.get(self.voter_create_url, {'voter_device_id': voter_device_id}) json_data2 = json.loads(response2.content.decode()) self.assertEqual('status' in json_data2,",
"def test_retrieve_with_voter_device_id(self): response = self.client.get(self.generate_voter_device_id_url) json_data = json.loads(response.content.decode()) voter_device_id = json_data['voter_device_id'] if 'voter_device_id'",
"# -*- coding: UTF-8 -*- from django.urls import reverse from django.test import TestCase",
"\"actual length = {length}\".format(length=len(json_data['email_address_list']))) def test_retrieve_with_voter_device_id(self): response = self.client.get(self.generate_voter_device_id_url) json_data = json.loads(response.content.decode()) voter_device_id",
"'voter_device_id' in json_data else '' # Create a voter so we can test",
"reverse(\"apis_v1:deviceIdGenerateView\") self.voter_create_url = reverse(\"apis_v1:voterCreateView\") self.voter_email_address_save_url = reverse(\"apis_v1:voterEmailAddressSaveView\") self.voter_email_address_retrieve_url = reverse(\"apis_v1:voterEmailAddressRetrieveView\") def test_retrieve_with_no_voter_device_id(self): response",
"json response but not found\") self.assertEqual('voter_device_id' in json_data2, True, \"voter_device_id expected in the",
"in json_data2, True, \"status expected in the voterEmailAddressRetrieveView json response but not found\")",
"-*- coding: UTF-8 -*- from django.urls import reverse from django.test import TestCase from",
"found\") self.assertEqual(json_data['status'], \"VALID_VOTER_DEVICE_ID_MISSING\", \"status = {status} Expected status VALID_VOTER_DEVICE_ID_MISSING\" \"voter_device_id: {voter_device_id}\".format(status=json_data['status'], voter_device_id=json_data['voter_device_id'])) self.assertEqual(len(json_data[\"email_address_list\"]),",
"expected in the voterEmailAddressRetrieveView json response but not found\") self.assertEqual('voter_device_id' in json_data2, True,",
"= self.client.get(self.voter_create_url, {'voter_device_id': voter_device_id}) json_data2 = json.loads(response2.content.decode()) self.assertEqual('status' in json_data2, True, \"status expected",
"length 0, \" \"actual length = {length}\".format(length=len(json_data['email_address_list']))) def test_retrieve_with_voter_device_id(self): response = self.client.get(self.generate_voter_device_id_url) json_data",
"\"Expected email_address_list to have length 0, \" \"actual length = {length}\".format(length=len(json_data['email_address_list']))) def test_retrieve_with_voter_device_id(self):",
"Be good. # -*- coding: UTF-8 -*- from django.urls import reverse from django.test",
"= json.loads(response.content.decode()) self.assertEqual('status' in json_data, True, \"status expected in the json response, and",
"= {status} Expected status VALID_VOTER_DEVICE_ID_MISSING\" \"voter_device_id: {voter_device_id}\".format(status=json_data['status'], voter_device_id=json_data['voter_device_id'])) self.assertEqual(len(json_data[\"email_address_list\"]), 0, \"Expected email_address_list to"
] |
[
"+= (features[i] * weights[i]) return result #makes the best possible amongst all of",
"r in range(3): for c in range(3): button = Button(frame, text=\"-\", command=partial(buttonClick, i))",
"2, checkLists)): return 2 #o win elif(board.count(0) != 0): return 3 #game still",
"'/resources/spartan-icon-small.png') root.call('wm', 'iconphoto', root._w, spartanImage) frame = Frame(root) frame.grid(row=0, column=0, sticky=N+S+E+W) buttonFont =",
"1, checkLists), twoInARow(a, 2, checkLists), openOne(a, 1, checkLists), openOne(a, 2, checkLists)] #returns the",
"Grid.rowconfigure(radioFrame, 0, weight=1) Grid.columnconfigure(radioFrame, 0, weight=1) Grid.columnconfigure(radioFrame, 1, weight=1) r1 = Radiobutton(radioFrame, text=\"X?\",",
"functools import partial from PIL import ImageTk #------------------------------------------------------------------------------------- #------------------------------------------------------------------------------------- #------------------------------------------------------------------------------------- #Author: <NAME> #Date:",
"determines if the game is: ongoing, a draw, a win for x, a",
"openOne(a, 1, checkLists), openOne(a, 2, checkLists)] #returns the value of a board based",
"x's in a row (0 or 1) # is there 3 o's in",
"1 or y == 4 or y == 7)]) b.append([board[y] for y in",
"weights[j] = weights[j] +(learnConstant*(value-estimate)*features[j]) #initialize our weights, the value of 0.5 is arbitrarily",
"buttonFont = tkFont.Font(family='Helvetica', size=72, weight='bold') buttons = [] i = 0 for r",
"board[a[randomNum]] = x #plays a tic-tac-toe game between the X and O AI",
"#------------------------------------------------------------------------------------- #Run via Python 2.7 #REQUIRES: pillow (python imaging library) #------------------------------------------------------------------------------------- #------------------------------------------------------------------------------------- #-------------------------------------------------------------------------------------",
"space # # of places where there is an x and two empty",
"(python imaging library) #------------------------------------------------------------------------------------- #------------------------------------------------------------------------------------- #------------------------------------------------------------------------------------- #the board is a list of size",
"our tic tac toe AI!!!\") print(\"final weights: \") print(xWeights) print(oWeights) print(\"launching the GUI,",
"Code-------------------------- #---------------------------------------------------- #determines if the game is still ongoing an updates the label",
"# of places where there is 2 x/o's & an empty space in",
"== top right space # 3 == center left space # 4 ==",
"value=1) r1.grid(row=0, column=0, sticky=N+S+E+W) r1.invoke() r2 = Radiobutton(radioFrame, text=\"O?\", variable=playAsWhich, value=2) r2.grid(row=0, column=1,",
"= 2 else: computerSide = 1 winnerLabel['text'] = 'game started' theBoard = [0",
"tac toeboard #the features are as follows: # is there 3 x's in",
"row=4, column=0) spartanLabel = Label(spartanFrame, image=spartanImage, cursor='hand2') spartanLabel.pack() spartanTextLink = Label(spartanFrame, text='www.spartanengineer.com', fg='blue',",
"== []): a = getCheckLists(board) for c in a: if(c.count(x) == 3): return",
"range(len(train))] if(result == 0): values[len(values)-1] = 0 elif(result == x): values[len(values)-1] = 100",
"return [conv[threeInARow(a, 1, checkLists)], conv[threeInARow(a, 2, checkLists)], twoInARow(a, 1, checkLists), twoInARow(a, 2, checkLists),",
"i in range(len(values)): board = train[i] features = getFeatures(board) value = values[i] estimate",
"a browser def openWebsite(event): webbrowser.open_new('http://www.spartanengineer.com') #the following code sets up the Tkinter GUI",
"space in each board: # 0 == empty space # 1 == x",
"left space # 4 == center center space # 5 == center right",
"X and O AI #we pit AI's against each other in order to",
"on the features (of the board) and their respective weights def estimateMoveValue(features, weights):",
"in range(len(features)): result += (features[i] * weights[i]) return result #makes the best possible",
"0, weight=1) Grid.columnconfigure(radioFrame, 1, weight=1) r1 = Radiobutton(radioFrame, text=\"X?\", variable=playAsWhich, value=1) r1.grid(row=0, column=0,",
"in range(9) if(y == 2 or y == 4 or y == 6)])",
"buttons.append(button) i += 1 newGameButton = Button(frame, command=newGameClick, text=\"New Game?\") newGameButton.grid(row=3, column=0, sticky=N+S+E+W)",
"# 5 == center right space # 6 == bottom left space #",
"space # 4 == center center space # 5 == center right space",
"two empty spaces in a row/col/diagonal def getFeatures(board): a = board checkLists =",
"a tic tac toeboard #the features are as follows: # is there 3",
"via a Tkinter # GUI. #------------------------------------------------------------------------------------- #Run via Python 2.7 #REQUIRES: pillow (python",
"center right space # 6 == bottom left space # 7 == bottom",
"or y == 7)]) b.append([board[y] for y in range(9) if(y == 2 or",
"minute or two...)\" % trainingIterations) for i in range(trainingIterations): xTrain, oTrain = [],",
"are updated by comparing the estimated move value with the actual move value",
"rootDirectory = os.path.dirname(os.path.realpath(__file__)) print('----------------------------------------------------') print('----------------------------------------------------') print('https://www.spartanengineer.com') print('----------------------------------------------------') print('----------------------------------------------------') learnConstant = 0.1 # learning",
"i in range(n_features)] trainingIterations = 10000 print(\"training our tic tac toe AI for",
"board = [0 for x in range(9)] gameState = 3 while(gameState == 3):",
"3 #game still going else: return 0 #draw conv = {True:1, False:0} #returns",
"arbitrarily picked initialWeight = 0.5 n_features = 6 oWeights = [initialWeight for i",
"b.append([board[y] for y in range(9) if(y == 0 or y == 4 or",
"win for x, a win for o def getGameState(board): checkLists = getCheckLists(board) if(threeInARow(board,",
"for c in a: if(c.count(x) == 3): return True return False #returns the",
"is 2 x/o's & an empty space in a row/col/diagonal def twoInARow(board, x,",
"sticky=N+S+E+W) playAsWhich = IntVar() radioFrame = Frame(frame) radioFrame.grid(row=3, column=1, sticky=N+S+E+W) Grid.rowconfigure(radioFrame, 0, weight=1)",
"3 or y == 6)]) #vertical b.append([board[y] for y in range(9) if(y ==",
"for i in range(trainingIterations): xTrain, oTrain = [], [] result = playGame(xWeights, oWeights,",
"openWebsite) spartanLabel.bind(\"<Button-1>\", openWebsite) spartanTextLink.pack() for r in range(5): Grid.rowconfigure(frame, r, weight=1) for c",
"win, and loss def updateWeights(weights, train, result, x): values = [0 for i",
"engineer website in a browser def openWebsite(event): webbrowser.open_new('http://www.spartanengineer.com') #the following code sets up",
"a tic-tac-toe game between the X and O AI #we pit AI's against",
"clicked def buttonClick(n): theBoard[n] = playerSide updateButtons() winnerLabel['text'] = 'computer turn' state =",
"spartanImage = ImageTk.PhotoImage(file=rootDirectory + '/resources/spartan-icon-small.png') root.call('wm', 'iconphoto', root._w, spartanImage) frame = Frame(root) frame.grid(row=0,",
"!= 3): for i in range(9): buttons[i]['state'] = 'disabled' return state #update our",
"trainingIterations = 10000 print(\"training our tic tac toe AI for %d games (this",
"def estimateMoveValue(features, weights): result = 0 for i in range(len(features)): result += (features[i]",
"2 or y == 5 or y == 8)]) b.append([board[y] for y in",
"space # 2 == o space rootDirectory = os.path.dirname(os.path.realpath(__file__)) print('----------------------------------------------------') print('----------------------------------------------------') print('https://www.spartanengineer.com') print('----------------------------------------------------')",
"range(9) if(y == 0 or y == 3 or y == 6)]) #vertical",
"== []): a = getCheckLists(board) for c in a: if(c.count(x) == 2 and",
"= Radiobutton(radioFrame, text=\"O?\", variable=playAsWhich, value=2) r2.grid(row=0, column=1, sticky=N+S+E+W) winnerLabel = Label(frame, text=\"new game\")",
"0, weight=1) Grid.columnconfigure(root, 0, weight=1) root.minsize(width=700, height=700) root.wm_title(\"SpartanTicTacToe\") spartanImage = ImageTk.PhotoImage(file=rootDirectory + '/resources/spartan-icon-small.png')",
"is 2 x's beside an empty space # # of places where there",
"not #x parameter should be 1(x) or 2(o) def threeInARow(board, x, a=[]): if(a",
"features (of the board) and their respective weights def estimateMoveValue(features, weights): result =",
"False:0} #returns a list of the features used to evaluate the value of",
"#initialize our weights, the value of 0.5 is arbitrarily picked initialWeight = 0.5",
"= playerSide updateButtons() winnerLabel['text'] = 'computer turn' state = determineWinner() if(state == 3):",
"checkLists = getCheckLists(a) return [conv[threeInARow(a, 1, checkLists)], conv[threeInARow(a, 2, checkLists)], twoInARow(a, 1, checkLists),",
"computerSide, theBoard playerSide = playAsWhich.get() if(playerSide == 1): computerSide = 2 else: computerSide",
"the X and O AI #we pit AI's against each other in order",
"an updates the label correctly def determineWinner(): state = getGameState(theBoard) if(state == 0):",
"board based on the features (of the board) and their respective weights def",
"value of a board based on the features (of the board) and their",
"= 0 elif(result == x): values[len(values)-1] = 100 else: values[len(values)-1] = -100 for",
"values = [], [] positions = [i for i in range(9) if(board[i] ==",
"boards, values = [], [] positions = [i for i in range(9) if(board[i]",
"a board based on the features (of the board) and their respective weights",
"toe AI!!!\") print(\"final weights: \") print(xWeights) print(oWeights) print(\"launching the GUI, this allows the",
"b.append(board[6:9]) b.append([board[y] for y in range(9) if(y == 0 or y == 3",
"top center space # 2 == top right space # 3 == center",
"space # 8 == bottom right space #value mapping for a space in",
"result #makes the best possible amongst all of the possible moves def makeBestMove(board,",
"a list of size 9 that contains information about the current tic #",
"for a draw, win, and loss def updateWeights(weights, train, result, x): values =",
"and c.count(0) == 2): result += 1 return result #this function determines if",
"is an x and two empty spaces in a row/col/diagonal # # of",
"center space # 2 == top right space # 3 == center left",
"print('https://www.spartanengineer.com') print('----------------------------------------------------') print('----------------------------------------------------') learnConstant = 0.1 # learning constant def getCheckLists(board): b =",
"playGame(xWeights, oWeights, xTrain, oTrain) updateWeights(xWeights, xTrain, result, 1) updateWeights(oWeights, oTrain, result, 2) print(\"finished",
"0 #draw conv = {True:1, False:0} #returns a list of the features used",
"\") print(xWeights) print(oWeights) print(\"launching the GUI, this allows the user to play against",
"c.count(0) == 1): result += 1 return result #returns the # of places",
"return 0 #draw conv = {True:1, False:0} #returns a list of the features",
"b = [] b.append(board[0:3]) #horizontal b.append(board[3:6]) b.append(board[6:9]) b.append([board[y] for y in range(9) if(y",
"where there is 2 x/o's & an empty space in a row/col/diagonal def",
"oTrain = [], [] result = playGame(xWeights, oWeights, xTrain, oTrain) updateWeights(xWeights, xTrain, result,",
"makeMove(): if(computerSide == 1): makeBestMove(theBoard, xWeights, 1) else: makeBestMove(theBoard, oWeights, 2) updateButtons() winnerLabel['text']",
"range(len(weights)): weights[j] = weights[j] +(learnConstant*(value-estimate)*features[j]) #initialize our weights, the value of 0.5 is",
"row/col/diagonal def openOne(board, x, a=[]): result = 0 if(a == []): a =",
"result, 1) updateWeights(oWeights, oTrain, result, 2) print(\"finished training our tic tac toe AI!!!\")",
"2) print(\"finished training our tic tac toe AI!!!\") print(\"final weights: \") print(xWeights) print(oWeights)",
"spartanLabel.pack() spartanTextLink = Label(spartanFrame, text='www.spartanengineer.com', fg='blue', cursor='hand2') spartanTextLink.bind(\"<Button-1>\", openWebsite) spartanLabel.bind(\"<Button-1>\", openWebsite) spartanTextLink.pack() for",
"newBoard[position] = x features = getFeatures(newBoard) value = estimateMoveValue(features, weights) boards.append(newBoard) values.append(value) mValue",
"= train[i] features = getFeatures(board) value = values[i] estimate = estimateMoveValue(features, weights) #update",
"mPosition = positions[i] board[mPosition] = x #makes a random move def makeRandomMove(board, x):",
"1, checkLists), openOne(a, 2, checkLists)] #returns the value of a board based on",
"makeRandomMove(board, x): a = [i for i in range(9) if(board[i] == 0)] randomNum",
"x #makes a random move def makeRandomMove(board, x): a = [i for i",
"!= 0): return 3 #game still going else: return 0 #draw conv =",
"Grid.columnconfigure(root, 0, weight=1) root.minsize(width=700, height=700) root.wm_title(\"SpartanTicTacToe\") spartanImage = ImageTk.PhotoImage(file=rootDirectory + '/resources/spartan-icon-small.png') root.call('wm', 'iconphoto',",
"= values[0] mPosition = positions[0] for i in range(1, len(positions)): if(values[i] > mValue):",
"== bottom right space #value mapping for a space in each board: #",
"going else: return 0 #draw conv = {True:1, False:0} #returns a list of",
"if(y == 0 or y == 4 or y == 8)]) #diagonal b.append([board[y]",
"theBoard = [0 for x in range(9)] for b in buttons: b['text'] =",
"1 gameState = getGameState(board) return gameState #update our weights based upon the training",
"= Radiobutton(radioFrame, text=\"X?\", variable=playAsWhich, value=1) r1.grid(row=0, column=0, sticky=N+S+E+W) r1.invoke() r2 = Radiobutton(radioFrame, text=\"O?\",",
"== 7)]) b.append([board[y] for y in range(9) if(y == 2 or y ==",
"function is called when on the board buttons are clicked def buttonClick(n): theBoard[n]",
"wins' elif(state == computerSide): winnerLabel['text'] = 'computer wins' if(state != 3): for i",
"* from functools import partial from PIL import ImageTk #------------------------------------------------------------------------------------- #------------------------------------------------------------------------------------- #------------------------------------------------------------------------------------- #Author:",
"# of places where there is 2 x's beside an empty space #",
"randomNum = random.randint(0, len(a)-1) board[a[randomNum]] = x #plays a tic-tac-toe game between the",
"the features used to evaluate the value of a tic tac toeboard #the",
"or 1) # # of places where there is 2 x's beside an",
"% trainingIterations) for i in range(trainingIterations): xTrain, oTrain = [], [] result =",
"range(len(features)): result += (features[i] * weights[i]) return result #makes the best possible amongst",
"random, tkFont, time, webbrowser, os from Tkinter import * from functools import partial",
"loads up the spartan engineer website in a browser def openWebsite(event): webbrowser.open_new('http://www.spartanengineer.com') #the",
"1) else: makeBestMove(theBoard, oWeights, 2) updateButtons() winnerLabel['text'] = 'player turn' determineWinner() #this function",
"c.count(0) == 2): result += 1 return result #this function determines if the",
"i in range(trainingIterations): xTrain, oTrain = [], [] result = playGame(xWeights, oWeights, xTrain,",
"copy, random, tkFont, time, webbrowser, os from Tkinter import * from functools import",
"winnerLabel['text'] = 'computer turn' state = determineWinner() if(state == 3): makeMove() #this function",
"for i in range(9): if(theBoard[i] != 0): b = buttons[i] if(theBoard[i] == 1):",
"weights, x): boards, values = [], [] positions = [i for i in",
"turn' state = determineWinner() if(state == 3): makeMove() #this function starts a new",
"for x in range(9)] gameState = 3 while(gameState == 3): if(turn == 1):",
"Game?\") newGameButton.grid(row=3, column=0, sticky=N+S+E+W) playAsWhich = IntVar() radioFrame = Frame(frame) radioFrame.grid(row=3, column=1, sticky=N+S+E+W)",
"from functools import partial from PIL import ImageTk #------------------------------------------------------------------------------------- #------------------------------------------------------------------------------------- #------------------------------------------------------------------------------------- #Author: <NAME>",
"== bottom center space # 8 == bottom right space #value mapping for",
"makeBestMove(board, xWeights, turn) xTrain.append(copy.deepcopy(board)) else: makeBestMove(board, oWeights, turn) oTrain.append(copy.deepcopy(board)) if(turn == 1): turn",
"an x/o and 2 empty spaces in a row/col/diagonal def openOne(board, x, a=[]):",
"about the current tic # tac toe board #the board maps as follows:",
"# 8 == bottom right space #value mapping for a space in each",
"#Run via Python 2.7 #REQUIRES: pillow (python imaging library) #------------------------------------------------------------------------------------- #------------------------------------------------------------------------------------- #------------------------------------------------------------------------------------- #the",
"an x and two empty spaces in a row/col/diagonal # # of places",
"list of the features used to evaluate the value of a tic tac",
"1, checkLists)], conv[threeInARow(a, 2, checkLists)], twoInARow(a, 1, checkLists), twoInARow(a, 2, checkLists), openOne(a, 1,",
"estimated move value with the actual move value #values of 0, 100, &",
"= 1 board = [0 for x in range(9)] gameState = 3 while(gameState",
"#Author: <NAME> #Date: 01/29/17 #Description: This code uses machine learning to train a",
"AI root = Tk() Grid.rowconfigure(root, 0, weight=1) Grid.columnconfigure(root, 0, weight=1) root.minsize(width=700, height=700) root.wm_title(\"SpartanTicTacToe\")",
"import partial from PIL import ImageTk #------------------------------------------------------------------------------------- #------------------------------------------------------------------------------------- #------------------------------------------------------------------------------------- #Author: <NAME> #Date: 01/29/17",
"x in range(9)] for b in buttons: b['text'] = '-' b['state'] = 'normal'",
"for y in range(9) if(y == 1 or y == 4 or y",
"range(9)] for b in buttons: b['text'] = '-' b['state'] = 'normal' if(computerSide ==",
"# of places where there is an x and two empty spaces in",
"0 if(a == []): a = getCheckLists(board) for c in a: if(c.count(x) ==",
"playerSide): winnerLabel['text'] = 'player wins' elif(state == computerSide): winnerLabel['text'] = 'computer wins' if(state",
"variable=playAsWhich, value=1) r1.grid(row=0, column=0, sticky=N+S+E+W) r1.invoke() r2 = Radiobutton(radioFrame, text=\"O?\", variable=playAsWhich, value=2) r2.grid(row=0,",
"row/col/diagonal # # of places where there is an o and two empty",
"turn = 1 board = [0 for x in range(9)] gameState = 3",
"x space # 2 == o space rootDirectory = os.path.dirname(os.path.realpath(__file__)) print('----------------------------------------------------') print('----------------------------------------------------') print('https://www.spartanengineer.com')",
"b.append(board[3:6]) b.append(board[6:9]) b.append([board[y] for y in range(9) if(y == 0 or y ==",
"learnConstant = 0.1 # learning constant def getCheckLists(board): b = [] b.append(board[0:3]) #horizontal",
"or y == 8)]) b.append([board[y] for y in range(9) if(y == 0 or",
"j in range(len(weights)): weights[j] = weights[j] +(learnConstant*(value-estimate)*features[j]) #initialize our weights, the value of",
"in a: if(c.count(x) == 3): return True return False #returns the # of",
"to train our AI's def playGame(xWeights, oWeights, xTrain, oTrain): turn = 1 board",
"print('----------------------------------------------------') print('----------------------------------------------------') print('https://www.spartanengineer.com') print('----------------------------------------------------') print('----------------------------------------------------') learnConstant = 0.1 # learning constant def getCheckLists(board):",
"when on the board buttons are clicked def buttonClick(n): theBoard[n] = playerSide updateButtons()",
"this allows the user to play against the AI\") #---------------------------------------------------- #------------------GUI Code-------------------------- #----------------------------------------------------",
"= 'disabled' buttons.append(button) i += 1 newGameButton = Button(frame, command=newGameClick, text=\"New Game?\") newGameButton.grid(row=3,",
"getCheckLists(board) for c in a: if(c.count(x) == 3): return True return False #returns",
"AI\") #---------------------------------------------------- #------------------GUI Code-------------------------- #---------------------------------------------------- #determines if the game is still ongoing an",
"text=\"New Game?\") newGameButton.grid(row=3, column=0, sticky=N+S+E+W) playAsWhich = IntVar() radioFrame = Frame(frame) radioFrame.grid(row=3, column=1,",
"= os.path.dirname(os.path.realpath(__file__)) print('----------------------------------------------------') print('----------------------------------------------------') print('https://www.spartanengineer.com') print('----------------------------------------------------') print('----------------------------------------------------') learnConstant = 0.1 # learning constant",
"estimateMoveValue(features, weights): result = 0 for i in range(len(features)): result += (features[i] *",
"0 == empty space # 1 == x space # 2 == o",
"where there is an o and two empty spaces in a row/col/diagonal def",
"updates the label correctly def determineWinner(): state = getGameState(theBoard) if(state == 0): winnerLabel['text']",
"3): for i in range(9): buttons[i]['state'] = 'disabled' return state #update our tic",
"of places where there is 2 x/o's & an empty space in a",
"'O' b['state'] = 'disabled' #makes a computer move def makeMove(): if(computerSide == 1):",
"checkLists), twoInARow(a, 2, checkLists), openOne(a, 1, checkLists), openOne(a, 2, checkLists)] #returns the value",
"if(state == 0): winnerLabel['text'] = 'draw' elif(state == playerSide): winnerLabel['text'] = 'player wins'",
"return result #makes the best possible amongst all of the possible moves def",
"playerSide, computerSide, theBoard playerSide = playAsWhich.get() if(playerSide == 1): computerSide = 2 else:",
"radioFrame.grid(row=3, column=1, sticky=N+S+E+W) Grid.rowconfigure(radioFrame, 0, weight=1) Grid.columnconfigure(radioFrame, 0, weight=1) Grid.columnconfigure(radioFrame, 1, weight=1) r1",
"r in range(5): Grid.rowconfigure(frame, r, weight=1) for c in range(3): Grid.columnconfigure(frame, c, weight=1)",
"empty spaces in a row/col/diagonal def openOne(board, x, a=[]): result = 0 if(a",
"1 #x win elif(threeInARow(board, 2, checkLists)): return 2 #o win elif(board.count(0) != 0):",
"== []): a = getCheckLists(board) for c in a: if(c.count(x) == 1 and",
"list of size 9 that contains information about the current tic # tac",
"= values[i] mPosition = positions[i] board[mPosition] = x #makes a random move def",
"in range(9) if(y == 1 or y == 4 or y == 7)])",
"def makeBestMove(board, weights, x): boards, values = [], [] positions = [i for",
"x's beside an empty space # # of places where there is 2",
"[] i = 0 for r in range(3): for c in range(3): button",
"the current tic # tac toe board #the board maps as follows: #",
"root = Tk() Grid.rowconfigure(root, 0, weight=1) Grid.columnconfigure(root, 0, weight=1) root.minsize(width=700, height=700) root.wm_title(\"SpartanTicTacToe\") spartanImage",
"# of places where there is an x/o and 2 empty spaces in",
"a: if(c.count(x) == 3): return True return False #returns the # of places",
"information about the current tic # tac toe board #the board maps as",
"a new tic tac toe game vs the AI def newGameClick(): global playerSide,",
"a: if(c.count(x) == 2 and c.count(0) == 1): result += 1 return result",
"range(len(positions)): position = positions[i] newBoard = copy.deepcopy(board) newBoard[position] = x features = getFeatures(newBoard)",
"for i in range(len(values)-1): values[i] = estimateMoveValue(getFeatures(train[i+1]), weights) for i in range(len(values)): board",
"and 2 empty spaces in a row/col/diagonal def openOne(board, x, a=[]): result =",
"else: makeBestMove(theBoard, oWeights, 2) updateButtons() winnerLabel['text'] = 'player turn' determineWinner() #this function is",
"getFeatures(newBoard) value = estimateMoveValue(features, weights) boards.append(newBoard) values.append(value) mValue = values[0] mPosition = positions[0]",
"#true if there is three in a row, false if not #x parameter",
"row (0 or 1) # is there 3 o's in a row (0",
"#the weights are updated by comparing the estimated move value with the actual",
"if(theBoard[i] != 0): b = buttons[i] if(theBoard[i] == 1): b['text'] = 'X' else:",
"spartanTextLink.bind(\"<Button-1>\", openWebsite) spartanLabel.bind(\"<Button-1>\", openWebsite) spartanTextLink.pack() for r in range(5): Grid.rowconfigure(frame, r, weight=1) for",
"there 3 x's in a row (0 or 1) # is there 3",
"buttons[i]['state'] = 'disabled' return state #update our tic tac toe board's graphical display",
"2): result += 1 return result #this function determines if the game is:",
"training data from the last played game #the weights are updated by comparing",
"started' theBoard = [0 for x in range(9)] for b in buttons: b['text']",
"as follows: # is there 3 x's in a row (0 or 1)",
"checkLists = getCheckLists(board) if(threeInARow(board, 1, checkLists)): return 1 #x win elif(threeInARow(board, 2, checkLists)):",
"text=\"new game\") winnerLabel.grid(row=3, column=2, sticky=N+S+W+E) spartanFrame = Frame(frame) spartanFrame.grid(columnspan=3, row=4, column=0) spartanLabel =",
"= ImageTk.PhotoImage(file=rootDirectory + '/resources/spartan-icon-small.png') root.call('wm', 'iconphoto', root._w, spartanImage) frame = Frame(root) frame.grid(row=0, column=0,",
"bottom left space # 7 == bottom center space # 8 == bottom",
"Tkinter import * from functools import partial from PIL import ImageTk #------------------------------------------------------------------------------------- #-------------------------------------------------------------------------------------",
"imaging library) #------------------------------------------------------------------------------------- #------------------------------------------------------------------------------------- #------------------------------------------------------------------------------------- #the board is a list of size 9",
"against the trained AI via a Tkinter # GUI. #------------------------------------------------------------------------------------- #Run via Python",
"2 #o win elif(board.count(0) != 0): return 3 #game still going else: return",
"parameter should be 1(x) or 2(o) def threeInARow(board, x, a=[]): if(a == []):",
"of a tic tac toeboard #the features are as follows: # is there",
"#update our weights for j in range(len(weights)): weights[j] = weights[j] +(learnConstant*(value-estimate)*features[j]) #initialize our",
"def openWebsite(event): webbrowser.open_new('http://www.spartanengineer.com') #the following code sets up the Tkinter GUI for playing",
"elif(threeInARow(board, 2, checkLists)): return 2 #o win elif(board.count(0) != 0): return 3 #game",
"'disabled' return state #update our tic tac toe board's graphical display def updateButtons():",
"if(y == 2 or y == 5 or y == 8)]) b.append([board[y] for",
"#draw conv = {True:1, False:0} #returns a list of the features used to",
"if(c.count(x) == 3): return True return False #returns the # of places where",
"== center left space # 4 == center center space # 5 ==",
"# of places where there is 2 o's beside an empty space #",
"Tkinter # GUI. #------------------------------------------------------------------------------------- #Run via Python 2.7 #REQUIRES: pillow (python imaging library)",
"if(result == 0): values[len(values)-1] = 0 elif(result == x): values[len(values)-1] = 100 else:",
"weight=1) Grid.columnconfigure(root, 0, weight=1) root.minsize(width=700, height=700) root.wm_title(\"SpartanTicTacToe\") spartanImage = ImageTk.PhotoImage(file=rootDirectory + '/resources/spartan-icon-small.png') root.call('wm',",
"in a row (0 or 1) # # of places where there is",
"r1.invoke() r2 = Radiobutton(radioFrame, text=\"O?\", variable=playAsWhich, value=2) r2.grid(row=0, column=1, sticky=N+S+E+W) winnerLabel = Label(frame,",
"= [0 for x in range(9)] for b in buttons: b['text'] = '-'",
"checkLists)], conv[threeInARow(a, 2, checkLists)], twoInARow(a, 1, checkLists), twoInARow(a, 2, checkLists), openOne(a, 1, checkLists),",
"else: values[len(values)-1] = -100 for i in range(len(values)-1): values[i] = estimateMoveValue(getFeatures(train[i+1]), weights) for",
"train[i] features = getFeatures(board) value = values[i] estimate = estimateMoveValue(features, weights) #update our",
"checkLists)], twoInARow(a, 1, checkLists), twoInARow(a, 2, checkLists), openOne(a, 1, checkLists), openOne(a, 2, checkLists)]",
"01/29/17 #Description: This code uses machine learning to train a tic tac toe",
"moves def makeBestMove(board, weights, x): boards, values = [], [] positions = [i",
"def playGame(xWeights, oWeights, xTrain, oTrain): turn = 1 board = [0 for x",
"beside an empty space # # of places where there is 2 o's",
"== 1): makeMove() #this function loads up the spartan engineer website in a",
"vs the AI def newGameClick(): global playerSide, computerSide, theBoard playerSide = playAsWhich.get() if(playerSide",
"i in range(1, len(positions)): if(values[i] > mValue): mValue = values[i] mPosition = positions[i]",
"= Label(spartanFrame, text='www.spartanengineer.com', fg='blue', cursor='hand2') spartanTextLink.bind(\"<Button-1>\", openWebsite) spartanLabel.bind(\"<Button-1>\", openWebsite) spartanTextLink.pack() for r in",
"b.append([board[y] for y in range(9) if(y == 1 or y == 4 or",
"text=\"O?\", variable=playAsWhich, value=2) r2.grid(row=0, column=1, sticky=N+S+E+W) winnerLabel = Label(frame, text=\"new game\") winnerLabel.grid(row=3, column=2,",
"0): return 3 #game still going else: return 0 #draw conv = {True:1,",
"#------------------GUI Code-------------------------- #---------------------------------------------------- #determines if the game is still ongoing an updates the",
"= Frame(frame) radioFrame.grid(row=3, column=1, sticky=N+S+E+W) Grid.rowconfigure(radioFrame, 0, weight=1) Grid.columnconfigure(radioFrame, 0, weight=1) Grid.columnconfigure(radioFrame, 1,",
"1(x) or 2(o) def threeInARow(board, x, a=[]): if(a == []): a = getCheckLists(board)",
"range(9) if(board[i] == 0)] for i in range(len(positions)): position = positions[i] newBoard =",
"# 6 == bottom left space # 7 == bottom center space #",
"= [], [] result = playGame(xWeights, oWeights, xTrain, oTrain) updateWeights(xWeights, xTrain, result, 1)",
"tkFont.Font(family='Helvetica', size=72, weight='bold') buttons = [] i = 0 for r in range(3):",
"spartanTextLink = Label(spartanFrame, text='www.spartanengineer.com', fg='blue', cursor='hand2') spartanTextLink.bind(\"<Button-1>\", openWebsite) spartanLabel.bind(\"<Button-1>\", openWebsite) spartanTextLink.pack() for r",
"Button(frame, text=\"-\", command=partial(buttonClick, i)) button.grid(row=r, column=c, sticky=N+S+E+W) button['font'] = buttonFont button['state'] = 'disabled'",
"= 'computer wins' if(state != 3): for i in range(9): buttons[i]['state'] = 'disabled'",
"be 1(x) or 2(o) def threeInARow(board, x, a=[]): if(a == []): a =",
"a draw, win, and loss def updateWeights(weights, train, result, x): values = [0",
"computerSide = 1 winnerLabel['text'] = 'game started' theBoard = [0 for x in",
"contains information about the current tic # tac toe board #the board maps",
"xTrain, result, 1) updateWeights(oWeights, oTrain, result, 2) print(\"finished training our tic tac toe",
"values[len(values)-1] = 0 elif(result == x): values[len(values)-1] = 100 else: values[len(values)-1] = -100",
"or y == 5 or y == 8)]) b.append([board[y] for y in range(9)",
"button['state'] = 'disabled' buttons.append(button) i += 1 newGameButton = Button(frame, command=newGameClick, text=\"New Game?\")",
"# is there 3 o's in a row (0 or 1) # #",
"based on the features (of the board) and their respective weights def estimateMoveValue(features,",
"a = board checkLists = getCheckLists(a) return [conv[threeInARow(a, 1, checkLists)], conv[threeInARow(a, 2, checkLists)],",
"or y == 8)]) #diagonal b.append([board[y] for y in range(9) if(y == 2",
"in range(trainingIterations): xTrain, oTrain = [], [] result = playGame(xWeights, oWeights, xTrain, oTrain)",
"the last played game #the weights are updated by comparing the estimated move",
"'player turn' determineWinner() #this function is called when on the board buttons are",
"in range(len(positions)): position = positions[i] newBoard = copy.deepcopy(board) newBoard[position] = x features =",
"of places where there is an x/o and 2 empty spaces in a",
"r2.grid(row=0, column=1, sticky=N+S+E+W) winnerLabel = Label(frame, text=\"new game\") winnerLabel.grid(row=3, column=2, sticky=N+S+W+E) spartanFrame =",
"#------------------------------------------------------------------------------------- #------------------------------------------------------------------------------------- #the board is a list of size 9 that contains information",
"result = 0 for i in range(len(features)): result += (features[i] * weights[i]) return",
"def newGameClick(): global playerSide, computerSide, theBoard playerSide = playAsWhich.get() if(playerSide == 1): computerSide",
"in a row/col/diagonal def twoInARow(board, x, a=[]): result = 0 if(a == []):",
"y in range(9) if(y == 0 or y == 3 or y ==",
"== center right space # 6 == bottom left space # 7 ==",
"= [], [] positions = [i for i in range(9) if(board[i] == 0)]",
"the trained AI via a Tkinter # GUI. #------------------------------------------------------------------------------------- #Run via Python 2.7",
"allow playing against the trained AI via a Tkinter # GUI. #------------------------------------------------------------------------------------- #Run",
"checkLists)): return 1 #x win elif(threeInARow(board, 2, checkLists)): return 2 #o win elif(board.count(0)",
"toeboard #the features are as follows: # is there 3 x's in a",
"possible moves def makeBestMove(board, weights, x): boards, values = [], [] positions =",
"to play against the AI\") #---------------------------------------------------- #------------------GUI Code-------------------------- #---------------------------------------------------- #determines if the game",
"for i in range(len(features)): result += (features[i] * weights[i]) return result #makes the",
"learning to train a tic tac toe game AI. # It also includes",
"against each other in order to train our AI's def playGame(xWeights, oWeights, xTrain,",
"there is an x/o and 2 empty spaces in a row/col/diagonal def openOne(board,",
"n_features = 6 oWeights = [initialWeight for i in range(n_features)] xWeights = [initialWeight",
"result += 1 return result #this function determines if the game is: ongoing,",
"winnerLabel['text'] = 'player turn' determineWinner() #this function is called when on the board",
"= determineWinner() if(state == 3): makeMove() #this function starts a new tic tac",
"winnerLabel = Label(frame, text=\"new game\") winnerLabel.grid(row=3, column=2, sticky=N+S+W+E) spartanFrame = Frame(frame) spartanFrame.grid(columnspan=3, row=4,",
"label correctly def determineWinner(): state = getGameState(theBoard) if(state == 0): winnerLabel['text'] = 'draw'",
"for x, a win for o def getGameState(board): checkLists = getCheckLists(board) if(threeInARow(board, 1,",
"column=1, sticky=N+S+E+W) winnerLabel = Label(frame, text=\"new game\") winnerLabel.grid(row=3, column=2, sticky=N+S+W+E) spartanFrame = Frame(frame)",
"result, x): values = [0 for i in range(len(train))] if(result == 0): values[len(values)-1]",
"x/o's & an empty space in a row/col/diagonal def twoInARow(board, x, a=[]): result",
"#x parameter should be 1(x) or 2(o) def threeInARow(board, x, a=[]): if(a ==",
"the AI root = Tk() Grid.rowconfigure(root, 0, weight=1) Grid.columnconfigure(root, 0, weight=1) root.minsize(width=700, height=700)",
"a random move def makeRandomMove(board, x): a = [i for i in range(9)",
"spartanLabel.bind(\"<Button-1>\", openWebsite) spartanTextLink.pack() for r in range(5): Grid.rowconfigure(frame, r, weight=1) for c in",
"function starts a new tic tac toe game vs the AI def newGameClick():",
"up the Tkinter GUI for playing against the AI root = Tk() Grid.rowconfigure(root,",
"# 2 == top right space # 3 == center left space #",
"is 2 o's beside an empty space # # of places where there",
"IntVar() radioFrame = Frame(frame) radioFrame.grid(row=3, column=1, sticky=N+S+E+W) Grid.rowconfigure(radioFrame, 0, weight=1) Grid.columnconfigure(radioFrame, 0, weight=1)",
"2.7 #REQUIRES: pillow (python imaging library) #------------------------------------------------------------------------------------- #------------------------------------------------------------------------------------- #------------------------------------------------------------------------------------- #the board is a",
"(this may take a minute or two...)\" % trainingIterations) for i in range(trainingIterations):",
"board #the board maps as follows: # 0 == top left space #",
"(of the board) and their respective weights def estimateMoveValue(features, weights): result = 0",
"getCheckLists(a) return [conv[threeInARow(a, 1, checkLists)], conv[threeInARow(a, 2, checkLists)], twoInARow(a, 1, checkLists), twoInARow(a, 2,",
"b #true if there is three in a row, false if not #x",
"pit AI's against each other in order to train our AI's def playGame(xWeights,",
"are used for a draw, win, and loss def updateWeights(weights, train, result, x):",
"#Description: This code uses machine learning to train a tic tac toe game",
"for r in range(5): Grid.rowconfigure(frame, r, weight=1) for c in range(3): Grid.columnconfigure(frame, c,",
"b.append([board[y] for y in range(9) if(y == 2 or y == 4 or",
"command=partial(buttonClick, i)) button.grid(row=r, column=c, sticky=N+S+E+W) button['font'] = buttonFont button['state'] = 'disabled' buttons.append(button) i",
"row/col/diagonal def twoInARow(board, x, a=[]): result = 0 if(a == []): a =",
"print(xWeights) print(oWeights) print(\"launching the GUI, this allows the user to play against the",
"8)]) #diagonal b.append([board[y] for y in range(9) if(y == 2 or y ==",
"= [initialWeight for i in range(n_features)] xWeights = [initialWeight for i in range(n_features)]",
"bottom center space # 8 == bottom right space #value mapping for a",
"-100 are used for a draw, win, and loss def updateWeights(weights, train, result,",
"is there 3 o's in a row (0 or 1) # # of",
"#------------------------------------------------------------------------------------- #------------------------------------------------------------------------------------- #------------------------------------------------------------------------------------- #the board is a list of size 9 that contains",
"result = 0 if(a == []): a = getCheckLists(board) for c in a:",
"b['state'] = 'normal' if(computerSide == 1): makeMove() #this function loads up the spartan",
"in range(3): button = Button(frame, text=\"-\", command=partial(buttonClick, i)) button.grid(row=r, column=c, sticky=N+S+E+W) button['font'] =",
"= [i for i in range(9) if(board[i] == 0)] for i in range(len(positions)):",
"'computer turn' state = determineWinner() if(state == 3): makeMove() #this function starts a",
"of places where there is 2 x's beside an empty space # #",
"= 2 else: turn = 1 gameState = getGameState(board) return gameState #update our",
"6 oWeights = [initialWeight for i in range(n_features)] xWeights = [initialWeight for i",
"result, 2) print(\"finished training our tic tac toe AI!!!\") print(\"final weights: \") print(xWeights)",
"of the possible moves def makeBestMove(board, weights, x): boards, values = [], []",
"2, checkLists)], twoInARow(a, 1, checkLists), twoInARow(a, 2, checkLists), openOne(a, 1, checkLists), openOne(a, 2,",
"0, weight=1) Grid.columnconfigure(radioFrame, 0, weight=1) Grid.columnconfigure(radioFrame, 1, weight=1) r1 = Radiobutton(radioFrame, text=\"X?\", variable=playAsWhich,",
"x, a=[]): if(a == []): a = getCheckLists(board) for c in a: if(c.count(x)",
"i in range(n_features)] xWeights = [initialWeight for i in range(n_features)] trainingIterations = 10000",
"buttons: b['text'] = '-' b['state'] = 'normal' if(computerSide == 1): makeMove() #this function",
"else: return 0 #draw conv = {True:1, False:0} #returns a list of the",
"website in a browser def openWebsite(event): webbrowser.open_new('http://www.spartanengineer.com') #the following code sets up the",
"weights def estimateMoveValue(features, weights): result = 0 for i in range(len(features)): result +=",
"[initialWeight for i in range(n_features)] trainingIterations = 10000 print(\"training our tic tac toe",
"estimateMoveValue(features, weights) #update our weights for j in range(len(weights)): weights[j] = weights[j] +(learnConstant*(value-estimate)*features[j])",
"i += 1 newGameButton = Button(frame, command=newGameClick, text=\"New Game?\") newGameButton.grid(row=3, column=0, sticky=N+S+E+W) playAsWhich",
"empty spaces in a row/col/diagonal # # of places where there is an",
"def buttonClick(n): theBoard[n] = playerSide updateButtons() winnerLabel['text'] = 'computer turn' state = determineWinner()",
"b['state'] = 'disabled' #makes a computer move def makeMove(): if(computerSide == 1): makeBestMove(theBoard,",
"for c in range(3): button = Button(frame, text=\"-\", command=partial(buttonClick, i)) button.grid(row=r, column=c, sticky=N+S+E+W)",
"value = estimateMoveValue(features, weights) boards.append(newBoard) values.append(value) mValue = values[0] mPosition = positions[0] for",
"weights[j] +(learnConstant*(value-estimate)*features[j]) #initialize our weights, the value of 0.5 is arbitrarily picked initialWeight",
"last played game #the weights are updated by comparing the estimated move value",
"= getGameState(theBoard) if(state == 0): winnerLabel['text'] = 'draw' elif(state == playerSide): winnerLabel['text'] =",
"in range(1, len(positions)): if(values[i] > mValue): mValue = values[i] mPosition = positions[i] board[mPosition]",
"center space # 5 == center right space # 6 == bottom left",
"#the board maps as follows: # 0 == top left space # 1",
"maps as follows: # 0 == top left space # 1 == top",
"weights[i]) return result #makes the best possible amongst all of the possible moves",
"there is 2 x/o's & an empty space in a row/col/diagonal def twoInARow(board,",
"# # of places where there is an o and two empty spaces",
"return True return False #returns the # of places where there is 2",
"in range(9): if(theBoard[i] != 0): b = buttons[i] if(theBoard[i] == 1): b['text'] =",
"or y == 4 or y == 6)]) return b #true if there",
"#returns a list of the features used to evaluate the value of a",
"= estimateMoveValue(features, weights) boards.append(newBoard) values.append(value) mValue = values[0] mPosition = positions[0] for i",
"value=2) r2.grid(row=0, column=1, sticky=N+S+E+W) winnerLabel = Label(frame, text=\"new game\") winnerLabel.grid(row=3, column=2, sticky=N+S+W+E) spartanFrame",
"1, checkLists)): return 1 #x win elif(threeInARow(board, 2, checkLists)): return 2 #o win",
"weights) boards.append(newBoard) values.append(value) mValue = values[0] mPosition = positions[0] for i in range(1,",
"for i in range(9) if(board[i] == 0)] for i in range(len(positions)): position =",
"[] positions = [i for i in range(9) if(board[i] == 0)] for i",
"else: computerSide = 1 winnerLabel['text'] = 'game started' theBoard = [0 for x",
"mapping for a space in each board: # 0 == empty space #",
"4 or y == 7)]) b.append([board[y] for y in range(9) if(y == 2",
"is three in a row, false if not #x parameter should be 1(x)",
"or y == 3 or y == 6)]) #vertical b.append([board[y] for y in",
"= [] b.append(board[0:3]) #horizontal b.append(board[3:6]) b.append(board[6:9]) b.append([board[y] for y in range(9) if(y ==",
"= Tk() Grid.rowconfigure(root, 0, weight=1) Grid.columnconfigure(root, 0, weight=1) root.minsize(width=700, height=700) root.wm_title(\"SpartanTicTacToe\") spartanImage =",
"if(theBoard[i] == 1): b['text'] = 'X' else: b['text'] = 'O' b['state'] = 'disabled'",
"also includes code to allow playing against the trained AI via a Tkinter",
"from PIL import ImageTk #------------------------------------------------------------------------------------- #------------------------------------------------------------------------------------- #------------------------------------------------------------------------------------- #Author: <NAME> #Date: 01/29/17 #Description: This",
"positions[0] for i in range(1, len(positions)): if(values[i] > mValue): mValue = values[i] mPosition",
"tic tac toe AI for %d games (this may take a minute or",
"len(positions)): if(values[i] > mValue): mValue = values[i] mPosition = positions[i] board[mPosition] = x",
"y == 6)]) return b #true if there is three in a row,",
"= buttonFont button['state'] = 'disabled' buttons.append(button) i += 1 newGameButton = Button(frame, command=newGameClick,",
"Grid.columnconfigure(radioFrame, 0, weight=1) Grid.columnconfigure(radioFrame, 1, weight=1) r1 = Radiobutton(radioFrame, text=\"X?\", variable=playAsWhich, value=1) r1.grid(row=0,",
"[0 for i in range(len(train))] if(result == 0): values[len(values)-1] = 0 elif(result ==",
"in a: if(c.count(x) == 2 and c.count(0) == 1): result += 1 return",
"8)]) b.append([board[y] for y in range(9) if(y == 0 or y == 4",
"range(9): if(theBoard[i] != 0): b = buttons[i] if(theBoard[i] == 1): b['text'] = 'X'",
"for i in range(9) if(board[i] == 0)] randomNum = random.randint(0, len(a)-1) board[a[randomNum]] =",
"tac toe board #the board maps as follows: # 0 == top left",
"makeBestMove(board, oWeights, turn) oTrain.append(copy.deepcopy(board)) if(turn == 1): turn = 2 else: turn =",
"1 return result #returns the # of places where there is an x/o",
"checkLists)): return 2 #o win elif(board.count(0) != 0): return 3 #game still going",
"the estimated move value with the actual move value #values of 0, 100,",
"False #returns the # of places where there is 2 x/o's & an",
"in a row, false if not #x parameter should be 1(x) or 2(o)",
"#------------------------------------------------------------------------------------- #------------------------------------------------------------------------------------- #Author: <NAME> #Date: 01/29/17 #Description: This code uses machine learning to",
"b.append([board[y] for y in range(9) if(y == 2 or y == 5 or",
"function loads up the spartan engineer website in a browser def openWebsite(event): webbrowser.open_new('http://www.spartanengineer.com')",
"of the features used to evaluate the value of a tic tac toeboard",
"print('----------------------------------------------------') learnConstant = 0.1 # learning constant def getCheckLists(board): b = [] b.append(board[0:3])",
"tac toe board's graphical display def updateButtons(): for i in range(9): if(theBoard[i] !=",
"xTrain, oTrain) updateWeights(xWeights, xTrain, result, 1) updateWeights(oWeights, oTrain, result, 2) print(\"finished training our",
"newGameClick(): global playerSide, computerSide, theBoard playerSide = playAsWhich.get() if(playerSide == 1): computerSide =",
"== x space # 2 == o space rootDirectory = os.path.dirname(os.path.realpath(__file__)) print('----------------------------------------------------') print('----------------------------------------------------')",
"= positions[0] for i in range(1, len(positions)): if(values[i] > mValue): mValue = values[i]",
"the # of places where there is an x/o and 2 empty spaces",
"a row (0 or 1) # # of places where there is 2",
"if(a == []): a = getCheckLists(board) for c in a: if(c.count(x) == 1",
"random.randint(0, len(a)-1) board[a[randomNum]] = x #plays a tic-tac-toe game between the X and",
"a row, false if not #x parameter should be 1(x) or 2(o) def",
"2) updateButtons() winnerLabel['text'] = 'player turn' determineWinner() #this function is called when on",
"a row/col/diagonal def getFeatures(board): a = board checkLists = getCheckLists(a) return [conv[threeInARow(a, 1,",
"if(c.count(x) == 1 and c.count(0) == 2): result += 1 return result #this",
"is an x/o and 2 empty spaces in a row/col/diagonal def openOne(board, x,",
"= 1 winnerLabel['text'] = 'game started' theBoard = [0 for x in range(9)]",
"each board: # 0 == empty space # 1 == x space #",
"beside an empty space # # of places where there is an x",
"there 3 o's in a row (0 or 1) # # of places",
"1 == top center space # 2 == top right space # 3",
"there is an o and two empty spaces in a row/col/diagonal def getFeatures(board):",
"= 'game started' theBoard = [0 for x in range(9)] for b in",
"tic tac toeboard #the features are as follows: # is there 3 x's",
"best possible amongst all of the possible moves def makeBestMove(board, weights, x): boards,",
"for y in range(9) if(y == 0 or y == 3 or y",
"6)]) #vertical b.append([board[y] for y in range(9) if(y == 1 or y ==",
"pillow (python imaging library) #------------------------------------------------------------------------------------- #------------------------------------------------------------------------------------- #------------------------------------------------------------------------------------- #the board is a list of",
"2 and c.count(0) == 1): result += 1 return result #returns the #",
"mValue = values[i] mPosition = positions[i] board[mPosition] = x #makes a random move",
"getGameState(theBoard) if(state == 0): winnerLabel['text'] = 'draw' elif(state == playerSide): winnerLabel['text'] = 'player",
"sticky=N+S+W+E) spartanFrame = Frame(frame) spartanFrame.grid(columnspan=3, row=4, column=0) spartanLabel = Label(spartanFrame, image=spartanImage, cursor='hand2') spartanLabel.pack()",
"range(9) if(y == 2 or y == 5 or y == 8)]) b.append([board[y]",
"= x #makes a random move def makeRandomMove(board, x): a = [i for",
"Frame(frame) spartanFrame.grid(columnspan=3, row=4, column=0) spartanLabel = Label(spartanFrame, image=spartanImage, cursor='hand2') spartanLabel.pack() spartanTextLink = Label(spartanFrame,",
"print('----------------------------------------------------') print('----------------------------------------------------') learnConstant = 0.1 # learning constant def getCheckLists(board): b = []",
"in range(9): buttons[i]['state'] = 'disabled' return state #update our tic tac toe board's",
"#REQUIRES: pillow (python imaging library) #------------------------------------------------------------------------------------- #------------------------------------------------------------------------------------- #------------------------------------------------------------------------------------- #the board is a list",
"x #plays a tic-tac-toe game between the X and O AI #we pit",
"import * from functools import partial from PIL import ImageTk #------------------------------------------------------------------------------------- #------------------------------------------------------------------------------------- #-------------------------------------------------------------------------------------",
"Radiobutton(radioFrame, text=\"X?\", variable=playAsWhich, value=1) r1.grid(row=0, column=0, sticky=N+S+E+W) r1.invoke() r2 = Radiobutton(radioFrame, text=\"O?\", variable=playAsWhich,",
"our weights, the value of 0.5 is arbitrarily picked initialWeight = 0.5 n_features",
"= copy.deepcopy(board) newBoard[position] = x features = getFeatures(newBoard) value = estimateMoveValue(features, weights) boards.append(newBoard)",
"1): makeBestMove(board, xWeights, turn) xTrain.append(copy.deepcopy(board)) else: makeBestMove(board, oWeights, turn) oTrain.append(copy.deepcopy(board)) if(turn == 1):",
"4 or y == 6)]) return b #true if there is three in",
"== 4 or y == 7)]) b.append([board[y] for y in range(9) if(y ==",
"winnerLabel.grid(row=3, column=2, sticky=N+S+W+E) spartanFrame = Frame(frame) spartanFrame.grid(columnspan=3, row=4, column=0) spartanLabel = Label(spartanFrame, image=spartanImage,",
"tic tac toe AI!!!\") print(\"final weights: \") print(xWeights) print(oWeights) print(\"launching the GUI, this",
"= 'X' else: b['text'] = 'O' b['state'] = 'disabled' #makes a computer move",
"= Label(frame, text=\"new game\") winnerLabel.grid(row=3, column=2, sticky=N+S+W+E) spartanFrame = Frame(frame) spartanFrame.grid(columnspan=3, row=4, column=0)",
"<gh_stars>0 import copy, random, tkFont, time, webbrowser, os from Tkinter import * from",
"new tic tac toe game vs the AI def newGameClick(): global playerSide, computerSide,",
"7 == bottom center space # 8 == bottom right space #value mapping",
"= x features = getFeatures(newBoard) value = estimateMoveValue(features, weights) boards.append(newBoard) values.append(value) mValue =",
"y in range(9) if(y == 1 or y == 4 or y ==",
"library) #------------------------------------------------------------------------------------- #------------------------------------------------------------------------------------- #------------------------------------------------------------------------------------- #the board is a list of size 9 that",
"for i in range(9): buttons[i]['state'] = 'disabled' return state #update our tic tac",
"playing against the AI root = Tk() Grid.rowconfigure(root, 0, weight=1) Grid.columnconfigure(root, 0, weight=1)",
"where there is an x/o and 2 empty spaces in a row/col/diagonal def",
"Frame(root) frame.grid(row=0, column=0, sticky=N+S+E+W) buttonFont = tkFont.Font(family='Helvetica', size=72, weight='bold') buttons = [] i",
"== 3): return True return False #returns the # of places where there",
"values.append(value) mValue = values[0] mPosition = positions[0] for i in range(1, len(positions)): if(values[i]",
"value of 0.5 is arbitrarily picked initialWeight = 0.5 n_features = 6 oWeights",
"elif(board.count(0) != 0): return 3 #game still going else: return 0 #draw conv",
"computerSide): winnerLabel['text'] = 'computer wins' if(state != 3): for i in range(9): buttons[i]['state']",
"buttons[i] if(theBoard[i] == 1): b['text'] = 'X' else: b['text'] = 'O' b['state'] =",
"def threeInARow(board, x, a=[]): if(a == []): a = getCheckLists(board) for c in",
"a=[]): result = 0 if(a == []): a = getCheckLists(board) for c in",
"or 2(o) def threeInARow(board, x, a=[]): if(a == []): a = getCheckLists(board) for",
"left space # 1 == top center space # 2 == top right",
"weight=1) r1 = Radiobutton(radioFrame, text=\"X?\", variable=playAsWhich, value=1) r1.grid(row=0, column=0, sticky=N+S+E+W) r1.invoke() r2 =",
"return 2 #o win elif(board.count(0) != 0): return 3 #game still going else:",
"if(computerSide == 1): makeBestMove(theBoard, xWeights, 1) else: makeBestMove(theBoard, oWeights, 2) updateButtons() winnerLabel['text'] =",
"== 1): result += 1 return result #returns the # of places where",
"evaluate the value of a tic tac toeboard #the features are as follows:",
"# 1 == top center space # 2 == top right space #",
"variable=playAsWhich, value=2) r2.grid(row=0, column=1, sticky=N+S+E+W) winnerLabel = Label(frame, text=\"new game\") winnerLabel.grid(row=3, column=2, sticky=N+S+W+E)",
"Label(spartanFrame, image=spartanImage, cursor='hand2') spartanLabel.pack() spartanTextLink = Label(spartanFrame, text='www.spartanengineer.com', fg='blue', cursor='hand2') spartanTextLink.bind(\"<Button-1>\", openWebsite) spartanLabel.bind(\"<Button-1>\",",
"return result #returns the # of places where there is an x/o and",
"y == 8)]) #diagonal b.append([board[y] for y in range(9) if(y == 2 or",
"top right space # 3 == center left space # 4 == center",
"cursor='hand2') spartanTextLink.bind(\"<Button-1>\", openWebsite) spartanLabel.bind(\"<Button-1>\", openWebsite) spartanTextLink.pack() for r in range(5): Grid.rowconfigure(frame, r, weight=1)",
"tic-tac-toe game between the X and O AI #we pit AI's against each",
"= x #plays a tic-tac-toe game between the X and O AI #we",
"i in range(len(values)-1): values[i] = estimateMoveValue(getFeatures(train[i+1]), weights) for i in range(len(values)): board =",
"the GUI, this allows the user to play against the AI\") #---------------------------------------------------- #------------------GUI",
"twoInARow(a, 1, checkLists), twoInARow(a, 2, checkLists), openOne(a, 1, checkLists), openOne(a, 2, checkLists)] #returns",
"function determines if the game is: ongoing, a draw, a win for x,",
"turn' determineWinner() #this function is called when on the board buttons are clicked",
"places where there is an x/o and 2 empty spaces in a row/col/diagonal",
"== top left space # 1 == top center space # 2 ==",
"winnerLabel['text'] = 'player wins' elif(state == computerSide): winnerLabel['text'] = 'computer wins' if(state !=",
"values[len(values)-1] = -100 for i in range(len(values)-1): values[i] = estimateMoveValue(getFeatures(train[i+1]), weights) for i",
"= Button(frame, text=\"-\", command=partial(buttonClick, i)) button.grid(row=r, column=c, sticky=N+S+E+W) button['font'] = buttonFont button['state'] =",
"= getFeatures(board) value = values[i] estimate = estimateMoveValue(features, weights) #update our weights for",
"false if not #x parameter should be 1(x) or 2(o) def threeInARow(board, x,",
"values[i] = estimateMoveValue(getFeatures(train[i+1]), weights) for i in range(len(values)): board = train[i] features =",
"right space # 6 == bottom left space # 7 == bottom center",
"for i in range(len(values)): board = train[i] features = getFeatures(board) value = values[i]",
"= [initialWeight for i in range(n_features)] trainingIterations = 10000 print(\"training our tic tac",
"getFeatures(board) value = values[i] estimate = estimateMoveValue(features, weights) #update our weights for j",
"win elif(board.count(0) != 0): return 3 #game still going else: return 0 #draw",
"result = playGame(xWeights, oWeights, xTrain, oTrain) updateWeights(xWeights, xTrain, result, 1) updateWeights(oWeights, oTrain, result,",
"if there is three in a row, false if not #x parameter should",
"playing against the trained AI via a Tkinter # GUI. #------------------------------------------------------------------------------------- #Run via",
"size=72, weight='bold') buttons = [] i = 0 for r in range(3): for",
"positions = [i for i in range(9) if(board[i] == 0)] for i in",
"column=c, sticky=N+S+E+W) button['font'] = buttonFont button['state'] = 'disabled' buttons.append(button) i += 1 newGameButton",
"weight=1) Grid.columnconfigure(radioFrame, 0, weight=1) Grid.columnconfigure(radioFrame, 1, weight=1) r1 = Radiobutton(radioFrame, text=\"X?\", variable=playAsWhich, value=1)",
"3): if(turn == 1): makeBestMove(board, xWeights, turn) xTrain.append(copy.deepcopy(board)) else: makeBestMove(board, oWeights, turn) oTrain.append(copy.deepcopy(board))",
"spartanLabel = Label(spartanFrame, image=spartanImage, cursor='hand2') spartanLabel.pack() spartanTextLink = Label(spartanFrame, text='www.spartanengineer.com', fg='blue', cursor='hand2') spartanTextLink.bind(\"<Button-1>\",",
"getCheckLists(board): b = [] b.append(board[0:3]) #horizontal b.append(board[3:6]) b.append(board[6:9]) b.append([board[y] for y in range(9)",
"radioFrame = Frame(frame) radioFrame.grid(row=3, column=1, sticky=N+S+E+W) Grid.rowconfigure(radioFrame, 0, weight=1) Grid.columnconfigure(radioFrame, 0, weight=1) Grid.columnconfigure(radioFrame,",
"weights) #update our weights for j in range(len(weights)): weights[j] = weights[j] +(learnConstant*(value-estimate)*features[j]) #initialize",
"result += (features[i] * weights[i]) return result #makes the best possible amongst all",
"ongoing an updates the label correctly def determineWinner(): state = getGameState(theBoard) if(state ==",
"played game #the weights are updated by comparing the estimated move value with",
"via Python 2.7 #REQUIRES: pillow (python imaging library) #------------------------------------------------------------------------------------- #------------------------------------------------------------------------------------- #------------------------------------------------------------------------------------- #the board",
"playAsWhich = IntVar() radioFrame = Frame(frame) radioFrame.grid(row=3, column=1, sticky=N+S+E+W) Grid.rowconfigure(radioFrame, 0, weight=1) Grid.columnconfigure(radioFrame,",
"follows: # 0 == top left space # 1 == top center space",
"board = train[i] features = getFeatures(board) value = values[i] estimate = estimateMoveValue(features, weights)",
"def getCheckLists(board): b = [] b.append(board[0:3]) #horizontal b.append(board[3:6]) b.append(board[6:9]) b.append([board[y] for y in",
"tic tac toe game AI. # It also includes code to allow playing",
"if(turn == 1): makeBestMove(board, xWeights, turn) xTrain.append(copy.deepcopy(board)) else: makeBestMove(board, oWeights, turn) oTrain.append(copy.deepcopy(board)) if(turn",
"places where there is an x and two empty spaces in a row/col/diagonal",
"8 == bottom right space #value mapping for a space in each board:",
"else: b['text'] = 'O' b['state'] = 'disabled' #makes a computer move def makeMove():",
"a = getCheckLists(board) for c in a: if(c.count(x) == 1 and c.count(0) ==",
"= 'draw' elif(state == playerSide): winnerLabel['text'] = 'player wins' elif(state == computerSide): winnerLabel['text']",
"weights based upon the training data from the last played game #the weights",
"for i in range(len(positions)): position = positions[i] newBoard = copy.deepcopy(board) newBoard[position] = x",
"board[mPosition] = x #makes a random move def makeRandomMove(board, x): a = [i",
"updateWeights(xWeights, xTrain, result, 1) updateWeights(oWeights, oTrain, result, 2) print(\"finished training our tic tac",
"picked initialWeight = 0.5 n_features = 6 oWeights = [initialWeight for i in",
"webbrowser, os from Tkinter import * from functools import partial from PIL import",
"tac toe game AI. # It also includes code to allow playing against",
"the board) and their respective weights def estimateMoveValue(features, weights): result = 0 for",
"constant def getCheckLists(board): b = [] b.append(board[0:3]) #horizontal b.append(board[3:6]) b.append(board[6:9]) b.append([board[y] for y",
"result #returns the # of places where there is an x/o and 2",
"in range(len(train))] if(result == 0): values[len(values)-1] = 0 elif(result == x): values[len(values)-1] =",
"x/o and 2 empty spaces in a row/col/diagonal def openOne(board, x, a=[]): result",
"c in a: if(c.count(x) == 3): return True return False #returns the #",
"result #this function determines if the game is: ongoing, a draw, a win",
"== 6)]) return b #true if there is three in a row, false",
"toe game vs the AI def newGameClick(): global playerSide, computerSide, theBoard playerSide =",
"computerSide = 2 else: computerSide = 1 winnerLabel['text'] = 'game started' theBoard =",
"def updateWeights(weights, train, result, x): values = [0 for i in range(len(train))] if(result",
"#update our weights based upon the training data from the last played game",
"#vertical b.append([board[y] for y in range(9) if(y == 1 or y == 4",
"empty space # # of places where there is 2 o's beside an",
"== 3): if(turn == 1): makeBestMove(board, xWeights, turn) xTrain.append(copy.deepcopy(board)) else: makeBestMove(board, oWeights, turn)",
"space # 6 == bottom left space # 7 == bottom center space",
"oWeights = [initialWeight for i in range(n_features)] xWeights = [initialWeight for i in",
"a row/col/diagonal def openOne(board, x, a=[]): result = 0 if(a == []): a",
"y in range(9) if(y == 2 or y == 5 or y ==",
"command=newGameClick, text=\"New Game?\") newGameButton.grid(row=3, column=0, sticky=N+S+E+W) playAsWhich = IntVar() radioFrame = Frame(frame) radioFrame.grid(row=3,",
"2 or y == 4 or y == 6)]) return b #true if",
"still ongoing an updates the label correctly def determineWinner(): state = getGameState(theBoard) if(state",
"return result #this function determines if the game is: ongoing, a draw, a",
"of places where there is 2 o's beside an empty space # #",
"#---------------------------------------------------- #------------------GUI Code-------------------------- #---------------------------------------------------- #determines if the game is still ongoing an updates",
"values[i] mPosition = positions[i] board[mPosition] = x #makes a random move def makeRandomMove(board,",
"== 2): result += 1 return result #this function determines if the game",
"in buttons: b['text'] = '-' b['state'] = 'normal' if(computerSide == 1): makeMove() #this",
"space rootDirectory = os.path.dirname(os.path.realpath(__file__)) print('----------------------------------------------------') print('----------------------------------------------------') print('https://www.spartanengineer.com') print('----------------------------------------------------') print('----------------------------------------------------') learnConstant = 0.1 #",
"+(learnConstant*(value-estimate)*features[j]) #initialize our weights, the value of 0.5 is arbitrarily picked initialWeight =",
"or y == 4 or y == 8)]) #diagonal b.append([board[y] for y in",
"two empty spaces in a row/col/diagonal # # of places where there is",
"sticky=N+S+E+W) button['font'] = buttonFont button['state'] = 'disabled' buttons.append(button) i += 1 newGameButton =",
"button.grid(row=r, column=c, sticky=N+S+E+W) button['font'] = buttonFont button['state'] = 'disabled' buttons.append(button) i += 1",
"updateButtons(): for i in range(9): if(theBoard[i] != 0): b = buttons[i] if(theBoard[i] ==",
"i in range(9) if(board[i] == 0)] randomNum = random.randint(0, len(a)-1) board[a[randomNum]] = x",
"learning constant def getCheckLists(board): b = [] b.append(board[0:3]) #horizontal b.append(board[3:6]) b.append(board[6:9]) b.append([board[y] for",
"makeBestMove(theBoard, oWeights, 2) updateButtons() winnerLabel['text'] = 'player turn' determineWinner() #this function is called",
"4 == center center space # 5 == center right space # 6",
"+= 1 return result #returns the # of places where there is an",
"== 0)] for i in range(len(positions)): position = positions[i] newBoard = copy.deepcopy(board) newBoard[position]",
"0.5 is arbitrarily picked initialWeight = 0.5 n_features = 6 oWeights = [initialWeight",
"weight='bold') buttons = [] i = 0 for r in range(3): for c",
"for playing against the AI root = Tk() Grid.rowconfigure(root, 0, weight=1) Grid.columnconfigure(root, 0,",
"0 == top left space # 1 == top center space # 2",
"i in range(9) if(board[i] == 0)] for i in range(len(positions)): position = positions[i]",
"#------------------------------------------------------------------------------------- #the board is a list of size 9 that contains information about",
"#------------------------------------------------------------------------------------- #Author: <NAME> #Date: 01/29/17 #Description: This code uses machine learning to train",
"3): return True return False #returns the # of places where there is",
"result += 1 return result #returns the # of places where there is",
"oTrain, result, 2) print(\"finished training our tic tac toe AI!!!\") print(\"final weights: \")",
"x): a = [i for i in range(9) if(board[i] == 0)] randomNum =",
"two...)\" % trainingIterations) for i in range(trainingIterations): xTrain, oTrain = [], [] result",
"board is a list of size 9 that contains information about the current",
"# # of places where there is an x and two empty spaces",
"== empty space # 1 == x space # 2 == o space",
"0, 100, & -100 are used for a draw, win, and loss def",
"buttons are clicked def buttonClick(n): theBoard[n] = playerSide updateButtons() winnerLabel['text'] = 'computer turn'",
"game is: ongoing, a draw, a win for x, a win for o",
"game vs the AI def newGameClick(): global playerSide, computerSide, theBoard playerSide = playAsWhich.get()",
"6)]) return b #true if there is three in a row, false if",
"is arbitrarily picked initialWeight = 0.5 n_features = 6 oWeights = [initialWeight for",
"== computerSide): winnerLabel['text'] = 'computer wins' if(state != 3): for i in range(9):",
"b['text'] = 'X' else: b['text'] = 'O' b['state'] = 'disabled' #makes a computer",
"newGameButton.grid(row=3, column=0, sticky=N+S+E+W) playAsWhich = IntVar() radioFrame = Frame(frame) radioFrame.grid(row=3, column=1, sticky=N+S+E+W) Grid.rowconfigure(radioFrame,",
"the actual move value #values of 0, 100, & -100 are used for",
"range(9)] gameState = 3 while(gameState == 3): if(turn == 1): makeBestMove(board, xWeights, turn)",
"turn = 1 gameState = getGameState(board) return gameState #update our weights based upon",
"len(a)-1) board[a[randomNum]] = x #plays a tic-tac-toe game between the X and O",
"column=0, sticky=N+S+E+W) r1.invoke() r2 = Radiobutton(radioFrame, text=\"O?\", variable=playAsWhich, value=2) r2.grid(row=0, column=1, sticky=N+S+E+W) winnerLabel",
"root.call('wm', 'iconphoto', root._w, spartanImage) frame = Frame(root) frame.grid(row=0, column=0, sticky=N+S+E+W) buttonFont = tkFont.Font(family='Helvetica',",
"following code sets up the Tkinter GUI for playing against the AI root",
"correctly def determineWinner(): state = getGameState(theBoard) if(state == 0): winnerLabel['text'] = 'draw' elif(state",
"0 elif(result == x): values[len(values)-1] = 100 else: values[len(values)-1] = -100 for i",
"def openOne(board, x, a=[]): result = 0 if(a == []): a = getCheckLists(board)",
"user to play against the AI\") #---------------------------------------------------- #------------------GUI Code-------------------------- #---------------------------------------------------- #determines if the",
"cursor='hand2') spartanLabel.pack() spartanTextLink = Label(spartanFrame, text='www.spartanengineer.com', fg='blue', cursor='hand2') spartanTextLink.bind(\"<Button-1>\", openWebsite) spartanLabel.bind(\"<Button-1>\", openWebsite) spartanTextLink.pack()",
"{True:1, False:0} #returns a list of the features used to evaluate the value",
"is: ongoing, a draw, a win for x, a win for o def",
"+ '/resources/spartan-icon-small.png') root.call('wm', 'iconphoto', root._w, spartanImage) frame = Frame(root) frame.grid(row=0, column=0, sticky=N+S+E+W) buttonFont",
"Grid.rowconfigure(root, 0, weight=1) Grid.columnconfigure(root, 0, weight=1) root.minsize(width=700, height=700) root.wm_title(\"SpartanTicTacToe\") spartanImage = ImageTk.PhotoImage(file=rootDirectory +",
"gameState = getGameState(board) return gameState #update our weights based upon the training data",
"openOne(a, 2, checkLists)] #returns the value of a board based on the features",
"game #the weights are updated by comparing the estimated move value with the",
"is still ongoing an updates the label correctly def determineWinner(): state = getGameState(theBoard)",
"theBoard playerSide = playAsWhich.get() if(playerSide == 1): computerSide = 2 else: computerSide =",
"winnerLabel['text'] = 'draw' elif(state == playerSide): winnerLabel['text'] = 'player wins' elif(state == computerSide):",
"'player wins' elif(state == computerSide): winnerLabel['text'] = 'computer wins' if(state != 3): for",
"1, weight=1) r1 = Radiobutton(radioFrame, text=\"X?\", variable=playAsWhich, value=1) r1.grid(row=0, column=0, sticky=N+S+E+W) r1.invoke() r2",
"features are as follows: # is there 3 x's in a row (0",
"or two...)\" % trainingIterations) for i in range(trainingIterations): xTrain, oTrain = [], []",
"3 == center left space # 4 == center center space # 5",
"#makes the best possible amongst all of the possible moves def makeBestMove(board, weights,",
"b in buttons: b['text'] = '-' b['state'] = 'normal' if(computerSide == 1): makeMove()",
"in range(len(values)): board = train[i] features = getFeatures(board) value = values[i] estimate =",
"a tic tac toe game AI. # It also includes code to allow",
"toe game AI. # It also includes code to allow playing against the",
"y == 4 or y == 7)]) b.append([board[y] for y in range(9) if(y",
"or y == 6)]) #vertical b.append([board[y] for y in range(9) if(y == 1",
"in a row (0 or 1) # is there 3 o's in a",
"image=spartanImage, cursor='hand2') spartanLabel.pack() spartanTextLink = Label(spartanFrame, text='www.spartanengineer.com', fg='blue', cursor='hand2') spartanTextLink.bind(\"<Button-1>\", openWebsite) spartanLabel.bind(\"<Button-1>\", openWebsite)",
"# 7 == bottom center space # 8 == bottom right space #value",
"in range(9) if(y == 0 or y == 3 or y == 6)])",
"trained AI via a Tkinter # GUI. #------------------------------------------------------------------------------------- #Run via Python 2.7 #REQUIRES:",
"if(state == 3): makeMove() #this function starts a new tic tac toe game",
"if(y == 0 or y == 3 or y == 6)]) #vertical b.append([board[y]",
"ImageTk.PhotoImage(file=rootDirectory + '/resources/spartan-icon-small.png') root.call('wm', 'iconphoto', root._w, spartanImage) frame = Frame(root) frame.grid(row=0, column=0, sticky=N+S+E+W)",
"== 0 or y == 3 or y == 6)]) #vertical b.append([board[y] for",
"i in range(len(features)): result += (features[i] * weights[i]) return result #makes the best",
"y == 4 or y == 8)]) #diagonal b.append([board[y] for y in range(9)",
"sticky=N+S+E+W) winnerLabel = Label(frame, text=\"new game\") winnerLabel.grid(row=3, column=2, sticky=N+S+W+E) spartanFrame = Frame(frame) spartanFrame.grid(columnspan=3,",
"if(values[i] > mValue): mValue = values[i] mPosition = positions[i] board[mPosition] = x #makes",
"== x): values[len(values)-1] = 100 else: values[len(values)-1] = -100 for i in range(len(values)-1):",
"a win for o def getGameState(board): checkLists = getCheckLists(board) if(threeInARow(board, 1, checkLists)): return",
"estimateMoveValue(features, weights) boards.append(newBoard) values.append(value) mValue = values[0] mPosition = positions[0] for i in",
"1) updateWeights(oWeights, oTrain, result, 2) print(\"finished training our tic tac toe AI!!!\") print(\"final",
"button['font'] = buttonFont button['state'] = 'disabled' buttons.append(button) i += 1 newGameButton = Button(frame,",
"2, checkLists)] #returns the value of a board based on the features (of",
"# 0 == top left space # 1 == top center space #",
"print(\"training our tic tac toe AI for %d games (this may take a",
"5 or y == 8)]) b.append([board[y] for y in range(9) if(y == 0",
"= 0.1 # learning constant def getCheckLists(board): b = [] b.append(board[0:3]) #horizontal b.append(board[3:6])",
"O AI #we pit AI's against each other in order to train our",
"a row/col/diagonal # # of places where there is an o and two",
"[], [] positions = [i for i in range(9) if(board[i] == 0)] for",
"there is 2 x's beside an empty space # # of places where",
"a = getCheckLists(board) for c in a: if(c.count(x) == 2 and c.count(0) ==",
"text='www.spartanengineer.com', fg='blue', cursor='hand2') spartanTextLink.bind(\"<Button-1>\", openWebsite) spartanLabel.bind(\"<Button-1>\", openWebsite) spartanTextLink.pack() for r in range(5): Grid.rowconfigure(frame,",
"game AI. # It also includes code to allow playing against the trained",
"time, webbrowser, os from Tkinter import * from functools import partial from PIL",
"#---------------------------------------------------- #determines if the game is still ongoing an updates the label correctly",
"y == 4 or y == 6)]) return b #true if there is",
"playerSide updateButtons() winnerLabel['text'] = 'computer turn' state = determineWinner() if(state == 3): makeMove()",
"win elif(threeInARow(board, 2, checkLists)): return 2 #o win elif(board.count(0) != 0): return 3",
"machine learning to train a tic tac toe game AI. # It also",
"[]): a = getCheckLists(board) for c in a: if(c.count(x) == 1 and c.count(0)",
"0)] for i in range(len(positions)): position = positions[i] newBoard = copy.deepcopy(board) newBoard[position] =",
"column=1, sticky=N+S+E+W) Grid.rowconfigure(radioFrame, 0, weight=1) Grid.columnconfigure(radioFrame, 0, weight=1) Grid.columnconfigure(radioFrame, 1, weight=1) r1 =",
"conv = {True:1, False:0} #returns a list of the features used to evaluate",
"spartan engineer website in a browser def openWebsite(event): webbrowser.open_new('http://www.spartanengineer.com') #the following code sets",
"between the X and O AI #we pit AI's against each other in",
"range(n_features)] xWeights = [initialWeight for i in range(n_features)] trainingIterations = 10000 print(\"training our",
"for %d games (this may take a minute or two...)\" % trainingIterations) for",
"import ImageTk #------------------------------------------------------------------------------------- #------------------------------------------------------------------------------------- #------------------------------------------------------------------------------------- #Author: <NAME> #Date: 01/29/17 #Description: This code uses",
"# 0 == empty space # 1 == x space # 2 ==",
"wins' if(state != 3): for i in range(9): buttons[i]['state'] = 'disabled' return state",
"== 0): winnerLabel['text'] = 'draw' elif(state == playerSide): winnerLabel['text'] = 'player wins' elif(state",
"places where there is 2 x/o's & an empty space in a row/col/diagonal",
"[i for i in range(9) if(board[i] == 0)] randomNum = random.randint(0, len(a)-1) board[a[randomNum]]",
"tkFont, time, webbrowser, os from Tkinter import * from functools import partial from",
"= 0 for i in range(len(features)): result += (features[i] * weights[i]) return result",
"Label(frame, text=\"new game\") winnerLabel.grid(row=3, column=2, sticky=N+S+W+E) spartanFrame = Frame(frame) spartanFrame.grid(columnspan=3, row=4, column=0) spartanLabel",
"#o win elif(board.count(0) != 0): return 3 #game still going else: return 0",
"1 return result #this function determines if the game is: ongoing, a draw,",
"2 else: computerSide = 1 winnerLabel['text'] = 'game started' theBoard = [0 for",
"includes code to allow playing against the trained AI via a Tkinter #",
"root.minsize(width=700, height=700) root.wm_title(\"SpartanTicTacToe\") spartanImage = ImageTk.PhotoImage(file=rootDirectory + '/resources/spartan-icon-small.png') root.call('wm', 'iconphoto', root._w, spartanImage) frame",
"b = buttons[i] if(theBoard[i] == 1): b['text'] = 'X' else: b['text'] = 'O'",
"empty space in a row/col/diagonal def twoInARow(board, x, a=[]): result = 0 if(a",
"makeBestMove(board, weights, x): boards, values = [], [] positions = [i for i",
"if the game is: ongoing, a draw, a win for x, a win",
"#x win elif(threeInARow(board, 2, checkLists)): return 2 #o win elif(board.count(0) != 0): return",
"toe AI for %d games (this may take a minute or two...)\" %",
"of size 9 that contains information about the current tic # tac toe",
"empty space # 1 == x space # 2 == o space rootDirectory",
"#this function is called when on the board buttons are clicked def buttonClick(n):",
"in range(9)] for b in buttons: b['text'] = '-' b['state'] = 'normal' if(computerSide",
"oWeights, 2) updateButtons() winnerLabel['text'] = 'player turn' determineWinner() #this function is called when",
"tic # tac toe board #the board maps as follows: # 0 ==",
"x, a win for o def getGameState(board): checkLists = getCheckLists(board) if(threeInARow(board, 1, checkLists)):",
"openOne(board, x, a=[]): result = 0 if(a == []): a = getCheckLists(board) for",
"space # 3 == center left space # 4 == center center space",
"== 1): b['text'] = 'X' else: b['text'] = 'O' b['state'] = 'disabled' #makes",
"value #values of 0, 100, & -100 are used for a draw, win,",
"return b #true if there is three in a row, false if not",
"top left space # 1 == top center space # 2 == top",
"games (this may take a minute or two...)\" % trainingIterations) for i in",
"for j in range(len(weights)): weights[j] = weights[j] +(learnConstant*(value-estimate)*features[j]) #initialize our weights, the value",
"for c in a: if(c.count(x) == 2 and c.count(0) == 1): result +=",
"= [0 for i in range(len(train))] if(result == 0): values[len(values)-1] = 0 elif(result",
"2, checkLists), openOne(a, 1, checkLists), openOne(a, 2, checkLists)] #returns the value of a",
"that contains information about the current tic # tac toe board #the board",
"mValue): mValue = values[i] mPosition = positions[i] board[mPosition] = x #makes a random",
"for y in range(9) if(y == 0 or y == 4 or y",
"for a space in each board: # 0 == empty space # 1",
"places where there is 2 x's beside an empty space # # of",
"board buttons are clicked def buttonClick(n): theBoard[n] = playerSide updateButtons() winnerLabel['text'] = 'computer",
"= playAsWhich.get() if(playerSide == 1): computerSide = 2 else: computerSide = 1 winnerLabel['text']",
"r1 = Radiobutton(radioFrame, text=\"X?\", variable=playAsWhich, value=1) r1.grid(row=0, column=0, sticky=N+S+E+W) r1.invoke() r2 = Radiobutton(radioFrame,",
"if(a == []): a = getCheckLists(board) for c in a: if(c.count(x) == 3):",
"a draw, a win for x, a win for o def getGameState(board): checkLists",
"1) # # of places where there is 2 x's beside an empty",
"the game is still ongoing an updates the label correctly def determineWinner(): state",
"space # 5 == center right space # 6 == bottom left space",
"row/col/diagonal def getFeatures(board): a = board checkLists = getCheckLists(a) return [conv[threeInARow(a, 1, checkLists)],",
"copy.deepcopy(board) newBoard[position] = x features = getFeatures(newBoard) value = estimateMoveValue(features, weights) boards.append(newBoard) values.append(value)",
"os from Tkinter import * from functools import partial from PIL import ImageTk",
"range(1, len(positions)): if(values[i] > mValue): mValue = values[i] mPosition = positions[i] board[mPosition] =",
"where there is 2 x's beside an empty space # # of places",
"def makeRandomMove(board, x): a = [i for i in range(9) if(board[i] == 0)]",
"updateWeights(weights, train, result, x): values = [0 for i in range(len(train))] if(result ==",
"print(oWeights) print(\"launching the GUI, this allows the user to play against the AI\")",
"= Frame(root) frame.grid(row=0, column=0, sticky=N+S+E+W) buttonFont = tkFont.Font(family='Helvetica', size=72, weight='bold') buttons = []",
"[initialWeight for i in range(n_features)] xWeights = [initialWeight for i in range(n_features)] trainingIterations",
"root._w, spartanImage) frame = Frame(root) frame.grid(row=0, column=0, sticky=N+S+E+W) buttonFont = tkFont.Font(family='Helvetica', size=72, weight='bold')",
"== 0 or y == 4 or y == 8)]) #diagonal b.append([board[y] for",
"= [] i = 0 for r in range(3): for c in range(3):",
"y == 3 or y == 6)]) #vertical b.append([board[y] for y in range(9)",
"oTrain.append(copy.deepcopy(board)) if(turn == 1): turn = 2 else: turn = 1 gameState =",
"game between the X and O AI #we pit AI's against each other",
"our weights for j in range(len(weights)): weights[j] = weights[j] +(learnConstant*(value-estimate)*features[j]) #initialize our weights,",
"there is an x and two empty spaces in a row/col/diagonal # #",
"if(board[i] == 0)] randomNum = random.randint(0, len(a)-1) board[a[randomNum]] = x #plays a tic-tac-toe",
"code sets up the Tkinter GUI for playing against the AI root =",
"0): b = buttons[i] if(theBoard[i] == 1): b['text'] = 'X' else: b['text'] =",
"range(9) if(y == 1 or y == 4 or y == 7)]) b.append([board[y]",
"print(\"finished training our tic tac toe AI!!!\") print(\"final weights: \") print(xWeights) print(oWeights) print(\"launching",
"#horizontal b.append(board[3:6]) b.append(board[6:9]) b.append([board[y] for y in range(9) if(y == 0 or y",
"== 1): makeBestMove(board, xWeights, turn) xTrain.append(copy.deepcopy(board)) else: makeBestMove(board, oWeights, turn) oTrain.append(copy.deepcopy(board)) if(turn ==",
"2 x's beside an empty space # # of places where there is",
"oWeights, xTrain, oTrain): turn = 1 board = [0 for x in range(9)]",
"= -100 for i in range(len(values)-1): values[i] = estimateMoveValue(getFeatures(train[i+1]), weights) for i in",
"turn = 2 else: turn = 1 gameState = getGameState(board) return gameState #update",
"== 8)]) b.append([board[y] for y in range(9) if(y == 0 or y ==",
"order to train our AI's def playGame(xWeights, oWeights, xTrain, oTrain): turn = 1",
"oTrain): turn = 1 board = [0 for x in range(9)] gameState =",
"move def makeRandomMove(board, x): a = [i for i in range(9) if(board[i] ==",
"# 2 == o space rootDirectory = os.path.dirname(os.path.realpath(__file__)) print('----------------------------------------------------') print('----------------------------------------------------') print('https://www.spartanengineer.com') print('----------------------------------------------------') print('----------------------------------------------------')",
"take a minute or two...)\" % trainingIterations) for i in range(trainingIterations): xTrain, oTrain",
"oWeights, xTrain, oTrain) updateWeights(xWeights, xTrain, result, 1) updateWeights(oWeights, oTrain, result, 2) print(\"finished training",
"of places where there is an x and two empty spaces in a",
"range(n_features)] trainingIterations = 10000 print(\"training our tic tac toe AI for %d games",
"== 0): values[len(values)-1] = 0 elif(result == x): values[len(values)-1] = 100 else: values[len(values)-1]",
"print('----------------------------------------------------') print('https://www.spartanengineer.com') print('----------------------------------------------------') print('----------------------------------------------------') learnConstant = 0.1 # learning constant def getCheckLists(board): b",
"= getCheckLists(a) return [conv[threeInARow(a, 1, checkLists)], conv[threeInARow(a, 2, checkLists)], twoInARow(a, 1, checkLists), twoInARow(a,",
"3 x's in a row (0 or 1) # is there 3 o's",
"= 'computer turn' state = determineWinner() if(state == 3): makeMove() #this function starts",
"position = positions[i] newBoard = copy.deepcopy(board) newBoard[position] = x features = getFeatures(newBoard) value",
"#makes a computer move def makeMove(): if(computerSide == 1): makeBestMove(theBoard, xWeights, 1) else:",
"a list of the features used to evaluate the value of a tic",
"board: # 0 == empty space # 1 == x space # 2",
"= getCheckLists(board) for c in a: if(c.count(x) == 2 and c.count(0) == 1):",
"updateButtons() winnerLabel['text'] = 'computer turn' state = determineWinner() if(state == 3): makeMove() #this",
"7)]) b.append([board[y] for y in range(9) if(y == 2 or y == 5",
"the # of places where there is 2 x/o's & an empty space",
"= 100 else: values[len(values)-1] = -100 for i in range(len(values)-1): values[i] = estimateMoveValue(getFeatures(train[i+1]),",
"weights, the value of 0.5 is arbitrarily picked initialWeight = 0.5 n_features =",
"#we pit AI's against each other in order to train our AI's def",
"(0 or 1) # # of places where there is 2 x's beside",
"oTrain) updateWeights(xWeights, xTrain, result, 1) updateWeights(oWeights, oTrain, result, 2) print(\"finished training our tic",
"== 4 or y == 8)]) #diagonal b.append([board[y] for y in range(9) if(y",
"in a row/col/diagonal # # of places where there is an o and",
"getFeatures(board): a = board checkLists = getCheckLists(a) return [conv[threeInARow(a, 1, checkLists)], conv[threeInARow(a, 2,",
"in order to train our AI's def playGame(xWeights, oWeights, xTrain, oTrain): turn =",
"for i in range(len(train))] if(result == 0): values[len(values)-1] = 0 elif(result == x):",
"for i in range(1, len(positions)): if(values[i] > mValue): mValue = values[i] mPosition =",
"there is 2 o's beside an empty space # # of places where",
"AI def newGameClick(): global playerSide, computerSide, theBoard playerSide = playAsWhich.get() if(playerSide == 1):",
"[conv[threeInARow(a, 1, checkLists)], conv[threeInARow(a, 2, checkLists)], twoInARow(a, 1, checkLists), twoInARow(a, 2, checkLists), openOne(a,",
"if(c.count(x) == 2 and c.count(0) == 1): result += 1 return result #returns",
"#values of 0, 100, & -100 are used for a draw, win, and",
"random move def makeRandomMove(board, x): a = [i for i in range(9) if(board[i]",
"the value of 0.5 is arbitrarily picked initialWeight = 0.5 n_features = 6",
"draw, a win for x, a win for o def getGameState(board): checkLists =",
"right space # 3 == center left space # 4 == center center",
"tac toe AI for %d games (this may take a minute or two...)\"",
"= 0.5 n_features = 6 oWeights = [initialWeight for i in range(n_features)] xWeights",
"and two empty spaces in a row/col/diagonal # # of places where there",
"value = values[i] estimate = estimateMoveValue(features, weights) #update our weights for j in",
"row, false if not #x parameter should be 1(x) or 2(o) def threeInARow(board,",
"move value #values of 0, 100, & -100 are used for a draw,",
"== 2 or y == 4 or y == 6)]) return b #true",
"= 'player wins' elif(state == computerSide): winnerLabel['text'] = 'computer wins' if(state != 3):",
"+= 1 return result #this function determines if the game is: ongoing, a",
"starts a new tic tac toe game vs the AI def newGameClick(): global",
"openWebsite) spartanTextLink.pack() for r in range(5): Grid.rowconfigure(frame, r, weight=1) for c in range(3):",
"#the board is a list of size 9 that contains information about the",
"space in a row/col/diagonal def twoInARow(board, x, a=[]): result = 0 if(a ==",
"openWebsite(event): webbrowser.open_new('http://www.spartanengineer.com') #the following code sets up the Tkinter GUI for playing against",
"1 and c.count(0) == 2): result += 1 return result #this function determines",
"else: makeBestMove(board, oWeights, turn) oTrain.append(copy.deepcopy(board)) if(turn == 1): turn = 2 else: turn",
"if(computerSide == 1): makeMove() #this function loads up the spartan engineer website in",
"button = Button(frame, text=\"-\", command=partial(buttonClick, i)) button.grid(row=r, column=c, sticky=N+S+E+W) button['font'] = buttonFont button['state']",
"getGameState(board) return gameState #update our weights based upon the training data from the",
"AI for %d games (this may take a minute or two...)\" % trainingIterations)",
"values = [0 for i in range(len(train))] if(result == 0): values[len(values)-1] = 0",
"[]): a = getCheckLists(board) for c in a: if(c.count(x) == 2 and c.count(0)",
"== 1): computerSide = 2 else: computerSide = 1 winnerLabel['text'] = 'game started'",
"0 or y == 3 or y == 6)]) #vertical b.append([board[y] for y",
"== 2 or y == 5 or y == 8)]) b.append([board[y] for y",
"Button(frame, command=newGameClick, text=\"New Game?\") newGameButton.grid(row=3, column=0, sticky=N+S+E+W) playAsWhich = IntVar() radioFrame = Frame(frame)",
"i = 0 for r in range(3): for c in range(3): button =",
"#Date: 01/29/17 #Description: This code uses machine learning to train a tic tac",
"[]): a = getCheckLists(board) for c in a: if(c.count(x) == 3): return True",
"= Button(frame, command=newGameClick, text=\"New Game?\") newGameButton.grid(row=3, column=0, sticky=N+S+E+W) playAsWhich = IntVar() radioFrame =",
"in a row/col/diagonal def openOne(board, x, a=[]): result = 0 if(a == []):",
"xTrain, oTrain = [], [] result = playGame(xWeights, oWeights, xTrain, oTrain) updateWeights(xWeights, xTrain,",
"== playerSide): winnerLabel['text'] = 'player wins' elif(state == computerSide): winnerLabel['text'] = 'computer wins'",
"threeInARow(board, x, a=[]): if(a == []): a = getCheckLists(board) for c in a:",
"x features = getFeatures(newBoard) value = estimateMoveValue(features, weights) boards.append(newBoard) values.append(value) mValue = values[0]",
"= playGame(xWeights, oWeights, xTrain, oTrain) updateWeights(xWeights, xTrain, result, 1) updateWeights(oWeights, oTrain, result, 2)",
"= 6 oWeights = [initialWeight for i in range(n_features)] xWeights = [initialWeight for",
"space # 1 == top center space # 2 == top right space",
"AI. # It also includes code to allow playing against the trained AI",
"values[i] estimate = estimateMoveValue(features, weights) #update our weights for j in range(len(weights)): weights[j]",
"-100 for i in range(len(values)-1): values[i] = estimateMoveValue(getFeatures(train[i+1]), weights) for i in range(len(values)):",
"x, a=[]): result = 0 if(a == []): a = getCheckLists(board) for c",
"== 1): turn = 2 else: turn = 1 gameState = getGameState(board) return",
"!= 0): b = buttons[i] if(theBoard[i] == 1): b['text'] = 'X' else: b['text']",
"left space # 7 == bottom center space # 8 == bottom right",
"values[0] mPosition = positions[0] for i in range(1, len(positions)): if(values[i] > mValue): mValue",
"twoInARow(a, 2, checkLists), openOne(a, 1, checkLists), openOne(a, 2, checkLists)] #returns the value of",
"features = getFeatures(newBoard) value = estimateMoveValue(features, weights) boards.append(newBoard) values.append(value) mValue = values[0] mPosition",
"to allow playing against the trained AI via a Tkinter # GUI. #-------------------------------------------------------------------------------------",
"1): computerSide = 2 else: computerSide = 1 winnerLabel['text'] = 'game started' theBoard",
"# GUI. #------------------------------------------------------------------------------------- #Run via Python 2.7 #REQUIRES: pillow (python imaging library) #-------------------------------------------------------------------------------------",
"c in a: if(c.count(x) == 2 and c.count(0) == 1): result += 1",
"the value of a tic tac toeboard #the features are as follows: #",
"display def updateButtons(): for i in range(9): if(theBoard[i] != 0): b = buttons[i]",
"in range(9) if(y == 2 or y == 5 or y == 8)])",
"buttonClick(n): theBoard[n] = playerSide updateButtons() winnerLabel['text'] = 'computer turn' state = determineWinner() if(state",
"= 10000 print(\"training our tic tac toe AI for %d games (this may",
"def getGameState(board): checkLists = getCheckLists(board) if(threeInARow(board, 1, checkLists)): return 1 #x win elif(threeInARow(board,",
"current tic # tac toe board #the board maps as follows: # 0",
"= getCheckLists(board) for c in a: if(c.count(x) == 1 and c.count(0) == 2):",
"y == 5 or y == 8)]) b.append([board[y] for y in range(9) if(y",
"global playerSide, computerSide, theBoard playerSide = playAsWhich.get() if(playerSide == 1): computerSide = 2",
"column=0, sticky=N+S+E+W) buttonFont = tkFont.Font(family='Helvetica', size=72, weight='bold') buttons = [] i = 0",
"1) # is there 3 o's in a row (0 or 1) #",
"weights): result = 0 for i in range(len(features)): result += (features[i] * weights[i])",
"if not #x parameter should be 1(x) or 2(o) def threeInARow(board, x, a=[]):",
"code uses machine learning to train a tic tac toe game AI. #",
"= random.randint(0, len(a)-1) board[a[randomNum]] = x #plays a tic-tac-toe game between the X",
"0 or y == 4 or y == 8)]) #diagonal b.append([board[y] for y",
"in a row/col/diagonal def getFeatures(board): a = board checkLists = getCheckLists(a) return [conv[threeInARow(a,",
"updated by comparing the estimated move value with the actual move value #values",
"Radiobutton(radioFrame, text=\"O?\", variable=playAsWhich, value=2) r2.grid(row=0, column=1, sticky=N+S+E+W) winnerLabel = Label(frame, text=\"new game\") winnerLabel.grid(row=3,",
"= [0 for x in range(9)] gameState = 3 while(gameState == 3): if(turn",
"Label(spartanFrame, text='www.spartanengineer.com', fg='blue', cursor='hand2') spartanTextLink.bind(\"<Button-1>\", openWebsite) spartanLabel.bind(\"<Button-1>\", openWebsite) spartanTextLink.pack() for r in range(5):",
"[] result = playGame(xWeights, oWeights, xTrain, oTrain) updateWeights(xWeights, xTrain, result, 1) updateWeights(oWeights, oTrain,",
"x): values = [0 for i in range(len(train))] if(result == 0): values[len(values)-1] =",
"x and two empty spaces in a row/col/diagonal # # of places where",
"webbrowser.open_new('http://www.spartanengineer.com') #the following code sets up the Tkinter GUI for playing against the",
"updateButtons() winnerLabel['text'] = 'player turn' determineWinner() #this function is called when on the",
"determineWinner(): state = getGameState(theBoard) if(state == 0): winnerLabel['text'] = 'draw' elif(state == playerSide):",
"= [i for i in range(9) if(board[i] == 0)] randomNum = random.randint(0, len(a)-1)",
"makeMove() #this function loads up the spartan engineer website in a browser def",
"5 == center right space # 6 == bottom left space # 7",
"= buttons[i] if(theBoard[i] == 1): b['text'] = 'X' else: b['text'] = 'O' b['state']",
"space # 7 == bottom center space # 8 == bottom right space",
"if(playerSide == 1): computerSide = 2 else: computerSide = 1 winnerLabel['text'] = 'game",
"AI #we pit AI's against each other in order to train our AI's",
"9 that contains information about the current tic # tac toe board #the",
"> mValue): mValue = values[i] mPosition = positions[i] board[mPosition] = x #makes a",
"in range(n_features)] trainingIterations = 10000 print(\"training our tic tac toe AI for %d",
"for b in buttons: b['text'] = '-' b['state'] = 'normal' if(computerSide == 1):",
"# # of places where there is 2 o's beside an empty space",
"x): boards, values = [], [] positions = [i for i in range(9)",
"return False #returns the # of places where there is 2 x/o's &",
"return gameState #update our weights based upon the training data from the last",
"and loss def updateWeights(weights, train, result, x): values = [0 for i in",
"#returns the value of a board based on the features (of the board)",
"the label correctly def determineWinner(): state = getGameState(theBoard) if(state == 0): winnerLabel['text'] =",
"2(o) def threeInARow(board, x, a=[]): if(a == []): a = getCheckLists(board) for c",
"y in range(9) if(y == 0 or y == 4 or y ==",
"size 9 that contains information about the current tic # tac toe board",
"# of places where there is an o and two empty spaces in",
"game is still ongoing an updates the label correctly def determineWinner(): state =",
"if(state != 3): for i in range(9): buttons[i]['state'] = 'disabled' return state #update",
"#the following code sets up the Tkinter GUI for playing against the AI",
"upon the training data from the last played game #the weights are updated",
"x): values[len(values)-1] = 100 else: values[len(values)-1] = -100 for i in range(len(values)-1): values[i]",
"'draw' elif(state == playerSide): winnerLabel['text'] = 'player wins' elif(state == computerSide): winnerLabel['text'] =",
"updateWeights(oWeights, oTrain, result, 2) print(\"finished training our tic tac toe AI!!!\") print(\"final weights:",
"import copy, random, tkFont, time, webbrowser, os from Tkinter import * from functools",
"0 for i in range(len(features)): result += (features[i] * weights[i]) return result #makes",
"turn) xTrain.append(copy.deepcopy(board)) else: makeBestMove(board, oWeights, turn) oTrain.append(copy.deepcopy(board)) if(turn == 1): turn = 2",
"elif(state == playerSide): winnerLabel['text'] = 'player wins' elif(state == computerSide): winnerLabel['text'] = 'computer",
"follows: # is there 3 x's in a row (0 or 1) #",
"= estimateMoveValue(features, weights) #update our weights for j in range(len(weights)): weights[j] = weights[j]",
"= positions[i] newBoard = copy.deepcopy(board) newBoard[position] = x features = getFeatures(newBoard) value =",
"== bottom left space # 7 == bottom center space # 8 ==",
"positions[i] board[mPosition] = x #makes a random move def makeRandomMove(board, x): a =",
"getCheckLists(board) for c in a: if(c.count(x) == 1 and c.count(0) == 2): result",
"o def getGameState(board): checkLists = getCheckLists(board) if(threeInARow(board, 1, checkLists)): return 1 #x win",
"== 0)] randomNum = random.randint(0, len(a)-1) board[a[randomNum]] = x #plays a tic-tac-toe game",
"a row (0 or 1) # is there 3 o's in a row",
"spaces in a row/col/diagonal def openOne(board, x, a=[]): result = 0 if(a ==",
"ImageTk #------------------------------------------------------------------------------------- #------------------------------------------------------------------------------------- #------------------------------------------------------------------------------------- #Author: <NAME> #Date: 01/29/17 #Description: This code uses machine",
"elif(state == computerSide): winnerLabel['text'] = 'computer wins' if(state != 3): for i in",
"game\") winnerLabel.grid(row=3, column=2, sticky=N+S+W+E) spartanFrame = Frame(frame) spartanFrame.grid(columnspan=3, row=4, column=0) spartanLabel = Label(spartanFrame,",
"2 o's beside an empty space # # of places where there is",
"range(3): for c in range(3): button = Button(frame, text=\"-\", command=partial(buttonClick, i)) button.grid(row=r, column=c,",
"# 3 == center left space # 4 == center center space #",
"column=2, sticky=N+S+W+E) spartanFrame = Frame(frame) spartanFrame.grid(columnspan=3, row=4, column=0) spartanLabel = Label(spartanFrame, image=spartanImage, cursor='hand2')",
"= IntVar() radioFrame = Frame(frame) radioFrame.grid(row=3, column=1, sticky=N+S+E+W) Grid.rowconfigure(radioFrame, 0, weight=1) Grid.columnconfigure(radioFrame, 0,",
"row (0 or 1) # # of places where there is 2 x's",
"uses machine learning to train a tic tac toe game AI. # It",
"0, weight=1) root.minsize(width=700, height=700) root.wm_title(\"SpartanTicTacToe\") spartanImage = ImageTk.PhotoImage(file=rootDirectory + '/resources/spartan-icon-small.png') root.call('wm', 'iconphoto', root._w,",
"spartanFrame.grid(columnspan=3, row=4, column=0) spartanLabel = Label(spartanFrame, image=spartanImage, cursor='hand2') spartanLabel.pack() spartanTextLink = Label(spartanFrame, text='www.spartanengineer.com',",
"loss def updateWeights(weights, train, result, x): values = [0 for i in range(len(train))]",
"three in a row, false if not #x parameter should be 1(x) or",
"AI's def playGame(xWeights, oWeights, xTrain, oTrain): turn = 1 board = [0 for",
"sets up the Tkinter GUI for playing against the AI root = Tk()",
"fg='blue', cursor='hand2') spartanTextLink.bind(\"<Button-1>\", openWebsite) spartanLabel.bind(\"<Button-1>\", openWebsite) spartanTextLink.pack() for r in range(5): Grid.rowconfigure(frame, r,",
"#value mapping for a space in each board: # 0 == empty space",
"determineWinner() if(state == 3): makeMove() #this function starts a new tic tac toe",
"for i in range(n_features)] xWeights = [initialWeight for i in range(n_features)] trainingIterations =",
"10000 print(\"training our tic tac toe AI for %d games (this may take",
"train a tic tac toe game AI. # It also includes code to",
"while(gameState == 3): if(turn == 1): makeBestMove(board, xWeights, turn) xTrain.append(copy.deepcopy(board)) else: makeBestMove(board, oWeights,",
"range(3): button = Button(frame, text=\"-\", command=partial(buttonClick, i)) button.grid(row=r, column=c, sticky=N+S+E+W) button['font'] = buttonFont",
"= Label(spartanFrame, image=spartanImage, cursor='hand2') spartanLabel.pack() spartanTextLink = Label(spartanFrame, text='www.spartanengineer.com', fg='blue', cursor='hand2') spartanTextLink.bind(\"<Button-1>\", openWebsite)",
"#game still going else: return 0 #draw conv = {True:1, False:0} #returns a",
"actual move value #values of 0, 100, & -100 are used for a",
"and c.count(0) == 1): result += 1 return result #returns the # of",
"= Frame(frame) spartanFrame.grid(columnspan=3, row=4, column=0) spartanLabel = Label(spartanFrame, image=spartanImage, cursor='hand2') spartanLabel.pack() spartanTextLink =",
"tac toe game vs the AI def newGameClick(): global playerSide, computerSide, theBoard playerSide",
"This code uses machine learning to train a tic tac toe game AI.",
"weight=1) Grid.columnconfigure(radioFrame, 1, weight=1) r1 = Radiobutton(radioFrame, text=\"X?\", variable=playAsWhich, value=1) r1.grid(row=0, column=0, sticky=N+S+E+W)",
"#returns the # of places where there is an x/o and 2 empty",
"xTrain.append(copy.deepcopy(board)) else: makeBestMove(board, oWeights, turn) oTrain.append(copy.deepcopy(board)) if(turn == 1): turn = 2 else:",
"amongst all of the possible moves def makeBestMove(board, weights, x): boards, values =",
"'game started' theBoard = [0 for x in range(9)] for b in buttons:",
"up the spartan engineer website in a browser def openWebsite(event): webbrowser.open_new('http://www.spartanengineer.com') #the following",
"text=\"X?\", variable=playAsWhich, value=1) r1.grid(row=0, column=0, sticky=N+S+E+W) r1.invoke() r2 = Radiobutton(radioFrame, text=\"O?\", variable=playAsWhich, value=2)",
"the value of a board based on the features (of the board) and",
"possible amongst all of the possible moves def makeBestMove(board, weights, x): boards, values",
"the training data from the last played game #the weights are updated by",
"state = getGameState(theBoard) if(state == 0): winnerLabel['text'] = 'draw' elif(state == playerSide): winnerLabel['text']",
"= board checkLists = getCheckLists(a) return [conv[threeInARow(a, 1, checkLists)], conv[threeInARow(a, 2, checkLists)], twoInARow(a,",
"our tic tac toe board's graphical display def updateButtons(): for i in range(9):",
"o space rootDirectory = os.path.dirname(os.path.realpath(__file__)) print('----------------------------------------------------') print('----------------------------------------------------') print('https://www.spartanengineer.com') print('----------------------------------------------------') print('----------------------------------------------------') learnConstant = 0.1",
"b['text'] = '-' b['state'] = 'normal' if(computerSide == 1): makeMove() #this function loads",
"spartanImage) frame = Frame(root) frame.grid(row=0, column=0, sticky=N+S+E+W) buttonFont = tkFont.Font(family='Helvetica', size=72, weight='bold') buttons",
"Python 2.7 #REQUIRES: pillow (python imaging library) #------------------------------------------------------------------------------------- #------------------------------------------------------------------------------------- #------------------------------------------------------------------------------------- #the board is",
"makeBestMove(theBoard, xWeights, 1) else: makeBestMove(theBoard, oWeights, 2) updateButtons() winnerLabel['text'] = 'player turn' determineWinner()",
"of 0, 100, & -100 are used for a draw, win, and loss",
"gameState = 3 while(gameState == 3): if(turn == 1): makeBestMove(board, xWeights, turn) xTrain.append(copy.deepcopy(board))",
"'normal' if(computerSide == 1): makeMove() #this function loads up the spartan engineer website",
"= 1 gameState = getGameState(board) return gameState #update our weights based upon the",
"a computer move def makeMove(): if(computerSide == 1): makeBestMove(theBoard, xWeights, 1) else: makeBestMove(theBoard,",
"newGameButton = Button(frame, command=newGameClick, text=\"New Game?\") newGameButton.grid(row=3, column=0, sticky=N+S+E+W) playAsWhich = IntVar() radioFrame",
"+= 1 newGameButton = Button(frame, command=newGameClick, text=\"New Game?\") newGameButton.grid(row=3, column=0, sticky=N+S+E+W) playAsWhich =",
"def makeMove(): if(computerSide == 1): makeBestMove(theBoard, xWeights, 1) else: makeBestMove(theBoard, oWeights, 2) updateButtons()",
"= 'O' b['state'] = 'disabled' #makes a computer move def makeMove(): if(computerSide ==",
"the features (of the board) and their respective weights def estimateMoveValue(features, weights): result",
"value with the actual move value #values of 0, 100, & -100 are",
"print(\"final weights: \") print(xWeights) print(oWeights) print(\"launching the GUI, this allows the user to",
"based upon the training data from the last played game #the weights are",
"determineWinner() #this function is called when on the board buttons are clicked def",
"initialWeight = 0.5 n_features = 6 oWeights = [initialWeight for i in range(n_features)]",
"tic tac toe board's graphical display def updateButtons(): for i in range(9): if(theBoard[i]",
"ongoing, a draw, a win for x, a win for o def getGameState(board):",
"<NAME> #Date: 01/29/17 #Description: This code uses machine learning to train a tic",
"a: if(c.count(x) == 1 and c.count(0) == 2): result += 1 return result",
"in range(9) if(board[i] == 0)] randomNum = random.randint(0, len(a)-1) board[a[randomNum]] = x #plays",
"height=700) root.wm_title(\"SpartanTicTacToe\") spartanImage = ImageTk.PhotoImage(file=rootDirectory + '/resources/spartan-icon-small.png') root.call('wm', 'iconphoto', root._w, spartanImage) frame =",
"move value with the actual move value #values of 0, 100, & -100",
"space #value mapping for a space in each board: # 0 == empty",
"their respective weights def estimateMoveValue(features, weights): result = 0 for i in range(len(features)):",
"empty space # # of places where there is an x and two",
"def getFeatures(board): a = board checkLists = getCheckLists(a) return [conv[threeInARow(a, 1, checkLists)], conv[threeInARow(a,",
"= 0 if(a == []): a = getCheckLists(board) for c in a: if(c.count(x)",
"# 1 == x space # 2 == o space rootDirectory = os.path.dirname(os.path.realpath(__file__))",
"playAsWhich.get() if(playerSide == 1): computerSide = 2 else: computerSide = 1 winnerLabel['text'] =",
"on the board buttons are clicked def buttonClick(n): theBoard[n] = playerSide updateButtons() winnerLabel['text']",
"= {True:1, False:0} #returns a list of the features used to evaluate the",
"Frame(frame) radioFrame.grid(row=3, column=1, sticky=N+S+E+W) Grid.rowconfigure(radioFrame, 0, weight=1) Grid.columnconfigure(radioFrame, 0, weight=1) Grid.columnconfigure(radioFrame, 1, weight=1)",
"comparing the estimated move value with the actual move value #values of 0,",
"#plays a tic-tac-toe game between the X and O AI #we pit AI's",
"the AI def newGameClick(): global playerSide, computerSide, theBoard playerSide = playAsWhich.get() if(playerSide ==",
"#returns the # of places where there is 2 x/o's & an empty",
"mPosition = positions[0] for i in range(1, len(positions)): if(values[i] > mValue): mValue =",
"4 or y == 8)]) #diagonal b.append([board[y] for y in range(9) if(y ==",
"3): makeMove() #this function starts a new tic tac toe game vs the",
"for o def getGameState(board): checkLists = getCheckLists(board) if(threeInARow(board, 1, checkLists)): return 1 #x",
"= positions[i] board[mPosition] = x #makes a random move def makeRandomMove(board, x): a",
"* weights[i]) return result #makes the best possible amongst all of the possible",
"is called when on the board buttons are clicked def buttonClick(n): theBoard[n] =",
"= estimateMoveValue(getFeatures(train[i+1]), weights) for i in range(len(values)): board = train[i] features = getFeatures(board)",
"y in range(9) if(y == 2 or y == 4 or y ==",
"in range(5): Grid.rowconfigure(frame, r, weight=1) for c in range(3): Grid.columnconfigure(frame, c, weight=1) root.mainloop()",
"xWeights, turn) xTrain.append(copy.deepcopy(board)) else: makeBestMove(board, oWeights, turn) oTrain.append(copy.deepcopy(board)) if(turn == 1): turn =",
"c in a: if(c.count(x) == 1 and c.count(0) == 2): result += 1",
"AI via a Tkinter # GUI. #------------------------------------------------------------------------------------- #Run via Python 2.7 #REQUIRES: pillow",
"center center space # 5 == center right space # 6 == bottom",
"in a: if(c.count(x) == 1 and c.count(0) == 2): result += 1 return",
"estimateMoveValue(getFeatures(train[i+1]), weights) for i in range(len(values)): board = train[i] features = getFeatures(board) value",
"buttons = [] i = 0 for r in range(3): for c in",
"# learning constant def getCheckLists(board): b = [] b.append(board[0:3]) #horizontal b.append(board[3:6]) b.append(board[6:9]) b.append([board[y]",
"0.1 # learning constant def getCheckLists(board): b = [] b.append(board[0:3]) #horizontal b.append(board[3:6]) b.append(board[6:9])",
"c in range(3): button = Button(frame, text=\"-\", command=partial(buttonClick, i)) button.grid(row=r, column=c, sticky=N+S+E+W) button['font']",
"b.append(board[0:3]) #horizontal b.append(board[3:6]) b.append(board[6:9]) b.append([board[y] for y in range(9) if(y == 0 or",
"It also includes code to allow playing against the trained AI via a",
"%d games (this may take a minute or two...)\" % trainingIterations) for i",
"checkLists), openOne(a, 1, checkLists), openOne(a, 2, checkLists)] #returns the value of a board",
"== 6)]) #vertical b.append([board[y] for y in range(9) if(y == 1 or y",
"6 == bottom left space # 7 == bottom center space # 8",
"= 0 for r in range(3): for c in range(3): button = Button(frame,",
"of 0.5 is arbitrarily picked initialWeight = 0.5 n_features = 6 oWeights =",
"empty spaces in a row/col/diagonal def getFeatures(board): a = board checkLists = getCheckLists(a)",
"are clicked def buttonClick(n): theBoard[n] = playerSide updateButtons() winnerLabel['text'] = 'computer turn' state",
"column=0, sticky=N+S+E+W) playAsWhich = IntVar() radioFrame = Frame(frame) radioFrame.grid(row=3, column=1, sticky=N+S+E+W) Grid.rowconfigure(radioFrame, 0,",
"for y in range(9) if(y == 2 or y == 4 or y",
"a row/col/diagonal def twoInARow(board, x, a=[]): result = 0 if(a == []): a",
"y == 6)]) #vertical b.append([board[y] for y in range(9) if(y == 1 or",
"spartanTextLink.pack() for r in range(5): Grid.rowconfigure(frame, r, weight=1) for c in range(3): Grid.columnconfigure(frame,",
"#update our tic tac toe board's graphical display def updateButtons(): for i in",
"the possible moves def makeBestMove(board, weights, x): boards, values = [], [] positions",
"Tk() Grid.rowconfigure(root, 0, weight=1) Grid.columnconfigure(root, 0, weight=1) root.minsize(width=700, height=700) root.wm_title(\"SpartanTicTacToe\") spartanImage = ImageTk.PhotoImage(file=rootDirectory",
"to evaluate the value of a tic tac toeboard #the features are as",
"'disabled' buttons.append(button) i += 1 newGameButton = Button(frame, command=newGameClick, text=\"New Game?\") newGameButton.grid(row=3, column=0,",
"each other in order to train our AI's def playGame(xWeights, oWeights, xTrain, oTrain):",
"toe board #the board maps as follows: # 0 == top left space",
"i in range(len(positions)): position = positions[i] newBoard = copy.deepcopy(board) newBoard[position] = x features",
"0): winnerLabel['text'] = 'draw' elif(state == playerSide): winnerLabel['text'] = 'player wins' elif(state ==",
"GUI. #------------------------------------------------------------------------------------- #Run via Python 2.7 #REQUIRES: pillow (python imaging library) #------------------------------------------------------------------------------------- #-------------------------------------------------------------------------------------",
"playGame(xWeights, oWeights, xTrain, oTrain): turn = 1 board = [0 for x in",
"o and two empty spaces in a row/col/diagonal def getFeatures(board): a = board",
"o's in a row (0 or 1) # # of places where there",
"print(\"launching the GUI, this allows the user to play against the AI\") #----------------------------------------------------",
"draw, win, and loss def updateWeights(weights, train, result, x): values = [0 for",
"range(trainingIterations): xTrain, oTrain = [], [] result = playGame(xWeights, oWeights, xTrain, oTrain) updateWeights(xWeights,",
"for i in range(n_features)] trainingIterations = 10000 print(\"training our tic tac toe AI",
"weights) for i in range(len(values)): board = train[i] features = getFeatures(board) value =",
"== 3): makeMove() #this function starts a new tic tac toe game vs",
"= values[i] estimate = estimateMoveValue(features, weights) #update our weights for j in range(len(weights)):",
"tic tac toe game vs the AI def newGameClick(): global playerSide, computerSide, theBoard",
"3 o's in a row (0 or 1) # # of places where",
"space # 1 == x space # 2 == o space rootDirectory =",
"our AI's def playGame(xWeights, oWeights, xTrain, oTrain): turn = 1 board = [0",
"an empty space # # of places where there is 2 o's beside",
"3 while(gameState == 3): if(turn == 1): makeBestMove(board, xWeights, turn) xTrain.append(copy.deepcopy(board)) else: makeBestMove(board,",
"== 1 or y == 4 or y == 7)]) b.append([board[y] for y",
"#this function determines if the game is: ongoing, a draw, a win for",
"where there is an x and two empty spaces in a row/col/diagonal #",
"bottom right space #value mapping for a space in each board: # 0",
"board checkLists = getCheckLists(a) return [conv[threeInARow(a, 1, checkLists)], conv[threeInARow(a, 2, checkLists)], twoInARow(a, 1,",
"os.path.dirname(os.path.realpath(__file__)) print('----------------------------------------------------') print('----------------------------------------------------') print('https://www.spartanengineer.com') print('----------------------------------------------------') print('----------------------------------------------------') learnConstant = 0.1 # learning constant def",
"def determineWinner(): state = getGameState(theBoard) if(state == 0): winnerLabel['text'] = 'draw' elif(state ==",
"& an empty space in a row/col/diagonal def twoInARow(board, x, a=[]): result =",
"#makes a random move def makeRandomMove(board, x): a = [i for i in",
"positions[i] newBoard = copy.deepcopy(board) newBoard[position] = x features = getFeatures(newBoard) value = estimateMoveValue(features,",
"graphical display def updateButtons(): for i in range(9): if(theBoard[i] != 0): b =",
"an empty space in a row/col/diagonal def twoInARow(board, x, a=[]): result = 0",
"= getFeatures(newBoard) value = estimateMoveValue(features, weights) boards.append(newBoard) values.append(value) mValue = values[0] mPosition =",
"in range(9) if(y == 0 or y == 4 or y == 8)])",
"gameState #update our weights based upon the training data from the last played",
"the Tkinter GUI for playing against the AI root = Tk() Grid.rowconfigure(root, 0,",
"#this function starts a new tic tac toe game vs the AI def",
"i in range(len(train))] if(result == 0): values[len(values)-1] = 0 elif(result == x): values[len(values)-1]",
"all of the possible moves def makeBestMove(board, weights, x): boards, values = [],",
"board) and their respective weights def estimateMoveValue(features, weights): result = 0 for i",
"trainingIterations) for i in range(trainingIterations): xTrain, oTrain = [], [] result = playGame(xWeights,",
"== o space rootDirectory = os.path.dirname(os.path.realpath(__file__)) print('----------------------------------------------------') print('----------------------------------------------------') print('https://www.spartanengineer.com') print('----------------------------------------------------') print('----------------------------------------------------') learnConstant =",
"frame.grid(row=0, column=0, sticky=N+S+E+W) buttonFont = tkFont.Font(family='Helvetica', size=72, weight='bold') buttons = [] i =",
"1 winnerLabel['text'] = 'game started' theBoard = [0 for x in range(9)] for",
"#the features are as follows: # is there 3 x's in a row",
"xWeights, 1) else: makeBestMove(theBoard, oWeights, 2) updateButtons() winnerLabel['text'] = 'player turn' determineWinner() #this",
"the game is: ongoing, a draw, a win for x, a win for",
"return 1 #x win elif(threeInARow(board, 2, checkLists)): return 2 #o win elif(board.count(0) !=",
"is a list of size 9 that contains information about the current tic",
"== 4 or y == 6)]) return b #true if there is three",
"partial from PIL import ImageTk #------------------------------------------------------------------------------------- #------------------------------------------------------------------------------------- #------------------------------------------------------------------------------------- #Author: <NAME> #Date: 01/29/17 #Description:",
"# It also includes code to allow playing against the trained AI via",
"turn) oTrain.append(copy.deepcopy(board)) if(turn == 1): turn = 2 else: turn = 1 gameState",
"weights: \") print(xWeights) print(oWeights) print(\"launching the GUI, this allows the user to play",
"return 3 #game still going else: return 0 #draw conv = {True:1, False:0}",
"1 == x space # 2 == o space rootDirectory = os.path.dirname(os.path.realpath(__file__)) print('----------------------------------------------------')",
"0)] randomNum = random.randint(0, len(a)-1) board[a[randomNum]] = x #plays a tic-tac-toe game between",
"and two empty spaces in a row/col/diagonal def getFeatures(board): a = board checkLists",
"else: turn = 1 gameState = getGameState(board) return gameState #update our weights based",
"100 else: values[len(values)-1] = -100 for i in range(len(values)-1): values[i] = estimateMoveValue(getFeatures(train[i+1]), weights)",
"with the actual move value #values of 0, 100, & -100 are used",
"[0 for x in range(9)] gameState = 3 while(gameState == 3): if(turn ==",
"against the AI root = Tk() Grid.rowconfigure(root, 0, weight=1) Grid.columnconfigure(root, 0, weight=1) root.minsize(width=700,",
"checkLists), openOne(a, 2, checkLists)] #returns the value of a board based on the",
"board's graphical display def updateButtons(): for i in range(9): if(theBoard[i] != 0): b",
"or y == 4 or y == 7)]) b.append([board[y] for y in range(9)",
"still going else: return 0 #draw conv = {True:1, False:0} #returns a list",
"def updateButtons(): for i in range(9): if(theBoard[i] != 0): b = buttons[i] if(theBoard[i]",
"called when on the board buttons are clicked def buttonClick(n): theBoard[n] = playerSide",
"the spartan engineer website in a browser def openWebsite(event): webbrowser.open_new('http://www.spartanengineer.com') #the following code",
"respective weights def estimateMoveValue(features, weights): result = 0 for i in range(len(features)): result",
"from the last played game #the weights are updated by comparing the estimated",
"Grid.columnconfigure(radioFrame, 1, weight=1) r1 = Radiobutton(radioFrame, text=\"X?\", variable=playAsWhich, value=1) r1.grid(row=0, column=0, sticky=N+S+E+W) r1.invoke()",
"state = determineWinner() if(state == 3): makeMove() #this function starts a new tic",
"= tkFont.Font(family='Helvetica', size=72, weight='bold') buttons = [] i = 0 for r in",
"#this function loads up the spartan engineer website in a browser def openWebsite(event):",
"space # # of places where there is 2 o's beside an empty",
"b.append([board[y] for y in range(9) if(y == 0 or y == 3 or",
"should be 1(x) or 2(o) def threeInARow(board, x, a=[]): if(a == []): a",
"spaces in a row/col/diagonal # # of places where there is an o",
"winnerLabel['text'] = 'game started' theBoard = [0 for x in range(9)] for b",
"places where there is 2 o's beside an empty space # # of",
"used to evaluate the value of a tic tac toeboard #the features are",
"1 newGameButton = Button(frame, command=newGameClick, text=\"New Game?\") newGameButton.grid(row=3, column=0, sticky=N+S+E+W) playAsWhich = IntVar()",
"return state #update our tic tac toe board's graphical display def updateButtons(): for",
"'-' b['state'] = 'normal' if(computerSide == 1): makeMove() #this function loads up the",
"playerSide = playAsWhich.get() if(playerSide == 1): computerSide = 2 else: computerSide = 1",
"0): values[len(values)-1] = 0 elif(result == x): values[len(values)-1] = 100 else: values[len(values)-1] =",
"GUI for playing against the AI root = Tk() Grid.rowconfigure(root, 0, weight=1) Grid.columnconfigure(root,",
"2 empty spaces in a row/col/diagonal def openOne(board, x, a=[]): result = 0",
"or y == 6)]) return b #true if there is three in a",
"our tic tac toe AI for %d games (this may take a minute",
"a Tkinter # GUI. #------------------------------------------------------------------------------------- #Run via Python 2.7 #REQUIRES: pillow (python imaging",
"# is there 3 x's in a row (0 or 1) # is",
"for r in range(3): for c in range(3): button = Button(frame, text=\"-\", command=partial(buttonClick,",
"= 'disabled' return state #update our tic tac toe board's graphical display def",
"makeMove() #this function starts a new tic tac toe game vs the AI",
"for y in range(9) if(y == 2 or y == 5 or y",
"text=\"-\", command=partial(buttonClick, i)) button.grid(row=r, column=c, sticky=N+S+E+W) button['font'] = buttonFont button['state'] = 'disabled' buttons.append(button)",
"y == 7)]) b.append([board[y] for y in range(9) if(y == 2 or y",
"code to allow playing against the trained AI via a Tkinter # GUI.",
"i in range(9): if(theBoard[i] != 0): b = buttons[i] if(theBoard[i] == 1): b['text']",
"== 1): makeBestMove(theBoard, xWeights, 1) else: makeBestMove(theBoard, oWeights, 2) updateButtons() winnerLabel['text'] = 'player",
"range(len(values)): board = train[i] features = getFeatures(board) value = values[i] estimate = estimateMoveValue(features,",
"y == 8)]) b.append([board[y] for y in range(9) if(y == 0 or y",
"getCheckLists(board) if(threeInARow(board, 1, checkLists)): return 1 #x win elif(threeInARow(board, 2, checkLists)): return 2",
"spaces in a row/col/diagonal def getFeatures(board): a = board checkLists = getCheckLists(a) return",
"r2 = Radiobutton(radioFrame, text=\"O?\", variable=playAsWhich, value=2) r2.grid(row=0, column=1, sticky=N+S+E+W) winnerLabel = Label(frame, text=\"new",
"where there is 2 o's beside an empty space # # of places",
"'X' else: b['text'] = 'O' b['state'] = 'disabled' #makes a computer move def",
"computer move def makeMove(): if(computerSide == 1): makeBestMove(theBoard, xWeights, 1) else: makeBestMove(theBoard, oWeights,",
"= '-' b['state'] = 'normal' if(computerSide == 1): makeMove() #this function loads up",
"Tkinter GUI for playing against the AI root = Tk() Grid.rowconfigure(root, 0, weight=1)",
"right space #value mapping for a space in each board: # 0 ==",
"twoInARow(board, x, a=[]): result = 0 if(a == []): a = getCheckLists(board) for",
"sticky=N+S+E+W) Grid.rowconfigure(radioFrame, 0, weight=1) Grid.columnconfigure(radioFrame, 0, weight=1) Grid.columnconfigure(radioFrame, 1, weight=1) r1 = Radiobutton(radioFrame,",
"#------------------------------------------------------------------------------------- #------------------------------------------------------------------------------------- #------------------------------------------------------------------------------------- #Author: <NAME> #Date: 01/29/17 #Description: This code uses machine learning",
"space # 2 == top right space # 3 == center left space",
"1 board = [0 for x in range(9)] gameState = 3 while(gameState ==",
"weight=1) root.minsize(width=700, height=700) root.wm_title(\"SpartanTicTacToe\") spartanImage = ImageTk.PhotoImage(file=rootDirectory + '/resources/spartan-icon-small.png') root.call('wm', 'iconphoto', root._w, spartanImage)",
"column=0) spartanLabel = Label(spartanFrame, image=spartanImage, cursor='hand2') spartanLabel.pack() spartanTextLink = Label(spartanFrame, text='www.spartanengineer.com', fg='blue', cursor='hand2')",
"i in range(9): buttons[i]['state'] = 'disabled' return state #update our tic tac toe",
"'iconphoto', root._w, spartanImage) frame = Frame(root) frame.grid(row=0, column=0, sticky=N+S+E+W) buttonFont = tkFont.Font(family='Helvetica', size=72,",
"0.5 n_features = 6 oWeights = [initialWeight for i in range(n_features)] xWeights =",
"= 3 while(gameState == 3): if(turn == 1): makeBestMove(board, xWeights, turn) xTrain.append(copy.deepcopy(board)) else:",
"against the AI\") #---------------------------------------------------- #------------------GUI Code-------------------------- #---------------------------------------------------- #determines if the game is still",
"in range(len(weights)): weights[j] = weights[j] +(learnConstant*(value-estimate)*features[j]) #initialize our weights, the value of 0.5",
"2 == top right space # 3 == center left space # 4",
"an empty space # # of places where there is an x and",
"1): makeMove() #this function loads up the spartan engineer website in a browser",
"browser def openWebsite(event): webbrowser.open_new('http://www.spartanengineer.com') #the following code sets up the Tkinter GUI for",
"in range(len(values)-1): values[i] = estimateMoveValue(getFeatures(train[i+1]), weights) for i in range(len(values)): board = train[i]",
"r1.grid(row=0, column=0, sticky=N+S+E+W) r1.invoke() r2 = Radiobutton(radioFrame, text=\"O?\", variable=playAsWhich, value=2) r2.grid(row=0, column=1, sticky=N+S+E+W)",
"1): turn = 2 else: turn = 1 gameState = getGameState(board) return gameState",
"if(y == 1 or y == 4 or y == 7)]) b.append([board[y] for",
"sticky=N+S+E+W) r1.invoke() r2 = Radiobutton(radioFrame, text=\"O?\", variable=playAsWhich, value=2) r2.grid(row=0, column=1, sticky=N+S+E+W) winnerLabel =",
"'disabled' #makes a computer move def makeMove(): if(computerSide == 1): makeBestMove(theBoard, xWeights, 1)",
"and O AI #we pit AI's against each other in order to train",
"the user to play against the AI\") #---------------------------------------------------- #------------------GUI Code-------------------------- #---------------------------------------------------- #determines if",
"i)) button.grid(row=r, column=c, sticky=N+S+E+W) button['font'] = buttonFont button['state'] = 'disabled' buttons.append(button) i +=",
"== 3 or y == 6)]) #vertical b.append([board[y] for y in range(9) if(y",
"the board buttons are clicked def buttonClick(n): theBoard[n] = playerSide updateButtons() winnerLabel['text'] =",
"of places where there is an o and two empty spaces in a",
"if(board[i] == 0)] for i in range(len(positions)): position = positions[i] newBoard = copy.deepcopy(board)",
"== 5 or y == 8)]) b.append([board[y] for y in range(9) if(y ==",
"data from the last played game #the weights are updated by comparing the",
"features = getFeatures(board) value = values[i] estimate = estimateMoveValue(features, weights) #update our weights",
"in range(9) if(board[i] == 0)] for i in range(len(positions)): position = positions[i] newBoard",
"range(9) if(y == 0 or y == 4 or y == 8)]) #diagonal",
"a=[]): if(a == []): a = getCheckLists(board) for c in a: if(c.count(x) ==",
"1): b['text'] = 'X' else: b['text'] = 'O' b['state'] = 'disabled' #makes a",
"is an o and two empty spaces in a row/col/diagonal def getFeatures(board): a",
"(features[i] * weights[i]) return result #makes the best possible amongst all of the",
"== top center space # 2 == top right space # 3 ==",
"estimate = estimateMoveValue(features, weights) #update our weights for j in range(len(weights)): weights[j] =",
"range(9) if(y == 2 or y == 4 or y == 6)]) return",
"2 x/o's & an empty space in a row/col/diagonal def twoInARow(board, x, a=[]):",
"a minute or two...)\" % trainingIterations) for i in range(trainingIterations): xTrain, oTrain =",
"a = getCheckLists(board) for c in a: if(c.count(x) == 3): return True return",
"x in range(9)] gameState = 3 while(gameState == 3): if(turn == 1): makeBestMove(board,",
"1): makeBestMove(theBoard, xWeights, 1) else: makeBestMove(theBoard, oWeights, 2) updateButtons() winnerLabel['text'] = 'player turn'",
"# 4 == center center space # 5 == center right space #",
"if(threeInARow(board, 1, checkLists)): return 1 #x win elif(threeInARow(board, 2, checkLists)): return 2 #o",
"spartanFrame = Frame(frame) spartanFrame.grid(columnspan=3, row=4, column=0) spartanLabel = Label(spartanFrame, image=spartanImage, cursor='hand2') spartanLabel.pack() spartanTextLink",
"train our AI's def playGame(xWeights, oWeights, xTrain, oTrain): turn = 1 board =",
"(0 or 1) # is there 3 o's in a row (0 or",
"the AI\") #---------------------------------------------------- #------------------GUI Code-------------------------- #---------------------------------------------------- #determines if the game is still ongoing",
"if the game is still ongoing an updates the label correctly def determineWinner():",
"from Tkinter import * from functools import partial from PIL import ImageTk #-------------------------------------------------------------------------------------",
"buttonFont button['state'] = 'disabled' buttons.append(button) i += 1 newGameButton = Button(frame, command=newGameClick, text=\"New",
"& -100 are used for a draw, win, and loss def updateWeights(weights, train,",
"AI's against each other in order to train our AI's def playGame(xWeights, oWeights,",
"== 2 and c.count(0) == 1): result += 1 return result #returns the",
"may take a minute or two...)\" % trainingIterations) for i in range(trainingIterations): xTrain,",
"are as follows: # is there 3 x's in a row (0 or",
"True return False #returns the # of places where there is 2 x/o's",
"a space in each board: # 0 == empty space # 1 ==",
"xTrain, oTrain): turn = 1 board = [0 for x in range(9)] gameState",
"2 else: turn = 1 gameState = getGameState(board) return gameState #update our weights",
"state #update our tic tac toe board's graphical display def updateButtons(): for i",
"= 'normal' if(computerSide == 1): makeMove() #this function loads up the spartan engineer",
"= getCheckLists(board) for c in a: if(c.count(x) == 3): return True return False",
"2 == o space rootDirectory = os.path.dirname(os.path.realpath(__file__)) print('----------------------------------------------------') print('----------------------------------------------------') print('https://www.spartanengineer.com') print('----------------------------------------------------') print('----------------------------------------------------') learnConstant",
"to train a tic tac toe game AI. # It also includes code",
"AI!!!\") print(\"final weights: \") print(xWeights) print(oWeights) print(\"launching the GUI, this allows the user",
"xWeights = [initialWeight for i in range(n_features)] trainingIterations = 10000 print(\"training our tic",
"== 8)]) #diagonal b.append([board[y] for y in range(9) if(y == 2 or y",
"def twoInARow(board, x, a=[]): result = 0 if(a == []): a = getCheckLists(board)",
"features used to evaluate the value of a tic tac toeboard #the features",
"a = [i for i in range(9) if(board[i] == 0)] randomNum = random.randint(0,",
"win for o def getGameState(board): checkLists = getCheckLists(board) if(threeInARow(board, 1, checkLists)): return 1",
"PIL import ImageTk #------------------------------------------------------------------------------------- #------------------------------------------------------------------------------------- #------------------------------------------------------------------------------------- #Author: <NAME> #Date: 01/29/17 #Description: This code",
"winnerLabel['text'] = 'computer wins' if(state != 3): for i in range(9): buttons[i]['state'] =",
"= 'player turn' determineWinner() #this function is called when on the board buttons",
"move def makeMove(): if(computerSide == 1): makeBestMove(theBoard, xWeights, 1) else: makeBestMove(theBoard, oWeights, 2)",
"range(9): buttons[i]['state'] = 'disabled' return state #update our tic tac toe board's graphical",
"in a browser def openWebsite(event): webbrowser.open_new('http://www.spartanengineer.com') #the following code sets up the Tkinter",
"getGameState(board): checkLists = getCheckLists(board) if(threeInARow(board, 1, checkLists)): return 1 #x win elif(threeInARow(board, 2,",
"= weights[j] +(learnConstant*(value-estimate)*features[j]) #initialize our weights, the value of 0.5 is arbitrarily picked",
"center space # 8 == bottom right space #value mapping for a space",
"GUI, this allows the user to play against the AI\") #---------------------------------------------------- #------------------GUI Code--------------------------",
"board maps as follows: # 0 == top left space # 1 ==",
"by comparing the estimated move value with the actual move value #values of",
"if(a == []): a = getCheckLists(board) for c in a: if(c.count(x) == 2",
"a win for x, a win for o def getGameState(board): checkLists = getCheckLists(board)",
"for x in range(9)] for b in buttons: b['text'] = '-' b['state'] =",
"in range(n_features)] xWeights = [initialWeight for i in range(n_features)] trainingIterations = 10000 print(\"training",
"an o and two empty spaces in a row/col/diagonal def getFeatures(board): a =",
"1): result += 1 return result #returns the # of places where there",
"in range(9)] gameState = 3 while(gameState == 3): if(turn == 1): makeBestMove(board, xWeights,",
"the best possible amongst all of the possible moves def makeBestMove(board, weights, x):",
"o's beside an empty space # # of places where there is an",
"weights for j in range(len(weights)): weights[j] = weights[j] +(learnConstant*(value-estimate)*features[j]) #initialize our weights, the",
"b['text'] = 'O' b['state'] = 'disabled' #makes a computer move def makeMove(): if(computerSide",
"of a board based on the features (of the board) and their respective",
"conv[threeInARow(a, 2, checkLists)], twoInARow(a, 1, checkLists), twoInARow(a, 2, checkLists), openOne(a, 1, checkLists), openOne(a,",
"checkLists)] #returns the value of a board based on the features (of the",
"other in order to train our AI's def playGame(xWeights, oWeights, xTrain, oTrain): turn",
"sticky=N+S+E+W) buttonFont = tkFont.Font(family='Helvetica', size=72, weight='bold') buttons = [] i = 0 for",
"allows the user to play against the AI\") #---------------------------------------------------- #------------------GUI Code-------------------------- #---------------------------------------------------- #determines",
"[0 for x in range(9)] for b in buttons: b['text'] = '-' b['state']",
"if(turn == 1): turn = 2 else: turn = 1 gameState = getGameState(board)",
"[] b.append(board[0:3]) #horizontal b.append(board[3:6]) b.append(board[6:9]) b.append([board[y] for y in range(9) if(y == 0",
"if(y == 2 or y == 4 or y == 6)]) return b",
"[i for i in range(9) if(board[i] == 0)] for i in range(len(positions)): position",
"training our tic tac toe AI!!!\") print(\"final weights: \") print(xWeights) print(oWeights) print(\"launching the",
"used for a draw, win, and loss def updateWeights(weights, train, result, x): values",
"[], [] result = playGame(xWeights, oWeights, xTrain, oTrain) updateWeights(xWeights, xTrain, result, 1) updateWeights(oWeights,",
"# # of places where there is 2 x's beside an empty space",
"0 for r in range(3): for c in range(3): button = Button(frame, text=\"-\",",
"#diagonal b.append([board[y] for y in range(9) if(y == 2 or y == 4",
"train, result, x): values = [0 for i in range(len(train))] if(result == 0):",
"mValue = values[0] mPosition = positions[0] for i in range(1, len(positions)): if(values[i] >",
"play against the AI\") #---------------------------------------------------- #------------------GUI Code-------------------------- #---------------------------------------------------- #determines if the game is",
"== 1 and c.count(0) == 2): result += 1 return result #this function",
"range(len(values)-1): values[i] = estimateMoveValue(getFeatures(train[i+1]), weights) for i in range(len(values)): board = train[i] features",
"our weights based upon the training data from the last played game #the",
"oWeights, turn) oTrain.append(copy.deepcopy(board)) if(turn == 1): turn = 2 else: turn = 1",
"100, & -100 are used for a draw, win, and loss def updateWeights(weights,",
"== center center space # 5 == center right space # 6 ==",
"in range(3): for c in range(3): button = Button(frame, text=\"-\", command=partial(buttonClick, i)) button.grid(row=r,",
"root.wm_title(\"SpartanTicTacToe\") spartanImage = ImageTk.PhotoImage(file=rootDirectory + '/resources/spartan-icon-small.png') root.call('wm', 'iconphoto', root._w, spartanImage) frame = Frame(root)",
"#determines if the game is still ongoing an updates the label correctly def",
"is there 3 x's in a row (0 or 1) # is there",
"for c in a: if(c.count(x) == 1 and c.count(0) == 2): result +=",
"= getGameState(board) return gameState #update our weights based upon the training data from",
"elif(result == x): values[len(values)-1] = 100 else: values[len(values)-1] = -100 for i in",
"# tac toe board #the board maps as follows: # 0 == top",
"and their respective weights def estimateMoveValue(features, weights): result = 0 for i in",
"frame = Frame(root) frame.grid(row=0, column=0, sticky=N+S+E+W) buttonFont = tkFont.Font(family='Helvetica', size=72, weight='bold') buttons =",
"values[len(values)-1] = 100 else: values[len(values)-1] = -100 for i in range(len(values)-1): values[i] =",
"range(9) if(board[i] == 0)] randomNum = random.randint(0, len(a)-1) board[a[randomNum]] = x #plays a",
"newBoard = copy.deepcopy(board) newBoard[position] = x features = getFeatures(newBoard) value = estimateMoveValue(features, weights)",
"getCheckLists(board) for c in a: if(c.count(x) == 2 and c.count(0) == 1): result",
"= 'disabled' #makes a computer move def makeMove(): if(computerSide == 1): makeBestMove(theBoard, xWeights,",
"toe board's graphical display def updateButtons(): for i in range(9): if(theBoard[i] != 0):",
"value of a tic tac toeboard #the features are as follows: # is",
"= getCheckLists(board) if(threeInARow(board, 1, checkLists)): return 1 #x win elif(threeInARow(board, 2, checkLists)): return",
"there is three in a row, false if not #x parameter should be",
"as follows: # 0 == top left space # 1 == top center",
"in each board: # 0 == empty space # 1 == x space",
"tac toe AI!!!\") print(\"final weights: \") print(xWeights) print(oWeights) print(\"launching the GUI, this allows",
"or 1) # is there 3 o's in a row (0 or 1)",
"theBoard[n] = playerSide updateButtons() winnerLabel['text'] = 'computer turn' state = determineWinner() if(state ==",
"places where there is an o and two empty spaces in a row/col/diagonal",
"center left space # 4 == center center space # 5 == center",
"weights are updated by comparing the estimated move value with the actual move",
"boards.append(newBoard) values.append(value) mValue = values[0] mPosition = positions[0] for i in range(1, len(positions)):",
"'computer wins' if(state != 3): for i in range(9): buttons[i]['state'] = 'disabled' return"
] |
[
"given value ( e.g. the edge ) \"\"\" if verbose: print(('get_arr_edge_indices for arr",
"along edge else: coords += [[point_lon, lat_e[n]+(lat_diff*i)] for i in np.linspace(0, 1, extra_points_point_on_edge,",
"lon_e[nn] need_lon_outer_edge = True need_lon_outer_edge = False # Add mid point to coordinates",
"of data for each day return data4days, day_list def obs2grid(glon=None, glat=None, galt=None, nest='high",
"extra_points_point_on_edge, endpoint=True)] # temporally save the previous box's value last_lon_box = arr[nn, n]",
"---- Loop X dimension ( lon ) for nn, lon_ in enumerate(lon_c): #",
"data4days = [i.values.astype(float) for i in data4days] print([type(i) for i in data4days]) #",
"need_lon_outer_edge: point_lon = lon_e[nn+1] else: point_lon = lon_e[nn] need_lon_outer_edge = True need_lon_outer_edge =",
"data4days]) # print data4days[0] # sys.exit() if debug: print(('returning data for {} days,",
"Function flagged for removal \"\"\" if isinstance(glon, type(None)): glon, glat, galt = get_latlonalt4res(nest=nest,",
"i in np.linspace(0, 1, extra_points_point_on_edge, endpoint=True)] # temporally save the previous box's value",
"Make sure we select the edge lon if need_lon_outer_edge: point_lon = lon_e[nn+1] else:",
"data and the bins ( days ) \"\"\" if verbose: print('split_data_by_days called') #",
"this is mappable, update? df['days'] = [datetime.datetime(*i.timetuple()[:3]) for i in dates] if debug:",
"dimension ( lon ) for nn, lon_ in enumerate(lon_c): # Loop Y dimension",
"for i in np.linspace(0, 1, extra_points_point_on_edge, endpoint=True)] # temporally save the previous box's",
"list of data and the bins ( days ) \"\"\" if verbose: print('split_data_by_days",
"n], last_lat_box, last_lon_box, arr[nn, n] == last_lat_box, arr[nn, n] == last_lon_box)) if arr[nn,",
"print(('returning data for {} days, with lengths: '.format( len(day_list)), [len(i) for i in",
"the edge ) \"\"\" if verbose: print(('get_arr_edge_indices for arr of shape: ', arr.shape))",
"a list of datetimes and data and returns a list of data and",
"Pull out site location indicies indices_list = [] for site in sites: lon,",
"lon, lat, alt = loc_dict[site] vars = get_xy(lon, lat, glon, glat) indices_list +=",
"where value does not equal a given value ( e.g. the edge )",
"lon_c, lat_c, NIU = get_latlonalt4res(res=res, centre=True) lon_e, lat_e, NIU = get_latlonalt4res(res=res, centre=False) lon_diff",
"sure we select the edge lon if need_lon_outer_edge: point_lon = lon_e[nn+1] else: point_lon",
"box point_lon = lon_e[nn]+lon_diff/2 if need_lat_outer_edge: point_lat = lat_e[n+1] else: point_lat = lat_e[n]",
"debug=debug) # Assume use of known CAST sites... unless others given. if isinstance(sites,",
"Y dimension ( lat ) and store edges for n, lat_ in enumerate(lat_c):",
"# Just return the values ( i.e. not pandas array ) data4days =",
"n] need_lon_outer_edge, need_lat_outer_edge = False, False if debug: print((lon_e, lat_e)) # ---- Loop",
"site location indicies indices_list = [] for site in sites: lon, lat, alt",
"== day])) data4days += [df['data'][df['days'] == day]] # Just return the values (",
"day ) <= this is mappable, update? df['days'] = [datetime.datetime(*i.timetuple()[:3]) for i in",
"number of points along edge else: coords += [[lon_e[nn]+(lon_diff*i), point_lat] for i in",
"= lat_e[n+1] else: point_lat = lat_e[n] need_lat_outer_edge = True need_lat_outer_edge = False #",
"type(None)): glon, glat, galt = get_latlonalt4res(nest=nest, centre=False, debug=debug) # Assume use of known",
"lon ) for nn, lon_ in enumerate(lon_c): # Loop Y dimension ( lat",
"n], last_lat_box, last_lon_box, arr[nn, n] == last_lat_box, arr[nn, n] == last_lon_box)) # Loop",
"edge else: coords += [[lon_e[nn]+(lon_diff*i), point_lat] for i in np.linspace(0, 1, extra_points_point_on_edge, endpoint=True)]",
"i in data4days])) # Return as list of days (datetimes) + list of",
"type(None)): mid_point = [point_lon, point_lat] coords += [mid_point] # Add given number of",
"of points along edge else: coords += [[point_lon, lat_e[n]+(lat_diff*i)] for i in np.linspace(0,",
"of dates ( just year, month, day ) <= this is mappable, update?",
"\"\"\" Redundant misc. functions to be eventually removed from AC_tools. \"\"\" import os",
"Add list of dates ( just year, month, day ) <= this is",
"endpoint=True)] # temporally save the previous box's value last_lon_box = arr[nn, n] return",
"centre=False) lon_diff = lon_e[-5]-lon_e[-6] lat_diff = lat_e[-5]-lat_e[-6] nn, n, = 0, 0 last_lat_box",
"in data4days])) # Return as list of days (datetimes) + list of data",
"if verbose: print(('get_arr_edge_indices for arr of shape: ', arr.shape)) # initialise variables lon_c,",
"day])) data4days += [df['data'][df['days'] == day]] # Just return the values ( i.e.",
"\"\"\" values that have a given lat, lon and alt Notes ------- -",
"lat, alt = loc_dict[site] vars = get_xy(lon, lat, glon, glat) indices_list += [vars]",
"0 last_lat_box = arr[nn, n] coords = [] last_lon_box = arr[nn, n] need_lon_outer_edge,",
"n] != last_lon_box: point_lat = lat_e[n]+lat_diff/2 # Make sure we select the edge",
"arr[nn, n] == last_lon_box)) if arr[nn, n] != last_lat_box: # If 1st lat,",
"last_lon_box = arr[nn, n] need_lon_outer_edge, need_lat_outer_edge = False, False if debug: print((lon_e, lat_e))",
"Notes ------- - Function flagged for removal \"\"\" if isinstance(glon, type(None)): glon, glat,",
"eventually removed from AC_tools. \"\"\" import os import numpy as np from matplotlib.backends.backend_pdf",
"value ( e.g. the edge ) \"\"\" if verbose: print(('get_arr_edge_indices for arr of",
"in value at to list if arr[nn, n] != last_lon_box: point_lat = lat_e[n]+lat_diff/2",
"in data4days] print([type(i) for i in data4days]) # print data4days[0] # sys.exit() if",
"False # Add mid point to coordinates list if isinstance(extra_points_point_on_edge, type(None)): mid_point =",
"list(loc_dict.keys()) # Pull out site location indicies indices_list = [] for site in",
"store edges for nn, lon_ in enumerate(lon_c): # If change in value at",
"not pandas array ) data4days = [i.values.astype(float) for i in data4days] print([type(i) for",
"sites=None, debug=False): \"\"\" values that have a given lat, lon and alt Notes",
"arr.shape)) # initialise variables lon_c, lat_c, NIU = get_latlonalt4res(res=res, centre=True) lon_e, lat_e, NIU",
"lon_diff = lon_e[-5]-lon_e[-6] lat_diff = lat_e[-5]-lat_e[-6] nn, n, = 0, 0 last_lat_box =",
") data4days = [i.values.astype(float) for i in data4days] print([type(i) for i in data4days])",
"temporally save the previous box's value last_lon_box = arr[nn, n] return coords def",
"( lon ) for nn, lon_ in enumerate(lon_c): # Loop Y dimension (",
"last_lon_box: point_lat = lat_e[n]+lat_diff/2 # Make sure we select the edge lon if",
"[df['data'][df['days'] == day]] # Just return the values ( i.e. not pandas array",
"enumerate(lon_c): # If change in value at to list if arr[nn, n] !=",
"for nn, lon_ in enumerate(lon_c): # If change in value at to list",
"isinstance(extra_points_point_on_edge, type(None)): mid_point = [point_lon, point_lat] coords += [mid_point] # Add given number",
"if isinstance(glon, type(None)): glon, glat, galt = get_latlonalt4res(nest=nest, centre=False, debug=debug) # Assume use",
"res='4x5', extra_points_point_on_edge=None, verbose=True, debug=False): \"\"\" Find indices in a lon, lat (2D) grid,",
"[point_lon, point_lat] coords += [mid_point] # Add given number of points along edge",
"alt = loc_dict[site] vars = get_xy(lon, lat, glon, glat) indices_list += [vars] return",
"coords def split_data_by_days(data=None, dates=None, day_list=None, verbose=False, debug=False): \"\"\" Takes a list of datetimes",
"= lat_e[-5]-lat_e[-6] nn, n, = 0, 0 last_lat_box = arr[nn, n] coords =",
"lat ) and store edges for n, lat_ in enumerate(lat_c): if debug: print((arr[nn,",
"initialise variables lon_c, lat_c, NIU = get_latlonalt4res(res=res, centre=True) lon_e, lat_e, NIU = get_latlonalt4res(res=res,",
"dimension ( lat ) and store edges for n, lat_ in enumerate(lat_c): if",
"print([type(i) for i in data4days]) # print data4days[0] # sys.exit() if debug: print(('returning",
"unique days and select data on these days data4days = [] for day",
"+= [[lon_e[nn]+(lon_diff*i), point_lat] for i in np.linspace(0, 1, extra_points_point_on_edge, endpoint=True)] # temporally save",
"the values ( i.e. not pandas array ) data4days = [i.values.astype(float) for i",
"as plt from pandas import DataFrame # time import time import datetime as",
"lon_e, lat_e, NIU = get_latlonalt4res(res=res, centre=False) lon_diff = lon_e[-5]-lon_e[-6] lat_diff = lat_e[-5]-lat_e[-6] nn,",
"lat_e, NIU = get_latlonalt4res(res=res, centre=False) lon_diff = lon_e[-5]-lon_e[-6] lat_diff = lat_e[-5]-lat_e[-6] nn, n,",
"the previous box's value last_lat_box = arr[nn, n] # ---- Loop Y dimension",
"and store edges for n, lat_ in enumerate(lat_c): if debug: print((arr[nn, n], last_lat_box,",
"enumerate(lat_c): if debug: print((arr[nn, n], last_lat_box, last_lon_box, arr[nn, n] == last_lat_box, arr[nn, n]",
"lat ) for n, lat_ in enumerate(lat_c): if debug: print((arr[nn, n], last_lat_box, last_lon_box,",
"n] == last_lon_box)) # Loop X dimension ( lon ) and store edges",
"= [] last_lon_box = arr[nn, n] need_lon_outer_edge, need_lat_outer_edge = False, False if debug:",
"for day in day_list: print((day, df[df['days'] == day])) data4days += [df['data'][df['days'] == day]]",
"galt = get_latlonalt4res(nest=nest, centre=False, debug=debug) # Assume use of known CAST sites... unless",
"sites... unless others given. if isinstance(sites, type(None)): loc_dict = get_loc(rtn_dict=True) sites = list(loc_dict.keys())",
"point to coordinates list if isinstance(extra_points_point_on_edge, type(None)): mid_point = [point_lon, point_lat] coords +=",
"from pandas import DataFrame # time import time import datetime as datetime #",
"does not equal a given value ( e.g. the edge ) \"\"\" if",
"n, = 0, 0 last_lat_box = arr[nn, n] coords = [] last_lon_box =",
"# Add list of dates ( just year, month, day ) <= this",
"Just return the values ( i.e. not pandas array ) data4days = [i.values.astype(float)",
"mid point to cordinates list if isinstance(extra_points_point_on_edge, type(None)): mid_point = [point_lon, point_lat] coords",
"print('split_data_by_days called') # Create DataFrame of Data and dates df = DataFrame(data, index=dates,",
"days if isinstance(day_list, type(None)): day_list = sorted(set(df['days'].values)) # Loop unique days and select",
"= [] for day in day_list: print((day, df[df['days'] == day])) data4days += [df['data'][df['days']",
"[mid_point] # Add given number of points along edge else: coords += [[lon_e[nn]+(lon_diff*i),",
"in enumerate(lon_c): # If change in value at to list if arr[nn, n]",
"utf-8 -*- \"\"\" Redundant misc. functions to be eventually removed from AC_tools. \"\"\"",
"if need_lat_outer_edge: point_lat = lat_e[n+1] else: point_lat = lat_e[n] need_lat_outer_edge = True need_lat_outer_edge",
"day_list = sorted(set(df['days'].values)) # Loop unique days and select data on these days",
"lat_e[n+1] else: point_lat = lat_e[n] need_lat_outer_edge = True need_lat_outer_edge = False # Add",
"data4days[0] # sys.exit() if debug: print(('returning data for {} days, with lengths: '.format(",
"arr[nn, n] coords = [] last_lon_box = arr[nn, n] need_lon_outer_edge, need_lat_outer_edge = False,",
"and select data on these days data4days = [] for day in day_list:",
"n] # ---- Loop Y dimension ( lat ) for n, lat_ in",
"in a lon, lat (2D) grid, where value does not equal a given",
"coords += [[point_lon, lat_e[n]+(lat_diff*i)] for i in np.linspace(0, 1, extra_points_point_on_edge, endpoint=True)] # temporally",
"i.e. not pandas array ) data4days = [i.values.astype(float) for i in data4days] print([type(i)",
"\"\"\" Find indices in a lon, lat (2D) grid, where value does not",
"values that have a given lat, lon and alt Notes ------- - Function",
"If change in value at to list if arr[nn, n] != last_lon_box: point_lat",
"these days data4days = [] for day in day_list: print((day, df[df['days'] == day]))",
"dates ( just year, month, day ) <= this is mappable, update? df['days']",
"verbose: print('split_data_by_days called') # Create DataFrame of Data and dates df = DataFrame(data,",
"If 1st lat, selct bottom of box point_lon = lon_e[nn]+lon_diff/2 if need_lat_outer_edge: point_lat",
"# ---- Loop Y dimension ( lat ) for n, lat_ in enumerate(lat_c):",
"variables lon_c, lat_c, NIU = get_latlonalt4res(res=res, centre=True) lon_e, lat_e, NIU = get_latlonalt4res(res=res, centre=False)",
"(datetimes) + list of data for each day return data4days, day_list def obs2grid(glon=None,",
"= lon_e[nn]+lon_diff/2 if need_lat_outer_edge: point_lat = lat_e[n+1] else: point_lat = lat_e[n] need_lat_outer_edge =",
"not equal a given value ( e.g. the edge ) \"\"\" if verbose:",
"array ) data4days = [i.values.astype(float) for i in data4days] print([type(i) for i in",
"selct bottom of box point_lon = lon_e[nn]+lon_diff/2 if need_lat_outer_edge: point_lat = lat_e[n+1] else:",
"get_latlonalt4res(nest=nest, centre=False, debug=debug) # Assume use of known CAST sites... unless others given.",
"get_loc(rtn_dict=True) sites = list(loc_dict.keys()) # Pull out site location indicies indices_list = []",
"[[lon_e[nn]+(lon_diff*i), point_lat] for i in np.linspace(0, 1, extra_points_point_on_edge, endpoint=True)] # temporally save the",
"NIU = get_latlonalt4res(res=res, centre=True) lon_e, lat_e, NIU = get_latlonalt4res(res=res, centre=False) lon_diff = lon_e[-5]-lon_e[-6]",
"= [] for site in sites: lon, lat, alt = loc_dict[site] vars =",
"pandas import DataFrame # time import time import datetime as datetime # math",
"nn, lon_ in enumerate(lon_c): # Loop Y dimension ( lat ) and store",
"lat_e[n]+(lat_diff*i)] for i in np.linspace(0, 1, extra_points_point_on_edge, endpoint=True)] # temporally save the previous",
"Add given number of points along edge else: coords += [[lon_e[nn]+(lon_diff*i), point_lat] for",
"points along edge else: coords += [[point_lon, lat_e[n]+(lat_diff*i)] for i in np.linspace(0, 1,",
"CAST sites... unless others given. if isinstance(sites, type(None)): loc_dict = get_loc(rtn_dict=True) sites =",
"if debug: print((arr[nn, n], last_lat_box, last_lon_box, arr[nn, n] == last_lat_box, arr[nn, n] ==",
"if isinstance(day_list, type(None)): day_list = sorted(set(df['days'].values)) # Loop unique days and select data",
"# print data4days[0] # sys.exit() if debug: print(('returning data for {} days, with",
"point_lat = lat_e[n] need_lat_outer_edge = True need_lat_outer_edge = False # Add mid point",
"dimension ( lon ) and store edges for nn, lon_ in enumerate(lon_c): #",
"arr[nn, n] == last_lon_box)) # Loop X dimension ( lon ) and store",
"lon and alt Notes ------- - Function flagged for removal \"\"\" if isinstance(glon,",
"time import time import datetime as datetime # math from math import radians,",
"on these days data4days = [] for day in day_list: print((day, df[df['days'] ==",
"- Function flagged for removal \"\"\" if isinstance(glon, type(None)): glon, glat, galt =",
"if verbose: print('split_data_by_days called') # Create DataFrame of Data and dates df =",
"import os import numpy as np from matplotlib.backends.backend_pdf import PdfPages import matplotlib.pyplot as",
"# -*- coding: utf-8 -*- \"\"\" Redundant misc. functions to be eventually removed",
"Loop Y dimension ( lat ) for n, lat_ in enumerate(lat_c): if debug:",
"grid, where value does not equal a given value ( e.g. the edge",
"arr[nn, n] # ---- Loop Y dimension ( lat ) for n, lat_",
"functions to be eventually removed from AC_tools. \"\"\" import os import numpy as",
"equal a given value ( e.g. the edge ) \"\"\" if verbose: print(('get_arr_edge_indices",
"edges for nn, lon_ in enumerate(lon_c): # If change in value at to",
"Get list of unique days if isinstance(day_list, type(None)): day_list = sorted(set(df['days'].values)) # Loop",
"Add mid point to cordinates list if isinstance(extra_points_point_on_edge, type(None)): mid_point = [point_lon, point_lat]",
"we select the edge lon if need_lon_outer_edge: point_lon = lon_e[nn+1] else: point_lon =",
"last_lat_box, arr[nn, n] == last_lon_box)) # Loop X dimension ( lon ) and",
"== last_lon_box)) # Loop X dimension ( lon ) and store edges for",
"obs2grid(glon=None, glat=None, galt=None, nest='high res global', sites=None, debug=False): \"\"\" values that have a",
"( e.g. the edge ) \"\"\" if verbose: print(('get_arr_edge_indices for arr of shape:",
"to list if arr[nn, n] != last_lon_box: point_lat = lat_e[n]+lat_diff/2 # Make sure",
"and store edges for nn, lon_ in enumerate(lon_c): # If change in value",
"coordinates list if isinstance(extra_points_point_on_edge, type(None)): mid_point = [point_lon, point_lat] coords += [mid_point] #",
"from math import radians, sin, cos, asin, sqrt, pi, atan2 def get_arr_edge_indices(arr, res='4x5',",
"data on these days data4days = [] for day in day_list: print((day, df[df['days']",
"n] == last_lat_box, arr[nn, n] == last_lon_box)) # Loop X dimension ( lon",
"data4days])) # Return as list of days (datetimes) + list of data for",
"def obs2grid(glon=None, glat=None, galt=None, nest='high res global', sites=None, debug=False): \"\"\" values that have",
"\"\"\" import os import numpy as np from matplotlib.backends.backend_pdf import PdfPages import matplotlib.pyplot",
"dates] if debug: print(df) # Get list of unique days if isinstance(day_list, type(None)):",
"[] for day in day_list: print((day, df[df['days'] == day])) data4days += [df['data'][df['days'] ==",
"the edge lon if need_lon_outer_edge: point_lon = lon_e[nn+1] else: point_lon = lon_e[nn] need_lon_outer_edge",
"a given value ( e.g. the edge ) \"\"\" if verbose: print(('get_arr_edge_indices for",
"Loop X dimension ( lon ) and store edges for nn, lon_ in",
"and dates df = DataFrame(data, index=dates, columns=['data']) # Add list of dates (",
"return coords def split_data_by_days(data=None, dates=None, day_list=None, verbose=False, debug=False): \"\"\" Takes a list of",
"-*- coding: utf-8 -*- \"\"\" Redundant misc. functions to be eventually removed from",
"time import datetime as datetime # math from math import radians, sin, cos,",
"endpoint=True)] # temporally save the previous box's value last_lat_box = arr[nn, n] #",
"\"\"\" Takes a list of datetimes and data and returns a list of",
"data for {} days, with lengths: '.format( len(day_list)), [len(i) for i in data4days]))",
"AC_tools. \"\"\" import os import numpy as np from matplotlib.backends.backend_pdf import PdfPages import",
"0, 0 last_lat_box = arr[nn, n] coords = [] last_lon_box = arr[nn, n]",
"to coordinates list if isinstance(extra_points_point_on_edge, type(None)): mid_point = [point_lon, point_lat] coords += [mid_point]",
"last_lat_box, last_lon_box, arr[nn, n] == last_lat_box, arr[nn, n] == last_lon_box)) # Loop X",
"nn, n, = 0, 0 last_lat_box = arr[nn, n] coords = [] last_lon_box",
"= DataFrame(data, index=dates, columns=['data']) # Add list of dates ( just year, month,",
"if isinstance(sites, type(None)): loc_dict = get_loc(rtn_dict=True) sites = list(loc_dict.keys()) # Pull out site",
"known CAST sites... unless others given. if isinstance(sites, type(None)): loc_dict = get_loc(rtn_dict=True) sites",
"sites: lon, lat, alt = loc_dict[site] vars = get_xy(lon, lat, glon, glat) indices_list",
"e.g. the edge ) \"\"\" if verbose: print(('get_arr_edge_indices for arr of shape: ',",
"i in data4days] print([type(i) for i in data4days]) # print data4days[0] # sys.exit()",
"bins ( days ) \"\"\" if verbose: print('split_data_by_days called') # Create DataFrame of",
"import matplotlib.pyplot as plt from pandas import DataFrame # time import time import",
"# initialise variables lon_c, lat_c, NIU = get_latlonalt4res(res=res, centre=True) lon_e, lat_e, NIU =",
"select the edge lon if need_lon_outer_edge: point_lon = lon_e[nn+1] else: point_lon = lon_e[nn]",
"of days (datetimes) + list of data for each day return data4days, day_list",
"indicies indices_list = [] for site in sites: lon, lat, alt = loc_dict[site]",
"def get_arr_edge_indices(arr, res='4x5', extra_points_point_on_edge=None, verbose=True, debug=False): \"\"\" Find indices in a lon, lat",
"# If change in value at to list if arr[nn, n] != last_lon_box:",
"days and select data on these days data4days = [] for day in",
"-*- \"\"\" Redundant misc. functions to be eventually removed from AC_tools. \"\"\" import",
"coords = [] last_lon_box = arr[nn, n] need_lon_outer_edge, need_lat_outer_edge = False, False if",
"# Add mid point to coordinates list if isinstance(extra_points_point_on_edge, type(None)): mid_point = [point_lon,",
"from matplotlib.backends.backend_pdf import PdfPages import matplotlib.pyplot as plt from pandas import DataFrame #",
"point_lon = lon_e[nn+1] else: point_lon = lon_e[nn] need_lon_outer_edge = True need_lon_outer_edge = False",
"isinstance(sites, type(None)): loc_dict = get_loc(rtn_dict=True) sites = list(loc_dict.keys()) # Pull out site location",
"day_list def obs2grid(glon=None, glat=None, galt=None, nest='high res global', sites=None, debug=False): \"\"\" values that",
"df['days'] = [datetime.datetime(*i.timetuple()[:3]) for i in dates] if debug: print(df) # Get list",
"mappable, update? df['days'] = [datetime.datetime(*i.timetuple()[:3]) for i in dates] if debug: print(df) #",
"returns a list of data and the bins ( days ) \"\"\" if",
"# temporally save the previous box's value last_lon_box = arr[nn, n] return coords",
"list of unique days if isinstance(day_list, type(None)): day_list = sorted(set(df['days'].values)) # Loop unique",
"import DataFrame # time import time import datetime as datetime # math from",
"edges for n, lat_ in enumerate(lat_c): if debug: print((arr[nn, n], last_lat_box, last_lon_box, arr[nn,",
"need_lat_outer_edge: point_lat = lat_e[n+1] else: point_lat = lat_e[n] need_lat_outer_edge = True need_lat_outer_edge =",
"list if arr[nn, n] != last_lon_box: point_lat = lat_e[n]+lat_diff/2 # Make sure we",
"at to list if arr[nn, n] != last_lon_box: point_lat = lat_e[n]+lat_diff/2 # Make",
"and data and returns a list of data and the bins ( days",
"point_lon = lon_e[nn]+lon_diff/2 if need_lat_outer_edge: point_lat = lat_e[n+1] else: point_lat = lat_e[n] need_lat_outer_edge",
"value at to list if arr[nn, n] != last_lon_box: point_lat = lat_e[n]+lat_diff/2 #",
"called') # Create DataFrame of Data and dates df = DataFrame(data, index=dates, columns=['data'])",
"given number of points along edge else: coords += [[lon_e[nn]+(lon_diff*i), point_lat] for i",
"lat (2D) grid, where value does not equal a given value ( e.g.",
"( just year, month, day ) <= this is mappable, update? df['days'] =",
"data4days] print([type(i) for i in data4days]) # print data4days[0] # sys.exit() if debug:",
"asin, sqrt, pi, atan2 def get_arr_edge_indices(arr, res='4x5', extra_points_point_on_edge=None, verbose=True, debug=False): \"\"\" Find indices",
"{} days, with lengths: '.format( len(day_list)), [len(i) for i in data4days])) # Return",
"point_lat = lat_e[n+1] else: point_lat = lat_e[n] need_lat_outer_edge = True need_lat_outer_edge = False",
"lon_e[nn]+lon_diff/2 if need_lat_outer_edge: point_lat = lat_e[n+1] else: point_lat = lat_e[n] need_lat_outer_edge = True",
"in dates] if debug: print(df) # Get list of unique days if isinstance(day_list,",
"print(df) # Get list of unique days if isinstance(day_list, type(None)): day_list = sorted(set(df['days'].values))",
"a lon, lat (2D) grid, where value does not equal a given value",
"of unique days if isinstance(day_list, type(None)): day_list = sorted(set(df['days'].values)) # Loop unique days",
"else: coords += [[lon_e[nn]+(lon_diff*i), point_lat] for i in np.linspace(0, 1, extra_points_point_on_edge, endpoint=True)] #",
"last_lat_box = arr[nn, n] # ---- Loop Y dimension ( lat ) for",
"1, extra_points_point_on_edge, endpoint=True)] # temporally save the previous box's value last_lat_box = arr[nn,",
"in data4days]) # print data4days[0] # sys.exit() if debug: print(('returning data for {}",
"dimension ( lat ) for n, lat_ in enumerate(lat_c): if debug: print((arr[nn, n],",
"data4days, day_list def obs2grid(glon=None, glat=None, galt=None, nest='high res global', sites=None, debug=False): \"\"\" values",
"number of points along edge else: coords += [[point_lon, lat_e[n]+(lat_diff*i)] for i in",
"Y dimension ( lat ) for n, lat_ in enumerate(lat_c): if debug: print((arr[nn,",
"<= this is mappable, update? df['days'] = [datetime.datetime(*i.timetuple()[:3]) for i in dates] if",
"site in sites: lon, lat, alt = loc_dict[site] vars = get_xy(lon, lat, glon,",
"arr[nn, n] == last_lat_box, arr[nn, n] == last_lon_box)) # Loop X dimension (",
"print((arr[nn, n], last_lat_box, last_lon_box, arr[nn, n] == last_lat_box, arr[nn, n] == last_lon_box)) if",
"return data4days, day_list def obs2grid(glon=None, glat=None, galt=None, nest='high res global', sites=None, debug=False): \"\"\"",
") \"\"\" if verbose: print('split_data_by_days called') # Create DataFrame of Data and dates",
"have a given lat, lon and alt Notes ------- - Function flagged for",
") for n, lat_ in enumerate(lat_c): if debug: print((arr[nn, n], last_lat_box, last_lon_box, arr[nn,",
"= lon_e[-5]-lon_e[-6] lat_diff = lat_e[-5]-lat_e[-6] nn, n, = 0, 0 last_lat_box = arr[nn,",
"Redundant misc. functions to be eventually removed from AC_tools. \"\"\" import os import",
"if need_lon_outer_edge: point_lon = lon_e[nn+1] else: point_lon = lon_e[nn] need_lon_outer_edge = True need_lon_outer_edge",
"removed from AC_tools. \"\"\" import os import numpy as np from matplotlib.backends.backend_pdf import",
"np.linspace(0, 1, extra_points_point_on_edge, endpoint=True)] # temporally save the previous box's value last_lon_box =",
"unless others given. if isinstance(sites, type(None)): loc_dict = get_loc(rtn_dict=True) sites = list(loc_dict.keys()) #",
"verbose=True, debug=False): \"\"\" Find indices in a lon, lat (2D) grid, where value",
"True need_lon_outer_edge = False # Add mid point to coordinates list if isinstance(extra_points_point_on_edge,",
"store edges for n, lat_ in enumerate(lat_c): if debug: print((arr[nn, n], last_lat_box, last_lon_box,",
"coords += [mid_point] # Add given number of points along edge else: coords",
"isinstance(glon, type(None)): glon, glat, galt = get_latlonalt4res(nest=nest, centre=False, debug=debug) # Assume use of",
"coords += [[lon_e[nn]+(lon_diff*i), point_lat] for i in np.linspace(0, 1, extra_points_point_on_edge, endpoint=True)] # temporally",
"point_lon = lon_e[nn] need_lon_outer_edge = True need_lon_outer_edge = False # Add mid point",
"update? df['days'] = [datetime.datetime(*i.timetuple()[:3]) for i in dates] if debug: print(df) # Get",
"bottom of box point_lon = lon_e[nn]+lon_diff/2 if need_lat_outer_edge: point_lat = lat_e[n+1] else: point_lat",
"datetime # math from math import radians, sin, cos, asin, sqrt, pi, atan2",
"for n, lat_ in enumerate(lat_c): if debug: print((arr[nn, n], last_lat_box, last_lon_box, arr[nn, n]",
"X dimension ( lon ) and store edges for nn, lon_ in enumerate(lon_c):",
"cos, asin, sqrt, pi, atan2 def get_arr_edge_indices(arr, res='4x5', extra_points_point_on_edge=None, verbose=True, debug=False): \"\"\" Find",
"last_lon_box = arr[nn, n] return coords def split_data_by_days(data=None, dates=None, day_list=None, verbose=False, debug=False): \"\"\"",
"= get_latlonalt4res(res=res, centre=False) lon_diff = lon_e[-5]-lon_e[-6] lat_diff = lat_e[-5]-lat_e[-6] nn, n, = 0,",
"need_lon_outer_edge = False # Add mid point to coordinates list if isinstance(extra_points_point_on_edge, type(None)):",
"'.format( len(day_list)), [len(i) for i in data4days])) # Return as list of days",
"Takes a list of datetimes and data and returns a list of data",
"= True need_lat_outer_edge = False # Add mid point to cordinates list if",
"lon_ in enumerate(lon_c): # If change in value at to list if arr[nn,",
"misc. functions to be eventually removed from AC_tools. \"\"\" import os import numpy",
"dates df = DataFrame(data, index=dates, columns=['data']) # Add list of dates ( just",
"last_lon_box)) # Loop X dimension ( lon ) and store edges for nn,",
"extra_points_point_on_edge, endpoint=True)] # temporally save the previous box's value last_lat_box = arr[nn, n]",
"last_lat_box, last_lon_box, arr[nn, n] == last_lat_box, arr[nn, n] == last_lon_box)) if arr[nn, n]",
"# Loop unique days and select data on these days data4days = []",
"box's value last_lon_box = arr[nn, n] return coords def split_data_by_days(data=None, dates=None, day_list=None, verbose=False,",
"previous box's value last_lat_box = arr[nn, n] # ---- Loop Y dimension (",
"math import radians, sin, cos, asin, sqrt, pi, atan2 def get_arr_edge_indices(arr, res='4x5', extra_points_point_on_edge=None,",
"of datetimes and data and returns a list of data and the bins",
"select data on these days data4days = [] for day in day_list: print((day,",
"if debug: print((lon_e, lat_e)) # ---- Loop X dimension ( lon ) for",
"lat_e[-5]-lat_e[-6] nn, n, = 0, 0 last_lat_box = arr[nn, n] coords = []",
"print((lon_e, lat_e)) # ---- Loop X dimension ( lon ) for nn, lon_",
"previous box's value last_lon_box = arr[nn, n] return coords def split_data_by_days(data=None, dates=None, day_list=None,",
"in enumerate(lon_c): # Loop Y dimension ( lat ) and store edges for",
"= [point_lon, point_lat] coords += [mid_point] # Add given number of points along",
"len(day_list)), [len(i) for i in data4days])) # Return as list of days (datetimes)",
"debug: print(('returning data for {} days, with lengths: '.format( len(day_list)), [len(i) for i",
"last_lon_box)) if arr[nn, n] != last_lat_box: # If 1st lat, selct bottom of",
"= get_latlonalt4res(res=res, centre=True) lon_e, lat_e, NIU = get_latlonalt4res(res=res, centre=False) lon_diff = lon_e[-5]-lon_e[-6] lat_diff",
"that have a given lat, lon and alt Notes ------- - Function flagged",
"just year, month, day ) <= this is mappable, update? df['days'] = [datetime.datetime(*i.timetuple()[:3])",
"plt from pandas import DataFrame # time import time import datetime as datetime",
"nest='high res global', sites=None, debug=False): \"\"\" values that have a given lat, lon",
"# Return as list of days (datetimes) + list of data for each",
"X dimension ( lon ) for nn, lon_ in enumerate(lon_c): # Loop Y",
"glat, galt = get_latlonalt4res(nest=nest, centre=False, debug=debug) # Assume use of known CAST sites...",
"from AC_tools. \"\"\" import os import numpy as np from matplotlib.backends.backend_pdf import PdfPages",
"matplotlib.backends.backend_pdf import PdfPages import matplotlib.pyplot as plt from pandas import DataFrame # time",
"lengths: '.format( len(day_list)), [len(i) for i in data4days])) # Return as list of",
"in np.linspace(0, 1, extra_points_point_on_edge, endpoint=True)] # temporally save the previous box's value last_lon_box",
"of points along edge else: coords += [[lon_e[nn]+(lon_diff*i), point_lat] for i in np.linspace(0,",
"month, day ) <= this is mappable, update? df['days'] = [datetime.datetime(*i.timetuple()[:3]) for i",
"edge else: coords += [[point_lon, lat_e[n]+(lat_diff*i)] for i in np.linspace(0, 1, extra_points_point_on_edge, endpoint=True)]",
"# Get list of unique days if isinstance(day_list, type(None)): day_list = sorted(set(df['days'].values)) #",
"of data and the bins ( days ) \"\"\" if verbose: print('split_data_by_days called')",
"res global', sites=None, debug=False): \"\"\" values that have a given lat, lon and",
"os import numpy as np from matplotlib.backends.backend_pdf import PdfPages import matplotlib.pyplot as plt",
"data4days += [df['data'][df['days'] == day]] # Just return the values ( i.e. not",
"last_lat_box = arr[nn, n] coords = [] last_lon_box = arr[nn, n] need_lon_outer_edge, need_lat_outer_edge",
"list if isinstance(extra_points_point_on_edge, type(None)): mid_point = [point_lon, point_lat] coords += [mid_point] # Add",
"need_lat_outer_edge = False # Add mid point to cordinates list if isinstance(extra_points_point_on_edge, type(None)):",
"lat_e[n]+lat_diff/2 # Make sure we select the edge lon if need_lon_outer_edge: point_lon =",
"= True need_lon_outer_edge = False # Add mid point to coordinates list if",
"debug=False): \"\"\" Takes a list of datetimes and data and returns a list",
"else: coords += [[point_lon, lat_e[n]+(lat_diff*i)] for i in np.linspace(0, 1, extra_points_point_on_edge, endpoint=True)] #",
"day_list: print((day, df[df['days'] == day])) data4days += [df['data'][df['days'] == day]] # Just return",
"value last_lat_box = arr[nn, n] # ---- Loop Y dimension ( lat )",
"temporally save the previous box's value last_lat_box = arr[nn, n] # ---- Loop",
"lon_e[nn+1] else: point_lon = lon_e[nn] need_lon_outer_edge = True need_lon_outer_edge = False # Add",
"import PdfPages import matplotlib.pyplot as plt from pandas import DataFrame # time import",
"+= [df['data'][df['days'] == day]] # Just return the values ( i.e. not pandas",
"enumerate(lon_c): # Loop Y dimension ( lat ) and store edges for n,",
"value does not equal a given value ( e.g. the edge ) \"\"\"",
"sorted(set(df['days'].values)) # Loop unique days and select data on these days data4days =",
"verbose: print(('get_arr_edge_indices for arr of shape: ', arr.shape)) # initialise variables lon_c, lat_c,",
"save the previous box's value last_lon_box = arr[nn, n] return coords def split_data_by_days(data=None,",
"= False # Add mid point to coordinates list if isinstance(extra_points_point_on_edge, type(None)): mid_point",
"change in value at to list if arr[nn, n] != last_lon_box: point_lat =",
"arr[nn, n] != last_lat_box: # If 1st lat, selct bottom of box point_lon",
"== last_lat_box, arr[nn, n] == last_lon_box)) if arr[nn, n] != last_lat_box: # If",
"if debug: print(df) # Get list of unique days if isinstance(day_list, type(None)): day_list",
"global', sites=None, debug=False): \"\"\" values that have a given lat, lon and alt",
"flagged for removal \"\"\" if isinstance(glon, type(None)): glon, glat, galt = get_latlonalt4res(nest=nest, centre=False,",
"use of known CAST sites... unless others given. if isinstance(sites, type(None)): loc_dict =",
"[[point_lon, lat_e[n]+(lat_diff*i)] for i in np.linspace(0, 1, extra_points_point_on_edge, endpoint=True)] # temporally save the",
"days data4days = [] for day in day_list: print((day, df[df['days'] == day])) data4days",
"in np.linspace(0, 1, extra_points_point_on_edge, endpoint=True)] # temporally save the previous box's value last_lat_box",
"lat_ in enumerate(lat_c): if debug: print((arr[nn, n], last_lat_box, last_lon_box, arr[nn, n] == last_lat_box,",
"== last_lat_box, arr[nn, n] == last_lon_box)) # Loop X dimension ( lon )",
"data and returns a list of data and the bins ( days )",
"Assume use of known CAST sites... unless others given. if isinstance(sites, type(None)): loc_dict",
"need_lat_outer_edge = True need_lat_outer_edge = False # Add mid point to cordinates list",
"is mappable, update? df['days'] = [datetime.datetime(*i.timetuple()[:3]) for i in dates] if debug: print(df)",
"# Pull out site location indicies indices_list = [] for site in sites:",
"', arr.shape)) # initialise variables lon_c, lat_c, NIU = get_latlonalt4res(res=res, centre=True) lon_e, lat_e,",
"[] last_lon_box = arr[nn, n] need_lon_outer_edge, need_lat_outer_edge = False, False if debug: print((lon_e,",
"as np from matplotlib.backends.backend_pdf import PdfPages import matplotlib.pyplot as plt from pandas import",
"the bins ( days ) \"\"\" if verbose: print('split_data_by_days called') # Create DataFrame",
"cordinates list if isinstance(extra_points_point_on_edge, type(None)): mid_point = [point_lon, point_lat] coords += [mid_point] #",
"math from math import radians, sin, cos, asin, sqrt, pi, atan2 def get_arr_edge_indices(arr,",
"in day_list: print((day, df[df['days'] == day])) data4days += [df['data'][df['days'] == day]] # Just",
"import datetime as datetime # math from math import radians, sin, cos, asin,",
"get_latlonalt4res(res=res, centre=True) lon_e, lat_e, NIU = get_latlonalt4res(res=res, centre=False) lon_diff = lon_e[-5]-lon_e[-6] lat_diff =",
"and returns a list of data and the bins ( days ) \"\"\"",
"mid point to coordinates list if isinstance(extra_points_point_on_edge, type(None)): mid_point = [point_lon, point_lat] coords",
"if arr[nn, n] != last_lat_box: # If 1st lat, selct bottom of box",
"type(None)): day_list = sorted(set(df['days'].values)) # Loop unique days and select data on these",
"print((day, df[df['days'] == day])) data4days += [df['data'][df['days'] == day]] # Just return the",
"= [i.values.astype(float) for i in data4days] print([type(i) for i in data4days]) # print",
"loc_dict = get_loc(rtn_dict=True) sites = list(loc_dict.keys()) # Pull out site location indicies indices_list",
"need_lat_outer_edge = False, False if debug: print((lon_e, lat_e)) # ---- Loop X dimension",
"debug: print(df) # Get list of unique days if isinstance(day_list, type(None)): day_list =",
"sites = list(loc_dict.keys()) # Pull out site location indicies indices_list = [] for",
"Data and dates df = DataFrame(data, index=dates, columns=['data']) # Add list of dates",
"Add given number of points along edge else: coords += [[point_lon, lat_e[n]+(lat_diff*i)] for",
"sys.exit() if debug: print(('returning data for {} days, with lengths: '.format( len(day_list)), [len(i)",
"need_lon_outer_edge, need_lat_outer_edge = False, False if debug: print((lon_e, lat_e)) # ---- Loop X",
"= False, False if debug: print((lon_e, lat_e)) # ---- Loop X dimension (",
"lat_c, NIU = get_latlonalt4res(res=res, centre=True) lon_e, lat_e, NIU = get_latlonalt4res(res=res, centre=False) lon_diff =",
"= [datetime.datetime(*i.timetuple()[:3]) for i in dates] if debug: print(df) # Get list of",
"= 0, 0 last_lat_box = arr[nn, n] coords = [] last_lon_box = arr[nn,",
"# ---- Loop X dimension ( lon ) for nn, lon_ in enumerate(lon_c):",
"# Create DataFrame of Data and dates df = DataFrame(data, index=dates, columns=['data']) #",
"list of datetimes and data and returns a list of data and the",
"return the values ( i.e. not pandas array ) data4days = [i.values.astype(float) for",
"n] == last_lon_box)) if arr[nn, n] != last_lat_box: # If 1st lat, selct",
"unique days if isinstance(day_list, type(None)): day_list = sorted(set(df['days'].values)) # Loop unique days and",
"along edge else: coords += [[lon_e[nn]+(lon_diff*i), point_lat] for i in np.linspace(0, 1, extra_points_point_on_edge,",
"else: point_lon = lon_e[nn] need_lon_outer_edge = True need_lon_outer_edge = False # Add mid",
"lat, selct bottom of box point_lon = lon_e[nn]+lon_diff/2 if need_lat_outer_edge: point_lat = lat_e[n+1]",
"False if debug: print((lon_e, lat_e)) # ---- Loop X dimension ( lon )",
"and alt Notes ------- - Function flagged for removal \"\"\" if isinstance(glon, type(None)):",
"Loop Y dimension ( lat ) and store edges for n, lat_ in",
") <= this is mappable, update? df['days'] = [datetime.datetime(*i.timetuple()[:3]) for i in dates]",
"if isinstance(extra_points_point_on_edge, type(None)): mid_point = [point_lon, point_lat] coords += [mid_point] # Add given",
"removal \"\"\" if isinstance(glon, type(None)): glon, glat, galt = get_latlonalt4res(nest=nest, centre=False, debug=debug) #",
"box's value last_lat_box = arr[nn, n] # ---- Loop Y dimension ( lat",
"arr[nn, n] != last_lon_box: point_lat = lat_e[n]+lat_diff/2 # Make sure we select the",
"\"\"\" if isinstance(glon, type(None)): glon, glat, galt = get_latlonalt4res(nest=nest, centre=False, debug=debug) # Assume",
"debug=False): \"\"\" Find indices in a lon, lat (2D) grid, where value does",
"Find indices in a lon, lat (2D) grid, where value does not equal",
"---- Loop Y dimension ( lat ) for n, lat_ in enumerate(lat_c): if",
"alt Notes ------- - Function flagged for removal \"\"\" if isinstance(glon, type(None)): glon,",
"list of dates ( just year, month, day ) <= this is mappable,",
"days (datetimes) + list of data for each day return data4days, day_list def",
"import radians, sin, cos, asin, sqrt, pi, atan2 def get_arr_edge_indices(arr, res='4x5', extra_points_point_on_edge=None, verbose=True,",
"the previous box's value last_lon_box = arr[nn, n] return coords def split_data_by_days(data=None, dates=None,",
"# Make sure we select the edge lon if need_lon_outer_edge: point_lon = lon_e[nn+1]",
"= loc_dict[site] vars = get_xy(lon, lat, glon, glat) indices_list += [vars] return indices_list",
"Create DataFrame of Data and dates df = DataFrame(data, index=dates, columns=['data']) # Add",
"= False # Add mid point to cordinates list if isinstance(extra_points_point_on_edge, type(None)): mid_point",
"== day]] # Just return the values ( i.e. not pandas array )",
"be eventually removed from AC_tools. \"\"\" import os import numpy as np from",
"( lon ) and store edges for nn, lon_ in enumerate(lon_c): # If",
"# Assume use of known CAST sites... unless others given. if isinstance(sites, type(None)):",
"= arr[nn, n] return coords def split_data_by_days(data=None, dates=None, day_list=None, verbose=False, debug=False): \"\"\" Takes",
"i in dates] if debug: print(df) # Get list of unique days if",
"# If 1st lat, selct bottom of box point_lon = lon_e[nn]+lon_diff/2 if need_lat_outer_edge:",
"n] == last_lat_box, arr[nn, n] == last_lon_box)) if arr[nn, n] != last_lat_box: #",
") for nn, lon_ in enumerate(lon_c): # Loop Y dimension ( lat )",
"centre=True) lon_e, lat_e, NIU = get_latlonalt4res(res=res, centre=False) lon_diff = lon_e[-5]-lon_e[-6] lat_diff = lat_e[-5]-lat_e[-6]",
"for {} days, with lengths: '.format( len(day_list)), [len(i) for i in data4days])) #",
"= get_loc(rtn_dict=True) sites = list(loc_dict.keys()) # Pull out site location indicies indices_list =",
"last_lat_box: # If 1st lat, selct bottom of box point_lon = lon_e[nn]+lon_diff/2 if",
"lon, lat (2D) grid, where value does not equal a given value (",
"indices in a lon, lat (2D) grid, where value does not equal a",
"isinstance(day_list, type(None)): day_list = sorted(set(df['days'].values)) # Loop unique days and select data on",
"debug: print((arr[nn, n], last_lat_box, last_lon_box, arr[nn, n] == last_lat_box, arr[nn, n] == last_lon_box))",
"dates=None, day_list=None, verbose=False, debug=False): \"\"\" Takes a list of datetimes and data and",
"np from matplotlib.backends.backend_pdf import PdfPages import matplotlib.pyplot as plt from pandas import DataFrame",
"Add mid point to coordinates list if isinstance(extra_points_point_on_edge, type(None)): mid_point = [point_lon, point_lat]",
"= arr[nn, n] coords = [] last_lon_box = arr[nn, n] need_lon_outer_edge, need_lat_outer_edge =",
"!= last_lon_box: point_lat = lat_e[n]+lat_diff/2 # Make sure we select the edge lon",
"days, with lengths: '.format( len(day_list)), [len(i) for i in data4days])) # Return as",
"import numpy as np from matplotlib.backends.backend_pdf import PdfPages import matplotlib.pyplot as plt from",
"arr[nn, n] return coords def split_data_by_days(data=None, dates=None, day_list=None, verbose=False, debug=False): \"\"\" Takes a",
"arr of shape: ', arr.shape)) # initialise variables lon_c, lat_c, NIU = get_latlonalt4res(res=res,",
"glat=None, galt=None, nest='high res global', sites=None, debug=False): \"\"\" values that have a given",
"#!/usr/bin/python # -*- coding: utf-8 -*- \"\"\" Redundant misc. functions to be eventually",
"n] != last_lat_box: # If 1st lat, selct bottom of box point_lon =",
"for i in data4days])) # Return as list of days (datetimes) + list",
"type(None)): loc_dict = get_loc(rtn_dict=True) sites = list(loc_dict.keys()) # Pull out site location indicies",
"if arr[nn, n] != last_lon_box: point_lat = lat_e[n]+lat_diff/2 # Make sure we select",
") and store edges for nn, lon_ in enumerate(lon_c): # If change in",
"get_arr_edge_indices(arr, res='4x5', extra_points_point_on_edge=None, verbose=True, debug=False): \"\"\" Find indices in a lon, lat (2D)",
"+ list of data for each day return data4days, day_list def obs2grid(glon=None, glat=None,",
"to cordinates list if isinstance(extra_points_point_on_edge, type(None)): mid_point = [point_lon, point_lat] coords += [mid_point]",
"for i in data4days] print([type(i) for i in data4days]) # print data4days[0] #",
"[mid_point] # Add given number of points along edge else: coords += [[point_lon,",
"for nn, lon_ in enumerate(lon_c): # Loop Y dimension ( lat ) and",
"arr[nn, n] == last_lat_box, arr[nn, n] == last_lon_box)) if arr[nn, n] != last_lat_box:",
"lon_ in enumerate(lon_c): # Loop Y dimension ( lat ) and store edges",
"= lon_e[nn] need_lon_outer_edge = True need_lon_outer_edge = False # Add mid point to",
"day_list=None, verbose=False, debug=False): \"\"\" Takes a list of datetimes and data and returns",
"Return as list of days (datetimes) + list of data for each day",
"radians, sin, cos, asin, sqrt, pi, atan2 def get_arr_edge_indices(arr, res='4x5', extra_points_point_on_edge=None, verbose=True, debug=False):",
"= arr[nn, n] # ---- Loop Y dimension ( lat ) for n,",
"of shape: ', arr.shape)) # initialise variables lon_c, lat_c, NIU = get_latlonalt4res(res=res, centre=True)",
") and store edges for n, lat_ in enumerate(lat_c): if debug: print((arr[nn, n],",
"split_data_by_days(data=None, dates=None, day_list=None, verbose=False, debug=False): \"\"\" Takes a list of datetimes and data",
"out site location indicies indices_list = [] for site in sites: lon, lat,",
"# temporally save the previous box's value last_lat_box = arr[nn, n] # ----",
"point to cordinates list if isinstance(extra_points_point_on_edge, type(None)): mid_point = [point_lon, point_lat] coords +=",
"last_lon_box, arr[nn, n] == last_lat_box, arr[nn, n] == last_lon_box)) if arr[nn, n] !=",
"point_lat = lat_e[n]+lat_diff/2 # Make sure we select the edge lon if need_lon_outer_edge:",
"( lat ) for n, lat_ in enumerate(lat_c): if debug: print((arr[nn, n], last_lat_box,",
"for site in sites: lon, lat, alt = loc_dict[site] vars = get_xy(lon, lat,",
"if debug: print(('returning data for {} days, with lengths: '.format( len(day_list)), [len(i) for",
"glon, glat, galt = get_latlonalt4res(nest=nest, centre=False, debug=debug) # Assume use of known CAST",
"in enumerate(lat_c): if debug: print((arr[nn, n], last_lat_box, last_lon_box, arr[nn, n] == last_lat_box, arr[nn,",
"DataFrame(data, index=dates, columns=['data']) # Add list of dates ( just year, month, day",
"debug: print((lon_e, lat_e)) # ---- Loop X dimension ( lon ) for nn,",
"# Loop Y dimension ( lat ) and store edges for n, lat_",
"as list of days (datetimes) + list of data for each day return",
"import time import datetime as datetime # math from math import radians, sin,",
"pandas array ) data4days = [i.values.astype(float) for i in data4days] print([type(i) for i",
"= lat_e[n] need_lat_outer_edge = True need_lat_outer_edge = False # Add mid point to",
"np.linspace(0, 1, extra_points_point_on_edge, endpoint=True)] # temporally save the previous box's value last_lat_box =",
"for i in dates] if debug: print(df) # Get list of unique days",
"debug=False): \"\"\" values that have a given lat, lon and alt Notes -------",
"( i.e. not pandas array ) data4days = [i.values.astype(float) for i in data4days]",
"and the bins ( days ) \"\"\" if verbose: print('split_data_by_days called') # Create",
"# math from math import radians, sin, cos, asin, sqrt, pi, atan2 def",
"extra_points_point_on_edge=None, verbose=True, debug=False): \"\"\" Find indices in a lon, lat (2D) grid, where",
"i in data4days]) # print data4days[0] # sys.exit() if debug: print(('returning data for",
"!= last_lat_box: # If 1st lat, selct bottom of box point_lon = lon_e[nn]+lon_diff/2",
"need_lon_outer_edge = True need_lon_outer_edge = False # Add mid point to coordinates list",
"= list(loc_dict.keys()) # Pull out site location indicies indices_list = [] for site",
"nn, lon_ in enumerate(lon_c): # If change in value at to list if",
"last_lon_box, arr[nn, n] == last_lat_box, arr[nn, n] == last_lon_box)) # Loop X dimension",
"= lat_e[n]+lat_diff/2 # Make sure we select the edge lon if need_lon_outer_edge: point_lon",
"False # Add mid point to cordinates list if isinstance(extra_points_point_on_edge, type(None)): mid_point =",
"Loop unique days and select data on these days data4days = [] for",
"verbose=False, debug=False): \"\"\" Takes a list of datetimes and data and returns a",
"else: point_lat = lat_e[n] need_lat_outer_edge = True need_lat_outer_edge = False # Add mid",
"------- - Function flagged for removal \"\"\" if isinstance(glon, type(None)): glon, glat, galt",
"datetime as datetime # math from math import radians, sin, cos, asin, sqrt,",
"# sys.exit() if debug: print(('returning data for {} days, with lengths: '.format( len(day_list)),",
"save the previous box's value last_lat_box = arr[nn, n] # ---- Loop Y",
"year, month, day ) <= this is mappable, update? df['days'] = [datetime.datetime(*i.timetuple()[:3]) for",
"of Data and dates df = DataFrame(data, index=dates, columns=['data']) # Add list of",
"given. if isinstance(sites, type(None)): loc_dict = get_loc(rtn_dict=True) sites = list(loc_dict.keys()) # Pull out",
"= arr[nn, n] need_lon_outer_edge, need_lat_outer_edge = False, False if debug: print((lon_e, lat_e)) #",
"# Add given number of points along edge else: coords += [[point_lon, lat_e[n]+(lat_diff*i)]",
"[i.values.astype(float) for i in data4days] print([type(i) for i in data4days]) # print data4days[0]",
"lon_e[-5]-lon_e[-6] lat_diff = lat_e[-5]-lat_e[-6] nn, n, = 0, 0 last_lat_box = arr[nn, n]",
"\"\"\" if verbose: print('split_data_by_days called') # Create DataFrame of Data and dates df",
"print data4days[0] # sys.exit() if debug: print(('returning data for {} days, with lengths:",
"lat_e)) # ---- Loop X dimension ( lon ) for nn, lon_ in",
"\"\"\" if verbose: print(('get_arr_edge_indices for arr of shape: ', arr.shape)) # initialise variables",
"+= [mid_point] # Add given number of points along edge else: coords +=",
"to be eventually removed from AC_tools. \"\"\" import os import numpy as np",
"# Add mid point to cordinates list if isinstance(extra_points_point_on_edge, type(None)): mid_point = [point_lon,",
"lon if need_lon_outer_edge: point_lon = lon_e[nn+1] else: point_lon = lon_e[nn] need_lon_outer_edge = True",
"def split_data_by_days(data=None, dates=None, day_list=None, verbose=False, debug=False): \"\"\" Takes a list of datetimes and",
"index=dates, columns=['data']) # Add list of dates ( just year, month, day )",
"each day return data4days, day_list def obs2grid(glon=None, glat=None, galt=None, nest='high res global', sites=None,",
"in sites: lon, lat, alt = loc_dict[site] vars = get_xy(lon, lat, glon, glat)",
"Loop X dimension ( lon ) for nn, lon_ in enumerate(lon_c): # Loop",
"edge lon if need_lon_outer_edge: point_lon = lon_e[nn+1] else: point_lon = lon_e[nn] need_lon_outer_edge =",
"indices_list = [] for site in sites: lon, lat, alt = loc_dict[site] vars",
"coding: utf-8 -*- \"\"\" Redundant misc. functions to be eventually removed from AC_tools.",
"lat_diff = lat_e[-5]-lat_e[-6] nn, n, = 0, 0 last_lat_box = arr[nn, n] coords",
"df[df['days'] == day])) data4days += [df['data'][df['days'] == day]] # Just return the values",
"for removal \"\"\" if isinstance(glon, type(None)): glon, glat, galt = get_latlonalt4res(nest=nest, centre=False, debug=debug)",
"edge ) \"\"\" if verbose: print(('get_arr_edge_indices for arr of shape: ', arr.shape)) #",
"( lat ) and store edges for n, lat_ in enumerate(lat_c): if debug:",
"as datetime # math from math import radians, sin, cos, asin, sqrt, pi,",
"location indicies indices_list = [] for site in sites: lon, lat, alt =",
"1st lat, selct bottom of box point_lon = lon_e[nn]+lon_diff/2 if need_lat_outer_edge: point_lat =",
"n] coords = [] last_lon_box = arr[nn, n] need_lon_outer_edge, need_lat_outer_edge = False, False",
"last_lat_box, arr[nn, n] == last_lon_box)) if arr[nn, n] != last_lat_box: # If 1st",
"sqrt, pi, atan2 def get_arr_edge_indices(arr, res='4x5', extra_points_point_on_edge=None, verbose=True, debug=False): \"\"\" Find indices in",
"DataFrame of Data and dates df = DataFrame(data, index=dates, columns=['data']) # Add list",
"n] return coords def split_data_by_days(data=None, dates=None, day_list=None, verbose=False, debug=False): \"\"\" Takes a list",
"numpy as np from matplotlib.backends.backend_pdf import PdfPages import matplotlib.pyplot as plt from pandas",
"data for each day return data4days, day_list def obs2grid(glon=None, glat=None, galt=None, nest='high res",
"point_lat] for i in np.linspace(0, 1, extra_points_point_on_edge, endpoint=True)] # temporally save the previous",
"= lon_e[nn+1] else: point_lon = lon_e[nn] need_lon_outer_edge = True need_lon_outer_edge = False #",
"values ( i.e. not pandas array ) data4days = [i.values.astype(float) for i in",
"datetimes and data and returns a list of data and the bins (",
"print((arr[nn, n], last_lat_box, last_lon_box, arr[nn, n] == last_lat_box, arr[nn, n] == last_lon_box)) #",
"point_lat] coords += [mid_point] # Add given number of points along edge else:",
"list of data for each day return data4days, day_list def obs2grid(glon=None, glat=None, galt=None,",
"lat_e[n] need_lat_outer_edge = True need_lat_outer_edge = False # Add mid point to cordinates",
"= sorted(set(df['days'].values)) # Loop unique days and select data on these days data4days",
"days ) \"\"\" if verbose: print('split_data_by_days called') # Create DataFrame of Data and",
"for arr of shape: ', arr.shape)) # initialise variables lon_c, lat_c, NIU =",
"DataFrame # time import time import datetime as datetime # math from math",
"mid_point = [point_lon, point_lat] coords += [mid_point] # Add given number of points",
"galt=None, nest='high res global', sites=None, debug=False): \"\"\" values that have a given lat,",
"arr[nn, n] need_lon_outer_edge, need_lat_outer_edge = False, False if debug: print((lon_e, lat_e)) # ----",
"day return data4days, day_list def obs2grid(glon=None, glat=None, galt=None, nest='high res global', sites=None, debug=False):",
"df = DataFrame(data, index=dates, columns=['data']) # Add list of dates ( just year,",
"centre=False, debug=debug) # Assume use of known CAST sites... unless others given. if",
"given number of points along edge else: coords += [[point_lon, lat_e[n]+(lat_diff*i)] for i",
"matplotlib.pyplot as plt from pandas import DataFrame # time import time import datetime",
"lon ) and store edges for nn, lon_ in enumerate(lon_c): # If change",
"a list of data and the bins ( days ) \"\"\" if verbose:",
"for i in data4days]) # print data4days[0] # sys.exit() if debug: print(('returning data",
"for each day return data4days, day_list def obs2grid(glon=None, glat=None, galt=None, nest='high res global',",
"value last_lon_box = arr[nn, n] return coords def split_data_by_days(data=None, dates=None, day_list=None, verbose=False, debug=False):",
"atan2 def get_arr_edge_indices(arr, res='4x5', extra_points_point_on_edge=None, verbose=True, debug=False): \"\"\" Find indices in a lon,",
"pi, atan2 def get_arr_edge_indices(arr, res='4x5', extra_points_point_on_edge=None, verbose=True, debug=False): \"\"\" Find indices in a",
") \"\"\" if verbose: print(('get_arr_edge_indices for arr of shape: ', arr.shape)) # initialise",
"sin, cos, asin, sqrt, pi, atan2 def get_arr_edge_indices(arr, res='4x5', extra_points_point_on_edge=None, verbose=True, debug=False): \"\"\"",
"(2D) grid, where value does not equal a given value ( e.g. the",
"[datetime.datetime(*i.timetuple()[:3]) for i in dates] if debug: print(df) # Get list of unique",
"PdfPages import matplotlib.pyplot as plt from pandas import DataFrame # time import time",
"NIU = get_latlonalt4res(res=res, centre=False) lon_diff = lon_e[-5]-lon_e[-6] lat_diff = lat_e[-5]-lat_e[-6] nn, n, =",
"data4days = [] for day in day_list: print((day, df[df['days'] == day])) data4days +=",
"[] for site in sites: lon, lat, alt = loc_dict[site] vars = get_xy(lon,",
"day in day_list: print((day, df[df['days'] == day])) data4days += [df['data'][df['days'] == day]] #",
"[len(i) for i in data4days])) # Return as list of days (datetimes) +",
"+= [[point_lon, lat_e[n]+(lat_diff*i)] for i in np.linspace(0, 1, extra_points_point_on_edge, endpoint=True)] # temporally save",
"lat, lon and alt Notes ------- - Function flagged for removal \"\"\" if",
"of box point_lon = lon_e[nn]+lon_diff/2 if need_lat_outer_edge: point_lat = lat_e[n+1] else: point_lat =",
"others given. if isinstance(sites, type(None)): loc_dict = get_loc(rtn_dict=True) sites = list(loc_dict.keys()) # Pull",
"# Add given number of points along edge else: coords += [[lon_e[nn]+(lon_diff*i), point_lat]",
"a given lat, lon and alt Notes ------- - Function flagged for removal",
"1, extra_points_point_on_edge, endpoint=True)] # temporally save the previous box's value last_lon_box = arr[nn,",
"False, False if debug: print((lon_e, lat_e)) # ---- Loop X dimension ( lon",
"# Loop X dimension ( lon ) and store edges for nn, lon_",
"# time import time import datetime as datetime # math from math import",
"list of days (datetimes) + list of data for each day return data4days,",
"True need_lat_outer_edge = False # Add mid point to cordinates list if isinstance(extra_points_point_on_edge,",
"of known CAST sites... unless others given. if isinstance(sites, type(None)): loc_dict = get_loc(rtn_dict=True)",
"== last_lon_box)) if arr[nn, n] != last_lat_box: # If 1st lat, selct bottom",
"day]] # Just return the values ( i.e. not pandas array ) data4days",
"with lengths: '.format( len(day_list)), [len(i) for i in data4days])) # Return as list",
"given lat, lon and alt Notes ------- - Function flagged for removal \"\"\"",
"print(('get_arr_edge_indices for arr of shape: ', arr.shape)) # initialise variables lon_c, lat_c, NIU",
"= get_latlonalt4res(nest=nest, centre=False, debug=debug) # Assume use of known CAST sites... unless others",
"shape: ', arr.shape)) # initialise variables lon_c, lat_c, NIU = get_latlonalt4res(res=res, centre=True) lon_e,",
"n, lat_ in enumerate(lat_c): if debug: print((arr[nn, n], last_lat_box, last_lon_box, arr[nn, n] ==",
"get_latlonalt4res(res=res, centre=False) lon_diff = lon_e[-5]-lon_e[-6] lat_diff = lat_e[-5]-lat_e[-6] nn, n, = 0, 0",
"columns=['data']) # Add list of dates ( just year, month, day ) <=",
"( days ) \"\"\" if verbose: print('split_data_by_days called') # Create DataFrame of Data",
"points along edge else: coords += [[lon_e[nn]+(lon_diff*i), point_lat] for i in np.linspace(0, 1,"
] |
[
"-*- coding: utf-8 -*- # @Author: mcxiaoke # @Date: 2018-01-27 09:47:26 from __future__",
"mcxiaoke # @Date: 2018-01-27 09:47:26 from __future__ import print_function, unicode_literals, absolute_import import requests",
"etree.HTML(text) captcha_image = root.xpath('//img[@id=\"captcha_image\"]/@src') captcha_id = root.xpath('//input[@name=\"captcha-id\"]/@value') if captcha_image and captcha_id: print(captcha_image[0]) print(captcha_id[0])",
"read_file def parse_doulist(): url = 'https://www.douban.com/doulist/39822487/?sort=time&sub_type=12' root = etree.HTML(commons.get(url).text) links = root.xpath('//a[contains(@href,\"/photos/album/\")]') return",
"unicode_literals, absolute_import import requests import json import os import sys import hashlib import",
"json import os import sys import hashlib import time import argparse import logging",
"distinct_list([l.attrib['href'] for l in links]) def parse_douban_captcha(): text = read_file(sys.argv[1]) root = etree.HTML(text)",
"= root.xpath('//input[@name=\"captcha-id\"]/@value') if captcha_image and captcha_id: print(captcha_image[0]) print(captcha_id[0]) if __name__ == '__main__': parse_douban_captcha()",
"import logging from lxml import etree, html sys.path.insert(1, os.path.dirname( os.path.dirname(os.path.realpath(__file__)))) from lib import",
"import print_function, unicode_literals, absolute_import import requests import json import os import sys import",
"import os import sys import hashlib import time import argparse import logging from",
"sys import hashlib import time import argparse import logging from lxml import etree,",
"url = 'https://www.douban.com/doulist/39822487/?sort=time&sub_type=12' root = etree.HTML(commons.get(url).text) links = root.xpath('//a[contains(@href,\"/photos/album/\")]') return distinct_list([l.attrib['href'] for l",
"captcha_id = root.xpath('//input[@name=\"captcha-id\"]/@value') if captcha_image and captcha_id: print(captcha_image[0]) print(captcha_id[0]) if __name__ == '__main__':",
"utf-8 -*- # @Author: mcxiaoke # @Date: 2018-01-27 09:47:26 from __future__ import print_function,",
"lib.utils import distinct_list, read_file def parse_doulist(): url = 'https://www.douban.com/doulist/39822487/?sort=time&sub_type=12' root = etree.HTML(commons.get(url).text) links",
"= 'https://www.douban.com/doulist/39822487/?sort=time&sub_type=12' root = etree.HTML(commons.get(url).text) links = root.xpath('//a[contains(@href,\"/photos/album/\")]') return distinct_list([l.attrib['href'] for l in",
"commons from lib.utils import distinct_list, read_file def parse_doulist(): url = 'https://www.douban.com/doulist/39822487/?sort=time&sub_type=12' root =",
"for l in links]) def parse_douban_captcha(): text = read_file(sys.argv[1]) root = etree.HTML(text) captcha_image",
"root = etree.HTML(text) captcha_image = root.xpath('//img[@id=\"captcha_image\"]/@src') captcha_id = root.xpath('//input[@name=\"captcha-id\"]/@value') if captcha_image and captcha_id:",
"= root.xpath('//img[@id=\"captcha_image\"]/@src') captcha_id = root.xpath('//input[@name=\"captcha-id\"]/@value') if captcha_image and captcha_id: print(captcha_image[0]) print(captcha_id[0]) if __name__",
"import distinct_list, read_file def parse_doulist(): url = 'https://www.douban.com/doulist/39822487/?sort=time&sub_type=12' root = etree.HTML(commons.get(url).text) links =",
"import sys import hashlib import time import argparse import logging from lxml import",
"hashlib import time import argparse import logging from lxml import etree, html sys.path.insert(1,",
"read_file(sys.argv[1]) root = etree.HTML(text) captcha_image = root.xpath('//img[@id=\"captcha_image\"]/@src') captcha_id = root.xpath('//input[@name=\"captcha-id\"]/@value') if captcha_image and",
"= root.xpath('//a[contains(@href,\"/photos/album/\")]') return distinct_list([l.attrib['href'] for l in links]) def parse_douban_captcha(): text = read_file(sys.argv[1])",
"etree, html sys.path.insert(1, os.path.dirname( os.path.dirname(os.path.realpath(__file__)))) from lib import commons from lib.utils import distinct_list,",
"parse_doulist(): url = 'https://www.douban.com/doulist/39822487/?sort=time&sub_type=12' root = etree.HTML(commons.get(url).text) links = root.xpath('//a[contains(@href,\"/photos/album/\")]') return distinct_list([l.attrib['href'] for",
"2018-01-27 09:47:26 from __future__ import print_function, unicode_literals, absolute_import import requests import json import",
"__future__ import print_function, unicode_literals, absolute_import import requests import json import os import sys",
"links]) def parse_douban_captcha(): text = read_file(sys.argv[1]) root = etree.HTML(text) captcha_image = root.xpath('//img[@id=\"captcha_image\"]/@src') captcha_id",
"links = root.xpath('//a[contains(@href,\"/photos/album/\")]') return distinct_list([l.attrib['href'] for l in links]) def parse_douban_captcha(): text =",
"return distinct_list([l.attrib['href'] for l in links]) def parse_douban_captcha(): text = read_file(sys.argv[1]) root =",
"import argparse import logging from lxml import etree, html sys.path.insert(1, os.path.dirname( os.path.dirname(os.path.realpath(__file__)))) from",
"argparse import logging from lxml import etree, html sys.path.insert(1, os.path.dirname( os.path.dirname(os.path.realpath(__file__)))) from lib",
"parse_douban_captcha(): text = read_file(sys.argv[1]) root = etree.HTML(text) captcha_image = root.xpath('//img[@id=\"captcha_image\"]/@src') captcha_id = root.xpath('//input[@name=\"captcha-id\"]/@value')",
"python # -*- coding: utf-8 -*- # @Author: mcxiaoke # @Date: 2018-01-27 09:47:26",
"lib import commons from lib.utils import distinct_list, read_file def parse_doulist(): url = 'https://www.douban.com/doulist/39822487/?sort=time&sub_type=12'",
"# @Author: mcxiaoke # @Date: 2018-01-27 09:47:26 from __future__ import print_function, unicode_literals, absolute_import",
"<gh_stars>1-10 #!/usr/bin/env python # -*- coding: utf-8 -*- # @Author: mcxiaoke # @Date:",
"import json import os import sys import hashlib import time import argparse import",
"@Author: mcxiaoke # @Date: 2018-01-27 09:47:26 from __future__ import print_function, unicode_literals, absolute_import import",
"import time import argparse import logging from lxml import etree, html sys.path.insert(1, os.path.dirname(",
"os.path.dirname(os.path.realpath(__file__)))) from lib import commons from lib.utils import distinct_list, read_file def parse_doulist(): url",
"text = read_file(sys.argv[1]) root = etree.HTML(text) captcha_image = root.xpath('//img[@id=\"captcha_image\"]/@src') captcha_id = root.xpath('//input[@name=\"captcha-id\"]/@value') if",
"html sys.path.insert(1, os.path.dirname( os.path.dirname(os.path.realpath(__file__)))) from lib import commons from lib.utils import distinct_list, read_file",
"#!/usr/bin/env python # -*- coding: utf-8 -*- # @Author: mcxiaoke # @Date: 2018-01-27",
"-*- # @Author: mcxiaoke # @Date: 2018-01-27 09:47:26 from __future__ import print_function, unicode_literals,",
"requests import json import os import sys import hashlib import time import argparse",
"'https://www.douban.com/doulist/39822487/?sort=time&sub_type=12' root = etree.HTML(commons.get(url).text) links = root.xpath('//a[contains(@href,\"/photos/album/\")]') return distinct_list([l.attrib['href'] for l in links])",
"lxml import etree, html sys.path.insert(1, os.path.dirname( os.path.dirname(os.path.realpath(__file__)))) from lib import commons from lib.utils",
"time import argparse import logging from lxml import etree, html sys.path.insert(1, os.path.dirname( os.path.dirname(os.path.realpath(__file__))))",
"import hashlib import time import argparse import logging from lxml import etree, html",
"def parse_douban_captcha(): text = read_file(sys.argv[1]) root = etree.HTML(text) captcha_image = root.xpath('//img[@id=\"captcha_image\"]/@src') captcha_id =",
"= read_file(sys.argv[1]) root = etree.HTML(text) captcha_image = root.xpath('//img[@id=\"captcha_image\"]/@src') captcha_id = root.xpath('//input[@name=\"captcha-id\"]/@value') if captcha_image",
"from __future__ import print_function, unicode_literals, absolute_import import requests import json import os import",
"sys.path.insert(1, os.path.dirname( os.path.dirname(os.path.realpath(__file__)))) from lib import commons from lib.utils import distinct_list, read_file def",
"from lib.utils import distinct_list, read_file def parse_doulist(): url = 'https://www.douban.com/doulist/39822487/?sort=time&sub_type=12' root = etree.HTML(commons.get(url).text)",
"root = etree.HTML(commons.get(url).text) links = root.xpath('//a[contains(@href,\"/photos/album/\")]') return distinct_list([l.attrib['href'] for l in links]) def",
"# -*- coding: utf-8 -*- # @Author: mcxiaoke # @Date: 2018-01-27 09:47:26 from",
"@Date: 2018-01-27 09:47:26 from __future__ import print_function, unicode_literals, absolute_import import requests import json",
"captcha_image = root.xpath('//img[@id=\"captcha_image\"]/@src') captcha_id = root.xpath('//input[@name=\"captcha-id\"]/@value') if captcha_image and captcha_id: print(captcha_image[0]) print(captcha_id[0]) if",
"root.xpath('//img[@id=\"captcha_image\"]/@src') captcha_id = root.xpath('//input[@name=\"captcha-id\"]/@value') if captcha_image and captcha_id: print(captcha_image[0]) print(captcha_id[0]) if __name__ ==",
"print_function, unicode_literals, absolute_import import requests import json import os import sys import hashlib",
"in links]) def parse_douban_captcha(): text = read_file(sys.argv[1]) root = etree.HTML(text) captcha_image = root.xpath('//img[@id=\"captcha_image\"]/@src')",
"from lxml import etree, html sys.path.insert(1, os.path.dirname( os.path.dirname(os.path.realpath(__file__)))) from lib import commons from",
"= etree.HTML(commons.get(url).text) links = root.xpath('//a[contains(@href,\"/photos/album/\")]') return distinct_list([l.attrib['href'] for l in links]) def parse_douban_captcha():",
"absolute_import import requests import json import os import sys import hashlib import time",
"os import sys import hashlib import time import argparse import logging from lxml",
"def parse_doulist(): url = 'https://www.douban.com/doulist/39822487/?sort=time&sub_type=12' root = etree.HTML(commons.get(url).text) links = root.xpath('//a[contains(@href,\"/photos/album/\")]') return distinct_list([l.attrib['href']",
"distinct_list, read_file def parse_doulist(): url = 'https://www.douban.com/doulist/39822487/?sort=time&sub_type=12' root = etree.HTML(commons.get(url).text) links = root.xpath('//a[contains(@href,\"/photos/album/\")]')",
"import commons from lib.utils import distinct_list, read_file def parse_doulist(): url = 'https://www.douban.com/doulist/39822487/?sort=time&sub_type=12' root",
"coding: utf-8 -*- # @Author: mcxiaoke # @Date: 2018-01-27 09:47:26 from __future__ import",
"from lib import commons from lib.utils import distinct_list, read_file def parse_doulist(): url =",
"etree.HTML(commons.get(url).text) links = root.xpath('//a[contains(@href,\"/photos/album/\")]') return distinct_list([l.attrib['href'] for l in links]) def parse_douban_captcha(): text",
"09:47:26 from __future__ import print_function, unicode_literals, absolute_import import requests import json import os",
"= etree.HTML(text) captcha_image = root.xpath('//img[@id=\"captcha_image\"]/@src') captcha_id = root.xpath('//input[@name=\"captcha-id\"]/@value') if captcha_image and captcha_id: print(captcha_image[0])",
"logging from lxml import etree, html sys.path.insert(1, os.path.dirname( os.path.dirname(os.path.realpath(__file__)))) from lib import commons",
"os.path.dirname( os.path.dirname(os.path.realpath(__file__)))) from lib import commons from lib.utils import distinct_list, read_file def parse_doulist():",
"import etree, html sys.path.insert(1, os.path.dirname( os.path.dirname(os.path.realpath(__file__)))) from lib import commons from lib.utils import",
"# @Date: 2018-01-27 09:47:26 from __future__ import print_function, unicode_literals, absolute_import import requests import",
"l in links]) def parse_douban_captcha(): text = read_file(sys.argv[1]) root = etree.HTML(text) captcha_image =",
"root.xpath('//a[contains(@href,\"/photos/album/\")]') return distinct_list([l.attrib['href'] for l in links]) def parse_douban_captcha(): text = read_file(sys.argv[1]) root",
"import requests import json import os import sys import hashlib import time import"
] |
[
"bool ''' return self.execCLI(\"show wsma id\") def _buildCorrelator(self, command): '''Build a correlator for",
"@property def odmFormatResult(self): '''When using format specifications (e.g. structured data instead of unstructured",
"we connect otherwise?) 2) this is a priv-lvl-1 command 3) this command is",
"def _buildCorrelator(self, command): '''Build a correlator for each command. Consists of - command",
"used to make a unique string to return as a correlator :rtype: str",
"logging.info(\"connect to {} as {}/{}\".format(self.url, self.username, self.password)) @abstractmethod def disconnect(self): '''Disconnects the transport",
"transports. Provides the groundwork for specified transports. WSMA defines the following transports: -",
"string: {}\".format(xml_text)) try: dom = parseString(xml_text) except ExpatError as e: return dict(error='%s' %",
"<reponame>aradford123/wsma_python # -*- coding: utf-8 -*- \"\"\" This defines the base class for",
"self.communicate(template_data) def configPersist(self): '''Makes configuration changes persistent. :rtype: bool ''' correlator = self._buildCorrelator(\"config-persist\")",
"__init__(self): \"\"\" :rtype : basestring \"\"\" self.begin_schema = \"\"\"<?xml version=\"1.0\" encoding=\"UTF-8\"?> <SOAP:Envelope xmlns:SOAP=\"http://schemas.xmlsoap.org/soap/envelope/\"",
"print(etree.tostring(element, pretty_print=True).decode('utf-8')) print(json.dumps(xmltodict.parse(xml_text), indent=4)) \"\"\" logging.debug(\"XML string: {}\".format(xml_text)) try: dom = parseString(xml_text) except",
"results.append(re) # look for first failed element for line in results: if line.get('failure'):",
"is configured on the device (how could we connect otherwise?) 2) this is",
"SSH - HTTP / HTTPS - TLS this is the WSMA :class:`Base <Base>`",
"</execCLI> \"\"\" self.template = Template(\"{0}{1}{2}\". format(self.begin_schema, self.body, self.end_schema)) class _ConfigTemplate(_Schema): def __init__(self): _Schema.__init__(self)",
"self.template = Template(\"{0}{1}{2}\". format(self.begin_schema, self.body, self.end_schema)) class _ConfigTemplate(_Schema): def __init__(self): _Schema.__init__(self) self.body =",
"from the device :param data: dictionary with response data :rtype: bool ''' self.data",
"failed element for line in results: if line.get('failure'): self.output = line.get('text') break return",
"format_text = \"\" etmplate = _ExecTemplate() template_data = etmplate.template.render(EXEC_CMD=command, TIMEOUT=self.timeout, CORRELATOR=correlator, FORMAT=format_text, Username=self.username,",
"pretty_print=True).decode('utf-8')) print(json.dumps(xmltodict.parse(xml_text), indent=4)) \"\"\" logging.debug(\"XML string: {}\".format(xml_text)) try: dom = parseString(xml_text) except ExpatError",
": basestring \"\"\" self.begin_schema = \"\"\"<?xml version=\"1.0\" encoding=\"UTF-8\"?> <SOAP:Envelope xmlns:SOAP=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:SOAP-ENC=\"http://schemas.xmlsoap.org/soap/encoding/\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">",
"device :param action_on_fail, can be \"stop\", \"continue\", \"rollback\" :rtype: bool ''' correlator =",
"no response is found, the SOAP 'Envelope' is returned. If an empty string",
"None: format_text = 'format=\"%s\"' % format_spec else: format_text = \"\" etmplate = _ExecTemplate()",
"The specific implementation has to be provided by the subclass. tls, ssh and",
"{}/{}\".format(self.url, self.username, self.password)) @abstractmethod def disconnect(self): '''Disconnects the transport ''' logging.info(\"disconnect from {}\".format(self.url))",
"the existence of the session self._count = 0 def __enter__(self): logging.debug('WITH/AS connect session')",
"overwritten in subclass, it should process provided template_data by sending it using the",
"an object. :rtype dict: ''' try: return self.data['response']['execLog']['dialogueLog']['received']['tree'] except KeyError: return None @property",
"= ABCMeta def __init__(self, host, username, password, port, timeout=60): super(Base, self).__init__() if not",
"logging.debug(\"Template {0:s}\".format(template_data)) return self.communicate(template_data) def configPersist(self): '''Makes configuration changes persistent. :rtype: bool '''",
"use :param password: <PASSWORD> :param port: port to connect to :param timeout: timeout",
"None: return False logging.info(\"JSON data: %s\", json.dumps(self.data, indent=4)) # was it successful? try:",
"block to be applied to the device :param action_on_fail, can be \"stop\", \"continue\",",
"\"rollback\" :rtype: bool ''' correlator = self._buildCorrelator(\"config\") fail_str = 'action-on-fail=\"%s\"' % action_on_fail self._count",
"template_data): '''Needs to be overwritten in subclass, it should process provided template_data by",
"except KeyError: return None @property def hasSession(self): '''checks whether we have a valid",
"# session holds the transport session self._session = None # count is used",
"exc_val, exc_tb): logging.debug('WITH/AS disconnect session') self.disconnect() def _ping(self): '''Test the connection, does it",
":param host: hostname of the WSMA server :param username: username to use :param",
"self._buildCorrelator(\"config\") fail_str = 'action-on-fail=\"%s\"' % action_on_fail self._count += 1 etmplate = _ConfigTemplate() template_data",
":rtype: bool ''' return self.execCLI(\"show wsma id\") def _buildCorrelator(self, command): '''Build a correlator",
"holds the error message (typos, config and exec) if not successful - xml_data:",
"self.output = 'unknown error / key error' return False # exec mode? if",
"a priv-lvl-1 command 3) this command is platform independent for platforms supporting WSMA",
"return dict(error='XML body is empty') \"\"\" from lxml import etree etree.register_namespace(\"SOAP\", \"http://schemas.xmlsoap.org/soap/envelope/\") element",
"1 etmplate = _ConfigTemplate() template_data = etmplate.template.render(CONFIG_CMD=command, CORRELATOR=correlator, ACTION_ON_FAIL=fail_str, Username=self.username, Password=self.password) logging.debug(\"Template {0:s}\".format(template_data))",
"- xml_data: holds the XML data received from the device :param data: dictionary",
"self: object \"\"\" _Schema.__init__(self) self.body = \"\"\"<request xmlns=\"urn:cisco:wsma-exec\" correlator=\"{{CORRELATOR}}\"> <execCLI maxWait=\"PT{{TIMEOUT}}S\" xsd=\"false\" {{FORMAT}}>",
"string to be run in exec mode on device :param format_spec: if there",
"<cli-config-data-block>{{CONFIG_CMD}}</cli-config-data-block> </config-data> </configApply>\"\"\" self.template = Template(\"{0}{1}{2}\". format(self.begin_schema, self.body, self.end_schema)) class _ConfigPersistTemplate(_Schema): def __init__(self):",
"\"\" etmplate = _ExecTemplate() template_data = etmplate.template.render(EXEC_CMD=command, TIMEOUT=self.timeout, CORRELATOR=correlator, FORMAT=format_text, Username=self.username, Password=<PASSWORD>) logging.debug(\"Template",
"or an error occurs during parsing then dict(error='some error string') is returned. This",
"basestring \"\"\" self.begin_schema = \"\"\"<?xml version=\"1.0\" encoding=\"UTF-8\"?> <SOAP:Envelope xmlns:SOAP=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:SOAP-ENC=\"http://schemas.xmlsoap.org/soap/encoding/\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"> <SOAP:Header>",
"WSMA defines the following transports: - SSH - HTTP / HTTPS - TLS",
"dictionary with the result data. :param command: command string to be run in",
"wass successful. it holds the error message (typos, config and exec) if not",
"Python module. \"\"\" from abc import ABCMeta, abstractmethod from jinja2 import Template from",
"= list() results.append(re) # look for first failed element for line in results:",
"template_data = etmplate.template.render(CORRELATOR=correlator, Username=self.username, Password=self.password) logging.debug(\"Template {0:s}\".format(template_data)) return self.communicate(template_data) @staticmethod def parseXML(xml_text): '''Parses",
"self.success: try: t = self.data['response']['execLog'][ 'dialogueLog']['received']['text'] except KeyError: t = None t =",
"return self.communicate(template_data) def configPersist(self): '''Makes configuration changes persistent. :rtype: bool ''' correlator =",
"= etmplate.template.render(CORRELATOR=correlator, Username=self.username, Password=self.password) logging.debug(\"Template {0:s}\".format(template_data)) return self.communicate(template_data) @staticmethod def parseXML(xml_text): '''Parses given",
"occurs during parsing then dict(error='some error string') is returned. This still assumes that",
"is returned. This still assumes that IF an XML string is passed into",
"bool ''' self.success= True self.output = '' self.data = None # make sure",
"xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"> <SOAP:Header> <wsse:Security xmlns:wsse=\"http://schemas.xmlsoap.org/ws/2002/04/secext\" SOAP:mustUnderstand=\"false\"> <wsse:UsernameToken> <wsse:Username>{{Username}}</wsse:Username> <wsse:Password>{{Password}}</wsse:Password> </wsse:UsernameToken> </wsse:Security> </SOAP:Header> <SOAP:Body>",
"KeyError: self.output = 'unknown error / key error' return False # exec mode?",
"xmlns:SOAP=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:SOAP-ENC=\"http://schemas.xmlsoap.org/soap/encoding/\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"> <SOAP:Header> <wsse:Security xmlns:wsse=\"http://schemas.xmlsoap.org/ws/2002/04/secext\" SOAP:mustUnderstand=\"false\"> <wsse:UsernameToken> <wsse:Username>{{Username}}</wsse:Username> <wsse:Password>{{Password}}</wsse:Password> </wsse:UsernameToken> </wsse:Security>",
"result def _process(self, xml_data): '''Process the given data dict and populate instance vars:",
"key error' return False # exec mode? if self.data['response']['@xmlns'] == \"urn:cisco:wsma-exec\": if self.success:",
"If format_spec is given (and valid), odmFormatResult will contain the dictionary with the",
"''' if xml_text is None: return dict(error='XML body is empty') \"\"\" from lxml",
"def connect(self): '''Connects to the WSMA host via a specific transport. The specific",
"self.host = host self.username = username self.password = password self.port = port self.success",
"alternative would be \"show version\" :rtype: bool ''' return self.execCLI(\"show wsma id\") def",
"supporting WSMA an alternative would be \"show version\" :rtype: bool ''' return self.execCLI(\"show",
"and populate instance vars: - success: was the call successful (bool) - output:",
"list() results.append(re) # look for first failed element for line in results: if",
"''' correlator = self._buildCorrelator(\"config\") fail_str = 'action-on-fail=\"%s\"' % action_on_fail self._count += 1 etmplate",
"string') is returned. This still assumes that IF an XML string is passed",
"{0:s}\".format(template_data)) return self.communicate(template_data) @staticmethod def parseXML(xml_text): '''Parses given XML string and returns the",
"execCLI(self, command, format_spec=None): '''Run given command in exec mode, return JSON response. The",
"a valid SOAP Envelope. :param xml_text: XML string to be converted :rtype: dict",
"from lxml import etree etree.register_namespace(\"SOAP\", \"http://schemas.xmlsoap.org/soap/envelope/\") element = etree.fromstring(xml_text.encode('utf-8')) print('#' * 40) print(etree.tostring(element,",
"IOS. ''' logging.info(\"connect to {} as {}/{}\".format(self.url, self.username, self.password)) @abstractmethod def disconnect(self): '''Disconnects",
"and exec) if not successful - xml_data: holds the XML data received from",
":param format_spec: if there is a ODM spec file for the command :rtype:",
"return False # catch all return False @abstractmethod def communicate(self, template_data): '''Needs to",
"exc_tb): logging.debug('WITH/AS disconnect session') self.disconnect() def _ping(self): '''Test the connection, does it make",
"import parseString from xml.parsers.expat import ExpatError import xmltodict import json import time import",
"defines the following transports: - SSH - HTTP / HTTPS - TLS this",
"self if self._ping() else None def __exit__(self, exc_type, exc_val, exc_tb): logging.debug('WITH/AS disconnect session')",
"self.begin_schema = \"\"\"<?xml version=\"1.0\" encoding=\"UTF-8\"?> <SOAP:Envelope xmlns:SOAP=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:SOAP-ENC=\"http://schemas.xmlsoap.org/soap/encoding/\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"> <SOAP:Header> <wsse:Security xmlns:wsse=\"http://schemas.xmlsoap.org/ws/2002/04/secext\"",
"exec mode? if self.data['response']['@xmlns'] == \"urn:cisco:wsma-exec\": if self.success: try: t = self.data['response']['execLog'][ 'dialogueLog']['received']['text']",
"None def __exit__(self, exc_type, exc_val, exc_tb): logging.debug('WITH/AS disconnect session') self.disconnect() def _ping(self): '''Test",
"''' self.success= True self.output = '' self.data = None # make sure we",
"session!' self.success= False return self.success @abstractmethod def connect(self): '''Connects to the WSMA host",
"self.success @abstractmethod def connect(self): '''Connects to the WSMA host via a specific transport.",
"encoding=\"UTF-8\"?> <SOAP:Envelope xmlns:SOAP=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:SOAP-ENC=\"http://schemas.xmlsoap.org/soap/encoding/\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"> <SOAP:Header> <wsse:Security xmlns:wsse=\"http://schemas.xmlsoap.org/ws/2002/04/secext\" SOAP:mustUnderstand=\"false\"> <wsse:UsernameToken> <wsse:Username>{{Username}}</wsse:Username> <wsse:Password>{{Password}}</wsse:Password>",
"_ExecTemplate(_Schema): def __init__(self): \"\"\" :type self: object \"\"\" _Schema.__init__(self) self.body = \"\"\"<request xmlns=\"urn:cisco:wsma-exec\"",
"None # session holds the transport session self._session = None # count is",
"hostname of the WSMA server :param username: username to use :param password: <PASSWORD>",
"Template(\"{0}{1}{2}\". format(self.begin_schema, self.body, self.end_schema)) class Base(object): '''The base class for all WSMA transports.",
"if there is a ODM spec file for the command :rtype: bool '''",
"= Template(\"{0}{1}{2}\". format(self.begin_schema, self.body, self.end_schema)) class Base(object): '''The base class for all WSMA",
"parseString from xml.parsers.expat import ExpatError import xmltodict import json import time import logging",
"self._session == None: self.output = 'no established session!' self.success= False return self.success @abstractmethod",
"''' try: return self.data['response']['execLog']['dialogueLog']['received']['tree'] except KeyError: return None @property def hasSession(self): '''checks whether",
"return True if not self.success: e = self.data['response']['execLog'][ 'errorInfo']['errorMessage'] self.output = e return",
"# did the parsing yield an error? if self.data.get('error') is not None: return",
"specific implementation has to be provided by the subclass. tls, ssh and http(s)",
":param command: used to make a unique string to return as a correlator",
"if t is None else t self.output = t return True if not",
"as {}/{}\".format(self.url, self.username, self.password)) @abstractmethod def disconnect(self): '''Disconnects the transport ''' logging.info(\"disconnect from",
"structured data instead of unstructured CLI output) then this property holds the structured",
"password self.port = port self.success = False self.output = '' self.data = None",
"id\") def _buildCorrelator(self, command): '''Build a correlator for each command. Consists of -",
"host via a specific transport. The specific implementation has to be provided by",
"def __init__(self): \"\"\" :type self: object \"\"\" _Schema.__init__(self) self.body = \"\"\"<request xmlns=\"urn:cisco:wsma-exec\" correlator=\"{{CORRELATOR}}\">",
"correlator :rtype: str ''' result = time.strftime(\"%H%M%S\") result += \"-%s\" % str(self._count) result",
"format(self.begin_schema, self.body, self.end_schema)) class _ConfigTemplate(_Schema): def __init__(self): _Schema.__init__(self) self.body = \"\"\"<request xmlns=\"urn:cisco:wsma-config\" correlator=\"{{CORRELATOR}}\">",
"bool ''' correlator = self._buildCorrelator(\"config\") fail_str = 'action-on-fail=\"%s\"' % action_on_fail self._count += 1",
":rtype: bool ''' correlator = self._buildCorrelator(\"config\") fail_str = 'action-on-fail=\"%s\"' % action_on_fail self._count +=",
"<Base>` class :param host: hostname of the WSMA server :param username: username to",
"_ConfigPersistTemplate() template_data = etmplate.template.render(CORRELATOR=correlator, Username=self.username, Password=self.password) logging.debug(\"Template {0:s}\".format(template_data)) return self.communicate(template_data) @staticmethod def parseXML(xml_text):",
":type self: object \"\"\" _Schema.__init__(self) self.body = \"\"\"<request xmlns=\"urn:cisco:wsma-exec\" correlator=\"{{CORRELATOR}}\"> <execCLI maxWait=\"PT{{TIMEOUT}}S\" xsd=\"false\"",
"'''Run given command in exec mode, return JSON response. The On success, self.output",
"timeout self.host = host self.username = username self.password = password self.port = port",
"otherwise?) 2) this is a priv-lvl-1 command 3) this command is platform independent",
"= line.get('text') break return False # catch all return False @abstractmethod def communicate(self,",
"command: config block to be applied to the device :param action_on_fail, can be",
"fail_str = 'action-on-fail=\"%s\"' % action_on_fail self._count += 1 etmplate = _ConfigTemplate() template_data =",
"indent=4)) # was it successful? try: self.success = bool(int(self.data['response']['@success'])) except KeyError: self.output =",
"dict(error='XML body is empty') \"\"\" from lxml import etree etree.register_namespace(\"SOAP\", \"http://schemas.xmlsoap.org/soap/envelope/\") element =",
"= re else: results = list() results.append(re) # look for first failed element",
"self._session = None # count is used for the correlator over # the",
"return self.success @abstractmethod def connect(self): '''Connects to the WSMA host via a specific",
"def __init__(self): _Schema.__init__(self) self.body = \"\"\"<request xmlns=\"urn:cisco:wsma-config\" correlator=\"{{CORRELATOR}}\"> <configApply details=\"all\" {{ACTION_ON_FAIL}}> <config-data> <cli-config-data-block>{{CONFIG_CMD}}</cli-config-data-block>",
"self.end_schema)) class _ConfigPersistTemplate(_Schema): def __init__(self): \"\"\" :type self: object \"\"\" _Schema.__init__(self) self.body =",
"@abstractmethod def connect(self): '''Connects to the WSMA host via a specific transport. The",
"</wsse:UsernameToken> </wsse:Security> </SOAP:Header> <SOAP:Body> \"\"\" self.end_schema = \"\"\" </request> </SOAP:Body> </SOAP:Envelope>\"\"\" class _ExecTemplate(_Schema):",
"self).__init__() if not host: raise ValueError(\"host argument may not be empty\") self.timeout =",
"command): '''Build a correlator for each command. Consists of - command to be",
"as e: return dict(error='%s' % e) logging.debug(\"XML tree:{}\".format(dom.childNodes[-1].toprettyxml())) response = dom.getElementsByTagName('response') if len(response)",
"command, action_on_fail=\"stop\"): '''Execute given commands in configuration mode. On success, self.output and self.success",
"+= 1 return result def _process(self, xml_data): '''Process the given data dict and",
"self.success: e = self.data['response']['execLog'][ 'errorInfo']['errorMessage'] self.output = e return False # config mode?",
"Password=<PASSWORD>) logging.debug(\"Template {}\".format(template_data)) return self.communicate(template_data) def config(self, command, action_on_fail=\"stop\"): '''Execute given commands in",
"__init__(self): \"\"\" :type self: object \"\"\" _Schema.__init__(self) self.body = \"\"\"<request xmlns=\"urn:cisco:wsma-config\" correlator=\"{{CORRELATOR}}\"> <configPersist>",
"usable in IOS. ''' logging.info(\"connect to {} as {}/{}\".format(self.url, self.username, self.password)) @abstractmethod def",
"dict: ''' try: return self.data['response']['execLog']['dialogueLog']['received']['tree'] except KeyError: return None @property def hasSession(self): '''checks",
"etree.fromstring(xml_text.encode('utf-8')) print('#' * 40) print(etree.tostring(element, pretty_print=True).decode('utf-8')) print(json.dumps(xmltodict.parse(xml_text), indent=4)) \"\"\" logging.debug(\"XML string: {}\".format(xml_text)) try:",
"_Schema.__init__(self) self.body = \"\"\"<request xmlns=\"urn:cisco:wsma-config\" correlator=\"{{CORRELATOR}}\"> <configPersist> </configPersist>\"\"\" self.template = Template(\"{0}{1}{2}\". format(self.begin_schema, self.body,",
"<SOAP:Envelope xmlns:SOAP=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:SOAP-ENC=\"http://schemas.xmlsoap.org/soap/encoding/\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"> <SOAP:Header> <wsse:Security xmlns:wsse=\"http://schemas.xmlsoap.org/ws/2002/04/secext\" SOAP:mustUnderstand=\"false\"> <wsse:UsernameToken> <wsse:Username>{{Username}}</wsse:Username> <wsse:Password>{{Password}}</wsse:Password> </wsse:UsernameToken>",
"session self._count = 0 def __enter__(self): logging.debug('WITH/AS connect session') self.connect() return self if",
"False # exec mode? if self.data['response']['@xmlns'] == \"urn:cisco:wsma-exec\": if self.success: try: t =",
"# look for first failed element for line in results: if line.get('failure'): self.output",
"''' logging.info(\"connect to {} as {}/{}\".format(self.url, self.username, self.password)) @abstractmethod def disconnect(self): '''Disconnects the",
"the call successful (bool) - output: holds CLI output (e.g. for show commands),",
"to be run in exec mode on device :param format_spec: if there is",
"False return self.success @abstractmethod def connect(self): '''Connects to the WSMA host via a",
"if self.data.get('error') is not None: return False logging.info(\"JSON data: %s\", json.dumps(self.data, indent=4)) #",
"\"\"\" self.begin_schema = \"\"\"<?xml version=\"1.0\" encoding=\"UTF-8\"?> <SOAP:Envelope xmlns:SOAP=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:SOAP-ENC=\"http://schemas.xmlsoap.org/soap/encoding/\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"> <SOAP:Header> <wsse:Security",
"given data dict and populate instance vars: - success: was the call successful",
"self.username = username self.password = password self.port = port self.success = False self.output",
"successful? try: self.success = bool(int(self.data['response']['@success'])) except KeyError: self.output = 'unknown error / key",
"correlator = self._buildCorrelator(\"config-persist\") etmplate = _ConfigPersistTemplate() template_data = etmplate.template.render(CORRELATOR=correlator, Username=self.username, Password=self.password) logging.debug(\"Template {0:s}\".format(template_data))",
"(typos, config and exec) if not successful - xml_data: holds the XML data",
"+= ''.join(command.split()) self._count += 1 return result def _process(self, xml_data): '''Process the given",
"server :param username: username to use :param password: <PASSWORD> :param port: port to",
"self.output and self.success will be updated. :param command: config block to be applied",
"try: t = self.data['response']['execLog'][ 'dialogueLog']['received']['text'] except KeyError: t = None t = ''",
"is returned. If an empty string is used or an error occurs during",
"structured data as an object. :rtype dict: ''' try: return self.data['response']['execLog']['dialogueLog']['received']['tree'] except KeyError:",
"specific transport. The specific implementation has to be provided by the subclass. tls,",
"= False self.output = '' self.data = None # session holds the transport",
"not applicable' self.output = t return True if not self.success: re = self.data['response']['resultEntry']",
"will contain the dictionary with the result data. :param command: command string to",
":class:`Base <Base>` class :param host: hostname of the WSMA server :param username: username",
"result += ''.join(command.split()) self._count += 1 return result def _process(self, xml_data): '''Process the",
"self.success= False return self.success @abstractmethod def connect(self): '''Connects to the WSMA host via",
"independent for platforms supporting WSMA an alternative would be \"show version\" :rtype: bool",
"list: results = re else: results = list() results.append(re) # look for first",
"is a priv-lvl-1 command 3) this command is platform independent for platforms supporting",
"command. Consists of - command to be sent -and- - timestamp :param command:",
"self.disconnect() def _ping(self): '''Test the connection, does it make sense to continue? it",
"all return False @abstractmethod def communicate(self, template_data): '''Needs to be overwritten in subclass,",
"config and exec) if not successful - xml_data: holds the XML data received",
"result = time.strftime(\"%H%M%S\") result += \"-%s\" % str(self._count) result += ''.join(command.split()) self._count +=",
"== \"urn:cisco:wsma-exec\": if self.success: try: t = self.data['response']['execLog'][ 'dialogueLog']['received']['text'] except KeyError: t =",
"this function then it should have a valid SOAP Envelope. :param xml_text: XML",
"_ConfigTemplate(_Schema): def __init__(self): _Schema.__init__(self) self.body = \"\"\"<request xmlns=\"urn:cisco:wsma-config\" correlator=\"{{CORRELATOR}}\"> <configApply details=\"all\" {{ACTION_ON_FAIL}}> <config-data>",
"be provided by the subclass. tls, ssh and http(s) are usable in IOS.",
"the transport ''' logging.info(\"disconnect from {}\".format(self.url)) self._session = None @property def odmFormatResult(self): '''When",
"transaction :rtype: bool ''' self.success= True self.output = '' self.data = None #",
"xmlns:wsse=\"http://schemas.xmlsoap.org/ws/2002/04/secext\" SOAP:mustUnderstand=\"false\"> <wsse:UsernameToken> <wsse:Username>{{Username}}</wsse:Username> <wsse:Password>{{Password}}</wsse:Password> </wsse:UsernameToken> </wsse:Security> </SOAP:Header> <SOAP:Body> \"\"\" self.end_schema = \"\"\"",
"is None else t self.output = t return True if not self.success: e",
"to :param timeout: timeout for transport ''' __metaclass__ = ABCMeta def __init__(self, host,",
"self.data = self.parseXML(xml_data) # did the parsing yield an error? if self.data.get('error') is",
"version\" :rtype: bool ''' return self.execCLI(\"show wsma id\") def _buildCorrelator(self, command): '''Build a",
"self.success = bool(int(self.data['response']['@success'])) except KeyError: self.output = 'unknown error / key error' return",
"return self.communicate(template_data) @staticmethod def parseXML(xml_text): '''Parses given XML string and returns the 'response'",
"import etree etree.register_namespace(\"SOAP\", \"http://schemas.xmlsoap.org/soap/envelope/\") element = etree.fromstring(xml_text.encode('utf-8')) print('#' * 40) print(etree.tostring(element, pretty_print=True).decode('utf-8')) print(json.dumps(xmltodict.parse(xml_text),",
"\"http://schemas.xmlsoap.org/soap/envelope/\") element = etree.fromstring(xml_text.encode('utf-8')) print('#' * 40) print(etree.tostring(element, pretty_print=True).decode('utf-8')) print(json.dumps(xmltodict.parse(xml_text), indent=4)) \"\"\" logging.debug(\"XML",
"return True if not self.success: re = self.data['response']['resultEntry'] # multi line config input",
"def configPersist(self): '''Makes configuration changes persistent. :rtype: bool ''' correlator = self._buildCorrelator(\"config-persist\") etmplate",
"error / key error' return False # exec mode? if self.data['response']['@xmlns'] == \"urn:cisco:wsma-exec\":",
"not host: raise ValueError(\"host argument may not be empty\") self.timeout = timeout self.host",
"the error message (typos, config and exec) if not successful - xml_data: holds",
"__init__(self): _Schema.__init__(self) self.body = \"\"\"<request xmlns=\"urn:cisco:wsma-config\" correlator=\"{{CORRELATOR}}\"> <configApply details=\"all\" {{ACTION_ON_FAIL}}> <config-data> <cli-config-data-block>{{CONFIG_CMD}}</cli-config-data-block> </config-data>",
"device :param data: dictionary with response data :rtype: bool ''' self.data = self.parseXML(xml_data)",
"line config input returns list if type(re) is list: results = re else:",
"a valid session or not. :rtype bool: ''' return self._session is not None",
"is a ODM spec file for the command :rtype: bool ''' correlator =",
"self.communicate(template_data) def config(self, command, action_on_fail=\"stop\"): '''Execute given commands in configuration mode. On success,",
"command, format_spec=None): '''Run given command in exec mode, return JSON response. The On",
"''' correlator = self._buildCorrelator(\"config-persist\") etmplate = _ConfigPersistTemplate() template_data = etmplate.template.render(CORRELATOR=correlator, Username=self.username, Password=self.password) logging.debug(\"Template",
"bool ''' correlator = self._buildCorrelator(\"exec\" + command) if format_spec is not None: format_text",
"SOAP 'Envelope' is returned. If an empty string is used or an error",
"\"\"\" self.end_schema = \"\"\" </request> </SOAP:Body> </SOAP:Envelope>\"\"\" class _ExecTemplate(_Schema): def __init__(self): \"\"\" :type",
"print(json.dumps(xmltodict.parse(xml_text), indent=4)) \"\"\" logging.debug(\"XML string: {}\".format(xml_text)) try: dom = parseString(xml_text) except ExpatError as",
"a specific transport. The specific implementation has to be provided by the subclass.",
"given command in exec mode, return JSON response. The On success, self.output and",
"_ConfigPersistTemplate(_Schema): def __init__(self): \"\"\" :type self: object \"\"\" _Schema.__init__(self) self.body = \"\"\"<request xmlns=\"urn:cisco:wsma-config\"",
"of unstructured CLI output) then this property holds the structured data as an",
"t = 'config mode / not applicable' self.output = t return True if",
"there is a ODM spec file for the command :rtype: bool ''' correlator",
"valid session or not. :rtype bool: ''' return self._session is not None and",
"\"\"\" logging.debug(\"XML string: {}\".format(xml_text)) try: dom = parseString(xml_text) except ExpatError as e: return",
"a correlator for each command. Consists of - command to be sent -and-",
"import xmltodict import json import time import logging class _Schema(object): def __init__(self): \"\"\"",
"to the WSMA host via a specific transport. The specific implementation has to",
"over # the existence of the session self._count = 0 def __enter__(self): logging.debug('WITH/AS",
"TIMEOUT=self.timeout, CORRELATOR=correlator, FORMAT=format_text, Username=self.username, Password=<PASSWORD>) logging.debug(\"Template {}\".format(template_data)) return self.communicate(template_data) def config(self, command, action_on_fail=\"stop\"):",
"command 3) this command is platform independent for platforms supporting WSMA an alternative",
"self.password = password self.port = port self.success = False self.output = '' self.data",
"password, port, timeout=60): super(Base, self).__init__() if not host: raise ValueError(\"host argument may not",
"xml.dom.minidom import parseString from xml.parsers.expat import ExpatError import xmltodict import json import time",
"return self.communicate(template_data) def config(self, command, action_on_fail=\"stop\"): '''Execute given commands in configuration mode. On",
"subclass, it should process provided template_data by sending it using the selected transport.",
"# catch all return False @abstractmethod def communicate(self, template_data): '''Needs to be overwritten",
":rtype: bool ''' self.success= True self.output = '' self.data = None # make",
"returned. If an empty string is used or an error occurs during parsing",
"ODM spec file for the command :rtype: bool ''' correlator = self._buildCorrelator(\"exec\" +",
"\"\"\" _Schema.__init__(self) self.body = \"\"\"<request xmlns=\"urn:cisco:wsma-exec\" correlator=\"{{CORRELATOR}}\"> <execCLI maxWait=\"PT{{TIMEOUT}}S\" xsd=\"false\" {{FORMAT}}> <cmd>{{EXEC_CMD}}</cmd> </execCLI>",
"= 'format=\"%s\"' % format_spec else: format_text = \"\" etmplate = _ExecTemplate() template_data =",
"False self.output = '' self.data = None # session holds the transport session",
"<wsse:Password>{{Password}}</wsse:Password> </wsse:UsernameToken> </wsse:Security> </SOAP:Header> <SOAP:Body> \"\"\" self.end_schema = \"\"\" </request> </SOAP:Body> </SOAP:Envelope>\"\"\" class",
"timestamp :param command: used to make a unique string to return as a",
"transport. Essentially: return self._process(send(data)) Assuming that send(template_data) returns XML from the device. :param",
"return None @property def hasSession(self): '''checks whether we have a valid session or",
"used for the correlator over # the existence of the session self._count =",
"0 def __enter__(self): logging.debug('WITH/AS connect session') self.connect() return self if self._ping() else None",
"tree:{}\".format(dom.childNodes[-1].toprettyxml())) response = dom.getElementsByTagName('response') if len(response) > 0: return xmltodict.parse(response[0].toxml()) return xmltodict.parse( dom.getElementsByTagNameNS(",
"message (typos, config and exec) if not successful - xml_data: holds the XML",
"the parsing yield an error? if self.data.get('error') is not None: return False logging.info(\"JSON",
"2) this is a priv-lvl-1 command 3) this command is platform independent for",
"converted :rtype: dict ''' if xml_text is None: return dict(error='XML body is empty')",
"</configPersist>\"\"\" self.template = Template(\"{0}{1}{2}\". format(self.begin_schema, self.body, self.end_schema)) class Base(object): '''The base class for",
"= t return True if not self.success: re = self.data['response']['resultEntry'] # multi line",
"it successful? try: self.success = bool(int(self.data['response']['@success'])) except KeyError: self.output = 'unknown error /",
"unique string to return as a correlator :rtype: str ''' result = time.strftime(\"%H%M%S\")",
"device (how could we connect otherwise?) 2) this is a priv-lvl-1 command 3)",
"error message (typos, config and exec) if not successful - xml_data: holds the",
"= Template(\"{0}{1}{2}\". format(self.begin_schema, self.body, self.end_schema)) class _ConfigPersistTemplate(_Schema): def __init__(self): \"\"\" :type self: object",
"string to return as a correlator :rtype: str ''' result = time.strftime(\"%H%M%S\") result",
"communicate(self, template_data): '''Needs to be overwritten in subclass, it should process provided template_data",
"\"-%s\" % str(self._count) result += ''.join(command.split()) self._count += 1 return result def _process(self,",
"Password=self.password) logging.debug(\"Template {0:s}\".format(template_data)) return self.communicate(template_data) @staticmethod def parseXML(xml_text): '''Parses given XML string and",
"_ping(self): '''Test the connection, does it make sense to continue? it is assumed",
"did the parsing yield an error? if self.data.get('error') is not None: return False",
"- HTTP / HTTPS - TLS this is the WSMA :class:`Base <Base>` class",
"in configuration mode. On success, self.output and self.success will be updated. :param command:",
"be sent -and- - timestamp :param command: used to make a unique string",
"False @abstractmethod def communicate(self, template_data): '''Needs to be overwritten in subclass, it should",
"subclass. tls, ssh and http(s) are usable in IOS. ''' logging.info(\"connect to {}",
"string to be sent in transaction :rtype: bool ''' self.success= True self.output =",
"will be updated. :param command: config block to be applied to the device",
"passed into this function then it should have a valid SOAP Envelope. :param",
"\"\"\" :type self: object \"\"\" _Schema.__init__(self) self.body = \"\"\"<request xmlns=\"urn:cisco:wsma-config\" correlator=\"{{CORRELATOR}}\"> <configPersist> </configPersist>\"\"\"",
"hasSession(self): '''checks whether we have a valid session or not. :rtype bool: '''",
"and self.success will be updated. :param command: config block to be applied to",
"= _ExecTemplate() template_data = etmplate.template.render(EXEC_CMD=command, TIMEOUT=self.timeout, CORRELATOR=correlator, FORMAT=format_text, Username=self.username, Password=<PASSWORD>) logging.debug(\"Template {}\".format(template_data)) return",
"string is passed into this function then it should have a valid SOAP",
"host: hostname of the WSMA server :param username: username to use :param password:",
"KeyError: t = None t = '' if t is None else t",
"else t self.output = t return True if not self.success: e = self.data['response']['execLog'][",
"raise ValueError(\"host argument may not be empty\") self.timeout = timeout self.host = host",
"return self.execCLI(\"show wsma id\") def _buildCorrelator(self, command): '''Build a correlator for each command.",
"correlator=\"{{CORRELATOR}}\"> <configPersist> </configPersist>\"\"\" self.template = Template(\"{0}{1}{2}\". format(self.begin_schema, self.body, self.end_schema)) class Base(object): '''The base",
"for transport ''' __metaclass__ = ABCMeta def __init__(self, host, username, password, port, timeout=60):",
"SOAP Envelope. :param xml_text: XML string to be converted :rtype: dict ''' if",
"base class for all WSMA transports. Provides the groundwork for specified transports. WSMA",
"\"\"\"<request xmlns=\"urn:cisco:wsma-exec\" correlator=\"{{CORRELATOR}}\"> <execCLI maxWait=\"PT{{TIMEOUT}}S\" xsd=\"false\" {{FORMAT}}> <cmd>{{EXEC_CMD}}</cmd> </execCLI> \"\"\" self.template = Template(\"{0}{1}{2}\".",
"\"show version\" :rtype: bool ''' return self.execCLI(\"show wsma id\") def _buildCorrelator(self, command): '''Build",
"object. :rtype dict: ''' try: return self.data['response']['execLog']['dialogueLog']['received']['tree'] except KeyError: return None @property def",
"result data. :param command: command string to be run in exec mode on",
"the command :rtype: bool ''' correlator = self._buildCorrelator(\"exec\" + command) if format_spec is",
"'''Makes configuration changes persistent. :rtype: bool ''' correlator = self._buildCorrelator(\"config-persist\") etmplate = _ConfigPersistTemplate()",
"configuration changes persistent. :rtype: bool ''' correlator = self._buildCorrelator(\"config-persist\") etmplate = _ConfigPersistTemplate() template_data",
"is not None and self._ping() def execCLI(self, command, format_spec=None): '''Run given command in",
"disconnect(self): '''Disconnects the transport ''' logging.info(\"disconnect from {}\".format(self.url)) self._session = None @property def",
"tree. If no response is found, the SOAP 'Envelope' is returned. If an",
"XML string to be sent in transaction :rtype: bool ''' self.success= True self.output",
"if the call wass successful. it holds the error message (typos, config and",
"should process provided template_data by sending it using the selected transport. Essentially: return",
"base class for the WSMA Python module. \"\"\" from abc import ABCMeta, abstractmethod",
"has to be provided by the subclass. tls, ssh and http(s) are usable",
"make a unique string to return as a correlator :rtype: str ''' result",
"t = None t = '' if t is None else t self.output",
"parsing then dict(error='some error string') is returned. This still assumes that IF an",
"logging.debug(\"XML string: {}\".format(xml_text)) try: dom = parseString(xml_text) except ExpatError as e: return dict(error='%s'",
"json import time import logging class _Schema(object): def __init__(self): \"\"\" :rtype : basestring",
"<config-data> <cli-config-data-block>{{CONFIG_CMD}}</cli-config-data-block> </config-data> </configApply>\"\"\" self.template = Template(\"{0}{1}{2}\". format(self.begin_schema, self.body, self.end_schema)) class _ConfigPersistTemplate(_Schema): def",
"if line.get('failure'): self.output = line.get('text') break return False # catch all return False",
"the selected transport. Essentially: return self._process(send(data)) Assuming that send(template_data) returns XML from the",
"ExpatError as e: return dict(error='%s' % e) logging.debug(\"XML tree:{}\".format(dom.childNodes[-1].toprettyxml())) response = dom.getElementsByTagName('response') if",
"configured on the device (how could we connect otherwise?) 2) this is a",
"\"urn:cisco:wsma-config\": if self.success: t = 'config mode / not applicable' self.output = t",
"groundwork for specified transports. WSMA defines the following transports: - SSH - HTTP",
"during parsing then dict(error='some error string') is returned. This still assumes that IF",
"details=\"all\" {{ACTION_ON_FAIL}}> <config-data> <cli-config-data-block>{{CONFIG_CMD}}</cli-config-data-block> </config-data> </configApply>\"\"\" self.template = Template(\"{0}{1}{2}\". format(self.begin_schema, self.body, self.end_schema)) class",
"{} as {}/{}\".format(self.url, self.username, self.password)) @abstractmethod def disconnect(self): '''Disconnects the transport ''' logging.info(\"disconnect",
":rtype: bool ''' self.data = self.parseXML(xml_data) # did the parsing yield an error?",
"40) print(etree.tostring(element, pretty_print=True).decode('utf-8')) print(json.dumps(xmltodict.parse(xml_text), indent=4)) \"\"\" logging.debug(\"XML string: {}\".format(xml_text)) try: dom = parseString(xml_text)",
"run in exec mode on device :param format_spec: if there is a ODM",
"instead of unstructured CLI output) then this property holds the structured data as",
"action_on_fail self._count += 1 etmplate = _ConfigTemplate() template_data = etmplate.template.render(CONFIG_CMD=command, CORRELATOR=correlator, ACTION_ON_FAIL=fail_str, Username=self.username,",
"\"\"\" :rtype : basestring \"\"\" self.begin_schema = \"\"\"<?xml version=\"1.0\" encoding=\"UTF-8\"?> <SOAP:Envelope xmlns:SOAP=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:SOAP-ENC=\"http://schemas.xmlsoap.org/soap/encoding/\"",
"'' self.data = None # make sure we have a session if self._session",
"self._session = None @property def odmFormatResult(self): '''When using format specifications (e.g. structured data",
"% format_spec else: format_text = \"\" etmplate = _ExecTemplate() template_data = etmplate.template.render(EXEC_CMD=command, TIMEOUT=self.timeout,",
"'''Build a correlator for each command. Consists of - command to be sent",
"if not self.success: e = self.data['response']['execLog'][ 'errorInfo']['errorMessage'] self.output = e return False #",
"is found, the SOAP 'Envelope' is returned. If an empty string is used",
"import ExpatError import xmltodict import json import time import logging class _Schema(object): def",
"transports: - SSH - HTTP / HTTPS - TLS this is the WSMA",
"</request> </SOAP:Body> </SOAP:Envelope>\"\"\" class _ExecTemplate(_Schema): def __init__(self): \"\"\" :type self: object \"\"\" _Schema.__init__(self)",
"show commands), (string) if the call wass successful. it holds the error message",
"# multi line config input returns list if type(re) is list: results =",
"data instead of unstructured CLI output) then this property holds the structured data",
"an error occurs during parsing then dict(error='some error string') is returned. This still",
"= bool(int(self.data['response']['@success'])) except KeyError: self.output = 'unknown error / key error' return False",
"with response data :rtype: bool ''' self.data = self.parseXML(xml_data) # did the parsing",
"= self.parseXML(xml_data) # did the parsing yield an error? if self.data.get('error') is not",
"= e return False # config mode? if self.data['response']['@xmlns'] == \"urn:cisco:wsma-config\": if self.success:",
"if format_spec is not None: format_text = 'format=\"%s\"' % format_spec else: format_text =",
"exc_type, exc_val, exc_tb): logging.debug('WITH/AS disconnect session') self.disconnect() def _ping(self): '''Test the connection, does",
"XML from the device. :param template_data: XML string to be sent in transaction",
"or not. :rtype bool: ''' return self._session is not None and self._ping() def",
"could we connect otherwise?) 2) this is a priv-lvl-1 command 3) this command",
"config(self, command, action_on_fail=\"stop\"): '''Execute given commands in configuration mode. On success, self.output and",
"used or an error occurs during parsing then dict(error='some error string') is returned.",
"# -*- coding: utf-8 -*- \"\"\" This defines the base class for the",
"function then it should have a valid SOAP Envelope. :param xml_text: XML string",
"def __init__(self, host, username, password, port, timeout=60): super(Base, self).__init__() if not host: raise",
"received from the device :param data: dictionary with response data :rtype: bool '''",
"= time.strftime(\"%H%M%S\") result += \"-%s\" % str(self._count) result += ''.join(command.split()) self._count += 1",
"provided template_data by sending it using the selected transport. Essentially: return self._process(send(data)) Assuming",
"holds the structured data as an object. :rtype dict: ''' try: return self.data['response']['execLog']['dialogueLog']['received']['tree']",
"def __init__(self): \"\"\" :type self: object \"\"\" _Schema.__init__(self) self.body = \"\"\"<request xmlns=\"urn:cisco:wsma-config\" correlator=\"{{CORRELATOR}}\">",
"CORRELATOR=correlator, FORMAT=format_text, Username=self.username, Password=<PASSWORD>) logging.debug(\"Template {}\".format(template_data)) return self.communicate(template_data) def config(self, command, action_on_fail=\"stop\"): '''Execute",
"None else t self.output = t return True if not self.success: e =",
"None @property def hasSession(self): '''checks whether we have a valid session or not.",
"_Schema(object): def __init__(self): \"\"\" :rtype : basestring \"\"\" self.begin_schema = \"\"\"<?xml version=\"1.0\" encoding=\"UTF-8\"?>",
"be \"show version\" :rtype: bool ''' return self.execCLI(\"show wsma id\") def _buildCorrelator(self, command):",
"KeyError: return None @property def hasSession(self): '''checks whether we have a valid session",
"<SOAP:Header> <wsse:Security xmlns:wsse=\"http://schemas.xmlsoap.org/ws/2002/04/secext\" SOAP:mustUnderstand=\"false\"> <wsse:UsernameToken> <wsse:Username>{{Username}}</wsse:Username> <wsse:Password>{{Password}}</wsse:Password> </wsse:UsernameToken> </wsse:Security> </SOAP:Header> <SOAP:Body> \"\"\" self.end_schema",
"applicable' self.output = t return True if not self.success: re = self.data['response']['resultEntry'] #",
"xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"> <SOAP:Header> <wsse:Security xmlns:wsse=\"http://schemas.xmlsoap.org/ws/2002/04/secext\" SOAP:mustUnderstand=\"false\"> <wsse:UsernameToken> <wsse:Username>{{Username}}</wsse:Username> <wsse:Password>{{Password}}</wsse:Password> </wsse:UsernameToken> </wsse:Security> </SOAP:Header> <SOAP:Body> \"\"\"",
"self.data['response']['execLog'][ 'errorInfo']['errorMessage'] self.output = e return False # config mode? if self.data['response']['@xmlns'] ==",
"WSMA :class:`Base <Base>` class :param host: hostname of the WSMA server :param username:",
":param port: port to connect to :param timeout: timeout for transport ''' __metaclass__",
"self._count += 1 etmplate = _ConfigTemplate() template_data = etmplate.template.render(CONFIG_CMD=command, CORRELATOR=correlator, ACTION_ON_FAIL=fail_str, Username=self.username, Password=self.password)",
"the subclass. tls, ssh and http(s) are usable in IOS. ''' logging.info(\"connect to",
"return as a correlator :rtype: str ''' result = time.strftime(\"%H%M%S\") result += \"-%s\"",
"# config mode? if self.data['response']['@xmlns'] == \"urn:cisco:wsma-config\": if self.success: t = 'config mode",
"= '' self.data = None # make sure we have a session if",
"is assumed that 1) wsma is configured on the device (how could we",
"return self.data['response']['execLog']['dialogueLog']['received']['tree'] except KeyError: return None @property def hasSession(self): '''checks whether we have",
"* 40) print(etree.tostring(element, pretty_print=True).decode('utf-8')) print(json.dumps(xmltodict.parse(xml_text), indent=4)) \"\"\" logging.debug(\"XML string: {}\".format(xml_text)) try: dom =",
"timeout for transport ''' __metaclass__ = ABCMeta def __init__(self, host, username, password, port,",
"for each command. Consists of - command to be sent -and- - timestamp",
"transport ''' __metaclass__ = ABCMeta def __init__(self, host, username, password, port, timeout=60): super(Base,",
"object \"\"\" _Schema.__init__(self) self.body = \"\"\"<request xmlns=\"urn:cisco:wsma-config\" correlator=\"{{CORRELATOR}}\"> <configPersist> </configPersist>\"\"\" self.template = Template(\"{0}{1}{2}\".",
"valid SOAP Envelope. :param xml_text: XML string to be converted :rtype: dict '''",
"string to be converted :rtype: dict ''' if xml_text is None: return dict(error='XML",
"session if self._session == None: self.output = 'no established session!' self.success= False return",
"etmplate = _ConfigTemplate() template_data = etmplate.template.render(CONFIG_CMD=command, CORRELATOR=correlator, ACTION_ON_FAIL=fail_str, Username=self.username, Password=self.password) logging.debug(\"Template {0:s}\".format(template_data)) return",
"holds CLI output (e.g. for show commands), (string) if the call wass successful.",
"''' __metaclass__ = ABCMeta def __init__(self, host, username, password, port, timeout=60): super(Base, self).__init__()",
"self.success = False self.output = '' self.data = None # session holds the",
"t = self.data['response']['execLog'][ 'dialogueLog']['received']['text'] except KeyError: t = None t = '' if",
"transport ''' logging.info(\"disconnect from {}\".format(self.url)) self._session = None @property def odmFormatResult(self): '''When using",
"self.port = port self.success = False self.output = '' self.data = None #",
"self.output and self.success will be updated. If format_spec is given (and valid), odmFormatResult",
"(bool) - output: holds CLI output (e.g. for show commands), (string) if the",
"mode. On success, self.output and self.success will be updated. :param command: config block",
"class Base(object): '''The base class for all WSMA transports. Provides the groundwork for",
"'''Connects to the WSMA host via a specific transport. The specific implementation has",
"def config(self, command, action_on_fail=\"stop\"): '''Execute given commands in configuration mode. On success, self.output",
"configuration mode. On success, self.output and self.success will be updated. :param command: config",
"def __exit__(self, exc_type, exc_val, exc_tb): logging.debug('WITH/AS disconnect session') self.disconnect() def _ping(self): '''Test the",
"self.output = '' self.data = None # make sure we have a session",
"<configPersist> </configPersist>\"\"\" self.template = Template(\"{0}{1}{2}\". format(self.begin_schema, self.body, self.end_schema)) class Base(object): '''The base class",
"catch all return False @abstractmethod def communicate(self, template_data): '''Needs to be overwritten in",
"logging.debug('WITH/AS connect session') self.connect() return self if self._ping() else None def __exit__(self, exc_type,",
"Template(\"{0}{1}{2}\". format(self.begin_schema, self.body, self.end_schema)) class _ConfigTemplate(_Schema): def __init__(self): _Schema.__init__(self) self.body = \"\"\"<request xmlns=\"urn:cisco:wsma-config\"",
"transport. The specific implementation has to be provided by the subclass. tls, ssh",
"xmlns=\"urn:cisco:wsma-exec\" correlator=\"{{CORRELATOR}}\"> <execCLI maxWait=\"PT{{TIMEOUT}}S\" xsd=\"false\" {{FORMAT}}> <cmd>{{EXEC_CMD}}</cmd> </execCLI> \"\"\" self.template = Template(\"{0}{1}{2}\". format(self.begin_schema,",
"given XML string and returns the 'response' child within the XML tree. If",
"self.body, self.end_schema)) class _ConfigPersistTemplate(_Schema): def __init__(self): \"\"\" :type self: object \"\"\" _Schema.__init__(self) self.body",
"sent -and- - timestamp :param command: used to make a unique string to",
"= None # make sure we have a session if self._session == None:",
"bool: ''' return self._session is not None and self._ping() def execCLI(self, command, format_spec=None):",
"we have a valid session or not. :rtype bool: ''' return self._session is",
"= \"\"\" </request> </SOAP:Body> </SOAP:Envelope>\"\"\" class _ExecTemplate(_Schema): def __init__(self): \"\"\" :type self: object",
"to be sent -and- - timestamp :param command: used to make a unique",
"platforms supporting WSMA an alternative would be \"show version\" :rtype: bool ''' return",
"does it make sense to continue? it is assumed that 1) wsma is",
"to be sent in transaction :rtype: bool ''' self.success= True self.output = ''",
"- TLS this is the WSMA :class:`Base <Base>` class :param host: hostname of",
"def hasSession(self): '''checks whether we have a valid session or not. :rtype bool:",
"be updated. :param command: config block to be applied to the device :param",
"@staticmethod def parseXML(xml_text): '''Parses given XML string and returns the 'response' child within",
"the 'response' child within the XML tree. If no response is found, the",
"an empty string is used or an error occurs during parsing then dict(error='some",
"an XML string is passed into this function then it should have a",
"This defines the base class for the WSMA Python module. \"\"\" from abc",
"return self if self._ping() else None def __exit__(self, exc_type, exc_val, exc_tb): logging.debug('WITH/AS disconnect",
"<SOAP:Body> \"\"\" self.end_schema = \"\"\" </request> </SOAP:Body> </SOAP:Envelope>\"\"\" class _ExecTemplate(_Schema): def __init__(self): \"\"\"",
"spec file for the command :rtype: bool ''' correlator = self._buildCorrelator(\"exec\" + command)",
"with the result data. :param command: command string to be run in exec",
"be converted :rtype: dict ''' if xml_text is None: return dict(error='XML body is",
"specified transports. WSMA defines the following transports: - SSH - HTTP / HTTPS",
"template_data = etmplate.template.render(CONFIG_CMD=command, CORRELATOR=correlator, ACTION_ON_FAIL=fail_str, Username=self.username, Password=self.password) logging.debug(\"Template {0:s}\".format(template_data)) return self.communicate(template_data) def configPersist(self):",
"the call wass successful. it holds the error message (typos, config and exec)",
"self.output = e return False # config mode? if self.data['response']['@xmlns'] == \"urn:cisco:wsma-config\": if",
"not self.success: re = self.data['response']['resultEntry'] # multi line config input returns list if",
"session or not. :rtype bool: ''' return self._session is not None and self._ping()",
"results = re else: results = list() results.append(re) # look for first failed",
"Assuming that send(template_data) returns XML from the device. :param template_data: XML string to",
"be sent in transaction :rtype: bool ''' self.success= True self.output = '' self.data",
"Username=self.username, Password=self.password) logging.debug(\"Template {0:s}\".format(template_data)) return self.communicate(template_data) @staticmethod def parseXML(xml_text): '''Parses given XML string",
"@property def hasSession(self): '''checks whether we have a valid session or not. :rtype",
"format_spec: if there is a ODM spec file for the command :rtype: bool",
"'action-on-fail=\"%s\"' % action_on_fail self._count += 1 etmplate = _ConfigTemplate() template_data = etmplate.template.render(CONFIG_CMD=command, CORRELATOR=correlator,",
"_ExecTemplate() template_data = etmplate.template.render(EXEC_CMD=command, TIMEOUT=self.timeout, CORRELATOR=correlator, FORMAT=format_text, Username=self.username, Password=<PASSWORD>) logging.debug(\"Template {}\".format(template_data)) return self.communicate(template_data)",
"username to use :param password: <PASSWORD> :param port: port to connect to :param",
"empty string is used or an error occurs during parsing then dict(error='some error",
"self._ping() def execCLI(self, command, format_spec=None): '''Run given command in exec mode, return JSON",
"= parseString(xml_text) except ExpatError as e: return dict(error='%s' % e) logging.debug(\"XML tree:{}\".format(dom.childNodes[-1].toprettyxml())) response",
"break return False # catch all return False @abstractmethod def communicate(self, template_data): '''Needs",
"% action_on_fail self._count += 1 etmplate = _ConfigTemplate() template_data = etmplate.template.render(CONFIG_CMD=command, CORRELATOR=correlator, ACTION_ON_FAIL=fail_str,",
"/ key error' return False # exec mode? if self.data['response']['@xmlns'] == \"urn:cisco:wsma-exec\": if",
"try: self.success = bool(int(self.data['response']['@success'])) except KeyError: self.output = 'unknown error / key error'",
"was it successful? try: self.success = bool(int(self.data['response']['@success'])) except KeyError: self.output = 'unknown error",
"empty') \"\"\" from lxml import etree etree.register_namespace(\"SOAP\", \"http://schemas.xmlsoap.org/soap/envelope/\") element = etree.fromstring(xml_text.encode('utf-8')) print('#' *",
"</config-data> </configApply>\"\"\" self.template = Template(\"{0}{1}{2}\". format(self.begin_schema, self.body, self.end_schema)) class _ConfigPersistTemplate(_Schema): def __init__(self): \"\"\"",
"if self.data['response']['@xmlns'] == \"urn:cisco:wsma-exec\": if self.success: try: t = self.data['response']['execLog'][ 'dialogueLog']['received']['text'] except KeyError:",
"be run in exec mode on device :param format_spec: if there is a",
"Base(object): '''The base class for all WSMA transports. Provides the groundwork for specified",
"= 'action-on-fail=\"%s\"' % action_on_fail self._count += 1 etmplate = _ConfigTemplate() template_data = etmplate.template.render(CONFIG_CMD=command,",
"if self.data['response']['@xmlns'] == \"urn:cisco:wsma-config\": if self.success: t = 'config mode / not applicable'",
"have a valid SOAP Envelope. :param xml_text: XML string to be converted :rtype:",
"= 0 def __enter__(self): logging.debug('WITH/AS connect session') self.connect() return self if self._ping() else",
"the WSMA host via a specific transport. The specific implementation has to be",
"command is platform independent for platforms supporting WSMA an alternative would be \"show",
"coding: utf-8 -*- \"\"\" This defines the base class for the WSMA Python",
"success, self.output and self.success will be updated. If format_spec is given (and valid),",
"should have a valid SOAP Envelope. :param xml_text: XML string to be converted",
"self.body = \"\"\"<request xmlns=\"urn:cisco:wsma-exec\" correlator=\"{{CORRELATOR}}\"> <execCLI maxWait=\"PT{{TIMEOUT}}S\" xsd=\"false\" {{FORMAT}}> <cmd>{{EXEC_CMD}}</cmd> </execCLI> \"\"\" self.template",
"is not None: return False logging.info(\"JSON data: %s\", json.dumps(self.data, indent=4)) # was it",
"lxml import etree etree.register_namespace(\"SOAP\", \"http://schemas.xmlsoap.org/soap/envelope/\") element = etree.fromstring(xml_text.encode('utf-8')) print('#' * 40) print(etree.tostring(element, pretty_print=True).decode('utf-8'))",
"= '' if t is None else t self.output = t return True",
"list if type(re) is list: results = re else: results = list() results.append(re)",
"% e) logging.debug(\"XML tree:{}\".format(dom.childNodes[-1].toprettyxml())) response = dom.getElementsByTagName('response') if len(response) > 0: return xmltodict.parse(response[0].toxml())",
"= 'no established session!' self.success= False return self.success @abstractmethod def connect(self): '''Connects to",
"def disconnect(self): '''Disconnects the transport ''' logging.info(\"disconnect from {}\".format(self.url)) self._session = None @property",
"to use :param password: <PASSWORD> :param port: port to connect to :param timeout:",
"%s\", json.dumps(self.data, indent=4)) # was it successful? try: self.success = bool(int(self.data['response']['@success'])) except KeyError:",
"vars: - success: was the call successful (bool) - output: holds CLI output",
"string and returns the 'response' child within the XML tree. If no response",
"dict and populate instance vars: - success: was the call successful (bool) -",
"error occurs during parsing then dict(error='some error string') is returned. This still assumes",
"logging.info(\"disconnect from {}\".format(self.url)) self._session = None @property def odmFormatResult(self): '''When using format specifications",
"_Schema.__init__(self) self.body = \"\"\"<request xmlns=\"urn:cisco:wsma-exec\" correlator=\"{{CORRELATOR}}\"> <execCLI maxWait=\"PT{{TIMEOUT}}S\" xsd=\"false\" {{FORMAT}}> <cmd>{{EXEC_CMD}}</cmd> </execCLI> \"\"\"",
"command :rtype: bool ''' correlator = self._buildCorrelator(\"exec\" + command) if format_spec is not",
"and http(s) are usable in IOS. ''' logging.info(\"connect to {} as {}/{}\".format(self.url, self.username,",
"= 'config mode / not applicable' self.output = t return True if not",
"have a valid session or not. :rtype bool: ''' return self._session is not",
"class _ExecTemplate(_Schema): def __init__(self): \"\"\" :type self: object \"\"\" _Schema.__init__(self) self.body = \"\"\"<request",
"HTTP / HTTPS - TLS this is the WSMA :class:`Base <Base>` class :param",
":param timeout: timeout for transport ''' __metaclass__ = ABCMeta def __init__(self, host, username,",
"1) wsma is configured on the device (how could we connect otherwise?) 2)",
":param username: username to use :param password: <PASSWORD> :param port: port to connect",
"def __enter__(self): logging.debug('WITH/AS connect session') self.connect() return self if self._ping() else None def",
"\"urn:cisco:wsma-exec\": if self.success: try: t = self.data['response']['execLog'][ 'dialogueLog']['received']['text'] except KeyError: t = None",
"'errorInfo']['errorMessage'] self.output = e return False # config mode? if self.data['response']['@xmlns'] == \"urn:cisco:wsma-config\":",
"= 'unknown error / key error' return False # exec mode? if self.data['response']['@xmlns']",
"call wass successful. it holds the error message (typos, config and exec) if",
"self.password)) @abstractmethod def disconnect(self): '''Disconnects the transport ''' logging.info(\"disconnect from {}\".format(self.url)) self._session =",
"format_spec=None): '''Run given command in exec mode, return JSON response. The On success,",
"be updated. If format_spec is given (and valid), odmFormatResult will contain the dictionary",
"t = '' if t is None else t self.output = t return",
"xmlns=\"urn:cisco:wsma-config\" correlator=\"{{CORRELATOR}}\"> <configPersist> </configPersist>\"\"\" self.template = Template(\"{0}{1}{2}\". format(self.begin_schema, self.body, self.end_schema)) class Base(object): '''The",
"+= \"-%s\" % str(self._count) result += ''.join(command.split()) self._count += 1 return result def",
"if self.success: try: t = self.data['response']['execLog'][ 'dialogueLog']['received']['text'] except KeyError: t = None t",
"_process(self, xml_data): '''Process the given data dict and populate instance vars: - success:",
"not None and self._ping() def execCLI(self, command, format_spec=None): '''Run given command in exec",
"\"\"\" from lxml import etree etree.register_namespace(\"SOAP\", \"http://schemas.xmlsoap.org/soap/envelope/\") element = etree.fromstring(xml_text.encode('utf-8')) print('#' * 40)",
"ssh and http(s) are usable in IOS. ''' logging.info(\"connect to {} as {}/{}\".format(self.url,",
"t return True if not self.success: re = self.data['response']['resultEntry'] # multi line config",
"command) if format_spec is not None: format_text = 'format=\"%s\"' % format_spec else: format_text",
"self.connect() return self if self._ping() else None def __exit__(self, exc_type, exc_val, exc_tb): logging.debug('WITH/AS",
"</SOAP:Header> <SOAP:Body> \"\"\" self.end_schema = \"\"\" </request> </SOAP:Body> </SOAP:Envelope>\"\"\" class _ExecTemplate(_Schema): def __init__(self):",
"re = self.data['response']['resultEntry'] # multi line config input returns list if type(re) is",
"exec mode on device :param format_spec: if there is a ODM spec file",
"timeout=60): super(Base, self).__init__() if not host: raise ValueError(\"host argument may not be empty\")",
"try: dom = parseString(xml_text) except ExpatError as e: return dict(error='%s' % e) logging.debug(\"XML",
"Template(\"{0}{1}{2}\". format(self.begin_schema, self.body, self.end_schema)) class _ConfigPersistTemplate(_Schema): def __init__(self): \"\"\" :type self: object \"\"\"",
"config mode? if self.data['response']['@xmlns'] == \"urn:cisco:wsma-config\": if self.success: t = 'config mode /",
"output) then this property holds the structured data as an object. :rtype dict:",
"session') self.disconnect() def _ping(self): '''Test the connection, does it make sense to continue?",
"response is found, the SOAP 'Envelope' is returned. If an empty string is",
"if self._ping() else None def __exit__(self, exc_type, exc_val, exc_tb): logging.debug('WITH/AS disconnect session') self.disconnect()",
"'''Test the connection, does it make sense to continue? it is assumed that",
"each command. Consists of - command to be sent -and- - timestamp :param",
"str(self._count) result += ''.join(command.split()) self._count += 1 return result def _process(self, xml_data): '''Process",
"1 return result def _process(self, xml_data): '''Process the given data dict and populate",
"xml_data: holds the XML data received from the device :param data: dictionary with",
"not self.success: e = self.data['response']['execLog'][ 'errorInfo']['errorMessage'] self.output = e return False # config",
"None # count is used for the correlator over # the existence of",
"\"\"\"<request xmlns=\"urn:cisco:wsma-config\" correlator=\"{{CORRELATOR}}\"> <configPersist> </configPersist>\"\"\" self.template = Template(\"{0}{1}{2}\". format(self.begin_schema, self.body, self.end_schema)) class Base(object):",
"self.template = Template(\"{0}{1}{2}\". format(self.begin_schema, self.body, self.end_schema)) class Base(object): '''The base class for all",
"session holds the transport session self._session = None # count is used for",
"''' return self._session is not None and self._ping() def execCLI(self, command, format_spec=None): '''Run",
"if type(re) is list: results = re else: results = list() results.append(re) #",
"successful. it holds the error message (typos, config and exec) if not successful",
"True self.output = '' self.data = None # make sure we have a",
"for first failed element for line in results: if line.get('failure'): self.output = line.get('text')",
"whether we have a valid session or not. :rtype bool: ''' return self._session",
"except ExpatError as e: return dict(error='%s' % e) logging.debug(\"XML tree:{}\".format(dom.childNodes[-1].toprettyxml())) response = dom.getElementsByTagName('response')",
"class _ConfigPersistTemplate(_Schema): def __init__(self): \"\"\" :type self: object \"\"\" _Schema.__init__(self) self.body = \"\"\"<request",
"bool ''' self.data = self.parseXML(xml_data) # did the parsing yield an error? if",
"an alternative would be \"show version\" :rtype: bool ''' return self.execCLI(\"show wsma id\")",
"all WSMA transports. Provides the groundwork for specified transports. WSMA defines the following",
"'Envelope' is returned. If an empty string is used or an error occurs",
"results = list() results.append(re) # look for first failed element for line in",
"Provides the groundwork for specified transports. WSMA defines the following transports: - SSH",
"import time import logging class _Schema(object): def __init__(self): \"\"\" :rtype : basestring \"\"\"",
"etmplate.template.render(CORRELATOR=correlator, Username=self.username, Password=self.password) logging.debug(\"Template {0:s}\".format(template_data)) return self.communicate(template_data) @staticmethod def parseXML(xml_text): '''Parses given XML",
"'''Disconnects the transport ''' logging.info(\"disconnect from {}\".format(self.url)) self._session = None @property def odmFormatResult(self):",
"xml_text: XML string to be converted :rtype: dict ''' if xml_text is None:",
"response = dom.getElementsByTagName('response') if len(response) > 0: return xmltodict.parse(response[0].toxml()) return xmltodict.parse( dom.getElementsByTagNameNS( \"http://schemas.xmlsoap.org/soap/envelope/\",",
"self._session is not None and self._ping() def execCLI(self, command, format_spec=None): '''Run given command",
"are usable in IOS. ''' logging.info(\"connect to {} as {}/{}\".format(self.url, self.username, self.password)) @abstractmethod",
"self._count += 1 return result def _process(self, xml_data): '''Process the given data dict",
"WSMA an alternative would be \"show version\" :rtype: bool ''' return self.execCLI(\"show wsma",
"etree.register_namespace(\"SOAP\", \"http://schemas.xmlsoap.org/soap/envelope/\") element = etree.fromstring(xml_text.encode('utf-8')) print('#' * 40) print(etree.tostring(element, pretty_print=True).decode('utf-8')) print(json.dumps(xmltodict.parse(xml_text), indent=4)) \"\"\"",
"mode, return JSON response. The On success, self.output and self.success will be updated.",
"for the command :rtype: bool ''' correlator = self._buildCorrelator(\"exec\" + command) if format_spec",
"this is the WSMA :class:`Base <Base>` class :param host: hostname of the WSMA",
"__enter__(self): logging.debug('WITH/AS connect session') self.connect() return self if self._ping() else None def __exit__(self,",
"it make sense to continue? it is assumed that 1) wsma is configured",
"result += \"-%s\" % str(self._count) result += ''.join(command.split()) self._count += 1 return result",
"else: format_text = \"\" etmplate = _ExecTemplate() template_data = etmplate.template.render(EXEC_CMD=command, TIMEOUT=self.timeout, CORRELATOR=correlator, FORMAT=format_text,",
"XML string is passed into this function then it should have a valid",
"xml_text is None: return dict(error='XML body is empty') \"\"\" from lxml import etree",
"transport session self._session = None # count is used for the correlator over",
"that IF an XML string is passed into this function then it should",
"to {} as {}/{}\".format(self.url, self.username, self.password)) @abstractmethod def disconnect(self): '''Disconnects the transport '''",
"- timestamp :param command: used to make a unique string to return as",
"is used for the correlator over # the existence of the session self._count",
"host self.username = username self.password = password self.port = port self.success = False",
"version=\"1.0\" encoding=\"UTF-8\"?> <SOAP:Envelope xmlns:SOAP=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:SOAP-ENC=\"http://schemas.xmlsoap.org/soap/encoding/\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"> <SOAP:Header> <wsse:Security xmlns:wsse=\"http://schemas.xmlsoap.org/ws/2002/04/secext\" SOAP:mustUnderstand=\"false\"> <wsse:UsernameToken> <wsse:Username>{{Username}}</wsse:Username>",
"self.body, self.end_schema)) class _ConfigTemplate(_Schema): def __init__(self): _Schema.__init__(self) self.body = \"\"\"<request xmlns=\"urn:cisco:wsma-config\" correlator=\"{{CORRELATOR}}\"> <configApply",
"self.end_schema = \"\"\" </request> </SOAP:Body> </SOAP:Envelope>\"\"\" class _ExecTemplate(_Schema): def __init__(self): \"\"\" :type self:",
"not successful - xml_data: holds the XML data received from the device :param",
"''' result = time.strftime(\"%H%M%S\") result += \"-%s\" % str(self._count) result += ''.join(command.split()) self._count",
"correlator = self._buildCorrelator(\"config\") fail_str = 'action-on-fail=\"%s\"' % action_on_fail self._count += 1 etmplate =",
"into this function then it should have a valid SOAP Envelope. :param xml_text:",
"</SOAP:Envelope>\"\"\" class _ExecTemplate(_Schema): def __init__(self): \"\"\" :type self: object \"\"\" _Schema.__init__(self) self.body =",
"correlator for each command. Consists of - command to be sent -and- -",
":rtype: str ''' result = time.strftime(\"%H%M%S\") result += \"-%s\" % str(self._count) result +=",
"instance vars: - success: was the call successful (bool) - output: holds CLI",
"None and self._ping() def execCLI(self, command, format_spec=None): '''Run given command in exec mode,",
"if xml_text is None: return dict(error='XML body is empty') \"\"\" from lxml import",
"self.body = \"\"\"<request xmlns=\"urn:cisco:wsma-config\" correlator=\"{{CORRELATOR}}\"> <configPersist> </configPersist>\"\"\" self.template = Template(\"{0}{1}{2}\". format(self.begin_schema, self.body, self.end_schema))",
"= self.data['response']['resultEntry'] # multi line config input returns list if type(re) is list:",
"= password self.port = port self.success = False self.output = '' self.data =",
"{}\".format(self.url)) self._session = None @property def odmFormatResult(self): '''When using format specifications (e.g. structured",
":param password: <PASSWORD> :param port: port to connect to :param timeout: timeout for",
"sure we have a session if self._session == None: self.output = 'no established",
"time import logging class _Schema(object): def __init__(self): \"\"\" :rtype : basestring \"\"\" self.begin_schema",
"response. The On success, self.output and self.success will be updated. If format_spec is",
"the transport session self._session = None # count is used for the correlator",
":rtype: bool ''' correlator = self._buildCorrelator(\"exec\" + command) if format_spec is not None:",
"to be provided by the subclass. tls, ssh and http(s) are usable in",
"contain the dictionary with the result data. :param command: command string to be",
"data. :param command: command string to be run in exec mode on device",
"def communicate(self, template_data): '''Needs to be overwritten in subclass, it should process provided",
"command to be sent -and- - timestamp :param command: used to make a",
"= None t = '' if t is None else t self.output =",
"e = self.data['response']['execLog'][ 'errorInfo']['errorMessage'] self.output = e return False # config mode? if",
"child within the XML tree. If no response is found, the SOAP 'Envelope'",
"# was it successful? try: self.success = bool(int(self.data['response']['@success'])) except KeyError: self.output = 'unknown",
"def execCLI(self, command, format_spec=None): '''Run given command in exec mode, return JSON response.",
"session self._session = None # count is used for the correlator over #",
"self.output = t return True if not self.success: e = self.data['response']['execLog'][ 'errorInfo']['errorMessage'] self.output",
"return self._process(send(data)) Assuming that send(template_data) returns XML from the device. :param template_data: XML",
"HTTPS - TLS this is the WSMA :class:`Base <Base>` class :param host: hostname",
"http(s) are usable in IOS. ''' logging.info(\"connect to {} as {}/{}\".format(self.url, self.username, self.password))",
"class _ConfigTemplate(_Schema): def __init__(self): _Schema.__init__(self) self.body = \"\"\"<request xmlns=\"urn:cisco:wsma-config\" correlator=\"{{CORRELATOR}}\"> <configApply details=\"all\" {{ACTION_ON_FAIL}}>",
"__metaclass__ = ABCMeta def __init__(self, host, username, password, port, timeout=60): super(Base, self).__init__() if",
"of the WSMA server :param username: username to use :param password: <PASSWORD> :param",
"# the existence of the session self._count = 0 def __enter__(self): logging.debug('WITH/AS connect",
"On success, self.output and self.success will be updated. :param command: config block to",
"if self.success: t = 'config mode / not applicable' self.output = t return",
"If no response is found, the SOAP 'Envelope' is returned. If an empty",
"(string) if the call wass successful. it holds the error message (typos, config",
"commands), (string) if the call wass successful. it holds the error message (typos,",
"print('#' * 40) print(etree.tostring(element, pretty_print=True).decode('utf-8')) print(json.dumps(xmltodict.parse(xml_text), indent=4)) \"\"\" logging.debug(\"XML string: {}\".format(xml_text)) try: dom",
"the XML data received from the device :param data: dictionary with response data",
"CLI output) then this property holds the structured data as an object. :rtype",
"{0:s}\".format(template_data)) return self.communicate(template_data) def configPersist(self): '''Makes configuration changes persistent. :rtype: bool ''' correlator",
"parsing yield an error? if self.data.get('error') is not None: return False logging.info(\"JSON data:",
"line in results: if line.get('failure'): self.output = line.get('text') break return False # catch",
"# make sure we have a session if self._session == None: self.output =",
"On success, self.output and self.success will be updated. If format_spec is given (and",
"configPersist(self): '''Makes configuration changes persistent. :rtype: bool ''' correlator = self._buildCorrelator(\"config-persist\") etmplate =",
"self: object \"\"\" _Schema.__init__(self) self.body = \"\"\"<request xmlns=\"urn:cisco:wsma-config\" correlator=\"{{CORRELATOR}}\"> <configPersist> </configPersist>\"\"\" self.template =",
"self.data['response']['@xmlns'] == \"urn:cisco:wsma-config\": if self.success: t = 'config mode / not applicable' self.output",
"the device :param data: dictionary with response data :rtype: bool ''' self.data =",
"that send(template_data) returns XML from the device. :param template_data: XML string to be",
"'' self.data = None # session holds the transport session self._session = None",
"the WSMA :class:`Base <Base>` class :param host: hostname of the WSMA server :param",
"argument may not be empty\") self.timeout = timeout self.host = host self.username =",
"@abstractmethod def communicate(self, template_data): '''Needs to be overwritten in subclass, it should process",
"be overwritten in subclass, it should process provided template_data by sending it using",
"/ HTTPS - TLS this is the WSMA :class:`Base <Base>` class :param host:",
"make sure we have a session if self._session == None: self.output = 'no",
"'no established session!' self.success= False return self.success @abstractmethod def connect(self): '''Connects to the",
"'''When using format specifications (e.g. structured data instead of unstructured CLI output) then",
"logging.debug(\"Template {0:s}\".format(template_data)) return self.communicate(template_data) @staticmethod def parseXML(xml_text): '''Parses given XML string and returns",
"'''Execute given commands in configuration mode. On success, self.output and self.success will be",
"def __init__(self): \"\"\" :rtype : basestring \"\"\" self.begin_schema = \"\"\"<?xml version=\"1.0\" encoding=\"UTF-8\"?> <SOAP:Envelope",
"<wsse:UsernameToken> <wsse:Username>{{Username}}</wsse:Username> <wsse:Password>{{Password}}</wsse:Password> </wsse:UsernameToken> </wsse:Security> </SOAP:Header> <SOAP:Body> \"\"\" self.end_schema = \"\"\" </request> </SOAP:Body>",
"etmplate = _ExecTemplate() template_data = etmplate.template.render(EXEC_CMD=command, TIMEOUT=self.timeout, CORRELATOR=correlator, FORMAT=format_text, Username=self.username, Password=<PASSWORD>) logging.debug(\"Template {}\".format(template_data))",
"mode / not applicable' self.output = t return True if not self.success: re",
"for the correlator over # the existence of the session self._count = 0",
":rtype : basestring \"\"\" self.begin_schema = \"\"\"<?xml version=\"1.0\" encoding=\"UTF-8\"?> <SOAP:Envelope xmlns:SOAP=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:SOAP-ENC=\"http://schemas.xmlsoap.org/soap/encoding/\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"",
"bool(int(self.data['response']['@success'])) except KeyError: self.output = 'unknown error / key error' return False #",
"the session self._count = 0 def __enter__(self): logging.debug('WITH/AS connect session') self.connect() return self",
"t return True if not self.success: e = self.data['response']['execLog'][ 'errorInfo']['errorMessage'] self.output = e",
"self.output = line.get('text') break return False # catch all return False @abstractmethod def",
"via a specific transport. The specific implementation has to be provided by the",
"the SOAP 'Envelope' is returned. If an empty string is used or an",
"returns XML from the device. :param template_data: XML string to be sent in",
"format_spec is not None: format_text = 'format=\"%s\"' % format_spec else: format_text = \"\"",
"this command is platform independent for platforms supporting WSMA an alternative would be",
"successful - xml_data: holds the XML data received from the device :param data:",
"False # catch all return False @abstractmethod def communicate(self, template_data): '''Needs to be",
"False # config mode? if self.data['response']['@xmlns'] == \"urn:cisco:wsma-config\": if self.success: t = 'config",
"returns list if type(re) is list: results = re else: results = list()",
"self.success= True self.output = '' self.data = None # make sure we have",
"def _process(self, xml_data): '''Process the given data dict and populate instance vars: -",
"e: return dict(error='%s' % e) logging.debug(\"XML tree:{}\".format(dom.childNodes[-1].toprettyxml())) response = dom.getElementsByTagName('response') if len(response) >",
"'format=\"%s\"' % format_spec else: format_text = \"\" etmplate = _ExecTemplate() template_data = etmplate.template.render(EXEC_CMD=command,",
"XML string and returns the 'response' child within the XML tree. If no",
"connection, does it make sense to continue? it is assumed that 1) wsma",
"xmltodict import json import time import logging class _Schema(object): def __init__(self): \"\"\" :rtype",
"dictionary with response data :rtype: bool ''' self.data = self.parseXML(xml_data) # did the",
"return False # exec mode? if self.data['response']['@xmlns'] == \"urn:cisco:wsma-exec\": if self.success: try: t",
"self.data = None # make sure we have a session if self._session ==",
"-and- - timestamp :param command: used to make a unique string to return",
"then this property holds the structured data as an object. :rtype dict: '''",
"as an object. :rtype dict: ''' try: return self.data['response']['execLog']['dialogueLog']['received']['tree'] except KeyError: return None",
"import logging class _Schema(object): def __init__(self): \"\"\" :rtype : basestring \"\"\" self.begin_schema =",
"- command to be sent -and- - timestamp :param command: used to make",
":rtype bool: ''' return self._session is not None and self._ping() def execCLI(self, command,",
"ABCMeta, abstractmethod from jinja2 import Template from xml.dom.minidom import parseString from xml.parsers.expat import",
"count is used for the correlator over # the existence of the session",
"else: results = list() results.append(re) # look for first failed element for line",
"updated. :param command: config block to be applied to the device :param action_on_fail,",
"config block to be applied to the device :param action_on_fail, can be \"stop\",",
"dict(error='%s' % e) logging.debug(\"XML tree:{}\".format(dom.childNodes[-1].toprettyxml())) response = dom.getElementsByTagName('response') if len(response) > 0: return",
"a correlator :rtype: str ''' result = time.strftime(\"%H%M%S\") result += \"-%s\" % str(self._count)",
"process provided template_data by sending it using the selected transport. Essentially: return self._process(send(data))",
"given (and valid), odmFormatResult will contain the dictionary with the result data. :param",
"using format specifications (e.g. structured data instead of unstructured CLI output) then this",
"-*- coding: utf-8 -*- \"\"\" This defines the base class for the WSMA",
"holds the transport session self._session = None # count is used for the",
"in subclass, it should process provided template_data by sending it using the selected",
"etree etree.register_namespace(\"SOAP\", \"http://schemas.xmlsoap.org/soap/envelope/\") element = etree.fromstring(xml_text.encode('utf-8')) print('#' * 40) print(etree.tostring(element, pretty_print=True).decode('utf-8')) print(json.dumps(xmltodict.parse(xml_text), indent=4))",
"be applied to the device :param action_on_fail, can be \"stop\", \"continue\", \"rollback\" :rtype:",
"FORMAT=format_text, Username=self.username, Password=<PASSWORD>) logging.debug(\"Template {}\".format(template_data)) return self.communicate(template_data) def config(self, command, action_on_fail=\"stop\"): '''Execute given",
"= '' self.data = None # session holds the transport session self._session =",
"= etmplate.template.render(CONFIG_CMD=command, CORRELATOR=correlator, ACTION_ON_FAIL=fail_str, Username=self.username, Password=self.password) logging.debug(\"Template {0:s}\".format(template_data)) return self.communicate(template_data) def configPersist(self): '''Makes",
"'dialogueLog']['received']['text'] except KeyError: t = None t = '' if t is None",
"commands in configuration mode. On success, self.output and self.success will be updated. :param",
"format_text = 'format=\"%s\"' % format_spec else: format_text = \"\" etmplate = _ExecTemplate() template_data",
"is passed into this function then it should have a valid SOAP Envelope.",
"__exit__(self, exc_type, exc_val, exc_tb): logging.debug('WITH/AS disconnect session') self.disconnect() def _ping(self): '''Test the connection,",
"== None: self.output = 'no established session!' self.success= False return self.success @abstractmethod def",
"the given data dict and populate instance vars: - success: was the call",
"following transports: - SSH - HTTP / HTTPS - TLS this is the",
"connect to :param timeout: timeout for transport ''' __metaclass__ = ABCMeta def __init__(self,",
"first failed element for line in results: if line.get('failure'): self.output = line.get('text') break",
"format(self.begin_schema, self.body, self.end_schema)) class Base(object): '''The base class for all WSMA transports. Provides",
"the dictionary with the result data. :param command: command string to be run",
"the device :param action_on_fail, can be \"stop\", \"continue\", \"rollback\" :rtype: bool ''' correlator",
"dom = parseString(xml_text) except ExpatError as e: return dict(error='%s' % e) logging.debug(\"XML tree:{}\".format(dom.childNodes[-1].toprettyxml()))",
"empty\") self.timeout = timeout self.host = host self.username = username self.password = password",
"provided by the subclass. tls, ssh and http(s) are usable in IOS. '''",
"it using the selected transport. Essentially: return self._process(send(data)) Assuming that send(template_data) returns XML",
"from the device. :param template_data: XML string to be sent in transaction :rtype:",
"command: command string to be run in exec mode on device :param format_spec:",
"'''checks whether we have a valid session or not. :rtype bool: ''' return",
"the device. :param template_data: XML string to be sent in transaction :rtype: bool",
"% str(self._count) result += ''.join(command.split()) self._count += 1 return result def _process(self, xml_data):",
"= self._buildCorrelator(\"config\") fail_str = 'action-on-fail=\"%s\"' % action_on_fail self._count += 1 etmplate = _ConfigTemplate()",
"the connection, does it make sense to continue? it is assumed that 1)",
"and returns the 'response' child within the XML tree. If no response is",
"the groundwork for specified transports. WSMA defines the following transports: - SSH -",
"on the device (how could we connect otherwise?) 2) this is a priv-lvl-1",
"<wsse:Username>{{Username}}</wsse:Username> <wsse:Password>{{Password}}</wsse:Password> </wsse:UsernameToken> </wsse:Security> </SOAP:Header> <SOAP:Body> \"\"\" self.end_schema = \"\"\" </request> </SOAP:Body> </SOAP:Envelope>\"\"\"",
"self.parseXML(xml_data) # did the parsing yield an error? if self.data.get('error') is not None:",
"(and valid), odmFormatResult will contain the dictionary with the result data. :param command:",
"body is empty') \"\"\" from lxml import etree etree.register_namespace(\"SOAP\", \"http://schemas.xmlsoap.org/soap/envelope/\") element = etree.fromstring(xml_text.encode('utf-8'))",
"= etmplate.template.render(EXEC_CMD=command, TIMEOUT=self.timeout, CORRELATOR=correlator, FORMAT=format_text, Username=self.username, Password=<PASSWORD>) logging.debug(\"Template {}\".format(template_data)) return self.communicate(template_data) def config(self,",
"# count is used for the correlator over # the existence of the",
"self.end_schema)) class _ConfigTemplate(_Schema): def __init__(self): _Schema.__init__(self) self.body = \"\"\"<request xmlns=\"urn:cisco:wsma-config\" correlator=\"{{CORRELATOR}}\"> <configApply details=\"all\"",
"- SSH - HTTP / HTTPS - TLS this is the WSMA :class:`Base",
"t self.output = t return True if not self.success: e = self.data['response']['execLog'][ 'errorInfo']['errorMessage']",
"class for the WSMA Python module. \"\"\" from abc import ABCMeta, abstractmethod from",
"+= 1 etmplate = _ConfigTemplate() template_data = etmplate.template.render(CONFIG_CMD=command, CORRELATOR=correlator, ACTION_ON_FAIL=fail_str, Username=self.username, Password=self.password) logging.debug(\"Template",
"if not host: raise ValueError(\"host argument may not be empty\") self.timeout = timeout",
"abc import ABCMeta, abstractmethod from jinja2 import Template from xml.dom.minidom import parseString from",
"self.timeout = timeout self.host = host self.username = username self.password = password self.port",
"response data :rtype: bool ''' self.data = self.parseXML(xml_data) # did the parsing yield",
"{}\".format(template_data)) return self.communicate(template_data) def config(self, command, action_on_fail=\"stop\"): '''Execute given commands in configuration mode.",
"disconnect session') self.disconnect() def _ping(self): '''Test the connection, does it make sense to",
"dict ''' if xml_text is None: return dict(error='XML body is empty') \"\"\" from",
"config input returns list if type(re) is list: results = re else: results",
"etmplate = _ConfigPersistTemplate() template_data = etmplate.template.render(CORRELATOR=correlator, Username=self.username, Password=self.password) logging.debug(\"Template {0:s}\".format(template_data)) return self.communicate(template_data) @staticmethod",
"continue? it is assumed that 1) wsma is configured on the device (how",
"XML data received from the device :param data: dictionary with response data :rtype:",
"</wsse:Security> </SOAP:Header> <SOAP:Body> \"\"\" self.end_schema = \"\"\" </request> </SOAP:Body> </SOAP:Envelope>\"\"\" class _ExecTemplate(_Schema): def",
"logging.info(\"JSON data: %s\", json.dumps(self.data, indent=4)) # was it successful? try: self.success = bool(int(self.data['response']['@success']))",
"be empty\") self.timeout = timeout self.host = host self.username = username self.password =",
"import json import time import logging class _Schema(object): def __init__(self): \"\"\" :rtype :",
"WSMA server :param username: username to use :param password: <PASSWORD> :param port: port",
"Username=self.username, Password=<PASSWORD>) logging.debug(\"Template {}\".format(template_data)) return self.communicate(template_data) def config(self, command, action_on_fail=\"stop\"): '''Execute given commands",
"= port self.success = False self.output = '' self.data = None # session",
"look for first failed element for line in results: if line.get('failure'): self.output =",
"- success: was the call successful (bool) - output: holds CLI output (e.g.",
"by the subclass. tls, ssh and http(s) are usable in IOS. ''' logging.info(\"connect",
"correlator=\"{{CORRELATOR}}\"> <configApply details=\"all\" {{ACTION_ON_FAIL}}> <config-data> <cli-config-data-block>{{CONFIG_CMD}}</cli-config-data-block> </config-data> </configApply>\"\"\" self.template = Template(\"{0}{1}{2}\". format(self.begin_schema, self.body,",
"to be converted :rtype: dict ''' if xml_text is None: return dict(error='XML body",
"= dom.getElementsByTagName('response') if len(response) > 0: return xmltodict.parse(response[0].toxml()) return xmltodict.parse( dom.getElementsByTagNameNS( \"http://schemas.xmlsoap.org/soap/envelope/\", \"Envelope\")[0].toxml())",
"a ODM spec file for the command :rtype: bool ''' correlator = self._buildCorrelator(\"exec\"",
"for line in results: if line.get('failure'): self.output = line.get('text') break return False #",
":param template_data: XML string to be sent in transaction :rtype: bool ''' self.success=",
"abstractmethod from jinja2 import Template from xml.dom.minidom import parseString from xml.parsers.expat import ExpatError",
"username: username to use :param password: <PASSWORD> :param port: port to connect to",
"data :rtype: bool ''' self.data = self.parseXML(xml_data) # did the parsing yield an",
"CORRELATOR=correlator, ACTION_ON_FAIL=fail_str, Username=self.username, Password=self.password) logging.debug(\"Template {0:s}\".format(template_data)) return self.communicate(template_data) def configPersist(self): '''Makes configuration changes",
"def _ping(self): '''Test the connection, does it make sense to continue? it is",
"return result def _process(self, xml_data): '''Process the given data dict and populate instance",
"property holds the structured data as an object. :rtype dict: ''' try: return",
"= \"\" etmplate = _ExecTemplate() template_data = etmplate.template.render(EXEC_CMD=command, TIMEOUT=self.timeout, CORRELATOR=correlator, FORMAT=format_text, Username=self.username, Password=<PASSWORD>)",
"ExpatError import xmltodict import json import time import logging class _Schema(object): def __init__(self):",
"timeout: timeout for transport ''' __metaclass__ = ABCMeta def __init__(self, host, username, password,",
"def odmFormatResult(self): '''When using format specifications (e.g. structured data instead of unstructured CLI",
"_ConfigTemplate() template_data = etmplate.template.render(CONFIG_CMD=command, CORRELATOR=correlator, ACTION_ON_FAIL=fail_str, Username=self.username, Password=self.password) logging.debug(\"Template {0:s}\".format(template_data)) return self.communicate(template_data) def",
"logging class _Schema(object): def __init__(self): \"\"\" :rtype : basestring \"\"\" self.begin_schema = \"\"\"<?xml",
"valid), odmFormatResult will contain the dictionary with the result data. :param command: command",
"for the WSMA Python module. \"\"\" from abc import ABCMeta, abstractmethod from jinja2",
"WSMA Python module. \"\"\" from abc import ABCMeta, abstractmethod from jinja2 import Template",
"can be \"stop\", \"continue\", \"rollback\" :rtype: bool ''' correlator = self._buildCorrelator(\"config\") fail_str =",
"_Schema.__init__(self) self.body = \"\"\"<request xmlns=\"urn:cisco:wsma-config\" correlator=\"{{CORRELATOR}}\"> <configApply details=\"all\" {{ACTION_ON_FAIL}}> <config-data> <cli-config-data-block>{{CONFIG_CMD}}</cli-config-data-block> </config-data> </configApply>\"\"\"",
"for show commands), (string) if the call wass successful. it holds the error",
"found, the SOAP 'Envelope' is returned. If an empty string is used or",
"assumes that IF an XML string is passed into this function then it",
"self._buildCorrelator(\"exec\" + command) if format_spec is not None: format_text = 'format=\"%s\"' % format_spec",
"<cmd>{{EXEC_CMD}}</cmd> </execCLI> \"\"\" self.template = Template(\"{0}{1}{2}\". format(self.begin_schema, self.body, self.end_schema)) class _ConfigTemplate(_Schema): def __init__(self):",
"be \"stop\", \"continue\", \"rollback\" :rtype: bool ''' correlator = self._buildCorrelator(\"config\") fail_str = 'action-on-fail=\"%s\"'",
"If an empty string is used or an error occurs during parsing then",
"xmlns:SOAP-ENC=\"http://schemas.xmlsoap.org/soap/encoding/\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"> <SOAP:Header> <wsse:Security xmlns:wsse=\"http://schemas.xmlsoap.org/ws/2002/04/secext\" SOAP:mustUnderstand=\"false\"> <wsse:UsernameToken> <wsse:Username>{{Username}}</wsse:Username> <wsse:Password>{{Password}}</wsse:Password> </wsse:UsernameToken> </wsse:Security> </SOAP:Header>",
"logging.debug(\"XML tree:{}\".format(dom.childNodes[-1].toprettyxml())) response = dom.getElementsByTagName('response') if len(response) > 0: return xmltodict.parse(response[0].toxml()) return xmltodict.parse(",
"self.output = 'no established session!' self.success= False return self.success @abstractmethod def connect(self): '''Connects",
"action_on_fail=\"stop\"): '''Execute given commands in configuration mode. On success, self.output and self.success will",
"''' self.data = self.parseXML(xml_data) # did the parsing yield an error? if self.data.get('error')",
"= \"\"\"<request xmlns=\"urn:cisco:wsma-exec\" correlator=\"{{CORRELATOR}}\"> <execCLI maxWait=\"PT{{TIMEOUT}}S\" xsd=\"false\" {{FORMAT}}> <cmd>{{EXEC_CMD}}</cmd> </execCLI> \"\"\" self.template =",
"it holds the error message (typos, config and exec) if not successful -",
"it should have a valid SOAP Envelope. :param xml_text: XML string to be",
"format_spec else: format_text = \"\" etmplate = _ExecTemplate() template_data = etmplate.template.render(EXEC_CMD=command, TIMEOUT=self.timeout, CORRELATOR=correlator,",
"of the session self._count = 0 def __enter__(self): logging.debug('WITH/AS connect session') self.connect() return",
"defines the base class for the WSMA Python module. \"\"\" from abc import",
"is platform independent for platforms supporting WSMA an alternative would be \"show version\"",
"\"\"\" This defines the base class for the WSMA Python module. \"\"\" from",
"from abc import ABCMeta, abstractmethod from jinja2 import Template from xml.dom.minidom import parseString",
"applied to the device :param action_on_fail, can be \"stop\", \"continue\", \"rollback\" :rtype: bool",
"SOAP:mustUnderstand=\"false\"> <wsse:UsernameToken> <wsse:Username>{{Username}}</wsse:Username> <wsse:Password>{{Password}}</wsse:Password> </wsse:UsernameToken> </wsse:Security> </SOAP:Header> <SOAP:Body> \"\"\" self.end_schema = \"\"\" </request>",
"= Template(\"{0}{1}{2}\". format(self.begin_schema, self.body, self.end_schema)) class _ConfigTemplate(_Schema): def __init__(self): _Schema.__init__(self) self.body = \"\"\"<request",
"line.get('text') break return False # catch all return False @abstractmethod def communicate(self, template_data):",
"{{FORMAT}}> <cmd>{{EXEC_CMD}}</cmd> </execCLI> \"\"\" self.template = Template(\"{0}{1}{2}\". format(self.begin_schema, self.body, self.end_schema)) class _ConfigTemplate(_Schema): def",
":type self: object \"\"\" _Schema.__init__(self) self.body = \"\"\"<request xmlns=\"urn:cisco:wsma-config\" correlator=\"{{CORRELATOR}}\"> <configPersist> </configPersist>\"\"\" self.template",
"<wsse:Security xmlns:wsse=\"http://schemas.xmlsoap.org/ws/2002/04/secext\" SOAP:mustUnderstand=\"false\"> <wsse:UsernameToken> <wsse:Username>{{Username}}</wsse:Username> <wsse:Password>{{Password}}</wsse:Password> </wsse:UsernameToken> </wsse:Security> </SOAP:Header> <SOAP:Body> \"\"\" self.end_schema =",
"e return False # config mode? if self.data['response']['@xmlns'] == \"urn:cisco:wsma-config\": if self.success: t",
"to the device :param action_on_fail, can be \"stop\", \"continue\", \"rollback\" :rtype: bool '''",
"changes persistent. :rtype: bool ''' correlator = self._buildCorrelator(\"config-persist\") etmplate = _ConfigPersistTemplate() template_data =",
"'response' child within the XML tree. If no response is found, the SOAP",
"sending it using the selected transport. Essentially: return self._process(send(data)) Assuming that send(template_data) returns",
"will be updated. If format_spec is given (and valid), odmFormatResult will contain the",
"that 1) wsma is configured on the device (how could we connect otherwise?)",
"and self._ping() def execCLI(self, command, format_spec=None): '''Run given command in exec mode, return",
"== \"urn:cisco:wsma-config\": if self.success: t = 'config mode / not applicable' self.output =",
"format_spec is given (and valid), odmFormatResult will contain the dictionary with the result",
"except KeyError: self.output = 'unknown error / key error' return False # exec",
"return dict(error='%s' % e) logging.debug(\"XML tree:{}\".format(dom.childNodes[-1].toprettyxml())) response = dom.getElementsByTagName('response') if len(response) > 0:",
"element = etree.fromstring(xml_text.encode('utf-8')) print('#' * 40) print(etree.tostring(element, pretty_print=True).decode('utf-8')) print(json.dumps(xmltodict.parse(xml_text), indent=4)) \"\"\" logging.debug(\"XML string:",
"still assumes that IF an XML string is passed into this function then",
"host, username, password, port, timeout=60): super(Base, self).__init__() if not host: raise ValueError(\"host argument",
"on device :param format_spec: if there is a ODM spec file for the",
"is used or an error occurs during parsing then dict(error='some error string') is",
"the correlator over # the existence of the session self._count = 0 def",
"/ not applicable' self.output = t return True if not self.success: re =",
"3) this command is platform independent for platforms supporting WSMA an alternative would",
"XML string to be converted :rtype: dict ''' if xml_text is None: return",
":rtype dict: ''' try: return self.data['response']['execLog']['dialogueLog']['received']['tree'] except KeyError: return None @property def hasSession(self):",
"class for all WSMA transports. Provides the groundwork for specified transports. WSMA defines",
"super(Base, self).__init__() if not host: raise ValueError(\"host argument may not be empty\") self.timeout",
"would be \"show version\" :rtype: bool ''' return self.execCLI(\"show wsma id\") def _buildCorrelator(self,",
"updated. If format_spec is given (and valid), odmFormatResult will contain the dictionary with",
":param action_on_fail, can be \"stop\", \"continue\", \"rollback\" :rtype: bool ''' correlator = self._buildCorrelator(\"config\")",
"self.data['response']['execLog']['dialogueLog']['received']['tree'] except KeyError: return None @property def hasSession(self): '''checks whether we have a",
"was the call successful (bool) - output: holds CLI output (e.g. for show",
"populate instance vars: - success: was the call successful (bool) - output: holds",
"an error? if self.data.get('error') is not None: return False logging.info(\"JSON data: %s\", json.dumps(self.data,",
"= host self.username = username self.password = password self.port = port self.success =",
"to continue? it is assumed that 1) wsma is configured on the device",
"odmFormatResult will contain the dictionary with the result data. :param command: command string",
"time.strftime(\"%H%M%S\") result += \"-%s\" % str(self._count) result += ''.join(command.split()) self._count += 1 return",
"in transaction :rtype: bool ''' self.success= True self.output = '' self.data = None",
"JSON response. The On success, self.output and self.success will be updated. If format_spec",
"in exec mode on device :param format_spec: if there is a ODM spec",
"'unknown error / key error' return False # exec mode? if self.data['response']['@xmlns'] ==",
"established session!' self.success= False return self.success @abstractmethod def connect(self): '''Connects to the WSMA",
"+ command) if format_spec is not None: format_text = 'format=\"%s\"' % format_spec else:",
"= self.data['response']['execLog'][ 'dialogueLog']['received']['text'] except KeyError: t = None t = '' if t",
"command: used to make a unique string to return as a correlator :rtype:",
"send(template_data) returns XML from the device. :param template_data: XML string to be sent",
"<configApply details=\"all\" {{ACTION_ON_FAIL}}> <config-data> <cli-config-data-block>{{CONFIG_CMD}}</cli-config-data-block> </config-data> </configApply>\"\"\" self.template = Template(\"{0}{1}{2}\". format(self.begin_schema, self.body, self.end_schema))",
"''' logging.info(\"disconnect from {}\".format(self.url)) self._session = None @property def odmFormatResult(self): '''When using format",
"a unique string to return as a correlator :rtype: str ''' result =",
"data dict and populate instance vars: - success: was the call successful (bool)",
"a session if self._session == None: self.output = 'no established session!' self.success= False",
"ACTION_ON_FAIL=fail_str, Username=self.username, Password=self.password) logging.debug(\"Template {0:s}\".format(template_data)) return self.communicate(template_data) def configPersist(self): '''Makes configuration changes persistent.",
"error string') is returned. This still assumes that IF an XML string is",
"This still assumes that IF an XML string is passed into this function",
"from jinja2 import Template from xml.dom.minidom import parseString from xml.parsers.expat import ExpatError import",
"import Template from xml.dom.minidom import parseString from xml.parsers.expat import ExpatError import xmltodict import",
"t is None else t self.output = t return True if not self.success:",
"Essentially: return self._process(send(data)) Assuming that send(template_data) returns XML from the device. :param template_data:",
"None: return dict(error='XML body is empty') \"\"\" from lxml import etree etree.register_namespace(\"SOAP\", \"http://schemas.xmlsoap.org/soap/envelope/\")",
"command string to be run in exec mode on device :param format_spec: if",
"logging.debug(\"Template {}\".format(template_data)) return self.communicate(template_data) def config(self, command, action_on_fail=\"stop\"): '''Execute given commands in configuration",
"odmFormatResult(self): '''When using format specifications (e.g. structured data instead of unstructured CLI output)",
"successful (bool) - output: holds CLI output (e.g. for show commands), (string) if",
"self.body = \"\"\"<request xmlns=\"urn:cisco:wsma-config\" correlator=\"{{CORRELATOR}}\"> <configApply details=\"all\" {{ACTION_ON_FAIL}}> <config-data> <cli-config-data-block>{{CONFIG_CMD}}</cli-config-data-block> </config-data> </configApply>\"\"\" self.template",
"self.data['response']['execLog'][ 'dialogueLog']['received']['text'] except KeyError: t = None t = '' if t is",
"True if not self.success: e = self.data['response']['execLog'][ 'errorInfo']['errorMessage'] self.output = e return False",
"class _Schema(object): def __init__(self): \"\"\" :rtype : basestring \"\"\" self.begin_schema = \"\"\"<?xml version=\"1.0\"",
"return False # config mode? if self.data['response']['@xmlns'] == \"urn:cisco:wsma-config\": if self.success: t =",
"specifications (e.g. structured data instead of unstructured CLI output) then this property holds",
"XML tree. If no response is found, the SOAP 'Envelope' is returned. If",
"if not self.success: re = self.data['response']['resultEntry'] # multi line config input returns list",
"Envelope. :param xml_text: XML string to be converted :rtype: dict ''' if xml_text",
"self._ping() else None def __exit__(self, exc_type, exc_val, exc_tb): logging.debug('WITH/AS disconnect session') self.disconnect() def",
"sent in transaction :rtype: bool ''' self.success= True self.output = '' self.data =",
"success: was the call successful (bool) - output: holds CLI output (e.g. for",
"None # make sure we have a session if self._session == None: self.output",
"= \"\"\"<request xmlns=\"urn:cisco:wsma-config\" correlator=\"{{CORRELATOR}}\"> <configApply details=\"all\" {{ACTION_ON_FAIL}}> <config-data> <cli-config-data-block>{{CONFIG_CMD}}</cli-config-data-block> </config-data> </configApply>\"\"\" self.template =",
"def parseXML(xml_text): '''Parses given XML string and returns the 'response' child within the",
"dict(error='some error string') is returned. This still assumes that IF an XML string",
"(e.g. structured data instead of unstructured CLI output) then this property holds the",
"\"continue\", \"rollback\" :rtype: bool ''' correlator = self._buildCorrelator(\"config\") fail_str = 'action-on-fail=\"%s\"' % action_on_fail",
"exec) if not successful - xml_data: holds the XML data received from the",
"call successful (bool) - output: holds CLI output (e.g. for show commands), (string)",
"not be empty\") self.timeout = timeout self.host = host self.username = username self.password",
":param xml_text: XML string to be converted :rtype: dict ''' if xml_text is",
"self.success will be updated. If format_spec is given (and valid), odmFormatResult will contain",
"utf-8 -*- \"\"\" This defines the base class for the WSMA Python module.",
"return self._session is not None and self._ping() def execCLI(self, command, format_spec=None): '''Run given",
"= t return True if not self.success: e = self.data['response']['execLog'][ 'errorInfo']['errorMessage'] self.output =",
"= self._buildCorrelator(\"exec\" + command) if format_spec is not None: format_text = 'format=\"%s\"' %",
"holds the XML data received from the device :param data: dictionary with response",
"<PASSWORD> :param port: port to connect to :param timeout: timeout for transport '''",
"is list: results = re else: results = list() results.append(re) # look for",
"it is assumed that 1) wsma is configured on the device (how could",
"may not be empty\") self.timeout = timeout self.host = host self.username = username",
"password: <PASSWORD> :param port: port to connect to :param timeout: timeout for transport",
"connect(self): '''Connects to the WSMA host via a specific transport. The specific implementation",
"then dict(error='some error string') is returned. This still assumes that IF an XML",
"CLI output (e.g. for show commands), (string) if the call wass successful. it",
"</configApply>\"\"\" self.template = Template(\"{0}{1}{2}\". format(self.begin_schema, self.body, self.end_schema)) class _ConfigPersistTemplate(_Schema): def __init__(self): \"\"\" :type",
"correlator=\"{{CORRELATOR}}\"> <execCLI maxWait=\"PT{{TIMEOUT}}S\" xsd=\"false\" {{FORMAT}}> <cmd>{{EXEC_CMD}}</cmd> </execCLI> \"\"\" self.template = Template(\"{0}{1}{2}\". format(self.begin_schema, self.body,",
"not. :rtype bool: ''' return self._session is not None and self._ping() def execCLI(self,",
"session') self.connect() return self if self._ping() else None def __exit__(self, exc_type, exc_val, exc_tb):",
"the WSMA server :param username: username to use :param password: <PASSWORD> :param port:",
"\"\"\" _Schema.__init__(self) self.body = \"\"\"<request xmlns=\"urn:cisco:wsma-config\" correlator=\"{{CORRELATOR}}\"> <configPersist> </configPersist>\"\"\" self.template = Template(\"{0}{1}{2}\". format(self.begin_schema,",
"connect session') self.connect() return self if self._ping() else None def __exit__(self, exc_type, exc_val,",
"device. :param template_data: XML string to be sent in transaction :rtype: bool '''",
"__init__(self): \"\"\" :type self: object \"\"\" _Schema.__init__(self) self.body = \"\"\"<request xmlns=\"urn:cisco:wsma-exec\" correlator=\"{{CORRELATOR}}\"> <execCLI",
"assumed that 1) wsma is configured on the device (how could we connect",
"template_data = etmplate.template.render(EXEC_CMD=command, TIMEOUT=self.timeout, CORRELATOR=correlator, FORMAT=format_text, Username=self.username, Password=<PASSWORD>) logging.debug(\"Template {}\".format(template_data)) return self.communicate(template_data) def",
"return False logging.info(\"JSON data: %s\", json.dumps(self.data, indent=4)) # was it successful? try: self.success",
"\"\"\" </request> </SOAP:Body> </SOAP:Envelope>\"\"\" class _ExecTemplate(_Schema): def __init__(self): \"\"\" :type self: object \"\"\"",
"data: %s\", json.dumps(self.data, indent=4)) # was it successful? try: self.success = bool(int(self.data['response']['@success'])) except",
"xmlns=\"urn:cisco:wsma-config\" correlator=\"{{CORRELATOR}}\"> <configApply details=\"all\" {{ACTION_ON_FAIL}}> <config-data> <cli-config-data-block>{{CONFIG_CMD}}</cli-config-data-block> </config-data> </configApply>\"\"\" self.template = Template(\"{0}{1}{2}\". format(self.begin_schema,",
"TLS this is the WSMA :class:`Base <Base>` class :param host: hostname of the",
"xml_data): '''Process the given data dict and populate instance vars: - success: was",
"'''Needs to be overwritten in subclass, it should process provided template_data by sending",
"from xml.parsers.expat import ExpatError import xmltodict import json import time import logging class",
":param command: command string to be run in exec mode on device :param",
"self.success will be updated. :param command: config block to be applied to the",
"= _ConfigTemplate() template_data = etmplate.template.render(CONFIG_CMD=command, CORRELATOR=correlator, ACTION_ON_FAIL=fail_str, Username=self.username, Password=self.password) logging.debug(\"Template {0:s}\".format(template_data)) return self.communicate(template_data)",
"etmplate.template.render(CONFIG_CMD=command, CORRELATOR=correlator, ACTION_ON_FAIL=fail_str, Username=self.username, Password=self.password) logging.debug(\"Template {0:s}\".format(template_data)) return self.communicate(template_data) def configPersist(self): '''Makes configuration",
"and self.success will be updated. If format_spec is given (and valid), odmFormatResult will",
"None: self.output = 'no established session!' self.success= False return self.success @abstractmethod def connect(self):",
"platform independent for platforms supporting WSMA an alternative would be \"show version\" :rtype:",
"self.data['response']['resultEntry'] # multi line config input returns list if type(re) is list: results",
"-*- \"\"\" This defines the base class for the WSMA Python module. \"\"\"",
"except KeyError: t = None t = '' if t is None else",
"self.username, self.password)) @abstractmethod def disconnect(self): '''Disconnects the transport ''' logging.info(\"disconnect from {}\".format(self.url)) self._session",
"the WSMA Python module. \"\"\" from abc import ABCMeta, abstractmethod from jinja2 import",
"''.join(command.split()) self._count += 1 return result def _process(self, xml_data): '''Process the given data",
"return False @abstractmethod def communicate(self, template_data): '''Needs to be overwritten in subclass, it",
"WSMA host via a specific transport. The specific implementation has to be provided",
"from xml.dom.minidom import parseString from xml.parsers.expat import ExpatError import xmltodict import json import",
"e) logging.debug(\"XML tree:{}\".format(dom.childNodes[-1].toprettyxml())) response = dom.getElementsByTagName('response') if len(response) > 0: return xmltodict.parse(response[0].toxml()) return",
"element for line in results: if line.get('failure'): self.output = line.get('text') break return False",
"None @property def odmFormatResult(self): '''When using format specifications (e.g. structured data instead of",
"bool ''' correlator = self._buildCorrelator(\"config-persist\") etmplate = _ConfigPersistTemplate() template_data = etmplate.template.render(CORRELATOR=correlator, Username=self.username, Password=self.password)",
"unstructured CLI output) then this property holds the structured data as an object.",
"to be applied to the device :param action_on_fail, can be \"stop\", \"continue\", \"rollback\"",
"''' return self.execCLI(\"show wsma id\") def _buildCorrelator(self, command): '''Build a correlator for each",
"Template from xml.dom.minidom import parseString from xml.parsers.expat import ExpatError import xmltodict import json",
"error? if self.data.get('error') is not None: return False logging.info(\"JSON data: %s\", json.dumps(self.data, indent=4))",
"= etree.fromstring(xml_text.encode('utf-8')) print('#' * 40) print(etree.tostring(element, pretty_print=True).decode('utf-8')) print(json.dumps(xmltodict.parse(xml_text), indent=4)) \"\"\" logging.debug(\"XML string: {}\".format(xml_text))",
"Username=self.username, Password=self.password) logging.debug(\"Template {0:s}\".format(template_data)) return self.communicate(template_data) def configPersist(self): '''Makes configuration changes persistent. :rtype:",
"the result data. :param command: command string to be run in exec mode",
"self._buildCorrelator(\"config-persist\") etmplate = _ConfigPersistTemplate() template_data = etmplate.template.render(CORRELATOR=correlator, Username=self.username, Password=self.password) logging.debug(\"Template {0:s}\".format(template_data)) return self.communicate(template_data)",
"= None @property def odmFormatResult(self): '''When using format specifications (e.g. structured data instead",
"parseString(xml_text) except ExpatError as e: return dict(error='%s' % e) logging.debug(\"XML tree:{}\".format(dom.childNodes[-1].toprettyxml())) response =",
"xsd=\"false\" {{FORMAT}}> <cmd>{{EXEC_CMD}}</cmd> </execCLI> \"\"\" self.template = Template(\"{0}{1}{2}\". format(self.begin_schema, self.body, self.end_schema)) class _ConfigTemplate(_Schema):",
"\"\"\" from abc import ABCMeta, abstractmethod from jinja2 import Template from xml.dom.minidom import",
"data received from the device :param data: dictionary with response data :rtype: bool",
"to return as a correlator :rtype: str ''' result = time.strftime(\"%H%M%S\") result +=",
"self.data = None # session holds the transport session self._session = None #",
"existence of the session self._count = 0 def __enter__(self): logging.debug('WITH/AS connect session') self.connect()",
"action_on_fail, can be \"stop\", \"continue\", \"rollback\" :rtype: bool ''' correlator = self._buildCorrelator(\"config\") fail_str",
"command in exec mode, return JSON response. The On success, self.output and self.success",
"= \"\"\"<?xml version=\"1.0\" encoding=\"UTF-8\"?> <SOAP:Envelope xmlns:SOAP=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:SOAP-ENC=\"http://schemas.xmlsoap.org/soap/encoding/\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"> <SOAP:Header> <wsse:Security xmlns:wsse=\"http://schemas.xmlsoap.org/ws/2002/04/secext\" SOAP:mustUnderstand=\"false\">",
"(how could we connect otherwise?) 2) this is a priv-lvl-1 command 3) this",
"username self.password = password self.port = port self.success = False self.output = ''",
"mode on device :param format_spec: if there is a ODM spec file for",
"correlator = self._buildCorrelator(\"exec\" + command) if format_spec is not None: format_text = 'format=\"%s\"'",
"{}\".format(xml_text)) try: dom = parseString(xml_text) except ExpatError as e: return dict(error='%s' % e)",
"returns the 'response' child within the XML tree. If no response is found,",
"it should process provided template_data by sending it using the selected transport. Essentially:",
":rtype: bool ''' correlator = self._buildCorrelator(\"config-persist\") etmplate = _ConfigPersistTemplate() template_data = etmplate.template.render(CORRELATOR=correlator, Username=self.username,",
"success, self.output and self.success will be updated. :param command: config block to be",
"in exec mode, return JSON response. The On success, self.output and self.success will",
"have a session if self._session == None: self.output = 'no established session!' self.success=",
"wsma is configured on the device (how could we connect otherwise?) 2) this",
"template_data: XML string to be sent in transaction :rtype: bool ''' self.success= True",
"implementation has to be provided by the subclass. tls, ssh and http(s) are",
"returned. This still assumes that IF an XML string is passed into this",
"make sense to continue? it is assumed that 1) wsma is configured on",
"\"\"\" :type self: object \"\"\" _Schema.__init__(self) self.body = \"\"\"<request xmlns=\"urn:cisco:wsma-exec\" correlator=\"{{CORRELATOR}}\"> <execCLI maxWait=\"PT{{TIMEOUT}}S\"",
"priv-lvl-1 command 3) this command is platform independent for platforms supporting WSMA an",
"json.dumps(self.data, indent=4)) # was it successful? try: self.success = bool(int(self.data['response']['@success'])) except KeyError: self.output",
"self.output = t return True if not self.success: re = self.data['response']['resultEntry'] # multi",
"etmplate.template.render(EXEC_CMD=command, TIMEOUT=self.timeout, CORRELATOR=correlator, FORMAT=format_text, Username=self.username, Password=<PASSWORD>) logging.debug(\"Template {}\".format(template_data)) return self.communicate(template_data) def config(self, command,",
"= self._buildCorrelator(\"config-persist\") etmplate = _ConfigPersistTemplate() template_data = etmplate.template.render(CORRELATOR=correlator, Username=self.username, Password=self.password) logging.debug(\"Template {0:s}\".format(template_data)) return",
"not None: return False logging.info(\"JSON data: %s\", json.dumps(self.data, indent=4)) # was it successful?",
"the base class for the WSMA Python module. \"\"\" from abc import ABCMeta,",
"\"\"\"<?xml version=\"1.0\" encoding=\"UTF-8\"?> <SOAP:Envelope xmlns:SOAP=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:SOAP-ENC=\"http://schemas.xmlsoap.org/soap/encoding/\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"> <SOAP:Header> <wsse:Security xmlns:wsse=\"http://schemas.xmlsoap.org/ws/2002/04/secext\" SOAP:mustUnderstand=\"false\"> <wsse:UsernameToken>",
"connect otherwise?) 2) this is a priv-lvl-1 command 3) this command is platform",
"for platforms supporting WSMA an alternative would be \"show version\" :rtype: bool '''",
"self.execCLI(\"show wsma id\") def _buildCorrelator(self, command): '''Build a correlator for each command. Consists",
"</SOAP:Body> </SOAP:Envelope>\"\"\" class _ExecTemplate(_Schema): def __init__(self): \"\"\" :type self: object \"\"\" _Schema.__init__(self) self.body",
"input returns list if type(re) is list: results = re else: results =",
"{{ACTION_ON_FAIL}}> <config-data> <cli-config-data-block>{{CONFIG_CMD}}</cli-config-data-block> </config-data> </configApply>\"\"\" self.template = Template(\"{0}{1}{2}\". format(self.begin_schema, self.body, self.end_schema)) class _ConfigPersistTemplate(_Schema):",
"if self._session == None: self.output = 'no established session!' self.success= False return self.success",
"''' correlator = self._buildCorrelator(\"exec\" + command) if format_spec is not None: format_text =",
"to be overwritten in subclass, it should process provided template_data by sending it",
"format(self.begin_schema, self.body, self.end_schema)) class _ConfigPersistTemplate(_Schema): def __init__(self): \"\"\" :type self: object \"\"\" _Schema.__init__(self)",
"\"\"\"<request xmlns=\"urn:cisco:wsma-config\" correlator=\"{{CORRELATOR}}\"> <configApply details=\"all\" {{ACTION_ON_FAIL}}> <config-data> <cli-config-data-block>{{CONFIG_CMD}}</cli-config-data-block> </config-data> </configApply>\"\"\" self.template = Template(\"{0}{1}{2}\".",
"for all WSMA transports. Provides the groundwork for specified transports. WSMA defines the",
"port: port to connect to :param timeout: timeout for transport ''' __metaclass__ =",
"= username self.password = password self.port = port self.success = False self.output =",
"<execCLI maxWait=\"PT{{TIMEOUT}}S\" xsd=\"false\" {{FORMAT}}> <cmd>{{EXEC_CMD}}</cmd> </execCLI> \"\"\" self.template = Template(\"{0}{1}{2}\". format(self.begin_schema, self.body, self.end_schema))",
"= timeout self.host = host self.username = username self.password = password self.port =",
"class :param host: hostname of the WSMA server :param username: username to use",
"parseXML(xml_text): '''Parses given XML string and returns the 'response' child within the XML",
"exec mode, return JSON response. The On success, self.output and self.success will be",
"within the XML tree. If no response is found, the SOAP 'Envelope' is",
"to make a unique string to return as a correlator :rtype: str '''",
"this is a priv-lvl-1 command 3) this command is platform independent for platforms",
"yield an error? if self.data.get('error') is not None: return False logging.info(\"JSON data: %s\",",
"self.success: re = self.data['response']['resultEntry'] # multi line config input returns list if type(re)",
"__init__(self, host, username, password, port, timeout=60): super(Base, self).__init__() if not host: raise ValueError(\"host",
"= \"\"\"<request xmlns=\"urn:cisco:wsma-config\" correlator=\"{{CORRELATOR}}\"> <configPersist> </configPersist>\"\"\" self.template = Template(\"{0}{1}{2}\". format(self.begin_schema, self.body, self.end_schema)) class",
"# exec mode? if self.data['response']['@xmlns'] == \"urn:cisco:wsma-exec\": if self.success: try: t = self.data['response']['execLog'][",
"mode? if self.data['response']['@xmlns'] == \"urn:cisco:wsma-config\": if self.success: t = 'config mode / not",
"data: dictionary with response data :rtype: bool ''' self.data = self.parseXML(xml_data) # did",
"error' return False # exec mode? if self.data['response']['@xmlns'] == \"urn:cisco:wsma-exec\": if self.success: try:",
"multi line config input returns list if type(re) is list: results = re",
"self.template = Template(\"{0}{1}{2}\". format(self.begin_schema, self.body, self.end_schema)) class _ConfigPersistTemplate(_Schema): def __init__(self): \"\"\" :type self:",
"object \"\"\" _Schema.__init__(self) self.body = \"\"\"<request xmlns=\"urn:cisco:wsma-exec\" correlator=\"{{CORRELATOR}}\"> <execCLI maxWait=\"PT{{TIMEOUT}}S\" xsd=\"false\" {{FORMAT}}> <cmd>{{EXEC_CMD}}</cmd>",
"is the WSMA :class:`Base <Base>` class :param host: hostname of the WSMA server",
"we have a session if self._session == None: self.output = 'no established session!'",
"not None: format_text = 'format=\"%s\"' % format_spec else: format_text = \"\" etmplate =",
"WSMA transports. Provides the groundwork for specified transports. WSMA defines the following transports:",
"= self.data['response']['execLog'][ 'errorInfo']['errorMessage'] self.output = e return False # config mode? if self.data['response']['@xmlns']",
"selected transport. Essentially: return self._process(send(data)) Assuming that send(template_data) returns XML from the device.",
"= _ConfigPersistTemplate() template_data = etmplate.template.render(CORRELATOR=correlator, Username=self.username, Password=self.password) logging.debug(\"Template {0:s}\".format(template_data)) return self.communicate(template_data) @staticmethod def",
"the device (how could we connect otherwise?) 2) this is a priv-lvl-1 command",
"wsma id\") def _buildCorrelator(self, command): '''Build a correlator for each command. Consists of",
"the following transports: - SSH - HTTP / HTTPS - TLS this is",
"device :param format_spec: if there is a ODM spec file for the command",
"str ''' result = time.strftime(\"%H%M%S\") result += \"-%s\" % str(self._count) result += ''.join(command.split())",
"then it should have a valid SOAP Envelope. :param xml_text: XML string to",
"data as an object. :rtype dict: ''' try: return self.data['response']['execLog']['dialogueLog']['received']['tree'] except KeyError: return",
"Password=self.password) logging.debug(\"Template {0:s}\".format(template_data)) return self.communicate(template_data) def configPersist(self): '''Makes configuration changes persistent. :rtype: bool",
"@abstractmethod def disconnect(self): '''Disconnects the transport ''' logging.info(\"disconnect from {}\".format(self.url)) self._session = None",
"template_data by sending it using the selected transport. Essentially: return self._process(send(data)) Assuming that",
"try: return self.data['response']['execLog']['dialogueLog']['received']['tree'] except KeyError: return None @property def hasSession(self): '''checks whether we",
"is given (and valid), odmFormatResult will contain the dictionary with the result data.",
":rtype: dict ''' if xml_text is None: return dict(error='XML body is empty') \"\"\"",
"output: holds CLI output (e.g. for show commands), (string) if the call wass",
"(e.g. for show commands), (string) if the call wass successful. it holds the",
"type(re) is list: results = re else: results = list() results.append(re) # look",
"correlator over # the existence of the session self._count = 0 def __enter__(self):",
"output (e.g. for show commands), (string) if the call wass successful. it holds",
"re else: results = list() results.append(re) # look for first failed element for",
"is not None: format_text = 'format=\"%s\"' % format_spec else: format_text = \"\" etmplate",
"self.end_schema)) class Base(object): '''The base class for all WSMA transports. Provides the groundwork",
"self.communicate(template_data) @staticmethod def parseXML(xml_text): '''Parses given XML string and returns the 'response' child",
"if not successful - xml_data: holds the XML data received from the device",
"return JSON response. The On success, self.output and self.success will be updated. If",
"the structured data as an object. :rtype dict: ''' try: return self.data['response']['execLog']['dialogueLog']['received']['tree'] except",
"from {}\".format(self.url)) self._session = None @property def odmFormatResult(self): '''When using format specifications (e.g.",
"of - command to be sent -and- - timestamp :param command: used to",
"Consists of - command to be sent -and- - timestamp :param command: used",
"self.body, self.end_schema)) class Base(object): '''The base class for all WSMA transports. Provides the",
"None t = '' if t is None else t self.output = t",
"string is used or an error occurs during parsing then dict(error='some error string')",
"ABCMeta def __init__(self, host, username, password, port, timeout=60): super(Base, self).__init__() if not host:",
"persistent. :rtype: bool ''' correlator = self._buildCorrelator(\"config-persist\") etmplate = _ConfigPersistTemplate() template_data = etmplate.template.render(CORRELATOR=correlator,",
"the XML tree. If no response is found, the SOAP 'Envelope' is returned.",
"line.get('failure'): self.output = line.get('text') break return False # catch all return False @abstractmethod",
"'''Parses given XML string and returns the 'response' child within the XML tree.",
"format specifications (e.g. structured data instead of unstructured CLI output) then this property",
"port, timeout=60): super(Base, self).__init__() if not host: raise ValueError(\"host argument may not be",
"'config mode / not applicable' self.output = t return True if not self.success:",
"The On success, self.output and self.success will be updated. If format_spec is given",
"transports. WSMA defines the following transports: - SSH - HTTP / HTTPS -",
"module. \"\"\" from abc import ABCMeta, abstractmethod from jinja2 import Template from xml.dom.minidom",
"mode? if self.data['response']['@xmlns'] == \"urn:cisco:wsma-exec\": if self.success: try: t = self.data['response']['execLog'][ 'dialogueLog']['received']['text'] except",
"file for the command :rtype: bool ''' correlator = self._buildCorrelator(\"exec\" + command) if",
"in results: if line.get('failure'): self.output = line.get('text') break return False # catch all",
"\"\"\" self.template = Template(\"{0}{1}{2}\". format(self.begin_schema, self.body, self.end_schema)) class _ConfigTemplate(_Schema): def __init__(self): _Schema.__init__(self) self.body",
"ValueError(\"host argument may not be empty\") self.timeout = timeout self.host = host self.username",
"self.data['response']['@xmlns'] == \"urn:cisco:wsma-exec\": if self.success: try: t = self.data['response']['execLog'][ 'dialogueLog']['received']['text'] except KeyError: t",
"self.success: t = 'config mode / not applicable' self.output = t return True",
"is empty') \"\"\" from lxml import etree etree.register_namespace(\"SOAP\", \"http://schemas.xmlsoap.org/soap/envelope/\") element = etree.fromstring(xml_text.encode('utf-8')) print('#'",
"maxWait=\"PT{{TIMEOUT}}S\" xsd=\"false\" {{FORMAT}}> <cmd>{{EXEC_CMD}}</cmd> </execCLI> \"\"\" self.template = Template(\"{0}{1}{2}\". format(self.begin_schema, self.body, self.end_schema)) class",
"username, password, port, timeout=60): super(Base, self).__init__() if not host: raise ValueError(\"host argument may",
"indent=4)) \"\"\" logging.debug(\"XML string: {}\".format(xml_text)) try: dom = parseString(xml_text) except ExpatError as e:",
"self.data.get('error') is not None: return False logging.info(\"JSON data: %s\", json.dumps(self.data, indent=4)) # was",
"'''The base class for all WSMA transports. Provides the groundwork for specified transports.",
"port self.success = False self.output = '' self.data = None # session holds",
"else None def __exit__(self, exc_type, exc_val, exc_tb): logging.debug('WITH/AS disconnect session') self.disconnect() def _ping(self):",
"for specified transports. WSMA defines the following transports: - SSH - HTTP /",
"given commands in configuration mode. On success, self.output and self.success will be updated.",
"by sending it using the selected transport. Essentially: return self._process(send(data)) Assuming that send(template_data)",
"'''Process the given data dict and populate instance vars: - success: was the",
"host: raise ValueError(\"host argument may not be empty\") self.timeout = timeout self.host =",
"- output: holds CLI output (e.g. for show commands), (string) if the call",
"jinja2 import Template from xml.dom.minidom import parseString from xml.parsers.expat import ExpatError import xmltodict",
"= None # session holds the transport session self._session = None # count",
":param data: dictionary with response data :rtype: bool ''' self.data = self.parseXML(xml_data) #",
"xml.parsers.expat import ExpatError import xmltodict import json import time import logging class _Schema(object):",
"in IOS. ''' logging.info(\"connect to {} as {}/{}\".format(self.url, self.username, self.password)) @abstractmethod def disconnect(self):",
"as a correlator :rtype: str ''' result = time.strftime(\"%H%M%S\") result += \"-%s\" %",
"to connect to :param timeout: timeout for transport ''' __metaclass__ = ABCMeta def",
"False logging.info(\"JSON data: %s\", json.dumps(self.data, indent=4)) # was it successful? try: self.success =",
"self._process(send(data)) Assuming that send(template_data) returns XML from the device. :param template_data: XML string",
"IF an XML string is passed into this function then it should have",
"sense to continue? it is assumed that 1) wsma is configured on the",
"port to connect to :param timeout: timeout for transport ''' __metaclass__ = ABCMeta",
"using the selected transport. Essentially: return self._process(send(data)) Assuming that send(template_data) returns XML from",
"self._count = 0 def __enter__(self): logging.debug('WITH/AS connect session') self.connect() return self if self._ping()",
"this property holds the structured data as an object. :rtype dict: ''' try:",
"self.output = '' self.data = None # session holds the transport session self._session",
"True if not self.success: re = self.data['response']['resultEntry'] # multi line config input returns",
"_buildCorrelator(self, command): '''Build a correlator for each command. Consists of - command to",
"is None: return dict(error='XML body is empty') \"\"\" from lxml import etree etree.register_namespace(\"SOAP\",",
"logging.debug('WITH/AS disconnect session') self.disconnect() def _ping(self): '''Test the connection, does it make sense",
"import ABCMeta, abstractmethod from jinja2 import Template from xml.dom.minidom import parseString from xml.parsers.expat",
"'' if t is None else t self.output = t return True if",
"tls, ssh and http(s) are usable in IOS. ''' logging.info(\"connect to {} as",
"= None # count is used for the correlator over # the existence",
"\"stop\", \"continue\", \"rollback\" :rtype: bool ''' correlator = self._buildCorrelator(\"config\") fail_str = 'action-on-fail=\"%s\"' %",
":param command: config block to be applied to the device :param action_on_fail, can",
"results: if line.get('failure'): self.output = line.get('text') break return False # catch all return"
] |
[
"values are the actual field values in generated files. botdir (str): Path to",
"files and values are the actual field values in generated files. botdir (str):",
"'RAWDATA') botname_formal = '_'.join(botname.lower().split()) botdir = os.path.join(rawdata, botname_formal) if not os.path.isdir(botdir): os.mkdir(botdir) descriptions",
"open(temp_path, 'r') as template, open(result_path, 'w') as result: content = template.read() for temp_value,",
"templates_filenames: temp_name = temp_path.split(os.sep)[-1] result_path = os.path.join(botdir, temp_name) with open(temp_path, 'r') as template,",
"not os.path.isdir(botdir): os.mkdir(botdir) descriptions = list() for top in topics: save_topic_file(top, botdir) try:",
"as arq: arq.write(topic.__str__()) def save_control_knowledge_files(map_values, botdir): \"\"\"Save CS control and knowledges files. Args:",
"any of necessary directories do not exist it will be created. Args: botname",
"descriptions.append(top.beauty_name.lower()) except AttributeError: continue map_values = { 'BOTNAME': botname.capitalize(), 'FALAR_SOBRE': ', '.join(descriptions) }",
"used in post processing phase\"\"\" import os import glob import re def save_topic_file(topic,",
"temp_name) with open(temp_path, 'r') as template, open(result_path, 'w') as result: content = template.read()",
"result.write(content) def save_chatbot_files(botname, topics, cs_path='../ChatScript'): \"\"\"This method creates the chatbot files in the",
"the passed path. If any of necessary directories do not exist it will",
"actual_value in map_values.items(): content = content.replace(temp_value, actual_value) result.write(content) def save_chatbot_files(botname, topics, cs_path='../ChatScript'): \"\"\"This",
"functions used in post processing phase\"\"\" import os import glob import re def",
"= '{}.top'.format(topic.name) filename = os.path.join(botdir, top_name) with open(filename, 'w') as arq: arq.write(topic.__str__()) def",
"topic (str): Topic content. botdir (str): Path to dir where to create topic",
"arq: arq.write(topic.__str__()) def save_control_knowledge_files(map_values, botdir): \"\"\"Save CS control and knowledges files. Args: map_values",
"directory. \"\"\" rawdata = os.path.join(cs_path, 'RAWDATA') botname_formal = '_'.join(botname.lower().split()) botdir = os.path.join(rawdata, botname_formal)",
"= os.path.join(*botdir.split(os.sep)[-2:]) + os.sep botfiles = os.path.join(rawdata, 'files{}.txt'.format(botname_formal)) with open(botfiles, 'w') as arq:",
"os.path.join(botdir, temp_name) with open(temp_path, 'r') as template, open(result_path, 'w') as result: content =",
"the chatbot. topics (list): List of chatbot's topics content. cs_path (str): Path of",
"= os.path.join(cs_path, 'RAWDATA') botname_formal = '_'.join(botname.lower().split()) botdir = os.path.join(rawdata, botname_formal) if not os.path.isdir(botdir):",
"passed path. If any of necessary directories do not exist it will be",
"it will be created. Args: botname (str): Name of the chatbot. topics (list):",
"\"\"\"Module with functions used in post processing phase\"\"\" import os import glob import",
"be created. Args: botname (str): Name of the chatbot. topics (list): List of",
"path. If any of necessary directories do not exist it will be created.",
"top_name = '{}.top'.format(topic.name) filename = os.path.join(botdir, top_name) with open(filename, 'w') as arq: arq.write(topic.__str__())",
"in templates_filenames: temp_name = temp_path.split(os.sep)[-1] result_path = os.path.join(botdir, temp_name) with open(temp_path, 'r') as",
"topics, cs_path='../ChatScript'): \"\"\"This method creates the chatbot files in the passed path. If",
"do not exist it will be created. Args: botname (str): Name of the",
"botdir): \"\"\"This method saves a topic in a file and returns its name.",
"to dir where to create files. \"\"\" dirname = os.path.dirname(os.path.abspath(__file__)) templates_dir = os.path.join(dirname,",
"except AttributeError: continue map_values = { 'BOTNAME': botname.capitalize(), 'FALAR_SOBRE': ', '.join(descriptions) } save_control_knowledge_files(map_values,",
"name. Args: topic (str): Topic content. botdir (str): Path to dir where to",
"values in generated files. botdir (str): Path to dir where to create files.",
"save_control_knowledge_files(map_values, botdir) botfiles_content = os.path.join(*botdir.split(os.sep)[-2:]) + os.sep botfiles = os.path.join(rawdata, 'files{}.txt'.format(botname_formal)) with open(botfiles,",
"rawdata = os.path.join(cs_path, 'RAWDATA') botname_formal = '_'.join(botname.lower().split()) botdir = os.path.join(rawdata, botname_formal) if not",
"botname_formal = '_'.join(botname.lower().split()) botdir = os.path.join(rawdata, botname_formal) if not os.path.isdir(botdir): os.mkdir(botdir) descriptions =",
"files. \"\"\" dirname = os.path.dirname(os.path.abspath(__file__)) templates_dir = os.path.join(dirname, 'templates') templates_filenames = glob.glob('{}*'.format(templates_dir+os.sep)) for",
"control and knowledges files. Args: map_values (dict): Keys are values in template files",
"dir where to create topic file. \"\"\" top_name = '{}.top'.format(topic.name) filename = os.path.join(botdir,",
"descriptions = list() for top in topics: save_topic_file(top, botdir) try: if top.beauty_name: descriptions.append(top.beauty_name.lower())",
"-*- \"\"\"Module with functions used in post processing phase\"\"\" import os import glob",
"try: if top.beauty_name: descriptions.append(top.beauty_name.lower()) except AttributeError: continue map_values = { 'BOTNAME': botname.capitalize(), 'FALAR_SOBRE':",
"save_topic_file(topic, botdir): \"\"\"This method saves a topic in a file and returns its",
"= os.path.join(dirname, 'templates') templates_filenames = glob.glob('{}*'.format(templates_dir+os.sep)) for temp_path in templates_filenames: temp_name = temp_path.split(os.sep)[-1]",
"generated files. botdir (str): Path to dir where to create files. \"\"\" dirname",
"Name of the chatbot. topics (list): List of chatbot's topics content. cs_path (str):",
"returns its name. Args: topic (str): Topic content. botdir (str): Path to dir",
"CS control and knowledges files. Args: map_values (dict): Keys are values in template",
"content = content.replace(temp_value, actual_value) result.write(content) def save_chatbot_files(botname, topics, cs_path='../ChatScript'): \"\"\"This method creates the",
"Path to dir where to create topic file. \"\"\" top_name = '{}.top'.format(topic.name) filename",
"glob.glob('{}*'.format(templates_dir+os.sep)) for temp_path in templates_filenames: temp_name = temp_path.split(os.sep)[-1] result_path = os.path.join(botdir, temp_name) with",
"of necessary directories do not exist it will be created. Args: botname (str):",
"import re def save_topic_file(topic, botdir): \"\"\"This method saves a topic in a file",
"of ChatScript base directory. \"\"\" rawdata = os.path.join(cs_path, 'RAWDATA') botname_formal = '_'.join(botname.lower().split()) botdir",
"temp_path.split(os.sep)[-1] result_path = os.path.join(botdir, temp_name) with open(temp_path, 'r') as template, open(result_path, 'w') as",
"in generated files. botdir (str): Path to dir where to create files. \"\"\"",
"in a file and returns its name. Args: topic (str): Topic content. botdir",
"to create files. \"\"\" dirname = os.path.dirname(os.path.abspath(__file__)) templates_dir = os.path.join(dirname, 'templates') templates_filenames =",
"temp_path in templates_filenames: temp_name = temp_path.split(os.sep)[-1] result_path = os.path.join(botdir, temp_name) with open(temp_path, 'r')",
"topic file. \"\"\" top_name = '{}.top'.format(topic.name) filename = os.path.join(botdir, top_name) with open(filename, 'w')",
"botdir = os.path.join(rawdata, botname_formal) if not os.path.isdir(botdir): os.mkdir(botdir) descriptions = list() for top",
"chatbot files in the passed path. If any of necessary directories do not",
"creates the chatbot files in the passed path. If any of necessary directories",
"values in template files and values are the actual field values in generated",
"List of chatbot's topics content. cs_path (str): Path of ChatScript base directory. \"\"\"",
"{ 'BOTNAME': botname.capitalize(), 'FALAR_SOBRE': ', '.join(descriptions) } save_control_knowledge_files(map_values, botdir) botfiles_content = os.path.join(*botdir.split(os.sep)[-2:]) +",
"a file and returns its name. Args: topic (str): Topic content. botdir (str):",
"open(filename, 'w') as arq: arq.write(topic.__str__()) def save_control_knowledge_files(map_values, botdir): \"\"\"Save CS control and knowledges",
"-*- coding: utf-8 -*- \"\"\"Module with functions used in post processing phase\"\"\" import",
"chatbot. topics (list): List of chatbot's topics content. cs_path (str): Path of ChatScript",
"topic in a file and returns its name. Args: topic (str): Topic content.",
"(dict): Keys are values in template files and values are the actual field",
"method saves a topic in a file and returns its name. Args: topic",
"for top in topics: save_topic_file(top, botdir) try: if top.beauty_name: descriptions.append(top.beauty_name.lower()) except AttributeError: continue",
"'r') as template, open(result_path, 'w') as result: content = template.read() for temp_value, actual_value",
"save_chatbot_files(botname, topics, cs_path='../ChatScript'): \"\"\"This method creates the chatbot files in the passed path.",
"its name. Args: topic (str): Topic content. botdir (str): Path to dir where",
"= content.replace(temp_value, actual_value) result.write(content) def save_chatbot_files(botname, topics, cs_path='../ChatScript'): \"\"\"This method creates the chatbot",
"chatbot's topics content. cs_path (str): Path of ChatScript base directory. \"\"\" rawdata =",
"templates_dir = os.path.join(dirname, 'templates') templates_filenames = glob.glob('{}*'.format(templates_dir+os.sep)) for temp_path in templates_filenames: temp_name =",
"= template.read() for temp_value, actual_value in map_values.items(): content = content.replace(temp_value, actual_value) result.write(content) def",
"= os.path.join(rawdata, botname_formal) if not os.path.isdir(botdir): os.mkdir(botdir) descriptions = list() for top in",
"in topics: save_topic_file(top, botdir) try: if top.beauty_name: descriptions.append(top.beauty_name.lower()) except AttributeError: continue map_values =",
"def save_control_knowledge_files(map_values, botdir): \"\"\"Save CS control and knowledges files. Args: map_values (dict): Keys",
"as template, open(result_path, 'w') as result: content = template.read() for temp_value, actual_value in",
"(list): List of chatbot's topics content. cs_path (str): Path of ChatScript base directory.",
"for temp_value, actual_value in map_values.items(): content = content.replace(temp_value, actual_value) result.write(content) def save_chatbot_files(botname, topics,",
"os.path.join(rawdata, botname_formal) if not os.path.isdir(botdir): os.mkdir(botdir) descriptions = list() for top in topics:",
"ChatScript base directory. \"\"\" rawdata = os.path.join(cs_path, 'RAWDATA') botname_formal = '_'.join(botname.lower().split()) botdir =",
"\"\"\" dirname = os.path.dirname(os.path.abspath(__file__)) templates_dir = os.path.join(dirname, 'templates') templates_filenames = glob.glob('{}*'.format(templates_dir+os.sep)) for temp_path",
"re def save_topic_file(topic, botdir): \"\"\"This method saves a topic in a file and",
"import glob import re def save_topic_file(topic, botdir): \"\"\"This method saves a topic in",
"coding: utf-8 -*- \"\"\"Module with functions used in post processing phase\"\"\" import os",
"files. Args: map_values (dict): Keys are values in template files and values are",
"in the passed path. If any of necessary directories do not exist it",
"in template files and values are the actual field values in generated files.",
"and returns its name. Args: topic (str): Topic content. botdir (str): Path to",
"topics: save_topic_file(top, botdir) try: if top.beauty_name: descriptions.append(top.beauty_name.lower()) except AttributeError: continue map_values = {",
"} save_control_knowledge_files(map_values, botdir) botfiles_content = os.path.join(*botdir.split(os.sep)[-2:]) + os.sep botfiles = os.path.join(rawdata, 'files{}.txt'.format(botname_formal)) with",
"topics content. cs_path (str): Path of ChatScript base directory. \"\"\" rawdata = os.path.join(cs_path,",
"top_name) with open(filename, 'w') as arq: arq.write(topic.__str__()) def save_control_knowledge_files(map_values, botdir): \"\"\"Save CS control",
"are values in template files and values are the actual field values in",
"import os import glob import re def save_topic_file(topic, botdir): \"\"\"This method saves a",
"Args: botname (str): Name of the chatbot. topics (list): List of chatbot's topics",
"botdir) try: if top.beauty_name: descriptions.append(top.beauty_name.lower()) except AttributeError: continue map_values = { 'BOTNAME': botname.capitalize(),",
"Path of ChatScript base directory. \"\"\" rawdata = os.path.join(cs_path, 'RAWDATA') botname_formal = '_'.join(botname.lower().split())",
"result: content = template.read() for temp_value, actual_value in map_values.items(): content = content.replace(temp_value, actual_value)",
"def save_chatbot_files(botname, topics, cs_path='../ChatScript'): \"\"\"This method creates the chatbot files in the passed",
"for temp_path in templates_filenames: temp_name = temp_path.split(os.sep)[-1] result_path = os.path.join(botdir, temp_name) with open(temp_path,",
"if top.beauty_name: descriptions.append(top.beauty_name.lower()) except AttributeError: continue map_values = { 'BOTNAME': botname.capitalize(), 'FALAR_SOBRE': ',",
"filename = os.path.join(botdir, top_name) with open(filename, 'w') as arq: arq.write(topic.__str__()) def save_control_knowledge_files(map_values, botdir):",
"to dir where to create topic file. \"\"\" top_name = '{}.top'.format(topic.name) filename =",
"field values in generated files. botdir (str): Path to dir where to create",
"= temp_path.split(os.sep)[-1] result_path = os.path.join(botdir, temp_name) with open(temp_path, 'r') as template, open(result_path, 'w')",
"with open(temp_path, 'r') as template, open(result_path, 'w') as result: content = template.read() for",
"os.mkdir(botdir) descriptions = list() for top in topics: save_topic_file(top, botdir) try: if top.beauty_name:",
"knowledges files. Args: map_values (dict): Keys are values in template files and values",
"', '.join(descriptions) } save_control_knowledge_files(map_values, botdir) botfiles_content = os.path.join(*botdir.split(os.sep)[-2:]) + os.sep botfiles = os.path.join(rawdata,",
"'templates') templates_filenames = glob.glob('{}*'.format(templates_dir+os.sep)) for temp_path in templates_filenames: temp_name = temp_path.split(os.sep)[-1] result_path =",
"(str): Path of ChatScript base directory. \"\"\" rawdata = os.path.join(cs_path, 'RAWDATA') botname_formal =",
"create files. \"\"\" dirname = os.path.dirname(os.path.abspath(__file__)) templates_dir = os.path.join(dirname, 'templates') templates_filenames = glob.glob('{}*'.format(templates_dir+os.sep))",
"os.path.join(*botdir.split(os.sep)[-2:]) + os.sep botfiles = os.path.join(rawdata, 'files{}.txt'.format(botname_formal)) with open(botfiles, 'w') as arq: arq.write(botfiles_content)",
"cs_path (str): Path of ChatScript base directory. \"\"\" rawdata = os.path.join(cs_path, 'RAWDATA') botname_formal",
"AttributeError: continue map_values = { 'BOTNAME': botname.capitalize(), 'FALAR_SOBRE': ', '.join(descriptions) } save_control_knowledge_files(map_values, botdir)",
"continue map_values = { 'BOTNAME': botname.capitalize(), 'FALAR_SOBRE': ', '.join(descriptions) } save_control_knowledge_files(map_values, botdir) botfiles_content",
"\"\"\" rawdata = os.path.join(cs_path, 'RAWDATA') botname_formal = '_'.join(botname.lower().split()) botdir = os.path.join(rawdata, botname_formal) if",
"botdir (str): Path to dir where to create topic file. \"\"\" top_name =",
"'FALAR_SOBRE': ', '.join(descriptions) } save_control_knowledge_files(map_values, botdir) botfiles_content = os.path.join(*botdir.split(os.sep)[-2:]) + os.sep botfiles =",
"'BOTNAME': botname.capitalize(), 'FALAR_SOBRE': ', '.join(descriptions) } save_control_knowledge_files(map_values, botdir) botfiles_content = os.path.join(*botdir.split(os.sep)[-2:]) + os.sep",
"and knowledges files. Args: map_values (dict): Keys are values in template files and",
"method creates the chatbot files in the passed path. If any of necessary",
"list() for top in topics: save_topic_file(top, botdir) try: if top.beauty_name: descriptions.append(top.beauty_name.lower()) except AttributeError:",
"(str): Name of the chatbot. topics (list): List of chatbot's topics content. cs_path",
"are the actual field values in generated files. botdir (str): Path to dir",
"os.path.dirname(os.path.abspath(__file__)) templates_dir = os.path.join(dirname, 'templates') templates_filenames = glob.glob('{}*'.format(templates_dir+os.sep)) for temp_path in templates_filenames: temp_name",
"arq.write(topic.__str__()) def save_control_knowledge_files(map_values, botdir): \"\"\"Save CS control and knowledges files. Args: map_values (dict):",
"actual field values in generated files. botdir (str): Path to dir where to",
"If any of necessary directories do not exist it will be created. Args:",
"topics (list): List of chatbot's topics content. cs_path (str): Path of ChatScript base",
"the chatbot files in the passed path. If any of necessary directories do",
"glob import re def save_topic_file(topic, botdir): \"\"\"This method saves a topic in a",
"(str): Path to dir where to create files. \"\"\" dirname = os.path.dirname(os.path.abspath(__file__)) templates_dir",
"cs_path='../ChatScript'): \"\"\"This method creates the chatbot files in the passed path. If any",
"= '_'.join(botname.lower().split()) botdir = os.path.join(rawdata, botname_formal) if not os.path.isdir(botdir): os.mkdir(botdir) descriptions = list()",
"content. botdir (str): Path to dir where to create topic file. \"\"\" top_name",
"def save_topic_file(topic, botdir): \"\"\"This method saves a topic in a file and returns",
"content = template.read() for temp_value, actual_value in map_values.items(): content = content.replace(temp_value, actual_value) result.write(content)",
"exist it will be created. Args: botname (str): Name of the chatbot. topics",
"with open(filename, 'w') as arq: arq.write(topic.__str__()) def save_control_knowledge_files(map_values, botdir): \"\"\"Save CS control and",
"actual_value) result.write(content) def save_chatbot_files(botname, topics, cs_path='../ChatScript'): \"\"\"This method creates the chatbot files in",
"create topic file. \"\"\" top_name = '{}.top'.format(topic.name) filename = os.path.join(botdir, top_name) with open(filename,",
"'w') as arq: arq.write(topic.__str__()) def save_control_knowledge_files(map_values, botdir): \"\"\"Save CS control and knowledges files.",
"# -*- coding: utf-8 -*- \"\"\"Module with functions used in post processing phase\"\"\"",
"files in the passed path. If any of necessary directories do not exist",
"'.join(descriptions) } save_control_knowledge_files(map_values, botdir) botfiles_content = os.path.join(*botdir.split(os.sep)[-2:]) + os.sep botfiles = os.path.join(rawdata, 'files{}.txt'.format(botname_formal))",
"save_control_knowledge_files(map_values, botdir): \"\"\"Save CS control and knowledges files. Args: map_values (dict): Keys are",
"os.path.join(dirname, 'templates') templates_filenames = glob.glob('{}*'.format(templates_dir+os.sep)) for temp_path in templates_filenames: temp_name = temp_path.split(os.sep)[-1] result_path",
"of the chatbot. topics (list): List of chatbot's topics content. cs_path (str): Path",
"botdir): \"\"\"Save CS control and knowledges files. Args: map_values (dict): Keys are values",
"directories do not exist it will be created. Args: botname (str): Name of",
"created. Args: botname (str): Name of the chatbot. topics (list): List of chatbot's",
"= list() for top in topics: save_topic_file(top, botdir) try: if top.beauty_name: descriptions.append(top.beauty_name.lower()) except",
"utf-8 -*- \"\"\"Module with functions used in post processing phase\"\"\" import os import",
"botdir) botfiles_content = os.path.join(*botdir.split(os.sep)[-2:]) + os.sep botfiles = os.path.join(rawdata, 'files{}.txt'.format(botname_formal)) with open(botfiles, 'w')",
"'{}.top'.format(topic.name) filename = os.path.join(botdir, top_name) with open(filename, 'w') as arq: arq.write(topic.__str__()) def save_control_knowledge_files(map_values,",
"save_topic_file(top, botdir) try: if top.beauty_name: descriptions.append(top.beauty_name.lower()) except AttributeError: continue map_values = { 'BOTNAME':",
"where to create topic file. \"\"\" top_name = '{}.top'.format(topic.name) filename = os.path.join(botdir, top_name)",
"map_values = { 'BOTNAME': botname.capitalize(), 'FALAR_SOBRE': ', '.join(descriptions) } save_control_knowledge_files(map_values, botdir) botfiles_content =",
"necessary directories do not exist it will be created. Args: botname (str): Name",
"where to create files. \"\"\" dirname = os.path.dirname(os.path.abspath(__file__)) templates_dir = os.path.join(dirname, 'templates') templates_filenames",
"the actual field values in generated files. botdir (str): Path to dir where",
"dir where to create files. \"\"\" dirname = os.path.dirname(os.path.abspath(__file__)) templates_dir = os.path.join(dirname, 'templates')",
"map_values.items(): content = content.replace(temp_value, actual_value) result.write(content) def save_chatbot_files(botname, topics, cs_path='../ChatScript'): \"\"\"This method creates",
"temp_name = temp_path.split(os.sep)[-1] result_path = os.path.join(botdir, temp_name) with open(temp_path, 'r') as template, open(result_path,",
"\"\"\" top_name = '{}.top'.format(topic.name) filename = os.path.join(botdir, top_name) with open(filename, 'w') as arq:",
"Keys are values in template files and values are the actual field values",
"= os.path.join(botdir, temp_name) with open(temp_path, 'r') as template, open(result_path, 'w') as result: content",
"will be created. Args: botname (str): Name of the chatbot. topics (list): List",
"botname_formal) if not os.path.isdir(botdir): os.mkdir(botdir) descriptions = list() for top in topics: save_topic_file(top,",
"open(result_path, 'w') as result: content = template.read() for temp_value, actual_value in map_values.items(): content",
"<gh_stars>1-10 # -*- coding: utf-8 -*- \"\"\"Module with functions used in post processing",
"\"\"\"This method creates the chatbot files in the passed path. If any of",
"= { 'BOTNAME': botname.capitalize(), 'FALAR_SOBRE': ', '.join(descriptions) } save_control_knowledge_files(map_values, botdir) botfiles_content = os.path.join(*botdir.split(os.sep)[-2:])",
"to create topic file. \"\"\" top_name = '{}.top'.format(topic.name) filename = os.path.join(botdir, top_name) with",
"result_path = os.path.join(botdir, temp_name) with open(temp_path, 'r') as template, open(result_path, 'w') as result:",
"a topic in a file and returns its name. Args: topic (str): Topic",
"temp_value, actual_value in map_values.items(): content = content.replace(temp_value, actual_value) result.write(content) def save_chatbot_files(botname, topics, cs_path='../ChatScript'):",
"saves a topic in a file and returns its name. Args: topic (str):",
"content.replace(temp_value, actual_value) result.write(content) def save_chatbot_files(botname, topics, cs_path='../ChatScript'): \"\"\"This method creates the chatbot files",
"botname (str): Name of the chatbot. topics (list): List of chatbot's topics content.",
"in map_values.items(): content = content.replace(temp_value, actual_value) result.write(content) def save_chatbot_files(botname, topics, cs_path='../ChatScript'): \"\"\"This method",
"processing phase\"\"\" import os import glob import re def save_topic_file(topic, botdir): \"\"\"This method",
"Args: map_values (dict): Keys are values in template files and values are the",
"and values are the actual field values in generated files. botdir (str): Path",
"base directory. \"\"\" rawdata = os.path.join(cs_path, 'RAWDATA') botname_formal = '_'.join(botname.lower().split()) botdir = os.path.join(rawdata,",
"file. \"\"\" top_name = '{}.top'.format(topic.name) filename = os.path.join(botdir, top_name) with open(filename, 'w') as",
"if not os.path.isdir(botdir): os.mkdir(botdir) descriptions = list() for top in topics: save_topic_file(top, botdir)",
"top.beauty_name: descriptions.append(top.beauty_name.lower()) except AttributeError: continue map_values = { 'BOTNAME': botname.capitalize(), 'FALAR_SOBRE': ', '.join(descriptions)",
"phase\"\"\" import os import glob import re def save_topic_file(topic, botdir): \"\"\"This method saves",
"Args: topic (str): Topic content. botdir (str): Path to dir where to create",
"file and returns its name. Args: topic (str): Topic content. botdir (str): Path",
"map_values (dict): Keys are values in template files and values are the actual",
"files. botdir (str): Path to dir where to create files. \"\"\" dirname =",
"with functions used in post processing phase\"\"\" import os import glob import re",
"(str): Path to dir where to create topic file. \"\"\" top_name = '{}.top'.format(topic.name)",
"= os.path.join(botdir, top_name) with open(filename, 'w') as arq: arq.write(topic.__str__()) def save_control_knowledge_files(map_values, botdir): \"\"\"Save",
"dirname = os.path.dirname(os.path.abspath(__file__)) templates_dir = os.path.join(dirname, 'templates') templates_filenames = glob.glob('{}*'.format(templates_dir+os.sep)) for temp_path in",
"'w') as result: content = template.read() for temp_value, actual_value in map_values.items(): content =",
"botfiles_content = os.path.join(*botdir.split(os.sep)[-2:]) + os.sep botfiles = os.path.join(rawdata, 'files{}.txt'.format(botname_formal)) with open(botfiles, 'w') as",
"os import glob import re def save_topic_file(topic, botdir): \"\"\"This method saves a topic",
"template files and values are the actual field values in generated files. botdir",
"botname.capitalize(), 'FALAR_SOBRE': ', '.join(descriptions) } save_control_knowledge_files(map_values, botdir) botfiles_content = os.path.join(*botdir.split(os.sep)[-2:]) + os.sep botfiles",
"as result: content = template.read() for temp_value, actual_value in map_values.items(): content = content.replace(temp_value,",
"'_'.join(botname.lower().split()) botdir = os.path.join(rawdata, botname_formal) if not os.path.isdir(botdir): os.mkdir(botdir) descriptions = list() for",
"os.path.join(cs_path, 'RAWDATA') botname_formal = '_'.join(botname.lower().split()) botdir = os.path.join(rawdata, botname_formal) if not os.path.isdir(botdir): os.mkdir(botdir)",
"of chatbot's topics content. cs_path (str): Path of ChatScript base directory. \"\"\" rawdata",
"\"\"\"This method saves a topic in a file and returns its name. Args:",
"os.path.isdir(botdir): os.mkdir(botdir) descriptions = list() for top in topics: save_topic_file(top, botdir) try: if",
"Topic content. botdir (str): Path to dir where to create topic file. \"\"\"",
"Path to dir where to create files. \"\"\" dirname = os.path.dirname(os.path.abspath(__file__)) templates_dir =",
"not exist it will be created. Args: botname (str): Name of the chatbot.",
"top in topics: save_topic_file(top, botdir) try: if top.beauty_name: descriptions.append(top.beauty_name.lower()) except AttributeError: continue map_values",
"template, open(result_path, 'w') as result: content = template.read() for temp_value, actual_value in map_values.items():",
"in post processing phase\"\"\" import os import glob import re def save_topic_file(topic, botdir):",
"content. cs_path (str): Path of ChatScript base directory. \"\"\" rawdata = os.path.join(cs_path, 'RAWDATA')",
"(str): Topic content. botdir (str): Path to dir where to create topic file.",
"\"\"\"Save CS control and knowledges files. Args: map_values (dict): Keys are values in",
"templates_filenames = glob.glob('{}*'.format(templates_dir+os.sep)) for temp_path in templates_filenames: temp_name = temp_path.split(os.sep)[-1] result_path = os.path.join(botdir,",
"template.read() for temp_value, actual_value in map_values.items(): content = content.replace(temp_value, actual_value) result.write(content) def save_chatbot_files(botname,",
"= os.path.dirname(os.path.abspath(__file__)) templates_dir = os.path.join(dirname, 'templates') templates_filenames = glob.glob('{}*'.format(templates_dir+os.sep)) for temp_path in templates_filenames:",
"= glob.glob('{}*'.format(templates_dir+os.sep)) for temp_path in templates_filenames: temp_name = temp_path.split(os.sep)[-1] result_path = os.path.join(botdir, temp_name)",
"os.path.join(botdir, top_name) with open(filename, 'w') as arq: arq.write(topic.__str__()) def save_control_knowledge_files(map_values, botdir): \"\"\"Save CS",
"post processing phase\"\"\" import os import glob import re def save_topic_file(topic, botdir): \"\"\"This",
"botdir (str): Path to dir where to create files. \"\"\" dirname = os.path.dirname(os.path.abspath(__file__))"
] |
[
"context.write_int(value._secondary_structure.value) def deserialize(self, version, context): residue = _Residue._create() residue._index = context.read_long() self.array.set_type(self.atom) residue._set_atoms(context.read_using_serializer(self.array))",
"residue._ribbon_mode = _Residue.RibbonMode.safe_cast(context.read_int()) residue._ribbon_color = context.read_using_serializer(self.color) if (version > 0): residue._labeled = context.read_bool()",
"0): residue._labeled = context.read_bool() residue._label_text = context.read_using_serializer(self.string) residue._type = context.read_using_serializer(self.string) residue._serial = context.read_int()",
"context.write_using_serializer(self.array, []) else: context.write_using_serializer(self.array, value._atoms) self.array.set_type(self.bond) if (self.shallow): context.write_using_serializer(self.array, []) else: context.write_using_serializer(self.array, value._bonds)",
"> 0): context.write_bool(value._labeled) context.write_using_serializer(self.string, value._label_text) context.write_using_serializer(self.string, value._type) context.write_int(value._serial) context.write_using_serializer(self.string, value._name) context.write_int(value._secondary_structure.value) def deserialize(self,",
"False): self.shallow = shallow self.array = _ArraySerializer() self.atom = _AtomSerializerID() self.bond = _BondSerializer()",
"from . import _BondSerializer from .. import _Residue from nanome.util import Logs from",
"(version > 0): context.write_bool(value._labeled) context.write_using_serializer(self.string, value._label_text) context.write_using_serializer(self.string, value._type) context.write_int(value._serial) context.write_using_serializer(self.string, value._name) context.write_int(value._secondary_structure.value) def",
"context.write_int(value._serial) context.write_using_serializer(self.string, value._name) context.write_int(value._secondary_structure.value) def deserialize(self, version, context): residue = _Residue._create() residue._index =",
"context): residue = _Residue._create() residue._index = context.read_long() self.array.set_type(self.atom) residue._set_atoms(context.read_using_serializer(self.array)) self.array.set_type(self.bond) residue._set_bonds(context.read_using_serializer(self.array)) residue._ribboned =",
"= context.read_using_serializer(self.color) if (version > 0): residue._labeled = context.read_bool() residue._label_text = context.read_using_serializer(self.string) residue._type",
"[]) else: context.write_using_serializer(self.array, value._bonds) context.write_bool(value._ribboned) context.write_float(value._ribbon_size) context.write_int(value._ribbon_mode) context.write_using_serializer(self.color, value._ribbon_color) if (version > 0):",
"context.write_float(value._ribbon_size) context.write_int(value._ribbon_mode) context.write_using_serializer(self.color, value._ribbon_color) if (version > 0): context.write_bool(value._labeled) context.write_using_serializer(self.string, value._label_text) context.write_using_serializer(self.string, value._type)",
"version, context): residue = _Residue._create() residue._index = context.read_long() self.array.set_type(self.atom) residue._set_atoms(context.read_using_serializer(self.array)) self.array.set_type(self.bond) residue._set_bonds(context.read_using_serializer(self.array)) residue._ribboned",
"_StringSerializer, _ColorSerializer from . import _AtomSerializerID from . import _BondSerializer from .. import",
"_ResidueSerializer(_TypeSerializer): def __init__(self, shallow = False): self.shallow = shallow self.array = _ArraySerializer() self.atom",
"residue._set_bonds(context.read_using_serializer(self.array)) residue._ribboned = context.read_bool() residue._ribbon_size = context.read_float() residue._ribbon_mode = _Residue.RibbonMode.safe_cast(context.read_int()) residue._ribbon_color = context.read_using_serializer(self.color)",
"import _ArraySerializer, _StringSerializer, _ColorSerializer from . import _AtomSerializerID from . import _BondSerializer from",
"def deserialize(self, version, context): residue = _Residue._create() residue._index = context.read_long() self.array.set_type(self.atom) residue._set_atoms(context.read_using_serializer(self.array)) self.array.set_type(self.bond)",
"nanome.util import Logs from nanome._internal._util._serializers import _TypeSerializer class _ResidueSerializer(_TypeSerializer): def __init__(self, shallow =",
"residue._type = context.read_using_serializer(self.string) residue._serial = context.read_int() residue._name = context.read_using_serializer(self.string) residue._secondary_structure = _Residue.SecondaryStructure.safe_cast(context.read_int()) return",
"deserialize(self, version, context): residue = _Residue._create() residue._index = context.read_long() self.array.set_type(self.atom) residue._set_atoms(context.read_using_serializer(self.array)) self.array.set_type(self.bond) residue._set_bonds(context.read_using_serializer(self.array))",
"_BondSerializer from .. import _Residue from nanome.util import Logs from nanome._internal._util._serializers import _TypeSerializer",
"from nanome._internal._util._serializers import _TypeSerializer class _ResidueSerializer(_TypeSerializer): def __init__(self, shallow = False): self.shallow =",
"= shallow self.array = _ArraySerializer() self.atom = _AtomSerializerID() self.bond = _BondSerializer() self.color =",
"context.write_bool(value._labeled) context.write_using_serializer(self.string, value._label_text) context.write_using_serializer(self.string, value._type) context.write_int(value._serial) context.write_using_serializer(self.string, value._name) context.write_int(value._secondary_structure.value) def deserialize(self, version, context):",
"= _AtomSerializerID() self.bond = _BondSerializer() self.color = _ColorSerializer() self.string = _StringSerializer() def version(self):",
"from nanome._internal._util._serializers import _ArraySerializer, _StringSerializer, _ColorSerializer from . import _AtomSerializerID from . import",
"import _Residue from nanome.util import Logs from nanome._internal._util._serializers import _TypeSerializer class _ResidueSerializer(_TypeSerializer): def",
"context.read_using_serializer(self.string) residue._type = context.read_using_serializer(self.string) residue._serial = context.read_int() residue._name = context.read_using_serializer(self.string) residue._secondary_structure = _Residue.SecondaryStructure.safe_cast(context.read_int())",
"_BondSerializer() self.color = _ColorSerializer() self.string = _StringSerializer() def version(self): #Version 0 corresponds to",
"context.write_bool(value._ribboned) context.write_float(value._ribbon_size) context.write_int(value._ribbon_mode) context.write_using_serializer(self.color, value._ribbon_color) if (version > 0): context.write_bool(value._labeled) context.write_using_serializer(self.string, value._label_text) context.write_using_serializer(self.string,",
"> 0): residue._labeled = context.read_bool() residue._label_text = context.read_using_serializer(self.string) residue._type = context.read_using_serializer(self.string) residue._serial =",
"if (version > 0): context.write_bool(value._labeled) context.write_using_serializer(self.string, value._label_text) context.write_using_serializer(self.string, value._type) context.write_int(value._serial) context.write_using_serializer(self.string, value._name) context.write_int(value._secondary_structure.value)",
"self.array.set_type(self.atom) if (self.shallow): context.write_using_serializer(self.array, []) else: context.write_using_serializer(self.array, value._atoms) self.array.set_type(self.bond) if (self.shallow): context.write_using_serializer(self.array, [])",
"context.write_using_serializer(self.string, value._label_text) context.write_using_serializer(self.string, value._type) context.write_int(value._serial) context.write_using_serializer(self.string, value._name) context.write_int(value._secondary_structure.value) def deserialize(self, version, context): residue",
"= context.read_bool() residue._ribbon_size = context.read_float() residue._ribbon_mode = _Residue.RibbonMode.safe_cast(context.read_int()) residue._ribbon_color = context.read_using_serializer(self.color) if (version",
"residue._index = context.read_long() self.array.set_type(self.atom) residue._set_atoms(context.read_using_serializer(self.array)) self.array.set_type(self.bond) residue._set_bonds(context.read_using_serializer(self.array)) residue._ribboned = context.read_bool() residue._ribbon_size = context.read_float()",
"context.write_using_serializer(self.array, []) else: context.write_using_serializer(self.array, value._bonds) context.write_bool(value._ribboned) context.write_float(value._ribbon_size) context.write_int(value._ribbon_mode) context.write_using_serializer(self.color, value._ribbon_color) if (version >",
". import _BondSerializer from .. import _Residue from nanome.util import Logs from nanome._internal._util._serializers",
"(version > 0): residue._labeled = context.read_bool() residue._label_text = context.read_using_serializer(self.string) residue._type = context.read_using_serializer(self.string) residue._serial",
"= _ArraySerializer() self.atom = _AtomSerializerID() self.bond = _BondSerializer() self.color = _ColorSerializer() self.string =",
"= context.read_long() self.array.set_type(self.atom) residue._set_atoms(context.read_using_serializer(self.array)) self.array.set_type(self.bond) residue._set_bonds(context.read_using_serializer(self.array)) residue._ribboned = context.read_bool() residue._ribbon_size = context.read_float() residue._ribbon_mode",
"context.read_long() self.array.set_type(self.atom) residue._set_atoms(context.read_using_serializer(self.array)) self.array.set_type(self.bond) residue._set_bonds(context.read_using_serializer(self.array)) residue._ribboned = context.read_bool() residue._ribbon_size = context.read_float() residue._ribbon_mode =",
"context.read_bool() residue._label_text = context.read_using_serializer(self.string) residue._type = context.read_using_serializer(self.string) residue._serial = context.read_int() residue._name = context.read_using_serializer(self.string)",
"import Logs from nanome._internal._util._serializers import _TypeSerializer class _ResidueSerializer(_TypeSerializer): def __init__(self, shallow = False):",
"if (self.shallow): context.write_using_serializer(self.array, []) else: context.write_using_serializer(self.array, value._bonds) context.write_bool(value._ribboned) context.write_float(value._ribbon_size) context.write_int(value._ribbon_mode) context.write_using_serializer(self.color, value._ribbon_color) if",
"value._name) context.write_int(value._secondary_structure.value) def deserialize(self, version, context): residue = _Residue._create() residue._index = context.read_long() self.array.set_type(self.atom)",
"= _Residue._create() residue._index = context.read_long() self.array.set_type(self.atom) residue._set_atoms(context.read_using_serializer(self.array)) self.array.set_type(self.bond) residue._set_bonds(context.read_using_serializer(self.array)) residue._ribboned = context.read_bool() residue._ribbon_size",
"def __init__(self, shallow = False): self.shallow = shallow self.array = _ArraySerializer() self.atom =",
"context): context.write_long(value._index) self.array.set_type(self.atom) if (self.shallow): context.write_using_serializer(self.array, []) else: context.write_using_serializer(self.array, value._atoms) self.array.set_type(self.bond) if (self.shallow):",
". import _AtomSerializerID from . import _BondSerializer from .. import _Residue from nanome.util",
"name(self): return \"Residue\" def serialize(self, version, value, context): context.write_long(value._index) self.array.set_type(self.atom) if (self.shallow): context.write_using_serializer(self.array,",
"context.write_using_serializer(self.string, value._type) context.write_int(value._serial) context.write_using_serializer(self.string, value._name) context.write_int(value._secondary_structure.value) def deserialize(self, version, context): residue = _Residue._create()",
"self.string = _StringSerializer() def version(self): #Version 0 corresponds to Nanome release 1.10 return",
"context.write_using_serializer(self.array, value._bonds) context.write_bool(value._ribboned) context.write_float(value._ribbon_size) context.write_int(value._ribbon_mode) context.write_using_serializer(self.color, value._ribbon_color) if (version > 0): context.write_bool(value._labeled) context.write_using_serializer(self.string,",
"context.write_using_serializer(self.color, value._ribbon_color) if (version > 0): context.write_bool(value._labeled) context.write_using_serializer(self.string, value._label_text) context.write_using_serializer(self.string, value._type) context.write_int(value._serial) context.write_using_serializer(self.string,",
"context.read_bool() residue._ribbon_size = context.read_float() residue._ribbon_mode = _Residue.RibbonMode.safe_cast(context.read_int()) residue._ribbon_color = context.read_using_serializer(self.color) if (version >",
"= _BondSerializer() self.color = _ColorSerializer() self.string = _StringSerializer() def version(self): #Version 0 corresponds",
"value._bonds) context.write_bool(value._ribboned) context.write_float(value._ribbon_size) context.write_int(value._ribbon_mode) context.write_using_serializer(self.color, value._ribbon_color) if (version > 0): context.write_bool(value._labeled) context.write_using_serializer(self.string, value._label_text)",
"Nanome release 1.10 return 1 def name(self): return \"Residue\" def serialize(self, version, value,",
"residue._labeled = context.read_bool() residue._label_text = context.read_using_serializer(self.string) residue._type = context.read_using_serializer(self.string) residue._serial = context.read_int() residue._name",
"#Version 0 corresponds to Nanome release 1.10 return 1 def name(self): return \"Residue\"",
"_TypeSerializer class _ResidueSerializer(_TypeSerializer): def __init__(self, shallow = False): self.shallow = shallow self.array =",
"context.write_long(value._index) self.array.set_type(self.atom) if (self.shallow): context.write_using_serializer(self.array, []) else: context.write_using_serializer(self.array, value._atoms) self.array.set_type(self.bond) if (self.shallow): context.write_using_serializer(self.array,",
"self.bond = _BondSerializer() self.color = _ColorSerializer() self.string = _StringSerializer() def version(self): #Version 0",
"__init__(self, shallow = False): self.shallow = shallow self.array = _ArraySerializer() self.atom = _AtomSerializerID()",
"self.array = _ArraySerializer() self.atom = _AtomSerializerID() self.bond = _BondSerializer() self.color = _ColorSerializer() self.string",
"value, context): context.write_long(value._index) self.array.set_type(self.atom) if (self.shallow): context.write_using_serializer(self.array, []) else: context.write_using_serializer(self.array, value._atoms) self.array.set_type(self.bond) if",
"return 1 def name(self): return \"Residue\" def serialize(self, version, value, context): context.write_long(value._index) self.array.set_type(self.atom)",
"(self.shallow): context.write_using_serializer(self.array, []) else: context.write_using_serializer(self.array, value._atoms) self.array.set_type(self.bond) if (self.shallow): context.write_using_serializer(self.array, []) else: context.write_using_serializer(self.array,",
".. import _Residue from nanome.util import Logs from nanome._internal._util._serializers import _TypeSerializer class _ResidueSerializer(_TypeSerializer):",
"nanome._internal._util._serializers import _TypeSerializer class _ResidueSerializer(_TypeSerializer): def __init__(self, shallow = False): self.shallow = shallow",
"_ArraySerializer() self.atom = _AtomSerializerID() self.bond = _BondSerializer() self.color = _ColorSerializer() self.string = _StringSerializer()",
"\"Residue\" def serialize(self, version, value, context): context.write_long(value._index) self.array.set_type(self.atom) if (self.shallow): context.write_using_serializer(self.array, []) else:",
"_ColorSerializer() self.string = _StringSerializer() def version(self): #Version 0 corresponds to Nanome release 1.10",
"self.array.set_type(self.bond) if (self.shallow): context.write_using_serializer(self.array, []) else: context.write_using_serializer(self.array, value._bonds) context.write_bool(value._ribboned) context.write_float(value._ribbon_size) context.write_int(value._ribbon_mode) context.write_using_serializer(self.color, value._ribbon_color)",
"residue._ribbon_color = context.read_using_serializer(self.color) if (version > 0): residue._labeled = context.read_bool() residue._label_text = context.read_using_serializer(self.string)",
"value._type) context.write_int(value._serial) context.write_using_serializer(self.string, value._name) context.write_int(value._secondary_structure.value) def deserialize(self, version, context): residue = _Residue._create() residue._index",
"_ColorSerializer from . import _AtomSerializerID from . import _BondSerializer from .. import _Residue",
"value._atoms) self.array.set_type(self.bond) if (self.shallow): context.write_using_serializer(self.array, []) else: context.write_using_serializer(self.array, value._bonds) context.write_bool(value._ribboned) context.write_float(value._ribbon_size) context.write_int(value._ribbon_mode) context.write_using_serializer(self.color,",
"1.10 return 1 def name(self): return \"Residue\" def serialize(self, version, value, context): context.write_long(value._index)",
"def name(self): return \"Residue\" def serialize(self, version, value, context): context.write_long(value._index) self.array.set_type(self.atom) if (self.shallow):",
"1 def name(self): return \"Residue\" def serialize(self, version, value, context): context.write_long(value._index) self.array.set_type(self.atom) if",
"context.read_using_serializer(self.color) if (version > 0): residue._labeled = context.read_bool() residue._label_text = context.read_using_serializer(self.string) residue._type =",
"version, value, context): context.write_long(value._index) self.array.set_type(self.atom) if (self.shallow): context.write_using_serializer(self.array, []) else: context.write_using_serializer(self.array, value._atoms) self.array.set_type(self.bond)",
"= context.read_bool() residue._label_text = context.read_using_serializer(self.string) residue._type = context.read_using_serializer(self.string) residue._serial = context.read_int() residue._name =",
"_AtomSerializerID from . import _BondSerializer from .. import _Residue from nanome.util import Logs",
"self.shallow = shallow self.array = _ArraySerializer() self.atom = _AtomSerializerID() self.bond = _BondSerializer() self.color",
"= context.read_using_serializer(self.string) residue._type = context.read_using_serializer(self.string) residue._serial = context.read_int() residue._name = context.read_using_serializer(self.string) residue._secondary_structure =",
"= _StringSerializer() def version(self): #Version 0 corresponds to Nanome release 1.10 return 1",
"import _AtomSerializerID from . import _BondSerializer from .. import _Residue from nanome.util import",
"from . import _AtomSerializerID from . import _BondSerializer from .. import _Residue from",
"if (self.shallow): context.write_using_serializer(self.array, []) else: context.write_using_serializer(self.array, value._atoms) self.array.set_type(self.bond) if (self.shallow): context.write_using_serializer(self.array, []) else:",
"value._label_text) context.write_using_serializer(self.string, value._type) context.write_int(value._serial) context.write_using_serializer(self.string, value._name) context.write_int(value._secondary_structure.value) def deserialize(self, version, context): residue =",
"0 corresponds to Nanome release 1.10 return 1 def name(self): return \"Residue\" def",
"else: context.write_using_serializer(self.array, value._bonds) context.write_bool(value._ribboned) context.write_float(value._ribbon_size) context.write_int(value._ribbon_mode) context.write_using_serializer(self.color, value._ribbon_color) if (version > 0): context.write_bool(value._labeled)",
"= _ColorSerializer() self.string = _StringSerializer() def version(self): #Version 0 corresponds to Nanome release",
"= _Residue.RibbonMode.safe_cast(context.read_int()) residue._ribbon_color = context.read_using_serializer(self.color) if (version > 0): residue._labeled = context.read_bool() residue._label_text",
"version(self): #Version 0 corresponds to Nanome release 1.10 return 1 def name(self): return",
"def serialize(self, version, value, context): context.write_long(value._index) self.array.set_type(self.atom) if (self.shallow): context.write_using_serializer(self.array, []) else: context.write_using_serializer(self.array,",
"residue._ribboned = context.read_bool() residue._ribbon_size = context.read_float() residue._ribbon_mode = _Residue.RibbonMode.safe_cast(context.read_int()) residue._ribbon_color = context.read_using_serializer(self.color) if",
"residue._ribbon_size = context.read_float() residue._ribbon_mode = _Residue.RibbonMode.safe_cast(context.read_int()) residue._ribbon_color = context.read_using_serializer(self.color) if (version > 0):",
"_ArraySerializer, _StringSerializer, _ColorSerializer from . import _AtomSerializerID from . import _BondSerializer from ..",
"residue._label_text = context.read_using_serializer(self.string) residue._type = context.read_using_serializer(self.string) residue._serial = context.read_int() residue._name = context.read_using_serializer(self.string) residue._secondary_structure",
"self.array.set_type(self.atom) residue._set_atoms(context.read_using_serializer(self.array)) self.array.set_type(self.bond) residue._set_bonds(context.read_using_serializer(self.array)) residue._ribboned = context.read_bool() residue._ribbon_size = context.read_float() residue._ribbon_mode = _Residue.RibbonMode.safe_cast(context.read_int())",
"to Nanome release 1.10 return 1 def name(self): return \"Residue\" def serialize(self, version,",
"context.write_int(value._ribbon_mode) context.write_using_serializer(self.color, value._ribbon_color) if (version > 0): context.write_bool(value._labeled) context.write_using_serializer(self.string, value._label_text) context.write_using_serializer(self.string, value._type) context.write_int(value._serial)",
"if (version > 0): residue._labeled = context.read_bool() residue._label_text = context.read_using_serializer(self.string) residue._type = context.read_using_serializer(self.string)",
"serialize(self, version, value, context): context.write_long(value._index) self.array.set_type(self.atom) if (self.shallow): context.write_using_serializer(self.array, []) else: context.write_using_serializer(self.array, value._atoms)",
"nanome._internal._util._serializers import _ArraySerializer, _StringSerializer, _ColorSerializer from . import _AtomSerializerID from . import _BondSerializer",
"shallow self.array = _ArraySerializer() self.atom = _AtomSerializerID() self.bond = _BondSerializer() self.color = _ColorSerializer()",
"[]) else: context.write_using_serializer(self.array, value._atoms) self.array.set_type(self.bond) if (self.shallow): context.write_using_serializer(self.array, []) else: context.write_using_serializer(self.array, value._bonds) context.write_bool(value._ribboned)",
"_Residue from nanome.util import Logs from nanome._internal._util._serializers import _TypeSerializer class _ResidueSerializer(_TypeSerializer): def __init__(self,",
"= context.read_using_serializer(self.string) residue._serial = context.read_int() residue._name = context.read_using_serializer(self.string) residue._secondary_structure = _Residue.SecondaryStructure.safe_cast(context.read_int()) return residue",
"import _BondSerializer from .. import _Residue from nanome.util import Logs from nanome._internal._util._serializers import",
"import _TypeSerializer class _ResidueSerializer(_TypeSerializer): def __init__(self, shallow = False): self.shallow = shallow self.array",
"_Residue._create() residue._index = context.read_long() self.array.set_type(self.atom) residue._set_atoms(context.read_using_serializer(self.array)) self.array.set_type(self.bond) residue._set_bonds(context.read_using_serializer(self.array)) residue._ribboned = context.read_bool() residue._ribbon_size =",
"= False): self.shallow = shallow self.array = _ArraySerializer() self.atom = _AtomSerializerID() self.bond =",
"def version(self): #Version 0 corresponds to Nanome release 1.10 return 1 def name(self):",
"value._ribbon_color) if (version > 0): context.write_bool(value._labeled) context.write_using_serializer(self.string, value._label_text) context.write_using_serializer(self.string, value._type) context.write_int(value._serial) context.write_using_serializer(self.string, value._name)",
"self.atom = _AtomSerializerID() self.bond = _BondSerializer() self.color = _ColorSerializer() self.string = _StringSerializer() def",
"class _ResidueSerializer(_TypeSerializer): def __init__(self, shallow = False): self.shallow = shallow self.array = _ArraySerializer()",
"from nanome.util import Logs from nanome._internal._util._serializers import _TypeSerializer class _ResidueSerializer(_TypeSerializer): def __init__(self, shallow",
"self.array.set_type(self.bond) residue._set_bonds(context.read_using_serializer(self.array)) residue._ribboned = context.read_bool() residue._ribbon_size = context.read_float() residue._ribbon_mode = _Residue.RibbonMode.safe_cast(context.read_int()) residue._ribbon_color =",
"0): context.write_bool(value._labeled) context.write_using_serializer(self.string, value._label_text) context.write_using_serializer(self.string, value._type) context.write_int(value._serial) context.write_using_serializer(self.string, value._name) context.write_int(value._secondary_structure.value) def deserialize(self, version,",
"corresponds to Nanome release 1.10 return 1 def name(self): return \"Residue\" def serialize(self,",
"(self.shallow): context.write_using_serializer(self.array, []) else: context.write_using_serializer(self.array, value._bonds) context.write_bool(value._ribboned) context.write_float(value._ribbon_size) context.write_int(value._ribbon_mode) context.write_using_serializer(self.color, value._ribbon_color) if (version",
"else: context.write_using_serializer(self.array, value._atoms) self.array.set_type(self.bond) if (self.shallow): context.write_using_serializer(self.array, []) else: context.write_using_serializer(self.array, value._bonds) context.write_bool(value._ribboned) context.write_float(value._ribbon_size)",
"_Residue.RibbonMode.safe_cast(context.read_int()) residue._ribbon_color = context.read_using_serializer(self.color) if (version > 0): residue._labeled = context.read_bool() residue._label_text =",
"return \"Residue\" def serialize(self, version, value, context): context.write_long(value._index) self.array.set_type(self.atom) if (self.shallow): context.write_using_serializer(self.array, [])",
"shallow = False): self.shallow = shallow self.array = _ArraySerializer() self.atom = _AtomSerializerID() self.bond",
"self.color = _ColorSerializer() self.string = _StringSerializer() def version(self): #Version 0 corresponds to Nanome",
"context.write_using_serializer(self.array, value._atoms) self.array.set_type(self.bond) if (self.shallow): context.write_using_serializer(self.array, []) else: context.write_using_serializer(self.array, value._bonds) context.write_bool(value._ribboned) context.write_float(value._ribbon_size) context.write_int(value._ribbon_mode)",
"release 1.10 return 1 def name(self): return \"Residue\" def serialize(self, version, value, context):",
"_StringSerializer() def version(self): #Version 0 corresponds to Nanome release 1.10 return 1 def",
"= context.read_float() residue._ribbon_mode = _Residue.RibbonMode.safe_cast(context.read_int()) residue._ribbon_color = context.read_using_serializer(self.color) if (version > 0): residue._labeled",
"context.write_using_serializer(self.string, value._name) context.write_int(value._secondary_structure.value) def deserialize(self, version, context): residue = _Residue._create() residue._index = context.read_long()",
"context.read_float() residue._ribbon_mode = _Residue.RibbonMode.safe_cast(context.read_int()) residue._ribbon_color = context.read_using_serializer(self.color) if (version > 0): residue._labeled =",
"Logs from nanome._internal._util._serializers import _TypeSerializer class _ResidueSerializer(_TypeSerializer): def __init__(self, shallow = False): self.shallow",
"_AtomSerializerID() self.bond = _BondSerializer() self.color = _ColorSerializer() self.string = _StringSerializer() def version(self): #Version",
"residue._set_atoms(context.read_using_serializer(self.array)) self.array.set_type(self.bond) residue._set_bonds(context.read_using_serializer(self.array)) residue._ribboned = context.read_bool() residue._ribbon_size = context.read_float() residue._ribbon_mode = _Residue.RibbonMode.safe_cast(context.read_int()) residue._ribbon_color",
"from .. import _Residue from nanome.util import Logs from nanome._internal._util._serializers import _TypeSerializer class",
"residue = _Residue._create() residue._index = context.read_long() self.array.set_type(self.atom) residue._set_atoms(context.read_using_serializer(self.array)) self.array.set_type(self.bond) residue._set_bonds(context.read_using_serializer(self.array)) residue._ribboned = context.read_bool()"
] |