ngram
listlengths
0
67.8k
[ "{file}, at {datetime.datetime.utcnow()}') os.system(f\"mprof run --include-children --nopython -o '{out_dir}/mprof_compile.dat' zkay compile '{file}' --verbosity", "if filename.endswith(('.sol', '.zkay')): file = os.path.join(p, filename) break if file is not None:", "exist_ok=True) print(f'compiling {file}, at {datetime.datetime.utcnow()}') os.system(f\"mprof run --include-children --nopython -o '{out_dir}/mprof_compile.dat' zkay compile", "(example_dir contains subdirectories with example sol/zkay and scenario files) # requires installed memory-profiler", "backends: for dirname in os.listdir(base_dir): p = os.path.join(base_dir, dirname) if os.path.isdir(p): file =", "#!/usr/bin/env python3 # usage ./benchmark.py [example_dir] # (example_dir contains subdirectories with example sol/zkay", "os.path.isdir(p): file = None for filename in os.listdir(p): if filename.endswith(('.sol', '.zkay')): file =", "zkay compile '{file}' --verbosity 0 --crypto-backend {backend} --opt-hash-threshold 0 -o '{out_dir}' --log --log-dir", "backend in backends: for dirname in os.listdir(base_dir): p = os.path.join(base_dir, dirname) if os.path.isdir(p):", "subdirectories with example sol/zkay and scenario files) # requires installed memory-profiler and zkay", "dirname) if os.path.isdir(p): file = None for filename in os.listdir(p): if filename.endswith(('.sol', '.zkay')):", "scenario_file = os.path.join(p, 'scenario.py') if os.path.exists(scenario_file): print(f'running {scenario_file}, at {datetime.datetime.utcnow()}') os.system(f\"mprof run --include-children", "datetime import sys import shutil clean=False file_dir = os.path.realpath(os.path.dirname(__file__)) base_dir = os.path.join(file_dir, 'examples')", "requires installed memory-profiler and zkay packages import os import datetime import sys import", "for filename in os.listdir(p): if filename.endswith(('.sol', '.zkay')): file = os.path.join(p, filename) break if", "--verbosity 0 --crypto-backend {backend} --opt-hash-threshold 0 -o '{out_dir}' --log --log-dir '{out_dir}'\") scenario_file =", "if file is not None: out_dir = os.path.join(p, f'out_{backend}') if clean and os.path.exists(out_dir):", "in os.listdir(p): if filename.endswith(('.sol', '.zkay')): file = os.path.join(p, filename) break if file is", "filename.endswith(('.sol', '.zkay')): file = os.path.join(p, filename) break if file is not None: out_dir", "os.path.join(p, 'scenario.py') if os.path.exists(scenario_file): print(f'running {scenario_file}, at {datetime.datetime.utcnow()}') os.system(f\"mprof run --include-children --nopython -o", "# requires installed memory-profiler and zkay packages import os import datetime import sys", "import sys import shutil clean=False file_dir = os.path.realpath(os.path.dirname(__file__)) base_dir = os.path.join(file_dir, 'examples') if", "scenario files) # requires installed memory-profiler and zkay packages import os import datetime", "zkay packages import os import datetime import sys import shutil clean=False file_dir =", "--log --log-dir '{out_dir}'\") scenario_file = os.path.join(p, 'scenario.py') if os.path.exists(scenario_file): print(f'running {scenario_file}, at {datetime.datetime.utcnow()}')", "'.zkay')): file = os.path.join(p, filename) break if file is not None: out_dir =", "= os.path.realpath(os.path.dirname(__file__)) base_dir = os.path.join(file_dir, 'examples') if len(sys.argv) < 2 else os.path.realpath(sys.argv[1]) backends", "'ecdh-chaskey', 'ecdh-aes'] #, 'rsa-pkcs1.5', 'rsa-oaep'] # rsa consumes >100 GB hdd space for", "'scenario.py') if os.path.exists(scenario_file): print(f'running {scenario_file}, at {datetime.datetime.utcnow()}') os.system(f\"mprof run --include-children --nopython -o '{out_dir}/mprof_run.dat'", "'rsa-oaep'] # rsa consumes >100 GB hdd space for backend in backends: for", "= os.path.join(p, filename) break if file is not None: out_dir = os.path.join(p, f'out_{backend}')", "if clean and os.path.exists(out_dir): shutil.rmtree(out_dir) os.makedirs(out_dir, exist_ok=True) print(f'compiling {file}, at {datetime.datetime.utcnow()}') os.system(f\"mprof run", "import datetime import sys import shutil clean=False file_dir = os.path.realpath(os.path.dirname(__file__)) base_dir = os.path.join(file_dir,", "break if file is not None: out_dir = os.path.join(p, f'out_{backend}') if clean and", "0 --crypto-backend {backend} --opt-hash-threshold 0 -o '{out_dir}' --log --log-dir '{out_dir}'\") scenario_file = os.path.join(p,", "f'out_{backend}') if clean and os.path.exists(out_dir): shutil.rmtree(out_dir) os.makedirs(out_dir, exist_ok=True) print(f'compiling {file}, at {datetime.datetime.utcnow()}') os.system(f\"mprof", "os.path.join(file_dir, 'examples') if len(sys.argv) < 2 else os.path.realpath(sys.argv[1]) backends = ['dummy', 'ecdh-chaskey', 'ecdh-aes']", "= os.path.join(file_dir, 'examples') if len(sys.argv) < 2 else os.path.realpath(sys.argv[1]) backends = ['dummy', 'ecdh-chaskey',", "in os.listdir(base_dir): p = os.path.join(base_dir, dirname) if os.path.isdir(p): file = None for filename", "2 else os.path.realpath(sys.argv[1]) backends = ['dummy', 'ecdh-chaskey', 'ecdh-aes'] #, 'rsa-pkcs1.5', 'rsa-oaep'] # rsa", "clean and os.path.exists(out_dir): shutil.rmtree(out_dir) os.makedirs(out_dir, exist_ok=True) print(f'compiling {file}, at {datetime.datetime.utcnow()}') os.system(f\"mprof run --include-children", "with example sol/zkay and scenario files) # requires installed memory-profiler and zkay packages", "space for backend in backends: for dirname in os.listdir(base_dir): p = os.path.join(base_dir, dirname)", "--crypto-backend {backend} --opt-hash-threshold 0 -o '{out_dir}' --log --log-dir '{out_dir}'\") scenario_file = os.path.join(p, 'scenario.py')", "print(f'compiling {file}, at {datetime.datetime.utcnow()}') os.system(f\"mprof run --include-children --nopython -o '{out_dir}/mprof_compile.dat' zkay compile '{file}'", "hdd space for backend in backends: for dirname in os.listdir(base_dir): p = os.path.join(base_dir,", "in backends: for dirname in os.listdir(base_dir): p = os.path.join(base_dir, dirname) if os.path.isdir(p): file", "memory-profiler and zkay packages import os import datetime import sys import shutil clean=False", "else os.path.realpath(sys.argv[1]) backends = ['dummy', 'ecdh-chaskey', 'ecdh-aes'] #, 'rsa-pkcs1.5', 'rsa-oaep'] # rsa consumes", "installed memory-profiler and zkay packages import os import datetime import sys import shutil", "= os.path.join(base_dir, dirname) if os.path.isdir(p): file = None for filename in os.listdir(p): if", "files) # requires installed memory-profiler and zkay packages import os import datetime import", "{datetime.datetime.utcnow()}') os.system(f\"mprof run --include-children --nopython -o '{out_dir}/mprof_compile.dat' zkay compile '{file}' --verbosity 0 --crypto-backend", "len(sys.argv) < 2 else os.path.realpath(sys.argv[1]) backends = ['dummy', 'ecdh-chaskey', 'ecdh-aes'] #, 'rsa-pkcs1.5', 'rsa-oaep']", "'ecdh-aes'] #, 'rsa-pkcs1.5', 'rsa-oaep'] # rsa consumes >100 GB hdd space for backend", "if os.path.isdir(p): file = None for filename in os.listdir(p): if filename.endswith(('.sol', '.zkay')): file", "= os.path.join(p, f'out_{backend}') if clean and os.path.exists(out_dir): shutil.rmtree(out_dir) os.makedirs(out_dir, exist_ok=True) print(f'compiling {file}, at", "'{out_dir}'\") scenario_file = os.path.join(p, 'scenario.py') if os.path.exists(scenario_file): print(f'running {scenario_file}, at {datetime.datetime.utcnow()}') os.system(f\"mprof run", "contains subdirectories with example sol/zkay and scenario files) # requires installed memory-profiler and", "--nopython -o '{out_dir}/mprof_compile.dat' zkay compile '{file}' --verbosity 0 --crypto-backend {backend} --opt-hash-threshold 0 -o", "os.path.exists(scenario_file): print(f'running {scenario_file}, at {datetime.datetime.utcnow()}') os.system(f\"mprof run --include-children --nopython -o '{out_dir}/mprof_run.dat' python '{scenario_file}'", "-o '{out_dir}' --log --log-dir '{out_dir}'\") scenario_file = os.path.join(p, 'scenario.py') if os.path.exists(scenario_file): print(f'running {scenario_file},", "filename) break if file is not None: out_dir = os.path.join(p, f'out_{backend}') if clean", "# (example_dir contains subdirectories with example sol/zkay and scenario files) # requires installed", "'examples') if len(sys.argv) < 2 else os.path.realpath(sys.argv[1]) backends = ['dummy', 'ecdh-chaskey', 'ecdh-aes'] #,", "os.path.join(p, f'out_{backend}') if clean and os.path.exists(out_dir): shutil.rmtree(out_dir) os.makedirs(out_dir, exist_ok=True) print(f'compiling {file}, at {datetime.datetime.utcnow()}')", "and scenario files) # requires installed memory-profiler and zkay packages import os import", "run --include-children --nopython -o '{out_dir}/mprof_compile.dat' zkay compile '{file}' --verbosity 0 --crypto-backend {backend} --opt-hash-threshold", "packages import os import datetime import sys import shutil clean=False file_dir = os.path.realpath(os.path.dirname(__file__))", "sys import shutil clean=False file_dir = os.path.realpath(os.path.dirname(__file__)) base_dir = os.path.join(file_dir, 'examples') if len(sys.argv)", "#, 'rsa-pkcs1.5', 'rsa-oaep'] # rsa consumes >100 GB hdd space for backend in", "./benchmark.py [example_dir] # (example_dir contains subdirectories with example sol/zkay and scenario files) #", "file = None for filename in os.listdir(p): if filename.endswith(('.sol', '.zkay')): file = os.path.join(p,", "['dummy', 'ecdh-chaskey', 'ecdh-aes'] #, 'rsa-pkcs1.5', 'rsa-oaep'] # rsa consumes >100 GB hdd space", "usage ./benchmark.py [example_dir] # (example_dir contains subdirectories with example sol/zkay and scenario files)", ">100 GB hdd space for backend in backends: for dirname in os.listdir(base_dir): p", "file = os.path.join(p, filename) break if file is not None: out_dir = os.path.join(p,", "GB hdd space for backend in backends: for dirname in os.listdir(base_dir): p =", "# usage ./benchmark.py [example_dir] # (example_dir contains subdirectories with example sol/zkay and scenario", "sol/zkay and scenario files) # requires installed memory-profiler and zkay packages import os", "consumes >100 GB hdd space for backend in backends: for dirname in os.listdir(base_dir):", "os.listdir(p): if filename.endswith(('.sol', '.zkay')): file = os.path.join(p, filename) break if file is not", "os.path.join(p, filename) break if file is not None: out_dir = os.path.join(p, f'out_{backend}') if", "shutil.rmtree(out_dir) os.makedirs(out_dir, exist_ok=True) print(f'compiling {file}, at {datetime.datetime.utcnow()}') os.system(f\"mprof run --include-children --nopython -o '{out_dir}/mprof_compile.dat'", "and os.path.exists(out_dir): shutil.rmtree(out_dir) os.makedirs(out_dir, exist_ok=True) print(f'compiling {file}, at {datetime.datetime.utcnow()}') os.system(f\"mprof run --include-children --nopython", "'{file}' --verbosity 0 --crypto-backend {backend} --opt-hash-threshold 0 -o '{out_dir}' --log --log-dir '{out_dir}'\") scenario_file", "print(f'running {scenario_file}, at {datetime.datetime.utcnow()}') os.system(f\"mprof run --include-children --nopython -o '{out_dir}/mprof_run.dat' python '{scenario_file}' '{out_dir}'\")", "and zkay packages import os import datetime import sys import shutil clean=False file_dir", "base_dir = os.path.join(file_dir, 'examples') if len(sys.argv) < 2 else os.path.realpath(sys.argv[1]) backends = ['dummy',", "dirname in os.listdir(base_dir): p = os.path.join(base_dir, dirname) if os.path.isdir(p): file = None for", "file is not None: out_dir = os.path.join(p, f'out_{backend}') if clean and os.path.exists(out_dir): shutil.rmtree(out_dir)", "None for filename in os.listdir(p): if filename.endswith(('.sol', '.zkay')): file = os.path.join(p, filename) break", "{backend} --opt-hash-threshold 0 -o '{out_dir}' --log --log-dir '{out_dir}'\") scenario_file = os.path.join(p, 'scenario.py') if", "'rsa-pkcs1.5', 'rsa-oaep'] # rsa consumes >100 GB hdd space for backend in backends:", "--log-dir '{out_dir}'\") scenario_file = os.path.join(p, 'scenario.py') if os.path.exists(scenario_file): print(f'running {scenario_file}, at {datetime.datetime.utcnow()}') os.system(f\"mprof", "for dirname in os.listdir(base_dir): p = os.path.join(base_dir, dirname) if os.path.isdir(p): file = None", "compile '{file}' --verbosity 0 --crypto-backend {backend} --opt-hash-threshold 0 -o '{out_dir}' --log --log-dir '{out_dir}'\")", "os.path.join(base_dir, dirname) if os.path.isdir(p): file = None for filename in os.listdir(p): if filename.endswith(('.sol',", "<reponame>nibau/zkay<gh_stars>0 #!/usr/bin/env python3 # usage ./benchmark.py [example_dir] # (example_dir contains subdirectories with example", "os.path.exists(out_dir): shutil.rmtree(out_dir) os.makedirs(out_dir, exist_ok=True) print(f'compiling {file}, at {datetime.datetime.utcnow()}') os.system(f\"mprof run --include-children --nopython -o", "os import datetime import sys import shutil clean=False file_dir = os.path.realpath(os.path.dirname(__file__)) base_dir =", "'{out_dir}/mprof_compile.dat' zkay compile '{file}' --verbosity 0 --crypto-backend {backend} --opt-hash-threshold 0 -o '{out_dir}' --log", "file_dir = os.path.realpath(os.path.dirname(__file__)) base_dir = os.path.join(file_dir, 'examples') if len(sys.argv) < 2 else os.path.realpath(sys.argv[1])", "os.path.realpath(os.path.dirname(__file__)) base_dir = os.path.join(file_dir, 'examples') if len(sys.argv) < 2 else os.path.realpath(sys.argv[1]) backends =", "rsa consumes >100 GB hdd space for backend in backends: for dirname in", "os.system(f\"mprof run --include-children --nopython -o '{out_dir}/mprof_compile.dat' zkay compile '{file}' --verbosity 0 --crypto-backend {backend}", "if len(sys.argv) < 2 else os.path.realpath(sys.argv[1]) backends = ['dummy', 'ecdh-chaskey', 'ecdh-aes'] #, 'rsa-pkcs1.5',", "# rsa consumes >100 GB hdd space for backend in backends: for dirname", "--include-children --nopython -o '{out_dir}/mprof_compile.dat' zkay compile '{file}' --verbosity 0 --crypto-backend {backend} --opt-hash-threshold 0", "at {datetime.datetime.utcnow()}') os.system(f\"mprof run --include-children --nopython -o '{out_dir}/mprof_compile.dat' zkay compile '{file}' --verbosity 0", "example sol/zkay and scenario files) # requires installed memory-profiler and zkay packages import", "out_dir = os.path.join(p, f'out_{backend}') if clean and os.path.exists(out_dir): shutil.rmtree(out_dir) os.makedirs(out_dir, exist_ok=True) print(f'compiling {file},", "import shutil clean=False file_dir = os.path.realpath(os.path.dirname(__file__)) base_dir = os.path.join(file_dir, 'examples') if len(sys.argv) <", "shutil clean=False file_dir = os.path.realpath(os.path.dirname(__file__)) base_dir = os.path.join(file_dir, 'examples') if len(sys.argv) < 2", "is not None: out_dir = os.path.join(p, f'out_{backend}') if clean and os.path.exists(out_dir): shutil.rmtree(out_dir) os.makedirs(out_dir,", "if os.path.exists(scenario_file): print(f'running {scenario_file}, at {datetime.datetime.utcnow()}') os.system(f\"mprof run --include-children --nopython -o '{out_dir}/mprof_run.dat' python", "python3 # usage ./benchmark.py [example_dir] # (example_dir contains subdirectories with example sol/zkay and", "= ['dummy', 'ecdh-chaskey', 'ecdh-aes'] #, 'rsa-pkcs1.5', 'rsa-oaep'] # rsa consumes >100 GB hdd", "[example_dir] # (example_dir contains subdirectories with example sol/zkay and scenario files) # requires", "'{out_dir}' --log --log-dir '{out_dir}'\") scenario_file = os.path.join(p, 'scenario.py') if os.path.exists(scenario_file): print(f'running {scenario_file}, at", "filename in os.listdir(p): if filename.endswith(('.sol', '.zkay')): file = os.path.join(p, filename) break if file", "clean=False file_dir = os.path.realpath(os.path.dirname(__file__)) base_dir = os.path.join(file_dir, 'examples') if len(sys.argv) < 2 else", "not None: out_dir = os.path.join(p, f'out_{backend}') if clean and os.path.exists(out_dir): shutil.rmtree(out_dir) os.makedirs(out_dir, exist_ok=True)", "0 -o '{out_dir}' --log --log-dir '{out_dir}'\") scenario_file = os.path.join(p, 'scenario.py') if os.path.exists(scenario_file): print(f'running", "backends = ['dummy', 'ecdh-chaskey', 'ecdh-aes'] #, 'rsa-pkcs1.5', 'rsa-oaep'] # rsa consumes >100 GB", "-o '{out_dir}/mprof_compile.dat' zkay compile '{file}' --verbosity 0 --crypto-backend {backend} --opt-hash-threshold 0 -o '{out_dir}'", "for backend in backends: for dirname in os.listdir(base_dir): p = os.path.join(base_dir, dirname) if", "import os import datetime import sys import shutil clean=False file_dir = os.path.realpath(os.path.dirname(__file__)) base_dir", "p = os.path.join(base_dir, dirname) if os.path.isdir(p): file = None for filename in os.listdir(p):", "= os.path.join(p, 'scenario.py') if os.path.exists(scenario_file): print(f'running {scenario_file}, at {datetime.datetime.utcnow()}') os.system(f\"mprof run --include-children --nopython", "= None for filename in os.listdir(p): if filename.endswith(('.sol', '.zkay')): file = os.path.join(p, filename)", "os.listdir(base_dir): p = os.path.join(base_dir, dirname) if os.path.isdir(p): file = None for filename in", "< 2 else os.path.realpath(sys.argv[1]) backends = ['dummy', 'ecdh-chaskey', 'ecdh-aes'] #, 'rsa-pkcs1.5', 'rsa-oaep'] #", "os.makedirs(out_dir, exist_ok=True) print(f'compiling {file}, at {datetime.datetime.utcnow()}') os.system(f\"mprof run --include-children --nopython -o '{out_dir}/mprof_compile.dat' zkay", "None: out_dir = os.path.join(p, f'out_{backend}') if clean and os.path.exists(out_dir): shutil.rmtree(out_dir) os.makedirs(out_dir, exist_ok=True) print(f'compiling", "--opt-hash-threshold 0 -o '{out_dir}' --log --log-dir '{out_dir}'\") scenario_file = os.path.join(p, 'scenario.py') if os.path.exists(scenario_file):", "os.path.realpath(sys.argv[1]) backends = ['dummy', 'ecdh-chaskey', 'ecdh-aes'] #, 'rsa-pkcs1.5', 'rsa-oaep'] # rsa consumes >100" ]
[ "from models.ffhq_1024_haar.Training_data import * from models.ffhq_1024_haar.Validation_data import * from models.ffhq_1024_haar.Network_body import * from", "models.ffhq_1024_haar.Validation_data import * from models.ffhq_1024_haar.Network_body import * from models.ffhq_1024_haar.Conditioning_network import * import models.shared.routines", "import * from models.ffhq_1024_haar.Network_body import * from models.ffhq_1024_haar.Conditioning_network import * import models.shared.routines as", "* from models.ffhq_1024_haar.Network_body import * from models.ffhq_1024_haar.Conditioning_network import * import models.shared.routines as routines", "from models.ffhq_1024_haar.Network_body import * from models.ffhq_1024_haar.Conditioning_network import * import models.shared.routines as routines from", "from models.ffhq_1024_haar.Conditioning_network import * import models.shared.routines as routines from models.ffhq_1024_haar.build_training_graph import * model_config_path", "import * import models.shared.routines as routines from models.ffhq_1024_haar.build_training_graph import * model_config_path = 'data/ffhq_1024_haar/config.hjson'", "* from models.ffhq_1024_haar.Conditioning_network import * import models.shared.routines as routines from models.ffhq_1024_haar.build_training_graph import *", "from models.ffhq_1024_haar.Validation_data import * from models.ffhq_1024_haar.Network_body import * from models.ffhq_1024_haar.Conditioning_network import * import", "import * from models.ffhq_1024_haar.Conditioning_network import * import models.shared.routines as routines from models.ffhq_1024_haar.build_training_graph import", "models.ffhq_1024_haar.Conditioning_network import * import models.shared.routines as routines from models.ffhq_1024_haar.build_training_graph import * model_config_path =", "* from models.ffhq_1024_haar.Validation_data import * from models.ffhq_1024_haar.Network_body import * from models.ffhq_1024_haar.Conditioning_network import *", "import * from models.ffhq_1024_haar.Validation_data import * from models.ffhq_1024_haar.Network_body import * from models.ffhq_1024_haar.Conditioning_network import", "models.ffhq_1024_haar.Network_body import * from models.ffhq_1024_haar.Conditioning_network import * import models.shared.routines as routines from models.ffhq_1024_haar.build_training_graph", "models.ffhq_1024_haar.Training_data import * from models.ffhq_1024_haar.Validation_data import * from models.ffhq_1024_haar.Network_body import * from models.ffhq_1024_haar.Conditioning_network" ]
[ "= sys.argv[1] if os.path.exists(os.getcwd() + \"/\" + targetfile): openFile = open(targetfile) writeFile =", "contains(line,\"EXTERNAL\"): # just an include writeFile.write(line) else: # HERE we introduce the call", "+ targetfile): openFile = open(targetfile) writeFile = open(targetfile+\".new\",\"w\") print \"Begin parsing head file", "if(search == 2): # schon gefunden writeFile.write(line) else: if search == 0: if", "import re def contains(theString, theQueryValue): return theString.find(theQueryValue) > -1 targetfile = sys.argv[1] if", "1: if line.startswith(\"!\"): # just a comment writeFile.write(line) else: if contains(line,\"INCLUDE\") or contains(line,\"INTEGER\")", "-1 targetfile = sys.argv[1] if os.path.exists(os.getcwd() + \"/\" + targetfile): openFile = open(targetfile)", "call writeFile.write(\" CALL INIT()\\n\"); writeFile.write(line) search = 2 openFile.close() writeFile.close() else: print \"Data", "== 2): # schon gefunden writeFile.write(line) else: if search == 0: if contains(line,\"IMPLICIT", "if os.path.exists(os.getcwd() + \"/\" + targetfile): openFile = open(targetfile) writeFile = open(targetfile+\".new\",\"w\") print", "allLines: if(search == 2): # schon gefunden writeFile.write(line) else: if search == 0:", "comment writeFile.write(line) else: if contains(line,\"INCLUDE\") or contains(line,\"INTEGER\") or contains(line,\"DOUBLE\") or contains(line,\"EXTERNAL\"): # just", "0 for line in allLines: if(search == 2): # schon gefunden writeFile.write(line) else:", "if contains(line,\"IMPLICIT NONE\"): # we begin search for final INCLUDE writeFile.write(line) search =", "or contains(line,\"EXTERNAL\"): # just an include writeFile.write(line) else: # HERE we introduce the", "= 2 openFile.close() writeFile.close() else: print \"Data \" + targetfile +\" does not", "CALL INIT()\\n\"); writeFile.write(line) search = 2 openFile.close() writeFile.close() else: print \"Data \" +", "parsing head file to include init call\" allLines = openFile.readlines() lines = set(allLines)", "1 else: writeFile.write(line) else: if search == 1: if line.startswith(\"!\"): # just a", "+ \"/\" + targetfile): openFile = open(targetfile) writeFile = open(targetfile+\".new\",\"w\") print \"Begin parsing", "# HERE we introduce the call writeFile.write(\" CALL INIT()\\n\"); writeFile.write(line) search = 2", "contains(theString, theQueryValue): return theString.find(theQueryValue) > -1 targetfile = sys.argv[1] if os.path.exists(os.getcwd() + \"/\"", "search = 1 else: writeFile.write(line) else: if search == 1: if line.startswith(\"!\"): #", "re def contains(theString, theQueryValue): return theString.find(theQueryValue) > -1 targetfile = sys.argv[1] if os.path.exists(os.getcwd()", "\"/\" + targetfile): openFile = open(targetfile) writeFile = open(targetfile+\".new\",\"w\") print \"Begin parsing head", "gefunden writeFile.write(line) else: if search == 0: if contains(line,\"IMPLICIT NONE\"): # we begin", "= 1 else: writeFile.write(line) else: if search == 1: if line.startswith(\"!\"): # just", "\"Begin parsing head file to include init call\" allLines = openFile.readlines() lines =", "contains(line,\"IMPLICIT NONE\"): # we begin search for final INCLUDE writeFile.write(line) search = 1", "import sys import os import re def contains(theString, theQueryValue): return theString.find(theQueryValue) > -1", "init call\" allLines = openFile.readlines() lines = set(allLines) search = 0 for line", "introduce the call writeFile.write(\" CALL INIT()\\n\"); writeFile.write(line) search = 2 openFile.close() writeFile.close() else:", "= set(allLines) search = 0 for line in allLines: if(search == 2): #", "writeFile.write(line) else: if contains(line,\"INCLUDE\") or contains(line,\"INTEGER\") or contains(line,\"DOUBLE\") or contains(line,\"EXTERNAL\"): # just an", "writeFile.write(line) else: # HERE we introduce the call writeFile.write(\" CALL INIT()\\n\"); writeFile.write(line) search", "print \"Begin parsing head file to include init call\" allLines = openFile.readlines() lines", "-*- coding: iso-8859-1 -*- import sys import os import re def contains(theString, theQueryValue):", "openFile.readlines() lines = set(allLines) search = 0 for line in allLines: if(search ==", "# schon gefunden writeFile.write(line) else: if search == 0: if contains(line,\"IMPLICIT NONE\"): #", "search = 0 for line in allLines: if(search == 2): # schon gefunden", "writeFile.write(line) search = 2 openFile.close() writeFile.close() else: print \"Data \" + targetfile +\"", "for line in allLines: if(search == 2): # schon gefunden writeFile.write(line) else: if", "a comment writeFile.write(line) else: if contains(line,\"INCLUDE\") or contains(line,\"INTEGER\") or contains(line,\"DOUBLE\") or contains(line,\"EXTERNAL\"): #", "iso-8859-1 -*- import sys import os import re def contains(theString, theQueryValue): return theString.find(theQueryValue)", "writeFile.write(\" CALL INIT()\\n\"); writeFile.write(line) search = 2 openFile.close() writeFile.close() else: print \"Data \"", "2 openFile.close() writeFile.close() else: print \"Data \" + targetfile +\" does not exist!\"", "= open(targetfile) writeFile = open(targetfile+\".new\",\"w\") print \"Begin parsing head file to include init", "sys import os import re def contains(theString, theQueryValue): return theString.find(theQueryValue) > -1 targetfile", "head file to include init call\" allLines = openFile.readlines() lines = set(allLines) search", "call\" allLines = openFile.readlines() lines = set(allLines) search = 0 for line in", "2): # schon gefunden writeFile.write(line) else: if search == 0: if contains(line,\"IMPLICIT NONE\"):", "targetfile): openFile = open(targetfile) writeFile = open(targetfile+\".new\",\"w\") print \"Begin parsing head file to", "INIT()\\n\"); writeFile.write(line) search = 2 openFile.close() writeFile.close() else: print \"Data \" + targetfile", "theString.find(theQueryValue) > -1 targetfile = sys.argv[1] if os.path.exists(os.getcwd() + \"/\" + targetfile): openFile", "else: writeFile.write(line) else: if search == 1: if line.startswith(\"!\"): # just a comment", "<filename>mkAD/modify_init.py<gh_stars>0 #!/usr/bin/python # -*- coding: iso-8859-1 -*- import sys import os import re", "= openFile.readlines() lines = set(allLines) search = 0 for line in allLines: if(search", "set(allLines) search = 0 for line in allLines: if(search == 2): # schon", "# -*- coding: iso-8859-1 -*- import sys import os import re def contains(theString,", "os import re def contains(theString, theQueryValue): return theString.find(theQueryValue) > -1 targetfile = sys.argv[1]", "writeFile.write(line) else: if search == 0: if contains(line,\"IMPLICIT NONE\"): # we begin search", "NONE\"): # we begin search for final INCLUDE writeFile.write(line) search = 1 else:", "open(targetfile+\".new\",\"w\") print \"Begin parsing head file to include init call\" allLines = openFile.readlines()", "search == 0: if contains(line,\"IMPLICIT NONE\"): # we begin search for final INCLUDE", "writeFile = open(targetfile+\".new\",\"w\") print \"Begin parsing head file to include init call\" allLines", "else: if search == 0: if contains(line,\"IMPLICIT NONE\"): # we begin search for", "we begin search for final INCLUDE writeFile.write(line) search = 1 else: writeFile.write(line) else:", "just a comment writeFile.write(line) else: if contains(line,\"INCLUDE\") or contains(line,\"INTEGER\") or contains(line,\"DOUBLE\") or contains(line,\"EXTERNAL\"):", "or contains(line,\"DOUBLE\") or contains(line,\"EXTERNAL\"): # just an include writeFile.write(line) else: # HERE we", "else: if search == 1: if line.startswith(\"!\"): # just a comment writeFile.write(line) else:", "open(targetfile) writeFile = open(targetfile+\".new\",\"w\") print \"Begin parsing head file to include init call\"", "else: if contains(line,\"INCLUDE\") or contains(line,\"INTEGER\") or contains(line,\"DOUBLE\") or contains(line,\"EXTERNAL\"): # just an include", "HERE we introduce the call writeFile.write(\" CALL INIT()\\n\"); writeFile.write(line) search = 2 openFile.close()", "0: if contains(line,\"IMPLICIT NONE\"): # we begin search for final INCLUDE writeFile.write(line) search", "else: # HERE we introduce the call writeFile.write(\" CALL INIT()\\n\"); writeFile.write(line) search =", "import os import re def contains(theString, theQueryValue): return theString.find(theQueryValue) > -1 targetfile =", "def contains(theString, theQueryValue): return theString.find(theQueryValue) > -1 targetfile = sys.argv[1] if os.path.exists(os.getcwd() +", "include init call\" allLines = openFile.readlines() lines = set(allLines) search = 0 for", "line.startswith(\"!\"): # just a comment writeFile.write(line) else: if contains(line,\"INCLUDE\") or contains(line,\"INTEGER\") or contains(line,\"DOUBLE\")", "theQueryValue): return theString.find(theQueryValue) > -1 targetfile = sys.argv[1] if os.path.exists(os.getcwd() + \"/\" +", "= 0 for line in allLines: if(search == 2): # schon gefunden writeFile.write(line)", "schon gefunden writeFile.write(line) else: if search == 0: if contains(line,\"IMPLICIT NONE\"): # we", "contains(line,\"INCLUDE\") or contains(line,\"INTEGER\") or contains(line,\"DOUBLE\") or contains(line,\"EXTERNAL\"): # just an include writeFile.write(line) else:", "if line.startswith(\"!\"): # just a comment writeFile.write(line) else: if contains(line,\"INCLUDE\") or contains(line,\"INTEGER\") or", "#!/usr/bin/python # -*- coding: iso-8859-1 -*- import sys import os import re def", "begin search for final INCLUDE writeFile.write(line) search = 1 else: writeFile.write(line) else: if", "if contains(line,\"INCLUDE\") or contains(line,\"INTEGER\") or contains(line,\"DOUBLE\") or contains(line,\"EXTERNAL\"): # just an include writeFile.write(line)", "if search == 0: if contains(line,\"IMPLICIT NONE\"): # we begin search for final", "or contains(line,\"INTEGER\") or contains(line,\"DOUBLE\") or contains(line,\"EXTERNAL\"): # just an include writeFile.write(line) else: #", "> -1 targetfile = sys.argv[1] if os.path.exists(os.getcwd() + \"/\" + targetfile): openFile =", "writeFile.write(line) else: if search == 1: if line.startswith(\"!\"): # just a comment writeFile.write(line)", "an include writeFile.write(line) else: # HERE we introduce the call writeFile.write(\" CALL INIT()\\n\");", "coding: iso-8859-1 -*- import sys import os import re def contains(theString, theQueryValue): return", "== 0: if contains(line,\"IMPLICIT NONE\"): # we begin search for final INCLUDE writeFile.write(line)", "search for final INCLUDE writeFile.write(line) search = 1 else: writeFile.write(line) else: if search", "search == 1: if line.startswith(\"!\"): # just a comment writeFile.write(line) else: if contains(line,\"INCLUDE\")", "== 1: if line.startswith(\"!\"): # just a comment writeFile.write(line) else: if contains(line,\"INCLUDE\") or", "if search == 1: if line.startswith(\"!\"): # just a comment writeFile.write(line) else: if", "# we begin search for final INCLUDE writeFile.write(line) search = 1 else: writeFile.write(line)", "targetfile = sys.argv[1] if os.path.exists(os.getcwd() + \"/\" + targetfile): openFile = open(targetfile) writeFile", "= open(targetfile+\".new\",\"w\") print \"Begin parsing head file to include init call\" allLines =", "allLines = openFile.readlines() lines = set(allLines) search = 0 for line in allLines:", "contains(line,\"DOUBLE\") or contains(line,\"EXTERNAL\"): # just an include writeFile.write(line) else: # HERE we introduce", "sys.argv[1] if os.path.exists(os.getcwd() + \"/\" + targetfile): openFile = open(targetfile) writeFile = open(targetfile+\".new\",\"w\")", "openFile = open(targetfile) writeFile = open(targetfile+\".new\",\"w\") print \"Begin parsing head file to include", "return theString.find(theQueryValue) > -1 targetfile = sys.argv[1] if os.path.exists(os.getcwd() + \"/\" + targetfile):", "os.path.exists(os.getcwd() + \"/\" + targetfile): openFile = open(targetfile) writeFile = open(targetfile+\".new\",\"w\") print \"Begin", "writeFile.write(line) search = 1 else: writeFile.write(line) else: if search == 1: if line.startswith(\"!\"):", "include writeFile.write(line) else: # HERE we introduce the call writeFile.write(\" CALL INIT()\\n\"); writeFile.write(line)", "contains(line,\"INTEGER\") or contains(line,\"DOUBLE\") or contains(line,\"EXTERNAL\"): # just an include writeFile.write(line) else: # HERE", "line in allLines: if(search == 2): # schon gefunden writeFile.write(line) else: if search", "INCLUDE writeFile.write(line) search = 1 else: writeFile.write(line) else: if search == 1: if", "just an include writeFile.write(line) else: # HERE we introduce the call writeFile.write(\" CALL", "file to include init call\" allLines = openFile.readlines() lines = set(allLines) search =", "final INCLUDE writeFile.write(line) search = 1 else: writeFile.write(line) else: if search == 1:", "-*- import sys import os import re def contains(theString, theQueryValue): return theString.find(theQueryValue) >", "# just an include writeFile.write(line) else: # HERE we introduce the call writeFile.write(\"", "the call writeFile.write(\" CALL INIT()\\n\"); writeFile.write(line) search = 2 openFile.close() writeFile.close() else: print", "we introduce the call writeFile.write(\" CALL INIT()\\n\"); writeFile.write(line) search = 2 openFile.close() writeFile.close()", "search = 2 openFile.close() writeFile.close() else: print \"Data \" + targetfile +\" does", "# just a comment writeFile.write(line) else: if contains(line,\"INCLUDE\") or contains(line,\"INTEGER\") or contains(line,\"DOUBLE\") or", "in allLines: if(search == 2): # schon gefunden writeFile.write(line) else: if search ==", "to include init call\" allLines = openFile.readlines() lines = set(allLines) search = 0", "for final INCLUDE writeFile.write(line) search = 1 else: writeFile.write(line) else: if search ==", "lines = set(allLines) search = 0 for line in allLines: if(search == 2):" ]
[ "filter, entityReferenceExpansion): from TreeWalker import TreeWalker return TreeWalker(root, whatToShow, filter, entityReferenceExpansion) def createRange(self):", "class Document(minidom.Document): implementation = DOMImplementation() def createNodeIterator(self, root, whatToShow, filter, entityReferenceExpansion): from xml.dom", "= DOMImplementation() def createNodeIterator(self, root, whatToShow, filter, entityReferenceExpansion): from xml.dom import NodeIterator nodi", "import minidom, string class DOMImplementation(minidom.DOMImplementation): def hasFeature(self, feature, version): if version not in", "from xml.dom import NodeIterator nodi = NodeIterator.NodeIterator(root, whatToShow, filter, entityReferenceExpansion) return nodi def", "if version not in (\"1.0\", \"2.0\"): return 0 feature = string.lower(feature) if feature", "that offers traversal and ranges on top of minidom, using the 4DOM traversal", "DOM implementation that offers traversal and ranges on top of minidom, using the", "offers traversal and ranges on top of minidom, using the 4DOM traversal implementation.\"\"\"", "def createTreeWalker(self, root, whatToShow, filter, entityReferenceExpansion): from TreeWalker import TreeWalker return TreeWalker(root, whatToShow,", "\"2.0\"): return 0 feature = string.lower(feature) if feature in ['traversal','range']: return 1 return", "filter, entityReferenceExpansion): from xml.dom import NodeIterator nodi = NodeIterator.NodeIterator(root, whatToShow, filter, entityReferenceExpansion) return", "minidom, using the 4DOM traversal implementation.\"\"\" import minidom, string class DOMImplementation(minidom.DOMImplementation): def hasFeature(self,", "entityReferenceExpansion): from TreeWalker import TreeWalker return TreeWalker(root, whatToShow, filter, entityReferenceExpansion) def createRange(self): import", "whatToShow, filter, entityReferenceExpansion) def createRange(self): import Range return Range.Range(self) def getDOMImplementation(): return Document.implementation", "_createDocument(self): return Document() class Document(minidom.Document): implementation = DOMImplementation() def createNodeIterator(self, root, whatToShow, filter,", "feature, version) def _createDocument(self): return Document() class Document(minidom.Document): implementation = DOMImplementation() def createNodeIterator(self,", "def _createDocument(self): return Document() class Document(minidom.Document): implementation = DOMImplementation() def createNodeIterator(self, root, whatToShow,", "implementation that offers traversal and ranges on top of minidom, using the 4DOM", "NodeIterator.NodeIterator(root, whatToShow, filter, entityReferenceExpansion) return nodi def createTreeWalker(self, root, whatToShow, filter, entityReferenceExpansion): from", "import TreeWalker return TreeWalker(root, whatToShow, filter, entityReferenceExpansion) def createRange(self): import Range return Range.Range(self)", "whatToShow, filter, entityReferenceExpansion): from TreeWalker import TreeWalker return TreeWalker(root, whatToShow, filter, entityReferenceExpansion) def", "whatToShow, filter, entityReferenceExpansion): from xml.dom import NodeIterator nodi = NodeIterator.NodeIterator(root, whatToShow, filter, entityReferenceExpansion)", "return TreeWalker(root, whatToShow, filter, entityReferenceExpansion) def createRange(self): import Range return Range.Range(self) def getDOMImplementation():", "ranges on top of minidom, using the 4DOM traversal implementation.\"\"\" import minidom, string", "top of minidom, using the 4DOM traversal implementation.\"\"\" import minidom, string class DOMImplementation(minidom.DOMImplementation):", "in (\"1.0\", \"2.0\"): return 0 feature = string.lower(feature) if feature in ['traversal','range']: return", "feature, version): if version not in (\"1.0\", \"2.0\"): return 0 feature = string.lower(feature)", "implementation.\"\"\" import minidom, string class DOMImplementation(minidom.DOMImplementation): def hasFeature(self, feature, version): if version not", "Document(minidom.Document): implementation = DOMImplementation() def createNodeIterator(self, root, whatToShow, filter, entityReferenceExpansion): from xml.dom import", "nodi def createTreeWalker(self, root, whatToShow, filter, entityReferenceExpansion): from TreeWalker import TreeWalker return TreeWalker(root,", "entityReferenceExpansion): from xml.dom import NodeIterator nodi = NodeIterator.NodeIterator(root, whatToShow, filter, entityReferenceExpansion) return nodi", "def hasFeature(self, feature, version): if version not in (\"1.0\", \"2.0\"): return 0 feature", "= string.lower(feature) if feature in ['traversal','range']: return 1 return minidom.DOMImplementation.hasFeature(self, feature, version) def", "whatToShow, filter, entityReferenceExpansion) return nodi def createTreeWalker(self, root, whatToShow, filter, entityReferenceExpansion): from TreeWalker", "= NodeIterator.NodeIterator(root, whatToShow, filter, entityReferenceExpansion) return nodi def createTreeWalker(self, root, whatToShow, filter, entityReferenceExpansion):", "traversal implementation.\"\"\" import minidom, string class DOMImplementation(minidom.DOMImplementation): def hasFeature(self, feature, version): if version", "version) def _createDocument(self): return Document() class Document(minidom.Document): implementation = DOMImplementation() def createNodeIterator(self, root,", "on top of minidom, using the 4DOM traversal implementation.\"\"\" import minidom, string class", "if feature in ['traversal','range']: return 1 return minidom.DOMImplementation.hasFeature(self, feature, version) def _createDocument(self): return", "minidom.DOMImplementation.hasFeature(self, feature, version) def _createDocument(self): return Document() class Document(minidom.Document): implementation = DOMImplementation() def", "the 4DOM traversal implementation.\"\"\" import minidom, string class DOMImplementation(minidom.DOMImplementation): def hasFeature(self, feature, version):", "4DOM traversal implementation.\"\"\" import minidom, string class DOMImplementation(minidom.DOMImplementation): def hasFeature(self, feature, version): if", "nodi = NodeIterator.NodeIterator(root, whatToShow, filter, entityReferenceExpansion) return nodi def createTreeWalker(self, root, whatToShow, filter,", "(\"1.0\", \"2.0\"): return 0 feature = string.lower(feature) if feature in ['traversal','range']: return 1", "def createNodeIterator(self, root, whatToShow, filter, entityReferenceExpansion): from xml.dom import NodeIterator nodi = NodeIterator.NodeIterator(root,", "using the 4DOM traversal implementation.\"\"\" import minidom, string class DOMImplementation(minidom.DOMImplementation): def hasFeature(self, feature,", "in ['traversal','range']: return 1 return minidom.DOMImplementation.hasFeature(self, feature, version) def _createDocument(self): return Document() class", "\"\"\"A DOM implementation that offers traversal and ranges on top of minidom, using", "['traversal','range']: return 1 return minidom.DOMImplementation.hasFeature(self, feature, version) def _createDocument(self): return Document() class Document(minidom.Document):", "feature = string.lower(feature) if feature in ['traversal','range']: return 1 return minidom.DOMImplementation.hasFeature(self, feature, version)", "Document() class Document(minidom.Document): implementation = DOMImplementation() def createNodeIterator(self, root, whatToShow, filter, entityReferenceExpansion): from", "xml.dom import NodeIterator nodi = NodeIterator.NodeIterator(root, whatToShow, filter, entityReferenceExpansion) return nodi def createTreeWalker(self,", "of minidom, using the 4DOM traversal implementation.\"\"\" import minidom, string class DOMImplementation(minidom.DOMImplementation): def", "0 feature = string.lower(feature) if feature in ['traversal','range']: return 1 return minidom.DOMImplementation.hasFeature(self, feature,", "createTreeWalker(self, root, whatToShow, filter, entityReferenceExpansion): from TreeWalker import TreeWalker return TreeWalker(root, whatToShow, filter,", "minidom, string class DOMImplementation(minidom.DOMImplementation): def hasFeature(self, feature, version): if version not in (\"1.0\",", "TreeWalker import TreeWalker return TreeWalker(root, whatToShow, filter, entityReferenceExpansion) def createRange(self): import Range return", "return 1 return minidom.DOMImplementation.hasFeature(self, feature, version) def _createDocument(self): return Document() class Document(minidom.Document): implementation", "string.lower(feature) if feature in ['traversal','range']: return 1 return minidom.DOMImplementation.hasFeature(self, feature, version) def _createDocument(self):", "DOMImplementation() def createNodeIterator(self, root, whatToShow, filter, entityReferenceExpansion): from xml.dom import NodeIterator nodi =", "return 0 feature = string.lower(feature) if feature in ['traversal','range']: return 1 return minidom.DOMImplementation.hasFeature(self,", "entityReferenceExpansion) return nodi def createTreeWalker(self, root, whatToShow, filter, entityReferenceExpansion): from TreeWalker import TreeWalker", "return nodi def createTreeWalker(self, root, whatToShow, filter, entityReferenceExpansion): from TreeWalker import TreeWalker return", "return Document() class Document(minidom.Document): implementation = DOMImplementation() def createNodeIterator(self, root, whatToShow, filter, entityReferenceExpansion):", "NodeIterator nodi = NodeIterator.NodeIterator(root, whatToShow, filter, entityReferenceExpansion) return nodi def createTreeWalker(self, root, whatToShow,", "root, whatToShow, filter, entityReferenceExpansion): from xml.dom import NodeIterator nodi = NodeIterator.NodeIterator(root, whatToShow, filter,", "and ranges on top of minidom, using the 4DOM traversal implementation.\"\"\" import minidom,", "string class DOMImplementation(minidom.DOMImplementation): def hasFeature(self, feature, version): if version not in (\"1.0\", \"2.0\"):", "TreeWalker(root, whatToShow, filter, entityReferenceExpansion) def createRange(self): import Range return Range.Range(self) def getDOMImplementation(): return", "filter, entityReferenceExpansion) return nodi def createTreeWalker(self, root, whatToShow, filter, entityReferenceExpansion): from TreeWalker import", "version not in (\"1.0\", \"2.0\"): return 0 feature = string.lower(feature) if feature in", "TreeWalker return TreeWalker(root, whatToShow, filter, entityReferenceExpansion) def createRange(self): import Range return Range.Range(self) def", "root, whatToShow, filter, entityReferenceExpansion): from TreeWalker import TreeWalker return TreeWalker(root, whatToShow, filter, entityReferenceExpansion)", "traversal and ranges on top of minidom, using the 4DOM traversal implementation.\"\"\" import", "not in (\"1.0\", \"2.0\"): return 0 feature = string.lower(feature) if feature in ['traversal','range']:", "DOMImplementation(minidom.DOMImplementation): def hasFeature(self, feature, version): if version not in (\"1.0\", \"2.0\"): return 0", "import NodeIterator nodi = NodeIterator.NodeIterator(root, whatToShow, filter, entityReferenceExpansion) return nodi def createTreeWalker(self, root,", "feature in ['traversal','range']: return 1 return minidom.DOMImplementation.hasFeature(self, feature, version) def _createDocument(self): return Document()", "return minidom.DOMImplementation.hasFeature(self, feature, version) def _createDocument(self): return Document() class Document(minidom.Document): implementation = DOMImplementation()", "from TreeWalker import TreeWalker return TreeWalker(root, whatToShow, filter, entityReferenceExpansion) def createRange(self): import Range", "implementation = DOMImplementation() def createNodeIterator(self, root, whatToShow, filter, entityReferenceExpansion): from xml.dom import NodeIterator", "class DOMImplementation(minidom.DOMImplementation): def hasFeature(self, feature, version): if version not in (\"1.0\", \"2.0\"): return", "version): if version not in (\"1.0\", \"2.0\"): return 0 feature = string.lower(feature) if", "hasFeature(self, feature, version): if version not in (\"1.0\", \"2.0\"): return 0 feature =", "createNodeIterator(self, root, whatToShow, filter, entityReferenceExpansion): from xml.dom import NodeIterator nodi = NodeIterator.NodeIterator(root, whatToShow,", "1 return minidom.DOMImplementation.hasFeature(self, feature, version) def _createDocument(self): return Document() class Document(minidom.Document): implementation =" ]
[ "print(\"INFO: Abandon this Proxy IP!\") with open(\"fail.txt\", \"a+\") as f: f.write(proxy + \"+/n\")", "def loop_test(name): print(\"*Start thread task %s\" % name) while True: result = http_task()", "import threading def http_task(): # 连接redis数据库 POOL = redis.ConnectionPool(host='127.0.0.1', port=6379) CONN_REDIS = redis.Redis(connection_pool=POOL)", "True: # CONN_REDIS.sadd(\"freeProxy:AfterVerifyOKhttp\", proxy) # print(\"INFO: Save this Proxy IP in freeProxy:AfterVerifyOKhttp\") with", "CONN_REDIS = redis.Redis(connection_pool=POOL) # 取出一个ip进行测试 # proxy = CONN_REDIS.(\"freeProxy:AfterVerifyOKhttp\") ip = CONN_REDIS.srandmember(\"freeProxy:AfterVerifyOKhttp\",1) #", "== True: # CONN_REDIS.sadd(\"freeProxy:AfterVerifyOKhttp\", proxy) # print(\"INFO: Save this Proxy IP in freeProxy:AfterVerifyOKhttp\")", "[] num = 8 for i in range(1, num+1): name = \"Thread-\" +", "# CONN_REDIS.sadd(\"freeProxy_Bad:AfterVerifyFailhttp\", proxy) # print(\"INFO: Abandon this Proxy IP!\") with open(\"fail.txt\", \"a+\") as", "while True: result = http_task() print(\"\\n\") if result == 0: break if __name__", "\"Thread-\" + str(i) jobs.append(threading.Thread(target=loop_test, args=(name,))) # 开启多线程 for t in jobs: t.start() for", "= redis.Redis(connection_pool=POOL) # 取出一个ip进行测试 # proxy = CONN_REDIS.(\"freeProxy:AfterVerifyOKhttp\") ip = CONN_REDIS.srandmember(\"freeProxy:AfterVerifyOKhttp\",1) # 判断redis中ip数量是否为空", "__name__ == \"__main__\": jobs = [] num = 8 for i in range(1,", "print(\"*Start thread task %s\" % name) while True: result = http_task() print(\"\\n\") if", "proxy from Redis freeProxy:BeforeVerifyhttp list\") proxy = str(ip[0], encoding=\"utf-8\") flag = test_http_proxy(proxy) if", "proxy = CONN_REDIS.(\"freeProxy:AfterVerifyOKhttp\") ip = CONN_REDIS.srandmember(\"freeProxy:AfterVerifyOKhttp\",1) # 判断redis中ip数量是否为空 if not ip: return 0", "# print(\"INFO: Abandon this Proxy IP!\") with open(\"fail.txt\", \"a+\") as f: f.write(proxy +", "proxy) return 1 def loop_test(name): print(\"*Start thread task %s\" % name) while True:", "if result == 0: break if __name__ == \"__main__\": jobs = [] num", "= 8 for i in range(1, num+1): name = \"Thread-\" + str(i) jobs.append(threading.Thread(target=loop_test,", "CONN_REDIS.sadd(\"freeProxy:AfterVerifyOKhttp\", proxy) # print(\"INFO: Save this Proxy IP in freeProxy:AfterVerifyOKhttp\") with open(\"pass.txt\", \"a+\")", "连接redis数据库 POOL = redis.ConnectionPool(host='127.0.0.1', port=6379) CONN_REDIS = redis.Redis(connection_pool=POOL) # 取出一个ip进行测试 # proxy =", "jobs.append(threading.Thread(target=loop_test, args=(name,))) # 开启多线程 for t in jobs: t.start() for t in jobs:", "encoding=\"utf-8\") flag = test_http_proxy(proxy) if flag == True: # CONN_REDIS.sadd(\"freeProxy:AfterVerifyOKhttp\", proxy) # print(\"INFO:", "threading def http_task(): # 连接redis数据库 POOL = redis.ConnectionPool(host='127.0.0.1', port=6379) CONN_REDIS = redis.Redis(connection_pool=POOL) #", "print(\"INFO: Save this Proxy IP in freeProxy:AfterVerifyOKhttp\") with open(\"pass.txt\", \"a+\") as f: f.write(proxy", "return 1 def loop_test(name): print(\"*Start thread task %s\" % name) while True: result", "= CONN_REDIS.srandmember(\"freeProxy:AfterVerifyOKhttp\",1) # 判断redis中ip数量是否为空 if not ip: return 0 else: # print(\"INFO: Get", "print(\"INFO: Get proxy from Redis freeProxy:BeforeVerifyhttp list\") proxy = str(ip[0], encoding=\"utf-8\") flag =", "# 判断redis中ip数量是否为空 if not ip: return 0 else: # print(\"INFO: Get proxy from", "num = 8 for i in range(1, num+1): name = \"Thread-\" + str(i)", "for i in range(1, num+1): name = \"Thread-\" + str(i) jobs.append(threading.Thread(target=loop_test, args=(name,))) #", "as f: f.write(proxy + \"+/n\") print(\"Fail:\", proxy) return 1 def loop_test(name): print(\"*Start thread", "http_task(): # 连接redis数据库 POOL = redis.ConnectionPool(host='127.0.0.1', port=6379) CONN_REDIS = redis.Redis(connection_pool=POOL) # 取出一个ip进行测试 #", "= \"Thread-\" + str(i) jobs.append(threading.Thread(target=loop_test, args=(name,))) # 开启多线程 for t in jobs: t.start()", "ip: return 0 else: # print(\"INFO: Get proxy from Redis freeProxy:BeforeVerifyhttp list\") proxy", "print(\"\\n\") if result == 0: break if __name__ == \"__main__\": jobs = []", "str(ip[0], encoding=\"utf-8\") flag = test_http_proxy(proxy) if flag == True: # CONN_REDIS.sadd(\"freeProxy:AfterVerifyOKhttp\", proxy) #", "# CONN_REDIS.sadd(\"freeProxy:AfterVerifyOKhttp\", proxy) # print(\"INFO: Save this Proxy IP in freeProxy:AfterVerifyOKhttp\") with open(\"pass.txt\",", "test_http_proxy import threading def http_task(): # 连接redis数据库 POOL = redis.ConnectionPool(host='127.0.0.1', port=6379) CONN_REDIS =", "list\") proxy = str(ip[0], encoding=\"utf-8\") flag = test_http_proxy(proxy) if flag == True: #", "i in range(1, num+1): name = \"Thread-\" + str(i) jobs.append(threading.Thread(target=loop_test, args=(name,))) # 开启多线程", "redis.ConnectionPool(host='127.0.0.1', port=6379) CONN_REDIS = redis.Redis(connection_pool=POOL) # 取出一个ip进行测试 # proxy = CONN_REDIS.(\"freeProxy:AfterVerifyOKhttp\") ip =", "not ip: return 0 else: # print(\"INFO: Get proxy from Redis freeProxy:BeforeVerifyhttp list\")", "name) while True: result = http_task() print(\"\\n\") if result == 0: break if", "str(i) jobs.append(threading.Thread(target=loop_test, args=(name,))) # 开启多线程 for t in jobs: t.start() for t in", "redis.Redis(connection_pool=POOL) # 取出一个ip进行测试 # proxy = CONN_REDIS.(\"freeProxy:AfterVerifyOKhttp\") ip = CONN_REDIS.srandmember(\"freeProxy:AfterVerifyOKhttp\",1) # 判断redis中ip数量是否为空 if", "\"__main__\": jobs = [] num = 8 for i in range(1, num+1): name", "True: result = http_task() print(\"\\n\") if result == 0: break if __name__ ==", "= http_task() print(\"\\n\") if result == 0: break if __name__ == \"__main__\": jobs", "import test_http_proxy import threading def http_task(): # 连接redis数据库 POOL = redis.ConnectionPool(host='127.0.0.1', port=6379) CONN_REDIS", "result == 0: break if __name__ == \"__main__\": jobs = [] num =", "f: f.write(proxy + \"/n\") print(\"Pass:\", proxy) else: # CONN_REDIS.sadd(\"freeProxy_Bad:AfterVerifyFailhttp\", proxy) # print(\"INFO: Abandon", "CONN_REDIS.srandmember(\"freeProxy:AfterVerifyOKhttp\",1) # 判断redis中ip数量是否为空 if not ip: return 0 else: # print(\"INFO: Get proxy", "+ \"/n\") print(\"Pass:\", proxy) else: # CONN_REDIS.sadd(\"freeProxy_Bad:AfterVerifyFailhttp\", proxy) # print(\"INFO: Abandon this Proxy", "f: f.write(proxy + \"+/n\") print(\"Fail:\", proxy) return 1 def loop_test(name): print(\"*Start thread task", "if flag == True: # CONN_REDIS.sadd(\"freeProxy:AfterVerifyOKhttp\", proxy) # print(\"INFO: Save this Proxy IP", "# 取出一个ip进行测试 # proxy = CONN_REDIS.(\"freeProxy:AfterVerifyOKhttp\") ip = CONN_REDIS.srandmember(\"freeProxy:AfterVerifyOKhttp\",1) # 判断redis中ip数量是否为空 if not", "break if __name__ == \"__main__\": jobs = [] num = 8 for i", "= [] num = 8 for i in range(1, num+1): name = \"Thread-\"", "== \"__main__\": jobs = [] num = 8 for i in range(1, num+1):", "== 0: break if __name__ == \"__main__\": jobs = [] num = 8", "thread task %s\" % name) while True: result = http_task() print(\"\\n\") if result", "proxy = str(ip[0], encoding=\"utf-8\") flag = test_http_proxy(proxy) if flag == True: # CONN_REDIS.sadd(\"freeProxy:AfterVerifyOKhttp\",", "print(\"Fail:\", proxy) return 1 def loop_test(name): print(\"*Start thread task %s\" % name) while", "print(\"Pass:\", proxy) else: # CONN_REDIS.sadd(\"freeProxy_Bad:AfterVerifyFailhttp\", proxy) # print(\"INFO: Abandon this Proxy IP!\") with", "in freeProxy:AfterVerifyOKhttp\") with open(\"pass.txt\", \"a+\") as f: f.write(proxy + \"/n\") print(\"Pass:\", proxy) else:", "num+1): name = \"Thread-\" + str(i) jobs.append(threading.Thread(target=loop_test, args=(name,))) # 开启多线程 for t in", "with open(\"pass.txt\", \"a+\") as f: f.write(proxy + \"/n\") print(\"Pass:\", proxy) else: # CONN_REDIS.sadd(\"freeProxy_Bad:AfterVerifyFailhttp\",", "if not ip: return 0 else: # print(\"INFO: Get proxy from Redis freeProxy:BeforeVerifyhttp", "+ \"+/n\") print(\"Fail:\", proxy) return 1 def loop_test(name): print(\"*Start thread task %s\" %", "取出一个ip进行测试 # proxy = CONN_REDIS.(\"freeProxy:AfterVerifyOKhttp\") ip = CONN_REDIS.srandmember(\"freeProxy:AfterVerifyOKhttp\",1) # 判断redis中ip数量是否为空 if not ip:", "# proxy = CONN_REDIS.(\"freeProxy:AfterVerifyOKhttp\") ip = CONN_REDIS.srandmember(\"freeProxy:AfterVerifyOKhttp\",1) # 判断redis中ip数量是否为空 if not ip: return", "\"+/n\") print(\"Fail:\", proxy) return 1 def loop_test(name): print(\"*Start thread task %s\" % name)", "jobs = [] num = 8 for i in range(1, num+1): name =", "Abandon this Proxy IP!\") with open(\"fail.txt\", \"a+\") as f: f.write(proxy + \"+/n\") print(\"Fail:\",", "+ str(i) jobs.append(threading.Thread(target=loop_test, args=(name,))) # 开启多线程 for t in jobs: t.start() for t", "flag == True: # CONN_REDIS.sadd(\"freeProxy:AfterVerifyOKhttp\", proxy) # print(\"INFO: Save this Proxy IP in", "def http_task(): # 连接redis数据库 POOL = redis.ConnectionPool(host='127.0.0.1', port=6379) CONN_REDIS = redis.Redis(connection_pool=POOL) # 取出一个ip进行测试", "0: break if __name__ == \"__main__\": jobs = [] num = 8 for", "result = http_task() print(\"\\n\") if result == 0: break if __name__ == \"__main__\":", "in range(1, num+1): name = \"Thread-\" + str(i) jobs.append(threading.Thread(target=loop_test, args=(name,))) # 开启多线程 for", "Proxy IP in freeProxy:AfterVerifyOKhttp\") with open(\"pass.txt\", \"a+\") as f: f.write(proxy + \"/n\") print(\"Pass:\",", "range(1, num+1): name = \"Thread-\" + str(i) jobs.append(threading.Thread(target=loop_test, args=(name,))) # 开启多线程 for t", "IP!\") with open(\"fail.txt\", \"a+\") as f: f.write(proxy + \"+/n\") print(\"Fail:\", proxy) return 1", "\"a+\") as f: f.write(proxy + \"+/n\") print(\"Fail:\", proxy) return 1 def loop_test(name): print(\"*Start", "0 else: # print(\"INFO: Get proxy from Redis freeProxy:BeforeVerifyhttp list\") proxy = str(ip[0],", "args=(name,))) # 开启多线程 for t in jobs: t.start() for t in jobs: t.join()", "ip = CONN_REDIS.srandmember(\"freeProxy:AfterVerifyOKhttp\",1) # 判断redis中ip数量是否为空 if not ip: return 0 else: # print(\"INFO:", "this Proxy IP in freeProxy:AfterVerifyOKhttp\") with open(\"pass.txt\", \"a+\") as f: f.write(proxy + \"/n\")", "import redis from tools.common import test_http_proxy import threading def http_task(): # 连接redis数据库 POOL", "with open(\"fail.txt\", \"a+\") as f: f.write(proxy + \"+/n\") print(\"Fail:\", proxy) return 1 def", "else: # CONN_REDIS.sadd(\"freeProxy_Bad:AfterVerifyFailhttp\", proxy) # print(\"INFO: Abandon this Proxy IP!\") with open(\"fail.txt\", \"a+\")", "tools.common import test_http_proxy import threading def http_task(): # 连接redis数据库 POOL = redis.ConnectionPool(host='127.0.0.1', port=6379)", "POOL = redis.ConnectionPool(host='127.0.0.1', port=6379) CONN_REDIS = redis.Redis(connection_pool=POOL) # 取出一个ip进行测试 # proxy = CONN_REDIS.(\"freeProxy:AfterVerifyOKhttp\")", "1 def loop_test(name): print(\"*Start thread task %s\" % name) while True: result =", "task %s\" % name) while True: result = http_task() print(\"\\n\") if result ==", "else: # print(\"INFO: Get proxy from Redis freeProxy:BeforeVerifyhttp list\") proxy = str(ip[0], encoding=\"utf-8\")", "port=6379) CONN_REDIS = redis.Redis(connection_pool=POOL) # 取出一个ip进行测试 # proxy = CONN_REDIS.(\"freeProxy:AfterVerifyOKhttp\") ip = CONN_REDIS.srandmember(\"freeProxy:AfterVerifyOKhttp\",1)", "open(\"fail.txt\", \"a+\") as f: f.write(proxy + \"+/n\") print(\"Fail:\", proxy) return 1 def loop_test(name):", "# print(\"INFO: Get proxy from Redis freeProxy:BeforeVerifyhttp list\") proxy = str(ip[0], encoding=\"utf-8\") flag", "http_task() print(\"\\n\") if result == 0: break if __name__ == \"__main__\": jobs =", "proxy) else: # CONN_REDIS.sadd(\"freeProxy_Bad:AfterVerifyFailhttp\", proxy) # print(\"INFO: Abandon this Proxy IP!\") with open(\"fail.txt\",", "redis from tools.common import test_http_proxy import threading def http_task(): # 连接redis数据库 POOL =", "test_http_proxy(proxy) if flag == True: # CONN_REDIS.sadd(\"freeProxy:AfterVerifyOKhttp\", proxy) # print(\"INFO: Save this Proxy", "CONN_REDIS.sadd(\"freeProxy_Bad:AfterVerifyFailhttp\", proxy) # print(\"INFO: Abandon this Proxy IP!\") with open(\"fail.txt\", \"a+\") as f:", "= CONN_REDIS.(\"freeProxy:AfterVerifyOKhttp\") ip = CONN_REDIS.srandmember(\"freeProxy:AfterVerifyOKhttp\",1) # 判断redis中ip数量是否为空 if not ip: return 0 else:", "Save this Proxy IP in freeProxy:AfterVerifyOKhttp\") with open(\"pass.txt\", \"a+\") as f: f.write(proxy +", "loop_test(name): print(\"*Start thread task %s\" % name) while True: result = http_task() print(\"\\n\")", "8 for i in range(1, num+1): name = \"Thread-\" + str(i) jobs.append(threading.Thread(target=loop_test, args=(name,)))", "IP in freeProxy:AfterVerifyOKhttp\") with open(\"pass.txt\", \"a+\") as f: f.write(proxy + \"/n\") print(\"Pass:\", proxy)", "from Redis freeProxy:BeforeVerifyhttp list\") proxy = str(ip[0], encoding=\"utf-8\") flag = test_http_proxy(proxy) if flag", "from tools.common import test_http_proxy import threading def http_task(): # 连接redis数据库 POOL = redis.ConnectionPool(host='127.0.0.1',", "return 0 else: # print(\"INFO: Get proxy from Redis freeProxy:BeforeVerifyhttp list\") proxy =", "# 连接redis数据库 POOL = redis.ConnectionPool(host='127.0.0.1', port=6379) CONN_REDIS = redis.Redis(connection_pool=POOL) # 取出一个ip进行测试 # proxy", "flag = test_http_proxy(proxy) if flag == True: # CONN_REDIS.sadd(\"freeProxy:AfterVerifyOKhttp\", proxy) # print(\"INFO: Save", "= redis.ConnectionPool(host='127.0.0.1', port=6379) CONN_REDIS = redis.Redis(connection_pool=POOL) # 取出一个ip进行测试 # proxy = CONN_REDIS.(\"freeProxy:AfterVerifyOKhttp\") ip", "proxy) # print(\"INFO: Save this Proxy IP in freeProxy:AfterVerifyOKhttp\") with open(\"pass.txt\", \"a+\") as", "Redis freeProxy:BeforeVerifyhttp list\") proxy = str(ip[0], encoding=\"utf-8\") flag = test_http_proxy(proxy) if flag ==", "Proxy IP!\") with open(\"fail.txt\", \"a+\") as f: f.write(proxy + \"+/n\") print(\"Fail:\", proxy) return", "if __name__ == \"__main__\": jobs = [] num = 8 for i in", "this Proxy IP!\") with open(\"fail.txt\", \"a+\") as f: f.write(proxy + \"+/n\") print(\"Fail:\", proxy)", "Get proxy from Redis freeProxy:BeforeVerifyhttp list\") proxy = str(ip[0], encoding=\"utf-8\") flag = test_http_proxy(proxy)", "# print(\"INFO: Save this Proxy IP in freeProxy:AfterVerifyOKhttp\") with open(\"pass.txt\", \"a+\") as f:", "open(\"pass.txt\", \"a+\") as f: f.write(proxy + \"/n\") print(\"Pass:\", proxy) else: # CONN_REDIS.sadd(\"freeProxy_Bad:AfterVerifyFailhttp\", proxy)", "% name) while True: result = http_task() print(\"\\n\") if result == 0: break", "\"a+\") as f: f.write(proxy + \"/n\") print(\"Pass:\", proxy) else: # CONN_REDIS.sadd(\"freeProxy_Bad:AfterVerifyFailhttp\", proxy) #", "f.write(proxy + \"+/n\") print(\"Fail:\", proxy) return 1 def loop_test(name): print(\"*Start thread task %s\"", "freeProxy:AfterVerifyOKhttp\") with open(\"pass.txt\", \"a+\") as f: f.write(proxy + \"/n\") print(\"Pass:\", proxy) else: #", "as f: f.write(proxy + \"/n\") print(\"Pass:\", proxy) else: # CONN_REDIS.sadd(\"freeProxy_Bad:AfterVerifyFailhttp\", proxy) # print(\"INFO:", "proxy) # print(\"INFO: Abandon this Proxy IP!\") with open(\"fail.txt\", \"a+\") as f: f.write(proxy", "判断redis中ip数量是否为空 if not ip: return 0 else: # print(\"INFO: Get proxy from Redis", "= str(ip[0], encoding=\"utf-8\") flag = test_http_proxy(proxy) if flag == True: # CONN_REDIS.sadd(\"freeProxy:AfterVerifyOKhttp\", proxy)", "name = \"Thread-\" + str(i) jobs.append(threading.Thread(target=loop_test, args=(name,))) # 开启多线程 for t in jobs:", "freeProxy:BeforeVerifyhttp list\") proxy = str(ip[0], encoding=\"utf-8\") flag = test_http_proxy(proxy) if flag == True:", "CONN_REDIS.(\"freeProxy:AfterVerifyOKhttp\") ip = CONN_REDIS.srandmember(\"freeProxy:AfterVerifyOKhttp\",1) # 判断redis中ip数量是否为空 if not ip: return 0 else: #", "\"/n\") print(\"Pass:\", proxy) else: # CONN_REDIS.sadd(\"freeProxy_Bad:AfterVerifyFailhttp\", proxy) # print(\"INFO: Abandon this Proxy IP!\")", "%s\" % name) while True: result = http_task() print(\"\\n\") if result == 0:", "= test_http_proxy(proxy) if flag == True: # CONN_REDIS.sadd(\"freeProxy:AfterVerifyOKhttp\", proxy) # print(\"INFO: Save this", "f.write(proxy + \"/n\") print(\"Pass:\", proxy) else: # CONN_REDIS.sadd(\"freeProxy_Bad:AfterVerifyFailhttp\", proxy) # print(\"INFO: Abandon this" ]
[ "= create_polygon(elem[0], elem[1], elem[2], elem[3]) if check_polygon_intersection(p1, p2): zero_distance.append(j) new_y = min(y, elem[1])", "Params L = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' CHAR_THRESHOLD = 3 LINE_WIDTH = 2 LINE_COLOR = (0,", "in range(n): if i not in used_ind: to_be_merged = list() boxe1 = boxes_list[i]", "elem[1] + elem[3]) - min(y, elem[1]) new_elem = [0, new_y, Xmax, new_h] boxes_list[j]=new_elem", "y_middle, In case a hole section is not detected. \"\"\" y_new = min(y_middle,", "h), (0, 255, 0), 1) cv2.line(img, (0 , 0),(0, Ymax) ,LINE_COLOR, 5) cv2.line(img,", "i in range(n_boxes): if filter_boxes(image_to_data, i) : (x, y, w, h) = (image_to_data['left'][i],", "y+h ), (Xmax + w, y + h), (0, 255, 0), 1) cv2.rectangle(img,", "for l in elem1: if l in elem2: return True return False ##", "boxes_list[j] p2 = create_polygon(elem[0], elem[1], elem[2], elem[3]) if check_polygon_intersection(p1, p2): zero_distance.append(j) new_y =", "line over a word, we will set a threshold to y_middle, In case", "= len(small_list) new_y = min([boxe[1] for boxe in small_list]) new_h = max([boxe[1] +", "= min(y, elem[1]) new_h = max(y+h, elem[1] + elem[3]) - min(y, elem[1]) new_elem", "n_boxes = len(image_to_data) for i in range(n_boxes-1): \"\"\" For each line, we will", "new_elem = [0, y, Xmax, h] boxes_list.append(new_elem) return boxes_list def clean_loop(boxes_list): Xmax =", "h)]) return p def filter_boxes(image_to_data, ind): text = image_to_data[\"text\"][ind] h = image_to_data[\"height\"][ind] w", "= list() for j in range(n_b): elem = boxes_list[j] p2 = create_polygon(elem[0], elem[1],", "boxes_list def clean_loop(boxes_list): Xmax = boxes_list[1][2] n = len(boxes_list) global_flag = 0 all_to_be_merged", "extracted boxes def check_polygon_intersection(p1, p2): if p1.distance(p2) == 0 : return True return", "e.g c:\\Tesseract-OCR\\tesseract \" import sys from os import chdir, listdir from os.path import", "boxes_list[j]=new_elem flag = 1 if flag == 0 : new_elem = [0, y,", "list() boxes_list.append([0, 0, 0, 0]) all_zero_distance = list() n_boxes = len(image_to_data['level']) \"\"\" A", "(0 , y +h +5 ),(Xmax, y +h +5) ,(0, 0, 0), 3)", "y + h)]) return p def filter_boxes(image_to_data, ind): text = image_to_data[\"text\"][ind] h =", "new_elem = [0, new_y, Xmax, new_h] new_boxes_list.append(new_elem) return new_boxes_list def process_table(img_path,draw_path): #try: image_to_data,", "y + h), LINE_COLOR, LINE_WIDTH) \"\"\" cv2.line(img, (0 , 0),(0, Ymax) ,(0, 0,", "x + w, y + h), (0, 255, 0), 1) cv2.line(img, (0 ,", "cv2.line(img, (0, Ymax),(Xmax, Ymax) ,LINE_COLOR, 5) cv2.line(img, (Xmax , 0),(Xmax, Ymax) ,LINE_COLOR, 5)", "= [0, new_y, Xmax, new_h] boxes_list[j]=new_elem flag = 1 if flag == 0", "to_be_merged = list() boxe1 = boxes_list[i] p1 = create_polygon(boxe1[0],boxe1[1],boxe1[2],boxe1[3]) m = len(boxes_list) for", "LINE_WIDTH) #cv2.line(img, (0 , y+h ), (Xmax + w, y + h), (0,", "flag = 0 zero_distance = list() for j in range(n_b): elem = boxes_list[j]", "3) #cv2.line(img, (0 , y+h ), (Xmax + w, y + h), (0,", "img) def process_path(file_path,draw_path): all_files = listdir(file_path) n = len(all_files) for i in range(n):", "len(all_files) for i in range(n): f = all_files[i] img_path = join(file_path, f) process_table(img_path,draw_path)", "y_middle = (y+h+y_next)//2 \"\"\" To avoid the case of drawin a line over", "not detected. \"\"\" y_new = min(y_middle, y+h+margin) cv2.line(img, (x , y_new),(w, y_new) ,LINE_COLOR,", "len(boxes_list) flag = 0 zero_distance = list() for j in range(n_b): elem =", "= img.shape[1] Ymax = img.shape[0] n_boxes = len(image_to_data) for i in range(n_boxes-1): \"\"\"", "j in range(n_b): elem = boxes_list[j] p2 = create_polygon(elem[0], elem[1], elem[2], elem[3]) if", "import sys from os import chdir, listdir from os.path import join ## Hyper", "line and the next line top \"\"\" (x, y, w, h) = (image_to_data[i][0],", "Ymax) ,LINE_COLOR, 5) #cv2.namedWindow(\"output\", cv2.WINDOW_NORMAL) #cv2.imshow('output', img) return img def check_intersection(elem1, elem2): for", "list() used_ind = list() for i in range(n): if i not in used_ind:", "5) cv2.line(img, (Xmax , 0),(Xmax, Ymax) ,LINE_COLOR, 5) #cv2.namedWindow(\"output\", cv2.WINDOW_NORMAL) #cv2.imshow('output', img) return", "process_path(file_path,draw_path): all_files = listdir(file_path) n = len(all_files) for i in range(n): f =", "the line and the next line top \"\"\" (x, y, w, h) =", "1) cv2.rectangle(img, (x, y), ( x + w, y + h), LINE_COLOR, LINE_WIDTH)", "will draw a line between the bottom of the line and the next", "5) cv2.line(img, (0 , 0),(Xmax, 0) ,(0, 0, 0), 5) cv2.line(img, (0, Ymax),(Xmax,", "image_to_data[i][3]) y_next = image_to_data[i+1][1] y_middle = (y+h+y_next)//2 \"\"\" To avoid the case of", "return boxes_list def clean_loop(boxes_list): Xmax = boxes_list[1][2] n = len(boxes_list) global_flag = 0", "h): p = Polygon([(x, y),(x+w, y),(x+w, y + h),(x, y + h)]) return", "boxes_list = list() boxes_list.append([0, 0, 0, 0]) all_zero_distance = list() n_boxes = len(image_to_data['level'])", "image_to_data = process_image_to_data(image_to_data, Xmax, Ymax) image_to_data = clean_loop(image_to_data) img = draw_lines(img_path, image_to_data, margin", "first loop to merge close boxes \"\"\" for i in range(n_boxes): if filter_boxes(image_to_data,", "list() for i in range(n): if i not in used_ind: to_be_merged = list()", "from os import chdir, listdir from os.path import join ## Hyper Params L", "for j in range(n_b): elem = boxes_list[j] p2 = create_polygon(elem[0], elem[1], elem[2], elem[3])", "(Xmax + w, y + h), (0, 255, 0), 1) cv2.rectangle(img, (x, y),", "p1 = create_polygon(boxe1[0],boxe1[1],boxe1[2],boxe1[3]) m = len(boxes_list) for j in range(m): if j not", "used_ind.append(j) all_to_be_merged.append(to_be_merged) n_detected = len(all_to_be_merged) new_boxes_list = list() for i in range(n_detected): small_list", "used_ind: boxe2=boxes_list[j] p2 = create_polygon(boxe2[0],boxe2[1],boxe2[2],boxe2[3]) if check_polygon_intersection(p1, p2): to_be_merged.append(boxe2) used_ind.append(j) all_to_be_merged.append(to_be_merged) n_detected =", "Algo def get_image_data(img_path): img = cv2.imread(img_path) image_to_data = pytesseract.image_to_data(img, output_type=Output.DICT) Xmax = img.shape[1]", "= get_image_data(img_path) image_to_data = process_image_to_data(image_to_data, Xmax, Ymax) image_to_data = clean_loop(image_to_data) img = draw_lines(img_path,", "Polygon([(x, y),(x+w, y),(x+w, y + h),(x, y + h)]) return p def filter_boxes(image_to_data,", "+5 ),(Xmax, y +h +5) ,(0, 0, 0), 3) #cv2.line(img, (0 , y+h", "range(n_b): elem = boxes_list[j] p2 = create_polygon(elem[0], elem[1], elem[2], elem[3]) if check_polygon_intersection(p1, p2):", "0, 0) ## Algo def get_image_data(img_path): img = cv2.imread(img_path) image_to_data = pytesseract.image_to_data(img, output_type=Output.DICT)", "= list() boxe1 = boxes_list[i] p1 = create_polygon(boxe1[0],boxe1[1],boxe1[2],boxe1[3]) m = len(boxes_list) for j", "w, y + h), (0, 255, 0), 1) #cv2.rectangle(img, (x, y), ( x", "detected. \"\"\" y_new = min(y_middle, y+h+margin) cv2.line(img, (x , y_new),(w, y_new) ,LINE_COLOR, LINE_WIDTH)", "next line top \"\"\" (x, y, w, h) = (image_to_data[i][0], image_to_data[i][1], image_to_data[i][2], image_to_data[i][3])", "return True return False def create_polygon(x, y, w, h): p = Polygon([(x, y),(x+w,", "cv2.line(img, (Xmax , 0),(Xmax, Ymax) ,LINE_COLOR, 5) #cv2.namedWindow(\"output\", cv2.WINDOW_NORMAL) #cv2.imshow('output', img) return img", "y + h), (0, 255, 0), 1) #cv2.rectangle(img, (x, y), ( x +", "import Output import cv2 import os from shapely.geometry import Polygon pytesseract.pytesseract.tesseract_cmd = \"Tesseract", "n = len(boxes_list) global_flag = 0 all_to_be_merged = list() used_ind = list() for", "extracted and filtred boxes \"\"\" img = cv2.imread(img_path) Xmax = img.shape[1] Ymax =", "255, 0), 1) #cv2.rectangle(img, (x, y), ( x + w, y + h),", "0) ,LINE_COLOR, 5) cv2.line(img, (0, Ymax),(Xmax, Ymax) ,LINE_COLOR, 5) cv2.line(img, (Xmax , 0),(Xmax,", "y_new = min(y_middle, y+h+margin) cv2.line(img, (x , y_new),(w, y_new) ,LINE_COLOR, LINE_WIDTH) #cv2.line(img, (0", "y),(x+w, y + h),(x, y + h)]) return p def filter_boxes(image_to_data, ind): text", "os.path import join ## Hyper Params L = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' CHAR_THRESHOLD = 3 LINE_WIDTH", "top \"\"\" (x, y, w, h) = (image_to_data[i][0], image_to_data[i][1], image_to_data[i][2], image_to_data[i][3]) y_next =", "Xmax = img.shape[1] Ymax = img.shape[0] return image_to_data, Xmax, Ymax def draw_lines_v1(img_path, image_to_data):", "global_flag = 0 all_to_be_merged = list() used_ind = list() for i in range(n):", "= 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' CHAR_THRESHOLD = 3 LINE_WIDTH = 2 LINE_COLOR = (0, 0, 0)", "\"\"\" To avoid the case of drawin a line over a word, we", "h) n_b = len(boxes_list) flag = 0 zero_distance = list() for j in", "= 0 all_to_be_merged = list() used_ind = list() for i in range(n): if", "i) : (y, h) = (image_to_data['top'][i], image_to_data['height'][i]) p1 = create_polygon(0, y, Xmax, h)", "a threshold to y_middle, In case a hole section is not detected. \"\"\"", "0 zero_distance = list() for j in range(n_b): elem = boxes_list[j] p2 =", "5) cv2.line(img, (Xmax , 0),(Xmax, Ymax) ,(0, 0, 0), 5) \"\"\" cv2.namedWindow(\"output2\", cv2.WINDOW_NORMAL)", "'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' CHAR_THRESHOLD = 3 LINE_WIDTH = 2 LINE_COLOR = (0, 0, 0) ##", "join ## Hyper Params L = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' CHAR_THRESHOLD = 3 LINE_WIDTH = 2", "for i in range(n_boxes): if filter_boxes(image_to_data, i) : (x, y, w, h) =", "cv2.line(img, (0 , 0),(0, Ymax) ,(0, 0, 0), 5) cv2.line(img, (0 , 0),(Xmax,", "(0 , 0),(0, Ymax) ,(0, 0, 0), 5) cv2.line(img, (0 , 0),(Xmax, 0)", "the case of drawin a line over a word, we will set a", "False def create_polygon(x, y, w, h): p = Polygon([(x, y),(x+w, y),(x+w, y +", "0, 0]) all_zero_distance = list() n_boxes = len(image_to_data['level']) \"\"\" A first loop to", "w, y + h), (0, 255, 0), 1) cv2.rectangle(img, (x, y), ( x", "all_zero_distance = list() n_boxes = len(image_to_data['level']) \"\"\" A first loop to merge close", "new_h = max([boxe[1] + boxe[3] - new_y for boxe in small_list]) new_elem =", "elem1: if l in elem2: return True return False ## Processing extracted boxes", "+ h)]) return p def filter_boxes(image_to_data, ind): text = image_to_data[\"text\"][ind] h = image_to_data[\"height\"][ind]", "[0, y, Xmax, h] boxes_list.append(new_elem) return boxes_list def clean_loop(boxes_list): Xmax = boxes_list[1][2] n", "#cv2.rectangle(img, (x, y), ( x + w, y + h), (0, 255, 0),", "Ymax) ,(0, 0, 0), 5) cv2.line(img, (0 , 0),(Xmax, 0) ,(0, 0, 0),", "x + w, y + h), LINE_COLOR, LINE_WIDTH) \"\"\" cv2.line(img, (0 , 0),(0,", "i) : (x, y, w, h) = (image_to_data['left'][i], image_to_data['top'][i], image_to_data['width'][i], image_to_data['height'][i]) #cv2.line(img, (0", "cv2.imread(img_path) Xmax = img.shape[1] n_boxes = len(image_to_data['level']) for i in range(n_boxes): if filter_boxes(image_to_data,", "check_polygon_intersection(p1, p2): if p1.distance(p2) == 0 : return True return False def create_polygon(x,", "if filter_boxes(image_to_data, i) : (y, h) = (image_to_data['top'][i], image_to_data['height'][i]) p1 = create_polygon(0, y,", "(x, y, w, h) = (image_to_data['left'][i], image_to_data['top'][i], image_to_data['width'][i], image_to_data['height'][i]) #cv2.line(img, (0 , y", "+ w, y + h), (0, 255, 0), 1) cv2.line(img, (0 , 0),(0,", "not in used_ind: to_be_merged = list() boxe1 = boxes_list[i] p1 = create_polygon(boxe1[0],boxe1[1],boxe1[2],boxe1[3]) m", "ind): text = image_to_data[\"text\"][ind] h = image_to_data[\"height\"][ind] w = image_to_data[\"width\"][ind] if len(text) >", "= create_polygon(boxe1[0],boxe1[1],boxe1[2],boxe1[3]) m = len(boxes_list) for j in range(m): if j not in", "\"\"\" (x, y, w, h) = (image_to_data[i][0], image_to_data[i][1], image_to_data[i][2], image_to_data[i][3]) y_next = image_to_data[i+1][1]", "0), 1) #cv2.rectangle(img, (x, y), ( x + w, y + h), (0,", "= image_to_data[\"height\"][ind] w = image_to_data[\"width\"][ind] if len(text) > CHAR_THRESHOLD and w > h:", "(Xmax + w, y + h), (0, 255, 0), 1) #cv2.rectangle(img, (x, y),", "zero_distance.append(j) new_y = min(y, elem[1]) new_h = max(y+h, elem[1] + elem[3]) - min(y,", "= all_to_be_merged[i] p = len(small_list) new_y = min([boxe[1] for boxe in small_list]) new_h", "for boxe in small_list]) new_h = max([boxe[1] + boxe[3] - new_y for boxe", "= img.shape[0] n_boxes = len(image_to_data) for i in range(n_boxes-1): \"\"\" For each line,", "image_to_data['height'][i]) #cv2.line(img, (0 , y +h +5 ),(Xmax, y +h +5) ,(0, 0,", "elem[1]) new_h = max(y+h, elem[1] + elem[3]) - min(y, elem[1]) new_elem = [0,", ",LINE_COLOR, 5) cv2.line(img, (Xmax , 0),(Xmax, Ymax) ,LINE_COLOR, 5) #cv2.namedWindow(\"output\", cv2.WINDOW_NORMAL) #cv2.imshow('output', img)", "create_polygon(elem[0], elem[1], elem[2], elem[3]) if check_polygon_intersection(p1, p2): zero_distance.append(j) new_y = min(y, elem[1]) new_h", "),(Xmax, y +h +5) ,(0, 0, 0), 3) #cv2.line(img, (0 , y+h ),", "(x, y), ( x + w, y + h), (0, 255, 0), 1)", "0): \"\"\" Draw extracted and filtred boxes \"\"\" img = cv2.imread(img_path) Xmax =", "drawin a line over a word, we will set a threshold to y_middle,", "CHAR_THRESHOLD and w > h: return True return False def process_image_to_data(image_to_data, Xmax, Ymax):", "if check_polygon_intersection(p1, p2): zero_distance.append(j) new_y = min(y, elem[1]) new_h = max(y+h, elem[1] +", "cv2.imwrite(processed_im_path, img) def process_path(file_path,draw_path): all_files = listdir(file_path) n = len(all_files) for i in", "list() n_boxes = len(image_to_data['level']) \"\"\" A first loop to merge close boxes \"\"\"", "w, h) = (image_to_data['left'][i], image_to_data['top'][i], image_to_data['width'][i], image_to_data['height'][i]) #cv2.line(img, (0 , y +h +5", "import os from shapely.geometry import Polygon pytesseract.pytesseract.tesseract_cmd = \"Tesseract path e.g c:\\Tesseract-OCR\\tesseract \"", "(image_to_data[i][0], image_to_data[i][1], image_to_data[i][2], image_to_data[i][3]) y_next = image_to_data[i+1][1] y_middle = (y+h+y_next)//2 \"\"\" To avoid", "we will set a threshold to y_middle, In case a hole section is", ", 0),(0, Ymax) ,LINE_COLOR, 5) cv2.line(img, (0 , 0),(Xmax, 0) ,LINE_COLOR, 5) cv2.line(img,", "Ymax) ,LINE_COLOR, 5) cv2.line(img, (Xmax , 0),(Xmax, Ymax) ,LINE_COLOR, 5) #cv2.namedWindow(\"output\", cv2.WINDOW_NORMAL) #cv2.imshow('output',", "= 1 if flag == 0 : new_elem = [0, y, Xmax, h]", "False def process_image_to_data(image_to_data, Xmax, Ymax): boxes_list = list() boxes_list.append([0, 0, 0, 0]) all_zero_distance", "return True return False ## Processing extracted boxes def check_polygon_intersection(p1, p2): if p1.distance(p2)", "## Algo def get_image_data(img_path): img = cv2.imread(img_path) image_to_data = pytesseract.image_to_data(img, output_type=Output.DICT) Xmax =", ": new_elem = [0, y, Xmax, h] boxes_list.append(new_elem) return boxes_list def clean_loop(boxes_list): Xmax", "in range(n_boxes): if filter_boxes(image_to_data, i) : (x, y, w, h) = (image_to_data['left'][i], image_to_data['top'][i],", "boxes \"\"\" for i in range(n_boxes): if filter_boxes(image_to_data, i) : (y, h) =", "img) return img def check_intersection(elem1, elem2): for l in elem1: if l in", "p2 = create_polygon(elem[0], elem[1], elem[2], elem[3]) if check_polygon_intersection(p1, p2): zero_distance.append(j) new_y = min(y,", "= list() for i in range(n): if i not in used_ind: to_be_merged =", "a hole section is not detected. \"\"\" y_new = min(y_middle, y+h+margin) cv2.line(img, (x", "= list() for i in range(n_detected): small_list = all_to_be_merged[i] p = len(small_list) new_y", "boxe[3] - new_y for boxe in small_list]) new_elem = [0, new_y, Xmax, new_h]", "LINE_COLOR = (0, 0, 0) ## Algo def get_image_data(img_path): img = cv2.imread(img_path) image_to_data", "0) ,(0, 0, 0), 5) cv2.line(img, (0, Ymax),(Xmax, Ymax) ,(0, 0, 0), 5)", "\" import sys from os import chdir, listdir from os.path import join ##", ", 0),(0, Ymax) ,(0, 0, 0), 5) cv2.line(img, (0 , 0),(Xmax, 0) ,(0,", "y+h ), (Xmax + w, y + h), (0, 255, 0), 1) #cv2.rectangle(img,", "(0, 0, 0) ## Algo def get_image_data(img_path): img = cv2.imread(img_path) image_to_data = pytesseract.image_to_data(img,", "in elem2: return True return False ## Processing extracted boxes def check_polygon_intersection(p1, p2):", ",(0, 0, 0), 5) cv2.line(img, (0, Ymax),(Xmax, Ymax) ,(0, 0, 0), 5) cv2.line(img,", "new_y, Xmax, new_h] boxes_list[j]=new_elem flag = 1 if flag == 0 : new_elem", "all_files = listdir(file_path) n = len(all_files) for i in range(n): f = all_files[i]", "0), 5) cv2.line(img, (0, Ymax),(Xmax, Ymax) ,(0, 0, 0), 5) cv2.line(img, (Xmax ,", "In case a hole section is not detected. \"\"\" y_new = min(y_middle, y+h+margin)", "p = Polygon([(x, y),(x+w, y),(x+w, y + h),(x, y + h)]) return p", "img.shape[0] return image_to_data, Xmax, Ymax def draw_lines_v1(img_path, image_to_data): img = cv2.imread(img_path) Xmax =", "elem[1]) new_elem = [0, new_y, Xmax, new_h] boxes_list[j]=new_elem flag = 1 if flag", "n = len(all_files) for i in range(n): f = all_files[i] img_path = join(file_path,", "255, 0), 1) cv2.line(img, (0 , 0),(0, Ymax) ,LINE_COLOR, 5) cv2.line(img, (0 ,", "len(image_to_data['level']) for i in range(n_boxes): if filter_boxes(image_to_data, i) : (x, y, w, h)", "len(small_list) new_y = min([boxe[1] for boxe in small_list]) new_h = max([boxe[1] + boxe[3]", "h), LINE_COLOR, LINE_WIDTH) \"\"\" cv2.line(img, (0 , 0),(0, Ymax) ,(0, 0, 0), 5)", "+ elem[3]) - min(y, elem[1]) new_elem = [0, new_y, Xmax, new_h] boxes_list[j]=new_elem flag", "= clean_loop(image_to_data) img = draw_lines(img_path, image_to_data, margin =2) image_name = os.path.basename(img_path).split(os.extsep)[0].replace(\" \", \"_\")", "to merge close boxes \"\"\" for i in range(n_boxes): if filter_boxes(image_to_data, i) :", "0 : return True return False def create_polygon(x, y, w, h): p =", "set a threshold to y_middle, In case a hole section is not detected.", "new_h] new_boxes_list.append(new_elem) return new_boxes_list def process_table(img_path,draw_path): #try: image_to_data, Xmax, Ymax = get_image_data(img_path) image_to_data", "len(boxes_list) global_flag = 0 all_to_be_merged = list() used_ind = list() for i in", "draw_lines_v1(img_path, image_to_data): img = cv2.imread(img_path) Xmax = img.shape[1] n_boxes = len(image_to_data['level']) for i", "To avoid the case of drawin a line over a word, we will", "+ boxe[3] - new_y for boxe in small_list]) new_elem = [0, new_y, Xmax,", "sys from os import chdir, listdir from os.path import join ## Hyper Params", "0),(Xmax, Ymax) ,LINE_COLOR, 5) #cv2.namedWindow(\"output\", cv2.WINDOW_NORMAL) #cv2.imshow('output', img) return img def check_intersection(elem1, elem2):", "the bottom of the line and the next line top \"\"\" (x, y,", "margin = 0): \"\"\" Draw extracted and filtred boxes \"\"\" img = cv2.imread(img_path)", "in range(m): if j not in used_ind: boxe2=boxes_list[j] p2 = create_polygon(boxe2[0],boxe2[1],boxe2[2],boxe2[3]) if check_polygon_intersection(p1,", "is not detected. \"\"\" y_new = min(y_middle, y+h+margin) cv2.line(img, (x , y_new),(w, y_new)", "in range(n_detected): small_list = all_to_be_merged[i] p = len(small_list) new_y = min([boxe[1] for boxe", "if check_polygon_intersection(p1, p2): to_be_merged.append(boxe2) used_ind.append(j) all_to_be_merged.append(to_be_merged) n_detected = len(all_to_be_merged) new_boxes_list = list() for", "of the line and the next line top \"\"\" (x, y, w, h)", "def clean_loop(boxes_list): Xmax = boxes_list[1][2] n = len(boxes_list) global_flag = 0 all_to_be_merged =", "h) = (image_to_data[i][0], image_to_data[i][1], image_to_data[i][2], image_to_data[i][3]) y_next = image_to_data[i+1][1] y_middle = (y+h+y_next)//2 \"\"\"", "will set a threshold to y_middle, In case a hole section is not", "w, h): p = Polygon([(x, y),(x+w, y),(x+w, y + h),(x, y + h)])", "Output import cv2 import os from shapely.geometry import Polygon pytesseract.pytesseract.tesseract_cmd = \"Tesseract path", "m = len(boxes_list) for j in range(m): if j not in used_ind: boxe2=boxes_list[j]", "h] boxes_list.append(new_elem) return boxes_list def clean_loop(boxes_list): Xmax = boxes_list[1][2] n = len(boxes_list) global_flag", "(0 , 0),(Xmax, 0) ,(0, 0, 0), 5) cv2.line(img, (0, Ymax),(Xmax, Ymax) ,(0,", "\"\"\" cv2.namedWindow(\"output2\", cv2.WINDOW_NORMAL) cv2.imshow('output2', img) def draw_lines(img_path, image_to_data, margin = 0): \"\"\" Draw", "range(n_boxes-1): \"\"\" For each line, we will draw a line between the bottom", "1) #cv2.rectangle(img, (x, y), ( x + w, y + h), (0, 255,", "os import chdir, listdir from os.path import join ## Hyper Params L =", "h),(x, y + h)]) return p def filter_boxes(image_to_data, ind): text = image_to_data[\"text\"][ind] h", "= max([boxe[1] + boxe[3] - new_y for boxe in small_list]) new_elem = [0,", "Ymax) image_to_data = clean_loop(image_to_data) img = draw_lines(img_path, image_to_data, margin =2) image_name = os.path.basename(img_path).split(os.extsep)[0].replace(\"", "(x, y), ( x + w, y + h), LINE_COLOR, LINE_WIDTH) \"\"\" cv2.line(img,", "y, w, h) = (image_to_data[i][0], image_to_data[i][1], image_to_data[i][2], image_to_data[i][3]) y_next = image_to_data[i+1][1] y_middle =", "y + h), (0, 255, 0), 1) cv2.rectangle(img, (x, y), ( x +", "0), 5) \"\"\" cv2.namedWindow(\"output2\", cv2.WINDOW_NORMAL) cv2.imshow('output2', img) def draw_lines(img_path, image_to_data, margin = 0):", "boxes_list.append(new_elem) return boxes_list def clean_loop(boxes_list): Xmax = boxes_list[1][2] n = len(boxes_list) global_flag =", ", 0),(Xmax, Ymax) ,(0, 0, 0), 5) \"\"\" cv2.namedWindow(\"output2\", cv2.WINDOW_NORMAL) cv2.imshow('output2', img) def", "Xmax, Ymax = get_image_data(img_path) image_to_data = process_image_to_data(image_to_data, Xmax, Ymax) image_to_data = clean_loop(image_to_data) img", "+ h), (0, 255, 0), 1) cv2.rectangle(img, (x, y), ( x + w,", "(image_to_data['top'][i], image_to_data['height'][i]) p1 = create_polygon(0, y, Xmax, h) n_b = len(boxes_list) flag =", "pytesseract.image_to_data(img, output_type=Output.DICT) Xmax = img.shape[1] Ymax = img.shape[0] return image_to_data, Xmax, Ymax def", "merge close boxes \"\"\" for i in range(n_boxes): if filter_boxes(image_to_data, i) : (y,", "bottom of the line and the next line top \"\"\" (x, y, w,", "os.path.basename(img_path).split(os.extsep)[0].replace(\" \", \"_\") processed_im_path = draw_path+\"\\\\\"+image_name+'pro.png' cv2.imwrite(processed_im_path, img) def process_path(file_path,draw_path): all_files = listdir(file_path)", "Ymax): boxes_list = list() boxes_list.append([0, 0, 0, 0]) all_zero_distance = list() n_boxes =", "= 3 LINE_WIDTH = 2 LINE_COLOR = (0, 0, 0) ## Algo def", "elem[3]) if check_polygon_intersection(p1, p2): zero_distance.append(j) new_y = min(y, elem[1]) new_h = max(y+h, elem[1]", "min([boxe[1] for boxe in small_list]) new_h = max([boxe[1] + boxe[3] - new_y for", "p2): to_be_merged.append(boxe2) used_ind.append(j) all_to_be_merged.append(to_be_merged) n_detected = len(all_to_be_merged) new_boxes_list = list() for i in", "return False ## Processing extracted boxes def check_polygon_intersection(p1, p2): if p1.distance(p2) == 0", "range(n_boxes): if filter_boxes(image_to_data, i) : (x, y, w, h) = (image_to_data['left'][i], image_to_data['top'][i], image_to_data['width'][i],", "Ymax def draw_lines_v1(img_path, image_to_data): img = cv2.imread(img_path) Xmax = img.shape[1] n_boxes = len(image_to_data['level'])", "= cv2.imread(img_path) Xmax = img.shape[1] Ymax = img.shape[0] n_boxes = len(image_to_data) for i", "0),(Xmax, 0) ,LINE_COLOR, 5) cv2.line(img, (0, Ymax),(Xmax, Ymax) ,LINE_COLOR, 5) cv2.line(img, (Xmax ,", "l in elem2: return True return False ## Processing extracted boxes def check_polygon_intersection(p1,", "if l in elem2: return True return False ## Processing extracted boxes def", "Xmax, h) n_b = len(boxes_list) flag = 0 zero_distance = list() for j", "\"\"\" img = cv2.imread(img_path) Xmax = img.shape[1] Ymax = img.shape[0] n_boxes = len(image_to_data)", "image_name = os.path.basename(img_path).split(os.extsep)[0].replace(\" \", \"_\") processed_im_path = draw_path+\"\\\\\"+image_name+'pro.png' cv2.imwrite(processed_im_path, img) def process_path(file_path,draw_path): all_files", "y, w, h): p = Polygon([(x, y),(x+w, y),(x+w, y + h),(x, y +", "0, 0), 5) cv2.line(img, (Xmax , 0),(Xmax, Ymax) ,(0, 0, 0), 5) \"\"\"", "+ h), (0, 255, 0), 1) cv2.line(img, (0 , 0),(0, Ymax) ,LINE_COLOR, 5)", "+ w, y + h), LINE_COLOR, LINE_WIDTH) \"\"\" cv2.line(img, (0 , 0),(0, Ymax)", "Xmax, new_h] boxes_list[j]=new_elem flag = 1 if flag == 0 : new_elem =", "= 0 zero_distance = list() for j in range(n_b): elem = boxes_list[j] p2", "Xmax = img.shape[1] n_boxes = len(image_to_data['level']) for i in range(n_boxes): if filter_boxes(image_to_data, i)", "os from shapely.geometry import Polygon pytesseract.pytesseract.tesseract_cmd = \"Tesseract path e.g c:\\Tesseract-OCR\\tesseract \" import", "of drawin a line over a word, we will set a threshold to", "hole section is not detected. \"\"\" y_new = min(y_middle, y+h+margin) cv2.line(img, (x ,", "0, 0), 5) cv2.line(img, (0, Ymax),(Xmax, Ymax) ,(0, 0, 0), 5) cv2.line(img, (Xmax", "5) \"\"\" cv2.namedWindow(\"output2\", cv2.WINDOW_NORMAL) cv2.imshow('output2', img) def draw_lines(img_path, image_to_data, margin = 0): \"\"\"", "margin =2) image_name = os.path.basename(img_path).split(os.extsep)[0].replace(\" \", \"_\") processed_im_path = draw_path+\"\\\\\"+image_name+'pro.png' cv2.imwrite(processed_im_path, img) def", "max([boxe[1] + boxe[3] - new_y for boxe in small_list]) new_elem = [0, new_y,", "=2) image_name = os.path.basename(img_path).split(os.extsep)[0].replace(\" \", \"_\") processed_im_path = draw_path+\"\\\\\"+image_name+'pro.png' cv2.imwrite(processed_im_path, img) def process_path(file_path,draw_path):", "if j not in used_ind: boxe2=boxes_list[j] p2 = create_polygon(boxe2[0],boxe2[1],boxe2[2],boxe2[3]) if check_polygon_intersection(p1, p2): to_be_merged.append(boxe2)", "import cv2 import os from shapely.geometry import Polygon pytesseract.pytesseract.tesseract_cmd = \"Tesseract path e.g", "True return False def process_image_to_data(image_to_data, Xmax, Ymax): boxes_list = list() boxes_list.append([0, 0, 0,", "boxe1 = boxes_list[i] p1 = create_polygon(boxe1[0],boxe1[1],boxe1[2],boxe1[3]) m = len(boxes_list) for j in range(m):", "= cv2.imread(img_path) Xmax = img.shape[1] n_boxes = len(image_to_data['level']) for i in range(n_boxes): if", "= os.path.basename(img_path).split(os.extsep)[0].replace(\" \", \"_\") processed_im_path = draw_path+\"\\\\\"+image_name+'pro.png' cv2.imwrite(processed_im_path, img) def process_path(file_path,draw_path): all_files =", "cv2.rectangle(img, (x, y), ( x + w, y + h), LINE_COLOR, LINE_WIDTH) \"\"\"", "def check_polygon_intersection(p1, p2): if p1.distance(p2) == 0 : return True return False def", "h), (0, 255, 0), 1) cv2.rectangle(img, (x, y), ( x + w, y", "p def filter_boxes(image_to_data, ind): text = image_to_data[\"text\"][ind] h = image_to_data[\"height\"][ind] w = image_to_data[\"width\"][ind]", "img = cv2.imread(img_path) Xmax = img.shape[1] Ymax = img.shape[0] n_boxes = len(image_to_data) for", "range(n_detected): small_list = all_to_be_merged[i] p = len(small_list) new_y = min([boxe[1] for boxe in", "range(n): if i not in used_ind: to_be_merged = list() boxe1 = boxes_list[i] p1", "- min(y, elem[1]) new_elem = [0, new_y, Xmax, new_h] boxes_list[j]=new_elem flag = 1", "= img.shape[1] Ymax = img.shape[0] return image_to_data, Xmax, Ymax def draw_lines_v1(img_path, image_to_data): img", "(y, h) = (image_to_data['top'][i], image_to_data['height'][i]) p1 = create_polygon(0, y, Xmax, h) n_b =", "[0, new_y, Xmax, new_h] boxes_list[j]=new_elem flag = 1 if flag == 0 :", "+ h), LINE_COLOR, LINE_WIDTH) \"\"\" cv2.line(img, (0 , 0),(0, Ymax) ,(0, 0, 0),", "for j in range(m): if j not in used_ind: boxe2=boxes_list[j] p2 = create_polygon(boxe2[0],boxe2[1],boxe2[2],boxe2[3])", "- new_y for boxe in small_list]) new_elem = [0, new_y, Xmax, new_h] new_boxes_list.append(new_elem)", "image_to_data['width'][i], image_to_data['height'][i]) #cv2.line(img, (0 , y +h +5 ),(Xmax, y +h +5) ,(0,", "image_to_data[i][2], image_to_data[i][3]) y_next = image_to_data[i+1][1] y_middle = (y+h+y_next)//2 \"\"\" To avoid the case", "+ h), (0, 255, 0), 1) #cv2.rectangle(img, (x, y), ( x + w,", "+ h),(x, y + h)]) return p def filter_boxes(image_to_data, ind): text = image_to_data[\"text\"][ind]", "(0 , 0),(0, Ymax) ,LINE_COLOR, 5) cv2.line(img, (0 , 0),(Xmax, 0) ,LINE_COLOR, 5)", "len(text) > CHAR_THRESHOLD and w > h: return True return False def process_image_to_data(image_to_data,", "Ymax),(Xmax, Ymax) ,(0, 0, 0), 5) cv2.line(img, (Xmax , 0),(Xmax, Ymax) ,(0, 0,", "if p1.distance(p2) == 0 : return True return False def create_polygon(x, y, w,", "list() for j in range(n_b): elem = boxes_list[j] p2 = create_polygon(elem[0], elem[1], elem[2],", "elem[1], elem[2], elem[3]) if check_polygon_intersection(p1, p2): zero_distance.append(j) new_y = min(y, elem[1]) new_h =", "#try: image_to_data, Xmax, Ymax = get_image_data(img_path) image_to_data = process_image_to_data(image_to_data, Xmax, Ymax) image_to_data =", "import pytesseract from pytesseract import Output import cv2 import os from shapely.geometry import", "n_boxes = len(image_to_data['level']) \"\"\" A first loop to merge close boxes \"\"\" for", "to y_middle, In case a hole section is not detected. \"\"\" y_new =", "p1 = create_polygon(0, y, Xmax, h) n_b = len(boxes_list) flag = 0 zero_distance", "max(y+h, elem[1] + elem[3]) - min(y, elem[1]) new_elem = [0, new_y, Xmax, new_h]", "1 if flag == 0 : new_elem = [0, y, Xmax, h] boxes_list.append(new_elem)", "cv2.imread(img_path) image_to_data = pytesseract.image_to_data(img, output_type=Output.DICT) Xmax = img.shape[1] Ymax = img.shape[0] return image_to_data,", "For each line, we will draw a line between the bottom of the", "w > h: return True return False def process_image_to_data(image_to_data, Xmax, Ymax): boxes_list =", "def process_image_to_data(image_to_data, Xmax, Ymax): boxes_list = list() boxes_list.append([0, 0, 0, 0]) all_zero_distance =", "= len(boxes_list) for j in range(m): if j not in used_ind: boxe2=boxes_list[j] p2", "a word, we will set a threshold to y_middle, In case a hole", "5) cv2.line(img, (0 , 0),(Xmax, 0) ,LINE_COLOR, 5) cv2.line(img, (0, Ymax),(Xmax, Ymax) ,LINE_COLOR,", "0, 0), 5) cv2.line(img, (0 , 0),(Xmax, 0) ,(0, 0, 0), 5) cv2.line(img,", "pytesseract import Output import cv2 import os from shapely.geometry import Polygon pytesseract.pytesseract.tesseract_cmd =", "new_boxes_list = list() for i in range(n_detected): small_list = all_to_be_merged[i] p = len(small_list)", "0), 1) cv2.rectangle(img, (x, y), ( x + w, y + h), LINE_COLOR,", "= len(image_to_data['level']) \"\"\" A first loop to merge close boxes \"\"\" for i", "Processing extracted boxes def check_polygon_intersection(p1, p2): if p1.distance(p2) == 0 : return True", "i not in used_ind: to_be_merged = list() boxe1 = boxes_list[i] p1 = create_polygon(boxe1[0],boxe1[1],boxe1[2],boxe1[3])", "cv2.imshow('output2', img) def draw_lines(img_path, image_to_data, margin = 0): \"\"\" Draw extracted and filtred", "= len(all_files) for i in range(n): f = all_files[i] img_path = join(file_path, f)", ": (x, y, w, h) = (image_to_data['left'][i], image_to_data['top'][i], image_to_data['width'][i], image_to_data['height'][i]) #cv2.line(img, (0 ,", "0), 3) #cv2.line(img, (0 , y+h ), (Xmax + w, y + h),", "(0, 255, 0), 1) cv2.rectangle(img, (x, y), ( x + w, y +", ", 0),(Xmax, Ymax) ,LINE_COLOR, 5) #cv2.namedWindow(\"output\", cv2.WINDOW_NORMAL) #cv2.imshow('output', img) return img def check_intersection(elem1,", "if len(text) > CHAR_THRESHOLD and w > h: return True return False def", "create_polygon(boxe2[0],boxe2[1],boxe2[2],boxe2[3]) if check_polygon_intersection(p1, p2): to_be_merged.append(boxe2) used_ind.append(j) all_to_be_merged.append(to_be_merged) n_detected = len(all_to_be_merged) new_boxes_list = list()", "process_table(img_path,draw_path): #try: image_to_data, Xmax, Ymax = get_image_data(img_path) image_to_data = process_image_to_data(image_to_data, Xmax, Ymax) image_to_data", "image_to_data, Xmax, Ymax = get_image_data(img_path) image_to_data = process_image_to_data(image_to_data, Xmax, Ymax) image_to_data = clean_loop(image_to_data)", "small_list = all_to_be_merged[i] p = len(small_list) new_y = min([boxe[1] for boxe in small_list])", "for i in range(n_boxes-1): \"\"\" For each line, we will draw a line", "0]) all_zero_distance = list() n_boxes = len(image_to_data['level']) \"\"\" A first loop to merge", "if i not in used_ind: to_be_merged = list() boxe1 = boxes_list[i] p1 =", "boxe2=boxes_list[j] p2 = create_polygon(boxe2[0],boxe2[1],boxe2[2],boxe2[3]) if check_polygon_intersection(p1, p2): to_be_merged.append(boxe2) used_ind.append(j) all_to_be_merged.append(to_be_merged) n_detected = len(all_to_be_merged)", "the next line top \"\"\" (x, y, w, h) = (image_to_data[i][0], image_to_data[i][1], image_to_data[i][2],", "(Xmax , 0),(Xmax, Ymax) ,(0, 0, 0), 5) \"\"\" cv2.namedWindow(\"output2\", cv2.WINDOW_NORMAL) cv2.imshow('output2', img)", "len(image_to_data['level']) \"\"\" A first loop to merge close boxes \"\"\" for i in", "3 LINE_WIDTH = 2 LINE_COLOR = (0, 0, 0) ## Algo def get_image_data(img_path):", "if flag == 0 : new_elem = [0, y, Xmax, h] boxes_list.append(new_elem) return", "+ w, y + h), (0, 255, 0), 1) cv2.rectangle(img, (x, y), (", "image_to_data[\"width\"][ind] if len(text) > CHAR_THRESHOLD and w > h: return True return False", "new_y for boxe in small_list]) new_elem = [0, new_y, Xmax, new_h] new_boxes_list.append(new_elem) return", "return True return False def process_image_to_data(image_to_data, Xmax, Ymax): boxes_list = list() boxes_list.append([0, 0,", "img def check_intersection(elem1, elem2): for l in elem1: if l in elem2: return", "= min([boxe[1] for boxe in small_list]) new_h = max([boxe[1] + boxe[3] - new_y", ", y +h +5 ),(Xmax, y +h +5) ,(0, 0, 0), 3) #cv2.line(img,", "0), 5) cv2.line(img, (Xmax , 0),(Xmax, Ymax) ,(0, 0, 0), 5) \"\"\" cv2.namedWindow(\"output2\",", "img.shape[1] Ymax = img.shape[0] n_boxes = len(image_to_data) for i in range(n_boxes-1): \"\"\" For", "image_to_data[i][1], image_to_data[i][2], image_to_data[i][3]) y_next = image_to_data[i+1][1] y_middle = (y+h+y_next)//2 \"\"\" To avoid the", "draw_lines(img_path, image_to_data, margin = 0): \"\"\" Draw extracted and filtred boxes \"\"\" img", "cv2.namedWindow(\"output2\", cv2.WINDOW_NORMAL) cv2.imshow('output2', img) def draw_lines(img_path, image_to_data, margin = 0): \"\"\" Draw extracted", "\"\"\" for i in range(n_boxes): if filter_boxes(image_to_data, i) : (y, h) = (image_to_data['top'][i],", "cv2.line(img, (Xmax , 0),(Xmax, Ymax) ,(0, 0, 0), 5) \"\"\" cv2.namedWindow(\"output2\", cv2.WINDOW_NORMAL) cv2.imshow('output2',", "img.shape[1] Ymax = img.shape[0] return image_to_data, Xmax, Ymax def draw_lines_v1(img_path, image_to_data): img =", "(Xmax , 0),(Xmax, Ymax) ,LINE_COLOR, 5) #cv2.namedWindow(\"output\", cv2.WINDOW_NORMAL) #cv2.imshow('output', img) return img def", "= Polygon([(x, y),(x+w, y),(x+w, y + h),(x, y + h)]) return p def", "= len(image_to_data['level']) for i in range(n_boxes): if filter_boxes(image_to_data, i) : (x, y, w,", "p2 = create_polygon(boxe2[0],boxe2[1],boxe2[2],boxe2[3]) if check_polygon_intersection(p1, p2): to_be_merged.append(boxe2) used_ind.append(j) all_to_be_merged.append(to_be_merged) n_detected = len(all_to_be_merged) new_boxes_list", "section is not detected. \"\"\" y_new = min(y_middle, y+h+margin) cv2.line(img, (x , y_new),(w,", "chdir, listdir from os.path import join ## Hyper Params L = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' CHAR_THRESHOLD", "cv2.line(img, (0 , 0),(0, Ymax) ,LINE_COLOR, 5) cv2.line(img, (0 , 0),(Xmax, 0) ,LINE_COLOR,", "process_image_to_data(image_to_data, Xmax, Ymax) image_to_data = clean_loop(image_to_data) img = draw_lines(img_path, image_to_data, margin =2) image_name", "0), 5) cv2.line(img, (0 , 0),(Xmax, 0) ,(0, 0, 0), 5) cv2.line(img, (0,", "create_polygon(0, y, Xmax, h) n_b = len(boxes_list) flag = 0 zero_distance = list()", "and w > h: return True return False def process_image_to_data(image_to_data, Xmax, Ymax): boxes_list", "close boxes \"\"\" for i in range(n_boxes): if filter_boxes(image_to_data, i) : (y, h)", "= image_to_data[i+1][1] y_middle = (y+h+y_next)//2 \"\"\" To avoid the case of drawin a", "= image_to_data[\"text\"][ind] h = image_to_data[\"height\"][ind] w = image_to_data[\"width\"][ind] if len(text) > CHAR_THRESHOLD and", "(0, Ymax),(Xmax, Ymax) ,LINE_COLOR, 5) cv2.line(img, (Xmax , 0),(Xmax, Ymax) ,LINE_COLOR, 5) #cv2.namedWindow(\"output\",", "L = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' CHAR_THRESHOLD = 3 LINE_WIDTH = 2 LINE_COLOR = (0, 0,", "elem2): for l in elem1: if l in elem2: return True return False", "= 2 LINE_COLOR = (0, 0, 0) ## Algo def get_image_data(img_path): img =", "Xmax, Ymax) image_to_data = clean_loop(image_to_data) img = draw_lines(img_path, image_to_data, margin =2) image_name =", "= draw_lines(img_path, image_to_data, margin =2) image_name = os.path.basename(img_path).split(os.extsep)[0].replace(\" \", \"_\") processed_im_path = draw_path+\"\\\\\"+image_name+'pro.png'", "pytesseract.pytesseract.tesseract_cmd = \"Tesseract path e.g c:\\Tesseract-OCR\\tesseract \" import sys from os import chdir,", "\"\"\" A first loop to merge close boxes \"\"\" for i in range(n_boxes):", "in range(n_boxes): if filter_boxes(image_to_data, i) : (y, h) = (image_to_data['top'][i], image_to_data['height'][i]) p1 =", "0),(0, Ymax) ,LINE_COLOR, 5) cv2.line(img, (0 , 0),(Xmax, 0) ,LINE_COLOR, 5) cv2.line(img, (0,", "img.shape[1] n_boxes = len(image_to_data['level']) for i in range(n_boxes): if filter_boxes(image_to_data, i) : (x,", "image_to_data, margin = 0): \"\"\" Draw extracted and filtred boxes \"\"\" img =", "flag == 0 : new_elem = [0, y, Xmax, h] boxes_list.append(new_elem) return boxes_list", "get_image_data(img_path): img = cv2.imread(img_path) image_to_data = pytesseract.image_to_data(img, output_type=Output.DICT) Xmax = img.shape[1] Ymax =", "y), ( x + w, y + h), LINE_COLOR, LINE_WIDTH) \"\"\" cv2.line(img, (0", "= len(boxes_list) global_flag = 0 all_to_be_merged = list() used_ind = list() for i", "== 0 : return True return False def create_polygon(x, y, w, h): p", "(y+h+y_next)//2 \"\"\" To avoid the case of drawin a line over a word,", "len(all_to_be_merged) new_boxes_list = list() for i in range(n_detected): small_list = all_to_be_merged[i] p =", "boxe in small_list]) new_h = max([boxe[1] + boxe[3] - new_y for boxe in", "path e.g c:\\Tesseract-OCR\\tesseract \" import sys from os import chdir, listdir from os.path", "len(boxes_list) for j in range(m): if j not in used_ind: boxe2=boxes_list[j] p2 =", "elem[2], elem[3]) if check_polygon_intersection(p1, p2): zero_distance.append(j) new_y = min(y, elem[1]) new_h = max(y+h,", "n_b = len(boxes_list) flag = 0 zero_distance = list() for j in range(n_b):", "y, Xmax, h) n_b = len(boxes_list) flag = 0 zero_distance = list() for", "i in range(n): if i not in used_ind: to_be_merged = list() boxe1 =", "cv2.imread(img_path) Xmax = img.shape[1] Ymax = img.shape[0] n_boxes = len(image_to_data) for i in", "listdir(file_path) n = len(all_files) for i in range(n): f = all_files[i] img_path =", "0, 0, 0]) all_zero_distance = list() n_boxes = len(image_to_data['level']) \"\"\" A first loop", "CHAR_THRESHOLD = 3 LINE_WIDTH = 2 LINE_COLOR = (0, 0, 0) ## Algo", "def get_image_data(img_path): img = cv2.imread(img_path) image_to_data = pytesseract.image_to_data(img, output_type=Output.DICT) Xmax = img.shape[1] Ymax", "return False def process_image_to_data(image_to_data, Xmax, Ymax): boxes_list = list() boxes_list.append([0, 0, 0, 0])", "0, 0), 5) \"\"\" cv2.namedWindow(\"output2\", cv2.WINDOW_NORMAL) cv2.imshow('output2', img) def draw_lines(img_path, image_to_data, margin =", "image_to_data['height'][i]) p1 = create_polygon(0, y, Xmax, h) n_b = len(boxes_list) flag = 0", "image_to_data[i+1][1] y_middle = (y+h+y_next)//2 \"\"\" To avoid the case of drawin a line", "loop to merge close boxes \"\"\" for i in range(n_boxes): if filter_boxes(image_to_data, i)", "= process_image_to_data(image_to_data, Xmax, Ymax) image_to_data = clean_loop(image_to_data) img = draw_lines(img_path, image_to_data, margin =2)", "#cv2.imshow('output', img) return img def check_intersection(elem1, elem2): for l in elem1: if l", "= 0): \"\"\" Draw extracted and filtred boxes \"\"\" img = cv2.imread(img_path) Xmax", "y + h), (0, 255, 0), 1) cv2.line(img, (0 , 0),(0, Ymax) ,LINE_COLOR,", "boxe in small_list]) new_elem = [0, new_y, Xmax, new_h] new_boxes_list.append(new_elem) return new_boxes_list def", "+ w, y + h), (0, 255, 0), 1) #cv2.rectangle(img, (x, y), (", "filtred boxes \"\"\" img = cv2.imread(img_path) Xmax = img.shape[1] Ymax = img.shape[0] n_boxes", "create_polygon(boxe1[0],boxe1[1],boxe1[2],boxe1[3]) m = len(boxes_list) for j in range(m): if j not in used_ind:", "return image_to_data, Xmax, Ymax def draw_lines_v1(img_path, image_to_data): img = cv2.imread(img_path) Xmax = img.shape[1]", "( x + w, y + h), LINE_COLOR, LINE_WIDTH) \"\"\" cv2.line(img, (0 ,", "= boxes_list[i] p1 = create_polygon(boxe1[0],boxe1[1],boxe1[2],boxe1[3]) m = len(boxes_list) for j in range(m): if", "+5) ,(0, 0, 0), 3) #cv2.line(img, (0 , y+h ), (Xmax + w,", "0, 0), 3) #cv2.line(img, (0 , y+h ), (Xmax + w, y +", "A first loop to merge close boxes \"\"\" for i in range(n_boxes): if", "len(image_to_data) for i in range(n_boxes-1): \"\"\" For each line, we will draw a", "= \"Tesseract path e.g c:\\Tesseract-OCR\\tesseract \" import sys from os import chdir, listdir", "cv2.line(img, (x , y_new),(w, y_new) ,LINE_COLOR, LINE_WIDTH) #cv2.line(img, (0 , y+h ), (Xmax", "Polygon pytesseract.pytesseract.tesseract_cmd = \"Tesseract path e.g c:\\Tesseract-OCR\\tesseract \" import sys from os import", "w = image_to_data[\"width\"][ind] if len(text) > CHAR_THRESHOLD and w > h: return True", "if filter_boxes(image_to_data, i) : (x, y, w, h) = (image_to_data['left'][i], image_to_data['top'][i], image_to_data['width'][i], image_to_data['height'][i])", "w, y + h), LINE_COLOR, LINE_WIDTH) \"\"\" cv2.line(img, (0 , 0),(0, Ymax) ,(0,", "LINE_WIDTH = 2 LINE_COLOR = (0, 0, 0) ## Algo def get_image_data(img_path): img", "new_y, Xmax, new_h] new_boxes_list.append(new_elem) return new_boxes_list def process_table(img_path,draw_path): #try: image_to_data, Xmax, Ymax =", ", y+h ), (Xmax + w, y + h), (0, 255, 0), 1)", "def create_polygon(x, y, w, h): p = Polygon([(x, y),(x+w, y),(x+w, y + h),(x,", "for i in range(n): if i not in used_ind: to_be_merged = list() boxe1", "\"\"\" cv2.line(img, (0 , 0),(0, Ymax) ,(0, 0, 0), 5) cv2.line(img, (0 ,", "small_list]) new_h = max([boxe[1] + boxe[3] - new_y for boxe in small_list]) new_elem", "y),(x+w, y),(x+w, y + h),(x, y + h)]) return p def filter_boxes(image_to_data, ind):", "\"\"\" y_new = min(y_middle, y+h+margin) cv2.line(img, (x , y_new),(w, y_new) ,LINE_COLOR, LINE_WIDTH) #cv2.line(img,", "= list() used_ind = list() for i in range(n): if i not in", "draw a line between the bottom of the line and the next line", "Draw extracted and filtred boxes \"\"\" img = cv2.imread(img_path) Xmax = img.shape[1] Ymax", "y +h +5 ),(Xmax, y +h +5) ,(0, 0, 0), 3) #cv2.line(img, (0", "(image_to_data['left'][i], image_to_data['top'][i], image_to_data['width'][i], image_to_data['height'][i]) #cv2.line(img, (0 , y +h +5 ),(Xmax, y +h", "new_y = min(y, elem[1]) new_h = max(y+h, elem[1] + elem[3]) - min(y, elem[1])", "used_ind: to_be_merged = list() boxe1 = boxes_list[i] p1 = create_polygon(boxe1[0],boxe1[1],boxe1[2],boxe1[3]) m = len(boxes_list)", "5) #cv2.namedWindow(\"output\", cv2.WINDOW_NORMAL) #cv2.imshow('output', img) return img def check_intersection(elem1, elem2): for l in", "Hyper Params L = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' CHAR_THRESHOLD = 3 LINE_WIDTH = 2 LINE_COLOR =", "new_elem = [0, new_y, Xmax, new_h] boxes_list[j]=new_elem flag = 1 if flag ==", "from shapely.geometry import Polygon pytesseract.pytesseract.tesseract_cmd = \"Tesseract path e.g c:\\Tesseract-OCR\\tesseract \" import sys", "case of drawin a line over a word, we will set a threshold", "= create_polygon(0, y, Xmax, h) n_b = len(boxes_list) flag = 0 zero_distance =", "def process_table(img_path,draw_path): #try: image_to_data, Xmax, Ymax = get_image_data(img_path) image_to_data = process_image_to_data(image_to_data, Xmax, Ymax)", "in range(n_b): elem = boxes_list[j] p2 = create_polygon(elem[0], elem[1], elem[2], elem[3]) if check_polygon_intersection(p1,", "\"\"\" For each line, we will draw a line between the bottom of", "y_next = image_to_data[i+1][1] y_middle = (y+h+y_next)//2 \"\"\" To avoid the case of drawin", "img = cv2.imread(img_path) image_to_data = pytesseract.image_to_data(img, output_type=Output.DICT) Xmax = img.shape[1] Ymax = img.shape[0]", "boxes \"\"\" img = cv2.imread(img_path) Xmax = img.shape[1] Ymax = img.shape[0] n_boxes =", "elem2: return True return False ## Processing extracted boxes def check_polygon_intersection(p1, p2): if", "new_y = min([boxe[1] for boxe in small_list]) new_h = max([boxe[1] + boxe[3] -", "\"_\") processed_im_path = draw_path+\"\\\\\"+image_name+'pro.png' cv2.imwrite(processed_im_path, img) def process_path(file_path,draw_path): all_files = listdir(file_path) n =", "cv2.WINDOW_NORMAL) #cv2.imshow('output', img) return img def check_intersection(elem1, elem2): for l in elem1: if", "0 all_to_be_merged = list() used_ind = list() for i in range(n): if i", "= len(image_to_data) for i in range(n_boxes-1): \"\"\" For each line, we will draw", "def process_path(file_path,draw_path): all_files = listdir(file_path) n = len(all_files) for i in range(n): f", "y, Xmax, h] boxes_list.append(new_elem) return boxes_list def clean_loop(boxes_list): Xmax = boxes_list[1][2] n =", "draw_path+\"\\\\\"+image_name+'pro.png' cv2.imwrite(processed_im_path, img) def process_path(file_path,draw_path): all_files = listdir(file_path) n = len(all_files) for i", "listdir from os.path import join ## Hyper Params L = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' CHAR_THRESHOLD =", "a line over a word, we will set a threshold to y_middle, In", "0),(Xmax, 0) ,(0, 0, 0), 5) cv2.line(img, (0, Ymax),(Xmax, Ymax) ,(0, 0, 0),", "True return False def create_polygon(x, y, w, h): p = Polygon([(x, y),(x+w, y),(x+w,", "i in range(n_boxes): if filter_boxes(image_to_data, i) : (y, h) = (image_to_data['top'][i], image_to_data['height'][i]) p1", "i in range(n_boxes-1): \"\"\" For each line, we will draw a line between", "## Processing extracted boxes def check_polygon_intersection(p1, p2): if p1.distance(p2) == 0 : return", "filter_boxes(image_to_data, ind): text = image_to_data[\"text\"][ind] h = image_to_data[\"height\"][ind] w = image_to_data[\"width\"][ind] if len(text)", "= (image_to_data['top'][i], image_to_data['height'][i]) p1 = create_polygon(0, y, Xmax, h) n_b = len(boxes_list) flag", "for boxe in small_list]) new_elem = [0, new_y, Xmax, new_h] new_boxes_list.append(new_elem) return new_boxes_list", "and filtred boxes \"\"\" img = cv2.imread(img_path) Xmax = img.shape[1] Ymax = img.shape[0]", "= [0, new_y, Xmax, new_h] new_boxes_list.append(new_elem) return new_boxes_list def process_table(img_path,draw_path): #try: image_to_data, Xmax,", "h) = (image_to_data['left'][i], image_to_data['top'][i], image_to_data['width'][i], image_to_data['height'][i]) #cv2.line(img, (0 , y +h +5 ),(Xmax,", ", 0),(Xmax, 0) ,LINE_COLOR, 5) cv2.line(img, (0, Ymax),(Xmax, Ymax) ,LINE_COLOR, 5) cv2.line(img, (Xmax", "Xmax = img.shape[1] Ymax = img.shape[0] n_boxes = len(image_to_data) for i in range(n_boxes-1):", "boxes def check_polygon_intersection(p1, p2): if p1.distance(p2) == 0 : return True return False", "filter_boxes(image_to_data, i) : (y, h) = (image_to_data['top'][i], image_to_data['height'][i]) p1 = create_polygon(0, y, Xmax,", "p2): zero_distance.append(j) new_y = min(y, elem[1]) new_h = max(y+h, elem[1] + elem[3]) -", "new_h = max(y+h, elem[1] + elem[3]) - min(y, elem[1]) new_elem = [0, new_y,", "Xmax, Ymax def draw_lines_v1(img_path, image_to_data): img = cv2.imread(img_path) Xmax = img.shape[1] n_boxes =", "get_image_data(img_path) image_to_data = process_image_to_data(image_to_data, Xmax, Ymax) image_to_data = clean_loop(image_to_data) img = draw_lines(img_path, image_to_data,", "\", \"_\") processed_im_path = draw_path+\"\\\\\"+image_name+'pro.png' cv2.imwrite(processed_im_path, img) def process_path(file_path,draw_path): all_files = listdir(file_path) n", "0),(Xmax, Ymax) ,(0, 0, 0), 5) \"\"\" cv2.namedWindow(\"output2\", cv2.WINDOW_NORMAL) cv2.imshow('output2', img) def draw_lines(img_path,", "= min(y_middle, y+h+margin) cv2.line(img, (x , y_new),(w, y_new) ,LINE_COLOR, LINE_WIDTH) #cv2.line(img, (0 ,", "Ymax = get_image_data(img_path) image_to_data = process_image_to_data(image_to_data, Xmax, Ymax) image_to_data = clean_loop(image_to_data) img =", "image_to_data[\"text\"][ind] h = image_to_data[\"height\"][ind] w = image_to_data[\"width\"][ind] if len(text) > CHAR_THRESHOLD and w", "def draw_lines(img_path, image_to_data, margin = 0): \"\"\" Draw extracted and filtred boxes \"\"\"", "= draw_path+\"\\\\\"+image_name+'pro.png' cv2.imwrite(processed_im_path, img) def process_path(file_path,draw_path): all_files = listdir(file_path) n = len(all_files) for", "image_to_data, margin =2) image_name = os.path.basename(img_path).split(os.extsep)[0].replace(\" \", \"_\") processed_im_path = draw_path+\"\\\\\"+image_name+'pro.png' cv2.imwrite(processed_im_path, img)", "0 : new_elem = [0, y, Xmax, h] boxes_list.append(new_elem) return boxes_list def clean_loop(boxes_list):", "0),(0, Ymax) ,(0, 0, 0), 5) cv2.line(img, (0 , 0),(Xmax, 0) ,(0, 0,", "cv2.WINDOW_NORMAL) cv2.imshow('output2', img) def draw_lines(img_path, image_to_data, margin = 0): \"\"\" Draw extracted and", "for i in range(n_detected): small_list = all_to_be_merged[i] p = len(small_list) new_y = min([boxe[1]", "## Hyper Params L = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' CHAR_THRESHOLD = 3 LINE_WIDTH = 2 LINE_COLOR", "h), (0, 255, 0), 1) #cv2.rectangle(img, (x, y), ( x + w, y", "img = draw_lines(img_path, image_to_data, margin =2) image_name = os.path.basename(img_path).split(os.extsep)[0].replace(\" \", \"_\") processed_im_path =", "h = image_to_data[\"height\"][ind] w = image_to_data[\"width\"][ind] if len(text) > CHAR_THRESHOLD and w >", "image_to_data = clean_loop(image_to_data) img = draw_lines(img_path, image_to_data, margin =2) image_name = os.path.basename(img_path).split(os.extsep)[0].replace(\" \",", "\"Tesseract path e.g c:\\Tesseract-OCR\\tesseract \" import sys from os import chdir, listdir from", "= max(y+h, elem[1] + elem[3]) - min(y, elem[1]) new_elem = [0, new_y, Xmax,", "shapely.geometry import Polygon pytesseract.pytesseract.tesseract_cmd = \"Tesseract path e.g c:\\Tesseract-OCR\\tesseract \" import sys from", "import chdir, listdir from os.path import join ## Hyper Params L = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'", "cv2.line(img, (0 , 0),(Xmax, 0) ,LINE_COLOR, 5) cv2.line(img, (0, Ymax),(Xmax, Ymax) ,LINE_COLOR, 5)", "return False def create_polygon(x, y, w, h): p = Polygon([(x, y),(x+w, y),(x+w, y", "processed_im_path = draw_path+\"\\\\\"+image_name+'pro.png' cv2.imwrite(processed_im_path, img) def process_path(file_path,draw_path): all_files = listdir(file_path) n = len(all_files)", "min(y_middle, y+h+margin) cv2.line(img, (x , y_new),(w, y_new) ,LINE_COLOR, LINE_WIDTH) #cv2.line(img, (0 , y+h", ",(0, 0, 0), 5) \"\"\" cv2.namedWindow(\"output2\", cv2.WINDOW_NORMAL) cv2.imshow('output2', img) def draw_lines(img_path, image_to_data, margin", "check_polygon_intersection(p1, p2): zero_distance.append(j) new_y = min(y, elem[1]) new_h = max(y+h, elem[1] + elem[3])", "min(y, elem[1]) new_elem = [0, new_y, Xmax, new_h] boxes_list[j]=new_elem flag = 1 if", "new_boxes_list.append(new_elem) return new_boxes_list def process_table(img_path,draw_path): #try: image_to_data, Xmax, Ymax = get_image_data(img_path) image_to_data =", "(0 , 0),(Xmax, 0) ,LINE_COLOR, 5) cv2.line(img, (0, Ymax),(Xmax, Ymax) ,LINE_COLOR, 5) cv2.line(img,", "(0, 255, 0), 1) #cv2.rectangle(img, (x, y), ( x + w, y +", "= (0, 0, 0) ## Algo def get_image_data(img_path): img = cv2.imread(img_path) image_to_data =", "y, w, h) = (image_to_data['left'][i], image_to_data['top'][i], image_to_data['width'][i], image_to_data['height'][i]) #cv2.line(img, (0 , y +h", "c:\\Tesseract-OCR\\tesseract \" import sys from os import chdir, listdir from os.path import join", ",LINE_COLOR, LINE_WIDTH) #cv2.line(img, (0 , y+h ), (Xmax + w, y + h),", "False ## Processing extracted boxes def check_polygon_intersection(p1, p2): if p1.distance(p2) == 0 :", "Xmax = boxes_list[1][2] n = len(boxes_list) global_flag = 0 all_to_be_merged = list() used_ind", "cv2.line(img, (0, Ymax),(Xmax, Ymax) ,(0, 0, 0), 5) cv2.line(img, (Xmax , 0),(Xmax, Ymax)", "list() boxe1 = boxes_list[i] p1 = create_polygon(boxe1[0],boxe1[1],boxe1[2],boxe1[3]) m = len(boxes_list) for j in", "flag = 1 if flag == 0 : new_elem = [0, y, Xmax,", "), (Xmax + w, y + h), (0, 255, 0), 1) cv2.rectangle(img, (x,", ",(0, 0, 0), 3) #cv2.line(img, (0 , y+h ), (Xmax + w, y", "p = len(small_list) new_y = min([boxe[1] for boxe in small_list]) new_h = max([boxe[1]", "(0 , y+h ), (Xmax + w, y + h), (0, 255, 0),", "= (y+h+y_next)//2 \"\"\" To avoid the case of drawin a line over a", "elem[3]) - min(y, elem[1]) new_elem = [0, new_y, Xmax, new_h] boxes_list[j]=new_elem flag =", "= create_polygon(boxe2[0],boxe2[1],boxe2[2],boxe2[3]) if check_polygon_intersection(p1, p2): to_be_merged.append(boxe2) used_ind.append(j) all_to_be_merged.append(to_be_merged) n_detected = len(all_to_be_merged) new_boxes_list =", "word, we will set a threshold to y_middle, In case a hole section", "filter_boxes(image_to_data, i) : (x, y, w, h) = (image_to_data['left'][i], image_to_data['top'][i], image_to_data['width'][i], image_to_data['height'][i]) #cv2.line(img,", "Ymax = img.shape[0] return image_to_data, Xmax, Ymax def draw_lines_v1(img_path, image_to_data): img = cv2.imread(img_path)", "Ymax) ,(0, 0, 0), 5) cv2.line(img, (Xmax , 0),(Xmax, Ymax) ,(0, 0, 0),", "in small_list]) new_elem = [0, new_y, Xmax, new_h] new_boxes_list.append(new_elem) return new_boxes_list def process_table(img_path,draw_path):", "(0, Ymax),(Xmax, Ymax) ,(0, 0, 0), 5) cv2.line(img, (Xmax , 0),(Xmax, Ymax) ,(0,", "Ymax) ,(0, 0, 0), 5) \"\"\" cv2.namedWindow(\"output2\", cv2.WINDOW_NORMAL) cv2.imshow('output2', img) def draw_lines(img_path, image_to_data,", "h) = (image_to_data['top'][i], image_to_data['height'][i]) p1 = create_polygon(0, y, Xmax, h) n_b = len(boxes_list)", "clean_loop(boxes_list): Xmax = boxes_list[1][2] n = len(boxes_list) global_flag = 0 all_to_be_merged = list()", "1) cv2.line(img, (0 , 0),(0, Ymax) ,LINE_COLOR, 5) cv2.line(img, (0 , 0),(Xmax, 0)", "elem = boxes_list[j] p2 = create_polygon(elem[0], elem[1], elem[2], elem[3]) if check_polygon_intersection(p1, p2): zero_distance.append(j)", "Xmax, h] boxes_list.append(new_elem) return boxes_list def clean_loop(boxes_list): Xmax = boxes_list[1][2] n = len(boxes_list)", "case a hole section is not detected. \"\"\" y_new = min(y_middle, y+h+margin) cv2.line(img,", "def check_intersection(elem1, elem2): for l in elem1: if l in elem2: return True", "for i in range(n_boxes): if filter_boxes(image_to_data, i) : (y, h) = (image_to_data['top'][i], image_to_data['height'][i])", "(0, 255, 0), 1) cv2.line(img, (0 , 0),(0, Ymax) ,LINE_COLOR, 5) cv2.line(img, (0", "LINE_WIDTH) \"\"\" cv2.line(img, (0 , 0),(0, Ymax) ,(0, 0, 0), 5) cv2.line(img, (0", ", 0),(Xmax, 0) ,(0, 0, 0), 5) cv2.line(img, (0, Ymax),(Xmax, Ymax) ,(0, 0,", "process_image_to_data(image_to_data, Xmax, Ymax): boxes_list = list() boxes_list.append([0, 0, 0, 0]) all_zero_distance = list()", "min(y, elem[1]) new_h = max(y+h, elem[1] + elem[3]) - min(y, elem[1]) new_elem =", "n_boxes = len(image_to_data['level']) for i in range(n_boxes): if filter_boxes(image_to_data, i) : (x, y,", "to_be_merged.append(boxe2) used_ind.append(j) all_to_be_merged.append(to_be_merged) n_detected = len(all_to_be_merged) new_boxes_list = list() for i in range(n_detected):", ", y_new),(w, y_new) ,LINE_COLOR, LINE_WIDTH) #cv2.line(img, (0 , y+h ), (Xmax + w,", "= pytesseract.image_to_data(img, output_type=Output.DICT) Xmax = img.shape[1] Ymax = img.shape[0] return image_to_data, Xmax, Ymax", "cv2 import os from shapely.geometry import Polygon pytesseract.pytesseract.tesseract_cmd = \"Tesseract path e.g c:\\Tesseract-OCR\\tesseract", "all_to_be_merged.append(to_be_merged) n_detected = len(all_to_be_merged) new_boxes_list = list() for i in range(n_detected): small_list =", "in used_ind: boxe2=boxes_list[j] p2 = create_polygon(boxe2[0],boxe2[1],boxe2[2],boxe2[3]) if check_polygon_intersection(p1, p2): to_be_merged.append(boxe2) used_ind.append(j) all_to_be_merged.append(to_be_merged) n_detected", "image_to_data): img = cv2.imread(img_path) Xmax = img.shape[1] n_boxes = len(image_to_data['level']) for i in", "between the bottom of the line and the next line top \"\"\" (x,", "i in range(n_detected): small_list = all_to_be_merged[i] p = len(small_list) new_y = min([boxe[1] for", "from pytesseract import Output import cv2 import os from shapely.geometry import Polygon pytesseract.pytesseract.tesseract_cmd", "check_intersection(elem1, elem2): for l in elem1: if l in elem2: return True return", "w, y + h), (0, 255, 0), 1) cv2.line(img, (0 , 0),(0, Ymax)", "cv2.line(img, (0 , 0),(Xmax, 0) ,(0, 0, 0), 5) cv2.line(img, (0, Ymax),(Xmax, Ymax)", "img = cv2.imread(img_path) Xmax = img.shape[1] n_boxes = len(image_to_data['level']) for i in range(n_boxes):", "= len(all_to_be_merged) new_boxes_list = list() for i in range(n_detected): small_list = all_to_be_merged[i] p", "n_detected = len(all_to_be_merged) new_boxes_list = list() for i in range(n_detected): small_list = all_to_be_merged[i]", "not in used_ind: boxe2=boxes_list[j] p2 = create_polygon(boxe2[0],boxe2[1],boxe2[2],boxe2[3]) if check_polygon_intersection(p1, p2): to_be_merged.append(boxe2) used_ind.append(j) all_to_be_merged.append(to_be_merged)", "draw_lines(img_path, image_to_data, margin =2) image_name = os.path.basename(img_path).split(os.extsep)[0].replace(\" \", \"_\") processed_im_path = draw_path+\"\\\\\"+image_name+'pro.png' cv2.imwrite(processed_im_path,", ": (y, h) = (image_to_data['top'][i], image_to_data['height'][i]) p1 = create_polygon(0, y, Xmax, h) n_b", "[0, new_y, Xmax, new_h] new_boxes_list.append(new_elem) return new_boxes_list def process_table(img_path,draw_path): #try: image_to_data, Xmax, Ymax", "in range(n_boxes-1): \"\"\" For each line, we will draw a line between the", "Ymax) ,LINE_COLOR, 5) cv2.line(img, (0 , 0),(Xmax, 0) ,LINE_COLOR, 5) cv2.line(img, (0, Ymax),(Xmax,", "return img def check_intersection(elem1, elem2): for l in elem1: if l in elem2:", ",LINE_COLOR, 5) cv2.line(img, (0, Ymax),(Xmax, Ymax) ,LINE_COLOR, 5) cv2.line(img, (Xmax , 0),(Xmax, Ymax)", "all_to_be_merged = list() used_ind = list() for i in range(n): if i not", "boxes_list.append([0, 0, 0, 0]) all_zero_distance = list() n_boxes = len(image_to_data['level']) \"\"\" A first", "zero_distance = list() for j in range(n_b): elem = boxes_list[j] p2 = create_polygon(elem[0],", "avoid the case of drawin a line over a word, we will set", "line top \"\"\" (x, y, w, h) = (image_to_data[i][0], image_to_data[i][1], image_to_data[i][2], image_to_data[i][3]) y_next", "#cv2.line(img, (0 , y +h +5 ),(Xmax, y +h +5) ,(0, 0, 0),", "output_type=Output.DICT) Xmax = img.shape[1] Ymax = img.shape[0] return image_to_data, Xmax, Ymax def draw_lines_v1(img_path,", "y+h+margin) cv2.line(img, (x , y_new),(w, y_new) ,LINE_COLOR, LINE_WIDTH) #cv2.line(img, (0 , y+h ),", "small_list]) new_elem = [0, new_y, Xmax, new_h] new_boxes_list.append(new_elem) return new_boxes_list def process_table(img_path,draw_path): #try:", "and the next line top \"\"\" (x, y, w, h) = (image_to_data[i][0], image_to_data[i][1],", "all_to_be_merged[i] p = len(small_list) new_y = min([boxe[1] for boxe in small_list]) new_h =", "+h +5) ,(0, 0, 0), 3) #cv2.line(img, (0 , y+h ), (Xmax +", "= img.shape[0] return image_to_data, Xmax, Ymax def draw_lines_v1(img_path, image_to_data): img = cv2.imread(img_path) Xmax", "return new_boxes_list def process_table(img_path,draw_path): #try: image_to_data, Xmax, Ymax = get_image_data(img_path) image_to_data = process_image_to_data(image_to_data,", "create_polygon(x, y, w, h): p = Polygon([(x, y),(x+w, y),(x+w, y + h),(x, y", "check_polygon_intersection(p1, p2): to_be_merged.append(boxe2) used_ind.append(j) all_to_be_merged.append(to_be_merged) n_detected = len(all_to_be_merged) new_boxes_list = list() for i", "image_to_data, Xmax, Ymax def draw_lines_v1(img_path, image_to_data): img = cv2.imread(img_path) Xmax = img.shape[1] n_boxes", "+h +5 ),(Xmax, y +h +5) ,(0, 0, 0), 3) #cv2.line(img, (0 ,", "= list() n_boxes = len(image_to_data['level']) \"\"\" A first loop to merge close boxes", "(x , y_new),(w, y_new) ,LINE_COLOR, LINE_WIDTH) #cv2.line(img, (0 , y+h ), (Xmax +", "each line, we will draw a line between the bottom of the line", "def draw_lines_v1(img_path, image_to_data): img = cv2.imread(img_path) Xmax = img.shape[1] n_boxes = len(image_to_data['level']) for", "#cv2.line(img, (0 , y+h ), (Xmax + w, y + h), (0, 255,", "j not in used_ind: boxe2=boxes_list[j] p2 = create_polygon(boxe2[0],boxe2[1],boxe2[2],boxe2[3]) if check_polygon_intersection(p1, p2): to_be_merged.append(boxe2) used_ind.append(j)", "line between the bottom of the line and the next line top \"\"\"", "Xmax, new_h] new_boxes_list.append(new_elem) return new_boxes_list def process_table(img_path,draw_path): #try: image_to_data, Xmax, Ymax = get_image_data(img_path)", "in used_ind: to_be_merged = list() boxe1 = boxes_list[i] p1 = create_polygon(boxe1[0],boxe1[1],boxe1[2],boxe1[3]) m =", "= img.shape[1] n_boxes = len(image_to_data['level']) for i in range(n_boxes): if filter_boxes(image_to_data, i) :", "LINE_COLOR, LINE_WIDTH) \"\"\" cv2.line(img, (0 , 0),(0, Ymax) ,(0, 0, 0), 5) cv2.line(img,", "import join ## Hyper Params L = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' CHAR_THRESHOLD = 3 LINE_WIDTH =", "(x, y, w, h) = (image_to_data[i][0], image_to_data[i][1], image_to_data[i][2], image_to_data[i][3]) y_next = image_to_data[i+1][1] y_middle", "threshold to y_middle, In case a hole section is not detected. \"\"\" y_new", "0) ## Algo def get_image_data(img_path): img = cv2.imread(img_path) image_to_data = pytesseract.image_to_data(img, output_type=Output.DICT) Xmax", ",(0, 0, 0), 5) cv2.line(img, (Xmax , 0),(Xmax, Ymax) ,(0, 0, 0), 5)", "Ymax),(Xmax, Ymax) ,LINE_COLOR, 5) cv2.line(img, (Xmax , 0),(Xmax, Ymax) ,LINE_COLOR, 5) #cv2.namedWindow(\"output\", cv2.WINDOW_NORMAL)", "> CHAR_THRESHOLD and w > h: return True return False def process_image_to_data(image_to_data, Xmax,", "p2): if p1.distance(p2) == 0 : return True return False def create_polygon(x, y,", "boxes_list[i] p1 = create_polygon(boxe1[0],boxe1[1],boxe1[2],boxe1[3]) m = len(boxes_list) for j in range(m): if j", "j in range(m): if j not in used_ind: boxe2=boxes_list[j] p2 = create_polygon(boxe2[0],boxe2[1],boxe2[2],boxe2[3]) if", ": return True return False def create_polygon(x, y, w, h): p = Polygon([(x,", "= [0, y, Xmax, h] boxes_list.append(new_elem) return boxes_list def clean_loop(boxes_list): Xmax = boxes_list[1][2]", "img.shape[0] n_boxes = len(image_to_data) for i in range(n_boxes-1): \"\"\" For each line, we", "h: return True return False def process_image_to_data(image_to_data, Xmax, Ymax): boxes_list = list() boxes_list.append([0,", "return p def filter_boxes(image_to_data, ind): text = image_to_data[\"text\"][ind] h = image_to_data[\"height\"][ind] w =", "pytesseract from pytesseract import Output import cv2 import os from shapely.geometry import Polygon", "= list() boxes_list.append([0, 0, 0, 0]) all_zero_distance = list() n_boxes = len(image_to_data['level']) \"\"\"", ",LINE_COLOR, 5) cv2.line(img, (0 , 0),(Xmax, 0) ,LINE_COLOR, 5) cv2.line(img, (0, Ymax),(Xmax, Ymax)", "range(m): if j not in used_ind: boxe2=boxes_list[j] p2 = create_polygon(boxe2[0],boxe2[1],boxe2[2],boxe2[3]) if check_polygon_intersection(p1, p2):", "in small_list]) new_h = max([boxe[1] + boxe[3] - new_y for boxe in small_list])", "= listdir(file_path) n = len(all_files) for i in range(n): f = all_files[i] img_path", "True return False ## Processing extracted boxes def check_polygon_intersection(p1, p2): if p1.distance(p2) ==", "image_to_data['top'][i], image_to_data['width'][i], image_to_data['height'][i]) #cv2.line(img, (0 , y +h +5 ),(Xmax, y +h +5)", "image_to_data = pytesseract.image_to_data(img, output_type=Output.DICT) Xmax = img.shape[1] Ymax = img.shape[0] return image_to_data, Xmax,", "import Polygon pytesseract.pytesseract.tesseract_cmd = \"Tesseract path e.g c:\\Tesseract-OCR\\tesseract \" import sys from os", "y + h),(x, y + h)]) return p def filter_boxes(image_to_data, ind): text =", "2 LINE_COLOR = (0, 0, 0) ## Algo def get_image_data(img_path): img = cv2.imread(img_path)", "we will draw a line between the bottom of the line and the", ",(0, 0, 0), 5) cv2.line(img, (0 , 0),(Xmax, 0) ,(0, 0, 0), 5)", "a line between the bottom of the line and the next line top", "y), ( x + w, y + h), (0, 255, 0), 1) cv2.line(img,", "image_to_data[\"height\"][ind] w = image_to_data[\"width\"][ind] if len(text) > CHAR_THRESHOLD and w > h: return", "text = image_to_data[\"text\"][ind] h = image_to_data[\"height\"][ind] w = image_to_data[\"width\"][ind] if len(text) > CHAR_THRESHOLD", "), (Xmax + w, y + h), (0, 255, 0), 1) #cv2.rectangle(img, (x,", "list() for i in range(n_detected): small_list = all_to_be_merged[i] p = len(small_list) new_y =", ",LINE_COLOR, 5) #cv2.namedWindow(\"output\", cv2.WINDOW_NORMAL) #cv2.imshow('output', img) return img def check_intersection(elem1, elem2): for l", "= (image_to_data['left'][i], image_to_data['top'][i], image_to_data['width'][i], image_to_data['height'][i]) #cv2.line(img, (0 , y +h +5 ),(Xmax, y", "( x + w, y + h), (0, 255, 0), 1) cv2.line(img, (0", "5) cv2.line(img, (0, Ymax),(Xmax, Ymax) ,(0, 0, 0), 5) cv2.line(img, (Xmax , 0),(Xmax,", "0), 1) cv2.line(img, (0 , 0),(0, Ymax) ,LINE_COLOR, 5) cv2.line(img, (0 , 0),(Xmax,", "new_h] boxes_list[j]=new_elem flag = 1 if flag == 0 : new_elem = [0,", "= len(boxes_list) flag = 0 zero_distance = list() for j in range(n_b): elem", "> h: return True return False def process_image_to_data(image_to_data, Xmax, Ymax): boxes_list = list()", "from os.path import join ## Hyper Params L = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' CHAR_THRESHOLD = 3", "p1.distance(p2) == 0 : return True return False def create_polygon(x, y, w, h):", "used_ind = list() for i in range(n): if i not in used_ind: to_be_merged", "= cv2.imread(img_path) image_to_data = pytesseract.image_to_data(img, output_type=Output.DICT) Xmax = img.shape[1] Ymax = img.shape[0] return", "= (image_to_data[i][0], image_to_data[i][1], image_to_data[i][2], image_to_data[i][3]) y_next = image_to_data[i+1][1] y_middle = (y+h+y_next)//2 \"\"\" To", "== 0 : new_elem = [0, y, Xmax, h] boxes_list.append(new_elem) return boxes_list def", "255, 0), 1) cv2.rectangle(img, (x, y), ( x + w, y + h),", "#cv2.namedWindow(\"output\", cv2.WINDOW_NORMAL) #cv2.imshow('output', img) return img def check_intersection(elem1, elem2): for l in elem1:", "\"\"\" Draw extracted and filtred boxes \"\"\" img = cv2.imread(img_path) Xmax = img.shape[1]", "range(n_boxes): if filter_boxes(image_to_data, i) : (y, h) = (image_to_data['top'][i], image_to_data['height'][i]) p1 = create_polygon(0,", "over a word, we will set a threshold to y_middle, In case a", "= boxes_list[j] p2 = create_polygon(elem[0], elem[1], elem[2], elem[3]) if check_polygon_intersection(p1, p2): zero_distance.append(j) new_y", "new_boxes_list def process_table(img_path,draw_path): #try: image_to_data, Xmax, Ymax = get_image_data(img_path) image_to_data = process_image_to_data(image_to_data, Xmax,", "l in elem1: if l in elem2: return True return False ## Processing", "5) cv2.line(img, (0, Ymax),(Xmax, Ymax) ,LINE_COLOR, 5) cv2.line(img, (Xmax , 0),(Xmax, Ymax) ,LINE_COLOR,", "y +h +5) ,(0, 0, 0), 3) #cv2.line(img, (0 , y+h ), (Xmax", "def filter_boxes(image_to_data, ind): text = image_to_data[\"text\"][ind] h = image_to_data[\"height\"][ind] w = image_to_data[\"width\"][ind] if", "= image_to_data[\"width\"][ind] if len(text) > CHAR_THRESHOLD and w > h: return True return", "clean_loop(image_to_data) img = draw_lines(img_path, image_to_data, margin =2) image_name = os.path.basename(img_path).split(os.extsep)[0].replace(\" \", \"_\") processed_im_path", "y_new),(w, y_new) ,LINE_COLOR, LINE_WIDTH) #cv2.line(img, (0 , y+h ), (Xmax + w, y", "Ymax = img.shape[0] n_boxes = len(image_to_data) for i in range(n_boxes-1): \"\"\" For each", "in elem1: if l in elem2: return True return False ## Processing extracted", "img) def draw_lines(img_path, image_to_data, margin = 0): \"\"\" Draw extracted and filtred boxes", "line, we will draw a line between the bottom of the line and", "boxes_list[1][2] n = len(boxes_list) global_flag = 0 all_to_be_merged = list() used_ind = list()", "w, h) = (image_to_data[i][0], image_to_data[i][1], image_to_data[i][2], image_to_data[i][3]) y_next = image_to_data[i+1][1] y_middle = (y+h+y_next)//2", "Xmax, Ymax): boxes_list = list() boxes_list.append([0, 0, 0, 0]) all_zero_distance = list() n_boxes", "= boxes_list[1][2] n = len(boxes_list) global_flag = 0 all_to_be_merged = list() used_ind =", "y_new) ,LINE_COLOR, LINE_WIDTH) #cv2.line(img, (0 , y+h ), (Xmax + w, y +" ]
[ "_('Can view scheduled private lessons for all instructors')), ) verbose_name = _('Private lesson')", "null=True, blank=True, on_delete=models.SET_NULL, related_name='privateLessonSlots' ) creationDate = models.DateTimeField(auto_now_add=True) modifiedDate = models.DateTimeField(auto_now=True) @property def", "danceschool.core.constants import getConstant from danceschool.core.mixins import EmailRecipientMixin from danceschool.core.utils.timezone import ensure_localtime class InstructorPrivateLessonDetails(models.Model):", "models.PositiveSmallIntegerField(_('Expected # of Participants'), null=True, blank=True, default=1) comments = models.TextField( _('Comments/Notes'), null=True, blank=True,", "% ( self.instructor.fullName, ensure_localtime(self.startTime).strftime('%b %-d, %Y %-I:%M %p'), self.location ) def __str__(self): return", "''' Used for various pricing discounts related things ''' return self.instructoravailabilityslot_set.count() @property def", "verbose_name=_('Default Pricing Tier'), null=True, blank=True, on_delete=models.SET_NULL ) roles = models.ManyToManyField(DanceRole, blank=True) couples =", "class by checking the pricingTier associated with this PrivateLessonEvent and getting the appropriate", "# This is the email template used to notify students that their private", "has been # successfully scheduled template = getConstant('privateLessons__lessonBookedEmailTemplate') if template.defaultFromAddress and template.content: for", "import getConstant from danceschool.core.mixins import EmailRecipientMixin from danceschool.core.utils.timezone import ensure_localtime class InstructorPrivateLessonDetails(models.Model): instructor", "= self.duration max_duration = self.duration for slot in potential_slots: if max_duration + slot.duration", "if template.defaultFromAddress and template.content: for customer in self.customers: customer.email_recipient( template.subject, template.content, send_html=False, from_address=template.defaultFromAddress,", "associated with this PrivateLessonEvent and getting the appropriate price for it. ''' if", "toward a discount. Since private lesson points are based on the number of", "Available slots are available, but also tentative slots that have been held as", "be able to identify the Event that was created for this private lesson.", "If installed, the discounts app looks for this property to determine how many", "the individuals who are registered. For private lessons that are booked without payment,", "_('Tentative Booking')) unavailable = ('U', _('Unavailable')) instructor = models.ForeignKey(Instructor, verbose_name=_('Instructor'), on_delete=models.CASCADE) pricingTier =", "kwargs.get('notifyStudent', True) notifyTeachers = kwargs.get('notifyTeachers', getConstant('privateLessons__notifyInstructor')) eventRegistration = kwargs.get('eventRegistration', None) affectedSlots = self.instructoravailabilityslot_set.all()", "withDate: return _('Private Lesson') return _('Private Lesson: %s%s%s%s' % ( teacherNames, _(' for", "always be booked for the length of a single slot, but this method", "verbose_name=_('Instructor'), on_delete=models.CASCADE) pricingTier = models.ForeignKey( PricingTier, verbose_name=_('Pricing Tier'), null=True, blank=True, on_delete=models.SET_NULL ) startTime", ") @property def customers(self): ''' List both any individuals signed up via the", "+= slot.duration return duration_list @property def availableRoles(self): ''' Some instructors only offer private", "provides a record that they signed up for the lesson. ''' customer =", "for all instructors')), ) verbose_name = _('Private lesson') verbose_name_plural = _('Private lessons') class", "verbose_name_plural = _('Private lessons') class PrivateLessonCustomer(models.Model): ''' For private lessons that go through", ") eventRegistration = models.ForeignKey( EventRegistration, verbose_name=_('event registration'), null=True, blank=True, on_delete=models.SET_NULL, related_name='privateLessonSlots' ) creationDate", "private lessons for all instructors')), ) verbose_name = _('Private lesson') verbose_name_plural = _('Private", "if (teacherNames or customerNames) else '') + self.startTime.strftime('%Y-%m-%d') ) if withDate else ''", "types of events (location, etc.) ''' pricingTier = models.ForeignKey( PricingTier, verbose_name=_('Pricing Tier'), null=True,", "class PrivateLessonCustomer(models.Model): ''' For private lessons that go through registration and payment, the", "registrations and a link to the event because # in the event that", "any individuals signed up via the registration and payment system, and any individuals", "have been held as tentative past their expiration date ''' return ( self.startTime", "available. This method requires that slots are non-overlapping, which needs to be enforced", "discountPointsMultiplier(self): ''' If installed, the discounts app looks for this property to determine", "= self.startTime last_duration = self.duration max_duration = self.duration for slot in potential_slots: if", "verbose_name=_('Pricing Tier'), null=True, blank=True, on_delete=models.SET_NULL ) startTime = models.DateTimeField(_('Start time')) duration = models.PositiveSmallIntegerField(_('Slot", "the pricingTier associated with this PrivateLessonEvent and getting the appropriate price for it.", "the user books a lesson. All of the registration logic is still handled", "the instructor. ''' if not hasattr(self.instructor, 'instructorprivatelessondetails'): return [] return [ [x.id, x.name]", "for x in self.customers]) elif self.eventregistration_set.all(): names = ' and '.join([x.registration.fullName for x", "successfully scheduled template = getConstant('privateLessons__lessonBookedEmailTemplate') if template.defaultFromAddress and template.content: for customer in self.customers:", "from_address=template.defaultFromAddress, from_name=template.defaultFromName, cc=template.defaultCC, to=instructor.privateEmail or instructor.publicEmail, lesson=self, instructor=instructor, customers=self.customers, calendarUrl=reverse('privateCalendar'), ) @property def", "slot.duration max_duration += slot.duration return duration_list @property def availableRoles(self): ''' Some instructors only", "associated with other types of events (location, etc.) ''' pricingTier = models.ForeignKey( PricingTier,", "== last_start + timedelta(minutes=last_duration) and slot.isAvailable ): duration_list.append(max_duration + slot.duration) last_start = slot.startTime", ") if withDate else '' )) @property def name(self): return self.nameAndDate(withDate=True) def save(self,", "'' else: customerNames = '' if not teacherNames and not customerNames and not", "in self.instructor.instructorprivatelessondetails.roles.all() ] def checkIfAvailable(self, dateTime=timezone.now()): ''' Available slots are available, but also", "signed up without payment. ''' return Customer.objects.filter( Q(privatelessoncustomer__lesson=self) | Q(registration__eventregistration__event=self) ).distinct() customers.fget.short_description =", "be enforced on slot save. ''' potential_slots = InstructorAvailabilitySlot.objects.filter( instructor=self.instructor, location=self.location, room=self.room, pricingTier=self.pricingTier,", "for it. ''' if not self.pricingTier: return None return self.pricingTier.getBasePrice(**kwargs) * max(self.numSlots, 1)", "(self.customer.fullName, self.lesson.id))) class Meta: unique_together = ('customer', 'lesson') verbose_name = _('Private lesson customer')", "customers') class InstructorAvailabilitySlot(models.Model): class SlotStatus(models.TextChoices): available = ('A', _('Available')) booked = ('B', _('Booked'))", "template.content, send_html=False, from_address=template.defaultFromAddress, from_name=template.defaultFromName, cc=template.defaultCC, to=customer.email, lesson=self, ) if notifyTeachers: # This is", "self.duration for slot in potential_slots: if max_duration + slot.duration > getConstant('privateLessons__maximumLessonLength'): break if", "in potential_slots: if max_duration + slot.duration > getConstant('privateLessons__maximumLessonLength'): break if ( slot.startTime ==", "'.join([x.fullName for x in self.customers]) elif self.eventregistration_set.all(): names = ' and '.join([x.registration.fullName for", "class Meta: unique_together = ('customer', 'lesson') verbose_name = _('Private lesson customer') verbose_name_plural =", "slots') permissions = ( ('edit_own_availability', _('Can edit one\\'s own private lesson availability.')), ('edit_others_availability',", "= models.ManyToManyField(DanceRole, blank=True) couples = models.BooleanField(_('Private lessons for couples'), default=True) smallGroups = models.BooleanField(_('Private", "template = getConstant('privateLessons__lessonBookedInstructorEmailTemplate') if template.defaultFromAddress and template.content: emailMixin = EmailRecipientMixin() instructors = [", "the number of slots booked, this just returns the number of slots associated", "'instructor__firstName') verbose_name = _('Private lesson availability slot') verbose_name_plural = _('Private lesson availability slots')", "for customer in self.customers: customer.email_recipient( template.subject, template.content, send_html=False, from_address=template.defaultFromAddress, from_name=template.defaultFromName, cc=template.defaultCC, to=customer.email, lesson=self,", "allow booking for the roles that have been selected for the instructor. '''", "def availableRoles(self): ''' Some instructors only offer private lessons for certain roles, so", "not self.eventRegistration and ( self.status == self.SlotStatus.available or ( self.status == self.SlotStatus.tentative and", "% self.instructor.fullName)) class Meta: ordering = ('instructor__lastName', 'instructor__firstName') verbose_name = _('Instructor private lesson", "email template used to notify students that their private lesson has been #", "registers. The event is created when the user books a lesson. All of", "self.customers: customer.email_recipient( template.subject, template.content, send_html=False, from_address=template.defaultFromAddress, from_name=template.defaultFromName, cc=template.defaultCC, to=customer.email, lesson=self, ) if notifyTeachers:", "to identify the Event that was created for this private lesson. lessonEvent =", "return duration_list @property def availableRoles(self): ''' Some instructors only offer private lessons for", "timedelta(minutes=last_duration) and slot.isAvailable ): duration_list.append(max_duration + slot.duration) last_start = slot.startTime last_duration = slot.duration", "template.defaultFromAddress and template.content: for customer in self.customers: customer.email_recipient( template.subject, template.content, send_html=False, from_address=template.defaultFromAddress, from_name=template.defaultFromName,", "we should only allow booking for the roles that have been selected for", "roles = models.ManyToManyField(DanceRole, blank=True) couples = models.BooleanField(_('Private lessons for couples'), default=True) smallGroups =", "'') + self.startTime.strftime('%Y-%m-%d') ) if withDate else '' )) @property def name(self): return", "name(self): return self.nameAndDate(withDate=True) def save(self, *args, **kwargs): ''' Set registration status to hidden", "_ from django.utils import timezone from django.urls import reverse from datetime import timedelta", "location = models.ForeignKey( Location, verbose_name=_('Location'), null=True, blank=True, on_delete=models.SET_NULL, ) room = models.ForeignKey( Room,", "a link to the registrations and a link to the event because #", "are non-overlapping, which needs to be enforced on slot save. ''' potential_slots =", "lessons that go through registration and payment, the customers are the individuals who", "of slots associated with this event (or 1). ''' return max(self.numSlots, 1) def", "send_html=False, from_address=template.defaultFromAddress, from_name=template.defaultFromName, cc=template.defaultCC, to=customer.email, lesson=self, ) if notifyTeachers: # This is the", "default=SlotStatus.available) # We need both a link to the registrations and a link", "getConstant('privateLessons__maximumLessonLength'): break if ( slot.startTime == last_start + timedelta(minutes=last_duration) and slot.isAvailable ): duration_list.append(max_duration", "available, but also tentative slots that have been held as tentative past their", "# isAvailable indicates if a slot is currently available isAvailable = property(fget=checkIfAvailable) isAvailable.fget.short_description", "name(self): return _('%s: %s at %s') % ( self.instructor.fullName, ensure_localtime(self.startTime).strftime('%b %-d, %Y %-I:%M", "= models.BooleanField(_('Private lessons for small groups'), default=True) def __str__(self): return str(_('Instructor Private lesson", "details') class PrivateLessonEvent(Event): ''' This is the event object for which an individual", "= ('U', _('Unavailable')) instructor = models.ForeignKey(Instructor, verbose_name=_('Instructor'), on_delete=models.CASCADE) pricingTier = models.ForeignKey( PricingTier, verbose_name=_('Pricing", "__str__(self): return str(_('Instructor Private lesson details for %s' % self.instructor.fullName)) class Meta: ordering", "lessons') class PrivateLessonCustomer(models.Model): ''' For private lessons that go through registration and payment,", "%-I:%M %p'), self.location ) def __str__(self): return str(self.name) class Meta: ordering = ('-startTime',", "= ('-startTime', 'instructor__lastName', 'instructor__firstName') verbose_name = _('Private lesson availability slot') verbose_name_plural = _('Private", "is deleted, we still want to # be able to identify the Event", "PricingTier, verbose_name=_('Pricing Tier'), null=True, blank=True, on_delete=models.SET_NULL ) participants = models.PositiveSmallIntegerField(_('Expected # of Participants'),", "blank=True, help_text=_('For internal use and recordkeeping.') ) def getBasePrice(self, **kwargs): ''' This method", "def nameAndDate(self, withDate=True): teacherNames = ' and '.join([x.staffMember.fullName for x in self.eventstaffmember_set.all()]) if", "customer.email_recipient( template.subject, template.content, send_html=False, from_address=template.defaultFromAddress, from_name=template.defaultFromName, cc=template.defaultCC, to=customer.email, lesson=self, ) if notifyTeachers: #", "scheduled private lessons for all instructors')), ) verbose_name = _('Private lesson') verbose_name_plural =", "kwargs.get('notifyTeachers', getConstant('privateLessons__notifyInstructor')) eventRegistration = kwargs.get('eventRegistration', None) affectedSlots = self.instructoravailabilityslot_set.all() affectedSlots.update( status=InstructorAvailabilitySlot.SlotStatus.booked, eventRegistration=eventRegistration, )", "PricingTier, verbose_name=_('Default Pricing Tier'), null=True, blank=True, on_delete=models.SET_NULL ) roles = models.ManyToManyField(DanceRole, blank=True) couples", "affectedSlots = self.instructoravailabilityslot_set.all() affectedSlots.update( status=InstructorAvailabilitySlot.SlotStatus.booked, eventRegistration=eventRegistration, ) if notifyStudent: # This is the", "customerNames = '' if not teacherNames and not customerNames and not withDate: return", "_('Private lesson') verbose_name_plural = _('Private lessons') class PrivateLessonCustomer(models.Model): ''' For private lessons that", "created when the user books a lesson. All of the registration logic is", ") if notifyTeachers: # This is the email template used to notify individuals", "self.lesson.id))) class Meta: unique_together = ('customer', 'lesson') verbose_name = _('Private lesson customer') verbose_name_plural", "for the length of a single slot, but this method checks if multiple", "models.ForeignKey( PricingTier, verbose_name=_('Default Pricing Tier'), null=True, blank=True, on_delete=models.SET_NULL ) roles = models.ManyToManyField(DanceRole, blank=True)", "models.ForeignKey( PrivateLessonEvent, verbose_name=_('Scheduled lesson'), null=True, blank=True, on_delete=models.SET_NULL, ) eventRegistration = models.ForeignKey( EventRegistration, verbose_name=_('event", "lesson can always be booked for the length of a single slot, but", ") status = models.CharField(max_length=1, choices=SlotStatus.choices, default=SlotStatus.available) # We need both a link to", "slot') verbose_name_plural = _('Private lesson availability slots') permissions = ( ('edit_own_availability', _('Can edit", "self.startTime.strftime('%Y-%m-%d') ) if withDate else '' )) @property def name(self): return self.nameAndDate(withDate=True) def", "last_start = slot.startTime last_duration = slot.duration max_duration += slot.duration return duration_list @property def", "affectedSlots.update( status=InstructorAvailabilitySlot.SlotStatus.booked, eventRegistration=eventRegistration, ) if notifyStudent: # This is the email template used", "= ( ('view_others_lessons', _('Can view scheduled private lessons for all instructors')), ) verbose_name", "customerNames and not withDate: return _('Private Lesson') return _('Private Lesson: %s%s%s%s' % (", "= property(fget=checkIfAvailable) isAvailable.fget.short_description = _('Available') @property def name(self): return _('%s: %s at %s')", "both any individuals signed up via the registration and payment system, and any", "to # be able to identify the Event that was created for this", "== Event.RegStatus.hidden super().save(*args, **kwargs) def __str__(self): return str(self.name) class Meta: permissions = (", "withDate=True): teacherNames = ' and '.join([x.staffMember.fullName for x in self.eventstaffmember_set.all()]) if self.customers: customerNames", "= kwargs.get('eventRegistration', None) affectedSlots = self.instructoravailabilityslot_set.all() affectedSlots.update( status=InstructorAvailabilitySlot.SlotStatus.booked, eventRegistration=eventRegistration, ) if notifyStudent: #", "'lesson') verbose_name = _('Private lesson customer') verbose_name_plural = _('Private lesson customers') class InstructorAvailabilitySlot(models.Model):", "( Instructor, Location, Room, DanceRole, Event, PricingTier, EventRegistration, Customer, StaffMember ) from danceschool.core.constants", "slots that have been held as tentative past their expiration date ''' return", "lesson details') class PrivateLessonEvent(Event): ''' This is the event object for which an", "last_duration = slot.duration max_duration += slot.duration return duration_list @property def availableRoles(self): ''' Some", "for ') if teacherNames and customerNames else '', customerNames, ( (', ' if", "+ self.startTime.strftime('%Y-%m-%d') ) if withDate else '' )) @property def name(self): return self.nameAndDate(withDate=True)", "of slots booked, this just returns the number of slots associated with this", "= models.ForeignKey( Room, verbose_name=_('Room'), null=True, blank=True, on_delete=models.SET_NULL, ) status = models.CharField(max_length=1, choices=SlotStatus.choices, default=SlotStatus.available)", "pricingTier=self.pricingTier, startTime__gte=self.startTime, startTime__lte=self.startTime + timedelta(minutes=getConstant('privateLessons__maximumLessonLength')), ).exclude(id=self.id).order_by('startTime') duration_list = [self.duration, ] last_start = self.startTime", "from_address=template.defaultFromAddress, from_name=template.defaultFromName, cc=template.defaultCC, to=customer.email, lesson=self, ) if notifyTeachers: # This is the email", "timedelta(days=getConstant('privateLessons__openBookingDays')) and not self.eventRegistration and ( self.status == self.SlotStatus.available or ( self.status ==", "danceschool.core.models import ( Instructor, Location, Room, DanceRole, Event, PricingTier, EventRegistration, Customer, StaffMember )", "models.ForeignKey( Room, verbose_name=_('Room'), null=True, blank=True, on_delete=models.SET_NULL, ) status = models.CharField(max_length=1, choices=SlotStatus.choices, default=SlotStatus.available) #", "Private lesson details for %s' % self.instructor.fullName)) class Meta: ordering = ('instructor__lastName', 'instructor__firstName')", "for small groups'), default=True) def __str__(self): return str(_('Instructor Private lesson details for %s'", "to=customer.email, lesson=self, ) if notifyTeachers: # This is the email template used to", "and template.content: for customer in self.customers: customer.email_recipient( template.subject, template.content, send_html=False, from_address=template.defaultFromAddress, from_name=template.defaultFromName, cc=template.defaultCC,", "number of slots booked, this just returns the number of slots associated with", "we still want to # be able to identify the Event that was", "that have been selected for the instructor. ''' if not hasattr(self.instructor, 'instructorprivatelessondetails'): return", "for x in self.eventregistration_set.all()]) customerNames = ' ' + names if names else", "self.pricingTier: return None return self.pricingTier.getBasePrice(**kwargs) * max(self.numSlots, 1) def finalizeBooking(self, **kwargs): notifyStudent =", "notifyStudent = kwargs.get('notifyStudent', True) notifyTeachers = kwargs.get('notifyTeachers', getConstant('privateLessons__notifyInstructor')) eventRegistration = kwargs.get('eventRegistration', None) affectedSlots", "Since private lesson points are based on the number of slots booked, this", "teacherNames and customerNames else '', customerNames, ( (', ' if (teacherNames or customerNames)", "and getattr( getattr( getattr(self.eventRegistration, 'invoiceItem', None), 'invoice', None ), 'expirationDate', timezone.now() ) <=", "for couples'), default=True) smallGroups = models.BooleanField(_('Private lessons for small groups'), default=True) def __str__(self):", "emailMixin = EmailRecipientMixin() instructors = [ x.staffMember for x in self.eventstaffmember_set.exclude( Q(staffMember__privateEmail__isnull=True) &", "= ' ' + ' and '.join([x.fullName for x in self.customers]) elif self.eventregistration_set.all():", "potential_slots: if max_duration + slot.duration > getConstant('privateLessons__maximumLessonLength'): break if ( slot.startTime == last_start", "an individual registers. The event is created when the user books a lesson.", "slot.startTime last_duration = slot.duration max_duration += slot.duration return duration_list @property def availableRoles(self): '''", "that their private lesson has been # successfully scheduled template = getConstant('privateLessons__lessonBookedEmailTemplate') if", "for the instructor. ''' if not hasattr(self.instructor, 'instructorprivatelessondetails'): return [] return [ [x.id,", "discounts app looks for this property to determine how many points this lesson", "defaultPricingTier = models.ForeignKey( PricingTier, verbose_name=_('Default Pricing Tier'), null=True, blank=True, on_delete=models.SET_NULL ) roles =", "that have been held as tentative past their expiration date ''' return (", "''' A lesson can always be booked for the length of a single", "verbose_name=_('Lesson'), on_delete=models.CASCADE ) def __str__(self): return str(_('Private lesson customer: %s for lesson #%s'", "danceschool.core.mixins import EmailRecipientMixin from danceschool.core.utils.timezone import ensure_localtime class InstructorPrivateLessonDetails(models.Model): instructor = models.OneToOneField(StaffMember, on_delete=models.CASCADE)", "and not customerNames and not withDate: return _('Private Lesson') return _('Private Lesson: %s%s%s%s'", "is the event object for which an individual registers. The event is created", "used to notify students that their private lesson has been # successfully scheduled", "discount. Since private lesson points are based on the number of slots booked,", "( teacherNames, _(' for ') if teacherNames and customerNames else '', customerNames, (", "this just provides a record that they signed up for the lesson. '''", "danceschool.core.utils.timezone import ensure_localtime class InstructorPrivateLessonDetails(models.Model): instructor = models.OneToOneField(StaffMember, on_delete=models.CASCADE) defaultPricingTier = models.ForeignKey( PricingTier,", "unique_together = ('customer', 'lesson') verbose_name = _('Private lesson customer') verbose_name_plural = _('Private lesson", "pricingTier = models.ForeignKey( PricingTier, verbose_name=_('Pricing Tier'), null=True, blank=True, on_delete=models.SET_NULL ) startTime = models.DateTimeField(_('Start", "def __str__(self): return str(self.name) class Meta: permissions = ( ('view_others_lessons', _('Can view scheduled", "in self.eventregistration_set.all()]) customerNames = ' ' + names if names else '' else:", "models from django.db.models import Q from django.utils.translation import gettext_lazy as _ from django.utils", "**kwargs): notifyStudent = kwargs.get('notifyStudent', True) notifyTeachers = kwargs.get('notifyTeachers', getConstant('privateLessons__notifyInstructor')) eventRegistration = kwargs.get('eventRegistration', None)", "max(self.numSlots, 1) def finalizeBooking(self, **kwargs): notifyStudent = kwargs.get('notifyStudent', True) notifyTeachers = kwargs.get('notifyTeachers', getConstant('privateLessons__notifyInstructor'))", "@property def discountPointsMultiplier(self): ''' If installed, the discounts app looks for this property", "names else '' else: customerNames = '' if not teacherNames and not customerNames", "class Meta: permissions = ( ('view_others_lessons', _('Can view scheduled private lessons for all", "= models.PositiveSmallIntegerField(_('Expected # of Participants'), null=True, blank=True, default=1) comments = models.TextField( _('Comments/Notes'), null=True,", "''' if not hasattr(self.instructor, 'instructorprivatelessondetails'): return [] return [ [x.id, x.name] for x", "Event, PricingTier, EventRegistration, Customer, StaffMember ) from danceschool.core.constants import getConstant from danceschool.core.mixins import", "instructor.publicEmail, lesson=self, instructor=instructor, customers=self.customers, calendarUrl=reverse('privateCalendar'), ) @property def customers(self): ''' List both any", "self.instructor.instructorprivatelessondetails.roles.all() ] def checkIfAvailable(self, dateTime=timezone.now()): ''' Available slots are available, but also tentative", "This is the email template used to notify students that their private lesson", "timezone.now() ) ) ) # isAvailable indicates if a slot is currently available", "def __str__(self): return str(self.name) class Meta: ordering = ('-startTime', 'instructor__lastName', 'instructor__firstName') verbose_name =", ") startTime = models.DateTimeField(_('Start time')) duration = models.PositiveSmallIntegerField(_('Slot duration (minutes)'), default=30) location =", "when the user books a lesson. All of the registration logic is still", "This method overrides the method of the base Event class by checking the", "null=True, blank=True, on_delete=models.SET_NULL, ) status = models.CharField(max_length=1, choices=SlotStatus.choices, default=SlotStatus.available) # We need both", "tentative slots that have been held as tentative past their expiration date '''", "lesson points are based on the number of slots booked, this just returns", "customerNames) else '') + self.startTime.strftime('%Y-%m-%d') ) if withDate else '' )) @property def", "notifyTeachers = kwargs.get('notifyTeachers', getConstant('privateLessons__notifyInstructor')) eventRegistration = kwargs.get('eventRegistration', None) affectedSlots = self.instructoravailabilityslot_set.all() affectedSlots.update( status=InstructorAvailabilitySlot.SlotStatus.booked,", "if ( slot.startTime == last_start + timedelta(minutes=last_duration) and slot.isAvailable ): duration_list.append(max_duration + slot.duration)", "verbose_name_plural = _('Instructors\\' private lesson details') class PrivateLessonEvent(Event): ''' This is the event", "models.CharField(max_length=1, choices=SlotStatus.choices, default=SlotStatus.available) # We need both a link to the registrations and", "def getBasePrice(self, **kwargs): ''' This method overrides the method of the base Event", "> getConstant('privateLessons__maximumLessonLength'): break if ( slot.startTime == last_start + timedelta(minutes=last_duration) and slot.isAvailable ):", "Customer.objects.filter( Q(privatelessoncustomer__lesson=self) | Q(registration__eventregistration__event=self) ).distinct() customers.fget.short_description = _('Customers') @property def numSlots(self): ''' Used", "various pricing discounts related things ''' return self.instructoravailabilityslot_set.count() @property def discountPointsMultiplier(self): ''' If", "__str__(self): return str(self.name) class Meta: permissions = ( ('view_others_lessons', _('Can view scheduled private", "for the lesson. ''' customer = models.ForeignKey( Customer, verbose_name=_('Customer'), on_delete=models.CASCADE ) lesson =", "('T', _('Tentative Booking')) unavailable = ('U', _('Unavailable')) instructor = models.ForeignKey(Instructor, verbose_name=_('Instructor'), on_delete=models.CASCADE) pricingTier", "# successfully scheduled template = getConstant('privateLessons__lessonBookedEmailTemplate') if template.defaultFromAddress and template.content: for customer in", "1) def finalizeBooking(self, **kwargs): notifyStudent = kwargs.get('notifyStudent', True) notifyTeachers = kwargs.get('notifyTeachers', getConstant('privateLessons__notifyInstructor')) eventRegistration", "lessonEvent = models.ForeignKey( PrivateLessonEvent, verbose_name=_('Scheduled lesson'), null=True, blank=True, on_delete=models.SET_NULL, ) eventRegistration = models.ForeignKey(", "return _('%s: %s at %s') % ( self.instructor.fullName, ensure_localtime(self.startTime).strftime('%b %-d, %Y %-I:%M %p'),", "else '', customerNames, ( (', ' if (teacherNames or customerNames) else '') +", "max_duration + slot.duration > getConstant('privateLessons__maximumLessonLength'): break if ( slot.startTime == last_start + timedelta(minutes=last_duration)", "to determine how many points this lesson is worth toward a discount. Since", "is worth toward a discount. Since private lesson points are based on the", ") # isAvailable indicates if a slot is currently available isAvailable = property(fget=checkIfAvailable)", "if names else '' else: customerNames = '' if not teacherNames and not", "return [ [x.id, x.name] for x in self.instructor.instructorprivatelessondetails.roles.all() ] def checkIfAvailable(self, dateTime=timezone.now()): '''", "lesson details') verbose_name_plural = _('Instructors\\' private lesson details') class PrivateLessonEvent(Event): ''' This is", "still want to # be able to identify the Event that was created", "small groups'), default=True) def __str__(self): return str(_('Instructor Private lesson details for %s' %", "availability slots') permissions = ( ('edit_own_availability', _('Can edit one\\'s own private lesson availability.')),", "are booked without payment, this just provides a record that they signed up", "on_delete=models.CASCADE) pricingTier = models.ForeignKey( PricingTier, verbose_name=_('Pricing Tier'), null=True, blank=True, on_delete=models.SET_NULL ) startTime =", "slots booked, this just returns the number of slots associated with this event", "this model inherits all of the fields associated with other types of events", "the event because # in the event that an expired (temporary) Registration is", "Participants'), null=True, blank=True, default=1) comments = models.TextField( _('Comments/Notes'), null=True, blank=True, help_text=_('For internal use", "@property def numSlots(self): ''' Used for various pricing discounts related things ''' return", "%s%s%s%s' % ( teacherNames, _(' for ') if teacherNames and customerNames else '',", "if withDate else '' )) @property def name(self): return self.nameAndDate(withDate=True) def save(self, *args,", "event object for which an individual registers. The event is created when the", "else: customerNames = '' if not teacherNames and not customerNames and not withDate:", "registration status to hidden if it is not specified otherwise ''' if not", "which needs to be enforced on slot save. ''' potential_slots = InstructorAvailabilitySlot.objects.filter( instructor=self.instructor,", "self.customers: customerNames = ' ' + ' and '.join([x.fullName for x in self.customers])", "), 'expirationDate', timezone.now() ) <= timezone.now() ) ) ) # isAvailable indicates if", "import timezone from django.urls import reverse from datetime import timedelta from danceschool.core.models import", "up without payment. ''' return Customer.objects.filter( Q(privatelessoncustomer__lesson=self) | Q(registration__eventregistration__event=self) ).distinct() customers.fget.short_description = _('Customers')", "lesson. lessonEvent = models.ForeignKey( PrivateLessonEvent, verbose_name=_('Scheduled lesson'), null=True, blank=True, on_delete=models.SET_NULL, ) eventRegistration =", "a discount. Since private lesson points are based on the number of slots", "import timedelta from danceschool.core.models import ( Instructor, Location, Room, DanceRole, Event, PricingTier, EventRegistration,", "' and '.join([x.staffMember.fullName for x in self.eventstaffmember_set.all()]) if self.customers: customerNames = ' '", "List both any individuals signed up via the registration and payment system, and", "looks for this property to determine how many points this lesson is worth", "Tier'), null=True, blank=True, on_delete=models.SET_NULL ) roles = models.ManyToManyField(DanceRole, blank=True) couples = models.BooleanField(_('Private lessons", "from django.urls import reverse from datetime import timedelta from danceschool.core.models import ( Instructor,", "= _('Private lesson availability slots') permissions = ( ('edit_own_availability', _('Can edit one\\'s own", "been held as tentative past their expiration date ''' return ( self.startTime >=", "null=True, blank=True, on_delete=models.SET_NULL ) participants = models.PositiveSmallIntegerField(_('Expected # of Participants'), null=True, blank=True, default=1)", "%Y %-I:%M %p'), self.location ) def __str__(self): return str(self.name) class Meta: ordering =", "self.status: self.status == Event.RegStatus.hidden super().save(*args, **kwargs) def __str__(self): return str(self.name) class Meta: permissions", "= ('instructor__lastName', 'instructor__firstName') verbose_name = _('Instructor private lesson details') verbose_name_plural = _('Instructors\\' private", "with other types of events (location, etc.) ''' pricingTier = models.ForeignKey( PricingTier, verbose_name=_('Pricing", ").distinct() customers.fget.short_description = _('Customers') @property def numSlots(self): ''' Used for various pricing discounts", "unavailable = ('U', _('Unavailable')) instructor = models.ForeignKey(Instructor, verbose_name=_('Instructor'), on_delete=models.CASCADE) pricingTier = models.ForeignKey( PricingTier,", "of events (location, etc.) ''' pricingTier = models.ForeignKey( PricingTier, verbose_name=_('Pricing Tier'), null=True, blank=True,", "= models.DateTimeField(auto_now=True) @property def availableDurations(self): ''' A lesson can always be booked for", "with this event (or 1). ''' return max(self.numSlots, 1) def nameAndDate(self, withDate=True): teacherNames", "Registration is deleted, we still want to # be able to identify the", "'.join([x.registration.fullName for x in self.eventregistration_set.all()]) customerNames = ' ' + names if names", "= self.duration for slot in potential_slots: if max_duration + slot.duration > getConstant('privateLessons__maximumLessonLength'): break", "own private lesson availability.')), ('edit_others_availability', _('Can edit other instructors\\' private lesson availability.')), )", "template.subject, template.content, send_html=False, from_address=template.defaultFromAddress, from_name=template.defaultFromName, cc=template.defaultCC, to=instructor.privateEmail or instructor.publicEmail, lesson=self, instructor=instructor, customers=self.customers, calendarUrl=reverse('privateCalendar'),", "customers(self): ''' List both any individuals signed up via the registration and payment", "= self.instructoravailabilityslot_set.all() affectedSlots.update( status=InstructorAvailabilitySlot.SlotStatus.booked, eventRegistration=eventRegistration, ) if notifyStudent: # This is the email", "run registration # that they have been compensated template = getConstant('privateLessons__lessonBookedInstructorEmailTemplate') if template.defaultFromAddress", "# We need both a link to the registrations and a link to", "recordkeeping.') ) def getBasePrice(self, **kwargs): ''' This method overrides the method of the", "= ('T', _('Tentative Booking')) unavailable = ('U', _('Unavailable')) instructor = models.ForeignKey(Instructor, verbose_name=_('Instructor'), on_delete=models.CASCADE)", "and ( self.status == self.SlotStatus.available or ( self.status == self.SlotStatus.tentative and getattr( getattr(", "return self.instructoravailabilityslot_set.count() @property def discountPointsMultiplier(self): ''' If installed, the discounts app looks for", "[ [x.id, x.name] for x in self.instructor.instructorprivatelessondetails.roles.all() ] def checkIfAvailable(self, dateTime=timezone.now()): ''' Available", "booked for the length of a single slot, but this method checks if", "an email address, instructor cannot be notified continue emailMixin.email_recipient( template.subject, template.content, send_html=False, from_address=template.defaultFromAddress,", "last_start = self.startTime last_duration = self.duration max_duration = self.duration for slot in potential_slots:", "django.db import models from django.db.models import Q from django.utils.translation import gettext_lazy as _", "instructor = models.OneToOneField(StaffMember, on_delete=models.CASCADE) defaultPricingTier = models.ForeignKey( PricingTier, verbose_name=_('Default Pricing Tier'), null=True, blank=True,", "all of the fields associated with other types of events (location, etc.) '''", "a slot is currently available isAvailable = property(fget=checkIfAvailable) isAvailable.fget.short_description = _('Available') @property def", "determine how many points this lesson is worth toward a discount. Since private", "getBasePrice(self, **kwargs): ''' This method overrides the method of the base Event class", "This is the email template used to notify individuals who run registration #", "= ('B', _('Booked')) tentative = ('T', _('Tentative Booking')) unavailable = ('U', _('Unavailable')) instructor", "appropriate price for it. ''' if not self.pricingTier: return None return self.pricingTier.getBasePrice(**kwargs) *", "inherits all of the fields associated with other types of events (location, etc.)", "+ slot.duration > getConstant('privateLessons__maximumLessonLength'): break if ( slot.startTime == last_start + timedelta(minutes=last_duration) and", "room = models.ForeignKey( Room, verbose_name=_('Room'), null=True, blank=True, on_delete=models.SET_NULL, ) status = models.CharField(max_length=1, choices=SlotStatus.choices,", "the roles that have been selected for the instructor. ''' if not hasattr(self.instructor,", "models.PositiveSmallIntegerField(_('Slot duration (minutes)'), default=30) location = models.ForeignKey( Location, verbose_name=_('Location'), null=True, blank=True, on_delete=models.SET_NULL, )", "= ' and '.join([x.staffMember.fullName for x in self.eventstaffmember_set.all()]) if self.customers: customerNames = '", "(', ' if (teacherNames or customerNames) else '') + self.startTime.strftime('%Y-%m-%d') ) if withDate", "verbose_name_plural = _('Private lesson availability slots') permissions = ( ('edit_own_availability', _('Can edit one\\'s", "max_duration = self.duration for slot in potential_slots: if max_duration + slot.duration > getConstant('privateLessons__maximumLessonLength'):", "the email template used to notify individuals who run registration # that they", "and payment system, and any individuals signed up without payment. ''' return Customer.objects.filter(", "notify students that their private lesson has been # successfully scheduled template =", "startTime__lte=self.startTime + timedelta(minutes=getConstant('privateLessons__maximumLessonLength')), ).exclude(id=self.id).order_by('startTime') duration_list = [self.duration, ] last_start = self.startTime last_duration =", "return [] return [ [x.id, x.name] for x in self.instructor.instructorprivatelessondetails.roles.all() ] def checkIfAvailable(self,", "x in self.eventstaffmember_set.all()]) if self.customers: customerNames = ' ' + ' and '.join([x.fullName", "by the core app, and this model inherits all of the fields associated", "Set registration status to hidden if it is not specified otherwise ''' if", "not self.pricingTier: return None return self.pricingTier.getBasePrice(**kwargs) * max(self.numSlots, 1) def finalizeBooking(self, **kwargs): notifyStudent", "self.eventstaffmember_set.all()]) if self.customers: customerNames = ' ' + ' and '.join([x.fullName for x", "customerNames, ( (', ' if (teacherNames or customerNames) else '') + self.startTime.strftime('%Y-%m-%d') )", "%p'), self.location ) def __str__(self): return str(self.name) class Meta: ordering = ('-startTime', 'instructor__lastName',", "return str(self.name) class Meta: ordering = ('-startTime', 'instructor__lastName', 'instructor__firstName') verbose_name = _('Private lesson", "permissions = ( ('edit_own_availability', _('Can edit one\\'s own private lesson availability.')), ('edit_others_availability', _('Can", "instructor = models.ForeignKey(Instructor, verbose_name=_('Instructor'), on_delete=models.CASCADE) pricingTier = models.ForeignKey( PricingTier, verbose_name=_('Pricing Tier'), null=True, blank=True,", "= slot.duration max_duration += slot.duration return duration_list @property def availableRoles(self): ''' Some instructors", "lesson customer: %s for lesson #%s' % (self.customer.fullName, self.lesson.id))) class Meta: unique_together =", "save. ''' potential_slots = InstructorAvailabilitySlot.objects.filter( instructor=self.instructor, location=self.location, room=self.room, pricingTier=self.pricingTier, startTime__gte=self.startTime, startTime__lte=self.startTime + timedelta(minutes=getConstant('privateLessons__maximumLessonLength')),", "this just returns the number of slots associated with this event (or 1).", "models.TextField( _('Comments/Notes'), null=True, blank=True, help_text=_('For internal use and recordkeeping.') ) def getBasePrice(self, **kwargs):", "on_delete=models.CASCADE ) lesson = models.ForeignKey( PrivateLessonEvent, verbose_name=_('Lesson'), on_delete=models.CASCADE ) def __str__(self): return str(_('Private", "the Event that was created for this private lesson. lessonEvent = models.ForeignKey( PrivateLessonEvent,", "null=True, blank=True, on_delete=models.SET_NULL ) roles = models.ManyToManyField(DanceRole, blank=True) couples = models.BooleanField(_('Private lessons for", "= models.ForeignKey( Location, verbose_name=_('Location'), null=True, blank=True, on_delete=models.SET_NULL, ) room = models.ForeignKey( Room, verbose_name=_('Room'),", "( slot.startTime == last_start + timedelta(minutes=last_duration) and slot.isAvailable ): duration_list.append(max_duration + slot.duration) last_start", "slot is currently available isAvailable = property(fget=checkIfAvailable) isAvailable.fget.short_description = _('Available') @property def name(self):", "payment, this just provides a record that they signed up for the lesson.", "the lesson. ''' customer = models.ForeignKey( Customer, verbose_name=_('Customer'), on_delete=models.CASCADE ) lesson = models.ForeignKey(", "number of slots associated with this event (or 1). ''' return max(self.numSlots, 1)", "registration and payment, the customers are the individuals who are registered. For private", "instructors = [ x.staffMember for x in self.eventstaffmember_set.exclude( Q(staffMember__privateEmail__isnull=True) & Q(staffMember__publicEmail__isnull=True) ) ]", "for this private lesson. lessonEvent = models.ForeignKey( PrivateLessonEvent, verbose_name=_('Scheduled lesson'), null=True, blank=True, on_delete=models.SET_NULL,", "*args, **kwargs): ''' Set registration status to hidden if it is not specified", "blank=True, on_delete=models.SET_NULL ) roles = models.ManyToManyField(DanceRole, blank=True) couples = models.BooleanField(_('Private lessons for couples'),", "lesson=self, instructor=instructor, customers=self.customers, calendarUrl=reverse('privateCalendar'), ) @property def customers(self): ''' List both any individuals", "students that their private lesson has been # successfully scheduled template = getConstant('privateLessons__lessonBookedEmailTemplate')", "self.SlotStatus.tentative and getattr( getattr( getattr(self.eventRegistration, 'invoiceItem', None), 'invoice', None ), 'expirationDate', timezone.now() )", "on_delete=models.SET_NULL, ) eventRegistration = models.ForeignKey( EventRegistration, verbose_name=_('event registration'), null=True, blank=True, on_delete=models.SET_NULL, related_name='privateLessonSlots' )", "they signed up for the lesson. ''' customer = models.ForeignKey( Customer, verbose_name=_('Customer'), on_delete=models.CASCADE", "django.urls import reverse from datetime import timedelta from danceschool.core.models import ( Instructor, Location,", "private lesson. lessonEvent = models.ForeignKey( PrivateLessonEvent, verbose_name=_('Scheduled lesson'), null=True, blank=True, on_delete=models.SET_NULL, ) eventRegistration", "verbose_name_plural = _('Private lesson customers') class InstructorAvailabilitySlot(models.Model): class SlotStatus(models.TextChoices): available = ('A', _('Available'))", "on_delete=models.SET_NULL, related_name='privateLessonSlots' ) creationDate = models.DateTimeField(auto_now_add=True) modifiedDate = models.DateTimeField(auto_now=True) @property def availableDurations(self): '''", "or ( self.status == self.SlotStatus.tentative and getattr( getattr( getattr(self.eventRegistration, 'invoiceItem', None), 'invoice', None", "and '.join([x.fullName for x in self.customers]) elif self.eventregistration_set.all(): names = ' and '.join([x.registration.fullName", "who run registration # that they have been compensated template = getConstant('privateLessons__lessonBookedInstructorEmailTemplate') if", "from django.db.models import Q from django.utils.translation import gettext_lazy as _ from django.utils import", "EventRegistration, verbose_name=_('event registration'), null=True, blank=True, on_delete=models.SET_NULL, related_name='privateLessonSlots' ) creationDate = models.DateTimeField(auto_now_add=True) modifiedDate =", "details') verbose_name_plural = _('Instructors\\' private lesson details') class PrivateLessonEvent(Event): ''' This is the", "Event.RegStatus.hidden super().save(*args, **kwargs) def __str__(self): return str(self.name) class Meta: permissions = ( ('view_others_lessons',", "are the individuals who are registered. For private lessons that are booked without", "if not hasattr(self.instructor, 'instructorprivatelessondetails'): return [] return [ [x.id, x.name] for x in", "their expiration date ''' return ( self.startTime >= dateTime + timedelta(days=getConstant('privateLessons__closeBookingDays')) and self.startTime", "lessons for all instructors')), ) verbose_name = _('Private lesson') verbose_name_plural = _('Private lessons')", "send_html=False, from_address=template.defaultFromAddress, from_name=template.defaultFromName, cc=template.defaultCC, to=instructor.privateEmail or instructor.publicEmail, lesson=self, instructor=instructor, customers=self.customers, calendarUrl=reverse('privateCalendar'), ) @property", "eventRegistration = kwargs.get('eventRegistration', None) affectedSlots = self.instructoravailabilityslot_set.all() affectedSlots.update( status=InstructorAvailabilitySlot.SlotStatus.booked, eventRegistration=eventRegistration, ) if notifyStudent:", "by checking the pricingTier associated with this PrivateLessonEvent and getting the appropriate price", "default=True) smallGroups = models.BooleanField(_('Private lessons for small groups'), default=True) def __str__(self): return str(_('Instructor", "many points this lesson is worth toward a discount. Since private lesson points", "are available, but also tentative slots that have been held as tentative past", "if notifyStudent: # This is the email template used to notify students that", "verbose_name = _('Private lesson') verbose_name_plural = _('Private lessons') class PrivateLessonCustomer(models.Model): ''' For private", "scheduled template = getConstant('privateLessons__lessonBookedEmailTemplate') if template.defaultFromAddress and template.content: for customer in self.customers: customer.email_recipient(", "customers=self.customers, calendarUrl=reverse('privateCalendar'), ) @property def customers(self): ''' List both any individuals signed up", "return Customer.objects.filter( Q(privatelessoncustomer__lesson=self) | Q(registration__eventregistration__event=self) ).distinct() customers.fget.short_description = _('Customers') @property def numSlots(self): '''", "related things ''' return self.instructoravailabilityslot_set.count() @property def discountPointsMultiplier(self): ''' If installed, the discounts", "lesson customer') verbose_name_plural = _('Private lesson customers') class InstructorAvailabilitySlot(models.Model): class SlotStatus(models.TextChoices): available =", ") participants = models.PositiveSmallIntegerField(_('Expected # of Participants'), null=True, blank=True, default=1) comments = models.TextField(", "%s') % ( self.instructor.fullName, ensure_localtime(self.startTime).strftime('%b %-d, %Y %-I:%M %p'), self.location ) def __str__(self):", "from_name=template.defaultFromName, cc=template.defaultCC, to=customer.email, lesson=self, ) if notifyTeachers: # This is the email template", "teacherNames, _(' for ') if teacherNames and customerNames else '', customerNames, ( (',", "_('Private lesson availability slots') permissions = ( ('edit_own_availability', _('Can edit one\\'s own private", "models.ForeignKey( Customer, verbose_name=_('Customer'), on_delete=models.CASCADE ) lesson = models.ForeignKey( PrivateLessonEvent, verbose_name=_('Lesson'), on_delete=models.CASCADE ) def", "and a link to the event because # in the event that an", "= kwargs.get('notifyTeachers', getConstant('privateLessons__notifyInstructor')) eventRegistration = kwargs.get('eventRegistration', None) affectedSlots = self.instructoravailabilityslot_set.all() affectedSlots.update( status=InstructorAvailabilitySlot.SlotStatus.booked, eventRegistration=eventRegistration,", "lessons for certain roles, so we should only allow booking for the roles", "x.name] for x in self.instructor.instructorprivatelessondetails.roles.all() ] def checkIfAvailable(self, dateTime=timezone.now()): ''' Available slots are", "dateTime=timezone.now()): ''' Available slots are available, but also tentative slots that have been", "getConstant('privateLessons__lessonBookedEmailTemplate') if template.defaultFromAddress and template.content: for customer in self.customers: customer.email_recipient( template.subject, template.content, send_html=False,", "= models.DateTimeField(auto_now_add=True) modifiedDate = models.DateTimeField(auto_now=True) @property def availableDurations(self): ''' A lesson can always", "private lessons that go through registration and payment, the customers are the individuals", "lesson. ''' customer = models.ForeignKey( Customer, verbose_name=_('Customer'), on_delete=models.CASCADE ) lesson = models.ForeignKey( PrivateLessonEvent,", "isAvailable = property(fget=checkIfAvailable) isAvailable.fget.short_description = _('Available') @property def name(self): return _('%s: %s at", "verbose_name = _('Private lesson availability slot') verbose_name_plural = _('Private lesson availability slots') permissions", "the discounts app looks for this property to determine how many points this", "max(self.numSlots, 1) def nameAndDate(self, withDate=True): teacherNames = ' and '.join([x.staffMember.fullName for x in", "lesson'), null=True, blank=True, on_delete=models.SET_NULL, ) eventRegistration = models.ForeignKey( EventRegistration, verbose_name=_('event registration'), null=True, blank=True,", "availableDurations(self): ''' A lesson can always be booked for the length of a", "def customers(self): ''' List both any individuals signed up via the registration and", "' ' + ' and '.join([x.fullName for x in self.customers]) elif self.eventregistration_set.all(): names", "on_delete=models.SET_NULL ) startTime = models.DateTimeField(_('Start time')) duration = models.PositiveSmallIntegerField(_('Slot duration (minutes)'), default=30) location", "InstructorAvailabilitySlot.objects.filter( instructor=self.instructor, location=self.location, room=self.room, pricingTier=self.pricingTier, startTime__gte=self.startTime, startTime__lte=self.startTime + timedelta(minutes=getConstant('privateLessons__maximumLessonLength')), ).exclude(id=self.id).order_by('startTime') duration_list = [self.duration,", "= [self.duration, ] last_start = self.startTime last_duration = self.duration max_duration = self.duration for", "+ timedelta(days=getConstant('privateLessons__closeBookingDays')) and self.startTime <= dateTime + timedelta(days=getConstant('privateLessons__openBookingDays')) and not self.eventRegistration and (", "null=True, blank=True, on_delete=models.SET_NULL, ) eventRegistration = models.ForeignKey( EventRegistration, verbose_name=_('event registration'), null=True, blank=True, on_delete=models.SET_NULL,", "nameAndDate(self, withDate=True): teacherNames = ' and '.join([x.staffMember.fullName for x in self.eventstaffmember_set.all()]) if self.customers:", "%s for lesson #%s' % (self.customer.fullName, self.lesson.id))) class Meta: unique_together = ('customer', 'lesson')", "on_delete=models.SET_NULL ) roles = models.ManyToManyField(DanceRole, blank=True) couples = models.BooleanField(_('Private lessons for couples'), default=True)", "from danceschool.core.models import ( Instructor, Location, Room, DanceRole, Event, PricingTier, EventRegistration, Customer, StaffMember", "creationDate = models.DateTimeField(auto_now_add=True) modifiedDate = models.DateTimeField(auto_now=True) @property def availableDurations(self): ''' A lesson can", "last_start + timedelta(minutes=last_duration) and slot.isAvailable ): duration_list.append(max_duration + slot.duration) last_start = slot.startTime last_duration", "_('Available') @property def name(self): return _('%s: %s at %s') % ( self.instructor.fullName, ensure_localtime(self.startTime).strftime('%b", "save(self, *args, **kwargs): ''' Set registration status to hidden if it is not", "booked, this just returns the number of slots associated with this event (or", "models.ManyToManyField(DanceRole, blank=True) couples = models.BooleanField(_('Private lessons for couples'), default=True) smallGroups = models.BooleanField(_('Private lessons", "lesson = models.ForeignKey( PrivateLessonEvent, verbose_name=_('Lesson'), on_delete=models.CASCADE ) def __str__(self): return str(_('Private lesson customer:", "for %s' % self.instructor.fullName)) class Meta: ordering = ('instructor__lastName', 'instructor__firstName') verbose_name = _('Instructor", "Meta: permissions = ( ('view_others_lessons', _('Can view scheduled private lessons for all instructors')),", "who are registered. For private lessons that are booked without payment, this just", "to be enforced on slot save. ''' potential_slots = InstructorAvailabilitySlot.objects.filter( instructor=self.instructor, location=self.location, room=self.room,", "instructor=instructor, customers=self.customers, calendarUrl=reverse('privateCalendar'), ) @property def customers(self): ''' List both any individuals signed", "getattr( getattr(self.eventRegistration, 'invoiceItem', None), 'invoice', None ), 'expirationDate', timezone.now() ) <= timezone.now() )", "individual registers. The event is created when the user books a lesson. All", "default=30) location = models.ForeignKey( Location, verbose_name=_('Location'), null=True, blank=True, on_delete=models.SET_NULL, ) room = models.ForeignKey(", ").exclude(id=self.id).order_by('startTime') duration_list = [self.duration, ] last_start = self.startTime last_duration = self.duration max_duration =", "or customerNames) else '') + self.startTime.strftime('%Y-%m-%d') ) if withDate else '' )) @property", "both a link to the registrations and a link to the event because", "can always be booked for the length of a single slot, but this", "availableRoles(self): ''' Some instructors only offer private lessons for certain roles, so we", "%-d, %Y %-I:%M %p'), self.location ) def __str__(self): return str(self.name) class Meta: ordering", "from django.utils import timezone from django.urls import reverse from datetime import timedelta from", "lesson is worth toward a discount. Since private lesson points are based on", "teacherNames and not customerNames and not withDate: return _('Private Lesson') return _('Private Lesson:", "django.utils.translation import gettext_lazy as _ from django.utils import timezone from django.urls import reverse", "DanceRole, Event, PricingTier, EventRegistration, Customer, StaffMember ) from danceschool.core.constants import getConstant from danceschool.core.mixins", "based on the number of slots booked, this just returns the number of", "') if teacherNames and customerNames else '', customerNames, ( (', ' if (teacherNames", "this PrivateLessonEvent and getting the appropriate price for it. ''' if not self.pricingTier:", "template used to notify individuals who run registration # that they have been", "self.customers]) elif self.eventregistration_set.all(): names = ' and '.join([x.registration.fullName for x in self.eventregistration_set.all()]) customerNames", "null=True, blank=True, on_delete=models.SET_NULL, ) room = models.ForeignKey( Room, verbose_name=_('Room'), null=True, blank=True, on_delete=models.SET_NULL, )", "verbose_name=_('Scheduled lesson'), null=True, blank=True, on_delete=models.SET_NULL, ) eventRegistration = models.ForeignKey( EventRegistration, verbose_name=_('event registration'), null=True,", "hidden if it is not specified otherwise ''' if not self.status: self.status ==", ") roles = models.ManyToManyField(DanceRole, blank=True) couples = models.BooleanField(_('Private lessons for couples'), default=True) smallGroups", "import ensure_localtime class InstructorPrivateLessonDetails(models.Model): instructor = models.OneToOneField(StaffMember, on_delete=models.CASCADE) defaultPricingTier = models.ForeignKey( PricingTier, verbose_name=_('Default", "max_duration += slot.duration return duration_list @property def availableRoles(self): ''' Some instructors only offer", "and getting the appropriate price for it. ''' if not self.pricingTier: return None", "import EmailRecipientMixin from danceschool.core.utils.timezone import ensure_localtime class InstructorPrivateLessonDetails(models.Model): instructor = models.OneToOneField(StaffMember, on_delete=models.CASCADE) defaultPricingTier", "still handled by the core app, and this model inherits all of the", "return self.nameAndDate(withDate=True) def save(self, *args, **kwargs): ''' Set registration status to hidden if", "a link to the event because # in the event that an expired", "''' Available slots are available, but also tentative slots that have been held", "event (or 1). ''' return max(self.numSlots, 1) def nameAndDate(self, withDate=True): teacherNames = '", "self.SlotStatus.available or ( self.status == self.SlotStatus.tentative and getattr( getattr( getattr(self.eventRegistration, 'invoiceItem', None), 'invoice',", "for x in self.instructor.instructorprivatelessondetails.roles.all() ] def checkIfAvailable(self, dateTime=timezone.now()): ''' Available slots are available,", "pricingTier associated with this PrivateLessonEvent and getting the appropriate price for it. '''", "Booking')) unavailable = ('U', _('Unavailable')) instructor = models.ForeignKey(Instructor, verbose_name=_('Instructor'), on_delete=models.CASCADE) pricingTier = models.ForeignKey(", "instructors only offer private lessons for certain roles, so we should only allow", "with this PrivateLessonEvent and getting the appropriate price for it. ''' if not", "True) notifyTeachers = kwargs.get('notifyTeachers', getConstant('privateLessons__notifyInstructor')) eventRegistration = kwargs.get('eventRegistration', None) affectedSlots = self.instructoravailabilityslot_set.all() affectedSlots.update(", "def availableDurations(self): ''' A lesson can always be booked for the length of", "duration_list = [self.duration, ] last_start = self.startTime last_duration = self.duration max_duration = self.duration", "the email template used to notify students that their private lesson has been", "go through registration and payment, the customers are the individuals who are registered.", "= models.ForeignKey( PrivateLessonEvent, verbose_name=_('Lesson'), on_delete=models.CASCADE ) def __str__(self): return str(_('Private lesson customer: %s", "points are based on the number of slots booked, this just returns the", "private lesson has been # successfully scheduled template = getConstant('privateLessons__lessonBookedEmailTemplate') if template.defaultFromAddress and", "registration logic is still handled by the core app, and this model inherits", "str(_('Private lesson customer: %s for lesson #%s' % (self.customer.fullName, self.lesson.id))) class Meta: unique_together", "_('Customers') @property def numSlots(self): ''' Used for various pricing discounts related things '''", "return ( self.startTime >= dateTime + timedelta(days=getConstant('privateLessons__closeBookingDays')) and self.startTime <= dateTime + timedelta(days=getConstant('privateLessons__openBookingDays'))", "Q(staffMember__publicEmail__isnull=True) ) ] for instructor in instructors: if not instructor.privateEmail and not instructor.publicEmail:", "core app, and this model inherits all of the fields associated with other", "_('Comments/Notes'), null=True, blank=True, help_text=_('For internal use and recordkeeping.') ) def getBasePrice(self, **kwargs): '''", "they have been compensated template = getConstant('privateLessons__lessonBookedInstructorEmailTemplate') if template.defaultFromAddress and template.content: emailMixin =", "return str(_('Instructor Private lesson details for %s' % self.instructor.fullName)) class Meta: ordering =", "payment system, and any individuals signed up without payment. ''' return Customer.objects.filter( Q(privatelessoncustomer__lesson=self)", "Used for various pricing discounts related things ''' return self.instructoravailabilityslot_set.count() @property def discountPointsMultiplier(self):", "_('Can edit one\\'s own private lesson availability.')), ('edit_others_availability', _('Can edit other instructors\\' private", "help_text=_('For internal use and recordkeeping.') ) def getBasePrice(self, **kwargs): ''' This method overrides", "the core app, and this model inherits all of the fields associated with", "and '.join([x.registration.fullName for x in self.eventregistration_set.all()]) customerNames = ' ' + names if", "from_name=template.defaultFromName, cc=template.defaultCC, to=instructor.privateEmail or instructor.publicEmail, lesson=self, instructor=instructor, customers=self.customers, calendarUrl=reverse('privateCalendar'), ) @property def customers(self):", "PrivateLessonEvent, verbose_name=_('Scheduled lesson'), null=True, blank=True, on_delete=models.SET_NULL, ) eventRegistration = models.ForeignKey( EventRegistration, verbose_name=_('event registration'),", "in self.eventstaffmember_set.all()]) if self.customers: customerNames = ' ' + ' and '.join([x.fullName for", "models.DateTimeField(auto_now=True) @property def availableDurations(self): ''' A lesson can always be booked for the", "lesson=self, ) if notifyTeachers: # This is the email template used to notify", "any individuals signed up without payment. ''' return Customer.objects.filter( Q(privatelessoncustomer__lesson=self) | Q(registration__eventregistration__event=self) ).distinct()", "class PrivateLessonEvent(Event): ''' This is the event object for which an individual registers.", "and not instructor.publicEmail: # Without an email address, instructor cannot be notified continue", "for this property to determine how many points this lesson is worth toward", "of a single slot, but this method checks if multiple slots are available.", "= _('Instructor private lesson details') verbose_name_plural = _('Instructors\\' private lesson details') class PrivateLessonEvent(Event):", "past their expiration date ''' return ( self.startTime >= dateTime + timedelta(days=getConstant('privateLessons__closeBookingDays')) and", "registration # that they have been compensated template = getConstant('privateLessons__lessonBookedInstructorEmailTemplate') if template.defaultFromAddress and", "**kwargs) def __str__(self): return str(self.name) class Meta: permissions = ( ('view_others_lessons', _('Can view", "timezone from django.urls import reverse from datetime import timedelta from danceschool.core.models import (", "PrivateLessonEvent and getting the appropriate price for it. ''' if not self.pricingTier: return", "getattr(self.eventRegistration, 'invoiceItem', None), 'invoice', None ), 'expirationDate', timezone.now() ) <= timezone.now() ) )", "customerNames else '', customerNames, ( (', ' if (teacherNames or customerNames) else '')", "the event that an expired (temporary) Registration is deleted, we still want to", "+ ' and '.join([x.fullName for x in self.customers]) elif self.eventregistration_set.all(): names = '", "books a lesson. All of the registration logic is still handled by the", "x in self.eventstaffmember_set.exclude( Q(staffMember__privateEmail__isnull=True) & Q(staffMember__publicEmail__isnull=True) ) ] for instructor in instructors: if", "getattr( getattr( getattr(self.eventRegistration, 'invoiceItem', None), 'invoice', None ), 'expirationDate', timezone.now() ) <= timezone.now()", "'instructor__lastName', 'instructor__firstName') verbose_name = _('Private lesson availability slot') verbose_name_plural = _('Private lesson availability", "payment, the customers are the individuals who are registered. For private lessons that", "method checks if multiple slots are available. This method requires that slots are", "identify the Event that was created for this private lesson. lessonEvent = models.ForeignKey(", "couples = models.BooleanField(_('Private lessons for couples'), default=True) smallGroups = models.BooleanField(_('Private lessons for small", "def numSlots(self): ''' Used for various pricing discounts related things ''' return self.instructoravailabilityslot_set.count()", "% (self.customer.fullName, self.lesson.id))) class Meta: unique_together = ('customer', 'lesson') verbose_name = _('Private lesson", "blank=True, on_delete=models.SET_NULL, ) status = models.CharField(max_length=1, choices=SlotStatus.choices, default=SlotStatus.available) # We need both a", "class SlotStatus(models.TextChoices): available = ('A', _('Available')) booked = ('B', _('Booked')) tentative = ('T',", "[x.id, x.name] for x in self.instructor.instructorprivatelessondetails.roles.all() ] def checkIfAvailable(self, dateTime=timezone.now()): ''' Available slots", "individuals signed up without payment. ''' return Customer.objects.filter( Q(privatelessoncustomer__lesson=self) | Q(registration__eventregistration__event=self) ).distinct() customers.fget.short_description", "str(self.name) class Meta: ordering = ('-startTime', 'instructor__lastName', 'instructor__firstName') verbose_name = _('Private lesson availability", "event is created when the user books a lesson. All of the registration", "system, and any individuals signed up without payment. ''' return Customer.objects.filter( Q(privatelessoncustomer__lesson=self) |", "= '' if not teacherNames and not customerNames and not withDate: return _('Private", "internal use and recordkeeping.') ) def getBasePrice(self, **kwargs): ''' This method overrides the", "A lesson can always be booked for the length of a single slot,", "teacherNames = ' and '.join([x.staffMember.fullName for x in self.eventstaffmember_set.all()]) if self.customers: customerNames =", "We need both a link to the registrations and a link to the", "in self.eventstaffmember_set.exclude( Q(staffMember__privateEmail__isnull=True) & Q(staffMember__publicEmail__isnull=True) ) ] for instructor in instructors: if not", "'' if not teacherNames and not customerNames and not withDate: return _('Private Lesson')", "if not instructor.privateEmail and not instructor.publicEmail: # Without an email address, instructor cannot", "from datetime import timedelta from danceschool.core.models import ( Instructor, Location, Room, DanceRole, Event,", "''' List both any individuals signed up via the registration and payment system,", "= _('Customers') @property def numSlots(self): ''' Used for various pricing discounts related things", "self.eventregistration_set.all()]) customerNames = ' ' + names if names else '' else: customerNames", "length of a single slot, but this method checks if multiple slots are", "this lesson is worth toward a discount. Since private lesson points are based", "is the email template used to notify students that their private lesson has", "are based on the number of slots booked, this just returns the number", "_('Private Lesson: %s%s%s%s' % ( teacherNames, _(' for ') if teacherNames and customerNames", "startTime__gte=self.startTime, startTime__lte=self.startTime + timedelta(minutes=getConstant('privateLessons__maximumLessonLength')), ).exclude(id=self.id).order_by('startTime') duration_list = [self.duration, ] last_start = self.startTime last_duration", "the base Event class by checking the pricingTier associated with this PrivateLessonEvent and", "Pricing Tier'), null=True, blank=True, on_delete=models.SET_NULL ) roles = models.ManyToManyField(DanceRole, blank=True) couples = models.BooleanField(_('Private", "( ('view_others_lessons', _('Can view scheduled private lessons for all instructors')), ) verbose_name =", "' and '.join([x.registration.fullName for x in self.eventregistration_set.all()]) customerNames = ' ' + names", "def __str__(self): return str(_('Instructor Private lesson details for %s' % self.instructor.fullName)) class Meta:", "price for it. ''' if not self.pricingTier: return None return self.pricingTier.getBasePrice(**kwargs) * max(self.numSlots,", "been compensated template = getConstant('privateLessons__lessonBookedInstructorEmailTemplate') if template.defaultFromAddress and template.content: emailMixin = EmailRecipientMixin() instructors", "and '.join([x.staffMember.fullName for x in self.eventstaffmember_set.all()]) if self.customers: customerNames = ' ' +", "Lesson: %s%s%s%s' % ( teacherNames, _(' for ') if teacherNames and customerNames else", "return max(self.numSlots, 1) def nameAndDate(self, withDate=True): teacherNames = ' and '.join([x.staffMember.fullName for x", "null=True, blank=True, on_delete=models.SET_NULL ) startTime = models.DateTimeField(_('Start time')) duration = models.PositiveSmallIntegerField(_('Slot duration (minutes)'),", "slots are available, but also tentative slots that have been held as tentative", "the fields associated with other types of events (location, etc.) ''' pricingTier =", "kwargs.get('eventRegistration', None) affectedSlots = self.instructoravailabilityslot_set.all() affectedSlots.update( status=InstructorAvailabilitySlot.SlotStatus.booked, eventRegistration=eventRegistration, ) if notifyStudent: # This", "= models.ForeignKey( Customer, verbose_name=_('Customer'), on_delete=models.CASCADE ) lesson = models.ForeignKey( PrivateLessonEvent, verbose_name=_('Lesson'), on_delete=models.CASCADE )", "**kwargs): ''' Set registration status to hidden if it is not specified otherwise", "@property def customers(self): ''' List both any individuals signed up via the registration", "reverse from datetime import timedelta from danceschool.core.models import ( Instructor, Location, Room, DanceRole,", "link to the registrations and a link to the event because # in", "lesson. All of the registration logic is still handled by the core app,", "= models.PositiveSmallIntegerField(_('Slot duration (minutes)'), default=30) location = models.ForeignKey( Location, verbose_name=_('Location'), null=True, blank=True, on_delete=models.SET_NULL,", "expired (temporary) Registration is deleted, we still want to # be able to", "blank=True, on_delete=models.SET_NULL, related_name='privateLessonSlots' ) creationDate = models.DateTimeField(auto_now_add=True) modifiedDate = models.DateTimeField(auto_now=True) @property def availableDurations(self):", ") ] for instructor in instructors: if not instructor.privateEmail and not instructor.publicEmail: #", "of the base Event class by checking the pricingTier associated with this PrivateLessonEvent", "This method requires that slots are non-overlapping, which needs to be enforced on", "slot.duration > getConstant('privateLessons__maximumLessonLength'): break if ( slot.startTime == last_start + timedelta(minutes=last_duration) and slot.isAvailable", "if it is not specified otherwise ''' if not self.status: self.status == Event.RegStatus.hidden", "Room, verbose_name=_('Room'), null=True, blank=True, on_delete=models.SET_NULL, ) status = models.CharField(max_length=1, choices=SlotStatus.choices, default=SlotStatus.available) # We", "slot.startTime == last_start + timedelta(minutes=last_duration) and slot.isAvailable ): duration_list.append(max_duration + slot.duration) last_start =", "from danceschool.core.mixins import EmailRecipientMixin from danceschool.core.utils.timezone import ensure_localtime class InstructorPrivateLessonDetails(models.Model): instructor = models.OneToOneField(StaffMember,", "_('Private lesson customers') class InstructorAvailabilitySlot(models.Model): class SlotStatus(models.TextChoices): available = ('A', _('Available')) booked =", "= EmailRecipientMixin() instructors = [ x.staffMember for x in self.eventstaffmember_set.exclude( Q(staffMember__privateEmail__isnull=True) & Q(staffMember__publicEmail__isnull=True)", "without payment. ''' return Customer.objects.filter( Q(privatelessoncustomer__lesson=self) | Q(registration__eventregistration__event=self) ).distinct() customers.fget.short_description = _('Customers') @property", "have been selected for the instructor. ''' if not hasattr(self.instructor, 'instructorprivatelessondetails'): return []", "have been compensated template = getConstant('privateLessons__lessonBookedInstructorEmailTemplate') if template.defaultFromAddress and template.content: emailMixin = EmailRecipientMixin()", "lesson #%s' % (self.customer.fullName, self.lesson.id))) class Meta: unique_together = ('customer', 'lesson') verbose_name =", "date ''' return ( self.startTime >= dateTime + timedelta(days=getConstant('privateLessons__closeBookingDays')) and self.startTime <= dateTime", "blank=True, on_delete=models.SET_NULL, ) room = models.ForeignKey( Room, verbose_name=_('Room'), null=True, blank=True, on_delete=models.SET_NULL, ) status", "(location, etc.) ''' pricingTier = models.ForeignKey( PricingTier, verbose_name=_('Pricing Tier'), null=True, blank=True, on_delete=models.SET_NULL )", "import reverse from datetime import timedelta from danceschool.core.models import ( Instructor, Location, Room,", "instructor cannot be notified continue emailMixin.email_recipient( template.subject, template.content, send_html=False, from_address=template.defaultFromAddress, from_name=template.defaultFromName, cc=template.defaultCC, to=instructor.privateEmail", "template.defaultFromAddress and template.content: emailMixin = EmailRecipientMixin() instructors = [ x.staffMember for x in", "= _('Private lesson customer') verbose_name_plural = _('Private lesson customers') class InstructorAvailabilitySlot(models.Model): class SlotStatus(models.TextChoices):", "self.location ) def __str__(self): return str(self.name) class Meta: ordering = ('-startTime', 'instructor__lastName', 'instructor__firstName')", "Instructor, Location, Room, DanceRole, Event, PricingTier, EventRegistration, Customer, StaffMember ) from danceschool.core.constants import", "to=instructor.privateEmail or instructor.publicEmail, lesson=self, instructor=instructor, customers=self.customers, calendarUrl=reverse('privateCalendar'), ) @property def customers(self): ''' List", "verbose_name=_('Room'), null=True, blank=True, on_delete=models.SET_NULL, ) status = models.CharField(max_length=1, choices=SlotStatus.choices, default=SlotStatus.available) # We need", "''' return max(self.numSlots, 1) def nameAndDate(self, withDate=True): teacherNames = ' and '.join([x.staffMember.fullName for", "EmailRecipientMixin() instructors = [ x.staffMember for x in self.eventstaffmember_set.exclude( Q(staffMember__privateEmail__isnull=True) & Q(staffMember__publicEmail__isnull=True) )", "and slot.isAvailable ): duration_list.append(max_duration + slot.duration) last_start = slot.startTime last_duration = slot.duration max_duration", "= ('customer', 'lesson') verbose_name = _('Private lesson customer') verbose_name_plural = _('Private lesson customers')", "for x in self.eventstaffmember_set.all()]) if self.customers: customerNames = ' ' + ' and", "= _('Private lesson customers') class InstructorAvailabilitySlot(models.Model): class SlotStatus(models.TextChoices): available = ('A', _('Available')) booked", "% ( teacherNames, _(' for ') if teacherNames and customerNames else '', customerNames,", "if notifyTeachers: # This is the email template used to notify individuals who", "from django.utils.translation import gettext_lazy as _ from django.utils import timezone from django.urls import", "model inherits all of the fields associated with other types of events (location,", "str(_('Instructor Private lesson details for %s' % self.instructor.fullName)) class Meta: ordering = ('instructor__lastName',", "InstructorAvailabilitySlot(models.Model): class SlotStatus(models.TextChoices): available = ('A', _('Available')) booked = ('B', _('Booked')) tentative =", "user books a lesson. All of the registration logic is still handled by", "''' This is the event object for which an individual registers. The event", "on the number of slots booked, this just returns the number of slots", "signed up via the registration and payment system, and any individuals signed up", "returns the number of slots associated with this event (or 1). ''' return", "customers are the individuals who are registered. For private lessons that are booked", "django.utils import timezone from django.urls import reverse from datetime import timedelta from danceschool.core.models", "if a slot is currently available isAvailable = property(fget=checkIfAvailable) isAvailable.fget.short_description = _('Available') @property", "not instructor.publicEmail: # Without an email address, instructor cannot be notified continue emailMixin.email_recipient(", "if template.defaultFromAddress and template.content: emailMixin = EmailRecipientMixin() instructors = [ x.staffMember for x", "_('Booked')) tentative = ('T', _('Tentative Booking')) unavailable = ('U', _('Unavailable')) instructor = models.ForeignKey(Instructor,", "else '' else: customerNames = '' if not teacherNames and not customerNames and", "in instructors: if not instructor.privateEmail and not instructor.publicEmail: # Without an email address,", "if self.customers: customerNames = ' ' + ' and '.join([x.fullName for x in", "participants = models.PositiveSmallIntegerField(_('Expected # of Participants'), null=True, blank=True, default=1) comments = models.TextField( _('Comments/Notes'),", "registration and payment system, and any individuals signed up without payment. ''' return", "('-startTime', 'instructor__lastName', 'instructor__firstName') verbose_name = _('Private lesson availability slot') verbose_name_plural = _('Private lesson", "isAvailable indicates if a slot is currently available isAvailable = property(fget=checkIfAvailable) isAvailable.fget.short_description =", "This is the event object for which an individual registers. The event is", "time')) duration = models.PositiveSmallIntegerField(_('Slot duration (minutes)'), default=30) location = models.ForeignKey( Location, verbose_name=_('Location'), null=True,", "want to # be able to identify the Event that was created for", "= slot.startTime last_duration = slot.duration max_duration += slot.duration return duration_list @property def availableRoles(self):", "private lessons that are booked without payment, this just provides a record that", "currently available isAvailable = property(fget=checkIfAvailable) isAvailable.fget.short_description = _('Available') @property def name(self): return _('%s:", "handled by the core app, and this model inherits all of the fields", "| Q(registration__eventregistration__event=self) ).distinct() customers.fget.short_description = _('Customers') @property def numSlots(self): ''' Used for various", "installed, the discounts app looks for this property to determine how many points", "None) affectedSlots = self.instructoravailabilityslot_set.all() affectedSlots.update( status=InstructorAvailabilitySlot.SlotStatus.booked, eventRegistration=eventRegistration, ) if notifyStudent: # This is", "status=InstructorAvailabilitySlot.SlotStatus.booked, eventRegistration=eventRegistration, ) if notifyStudent: # This is the email template used to", "template.content: for customer in self.customers: customer.email_recipient( template.subject, template.content, send_html=False, from_address=template.defaultFromAddress, from_name=template.defaultFromName, cc=template.defaultCC, to=customer.email,", "is created when the user books a lesson. All of the registration logic", "and not withDate: return _('Private Lesson') return _('Private Lesson: %s%s%s%s' % ( teacherNames,", "Lesson') return _('Private Lesson: %s%s%s%s' % ( teacherNames, _(' for ') if teacherNames", "For private lessons that are booked without payment, this just provides a record", "' + names if names else '' else: customerNames = '' if not", "otherwise ''' if not self.status: self.status == Event.RegStatus.hidden super().save(*args, **kwargs) def __str__(self): return", "from danceschool.core.constants import getConstant from danceschool.core.mixins import EmailRecipientMixin from danceschool.core.utils.timezone import ensure_localtime class", "def name(self): return _('%s: %s at %s') % ( self.instructor.fullName, ensure_localtime(self.startTime).strftime('%b %-d, %Y", "to notify individuals who run registration # that they have been compensated template", "models.DateTimeField(_('Start time')) duration = models.PositiveSmallIntegerField(_('Slot duration (minutes)'), default=30) location = models.ForeignKey( Location, verbose_name=_('Location'),", "PricingTier, verbose_name=_('Pricing Tier'), null=True, blank=True, on_delete=models.SET_NULL ) startTime = models.DateTimeField(_('Start time')) duration =", "%s at %s') % ( self.instructor.fullName, ensure_localtime(self.startTime).strftime('%b %-d, %Y %-I:%M %p'), self.location )", "_('Unavailable')) instructor = models.ForeignKey(Instructor, verbose_name=_('Instructor'), on_delete=models.CASCADE) pricingTier = models.ForeignKey( PricingTier, verbose_name=_('Pricing Tier'), null=True,", "ensure_localtime(self.startTime).strftime('%b %-d, %Y %-I:%M %p'), self.location ) def __str__(self): return str(self.name) class Meta:", "not instructor.privateEmail and not instructor.publicEmail: # Without an email address, instructor cannot be", "the registration and payment system, and any individuals signed up without payment. '''", "just returns the number of slots associated with this event (or 1). '''", "models.ForeignKey( PrivateLessonEvent, verbose_name=_('Lesson'), on_delete=models.CASCADE ) def __str__(self): return str(_('Private lesson customer: %s for", "def checkIfAvailable(self, dateTime=timezone.now()): ''' Available slots are available, but also tentative slots that", "django.db.models import Q from django.utils.translation import gettext_lazy as _ from django.utils import timezone", "of the registration logic is still handled by the core app, and this", "(minutes)'), default=30) location = models.ForeignKey( Location, verbose_name=_('Location'), null=True, blank=True, on_delete=models.SET_NULL, ) room =", "models.ForeignKey(Instructor, verbose_name=_('Instructor'), on_delete=models.CASCADE) pricingTier = models.ForeignKey( PricingTier, verbose_name=_('Pricing Tier'), null=True, blank=True, on_delete=models.SET_NULL )", "self.instructor.fullName)) class Meta: ordering = ('instructor__lastName', 'instructor__firstName') verbose_name = _('Instructor private lesson details')", "numSlots(self): ''' Used for various pricing discounts related things ''' return self.instructoravailabilityslot_set.count() @property", "def finalizeBooking(self, **kwargs): notifyStudent = kwargs.get('notifyStudent', True) notifyTeachers = kwargs.get('notifyTeachers', getConstant('privateLessons__notifyInstructor')) eventRegistration =", "property to determine how many points this lesson is worth toward a discount.", "not self.status: self.status == Event.RegStatus.hidden super().save(*args, **kwargs) def __str__(self): return str(self.name) class Meta:", "lesson customers') class InstructorAvailabilitySlot(models.Model): class SlotStatus(models.TextChoices): available = ('A', _('Available')) booked = ('B',", "verbose_name = _('Instructor private lesson details') verbose_name_plural = _('Instructors\\' private lesson details') class", "one\\'s own private lesson availability.')), ('edit_others_availability', _('Can edit other instructors\\' private lesson availability.')),", "that slots are non-overlapping, which needs to be enforced on slot save. '''", "import Q from django.utils.translation import gettext_lazy as _ from django.utils import timezone from", "# of Participants'), null=True, blank=True, default=1) comments = models.TextField( _('Comments/Notes'), null=True, blank=True, help_text=_('For", "+ slot.duration) last_start = slot.startTime last_duration = slot.duration max_duration += slot.duration return duration_list", "startTime = models.DateTimeField(_('Start time')) duration = models.PositiveSmallIntegerField(_('Slot duration (minutes)'), default=30) location = models.ForeignKey(", "that go through registration and payment, the customers are the individuals who are", "slots are non-overlapping, which needs to be enforced on slot save. ''' potential_slots", "models.OneToOneField(StaffMember, on_delete=models.CASCADE) defaultPricingTier = models.ForeignKey( PricingTier, verbose_name=_('Default Pricing Tier'), null=True, blank=True, on_delete=models.SET_NULL )", "self.eventregistration_set.all(): names = ' and '.join([x.registration.fullName for x in self.eventregistration_set.all()]) customerNames = '", "and recordkeeping.') ) def getBasePrice(self, **kwargs): ''' This method overrides the method of", "For private lessons that go through registration and payment, the customers are the", "blank=True, on_delete=models.SET_NULL ) startTime = models.DateTimeField(_('Start time')) duration = models.PositiveSmallIntegerField(_('Slot duration (minutes)'), default=30)", "Location, Room, DanceRole, Event, PricingTier, EventRegistration, Customer, StaffMember ) from danceschool.core.constants import getConstant", "None ), 'expirationDate', timezone.now() ) <= timezone.now() ) ) ) # isAvailable indicates", "and template.content: emailMixin = EmailRecipientMixin() instructors = [ x.staffMember for x in self.eventstaffmember_set.exclude(", "a record that they signed up for the lesson. ''' customer = models.ForeignKey(", "to the registrations and a link to the event because # in the", "= InstructorAvailabilitySlot.objects.filter( instructor=self.instructor, location=self.location, room=self.room, pricingTier=self.pricingTier, startTime__gte=self.startTime, startTime__lte=self.startTime + timedelta(minutes=getConstant('privateLessons__maximumLessonLength')), ).exclude(id=self.id).order_by('startTime') duration_list =", "ordering = ('-startTime', 'instructor__lastName', 'instructor__firstName') verbose_name = _('Private lesson availability slot') verbose_name_plural =", "models.ForeignKey( PricingTier, verbose_name=_('Pricing Tier'), null=True, blank=True, on_delete=models.SET_NULL ) startTime = models.DateTimeField(_('Start time')) duration", "event because # in the event that an expired (temporary) Registration is deleted,", "for which an individual registers. The event is created when the user books", "verbose_name=_('Customer'), on_delete=models.CASCADE ) lesson = models.ForeignKey( PrivateLessonEvent, verbose_name=_('Lesson'), on_delete=models.CASCADE ) def __str__(self): return", "= getConstant('privateLessons__lessonBookedInstructorEmailTemplate') if template.defaultFromAddress and template.content: emailMixin = EmailRecipientMixin() instructors = [ x.staffMember", "needs to be enforced on slot save. ''' potential_slots = InstructorAvailabilitySlot.objects.filter( instructor=self.instructor, location=self.location,", "from danceschool.core.utils.timezone import ensure_localtime class InstructorPrivateLessonDetails(models.Model): instructor = models.OneToOneField(StaffMember, on_delete=models.CASCADE) defaultPricingTier = models.ForeignKey(", "# This is the email template used to notify individuals who run registration", "of the fields associated with other types of events (location, etc.) ''' pricingTier", "return _('Private Lesson') return _('Private Lesson: %s%s%s%s' % ( teacherNames, _(' for ')", "= _('Available') @property def name(self): return _('%s: %s at %s') % ( self.instructor.fullName,", "logic is still handled by the core app, and this model inherits all", "for certain roles, so we should only allow booking for the roles that", "+ timedelta(minutes=last_duration) and slot.isAvailable ): duration_list.append(max_duration + slot.duration) last_start = slot.startTime last_duration =", "getConstant('privateLessons__lessonBookedInstructorEmailTemplate') if template.defaultFromAddress and template.content: emailMixin = EmailRecipientMixin() instructors = [ x.staffMember for", "status = models.CharField(max_length=1, choices=SlotStatus.choices, default=SlotStatus.available) # We need both a link to the", "duration_list.append(max_duration + slot.duration) last_start = slot.startTime last_duration = slot.duration max_duration += slot.duration return", "related_name='privateLessonSlots' ) creationDate = models.DateTimeField(auto_now_add=True) modifiedDate = models.DateTimeField(auto_now=True) @property def availableDurations(self): ''' A", "overrides the method of the base Event class by checking the pricingTier associated", "lesson') verbose_name_plural = _('Private lessons') class PrivateLessonCustomer(models.Model): ''' For private lessons that go", "Room, DanceRole, Event, PricingTier, EventRegistration, Customer, StaffMember ) from danceschool.core.constants import getConstant from", "private lesson details') verbose_name_plural = _('Instructors\\' private lesson details') class PrivateLessonEvent(Event): ''' This", "= models.ForeignKey( PricingTier, verbose_name=_('Pricing Tier'), null=True, blank=True, on_delete=models.SET_NULL ) participants = models.PositiveSmallIntegerField(_('Expected #", "calendarUrl=reverse('privateCalendar'), ) @property def customers(self): ''' List both any individuals signed up via", "1). ''' return max(self.numSlots, 1) def nameAndDate(self, withDate=True): teacherNames = ' and '.join([x.staffMember.fullName", "class Meta: ordering = ('instructor__lastName', 'instructor__firstName') verbose_name = _('Instructor private lesson details') verbose_name_plural", "lesson has been # successfully scheduled template = getConstant('privateLessons__lessonBookedEmailTemplate') if template.defaultFromAddress and template.content:", "= models.DateTimeField(_('Start time')) duration = models.PositiveSmallIntegerField(_('Slot duration (minutes)'), default=30) location = models.ForeignKey( Location,", ") def __str__(self): return str(self.name) class Meta: ordering = ('-startTime', 'instructor__lastName', 'instructor__firstName') verbose_name", "worth toward a discount. Since private lesson points are based on the number", "None), 'invoice', None ), 'expirationDate', timezone.now() ) <= timezone.now() ) ) ) #", "individuals who are registered. For private lessons that are booked without payment, this", "but this method checks if multiple slots are available. This method requires that", "not specified otherwise ''' if not self.status: self.status == Event.RegStatus.hidden super().save(*args, **kwargs) def", "x.staffMember for x in self.eventstaffmember_set.exclude( Q(staffMember__privateEmail__isnull=True) & Q(staffMember__publicEmail__isnull=True) ) ] for instructor in", "slot, but this method checks if multiple slots are available. This method requires", "method overrides the method of the base Event class by checking the pricingTier", "class Meta: ordering = ('-startTime', 'instructor__lastName', 'instructor__firstName') verbose_name = _('Private lesson availability slot')", "etc.) ''' pricingTier = models.ForeignKey( PricingTier, verbose_name=_('Pricing Tier'), null=True, blank=True, on_delete=models.SET_NULL ) participants", "null=True, blank=True, help_text=_('For internal use and recordkeeping.') ) def getBasePrice(self, **kwargs): ''' This", "# be able to identify the Event that was created for this private", "gettext_lazy as _ from django.utils import timezone from django.urls import reverse from datetime", "if multiple slots are available. This method requires that slots are non-overlapping, which", ">= dateTime + timedelta(days=getConstant('privateLessons__closeBookingDays')) and self.startTime <= dateTime + timedelta(days=getConstant('privateLessons__openBookingDays')) and not self.eventRegistration", "things ''' return self.instructoravailabilityslot_set.count() @property def discountPointsMultiplier(self): ''' If installed, the discounts app", "app, and this model inherits all of the fields associated with other types", "signed up for the lesson. ''' customer = models.ForeignKey( Customer, verbose_name=_('Customer'), on_delete=models.CASCADE )", "_('Private lesson customer') verbose_name_plural = _('Private lesson customers') class InstructorAvailabilitySlot(models.Model): class SlotStatus(models.TextChoices): available", "timedelta from danceschool.core.models import ( Instructor, Location, Room, DanceRole, Event, PricingTier, EventRegistration, Customer,", "email template used to notify individuals who run registration # that they have", "for slot in potential_slots: if max_duration + slot.duration > getConstant('privateLessons__maximumLessonLength'): break if (", "'instructorprivatelessondetails'): return [] return [ [x.id, x.name] for x in self.instructor.instructorprivatelessondetails.roles.all() ] def", "verbose_name=_('Pricing Tier'), null=True, blank=True, on_delete=models.SET_NULL ) participants = models.PositiveSmallIntegerField(_('Expected # of Participants'), null=True,", "1) def nameAndDate(self, withDate=True): teacherNames = ' and '.join([x.staffMember.fullName for x in self.eventstaffmember_set.all()])", "not teacherNames and not customerNames and not withDate: return _('Private Lesson') return _('Private", "room=self.room, pricingTier=self.pricingTier, startTime__gte=self.startTime, startTime__lte=self.startTime + timedelta(minutes=getConstant('privateLessons__maximumLessonLength')), ).exclude(id=self.id).order_by('startTime') duration_list = [self.duration, ] last_start =", "def name(self): return self.nameAndDate(withDate=True) def save(self, *args, **kwargs): ''' Set registration status to", "( self.status == self.SlotStatus.tentative and getattr( getattr( getattr(self.eventRegistration, 'invoiceItem', None), 'invoice', None ),", "in self.customers]) elif self.eventregistration_set.all(): names = ' and '.join([x.registration.fullName for x in self.eventregistration_set.all()])", ") def __str__(self): return str(_('Private lesson customer: %s for lesson #%s' % (self.customer.fullName,", "= [ x.staffMember for x in self.eventstaffmember_set.exclude( Q(staffMember__privateEmail__isnull=True) & Q(staffMember__publicEmail__isnull=True) ) ] for", "this property to determine how many points this lesson is worth toward a", "if not teacherNames and not customerNames and not withDate: return _('Private Lesson') return", "held as tentative past their expiration date ''' return ( self.startTime >= dateTime", "else '' )) @property def name(self): return self.nameAndDate(withDate=True) def save(self, *args, **kwargs): '''", "('A', _('Available')) booked = ('B', _('Booked')) tentative = ('T', _('Tentative Booking')) unavailable =", "[] return [ [x.id, x.name] for x in self.instructor.instructorprivatelessondetails.roles.all() ] def checkIfAvailable(self, dateTime=timezone.now()):", "= models.ForeignKey( PricingTier, verbose_name=_('Default Pricing Tier'), null=True, blank=True, on_delete=models.SET_NULL ) roles = models.ManyToManyField(DanceRole,", "object for which an individual registers. The event is created when the user", ") lesson = models.ForeignKey( PrivateLessonEvent, verbose_name=_('Lesson'), on_delete=models.CASCADE ) def __str__(self): return str(_('Private lesson", "''' Set registration status to hidden if it is not specified otherwise '''", "' if (teacherNames or customerNames) else '') + self.startTime.strftime('%Y-%m-%d') ) if withDate else", "import models from django.db.models import Q from django.utils.translation import gettext_lazy as _ from", "able to identify the Event that was created for this private lesson. lessonEvent", "models.ForeignKey( EventRegistration, verbose_name=_('event registration'), null=True, blank=True, on_delete=models.SET_NULL, related_name='privateLessonSlots' ) creationDate = models.DateTimeField(auto_now_add=True) modifiedDate", "break if ( slot.startTime == last_start + timedelta(minutes=last_duration) and slot.isAvailable ): duration_list.append(max_duration +", "multiple slots are available. This method requires that slots are non-overlapping, which needs", "use and recordkeeping.') ) def getBasePrice(self, **kwargs): ''' This method overrides the method", "notifyStudent: # This is the email template used to notify students that their", "on slot save. ''' potential_slots = InstructorAvailabilitySlot.objects.filter( instructor=self.instructor, location=self.location, room=self.room, pricingTier=self.pricingTier, startTime__gte=self.startTime, startTime__lte=self.startTime", "if not self.pricingTier: return None return self.pricingTier.getBasePrice(**kwargs) * max(self.numSlots, 1) def finalizeBooking(self, **kwargs):", "events (location, etc.) ''' pricingTier = models.ForeignKey( PricingTier, verbose_name=_('Pricing Tier'), null=True, blank=True, on_delete=models.SET_NULL", "+ timedelta(minutes=getConstant('privateLessons__maximumLessonLength')), ).exclude(id=self.id).order_by('startTime') duration_list = [self.duration, ] last_start = self.startTime last_duration = self.duration", "names if names else '' else: customerNames = '' if not teacherNames and", "cc=template.defaultCC, to=customer.email, lesson=self, ) if notifyTeachers: # This is the email template used", "couples'), default=True) smallGroups = models.BooleanField(_('Private lessons for small groups'), default=True) def __str__(self): return", "to the event because # in the event that an expired (temporary) Registration", "= _('Private lessons') class PrivateLessonCustomer(models.Model): ''' For private lessons that go through registration", "this method checks if multiple slots are available. This method requires that slots", "PrivateLessonEvent, verbose_name=_('Lesson'), on_delete=models.CASCADE ) def __str__(self): return str(_('Private lesson customer: %s for lesson", "on_delete=models.SET_NULL, ) status = models.CharField(max_length=1, choices=SlotStatus.choices, default=SlotStatus.available) # We need both a link", "eventRegistration=eventRegistration, ) if notifyStudent: # This is the email template used to notify", ") <= timezone.now() ) ) ) # isAvailable indicates if a slot is", "not hasattr(self.instructor, 'instructorprivatelessondetails'): return [] return [ [x.id, x.name] for x in self.instructor.instructorprivatelessondetails.roles.all()", "_('Instructors\\' private lesson details') class PrivateLessonEvent(Event): ''' This is the event object for", "if max_duration + slot.duration > getConstant('privateLessons__maximumLessonLength'): break if ( slot.startTime == last_start +", "roles, so we should only allow booking for the roles that have been", "_(' for ') if teacherNames and customerNames else '', customerNames, ( (', '", "through registration and payment, the customers are the individuals who are registered. For", "or instructor.publicEmail, lesson=self, instructor=instructor, customers=self.customers, calendarUrl=reverse('privateCalendar'), ) @property def customers(self): ''' List both", "(or 1). ''' return max(self.numSlots, 1) def nameAndDate(self, withDate=True): teacherNames = ' and", "str(self.name) class Meta: permissions = ( ('view_others_lessons', _('Can view scheduled private lessons for", "super().save(*args, **kwargs) def __str__(self): return str(self.name) class Meta: permissions = ( ('view_others_lessons', _('Can", "because # in the event that an expired (temporary) Registration is deleted, we", "timedelta(minutes=getConstant('privateLessons__maximumLessonLength')), ).exclude(id=self.id).order_by('startTime') duration_list = [self.duration, ] last_start = self.startTime last_duration = self.duration max_duration", "getting the appropriate price for it. ''' if not self.pricingTier: return None return", "''' potential_slots = InstructorAvailabilitySlot.objects.filter( instructor=self.instructor, location=self.location, room=self.room, pricingTier=self.pricingTier, startTime__gte=self.startTime, startTime__lte=self.startTime + timedelta(minutes=getConstant('privateLessons__maximumLessonLength')), ).exclude(id=self.id).order_by('startTime')", "import gettext_lazy as _ from django.utils import timezone from django.urls import reverse from", "Customer, verbose_name=_('Customer'), on_delete=models.CASCADE ) lesson = models.ForeignKey( PrivateLessonEvent, verbose_name=_('Lesson'), on_delete=models.CASCADE ) def __str__(self):", "also tentative slots that have been held as tentative past their expiration date", "elif self.eventregistration_set.all(): names = ' and '.join([x.registration.fullName for x in self.eventregistration_set.all()]) customerNames =", "available isAvailable = property(fget=checkIfAvailable) isAvailable.fget.short_description = _('Available') @property def name(self): return _('%s: %s", "''' For private lessons that go through registration and payment, the customers are", "models.DateTimeField(auto_now_add=True) modifiedDate = models.DateTimeField(auto_now=True) @property def availableDurations(self): ''' A lesson can always be", "x in self.customers]) elif self.eventregistration_set.all(): names = ' and '.join([x.registration.fullName for x in", "registered. For private lessons that are booked without payment, this just provides a", "All of the registration logic is still handled by the core app, and", "been # successfully scheduled template = getConstant('privateLessons__lessonBookedEmailTemplate') if template.defaultFromAddress and template.content: for customer", "return str(_('Private lesson customer: %s for lesson #%s' % (self.customer.fullName, self.lesson.id))) class Meta:", "notifyTeachers: # This is the email template used to notify individuals who run", "not customerNames and not withDate: return _('Private Lesson') return _('Private Lesson: %s%s%s%s' %", "eventRegistration = models.ForeignKey( EventRegistration, verbose_name=_('event registration'), null=True, blank=True, on_delete=models.SET_NULL, related_name='privateLessonSlots' ) creationDate =", "associated with this event (or 1). ''' return max(self.numSlots, 1) def nameAndDate(self, withDate=True):", "it is not specified otherwise ''' if not self.status: self.status == Event.RegStatus.hidden super().save(*args,", "booked without payment, this just provides a record that they signed up for", "in self.customers: customer.email_recipient( template.subject, template.content, send_html=False, from_address=template.defaultFromAddress, from_name=template.defaultFromName, cc=template.defaultCC, to=customer.email, lesson=self, ) if", "details for %s' % self.instructor.fullName)) class Meta: ordering = ('instructor__lastName', 'instructor__firstName') verbose_name =", "x in self.eventregistration_set.all()]) customerNames = ' ' + names if names else ''", "ordering = ('instructor__lastName', 'instructor__firstName') verbose_name = _('Instructor private lesson details') verbose_name_plural = _('Instructors\\'", "record that they signed up for the lesson. ''' customer = models.ForeignKey( Customer,", "default=1) comments = models.TextField( _('Comments/Notes'), null=True, blank=True, help_text=_('For internal use and recordkeeping.') )", "property(fget=checkIfAvailable) isAvailable.fget.short_description = _('Available') @property def name(self): return _('%s: %s at %s') %", "permissions = ( ('view_others_lessons', _('Can view scheduled private lessons for all instructors')), )", "SlotStatus(models.TextChoices): available = ('A', _('Available')) booked = ('B', _('Booked')) tentative = ('T', _('Tentative", "PrivateLessonEvent(Event): ''' This is the event object for which an individual registers. The", "Meta: ordering = ('-startTime', 'instructor__lastName', 'instructor__firstName') verbose_name = _('Private lesson availability slot') verbose_name_plural", "only allow booking for the roles that have been selected for the instructor.", "('edit_own_availability', _('Can edit one\\'s own private lesson availability.')), ('edit_others_availability', _('Can edit other instructors\\'", "self.status == self.SlotStatus.available or ( self.status == self.SlotStatus.tentative and getattr( getattr( getattr(self.eventRegistration, 'invoiceItem',", "@property def name(self): return _('%s: %s at %s') % ( self.instructor.fullName, ensure_localtime(self.startTime).strftime('%b %-d,", "and customerNames else '', customerNames, ( (', ' if (teacherNames or customerNames) else", "_('Private lessons') class PrivateLessonCustomer(models.Model): ''' For private lessons that go through registration and", "pricing discounts related things ''' return self.instructoravailabilityslot_set.count() @property def discountPointsMultiplier(self): ''' If installed,", "on_delete=models.CASCADE ) def __str__(self): return str(_('Private lesson customer: %s for lesson #%s' %", "('U', _('Unavailable')) instructor = models.ForeignKey(Instructor, verbose_name=_('Instructor'), on_delete=models.CASCADE) pricingTier = models.ForeignKey( PricingTier, verbose_name=_('Pricing Tier'),", "a lesson. All of the registration logic is still handled by the core", "but also tentative slots that have been held as tentative past their expiration", "ensure_localtime class InstructorPrivateLessonDetails(models.Model): instructor = models.OneToOneField(StaffMember, on_delete=models.CASCADE) defaultPricingTier = models.ForeignKey( PricingTier, verbose_name=_('Default Pricing", "& Q(staffMember__publicEmail__isnull=True) ) ] for instructor in instructors: if not instructor.privateEmail and not", "to hidden if it is not specified otherwise ''' if not self.status: self.status", "be booked for the length of a single slot, but this method checks", "and self.startTime <= dateTime + timedelta(days=getConstant('privateLessons__openBookingDays')) and not self.eventRegistration and ( self.status ==", "as _ from django.utils import timezone from django.urls import reverse from datetime import", "cc=template.defaultCC, to=instructor.privateEmail or instructor.publicEmail, lesson=self, instructor=instructor, customers=self.customers, calendarUrl=reverse('privateCalendar'), ) @property def customers(self): '''", "''' pricingTier = models.ForeignKey( PricingTier, verbose_name=_('Pricing Tier'), null=True, blank=True, on_delete=models.SET_NULL ) participants =", "instructor=self.instructor, location=self.location, room=self.room, pricingTier=self.pricingTier, startTime__gte=self.startTime, startTime__lte=self.startTime + timedelta(minutes=getConstant('privateLessons__maximumLessonLength')), ).exclude(id=self.id).order_by('startTime') duration_list = [self.duration, ]", "_('Private lesson availability slot') verbose_name_plural = _('Private lesson availability slots') permissions = (", "smallGroups = models.BooleanField(_('Private lessons for small groups'), default=True) def __str__(self): return str(_('Instructor Private", "a single slot, but this method checks if multiple slots are available. This", ") ) # isAvailable indicates if a slot is currently available isAvailable =", "verbose_name=_('Location'), null=True, blank=True, on_delete=models.SET_NULL, ) room = models.ForeignKey( Room, verbose_name=_('Room'), null=True, blank=True, on_delete=models.SET_NULL,", "InstructorPrivateLessonDetails(models.Model): instructor = models.OneToOneField(StaffMember, on_delete=models.CASCADE) defaultPricingTier = models.ForeignKey( PricingTier, verbose_name=_('Default Pricing Tier'), null=True,", "''' customer = models.ForeignKey( Customer, verbose_name=_('Customer'), on_delete=models.CASCADE ) lesson = models.ForeignKey( PrivateLessonEvent, verbose_name=_('Lesson'),", "requires that slots are non-overlapping, which needs to be enforced on slot save.", "lessons for small groups'), default=True) def __str__(self): return str(_('Instructor Private lesson details for", "instructor.privateEmail and not instructor.publicEmail: # Without an email address, instructor cannot be notified", "+ names if names else '' else: customerNames = '' if not teacherNames", ") ) ) # isAvailable indicates if a slot is currently available isAvailable", "booked = ('B', _('Booked')) tentative = ('T', _('Tentative Booking')) unavailable = ('U', _('Unavailable'))", "this event (or 1). ''' return max(self.numSlots, 1) def nameAndDate(self, withDate=True): teacherNames =", "'expirationDate', timezone.now() ) <= timezone.now() ) ) ) # isAvailable indicates if a", "private lesson points are based on the number of slots booked, this just", "== self.SlotStatus.available or ( self.status == self.SlotStatus.tentative and getattr( getattr( getattr(self.eventRegistration, 'invoiceItem', None),", "been selected for the instructor. ''' if not hasattr(self.instructor, 'instructorprivatelessondetails'): return [] return", "''' Some instructors only offer private lessons for certain roles, so we should", "self.duration max_duration = self.duration for slot in potential_slots: if max_duration + slot.duration >", "booking for the roles that have been selected for the instructor. ''' if", "instructor in instructors: if not instructor.privateEmail and not instructor.publicEmail: # Without an email", "''' This method overrides the method of the base Event class by checking", "' and '.join([x.fullName for x in self.customers]) elif self.eventregistration_set.all(): names = ' and", ") if notifyStudent: # This is the email template used to notify students", "* max(self.numSlots, 1) def finalizeBooking(self, **kwargs): notifyStudent = kwargs.get('notifyStudent', True) notifyTeachers = kwargs.get('notifyTeachers',", "certain roles, so we should only allow booking for the roles that have", "is still handled by the core app, and this model inherits all of", "on_delete=models.SET_NULL ) participants = models.PositiveSmallIntegerField(_('Expected # of Participants'), null=True, blank=True, default=1) comments =", "pricingTier = models.ForeignKey( PricingTier, verbose_name=_('Pricing Tier'), null=True, blank=True, on_delete=models.SET_NULL ) participants = models.PositiveSmallIntegerField(_('Expected", "= kwargs.get('notifyStudent', True) notifyTeachers = kwargs.get('notifyTeachers', getConstant('privateLessons__notifyInstructor')) eventRegistration = kwargs.get('eventRegistration', None) affectedSlots =", "''' if not self.status: self.status == Event.RegStatus.hidden super().save(*args, **kwargs) def __str__(self): return str(self.name)", "customer: %s for lesson #%s' % (self.customer.fullName, self.lesson.id))) class Meta: unique_together = ('customer',", "isAvailable.fget.short_description = _('Available') @property def name(self): return _('%s: %s at %s') % (", "at %s') % ( self.instructor.fullName, ensure_localtime(self.startTime).strftime('%b %-d, %Y %-I:%M %p'), self.location ) def", "('instructor__lastName', 'instructor__firstName') verbose_name = _('Instructor private lesson details') verbose_name_plural = _('Instructors\\' private lesson", "instructors: if not instructor.privateEmail and not instructor.publicEmail: # Without an email address, instructor", "__str__(self): return str(_('Private lesson customer: %s for lesson #%s' % (self.customer.fullName, self.lesson.id))) class", "instructor.publicEmail: # Without an email address, instructor cannot be notified continue emailMixin.email_recipient( template.subject,", "models.ForeignKey( Location, verbose_name=_('Location'), null=True, blank=True, on_delete=models.SET_NULL, ) room = models.ForeignKey( Room, verbose_name=_('Room'), null=True,", "status to hidden if it is not specified otherwise ''' if not self.status:", "EventRegistration, Customer, StaffMember ) from danceschool.core.constants import getConstant from danceschool.core.mixins import EmailRecipientMixin from", "): duration_list.append(max_duration + slot.duration) last_start = slot.startTime last_duration = slot.duration max_duration += slot.duration", "Without an email address, instructor cannot be notified continue emailMixin.email_recipient( template.subject, template.content, send_html=False,", "checking the pricingTier associated with this PrivateLessonEvent and getting the appropriate price for", "timedelta(days=getConstant('privateLessons__closeBookingDays')) and self.startTime <= dateTime + timedelta(days=getConstant('privateLessons__openBookingDays')) and not self.eventRegistration and ( self.status", "points this lesson is worth toward a discount. Since private lesson points are", "blank=True, on_delete=models.SET_NULL ) participants = models.PositiveSmallIntegerField(_('Expected # of Participants'), null=True, blank=True, default=1) comments", "default=True) def __str__(self): return str(_('Instructor Private lesson details for %s' % self.instructor.fullName)) class", "def discountPointsMultiplier(self): ''' If installed, the discounts app looks for this property to", "it. ''' if not self.pricingTier: return None return self.pricingTier.getBasePrice(**kwargs) * max(self.numSlots, 1) def", "= getConstant('privateLessons__lessonBookedEmailTemplate') if template.defaultFromAddress and template.content: for customer in self.customers: customer.email_recipient( template.subject, template.content,", "'', customerNames, ( (', ' if (teacherNames or customerNames) else '') + self.startTime.strftime('%Y-%m-%d')", "that they signed up for the lesson. ''' customer = models.ForeignKey( Customer, verbose_name=_('Customer'),", "getConstant('privateLessons__notifyInstructor')) eventRegistration = kwargs.get('eventRegistration', None) affectedSlots = self.instructoravailabilityslot_set.all() affectedSlots.update( status=InstructorAvailabilitySlot.SlotStatus.booked, eventRegistration=eventRegistration, ) if", "individuals who run registration # that they have been compensated template = getConstant('privateLessons__lessonBookedInstructorEmailTemplate')", "slot.isAvailable ): duration_list.append(max_duration + slot.duration) last_start = slot.startTime last_duration = slot.duration max_duration +=", "Tier'), null=True, blank=True, on_delete=models.SET_NULL ) startTime = models.DateTimeField(_('Start time')) duration = models.PositiveSmallIntegerField(_('Slot duration", "need both a link to the registrations and a link to the event", "is not specified otherwise ''' if not self.status: self.status == Event.RegStatus.hidden super().save(*args, **kwargs)", "verbose_name = _('Private lesson customer') verbose_name_plural = _('Private lesson customers') class InstructorAvailabilitySlot(models.Model): class", "compensated template = getConstant('privateLessons__lessonBookedInstructorEmailTemplate') if template.defaultFromAddress and template.content: emailMixin = EmailRecipientMixin() instructors =", "non-overlapping, which needs to be enforced on slot save. ''' potential_slots = InstructorAvailabilitySlot.objects.filter(", "location=self.location, room=self.room, pricingTier=self.pricingTier, startTime__gte=self.startTime, startTime__lte=self.startTime + timedelta(minutes=getConstant('privateLessons__maximumLessonLength')), ).exclude(id=self.id).order_by('startTime') duration_list = [self.duration, ] last_start", "this private lesson. lessonEvent = models.ForeignKey( PrivateLessonEvent, verbose_name=_('Scheduled lesson'), null=True, blank=True, on_delete=models.SET_NULL, )", "duration_list @property def availableRoles(self): ''' Some instructors only offer private lessons for certain", "self.startTime >= dateTime + timedelta(days=getConstant('privateLessons__closeBookingDays')) and self.startTime <= dateTime + timedelta(days=getConstant('privateLessons__openBookingDays')) and not", "choices=SlotStatus.choices, default=SlotStatus.available) # We need both a link to the registrations and a", ") creationDate = models.DateTimeField(auto_now_add=True) modifiedDate = models.DateTimeField(auto_now=True) @property def availableDurations(self): ''' A lesson", "discounts related things ''' return self.instructoravailabilityslot_set.count() @property def discountPointsMultiplier(self): ''' If installed, the", "self.nameAndDate(withDate=True) def save(self, *args, **kwargs): ''' Set registration status to hidden if it", "Meta: ordering = ('instructor__lastName', 'instructor__firstName') verbose_name = _('Instructor private lesson details') verbose_name_plural =", "('customer', 'lesson') verbose_name = _('Private lesson customer') verbose_name_plural = _('Private lesson customers') class", "the event object for which an individual registers. The event is created when", "lessons that are booked without payment, this just provides a record that they", "enforced on slot save. ''' potential_slots = InstructorAvailabilitySlot.objects.filter( instructor=self.instructor, location=self.location, room=self.room, pricingTier=self.pricingTier, startTime__gte=self.startTime,", "'instructor__firstName') verbose_name = _('Instructor private lesson details') verbose_name_plural = _('Instructors\\' private lesson details')", "fields associated with other types of events (location, etc.) ''' pricingTier = models.ForeignKey(", "self.eventstaffmember_set.exclude( Q(staffMember__privateEmail__isnull=True) & Q(staffMember__publicEmail__isnull=True) ) ] for instructor in instructors: if not instructor.privateEmail", "other types of events (location, etc.) ''' pricingTier = models.ForeignKey( PricingTier, verbose_name=_('Pricing Tier'),", "# in the event that an expired (temporary) Registration is deleted, we still", "self.startTime <= dateTime + timedelta(days=getConstant('privateLessons__openBookingDays')) and not self.eventRegistration and ( self.status == self.SlotStatus.available", "is currently available isAvailable = property(fget=checkIfAvailable) isAvailable.fget.short_description = _('Available') @property def name(self): return", "= ( ('edit_own_availability', _('Can edit one\\'s own private lesson availability.')), ('edit_others_availability', _('Can edit", "models.BooleanField(_('Private lessons for couples'), default=True) smallGroups = models.BooleanField(_('Private lessons for small groups'), default=True)", "Location, verbose_name=_('Location'), null=True, blank=True, on_delete=models.SET_NULL, ) room = models.ForeignKey( Room, verbose_name=_('Room'), null=True, blank=True,", "Customer, StaffMember ) from danceschool.core.constants import getConstant from danceschool.core.mixins import EmailRecipientMixin from danceschool.core.utils.timezone", "self.instructoravailabilityslot_set.all() affectedSlots.update( status=InstructorAvailabilitySlot.SlotStatus.booked, eventRegistration=eventRegistration, ) if notifyStudent: # This is the email template", "] last_start = self.startTime last_duration = self.duration max_duration = self.duration for slot in", "comments = models.TextField( _('Comments/Notes'), null=True, blank=True, help_text=_('For internal use and recordkeeping.') ) def", "notified continue emailMixin.email_recipient( template.subject, template.content, send_html=False, from_address=template.defaultFromAddress, from_name=template.defaultFromName, cc=template.defaultCC, to=instructor.privateEmail or instructor.publicEmail, lesson=self,", "slots associated with this event (or 1). ''' return max(self.numSlots, 1) def nameAndDate(self,", "blank=True, default=1) comments = models.TextField( _('Comments/Notes'), null=True, blank=True, help_text=_('For internal use and recordkeeping.')", "instructors')), ) verbose_name = _('Private lesson') verbose_name_plural = _('Private lessons') class PrivateLessonCustomer(models.Model): '''", "== self.SlotStatus.tentative and getattr( getattr( getattr(self.eventRegistration, 'invoiceItem', None), 'invoice', None ), 'expirationDate', timezone.now()", "without payment, this just provides a record that they signed up for the", "verbose_name=_('event registration'), null=True, blank=True, on_delete=models.SET_NULL, related_name='privateLessonSlots' ) creationDate = models.DateTimeField(auto_now_add=True) modifiedDate = models.DateTimeField(auto_now=True)", "customer') verbose_name_plural = _('Private lesson customers') class InstructorAvailabilitySlot(models.Model): class SlotStatus(models.TextChoices): available = ('A',", "__str__(self): return str(self.name) class Meta: ordering = ('-startTime', 'instructor__lastName', 'instructor__firstName') verbose_name = _('Private", "if not self.status: self.status == Event.RegStatus.hidden super().save(*args, **kwargs) def __str__(self): return str(self.name) class", "specified otherwise ''' if not self.status: self.status == Event.RegStatus.hidden super().save(*args, **kwargs) def __str__(self):", "tentative = ('T', _('Tentative Booking')) unavailable = ('U', _('Unavailable')) instructor = models.ForeignKey(Instructor, verbose_name=_('Instructor'),", "Event that was created for this private lesson. lessonEvent = models.ForeignKey( PrivateLessonEvent, verbose_name=_('Scheduled", "indicates if a slot is currently available isAvailable = property(fget=checkIfAvailable) isAvailable.fget.short_description = _('Available')", "the customers are the individuals who are registered. For private lessons that are", "continue emailMixin.email_recipient( template.subject, template.content, send_html=False, from_address=template.defaultFromAddress, from_name=template.defaultFromName, cc=template.defaultCC, to=instructor.privateEmail or instructor.publicEmail, lesson=self, instructor=instructor,", "an expired (temporary) Registration is deleted, we still want to # be able", "template used to notify students that their private lesson has been # successfully", "individuals signed up via the registration and payment system, and any individuals signed", "of Participants'), null=True, blank=True, default=1) comments = models.TextField( _('Comments/Notes'), null=True, blank=True, help_text=_('For internal", "Q(privatelessoncustomer__lesson=self) | Q(registration__eventregistration__event=self) ).distinct() customers.fget.short_description = _('Customers') @property def numSlots(self): ''' Used for", "_('Private Lesson') return _('Private Lesson: %s%s%s%s' % ( teacherNames, _(' for ') if", "if teacherNames and customerNames else '', customerNames, ( (', ' if (teacherNames or", "base Event class by checking the pricingTier associated with this PrivateLessonEvent and getting", "payment. ''' return Customer.objects.filter( Q(privatelessoncustomer__lesson=self) | Q(registration__eventregistration__event=self) ).distinct() customers.fget.short_description = _('Customers') @property def", "'.join([x.staffMember.fullName for x in self.eventstaffmember_set.all()]) if self.customers: customerNames = ' ' + '", "(teacherNames or customerNames) else '') + self.startTime.strftime('%Y-%m-%d') ) if withDate else '' ))", ") verbose_name = _('Private lesson') verbose_name_plural = _('Private lessons') class PrivateLessonCustomer(models.Model): ''' For", "up for the lesson. ''' customer = models.ForeignKey( Customer, verbose_name=_('Customer'), on_delete=models.CASCADE ) lesson", "#%s' % (self.customer.fullName, self.lesson.id))) class Meta: unique_together = ('customer', 'lesson') verbose_name = _('Private", "slots are available. This method requires that slots are non-overlapping, which needs to", "for x in self.eventstaffmember_set.exclude( Q(staffMember__privateEmail__isnull=True) & Q(staffMember__publicEmail__isnull=True) ) ] for instructor in instructors:", "lessons for couples'), default=True) smallGroups = models.BooleanField(_('Private lessons for small groups'), default=True) def", "Q from django.utils.translation import gettext_lazy as _ from django.utils import timezone from django.urls", "= ' ' + names if names else '' else: customerNames = ''", "= ('A', _('Available')) booked = ('B', _('Booked')) tentative = ('T', _('Tentative Booking')) unavailable", "modifiedDate = models.DateTimeField(auto_now=True) @property def availableDurations(self): ''' A lesson can always be booked", "not withDate: return _('Private Lesson') return _('Private Lesson: %s%s%s%s' % ( teacherNames, _('", "groups'), default=True) def __str__(self): return str(_('Instructor Private lesson details for %s' % self.instructor.fullName))", "the method of the base Event class by checking the pricingTier associated with", "are registered. For private lessons that are booked without payment, this just provides", "'' )) @property def name(self): return self.nameAndDate(withDate=True) def save(self, *args, **kwargs): ''' Set", "''' If installed, the discounts app looks for this property to determine how", "instructor. ''' if not hasattr(self.instructor, 'instructorprivatelessondetails'): return [] return [ [x.id, x.name] for", "Q(registration__eventregistration__event=self) ).distinct() customers.fget.short_description = _('Customers') @property def numSlots(self): ''' Used for various pricing", "The event is created when the user books a lesson. All of the", "for instructor in instructors: if not instructor.privateEmail and not instructor.publicEmail: # Without an", "''' return Customer.objects.filter( Q(privatelessoncustomer__lesson=self) | Q(registration__eventregistration__event=self) ).distinct() customers.fget.short_description = _('Customers') @property def numSlots(self):", "private lessons for certain roles, so we should only allow booking for the", "PricingTier, EventRegistration, Customer, StaffMember ) from danceschool.core.constants import getConstant from danceschool.core.mixins import EmailRecipientMixin", "up via the registration and payment system, and any individuals signed up without", "how many points this lesson is worth toward a discount. Since private lesson", "was created for this private lesson. lessonEvent = models.ForeignKey( PrivateLessonEvent, verbose_name=_('Scheduled lesson'), null=True,", "%s' % self.instructor.fullName)) class Meta: ordering = ('instructor__lastName', 'instructor__firstName') verbose_name = _('Instructor private", "to notify students that their private lesson has been # successfully scheduled template", "class InstructorPrivateLessonDetails(models.Model): instructor = models.OneToOneField(StaffMember, on_delete=models.CASCADE) defaultPricingTier = models.ForeignKey( PricingTier, verbose_name=_('Default Pricing Tier'),", "PrivateLessonCustomer(models.Model): ''' For private lessons that go through registration and payment, the customers", "@property def availableDurations(self): ''' A lesson can always be booked for the length", "''' if not self.pricingTier: return None return self.pricingTier.getBasePrice(**kwargs) * max(self.numSlots, 1) def finalizeBooking(self,", "that an expired (temporary) Registration is deleted, we still want to # be", "emailMixin.email_recipient( template.subject, template.content, send_html=False, from_address=template.defaultFromAddress, from_name=template.defaultFromName, cc=template.defaultCC, to=instructor.privateEmail or instructor.publicEmail, lesson=self, instructor=instructor, customers=self.customers,", "customers.fget.short_description = _('Customers') @property def numSlots(self): ''' Used for various pricing discounts related", "customerNames = ' ' + names if names else '' else: customerNames =", "self.status == Event.RegStatus.hidden super().save(*args, **kwargs) def __str__(self): return str(self.name) class Meta: permissions =", "checks if multiple slots are available. This method requires that slots are non-overlapping,", "= _('Private lesson availability slot') verbose_name_plural = _('Private lesson availability slots') permissions =", "be notified continue emailMixin.email_recipient( template.subject, template.content, send_html=False, from_address=template.defaultFromAddress, from_name=template.defaultFromName, cc=template.defaultCC, to=instructor.privateEmail or instructor.publicEmail,", "blank=True) couples = models.BooleanField(_('Private lessons for couples'), default=True) smallGroups = models.BooleanField(_('Private lessons for", "= models.OneToOneField(StaffMember, on_delete=models.CASCADE) defaultPricingTier = models.ForeignKey( PricingTier, verbose_name=_('Default Pricing Tier'), null=True, blank=True, on_delete=models.SET_NULL", "slot in potential_slots: if max_duration + slot.duration > getConstant('privateLessons__maximumLessonLength'): break if ( slot.startTime", "is the email template used to notify individuals who run registration # that", "return str(self.name) class Meta: permissions = ( ('view_others_lessons', _('Can view scheduled private lessons", "created for this private lesson. lessonEvent = models.ForeignKey( PrivateLessonEvent, verbose_name=_('Scheduled lesson'), null=True, blank=True,", "= models.ForeignKey( EventRegistration, verbose_name=_('event registration'), null=True, blank=True, on_delete=models.SET_NULL, related_name='privateLessonSlots' ) creationDate = models.DateTimeField(auto_now_add=True)", "''' return ( self.startTime >= dateTime + timedelta(days=getConstant('privateLessons__closeBookingDays')) and self.startTime <= dateTime +", "_('%s: %s at %s') % ( self.instructor.fullName, ensure_localtime(self.startTime).strftime('%b %-d, %Y %-I:%M %p'), self.location", "= _('Instructors\\' private lesson details') class PrivateLessonEvent(Event): ''' This is the event object", ") room = models.ForeignKey( Room, verbose_name=_('Room'), null=True, blank=True, on_delete=models.SET_NULL, ) status = models.CharField(max_length=1,", "' + ' and '.join([x.fullName for x in self.customers]) elif self.eventregistration_set.all(): names =", "all instructors')), ) verbose_name = _('Private lesson') verbose_name_plural = _('Private lessons') class PrivateLessonCustomer(models.Model):", "blank=True, on_delete=models.SET_NULL, ) eventRegistration = models.ForeignKey( EventRegistration, verbose_name=_('event registration'), null=True, blank=True, on_delete=models.SET_NULL, related_name='privateLessonSlots'", "import ( Instructor, Location, Room, DanceRole, Event, PricingTier, EventRegistration, Customer, StaffMember ) from", ") def getBasePrice(self, **kwargs): ''' This method overrides the method of the base", "self.pricingTier.getBasePrice(**kwargs) * max(self.numSlots, 1) def finalizeBooking(self, **kwargs): notifyStudent = kwargs.get('notifyStudent', True) notifyTeachers =", "template.subject, template.content, send_html=False, from_address=template.defaultFromAddress, from_name=template.defaultFromName, cc=template.defaultCC, to=customer.email, lesson=self, ) if notifyTeachers: # This", "for lesson #%s' % (self.customer.fullName, self.lesson.id))) class Meta: unique_together = ('customer', 'lesson') verbose_name", "EmailRecipientMixin from danceschool.core.utils.timezone import ensure_localtime class InstructorPrivateLessonDetails(models.Model): instructor = models.OneToOneField(StaffMember, on_delete=models.CASCADE) defaultPricingTier =", "the number of slots associated with this event (or 1). ''' return max(self.numSlots,", "used to notify individuals who run registration # that they have been compensated", "customer = models.ForeignKey( Customer, verbose_name=_('Customer'), on_delete=models.CASCADE ) lesson = models.ForeignKey( PrivateLessonEvent, verbose_name=_('Lesson'), on_delete=models.CASCADE", "@property def availableRoles(self): ''' Some instructors only offer private lessons for certain roles,", "class InstructorAvailabilitySlot(models.Model): class SlotStatus(models.TextChoices): available = ('A', _('Available')) booked = ('B', _('Booked')) tentative", "roles that have been selected for the instructor. ''' if not hasattr(self.instructor, 'instructorprivatelessondetails'):", "self.eventRegistration and ( self.status == self.SlotStatus.available or ( self.status == self.SlotStatus.tentative and getattr(", "Q(staffMember__privateEmail__isnull=True) & Q(staffMember__publicEmail__isnull=True) ) ] for instructor in instructors: if not instructor.privateEmail and", "return None return self.pricingTier.getBasePrice(**kwargs) * max(self.numSlots, 1) def finalizeBooking(self, **kwargs): notifyStudent = kwargs.get('notifyStudent',", "available = ('A', _('Available')) booked = ('B', _('Booked')) tentative = ('T', _('Tentative Booking'))", "<= timezone.now() ) ) ) # isAvailable indicates if a slot is currently", "availability slot') verbose_name_plural = _('Private lesson availability slots') permissions = ( ('edit_own_availability', _('Can", "''' return self.instructoravailabilityslot_set.count() @property def discountPointsMultiplier(self): ''' If installed, the discounts app looks", "def __str__(self): return str(_('Private lesson customer: %s for lesson #%s' % (self.customer.fullName, self.lesson.id)))", "<= dateTime + timedelta(days=getConstant('privateLessons__openBookingDays')) and not self.eventRegistration and ( self.status == self.SlotStatus.available or", "template.content, send_html=False, from_address=template.defaultFromAddress, from_name=template.defaultFromName, cc=template.defaultCC, to=instructor.privateEmail or instructor.publicEmail, lesson=self, instructor=instructor, customers=self.customers, calendarUrl=reverse('privateCalendar'), )", "are available. This method requires that slots are non-overlapping, which needs to be", "else '') + self.startTime.strftime('%Y-%m-%d') ) if withDate else '' )) @property def name(self):", "selected for the instructor. ''' if not hasattr(self.instructor, 'instructorprivatelessondetails'): return [] return [", "link to the event because # in the event that an expired (temporary)", "= models.ForeignKey(Instructor, verbose_name=_('Instructor'), on_delete=models.CASCADE) pricingTier = models.ForeignKey( PricingTier, verbose_name=_('Pricing Tier'), null=True, blank=True, on_delete=models.SET_NULL", "method of the base Event class by checking the pricingTier associated with this", "Some instructors only offer private lessons for certain roles, so we should only", "getConstant from danceschool.core.mixins import EmailRecipientMixin from danceschool.core.utils.timezone import ensure_localtime class InstructorPrivateLessonDetails(models.Model): instructor =", "'invoiceItem', None), 'invoice', None ), 'expirationDate', timezone.now() ) <= timezone.now() ) ) )", "_('Available')) booked = ('B', _('Booked')) tentative = ('T', _('Tentative Booking')) unavailable = ('U',", "_('Instructor private lesson details') verbose_name_plural = _('Instructors\\' private lesson details') class PrivateLessonEvent(Event): '''", "tentative past their expiration date ''' return ( self.startTime >= dateTime + timedelta(days=getConstant('privateLessons__closeBookingDays'))", "( self.instructor.fullName, ensure_localtime(self.startTime).strftime('%b %-d, %Y %-I:%M %p'), self.location ) def __str__(self): return str(self.name)", "# Without an email address, instructor cannot be notified continue emailMixin.email_recipient( template.subject, template.content,", "return _('Private Lesson: %s%s%s%s' % ( teacherNames, _(' for ') if teacherNames and", "('B', _('Booked')) tentative = ('T', _('Tentative Booking')) unavailable = ('U', _('Unavailable')) instructor =", "[self.duration, ] last_start = self.startTime last_duration = self.duration max_duration = self.duration for slot", "that was created for this private lesson. lessonEvent = models.ForeignKey( PrivateLessonEvent, verbose_name=_('Scheduled lesson'),", "registration'), null=True, blank=True, on_delete=models.SET_NULL, related_name='privateLessonSlots' ) creationDate = models.DateTimeField(auto_now_add=True) modifiedDate = models.DateTimeField(auto_now=True) @property", "x in self.instructor.instructorprivatelessondetails.roles.all() ] def checkIfAvailable(self, dateTime=timezone.now()): ''' Available slots are available, but", "models.BooleanField(_('Private lessons for small groups'), default=True) def __str__(self): return str(_('Instructor Private lesson details", "= models.BooleanField(_('Private lessons for couples'), default=True) smallGroups = models.BooleanField(_('Private lessons for small groups'),", "( (', ' if (teacherNames or customerNames) else '') + self.startTime.strftime('%Y-%m-%d') ) if", "**kwargs): ''' This method overrides the method of the base Event class by", "withDate else '' )) @property def name(self): return self.nameAndDate(withDate=True) def save(self, *args, **kwargs):", "single slot, but this method checks if multiple slots are available. This method", "last_duration = self.duration max_duration = self.duration for slot in potential_slots: if max_duration +", "and this model inherits all of the fields associated with other types of", ") from danceschool.core.constants import getConstant from danceschool.core.mixins import EmailRecipientMixin from danceschool.core.utils.timezone import ensure_localtime", "private lesson details') class PrivateLessonEvent(Event): ''' This is the event object for which", "template = getConstant('privateLessons__lessonBookedEmailTemplate') if template.defaultFromAddress and template.content: for customer in self.customers: customer.email_recipient( template.subject,", "that they have been compensated template = getConstant('privateLessons__lessonBookedInstructorEmailTemplate') if template.defaultFromAddress and template.content: emailMixin", "view scheduled private lessons for all instructors')), ) verbose_name = _('Private lesson') verbose_name_plural", "just provides a record that they signed up for the lesson. ''' customer", "lesson details for %s' % self.instructor.fullName)) class Meta: ordering = ('instructor__lastName', 'instructor__firstName') verbose_name", "timezone.now() ) <= timezone.now() ) ) ) # isAvailable indicates if a slot", "notify individuals who run registration # that they have been compensated template =", "address, instructor cannot be notified continue emailMixin.email_recipient( template.subject, template.content, send_html=False, from_address=template.defaultFromAddress, from_name=template.defaultFromName, cc=template.defaultCC,", "cannot be notified continue emailMixin.email_recipient( template.subject, template.content, send_html=False, from_address=template.defaultFromAddress, from_name=template.defaultFromName, cc=template.defaultCC, to=instructor.privateEmail or", "only offer private lessons for certain roles, so we should only allow booking", "email address, instructor cannot be notified continue emailMixin.email_recipient( template.subject, template.content, send_html=False, from_address=template.defaultFromAddress, from_name=template.defaultFromName,", "Tier'), null=True, blank=True, on_delete=models.SET_NULL ) participants = models.PositiveSmallIntegerField(_('Expected # of Participants'), null=True, blank=True,", "lesson availability slots') permissions = ( ('edit_own_availability', _('Can edit one\\'s own private lesson", "datetime import timedelta from danceschool.core.models import ( Instructor, Location, Room, DanceRole, Event, PricingTier,", "for the roles that have been selected for the instructor. ''' if not", "via the registration and payment system, and any individuals signed up without payment.", "('view_others_lessons', _('Can view scheduled private lessons for all instructors')), ) verbose_name = _('Private", "self.startTime last_duration = self.duration max_duration = self.duration for slot in potential_slots: if max_duration", "slot.duration return duration_list @property def availableRoles(self): ''' Some instructors only offer private lessons", "as tentative past their expiration date ''' return ( self.startTime >= dateTime +", "the registrations and a link to the event because # in the event", "+ timedelta(days=getConstant('privateLessons__openBookingDays')) and not self.eventRegistration and ( self.status == self.SlotStatus.available or ( self.status", "their private lesson has been # successfully scheduled template = getConstant('privateLessons__lessonBookedEmailTemplate') if template.defaultFromAddress", "app looks for this property to determine how many points this lesson is", "offer private lessons for certain roles, so we should only allow booking for", "models.ForeignKey( PricingTier, verbose_name=_('Pricing Tier'), null=True, blank=True, on_delete=models.SET_NULL ) participants = models.PositiveSmallIntegerField(_('Expected # of", "= models.TextField( _('Comments/Notes'), null=True, blank=True, help_text=_('For internal use and recordkeeping.') ) def getBasePrice(self,", "template.content: emailMixin = EmailRecipientMixin() instructors = [ x.staffMember for x in self.eventstaffmember_set.exclude( Q(staffMember__privateEmail__isnull=True)", "Event class by checking the pricingTier associated with this PrivateLessonEvent and getting the", "None return self.pricingTier.getBasePrice(**kwargs) * max(self.numSlots, 1) def finalizeBooking(self, **kwargs): notifyStudent = kwargs.get('notifyStudent', True)", "on_delete=models.CASCADE) defaultPricingTier = models.ForeignKey( PricingTier, verbose_name=_('Default Pricing Tier'), null=True, blank=True, on_delete=models.SET_NULL ) roles", "' ' + names if names else '' else: customerNames = '' if", "duration (minutes)'), default=30) location = models.ForeignKey( Location, verbose_name=_('Location'), null=True, blank=True, on_delete=models.SET_NULL, ) room", "(temporary) Registration is deleted, we still want to # be able to identify", "and payment, the customers are the individuals who are registered. For private lessons", "= models.ForeignKey( PrivateLessonEvent, verbose_name=_('Scheduled lesson'), null=True, blank=True, on_delete=models.SET_NULL, ) eventRegistration = models.ForeignKey( EventRegistration,", "( self.status == self.SlotStatus.available or ( self.status == self.SlotStatus.tentative and getattr( getattr( getattr(self.eventRegistration,", "[ x.staffMember for x in self.eventstaffmember_set.exclude( Q(staffMember__privateEmail__isnull=True) & Q(staffMember__publicEmail__isnull=True) ) ] for instructor", "names = ' and '.join([x.registration.fullName for x in self.eventregistration_set.all()]) customerNames = ' '", "the registration logic is still handled by the core app, and this model", "= models.ForeignKey( PricingTier, verbose_name=_('Pricing Tier'), null=True, blank=True, on_delete=models.SET_NULL ) startTime = models.DateTimeField(_('Start time'))", "deleted, we still want to # be able to identify the Event that", "] for instructor in instructors: if not instructor.privateEmail and not instructor.publicEmail: # Without", "customer in self.customers: customer.email_recipient( template.subject, template.content, send_html=False, from_address=template.defaultFromAddress, from_name=template.defaultFromName, cc=template.defaultCC, to=customer.email, lesson=self, )", "'invoice', None ), 'expirationDate', timezone.now() ) <= timezone.now() ) ) ) # isAvailable", "= ' and '.join([x.registration.fullName for x in self.eventregistration_set.all()]) customerNames = ' ' +", "the length of a single slot, but this method checks if multiple slots", "= _('Private lesson') verbose_name_plural = _('Private lessons') class PrivateLessonCustomer(models.Model): ''' For private lessons", ")) @property def name(self): return self.nameAndDate(withDate=True) def save(self, *args, **kwargs): ''' Set registration", "Meta: unique_together = ('customer', 'lesson') verbose_name = _('Private lesson customer') verbose_name_plural = _('Private", "null=True, blank=True, default=1) comments = models.TextField( _('Comments/Notes'), null=True, blank=True, help_text=_('For internal use and", "event that an expired (temporary) Registration is deleted, we still want to #", "self.instructoravailabilityslot_set.count() @property def discountPointsMultiplier(self): ''' If installed, the discounts app looks for this", "expiration date ''' return ( self.startTime >= dateTime + timedelta(days=getConstant('privateLessons__closeBookingDays')) and self.startTime <=", "def save(self, *args, **kwargs): ''' Set registration status to hidden if it is", "from django.db import models from django.db.models import Q from django.utils.translation import gettext_lazy as", "which an individual registers. The event is created when the user books a", "method requires that slots are non-overlapping, which needs to be enforced on slot", "return self.pricingTier.getBasePrice(**kwargs) * max(self.numSlots, 1) def finalizeBooking(self, **kwargs): notifyStudent = kwargs.get('notifyStudent', True) notifyTeachers", "self.instructor.fullName, ensure_localtime(self.startTime).strftime('%b %-d, %Y %-I:%M %p'), self.location ) def __str__(self): return str(self.name) class", "the appropriate price for it. ''' if not self.pricingTier: return None return self.pricingTier.getBasePrice(**kwargs)", "dateTime + timedelta(days=getConstant('privateLessons__openBookingDays')) and not self.eventRegistration and ( self.status == self.SlotStatus.available or (", "self.status == self.SlotStatus.tentative and getattr( getattr( getattr(self.eventRegistration, 'invoiceItem', None), 'invoice', None ), 'expirationDate',", "slot.duration) last_start = slot.startTime last_duration = slot.duration max_duration += slot.duration return duration_list @property", "@property def name(self): return self.nameAndDate(withDate=True) def save(self, *args, **kwargs): ''' Set registration status", "in the event that an expired (temporary) Registration is deleted, we still want", "( self.startTime >= dateTime + timedelta(days=getConstant('privateLessons__closeBookingDays')) and self.startTime <= dateTime + timedelta(days=getConstant('privateLessons__openBookingDays')) and", "and not self.eventRegistration and ( self.status == self.SlotStatus.available or ( self.status == self.SlotStatus.tentative", "should only allow booking for the roles that have been selected for the", "StaffMember ) from danceschool.core.constants import getConstant from danceschool.core.mixins import EmailRecipientMixin from danceschool.core.utils.timezone import", "for various pricing discounts related things ''' return self.instructoravailabilityslot_set.count() @property def discountPointsMultiplier(self): '''", "on_delete=models.SET_NULL, ) room = models.ForeignKey( Room, verbose_name=_('Room'), null=True, blank=True, on_delete=models.SET_NULL, ) status =", "dateTime + timedelta(days=getConstant('privateLessons__closeBookingDays')) and self.startTime <= dateTime + timedelta(days=getConstant('privateLessons__openBookingDays')) and not self.eventRegistration and", "( ('edit_own_availability', _('Can edit one\\'s own private lesson availability.')), ('edit_others_availability', _('Can edit other", "duration = models.PositiveSmallIntegerField(_('Slot duration (minutes)'), default=30) location = models.ForeignKey( Location, verbose_name=_('Location'), null=True, blank=True,", "hasattr(self.instructor, 'instructorprivatelessondetails'): return [] return [ [x.id, x.name] for x in self.instructor.instructorprivatelessondetails.roles.all() ]", "# that they have been compensated template = getConstant('privateLessons__lessonBookedInstructorEmailTemplate') if template.defaultFromAddress and template.content:", "= models.CharField(max_length=1, choices=SlotStatus.choices, default=SlotStatus.available) # We need both a link to the registrations", "checkIfAvailable(self, dateTime=timezone.now()): ''' Available slots are available, but also tentative slots that have", "lesson availability slot') verbose_name_plural = _('Private lesson availability slots') permissions = ( ('edit_own_availability',", "and any individuals signed up without payment. ''' return Customer.objects.filter( Q(privatelessoncustomer__lesson=self) | Q(registration__eventregistration__event=self)", "so we should only allow booking for the roles that have been selected", "that are booked without payment, this just provides a record that they signed", "] def checkIfAvailable(self, dateTime=timezone.now()): ''' Available slots are available, but also tentative slots", "slot save. ''' potential_slots = InstructorAvailabilitySlot.objects.filter( instructor=self.instructor, location=self.location, room=self.room, pricingTier=self.pricingTier, startTime__gte=self.startTime, startTime__lte=self.startTime +", "potential_slots = InstructorAvailabilitySlot.objects.filter( instructor=self.instructor, location=self.location, room=self.room, pricingTier=self.pricingTier, startTime__gte=self.startTime, startTime__lte=self.startTime + timedelta(minutes=getConstant('privateLessons__maximumLessonLength')), ).exclude(id=self.id).order_by('startTime') duration_list", "edit one\\'s own private lesson availability.')), ('edit_others_availability', _('Can edit other instructors\\' private lesson", "finalizeBooking(self, **kwargs): notifyStudent = kwargs.get('notifyStudent', True) notifyTeachers = kwargs.get('notifyTeachers', getConstant('privateLessons__notifyInstructor')) eventRegistration = kwargs.get('eventRegistration',", "customerNames = ' ' + ' and '.join([x.fullName for x in self.customers]) elif" ]
[ "\".txt\") as f, open( \"subtrees-text-4096-64-comps/\" + filename + \".txt\", \"w+\") as g: for", "open( \"subtrees-text-4096-64-comps/\" + filename + \".txt\", \"w+\") as g: for line in f.readlines():", "filename + \".txt\") as f, open( \"subtrees-text-4096-64-comps/\" + filename + \".txt\", \"w+\") as", "[\"test\", \"train\", \"valid\"]: with open(\"subtrees-text-4096/\" + filename + \".txt\") as f, open( \"subtrees-text-4096-64-comps/\"", "in [\"test\", \"train\", \"valid\"]: with open(\"subtrees-text-4096/\" + filename + \".txt\") as f, open(", "\"train\", \"valid\"]: with open(\"subtrees-text-4096/\" + filename + \".txt\") as f, open( \"subtrees-text-4096-64-comps/\" +", "with open(\"subtrees-text-4096/\" + filename + \".txt\") as f, open( \"subtrees-text-4096-64-comps/\" + filename +", "filename in [\"test\", \"train\", \"valid\"]: with open(\"subtrees-text-4096/\" + filename + \".txt\") as f,", "\"subtrees-text-4096-64-comps/\" + filename + \".txt\", \"w+\") as g: for line in f.readlines(): if", "+ \".txt\", \"w+\") as g: for line in f.readlines(): if line.count(\"<post\") <= 64:", "+ filename + \".txt\", \"w+\") as g: for line in f.readlines(): if line.count(\"<post\")", "open(\"subtrees-text-4096/\" + filename + \".txt\") as f, open( \"subtrees-text-4096-64-comps/\" + filename + \".txt\",", "\".txt\", \"w+\") as g: for line in f.readlines(): if line.count(\"<post\") <= 64: g.write(line)", "\"valid\"]: with open(\"subtrees-text-4096/\" + filename + \".txt\") as f, open( \"subtrees-text-4096-64-comps/\" + filename", "+ filename + \".txt\") as f, open( \"subtrees-text-4096-64-comps/\" + filename + \".txt\", \"w+\")", "f, open( \"subtrees-text-4096-64-comps/\" + filename + \".txt\", \"w+\") as g: for line in", "filename + \".txt\", \"w+\") as g: for line in f.readlines(): if line.count(\"<post\") <=", "for filename in [\"test\", \"train\", \"valid\"]: with open(\"subtrees-text-4096/\" + filename + \".txt\") as", "as f, open( \"subtrees-text-4096-64-comps/\" + filename + \".txt\", \"w+\") as g: for line", "+ \".txt\") as f, open( \"subtrees-text-4096-64-comps/\" + filename + \".txt\", \"w+\") as g:" ]
[]
[ "points by the model. Inputs: 1) model - Trained model 2) testData -", "test input features 3) labels - True labels for the given test data", "at a time batch_size = 250 iter = int(2500/batch_size) for i in range(iter):", "= random.randint(0,1500) end_index = start_index + 2500 train_data = train_data.iloc[start_index:end_index,:] #If type is", "compute_loss(nb_model,test_features,test_labels) nb_score = 1 - nb_l nb_accuracy.append(nb_score) nb_loss.append(nb_l) x.append(batch_size) batch_size += minb losses.append(x)", "= compute_loss(nb_model,test_features,test_labels) nb_score = 1 - nb_l nb_accuracy.append(nb_score) nb_loss.append(nb_l) x.append(batch_size) batch_size += minb", "= train_data.iloc[:batch_size,-1] print(type , \" learner ----> Iteration \",i+1 ,\" out of \",", "GaussianNB() nb_model = nb.fit(train_features,train_labels) nb_l = compute_loss(nb_model,test_features,test_labels) nb_score = 1 - nb_l nb_accuracy.append(nb_score)", "on type of dataset if mode != \"DIFFICULT\": test_features = test_data.iloc[:,:26] test_labels =", "numpy as np import pandas as pd import seaborn as sns from sklearn.svm", ",\" out of \", iter ) #Train appropriate model based on \"base\" parameter", "features 3) labels - True labels for the given test data Outputs: 1)", "labels - True labels for the given test data Outputs: 1) loss -", "funtions trains a passive or random learner based on the given input parameters.", ", \" learner ----> Iteration \",i+1 ,\" out of \", iter ) #Train", "= pd.read_csv(test_file) #Extract input features and labels based on type of dataset if", "the next 2500 consecutive points if type == \"passive\": start_index = random.randint(0,1500) end_index", "+ 2500 train_data = train_data.iloc[start_index:end_index,:] #If type is random, uniformly sample 2500 points", "== \"svm\": #Using multi-class SVM svm = LinearSVC(multi_class='ovr') svm_model = svm.fit(train_features,train_labels) svm_score =", "= test_data.iloc[:,-1] print(\"-----------------\",type,\" \",base,\": \", mode,\"-----------------\") minb = 250 #batch_size defines how many", "decision trees rf = RandomForestClassifier(n_estimators=100,criterion=\"gini\") rf_model = rf.fit(train_features,train_labels) rf_l = compute_loss(rf_model,test_features,test_labels) rf_score =", "a time batch_size = 250 iter = int(2500/batch_size) for i in range(iter): if", "[] svm_loss = [] rf_loss = [] nb_loss = [] svm_accuracy = []", "predicted != true: count+=1 loss = count/len(labels) if(loss>1): loss = 1 return loss", "count/len(labels) if(loss>1): loss = 1 return loss def learner(type,mode,base=\"gaussianNB\"): ''' This funtions trains", "\" learner ----> Iteration \",i+1 ,\" out of \", iter ) #Train appropriate", "or random learner based on the given input parameters. Inputs: 1) type -", "type == \"random\": train_data = train_data.sample(frac=1).reset_index(drop=True) train_data = train_data.iloc[:2500,:] test_data = pd.read_csv(test_file) #Extract", "out of \", iter ) #Train appropriate model based on \"base\" parameter if", "#Train appropriate model based on \"base\" parameter if base == \"svm\": #Using multi-class", "the given test data Outputs: 1) loss - fraction of wrongly classified points", "input parameters. Inputs: 1) type - \"passive\" learner or \"random\" learner 2) mode", "1 - rf_l rf_accuracy.append(rf_score) rf_loss.append(rf_l) else: #Using Gaussian Naive Bayes classifier nb =", "2) mode - Type of dataset \"EASY\", \"MODERATE\" or \"DIFFICULT\" 3) base -", "250 iter = int(2500/batch_size) for i in range(iter): if mode !=\"DIFFICULT\": train_features =", "the model at a given iteration. Loss here has been defined as the", "as pd import seaborn as sns from sklearn.svm import LinearSVC from sklearn.ensemble import", "type is passive, Initialize a random starting point and choose the next 2500", "1 return loss def learner(type,mode,base=\"gaussianNB\"): ''' This funtions trains a passive or random", "''' sns.set() losses = [] accuracies = [] svm_loss = [] rf_loss =", "data Outputs: 1) loss - fraction of wrongly classified points ''' predicted_labels =", "samples we process at a time batch_size = 250 iter = int(2500/batch_size) for", "else: test_features = test_data.iloc[:,:52] test_labels = test_data.iloc[:,-1] print(\"-----------------\",type,\" \",base,\": \", mode,\"-----------------\") minb =", "model.predict(testData) count = 0 for predicted,true in zip(predicted_labels,labels): if predicted != true: count+=1", "mode - Type of dataset \"EASY\", \"MODERATE\" or \"DIFFICULT\" 3) base - Base", "+ \"_TEST.csv\" blinded_file = mode + \"_BLINDED.csv\" train_data = pd.read_csv(train_file) #If type is", "test_data.iloc[:,-1] else: test_features = test_data.iloc[:,:52] test_labels = test_data.iloc[:,-1] print(\"-----------------\",type,\" \",base,\": \", mode,\"-----------------\") minb", "2500 train_data = train_data.iloc[start_index:end_index,:] #If type is random, uniformly sample 2500 points from", "- \"passive\" learner or \"random\" learner 2) mode - Type of dataset \"EASY\",", "by the model. Inputs: 1) model - Trained model 2) testData - test", "train_features = train_data.iloc[:batch_size,:52] train_labels = train_data.iloc[:batch_size,-1] print(type , \" learner ----> Iteration \",i+1", "from sklearn.naive_bayes import GaussianNB import matplotlib.patches as mpatches import random def compute_loss(model,testData,labels): '''", "is passive, Initialize a random starting point and choose the next 2500 consecutive", "parameters. Inputs: 1) type - \"passive\" learner or \"random\" learner 2) mode -", "type == \"passive\": start_index = random.randint(0,1500) end_index = start_index + 2500 train_data =", "nb_loss = [] svm_accuracy = [] rf_accuracy = [] nb_accuracy = [] x", "accuracies = [] svm_loss = [] rf_loss = [] nb_loss = [] svm_accuracy", "= nb.fit(train_features,train_labels) nb_l = compute_loss(nb_model,test_features,test_labels) nb_score = 1 - nb_l nb_accuracy.append(nb_score) nb_loss.append(nb_l) x.append(batch_size)", "import pandas as pd import seaborn as sns from sklearn.svm import LinearSVC from", "mode + \"_BLINDED.csv\" train_data = pd.read_csv(train_file) #If type is passive, Initialize a random", "time batch_size = 250 iter = int(2500/batch_size) for i in range(iter): if mode", "seaborn as sns from sklearn.svm import LinearSVC from sklearn.ensemble import RandomForestClassifier from sklearn.naive_bayes", "0 for predicted,true in zip(predicted_labels,labels): if predicted != true: count+=1 loss = count/len(labels)", "pandas as pd import seaborn as sns from sklearn.svm import LinearSVC from sklearn.ensemble", "of dataset \"EASY\", \"MODERATE\" or \"DIFFICULT\" 3) base - Base learner to use", "= [] rf_loss = [] nb_loss = [] svm_accuracy = [] rf_accuracy =", "iteration. Loss here has been defined as the fraction of misclassified points by", "as sns from sklearn.svm import LinearSVC from sklearn.ensemble import RandomForestClassifier from sklearn.naive_bayes import", "\"_TEST.csv\" blinded_file = mode + \"_BLINDED.csv\" train_data = pd.read_csv(train_file) #If type is passive,", "import matplotlib.patches as mpatches import random def compute_loss(model,testData,labels): ''' This funtion computes the", "test_data.iloc[:,-1] print(\"-----------------\",type,\" \",base,\": \", mode,\"-----------------\") minb = 250 #batch_size defines how many input", "import random def compute_loss(model,testData,labels): ''' This funtion computes the loss of the model", "Trained model 2) testData - test input features 3) labels - True labels", "def compute_loss(model,testData,labels): ''' This funtion computes the loss of the model at a", "dataset if type == \"random\": train_data = train_data.sample(frac=1).reset_index(drop=True) train_data = train_data.iloc[:2500,:] test_data =", "= rf.fit(train_features,train_labels) rf_l = compute_loss(rf_model,test_features,test_labels) rf_score = 1 - rf_l rf_accuracy.append(rf_score) rf_loss.append(rf_l) else:", "x.append(batch_size) batch_size += minb losses.append(x) accuracies.append(x) if(base == \"svm\"): losses.append(svm_loss) accuracies.append(svm_accuracy) if base", "print(type , \" learner ----> Iteration \",i+1 ,\" out of \", iter )", "svm_score = svm_model.score(test_features,test_labels) svm_l = compute_loss(svm_model,test_features,test_labels) svm_accuracy.append(svm_score) svm_loss.append(svm_l) elif base == \"randomForest\": #Using", "nb_model = nb.fit(train_features,train_labels) nb_l = compute_loss(nb_model,test_features,test_labels) nb_score = 1 - nb_l nb_accuracy.append(nb_score) nb_loss.append(nb_l)", "as mpatches import random def compute_loss(model,testData,labels): ''' This funtion computes the loss of", "\"randomForest\" or \"svm\" Ouputs: [losses,accuracies] where, losses - holds the loss of the", "Bayes classifier nb = GaussianNB() nb_model = nb.fit(train_features,train_labels) nb_l = compute_loss(nb_model,test_features,test_labels) nb_score =", "= [] nb_loss = [] svm_accuracy = [] rf_accuracy = [] nb_accuracy =", "the accuracies of the model at each iteration ''' sns.set() losses = []", "rf.fit(train_features,train_labels) rf_l = compute_loss(rf_model,test_features,test_labels) rf_score = 1 - rf_l rf_accuracy.append(rf_score) rf_loss.append(rf_l) else: #Using", "fraction of wrongly classified points ''' predicted_labels = model.predict(testData) count = 0 for", "nb_accuracy = [] x = [] train_file = mode+ \"_TRAIN.csv\" test_file = mode", "\"svm\"): losses.append(svm_loss) accuracies.append(svm_accuracy) if base == \"randomForest\": losses.append(rf_loss) accuracies.append(rf_accuracy) else: losses.append(nb_loss) accuracies.append(nb_accuracy) return", "!= true: count+=1 loss = count/len(labels) if(loss>1): loss = 1 return loss def", "= test_data.iloc[:,-1] else: test_features = test_data.iloc[:,:52] test_labels = test_data.iloc[:,-1] print(\"-----------------\",type,\" \",base,\": \", mode,\"-----------------\")", "- True labels for the given test data Outputs: 1) loss - fraction", "of wrongly classified points ''' predicted_labels = model.predict(testData) count = 0 for predicted,true", "compute_loss(svm_model,test_features,test_labels) svm_accuracy.append(svm_score) svm_loss.append(svm_l) elif base == \"randomForest\": #Using decision trees rf = RandomForestClassifier(n_estimators=100,criterion=\"gini\")", "in zip(predicted_labels,labels): if predicted != true: count+=1 loss = count/len(labels) if(loss>1): loss =", "= model.predict(testData) count = 0 for predicted,true in zip(predicted_labels,labels): if predicted != true:", "loss = count/len(labels) if(loss>1): loss = 1 return loss def learner(type,mode,base=\"gaussianNB\"): ''' This", "sklearn.svm import LinearSVC from sklearn.ensemble import RandomForestClassifier from sklearn.naive_bayes import GaussianNB import matplotlib.patches", "train_labels = train_data.iloc[:batch_size,-1] else: train_features = train_data.iloc[:batch_size,:52] train_labels = train_data.iloc[:batch_size,-1] print(type , \"", "holds the loss of the model at each iteration accuracies - holds the", "!=\"DIFFICULT\": train_features = train_data.iloc[:batch_size,:26] train_labels = train_data.iloc[:batch_size,-1] else: train_features = train_data.iloc[:batch_size,:52] train_labels =", "zip(predicted_labels,labels): if predicted != true: count+=1 loss = count/len(labels) if(loss>1): loss = 1", "learner ----> Iteration \",i+1 ,\" out of \", iter ) #Train appropriate model", "if base == \"svm\": #Using multi-class SVM svm = LinearSVC(multi_class='ovr') svm_model = svm.fit(train_features,train_labels)", "import RandomForestClassifier from sklearn.naive_bayes import GaussianNB import matplotlib.patches as mpatches import random def", "matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn", "each iteration ''' sns.set() losses = [] accuracies = [] svm_loss = []", "test_labels = test_data.iloc[:,-1] print(\"-----------------\",type,\" \",base,\": \", mode,\"-----------------\") minb = 250 #batch_size defines how", "train_data.sample(frac=1).reset_index(drop=True) train_data = train_data.iloc[:2500,:] test_data = pd.read_csv(test_file) #Extract input features and labels based", "\"DIFFICULT\": test_features = test_data.iloc[:,:26] test_labels = test_data.iloc[:,-1] else: test_features = test_data.iloc[:,:52] test_labels =", "mode + \"_TEST.csv\" blinded_file = mode + \"_BLINDED.csv\" train_data = pd.read_csv(train_file) #If type", "= svm_model.score(test_features,test_labels) svm_l = compute_loss(svm_model,test_features,test_labels) svm_accuracy.append(svm_score) svm_loss.append(svm_l) elif base == \"randomForest\": #Using decision", "- holds the loss of the model at each iteration accuracies - holds", "== \"randomForest\": #Using decision trees rf = RandomForestClassifier(n_estimators=100,criterion=\"gini\") rf_model = rf.fit(train_features,train_labels) rf_l =", "input samples we process at a time batch_size = 250 iter = int(2500/batch_size)", "[] nb_accuracy = [] x = [] train_file = mode+ \"_TRAIN.csv\" test_file =", "= train_data.iloc[:batch_size,:26] train_labels = train_data.iloc[:batch_size,-1] else: train_features = train_data.iloc[:batch_size,:52] train_labels = train_data.iloc[:batch_size,-1] print(type", ") #Train appropriate model based on \"base\" parameter if base == \"svm\": #Using", "matplotlib.patches as mpatches import random def compute_loss(model,testData,labels): ''' This funtion computes the loss", "model - Trained model 2) testData - test input features 3) labels -", "at each iteration accuracies - holds the accuracies of the model at each", "at each iteration ''' sns.set() losses = [] accuracies = [] svm_loss =", "points ''' predicted_labels = model.predict(testData) count = 0 for predicted,true in zip(predicted_labels,labels): if", "the loss of the model at each iteration accuracies - holds the accuracies", "= 1 return loss def learner(type,mode,base=\"gaussianNB\"): ''' This funtions trains a passive or", "3) base - Base learner to use - \"gaussianNB\" or \"randomForest\" or \"svm\"", "int(2500/batch_size) for i in range(iter): if mode !=\"DIFFICULT\": train_features = train_data.iloc[:batch_size,:26] train_labels =", "Inputs: 1) model - Trained model 2) testData - test input features 3)", "model at a given iteration. Loss here has been defined as the fraction", "defined as the fraction of misclassified points by the model. Inputs: 1) model", "is random, uniformly sample 2500 points from the dataset if type == \"random\":", "a random starting point and choose the next 2500 consecutive points if type", "sns from sklearn.svm import LinearSVC from sklearn.ensemble import RandomForestClassifier from sklearn.naive_bayes import GaussianNB", "true: count+=1 loss = count/len(labels) if(loss>1): loss = 1 return loss def learner(type,mode,base=\"gaussianNB\"):", "labels based on type of dataset if mode != \"DIFFICULT\": test_features = test_data.iloc[:,:26]", "nb.fit(train_features,train_labels) nb_l = compute_loss(nb_model,test_features,test_labels) nb_score = 1 - nb_l nb_accuracy.append(nb_score) nb_loss.append(nb_l) x.append(batch_size) batch_size", "count+=1 loss = count/len(labels) if(loss>1): loss = 1 return loss def learner(type,mode,base=\"gaussianNB\"): '''", "test_labels = test_data.iloc[:,-1] else: test_features = test_data.iloc[:,:52] test_labels = test_data.iloc[:,-1] print(\"-----------------\",type,\" \",base,\": \",", "point and choose the next 2500 consecutive points if type == \"passive\": start_index", "rf = RandomForestClassifier(n_estimators=100,criterion=\"gini\") rf_model = rf.fit(train_features,train_labels) rf_l = compute_loss(rf_model,test_features,test_labels) rf_score = 1 -", "if predicted != true: count+=1 loss = count/len(labels) if(loss>1): loss = 1 return", "sklearn.naive_bayes import GaussianNB import matplotlib.patches as mpatches import random def compute_loss(model,testData,labels): ''' This", "random def compute_loss(model,testData,labels): ''' This funtion computes the loss of the model at", "svm = LinearSVC(multi_class='ovr') svm_model = svm.fit(train_features,train_labels) svm_score = svm_model.score(test_features,test_labels) svm_l = compute_loss(svm_model,test_features,test_labels) svm_accuracy.append(svm_score)", "\"svm\": #Using multi-class SVM svm = LinearSVC(multi_class='ovr') svm_model = svm.fit(train_features,train_labels) svm_score = svm_model.score(test_features,test_labels)", "[] rf_accuracy = [] nb_accuracy = [] x = [] train_file = mode+", "funtion computes the loss of the model at a given iteration. Loss here", "1) model - Trained model 2) testData - test input features 3) labels", "losses - holds the loss of the model at each iteration accuracies -", "if type == \"passive\": start_index = random.randint(0,1500) end_index = start_index + 2500 train_data", "type is random, uniformly sample 2500 points from the dataset if type ==", "= GaussianNB() nb_model = nb.fit(train_features,train_labels) nb_l = compute_loss(nb_model,test_features,test_labels) nb_score = 1 - nb_l", "\"gaussianNB\" or \"randomForest\" or \"svm\" Ouputs: [losses,accuracies] where, losses - holds the loss", "This funtion computes the loss of the model at a given iteration. Loss", "the dataset if type == \"random\": train_data = train_data.sample(frac=1).reset_index(drop=True) train_data = train_data.iloc[:2500,:] test_data", "in range(iter): if mode !=\"DIFFICULT\": train_features = train_data.iloc[:batch_size,:26] train_labels = train_data.iloc[:batch_size,-1] else: train_features", "if(loss>1): loss = 1 return loss def learner(type,mode,base=\"gaussianNB\"): ''' This funtions trains a", "been defined as the fraction of misclassified points by the model. Inputs: 1)", "test data Outputs: 1) loss - fraction of wrongly classified points ''' predicted_labels", "def learner(type,mode,base=\"gaussianNB\"): ''' This funtions trains a passive or random learner based on", "\"svm\" Ouputs: [losses,accuracies] where, losses - holds the loss of the model at", "plt import numpy as np import pandas as pd import seaborn as sns", "import GaussianNB import matplotlib.patches as mpatches import random def compute_loss(model,testData,labels): ''' This funtion", "2500 consecutive points if type == \"passive\": start_index = random.randint(0,1500) end_index = start_index", "given test data Outputs: 1) loss - fraction of wrongly classified points '''", "how many input samples we process at a time batch_size = 250 iter", "the loss of the model at a given iteration. Loss here has been", "\"EASY\", \"MODERATE\" or \"DIFFICULT\" 3) base - Base learner to use - \"gaussianNB\"", "print(\"-----------------\",type,\" \",base,\": \", mode,\"-----------------\") minb = 250 #batch_size defines how many input samples", "features and labels based on type of dataset if mode != \"DIFFICULT\": test_features", "= train_data.iloc[:2500,:] test_data = pd.read_csv(test_file) #Extract input features and labels based on type", "accuracies of the model at each iteration ''' sns.set() losses = [] accuracies", "\"MODERATE\" or \"DIFFICULT\" 3) base - Base learner to use - \"gaussianNB\" or", "where, losses - holds the loss of the model at each iteration accuracies", "= compute_loss(rf_model,test_features,test_labels) rf_score = 1 - rf_l rf_accuracy.append(rf_score) rf_loss.append(rf_l) else: #Using Gaussian Naive", "classified points ''' predicted_labels = model.predict(testData) count = 0 for predicted,true in zip(predicted_labels,labels):", "#Using multi-class SVM svm = LinearSVC(multi_class='ovr') svm_model = svm.fit(train_features,train_labels) svm_score = svm_model.score(test_features,test_labels) svm_l", "here has been defined as the fraction of misclassified points by the model.", "sklearn.ensemble import RandomForestClassifier from sklearn.naive_bayes import GaussianNB import matplotlib.patches as mpatches import random", "losses = [] accuracies = [] svm_loss = [] rf_loss = [] nb_loss", "import seaborn as sns from sklearn.svm import LinearSVC from sklearn.ensemble import RandomForestClassifier from", "SVM svm = LinearSVC(multi_class='ovr') svm_model = svm.fit(train_features,train_labels) svm_score = svm_model.score(test_features,test_labels) svm_l = compute_loss(svm_model,test_features,test_labels)", "+= minb losses.append(x) accuracies.append(x) if(base == \"svm\"): losses.append(svm_loss) accuracies.append(svm_accuracy) if base == \"randomForest\":", "loss of the model at each iteration accuracies - holds the accuracies of", "misclassified points by the model. Inputs: 1) model - Trained model 2) testData", "fraction of misclassified points by the model. Inputs: 1) model - Trained model", "== \"svm\"): losses.append(svm_loss) accuracies.append(svm_accuracy) if base == \"randomForest\": losses.append(rf_loss) accuracies.append(rf_accuracy) else: losses.append(nb_loss) accuracies.append(nb_accuracy)", "type - \"passive\" learner or \"random\" learner 2) mode - Type of dataset", "train_file = mode+ \"_TRAIN.csv\" test_file = mode + \"_TEST.csv\" blinded_file = mode +", "multi-class SVM svm = LinearSVC(multi_class='ovr') svm_model = svm.fit(train_features,train_labels) svm_score = svm_model.score(test_features,test_labels) svm_l =", "[] svm_accuracy = [] rf_accuracy = [] nb_accuracy = [] x = []", "import matplotlib.pyplot as plt import numpy as np import pandas as pd import", "of the model at each iteration ''' sns.set() losses = [] accuracies =", "process at a time batch_size = 250 iter = int(2500/batch_size) for i in", "[] x = [] train_file = mode+ \"_TRAIN.csv\" test_file = mode + \"_TEST.csv\"", "and labels based on type of dataset if mode != \"DIFFICULT\": test_features =", "train_data.iloc[:2500,:] test_data = pd.read_csv(test_file) #Extract input features and labels based on type of", "labels for the given test data Outputs: 1) loss - fraction of wrongly", "= LinearSVC(multi_class='ovr') svm_model = svm.fit(train_features,train_labels) svm_score = svm_model.score(test_features,test_labels) svm_l = compute_loss(svm_model,test_features,test_labels) svm_accuracy.append(svm_score) svm_loss.append(svm_l)", "== \"passive\": start_index = random.randint(0,1500) end_index = start_index + 2500 train_data = train_data.iloc[start_index:end_index,:]", "mode != \"DIFFICULT\": test_features = test_data.iloc[:,:26] test_labels = test_data.iloc[:,-1] else: test_features = test_data.iloc[:,:52]", "model 2) testData - test input features 3) labels - True labels for", "and choose the next 2500 consecutive points if type == \"passive\": start_index =", "= [] train_file = mode+ \"_TRAIN.csv\" test_file = mode + \"_TEST.csv\" blinded_file =", "= train_data.iloc[:batch_size,-1] else: train_features = train_data.iloc[:batch_size,:52] train_labels = train_data.iloc[:batch_size,-1] print(type , \" learner", "nb_loss.append(nb_l) x.append(batch_size) batch_size += minb losses.append(x) accuracies.append(x) if(base == \"svm\"): losses.append(svm_loss) accuracies.append(svm_accuracy) if", "= [] x = [] train_file = mode+ \"_TRAIN.csv\" test_file = mode +", "count = 0 for predicted,true in zip(predicted_labels,labels): if predicted != true: count+=1 loss", "- \"gaussianNB\" or \"randomForest\" or \"svm\" Ouputs: [losses,accuracies] where, losses - holds the", "= mode+ \"_TRAIN.csv\" test_file = mode + \"_TEST.csv\" blinded_file = mode + \"_BLINDED.csv\"", "np import pandas as pd import seaborn as sns from sklearn.svm import LinearSVC", "#Extract input features and labels based on type of dataset if mode !=", "type of dataset if mode != \"DIFFICULT\": test_features = test_data.iloc[:,:26] test_labels = test_data.iloc[:,-1]", "1 - nb_l nb_accuracy.append(nb_score) nb_loss.append(nb_l) x.append(batch_size) batch_size += minb losses.append(x) accuracies.append(x) if(base ==", "2) testData - test input features 3) labels - True labels for the", "\", iter ) #Train appropriate model based on \"base\" parameter if base ==", "base == \"randomForest\": #Using decision trees rf = RandomForestClassifier(n_estimators=100,criterion=\"gini\") rf_model = rf.fit(train_features,train_labels) rf_l", "from sklearn.ensemble import RandomForestClassifier from sklearn.naive_bayes import GaussianNB import matplotlib.patches as mpatches import", "loss - fraction of wrongly classified points ''' predicted_labels = model.predict(testData) count =", "\", mode,\"-----------------\") minb = 250 #batch_size defines how many input samples we process", "test_features = test_data.iloc[:,:52] test_labels = test_data.iloc[:,-1] print(\"-----------------\",type,\" \",base,\": \", mode,\"-----------------\") minb = 250", "input features and labels based on type of dataset if mode != \"DIFFICULT\":", "This funtions trains a passive or random learner based on the given input", "Inputs: 1) type - \"passive\" learner or \"random\" learner 2) mode - Type", "loss of the model at a given iteration. Loss here has been defined", "else: train_features = train_data.iloc[:batch_size,:52] train_labels = train_data.iloc[:batch_size,-1] print(type , \" learner ----> Iteration", "nb_l = compute_loss(nb_model,test_features,test_labels) nb_score = 1 - nb_l nb_accuracy.append(nb_score) nb_loss.append(nb_l) x.append(batch_size) batch_size +=", "model. Inputs: 1) model - Trained model 2) testData - test input features", "to use - \"gaussianNB\" or \"randomForest\" or \"svm\" Ouputs: [losses,accuracies] where, losses -", "svm.fit(train_features,train_labels) svm_score = svm_model.score(test_features,test_labels) svm_l = compute_loss(svm_model,test_features,test_labels) svm_accuracy.append(svm_score) svm_loss.append(svm_l) elif base == \"randomForest\":", "- holds the accuracies of the model at each iteration ''' sns.set() losses", "as the fraction of misclassified points by the model. Inputs: 1) model -", "\"passive\" learner or \"random\" learner 2) mode - Type of dataset \"EASY\", \"MODERATE\"", "from the dataset if type == \"random\": train_data = train_data.sample(frac=1).reset_index(drop=True) train_data = train_data.iloc[:2500,:]", "Iteration \",i+1 ,\" out of \", iter ) #Train appropriate model based on", "as plt import numpy as np import pandas as pd import seaborn as", "train_data = train_data.iloc[:2500,:] test_data = pd.read_csv(test_file) #Extract input features and labels based on", "= [] nb_accuracy = [] x = [] train_file = mode+ \"_TRAIN.csv\" test_file", "= test_data.iloc[:,:52] test_labels = test_data.iloc[:,-1] print(\"-----------------\",type,\" \",base,\": \", mode,\"-----------------\") minb = 250 #batch_size", "Loss here has been defined as the fraction of misclassified points by the", "\",i+1 ,\" out of \", iter ) #Train appropriate model based on \"base\"", "= 1 - rf_l rf_accuracy.append(rf_score) rf_loss.append(rf_l) else: #Using Gaussian Naive Bayes classifier nb", "has been defined as the fraction of misclassified points by the model. Inputs:", "loss def learner(type,mode,base=\"gaussianNB\"): ''' This funtions trains a passive or random learner based", "return loss def learner(type,mode,base=\"gaussianNB\"): ''' This funtions trains a passive or random learner", "rf_loss.append(rf_l) else: #Using Gaussian Naive Bayes classifier nb = GaussianNB() nb_model = nb.fit(train_features,train_labels)", "learner to use - \"gaussianNB\" or \"randomForest\" or \"svm\" Ouputs: [losses,accuracies] where, losses", "of dataset if mode != \"DIFFICULT\": test_features = test_data.iloc[:,:26] test_labels = test_data.iloc[:,-1] else:", "= 0 for predicted,true in zip(predicted_labels,labels): if predicted != true: count+=1 loss =", "= 250 iter = int(2500/batch_size) for i in range(iter): if mode !=\"DIFFICULT\": train_features", "Ouputs: [losses,accuracies] where, losses - holds the loss of the model at each", "\"passive\": start_index = random.randint(0,1500) end_index = start_index + 2500 train_data = train_data.iloc[start_index:end_index,:] #If", "#Using decision trees rf = RandomForestClassifier(n_estimators=100,criterion=\"gini\") rf_model = rf.fit(train_features,train_labels) rf_l = compute_loss(rf_model,test_features,test_labels) rf_score", "or \"svm\" Ouputs: [losses,accuracies] where, losses - holds the loss of the model", "== \"random\": train_data = train_data.sample(frac=1).reset_index(drop=True) train_data = train_data.iloc[:2500,:] test_data = pd.read_csv(test_file) #Extract input", "train_data.iloc[:batch_size,-1] print(type , \" learner ----> Iteration \",i+1 ,\" out of \", iter", "model at each iteration accuracies - holds the accuracies of the model at", "rf_score = 1 - rf_l rf_accuracy.append(rf_score) rf_loss.append(rf_l) else: #Using Gaussian Naive Bayes classifier", "import LinearSVC from sklearn.ensemble import RandomForestClassifier from sklearn.naive_bayes import GaussianNB import matplotlib.patches as", "iteration ''' sns.set() losses = [] accuracies = [] svm_loss = [] rf_loss", "mpatches import random def compute_loss(model,testData,labels): ''' This funtion computes the loss of the", "computes the loss of the model at a given iteration. Loss here has", "\"DIFFICULT\" 3) base - Base learner to use - \"gaussianNB\" or \"randomForest\" or", "svm_accuracy = [] rf_accuracy = [] nb_accuracy = [] x = [] train_file", "import numpy as np import pandas as pd import seaborn as sns from", "of the model at a given iteration. Loss here has been defined as", "points if type == \"passive\": start_index = random.randint(0,1500) end_index = start_index + 2500", "nb_score = 1 - nb_l nb_accuracy.append(nb_score) nb_loss.append(nb_l) x.append(batch_size) batch_size += minb losses.append(x) accuracies.append(x)", "if type == \"random\": train_data = train_data.sample(frac=1).reset_index(drop=True) train_data = train_data.iloc[:2500,:] test_data = pd.read_csv(test_file)", "#batch_size defines how many input samples we process at a time batch_size =", "- test input features 3) labels - True labels for the given test", "predicted_labels = model.predict(testData) count = 0 for predicted,true in zip(predicted_labels,labels): if predicted !=", "rf_accuracy = [] nb_accuracy = [] x = [] train_file = mode+ \"_TRAIN.csv\"", "if mode !=\"DIFFICULT\": train_features = train_data.iloc[:batch_size,:26] train_labels = train_data.iloc[:batch_size,-1] else: train_features = train_data.iloc[:batch_size,:52]", "parameter if base == \"svm\": #Using multi-class SVM svm = LinearSVC(multi_class='ovr') svm_model =", "- fraction of wrongly classified points ''' predicted_labels = model.predict(testData) count = 0", "i in range(iter): if mode !=\"DIFFICULT\": train_features = train_data.iloc[:batch_size,:26] train_labels = train_data.iloc[:batch_size,-1] else:", "= 1 - nb_l nb_accuracy.append(nb_score) nb_loss.append(nb_l) x.append(batch_size) batch_size += minb losses.append(x) accuracies.append(x) if(base", "test_features = test_data.iloc[:,:26] test_labels = test_data.iloc[:,-1] else: test_features = test_data.iloc[:,:52] test_labels = test_data.iloc[:,-1]", "model at each iteration ''' sns.set() losses = [] accuracies = [] svm_loss", "test_file = mode + \"_TEST.csv\" blinded_file = mode + \"_BLINDED.csv\" train_data = pd.read_csv(train_file)", "passive or random learner based on the given input parameters. Inputs: 1) type", "defines how many input samples we process at a time batch_size = 250", "for i in range(iter): if mode !=\"DIFFICULT\": train_features = train_data.iloc[:batch_size,:26] train_labels = train_data.iloc[:batch_size,-1]", "Type of dataset \"EASY\", \"MODERATE\" or \"DIFFICULT\" 3) base - Base learner to", "LinearSVC from sklearn.ensemble import RandomForestClassifier from sklearn.naive_bayes import GaussianNB import matplotlib.patches as mpatches", "the model at each iteration accuracies - holds the accuracies of the model", "classifier nb = GaussianNB() nb_model = nb.fit(train_features,train_labels) nb_l = compute_loss(nb_model,test_features,test_labels) nb_score = 1", "learner 2) mode - Type of dataset \"EASY\", \"MODERATE\" or \"DIFFICULT\" 3) base", "else: #Using Gaussian Naive Bayes classifier nb = GaussianNB() nb_model = nb.fit(train_features,train_labels) nb_l", "\"random\" learner 2) mode - Type of dataset \"EASY\", \"MODERATE\" or \"DIFFICULT\" 3)", "losses.append(x) accuracies.append(x) if(base == \"svm\"): losses.append(svm_loss) accuracies.append(svm_accuracy) if base == \"randomForest\": losses.append(rf_loss) accuracies.append(rf_accuracy)", "+ \"_BLINDED.csv\" train_data = pd.read_csv(train_file) #If type is passive, Initialize a random starting", "holds the accuracies of the model at each iteration ''' sns.set() losses =", "given input parameters. Inputs: 1) type - \"passive\" learner or \"random\" learner 2)", "mode !=\"DIFFICULT\": train_features = train_data.iloc[:batch_size,:26] train_labels = train_data.iloc[:batch_size,-1] else: train_features = train_data.iloc[:batch_size,:52] train_labels", "we process at a time batch_size = 250 iter = int(2500/batch_size) for i", "each iteration accuracies - holds the accuracies of the model at each iteration", "learner based on the given input parameters. Inputs: 1) type - \"passive\" learner", "nb_l nb_accuracy.append(nb_score) nb_loss.append(nb_l) x.append(batch_size) batch_size += minb losses.append(x) accuracies.append(x) if(base == \"svm\"): losses.append(svm_loss)", "based on \"base\" parameter if base == \"svm\": #Using multi-class SVM svm =", "blinded_file = mode + \"_BLINDED.csv\" train_data = pd.read_csv(train_file) #If type is passive, Initialize", "x = [] train_file = mode+ \"_TRAIN.csv\" test_file = mode + \"_TEST.csv\" blinded_file", "\"randomForest\": #Using decision trees rf = RandomForestClassifier(n_estimators=100,criterion=\"gini\") rf_model = rf.fit(train_features,train_labels) rf_l = compute_loss(rf_model,test_features,test_labels)", "a passive or random learner based on the given input parameters. Inputs: 1)", "True labels for the given test data Outputs: 1) loss - fraction of", "dataset \"EASY\", \"MODERATE\" or \"DIFFICULT\" 3) base - Base learner to use -", "start_index = random.randint(0,1500) end_index = start_index + 2500 train_data = train_data.iloc[start_index:end_index,:] #If type", "''' predicted_labels = model.predict(testData) count = 0 for predicted,true in zip(predicted_labels,labels): if predicted", "end_index = start_index + 2500 train_data = train_data.iloc[start_index:end_index,:] #If type is random, uniformly", "\"random\": train_data = train_data.sample(frac=1).reset_index(drop=True) train_data = train_data.iloc[:2500,:] test_data = pd.read_csv(test_file) #Extract input features", "= train_data.sample(frac=1).reset_index(drop=True) train_data = train_data.iloc[:2500,:] test_data = pd.read_csv(test_file) #Extract input features and labels", "train_data = train_data.iloc[start_index:end_index,:] #If type is random, uniformly sample 2500 points from the", "#Using Gaussian Naive Bayes classifier nb = GaussianNB() nb_model = nb.fit(train_features,train_labels) nb_l =", "svm_model = svm.fit(train_features,train_labels) svm_score = svm_model.score(test_features,test_labels) svm_l = compute_loss(svm_model,test_features,test_labels) svm_accuracy.append(svm_score) svm_loss.append(svm_l) elif base", "elif base == \"randomForest\": #Using decision trees rf = RandomForestClassifier(n_estimators=100,criterion=\"gini\") rf_model = rf.fit(train_features,train_labels)", "random learner based on the given input parameters. Inputs: 1) type - \"passive\"", "- Type of dataset \"EASY\", \"MODERATE\" or \"DIFFICULT\" 3) base - Base learner", "compute_loss(rf_model,test_features,test_labels) rf_score = 1 - rf_l rf_accuracy.append(rf_score) rf_loss.append(rf_l) else: #Using Gaussian Naive Bayes", "pd.read_csv(train_file) #If type is passive, Initialize a random starting point and choose the", "minb losses.append(x) accuracies.append(x) if(base == \"svm\"): losses.append(svm_loss) accuracies.append(svm_accuracy) if base == \"randomForest\": losses.append(rf_loss)", "trees rf = RandomForestClassifier(n_estimators=100,criterion=\"gini\") rf_model = rf.fit(train_features,train_labels) rf_l = compute_loss(rf_model,test_features,test_labels) rf_score = 1", "#If type is passive, Initialize a random starting point and choose the next", "Outputs: 1) loss - fraction of wrongly classified points ''' predicted_labels = model.predict(testData)", "the model at each iteration ''' sns.set() losses = [] accuracies = []", "batch_size += minb losses.append(x) accuracies.append(x) if(base == \"svm\"): losses.append(svm_loss) accuracies.append(svm_accuracy) if base ==", "= mode + \"_TEST.csv\" blinded_file = mode + \"_BLINDED.csv\" train_data = pd.read_csv(train_file) #If", "accuracies.append(x) if(base == \"svm\"): losses.append(svm_loss) accuracies.append(svm_accuracy) if base == \"randomForest\": losses.append(rf_loss) accuracies.append(rf_accuracy) else:", "\",base,\": \", mode,\"-----------------\") minb = 250 #batch_size defines how many input samples we", "Gaussian Naive Bayes classifier nb = GaussianNB() nb_model = nb.fit(train_features,train_labels) nb_l = compute_loss(nb_model,test_features,test_labels)", "\"_TRAIN.csv\" test_file = mode + \"_TEST.csv\" blinded_file = mode + \"_BLINDED.csv\" train_data =", "starting point and choose the next 2500 consecutive points if type == \"passive\":", "Base learner to use - \"gaussianNB\" or \"randomForest\" or \"svm\" Ouputs: [losses,accuracies] where,", "[] train_file = mode+ \"_TRAIN.csv\" test_file = mode + \"_TEST.csv\" blinded_file = mode", "given iteration. Loss here has been defined as the fraction of misclassified points", "iter = int(2500/batch_size) for i in range(iter): if mode !=\"DIFFICULT\": train_features = train_data.iloc[:batch_size,:26]", "for the given test data Outputs: 1) loss - fraction of wrongly classified", "[] accuracies = [] svm_loss = [] rf_loss = [] nb_loss = []", "a given iteration. Loss here has been defined as the fraction of misclassified", "of \", iter ) #Train appropriate model based on \"base\" parameter if base", "GaussianNB import matplotlib.patches as mpatches import random def compute_loss(model,testData,labels): ''' This funtion computes", "train_data.iloc[:batch_size,-1] else: train_features = train_data.iloc[:batch_size,:52] train_labels = train_data.iloc[:batch_size,-1] print(type , \" learner ---->", "if mode != \"DIFFICULT\": test_features = test_data.iloc[:,:26] test_labels = test_data.iloc[:,-1] else: test_features =", "= [] svm_loss = [] rf_loss = [] nb_loss = [] svm_accuracy =", "test_data = pd.read_csv(test_file) #Extract input features and labels based on type of dataset", "pd import seaborn as sns from sklearn.svm import LinearSVC from sklearn.ensemble import RandomForestClassifier", "dataset if mode != \"DIFFICULT\": test_features = test_data.iloc[:,:26] test_labels = test_data.iloc[:,-1] else: test_features", "= svm.fit(train_features,train_labels) svm_score = svm_model.score(test_features,test_labels) svm_l = compute_loss(svm_model,test_features,test_labels) svm_accuracy.append(svm_score) svm_loss.append(svm_l) elif base ==", "3) labels - True labels for the given test data Outputs: 1) loss", "appropriate model based on \"base\" parameter if base == \"svm\": #Using multi-class SVM", "rf_loss = [] nb_loss = [] svm_accuracy = [] rf_accuracy = [] nb_accuracy", "Initialize a random starting point and choose the next 2500 consecutive points if", "= train_data.iloc[start_index:end_index,:] #If type is random, uniformly sample 2500 points from the dataset", "based on the given input parameters. Inputs: 1) type - \"passive\" learner or", "1) type - \"passive\" learner or \"random\" learner 2) mode - Type of", "rf_l rf_accuracy.append(rf_score) rf_loss.append(rf_l) else: #Using Gaussian Naive Bayes classifier nb = GaussianNB() nb_model", "----> Iteration \",i+1 ,\" out of \", iter ) #Train appropriate model based", "train_features = train_data.iloc[:batch_size,:26] train_labels = train_data.iloc[:batch_size,-1] else: train_features = train_data.iloc[:batch_size,:52] train_labels = train_data.iloc[:batch_size,-1]", "= [] svm_accuracy = [] rf_accuracy = [] nb_accuracy = [] x =", "predicted,true in zip(predicted_labels,labels): if predicted != true: count+=1 loss = count/len(labels) if(loss>1): loss", "= train_data.iloc[:batch_size,:52] train_labels = train_data.iloc[:batch_size,-1] print(type , \" learner ----> Iteration \",i+1 ,\"", "svm_model.score(test_features,test_labels) svm_l = compute_loss(svm_model,test_features,test_labels) svm_accuracy.append(svm_score) svm_loss.append(svm_l) elif base == \"randomForest\": #Using decision trees", "test_data.iloc[:,:52] test_labels = test_data.iloc[:,-1] print(\"-----------------\",type,\" \",base,\": \", mode,\"-----------------\") minb = 250 #batch_size defines", "base == \"svm\": #Using multi-class SVM svm = LinearSVC(multi_class='ovr') svm_model = svm.fit(train_features,train_labels) svm_score", "train_data.iloc[start_index:end_index,:] #If type is random, uniformly sample 2500 points from the dataset if", "on \"base\" parameter if base == \"svm\": #Using multi-class SVM svm = LinearSVC(multi_class='ovr')", "rf_accuracy.append(rf_score) rf_loss.append(rf_l) else: #Using Gaussian Naive Bayes classifier nb = GaussianNB() nb_model =", "random.randint(0,1500) end_index = start_index + 2500 train_data = train_data.iloc[start_index:end_index,:] #If type is random,", "''' This funtions trains a passive or random learner based on the given", "for predicted,true in zip(predicted_labels,labels): if predicted != true: count+=1 loss = count/len(labels) if(loss>1):", "or \"random\" learner 2) mode - Type of dataset \"EASY\", \"MODERATE\" or \"DIFFICULT\"", "losses.append(svm_loss) accuracies.append(svm_accuracy) if base == \"randomForest\": losses.append(rf_loss) accuracies.append(rf_accuracy) else: losses.append(nb_loss) accuracies.append(nb_accuracy) return ([losses,accuracies])", "loss = 1 return loss def learner(type,mode,base=\"gaussianNB\"): ''' This funtions trains a passive", "mode,\"-----------------\") minb = 250 #batch_size defines how many input samples we process at", "accuracies - holds the accuracies of the model at each iteration ''' sns.set()", "\"_BLINDED.csv\" train_data = pd.read_csv(train_file) #If type is passive, Initialize a random starting point", "train_data = pd.read_csv(train_file) #If type is passive, Initialize a random starting point and", "2500 points from the dataset if type == \"random\": train_data = train_data.sample(frac=1).reset_index(drop=True) train_data", "the model. Inputs: 1) model - Trained model 2) testData - test input", "of the model at each iteration accuracies - holds the accuracies of the", "svm_loss = [] rf_loss = [] nb_loss = [] svm_accuracy = [] rf_accuracy", "the fraction of misclassified points by the model. Inputs: 1) model - Trained", "the given input parameters. Inputs: 1) type - \"passive\" learner or \"random\" learner", "- Trained model 2) testData - test input features 3) labels - True", "or \"DIFFICULT\" 3) base - Base learner to use - \"gaussianNB\" or \"randomForest\"", "wrongly classified points ''' predicted_labels = model.predict(testData) count = 0 for predicted,true in", "mode+ \"_TRAIN.csv\" test_file = mode + \"_TEST.csv\" blinded_file = mode + \"_BLINDED.csv\" train_data", "points from the dataset if type == \"random\": train_data = train_data.sample(frac=1).reset_index(drop=True) train_data =", "!= \"DIFFICULT\": test_features = test_data.iloc[:,:26] test_labels = test_data.iloc[:,-1] else: test_features = test_data.iloc[:,:52] test_labels", "rf_l = compute_loss(rf_model,test_features,test_labels) rf_score = 1 - rf_l rf_accuracy.append(rf_score) rf_loss.append(rf_l) else: #Using Gaussian", "as np import pandas as pd import seaborn as sns from sklearn.svm import", "train_data = train_data.sample(frac=1).reset_index(drop=True) train_data = train_data.iloc[:2500,:] test_data = pd.read_csv(test_file) #Extract input features and", "choose the next 2500 consecutive points if type == \"passive\": start_index = random.randint(0,1500)", "train_labels = train_data.iloc[:batch_size,-1] print(type , \" learner ----> Iteration \",i+1 ,\" out of", "[] rf_loss = [] nb_loss = [] svm_accuracy = [] rf_accuracy = []", "consecutive points if type == \"passive\": start_index = random.randint(0,1500) end_index = start_index +", "sample 2500 points from the dataset if type == \"random\": train_data = train_data.sample(frac=1).reset_index(drop=True)", "- nb_l nb_accuracy.append(nb_score) nb_loss.append(nb_l) x.append(batch_size) batch_size += minb losses.append(x) accuracies.append(x) if(base == \"svm\"):", "compute_loss(model,testData,labels): ''' This funtion computes the loss of the model at a given", "testData - test input features 3) labels - True labels for the given", "or \"randomForest\" or \"svm\" Ouputs: [losses,accuracies] where, losses - holds the loss of", "passive, Initialize a random starting point and choose the next 2500 consecutive points", "minb = 250 #batch_size defines how many input samples we process at a", "rf_model = rf.fit(train_features,train_labels) rf_l = compute_loss(rf_model,test_features,test_labels) rf_score = 1 - rf_l rf_accuracy.append(rf_score) rf_loss.append(rf_l)", "= RandomForestClassifier(n_estimators=100,criterion=\"gini\") rf_model = rf.fit(train_features,train_labels) rf_l = compute_loss(rf_model,test_features,test_labels) rf_score = 1 - rf_l", "based on type of dataset if mode != \"DIFFICULT\": test_features = test_data.iloc[:,:26] test_labels", "= test_data.iloc[:,:26] test_labels = test_data.iloc[:,-1] else: test_features = test_data.iloc[:,:52] test_labels = test_data.iloc[:,-1] print(\"-----------------\",type,\"", "nb = GaussianNB() nb_model = nb.fit(train_features,train_labels) nb_l = compute_loss(nb_model,test_features,test_labels) nb_score = 1 -", "uniformly sample 2500 points from the dataset if type == \"random\": train_data =", "pd.read_csv(test_file) #Extract input features and labels based on type of dataset if mode", "= pd.read_csv(train_file) #If type is passive, Initialize a random starting point and choose", "range(iter): if mode !=\"DIFFICULT\": train_features = train_data.iloc[:batch_size,:26] train_labels = train_data.iloc[:batch_size,-1] else: train_features =", "svm_l = compute_loss(svm_model,test_features,test_labels) svm_accuracy.append(svm_score) svm_loss.append(svm_l) elif base == \"randomForest\": #Using decision trees rf", "learner(type,mode,base=\"gaussianNB\"): ''' This funtions trains a passive or random learner based on the", "base - Base learner to use - \"gaussianNB\" or \"randomForest\" or \"svm\" Ouputs:", "iter ) #Train appropriate model based on \"base\" parameter if base == \"svm\":", "sns.set() losses = [] accuracies = [] svm_loss = [] rf_loss = []", "= [] accuracies = [] svm_loss = [] rf_loss = [] nb_loss =", "trains a passive or random learner based on the given input parameters. Inputs:", "[] nb_loss = [] svm_accuracy = [] rf_accuracy = [] nb_accuracy = []", "of misclassified points by the model. Inputs: 1) model - Trained model 2)", "test_data.iloc[:,:26] test_labels = test_data.iloc[:,-1] else: test_features = test_data.iloc[:,:52] test_labels = test_data.iloc[:,-1] print(\"-----------------\",type,\" \",base,\":", "batch_size = 250 iter = int(2500/batch_size) for i in range(iter): if mode !=\"DIFFICULT\":", "model based on \"base\" parameter if base == \"svm\": #Using multi-class SVM svm", "- Base learner to use - \"gaussianNB\" or \"randomForest\" or \"svm\" Ouputs: [losses,accuracies]", "\"base\" parameter if base == \"svm\": #Using multi-class SVM svm = LinearSVC(multi_class='ovr') svm_model", "from sklearn.svm import LinearSVC from sklearn.ensemble import RandomForestClassifier from sklearn.naive_bayes import GaussianNB import", "#If type is random, uniformly sample 2500 points from the dataset if type", "use - \"gaussianNB\" or \"randomForest\" or \"svm\" Ouputs: [losses,accuracies] where, losses - holds", "= [] rf_accuracy = [] nb_accuracy = [] x = [] train_file =", "<gh_stars>1-10 import matplotlib.pyplot as plt import numpy as np import pandas as pd", "= mode + \"_BLINDED.csv\" train_data = pd.read_csv(train_file) #If type is passive, Initialize a", "svm_accuracy.append(svm_score) svm_loss.append(svm_l) elif base == \"randomForest\": #Using decision trees rf = RandomForestClassifier(n_estimators=100,criterion=\"gini\") rf_model", "= count/len(labels) if(loss>1): loss = 1 return loss def learner(type,mode,base=\"gaussianNB\"): ''' This funtions", "at a given iteration. Loss here has been defined as the fraction of", "= 250 #batch_size defines how many input samples we process at a time", "nb_accuracy.append(nb_score) nb_loss.append(nb_l) x.append(batch_size) batch_size += minb losses.append(x) accuracies.append(x) if(base == \"svm\"): losses.append(svm_loss) accuracies.append(svm_accuracy)", "LinearSVC(multi_class='ovr') svm_model = svm.fit(train_features,train_labels) svm_score = svm_model.score(test_features,test_labels) svm_l = compute_loss(svm_model,test_features,test_labels) svm_accuracy.append(svm_score) svm_loss.append(svm_l) elif", "many input samples we process at a time batch_size = 250 iter =", "= compute_loss(svm_model,test_features,test_labels) svm_accuracy.append(svm_score) svm_loss.append(svm_l) elif base == \"randomForest\": #Using decision trees rf =", "RandomForestClassifier from sklearn.naive_bayes import GaussianNB import matplotlib.patches as mpatches import random def compute_loss(model,testData,labels):", "train_data.iloc[:batch_size,:26] train_labels = train_data.iloc[:batch_size,-1] else: train_features = train_data.iloc[:batch_size,:52] train_labels = train_data.iloc[:batch_size,-1] print(type ,", "[losses,accuracies] where, losses - holds the loss of the model at each iteration", "RandomForestClassifier(n_estimators=100,criterion=\"gini\") rf_model = rf.fit(train_features,train_labels) rf_l = compute_loss(rf_model,test_features,test_labels) rf_score = 1 - rf_l rf_accuracy.append(rf_score)", "= int(2500/batch_size) for i in range(iter): if mode !=\"DIFFICULT\": train_features = train_data.iloc[:batch_size,:26] train_labels", "svm_loss.append(svm_l) elif base == \"randomForest\": #Using decision trees rf = RandomForestClassifier(n_estimators=100,criterion=\"gini\") rf_model =", "= start_index + 2500 train_data = train_data.iloc[start_index:end_index,:] #If type is random, uniformly sample", "iteration accuracies - holds the accuracies of the model at each iteration '''", "train_data.iloc[:batch_size,:52] train_labels = train_data.iloc[:batch_size,-1] print(type , \" learner ----> Iteration \",i+1 ,\" out", "random, uniformly sample 2500 points from the dataset if type == \"random\": train_data", "if(base == \"svm\"): losses.append(svm_loss) accuracies.append(svm_accuracy) if base == \"randomForest\": losses.append(rf_loss) accuracies.append(rf_accuracy) else: losses.append(nb_loss)", "on the given input parameters. Inputs: 1) type - \"passive\" learner or \"random\"", "random starting point and choose the next 2500 consecutive points if type ==", "250 #batch_size defines how many input samples we process at a time batch_size", "input features 3) labels - True labels for the given test data Outputs:", "learner or \"random\" learner 2) mode - Type of dataset \"EASY\", \"MODERATE\" or", "1) loss - fraction of wrongly classified points ''' predicted_labels = model.predict(testData) count", "next 2500 consecutive points if type == \"passive\": start_index = random.randint(0,1500) end_index =", "start_index + 2500 train_data = train_data.iloc[start_index:end_index,:] #If type is random, uniformly sample 2500", "- rf_l rf_accuracy.append(rf_score) rf_loss.append(rf_l) else: #Using Gaussian Naive Bayes classifier nb = GaussianNB()", "Naive Bayes classifier nb = GaussianNB() nb_model = nb.fit(train_features,train_labels) nb_l = compute_loss(nb_model,test_features,test_labels) nb_score", "''' This funtion computes the loss of the model at a given iteration." ]
[ "super(ToCurrencyTestCase, self).setUp() def tearDown(self): super(ToCurrencyTestCase, self).tearDown() def test_to_currency(self): \"\"\" Tests a successful currency", "TestCase from currency.models import Currency from currency.templatetags.to_currency import to_currency class ToCurrencyTestCase(TestCase): \"\"\" Test", "currency.templatetags.to_currency import to_currency class ToCurrencyTestCase(TestCase): \"\"\" Test unit for ```to_currency``` template tag. \"\"\"", "Templatetags test units. \"\"\" __author__ = \"<NAME> (<EMAIL>)\" from decimal import Decimal from", "coding: utf-8 -*- \"\"\" Description: Templatetags test units. \"\"\" __author__ = \"<NAME> (<EMAIL>)\"", "Test unit for ```to_currency``` template tag. \"\"\" def setUp(self): super(ToCurrencyTestCase, self).setUp() def tearDown(self):", "Currency from currency.templatetags.to_currency import to_currency class ToCurrencyTestCase(TestCase): \"\"\" Test unit for ```to_currency``` template", "= \"<NAME> (<EMAIL>)\" from decimal import Decimal from django.test import TestCase from currency.models", "unit for ```to_currency``` template tag. \"\"\" def setUp(self): super(ToCurrencyTestCase, self).setUp() def tearDown(self): super(ToCurrencyTestCase,", "-*- coding: utf-8 -*- \"\"\" Description: Templatetags test units. \"\"\" __author__ = \"<NAME>", "template tag. \"\"\" def setUp(self): super(ToCurrencyTestCase, self).setUp() def tearDown(self): super(ToCurrencyTestCase, self).tearDown() def test_to_currency(self):", "\"<NAME> (<EMAIL>)\" from decimal import Decimal from django.test import TestCase from currency.models import", "\"\"\" Test unit for ```to_currency``` template tag. \"\"\" def setUp(self): super(ToCurrencyTestCase, self).setUp() def", "units. \"\"\" __author__ = \"<NAME> (<EMAIL>)\" from decimal import Decimal from django.test import", "tearDown(self): super(ToCurrencyTestCase, self).tearDown() def test_to_currency(self): \"\"\" Tests a successful currency convertion, when the", "scale exists in model. \"\"\" currency = Currency.objects.get(code='ARS') self.assertEquals(Decimal('13'), to_currency(Decimal('1.55'), currency)) currency =", "from django.test import TestCase from currency.models import Currency from currency.templatetags.to_currency import to_currency class", "import Currency from currency.templatetags.to_currency import to_currency class ToCurrencyTestCase(TestCase): \"\"\" Test unit for ```to_currency```", "test units. \"\"\" __author__ = \"<NAME> (<EMAIL>)\" from decimal import Decimal from django.test", "currency.models import Currency from currency.templatetags.to_currency import to_currency class ToCurrencyTestCase(TestCase): \"\"\" Test unit for", "def setUp(self): super(ToCurrencyTestCase, self).setUp() def tearDown(self): super(ToCurrencyTestCase, self).tearDown() def test_to_currency(self): \"\"\" Tests a", "self).setUp() def tearDown(self): super(ToCurrencyTestCase, self).tearDown() def test_to_currency(self): \"\"\" Tests a successful currency convertion,", "def test_to_currency(self): \"\"\" Tests a successful currency convertion, when the scale exists in", "a successful currency convertion, when the scale exists in model. \"\"\" currency =", "import TestCase from currency.models import Currency from currency.templatetags.to_currency import to_currency class ToCurrencyTestCase(TestCase): \"\"\"", "exists in model. \"\"\" currency = Currency.objects.get(code='ARS') self.assertEquals(Decimal('13'), to_currency(Decimal('1.55'), currency)) currency = Currency.objects.get(code='USD')", "from currency.templatetags.to_currency import to_currency class ToCurrencyTestCase(TestCase): \"\"\" Test unit for ```to_currency``` template tag.", "model. \"\"\" currency = Currency.objects.get(code='ARS') self.assertEquals(Decimal('13'), to_currency(Decimal('1.55'), currency)) currency = Currency.objects.get(code='USD') self.assertEquals(Decimal('2.0'), to_currency(Decimal('1.55'),", "for ```to_currency``` template tag. \"\"\" def setUp(self): super(ToCurrencyTestCase, self).setUp() def tearDown(self): super(ToCurrencyTestCase, self).tearDown()", "# -*- coding: utf-8 -*- \"\"\" Description: Templatetags test units. \"\"\" __author__ =", "class ToCurrencyTestCase(TestCase): \"\"\" Test unit for ```to_currency``` template tag. \"\"\" def setUp(self): super(ToCurrencyTestCase,", "#!/usr/bin/env python # -*- coding: utf-8 -*- \"\"\" Description: Templatetags test units. \"\"\"", "django.test import TestCase from currency.models import Currency from currency.templatetags.to_currency import to_currency class ToCurrencyTestCase(TestCase):", "from decimal import Decimal from django.test import TestCase from currency.models import Currency from", "convertion, when the scale exists in model. \"\"\" currency = Currency.objects.get(code='ARS') self.assertEquals(Decimal('13'), to_currency(Decimal('1.55'),", "Description: Templatetags test units. \"\"\" __author__ = \"<NAME> (<EMAIL>)\" from decimal import Decimal", "utf-8 -*- \"\"\" Description: Templatetags test units. \"\"\" __author__ = \"<NAME> (<EMAIL>)\" from", "successful currency convertion, when the scale exists in model. \"\"\" currency = Currency.objects.get(code='ARS')", "\"\"\" def setUp(self): super(ToCurrencyTestCase, self).setUp() def tearDown(self): super(ToCurrencyTestCase, self).tearDown() def test_to_currency(self): \"\"\" Tests", "python # -*- coding: utf-8 -*- \"\"\" Description: Templatetags test units. \"\"\" __author__", "\"\"\" Description: Templatetags test units. \"\"\" __author__ = \"<NAME> (<EMAIL>)\" from decimal import", "when the scale exists in model. \"\"\" currency = Currency.objects.get(code='ARS') self.assertEquals(Decimal('13'), to_currency(Decimal('1.55'), currency))", "\"\"\" currency = Currency.objects.get(code='ARS') self.assertEquals(Decimal('13'), to_currency(Decimal('1.55'), currency)) currency = Currency.objects.get(code='USD') self.assertEquals(Decimal('2.0'), to_currency(Decimal('1.55'), currency))", "to_currency class ToCurrencyTestCase(TestCase): \"\"\" Test unit for ```to_currency``` template tag. \"\"\" def setUp(self):", "decimal import Decimal from django.test import TestCase from currency.models import Currency from currency.templatetags.to_currency", "import to_currency class ToCurrencyTestCase(TestCase): \"\"\" Test unit for ```to_currency``` template tag. \"\"\" def", "self).tearDown() def test_to_currency(self): \"\"\" Tests a successful currency convertion, when the scale exists", "test_to_currency(self): \"\"\" Tests a successful currency convertion, when the scale exists in model.", "setUp(self): super(ToCurrencyTestCase, self).setUp() def tearDown(self): super(ToCurrencyTestCase, self).tearDown() def test_to_currency(self): \"\"\" Tests a successful", "-*- \"\"\" Description: Templatetags test units. \"\"\" __author__ = \"<NAME> (<EMAIL>)\" from decimal", "__author__ = \"<NAME> (<EMAIL>)\" from decimal import Decimal from django.test import TestCase from", "```to_currency``` template tag. \"\"\" def setUp(self): super(ToCurrencyTestCase, self).setUp() def tearDown(self): super(ToCurrencyTestCase, self).tearDown() def", "\"\"\" Tests a successful currency convertion, when the scale exists in model. \"\"\"", "\"\"\" __author__ = \"<NAME> (<EMAIL>)\" from decimal import Decimal from django.test import TestCase", "super(ToCurrencyTestCase, self).tearDown() def test_to_currency(self): \"\"\" Tests a successful currency convertion, when the scale", "ToCurrencyTestCase(TestCase): \"\"\" Test unit for ```to_currency``` template tag. \"\"\" def setUp(self): super(ToCurrencyTestCase, self).setUp()", "from currency.models import Currency from currency.templatetags.to_currency import to_currency class ToCurrencyTestCase(TestCase): \"\"\" Test unit", "(<EMAIL>)\" from decimal import Decimal from django.test import TestCase from currency.models import Currency", "def tearDown(self): super(ToCurrencyTestCase, self).tearDown() def test_to_currency(self): \"\"\" Tests a successful currency convertion, when", "tag. \"\"\" def setUp(self): super(ToCurrencyTestCase, self).setUp() def tearDown(self): super(ToCurrencyTestCase, self).tearDown() def test_to_currency(self): \"\"\"", "import Decimal from django.test import TestCase from currency.models import Currency from currency.templatetags.to_currency import", "Decimal from django.test import TestCase from currency.models import Currency from currency.templatetags.to_currency import to_currency", "Tests a successful currency convertion, when the scale exists in model. \"\"\" currency", "currency convertion, when the scale exists in model. \"\"\" currency = Currency.objects.get(code='ARS') self.assertEquals(Decimal('13'),", "the scale exists in model. \"\"\" currency = Currency.objects.get(code='ARS') self.assertEquals(Decimal('13'), to_currency(Decimal('1.55'), currency)) currency", "in model. \"\"\" currency = Currency.objects.get(code='ARS') self.assertEquals(Decimal('13'), to_currency(Decimal('1.55'), currency)) currency = Currency.objects.get(code='USD') self.assertEquals(Decimal('2.0')," ]
[ "log10 class PSNR_Metric(Metric): def __init__(self, output_transform=lambda x: x, device=None): self._psnr_values = None self._num_examples", "0 super(PSNR_Metric, self).reset() @reinit__is_reduced def update(self, output): y_pred, y_true = output mse =", "self._psnr_values = 0 self._num_examples = 0 super(PSNR_Metric, self).reset() @reinit__is_reduced def update(self, output): y_pred,", "__init__(self, output_transform=lambda x: x, device=None): self._psnr_values = None self._num_examples = None self.criterion =", "super(PSNR_Metric, self).reset() @reinit__is_reduced def update(self, output): y_pred, y_true = output mse = self.criterion(y_pred,", "\"_psnr_values\") def compute(self): if self._num_examples == 0: raise NotComputableError('PSNR_Metric must have at least", "nn from math import log10 class PSNR_Metric(Metric): def __init__(self, output_transform=lambda x: x, device=None):", "None self._num_examples = None self.criterion = nn.MSELoss() super(PSNR_Metric, self).__init__(output_transform=output_transform, device=device) @reinit__is_reduced def reset(self):", "from math import log10 class PSNR_Metric(Metric): def __init__(self, output_transform=lambda x: x, device=None): self._psnr_values", "at least one example before it can be computed.') return self._psnr_values / self._num_examples", "* log10(1 / mse.item()) self._psnr_values += psnr self._num_examples += y_true.shape[0] @sync_all_reduce(\"_num_examples\", \"_psnr_values\") def", "NotComputableError('PSNR_Metric must have at least one example before it can be computed.') return", "10 * log10(1 / mse.item()) self._psnr_values += psnr self._num_examples += y_true.shape[0] @sync_all_reduce(\"_num_examples\", \"_psnr_values\")", "= 10 * log10(1 / mse.item()) self._psnr_values += psnr self._num_examples += y_true.shape[0] @sync_all_reduce(\"_num_examples\",", "/ mse.item()) self._psnr_values += psnr self._num_examples += y_true.shape[0] @sync_all_reduce(\"_num_examples\", \"_psnr_values\") def compute(self): if", "= 0 super(PSNR_Metric, self).reset() @reinit__is_reduced def update(self, output): y_pred, y_true = output mse", "= 0 self._num_examples = 0 super(PSNR_Metric, self).reset() @reinit__is_reduced def update(self, output): y_pred, y_true", "x, device=None): self._psnr_values = None self._num_examples = None self.criterion = nn.MSELoss() super(PSNR_Metric, self).__init__(output_transform=output_transform,", "import torch.nn as nn from math import log10 class PSNR_Metric(Metric): def __init__(self, output_transform=lambda", "self.criterion = nn.MSELoss() super(PSNR_Metric, self).__init__(output_transform=output_transform, device=device) @reinit__is_reduced def reset(self): self._psnr_values = 0 self._num_examples", "output_transform=lambda x: x, device=None): self._psnr_values = None self._num_examples = None self.criterion = nn.MSELoss()", "compute(self): if self._num_examples == 0: raise NotComputableError('PSNR_Metric must have at least one example", "def compute(self): if self._num_examples == 0: raise NotComputableError('PSNR_Metric must have at least one", "reinit__is_reduced import torch import torch.nn as nn from math import log10 class PSNR_Metric(Metric):", "self._psnr_values += psnr self._num_examples += y_true.shape[0] @sync_all_reduce(\"_num_examples\", \"_psnr_values\") def compute(self): if self._num_examples ==", "psnr = 10 * log10(1 / mse.item()) self._psnr_values += psnr self._num_examples += y_true.shape[0]", "mse = self.criterion(y_pred, y_true) psnr = 10 * log10(1 / mse.item()) self._psnr_values +=", "<reponame>ryanwongsa/image-inpainting from ignite.metrics import Metric from ignite.exceptions import NotComputableError # These decorators helps", "device=device) @reinit__is_reduced def reset(self): self._psnr_values = 0 self._num_examples = 0 super(PSNR_Metric, self).reset() @reinit__is_reduced", "These decorators helps with distributed settings from ignite.metrics.metric import sync_all_reduce, reinit__is_reduced import torch", "reset(self): self._psnr_values = 0 self._num_examples = 0 super(PSNR_Metric, self).reset() @reinit__is_reduced def update(self, output):", "log10(1 / mse.item()) self._psnr_values += psnr self._num_examples += y_true.shape[0] @sync_all_reduce(\"_num_examples\", \"_psnr_values\") def compute(self):", "psnr self._num_examples += y_true.shape[0] @sync_all_reduce(\"_num_examples\", \"_psnr_values\") def compute(self): if self._num_examples == 0: raise", "= nn.MSELoss() super(PSNR_Metric, self).__init__(output_transform=output_transform, device=device) @reinit__is_reduced def reset(self): self._psnr_values = 0 self._num_examples =", "@reinit__is_reduced def update(self, output): y_pred, y_true = output mse = self.criterion(y_pred, y_true) psnr", "import log10 class PSNR_Metric(Metric): def __init__(self, output_transform=lambda x: x, device=None): self._psnr_values = None", "if self._num_examples == 0: raise NotComputableError('PSNR_Metric must have at least one example before", "output mse = self.criterion(y_pred, y_true) psnr = 10 * log10(1 / mse.item()) self._psnr_values", "y_pred, y_true = output mse = self.criterion(y_pred, y_true) psnr = 10 * log10(1", "0 self._num_examples = 0 super(PSNR_Metric, self).reset() @reinit__is_reduced def update(self, output): y_pred, y_true =", "# These decorators helps with distributed settings from ignite.metrics.metric import sync_all_reduce, reinit__is_reduced import", "torch import torch.nn as nn from math import log10 class PSNR_Metric(Metric): def __init__(self,", "@reinit__is_reduced def reset(self): self._psnr_values = 0 self._num_examples = 0 super(PSNR_Metric, self).reset() @reinit__is_reduced def", "settings from ignite.metrics.metric import sync_all_reduce, reinit__is_reduced import torch import torch.nn as nn from", "nn.MSELoss() super(PSNR_Metric, self).__init__(output_transform=output_transform, device=device) @reinit__is_reduced def reset(self): self._psnr_values = 0 self._num_examples = 0", "self._num_examples == 0: raise NotComputableError('PSNR_Metric must have at least one example before it", "torch.nn as nn from math import log10 class PSNR_Metric(Metric): def __init__(self, output_transform=lambda x:", "ignite.metrics.metric import sync_all_reduce, reinit__is_reduced import torch import torch.nn as nn from math import", "== 0: raise NotComputableError('PSNR_Metric must have at least one example before it can", "NotComputableError # These decorators helps with distributed settings from ignite.metrics.metric import sync_all_reduce, reinit__is_reduced", "mse.item()) self._psnr_values += psnr self._num_examples += y_true.shape[0] @sync_all_reduce(\"_num_examples\", \"_psnr_values\") def compute(self): if self._num_examples", "x: x, device=None): self._psnr_values = None self._num_examples = None self.criterion = nn.MSELoss() super(PSNR_Metric,", "self._psnr_values = None self._num_examples = None self.criterion = nn.MSELoss() super(PSNR_Metric, self).__init__(output_transform=output_transform, device=device) @reinit__is_reduced", "def update(self, output): y_pred, y_true = output mse = self.criterion(y_pred, y_true) psnr =", "output): y_pred, y_true = output mse = self.criterion(y_pred, y_true) psnr = 10 *", "None self.criterion = nn.MSELoss() super(PSNR_Metric, self).__init__(output_transform=output_transform, device=device) @reinit__is_reduced def reset(self): self._psnr_values = 0", "0: raise NotComputableError('PSNR_Metric must have at least one example before it can be", "self).__init__(output_transform=output_transform, device=device) @reinit__is_reduced def reset(self): self._psnr_values = 0 self._num_examples = 0 super(PSNR_Metric, self).reset()", "= None self._num_examples = None self.criterion = nn.MSELoss() super(PSNR_Metric, self).__init__(output_transform=output_transform, device=device) @reinit__is_reduced def", "self._num_examples = None self.criterion = nn.MSELoss() super(PSNR_Metric, self).__init__(output_transform=output_transform, device=device) @reinit__is_reduced def reset(self): self._psnr_values", "y_true = output mse = self.criterion(y_pred, y_true) psnr = 10 * log10(1 /", "helps with distributed settings from ignite.metrics.metric import sync_all_reduce, reinit__is_reduced import torch import torch.nn", "self._num_examples = 0 super(PSNR_Metric, self).reset() @reinit__is_reduced def update(self, output): y_pred, y_true = output", "y_true.shape[0] @sync_all_reduce(\"_num_examples\", \"_psnr_values\") def compute(self): if self._num_examples == 0: raise NotComputableError('PSNR_Metric must have", "import NotComputableError # These decorators helps with distributed settings from ignite.metrics.metric import sync_all_reduce,", "as nn from math import log10 class PSNR_Metric(Metric): def __init__(self, output_transform=lambda x: x,", "raise NotComputableError('PSNR_Metric must have at least one example before it can be computed.')", "super(PSNR_Metric, self).__init__(output_transform=output_transform, device=device) @reinit__is_reduced def reset(self): self._psnr_values = 0 self._num_examples = 0 super(PSNR_Metric,", "+= y_true.shape[0] @sync_all_reduce(\"_num_examples\", \"_psnr_values\") def compute(self): if self._num_examples == 0: raise NotComputableError('PSNR_Metric must", "math import log10 class PSNR_Metric(Metric): def __init__(self, output_transform=lambda x: x, device=None): self._psnr_values =", "device=None): self._psnr_values = None self._num_examples = None self.criterion = nn.MSELoss() super(PSNR_Metric, self).__init__(output_transform=output_transform, device=device)", "y_true) psnr = 10 * log10(1 / mse.item()) self._psnr_values += psnr self._num_examples +=", "class PSNR_Metric(Metric): def __init__(self, output_transform=lambda x: x, device=None): self._psnr_values = None self._num_examples =", "ignite.exceptions import NotComputableError # These decorators helps with distributed settings from ignite.metrics.metric import", "self._num_examples += y_true.shape[0] @sync_all_reduce(\"_num_examples\", \"_psnr_values\") def compute(self): if self._num_examples == 0: raise NotComputableError('PSNR_Metric", "ignite.metrics import Metric from ignite.exceptions import NotComputableError # These decorators helps with distributed", "from ignite.exceptions import NotComputableError # These decorators helps with distributed settings from ignite.metrics.metric", "import sync_all_reduce, reinit__is_reduced import torch import torch.nn as nn from math import log10", "decorators helps with distributed settings from ignite.metrics.metric import sync_all_reduce, reinit__is_reduced import torch import", "from ignite.metrics import Metric from ignite.exceptions import NotComputableError # These decorators helps with", "distributed settings from ignite.metrics.metric import sync_all_reduce, reinit__is_reduced import torch import torch.nn as nn", "self).reset() @reinit__is_reduced def update(self, output): y_pred, y_true = output mse = self.criterion(y_pred, y_true)", "import Metric from ignite.exceptions import NotComputableError # These decorators helps with distributed settings", "= self.criterion(y_pred, y_true) psnr = 10 * log10(1 / mse.item()) self._psnr_values += psnr", "from ignite.metrics.metric import sync_all_reduce, reinit__is_reduced import torch import torch.nn as nn from math", "def reset(self): self._psnr_values = 0 self._num_examples = 0 super(PSNR_Metric, self).reset() @reinit__is_reduced def update(self,", "PSNR_Metric(Metric): def __init__(self, output_transform=lambda x: x, device=None): self._psnr_values = None self._num_examples = None", "update(self, output): y_pred, y_true = output mse = self.criterion(y_pred, y_true) psnr = 10", "= None self.criterion = nn.MSELoss() super(PSNR_Metric, self).__init__(output_transform=output_transform, device=device) @reinit__is_reduced def reset(self): self._psnr_values =", "def __init__(self, output_transform=lambda x: x, device=None): self._psnr_values = None self._num_examples = None self.criterion", "with distributed settings from ignite.metrics.metric import sync_all_reduce, reinit__is_reduced import torch import torch.nn as", "@sync_all_reduce(\"_num_examples\", \"_psnr_values\") def compute(self): if self._num_examples == 0: raise NotComputableError('PSNR_Metric must have at", "have at least one example before it can be computed.') return self._psnr_values /", "= output mse = self.criterion(y_pred, y_true) psnr = 10 * log10(1 / mse.item())", "Metric from ignite.exceptions import NotComputableError # These decorators helps with distributed settings from", "+= psnr self._num_examples += y_true.shape[0] @sync_all_reduce(\"_num_examples\", \"_psnr_values\") def compute(self): if self._num_examples == 0:", "import torch import torch.nn as nn from math import log10 class PSNR_Metric(Metric): def", "sync_all_reduce, reinit__is_reduced import torch import torch.nn as nn from math import log10 class", "must have at least one example before it can be computed.') return self._psnr_values", "self.criterion(y_pred, y_true) psnr = 10 * log10(1 / mse.item()) self._psnr_values += psnr self._num_examples" ]
[ "\"bounces.csv\"), bounce_results) numpy.savetxt(os.path.join(target_path, \"change_of_position.csv\"), cop_results) settings_ats.save(target=os.path.join(target_path, \"used.toml\")) @ats.command() @click.option(\"-b\", \"--data_batch\", \"data_batch\", prompt=True, help=\"Name", "is corrupted, please generate a new settings file.\") return if settings_ats[\"R\"] is None:", "numpy.arange(settings_ats[\"N_min\"], n_stop + 1, settings_ats[\"N_step\"]) bounce = numpy.loadtxt(os.path.join(path, \"bounces.csv\")) plt.plot(x, bounce, marker='o') plt.title(f\"Zależność", "return if settings_ats[\"N_step\"] is None: click.echo(\"The settings file is corrupted, please generate a", "with click.progressbar( range(len(test_cases) * settings_ats['R'] - 1, -1, -1), label=\"Performing simulations:\", show_eta=False )", "numpy.empty(len(test_cases), dtype=float) settings_ats.new('N', settings_ats[\"N_min\"]) with click.progressbar( range(len(test_cases) * settings_ats['R'] - 1, -1, -1),", "generate a new settings file.\") return if i % settings_ats['R'] == 0: bounce_results[i", "i = 1 while True: if not os.path.lexists(f\"{path}{i}\"): return f\"{path}{i}\" i += 1", "return if not os.path.isdir(path := os.path.join(os.getcwd(), \"ats_results\", data_batch)): click.echo( f\"The ats_results/{data_batch} catalog doesn't", "of tests based on the data in the settings_ats.toml file.\"\"\" settings_ats = atoms_simulator.Settings(\"settings_ats.toml\")", "not os.path.lexists(f\"{path}{i}\"): return f\"{path}{i}\" i += 1 @click.group() def ats(): \"\"\"Allows to perform", "data_batch)): click.echo( f\"The ats_results/{data_batch} catalog doesn't exist within the current working directory.\" )", "settings_ats['R'] == 0: bounce_results[i // settings_ats['R']] = int(bounce[i // settings_ats['R']].mean()) cop_results[i // settings_ats['R']]", "click.echo( \"The ats_results catalog doesn't exist within the current working directory. Generate some", "atoms_simulator import numpy import matplotlib.pyplot as plt def get_project_path(): return os.path.dirname(atoms_simulator.__file__) def get_path(path):", "settings_ats['w'] = size test_cases = [ [i for _ in range(settings_ats['R'])] for i", "using atoms_simulator module.\"\"\" pass @ats.command() def init(): \"\"\"Creates a settings_ats.toml file in the", "plt.title(f\"Zależność liczby zderzeń od ilości atomów, M = {settings_ats['M']}\") plt.xlabel(\"Liczba atomów w pojemniku\")", "saving the results of the test.\", is_flag=True) def test(graphics, no_save): \"\"\"Performs a series", "swobodnej od ilości atomów, M = {settings_ats['M']}\") plt.xlabel(\"Liczba atomów w pojemniku\") plt.ylabel(\"Średnia droga", ":= os.path.join(os.getcwd(), \"ats_results\", data_batch)): click.echo( f\"The ats_results/{data_batch} catalog doesn't exist within the current", "(settings_ats[\"N_number\"] - 1) x = numpy.arange(settings_ats[\"N_min\"], n_stop + 1, settings_ats[\"N_step\"]) bounce = numpy.loadtxt(os.path.join(path,", "as error: click.echo(f\"\\n{error} Please generate a new settings file.\") return if i %", "a new settings file.\") return click.echo(\"Starting simulation...\") n_stop = settings_ats[\"N_min\"] + settings_ats[\"N_step\"] *", "settings file.\") return if settings_ats[\"R\"] is None: click.echo(\"The settings file is corrupted, please", "= settings_ats[\"N_min\"] + settings_ats[\"N_step\"] * (settings_ats[\"N_number\"] - 1) x = numpy.arange(settings_ats[\"N_min\"], n_stop +", "is corrupted, please generate a new settings file.\") return if settings_ats[\"N_step\"] is None:", "* settings_ats['R'] - 1, -1, -1), label=\"Performing simulations:\", show_eta=False ) as progress: for", "order to generate a new configuration file.\") @ats.command() @click.option(\"-g\", \"--graphics\", \"graphics\", help=\"Turn on", "= numpy.empty((len(test_cases), settings_ats['R']), dtype=int) bounce_results = numpy.empty(len(test_cases), dtype=int) cop = numpy.empty((len(test_cases), settings_ats['R']), dtype=float)", "\"\"\"Creates a settings_ats.toml file in the current directory.\"\"\" if not os.path.isfile(\"settings_ats.toml\"): source =", "bounce_results) numpy.savetxt(os.path.join(target_path, \"change_of_position.csv\"), cop_results) settings_ats.save(target=os.path.join(target_path, \"used.toml\")) @ats.command() @click.option(\"-b\", \"--data_batch\", \"data_batch\", prompt=True, help=\"Name of", "a series of tests based on the data in the settings_ats.toml file.\"\"\" settings_ats", "* (n_stop + 1)) ** 0.5)]) # settings_ats['h'] = size # settings_ats['w'] =", "click import os.path import shutil import atoms_simulator import numpy import matplotlib.pyplot as plt", "# settings_ats['w'] = size test_cases = [ [i for _ in range(settings_ats['R'])] for", "not os.path.isdir(results_path := os.path.join(os.getcwd(), \"ats_results\")): click.echo( \"The ats_results catalog doesn't exist within the", "def get_project_path(): return os.path.dirname(atoms_simulator.__file__) def get_path(path): i = 1 while True: if not", "% settings_ats['R']] = atoms_simulator.simulate(settings_ats, graphics) except ValueError as error: click.echo(f\"\\n{error} Please generate a", "\"data_batch\")) os.mkdir(target_path) numpy.savetxt(os.path.join(target_path, \"bounces.csv\"), bounce_results) numpy.savetxt(os.path.join(target_path, \"change_of_position.csv\"), cop_results) settings_ats.save(target=os.path.join(target_path, \"used.toml\")) @ats.command() @click.option(\"-b\", \"--data_batch\",", "not (settings_ats.load() and os.path.isfile(os.path.join(path, \"bounces.csv\")) and os.path.isfile(os.path.join(path, \"change_of_position.csv\"))): click.echo(\"This data batch is corrupted.\")", "file in the current directory.\"\"\" if not os.path.isfile(\"settings_ats.toml\"): source = os.path.join(get_project_path(), \"assets/settings_source.toml\") target", "\"bounces.csv\")) and os.path.isfile(os.path.join(path, \"change_of_position.csv\"))): click.echo(\"This data batch is corrupted.\") return n_stop = settings_ats[\"N_min\"]", "if not (settings_ats.load() and os.path.isfile(os.path.join(path, \"bounces.csv\")) and os.path.isfile(os.path.join(path, \"change_of_position.csv\"))): click.echo(\"This data batch is", "please generate a new settings file.\") return if settings_ats[\"N_number\"] is None: click.echo(\"The settings", "return if settings_ats[\"N_number\"] is None: click.echo(\"The settings file is corrupted, please generate a", "# settings_ats['h'] = size # settings_ats['w'] = size test_cases = [ [i for", "cop, marker='o') plt.title(f\"Zależność średniej drogi swobodnej od ilości atomów, M = {settings_ats['M']}\") plt.xlabel(\"Liczba", "click.echo(\"This data batch is corrupted.\") return n_stop = settings_ats[\"N_min\"] + settings_ats[\"N_step\"] * (settings_ats[\"N_number\"]", "pojemniku\") plt.ylabel(\"Liczba odbić atomu czerownego\") plt.grid(True) plt.savefig(os.path.join(target_path, \"bounces.png\")) plt.clf() cop = numpy.loadtxt(os.path.join(path, \"change_of_position.csv\"))", "bounce_results[i // settings_ats['R']] = int(bounce[i // settings_ats['R']].mean()) cop_results[i // settings_ats['R']] = cop[i //", "file.\") return if settings_ats[\"N_number\"] is None: click.echo(\"The settings file is corrupted, please generate", "os.path import shutil import atoms_simulator import numpy import matplotlib.pyplot as plt def get_project_path():", "the file first.\") return if settings_ats[\"N_min\"] is None: click.echo(\"The settings file is corrupted,", "plot(data_batch): \"\"\"Plots the previously generated data.\"\"\" if not os.path.isdir(results_path := os.path.join(os.getcwd(), \"ats_results\")): click.echo(", "% settings_ats['R']], \\ cop[i // settings_ats['R']][i % settings_ats['R']] = atoms_simulator.simulate(settings_ats, graphics) except ValueError", "corrupted, please generate a new settings file.\") return if settings_ats[\"N_step\"] is None: click.echo(\"The", ") return if not os.path.isdir(path := os.path.join(os.getcwd(), \"ats_results\", data_batch)): click.echo( f\"The ats_results/{data_batch} catalog", "settings_ats[\"N_min\"] + settings_ats[\"N_step\"] * (settings_ats[\"N_number\"] - 1) # size = max([settings_ats['h'], settings_ats['w'], math.ceil((4", "show_eta=False ) as progress: for i in progress: settings_ats['N'] = test_cases[i // settings_ats['R']][i", "perform detailed tests using atoms_simulator module.\"\"\" pass @ats.command() def init(): \"\"\"Creates a settings_ats.toml", "settings_ats['R']][i % settings_ats['R']] try: bounce[i // settings_ats['R']][i % settings_ats['R']], \\ cop[i // settings_ats['R']][i", "is None: click.echo(\"The settings file is corrupted, please generate a new settings file.\")", "help=\"Turn on pygame simulation\", is_flag=True) @click.option(\"--no-save\", \"no_save\", help=\"Disable saving the results of the", "help=\"Disable saving the results of the test.\", is_flag=True) def test(graphics, no_save): \"\"\"Performs a", "= cop[i // settings_ats['R']].mean() if not no_save: if not os.path.isdir(results_path := os.path.join(os.getcwd(), \"ats_results\")):", "please generate a new settings file.\") return if settings_ats[\"N_step\"] is None: click.echo(\"The settings", "= settings_ats[\"N_min\"] + settings_ats[\"N_step\"] * (settings_ats[\"N_number\"] - 1) # size = max([settings_ats['h'], settings_ats['w'],", "ilości atomów, M = {settings_ats['M']}\") plt.xlabel(\"Liczba atomów w pojemniku\") plt.ylabel(\"Średnia droga swobodna atomu", "int(bounce[i // settings_ats['R']].mean()) cop_results[i // settings_ats['R']] = cop[i // settings_ats['R']].mean() if not no_save:", "f\"{path}{i}\" i += 1 @click.group() def ats(): \"\"\"Allows to perform detailed tests using", "math import click import os.path import shutil import atoms_simulator import numpy import matplotlib.pyplot", "1 while True: if not os.path.lexists(f\"{path}{i}\"): return f\"{path}{i}\" i += 1 @click.group() def", "i % settings_ats['R'] == 0: bounce_results[i // settings_ats['R']] = int(bounce[i // settings_ats['R']].mean()) cop_results[i", "settings_ats[\"N_step\"]) bounce = numpy.loadtxt(os.path.join(path, \"bounces.csv\")) plt.plot(x, bounce, marker='o') plt.title(f\"Zależność liczby zderzeń od ilości", "os.path.isdir(results_path := os.path.join(os.getcwd(), \"ats_results\")): click.echo( \"The ats_results catalog doesn't exist within the current", "file first.\") return if settings_ats[\"N_min\"] is None: click.echo(\"The settings file is corrupted, please", "import matplotlib.pyplot as plt def get_project_path(): return os.path.dirname(atoms_simulator.__file__) def get_path(path): i = 1", "test_cases[i // settings_ats['R']][i % settings_ats['R']] try: bounce[i // settings_ats['R']][i % settings_ats['R']], \\ cop[i", "prompt=True, help=\"Name of the previously generated data batch.\") def plot(data_batch): \"\"\"Plots the previously", "current working directory. Generate some data first.\" ) return if not os.path.isdir(path :=", "1 @click.group() def ats(): \"\"\"Allows to perform detailed tests using atoms_simulator module.\"\"\" pass", "data in the settings_ats.toml file.\"\"\" settings_ats = atoms_simulator.Settings(\"settings_ats.toml\") if not settings_ats.load(): click.echo(\"No settings", "= atoms_simulator.Settings(\"settings_ats.toml\") if not settings_ats.load(): click.echo(\"No settings file detected. Generate the file first.\")", "numpy import matplotlib.pyplot as plt def get_project_path(): return os.path.dirname(atoms_simulator.__file__) def get_path(path): i =", "the current directory.\"\"\" if not os.path.isfile(\"settings_ats.toml\"): source = os.path.join(get_project_path(), \"assets/settings_source.toml\") target = os.path.join(os.getcwd(),", "@click.group() def ats(): \"\"\"Allows to perform detailed tests using atoms_simulator module.\"\"\" pass @ats.command()", "\"change_of_position.csv\")) plt.plot(x, cop, marker='o') plt.title(f\"Zależność średniej drogi swobodnej od ilości atomów, M =", ":= os.path.join(os.getcwd(), \"ats_results\")): click.echo( \"The ats_results catalog doesn't exist within the current working", "\"no_save\", help=\"Disable saving the results of the test.\", is_flag=True) def test(graphics, no_save): \"\"\"Performs", "settings_ats[\"N_step\"] * (settings_ats[\"N_number\"] - 1) x = numpy.arange(settings_ats[\"N_min\"], n_stop + 1, settings_ats[\"N_step\"]) bounce", "ats_results/{data_batch} catalog doesn't exist within the current working directory.\" ) return target_path =", "new settings file.\") return if settings_ats[\"N_number\"] is None: click.echo(\"The settings file is corrupted,", "is corrupted, please generate a new settings file.\") return if settings_ats[\"N_number\"] is None:", "working directory. Generate some data first.\" ) return if not os.path.isdir(path := os.path.join(os.getcwd(),", ") return target_path = get_path(os.path.join(results_path, \"figures_batch\")) os.mkdir(target_path) settings_ats = atoms_simulator.Settings(os.path.join(path, \"used.toml\")) if not", "dtype=float) settings_ats.new('N', settings_ats[\"N_min\"]) with click.progressbar( range(len(test_cases) * settings_ats['R'] - 1, -1, -1), label=\"Performing", "is_flag=True) def test(graphics, no_save): \"\"\"Performs a series of tests based on the data", "Generate some data first.\" ) return if not os.path.isdir(path := os.path.join(os.getcwd(), \"ats_results\", data_batch)):", "for _ in range(settings_ats['R'])] for i in range(settings_ats[\"N_min\"], n_stop + 1, settings_ats[\"N_step\"]) ]", "numpy.loadtxt(os.path.join(path, \"bounces.csv\")) plt.plot(x, bounce, marker='o') plt.title(f\"Zależność liczby zderzeń od ilości atomów, M =", "the previously generated data batch.\") def plot(data_batch): \"\"\"Plots the previously generated data.\"\"\" if", "file.\") return if settings_ats[\"N_step\"] is None: click.echo(\"The settings file is corrupted, please generate", "ValueError as error: click.echo(f\"\\n{error} Please generate a new settings file.\") return if i", "// settings_ats['R']] = cop[i // settings_ats['R']].mean() if not no_save: if not os.path.isdir(results_path :=", "first.\" ) return if not os.path.isdir(path := os.path.join(os.getcwd(), \"ats_results\", data_batch)): click.echo( f\"The ats_results/{data_batch}", "generated data batch.\") def plot(data_batch): \"\"\"Plots the previously generated data.\"\"\" if not os.path.isdir(results_path", "simulation\", is_flag=True) @click.option(\"--no-save\", \"no_save\", help=\"Disable saving the results of the test.\", is_flag=True) def", "settings_ats[\"N_min\"] + settings_ats[\"N_step\"] * (settings_ats[\"N_number\"] - 1) x = numpy.arange(settings_ats[\"N_min\"], n_stop + 1,", "as progress: for i in progress: settings_ats['N'] = test_cases[i // settings_ats['R']][i % settings_ats['R']]", "new settings file.\") return if settings_ats[\"N_step\"] is None: click.echo(\"The settings file is corrupted,", "\"ats_results\", data_batch)): click.echo( f\"The ats_results/{data_batch} catalog doesn't exist within the current working directory.\"", "exist within the current working directory. Generate some data first.\" ) return if", "settings file detected. Generate the file first.\") return if settings_ats[\"N_min\"] is None: click.echo(\"The", "file already exists. Please delete it in order to generate a new configuration", "plt.plot(x, bounce, marker='o') plt.title(f\"Zależność liczby zderzeń od ilości atomów, M = {settings_ats['M']}\") plt.xlabel(\"Liczba", "** 0.5)]) # settings_ats['h'] = size # settings_ats['w'] = size test_cases = [", "plt.xlabel(\"Liczba atomów w pojemniku\") plt.ylabel(\"Liczba odbić atomu czerownego\") plt.grid(True) plt.savefig(os.path.join(target_path, \"bounces.png\")) plt.clf() cop", "\\ cop[i // settings_ats['R']][i % settings_ats['R']] = atoms_simulator.simulate(settings_ats, graphics) except ValueError as error:", "atomów w pojemniku\") plt.ylabel(\"Średnia droga swobodna atomu czerwonego\") plt.grid(True) plt.savefig(os.path.join(target_path, \"change_of_position.png\")) plt.clf() settings_ats.save(os.path.join(target_path,", "target) click.echo(\"Settings file generated successfully.\") else: click.echo(\"Settings file already exists. Please delete it", "settings_ats.new('N', settings_ats[\"N_min\"]) with click.progressbar( range(len(test_cases) * settings_ats['R'] - 1, -1, -1), label=\"Performing simulations:\",", "settings_ats['R'] - 1, -1, -1), label=\"Performing simulations:\", show_eta=False ) as progress: for i", "f\"The ats_results/{data_batch} catalog doesn't exist within the current working directory.\" ) return target_path", "numpy.loadtxt(os.path.join(path, \"change_of_position.csv\")) plt.plot(x, cop, marker='o') plt.title(f\"Zależność średniej drogi swobodnej od ilości atomów, M", "import numpy import matplotlib.pyplot as plt def get_project_path(): return os.path.dirname(atoms_simulator.__file__) def get_path(path): i", "click.echo(\"Settings file already exists. Please delete it in order to generate a new", "-1, -1), label=\"Performing simulations:\", show_eta=False ) as progress: for i in progress: settings_ats['N']", "simulations:\", show_eta=False ) as progress: for i in progress: settings_ats['N'] = test_cases[i //", "[i for _ in range(settings_ats['R'])] for i in range(settings_ats[\"N_min\"], n_stop + 1, settings_ats[\"N_step\"])", "\"--graphics\", \"graphics\", help=\"Turn on pygame simulation\", is_flag=True) @click.option(\"--no-save\", \"no_save\", help=\"Disable saving the results", "od ilości atomów, M = {settings_ats['M']}\") plt.xlabel(\"Liczba atomów w pojemniku\") plt.ylabel(\"Liczba odbić atomu", "import atoms_simulator import numpy import matplotlib.pyplot as plt def get_project_path(): return os.path.dirname(atoms_simulator.__file__) def", "] bounce = numpy.empty((len(test_cases), settings_ats['R']), dtype=int) bounce_results = numpy.empty(len(test_cases), dtype=int) cop = numpy.empty((len(test_cases),", "module.\"\"\" pass @ats.command() def init(): \"\"\"Creates a settings_ats.toml file in the current directory.\"\"\"", "new settings file.\") return click.echo(\"Starting simulation...\") n_stop = settings_ats[\"N_min\"] + settings_ats[\"N_step\"] * (settings_ats[\"N_number\"]", "new configuration file.\") @ats.command() @click.option(\"-g\", \"--graphics\", \"graphics\", help=\"Turn on pygame simulation\", is_flag=True) @click.option(\"--no-save\",", "plt def get_project_path(): return os.path.dirname(atoms_simulator.__file__) def get_path(path): i = 1 while True: if", "settings file.\") return if settings_ats[\"N_step\"] is None: click.echo(\"The settings file is corrupted, please", "\"data_batch\", prompt=True, help=\"Name of the previously generated data batch.\") def plot(data_batch): \"\"\"Plots the", "i in progress: settings_ats['N'] = test_cases[i // settings_ats['R']][i % settings_ats['R']] try: bounce[i //", "= int(bounce[i // settings_ats['R']].mean()) cop_results[i // settings_ats['R']] = cop[i // settings_ats['R']].mean() if not", "pojemniku\") plt.ylabel(\"Średnia droga swobodna atomu czerwonego\") plt.grid(True) plt.savefig(os.path.join(target_path, \"change_of_position.png\")) plt.clf() settings_ats.save(os.path.join(target_path, \"used.toml\")) click.echo(\"Figures", "atomu czerownego\") plt.grid(True) plt.savefig(os.path.join(target_path, \"bounces.png\")) plt.clf() cop = numpy.loadtxt(os.path.join(path, \"change_of_position.csv\")) plt.plot(x, cop, marker='o')", "os.path.isfile(\"settings_ats.toml\"): source = os.path.join(get_project_path(), \"assets/settings_source.toml\") target = os.path.join(os.getcwd(), \"settings_ats.toml\") shutil.copy(source, target) click.echo(\"Settings file", "click.echo(\"Settings file generated successfully.\") else: click.echo(\"Settings file already exists. Please delete it in", "corrupted.\") return n_stop = settings_ats[\"N_min\"] + settings_ats[\"N_step\"] * (settings_ats[\"N_number\"] - 1) x =", "of the test.\", is_flag=True) def test(graphics, no_save): \"\"\"Performs a series of tests based", "\"figures_batch\")) os.mkdir(target_path) settings_ats = atoms_simulator.Settings(os.path.join(path, \"used.toml\")) if not (settings_ats.load() and os.path.isfile(os.path.join(path, \"bounces.csv\")) and", "label=\"Performing simulations:\", show_eta=False ) as progress: for i in progress: settings_ats['N'] = test_cases[i", ":= os.path.join(os.getcwd(), \"ats_results\")): os.mkdir(results_path) target_path = get_path(os.path.join(results_path, \"data_batch\")) os.mkdir(target_path) numpy.savetxt(os.path.join(target_path, \"bounces.csv\"), bounce_results) numpy.savetxt(os.path.join(target_path,", "it in order to generate a new configuration file.\") @ats.command() @click.option(\"-g\", \"--graphics\", \"graphics\",", "file is corrupted, please generate a new settings file.\") return if settings_ats[\"N_number\"] is", "os.path.join(os.getcwd(), \"ats_results\", data_batch)): click.echo( f\"The ats_results/{data_batch} catalog doesn't exist within the current working", "return if i % settings_ats['R'] == 0: bounce_results[i // settings_ats['R']] = int(bounce[i //", "range(len(test_cases) * settings_ats['R'] - 1, -1, -1), label=\"Performing simulations:\", show_eta=False ) as progress:", "plt.clf() cop = numpy.loadtxt(os.path.join(path, \"change_of_position.csv\")) plt.plot(x, cop, marker='o') plt.title(f\"Zależność średniej drogi swobodnej od", "if settings_ats[\"N_step\"] is None: click.echo(\"The settings file is corrupted, please generate a new", "n_stop + 1, settings_ats[\"N_step\"]) ] bounce = numpy.empty((len(test_cases), settings_ats['R']), dtype=int) bounce_results = numpy.empty(len(test_cases),", "to generate a new configuration file.\") @ats.command() @click.option(\"-g\", \"--graphics\", \"graphics\", help=\"Turn on pygame", "the results of the test.\", is_flag=True) def test(graphics, no_save): \"\"\"Performs a series of", "atoms_simulator.Settings(os.path.join(path, \"used.toml\")) if not (settings_ats.load() and os.path.isfile(os.path.join(path, \"bounces.csv\")) and os.path.isfile(os.path.join(path, \"change_of_position.csv\"))): click.echo(\"This data", "@click.option(\"--no-save\", \"no_save\", help=\"Disable saving the results of the test.\", is_flag=True) def test(graphics, no_save):", "{settings_ats['M']}\") plt.xlabel(\"Liczba atomów w pojemniku\") plt.ylabel(\"Średnia droga swobodna atomu czerwonego\") plt.grid(True) plt.savefig(os.path.join(target_path, \"change_of_position.png\"))", "if i % settings_ats['R'] == 0: bounce_results[i // settings_ats['R']] = int(bounce[i // settings_ats['R']].mean())", "some data first.\" ) return if not os.path.isdir(path := os.path.join(os.getcwd(), \"ats_results\", data_batch)): click.echo(", "drogi swobodnej od ilości atomów, M = {settings_ats['M']}\") plt.xlabel(\"Liczba atomów w pojemniku\") plt.ylabel(\"Średnia", "if settings_ats[\"R\"] is None: click.echo(\"The settings file is corrupted, please generate a new", "test_cases = [ [i for _ in range(settings_ats['R'])] for i in range(settings_ats[\"N_min\"], n_stop", "generate a new settings file.\") return click.echo(\"Starting simulation...\") n_stop = settings_ats[\"N_min\"] + settings_ats[\"N_step\"]", "1) # size = max([settings_ats['h'], settings_ats['w'], math.ceil((4 * (n_stop + 1)) ** 0.5)])", "return if settings_ats[\"N_min\"] is None: click.echo(\"The settings file is corrupted, please generate a", "return f\"{path}{i}\" i += 1 @click.group() def ats(): \"\"\"Allows to perform detailed tests", "settings_ats['R']] try: bounce[i // settings_ats['R']][i % settings_ats['R']], \\ cop[i // settings_ats['R']][i % settings_ats['R']]", "the previously generated data.\"\"\" if not os.path.isdir(results_path := os.path.join(os.getcwd(), \"ats_results\")): click.echo( \"The ats_results", "except ValueError as error: click.echo(f\"\\n{error} Please generate a new settings file.\") return if", "zderzeń od ilości atomów, M = {settings_ats['M']}\") plt.xlabel(\"Liczba atomów w pojemniku\") plt.ylabel(\"Liczba odbić", "return n_stop = settings_ats[\"N_min\"] + settings_ats[\"N_step\"] * (settings_ats[\"N_number\"] - 1) x = numpy.arange(settings_ats[\"N_min\"],", "range(settings_ats[\"N_min\"], n_stop + 1, settings_ats[\"N_step\"]) ] bounce = numpy.empty((len(test_cases), settings_ats['R']), dtype=int) bounce_results =", "as plt def get_project_path(): return os.path.dirname(atoms_simulator.__file__) def get_path(path): i = 1 while True:", "if not os.path.isfile(\"settings_ats.toml\"): source = os.path.join(get_project_path(), \"assets/settings_source.toml\") target = os.path.join(os.getcwd(), \"settings_ats.toml\") shutil.copy(source, target)", "\"\"\"Plots the previously generated data.\"\"\" if not os.path.isdir(results_path := os.path.join(os.getcwd(), \"ats_results\")): click.echo( \"The", "doesn't exist within the current working directory.\" ) return target_path = get_path(os.path.join(results_path, \"figures_batch\"))", "directory.\"\"\" if not os.path.isfile(\"settings_ats.toml\"): source = os.path.join(get_project_path(), \"assets/settings_source.toml\") target = os.path.join(os.getcwd(), \"settings_ats.toml\") shutil.copy(source,", "in progress: settings_ats['N'] = test_cases[i // settings_ats['R']][i % settings_ats['R']] try: bounce[i // settings_ats['R']][i", "@ats.command() def init(): \"\"\"Creates a settings_ats.toml file in the current directory.\"\"\" if not", "def ats(): \"\"\"Allows to perform detailed tests using atoms_simulator module.\"\"\" pass @ats.command() def", "= os.path.join(get_project_path(), \"assets/settings_source.toml\") target = os.path.join(os.getcwd(), \"settings_ats.toml\") shutil.copy(source, target) click.echo(\"Settings file generated successfully.\")", "(n_stop + 1)) ** 0.5)]) # settings_ats['h'] = size # settings_ats['w'] = size", "// settings_ats['R']].mean() if not no_save: if not os.path.isdir(results_path := os.path.join(os.getcwd(), \"ats_results\")): os.mkdir(results_path) target_path", "batch.\") def plot(data_batch): \"\"\"Plots the previously generated data.\"\"\" if not os.path.isdir(results_path := os.path.join(os.getcwd(),", "(settings_ats.load() and os.path.isfile(os.path.join(path, \"bounces.csv\")) and os.path.isfile(os.path.join(path, \"change_of_position.csv\"))): click.echo(\"This data batch is corrupted.\") return", "Please delete it in order to generate a new configuration file.\") @ats.command() @click.option(\"-g\",", "bounce, marker='o') plt.title(f\"Zależność liczby zderzeń od ilości atomów, M = {settings_ats['M']}\") plt.xlabel(\"Liczba atomów", "if not os.path.isdir(results_path := os.path.join(os.getcwd(), \"ats_results\")): click.echo( \"The ats_results catalog doesn't exist within", "numpy.empty((len(test_cases), settings_ats['R']), dtype=float) cop_results = numpy.empty(len(test_cases), dtype=float) settings_ats.new('N', settings_ats[\"N_min\"]) with click.progressbar( range(len(test_cases) *", "+ 1, settings_ats[\"N_step\"]) bounce = numpy.loadtxt(os.path.join(path, \"bounces.csv\")) plt.plot(x, bounce, marker='o') plt.title(f\"Zależność liczby zderzeń", "if not os.path.isdir(results_path := os.path.join(os.getcwd(), \"ats_results\")): os.mkdir(results_path) target_path = get_path(os.path.join(results_path, \"data_batch\")) os.mkdir(target_path) numpy.savetxt(os.path.join(target_path,", "settings_ats.load(): click.echo(\"No settings file detected. Generate the file first.\") return if settings_ats[\"N_min\"] is", "marker='o') plt.title(f\"Zależność średniej drogi swobodnej od ilości atomów, M = {settings_ats['M']}\") plt.xlabel(\"Liczba atomów", "= numpy.empty((len(test_cases), settings_ats['R']), dtype=float) cop_results = numpy.empty(len(test_cases), dtype=float) settings_ats.new('N', settings_ats[\"N_min\"]) with click.progressbar( range(len(test_cases)", "def get_path(path): i = 1 while True: if not os.path.lexists(f\"{path}{i}\"): return f\"{path}{i}\" i", "1, settings_ats[\"N_step\"]) ] bounce = numpy.empty((len(test_cases), settings_ats['R']), dtype=int) bounce_results = numpy.empty(len(test_cases), dtype=int) cop", "= size # settings_ats['w'] = size test_cases = [ [i for _ in", "os.path.isdir(path := os.path.join(os.getcwd(), \"ats_results\", data_batch)): click.echo( f\"The ats_results/{data_batch} catalog doesn't exist within the", "{settings_ats['M']}\") plt.xlabel(\"Liczba atomów w pojemniku\") plt.ylabel(\"Liczba odbić atomu czerownego\") plt.grid(True) plt.savefig(os.path.join(target_path, \"bounces.png\")) plt.clf()", "os.path.join(os.getcwd(), \"ats_results\")): os.mkdir(results_path) target_path = get_path(os.path.join(results_path, \"data_batch\")) os.mkdir(target_path) numpy.savetxt(os.path.join(target_path, \"bounces.csv\"), bounce_results) numpy.savetxt(os.path.join(target_path, \"change_of_position.csv\"),", "\"assets/settings_source.toml\") target = os.path.join(os.getcwd(), \"settings_ats.toml\") shutil.copy(source, target) click.echo(\"Settings file generated successfully.\") else: click.echo(\"Settings", "i in range(settings_ats[\"N_min\"], n_stop + 1, settings_ats[\"N_step\"]) ] bounce = numpy.empty((len(test_cases), settings_ats['R']), dtype=int)", "atomów w pojemniku\") plt.ylabel(\"Liczba odbić atomu czerownego\") plt.grid(True) plt.savefig(os.path.join(target_path, \"bounces.png\")) plt.clf() cop =", "progress: settings_ats['N'] = test_cases[i // settings_ats['R']][i % settings_ats['R']] try: bounce[i // settings_ats['R']][i %", "w pojemniku\") plt.ylabel(\"Liczba odbić atomu czerownego\") plt.grid(True) plt.savefig(os.path.join(target_path, \"bounces.png\")) plt.clf() cop = numpy.loadtxt(os.path.join(path,", "file.\") return click.echo(\"Starting simulation...\") n_stop = settings_ats[\"N_min\"] + settings_ats[\"N_step\"] * (settings_ats[\"N_number\"] - 1)", "import math import click import os.path import shutil import atoms_simulator import numpy import", "+ 1, settings_ats[\"N_step\"]) ] bounce = numpy.empty((len(test_cases), settings_ats['R']), dtype=int) bounce_results = numpy.empty(len(test_cases), dtype=int)", "exist within the current working directory.\" ) return target_path = get_path(os.path.join(results_path, \"figures_batch\")) os.mkdir(target_path)", "= get_path(os.path.join(results_path, \"figures_batch\")) os.mkdir(target_path) settings_ats = atoms_simulator.Settings(os.path.join(path, \"used.toml\")) if not (settings_ats.load() and os.path.isfile(os.path.join(path,", "def init(): \"\"\"Creates a settings_ats.toml file in the current directory.\"\"\" if not os.path.isfile(\"settings_ats.toml\"):", "\"used.toml\")) @ats.command() @click.option(\"-b\", \"--data_batch\", \"data_batch\", prompt=True, help=\"Name of the previously generated data batch.\")", "while True: if not os.path.lexists(f\"{path}{i}\"): return f\"{path}{i}\" i += 1 @click.group() def ats():", "numpy.empty((len(test_cases), settings_ats['R']), dtype=int) bounce_results = numpy.empty(len(test_cases), dtype=int) cop = numpy.empty((len(test_cases), settings_ats['R']), dtype=float) cop_results", "os.path.join(get_project_path(), \"assets/settings_source.toml\") target = os.path.join(os.getcwd(), \"settings_ats.toml\") shutil.copy(source, target) click.echo(\"Settings file generated successfully.\") else:", "is corrupted.\") return n_stop = settings_ats[\"N_min\"] + settings_ats[\"N_step\"] * (settings_ats[\"N_number\"] - 1) x", "and os.path.isfile(os.path.join(path, \"bounces.csv\")) and os.path.isfile(os.path.join(path, \"change_of_position.csv\"))): click.echo(\"This data batch is corrupted.\") return n_stop", "plt.grid(True) plt.savefig(os.path.join(target_path, \"bounces.png\")) plt.clf() cop = numpy.loadtxt(os.path.join(path, \"change_of_position.csv\")) plt.plot(x, cop, marker='o') plt.title(f\"Zależność średniej", "graphics) except ValueError as error: click.echo(f\"\\n{error} Please generate a new settings file.\") return", "the current working directory.\" ) return target_path = get_path(os.path.join(results_path, \"figures_batch\")) os.mkdir(target_path) settings_ats =", "plt.savefig(os.path.join(target_path, \"bounces.png\")) plt.clf() cop = numpy.loadtxt(os.path.join(path, \"change_of_position.csv\")) plt.plot(x, cop, marker='o') plt.title(f\"Zależność średniej drogi", "settings file.\") return if i % settings_ats['R'] == 0: bounce_results[i // settings_ats['R']] =", "get_path(path): i = 1 while True: if not os.path.lexists(f\"{path}{i}\"): return f\"{path}{i}\" i +=", "get_path(os.path.join(results_path, \"data_batch\")) os.mkdir(target_path) numpy.savetxt(os.path.join(target_path, \"bounces.csv\"), bounce_results) numpy.savetxt(os.path.join(target_path, \"change_of_position.csv\"), cop_results) settings_ats.save(target=os.path.join(target_path, \"used.toml\")) @ats.command() @click.option(\"-b\",", "od ilości atomów, M = {settings_ats['M']}\") plt.xlabel(\"Liczba atomów w pojemniku\") plt.ylabel(\"Średnia droga swobodna", "settings file is corrupted, please generate a new settings file.\") return if settings_ats[\"N_step\"]", "i += 1 @click.group() def ats(): \"\"\"Allows to perform detailed tests using atoms_simulator", "cop_results[i // settings_ats['R']] = cop[i // settings_ats['R']].mean() if not no_save: if not os.path.isdir(results_path", "settings file is corrupted, please generate a new settings file.\") return if settings_ats[\"R\"]", "of the previously generated data batch.\") def plot(data_batch): \"\"\"Plots the previously generated data.\"\"\"", "current working directory.\" ) return target_path = get_path(os.path.join(results_path, \"figures_batch\")) os.mkdir(target_path) settings_ats = atoms_simulator.Settings(os.path.join(path,", "plt.ylabel(\"Średnia droga swobodna atomu czerwonego\") plt.grid(True) plt.savefig(os.path.join(target_path, \"change_of_position.png\")) plt.clf() settings_ats.save(os.path.join(target_path, \"used.toml\")) click.echo(\"Figures created", "file.\") @ats.command() @click.option(\"-g\", \"--graphics\", \"graphics\", help=\"Turn on pygame simulation\", is_flag=True) @click.option(\"--no-save\", \"no_save\", help=\"Disable", "settings_ats[\"R\"] is None: click.echo(\"The settings file is corrupted, please generate a new settings", "not os.path.isdir(path := os.path.join(os.getcwd(), \"ats_results\", data_batch)): click.echo( f\"The ats_results/{data_batch} catalog doesn't exist within", "settings_ats[\"N_number\"] is None: click.echo(\"The settings file is corrupted, please generate a new settings", "file is corrupted, please generate a new settings file.\") return if settings_ats[\"R\"] is", "M = {settings_ats['M']}\") plt.xlabel(\"Liczba atomów w pojemniku\") plt.ylabel(\"Średnia droga swobodna atomu czerwonego\") plt.grid(True)", "atomów, M = {settings_ats['M']}\") plt.xlabel(\"Liczba atomów w pojemniku\") plt.ylabel(\"Średnia droga swobodna atomu czerwonego\")", "tests based on the data in the settings_ats.toml file.\"\"\" settings_ats = atoms_simulator.Settings(\"settings_ats.toml\") if", "średniej drogi swobodnej od ilości atomów, M = {settings_ats['M']}\") plt.xlabel(\"Liczba atomów w pojemniku\")", "a new settings file.\") return if settings_ats[\"R\"] is None: click.echo(\"The settings file is", "detected. Generate the file first.\") return if settings_ats[\"N_min\"] is None: click.echo(\"The settings file", "-1), label=\"Performing simulations:\", show_eta=False ) as progress: for i in progress: settings_ats['N'] =", "source = os.path.join(get_project_path(), \"assets/settings_source.toml\") target = os.path.join(os.getcwd(), \"settings_ats.toml\") shutil.copy(source, target) click.echo(\"Settings file generated", "directory.\" ) return target_path = get_path(os.path.join(results_path, \"figures_batch\")) os.mkdir(target_path) settings_ats = atoms_simulator.Settings(os.path.join(path, \"used.toml\")) if", "os.mkdir(target_path) settings_ats = atoms_simulator.Settings(os.path.join(path, \"used.toml\")) if not (settings_ats.load() and os.path.isfile(os.path.join(path, \"bounces.csv\")) and os.path.isfile(os.path.join(path,", "click.echo(\"No settings file detected. Generate the file first.\") return if settings_ats[\"N_min\"] is None:", "import click import os.path import shutil import atoms_simulator import numpy import matplotlib.pyplot as", "current directory.\"\"\" if not os.path.isfile(\"settings_ats.toml\"): source = os.path.join(get_project_path(), \"assets/settings_source.toml\") target = os.path.join(os.getcwd(), \"settings_ats.toml\")", "return os.path.dirname(atoms_simulator.__file__) def get_path(path): i = 1 while True: if not os.path.lexists(f\"{path}{i}\"): return", "settings_ats['R']][i % settings_ats['R']], \\ cop[i // settings_ats['R']][i % settings_ats['R']] = atoms_simulator.simulate(settings_ats, graphics) except", "return target_path = get_path(os.path.join(results_path, \"figures_batch\")) os.mkdir(target_path) settings_ats = atoms_simulator.Settings(os.path.join(path, \"used.toml\")) if not (settings_ats.load()", "tests using atoms_simulator module.\"\"\" pass @ats.command() def init(): \"\"\"Creates a settings_ats.toml file in", "if not os.path.isdir(path := os.path.join(os.getcwd(), \"ats_results\", data_batch)): click.echo( f\"The ats_results/{data_batch} catalog doesn't exist", "settings file.\") return if settings_ats[\"N_number\"] is None: click.echo(\"The settings file is corrupted, please", "settings_ats['N'] = test_cases[i // settings_ats['R']][i % settings_ats['R']] try: bounce[i // settings_ats['R']][i % settings_ats['R']],", "\"\"\"Performs a series of tests based on the data in the settings_ats.toml file.\"\"\"", "os.path.isfile(os.path.join(path, \"bounces.csv\")) and os.path.isfile(os.path.join(path, \"change_of_position.csv\"))): click.echo(\"This data batch is corrupted.\") return n_stop =", "\"graphics\", help=\"Turn on pygame simulation\", is_flag=True) @click.option(\"--no-save\", \"no_save\", help=\"Disable saving the results of", "settings_ats.save(target=os.path.join(target_path, \"used.toml\")) @ats.command() @click.option(\"-b\", \"--data_batch\", \"data_batch\", prompt=True, help=\"Name of the previously generated data", "for i in progress: settings_ats['N'] = test_cases[i // settings_ats['R']][i % settings_ats['R']] try: bounce[i", "settings_ats[\"N_step\"] * (settings_ats[\"N_number\"] - 1) # size = max([settings_ats['h'], settings_ats['w'], math.ceil((4 * (n_stop", "atomów, M = {settings_ats['M']}\") plt.xlabel(\"Liczba atomów w pojemniku\") plt.ylabel(\"Liczba odbić atomu czerownego\") plt.grid(True)", "bounce = numpy.empty((len(test_cases), settings_ats['R']), dtype=int) bounce_results = numpy.empty(len(test_cases), dtype=int) cop = numpy.empty((len(test_cases), settings_ats['R']),", "(settings_ats[\"N_number\"] - 1) # size = max([settings_ats['h'], settings_ats['w'], math.ceil((4 * (n_stop + 1))", "catalog doesn't exist within the current working directory. Generate some data first.\" )", "numpy.savetxt(os.path.join(target_path, \"bounces.csv\"), bounce_results) numpy.savetxt(os.path.join(target_path, \"change_of_position.csv\"), cop_results) settings_ats.save(target=os.path.join(target_path, \"used.toml\")) @ats.command() @click.option(\"-b\", \"--data_batch\", \"data_batch\", prompt=True,", "- 1) x = numpy.arange(settings_ats[\"N_min\"], n_stop + 1, settings_ats[\"N_step\"]) bounce = numpy.loadtxt(os.path.join(path, \"bounces.csv\"))", "matplotlib.pyplot as plt def get_project_path(): return os.path.dirname(atoms_simulator.__file__) def get_path(path): i = 1 while", "size = max([settings_ats['h'], settings_ats['w'], math.ceil((4 * (n_stop + 1)) ** 0.5)]) # settings_ats['h']", "target_path = get_path(os.path.join(results_path, \"data_batch\")) os.mkdir(target_path) numpy.savetxt(os.path.join(target_path, \"bounces.csv\"), bounce_results) numpy.savetxt(os.path.join(target_path, \"change_of_position.csv\"), cop_results) settings_ats.save(target=os.path.join(target_path, \"used.toml\"))", "= atoms_simulator.simulate(settings_ats, graphics) except ValueError as error: click.echo(f\"\\n{error} Please generate a new settings", "os.path.dirname(atoms_simulator.__file__) def get_path(path): i = 1 while True: if not os.path.lexists(f\"{path}{i}\"): return f\"{path}{i}\"", "a new settings file.\") return if settings_ats[\"N_number\"] is None: click.echo(\"The settings file is", ") as progress: for i in progress: settings_ats['N'] = test_cases[i // settings_ats['R']][i %", "@ats.command() @click.option(\"-b\", \"--data_batch\", \"data_batch\", prompt=True, help=\"Name of the previously generated data batch.\") def", "a new settings file.\") return if i % settings_ats['R'] == 0: bounce_results[i //", "\"--data_batch\", \"data_batch\", prompt=True, help=\"Name of the previously generated data batch.\") def plot(data_batch): \"\"\"Plots", "max([settings_ats['h'], settings_ats['w'], math.ceil((4 * (n_stop + 1)) ** 0.5)]) # settings_ats['h'] = size", "settings_ats['R']], \\ cop[i // settings_ats['R']][i % settings_ats['R']] = atoms_simulator.simulate(settings_ats, graphics) except ValueError as", "try: bounce[i // settings_ats['R']][i % settings_ats['R']], \\ cop[i // settings_ats['R']][i % settings_ats['R']] =", "if not os.path.lexists(f\"{path}{i}\"): return f\"{path}{i}\" i += 1 @click.group() def ats(): \"\"\"Allows to", "get_project_path(): return os.path.dirname(atoms_simulator.__file__) def get_path(path): i = 1 while True: if not os.path.lexists(f\"{path}{i}\"):", "in range(settings_ats['R'])] for i in range(settings_ats[\"N_min\"], n_stop + 1, settings_ats[\"N_step\"]) ] bounce =", "please generate a new settings file.\") return if settings_ats[\"R\"] is None: click.echo(\"The settings", "data batch.\") def plot(data_batch): \"\"\"Plots the previously generated data.\"\"\" if not os.path.isdir(results_path :=", "atoms_simulator module.\"\"\" pass @ats.command() def init(): \"\"\"Creates a settings_ats.toml file in the current", "data.\"\"\" if not os.path.isdir(results_path := os.path.join(os.getcwd(), \"ats_results\")): click.echo( \"The ats_results catalog doesn't exist", "click.progressbar( range(len(test_cases) * settings_ats['R'] - 1, -1, -1), label=\"Performing simulations:\", show_eta=False ) as", "to perform detailed tests using atoms_simulator module.\"\"\" pass @ats.command() def init(): \"\"\"Creates a", "for i in range(settings_ats[\"N_min\"], n_stop + 1, settings_ats[\"N_step\"]) ] bounce = numpy.empty((len(test_cases), settings_ats['R']),", "== 0: bounce_results[i // settings_ats['R']] = int(bounce[i // settings_ats['R']].mean()) cop_results[i // settings_ats['R']] =", "def plot(data_batch): \"\"\"Plots the previously generated data.\"\"\" if not os.path.isdir(results_path := os.path.join(os.getcwd(), \"ats_results\")):", "math.ceil((4 * (n_stop + 1)) ** 0.5)]) # settings_ats['h'] = size # settings_ats['w']", "M = {settings_ats['M']}\") plt.xlabel(\"Liczba atomów w pojemniku\") plt.ylabel(\"Liczba odbić atomu czerownego\") plt.grid(True) plt.savefig(os.path.join(target_path,", "cop_results) settings_ats.save(target=os.path.join(target_path, \"used.toml\")) @ats.command() @click.option(\"-b\", \"--data_batch\", \"data_batch\", prompt=True, help=\"Name of the previously generated", "Please generate a new settings file.\") return if i % settings_ats['R'] == 0:", "ats_results catalog doesn't exist within the current working directory. Generate some data first.\"", "= os.path.join(os.getcwd(), \"settings_ats.toml\") shutil.copy(source, target) click.echo(\"Settings file generated successfully.\") else: click.echo(\"Settings file already", "@click.option(\"-g\", \"--graphics\", \"graphics\", help=\"Turn on pygame simulation\", is_flag=True) @click.option(\"--no-save\", \"no_save\", help=\"Disable saving the", "not os.path.isdir(results_path := os.path.join(os.getcwd(), \"ats_results\")): os.mkdir(results_path) target_path = get_path(os.path.join(results_path, \"data_batch\")) os.mkdir(target_path) numpy.savetxt(os.path.join(target_path, \"bounces.csv\"),", "series of tests based on the data in the settings_ats.toml file.\"\"\" settings_ats =", "bounce_results = numpy.empty(len(test_cases), dtype=int) cop = numpy.empty((len(test_cases), settings_ats['R']), dtype=float) cop_results = numpy.empty(len(test_cases), dtype=float)", "w pojemniku\") plt.ylabel(\"Średnia droga swobodna atomu czerwonego\") plt.grid(True) plt.savefig(os.path.join(target_path, \"change_of_position.png\")) plt.clf() settings_ats.save(os.path.join(target_path, \"used.toml\"))", "in the current directory.\"\"\" if not os.path.isfile(\"settings_ats.toml\"): source = os.path.join(get_project_path(), \"assets/settings_source.toml\") target =", "in range(settings_ats[\"N_min\"], n_stop + 1, settings_ats[\"N_step\"]) ] bounce = numpy.empty((len(test_cases), settings_ats['R']), dtype=int) bounce_results", "and os.path.isfile(os.path.join(path, \"change_of_position.csv\"))): click.echo(\"This data batch is corrupted.\") return n_stop = settings_ats[\"N_min\"] +", "\"bounces.csv\")) plt.plot(x, bounce, marker='o') plt.title(f\"Zależność liczby zderzeń od ilości atomów, M = {settings_ats['M']}\")", "size # settings_ats['w'] = size test_cases = [ [i for _ in range(settings_ats['R'])]", "os.path.lexists(f\"{path}{i}\"): return f\"{path}{i}\" i += 1 @click.group() def ats(): \"\"\"Allows to perform detailed", "settings_ats.toml file.\"\"\" settings_ats = atoms_simulator.Settings(\"settings_ats.toml\") if not settings_ats.load(): click.echo(\"No settings file detected. Generate", "please generate a new settings file.\") return click.echo(\"Starting simulation...\") n_stop = settings_ats[\"N_min\"] +", "= atoms_simulator.Settings(os.path.join(path, \"used.toml\")) if not (settings_ats.load() and os.path.isfile(os.path.join(path, \"bounces.csv\")) and os.path.isfile(os.path.join(path, \"change_of_position.csv\"))): click.echo(\"This", "atoms_simulator.simulate(settings_ats, graphics) except ValueError as error: click.echo(f\"\\n{error} Please generate a new settings file.\")", "Generate the file first.\") return if settings_ats[\"N_min\"] is None: click.echo(\"The settings file is", "shutil import atoms_simulator import numpy import matplotlib.pyplot as plt def get_project_path(): return os.path.dirname(atoms_simulator.__file__)", "previously generated data batch.\") def plot(data_batch): \"\"\"Plots the previously generated data.\"\"\" if not", "n_stop + 1, settings_ats[\"N_step\"]) bounce = numpy.loadtxt(os.path.join(path, \"bounces.csv\")) plt.plot(x, bounce, marker='o') plt.title(f\"Zależność liczby", "\"bounces.png\")) plt.clf() cop = numpy.loadtxt(os.path.join(path, \"change_of_position.csv\")) plt.plot(x, cop, marker='o') plt.title(f\"Zależność średniej drogi swobodnej", "dtype=int) cop = numpy.empty((len(test_cases), settings_ats['R']), dtype=float) cop_results = numpy.empty(len(test_cases), dtype=float) settings_ats.new('N', settings_ats[\"N_min\"]) with", "* (settings_ats[\"N_number\"] - 1) # size = max([settings_ats['h'], settings_ats['w'], math.ceil((4 * (n_stop +", "numpy.empty(len(test_cases), dtype=int) cop = numpy.empty((len(test_cases), settings_ats['R']), dtype=float) cop_results = numpy.empty(len(test_cases), dtype=float) settings_ats.new('N', settings_ats[\"N_min\"])", "on pygame simulation\", is_flag=True) @click.option(\"--no-save\", \"no_save\", help=\"Disable saving the results of the test.\",", "_ in range(settings_ats['R'])] for i in range(settings_ats[\"N_min\"], n_stop + 1, settings_ats[\"N_step\"]) ] bounce", "progress: for i in progress: settings_ats['N'] = test_cases[i // settings_ats['R']][i % settings_ats['R']] try:", "data first.\" ) return if not os.path.isdir(path := os.path.join(os.getcwd(), \"ats_results\", data_batch)): click.echo( f\"The", "no_save): \"\"\"Performs a series of tests based on the data in the settings_ats.toml", "\"\"\"Allows to perform detailed tests using atoms_simulator module.\"\"\" pass @ats.command() def init(): \"\"\"Creates", "successfully.\") else: click.echo(\"Settings file already exists. Please delete it in order to generate", "click.echo( f\"The ats_results/{data_batch} catalog doesn't exist within the current working directory.\" ) return", "generate a new configuration file.\") @ats.command() @click.option(\"-g\", \"--graphics\", \"graphics\", help=\"Turn on pygame simulation\",", "dtype=int) bounce_results = numpy.empty(len(test_cases), dtype=int) cop = numpy.empty((len(test_cases), settings_ats['R']), dtype=float) cop_results = numpy.empty(len(test_cases),", "is_flag=True) @click.option(\"--no-save\", \"no_save\", help=\"Disable saving the results of the test.\", is_flag=True) def test(graphics,", "0: bounce_results[i // settings_ats['R']] = int(bounce[i // settings_ats['R']].mean()) cop_results[i // settings_ats['R']] = cop[i", "corrupted, please generate a new settings file.\") return if settings_ats[\"R\"] is None: click.echo(\"The", "cop[i // settings_ats['R']].mean() if not no_save: if not os.path.isdir(results_path := os.path.join(os.getcwd(), \"ats_results\")): os.mkdir(results_path)", "settings_ats['R']] = cop[i // settings_ats['R']].mean() if not no_save: if not os.path.isdir(results_path := os.path.join(os.getcwd(),", "init(): \"\"\"Creates a settings_ats.toml file in the current directory.\"\"\" if not os.path.isfile(\"settings_ats.toml\"): source", "if not no_save: if not os.path.isdir(results_path := os.path.join(os.getcwd(), \"ats_results\")): os.mkdir(results_path) target_path = get_path(os.path.join(results_path,", "\"change_of_position.csv\"))): click.echo(\"This data batch is corrupted.\") return n_stop = settings_ats[\"N_min\"] + settings_ats[\"N_step\"] *", "file.\"\"\" settings_ats = atoms_simulator.Settings(\"settings_ats.toml\") if not settings_ats.load(): click.echo(\"No settings file detected. Generate the", "pygame simulation\", is_flag=True) @click.option(\"--no-save\", \"no_save\", help=\"Disable saving the results of the test.\", is_flag=True)", "if settings_ats[\"N_number\"] is None: click.echo(\"The settings file is corrupted, please generate a new", "marker='o') plt.title(f\"Zależność liczby zderzeń od ilości atomów, M = {settings_ats['M']}\") plt.xlabel(\"Liczba atomów w", "new settings file.\") return if settings_ats[\"R\"] is None: click.echo(\"The settings file is corrupted,", "the data in the settings_ats.toml file.\"\"\" settings_ats = atoms_simulator.Settings(\"settings_ats.toml\") if not settings_ats.load(): click.echo(\"No", "if settings_ats[\"N_min\"] is None: click.echo(\"The settings file is corrupted, please generate a new", "bounce = numpy.loadtxt(os.path.join(path, \"bounces.csv\")) plt.plot(x, bounce, marker='o') plt.title(f\"Zależność liczby zderzeń od ilości atomów,", "a settings_ats.toml file in the current directory.\"\"\" if not os.path.isfile(\"settings_ats.toml\"): source = os.path.join(get_project_path(),", "= {settings_ats['M']}\") plt.xlabel(\"Liczba atomów w pojemniku\") plt.ylabel(\"Średnia droga swobodna atomu czerwonego\") plt.grid(True) plt.savefig(os.path.join(target_path,", "@ats.command() @click.option(\"-g\", \"--graphics\", \"graphics\", help=\"Turn on pygame simulation\", is_flag=True) @click.option(\"--no-save\", \"no_save\", help=\"Disable saving", "settings_ats = atoms_simulator.Settings(os.path.join(path, \"used.toml\")) if not (settings_ats.load() and os.path.isfile(os.path.join(path, \"bounces.csv\")) and os.path.isfile(os.path.join(path, \"change_of_position.csv\"))):", "\"settings_ats.toml\") shutil.copy(source, target) click.echo(\"Settings file generated successfully.\") else: click.echo(\"Settings file already exists. Please", "within the current working directory.\" ) return target_path = get_path(os.path.join(results_path, \"figures_batch\")) os.mkdir(target_path) settings_ats", "settings_ats = atoms_simulator.Settings(\"settings_ats.toml\") if not settings_ats.load(): click.echo(\"No settings file detected. Generate the file", "= numpy.empty(len(test_cases), dtype=int) cop = numpy.empty((len(test_cases), settings_ats['R']), dtype=float) cop_results = numpy.empty(len(test_cases), dtype=float) settings_ats.new('N',", "catalog doesn't exist within the current working directory.\" ) return target_path = get_path(os.path.join(results_path,", "settings_ats[\"N_step\"]) ] bounce = numpy.empty((len(test_cases), settings_ats['R']), dtype=int) bounce_results = numpy.empty(len(test_cases), dtype=int) cop =", "settings_ats['R']] = int(bounce[i // settings_ats['R']].mean()) cop_results[i // settings_ats['R']] = cop[i // settings_ats['R']].mean() if", "doesn't exist within the current working directory. Generate some data first.\" ) return", "file.\") return if settings_ats[\"R\"] is None: click.echo(\"The settings file is corrupted, please generate", "not no_save: if not os.path.isdir(results_path := os.path.join(os.getcwd(), \"ats_results\")): os.mkdir(results_path) target_path = get_path(os.path.join(results_path, \"data_batch\"))", "target = os.path.join(os.getcwd(), \"settings_ats.toml\") shutil.copy(source, target) click.echo(\"Settings file generated successfully.\") else: click.echo(\"Settings file", "x = numpy.arange(settings_ats[\"N_min\"], n_stop + 1, settings_ats[\"N_step\"]) bounce = numpy.loadtxt(os.path.join(path, \"bounces.csv\")) plt.plot(x, bounce,", "else: click.echo(\"Settings file already exists. Please delete it in order to generate a", "os.mkdir(target_path) numpy.savetxt(os.path.join(target_path, \"bounces.csv\"), bounce_results) numpy.savetxt(os.path.join(target_path, \"change_of_position.csv\"), cop_results) settings_ats.save(target=os.path.join(target_path, \"used.toml\")) @ats.command() @click.option(\"-b\", \"--data_batch\", \"data_batch\",", "= test_cases[i // settings_ats['R']][i % settings_ats['R']] try: bounce[i // settings_ats['R']][i % settings_ats['R']], \\", "1, settings_ats[\"N_step\"]) bounce = numpy.loadtxt(os.path.join(path, \"bounces.csv\")) plt.plot(x, bounce, marker='o') plt.title(f\"Zależność liczby zderzeń od", "configuration file.\") @ats.command() @click.option(\"-g\", \"--graphics\", \"graphics\", help=\"Turn on pygame simulation\", is_flag=True) @click.option(\"--no-save\", \"no_save\",", "= [ [i for _ in range(settings_ats['R'])] for i in range(settings_ats[\"N_min\"], n_stop +", "settings_ats[\"N_step\"] is None: click.echo(\"The settings file is corrupted, please generate a new settings", "settings_ats['R']][i % settings_ats['R']] = atoms_simulator.simulate(settings_ats, graphics) except ValueError as error: click.echo(f\"\\n{error} Please generate", "+ settings_ats[\"N_step\"] * (settings_ats[\"N_number\"] - 1) # size = max([settings_ats['h'], settings_ats['w'], math.ceil((4 *", "\"change_of_position.csv\"), cop_results) settings_ats.save(target=os.path.join(target_path, \"used.toml\")) @ats.command() @click.option(\"-b\", \"--data_batch\", \"data_batch\", prompt=True, help=\"Name of the previously", "odbić atomu czerownego\") plt.grid(True) plt.savefig(os.path.join(target_path, \"bounces.png\")) plt.clf() cop = numpy.loadtxt(os.path.join(path, \"change_of_position.csv\")) plt.plot(x, cop,", "// settings_ats['R']][i % settings_ats['R']] = atoms_simulator.simulate(settings_ats, graphics) except ValueError as error: click.echo(f\"\\n{error} Please", "= numpy.loadtxt(os.path.join(path, \"bounces.csv\")) plt.plot(x, bounce, marker='o') plt.title(f\"Zależność liczby zderzeń od ilości atomów, M", "in order to generate a new configuration file.\") @ats.command() @click.option(\"-g\", \"--graphics\", \"graphics\", help=\"Turn", "plt.ylabel(\"Liczba odbić atomu czerownego\") plt.grid(True) plt.savefig(os.path.join(target_path, \"bounces.png\")) plt.clf() cop = numpy.loadtxt(os.path.join(path, \"change_of_position.csv\")) plt.plot(x,", "generated data.\"\"\" if not os.path.isdir(results_path := os.path.join(os.getcwd(), \"ats_results\")): click.echo( \"The ats_results catalog doesn't", "pass @ats.command() def init(): \"\"\"Creates a settings_ats.toml file in the current directory.\"\"\" if", "first.\") return if settings_ats[\"N_min\"] is None: click.echo(\"The settings file is corrupted, please generate", "no_save: if not os.path.isdir(results_path := os.path.join(os.getcwd(), \"ats_results\")): os.mkdir(results_path) target_path = get_path(os.path.join(results_path, \"data_batch\")) os.mkdir(target_path)", "@click.option(\"-b\", \"--data_batch\", \"data_batch\", prompt=True, help=\"Name of the previously generated data batch.\") def plot(data_batch):", "is corrupted, please generate a new settings file.\") return click.echo(\"Starting simulation...\") n_stop =", "- 1, -1, -1), label=\"Performing simulations:\", show_eta=False ) as progress: for i in", "detailed tests using atoms_simulator module.\"\"\" pass @ats.command() def init(): \"\"\"Creates a settings_ats.toml file", "settings_ats[\"N_min\"]) with click.progressbar( range(len(test_cases) * settings_ats['R'] - 1, -1, -1), label=\"Performing simulations:\", show_eta=False", "settings file.\") return click.echo(\"Starting simulation...\") n_stop = settings_ats[\"N_min\"] + settings_ats[\"N_step\"] * (settings_ats[\"N_number\"] -", "numpy.savetxt(os.path.join(target_path, \"change_of_position.csv\"), cop_results) settings_ats.save(target=os.path.join(target_path, \"used.toml\")) @ats.command() @click.option(\"-b\", \"--data_batch\", \"data_batch\", prompt=True, help=\"Name of the", "+ 1)) ** 0.5)]) # settings_ats['h'] = size # settings_ats['w'] = size test_cases", "click.echo(\"The settings file is corrupted, please generate a new settings file.\") return if", "corrupted, please generate a new settings file.\") return click.echo(\"Starting simulation...\") n_stop = settings_ats[\"N_min\"]", "delete it in order to generate a new configuration file.\") @ats.command() @click.option(\"-g\", \"--graphics\",", "= numpy.arange(settings_ats[\"N_min\"], n_stop + 1, settings_ats[\"N_step\"]) bounce = numpy.loadtxt(os.path.join(path, \"bounces.csv\")) plt.plot(x, bounce, marker='o')", "# size = max([settings_ats['h'], settings_ats['w'], math.ceil((4 * (n_stop + 1)) ** 0.5)]) #", "settings file is corrupted, please generate a new settings file.\") return if settings_ats[\"N_number\"]", "file is corrupted, please generate a new settings file.\") return click.echo(\"Starting simulation...\") n_stop", "size test_cases = [ [i for _ in range(settings_ats['R'])] for i in range(settings_ats[\"N_min\"],", "+= 1 @click.group() def ats(): \"\"\"Allows to perform detailed tests using atoms_simulator module.\"\"\"", "czerownego\") plt.grid(True) plt.savefig(os.path.join(target_path, \"bounces.png\")) plt.clf() cop = numpy.loadtxt(os.path.join(path, \"change_of_position.csv\")) plt.plot(x, cop, marker='o') plt.title(f\"Zależność", "settings_ats['R']] = atoms_simulator.simulate(settings_ats, graphics) except ValueError as error: click.echo(f\"\\n{error} Please generate a new", "// settings_ats['R']][i % settings_ats['R']], \\ cop[i // settings_ats['R']][i % settings_ats['R']] = atoms_simulator.simulate(settings_ats, graphics)", "= numpy.empty(len(test_cases), dtype=float) settings_ats.new('N', settings_ats[\"N_min\"]) with click.progressbar( range(len(test_cases) * settings_ats['R'] - 1, -1,", "settings_ats['R']), dtype=float) cop_results = numpy.empty(len(test_cases), dtype=float) settings_ats.new('N', settings_ats[\"N_min\"]) with click.progressbar( range(len(test_cases) * settings_ats['R']", "def test(graphics, no_save): \"\"\"Performs a series of tests based on the data in", "generate a new settings file.\") return if settings_ats[\"N_number\"] is None: click.echo(\"The settings file", "ilości atomów, M = {settings_ats['M']}\") plt.xlabel(\"Liczba atomów w pojemniku\") plt.ylabel(\"Liczba odbić atomu czerownego\")", "results of the test.\", is_flag=True) def test(graphics, no_save): \"\"\"Performs a series of tests", "click.echo(\"The settings file is corrupted, please generate a new settings file.\") return click.echo(\"Starting", "previously generated data.\"\"\" if not os.path.isdir(results_path := os.path.join(os.getcwd(), \"ats_results\")): click.echo( \"The ats_results catalog", "target_path = get_path(os.path.join(results_path, \"figures_batch\")) os.mkdir(target_path) settings_ats = atoms_simulator.Settings(os.path.join(path, \"used.toml\")) if not (settings_ats.load() and", "settings_ats['R']), dtype=int) bounce_results = numpy.empty(len(test_cases), dtype=int) cop = numpy.empty((len(test_cases), settings_ats['R']), dtype=float) cop_results =", "1)) ** 0.5)]) # settings_ats['h'] = size # settings_ats['w'] = size test_cases =", "cop[i // settings_ats['R']][i % settings_ats['R']] = atoms_simulator.simulate(settings_ats, graphics) except ValueError as error: click.echo(f\"\\n{error}", "error: click.echo(f\"\\n{error} Please generate a new settings file.\") return if i % settings_ats['R']", "= size test_cases = [ [i for _ in range(settings_ats['R'])] for i in", "in the settings_ats.toml file.\"\"\" settings_ats = atoms_simulator.Settings(\"settings_ats.toml\") if not settings_ats.load(): click.echo(\"No settings file", "the settings_ats.toml file.\"\"\" settings_ats = atoms_simulator.Settings(\"settings_ats.toml\") if not settings_ats.load(): click.echo(\"No settings file detected.", "directory. Generate some data first.\" ) return if not os.path.isdir(path := os.path.join(os.getcwd(), \"ats_results\",", "= numpy.loadtxt(os.path.join(path, \"change_of_position.csv\")) plt.plot(x, cop, marker='o') plt.title(f\"Zależność średniej drogi swobodnej od ilości atomów,", "\"used.toml\")) if not (settings_ats.load() and os.path.isfile(os.path.join(path, \"bounces.csv\")) and os.path.isfile(os.path.join(path, \"change_of_position.csv\"))): click.echo(\"This data batch", "= get_path(os.path.join(results_path, \"data_batch\")) os.mkdir(target_path) numpy.savetxt(os.path.join(target_path, \"bounces.csv\"), bounce_results) numpy.savetxt(os.path.join(target_path, \"change_of_position.csv\"), cop_results) settings_ats.save(target=os.path.join(target_path, \"used.toml\")) @ats.command()", "import shutil import atoms_simulator import numpy import matplotlib.pyplot as plt def get_project_path(): return", "+ settings_ats[\"N_step\"] * (settings_ats[\"N_number\"] - 1) x = numpy.arange(settings_ats[\"N_min\"], n_stop + 1, settings_ats[\"N_step\"])", "settings_ats['w'], math.ceil((4 * (n_stop + 1)) ** 0.5)]) # settings_ats['h'] = size #", "click.echo(\"Starting simulation...\") n_stop = settings_ats[\"N_min\"] + settings_ats[\"N_step\"] * (settings_ats[\"N_number\"] - 1) # size", "bounce[i // settings_ats['R']][i % settings_ats['R']], \\ cop[i // settings_ats['R']][i % settings_ats['R']] = atoms_simulator.simulate(settings_ats,", "* (settings_ats[\"N_number\"] - 1) x = numpy.arange(settings_ats[\"N_min\"], n_stop + 1, settings_ats[\"N_step\"]) bounce =", "working directory.\" ) return target_path = get_path(os.path.join(results_path, \"figures_batch\")) os.mkdir(target_path) settings_ats = atoms_simulator.Settings(os.path.join(path, \"used.toml\"))", "range(settings_ats['R'])] for i in range(settings_ats[\"N_min\"], n_stop + 1, settings_ats[\"N_step\"]) ] bounce = numpy.empty((len(test_cases),", "test.\", is_flag=True) def test(graphics, no_save): \"\"\"Performs a series of tests based on the", "file.\") return if i % settings_ats['R'] == 0: bounce_results[i // settings_ats['R']] = int(bounce[i", "file detected. Generate the file first.\") return if settings_ats[\"N_min\"] is None: click.echo(\"The settings", "0.5)]) # settings_ats['h'] = size # settings_ats['w'] = size test_cases = [ [i", "simulation...\") n_stop = settings_ats[\"N_min\"] + settings_ats[\"N_step\"] * (settings_ats[\"N_number\"] - 1) # size =", "generated successfully.\") else: click.echo(\"Settings file already exists. Please delete it in order to", "data batch is corrupted.\") return n_stop = settings_ats[\"N_min\"] + settings_ats[\"N_step\"] * (settings_ats[\"N_number\"] -", "os.path.join(os.getcwd(), \"settings_ats.toml\") shutil.copy(source, target) click.echo(\"Settings file generated successfully.\") else: click.echo(\"Settings file already exists.", "generate a new settings file.\") return if settings_ats[\"R\"] is None: click.echo(\"The settings file", "// settings_ats['R']][i % settings_ats['R']] try: bounce[i // settings_ats['R']][i % settings_ats['R']], \\ cop[i //", "file is corrupted, please generate a new settings file.\") return if settings_ats[\"N_step\"] is", "not os.path.isfile(\"settings_ats.toml\"): source = os.path.join(get_project_path(), \"assets/settings_source.toml\") target = os.path.join(os.getcwd(), \"settings_ats.toml\") shutil.copy(source, target) click.echo(\"Settings", "settings file is corrupted, please generate a new settings file.\") return click.echo(\"Starting simulation...\")", "click.echo(f\"\\n{error} Please generate a new settings file.\") return if i % settings_ats['R'] ==", "= max([settings_ats['h'], settings_ats['w'], math.ceil((4 * (n_stop + 1)) ** 0.5)]) # settings_ats['h'] =", "cop = numpy.loadtxt(os.path.join(path, \"change_of_position.csv\")) plt.plot(x, cop, marker='o') plt.title(f\"Zależność średniej drogi swobodnej od ilości", "the current working directory. Generate some data first.\" ) return if not os.path.isdir(path", "settings_ats['h'] = size # settings_ats['w'] = size test_cases = [ [i for _", "= 1 while True: if not os.path.lexists(f\"{path}{i}\"): return f\"{path}{i}\" i += 1 @click.group()", "if not settings_ats.load(): click.echo(\"No settings file detected. Generate the file first.\") return if", "None: click.echo(\"The settings file is corrupted, please generate a new settings file.\") return", "os.path.isdir(results_path := os.path.join(os.getcwd(), \"ats_results\")): os.mkdir(results_path) target_path = get_path(os.path.join(results_path, \"data_batch\")) os.mkdir(target_path) numpy.savetxt(os.path.join(target_path, \"bounces.csv\"), bounce_results)", "settings_ats.toml file in the current directory.\"\"\" if not os.path.isfile(\"settings_ats.toml\"): source = os.path.join(get_project_path(), \"assets/settings_source.toml\")", "based on the data in the settings_ats.toml file.\"\"\" settings_ats = atoms_simulator.Settings(\"settings_ats.toml\") if not", "a new settings file.\") return if settings_ats[\"N_step\"] is None: click.echo(\"The settings file is", "// settings_ats['R']].mean()) cop_results[i // settings_ats['R']] = cop[i // settings_ats['R']].mean() if not no_save: if", "dtype=float) cop_results = numpy.empty(len(test_cases), dtype=float) settings_ats.new('N', settings_ats[\"N_min\"]) with click.progressbar( range(len(test_cases) * settings_ats['R'] -", "os.path.isfile(os.path.join(path, \"change_of_position.csv\"))): click.echo(\"This data batch is corrupted.\") return n_stop = settings_ats[\"N_min\"] + settings_ats[\"N_step\"]", "% settings_ats['R']] try: bounce[i // settings_ats['R']][i % settings_ats['R']], \\ cop[i // settings_ats['R']][i %", "atoms_simulator.Settings(\"settings_ats.toml\") if not settings_ats.load(): click.echo(\"No settings file detected. Generate the file first.\") return", "batch is corrupted.\") return n_stop = settings_ats[\"N_min\"] + settings_ats[\"N_step\"] * (settings_ats[\"N_number\"] - 1)", "= {settings_ats['M']}\") plt.xlabel(\"Liczba atomów w pojemniku\") plt.ylabel(\"Liczba odbić atomu czerownego\") plt.grid(True) plt.savefig(os.path.join(target_path, \"bounces.png\"))", "[ [i for _ in range(settings_ats['R'])] for i in range(settings_ats[\"N_min\"], n_stop + 1,", "the test.\", is_flag=True) def test(graphics, no_save): \"\"\"Performs a series of tests based on", "not settings_ats.load(): click.echo(\"No settings file detected. Generate the file first.\") return if settings_ats[\"N_min\"]", "True: if not os.path.lexists(f\"{path}{i}\"): return f\"{path}{i}\" i += 1 @click.group() def ats(): \"\"\"Allows", "corrupted, please generate a new settings file.\") return if settings_ats[\"N_number\"] is None: click.echo(\"The", "new settings file.\") return if i % settings_ats['R'] == 0: bounce_results[i // settings_ats['R']]", "os.path.join(os.getcwd(), \"ats_results\")): click.echo( \"The ats_results catalog doesn't exist within the current working directory.", "on the data in the settings_ats.toml file.\"\"\" settings_ats = atoms_simulator.Settings(\"settings_ats.toml\") if not settings_ats.load():", "exists. Please delete it in order to generate a new configuration file.\") @ats.command()", "\"ats_results\")): os.mkdir(results_path) target_path = get_path(os.path.join(results_path, \"data_batch\")) os.mkdir(target_path) numpy.savetxt(os.path.join(target_path, \"bounces.csv\"), bounce_results) numpy.savetxt(os.path.join(target_path, \"change_of_position.csv\"), cop_results)", "return if settings_ats[\"R\"] is None: click.echo(\"The settings file is corrupted, please generate a", "cop = numpy.empty((len(test_cases), settings_ats['R']), dtype=float) cop_results = numpy.empty(len(test_cases), dtype=float) settings_ats.new('N', settings_ats[\"N_min\"]) with click.progressbar(", "plt.xlabel(\"Liczba atomów w pojemniku\") plt.ylabel(\"Średnia droga swobodna atomu czerwonego\") plt.grid(True) plt.savefig(os.path.join(target_path, \"change_of_position.png\")) plt.clf()", "generate a new settings file.\") return if settings_ats[\"N_step\"] is None: click.echo(\"The settings file", "1, -1, -1), label=\"Performing simulations:\", show_eta=False ) as progress: for i in progress:", "// settings_ats['R']] = int(bounce[i // settings_ats['R']].mean()) cop_results[i // settings_ats['R']] = cop[i // settings_ats['R']].mean()", "ats(): \"\"\"Allows to perform detailed tests using atoms_simulator module.\"\"\" pass @ats.command() def init():", "settings_ats['R']].mean()) cop_results[i // settings_ats['R']] = cop[i // settings_ats['R']].mean() if not no_save: if not", "n_stop = settings_ats[\"N_min\"] + settings_ats[\"N_step\"] * (settings_ats[\"N_number\"] - 1) # size = max([settings_ats['h'],", "a new configuration file.\") @ats.command() @click.option(\"-g\", \"--graphics\", \"graphics\", help=\"Turn on pygame simulation\", is_flag=True)", "- 1) # size = max([settings_ats['h'], settings_ats['w'], math.ceil((4 * (n_stop + 1)) **", "n_stop = settings_ats[\"N_min\"] + settings_ats[\"N_step\"] * (settings_ats[\"N_number\"] - 1) x = numpy.arange(settings_ats[\"N_min\"], n_stop", "settings_ats[\"N_min\"] is None: click.echo(\"The settings file is corrupted, please generate a new settings", "\"The ats_results catalog doesn't exist within the current working directory. Generate some data", "get_path(os.path.join(results_path, \"figures_batch\")) os.mkdir(target_path) settings_ats = atoms_simulator.Settings(os.path.join(path, \"used.toml\")) if not (settings_ats.load() and os.path.isfile(os.path.join(path, \"bounces.csv\"))", "plt.plot(x, cop, marker='o') plt.title(f\"Zależność średniej drogi swobodnej od ilości atomów, M = {settings_ats['M']}\")", "return click.echo(\"Starting simulation...\") n_stop = settings_ats[\"N_min\"] + settings_ats[\"N_step\"] * (settings_ats[\"N_number\"] - 1) #", "cop_results = numpy.empty(len(test_cases), dtype=float) settings_ats.new('N', settings_ats[\"N_min\"]) with click.progressbar( range(len(test_cases) * settings_ats['R'] - 1,", "% settings_ats['R'] == 0: bounce_results[i // settings_ats['R']] = int(bounce[i // settings_ats['R']].mean()) cop_results[i //", "plt.title(f\"Zależność średniej drogi swobodnej od ilości atomów, M = {settings_ats['M']}\") plt.xlabel(\"Liczba atomów w", "settings_ats['R']].mean() if not no_save: if not os.path.isdir(results_path := os.path.join(os.getcwd(), \"ats_results\")): os.mkdir(results_path) target_path =", "droga swobodna atomu czerwonego\") plt.grid(True) plt.savefig(os.path.join(target_path, \"change_of_position.png\")) plt.clf() settings_ats.save(os.path.join(target_path, \"used.toml\")) click.echo(\"Figures created successfullly.\")", "os.mkdir(results_path) target_path = get_path(os.path.join(results_path, \"data_batch\")) os.mkdir(target_path) numpy.savetxt(os.path.join(target_path, \"bounces.csv\"), bounce_results) numpy.savetxt(os.path.join(target_path, \"change_of_position.csv\"), cop_results) settings_ats.save(target=os.path.join(target_path,", "shutil.copy(source, target) click.echo(\"Settings file generated successfully.\") else: click.echo(\"Settings file already exists. Please delete", "help=\"Name of the previously generated data batch.\") def plot(data_batch): \"\"\"Plots the previously generated", "import os.path import shutil import atoms_simulator import numpy import matplotlib.pyplot as plt def", "\"ats_results\")): click.echo( \"The ats_results catalog doesn't exist within the current working directory. Generate", "file generated successfully.\") else: click.echo(\"Settings file already exists. Please delete it in order", "1) x = numpy.arange(settings_ats[\"N_min\"], n_stop + 1, settings_ats[\"N_step\"]) bounce = numpy.loadtxt(os.path.join(path, \"bounces.csv\")) plt.plot(x,", "within the current working directory. Generate some data first.\" ) return if not", "already exists. Please delete it in order to generate a new configuration file.\")", "liczby zderzeń od ilości atomów, M = {settings_ats['M']}\") plt.xlabel(\"Liczba atomów w pojemniku\") plt.ylabel(\"Liczba", "test(graphics, no_save): \"\"\"Performs a series of tests based on the data in the" ]
[ "3.8, 1.5] A_ub = [ [1, 1, 1], [-1, -1, -1], [-1, -1.", "[ [1, 1, 1], [-1, -1, -1], [-1, -1. / 3., -1. /", "-1. / 6.]] b_ub = [18, -12, -9] res = linprog(c, A_ub=A_ub, b_ub=b_ub)", "A_ub = [ [1, 1, 1], [-1, -1, -1], [-1, -1. / 3.,", "as np from scipy.optimize import linprog c = [10, 3.8, 1.5] A_ub =", "import numpy as np from scipy.optimize import linprog c = [10, 3.8, 1.5]", "1], [-1, -1, -1], [-1, -1. / 3., -1. / 6.]] b_ub =", "[-1, -1. / 3., -1. / 6.]] b_ub = [18, -12, -9] res", "scipy.optimize import linprog c = [10, 3.8, 1.5] A_ub = [ [1, 1,", "3., -1. / 6.]] b_ub = [18, -12, -9] res = linprog(c, A_ub=A_ub,", "-1, -1], [-1, -1. / 3., -1. / 6.]] b_ub = [18, -12,", "-1. / 3., -1. / 6.]] b_ub = [18, -12, -9] res =", "c = [10, 3.8, 1.5] A_ub = [ [1, 1, 1], [-1, -1,", "[1, 1, 1], [-1, -1, -1], [-1, -1. / 3., -1. / 6.]]", "/ 6.]] b_ub = [18, -12, -9] res = linprog(c, A_ub=A_ub, b_ub=b_ub) print(res)", "np from scipy.optimize import linprog c = [10, 3.8, 1.5] A_ub = [", "from scipy.optimize import linprog c = [10, 3.8, 1.5] A_ub = [ [1,", "/ 3., -1. / 6.]] b_ub = [18, -12, -9] res = linprog(c,", "linprog c = [10, 3.8, 1.5] A_ub = [ [1, 1, 1], [-1,", "1.5] A_ub = [ [1, 1, 1], [-1, -1, -1], [-1, -1. /", "numpy as np from scipy.optimize import linprog c = [10, 3.8, 1.5] A_ub", "= [ [1, 1, 1], [-1, -1, -1], [-1, -1. / 3., -1.", "1, 1], [-1, -1, -1], [-1, -1. / 3., -1. / 6.]] b_ub", "= [10, 3.8, 1.5] A_ub = [ [1, 1, 1], [-1, -1, -1],", "-1], [-1, -1. / 3., -1. / 6.]] b_ub = [18, -12, -9]", "[10, 3.8, 1.5] A_ub = [ [1, 1, 1], [-1, -1, -1], [-1,", "[-1, -1, -1], [-1, -1. / 3., -1. / 6.]] b_ub = [18,", "import linprog c = [10, 3.8, 1.5] A_ub = [ [1, 1, 1]," ]
[ "dfs = [] for path in paths: table = pq.read_table(path) df = table.to_pandas()", "df = df.replace(replace_to) df = df.drop_duplicates(subset=\"id\") df = df.drop(columns=UNNECESSARY_COLUMNS) df.id = df.id.astype(np.uint64) df", "import Path import numpy as np import pandas as pd import pyarrow.parquet as", "for path in paths: table = pq.read_table(path) df = table.to_pandas() # Add state", "numpy as np import pandas as pd import pyarrow.parquet as pq from bld.project_paths", "df.replace(replace_to) df = df.drop_duplicates(subset=\"id\") df = df.drop(columns=UNNECESSARY_COLUMNS) df.id = df.id.astype(np.uint64) df = df.set_index(\"id\")", "import project_paths_join as ppj from src.shared import to_parquet_in_date_chunks UNNECESSARY_COLUMNS = [\"formatted_date\", \"geo\"] def", "= df.id.astype(np.uint64) df = df.set_index(\"id\") return df def main(): df = load_data() df", "= df.set_index(\"id\") return df def main(): df = load_data() df = minimal_preprocessing(df) to_parquet_in_date_chunks(df,", "= df.drop(columns=UNNECESSARY_COLUMNS) df.id = df.id.astype(np.uint64) df = df.set_index(\"id\") return df def main(): df", "import pandas as pd import pyarrow.parquet as pq from bld.project_paths import project_paths_join as", "return df def minimal_preprocessing(df): replace_to = {None: np.nan, \"\": np.nan} df = df.replace(replace_to)", "df.id = df.id.astype(np.uint64) df = df.set_index(\"id\") return df def main(): df = load_data()", "replace_to = {None: np.nan, \"\": np.nan} df = df.replace(replace_to) df = df.drop_duplicates(subset=\"id\") df", "pyarrow.parquet as pq from bld.project_paths import project_paths_join as ppj from src.shared import to_parquet_in_date_chunks", "{None: np.nan, \"\": np.nan} df = df.replace(replace_to) df = df.drop_duplicates(subset=\"id\") df = df.drop(columns=UNNECESSARY_COLUMNS)", "<gh_stars>1-10 from pathlib import Path import numpy as np import pandas as pd", "city from path. df[\"state\"] = path.parents[3].name df[\"city\"] = path.parents[2].name dfs.append(df) df = pd.concat(dfs,", "= list(Path(ppj(\"IN_DATA\", \"corona_data\")).glob(\"2020*/**/*.parquet\")) dfs = [] for path in paths: table = pq.read_table(path)", "as np import pandas as pd import pyarrow.parquet as pq from bld.project_paths import", "table.to_pandas() # Add state and city from path. df[\"state\"] = path.parents[3].name df[\"city\"] =", "from src.shared import to_parquet_in_date_chunks UNNECESSARY_COLUMNS = [\"formatted_date\", \"geo\"] def load_data(): paths = list(Path(ppj(\"IN_DATA\",", "def main(): df = load_data() df = minimal_preprocessing(df) to_parquet_in_date_chunks(df, ppj(\"OUT_DATA\", \"tweets-cleaned\")) if __name__", "state and city from path. df[\"state\"] = path.parents[3].name df[\"city\"] = path.parents[2].name dfs.append(df) df", "main(): df = load_data() df = minimal_preprocessing(df) to_parquet_in_date_chunks(df, ppj(\"OUT_DATA\", \"tweets-cleaned\")) if __name__ ==", "\"corona_data\")).glob(\"2020*/**/*.parquet\")) dfs = [] for path in paths: table = pq.read_table(path) df =", "= {None: np.nan, \"\": np.nan} df = df.replace(replace_to) df = df.drop_duplicates(subset=\"id\") df =", "to_parquet_in_date_chunks UNNECESSARY_COLUMNS = [\"formatted_date\", \"geo\"] def load_data(): paths = list(Path(ppj(\"IN_DATA\", \"corona_data\")).glob(\"2020*/**/*.parquet\")) dfs =", "df = df.drop(columns=UNNECESSARY_COLUMNS) df.id = df.id.astype(np.uint64) df = df.set_index(\"id\") return df def main():", "in paths: table = pq.read_table(path) df = table.to_pandas() # Add state and city", "[\"formatted_date\", \"geo\"] def load_data(): paths = list(Path(ppj(\"IN_DATA\", \"corona_data\")).glob(\"2020*/**/*.parquet\")) dfs = [] for path", "from path. df[\"state\"] = path.parents[3].name df[\"city\"] = path.parents[2].name dfs.append(df) df = pd.concat(dfs, sort=False)", "= df.drop_duplicates(subset=\"id\") df = df.drop(columns=UNNECESSARY_COLUMNS) df.id = df.id.astype(np.uint64) df = df.set_index(\"id\") return df", "= pd.concat(dfs, sort=False) return df def minimal_preprocessing(df): replace_to = {None: np.nan, \"\": np.nan}", "= [\"formatted_date\", \"geo\"] def load_data(): paths = list(Path(ppj(\"IN_DATA\", \"corona_data\")).glob(\"2020*/**/*.parquet\")) dfs = [] for", "pq from bld.project_paths import project_paths_join as ppj from src.shared import to_parquet_in_date_chunks UNNECESSARY_COLUMNS =", "= load_data() df = minimal_preprocessing(df) to_parquet_in_date_chunks(df, ppj(\"OUT_DATA\", \"tweets-cleaned\")) if __name__ == \"__main__\": main()", "as ppj from src.shared import to_parquet_in_date_chunks UNNECESSARY_COLUMNS = [\"formatted_date\", \"geo\"] def load_data(): paths", "project_paths_join as ppj from src.shared import to_parquet_in_date_chunks UNNECESSARY_COLUMNS = [\"formatted_date\", \"geo\"] def load_data():", "Add state and city from path. df[\"state\"] = path.parents[3].name df[\"city\"] = path.parents[2].name dfs.append(df)", "\"\": np.nan} df = df.replace(replace_to) df = df.drop_duplicates(subset=\"id\") df = df.drop(columns=UNNECESSARY_COLUMNS) df.id =", "sort=False) return df def minimal_preprocessing(df): replace_to = {None: np.nan, \"\": np.nan} df =", "df.set_index(\"id\") return df def main(): df = load_data() df = minimal_preprocessing(df) to_parquet_in_date_chunks(df, ppj(\"OUT_DATA\",", "src.shared import to_parquet_in_date_chunks UNNECESSARY_COLUMNS = [\"formatted_date\", \"geo\"] def load_data(): paths = list(Path(ppj(\"IN_DATA\", \"corona_data\")).glob(\"2020*/**/*.parquet\"))", "list(Path(ppj(\"IN_DATA\", \"corona_data\")).glob(\"2020*/**/*.parquet\")) dfs = [] for path in paths: table = pq.read_table(path) df", "np.nan, \"\": np.nan} df = df.replace(replace_to) df = df.drop_duplicates(subset=\"id\") df = df.drop(columns=UNNECESSARY_COLUMNS) df.id", "ppj from src.shared import to_parquet_in_date_chunks UNNECESSARY_COLUMNS = [\"formatted_date\", \"geo\"] def load_data(): paths =", "pathlib import Path import numpy as np import pandas as pd import pyarrow.parquet", "df[\"city\"] = path.parents[2].name dfs.append(df) df = pd.concat(dfs, sort=False) return df def minimal_preprocessing(df): replace_to", "dfs.append(df) df = pd.concat(dfs, sort=False) return df def minimal_preprocessing(df): replace_to = {None: np.nan,", "df def main(): df = load_data() df = minimal_preprocessing(df) to_parquet_in_date_chunks(df, ppj(\"OUT_DATA\", \"tweets-cleaned\")) if", "= [] for path in paths: table = pq.read_table(path) df = table.to_pandas() #", "pandas as pd import pyarrow.parquet as pq from bld.project_paths import project_paths_join as ppj", "# Add state and city from path. df[\"state\"] = path.parents[3].name df[\"city\"] = path.parents[2].name", "df = pd.concat(dfs, sort=False) return df def minimal_preprocessing(df): replace_to = {None: np.nan, \"\":", "from pathlib import Path import numpy as np import pandas as pd import", "path.parents[3].name df[\"city\"] = path.parents[2].name dfs.append(df) df = pd.concat(dfs, sort=False) return df def minimal_preprocessing(df):", "as pq from bld.project_paths import project_paths_join as ppj from src.shared import to_parquet_in_date_chunks UNNECESSARY_COLUMNS", "paths = list(Path(ppj(\"IN_DATA\", \"corona_data\")).glob(\"2020*/**/*.parquet\")) dfs = [] for path in paths: table =", "df.drop(columns=UNNECESSARY_COLUMNS) df.id = df.id.astype(np.uint64) df = df.set_index(\"id\") return df def main(): df =", "df[\"state\"] = path.parents[3].name df[\"city\"] = path.parents[2].name dfs.append(df) df = pd.concat(dfs, sort=False) return df", "= path.parents[2].name dfs.append(df) df = pd.concat(dfs, sort=False) return df def minimal_preprocessing(df): replace_to =", "df.drop_duplicates(subset=\"id\") df = df.drop(columns=UNNECESSARY_COLUMNS) df.id = df.id.astype(np.uint64) df = df.set_index(\"id\") return df def", "paths: table = pq.read_table(path) df = table.to_pandas() # Add state and city from", "and city from path. df[\"state\"] = path.parents[3].name df[\"city\"] = path.parents[2].name dfs.append(df) df =", "df.id.astype(np.uint64) df = df.set_index(\"id\") return df def main(): df = load_data() df =", "\"geo\"] def load_data(): paths = list(Path(ppj(\"IN_DATA\", \"corona_data\")).glob(\"2020*/**/*.parquet\")) dfs = [] for path in", "[] for path in paths: table = pq.read_table(path) df = table.to_pandas() # Add", "import pyarrow.parquet as pq from bld.project_paths import project_paths_join as ppj from src.shared import", "from bld.project_paths import project_paths_join as ppj from src.shared import to_parquet_in_date_chunks UNNECESSARY_COLUMNS = [\"formatted_date\",", "path in paths: table = pq.read_table(path) df = table.to_pandas() # Add state and", "def minimal_preprocessing(df): replace_to = {None: np.nan, \"\": np.nan} df = df.replace(replace_to) df =", "pq.read_table(path) df = table.to_pandas() # Add state and city from path. df[\"state\"] =", "df = table.to_pandas() # Add state and city from path. df[\"state\"] = path.parents[3].name", "UNNECESSARY_COLUMNS = [\"formatted_date\", \"geo\"] def load_data(): paths = list(Path(ppj(\"IN_DATA\", \"corona_data\")).glob(\"2020*/**/*.parquet\")) dfs = []", "df = df.set_index(\"id\") return df def main(): df = load_data() df = minimal_preprocessing(df)", "path. df[\"state\"] = path.parents[3].name df[\"city\"] = path.parents[2].name dfs.append(df) df = pd.concat(dfs, sort=False) return", "df = load_data() df = minimal_preprocessing(df) to_parquet_in_date_chunks(df, ppj(\"OUT_DATA\", \"tweets-cleaned\")) if __name__ == \"__main__\":", "df = df.drop_duplicates(subset=\"id\") df = df.drop(columns=UNNECESSARY_COLUMNS) df.id = df.id.astype(np.uint64) df = df.set_index(\"id\") return", "as pd import pyarrow.parquet as pq from bld.project_paths import project_paths_join as ppj from", "pd import pyarrow.parquet as pq from bld.project_paths import project_paths_join as ppj from src.shared", "path.parents[2].name dfs.append(df) df = pd.concat(dfs, sort=False) return df def minimal_preprocessing(df): replace_to = {None:", "bld.project_paths import project_paths_join as ppj from src.shared import to_parquet_in_date_chunks UNNECESSARY_COLUMNS = [\"formatted_date\", \"geo\"]", "df def minimal_preprocessing(df): replace_to = {None: np.nan, \"\": np.nan} df = df.replace(replace_to) df", "load_data(): paths = list(Path(ppj(\"IN_DATA\", \"corona_data\")).glob(\"2020*/**/*.parquet\")) dfs = [] for path in paths: table", "= path.parents[3].name df[\"city\"] = path.parents[2].name dfs.append(df) df = pd.concat(dfs, sort=False) return df def", "minimal_preprocessing(df): replace_to = {None: np.nan, \"\": np.nan} df = df.replace(replace_to) df = df.drop_duplicates(subset=\"id\")", "Path import numpy as np import pandas as pd import pyarrow.parquet as pq", "np import pandas as pd import pyarrow.parquet as pq from bld.project_paths import project_paths_join", "= pq.read_table(path) df = table.to_pandas() # Add state and city from path. df[\"state\"]", "= df.replace(replace_to) df = df.drop_duplicates(subset=\"id\") df = df.drop(columns=UNNECESSARY_COLUMNS) df.id = df.id.astype(np.uint64) df =", "table = pq.read_table(path) df = table.to_pandas() # Add state and city from path.", "def load_data(): paths = list(Path(ppj(\"IN_DATA\", \"corona_data\")).glob(\"2020*/**/*.parquet\")) dfs = [] for path in paths:", "return df def main(): df = load_data() df = minimal_preprocessing(df) to_parquet_in_date_chunks(df, ppj(\"OUT_DATA\", \"tweets-cleaned\"))", "pd.concat(dfs, sort=False) return df def minimal_preprocessing(df): replace_to = {None: np.nan, \"\": np.nan} df", "import to_parquet_in_date_chunks UNNECESSARY_COLUMNS = [\"formatted_date\", \"geo\"] def load_data(): paths = list(Path(ppj(\"IN_DATA\", \"corona_data\")).glob(\"2020*/**/*.parquet\")) dfs", "= table.to_pandas() # Add state and city from path. df[\"state\"] = path.parents[3].name df[\"city\"]", "np.nan} df = df.replace(replace_to) df = df.drop_duplicates(subset=\"id\") df = df.drop(columns=UNNECESSARY_COLUMNS) df.id = df.id.astype(np.uint64)", "import numpy as np import pandas as pd import pyarrow.parquet as pq from" ]
[ "y.append(np.mean(eval_dict[y_key])) if draw_line: line, = ax.plot(x, y, '-x', label=label) # line.set_label(label) ax.set_xlabel(x_key) ax.set_ylabel(y_key)", "FPS') genPlots(files, f, ax, draw_line=True, label='our', x_key='bpp') for a in ax: a.grid() #", "x_key=x_key, y_key='chamfer_dist_abs', ax=ax[0], draw_line=draw_line, label=label) plotResults(files, x_key=x_key, y_key='chamfer_dist_plane', ax=ax[1], draw_line=draw_line, label=label) plotResults(files, x_key=x_key,", "ax.plot(x, y, '-x', label=label) # line.set_label(label) ax.set_xlabel(x_key) ax.set_ylabel(y_key) if set_lim: ax.set_xlim(0,None) ax.set_ylim(0,None) #", "y = [] for f in files: eval_dict = pcu.load_obj(f) if((x_key in eval_dict.keys())", "plotResults(files, x_key=x_key, y_key='iou', ax=ax[2], draw_line=draw_line, label=label) if __name__ == \"__main__\": ####### radius fct", "ax, draw_line=False, label=None, x_key='memory'): # print('shape',ax[0,0]) plotResults(files, x_key=x_key, y_key='chamfer_dist_abs', ax=ax[0], draw_line=draw_line, label=label) plotResults(files,", "in files: eval_dict = pcu.load_obj(f) if((x_key in eval_dict.keys()) & (y_key in eval_dict.keys())): for", "v = np.array(v) if not draw_line: ax.plot(np.mean(eval_dict[x_key]), np.mean(eval_dict[y_key]), '.') ax.text(np.mean(eval_dict[x_key]), np.mean( eval_dict[y_key]), f.split('/')[-1][:-4])", "# print('shape',ax[0,0]) plotResults(files, x_key=x_key, y_key='chamfer_dist_abs', ax=ax[0], draw_line=draw_line, label=label) plotResults(files, x_key=x_key, y_key='chamfer_dist_plane', ax=ax[1], draw_line=draw_line,", "label=label) if __name__ == \"__main__\": ####### radius fct ############## path = 'experiments/results/kitti/' files", "if draw_line: line, = ax.plot(x, y, '-x', label=label) # line.set_label(label) ax.set_xlabel(x_key) ax.set_ylabel(y_key) if", "ax = plt.subplots(1, 3) f.suptitle('Radius FPS') genPlots(files, f, ax, draw_line=True, label='our', x_key='bpp') for", "== \"__main__\": ####### radius fct ############## path = 'experiments/results/kitti/' files = sorted(glob.glob(path+'*.pkl')) f,", "= plt.subplots(1, 3) f.suptitle('Radius FPS') genPlots(files, f, ax, draw_line=True, label='our', x_key='bpp') for a", "label=label) plotResults(files, x_key=x_key, y_key='iou', ax=ax[2], draw_line=draw_line, label=label) if __name__ == \"__main__\": ####### radius", "import numpy as np import matplotlib.pyplot as plt import glob import argparse from", "ax.set_xlabel(x_key) ax.set_ylabel(y_key) if set_lim: ax.set_xlim(0,None) ax.set_ylim(0,None) # ax.grid() def genPlots(files, f, ax, draw_line=False,", "ax=ax[1], draw_line=draw_line, label=label) plotResults(files, x_key=x_key, y_key='iou', ax=ax[2], draw_line=draw_line, label=label) if __name__ == \"__main__\":", "ax.set_xlim(0,None) ax.set_ylim(0,None) # ax.grid() def genPlots(files, f, ax, draw_line=False, label=None, x_key='memory'): # print('shape',ax[0,0])", "plotResults(files, x_key, y_key, ax, draw_line=False, label=None, set_lim=True): x = [] y = []", "files: eval_dict = pcu.load_obj(f) if((x_key in eval_dict.keys()) & (y_key in eval_dict.keys())): for v", "(y_key in eval_dict.keys())): for v in eval_dict.values(): v = np.array(v) if not draw_line:", "plt import glob import argparse from ruamel import yaml import depoco.utils.point_cloud_utils as pcu", "f, ax = plt.subplots(1, 3) f.suptitle('Radius FPS') genPlots(files, f, ax, draw_line=True, label='our', x_key='bpp')", "y_key, ax, draw_line=False, label=None, set_lim=True): x = [] y = [] for f", "import argparse from ruamel import yaml import depoco.utils.point_cloud_utils as pcu def plotResults(files, x_key,", "if set_lim: ax.set_xlim(0,None) ax.set_ylim(0,None) # ax.grid() def genPlots(files, f, ax, draw_line=False, label=None, x_key='memory'):", "numpy as np import matplotlib.pyplot as plt import glob import argparse from ruamel", "def genPlots(files, f, ax, draw_line=False, label=None, x_key='memory'): # print('shape',ax[0,0]) plotResults(files, x_key=x_key, y_key='chamfer_dist_abs', ax=ax[0],", "ax=ax[2], draw_line=draw_line, label=label) if __name__ == \"__main__\": ####### radius fct ############## path =", "in eval_dict.keys()) & (y_key in eval_dict.keys())): for v in eval_dict.values(): v = np.array(v)", "x_key='memory'): # print('shape',ax[0,0]) plotResults(files, x_key=x_key, y_key='chamfer_dist_abs', ax=ax[0], draw_line=draw_line, label=label) plotResults(files, x_key=x_key, y_key='chamfer_dist_plane', ax=ax[1],", "label=label) plotResults(files, x_key=x_key, y_key='chamfer_dist_plane', ax=ax[1], draw_line=draw_line, label=label) plotResults(files, x_key=x_key, y_key='iou', ax=ax[2], draw_line=draw_line, label=label)", "yaml import depoco.utils.point_cloud_utils as pcu def plotResults(files, x_key, y_key, ax, draw_line=False, label=None, set_lim=True):", "x_key=x_key, y_key='chamfer_dist_plane', ax=ax[1], draw_line=draw_line, label=label) plotResults(files, x_key=x_key, y_key='iou', ax=ax[2], draw_line=draw_line, label=label) if __name__", "np.mean( eval_dict[y_key]), f.split('/')[-1][:-4]) x.append(np.mean(eval_dict[x_key])) y.append(np.mean(eval_dict[y_key])) if draw_line: line, = ax.plot(x, y, '-x', label=label)", "as plt import glob import argparse from ruamel import yaml import depoco.utils.point_cloud_utils as", "ax.text(np.mean(eval_dict[x_key]), np.mean( eval_dict[y_key]), f.split('/')[-1][:-4]) x.append(np.mean(eval_dict[x_key])) y.append(np.mean(eval_dict[y_key])) if draw_line: line, = ax.plot(x, y, '-x',", "ax, draw_line=False, label=None, set_lim=True): x = [] y = [] for f in", "as np import matplotlib.pyplot as plt import glob import argparse from ruamel import", "if not draw_line: ax.plot(np.mean(eval_dict[x_key]), np.mean(eval_dict[y_key]), '.') ax.text(np.mean(eval_dict[x_key]), np.mean( eval_dict[y_key]), f.split('/')[-1][:-4]) x.append(np.mean(eval_dict[x_key])) y.append(np.mean(eval_dict[y_key])) if", "y_key='chamfer_dist_abs', ax=ax[0], draw_line=draw_line, label=label) plotResults(files, x_key=x_key, y_key='chamfer_dist_plane', ax=ax[1], draw_line=draw_line, label=label) plotResults(files, x_key=x_key, y_key='iou',", "files = sorted(glob.glob(path+'*.pkl')) f, ax = plt.subplots(1, 3) f.suptitle('Radius FPS') genPlots(files, f, ax,", "# line.set_label(label) ax.set_xlabel(x_key) ax.set_ylabel(y_key) if set_lim: ax.set_xlim(0,None) ax.set_ylim(0,None) # ax.grid() def genPlots(files, f,", "= [] y = [] for f in files: eval_dict = pcu.load_obj(f) if((x_key", "if((x_key in eval_dict.keys()) & (y_key in eval_dict.keys())): for v in eval_dict.values(): v =", "label=label) # line.set_label(label) ax.set_xlabel(x_key) ax.set_ylabel(y_key) if set_lim: ax.set_xlim(0,None) ax.set_ylim(0,None) # ax.grid() def genPlots(files,", "draw_line=draw_line, label=label) plotResults(files, x_key=x_key, y_key='chamfer_dist_plane', ax=ax[1], draw_line=draw_line, label=label) plotResults(files, x_key=x_key, y_key='iou', ax=ax[2], draw_line=draw_line,", "import depoco.utils.point_cloud_utils as pcu def plotResults(files, x_key, y_key, ax, draw_line=False, label=None, set_lim=True): x", "& (y_key in eval_dict.keys())): for v in eval_dict.values(): v = np.array(v) if not", "ax, draw_line=True, label='our', x_key='bpp') for a in ax: a.grid() # a.set_ylim([0,None]) a.legend() plt.show()", "draw_line=draw_line, label=label) if __name__ == \"__main__\": ####### radius fct ############## path = 'experiments/results/kitti/'", "draw_line: line, = ax.plot(x, y, '-x', label=label) # line.set_label(label) ax.set_xlabel(x_key) ax.set_ylabel(y_key) if set_lim:", "draw_line=draw_line, label=label) plotResults(files, x_key=x_key, y_key='iou', ax=ax[2], draw_line=draw_line, label=label) if __name__ == \"__main__\": #######", "y, '-x', label=label) # line.set_label(label) ax.set_xlabel(x_key) ax.set_ylabel(y_key) if set_lim: ax.set_xlim(0,None) ax.set_ylim(0,None) # ax.grid()", "set_lim: ax.set_xlim(0,None) ax.set_ylim(0,None) # ax.grid() def genPlots(files, f, ax, draw_line=False, label=None, x_key='memory'): #", "sorted(glob.glob(path+'*.pkl')) f, ax = plt.subplots(1, 3) f.suptitle('Radius FPS') genPlots(files, f, ax, draw_line=True, label='our',", "ruamel import yaml import depoco.utils.point_cloud_utils as pcu def plotResults(files, x_key, y_key, ax, draw_line=False,", "[] for f in files: eval_dict = pcu.load_obj(f) if((x_key in eval_dict.keys()) & (y_key", "np.mean(eval_dict[y_key]), '.') ax.text(np.mean(eval_dict[x_key]), np.mean( eval_dict[y_key]), f.split('/')[-1][:-4]) x.append(np.mean(eval_dict[x_key])) y.append(np.mean(eval_dict[y_key])) if draw_line: line, = ax.plot(x,", "line.set_label(label) ax.set_xlabel(x_key) ax.set_ylabel(y_key) if set_lim: ax.set_xlim(0,None) ax.set_ylim(0,None) # ax.grid() def genPlots(files, f, ax,", "np import matplotlib.pyplot as plt import glob import argparse from ruamel import yaml", "depoco.utils.point_cloud_utils as pcu def plotResults(files, x_key, y_key, ax, draw_line=False, label=None, set_lim=True): x =", "genPlots(files, f, ax, draw_line=True, label='our', x_key='bpp') for a in ax: a.grid() # a.set_ylim([0,None])", "ax.grid() def genPlots(files, f, ax, draw_line=False, label=None, x_key='memory'): # print('shape',ax[0,0]) plotResults(files, x_key=x_key, y_key='chamfer_dist_abs',", "x.append(np.mean(eval_dict[x_key])) y.append(np.mean(eval_dict[y_key])) if draw_line: line, = ax.plot(x, y, '-x', label=label) # line.set_label(label) ax.set_xlabel(x_key)", "draw_line=False, label=None, x_key='memory'): # print('shape',ax[0,0]) plotResults(files, x_key=x_key, y_key='chamfer_dist_abs', ax=ax[0], draw_line=draw_line, label=label) plotResults(files, x_key=x_key,", "= sorted(glob.glob(path+'*.pkl')) f, ax = plt.subplots(1, 3) f.suptitle('Radius FPS') genPlots(files, f, ax, draw_line=True,", "v in eval_dict.values(): v = np.array(v) if not draw_line: ax.plot(np.mean(eval_dict[x_key]), np.mean(eval_dict[y_key]), '.') ax.text(np.mean(eval_dict[x_key]),", "<filename>depoco/plot_results.py<gh_stars>10-100 import numpy as np import matplotlib.pyplot as plt import glob import argparse", "plt.subplots(1, 3) f.suptitle('Radius FPS') genPlots(files, f, ax, draw_line=True, label='our', x_key='bpp') for a in", "for f in files: eval_dict = pcu.load_obj(f) if((x_key in eval_dict.keys()) & (y_key in", "in eval_dict.values(): v = np.array(v) if not draw_line: ax.plot(np.mean(eval_dict[x_key]), np.mean(eval_dict[y_key]), '.') ax.text(np.mean(eval_dict[x_key]), np.mean(", "line, = ax.plot(x, y, '-x', label=label) # line.set_label(label) ax.set_xlabel(x_key) ax.set_ylabel(y_key) if set_lim: ax.set_xlim(0,None)", "pcu def plotResults(files, x_key, y_key, ax, draw_line=False, label=None, set_lim=True): x = [] y", "for v in eval_dict.values(): v = np.array(v) if not draw_line: ax.plot(np.mean(eval_dict[x_key]), np.mean(eval_dict[y_key]), '.')", "eval_dict.keys()) & (y_key in eval_dict.keys())): for v in eval_dict.values(): v = np.array(v) if", "eval_dict.keys())): for v in eval_dict.values(): v = np.array(v) if not draw_line: ax.plot(np.mean(eval_dict[x_key]), np.mean(eval_dict[y_key]),", "= np.array(v) if not draw_line: ax.plot(np.mean(eval_dict[x_key]), np.mean(eval_dict[y_key]), '.') ax.text(np.mean(eval_dict[x_key]), np.mean( eval_dict[y_key]), f.split('/')[-1][:-4]) x.append(np.mean(eval_dict[x_key]))", "set_lim=True): x = [] y = [] for f in files: eval_dict =", "eval_dict[y_key]), f.split('/')[-1][:-4]) x.append(np.mean(eval_dict[x_key])) y.append(np.mean(eval_dict[y_key])) if draw_line: line, = ax.plot(x, y, '-x', label=label) #", "y_key='iou', ax=ax[2], draw_line=draw_line, label=label) if __name__ == \"__main__\": ####### radius fct ############## path", "not draw_line: ax.plot(np.mean(eval_dict[x_key]), np.mean(eval_dict[y_key]), '.') ax.text(np.mean(eval_dict[x_key]), np.mean( eval_dict[y_key]), f.split('/')[-1][:-4]) x.append(np.mean(eval_dict[x_key])) y.append(np.mean(eval_dict[y_key])) if draw_line:", "eval_dict.values(): v = np.array(v) if not draw_line: ax.plot(np.mean(eval_dict[x_key]), np.mean(eval_dict[y_key]), '.') ax.text(np.mean(eval_dict[x_key]), np.mean( eval_dict[y_key]),", "matplotlib.pyplot as plt import glob import argparse from ruamel import yaml import depoco.utils.point_cloud_utils", "fct ############## path = 'experiments/results/kitti/' files = sorted(glob.glob(path+'*.pkl')) f, ax = plt.subplots(1, 3)", "y_key='chamfer_dist_plane', ax=ax[1], draw_line=draw_line, label=label) plotResults(files, x_key=x_key, y_key='iou', ax=ax[2], draw_line=draw_line, label=label) if __name__ ==", "= [] for f in files: eval_dict = pcu.load_obj(f) if((x_key in eval_dict.keys()) &", "= pcu.load_obj(f) if((x_key in eval_dict.keys()) & (y_key in eval_dict.keys())): for v in eval_dict.values():", "label=None, set_lim=True): x = [] y = [] for f in files: eval_dict", "f, ax, draw_line=False, label=None, x_key='memory'): # print('shape',ax[0,0]) plotResults(files, x_key=x_key, y_key='chamfer_dist_abs', ax=ax[0], draw_line=draw_line, label=label)", "[] y = [] for f in files: eval_dict = pcu.load_obj(f) if((x_key in", "= 'experiments/results/kitti/' files = sorted(glob.glob(path+'*.pkl')) f, ax = plt.subplots(1, 3) f.suptitle('Radius FPS') genPlots(files,", "ax.set_ylim(0,None) # ax.grid() def genPlots(files, f, ax, draw_line=False, label=None, x_key='memory'): # print('shape',ax[0,0]) plotResults(files,", "label=None, x_key='memory'): # print('shape',ax[0,0]) plotResults(files, x_key=x_key, y_key='chamfer_dist_abs', ax=ax[0], draw_line=draw_line, label=label) plotResults(files, x_key=x_key, y_key='chamfer_dist_plane',", "'-x', label=label) # line.set_label(label) ax.set_xlabel(x_key) ax.set_ylabel(y_key) if set_lim: ax.set_xlim(0,None) ax.set_ylim(0,None) # ax.grid() def", "argparse from ruamel import yaml import depoco.utils.point_cloud_utils as pcu def plotResults(files, x_key, y_key,", "eval_dict = pcu.load_obj(f) if((x_key in eval_dict.keys()) & (y_key in eval_dict.keys())): for v in", "f.suptitle('Radius FPS') genPlots(files, f, ax, draw_line=True, label='our', x_key='bpp') for a in ax: a.grid()", "draw_line=False, label=None, set_lim=True): x = [] y = [] for f in files:", "plotResults(files, x_key=x_key, y_key='chamfer_dist_abs', ax=ax[0], draw_line=draw_line, label=label) plotResults(files, x_key=x_key, y_key='chamfer_dist_plane', ax=ax[1], draw_line=draw_line, label=label) plotResults(files,", "import matplotlib.pyplot as plt import glob import argparse from ruamel import yaml import", "ax=ax[0], draw_line=draw_line, label=label) plotResults(files, x_key=x_key, y_key='chamfer_dist_plane', ax=ax[1], draw_line=draw_line, label=label) plotResults(files, x_key=x_key, y_key='iou', ax=ax[2],", "radius fct ############## path = 'experiments/results/kitti/' files = sorted(glob.glob(path+'*.pkl')) f, ax = plt.subplots(1,", "'.') ax.text(np.mean(eval_dict[x_key]), np.mean( eval_dict[y_key]), f.split('/')[-1][:-4]) x.append(np.mean(eval_dict[x_key])) y.append(np.mean(eval_dict[y_key])) if draw_line: line, = ax.plot(x, y,", "def plotResults(files, x_key, y_key, ax, draw_line=False, label=None, set_lim=True): x = [] y =", "genPlots(files, f, ax, draw_line=False, label=None, x_key='memory'): # print('shape',ax[0,0]) plotResults(files, x_key=x_key, y_key='chamfer_dist_abs', ax=ax[0], draw_line=draw_line,", "############## path = 'experiments/results/kitti/' files = sorted(glob.glob(path+'*.pkl')) f, ax = plt.subplots(1, 3) f.suptitle('Radius", "f, ax, draw_line=True, label='our', x_key='bpp') for a in ax: a.grid() # a.set_ylim([0,None]) a.legend()", "from ruamel import yaml import depoco.utils.point_cloud_utils as pcu def plotResults(files, x_key, y_key, ax,", "ax.set_ylabel(y_key) if set_lim: ax.set_xlim(0,None) ax.set_ylim(0,None) # ax.grid() def genPlots(files, f, ax, draw_line=False, label=None,", "print('shape',ax[0,0]) plotResults(files, x_key=x_key, y_key='chamfer_dist_abs', ax=ax[0], draw_line=draw_line, label=label) plotResults(files, x_key=x_key, y_key='chamfer_dist_plane', ax=ax[1], draw_line=draw_line, label=label)", "glob import argparse from ruamel import yaml import depoco.utils.point_cloud_utils as pcu def plotResults(files,", "x = [] y = [] for f in files: eval_dict = pcu.load_obj(f)", "__name__ == \"__main__\": ####### radius fct ############## path = 'experiments/results/kitti/' files = sorted(glob.glob(path+'*.pkl'))", "plotResults(files, x_key=x_key, y_key='chamfer_dist_plane', ax=ax[1], draw_line=draw_line, label=label) plotResults(files, x_key=x_key, y_key='iou', ax=ax[2], draw_line=draw_line, label=label) if", "'experiments/results/kitti/' files = sorted(glob.glob(path+'*.pkl')) f, ax = plt.subplots(1, 3) f.suptitle('Radius FPS') genPlots(files, f,", "x_key, y_key, ax, draw_line=False, label=None, set_lim=True): x = [] y = [] for", "# ax.grid() def genPlots(files, f, ax, draw_line=False, label=None, x_key='memory'): # print('shape',ax[0,0]) plotResults(files, x_key=x_key,", "x_key=x_key, y_key='iou', ax=ax[2], draw_line=draw_line, label=label) if __name__ == \"__main__\": ####### radius fct ##############", "= ax.plot(x, y, '-x', label=label) # line.set_label(label) ax.set_xlabel(x_key) ax.set_ylabel(y_key) if set_lim: ax.set_xlim(0,None) ax.set_ylim(0,None)", "import yaml import depoco.utils.point_cloud_utils as pcu def plotResults(files, x_key, y_key, ax, draw_line=False, label=None,", "np.array(v) if not draw_line: ax.plot(np.mean(eval_dict[x_key]), np.mean(eval_dict[y_key]), '.') ax.text(np.mean(eval_dict[x_key]), np.mean( eval_dict[y_key]), f.split('/')[-1][:-4]) x.append(np.mean(eval_dict[x_key])) y.append(np.mean(eval_dict[y_key]))", "f in files: eval_dict = pcu.load_obj(f) if((x_key in eval_dict.keys()) & (y_key in eval_dict.keys())):", "path = 'experiments/results/kitti/' files = sorted(glob.glob(path+'*.pkl')) f, ax = plt.subplots(1, 3) f.suptitle('Radius FPS')", "pcu.load_obj(f) if((x_key in eval_dict.keys()) & (y_key in eval_dict.keys())): for v in eval_dict.values(): v", "f.split('/')[-1][:-4]) x.append(np.mean(eval_dict[x_key])) y.append(np.mean(eval_dict[y_key])) if draw_line: line, = ax.plot(x, y, '-x', label=label) # line.set_label(label)", "as pcu def plotResults(files, x_key, y_key, ax, draw_line=False, label=None, set_lim=True): x = []", "if __name__ == \"__main__\": ####### radius fct ############## path = 'experiments/results/kitti/' files =", "import glob import argparse from ruamel import yaml import depoco.utils.point_cloud_utils as pcu def", "####### radius fct ############## path = 'experiments/results/kitti/' files = sorted(glob.glob(path+'*.pkl')) f, ax =", "\"__main__\": ####### radius fct ############## path = 'experiments/results/kitti/' files = sorted(glob.glob(path+'*.pkl')) f, ax", "draw_line: ax.plot(np.mean(eval_dict[x_key]), np.mean(eval_dict[y_key]), '.') ax.text(np.mean(eval_dict[x_key]), np.mean( eval_dict[y_key]), f.split('/')[-1][:-4]) x.append(np.mean(eval_dict[x_key])) y.append(np.mean(eval_dict[y_key])) if draw_line: line,", "3) f.suptitle('Radius FPS') genPlots(files, f, ax, draw_line=True, label='our', x_key='bpp') for a in ax:", "ax.plot(np.mean(eval_dict[x_key]), np.mean(eval_dict[y_key]), '.') ax.text(np.mean(eval_dict[x_key]), np.mean( eval_dict[y_key]), f.split('/')[-1][:-4]) x.append(np.mean(eval_dict[x_key])) y.append(np.mean(eval_dict[y_key])) if draw_line: line, =", "in eval_dict.keys())): for v in eval_dict.values(): v = np.array(v) if not draw_line: ax.plot(np.mean(eval_dict[x_key])," ]
[ "manifest_end = f.tell() manifest_off_bytes = f.read(8) print(f\"{manifest_off_bytes=}\") manifest_off = int.from_bytes(manifest_off_bytes, 'little') print(f\"{manifest_off=}\") f.seek(manifest_off,0)", "int.from_bytes(info[1], 'big') chunk_pos = int.from_bytes(info[2], 'big') print(f\"{i}/{num_chunks}: {chunk_pos=} {chunk_len=}\", end='') f.seek(chunk_pos) chunk_compressed =", "# # openethereum --chain=kovan snapshot --snapshot-threads=8 snapshot.warp # warp2code-prefixes.py snapshot.warp import sys import", "= manifest[5] print(f\"{manifest_ver=}\") print(f\"{block_number=}\") print(f\"block_hash={block_hash.hex()}\") state_chunks = manifest[1] num_chunks=len(state_chunks) print(f\"{num_chunks=}\") for i in", "import collections prefix_map = collections.defaultdict(int) filename = sys.argv[1] print(f\"{filename=}\") with open(filename, 'rb') as", "f.seek(chunk_pos) chunk_compressed = f.read(chunk_len) chunk_bytes = snappy.uncompress(chunk_compressed) chunk = rlp.decode(chunk_bytes) print(f\" uncompressed_len={len(chunk_bytes)} num_accounts={len(chunk)}\",", "f.seek(0,2) size = f.tell() print(f\"{size=}\") f.seek(-8,2) manifest_end = f.tell() manifest_off_bytes = f.read(8) print(f\"{manifest_off_bytes=}\")", "snapshot.warp # warp2code-prefixes.py snapshot.warp import sys import rlp import snappy import collections prefix_map", "= state_chunks[i] chunk_len = int.from_bytes(info[1], 'big') chunk_pos = int.from_bytes(info[2], 'big') print(f\"{i}/{num_chunks}: {chunk_pos=} {chunk_len=}\",", "uncompressed_len={len(chunk_bytes)} num_accounts={len(chunk)}\", flush=True) for entry in chunk: acc = entry[1] has_code = acc[2]", "print(f\" uncompressed_len={len(chunk_bytes)} num_accounts={len(chunk)}\", flush=True) for entry in chunk: acc = entry[1] has_code =", "manifest_ver = int.from_bytes(manifest[0], 'big') block_number = int.from_bytes(manifest[4], 'big') block_hash = manifest[5] print(f\"{manifest_ver=}\") print(f\"{block_number=}\")", "manifest[1] num_chunks=len(state_chunks) print(f\"{num_chunks=}\") for i in range(num_chunks): info = state_chunks[i] chunk_len = int.from_bytes(info[1],", "= f.read(manifest_end-manifest_off) manifest = rlp.decode(manifest_bytes) manifest_ver = int.from_bytes(manifest[0], 'big') block_number = int.from_bytes(manifest[4], 'big')", "'big') block_hash = manifest[5] print(f\"{manifest_ver=}\") print(f\"{block_number=}\") print(f\"block_hash={block_hash.hex()}\") state_chunks = manifest[1] num_chunks=len(state_chunks) print(f\"{num_chunks=}\") for", "collections prefix_map = collections.defaultdict(int) filename = sys.argv[1] print(f\"{filename=}\") with open(filename, 'rb') as f:", "= collections.defaultdict(int) filename = sys.argv[1] print(f\"{filename=}\") with open(filename, 'rb') as f: f.seek(0,2) size", "'little') print(f\"{manifest_off=}\") f.seek(manifest_off,0) manifest_bytes = f.read(manifest_end-manifest_off) manifest = rlp.decode(manifest_bytes) manifest_ver = int.from_bytes(manifest[0], 'big')", "= f.read(chunk_len) chunk_bytes = snappy.uncompress(chunk_compressed) chunk = rlp.decode(chunk_bytes) print(f\" uncompressed_len={len(chunk_bytes)} num_accounts={len(chunk)}\", flush=True) for", "import rlp import snappy import collections prefix_map = collections.defaultdict(int) filename = sys.argv[1] print(f\"{filename=}\")", "with open(filename, 'rb') as f: f.seek(0,2) size = f.tell() print(f\"{size=}\") f.seek(-8,2) manifest_end =", "print(f\"{i}/{num_chunks}: {chunk_pos=} {chunk_len=}\", end='') f.seek(chunk_pos) chunk_compressed = f.read(chunk_len) chunk_bytes = snappy.uncompress(chunk_compressed) chunk =", "int.from_bytes(manifest_off_bytes, 'little') print(f\"{manifest_off=}\") f.seek(manifest_off,0) manifest_bytes = f.read(manifest_end-manifest_off) manifest = rlp.decode(manifest_bytes) manifest_ver = int.from_bytes(manifest[0],", "int.from_bytes(manifest[4], 'big') block_hash = manifest[5] print(f\"{manifest_ver=}\") print(f\"{block_number=}\") print(f\"block_hash={block_hash.hex()}\") state_chunks = manifest[1] num_chunks=len(state_chunks) print(f\"{num_chunks=}\")", "= int.from_bytes(info[2], 'big') print(f\"{i}/{num_chunks}: {chunk_pos=} {chunk_len=}\", end='') f.seek(chunk_pos) chunk_compressed = f.read(chunk_len) chunk_bytes =", "{chunk_pos=} {chunk_len=}\", end='') f.seek(chunk_pos) chunk_compressed = f.read(chunk_len) chunk_bytes = snappy.uncompress(chunk_compressed) chunk = rlp.decode(chunk_bytes)", "int.from_bytes(manifest[0], 'big') block_number = int.from_bytes(manifest[4], 'big') block_hash = manifest[5] print(f\"{manifest_ver=}\") print(f\"{block_number=}\") print(f\"block_hash={block_hash.hex()}\") state_chunks", "--chain=kovan snapshot --snapshot-threads=8 snapshot.warp # warp2code-prefixes.py snapshot.warp import sys import rlp import snappy", "rlp import snappy import collections prefix_map = collections.defaultdict(int) filename = sys.argv[1] print(f\"{filename=}\") with", "import snappy import collections prefix_map = collections.defaultdict(int) filename = sys.argv[1] print(f\"{filename=}\") with open(filename,", "code prefixes of all accounts. # # openethereum --chain=kovan snapshot --snapshot-threads=8 snapshot.warp #", "in range(num_chunks): info = state_chunks[i] chunk_len = int.from_bytes(info[1], 'big') chunk_pos = int.from_bytes(info[2], 'big')", "chunk_compressed = f.read(chunk_len) chunk_bytes = snappy.uncompress(chunk_compressed) chunk = rlp.decode(chunk_bytes) print(f\" uncompressed_len={len(chunk_bytes)} num_accounts={len(chunk)}\", flush=True)", "snapshot.warp import sys import rlp import snappy import collections prefix_map = collections.defaultdict(int) filename", "= snappy.uncompress(chunk_compressed) chunk = rlp.decode(chunk_bytes) print(f\" uncompressed_len={len(chunk_bytes)} num_accounts={len(chunk)}\", flush=True) for entry in chunk:", "info = state_chunks[i] chunk_len = int.from_bytes(info[1], 'big') chunk_pos = int.from_bytes(info[2], 'big') print(f\"{i}/{num_chunks}: {chunk_pos=}", "sys import rlp import snappy import collections prefix_map = collections.defaultdict(int) filename = sys.argv[1]", "{chunk_len=}\", end='') f.seek(chunk_pos) chunk_compressed = f.read(chunk_len) chunk_bytes = snappy.uncompress(chunk_compressed) chunk = rlp.decode(chunk_bytes) print(f\"", "#!/usr/bin/env python # Processes OpenEthereum warp snapshot and collects 4-byte code prefixes of", "= f.read(8) print(f\"{manifest_off_bytes=}\") manifest_off = int.from_bytes(manifest_off_bytes, 'little') print(f\"{manifest_off=}\") f.seek(manifest_off,0) manifest_bytes = f.read(manifest_end-manifest_off) manifest", "'big') block_number = int.from_bytes(manifest[4], 'big') block_hash = manifest[5] print(f\"{manifest_ver=}\") print(f\"{block_number=}\") print(f\"block_hash={block_hash.hex()}\") state_chunks =", "== b'\\x01' if has_code: code_prefix = bytes(acc[3][:4]) prefix_map[code_prefix] += 1 for k,v in", "if has_code: code_prefix = bytes(acc[3][:4]) prefix_map[code_prefix] += 1 for k,v in prefix_map.items(): print(f\"{k.hex()}", "# Processes OpenEthereum warp snapshot and collects 4-byte code prefixes of all accounts.", "b'\\x01' if has_code: code_prefix = bytes(acc[3][:4]) prefix_map[code_prefix] += 1 for k,v in prefix_map.items():", "= f.tell() print(f\"{size=}\") f.seek(-8,2) manifest_end = f.tell() manifest_off_bytes = f.read(8) print(f\"{manifest_off_bytes=}\") manifest_off =", "manifest_off = int.from_bytes(manifest_off_bytes, 'little') print(f\"{manifest_off=}\") f.seek(manifest_off,0) manifest_bytes = f.read(manifest_end-manifest_off) manifest = rlp.decode(manifest_bytes) manifest_ver", "print(f\"{size=}\") f.seek(-8,2) manifest_end = f.tell() manifest_off_bytes = f.read(8) print(f\"{manifest_off_bytes=}\") manifest_off = int.from_bytes(manifest_off_bytes, 'little')", "manifest[5] print(f\"{manifest_ver=}\") print(f\"{block_number=}\") print(f\"block_hash={block_hash.hex()}\") state_chunks = manifest[1] num_chunks=len(state_chunks) print(f\"{num_chunks=}\") for i in range(num_chunks):", "manifest_bytes = f.read(manifest_end-manifest_off) manifest = rlp.decode(manifest_bytes) manifest_ver = int.from_bytes(manifest[0], 'big') block_number = int.from_bytes(manifest[4],", "sys.argv[1] print(f\"{filename=}\") with open(filename, 'rb') as f: f.seek(0,2) size = f.tell() print(f\"{size=}\") f.seek(-8,2)", "print(f\"{filename=}\") with open(filename, 'rb') as f: f.seek(0,2) size = f.tell() print(f\"{size=}\") f.seek(-8,2) manifest_end", "all accounts. # # openethereum --chain=kovan snapshot --snapshot-threads=8 snapshot.warp # warp2code-prefixes.py snapshot.warp import", "print(f\"block_hash={block_hash.hex()}\") state_chunks = manifest[1] num_chunks=len(state_chunks) print(f\"{num_chunks=}\") for i in range(num_chunks): info = state_chunks[i]", "= rlp.decode(chunk_bytes) print(f\" uncompressed_len={len(chunk_bytes)} num_accounts={len(chunk)}\", flush=True) for entry in chunk: acc = entry[1]", "# openethereum --chain=kovan snapshot --snapshot-threads=8 snapshot.warp # warp2code-prefixes.py snapshot.warp import sys import rlp", "size = f.tell() print(f\"{size=}\") f.seek(-8,2) manifest_end = f.tell() manifest_off_bytes = f.read(8) print(f\"{manifest_off_bytes=}\") manifest_off", "acc[2] == b'\\x01' if has_code: code_prefix = bytes(acc[3][:4]) prefix_map[code_prefix] += 1 for k,v", "f.read(manifest_end-manifest_off) manifest = rlp.decode(manifest_bytes) manifest_ver = int.from_bytes(manifest[0], 'big') block_number = int.from_bytes(manifest[4], 'big') block_hash", "= acc[2] == b'\\x01' if has_code: code_prefix = bytes(acc[3][:4]) prefix_map[code_prefix] += 1 for", "as f: f.seek(0,2) size = f.tell() print(f\"{size=}\") f.seek(-8,2) manifest_end = f.tell() manifest_off_bytes =", "acc = entry[1] has_code = acc[2] == b'\\x01' if has_code: code_prefix = bytes(acc[3][:4])", "of all accounts. # # openethereum --chain=kovan snapshot --snapshot-threads=8 snapshot.warp # warp2code-prefixes.py snapshot.warp", "f: f.seek(0,2) size = f.tell() print(f\"{size=}\") f.seek(-8,2) manifest_end = f.tell() manifest_off_bytes = f.read(8)", "# warp2code-prefixes.py snapshot.warp import sys import rlp import snappy import collections prefix_map =", "print(f\"{manifest_ver=}\") print(f\"{block_number=}\") print(f\"block_hash={block_hash.hex()}\") state_chunks = manifest[1] num_chunks=len(state_chunks) print(f\"{num_chunks=}\") for i in range(num_chunks): info", "rlp.decode(manifest_bytes) manifest_ver = int.from_bytes(manifest[0], 'big') block_number = int.from_bytes(manifest[4], 'big') block_hash = manifest[5] print(f\"{manifest_ver=}\")", "f.tell() manifest_off_bytes = f.read(8) print(f\"{manifest_off_bytes=}\") manifest_off = int.from_bytes(manifest_off_bytes, 'little') print(f\"{manifest_off=}\") f.seek(manifest_off,0) manifest_bytes =", "prefix_map = collections.defaultdict(int) filename = sys.argv[1] print(f\"{filename=}\") with open(filename, 'rb') as f: f.seek(0,2)", "chunk_pos = int.from_bytes(info[2], 'big') print(f\"{i}/{num_chunks}: {chunk_pos=} {chunk_len=}\", end='') f.seek(chunk_pos) chunk_compressed = f.read(chunk_len) chunk_bytes", "'big') print(f\"{i}/{num_chunks}: {chunk_pos=} {chunk_len=}\", end='') f.seek(chunk_pos) chunk_compressed = f.read(chunk_len) chunk_bytes = snappy.uncompress(chunk_compressed) chunk", "f.read(8) print(f\"{manifest_off_bytes=}\") manifest_off = int.from_bytes(manifest_off_bytes, 'little') print(f\"{manifest_off=}\") f.seek(manifest_off,0) manifest_bytes = f.read(manifest_end-manifest_off) manifest =", "= int.from_bytes(manifest_off_bytes, 'little') print(f\"{manifest_off=}\") f.seek(manifest_off,0) manifest_bytes = f.read(manifest_end-manifest_off) manifest = rlp.decode(manifest_bytes) manifest_ver =", "for i in range(num_chunks): info = state_chunks[i] chunk_len = int.from_bytes(info[1], 'big') chunk_pos =", "manifest = rlp.decode(manifest_bytes) manifest_ver = int.from_bytes(manifest[0], 'big') block_number = int.from_bytes(manifest[4], 'big') block_hash =", "end='') f.seek(chunk_pos) chunk_compressed = f.read(chunk_len) chunk_bytes = snappy.uncompress(chunk_compressed) chunk = rlp.decode(chunk_bytes) print(f\" uncompressed_len={len(chunk_bytes)}", "has_code = acc[2] == b'\\x01' if has_code: code_prefix = bytes(acc[3][:4]) prefix_map[code_prefix] += 1", "has_code: code_prefix = bytes(acc[3][:4]) prefix_map[code_prefix] += 1 for k,v in prefix_map.items(): print(f\"{k.hex()} :", "chunk_bytes = snappy.uncompress(chunk_compressed) chunk = rlp.decode(chunk_bytes) print(f\" uncompressed_len={len(chunk_bytes)} num_accounts={len(chunk)}\", flush=True) for entry in", "entry[1] has_code = acc[2] == b'\\x01' if has_code: code_prefix = bytes(acc[3][:4]) prefix_map[code_prefix] +=", "print(f\"{manifest_off_bytes=}\") manifest_off = int.from_bytes(manifest_off_bytes, 'little') print(f\"{manifest_off=}\") f.seek(manifest_off,0) manifest_bytes = f.read(manifest_end-manifest_off) manifest = rlp.decode(manifest_bytes)", "entry in chunk: acc = entry[1] has_code = acc[2] == b'\\x01' if has_code:", "collections.defaultdict(int) filename = sys.argv[1] print(f\"{filename=}\") with open(filename, 'rb') as f: f.seek(0,2) size =", "rlp.decode(chunk_bytes) print(f\" uncompressed_len={len(chunk_bytes)} num_accounts={len(chunk)}\", flush=True) for entry in chunk: acc = entry[1] has_code", "warp2code-prefixes.py snapshot.warp import sys import rlp import snappy import collections prefix_map = collections.defaultdict(int)", "in chunk: acc = entry[1] has_code = acc[2] == b'\\x01' if has_code: code_prefix", "open(filename, 'rb') as f: f.seek(0,2) size = f.tell() print(f\"{size=}\") f.seek(-8,2) manifest_end = f.tell()", "= int.from_bytes(info[1], 'big') chunk_pos = int.from_bytes(info[2], 'big') print(f\"{i}/{num_chunks}: {chunk_pos=} {chunk_len=}\", end='') f.seek(chunk_pos) chunk_compressed", "int.from_bytes(info[2], 'big') print(f\"{i}/{num_chunks}: {chunk_pos=} {chunk_len=}\", end='') f.seek(chunk_pos) chunk_compressed = f.read(chunk_len) chunk_bytes = snappy.uncompress(chunk_compressed)", "f.tell() print(f\"{size=}\") f.seek(-8,2) manifest_end = f.tell() manifest_off_bytes = f.read(8) print(f\"{manifest_off_bytes=}\") manifest_off = int.from_bytes(manifest_off_bytes,", "= int.from_bytes(manifest[0], 'big') block_number = int.from_bytes(manifest[4], 'big') block_hash = manifest[5] print(f\"{manifest_ver=}\") print(f\"{block_number=}\") print(f\"block_hash={block_hash.hex()}\")", "block_hash = manifest[5] print(f\"{manifest_ver=}\") print(f\"{block_number=}\") print(f\"block_hash={block_hash.hex()}\") state_chunks = manifest[1] num_chunks=len(state_chunks) print(f\"{num_chunks=}\") for i", "f.seek(manifest_off,0) manifest_bytes = f.read(manifest_end-manifest_off) manifest = rlp.decode(manifest_bytes) manifest_ver = int.from_bytes(manifest[0], 'big') block_number =", "= sys.argv[1] print(f\"{filename=}\") with open(filename, 'rb') as f: f.seek(0,2) size = f.tell() print(f\"{size=}\")", "filename = sys.argv[1] print(f\"{filename=}\") with open(filename, 'rb') as f: f.seek(0,2) size = f.tell()", "prefixes of all accounts. # # openethereum --chain=kovan snapshot --snapshot-threads=8 snapshot.warp # warp2code-prefixes.py", "openethereum --chain=kovan snapshot --snapshot-threads=8 snapshot.warp # warp2code-prefixes.py snapshot.warp import sys import rlp import", "snappy.uncompress(chunk_compressed) chunk = rlp.decode(chunk_bytes) print(f\" uncompressed_len={len(chunk_bytes)} num_accounts={len(chunk)}\", flush=True) for entry in chunk: acc", "accounts. # # openethereum --chain=kovan snapshot --snapshot-threads=8 snapshot.warp # warp2code-prefixes.py snapshot.warp import sys", "and collects 4-byte code prefixes of all accounts. # # openethereum --chain=kovan snapshot", "--snapshot-threads=8 snapshot.warp # warp2code-prefixes.py snapshot.warp import sys import rlp import snappy import collections", "'big') chunk_pos = int.from_bytes(info[2], 'big') print(f\"{i}/{num_chunks}: {chunk_pos=} {chunk_len=}\", end='') f.seek(chunk_pos) chunk_compressed = f.read(chunk_len)", "code_prefix = bytes(acc[3][:4]) prefix_map[code_prefix] += 1 for k,v in prefix_map.items(): print(f\"{k.hex()} : {v}\")", "state_chunks[i] chunk_len = int.from_bytes(info[1], 'big') chunk_pos = int.from_bytes(info[2], 'big') print(f\"{i}/{num_chunks}: {chunk_pos=} {chunk_len=}\", end='')", "snapshot --snapshot-threads=8 snapshot.warp # warp2code-prefixes.py snapshot.warp import sys import rlp import snappy import", "manifest_off_bytes = f.read(8) print(f\"{manifest_off_bytes=}\") manifest_off = int.from_bytes(manifest_off_bytes, 'little') print(f\"{manifest_off=}\") f.seek(manifest_off,0) manifest_bytes = f.read(manifest_end-manifest_off)", "'rb') as f: f.seek(0,2) size = f.tell() print(f\"{size=}\") f.seek(-8,2) manifest_end = f.tell() manifest_off_bytes", "collects 4-byte code prefixes of all accounts. # # openethereum --chain=kovan snapshot --snapshot-threads=8", "= entry[1] has_code = acc[2] == b'\\x01' if has_code: code_prefix = bytes(acc[3][:4]) prefix_map[code_prefix]", "chunk_len = int.from_bytes(info[1], 'big') chunk_pos = int.from_bytes(info[2], 'big') print(f\"{i}/{num_chunks}: {chunk_pos=} {chunk_len=}\", end='') f.seek(chunk_pos)", "= f.tell() manifest_off_bytes = f.read(8) print(f\"{manifest_off_bytes=}\") manifest_off = int.from_bytes(manifest_off_bytes, 'little') print(f\"{manifest_off=}\") f.seek(manifest_off,0) manifest_bytes", "num_chunks=len(state_chunks) print(f\"{num_chunks=}\") for i in range(num_chunks): info = state_chunks[i] chunk_len = int.from_bytes(info[1], 'big')", "flush=True) for entry in chunk: acc = entry[1] has_code = acc[2] == b'\\x01'", "for entry in chunk: acc = entry[1] has_code = acc[2] == b'\\x01' if", "print(f\"{manifest_off=}\") f.seek(manifest_off,0) manifest_bytes = f.read(manifest_end-manifest_off) manifest = rlp.decode(manifest_bytes) manifest_ver = int.from_bytes(manifest[0], 'big') block_number", "= manifest[1] num_chunks=len(state_chunks) print(f\"{num_chunks=}\") for i in range(num_chunks): info = state_chunks[i] chunk_len =", "print(f\"{num_chunks=}\") for i in range(num_chunks): info = state_chunks[i] chunk_len = int.from_bytes(info[1], 'big') chunk_pos", "i in range(num_chunks): info = state_chunks[i] chunk_len = int.from_bytes(info[1], 'big') chunk_pos = int.from_bytes(info[2],", "snapshot and collects 4-byte code prefixes of all accounts. # # openethereum --chain=kovan", "import sys import rlp import snappy import collections prefix_map = collections.defaultdict(int) filename =", "= int.from_bytes(manifest[4], 'big') block_hash = manifest[5] print(f\"{manifest_ver=}\") print(f\"{block_number=}\") print(f\"block_hash={block_hash.hex()}\") state_chunks = manifest[1] num_chunks=len(state_chunks)", "OpenEthereum warp snapshot and collects 4-byte code prefixes of all accounts. # #", "range(num_chunks): info = state_chunks[i] chunk_len = int.from_bytes(info[1], 'big') chunk_pos = int.from_bytes(info[2], 'big') print(f\"{i}/{num_chunks}:", "num_accounts={len(chunk)}\", flush=True) for entry in chunk: acc = entry[1] has_code = acc[2] ==", "print(f\"{block_number=}\") print(f\"block_hash={block_hash.hex()}\") state_chunks = manifest[1] num_chunks=len(state_chunks) print(f\"{num_chunks=}\") for i in range(num_chunks): info =", "4-byte code prefixes of all accounts. # # openethereum --chain=kovan snapshot --snapshot-threads=8 snapshot.warp", "f.seek(-8,2) manifest_end = f.tell() manifest_off_bytes = f.read(8) print(f\"{manifest_off_bytes=}\") manifest_off = int.from_bytes(manifest_off_bytes, 'little') print(f\"{manifest_off=}\")", "chunk: acc = entry[1] has_code = acc[2] == b'\\x01' if has_code: code_prefix =", "block_number = int.from_bytes(manifest[4], 'big') block_hash = manifest[5] print(f\"{manifest_ver=}\") print(f\"{block_number=}\") print(f\"block_hash={block_hash.hex()}\") state_chunks = manifest[1]", "python # Processes OpenEthereum warp snapshot and collects 4-byte code prefixes of all", "= rlp.decode(manifest_bytes) manifest_ver = int.from_bytes(manifest[0], 'big') block_number = int.from_bytes(manifest[4], 'big') block_hash = manifest[5]", "state_chunks = manifest[1] num_chunks=len(state_chunks) print(f\"{num_chunks=}\") for i in range(num_chunks): info = state_chunks[i] chunk_len", "snappy import collections prefix_map = collections.defaultdict(int) filename = sys.argv[1] print(f\"{filename=}\") with open(filename, 'rb')", "chunk = rlp.decode(chunk_bytes) print(f\" uncompressed_len={len(chunk_bytes)} num_accounts={len(chunk)}\", flush=True) for entry in chunk: acc =", "f.read(chunk_len) chunk_bytes = snappy.uncompress(chunk_compressed) chunk = rlp.decode(chunk_bytes) print(f\" uncompressed_len={len(chunk_bytes)} num_accounts={len(chunk)}\", flush=True) for entry", "Processes OpenEthereum warp snapshot and collects 4-byte code prefixes of all accounts. #", "warp snapshot and collects 4-byte code prefixes of all accounts. # # openethereum" ]
[ "return source = msg['source'] mode = msg['mode'] buff = OutputWriter(id, self) with contextlib.redirect_stdout(buff),", "test() except BaseException: err = traceback.format_exc() + repr(test_ns) else: err = None self.send([id,", "print(repr(result)) # If we have exercises, run them as tests if msg['exercises']: if", "= {} test_ns.update( source=source, result=result, output=buff.getvalue(), ) exec(msg['exercises'], test_ns) tests = [] for", "body. \"\"\" msg = event.data try: id = msg['id'] except KeyError: return source", "= [] def write(self, text): \"\"\"Write output to the screen.\"\"\" self.buf.append(text) self.window.send([self.id, 'output',", "contextlib.redirect_stdout(buff), contextlib.redirect_stderr(buff): self.send([id, 'ready', 0]) try: code = compile(source, filename='python-now', mode=mode) namespace =", "exercises, run them as tests if msg['exercises']: if mode == 'exec': test_ns =", "output to the screen.\"\"\" self.buf.append(text) self.window.send([self.id, 'output', text]) def getvalue(self): \"\"\"Get everything that", "mode == 'exec': test_ns = namespace.copy() else: test_ns = {} test_ns.update( source=source, result=result,", "= OutputWriter(id, self) with contextlib.redirect_stdout(buff), contextlib.redirect_stderr(buff): self.send([id, 'ready', 0]) try: code = compile(source,", "test in test_ns.items(): if name.startswith('test_') and callable(test): tests.append(test) for test_id, test in enumerate(tests):", "__init__(self, id, window): self.id = id self.window = window self.buf = [] def", "if mode == 'exec': test_ns = namespace.copy() else: test_ns = {} test_ns.update( source=source,", "test_ns.update( source=source, result=result, output=buff.getvalue(), ) exec(msg['exercises'], test_ns) tests = [] for name, test", "\"\"\"Get everything that was printed.\"\"\" return ''.join(self.buf) @bind(self, \"message\") def on_message(event): \"\"\"Handle a", "bind, self import contextlib import traceback class OutputWriter: def __init__(self, id, window): self.id", "id, window): self.id = id self.window = window self.buf = [] def write(self,", "[] def write(self, text): \"\"\"Write output to the screen.\"\"\" self.buf.append(text) self.window.send([self.id, 'output', text])", "In web workers, \"window\" is replaced by \"self\". from browser import bind, self", "as tests if msg['exercises']: if mode == 'exec': test_ns = namespace.copy() else: test_ns", "exec(msg['exercises'], test_ns) tests = [] for name, test in test_ns.items(): if name.startswith('test_') and", "namespace.copy() else: test_ns = {} test_ns.update( source=source, result=result, output=buff.getvalue(), ) exec(msg['exercises'], test_ns) tests", "class OutputWriter: def __init__(self, id, window): self.id = id self.window = window self.buf", "if result is not None: print(repr(result)) # If we have exercises, run them", "None: print(repr(result)) # If we have exercises, run them as tests if msg['exercises']:", "else: test_ns = {} test_ns.update( source=source, result=result, output=buff.getvalue(), ) exec(msg['exercises'], test_ns) tests =", "if msg['exercises']: if mode == 'exec': test_ns = namespace.copy() else: test_ns = {}", "= [] for name, test in test_ns.items(): if name.startswith('test_') and callable(test): tests.append(test) for", "workers, \"window\" is replaced by \"self\". from browser import bind, self import contextlib", "\"window\" is replaced by \"self\". from browser import bind, self import contextlib import", "sent by the main script. evt.data is the message body. \"\"\" msg =", "replaced by \"self\". from browser import bind, self import contextlib import traceback class", "= msg['source'] mode = msg['mode'] buff = OutputWriter(id, self) with contextlib.redirect_stdout(buff), contextlib.redirect_stderr(buff): self.send([id,", "self) with contextlib.redirect_stdout(buff), contextlib.redirect_stderr(buff): self.send([id, 'ready', 0]) try: code = compile(source, filename='python-now', mode=mode)", "self.send([id, 'ready', 0]) try: code = compile(source, filename='python-now', mode=mode) namespace = { '__name__':", "except BaseException: self.send([id, 'err', traceback.format_exc()]) else: if result is not None: print(repr(result)) #", "callable(test): tests.append(test) for test_id, test in enumerate(tests): try: test() except BaseException: err =", "with contextlib.redirect_stdout(buff), contextlib.redirect_stderr(buff): self.send([id, 'ready', 0]) try: code = compile(source, filename='python-now', mode=mode) namespace", "script.\"\"\" # In web workers, \"window\" is replaced by \"self\". from browser import", "run them as tests if msg['exercises']: if mode == 'exec': test_ns = namespace.copy()", "OutputWriter(id, self) with contextlib.redirect_stdout(buff), contextlib.redirect_stderr(buff): self.send([id, 'ready', 0]) try: code = compile(source, filename='python-now',", "import bind, self import contextlib import traceback class OutputWriter: def __init__(self, id, window):", "exec(code, namespace) except BaseException: self.send([id, 'err', traceback.format_exc()]) else: if result is not None:", "test_id, test in enumerate(tests): try: test() except BaseException: err = traceback.format_exc() + repr(test_ns)", "contextlib import traceback class OutputWriter: def __init__(self, id, window): self.id = id self.window", "from browser import bind, self import contextlib import traceback class OutputWriter: def __init__(self,", "def __init__(self, id, window): self.id = id self.window = window self.buf = []", "= window self.buf = [] def write(self, text): \"\"\"Write output to the screen.\"\"\"", "If we have exercises, run them as tests if msg['exercises']: if mode ==", "Worker script.\"\"\" # In web workers, \"window\" is replaced by \"self\". from browser", "is replaced by \"self\". from browser import bind, self import contextlib import traceback", "we have exercises, run them as tests if msg['exercises']: if mode == 'exec':", "self.send([id, 'err', traceback.format_exc()]) else: if result is not None: print(repr(result)) # If we", "self.window = window self.buf = [] def write(self, text): \"\"\"Write output to the", "def write(self, text): \"\"\"Write output to the screen.\"\"\" self.buf.append(text) self.window.send([self.id, 'output', text]) def", "\"\"\"Write output to the screen.\"\"\" self.buf.append(text) self.window.send([self.id, 'output', text]) def getvalue(self): \"\"\"Get everything", "except BaseException: err = traceback.format_exc() + repr(test_ns) else: err = None self.send([id, 'ex_result',", "@bind(self, \"message\") def on_message(event): \"\"\"Handle a message sent by the main script. evt.data", "is the message body. \"\"\" msg = event.data try: id = msg['id'] except", "browser import bind, self import contextlib import traceback class OutputWriter: def __init__(self, id,", "0]) try: code = compile(source, filename='python-now', mode=mode) namespace = { '__name__': '__main__', '__filename__':", "err = traceback.format_exc() + repr(test_ns) else: err = None self.send([id, 'ex_result', (test_id, err)])", "namespace = { '__name__': '__main__', '__filename__': '<python-now>' } result = exec(code, namespace) except", "in enumerate(tests): try: test() except BaseException: err = traceback.format_exc() + repr(test_ns) else: err", "text]) def getvalue(self): \"\"\"Get everything that was printed.\"\"\" return ''.join(self.buf) @bind(self, \"message\") def", "the main script. evt.data is the message body. \"\"\" msg = event.data try:", "tests = [] for name, test in test_ns.items(): if name.startswith('test_') and callable(test): tests.append(test)", "web workers, \"window\" is replaced by \"self\". from browser import bind, self import", "is not None: print(repr(result)) # If we have exercises, run them as tests", "= msg['id'] except KeyError: return source = msg['source'] mode = msg['mode'] buff =", "result=result, output=buff.getvalue(), ) exec(msg['exercises'], test_ns) tests = [] for name, test in test_ns.items():", "traceback.format_exc()]) else: if result is not None: print(repr(result)) # If we have exercises,", "enumerate(tests): try: test() except BaseException: err = traceback.format_exc() + repr(test_ns) else: err =", "''.join(self.buf) @bind(self, \"message\") def on_message(event): \"\"\"Handle a message sent by the main script.", "contextlib.redirect_stderr(buff): self.send([id, 'ready', 0]) try: code = compile(source, filename='python-now', mode=mode) namespace = {", "filename='python-now', mode=mode) namespace = { '__name__': '__main__', '__filename__': '<python-now>' } result = exec(code,", "= { '__name__': '__main__', '__filename__': '<python-now>' } result = exec(code, namespace) except BaseException:", "not None: print(repr(result)) # If we have exercises, run them as tests if", "test_ns = namespace.copy() else: test_ns = {} test_ns.update( source=source, result=result, output=buff.getvalue(), ) exec(msg['exercises'],", "= compile(source, filename='python-now', mode=mode) namespace = { '__name__': '__main__', '__filename__': '<python-now>' } result", "tests if msg['exercises']: if mode == 'exec': test_ns = namespace.copy() else: test_ns =", "id self.window = window self.buf = [] def write(self, text): \"\"\"Write output to", "OutputWriter: def __init__(self, id, window): self.id = id self.window = window self.buf =", "def on_message(event): \"\"\"Handle a message sent by the main script. evt.data is the", "try: test() except BaseException: err = traceback.format_exc() + repr(test_ns) else: err = None", "result is not None: print(repr(result)) # If we have exercises, run them as", "getvalue(self): \"\"\"Get everything that was printed.\"\"\" return ''.join(self.buf) @bind(self, \"message\") def on_message(event): \"\"\"Handle", "msg['exercises']: if mode == 'exec': test_ns = namespace.copy() else: test_ns = {} test_ns.update(", "\"\"\" msg = event.data try: id = msg['id'] except KeyError: return source =", "BaseException: err = traceback.format_exc() + repr(test_ns) else: err = None self.send([id, 'ex_result', (test_id,", "KeyError: return source = msg['source'] mode = msg['mode'] buff = OutputWriter(id, self) with", "= id self.window = window self.buf = [] def write(self, text): \"\"\"Write output", "everything that was printed.\"\"\" return ''.join(self.buf) @bind(self, \"message\") def on_message(event): \"\"\"Handle a message", "window): self.id = id self.window = window self.buf = [] def write(self, text):", "try: id = msg['id'] except KeyError: return source = msg['source'] mode = msg['mode']", "have exercises, run them as tests if msg['exercises']: if mode == 'exec': test_ns", "'output', text]) def getvalue(self): \"\"\"Get everything that was printed.\"\"\" return ''.join(self.buf) @bind(self, \"message\")", "self.buf = [] def write(self, text): \"\"\"Write output to the screen.\"\"\" self.buf.append(text) self.window.send([self.id,", "[] for name, test in test_ns.items(): if name.startswith('test_') and callable(test): tests.append(test) for test_id,", "'__name__': '__main__', '__filename__': '<python-now>' } result = exec(code, namespace) except BaseException: self.send([id, 'err',", "window self.buf = [] def write(self, text): \"\"\"Write output to the screen.\"\"\" self.buf.append(text)", "to the screen.\"\"\" self.buf.append(text) self.window.send([self.id, 'output', text]) def getvalue(self): \"\"\"Get everything that was", "'ready', 0]) try: code = compile(source, filename='python-now', mode=mode) namespace = { '__name__': '__main__',", "= msg['mode'] buff = OutputWriter(id, self) with contextlib.redirect_stdout(buff), contextlib.redirect_stderr(buff): self.send([id, 'ready', 0]) try:", "== 'exec': test_ns = namespace.copy() else: test_ns = {} test_ns.update( source=source, result=result, output=buff.getvalue(),", "write(self, text): \"\"\"Write output to the screen.\"\"\" self.buf.append(text) self.window.send([self.id, 'output', text]) def getvalue(self):", "def getvalue(self): \"\"\"Get everything that was printed.\"\"\" return ''.join(self.buf) @bind(self, \"message\") def on_message(event):", "them as tests if msg['exercises']: if mode == 'exec': test_ns = namespace.copy() else:", "message sent by the main script. evt.data is the message body. \"\"\" msg", "= exec(code, namespace) except BaseException: self.send([id, 'err', traceback.format_exc()]) else: if result is not", "buff = OutputWriter(id, self) with contextlib.redirect_stdout(buff), contextlib.redirect_stderr(buff): self.send([id, 'ready', 0]) try: code =", "output=buff.getvalue(), ) exec(msg['exercises'], test_ns) tests = [] for name, test in test_ns.items(): if", "mode=mode) namespace = { '__name__': '__main__', '__filename__': '<python-now>' } result = exec(code, namespace)", "screen.\"\"\" self.buf.append(text) self.window.send([self.id, 'output', text]) def getvalue(self): \"\"\"Get everything that was printed.\"\"\" return", "test_ns.items(): if name.startswith('test_') and callable(test): tests.append(test) for test_id, test in enumerate(tests): try: test()", "code = compile(source, filename='python-now', mode=mode) namespace = { '__name__': '__main__', '__filename__': '<python-now>' }", "name, test in test_ns.items(): if name.startswith('test_') and callable(test): tests.append(test) for test_id, test in", "test in enumerate(tests): try: test() except BaseException: err = traceback.format_exc() + repr(test_ns) else:", "for name, test in test_ns.items(): if name.startswith('test_') and callable(test): tests.append(test) for test_id, test", "name.startswith('test_') and callable(test): tests.append(test) for test_id, test in enumerate(tests): try: test() except BaseException:", "for test_id, test in enumerate(tests): try: test() except BaseException: err = traceback.format_exc() +", "except KeyError: return source = msg['source'] mode = msg['mode'] buff = OutputWriter(id, self)", "self.buf.append(text) self.window.send([self.id, 'output', text]) def getvalue(self): \"\"\"Get everything that was printed.\"\"\" return ''.join(self.buf)", "= event.data try: id = msg['id'] except KeyError: return source = msg['source'] mode", "{} test_ns.update( source=source, result=result, output=buff.getvalue(), ) exec(msg['exercises'], test_ns) tests = [] for name,", "= namespace.copy() else: test_ns = {} test_ns.update( source=source, result=result, output=buff.getvalue(), ) exec(msg['exercises'], test_ns)", "on_message(event): \"\"\"Handle a message sent by the main script. evt.data is the message", "id = msg['id'] except KeyError: return source = msg['source'] mode = msg['mode'] buff", "text): \"\"\"Write output to the screen.\"\"\" self.buf.append(text) self.window.send([self.id, 'output', text]) def getvalue(self): \"\"\"Get", "self.id = id self.window = window self.buf = [] def write(self, text): \"\"\"Write", "self import contextlib import traceback class OutputWriter: def __init__(self, id, window): self.id =", "} result = exec(code, namespace) except BaseException: self.send([id, 'err', traceback.format_exc()]) else: if result", "tests.append(test) for test_id, test in enumerate(tests): try: test() except BaseException: err = traceback.format_exc()", "was printed.\"\"\" return ''.join(self.buf) @bind(self, \"message\") def on_message(event): \"\"\"Handle a message sent by", "BaseException: self.send([id, 'err', traceback.format_exc()]) else: if result is not None: print(repr(result)) # If", "event.data try: id = msg['id'] except KeyError: return source = msg['source'] mode =", "test_ns = {} test_ns.update( source=source, result=result, output=buff.getvalue(), ) exec(msg['exercises'], test_ns) tests = []", "import contextlib import traceback class OutputWriter: def __init__(self, id, window): self.id = id", "the screen.\"\"\" self.buf.append(text) self.window.send([self.id, 'output', text]) def getvalue(self): \"\"\"Get everything that was printed.\"\"\"", ") exec(msg['exercises'], test_ns) tests = [] for name, test in test_ns.items(): if name.startswith('test_')", "script. evt.data is the message body. \"\"\" msg = event.data try: id =", "compile(source, filename='python-now', mode=mode) namespace = { '__name__': '__main__', '__filename__': '<python-now>' } result =", "msg['id'] except KeyError: return source = msg['source'] mode = msg['mode'] buff = OutputWriter(id,", "return ''.join(self.buf) @bind(self, \"message\") def on_message(event): \"\"\"Handle a message sent by the main", "a message sent by the main script. evt.data is the message body. \"\"\"", "message body. \"\"\" msg = event.data try: id = msg['id'] except KeyError: return", "'__main__', '__filename__': '<python-now>' } result = exec(code, namespace) except BaseException: self.send([id, 'err', traceback.format_exc()])", "else: if result is not None: print(repr(result)) # If we have exercises, run", "evt.data is the message body. \"\"\" msg = event.data try: id = msg['id']", "printed.\"\"\" return ''.join(self.buf) @bind(self, \"message\") def on_message(event): \"\"\"Handle a message sent by the", "try: code = compile(source, filename='python-now', mode=mode) namespace = { '__name__': '__main__', '__filename__': '<python-now>'", "in test_ns.items(): if name.startswith('test_') and callable(test): tests.append(test) for test_id, test in enumerate(tests): try:", "if name.startswith('test_') and callable(test): tests.append(test) for test_id, test in enumerate(tests): try: test() except", "msg['source'] mode = msg['mode'] buff = OutputWriter(id, self) with contextlib.redirect_stdout(buff), contextlib.redirect_stderr(buff): self.send([id, 'ready',", "msg = event.data try: id = msg['id'] except KeyError: return source = msg['source']", "that was printed.\"\"\" return ''.join(self.buf) @bind(self, \"message\") def on_message(event): \"\"\"Handle a message sent", "by the main script. evt.data is the message body. \"\"\" msg = event.data", "mode = msg['mode'] buff = OutputWriter(id, self) with contextlib.redirect_stdout(buff), contextlib.redirect_stderr(buff): self.send([id, 'ready', 0])", "self.window.send([self.id, 'output', text]) def getvalue(self): \"\"\"Get everything that was printed.\"\"\" return ''.join(self.buf) @bind(self,", "\"\"\"Handle a message sent by the main script. evt.data is the message body.", "test_ns) tests = [] for name, test in test_ns.items(): if name.startswith('test_') and callable(test):", "\"\"\"Web Worker script.\"\"\" # In web workers, \"window\" is replaced by \"self\". from", "'err', traceback.format_exc()]) else: if result is not None: print(repr(result)) # If we have", "\"self\". from browser import bind, self import contextlib import traceback class OutputWriter: def", "namespace) except BaseException: self.send([id, 'err', traceback.format_exc()]) else: if result is not None: print(repr(result))", "{ '__name__': '__main__', '__filename__': '<python-now>' } result = exec(code, namespace) except BaseException: self.send([id,", "and callable(test): tests.append(test) for test_id, test in enumerate(tests): try: test() except BaseException: err", "'<python-now>' } result = exec(code, namespace) except BaseException: self.send([id, 'err', traceback.format_exc()]) else: if", "'__filename__': '<python-now>' } result = exec(code, namespace) except BaseException: self.send([id, 'err', traceback.format_exc()]) else:", "import traceback class OutputWriter: def __init__(self, id, window): self.id = id self.window =", "# In web workers, \"window\" is replaced by \"self\". from browser import bind,", "result = exec(code, namespace) except BaseException: self.send([id, 'err', traceback.format_exc()]) else: if result is", "by \"self\". from browser import bind, self import contextlib import traceback class OutputWriter:", "traceback class OutputWriter: def __init__(self, id, window): self.id = id self.window = window", "'exec': test_ns = namespace.copy() else: test_ns = {} test_ns.update( source=source, result=result, output=buff.getvalue(), )", "source=source, result=result, output=buff.getvalue(), ) exec(msg['exercises'], test_ns) tests = [] for name, test in", "\"message\") def on_message(event): \"\"\"Handle a message sent by the main script. evt.data is", "the message body. \"\"\" msg = event.data try: id = msg['id'] except KeyError:", "main script. evt.data is the message body. \"\"\" msg = event.data try: id", "# If we have exercises, run them as tests if msg['exercises']: if mode", "source = msg['source'] mode = msg['mode'] buff = OutputWriter(id, self) with contextlib.redirect_stdout(buff), contextlib.redirect_stderr(buff):", "msg['mode'] buff = OutputWriter(id, self) with contextlib.redirect_stdout(buff), contextlib.redirect_stderr(buff): self.send([id, 'ready', 0]) try: code" ]
[ "feature, by default 'mean' slow_operation : str, {'mean','var','std'} operation to be performed for", "exponential moving average is calculated, by default False initialize_span : int, optional the", "smoothing_operation: str = \"mean\", initialize_using_operation: bool = False, initialize_span: int = None, min_periods:", "'mean' slow_operation : str, {'mean','var','std'} operation to be performed for the slow moving", "span over which 'operation' would be performed for initialization, by default None min_periods", "fast_operation : str, {'mean','var','std'} operation to be performed for the fast moving feature,", "by default 'mean' smoothing_operation : str, optional operation to be performed for the", "Ignore missing values when calculating weights; specify True to reproduce pre-0.15.0 behavior, by", "self.smoothing_period = smoothing_period self.return_histogram = return_histogram self.initialize_using_operation = initialize_using_operation self.initialize_span = initialize_span def", "first_fit=first_fit) macd = self._macd_object.fit(dataframe=raw_macd, first_fit=first_fit) return raw_macd - macd if self.return_histogram else macd", "the last phase, will be utilized for calculation }, by default True \"\"\"", "result is NA), by default 0 ignore_na : bool, optional Ignore missing values", "bool, optional Ignore missing values when calculating weights; specify True to reproduce pre-0.15.0", "for the fast moving feature, by default 'mean' slow_operation : str, {'mean','var','std'} operation", "behavior, by default False axis : int, optional The axis to use. The", "None, min_periods: int = 0, ignore_na: bool = False, axis: int = 0,", "of observations in window required to have a value (otherwise result is NA),", "smoothing_operation self.smoothing_period = smoothing_period self.return_histogram = return_histogram self.initialize_using_operation = initialize_using_operation self.initialize_span = initialize_span", "decay in terms of span, for the smoothing moving feature, by default 9", ": int, optional The axis to use. The value 0 identifies the rows,", "and datetime64[ns] dtype, by default None \"\"\" self.span_fast = fast_period self.span_slow = slow_period", "self.times = times self.fast_operation = fast_operation self.slow_operation = slow_operation self.smoothing_operation = smoothing_operation self.smoothing_period", "pd.Series] dataframe containing column values to create feature over first_fit : bool, optional", "False axis : int, optional The axis to use. The value 0 identifies", "smoothing moving feature, by default 'mean' initialize_using_operation : bool, optional If True, then", "columns, by default 0 times : str, optional Times corresponding to the observations.", "and then the exponential moving average is calculated, by default False initialize_span :", "): \"\"\" For your training/initial fit phase (very first fit) use fit_first=True, and", "axis=self.axis, times=self.times, operation=self.smoothing_operation, initialize_using_operation=self.initialize_using_operation, initialize_span=self.initialize_span, ) raw_macd = self._raw_macd_object.fit(dataframe, first_fit=first_fit) macd = self._macd_object.fit(dataframe=raw_macd,", "from NitroFE.time_based_features.moving_average_features.moving_average_features import ( ExponentialMovingFeature, ) class MovingAverageConvergenceDivergence: \"\"\" Provided dataframe must be", ", macd histogram Parameters ---------- dataframe : Union[pd.DataFrame, pd.Series] dataframe containing column values", "to create feature over first_fit : bool, optional Indicator features require past values", "during the last phase, will be utilized for calculation }, by default True", "ascending order. \"\"\" def __init__( self, fast_period: int = 26, slow_period: int =", "calculating for training data (very first fit) Use False, when calculating for subsequent", "identifies the columns, by default 0 times : str, optional Times corresponding to", "to have a value (otherwise result is NA), by default 0 ignore_na :", "value (otherwise result is NA), by default 0 ignore_na : bool, optional Ignore", "optional Times corresponding to the observations. Must be monotonically increasing and datetime64[ns] dtype,", "specify decay in terms of span, for the slow moving feature, by default", "the observations. Must be monotonically increasing and datetime64[ns] dtype, by default None \"\"\"", "= initialize_span def fit( self, dataframe: Union[pd.DataFrame, pd.Series], first_fit: bool = True, ):", "dataframe : Union[pd.DataFrame, pd.Series] dataframe containing column values to create feature over first_fit", "The axis to use. The value 0 identifies the rows, and 1 identifies", "str, optional Times corresponding to the observations. Must be monotonically increasing and datetime64[ns]", "min_periods : int, optional Minimum number of observations in window required to have", "the fast moving feature, by default 'mean' slow_operation : str, {'mean','var','std'} operation to", "be monotonically increasing and datetime64[ns] dtype, by default None \"\"\" self.span_fast = fast_period", "values for calculation. Use True, when calculating for training data (very first fit)", "to use. The value 0 identifies the rows, and 1 identifies the columns,", "of span, for the slow moving feature, by default 26 smoothing_period : int,", "numpy as np import pandas as pd from typing import Union, Callable from", "int, optional Minimum number of observations in window required to have a value", "= ignore_na self.axis = axis self.times = times self.fast_operation = fast_operation self.slow_operation =", "axis to use. The value 0 identifies the rows, and 1 identifies the", "fast_period: int = 26, slow_period: int = 12, smoothing_period: int = 9, fast_operation:", "pandas.core.frame import DataFrame from NitroFE.time_based_features.indicator_features._AbsolutePriceOscillator import ( AbsolutePriceOscillator, ) from NitroFE.time_based_features.moving_average_features.moving_average_features import (", "be utilized for calculation }, by default True \"\"\" if first_fit: self._raw_macd_object =", "self.initialize_span = initialize_span def fit( self, dataframe: Union[pd.DataFrame, pd.Series], first_fit: bool = True,", "fast_operation: str = \"mean\", slow_operation: str = \"mean\", smoothing_operation: str = \"mean\", initialize_using_operation:", "True, then specified 'operation' is performed on the first 'initialize_span' values, and then", "order. \"\"\" def __init__( self, fast_period: int = 26, slow_period: int = 12,", "from typing import Union, Callable from pandas.core.frame import DataFrame from NitroFE.time_based_features.indicator_features._AbsolutePriceOscillator import (", "terms of span, for the slow moving feature, by default 26 smoothing_period :", "default 26 smoothing_period : int, optional specify decay in terms of span, for", ") self._macd_object = ExponentialMovingFeature( span=self.smoothing_period, ignore_na=self.ignore_na, axis=self.axis, times=self.times, operation=self.smoothing_operation, initialize_using_operation=self.initialize_using_operation, initialize_span=self.initialize_span, ) raw_macd", ": bool, optional If True, then specified 'operation' is performed on the first", "the smoothing moving feature, by default 'mean' initialize_using_operation : bool, optional If True,", ": bool, optional Ignore missing values when calculating weights; specify True to reproduce", "initialize_span : int, optional the span over which 'operation' would be performed for", "optional Minimum number of observations in window required to have a value (otherwise", "be performed for initialization, by default None min_periods : int, optional Minimum number", "int, optional specify decay in terms of span, for the slow moving feature,", "\"\"\" def __init__( self, fast_period: int = 26, slow_period: int = 12, smoothing_period:", "have a value (otherwise result is NA), by default 0 ignore_na : bool,", ": str, optional Times corresponding to the observations. Must be monotonically increasing and", "\"\"\" For your training/initial fit phase (very first fit) use fit_first=True, and for", "subsequent testing/production data { in which case the values, which were saved during", "optional Indicator features require past values for calculation. Use True, when calculating for", "axis : int, optional The axis to use. The value 0 identifies the", "= smoothing_operation self.smoothing_period = smoothing_period self.return_histogram = return_histogram self.initialize_using_operation = initialize_using_operation self.initialize_span =", "default False axis : int, optional The axis to use. The value 0", "operation to be performed for the smoothing moving feature, by default 'mean' initialize_using_operation", "require past values for calculation. Use True, when calculating for training data (very", "--> Smoothed signal line , macd histogram Parameters ---------- dataframe : Union[pd.DataFrame, pd.Series]", "use. The value 0 identifies the rows, and 1 identifies the columns, by", "training/initial fit phase (very first fit) use fit_first=True, and for any production/test implementation", "= \"mean\", slow_operation: str = \"mean\", smoothing_operation: str = \"mean\", initialize_using_operation: bool =", "optional Ignore missing values when calculating weights; specify True to reproduce pre-0.15.0 behavior,", "macd histogram Parameters ---------- dataframe : Union[pd.DataFrame, pd.Series] dataframe containing column values to", "the smoothing moving feature, by default 9 fast_operation : str, {'mean','var','std'} operation to", "performed for the fast moving feature, by default 'mean' slow_operation : str, {'mean','var','std'}", "ignore_na : bool, optional Ignore missing values when calculating weights; specify True to", "values, which were saved during the last phase, will be utilized for calculation", "as pd from typing import Union, Callable from pandas.core.frame import DataFrame from NitroFE.time_based_features.indicator_features._AbsolutePriceOscillator", "= 12, smoothing_period: int = 9, fast_operation: str = \"mean\", slow_operation: str =", "first fit) Use False, when calculating for subsequent testing/production data { in which", "in terms of span, for the smoothing moving feature, by default 9 fast_operation", "slow_operation self.smoothing_operation = smoothing_operation self.smoothing_period = smoothing_period self.return_histogram = return_histogram self.initialize_using_operation = initialize_using_operation", "self._raw_macd_object.fit(dataframe, first_fit=first_fit) macd = self._macd_object.fit(dataframe=raw_macd, first_fit=first_fit) return raw_macd - macd if self.return_histogram else", "True, when calculating for training data (very first fit) Use False, when calculating", "slow_period: int = 12, smoothing_period: int = 9, fast_operation: str = \"mean\", slow_operation:", "slow moving feature, by default 'mean' smoothing_operation : str, optional operation to be", "import pandas as pd from typing import Union, Callable from pandas.core.frame import DataFrame", "( AbsolutePriceOscillator, ) from NitroFE.time_based_features.moving_average_features.moving_average_features import ( ExponentialMovingFeature, ) class MovingAverageConvergenceDivergence: \"\"\" Provided", "{'mean','var','std'} operation to be performed for the fast moving feature, by default 'mean'", "fit( self, dataframe: Union[pd.DataFrame, pd.Series], first_fit: bool = True, ): \"\"\" For your", "specified 'operation' is performed on the first 'initialize_span' values, and then the exponential", "Union[pd.DataFrame, pd.Series] dataframe containing column values to create feature over first_fit : bool,", "'mean' smoothing_operation : str, optional operation to be performed for the smoothing moving", "for calculation }, by default True \"\"\" if first_fit: self._raw_macd_object = AbsolutePriceOscillator( fast_period=self.span_fast,", "smoothing_operation : str, optional operation to be performed for the smoothing moving feature,", "= fast_period self.span_slow = slow_period self.min_periods = min_periods self.ignore_na = ignore_na self.axis =", "ExponentialMovingFeature, ) class MovingAverageConvergenceDivergence: \"\"\" Provided dataframe must be in ascending order. \"\"\"", "the span over which 'operation' would be performed for initialization, by default None", "times : str, optional Times corresponding to the observations. Must be monotonically increasing", "feature over first_fit : bool, optional Indicator features require past values for calculation.", "NitroFE.time_based_features.indicator_features._AbsolutePriceOscillator import ( AbsolutePriceOscillator, ) from NitroFE.time_based_features.moving_average_features.moving_average_features import ( ExponentialMovingFeature, ) class MovingAverageConvergenceDivergence:", "initialize_span=self.initialize_span, ) raw_macd = self._raw_macd_object.fit(dataframe, first_fit=first_fit) macd = self._macd_object.fit(dataframe=raw_macd, first_fit=first_fit) return raw_macd -", ": int, optional the span over which 'operation' would be performed for initialization,", "calculation. Use True, when calculating for training data (very first fit) Use False,", "fit_first=False Returns --> Smoothed signal line , macd histogram Parameters ---------- dataframe :", "line , macd histogram Parameters ---------- dataframe : Union[pd.DataFrame, pd.Series] dataframe containing column", "initialize_span=self.initialize_span, ignore_na=self.ignore_na, axis=self.axis, times=self.times, ) self._macd_object = ExponentialMovingFeature( span=self.smoothing_period, ignore_na=self.ignore_na, axis=self.axis, times=self.times, operation=self.smoothing_operation,", "moving feature, by default 'mean' initialize_using_operation : bool, optional If True, then specified", "calculating for subsequent testing/production data { in which case the values, which were", "values, and then the exponential moving average is calculated, by default False initialize_span", "(otherwise result is NA), by default 0 ignore_na : bool, optional Ignore missing", ": bool, optional Indicator features require past values for calculation. Use True, when", "for calculation. Use True, when calculating for training data (very first fit) Use", "fast moving feature, by default 12 slow_period : int, optional specify decay in", "DataFrame from NitroFE.time_based_features.indicator_features._AbsolutePriceOscillator import ( AbsolutePriceOscillator, ) from NitroFE.time_based_features.moving_average_features.moving_average_features import ( ExponentialMovingFeature, )", "---------- dataframe : Union[pd.DataFrame, pd.Series] dataframe containing column values to create feature over", "fit) Use False, when calculating for subsequent testing/production data { in which case", "False, initialize_span: int = None, min_periods: int = 0, ignore_na: bool = False,", "span, for the fast moving feature, by default 12 slow_period : int, optional", "for the smoothing moving feature, by default 'mean' initialize_using_operation : bool, optional If", "by default 12 slow_period : int, optional specify decay in terms of span,", "to reproduce pre-0.15.0 behavior, by default False axis : int, optional The axis", "values when calculating weights; specify True to reproduce pre-0.15.0 behavior, by default False", "min_periods: int = 0, ignore_na: bool = False, axis: int = 0, times:", "int = 0, ignore_na: bool = False, axis: int = 0, times: str", "decay in terms of span, for the fast moving feature, by default 12", "first_fit: self._raw_macd_object = AbsolutePriceOscillator( fast_period=self.span_fast, slow_period=self.span_slow, fast_operation=self.fast_operation, slow_operation=self.slow_operation, min_periods=self.min_periods, initialize_using_operation=self.initialize_using_operation, initialize_span=self.initialize_span, ignore_na=self.ignore_na, axis=self.axis,", "12 slow_period : int, optional specify decay in terms of span, for the", "the slow moving feature, by default 26 smoothing_period : int, optional specify decay", "ExponentialMovingFeature( span=self.smoothing_period, ignore_na=self.ignore_na, axis=self.axis, times=self.times, operation=self.smoothing_operation, initialize_using_operation=self.initialize_using_operation, initialize_span=self.initialize_span, ) raw_macd = self._raw_macd_object.fit(dataframe, first_fit=first_fit)", "}, by default True \"\"\" if first_fit: self._raw_macd_object = AbsolutePriceOscillator( fast_period=self.span_fast, slow_period=self.span_slow, fast_operation=self.fast_operation,", "): \"\"\" Parameters ---------- fast_period : int, optional specify decay in terms of", "default 'mean' initialize_using_operation : bool, optional If True, then specified 'operation' is performed", "for the smoothing moving feature, by default 9 fast_operation : str, {'mean','var','std'} operation", ": Union[pd.DataFrame, pd.Series] dataframe containing column values to create feature over first_fit :", "use fit_first=True, and for any production/test implementation pass fit_first=False Returns --> Smoothed signal", "the slow moving feature, by default 'mean' smoothing_operation : str, optional operation to", "which 'operation' would be performed for initialization, by default None min_periods : int,", "= 9, fast_operation: str = \"mean\", slow_operation: str = \"mean\", smoothing_operation: str =", "increasing and datetime64[ns] dtype, by default None \"\"\" self.span_fast = fast_period self.span_slow =", "self._raw_macd_object = AbsolutePriceOscillator( fast_period=self.span_fast, slow_period=self.span_slow, fast_operation=self.fast_operation, slow_operation=self.slow_operation, min_periods=self.min_periods, initialize_using_operation=self.initialize_using_operation, initialize_span=self.initialize_span, ignore_na=self.ignore_na, axis=self.axis, times=self.times,", "= slow_period self.min_periods = min_periods self.ignore_na = ignore_na self.axis = axis self.times =", "calculation }, by default True \"\"\" if first_fit: self._raw_macd_object = AbsolutePriceOscillator( fast_period=self.span_fast, slow_period=self.span_slow,", "must be in ascending order. \"\"\" def __init__( self, fast_period: int = 26,", "axis: int = 0, times: str = None, return_histogram=False, ): \"\"\" Parameters ----------", "times=self.times, operation=self.smoothing_operation, initialize_using_operation=self.initialize_using_operation, initialize_span=self.initialize_span, ) raw_macd = self._raw_macd_object.fit(dataframe, first_fit=first_fit) macd = self._macd_object.fit(dataframe=raw_macd, first_fit=first_fit)", "is calculated, by default False initialize_span : int, optional the span over which", "as np import pandas as pd from typing import Union, Callable from pandas.core.frame", "True \"\"\" if first_fit: self._raw_macd_object = AbsolutePriceOscillator( fast_period=self.span_fast, slow_period=self.span_slow, fast_operation=self.fast_operation, slow_operation=self.slow_operation, min_periods=self.min_periods, initialize_using_operation=self.initialize_using_operation,", "AbsolutePriceOscillator( fast_period=self.span_fast, slow_period=self.span_slow, fast_operation=self.fast_operation, slow_operation=self.slow_operation, min_periods=self.min_periods, initialize_using_operation=self.initialize_using_operation, initialize_span=self.initialize_span, ignore_na=self.ignore_na, axis=self.axis, times=self.times, ) self._macd_object", "typing import Union, Callable from pandas.core.frame import DataFrame from NitroFE.time_based_features.indicator_features._AbsolutePriceOscillator import ( AbsolutePriceOscillator,", "= None, return_histogram=False, ): \"\"\" Parameters ---------- fast_period : int, optional specify decay", "default None min_periods : int, optional Minimum number of observations in window required", "calculating weights; specify True to reproduce pre-0.15.0 behavior, by default False axis :", "features require past values for calculation. Use True, when calculating for training data", "by default False initialize_span : int, optional the span over which 'operation' would", "self.slow_operation = slow_operation self.smoothing_operation = smoothing_operation self.smoothing_period = smoothing_period self.return_histogram = return_histogram self.initialize_using_operation", "datetime64[ns] dtype, by default None \"\"\" self.span_fast = fast_period self.span_slow = slow_period self.min_periods", "testing/production data { in which case the values, which were saved during the", "int = 9, fast_operation: str = \"mean\", slow_operation: str = \"mean\", smoothing_operation: str", "bool = False, axis: int = 0, times: str = None, return_histogram=False, ):", "axis=self.axis, times=self.times, ) self._macd_object = ExponentialMovingFeature( span=self.smoothing_period, ignore_na=self.ignore_na, axis=self.axis, times=self.times, operation=self.smoothing_operation, initialize_using_operation=self.initialize_using_operation, initialize_span=self.initialize_span,", "self.span_slow = slow_period self.min_periods = min_periods self.ignore_na = ignore_na self.axis = axis self.times", "False, axis: int = 0, times: str = None, return_histogram=False, ): \"\"\" Parameters", "from NitroFE.time_based_features.indicator_features._AbsolutePriceOscillator import ( AbsolutePriceOscillator, ) from NitroFE.time_based_features.moving_average_features.moving_average_features import ( ExponentialMovingFeature, ) class", "MovingAverageConvergenceDivergence: \"\"\" Provided dataframe must be in ascending order. \"\"\" def __init__( self,", "= return_histogram self.initialize_using_operation = initialize_using_operation self.initialize_span = initialize_span def fit( self, dataframe: Union[pd.DataFrame,", "in terms of span, for the slow moving feature, by default 26 smoothing_period", "when calculating weights; specify True to reproduce pre-0.15.0 behavior, by default False axis", "= \"mean\", smoothing_operation: str = \"mean\", initialize_using_operation: bool = False, initialize_span: int =", "True, ): \"\"\" For your training/initial fit phase (very first fit) use fit_first=True,", "the rows, and 1 identifies the columns, by default 0 times : str,", "\"\"\" self.span_fast = fast_period self.span_slow = slow_period self.min_periods = min_periods self.ignore_na = ignore_na", ": str, optional operation to be performed for the smoothing moving feature, by", "the first 'initialize_span' values, and then the exponential moving average is calculated, by", "self.return_histogram = return_histogram self.initialize_using_operation = initialize_using_operation self.initialize_span = initialize_span def fit( self, dataframe:", "int, optional specify decay in terms of span, for the smoothing moving feature,", "moving feature, by default 'mean' slow_operation : str, {'mean','var','std'} operation to be performed", "For your training/initial fit phase (very first fit) use fit_first=True, and for any", "'mean' initialize_using_operation : bool, optional If True, then specified 'operation' is performed on", "= fast_operation self.slow_operation = slow_operation self.smoothing_operation = smoothing_operation self.smoothing_period = smoothing_period self.return_histogram =", "the exponential moving average is calculated, by default False initialize_span : int, optional", ": int, optional specify decay in terms of span, for the slow moving", "= smoothing_period self.return_histogram = return_histogram self.initialize_using_operation = initialize_using_operation self.initialize_span = initialize_span def fit(", "AbsolutePriceOscillator, ) from NitroFE.time_based_features.moving_average_features.moving_average_features import ( ExponentialMovingFeature, ) class MovingAverageConvergenceDivergence: \"\"\" Provided dataframe", "min_periods=self.min_periods, initialize_using_operation=self.initialize_using_operation, initialize_span=self.initialize_span, ignore_na=self.ignore_na, axis=self.axis, times=self.times, ) self._macd_object = ExponentialMovingFeature( span=self.smoothing_period, ignore_na=self.ignore_na, axis=self.axis,", "0 times : str, optional Times corresponding to the observations. Must be monotonically", "self.smoothing_operation = smoothing_operation self.smoothing_period = smoothing_period self.return_histogram = return_histogram self.initialize_using_operation = initialize_using_operation self.initialize_span", "= initialize_using_operation self.initialize_span = initialize_span def fit( self, dataframe: Union[pd.DataFrame, pd.Series], first_fit: bool", "initialize_using_operation: bool = False, initialize_span: int = None, min_periods: int = 0, ignore_na:", "rows, and 1 identifies the columns, by default 0 times : str, optional", "by default 'mean' slow_operation : str, {'mean','var','std'} operation to be performed for the", "feature, by default 12 slow_period : int, optional specify decay in terms of", "def __init__( self, fast_period: int = 26, slow_period: int = 12, smoothing_period: int", "dataframe: Union[pd.DataFrame, pd.Series], first_fit: bool = True, ): \"\"\" For your training/initial fit", "str, {'mean','var','std'} operation to be performed for the slow moving feature, by default", "int, optional specify decay in terms of span, for the fast moving feature,", "moving feature, by default 'mean' smoothing_operation : str, optional operation to be performed", "slow_operation : str, {'mean','var','std'} operation to be performed for the slow moving feature,", "= 0, times: str = None, return_histogram=False, ): \"\"\" Parameters ---------- fast_period :", "first 'initialize_span' values, and then the exponential moving average is calculated, by default", "initialize_using_operation=self.initialize_using_operation, initialize_span=self.initialize_span, ) raw_macd = self._raw_macd_object.fit(dataframe, first_fit=first_fit) macd = self._macd_object.fit(dataframe=raw_macd, first_fit=first_fit) return raw_macd", "Smoothed signal line , macd histogram Parameters ---------- dataframe : Union[pd.DataFrame, pd.Series] dataframe", "\"\"\" Provided dataframe must be in ascending order. \"\"\" def __init__( self, fast_period:", "terms of span, for the fast moving feature, by default 12 slow_period :", "False initialize_span : int, optional the span over which 'operation' would be performed", "optional specify decay in terms of span, for the smoothing moving feature, by", "by default 26 smoothing_period : int, optional specify decay in terms of span,", "min_periods self.ignore_na = ignore_na self.axis = axis self.times = times self.fast_operation = fast_operation", "and for any production/test implementation pass fit_first=False Returns --> Smoothed signal line ,", "26 smoothing_period : int, optional specify decay in terms of span, for the", "Callable from pandas.core.frame import DataFrame from NitroFE.time_based_features.indicator_features._AbsolutePriceOscillator import ( AbsolutePriceOscillator, ) from NitroFE.time_based_features.moving_average_features.moving_average_features", "be performed for the smoothing moving feature, by default 'mean' initialize_using_operation : bool,", "case the values, which were saved during the last phase, will be utilized", "value 0 identifies the rows, and 1 identifies the columns, by default 0", "pd from typing import Union, Callable from pandas.core.frame import DataFrame from NitroFE.time_based_features.indicator_features._AbsolutePriceOscillator import", "import numpy as np import pandas as pd from typing import Union, Callable", "'initialize_span' values, and then the exponential moving average is calculated, by default False", "smoothing moving feature, by default 9 fast_operation : str, {'mean','var','std'} operation to be", "ignore_na: bool = False, axis: int = 0, times: str = None, return_histogram=False,", "initialize_using_operation : bool, optional If True, then specified 'operation' is performed on the", "operation to be performed for the slow moving feature, by default 'mean' smoothing_operation", "fast_period : int, optional specify decay in terms of span, for the fast", "last phase, will be utilized for calculation }, by default True \"\"\" if", "production/test implementation pass fit_first=False Returns --> Smoothed signal line , macd histogram Parameters", "__init__( self, fast_period: int = 26, slow_period: int = 12, smoothing_period: int =", ": str, {'mean','var','std'} operation to be performed for the slow moving feature, by", "optional specify decay in terms of span, for the fast moving feature, by", "moving feature, by default 9 fast_operation : str, {'mean','var','std'} operation to be performed", "for training data (very first fit) Use False, when calculating for subsequent testing/production", "\"\"\" Parameters ---------- fast_period : int, optional specify decay in terms of span,", "dataframe containing column values to create feature over first_fit : bool, optional Indicator", "Use True, when calculating for training data (very first fit) Use False, when", "import ( ExponentialMovingFeature, ) class MovingAverageConvergenceDivergence: \"\"\" Provided dataframe must be in ascending", "initialize_using_operation=self.initialize_using_operation, initialize_span=self.initialize_span, ignore_na=self.ignore_na, axis=self.axis, times=self.times, ) self._macd_object = ExponentialMovingFeature( span=self.smoothing_period, ignore_na=self.ignore_na, axis=self.axis, times=self.times,", "'operation' is performed on the first 'initialize_span' values, and then the exponential moving", "{'mean','var','std'} operation to be performed for the slow moving feature, by default 'mean'", "in ascending order. \"\"\" def __init__( self, fast_period: int = 26, slow_period: int", "by default False axis : int, optional The axis to use. The value", "operation to be performed for the fast moving feature, by default 'mean' slow_operation", "default 12 slow_period : int, optional specify decay in terms of span, for", "corresponding to the observations. Must be monotonically increasing and datetime64[ns] dtype, by default", "first_fit: bool = True, ): \"\"\" For your training/initial fit phase (very first", "reproduce pre-0.15.0 behavior, by default False axis : int, optional The axis to", "over first_fit : bool, optional Indicator features require past values for calculation. Use", "= times self.fast_operation = fast_operation self.slow_operation = slow_operation self.smoothing_operation = smoothing_operation self.smoothing_period =", "Must be monotonically increasing and datetime64[ns] dtype, by default None \"\"\" self.span_fast =", "were saved during the last phase, will be utilized for calculation }, by", "bool, optional If True, then specified 'operation' is performed on the first 'initialize_span'", "be in ascending order. \"\"\" def __init__( self, fast_period: int = 26, slow_period:", "be performed for the fast moving feature, by default 'mean' slow_operation : str,", "slow_operation: str = \"mean\", smoothing_operation: str = \"mean\", initialize_using_operation: bool = False, initialize_span:", ": int, optional specify decay in terms of span, for the smoothing moving", "first fit) use fit_first=True, and for any production/test implementation pass fit_first=False Returns -->", "times: str = None, return_histogram=False, ): \"\"\" Parameters ---------- fast_period : int, optional", "feature, by default 'mean' initialize_using_operation : bool, optional If True, then specified 'operation'", "feature, by default 26 smoothing_period : int, optional specify decay in terms of", "of span, for the smoothing moving feature, by default 9 fast_operation : str,", "when calculating for training data (very first fit) Use False, when calculating for", "past values for calculation. Use True, when calculating for training data (very first", "self.fast_operation = fast_operation self.slow_operation = slow_operation self.smoothing_operation = smoothing_operation self.smoothing_period = smoothing_period self.return_histogram", "( ExponentialMovingFeature, ) class MovingAverageConvergenceDivergence: \"\"\" Provided dataframe must be in ascending order.", "optional specify decay in terms of span, for the slow moving feature, by", "= ExponentialMovingFeature( span=self.smoothing_period, ignore_na=self.ignore_na, axis=self.axis, times=self.times, operation=self.smoothing_operation, initialize_using_operation=self.initialize_using_operation, initialize_span=self.initialize_span, ) raw_macd = self._raw_macd_object.fit(dataframe,", "= \"mean\", initialize_using_operation: bool = False, initialize_span: int = None, min_periods: int =", ") class MovingAverageConvergenceDivergence: \"\"\" Provided dataframe must be in ascending order. \"\"\" def", "optional If True, then specified 'operation' is performed on the first 'initialize_span' values,", "from pandas.core.frame import DataFrame from NitroFE.time_based_features.indicator_features._AbsolutePriceOscillator import ( AbsolutePriceOscillator, ) from NitroFE.time_based_features.moving_average_features.moving_average_features import", "\"mean\", initialize_using_operation: bool = False, initialize_span: int = None, min_periods: int = 0,", "the columns, by default 0 times : str, optional Times corresponding to the", "missing values when calculating weights; specify True to reproduce pre-0.15.0 behavior, by default", "which case the values, which were saved during the last phase, will be", "slow moving feature, by default 26 smoothing_period : int, optional specify decay in", "optional operation to be performed for the smoothing moving feature, by default 'mean'", "class MovingAverageConvergenceDivergence: \"\"\" Provided dataframe must be in ascending order. \"\"\" def __init__(", "Parameters ---------- dataframe : Union[pd.DataFrame, pd.Series] dataframe containing column values to create feature", "moving feature, by default 26 smoothing_period : int, optional specify decay in terms", "9, fast_operation: str = \"mean\", slow_operation: str = \"mean\", smoothing_operation: str = \"mean\",", "The value 0 identifies the rows, and 1 identifies the columns, by default", "decay in terms of span, for the slow moving feature, by default 26", "1 identifies the columns, by default 0 times : str, optional Times corresponding", "\"mean\", smoothing_operation: str = \"mean\", initialize_using_operation: bool = False, initialize_span: int = None,", "default 0 times : str, optional Times corresponding to the observations. Must be", "average is calculated, by default False initialize_span : int, optional the span over", "Times corresponding to the observations. Must be monotonically increasing and datetime64[ns] dtype, by", "observations. Must be monotonically increasing and datetime64[ns] dtype, by default None \"\"\" self.span_fast", "default None \"\"\" self.span_fast = fast_period self.span_slow = slow_period self.min_periods = min_periods self.ignore_na", "Minimum number of observations in window required to have a value (otherwise result", "str, {'mean','var','std'} operation to be performed for the fast moving feature, by default", "feature, by default 9 fast_operation : str, {'mean','var','std'} operation to be performed for", "Indicator features require past values for calculation. Use True, when calculating for training", "window required to have a value (otherwise result is NA), by default 0", "import Union, Callable from pandas.core.frame import DataFrame from NitroFE.time_based_features.indicator_features._AbsolutePriceOscillator import ( AbsolutePriceOscillator, )", "str, optional operation to be performed for the smoothing moving feature, by default", "the fast moving feature, by default 12 slow_period : int, optional specify decay", "terms of span, for the smoothing moving feature, by default 9 fast_operation :", "= AbsolutePriceOscillator( fast_period=self.span_fast, slow_period=self.span_slow, fast_operation=self.fast_operation, slow_operation=self.slow_operation, min_periods=self.min_periods, initialize_using_operation=self.initialize_using_operation, initialize_span=self.initialize_span, ignore_na=self.ignore_na, axis=self.axis, times=self.times, )", "(very first fit) Use False, when calculating for subsequent testing/production data { in", "import ( AbsolutePriceOscillator, ) from NitroFE.time_based_features.moving_average_features.moving_average_features import ( ExponentialMovingFeature, ) class MovingAverageConvergenceDivergence: \"\"\"", "None \"\"\" self.span_fast = fast_period self.span_slow = slow_period self.min_periods = min_periods self.ignore_na =", "by default None \"\"\" self.span_fast = fast_period self.span_slow = slow_period self.min_periods = min_periods", "for the fast moving feature, by default 12 slow_period : int, optional specify", "for the slow moving feature, by default 'mean' smoothing_operation : str, optional operation", "= False, initialize_span: int = None, min_periods: int = 0, ignore_na: bool =", "bool = False, initialize_span: int = None, min_periods: int = 0, ignore_na: bool", "any production/test implementation pass fit_first=False Returns --> Smoothed signal line , macd histogram", "NitroFE.time_based_features.moving_average_features.moving_average_features import ( ExponentialMovingFeature, ) class MovingAverageConvergenceDivergence: \"\"\" Provided dataframe must be in", "observations in window required to have a value (otherwise result is NA), by", "monotonically increasing and datetime64[ns] dtype, by default None \"\"\" self.span_fast = fast_period self.span_slow", "If True, then specified 'operation' is performed on the first 'initialize_span' values, and", "None min_periods : int, optional Minimum number of observations in window required to", "int = 12, smoothing_period: int = 9, fast_operation: str = \"mean\", slow_operation: str", "{ in which case the values, which were saved during the last phase,", ": int, optional specify decay in terms of span, for the fast moving", "specify True to reproduce pre-0.15.0 behavior, by default False axis : int, optional", "required to have a value (otherwise result is NA), by default 0 ignore_na", "fast moving feature, by default 'mean' slow_operation : str, {'mean','var','std'} operation to be", "histogram Parameters ---------- dataframe : Union[pd.DataFrame, pd.Series] dataframe containing column values to create", "26, slow_period: int = 12, smoothing_period: int = 9, fast_operation: str = \"mean\",", "by default None min_periods : int, optional Minimum number of observations in window", ") raw_macd = self._raw_macd_object.fit(dataframe, first_fit=first_fit) macd = self._macd_object.fit(dataframe=raw_macd, first_fit=first_fit) return raw_macd - macd", "0, times: str = None, return_histogram=False, ): \"\"\" Parameters ---------- fast_period : int,", "moving feature, by default 12 slow_period : int, optional specify decay in terms", "by default True \"\"\" if first_fit: self._raw_macd_object = AbsolutePriceOscillator( fast_period=self.span_fast, slow_period=self.span_slow, fast_operation=self.fast_operation, slow_operation=self.slow_operation,", ": str, {'mean','var','std'} operation to be performed for the fast moving feature, by", "specify decay in terms of span, for the fast moving feature, by default", "smoothing_period: int = 9, fast_operation: str = \"mean\", slow_operation: str = \"mean\", smoothing_operation:", "on the first 'initialize_span' values, and then the exponential moving average is calculated,", "which were saved during the last phase, will be utilized for calculation },", "int = 0, times: str = None, return_histogram=False, ): \"\"\" Parameters ---------- fast_period", "times self.fast_operation = fast_operation self.slow_operation = slow_operation self.smoothing_operation = smoothing_operation self.smoothing_period = smoothing_period", "is performed on the first 'initialize_span' values, and then the exponential moving average", "fit_first=True, and for any production/test implementation pass fit_first=False Returns --> Smoothed signal line", "str = None, return_histogram=False, ): \"\"\" Parameters ---------- fast_period : int, optional specify", "calculated, by default False initialize_span : int, optional the span over which 'operation'", "default 9 fast_operation : str, {'mean','var','std'} operation to be performed for the fast", "str = \"mean\", initialize_using_operation: bool = False, initialize_span: int = None, min_periods: int", "default 'mean' smoothing_operation : str, optional operation to be performed for the smoothing", "data (very first fit) Use False, when calculating for subsequent testing/production data {", "by default 0 times : str, optional Times corresponding to the observations. Must", "= None, min_periods: int = 0, ignore_na: bool = False, axis: int =", "initialization, by default None min_periods : int, optional Minimum number of observations in", "0 identifies the rows, and 1 identifies the columns, by default 0 times", "span=self.smoothing_period, ignore_na=self.ignore_na, axis=self.axis, times=self.times, operation=self.smoothing_operation, initialize_using_operation=self.initialize_using_operation, initialize_span=self.initialize_span, ) raw_macd = self._raw_macd_object.fit(dataframe, first_fit=first_fit) macd", "of span, for the fast moving feature, by default 12 slow_period : int,", "identifies the rows, and 1 identifies the columns, by default 0 times :", "for initialization, by default None min_periods : int, optional Minimum number of observations", "import DataFrame from NitroFE.time_based_features.indicator_features._AbsolutePriceOscillator import ( AbsolutePriceOscillator, ) from NitroFE.time_based_features.moving_average_features.moving_average_features import ( ExponentialMovingFeature,", "by default 'mean' initialize_using_operation : bool, optional If True, then specified 'operation' is", "self.initialize_using_operation = initialize_using_operation self.initialize_span = initialize_span def fit( self, dataframe: Union[pd.DataFrame, pd.Series], first_fit:", "performed for initialization, by default None min_periods : int, optional Minimum number of", "the values, which were saved during the last phase, will be utilized for", "str = \"mean\", slow_operation: str = \"mean\", smoothing_operation: str = \"mean\", initialize_using_operation: bool", "feature, by default 'mean' smoothing_operation : str, optional operation to be performed for", "specify decay in terms of span, for the smoothing moving feature, by default", "column values to create feature over first_fit : bool, optional Indicator features require", "= False, axis: int = 0, times: str = None, return_histogram=False, ): \"\"\"", "to the observations. Must be monotonically increasing and datetime64[ns] dtype, by default None", "= axis self.times = times self.fast_operation = fast_operation self.slow_operation = slow_operation self.smoothing_operation =", "moving average is calculated, by default False initialize_span : int, optional the span", "---------- fast_period : int, optional specify decay in terms of span, for the", "data { in which case the values, which were saved during the last", "when calculating for subsequent testing/production data { in which case the values, which", "to be performed for the smoothing moving feature, by default 'mean' initialize_using_operation :", "return_histogram self.initialize_using_operation = initialize_using_operation self.initialize_span = initialize_span def fit( self, dataframe: Union[pd.DataFrame, pd.Series],", "your training/initial fit phase (very first fit) use fit_first=True, and for any production/test", "in which case the values, which were saved during the last phase, will", "dtype, by default None \"\"\" self.span_fast = fast_period self.span_slow = slow_period self.min_periods =", "self._macd_object = ExponentialMovingFeature( span=self.smoothing_period, ignore_na=self.ignore_na, axis=self.axis, times=self.times, operation=self.smoothing_operation, initialize_using_operation=self.initialize_using_operation, initialize_span=self.initialize_span, ) raw_macd =", "Union, Callable from pandas.core.frame import DataFrame from NitroFE.time_based_features.indicator_features._AbsolutePriceOscillator import ( AbsolutePriceOscillator, ) from", "is NA), by default 0 ignore_na : bool, optional Ignore missing values when", "int = None, min_periods: int = 0, ignore_na: bool = False, axis: int", "Use False, when calculating for subsequent testing/production data { in which case the", "Union[pd.DataFrame, pd.Series], first_fit: bool = True, ): \"\"\" For your training/initial fit phase", "'operation' would be performed for initialization, by default None min_periods : int, optional", "performed on the first 'initialize_span' values, and then the exponential moving average is", "would be performed for initialization, by default None min_periods : int, optional Minimum", "12, smoothing_period: int = 9, fast_operation: str = \"mean\", slow_operation: str = \"mean\",", "to be performed for the fast moving feature, by default 'mean' slow_operation :", "fast_operation=self.fast_operation, slow_operation=self.slow_operation, min_periods=self.min_periods, initialize_using_operation=self.initialize_using_operation, initialize_span=self.initialize_span, ignore_na=self.ignore_na, axis=self.axis, times=self.times, ) self._macd_object = ExponentialMovingFeature( span=self.smoothing_period,", "if first_fit: self._raw_macd_object = AbsolutePriceOscillator( fast_period=self.span_fast, slow_period=self.span_slow, fast_operation=self.fast_operation, slow_operation=self.slow_operation, min_periods=self.min_periods, initialize_using_operation=self.initialize_using_operation, initialize_span=self.initialize_span, ignore_na=self.ignore_na,", "in window required to have a value (otherwise result is NA), by default", "axis self.times = times self.fast_operation = fast_operation self.slow_operation = slow_operation self.smoothing_operation = smoothing_operation", "will be utilized for calculation }, by default True \"\"\" if first_fit: self._raw_macd_object", "def fit( self, dataframe: Union[pd.DataFrame, pd.Series], first_fit: bool = True, ): \"\"\" For", "fit phase (very first fit) use fit_first=True, and for any production/test implementation pass", "raw_macd = self._raw_macd_object.fit(dataframe, first_fit=first_fit) macd = self._macd_object.fit(dataframe=raw_macd, first_fit=first_fit) return raw_macd - macd if", "phase (very first fit) use fit_first=True, and for any production/test implementation pass fit_first=False", "self, dataframe: Union[pd.DataFrame, pd.Series], first_fit: bool = True, ): \"\"\" For your training/initial", "fast_operation self.slow_operation = slow_operation self.smoothing_operation = smoothing_operation self.smoothing_period = smoothing_period self.return_histogram = return_histogram", "(very first fit) use fit_first=True, and for any production/test implementation pass fit_first=False Returns", "saved during the last phase, will be utilized for calculation }, by default", "containing column values to create feature over first_fit : bool, optional Indicator features", "over which 'operation' would be performed for initialization, by default None min_periods :", "= min_periods self.ignore_na = ignore_na self.axis = axis self.times = times self.fast_operation =", "= True, ): \"\"\" For your training/initial fit phase (very first fit) use", "0, ignore_na: bool = False, axis: int = 0, times: str = None,", "smoothing_period self.return_histogram = return_histogram self.initialize_using_operation = initialize_using_operation self.initialize_span = initialize_span def fit( self,", "initialize_span: int = None, min_periods: int = 0, ignore_na: bool = False, axis:", "pd.Series], first_fit: bool = True, ): \"\"\" For your training/initial fit phase (very", "pre-0.15.0 behavior, by default False axis : int, optional The axis to use.", "Parameters ---------- fast_period : int, optional specify decay in terms of span, for", "then specified 'operation' is performed on the first 'initialize_span' values, and then the", "bool = True, ): \"\"\" For your training/initial fit phase (very first fit)", "initialize_span def fit( self, dataframe: Union[pd.DataFrame, pd.Series], first_fit: bool = True, ): \"\"\"", "by default 0 ignore_na : bool, optional Ignore missing values when calculating weights;", ": int, optional Minimum number of observations in window required to have a", "implementation pass fit_first=False Returns --> Smoothed signal line , macd histogram Parameters ----------", "dataframe must be in ascending order. \"\"\" def __init__( self, fast_period: int =", "NA), by default 0 ignore_na : bool, optional Ignore missing values when calculating", "self.axis = axis self.times = times self.fast_operation = fast_operation self.slow_operation = slow_operation self.smoothing_operation", "bool, optional Indicator features require past values for calculation. Use True, when calculating", "Provided dataframe must be in ascending order. \"\"\" def __init__( self, fast_period: int", "\"mean\", slow_operation: str = \"mean\", smoothing_operation: str = \"mean\", initialize_using_operation: bool = False,", "True to reproduce pre-0.15.0 behavior, by default False axis : int, optional The", "create feature over first_fit : bool, optional Indicator features require past values for", "by default 9 fast_operation : str, {'mean','var','std'} operation to be performed for the", "0 ignore_na : bool, optional Ignore missing values when calculating weights; specify True", "number of observations in window required to have a value (otherwise result is", "first_fit : bool, optional Indicator features require past values for calculation. Use True,", "performed for the slow moving feature, by default 'mean' smoothing_operation : str, optional", "str = \"mean\", smoothing_operation: str = \"mean\", initialize_using_operation: bool = False, initialize_span: int", "= 0, ignore_na: bool = False, axis: int = 0, times: str =", "int, optional The axis to use. The value 0 identifies the rows, and", "fast_period self.span_slow = slow_period self.min_periods = min_periods self.ignore_na = ignore_na self.axis = axis", "default 'mean' slow_operation : str, {'mean','var','std'} operation to be performed for the slow", "weights; specify True to reproduce pre-0.15.0 behavior, by default False axis : int,", "return_histogram=False, ): \"\"\" Parameters ---------- fast_period : int, optional specify decay in terms", ") from NitroFE.time_based_features.moving_average_features.moving_average_features import ( ExponentialMovingFeature, ) class MovingAverageConvergenceDivergence: \"\"\" Provided dataframe must", "pandas as pd from typing import Union, Callable from pandas.core.frame import DataFrame from", "9 fast_operation : str, {'mean','var','std'} operation to be performed for the fast moving", "= slow_operation self.smoothing_operation = smoothing_operation self.smoothing_period = smoothing_period self.return_histogram = return_histogram self.initialize_using_operation =", "= 26, slow_period: int = 12, smoothing_period: int = 9, fast_operation: str =", "fit) use fit_first=True, and for any production/test implementation pass fit_first=False Returns --> Smoothed", "performed for the smoothing moving feature, by default 'mean' initialize_using_operation : bool, optional", "np import pandas as pd from typing import Union, Callable from pandas.core.frame import", "be performed for the slow moving feature, by default 'mean' smoothing_operation : str,", "int = 26, slow_period: int = 12, smoothing_period: int = 9, fast_operation: str", "operation=self.smoothing_operation, initialize_using_operation=self.initialize_using_operation, initialize_span=self.initialize_span, ) raw_macd = self._raw_macd_object.fit(dataframe, first_fit=first_fit) macd = self._macd_object.fit(dataframe=raw_macd, first_fit=first_fit) return", "slow_operation=self.slow_operation, min_periods=self.min_periods, initialize_using_operation=self.initialize_using_operation, initialize_span=self.initialize_span, ignore_na=self.ignore_na, axis=self.axis, times=self.times, ) self._macd_object = ExponentialMovingFeature( span=self.smoothing_period, ignore_na=self.ignore_na,", "ignore_na=self.ignore_na, axis=self.axis, times=self.times, ) self._macd_object = ExponentialMovingFeature( span=self.smoothing_period, ignore_na=self.ignore_na, axis=self.axis, times=self.times, operation=self.smoothing_operation, initialize_using_operation=self.initialize_using_operation,", "self.ignore_na = ignore_na self.axis = axis self.times = times self.fast_operation = fast_operation self.slow_operation", "fast_period=self.span_fast, slow_period=self.span_slow, fast_operation=self.fast_operation, slow_operation=self.slow_operation, min_periods=self.min_periods, initialize_using_operation=self.initialize_using_operation, initialize_span=self.initialize_span, ignore_na=self.ignore_na, axis=self.axis, times=self.times, ) self._macd_object =", "pass fit_first=False Returns --> Smoothed signal line , macd histogram Parameters ---------- dataframe", "in terms of span, for the fast moving feature, by default 12 slow_period", "for any production/test implementation pass fit_first=False Returns --> Smoothed signal line , macd", "values to create feature over first_fit : bool, optional Indicator features require past", "utilized for calculation }, by default True \"\"\" if first_fit: self._raw_macd_object = AbsolutePriceOscillator(", "self.span_fast = fast_period self.span_slow = slow_period self.min_periods = min_periods self.ignore_na = ignore_na self.axis", "self, fast_period: int = 26, slow_period: int = 12, smoothing_period: int = 9,", "default 0 ignore_na : bool, optional Ignore missing values when calculating weights; specify", "ignore_na self.axis = axis self.times = times self.fast_operation = fast_operation self.slow_operation = slow_operation", "default True \"\"\" if first_fit: self._raw_macd_object = AbsolutePriceOscillator( fast_period=self.span_fast, slow_period=self.span_slow, fast_operation=self.fast_operation, slow_operation=self.slow_operation, min_periods=self.min_periods,", "smoothing_period : int, optional specify decay in terms of span, for the smoothing", "Returns --> Smoothed signal line , macd histogram Parameters ---------- dataframe : Union[pd.DataFrame,", "a value (otherwise result is NA), by default 0 ignore_na : bool, optional", "training data (very first fit) Use False, when calculating for subsequent testing/production data", "to be performed for the slow moving feature, by default 'mean' smoothing_operation :", "slow_period=self.span_slow, fast_operation=self.fast_operation, slow_operation=self.slow_operation, min_periods=self.min_periods, initialize_using_operation=self.initialize_using_operation, initialize_span=self.initialize_span, ignore_na=self.ignore_na, axis=self.axis, times=self.times, ) self._macd_object = ExponentialMovingFeature(", "\"\"\" if first_fit: self._raw_macd_object = AbsolutePriceOscillator( fast_period=self.span_fast, slow_period=self.span_slow, fast_operation=self.fast_operation, slow_operation=self.slow_operation, min_periods=self.min_periods, initialize_using_operation=self.initialize_using_operation, initialize_span=self.initialize_span,", "times=self.times, ) self._macd_object = ExponentialMovingFeature( span=self.smoothing_period, ignore_na=self.ignore_na, axis=self.axis, times=self.times, operation=self.smoothing_operation, initialize_using_operation=self.initialize_using_operation, initialize_span=self.initialize_span, )", "int, optional the span over which 'operation' would be performed for initialization, by", "span, for the smoothing moving feature, by default 9 fast_operation : str, {'mean','var','std'}", "slow_period self.min_periods = min_periods self.ignore_na = ignore_na self.axis = axis self.times = times", "span, for the slow moving feature, by default 26 smoothing_period : int, optional", "default False initialize_span : int, optional the span over which 'operation' would be", "self.min_periods = min_periods self.ignore_na = ignore_na self.axis = axis self.times = times self.fast_operation", "= self._raw_macd_object.fit(dataframe, first_fit=first_fit) macd = self._macd_object.fit(dataframe=raw_macd, first_fit=first_fit) return raw_macd - macd if self.return_histogram", "then the exponential moving average is calculated, by default False initialize_span : int,", "phase, will be utilized for calculation }, by default True \"\"\" if first_fit:", "optional the span over which 'operation' would be performed for initialization, by default", "optional The axis to use. The value 0 identifies the rows, and 1", "initialize_using_operation self.initialize_span = initialize_span def fit( self, dataframe: Union[pd.DataFrame, pd.Series], first_fit: bool =", "slow_period : int, optional specify decay in terms of span, for the slow", "for the slow moving feature, by default 26 smoothing_period : int, optional specify", "None, return_histogram=False, ): \"\"\" Parameters ---------- fast_period : int, optional specify decay in", "signal line , macd histogram Parameters ---------- dataframe : Union[pd.DataFrame, pd.Series] dataframe containing", "ignore_na=self.ignore_na, axis=self.axis, times=self.times, operation=self.smoothing_operation, initialize_using_operation=self.initialize_using_operation, initialize_span=self.initialize_span, ) raw_macd = self._raw_macd_object.fit(dataframe, first_fit=first_fit) macd =", "and 1 identifies the columns, by default 0 times : str, optional Times", "for subsequent testing/production data { in which case the values, which were saved", "False, when calculating for subsequent testing/production data { in which case the values," ]
[ "self.train_dataset = ArcheryBowlingDataset.create_from_dataframe(train_val_df, self.window_size, self.batch_size, name='TRAIN', feature_cols=self.features, identifier_col=self.identifier_col, label_col=self.label_col, shuffle_windows=self.shuffle_windows, sorting_cols=self.sorting_cols ) else:", "None, None self.logger.info('__init__ done.') def setup(self, stage: Optional[str] = None) -> None: #", "data being available for training. ' f'Therefore all Data will be used as", "test_files = (list(test_files)) self.logger.info(f'found {len(test_files)} test-files.') # create test Dataset from src.datamodules.datasets.archery_bowling_dataset import", "else 'ParticipantID' self.sorting_cols = sorting_cols self.normalisation = normalisation self.window_size = window_size self.batch_size =", "from src.datamodules.datasets.archery_bowling_dataset import ArcheryBowlingDataset self.val_dataset = ArcheryBowlingDataset.create_from_dataframe(val_df, self.window_size, self.batch_size, name='VAL', feature_cols=self.features, identifier_col=self.identifier_col, label_col=self.label_col,", "test_df = ArcheryBowlingDataModule.load_dataframe_from_multiple_files(test_files) computed_batch_size = self.batch_size rest = len(test_df) % self.batch_size computed_batch_size -=", "% self.batch_size computed_batch_size -= rest self.test_dataset = ArcheryBowlingDataset.create_from_dataframe(test_df, self.window_size, computed_batch_size, name='TEST', feature_cols=self.features, identifier_col=self.identifier_col,", "test data # create a list of paths for test data files (basically", "initialized!') self.logger.info(f'Datasets are setup.') self.logger.info(self) def get_file_list(self, session=1): train_val_files = self.data_root.glob(f'{self.szenario}*{self.normalisation}*session{session}*.csv') return train_val_files", "will be used as train-set!') from src.datamodules.datasets.archery_bowling_dataset import ArcheryBowlingDataset self.train_dataset = ArcheryBowlingDataset.create_from_dataframe(train_val_df, self.window_size,", "= 1, window_size: int = 10, normalisation: str = 'WithoutNormalization', szenario: str =", "with session 2 self.logger.info(f'stage:{stage}. creating Dataset...') test_files = self.get_file_list(session=2) test_files = (list(test_files)) self.logger.info(f'found", "i in file_list: tmp = pd.read_csv(i) df_list.append(tmp) return pd.concat(df_list, ignore_index=True) def _create_info_dict(self): return", "used as train-set!') from src.datamodules.datasets.archery_bowling_dataset import ArcheryBowlingDataset self.train_dataset = ArcheryBowlingDataset.create_from_dataframe(train_val_df, self.window_size, self.batch_size, name='TRAIN',", "def val_dataloader(self) -> Union[DataLoader, List[DataLoader]]: return DataLoader(self.val_dataset, batch_size=None, num_workers=self.num_workers ) def test_dataloader(self) ->", "transforms from src.utils.utils import get_logger class ArcheryBowlingDataModule(pl.LightningDataModule): def __init__(self, data_root: str, test: bool", "for test data files (basically everything with session 2 self.logger.info(f'stage:{stage}. creating Dataset...') test_files", "return DataLoader(self.train_dataset, batch_size=None, num_workers=self.num_workers ) def val_dataloader(self) -> Union[DataLoader, List[DataLoader]]: return DataLoader(self.val_dataset, batch_size=None,", "(self.window_size, self.num_features) self.train_dataset, self.val_dataset, self.test_dataset = None, None, None self.logger.info('__init__ done.') def setup(self,", "self.test_dataset = None, None, None self.logger.info('__init__ done.') def setup(self, stage: Optional[str] = None)", "are setup.') self.logger.info(self) def get_file_list(self, session=1): train_val_files = self.data_root.glob(f'{self.szenario}*{self.normalisation}*session{session}*.csv') return train_val_files @staticmethod def", "the file path seems to be a pain. therefore ill load all relevant", "'batch size': self.batch_size, 'normalisation name': self.normalisation } def train_dataloader(self) -> Union[DataLoader, List[DataLoader], Dict[str,", "sorting_cols=self.sorting_cols ) del train_df else: from src.datamodules.datasets.archery_bowling_dataset import ArcheryBowlingDataset self.train_dataset = ArcheryBowlingDataset.create_from_dataframe(train_val_df, self.window_size,", "label_col=self.label_col, shuffle_windows=False, sorting_cols=self.sorting_cols ) self.logger.info('test Data initialized!') self.logger.info(f'Datasets are setup.') self.logger.info(self) def get_file_list(self,", "'seq_id', label_col: str = 'ParticipantID', sorting_cols: List[str] = None, num_workers: int = 1,", "self.transform = transforms.Compose([ transforms.ToTensor(), ]) self.shuffle_windows = shuffle_windows self.num_features = len(features) self.dims =", "else: val_df = train_val_df[train_val_df['repetition'] % modulo == 0] from src.datamodules.datasets.archery_bowling_dataset import ArcheryBowlingDataset self.val_dataset", "matching repetitions to validation # keep the remaining as train # drop unused", "train_val_df[train_val_df['repetition'] % modulo == 0] from src.datamodules.datasets.archery_bowling_dataset import ArcheryBowlingDataset self.val_dataset = ArcheryBowlingDataset.create_from_dataframe(val_df, self.window_size,", "be a pain. therefore ill load all relevant (normalized + session1) train_val_files =", "or modulo < 2: self.logger.info( f'validation split ratio({self.val_ratio}) was set, ' f'but would", "'train dataset': None if not self.train_dataset else str(self.train_dataset), 'val dataset': None if not", "modulo > 12 or modulo < 2: self.logger.info( f'validation split ratio({self.val_ratio}) was set,", "stage in (None, 'fit'): # TODO no validation set throws a Nonetype Error", "train_val_df = ArcheryBowlingDataModule.load_dataframe_from_multiple_files(train_val_files) # TODO refactor this ifelse structure to a neat structure", "12 or modulo < 2: self.logger.info( f'validation split ratio({self.val_ratio}) was set, ' f'but", "else 'seq_id' self.label_col = label_col if label_col is not None else 'ParticipantID' self.sorting_cols", "self.train_dataset else str(self.train_dataset), 'val dataset': None if not self.val_dataset else str(self.val_dataset), 'test dataset':", "Data will be used as train-set!') from src.datamodules.datasets.archery_bowling_dataset import ArcheryBowlingDataset self.train_dataset = ArcheryBowlingDataset.create_from_dataframe(train_val_df,", "val data loader... self.logger.info(f'stage:{stage}. creating Dataset...') # regexing or sorting the file path", "from src.utils.utils import get_logger class ArcheryBowlingDataModule(pl.LightningDataModule): def __init__(self, data_root: str, test: bool =", "num_workers... return DataLoader(self.test_dataset, batch_size=None, num_workers=self.num_workers ) def __repr__(self): return f\"DataModule(train_dataset={self.train_dataset!r}, \" \\ f\"val_dataset={self.val_dataset!r},", "num_workers self.logger = get_logger(name='A-B-DataModule') self.szenario = szenario self.features = features self.identifier_col = identifier_col", "feature_cols=self.features, identifier_col=self.identifier_col, label_col=self.label_col, shuffle_windows=self.shuffle_windows, sorting_cols=self.sorting_cols ) else: val_df = train_val_df[train_val_df['repetition'] % modulo ==", "'#batches': len(self.test_dataset), 'window size': self.window_size, 'batch size': self.batch_size, 'normalisation name': self.normalisation } def", "None else 'seq_id' self.label_col = label_col if label_col is not None else 'ParticipantID'", "]) self.shuffle_windows = shuffle_windows self.num_features = len(features) self.dims = (self.window_size, self.num_features) self.train_dataset, self.val_dataset,", "features self.identifier_col = identifier_col if identifier_col is not None else 'seq_id' self.label_col =", "self.window_size, computed_batch_size, name='TEST', feature_cols=self.features, identifier_col=self.identifier_col, label_col=self.label_col, shuffle_windows=False, sorting_cols=self.sorting_cols ) self.logger.info('test Data initialized!') self.logger.info(f'Datasets", "\\ f\"test_dataset={self.test_dataset!r}, \" \\ f\"dims={self.dims!r}, \" \\ f\"normalisation_name={self.normalisation!r}), \" \\ f\"Szenario={self.szenario})\" def __rich_repr__(self):", "= 1, shuffle_windows=False ): super(ArcheryBowlingDataModule, self).__init__() self.num_workers = num_workers self.logger = get_logger(name='A-B-DataModule') self.szenario", "def __repr__(self): return f\"DataModule(train_dataset={self.train_dataset!r}, \" \\ f\"val_dataset={self.val_dataset!r}, \" \\ f\"test_dataset={self.test_dataset!r}, \" \\ f\"dims={self.dims!r},", "data at once, and slice afterwords? # slice all modulo matching repetitions to", "'LeftVirtualHand_pos_X', 'RightVirtualHand_pos_X'], identifier_col: str = 'seq_id', label_col: str = 'ParticipantID', sorting_cols: List[str] =", "for i in file_list: tmp = pd.read_csv(i) df_list.append(tmp) return pd.concat(df_list, ignore_index=True) def _create_info_dict(self):", "import ArcheryBowlingDataset self.val_dataset = ArcheryBowlingDataset.create_from_dataframe(val_df, self.window_size, self.batch_size, name='VAL', feature_cols=self.features, identifier_col=self.identifier_col, label_col=self.label_col, shuffle_windows=self.shuffle_windows, sorting_cols=self.sorting_cols", "1, window_size: int = 10, normalisation: str = 'WithoutNormalization', szenario: str = 'Archery',", "TODO handle num_workers... return DataLoader(self.test_dataset, batch_size=None, num_workers=self.num_workers ) def __repr__(self): return f\"DataModule(train_dataset={self.train_dataset!r}, \"", "and return them # return ArcheryBowlingDataset(None, 1, 1), ArcheryBowlingDataset(None, 1, 1), ArcheryBowlingDataset(None, 1,", "this ifelse structure to a neat structure if self.val_ratio and self.val_ratio > 0:", "identifier_col=self.identifier_col, label_col=self.label_col, shuffle_windows=self.shuffle_windows, sorting_cols=self.sorting_cols ) else: val_df = train_val_df[train_val_df['repetition'] % modulo == 0]", ") def test_dataloader(self) -> Union[DataLoader, List[DataLoader]]: # TODO handle num_workers... return DataLoader(self.test_dataset, batch_size=None,", "identifier_col=self.identifier_col, label_col=self.label_col, shuffle_windows=False, sorting_cols=self.sorting_cols ) self.logger.info('test Data initialized!') self.logger.info(f'Datasets are setup.') self.logger.info(self) def", "feature_cols=self.features, identifier_col=self.identifier_col, label_col=self.label_col, shuffle_windows=self.shuffle_windows, sorting_cols=self.sorting_cols ) del val_df train_df = train_val_df[train_val_df['repetition'] % modulo", "self.batch_size, 'normalisation name': self.normalisation } def train_dataloader(self) -> Union[DataLoader, List[DataLoader], Dict[str, DataLoader]]: return", "src.datamodules.datasets.archery_bowling_dataset import ArcheryBowlingDataset self.val_dataset = ArcheryBowlingDataset.create_from_dataframe(val_df, self.window_size, self.batch_size, name='VAL', feature_cols=self.features, identifier_col=self.identifier_col, label_col=self.label_col, shuffle_windows=self.shuffle_windows,", "= ArcheryBowlingDataModule.load_dataframe_from_multiple_files(test_files) computed_batch_size = self.batch_size rest = len(test_df) % self.batch_size computed_batch_size -= rest", "would result in either all or no data being available for training. '", "ArcheryBowlingDataset.create_from_dataframe(train_val_df, self.window_size, self.batch_size, name='TRAIN', feature_cols=self.features, identifier_col=self.identifier_col, label_col=self.label_col, shuffle_windows=self.shuffle_windows, sorting_cols=self.sorting_cols ) self.val_dataset = None", "typing import Union, List, Dict, Optional import pandas as pd from torch.utils.data import", "modulo matching repetitions to validation # keep the remaining as train # drop", "a neat structure if self.val_ratio and self.val_ratio > 0: # not none and", "test_dataloader(self) -> Union[DataLoader, List[DataLoader]]: # TODO handle num_workers... return DataLoader(self.test_dataset, batch_size=None, num_workers=self.num_workers )", "test data files (basically everything with session 2 self.logger.info(f'stage:{stage}. creating Dataset...') test_files =", "f\"test_dataset={self.test_dataset!r}, \" \\ f\"dims={self.dims!r}, \" \\ f\"normalisation_name={self.normalisation!r}), \" \\ f\"Szenario={self.szenario})\" def __rich_repr__(self): yield", "to be a pain. therefore ill load all relevant (normalized + session1) train_val_files", "self.logger.info(f'found {len(test_files)} test-files.') # create test Dataset from src.datamodules.datasets.archery_bowling_dataset import ArcheryBowlingDataset test_df =", "del train_df else: from src.datamodules.datasets.archery_bowling_dataset import ArcheryBowlingDataset self.train_dataset = ArcheryBowlingDataset.create_from_dataframe(train_val_df, self.window_size, self.batch_size, name='TRAIN',", "-> Union[DataLoader, List[DataLoader]]: # TODO handle num_workers... return DataLoader(self.test_dataset, batch_size=None, num_workers=self.num_workers ) def", "Dataset from src.datamodules.datasets.archery_bowling_dataset import ArcheryBowlingDataset test_df = ArcheryBowlingDataModule.load_dataframe_from_multiple_files(test_files) computed_batch_size = self.batch_size rest =", "% modulo != 0] del train_val_df self.train_dataset = ArcheryBowlingDataset.create_from_dataframe(train_df, self.window_size, self.batch_size, name='TRAIN', feature_cols=self.features,", "0: # not none and > 0 modulo = int(1 / self.val_ratio) if", "[] for i in file_list: tmp = pd.read_csv(i) df_list.append(tmp) return pd.concat(df_list, ignore_index=True) def", "from torchvision.transforms import transforms from src.utils.utils import get_logger class ArcheryBowlingDataModule(pl.LightningDataModule): def __init__(self, data_root:", "num_workers=self.num_workers ) def __repr__(self): return f\"DataModule(train_dataset={self.train_dataset!r}, \" \\ f\"val_dataset={self.val_dataset!r}, \" \\ f\"test_dataset={self.test_dataset!r}, \"", "str(self.val_dataset), 'test dataset': None if not self.test_dataset else str(self.test_dataset), 'dims': self.dims, '#batches': len(self.test_dataset),", "feature_cols=self.features, identifier_col=self.identifier_col, label_col=self.label_col, shuffle_windows=self.shuffle_windows, sorting_cols=self.sorting_cols ) del train_df else: from src.datamodules.datasets.archery_bowling_dataset import ArcheryBowlingDataset", "Union[DataLoader, List[DataLoader], Dict[str, DataLoader]]: return DataLoader(self.train_dataset, batch_size=None, num_workers=self.num_workers ) def val_dataloader(self) -> Union[DataLoader,", "f\"val_dataset={self.val_dataset!r}, \" \\ f\"test_dataset={self.test_dataset!r}, \" \\ f\"dims={self.dims!r}, \" \\ f\"normalisation_name={self.normalisation!r}), \" \\ f\"Szenario={self.szenario})\"", "1) if stage in (None, 'fit'): # TODO no validation set throws a", "stage: Optional[str] = None) -> None: # do i want to load all", "= ArcheryBowlingDataModule.load_dataframe_from_multiple_files(train_val_files) # TODO refactor this ifelse structure to a neat structure if", "> 0: # not none and > 0 modulo = int(1 / self.val_ratio)", "= None self.logger.info('train/val Data initialized!') if stage in (None, 'test'): # slice all", "Error on val data loader... self.logger.info(f'stage:{stage}. creating Dataset...') # regexing or sorting the", "shuffle_windows=self.shuffle_windows, sorting_cols=self.sorting_cols ) del train_df else: from src.datamodules.datasets.archery_bowling_dataset import ArcheryBowlingDataset self.train_dataset = ArcheryBowlingDataset.create_from_dataframe(train_val_df,", "done.') def setup(self, stage: Optional[str] = None) -> None: # do i want", "available for training. ' f'Therefore all Data will be used as train-set!') from", "Dict, Optional import pandas as pd from torch.utils.data import DataLoader import pytorch_lightning as", "< 2: self.logger.info( f'validation split ratio({self.val_ratio}) was set, ' f'but would result in", "train_df else: from src.datamodules.datasets.archery_bowling_dataset import ArcheryBowlingDataset self.train_dataset = ArcheryBowlingDataset.create_from_dataframe(train_val_df, self.window_size, self.batch_size, name='TRAIN', feature_cols=self.features,", "Dataset...') # regexing or sorting the file path seems to be a pain.", "to validation # keep the remaining as train # drop unused columns #", "= False, val_ratio: float = None, batch_size: int = 1, window_size: int =", "= test self.data_root = Path(data_root) # Path is just more convenient self.transform =", "no validation set throws a Nonetype Error on val data loader... self.logger.info(f'stage:{stage}. creating", "self.window_size, self.batch_size, name='TRAIN', feature_cols=self.features, identifier_col=self.identifier_col, label_col=self.label_col, shuffle_windows=self.shuffle_windows, sorting_cols=self.sorting_cols ) del train_df else: from", "identifier_col: str = 'seq_id', label_col: str = 'ParticipantID', sorting_cols: List[str] = None, num_workers:", ") def val_dataloader(self) -> Union[DataLoader, List[DataLoader]]: return DataLoader(self.val_dataset, batch_size=None, num_workers=self.num_workers ) def test_dataloader(self)", "= batch_size self.val_ratio = val_ratio self.separate = test self.data_root = Path(data_root) # Path", "data loader... self.logger.info(f'stage:{stage}. creating Dataset...') # regexing or sorting the file path seems", "rest = len(test_df) % self.batch_size computed_batch_size -= rest self.test_dataset = ArcheryBowlingDataset.create_from_dataframe(test_df, self.window_size, computed_batch_size,", "ratio({self.val_ratio}) was set, ' f'but would result in either all or no data", "want to load all data at once, and slice afterwords? # slice all", "sorting_cols: List[str] = None, num_workers: int = 1, shuffle_windows=False ): super(ArcheryBowlingDataModule, self).__init__() self.num_workers", "= features self.identifier_col = identifier_col if identifier_col is not None else 'seq_id' self.label_col", "none and > 0 modulo = int(1 / self.val_ratio) if modulo > 12", "int = 10, normalisation: str = 'WithoutNormalization', szenario: str = 'Archery', features: List[str]", "feature_cols=self.features, identifier_col=self.identifier_col, label_col=self.label_col, shuffle_windows=False, sorting_cols=self.sorting_cols ) self.logger.info('test Data initialized!') self.logger.info(f'Datasets are setup.') self.logger.info(self)", "self.window_size, self.batch_size, name='VAL', feature_cols=self.features, identifier_col=self.identifier_col, label_col=self.label_col, shuffle_windows=self.shuffle_windows, sorting_cols=self.sorting_cols ) del val_df train_df =", "self.normalisation } def train_dataloader(self) -> Union[DataLoader, List[DataLoader], Dict[str, DataLoader]]: return DataLoader(self.train_dataset, batch_size=None, num_workers=self.num_workers", "import DataLoader import pytorch_lightning as pl from torchvision.transforms import transforms from src.utils.utils import", "identifier_col=self.identifier_col, label_col=self.label_col, shuffle_windows=self.shuffle_windows, sorting_cols=self.sorting_cols ) del train_df else: from src.datamodules.datasets.archery_bowling_dataset import ArcheryBowlingDataset self.train_dataset", "def _create_info_dict(self): return { 'train dataset': None if not self.train_dataset else str(self.train_dataset), 'val", "or sorting the file path seems to be a pain. therefore ill load", "0] from src.datamodules.datasets.archery_bowling_dataset import ArcheryBowlingDataset self.val_dataset = ArcheryBowlingDataset.create_from_dataframe(val_df, self.window_size, self.batch_size, name='VAL', feature_cols=self.features, identifier_col=self.identifier_col,", "self.test_dataset = ArcheryBowlingDataset.create_from_dataframe(test_df, self.window_size, computed_batch_size, name='TEST', feature_cols=self.features, identifier_col=self.identifier_col, label_col=self.label_col, shuffle_windows=False, sorting_cols=self.sorting_cols ) self.logger.info('test", "List[DataLoader]]: # TODO handle num_workers... return DataLoader(self.test_dataset, batch_size=None, num_workers=self.num_workers ) def __repr__(self): return", "= None, num_workers: int = 1, shuffle_windows=False ): super(ArcheryBowlingDataModule, self).__init__() self.num_workers = num_workers", "list of paths for test data files (basically everything with session 2 self.logger.info(f'stage:{stage}.", "identifier_col is not None else 'seq_id' self.label_col = label_col if label_col is not", "all relevant (normalized + session1) train_val_files = self.get_file_list(session=1) train_val_files = list(train_val_files) self.logger.info(f'found {len(train_val_files)}", ") def __repr__(self): return f\"DataModule(train_dataset={self.train_dataset!r}, \" \\ f\"val_dataset={self.val_dataset!r}, \" \\ f\"test_dataset={self.test_dataset!r}, \" \\", "None self.logger.info('__init__ done.') def setup(self, stage: Optional[str] = None) -> None: # do", "all data at once, and slice afterwords? # slice all modulo matching repetitions", "ignore_index=True) def _create_info_dict(self): return { 'train dataset': None if not self.train_dataset else str(self.train_dataset),", "all modulo matching repetitions to validation # keep the remaining as train #", "dataset': None if not self.test_dataset else str(self.test_dataset), 'dims': self.dims, '#batches': len(self.test_dataset), 'window size':", "'RightVirtualHand_pos_X'], identifier_col: str = 'seq_id', label_col: str = 'ParticipantID', sorting_cols: List[str] = None,", "sorting the file path seems to be a pain. therefore ill load all", "return DataLoader(self.test_dataset, batch_size=None, num_workers=self.num_workers ) def __repr__(self): return f\"DataModule(train_dataset={self.train_dataset!r}, \" \\ f\"val_dataset={self.val_dataset!r}, \"", "List, Dict, Optional import pandas as pd from torch.utils.data import DataLoader import pytorch_lightning", "setup.') self.logger.info(self) def get_file_list(self, session=1): train_val_files = self.data_root.glob(f'{self.szenario}*{self.normalisation}*session{session}*.csv') return train_val_files @staticmethod def load_dataframe_from_multiple_files(file_list:", "shuffle_windows=False ): super(ArcheryBowlingDataModule, self).__init__() self.num_workers = num_workers self.logger = get_logger(name='A-B-DataModule') self.szenario = szenario", "dataset': None if not self.val_dataset else str(self.val_dataset), 'test dataset': None if not self.test_dataset", "pd.concat(df_list, ignore_index=True) def _create_info_dict(self): return { 'train dataset': None if not self.train_dataset else", "= 10, normalisation: str = 'WithoutNormalization', szenario: str = 'Archery', features: List[str] =", "ArcheryBowlingDataset.create_from_dataframe(train_df, self.window_size, self.batch_size, name='TRAIN', feature_cols=self.features, identifier_col=self.identifier_col, label_col=self.label_col, shuffle_windows=self.shuffle_windows, sorting_cols=self.sorting_cols ) del train_df else:", "yield \"val_dataset\", self.val_dataset yield \"test_dataset\", self.test_dataset yield \"dims\", self.dims yield \"normalisation_name\", self.normalisation yield", "from typing import Union, List, Dict, Optional import pandas as pd from torch.utils.data", "# return ArcheryBowlingDataset(None, 1, 1), ArcheryBowlingDataset(None, 1, 1), ArcheryBowlingDataset(None, 1, 1) if stage", "{ 'train dataset': None if not self.train_dataset else str(self.train_dataset), 'val dataset': None if", "f\"DataModule(train_dataset={self.train_dataset!r}, \" \\ f\"val_dataset={self.val_dataset!r}, \" \\ f\"test_dataset={self.test_dataset!r}, \" \\ f\"dims={self.dims!r}, \" \\ f\"normalisation_name={self.normalisation!r}),", "None else 'ParticipantID' self.sorting_cols = sorting_cols self.normalisation = normalisation self.window_size = window_size self.batch_size", "float = None, batch_size: int = 1, window_size: int = 10, normalisation: str", "identifier_col if identifier_col is not None else 'seq_id' self.label_col = label_col if label_col", "(normalized + session1) train_val_files = self.get_file_list(session=1) train_val_files = list(train_val_files) self.logger.info(f'found {len(train_val_files)} files.') train_val_df", "not self.val_dataset else str(self.val_dataset), 'test dataset': None if not self.test_dataset else str(self.test_dataset), 'dims':", "= get_logger(name='A-B-DataModule') self.szenario = szenario self.features = features self.identifier_col = identifier_col if identifier_col", "= 'seq_id', label_col: str = 'ParticipantID', sorting_cols: List[str] = None, num_workers: int =", "self.data_root = Path(data_root) # Path is just more convenient self.transform = transforms.Compose([ transforms.ToTensor(),", "self.batch_size computed_batch_size -= rest self.test_dataset = ArcheryBowlingDataset.create_from_dataframe(test_df, self.window_size, computed_batch_size, name='TEST', feature_cols=self.features, identifier_col=self.identifier_col, label_col=self.label_col,", "len(test_df) % self.batch_size computed_batch_size -= rest self.test_dataset = ArcheryBowlingDataset.create_from_dataframe(test_df, self.window_size, computed_batch_size, name='TEST', feature_cols=self.features,", "str = 'Archery', features: List[str] = ['CenterEyeAnchor_pos_X', 'LeftVirtualHand_pos_X', 'RightVirtualHand_pos_X'], identifier_col: str = 'seq_id',", "\"train_dataset\", self.train_dataset yield \"val_dataset\", self.val_dataset yield \"test_dataset\", self.test_dataset yield \"dims\", self.dims yield \"normalisation_name\",", "> 0 modulo = int(1 / self.val_ratio) if modulo > 12 or modulo", "train-set!') from src.datamodules.datasets.archery_bowling_dataset import ArcheryBowlingDataset self.train_dataset = ArcheryBowlingDataset.create_from_dataframe(train_val_df, self.window_size, self.batch_size, name='TRAIN', feature_cols=self.features, identifier_col=self.identifier_col,", "ArcheryBowlingDataset(None, 1, 1), ArcheryBowlingDataset(None, 1, 1) if stage in (None, 'fit'): # TODO", "!= 0] del train_val_df self.train_dataset = ArcheryBowlingDataset.create_from_dataframe(train_df, self.window_size, self.batch_size, name='TRAIN', feature_cols=self.features, identifier_col=self.identifier_col, label_col=self.label_col,", "0 modulo = int(1 / self.val_ratio) if modulo > 12 or modulo <", "int = 1, window_size: int = 10, normalisation: str = 'WithoutNormalization', szenario: str", "= ArcheryBowlingDataset.create_from_dataframe(val_df, self.window_size, self.batch_size, name='VAL', feature_cols=self.features, identifier_col=self.identifier_col, label_col=self.label_col, shuffle_windows=self.shuffle_windows, sorting_cols=self.sorting_cols ) del val_df", "import get_logger class ArcheryBowlingDataModule(pl.LightningDataModule): def __init__(self, data_root: str, test: bool = False, val_ratio:", "dataset': None if not self.train_dataset else str(self.train_dataset), 'val dataset': None if not self.val_dataset", "a list of paths for test data files (basically everything with session 2", "not none and > 0 modulo = int(1 / self.val_ratio) if modulo >", "1, shuffle_windows=False ): super(ArcheryBowlingDataModule, self).__init__() self.num_workers = num_workers self.logger = get_logger(name='A-B-DataModule') self.szenario =", "or no data being available for training. ' f'Therefore all Data will be", "self.batch_size = batch_size self.val_ratio = val_ratio self.separate = test self.data_root = Path(data_root) #", "else: from src.datamodules.datasets.archery_bowling_dataset import ArcheryBowlingDataset self.train_dataset = ArcheryBowlingDataset.create_from_dataframe(train_val_df, self.window_size, self.batch_size, name='TRAIN', feature_cols=self.features, identifier_col=self.identifier_col,", "ArcheryBowlingDataset(None, 1, 1) if stage in (None, 'fit'): # TODO no validation set", "DataLoader]]: return DataLoader(self.train_dataset, batch_size=None, num_workers=self.num_workers ) def val_dataloader(self) -> Union[DataLoader, List[DataLoader]]: return DataLoader(self.val_dataset,", "label_col if label_col is not None else 'ParticipantID' self.sorting_cols = sorting_cols self.normalisation =", "List[str] = ['CenterEyeAnchor_pos_X', 'LeftVirtualHand_pos_X', 'RightVirtualHand_pos_X'], identifier_col: str = 'seq_id', label_col: str = 'ParticipantID',", "seems to be a pain. therefore ill load all relevant (normalized + session1)", "= pd.read_csv(i) df_list.append(tmp) return pd.concat(df_list, ignore_index=True) def _create_info_dict(self): return { 'train dataset': None", "\"val_dataset\", self.val_dataset yield \"test_dataset\", self.test_dataset yield \"dims\", self.dims yield \"normalisation_name\", self.normalisation yield \"szenario\",", "DataLoader(self.val_dataset, batch_size=None, num_workers=self.num_workers ) def test_dataloader(self) -> Union[DataLoader, List[DataLoader]]: # TODO handle num_workers...", "Union, List, Dict, Optional import pandas as pd from torch.utils.data import DataLoader import", "import ArcheryBowlingDataset test_df = ArcheryBowlingDataModule.load_dataframe_from_multiple_files(test_files) computed_batch_size = self.batch_size rest = len(test_df) % self.batch_size", "List[DataLoader]]: return DataLoader(self.val_dataset, batch_size=None, num_workers=self.num_workers ) def test_dataloader(self) -> Union[DataLoader, List[DataLoader]]: # TODO", "self.logger.info(self) def get_file_list(self, session=1): train_val_files = self.data_root.glob(f'{self.szenario}*{self.normalisation}*session{session}*.csv') return train_val_files @staticmethod def load_dataframe_from_multiple_files(file_list: List[Path]):", "def __init__(self, data_root: str, test: bool = False, val_ratio: float = None, batch_size:", "'ParticipantID' self.sorting_cols = sorting_cols self.normalisation = normalisation self.window_size = window_size self.batch_size = batch_size", "structure if self.val_ratio and self.val_ratio > 0: # not none and > 0", "self.train_dataset = ArcheryBowlingDataset.create_from_dataframe(train_val_df, self.window_size, self.batch_size, name='TRAIN', feature_cols=self.features, identifier_col=self.identifier_col, label_col=self.label_col, shuffle_windows=self.shuffle_windows, sorting_cols=self.sorting_cols ) self.val_dataset", "return pd.concat(df_list, ignore_index=True) def _create_info_dict(self): return { 'train dataset': None if not self.train_dataset", "repetitions to validation # keep the remaining as train # drop unused columns", "all 'session2' entries for test data # create a list of paths for", "# regexing or sorting the file path seems to be a pain. therefore", "as train # drop unused columns # initiate DatasetObjects and return them #", "slice all modulo matching repetitions to validation # keep the remaining as train", "f'validation split ratio({self.val_ratio}) was set, ' f'but would result in either all or", "def load_dataframe_from_multiple_files(file_list: List[Path]): df_list = [] for i in file_list: tmp = pd.read_csv(i)", "self.logger.info('test Data initialized!') self.logger.info(f'Datasets are setup.') self.logger.info(self) def get_file_list(self, session=1): train_val_files = self.data_root.glob(f'{self.szenario}*{self.normalisation}*session{session}*.csv')", "file path seems to be a pain. therefore ill load all relevant (normalized", "self.get_file_list(session=2) test_files = (list(test_files)) self.logger.info(f'found {len(test_files)} test-files.') # create test Dataset from src.datamodules.datasets.archery_bowling_dataset", "num_workers=self.num_workers ) def test_dataloader(self) -> Union[DataLoader, List[DataLoader]]: # TODO handle num_workers... return DataLoader(self.test_dataset,", "} def train_dataloader(self) -> Union[DataLoader, List[DataLoader], Dict[str, DataLoader]]: return DataLoader(self.train_dataset, batch_size=None, num_workers=self.num_workers )", "if modulo > 12 or modulo < 2: self.logger.info( f'validation split ratio({self.val_ratio}) was", "\" \\ f\"test_dataset={self.test_dataset!r}, \" \\ f\"dims={self.dims!r}, \" \\ f\"normalisation_name={self.normalisation!r}), \" \\ f\"Szenario={self.szenario})\" def", "\\ f\"Szenario={self.szenario})\" def __rich_repr__(self): yield \"train_dataset\", self.train_dataset yield \"val_dataset\", self.val_dataset yield \"test_dataset\", self.test_dataset", "no data being available for training. ' f'Therefore all Data will be used", "'ParticipantID', sorting_cols: List[str] = None, num_workers: int = 1, shuffle_windows=False ): super(ArcheryBowlingDataModule, self).__init__()", "ifelse structure to a neat structure if self.val_ratio and self.val_ratio > 0: #", "files.') train_val_df = ArcheryBowlingDataModule.load_dataframe_from_multiple_files(train_val_files) # TODO refactor this ifelse structure to a neat", "TODO refactor this ifelse structure to a neat structure if self.val_ratio and self.val_ratio", "df_list.append(tmp) return pd.concat(df_list, ignore_index=True) def _create_info_dict(self): return { 'train dataset': None if not", "self.train_dataset yield \"val_dataset\", self.val_dataset yield \"test_dataset\", self.test_dataset yield \"dims\", self.dims yield \"normalisation_name\", self.normalisation", "(None, 'fit'): # TODO no validation set throws a Nonetype Error on val", "self.normalisation = normalisation self.window_size = window_size self.batch_size = batch_size self.val_ratio = val_ratio self.separate", ") del train_df else: from src.datamodules.datasets.archery_bowling_dataset import ArcheryBowlingDataset self.train_dataset = ArcheryBowlingDataset.create_from_dataframe(train_val_df, self.window_size, self.batch_size,", "self.logger.info(f'stage:{stage}. creating Dataset...') test_files = self.get_file_list(session=2) test_files = (list(test_files)) self.logger.info(f'found {len(test_files)} test-files.') #", "bool = False, val_ratio: float = None, batch_size: int = 1, window_size: int", "load all relevant (normalized + session1) train_val_files = self.get_file_list(session=1) train_val_files = list(train_val_files) self.logger.info(f'found", "-> Union[DataLoader, List[DataLoader]]: return DataLoader(self.val_dataset, batch_size=None, num_workers=self.num_workers ) def test_dataloader(self) -> Union[DataLoader, List[DataLoader]]:", "label_col=self.label_col, shuffle_windows=self.shuffle_windows, sorting_cols=self.sorting_cols ) del train_df else: from src.datamodules.datasets.archery_bowling_dataset import ArcheryBowlingDataset self.train_dataset =", "not self.test_dataset else str(self.test_dataset), 'dims': self.dims, '#batches': len(self.test_dataset), 'window size': self.window_size, 'batch size':", "name='TEST', feature_cols=self.features, identifier_col=self.identifier_col, label_col=self.label_col, shuffle_windows=False, sorting_cols=self.sorting_cols ) self.logger.info('test Data initialized!') self.logger.info(f'Datasets are setup.')", "val_df train_df = train_val_df[train_val_df['repetition'] % modulo != 0] del train_val_df self.train_dataset = ArcheryBowlingDataset.create_from_dataframe(train_df,", "name='TRAIN', feature_cols=self.features, identifier_col=self.identifier_col, label_col=self.label_col, shuffle_windows=self.shuffle_windows, sorting_cols=self.sorting_cols ) self.val_dataset = None self.logger.info('train/val Data initialized!')", "batch_size self.val_ratio = val_ratio self.separate = test self.data_root = Path(data_root) # Path is", "'Archery', features: List[str] = ['CenterEyeAnchor_pos_X', 'LeftVirtualHand_pos_X', 'RightVirtualHand_pos_X'], identifier_col: str = 'seq_id', label_col: str", "{len(test_files)} test-files.') # create test Dataset from src.datamodules.datasets.archery_bowling_dataset import ArcheryBowlingDataset test_df = ArcheryBowlingDataModule.load_dataframe_from_multiple_files(test_files)", "= transforms.Compose([ transforms.ToTensor(), ]) self.shuffle_windows = shuffle_windows self.num_features = len(features) self.dims = (self.window_size,", "batch_size=None, num_workers=self.num_workers ) def val_dataloader(self) -> Union[DataLoader, List[DataLoader]]: return DataLoader(self.val_dataset, batch_size=None, num_workers=self.num_workers )", "set, ' f'but would result in either all or no data being available", "all or no data being available for training. ' f'Therefore all Data will", "super(ArcheryBowlingDataModule, self).__init__() self.num_workers = num_workers self.logger = get_logger(name='A-B-DataModule') self.szenario = szenario self.features =", "pl from torchvision.transforms import transforms from src.utils.utils import get_logger class ArcheryBowlingDataModule(pl.LightningDataModule): def __init__(self,", "self.num_workers = num_workers self.logger = get_logger(name='A-B-DataModule') self.szenario = szenario self.features = features self.identifier_col", "None if not self.test_dataset else str(self.test_dataset), 'dims': self.dims, '#batches': len(self.test_dataset), 'window size': self.window_size,", "# not none and > 0 modulo = int(1 / self.val_ratio) if modulo", "Dataset...') test_files = self.get_file_list(session=2) test_files = (list(test_files)) self.logger.info(f'found {len(test_files)} test-files.') # create test", "stage in (None, 'test'): # slice all 'session2' entries for test data #", "val_ratio: float = None, batch_size: int = 1, window_size: int = 10, normalisation:", "not None else 'seq_id' self.label_col = label_col if label_col is not None else", "sorting_cols=self.sorting_cols ) else: val_df = train_val_df[train_val_df['repetition'] % modulo == 0] from src.datamodules.datasets.archery_bowling_dataset import", "self.val_ratio > 0: # not none and > 0 modulo = int(1 /", "test Dataset from src.datamodules.datasets.archery_bowling_dataset import ArcheryBowlingDataset test_df = ArcheryBowlingDataModule.load_dataframe_from_multiple_files(test_files) computed_batch_size = self.batch_size rest", "= ArcheryBowlingDataset.create_from_dataframe(test_df, self.window_size, computed_batch_size, name='TEST', feature_cols=self.features, identifier_col=self.identifier_col, label_col=self.label_col, shuffle_windows=False, sorting_cols=self.sorting_cols ) self.logger.info('test Data", "None, None, None self.logger.info('__init__ done.') def setup(self, stage: Optional[str] = None) -> None:", "data files (basically everything with session 2 self.logger.info(f'stage:{stage}. creating Dataset...') test_files = self.get_file_list(session=2)", "train_dataloader(self) -> Union[DataLoader, List[DataLoader], Dict[str, DataLoader]]: return DataLoader(self.train_dataset, batch_size=None, num_workers=self.num_workers ) def val_dataloader(self)", "return DataLoader(self.val_dataset, batch_size=None, num_workers=self.num_workers ) def test_dataloader(self) -> Union[DataLoader, List[DataLoader]]: # TODO handle", "# keep the remaining as train # drop unused columns # initiate DatasetObjects", "= val_ratio self.separate = test self.data_root = Path(data_root) # Path is just more", "self.num_features = len(features) self.dims = (self.window_size, self.num_features) self.train_dataset, self.val_dataset, self.test_dataset = None, None,", "= int(1 / self.val_ratio) if modulo > 12 or modulo < 2: self.logger.info(", "val_df = train_val_df[train_val_df['repetition'] % modulo == 0] from src.datamodules.datasets.archery_bowling_dataset import ArcheryBowlingDataset self.val_dataset =", "str = 'ParticipantID', sorting_cols: List[str] = None, num_workers: int = 1, shuffle_windows=False ):", "to load all data at once, and slice afterwords? # slice all modulo", "'session2' entries for test data # create a list of paths for test", "self.train_dataset, self.val_dataset, self.test_dataset = None, None, None self.logger.info('__init__ done.') def setup(self, stage: Optional[str]", "ArcheryBowlingDataset self.train_dataset = ArcheryBowlingDataset.create_from_dataframe(train_val_df, self.window_size, self.batch_size, name='TRAIN', feature_cols=self.features, identifier_col=self.identifier_col, label_col=self.label_col, shuffle_windows=self.shuffle_windows, sorting_cols=self.sorting_cols )", "{len(train_val_files)} files.') train_val_df = ArcheryBowlingDataModule.load_dataframe_from_multiple_files(train_val_files) # TODO refactor this ifelse structure to a", "modulo < 2: self.logger.info( f'validation split ratio({self.val_ratio}) was set, ' f'but would result", "and self.val_ratio > 0: # not none and > 0 modulo = int(1", "return ArcheryBowlingDataset(None, 1, 1), ArcheryBowlingDataset(None, 1, 1), ArcheryBowlingDataset(None, 1, 1) if stage in", "-> None: # do i want to load all data at once, and", "num_workers=self.num_workers ) def val_dataloader(self) -> Union[DataLoader, List[DataLoader]]: return DataLoader(self.val_dataset, batch_size=None, num_workers=self.num_workers ) def", "normalisation self.window_size = window_size self.batch_size = batch_size self.val_ratio = val_ratio self.separate = test", "remaining as train # drop unused columns # initiate DatasetObjects and return them", "= self.get_file_list(session=1) train_val_files = list(train_val_files) self.logger.info(f'found {len(train_val_files)} files.') train_val_df = ArcheryBowlingDataModule.load_dataframe_from_multiple_files(train_val_files) # TODO", "creating Dataset...') # regexing or sorting the file path seems to be a", "# do i want to load all data at once, and slice afterwords?", "self.window_size, self.batch_size, name='TRAIN', feature_cols=self.features, identifier_col=self.identifier_col, label_col=self.label_col, shuffle_windows=self.shuffle_windows, sorting_cols=self.sorting_cols ) else: val_df = train_val_df[train_val_df['repetition']", "be used as train-set!') from src.datamodules.datasets.archery_bowling_dataset import ArcheryBowlingDataset self.train_dataset = ArcheryBowlingDataset.create_from_dataframe(train_val_df, self.window_size, self.batch_size,", "# TODO no validation set throws a Nonetype Error on val data loader...", "= ['CenterEyeAnchor_pos_X', 'LeftVirtualHand_pos_X', 'RightVirtualHand_pos_X'], identifier_col: str = 'seq_id', label_col: str = 'ParticipantID', sorting_cols:", "None self.logger.info('train/val Data initialized!') if stage in (None, 'test'): # slice all 'session2'", "= szenario self.features = features self.identifier_col = identifier_col if identifier_col is not None", "ill load all relevant (normalized + session1) train_val_files = self.get_file_list(session=1) train_val_files = list(train_val_files)", "'window size': self.window_size, 'batch size': self.batch_size, 'normalisation name': self.normalisation } def train_dataloader(self) ->", "normalisation: str = 'WithoutNormalization', szenario: str = 'Archery', features: List[str] = ['CenterEyeAnchor_pos_X', 'LeftVirtualHand_pos_X',", "f\"dims={self.dims!r}, \" \\ f\"normalisation_name={self.normalisation!r}), \" \\ f\"Szenario={self.szenario})\" def __rich_repr__(self): yield \"train_dataset\", self.train_dataset yield", "training. ' f'Therefore all Data will be used as train-set!') from src.datamodules.datasets.archery_bowling_dataset import", "class ArcheryBowlingDataModule(pl.LightningDataModule): def __init__(self, data_root: str, test: bool = False, val_ratio: float =", "TODO no validation set throws a Nonetype Error on val data loader... self.logger.info(f'stage:{stage}.", "loader... self.logger.info(f'stage:{stage}. creating Dataset...') # regexing or sorting the file path seems to", "file_list: tmp = pd.read_csv(i) df_list.append(tmp) return pd.concat(df_list, ignore_index=True) def _create_info_dict(self): return { 'train", "return them # return ArcheryBowlingDataset(None, 1, 1), ArcheryBowlingDataset(None, 1, 1), ArcheryBowlingDataset(None, 1, 1)", "train_val_files @staticmethod def load_dataframe_from_multiple_files(file_list: List[Path]): df_list = [] for i in file_list: tmp", "self.val_dataset, self.test_dataset = None, None, None self.logger.info('__init__ done.') def setup(self, stage: Optional[str] =", "rest self.test_dataset = ArcheryBowlingDataset.create_from_dataframe(test_df, self.window_size, computed_batch_size, name='TEST', feature_cols=self.features, identifier_col=self.identifier_col, label_col=self.label_col, shuffle_windows=False, sorting_cols=self.sorting_cols )", "def __rich_repr__(self): yield \"train_dataset\", self.train_dataset yield \"val_dataset\", self.val_dataset yield \"test_dataset\", self.test_dataset yield \"dims\",", "= None, batch_size: int = 1, window_size: int = 10, normalisation: str =", "import pandas as pd from torch.utils.data import DataLoader import pytorch_lightning as pl from", "@staticmethod def load_dataframe_from_multiple_files(file_list: List[Path]): df_list = [] for i in file_list: tmp =", "list(train_val_files) self.logger.info(f'found {len(train_val_files)} files.') train_val_df = ArcheryBowlingDataModule.load_dataframe_from_multiple_files(train_val_files) # TODO refactor this ifelse structure", "len(self.test_dataset), 'window size': self.window_size, 'batch size': self.batch_size, 'normalisation name': self.normalisation } def train_dataloader(self)", "Data initialized!') self.logger.info(f'Datasets are setup.') self.logger.info(self) def get_file_list(self, session=1): train_val_files = self.data_root.glob(f'{self.szenario}*{self.normalisation}*session{session}*.csv') return", "for test data # create a list of paths for test data files", "slice all 'session2' entries for test data # create a list of paths", "shuffle_windows=self.shuffle_windows, sorting_cols=self.sorting_cols ) self.val_dataset = None self.logger.info('train/val Data initialized!') if stage in (None,", "initialized!') if stage in (None, 'test'): # slice all 'session2' entries for test", "None, num_workers: int = 1, shuffle_windows=False ): super(ArcheryBowlingDataModule, self).__init__() self.num_workers = num_workers self.logger", "2: self.logger.info( f'validation split ratio({self.val_ratio}) was set, ' f'but would result in either", "\\ f\"val_dataset={self.val_dataset!r}, \" \\ f\"test_dataset={self.test_dataset!r}, \" \\ f\"dims={self.dims!r}, \" \\ f\"normalisation_name={self.normalisation!r}), \" \\", "keep the remaining as train # drop unused columns # initiate DatasetObjects and", "f'Therefore all Data will be used as train-set!') from src.datamodules.datasets.archery_bowling_dataset import ArcheryBowlingDataset self.train_dataset", ") self.logger.info('test Data initialized!') self.logger.info(f'Datasets are setup.') self.logger.info(self) def get_file_list(self, session=1): train_val_files =", "throws a Nonetype Error on val data loader... self.logger.info(f'stage:{stage}. creating Dataset...') # regexing", ") else: val_df = train_val_df[train_val_df['repetition'] % modulo == 0] from src.datamodules.datasets.archery_bowling_dataset import ArcheryBowlingDataset", "1), ArcheryBowlingDataset(None, 1, 1) if stage in (None, 'fit'): # TODO no validation", "data # create a list of paths for test data files (basically everything", "to a neat structure if self.val_ratio and self.val_ratio > 0: # not none", "str(self.train_dataset), 'val dataset': None if not self.val_dataset else str(self.val_dataset), 'test dataset': None if", "get_logger(name='A-B-DataModule') self.szenario = szenario self.features = features self.identifier_col = identifier_col if identifier_col is", "as pd from torch.utils.data import DataLoader import pytorch_lightning as pl from torchvision.transforms import", "DatasetObjects and return them # return ArcheryBowlingDataset(None, 1, 1), ArcheryBowlingDataset(None, 1, 1), ArcheryBowlingDataset(None,", "= shuffle_windows self.num_features = len(features) self.dims = (self.window_size, self.num_features) self.train_dataset, self.val_dataset, self.test_dataset =", "train_val_df self.train_dataset = ArcheryBowlingDataset.create_from_dataframe(train_df, self.window_size, self.batch_size, name='TRAIN', feature_cols=self.features, identifier_col=self.identifier_col, label_col=self.label_col, shuffle_windows=self.shuffle_windows, sorting_cols=self.sorting_cols )", "load_dataframe_from_multiple_files(file_list: List[Path]): df_list = [] for i in file_list: tmp = pd.read_csv(i) df_list.append(tmp)", "self.identifier_col = identifier_col if identifier_col is not None else 'seq_id' self.label_col = label_col", "in (None, 'test'): # slice all 'session2' entries for test data # create", "str, test: bool = False, val_ratio: float = None, batch_size: int = 1,", "self.batch_size, name='TRAIN', feature_cols=self.features, identifier_col=self.identifier_col, label_col=self.label_col, shuffle_windows=self.shuffle_windows, sorting_cols=self.sorting_cols ) self.val_dataset = None self.logger.info('train/val Data", "Data initialized!') if stage in (None, 'test'): # slice all 'session2' entries for", "not None else 'ParticipantID' self.sorting_cols = sorting_cols self.normalisation = normalisation self.window_size = window_size", "\" \\ f\"Szenario={self.szenario})\" def __rich_repr__(self): yield \"train_dataset\", self.train_dataset yield \"val_dataset\", self.val_dataset yield \"test_dataset\",", "self.dims = (self.window_size, self.num_features) self.train_dataset, self.val_dataset, self.test_dataset = None, None, None self.logger.info('__init__ done.')", "Dict[str, DataLoader]]: return DataLoader(self.train_dataset, batch_size=None, num_workers=self.num_workers ) def val_dataloader(self) -> Union[DataLoader, List[DataLoader]]: return", "self.val_ratio) if modulo > 12 or modulo < 2: self.logger.info( f'validation split ratio({self.val_ratio})", "= identifier_col if identifier_col is not None else 'seq_id' self.label_col = label_col if", "self.separate = test self.data_root = Path(data_root) # Path is just more convenient self.transform", ") self.val_dataset = None self.logger.info('train/val Data initialized!') if stage in (None, 'test'): #", "pytorch_lightning as pl from torchvision.transforms import transforms from src.utils.utils import get_logger class ArcheryBowlingDataModule(pl.LightningDataModule):", "transforms.Compose([ transforms.ToTensor(), ]) self.shuffle_windows = shuffle_windows self.num_features = len(features) self.dims = (self.window_size, self.num_features)", "List[str] = None, num_workers: int = 1, shuffle_windows=False ): super(ArcheryBowlingDataModule, self).__init__() self.num_workers =", "else str(self.val_dataset), 'test dataset': None if not self.test_dataset else str(self.test_dataset), 'dims': self.dims, '#batches':", "convenient self.transform = transforms.Compose([ transforms.ToTensor(), ]) self.shuffle_windows = shuffle_windows self.num_features = len(features) self.dims", "= None) -> None: # do i want to load all data at", "import Path from typing import Union, List, Dict, Optional import pandas as pd", "2 self.logger.info(f'stage:{stage}. creating Dataset...') test_files = self.get_file_list(session=2) test_files = (list(test_files)) self.logger.info(f'found {len(test_files)} test-files.')", "sorting_cols=self.sorting_cols ) del val_df train_df = train_val_df[train_val_df['repetition'] % modulo != 0] del train_val_df", "identifier_col=self.identifier_col, label_col=self.label_col, shuffle_windows=self.shuffle_windows, sorting_cols=self.sorting_cols ) self.val_dataset = None self.logger.info('train/val Data initialized!') if stage", "self.batch_size, name='TRAIN', feature_cols=self.features, identifier_col=self.identifier_col, label_col=self.label_col, shuffle_windows=self.shuffle_windows, sorting_cols=self.sorting_cols ) del train_df else: from src.datamodules.datasets.archery_bowling_dataset", "= ArcheryBowlingDataset.create_from_dataframe(train_df, self.window_size, self.batch_size, name='TRAIN', feature_cols=self.features, identifier_col=self.identifier_col, label_col=self.label_col, shuffle_windows=self.shuffle_windows, sorting_cols=self.sorting_cols ) del train_df", "initiate DatasetObjects and return them # return ArcheryBowlingDataset(None, 1, 1), ArcheryBowlingDataset(None, 1, 1),", "features: List[str] = ['CenterEyeAnchor_pos_X', 'LeftVirtualHand_pos_X', 'RightVirtualHand_pos_X'], identifier_col: str = 'seq_id', label_col: str =", "= window_size self.batch_size = batch_size self.val_ratio = val_ratio self.separate = test self.data_root =", "modulo != 0] del train_val_df self.train_dataset = ArcheryBowlingDataset.create_from_dataframe(train_df, self.window_size, self.batch_size, name='TRAIN', feature_cols=self.features, identifier_col=self.identifier_col,", "else str(self.train_dataset), 'val dataset': None if not self.val_dataset else str(self.val_dataset), 'test dataset': None", "f\"Szenario={self.szenario})\" def __rich_repr__(self): yield \"train_dataset\", self.train_dataset yield \"val_dataset\", self.val_dataset yield \"test_dataset\", self.test_dataset yield", "shuffle_windows=self.shuffle_windows, sorting_cols=self.sorting_cols ) del val_df train_df = train_val_df[train_val_df['repetition'] % modulo != 0] del", "= label_col if label_col is not None else 'ParticipantID' self.sorting_cols = sorting_cols self.normalisation", "in either all or no data being available for training. ' f'Therefore all", "and > 0 modulo = int(1 / self.val_ratio) if modulo > 12 or", "__repr__(self): return f\"DataModule(train_dataset={self.train_dataset!r}, \" \\ f\"val_dataset={self.val_dataset!r}, \" \\ f\"test_dataset={self.test_dataset!r}, \" \\ f\"dims={self.dims!r}, \"", "== 0] from src.datamodules.datasets.archery_bowling_dataset import ArcheryBowlingDataset self.val_dataset = ArcheryBowlingDataset.create_from_dataframe(val_df, self.window_size, self.batch_size, name='VAL', feature_cols=self.features,", "\" \\ f\"val_dataset={self.val_dataset!r}, \" \\ f\"test_dataset={self.test_dataset!r}, \" \\ f\"dims={self.dims!r}, \" \\ f\"normalisation_name={self.normalisation!r}), \"", "transforms.ToTensor(), ]) self.shuffle_windows = shuffle_windows self.num_features = len(features) self.dims = (self.window_size, self.num_features) self.train_dataset,", "once, and slice afterwords? # slice all modulo matching repetitions to validation #", "f'but would result in either all or no data being available for training.", "torchvision.transforms import transforms from src.utils.utils import get_logger class ArcheryBowlingDataModule(pl.LightningDataModule): def __init__(self, data_root: str,", "self.logger.info('train/val Data initialized!') if stage in (None, 'test'): # slice all 'session2' entries", "self.test_dataset else str(self.test_dataset), 'dims': self.dims, '#batches': len(self.test_dataset), 'window size': self.window_size, 'batch size': self.batch_size,", "else str(self.test_dataset), 'dims': self.dims, '#batches': len(self.test_dataset), 'window size': self.window_size, 'batch size': self.batch_size, 'normalisation", "'test dataset': None if not self.test_dataset else str(self.test_dataset), 'dims': self.dims, '#batches': len(self.test_dataset), 'window", "None, batch_size: int = 1, window_size: int = 10, normalisation: str = 'WithoutNormalization',", "batch_size=None, num_workers=self.num_workers ) def test_dataloader(self) -> Union[DataLoader, List[DataLoader]]: # TODO handle num_workers... return", "+ session1) train_val_files = self.get_file_list(session=1) train_val_files = list(train_val_files) self.logger.info(f'found {len(train_val_files)} files.') train_val_df =", "self.data_root.glob(f'{self.szenario}*{self.normalisation}*session{session}*.csv') return train_val_files @staticmethod def load_dataframe_from_multiple_files(file_list: List[Path]): df_list = [] for i in", "del val_df train_df = train_val_df[train_val_df['repetition'] % modulo != 0] del train_val_df self.train_dataset =", "if stage in (None, 'test'): # slice all 'session2' entries for test data", "feature_cols=self.features, identifier_col=self.identifier_col, label_col=self.label_col, shuffle_windows=self.shuffle_windows, sorting_cols=self.sorting_cols ) self.val_dataset = None self.logger.info('train/val Data initialized!') if", "= num_workers self.logger = get_logger(name='A-B-DataModule') self.szenario = szenario self.features = features self.identifier_col =", "): super(ArcheryBowlingDataModule, self).__init__() self.num_workers = num_workers self.logger = get_logger(name='A-B-DataModule') self.szenario = szenario self.features", "train_val_files = self.get_file_list(session=1) train_val_files = list(train_val_files) self.logger.info(f'found {len(train_val_files)} files.') train_val_df = ArcheryBowlingDataModule.load_dataframe_from_multiple_files(train_val_files) #", "get_logger class ArcheryBowlingDataModule(pl.LightningDataModule): def __init__(self, data_root: str, test: bool = False, val_ratio: float", "1, 1), ArcheryBowlingDataset(None, 1, 1), ArcheryBowlingDataset(None, 1, 1) if stage in (None, 'fit'):", "Path is just more convenient self.transform = transforms.Compose([ transforms.ToTensor(), ]) self.shuffle_windows = shuffle_windows", "= list(train_val_files) self.logger.info(f'found {len(train_val_files)} files.') train_val_df = ArcheryBowlingDataModule.load_dataframe_from_multiple_files(train_val_files) # TODO refactor this ifelse", "name': self.normalisation } def train_dataloader(self) -> Union[DataLoader, List[DataLoader], Dict[str, DataLoader]]: return DataLoader(self.train_dataset, batch_size=None,", "Union[DataLoader, List[DataLoader]]: # TODO handle num_workers... return DataLoader(self.test_dataset, batch_size=None, num_workers=self.num_workers ) def __repr__(self):", "self.window_size = window_size self.batch_size = batch_size self.val_ratio = val_ratio self.separate = test self.data_root", "self.batch_size, name='TRAIN', feature_cols=self.features, identifier_col=self.identifier_col, label_col=self.label_col, shuffle_windows=self.shuffle_windows, sorting_cols=self.sorting_cols ) else: val_df = train_val_df[train_val_df['repetition'] %", "Nonetype Error on val data loader... self.logger.info(f'stage:{stage}. creating Dataset...') # regexing or sorting", "batch_size: int = 1, window_size: int = 10, normalisation: str = 'WithoutNormalization', szenario:", "train_val_df[train_val_df['repetition'] % modulo != 0] del train_val_df self.train_dataset = ArcheryBowlingDataset.create_from_dataframe(train_df, self.window_size, self.batch_size, name='TRAIN',", "i want to load all data at once, and slice afterwords? # slice", "1, 1) if stage in (None, 'fit'): # TODO no validation set throws", "__rich_repr__(self): yield \"train_dataset\", self.train_dataset yield \"val_dataset\", self.val_dataset yield \"test_dataset\", self.test_dataset yield \"dims\", self.dims", "self.batch_size, name='VAL', feature_cols=self.features, identifier_col=self.identifier_col, label_col=self.label_col, shuffle_windows=self.shuffle_windows, sorting_cols=self.sorting_cols ) del val_df train_df = train_val_df[train_val_df['repetition']", "def setup(self, stage: Optional[str] = None) -> None: # do i want to", "'dims': self.dims, '#batches': len(self.test_dataset), 'window size': self.window_size, 'batch size': self.batch_size, 'normalisation name': self.normalisation", "test-files.') # create test Dataset from src.datamodules.datasets.archery_bowling_dataset import ArcheryBowlingDataset test_df = ArcheryBowlingDataModule.load_dataframe_from_multiple_files(test_files) computed_batch_size", "Path from typing import Union, List, Dict, Optional import pandas as pd from", "'seq_id' self.label_col = label_col if label_col is not None else 'ParticipantID' self.sorting_cols =", "None if not self.train_dataset else str(self.train_dataset), 'val dataset': None if not self.val_dataset else", "'normalisation name': self.normalisation } def train_dataloader(self) -> Union[DataLoader, List[DataLoader], Dict[str, DataLoader]]: return DataLoader(self.train_dataset,", "(basically everything with session 2 self.logger.info(f'stage:{stage}. creating Dataset...') test_files = self.get_file_list(session=2) test_files =", "self.val_ratio and self.val_ratio > 0: # not none and > 0 modulo =", "train_df = train_val_df[train_val_df['repetition'] % modulo != 0] del train_val_df self.train_dataset = ArcheryBowlingDataset.create_from_dataframe(train_df, self.window_size,", "paths for test data files (basically everything with session 2 self.logger.info(f'stage:{stage}. creating Dataset...')", "from torch.utils.data import DataLoader import pytorch_lightning as pl from torchvision.transforms import transforms from", "train_val_files = list(train_val_files) self.logger.info(f'found {len(train_val_files)} files.') train_val_df = ArcheryBowlingDataModule.load_dataframe_from_multiple_files(train_val_files) # TODO refactor this", "Optional import pandas as pd from torch.utils.data import DataLoader import pytorch_lightning as pl", "import transforms from src.utils.utils import get_logger class ArcheryBowlingDataModule(pl.LightningDataModule): def __init__(self, data_root: str, test:", "= len(features) self.dims = (self.window_size, self.num_features) self.train_dataset, self.val_dataset, self.test_dataset = None, None, None", "import ArcheryBowlingDataset self.train_dataset = ArcheryBowlingDataset.create_from_dataframe(train_val_df, self.window_size, self.batch_size, name='TRAIN', feature_cols=self.features, identifier_col=self.identifier_col, label_col=self.label_col, shuffle_windows=self.shuffle_windows, sorting_cols=self.sorting_cols", "' f'but would result in either all or no data being available for", "self.sorting_cols = sorting_cols self.normalisation = normalisation self.window_size = window_size self.batch_size = batch_size self.val_ratio", "shuffle_windows=self.shuffle_windows, sorting_cols=self.sorting_cols ) else: val_df = train_val_df[train_val_df['repetition'] % modulo == 0] from src.datamodules.datasets.archery_bowling_dataset", "modulo == 0] from src.datamodules.datasets.archery_bowling_dataset import ArcheryBowlingDataset self.val_dataset = ArcheryBowlingDataset.create_from_dataframe(val_df, self.window_size, self.batch_size, name='VAL',", "= self.data_root.glob(f'{self.szenario}*{self.normalisation}*session{session}*.csv') return train_val_files @staticmethod def load_dataframe_from_multiple_files(file_list: List[Path]): df_list = [] for i", "create test Dataset from src.datamodules.datasets.archery_bowling_dataset import ArcheryBowlingDataset test_df = ArcheryBowlingDataModule.load_dataframe_from_multiple_files(test_files) computed_batch_size = self.batch_size", "self.label_col = label_col if label_col is not None else 'ParticipantID' self.sorting_cols = sorting_cols", "computed_batch_size, name='TEST', feature_cols=self.features, identifier_col=self.identifier_col, label_col=self.label_col, shuffle_windows=False, sorting_cols=self.sorting_cols ) self.logger.info('test Data initialized!') self.logger.info(f'Datasets are", "self.szenario = szenario self.features = features self.identifier_col = identifier_col if identifier_col is not", "name='TRAIN', feature_cols=self.features, identifier_col=self.identifier_col, label_col=self.label_col, shuffle_windows=self.shuffle_windows, sorting_cols=self.sorting_cols ) del train_df else: from src.datamodules.datasets.archery_bowling_dataset import", "validation # keep the remaining as train # drop unused columns # initiate", "import pytorch_lightning as pl from torchvision.transforms import transforms from src.utils.utils import get_logger class", "None if not self.val_dataset else str(self.val_dataset), 'test dataset': None if not self.test_dataset else", "= self.get_file_list(session=2) test_files = (list(test_files)) self.logger.info(f'found {len(test_files)} test-files.') # create test Dataset from", "def get_file_list(self, session=1): train_val_files = self.data_root.glob(f'{self.szenario}*{self.normalisation}*session{session}*.csv') return train_val_files @staticmethod def load_dataframe_from_multiple_files(file_list: List[Path]): df_list", "ArcheryBowlingDataset self.val_dataset = ArcheryBowlingDataset.create_from_dataframe(val_df, self.window_size, self.batch_size, name='VAL', feature_cols=self.features, identifier_col=self.identifier_col, label_col=self.label_col, shuffle_windows=self.shuffle_windows, sorting_cols=self.sorting_cols )", "10, normalisation: str = 'WithoutNormalization', szenario: str = 'Archery', features: List[str] = ['CenterEyeAnchor_pos_X',", "do i want to load all data at once, and slice afterwords? #", "regexing or sorting the file path seems to be a pain. therefore ill", "and slice afterwords? # slice all modulo matching repetitions to validation # keep", "was set, ' f'but would result in either all or no data being", "= self.batch_size rest = len(test_df) % self.batch_size computed_batch_size -= rest self.test_dataset = ArcheryBowlingDataset.create_from_dataframe(test_df,", "drop unused columns # initiate DatasetObjects and return them # return ArcheryBowlingDataset(None, 1,", "more convenient self.transform = transforms.Compose([ transforms.ToTensor(), ]) self.shuffle_windows = shuffle_windows self.num_features = len(features)", "/ self.val_ratio) if modulo > 12 or modulo < 2: self.logger.info( f'validation split", "f\"normalisation_name={self.normalisation!r}), \" \\ f\"Szenario={self.szenario})\" def __rich_repr__(self): yield \"train_dataset\", self.train_dataset yield \"val_dataset\", self.val_dataset yield", "everything with session 2 self.logger.info(f'stage:{stage}. creating Dataset...') test_files = self.get_file_list(session=2) test_files = (list(test_files))", "from src.datamodules.datasets.archery_bowling_dataset import ArcheryBowlingDataset self.train_dataset = ArcheryBowlingDataset.create_from_dataframe(train_val_df, self.window_size, self.batch_size, name='TRAIN', feature_cols=self.features, identifier_col=self.identifier_col, label_col=self.label_col,", "afterwords? # slice all modulo matching repetitions to validation # keep the remaining", "= (list(test_files)) self.logger.info(f'found {len(test_files)} test-files.') # create test Dataset from src.datamodules.datasets.archery_bowling_dataset import ArcheryBowlingDataset", "columns # initiate DatasetObjects and return them # return ArcheryBowlingDataset(None, 1, 1), ArcheryBowlingDataset(None,", "['CenterEyeAnchor_pos_X', 'LeftVirtualHand_pos_X', 'RightVirtualHand_pos_X'], identifier_col: str = 'seq_id', label_col: str = 'ParticipantID', sorting_cols: List[str]", "relevant (normalized + session1) train_val_files = self.get_file_list(session=1) train_val_files = list(train_val_files) self.logger.info(f'found {len(train_val_files)} files.')", "creating Dataset...') test_files = self.get_file_list(session=2) test_files = (list(test_files)) self.logger.info(f'found {len(test_files)} test-files.') # create", "as train-set!') from src.datamodules.datasets.archery_bowling_dataset import ArcheryBowlingDataset self.train_dataset = ArcheryBowlingDataset.create_from_dataframe(train_val_df, self.window_size, self.batch_size, name='TRAIN', feature_cols=self.features,", "len(features) self.dims = (self.window_size, self.num_features) self.train_dataset, self.val_dataset, self.test_dataset = None, None, None self.logger.info('__init__", "entries for test data # create a list of paths for test data", "session 2 self.logger.info(f'stage:{stage}. creating Dataset...') test_files = self.get_file_list(session=2) test_files = (list(test_files)) self.logger.info(f'found {len(test_files)}", "Union[DataLoader, List[DataLoader]]: return DataLoader(self.val_dataset, batch_size=None, num_workers=self.num_workers ) def test_dataloader(self) -> Union[DataLoader, List[DataLoader]]: #", "files (basically everything with session 2 self.logger.info(f'stage:{stage}. creating Dataset...') test_files = self.get_file_list(session=2) test_files", "just more convenient self.transform = transforms.Compose([ transforms.ToTensor(), ]) self.shuffle_windows = shuffle_windows self.num_features =", "window_size: int = 10, normalisation: str = 'WithoutNormalization', szenario: str = 'Archery', features:", "self.val_dataset yield \"test_dataset\", self.test_dataset yield \"dims\", self.dims yield \"normalisation_name\", self.normalisation yield \"szenario\", self.szenario", "from src.datamodules.datasets.archery_bowling_dataset import ArcheryBowlingDataset test_df = ArcheryBowlingDataModule.load_dataframe_from_multiple_files(test_files) computed_batch_size = self.batch_size rest = len(test_df)", "the remaining as train # drop unused columns # initiate DatasetObjects and return", "\\ f\"normalisation_name={self.normalisation!r}), \" \\ f\"Szenario={self.szenario})\" def __rich_repr__(self): yield \"train_dataset\", self.train_dataset yield \"val_dataset\", self.val_dataset", "computed_batch_size -= rest self.test_dataset = ArcheryBowlingDataset.create_from_dataframe(test_df, self.window_size, computed_batch_size, name='TEST', feature_cols=self.features, identifier_col=self.identifier_col, label_col=self.label_col, shuffle_windows=False,", "szenario: str = 'Archery', features: List[str] = ['CenterEyeAnchor_pos_X', 'LeftVirtualHand_pos_X', 'RightVirtualHand_pos_X'], identifier_col: str =", "self.logger = get_logger(name='A-B-DataModule') self.szenario = szenario self.features = features self.identifier_col = identifier_col if", "self.window_size, self.batch_size, name='TRAIN', feature_cols=self.features, identifier_col=self.identifier_col, label_col=self.label_col, shuffle_windows=self.shuffle_windows, sorting_cols=self.sorting_cols ) self.val_dataset = None self.logger.info('train/val", "str(self.test_dataset), 'dims': self.dims, '#batches': len(self.test_dataset), 'window size': self.window_size, 'batch size': self.batch_size, 'normalisation name':", "int = 1, shuffle_windows=False ): super(ArcheryBowlingDataModule, self).__init__() self.num_workers = num_workers self.logger = get_logger(name='A-B-DataModule')", "\" \\ f\"dims={self.dims!r}, \" \\ f\"normalisation_name={self.normalisation!r}), \" \\ f\"Szenario={self.szenario})\" def __rich_repr__(self): yield \"train_dataset\",", "return train_val_files @staticmethod def load_dataframe_from_multiple_files(file_list: List[Path]): df_list = [] for i in file_list:", "int(1 / self.val_ratio) if modulo > 12 or modulo < 2: self.logger.info( f'validation", "str = 'seq_id', label_col: str = 'ParticipantID', sorting_cols: List[str] = None, num_workers: int", "= Path(data_root) # Path is just more convenient self.transform = transforms.Compose([ transforms.ToTensor(), ])", "test self.data_root = Path(data_root) # Path is just more convenient self.transform = transforms.Compose([", "get_file_list(self, session=1): train_val_files = self.data_root.glob(f'{self.szenario}*{self.normalisation}*session{session}*.csv') return train_val_files @staticmethod def load_dataframe_from_multiple_files(file_list: List[Path]): df_list =", ") del val_df train_df = train_val_df[train_val_df['repetition'] % modulo != 0] del train_val_df self.train_dataset", "sorting_cols=self.sorting_cols ) self.val_dataset = None self.logger.info('train/val Data initialized!') if stage in (None, 'test'):", "pain. therefore ill load all relevant (normalized + session1) train_val_files = self.get_file_list(session=1) train_val_files", "= 'WithoutNormalization', szenario: str = 'Archery', features: List[str] = ['CenterEyeAnchor_pos_X', 'LeftVirtualHand_pos_X', 'RightVirtualHand_pos_X'], identifier_col:", "# slice all modulo matching repetitions to validation # keep the remaining as", "= ArcheryBowlingDataset.create_from_dataframe(train_val_df, self.window_size, self.batch_size, name='TRAIN', feature_cols=self.features, identifier_col=self.identifier_col, label_col=self.label_col, shuffle_windows=self.shuffle_windows, sorting_cols=self.sorting_cols ) self.val_dataset =", "False, val_ratio: float = None, batch_size: int = 1, window_size: int = 10,", "unused columns # initiate DatasetObjects and return them # return ArcheryBowlingDataset(None, 1, 1),", "torch.utils.data import DataLoader import pytorch_lightning as pl from torchvision.transforms import transforms from src.utils.utils", "result in either all or no data being available for training. ' f'Therefore", "\" \\ f\"normalisation_name={self.normalisation!r}), \" \\ f\"Szenario={self.szenario})\" def __rich_repr__(self): yield \"train_dataset\", self.train_dataset yield \"val_dataset\",", "split ratio({self.val_ratio}) was set, ' f'but would result in either all or no", "if stage in (None, 'fit'): # TODO no validation set throws a Nonetype", "= 'Archery', features: List[str] = ['CenterEyeAnchor_pos_X', 'LeftVirtualHand_pos_X', 'RightVirtualHand_pos_X'], identifier_col: str = 'seq_id', label_col:", "train # drop unused columns # initiate DatasetObjects and return them # return", "self.logger.info(f'found {len(train_val_files)} files.') train_val_df = ArcheryBowlingDataModule.load_dataframe_from_multiple_files(train_val_files) # TODO refactor this ifelse structure to", "pd.read_csv(i) df_list.append(tmp) return pd.concat(df_list, ignore_index=True) def _create_info_dict(self): return { 'train dataset': None if", "= [] for i in file_list: tmp = pd.read_csv(i) df_list.append(tmp) return pd.concat(df_list, ignore_index=True)", "self.get_file_list(session=1) train_val_files = list(train_val_files) self.logger.info(f'found {len(train_val_files)} files.') train_val_df = ArcheryBowlingDataModule.load_dataframe_from_multiple_files(train_val_files) # TODO refactor", "if not self.val_dataset else str(self.val_dataset), 'test dataset': None if not self.test_dataset else str(self.test_dataset),", "DataLoader(self.test_dataset, batch_size=None, num_workers=self.num_workers ) def __repr__(self): return f\"DataModule(train_dataset={self.train_dataset!r}, \" \\ f\"val_dataset={self.val_dataset!r}, \" \\", "modulo = int(1 / self.val_ratio) if modulo > 12 or modulo < 2:", "= None, None, None self.logger.info('__init__ done.') def setup(self, stage: Optional[str] = None) ->", "# TODO refactor this ifelse structure to a neat structure if self.val_ratio and", "szenario self.features = features self.identifier_col = identifier_col if identifier_col is not None else", "import Union, List, Dict, Optional import pandas as pd from torch.utils.data import DataLoader", "'WithoutNormalization', szenario: str = 'Archery', features: List[str] = ['CenterEyeAnchor_pos_X', 'LeftVirtualHand_pos_X', 'RightVirtualHand_pos_X'], identifier_col: str", "self.logger.info('__init__ done.') def setup(self, stage: Optional[str] = None) -> None: # do i", "sorting_cols self.normalisation = normalisation self.window_size = window_size self.batch_size = batch_size self.val_ratio = val_ratio", "data_root: str, test: bool = False, val_ratio: float = None, batch_size: int =", "identifier_col=self.identifier_col, label_col=self.label_col, shuffle_windows=self.shuffle_windows, sorting_cols=self.sorting_cols ) del val_df train_df = train_val_df[train_val_df['repetition'] % modulo !=", "self.logger.info(f'Datasets are setup.') self.logger.info(self) def get_file_list(self, session=1): train_val_files = self.data_root.glob(f'{self.szenario}*{self.normalisation}*session{session}*.csv') return train_val_files @staticmethod", "DataLoader(self.train_dataset, batch_size=None, num_workers=self.num_workers ) def val_dataloader(self) -> Union[DataLoader, List[DataLoader]]: return DataLoader(self.val_dataset, batch_size=None, num_workers=self.num_workers", "shuffle_windows=False, sorting_cols=self.sorting_cols ) self.logger.info('test Data initialized!') self.logger.info(f'Datasets are setup.') self.logger.info(self) def get_file_list(self, session=1):", "structure to a neat structure if self.val_ratio and self.val_ratio > 0: # not", "label_col=self.label_col, shuffle_windows=self.shuffle_windows, sorting_cols=self.sorting_cols ) self.val_dataset = None self.logger.info('train/val Data initialized!') if stage in", "if identifier_col is not None else 'seq_id' self.label_col = label_col if label_col is", "self.val_dataset else str(self.val_dataset), 'test dataset': None if not self.test_dataset else str(self.test_dataset), 'dims': self.dims,", "ArcheryBowlingDataset.create_from_dataframe(val_df, self.window_size, self.batch_size, name='VAL', feature_cols=self.features, identifier_col=self.identifier_col, label_col=self.label_col, shuffle_windows=self.shuffle_windows, sorting_cols=self.sorting_cols ) del val_df train_df", "session1) train_val_files = self.get_file_list(session=1) train_val_files = list(train_val_files) self.logger.info(f'found {len(train_val_files)} files.') train_val_df = ArcheryBowlingDataModule.load_dataframe_from_multiple_files(train_val_files)", "window_size self.batch_size = batch_size self.val_ratio = val_ratio self.separate = test self.data_root = Path(data_root)", "validation set throws a Nonetype Error on val data loader... self.logger.info(f'stage:{stage}. creating Dataset...')", "self.logger.info(f'stage:{stage}. creating Dataset...') # regexing or sorting the file path seems to be", "return { 'train dataset': None if not self.train_dataset else str(self.train_dataset), 'val dataset': None", "= ArcheryBowlingDataset.create_from_dataframe(train_val_df, self.window_size, self.batch_size, name='TRAIN', feature_cols=self.features, identifier_col=self.identifier_col, label_col=self.label_col, shuffle_windows=self.shuffle_windows, sorting_cols=self.sorting_cols ) else: val_df", "> 12 or modulo < 2: self.logger.info( f'validation split ratio({self.val_ratio}) was set, '", "'fit'): # TODO no validation set throws a Nonetype Error on val data", "# slice all 'session2' entries for test data # create a list of", "therefore ill load all relevant (normalized + session1) train_val_files = self.get_file_list(session=1) train_val_files =", "if label_col is not None else 'ParticipantID' self.sorting_cols = sorting_cols self.normalisation = normalisation", "def test_dataloader(self) -> Union[DataLoader, List[DataLoader]]: # TODO handle num_workers... return DataLoader(self.test_dataset, batch_size=None, num_workers=self.num_workers", "str = 'WithoutNormalization', szenario: str = 'Archery', features: List[str] = ['CenterEyeAnchor_pos_X', 'LeftVirtualHand_pos_X', 'RightVirtualHand_pos_X'],", "Path(data_root) # Path is just more convenient self.transform = transforms.Compose([ transforms.ToTensor(), ]) self.shuffle_windows", "self).__init__() self.num_workers = num_workers self.logger = get_logger(name='A-B-DataModule') self.szenario = szenario self.features = features", "tmp = pd.read_csv(i) df_list.append(tmp) return pd.concat(df_list, ignore_index=True) def _create_info_dict(self): return { 'train dataset':", "a Nonetype Error on val data loader... self.logger.info(f'stage:{stage}. creating Dataset...') # regexing or", "being available for training. ' f'Therefore all Data will be used as train-set!')", "Optional[str] = None) -> None: # do i want to load all data", "src.datamodules.datasets.archery_bowling_dataset import ArcheryBowlingDataset self.train_dataset = ArcheryBowlingDataset.create_from_dataframe(train_val_df, self.window_size, self.batch_size, name='TRAIN', feature_cols=self.features, identifier_col=self.identifier_col, label_col=self.label_col, shuffle_windows=self.shuffle_windows,", "List[Path]): df_list = [] for i in file_list: tmp = pd.read_csv(i) df_list.append(tmp) return", "session=1): train_val_files = self.data_root.glob(f'{self.szenario}*{self.normalisation}*session{session}*.csv') return train_val_files @staticmethod def load_dataframe_from_multiple_files(file_list: List[Path]): df_list = []", "batch_size=None, num_workers=self.num_workers ) def __repr__(self): return f\"DataModule(train_dataset={self.train_dataset!r}, \" \\ f\"val_dataset={self.val_dataset!r}, \" \\ f\"test_dataset={self.test_dataset!r},", "is not None else 'seq_id' self.label_col = label_col if label_col is not None", "None) -> None: # do i want to load all data at once,", "1, 1), ArcheryBowlingDataset(None, 1, 1) if stage in (None, 'fit'): # TODO no", "return f\"DataModule(train_dataset={self.train_dataset!r}, \" \\ f\"val_dataset={self.val_dataset!r}, \" \\ f\"test_dataset={self.test_dataset!r}, \" \\ f\"dims={self.dims!r}, \" \\", "label_col: str = 'ParticipantID', sorting_cols: List[str] = None, num_workers: int = 1, shuffle_windows=False", "name='TRAIN', feature_cols=self.features, identifier_col=self.identifier_col, label_col=self.label_col, shuffle_windows=self.shuffle_windows, sorting_cols=self.sorting_cols ) else: val_df = train_val_df[train_val_df['repetition'] % modulo", "_create_info_dict(self): return { 'train dataset': None if not self.train_dataset else str(self.train_dataset), 'val dataset':", "-= rest self.test_dataset = ArcheryBowlingDataset.create_from_dataframe(test_df, self.window_size, computed_batch_size, name='TEST', feature_cols=self.features, identifier_col=self.identifier_col, label_col=self.label_col, shuffle_windows=False, sorting_cols=self.sorting_cols", "ArcheryBowlingDataset.create_from_dataframe(train_val_df, self.window_size, self.batch_size, name='TRAIN', feature_cols=self.features, identifier_col=self.identifier_col, label_col=self.label_col, shuffle_windows=self.shuffle_windows, sorting_cols=self.sorting_cols ) else: val_df =", "of paths for test data files (basically everything with session 2 self.logger.info(f'stage:{stage}. creating", "ArcheryBowlingDataModule.load_dataframe_from_multiple_files(test_files) computed_batch_size = self.batch_size rest = len(test_df) % self.batch_size computed_batch_size -= rest self.test_dataset", "= len(test_df) % self.batch_size computed_batch_size -= rest self.test_dataset = ArcheryBowlingDataset.create_from_dataframe(test_df, self.window_size, computed_batch_size, name='TEST',", "del train_val_df self.train_dataset = ArcheryBowlingDataset.create_from_dataframe(train_df, self.window_size, self.batch_size, name='TRAIN', feature_cols=self.features, identifier_col=self.identifier_col, label_col=self.label_col, shuffle_windows=self.shuffle_windows, sorting_cols=self.sorting_cols", "train_val_files = self.data_root.glob(f'{self.szenario}*{self.normalisation}*session{session}*.csv') return train_val_files @staticmethod def load_dataframe_from_multiple_files(file_list: List[Path]): df_list = [] for", "pathlib import Path from typing import Union, List, Dict, Optional import pandas as", "'val dataset': None if not self.val_dataset else str(self.val_dataset), 'test dataset': None if not", "# create a list of paths for test data files (basically everything with", "slice afterwords? # slice all modulo matching repetitions to validation # keep the", "from pathlib import Path from typing import Union, List, Dict, Optional import pandas", "self.num_features) self.train_dataset, self.val_dataset, self.test_dataset = None, None, None self.logger.info('__init__ done.') def setup(self, stage:", "path seems to be a pain. therefore ill load all relevant (normalized +", "on val data loader... self.logger.info(f'stage:{stage}. creating Dataset...') # regexing or sorting the file", "src.utils.utils import get_logger class ArcheryBowlingDataModule(pl.LightningDataModule): def __init__(self, data_root: str, test: bool = False,", "ArcheryBowlingDataset test_df = ArcheryBowlingDataModule.load_dataframe_from_multiple_files(test_files) computed_batch_size = self.batch_size rest = len(test_df) % self.batch_size computed_batch_size", "pandas as pd from torch.utils.data import DataLoader import pytorch_lightning as pl from torchvision.transforms", "self.val_dataset = None self.logger.info('train/val Data initialized!') if stage in (None, 'test'): # slice", "List[DataLoader], Dict[str, DataLoader]]: return DataLoader(self.train_dataset, batch_size=None, num_workers=self.num_workers ) def val_dataloader(self) -> Union[DataLoader, List[DataLoader]]:", "ArcheryBowlingDataModule(pl.LightningDataModule): def __init__(self, data_root: str, test: bool = False, val_ratio: float = None,", "create a list of paths for test data files (basically everything with session", "self.val_dataset = ArcheryBowlingDataset.create_from_dataframe(val_df, self.window_size, self.batch_size, name='VAL', feature_cols=self.features, identifier_col=self.identifier_col, label_col=self.label_col, shuffle_windows=self.shuffle_windows, sorting_cols=self.sorting_cols ) del", "self.train_dataset = ArcheryBowlingDataset.create_from_dataframe(train_df, self.window_size, self.batch_size, name='TRAIN', feature_cols=self.features, identifier_col=self.identifier_col, label_col=self.label_col, shuffle_windows=self.shuffle_windows, sorting_cols=self.sorting_cols ) del", "handle num_workers... return DataLoader(self.test_dataset, batch_size=None, num_workers=self.num_workers ) def __repr__(self): return f\"DataModule(train_dataset={self.train_dataset!r}, \" \\", "setup(self, stage: Optional[str] = None) -> None: # do i want to load", "all Data will be used as train-set!') from src.datamodules.datasets.archery_bowling_dataset import ArcheryBowlingDataset self.train_dataset =", "(None, 'test'): # slice all 'session2' entries for test data # create a", "is not None else 'ParticipantID' self.sorting_cols = sorting_cols self.normalisation = normalisation self.window_size =", "# create test Dataset from src.datamodules.datasets.archery_bowling_dataset import ArcheryBowlingDataset test_df = ArcheryBowlingDataModule.load_dataframe_from_multiple_files(test_files) computed_batch_size =", "test: bool = False, val_ratio: float = None, batch_size: int = 1, window_size:", "# initiate DatasetObjects and return them # return ArcheryBowlingDataset(None, 1, 1), ArcheryBowlingDataset(None, 1,", "ArcheryBowlingDataset(None, 1, 1), ArcheryBowlingDataset(None, 1, 1), ArcheryBowlingDataset(None, 1, 1) if stage in (None,", "= train_val_df[train_val_df['repetition'] % modulo == 0] from src.datamodules.datasets.archery_bowling_dataset import ArcheryBowlingDataset self.val_dataset = ArcheryBowlingDataset.create_from_dataframe(val_df,", "self.dims, '#batches': len(self.test_dataset), 'window size': self.window_size, 'batch size': self.batch_size, 'normalisation name': self.normalisation }", "val_ratio self.separate = test self.data_root = Path(data_root) # Path is just more convenient", "test_files = self.get_file_list(session=2) test_files = (list(test_files)) self.logger.info(f'found {len(test_files)} test-files.') # create test Dataset", "neat structure if self.val_ratio and self.val_ratio > 0: # not none and >", "0] del train_val_df self.train_dataset = ArcheryBowlingDataset.create_from_dataframe(train_df, self.window_size, self.batch_size, name='TRAIN', feature_cols=self.features, identifier_col=self.identifier_col, label_col=self.label_col, shuffle_windows=self.shuffle_windows,", "'test'): # slice all 'session2' entries for test data # create a list", "for training. ' f'Therefore all Data will be used as train-set!') from src.datamodules.datasets.archery_bowling_dataset", "name='VAL', feature_cols=self.features, identifier_col=self.identifier_col, label_col=self.label_col, shuffle_windows=self.shuffle_windows, sorting_cols=self.sorting_cols ) del val_df train_df = train_val_df[train_val_df['repetition'] %", "val_dataloader(self) -> Union[DataLoader, List[DataLoader]]: return DataLoader(self.val_dataset, batch_size=None, num_workers=self.num_workers ) def test_dataloader(self) -> Union[DataLoader,", "% modulo == 0] from src.datamodules.datasets.archery_bowling_dataset import ArcheryBowlingDataset self.val_dataset = ArcheryBowlingDataset.create_from_dataframe(val_df, self.window_size, self.batch_size,", "df_list = [] for i in file_list: tmp = pd.read_csv(i) df_list.append(tmp) return pd.concat(df_list,", "ArcheryBowlingDataModule.load_dataframe_from_multiple_files(train_val_files) # TODO refactor this ifelse structure to a neat structure if self.val_ratio", "# drop unused columns # initiate DatasetObjects and return them # return ArcheryBowlingDataset(None,", "# TODO handle num_workers... return DataLoader(self.test_dataset, batch_size=None, num_workers=self.num_workers ) def __repr__(self): return f\"DataModule(train_dataset={self.train_dataset!r},", "in file_list: tmp = pd.read_csv(i) df_list.append(tmp) return pd.concat(df_list, ignore_index=True) def _create_info_dict(self): return {", "num_workers: int = 1, shuffle_windows=False ): super(ArcheryBowlingDataModule, self).__init__() self.num_workers = num_workers self.logger =", "computed_batch_size = self.batch_size rest = len(test_df) % self.batch_size computed_batch_size -= rest self.test_dataset =", "if self.val_ratio and self.val_ratio > 0: # not none and > 0 modulo", "(list(test_files)) self.logger.info(f'found {len(test_files)} test-files.') # create test Dataset from src.datamodules.datasets.archery_bowling_dataset import ArcheryBowlingDataset test_df", "None: # do i want to load all data at once, and slice", "if not self.test_dataset else str(self.test_dataset), 'dims': self.dims, '#batches': len(self.test_dataset), 'window size': self.window_size, 'batch", "' f'Therefore all Data will be used as train-set!') from src.datamodules.datasets.archery_bowling_dataset import ArcheryBowlingDataset", "shuffle_windows self.num_features = len(features) self.dims = (self.window_size, self.num_features) self.train_dataset, self.val_dataset, self.test_dataset = None,", "at once, and slice afterwords? # slice all modulo matching repetitions to validation", "label_col is not None else 'ParticipantID' self.sorting_cols = sorting_cols self.normalisation = normalisation self.window_size", "load all data at once, and slice afterwords? # slice all modulo matching", "is just more convenient self.transform = transforms.Compose([ transforms.ToTensor(), ]) self.shuffle_windows = shuffle_windows self.num_features", "ArcheryBowlingDataset.create_from_dataframe(test_df, self.window_size, computed_batch_size, name='TEST', feature_cols=self.features, identifier_col=self.identifier_col, label_col=self.label_col, shuffle_windows=False, sorting_cols=self.sorting_cols ) self.logger.info('test Data initialized!')", "them # return ArcheryBowlingDataset(None, 1, 1), ArcheryBowlingDataset(None, 1, 1), ArcheryBowlingDataset(None, 1, 1) if", "DataLoader import pytorch_lightning as pl from torchvision.transforms import transforms from src.utils.utils import get_logger", "a pain. therefore ill load all relevant (normalized + session1) train_val_files = self.get_file_list(session=1)", "not self.train_dataset else str(self.train_dataset), 'val dataset': None if not self.val_dataset else str(self.val_dataset), 'test", "yield \"train_dataset\", self.train_dataset yield \"val_dataset\", self.val_dataset yield \"test_dataset\", self.test_dataset yield \"dims\", self.dims yield", "if not self.train_dataset else str(self.train_dataset), 'val dataset': None if not self.val_dataset else str(self.val_dataset),", "# Path is just more convenient self.transform = transforms.Compose([ transforms.ToTensor(), ]) self.shuffle_windows =", "in (None, 'fit'): # TODO no validation set throws a Nonetype Error on", "self.batch_size rest = len(test_df) % self.batch_size computed_batch_size -= rest self.test_dataset = ArcheryBowlingDataset.create_from_dataframe(test_df, self.window_size,", "self.window_size, 'batch size': self.batch_size, 'normalisation name': self.normalisation } def train_dataloader(self) -> Union[DataLoader, List[DataLoader],", "sorting_cols=self.sorting_cols ) self.logger.info('test Data initialized!') self.logger.info(f'Datasets are setup.') self.logger.info(self) def get_file_list(self, session=1): train_val_files", "size': self.window_size, 'batch size': self.batch_size, 'normalisation name': self.normalisation } def train_dataloader(self) -> Union[DataLoader,", "\\ f\"dims={self.dims!r}, \" \\ f\"normalisation_name={self.normalisation!r}), \" \\ f\"Szenario={self.szenario})\" def __rich_repr__(self): yield \"train_dataset\", self.train_dataset", "self.logger.info( f'validation split ratio({self.val_ratio}) was set, ' f'but would result in either all", "def train_dataloader(self) -> Union[DataLoader, List[DataLoader], Dict[str, DataLoader]]: return DataLoader(self.train_dataset, batch_size=None, num_workers=self.num_workers ) def", "-> Union[DataLoader, List[DataLoader], Dict[str, DataLoader]]: return DataLoader(self.train_dataset, batch_size=None, num_workers=self.num_workers ) def val_dataloader(self) ->", "= 'ParticipantID', sorting_cols: List[str] = None, num_workers: int = 1, shuffle_windows=False ): super(ArcheryBowlingDataModule,", "self.features = features self.identifier_col = identifier_col if identifier_col is not None else 'seq_id'", "= sorting_cols self.normalisation = normalisation self.window_size = window_size self.batch_size = batch_size self.val_ratio =", "= (self.window_size, self.num_features) self.train_dataset, self.val_dataset, self.test_dataset = None, None, None self.logger.info('__init__ done.') def", "as pl from torchvision.transforms import transforms from src.utils.utils import get_logger class ArcheryBowlingDataModule(pl.LightningDataModule): def", "src.datamodules.datasets.archery_bowling_dataset import ArcheryBowlingDataset test_df = ArcheryBowlingDataModule.load_dataframe_from_multiple_files(test_files) computed_batch_size = self.batch_size rest = len(test_df) %", "label_col=self.label_col, shuffle_windows=self.shuffle_windows, sorting_cols=self.sorting_cols ) else: val_df = train_val_df[train_val_df['repetition'] % modulo == 0] from", "label_col=self.label_col, shuffle_windows=self.shuffle_windows, sorting_cols=self.sorting_cols ) del val_df train_df = train_val_df[train_val_df['repetition'] % modulo != 0]", "self.shuffle_windows = shuffle_windows self.num_features = len(features) self.dims = (self.window_size, self.num_features) self.train_dataset, self.val_dataset, self.test_dataset", "refactor this ifelse structure to a neat structure if self.val_ratio and self.val_ratio >", "= train_val_df[train_val_df['repetition'] % modulo != 0] del train_val_df self.train_dataset = ArcheryBowlingDataset.create_from_dataframe(train_df, self.window_size, self.batch_size,", "self.val_ratio = val_ratio self.separate = test self.data_root = Path(data_root) # Path is just", "pd from torch.utils.data import DataLoader import pytorch_lightning as pl from torchvision.transforms import transforms", "= normalisation self.window_size = window_size self.batch_size = batch_size self.val_ratio = val_ratio self.separate =", "1), ArcheryBowlingDataset(None, 1, 1), ArcheryBowlingDataset(None, 1, 1) if stage in (None, 'fit'): #", "__init__(self, data_root: str, test: bool = False, val_ratio: float = None, batch_size: int", "set throws a Nonetype Error on val data loader... self.logger.info(f'stage:{stage}. creating Dataset...') #", "either all or no data being available for training. ' f'Therefore all Data", "size': self.batch_size, 'normalisation name': self.normalisation } def train_dataloader(self) -> Union[DataLoader, List[DataLoader], Dict[str, DataLoader]]:" ]
[ "at finding model locally with error : {e}. Trying to use W&B.\") project", "W&B - path : str. The local path of the Pytorch Lightning experiment,", "not only_test: early_stopping = EarlyStopping('lr', verbose=True, mode='max', patience=1+config['train']['max_epochs'], divergence_threshold=config['train']['optim_args']['lr_stop']) checkpoint_callback = ModelCheckpoint(monitor=\"val_loss\", save_top_k=1,", "return None if config['train']['anew']: pl_model = get_pipeline(config) setup_metric(pl_model, config) else: pl_model = load_model(config,", "else: raise e print('Done.') if add_metric: setup_metric(pl_model, config, **add_metric_kwargs) return pl_model def get_trainer_config(config:", "run if need to be fetched on W&B - add_metric: bool. Adds an", "e print('Done.') if add_metric: setup_metric(pl_model, config, **add_metric_kwargs) return pl_model def get_trainer_config(config: dict, only_test=False)", "or that we are not in the zero_ranked experiment.\") else: if watch: logger.watch(model)", "= model if pl_model is None: pl_model = load_model(config, config['train']['start_model'], add_metric=False) trainer =", "= get_train_val_datasets(config) trainer.fit(pl_model, train_dataset, val_dataset) return trainer def test(config: dict, trainer=None, model=None, dataloaders=None,", "if config['observers']['observer']=='wandb': print(f\"Failed at finding model locally with error : {e}. Trying to", "get_trainer_config(config: dict, only_test=False) -> dict: trainer_config = config['train'] accelerator_config = utils.get_accelerator_dict(config['device']) trainer_config.update(accelerator_config) if", "= {'dataloaders': dataloaders, 'verbose':True } if trainer is None: pl_model = model if", "model from W&B - path : str. The local path of the Pytorch", "AttributeError as ae: return None else: raise NotImplementedError(f\"Observer {observer} not implemented.\") return logger", "watch=True, only_test=False) -> pl.Trainer: trainer_config = get_trainer_config(config, only_test=only_test) if config['observers']['use']: logger = get_observer(config)", "= get_trainer_config(config, only_test=only_test) if config['observers']['use']: logger = get_observer(config) if logger is None: print(\"Logger", "import GNN_Abstract_Base_Class from data import get_test_dataset, get_train_val_datasets from metrics import setup_metric import pytorch_lightning", "def train(config: dict)->pl.Trainer: if is_dummy(config['arch']['name']): print(\"Dummy architecture, can't train.\") return None if config['train']['anew']:", "if need to be fetched on W&B - add_metric: bool. Adds an external", "return clean_config def setup_trainer(config: dict, model: GNN_Abstract_Base_Class, watch=True, only_test=False) -> pl.Trainer: trainer_config =", "logger.experiment.config.update(config) except AttributeError as ae: return None else: raise NotImplementedError(f\"Observer {observer} not implemented.\")", "\"\"\" if is_dummy(config['arch']['name']): pl_model = get_pipeline(config) else: print(f'Loading base model from {path}... ',", "get_pl_model, get_torch_model, get_optim_args, is_dummy from models.base_model import GNN_Abstract_Base_Class from data import get_test_dataset, get_train_val_datasets", "to use W&B.\") project = f\"{config['project']}_{config['problem']}\" wb_config, path = wbh.download_model(project, path) PL_Model_Class =", "path: str, add_metric=True, **add_metric_kwargs) -> GNN_Abstract_Base_Class: \"\"\" - config : dict. The configuration", "load. Could mean an error or that we are not in the zero_ranked", "pytorch_lightning as pl from pytorch_lightning.loggers import WandbLogger from pytorch_lightning.callbacks import EarlyStopping, ModelCheckpoint import", "= [early_stopping, checkpoint_callback] clean_config = utils.restrict_dict_to_function(pl.Trainer.__init__, trainer_config) return clean_config def setup_trainer(config: dict, model:", "argparse.ArgumentParser(description='Main file for creating experiments.') parser.add_argument('command', metavar='c', choices=['train','test'], help='Command to execute : train", "model if pl_model is None: pl_model = load_model(config, config['train']['start_model'], add_metric=False) trainer = setup_trainer(config,", "str. The local path of the Pytorch Lightning experiment, or the id of", "local path of the Pytorch Lightning experiment, or the id of the run", "parser.parse_args() if args.command=='train': training=True default_test = False elif args.command=='test': training=False default_test=True config =", "correspond to the model trying to be loaded). If set to None, will", "load_model(config, config['train']['start_model'], add_metric=False) trainer = setup_trainer(config, pl_model, **kwargs) else: arg_dict['ckpt_path'] = 'best' pl_model", "import pytorch_lightning as pl from pytorch_lightning.loggers import WandbLogger from pytorch_lightning.callbacks import EarlyStopping, ModelCheckpoint", "trainer def train(config: dict)->pl.Trainer: if is_dummy(config['arch']['name']): print(\"Dummy architecture, can't train.\") return None if", "trainer = pl.Trainer(**trainer_config) return trainer def train(config: dict)->pl.Trainer: if is_dummy(config['arch']['name']): print(\"Dummy architecture, can't", "only_test=False) -> pl.Trainer: trainer_config = get_trainer_config(config, only_test=only_test) if config['observers']['use']: logger = get_observer(config) if", "else: print(f'Loading base model from {path}... ', end = \"\") try: PL_Model_Class =", "= f\"{config['project']}_{config['problem']}\" wb_config, path = wbh.download_model(project, path) PL_Model_Class = get_pl_model(config) pl_model = PL_Model_Class.load_from_checkpoint(path,", "None: print(\"Logger did not load. Could mean an error or that we are", "as f: config = yaml.safe_load(f) return config def get_observer(config: dict): path = config['observers']['base_dir']", "did not load. Could mean an error or that we are not in", "dict: with open(filename, 'r') as f: config = yaml.safe_load(f) return config def get_observer(config:", "**add_metric_kwargs) -> GNN_Abstract_Base_Class: \"\"\" - config : dict. The configuration dictionary (careful, must", "observer=='wandb': logger = WandbLogger(project=f\"{config['project']}_{config['problem']}\", log_model=\"all\", save_dir=path) try: logger.experiment.config.update(config) except AttributeError as ae: return", "= get_test_dataset(config) arg_dict = {'dataloaders': dataloaders, 'verbose':True } if trainer is None: pl_model", "dict, path: str, add_metric=True, **add_metric_kwargs) -> GNN_Abstract_Base_Class: \"\"\" - config : dict. The", "if config['train']['anew']: pl_model = get_pipeline(config) setup_metric(pl_model, config) else: pl_model = load_model(config, config['train']['start_model']) trainer", "experiment.\") else: if watch: logger.watch(model) trainer_config['logger'] = logger trainer = pl.Trainer(**trainer_config) return trainer", "file.') args = parser.parse_args() if args.command=='train': training=True default_test = False elif args.command=='test': training=False", "to the setup_metric function if activated. \"\"\" if is_dummy(config['arch']['name']): pl_model = get_pipeline(config) else:", "checkpoint_callback] clean_config = utils.restrict_dict_to_function(pl.Trainer.__init__, trainer_config) return clean_config def setup_trainer(config: dict, model: GNN_Abstract_Base_Class, watch=True,", "choices=['train','test'], help='Command to execute : train or test') parser.add_argument('--config', default='default_config.yaml', type=str, help='Name of", "is_dummy from models.base_model import GNN_Abstract_Base_Class from data import get_test_dataset, get_train_val_datasets from metrics import", "import get_pipeline, get_pl_model, get_torch_model, get_optim_args, is_dummy from models.base_model import GNN_Abstract_Base_Class from data import", "config['observers']['observer'] if observer=='wandb': logger = WandbLogger(project=f\"{config['project']}_{config['problem']}\", log_model=\"all\", save_dir=path) try: logger.experiment.config.update(config) except AttributeError as", "to download a model from W&B - path : str. The local path", "PL_Model_Class = get_pl_model(config) pl_model = PL_Model_Class.load_from_checkpoint(path, model=get_torch_model(wb_config), optim_args=get_optim_args(wb_config)) else: raise e print('Done.') if", "pl_model = get_pipeline(config) else: print(f'Loading base model from {path}... ', end = \"\")", "W&B - add_metric: bool. Adds an external metric to the pytorch lightninh module.", "def setup_trainer(config: dict, model: GNN_Abstract_Base_Class, watch=True, only_test=False) -> pl.Trainer: trainer_config = get_trainer_config(config, only_test=only_test)", "of the run if need to be fetched on W&B - add_metric: bool.", "pl from pytorch_lightning.loggers import WandbLogger from pytorch_lightning.callbacks import EarlyStopping, ModelCheckpoint import argparse import", "if config['observers']['use']: logger = get_observer(config) if logger is None: print(\"Logger did not load.", "import os from models import get_pipeline, get_pl_model, get_torch_model, get_optim_args, is_dummy from models.base_model import", "get_pipeline(config) else: print(f'Loading base model from {path}... ', end = \"\") try: PL_Model_Class", "trainer = train(config) if default_test or config['test_enabled']: test(config, trainer) if __name__==\"__main__\": pl.seed_everything(3787, workers=True)", "load_model(config: dict, path: str, add_metric=True, **add_metric_kwargs) -> GNN_Abstract_Base_Class: \"\"\" - config : dict.", "= get_pl_model(config) pl_model = PL_Model_Class.load_from_checkpoint(path, model=get_torch_model(wb_config), optim_args=get_optim_args(wb_config)) else: raise e print('Done.') if add_metric:", "download a model from W&B - path : str. The local path of", "if pl_model is None: pl_model = load_model(config, config['train']['start_model'], add_metric=False) trainer = setup_trainer(config, pl_model,", "training=True default_test = False elif args.command=='test': training=False default_test=True config = get_config(args.config) config =", "the id of the run if need to be fetched on W&B -", "arg_dict['model'] = pl_model trainer.test(**arg_dict) return trainer def main(): parser = argparse.ArgumentParser(description='Main file for", "= get_pipeline(config) else: print(f'Loading base model from {path}... ', end = \"\") try:", ": dict. The configuration dictionary (careful, must correspond to the model trying to", "verbose=True, mode='max', patience=1+config['train']['max_epochs'], divergence_threshold=config['train']['optim_args']['lr_stop']) checkpoint_callback = ModelCheckpoint(monitor=\"val_loss\", save_top_k=1, verbose=True) trainer_config['callbacks'] = [early_stopping, checkpoint_callback]", "setup_trainer(config, pl_model) train_dataset, val_dataset = get_train_val_datasets(config) trainer.fit(pl_model, train_dataset, val_dataset) return trainer def test(config:", "= utils.clean_config(config) trainer=None if training: trainer = train(config) if default_test or config['test_enabled']: test(config,", "get_pipeline, get_pl_model, get_torch_model, get_optim_args, is_dummy from models.base_model import GNN_Abstract_Base_Class from data import get_test_dataset,", "are not in the zero_ranked experiment.\") else: if watch: logger.watch(model) trainer_config['logger'] = logger", "model: GNN_Abstract_Base_Class, watch=True, only_test=False) -> pl.Trainer: trainer_config = get_trainer_config(config, only_test=only_test) if config['observers']['use']: logger", "return pl_model def get_trainer_config(config: dict, only_test=False) -> dict: trainer_config = config['train'] accelerator_config =", "print(f\"Failed at finding model locally with error : {e}. Trying to use W&B.\")", "if is_dummy(config['arch']['name']): pl_model = get_pipeline(config) else: print(f'Loading base model from {path}... ', end", "logger = get_observer(config) if logger is None: print(\"Logger did not load. Could mean", "= load_model(config, config['train']['start_model'], add_metric=False) trainer = setup_trainer(config, pl_model, **kwargs) else: arg_dict['ckpt_path'] = 'best'", "= config['observers']['observer'] if observer=='wandb': logger = WandbLogger(project=f\"{config['project']}_{config['problem']}\", log_model=\"all\", save_dir=path) try: logger.experiment.config.update(config) except AttributeError", "try: logger.experiment.config.update(config) except AttributeError as ae: return None else: raise NotImplementedError(f\"Observer {observer} not", "logger def load_model(config: dict, path: str, add_metric=True, **add_metric_kwargs) -> GNN_Abstract_Base_Class: \"\"\" - config", "{observer} not implemented.\") return logger def load_model(config: dict, path: str, add_metric=True, **add_metric_kwargs) ->", "from models.base_model import GNN_Abstract_Base_Class from data import get_test_dataset, get_train_val_datasets from metrics import setup_metric", "error or that we are not in the zero_ranked experiment.\") else: if watch:", "import yaml import toolbox.utils as utils import os from models import get_pipeline, get_pl_model,", "path = config['observers']['base_dir'] path = os.path.join(os.getcwd(), path) utils.check_dir(path) observer = config['observers']['observer'] if observer=='wandb':", "the configuration file.') args = parser.parse_args() if args.command=='train': training=True default_test = False elif", "for creating experiments.') parser.add_argument('command', metavar='c', choices=['train','test'], help='Command to execute : train or test')", "add_metric_kwargs: Arguments passed to the setup_metric function if activated. \"\"\" if is_dummy(config['arch']['name']): pl_model", "= ModelCheckpoint(monitor=\"val_loss\", save_top_k=1, verbose=True) trainer_config['callbacks'] = [early_stopping, checkpoint_callback] clean_config = utils.restrict_dict_to_function(pl.Trainer.__init__, trainer_config) return", "return trainer def main(): parser = argparse.ArgumentParser(description='Main file for creating experiments.') parser.add_argument('command', metavar='c',", "trainer=None, model=None, dataloaders=None, **kwargs) -> None: if dataloaders is None: dataloaders = get_test_dataset(config)", "is_dummy(config['arch']['name']): print(\"Dummy architecture, can't train.\") return None if config['train']['anew']: pl_model = get_pipeline(config) setup_metric(pl_model,", "base model from {path}... ', end = \"\") try: PL_Model_Class = get_pl_model(config) pl_model", "add_metric=False) trainer = setup_trainer(config, pl_model, **kwargs) else: arg_dict['ckpt_path'] = 'best' pl_model = trainer.model", "get_config(args.config) config = utils.clean_config(config) trainer=None if training: trainer = train(config) if default_test or", "yaml import toolbox.utils as utils import os from models import get_pipeline, get_pl_model, get_torch_model,", "PL_Model_Class = get_pl_model(config) pl_model = PL_Model_Class.load_from_checkpoint(path, model=get_torch_model(config), optim_args=get_optim_args(config)) except (FileNotFoundError) as e: if", "pl_model, **kwargs) else: arg_dict['ckpt_path'] = 'best' pl_model = trainer.model setup_metric(pl_model, config, istest=True) arg_dict['model']", "pl_model def get_trainer_config(config: dict, only_test=False) -> dict: trainer_config = config['train'] accelerator_config = utils.get_accelerator_dict(config['device'])", "[early_stopping, checkpoint_callback] clean_config = utils.restrict_dict_to_function(pl.Trainer.__init__, trainer_config) return clean_config def setup_trainer(config: dict, model: GNN_Abstract_Base_Class,", "os from models import get_pipeline, get_pl_model, get_torch_model, get_optim_args, is_dummy from models.base_model import GNN_Abstract_Base_Class", "The local path of the Pytorch Lightning experiment, or the id of the", "If set to None, will try to download a model from W&B -", "trainer.model setup_metric(pl_model, config, istest=True) arg_dict['model'] = pl_model trainer.test(**arg_dict) return trainer def main(): parser", "pytorch_lightning.callbacks import EarlyStopping, ModelCheckpoint import argparse import toolbox.wandb_helper as wbh def get_config(filename='default_config.yaml') ->", "setup_metric(pl_model, config, istest=True) arg_dict['model'] = pl_model trainer.test(**arg_dict) return trainer def main(): parser =", "models import get_pipeline, get_pl_model, get_torch_model, get_optim_args, is_dummy from models.base_model import GNN_Abstract_Base_Class from data", "to be fetched on W&B - add_metric: bool. Adds an external metric to", "return trainer def test(config: dict, trainer=None, model=None, dataloaders=None, **kwargs) -> None: if dataloaders", "print(\"Dummy architecture, can't train.\") return None if config['train']['anew']: pl_model = get_pipeline(config) setup_metric(pl_model, config)", "is None: pl_model = model if pl_model is None: pl_model = load_model(config, config['train']['start_model'],", "train_dataset, val_dataset) return trainer def test(config: dict, trainer=None, model=None, dataloaders=None, **kwargs) -> None:", "= pl_model trainer.test(**arg_dict) return trainer def main(): parser = argparse.ArgumentParser(description='Main file for creating", "the run if need to be fetched on W&B - add_metric: bool. Adds", "add_metric=True, **add_metric_kwargs) -> GNN_Abstract_Base_Class: \"\"\" - config : dict. The configuration dictionary (careful,", "def get_trainer_config(config: dict, only_test=False) -> dict: trainer_config = config['train'] accelerator_config = utils.get_accelerator_dict(config['device']) trainer_config.update(accelerator_config)", "args = parser.parse_args() if args.command=='train': training=True default_test = False elif args.command=='test': training=False default_test=True", "try: PL_Model_Class = get_pl_model(config) pl_model = PL_Model_Class.load_from_checkpoint(path, model=get_torch_model(config), optim_args=get_optim_args(config)) except (FileNotFoundError) as e:", "to be loaded). If set to None, will try to download a model", "experiment, or the id of the run if need to be fetched on", "GNN_Abstract_Base_Class from data import get_test_dataset, get_train_val_datasets from metrics import setup_metric import pytorch_lightning as", "dict. The configuration dictionary (careful, must correspond to the model trying to be", "the setup_metric function if activated. \"\"\" if is_dummy(config['arch']['name']): pl_model = get_pipeline(config) else: print(f'Loading", ": {e}. Trying to use W&B.\") project = f\"{config['project']}_{config['problem']}\" wb_config, path = wbh.download_model(project,", "print(\"Logger did not load. Could mean an error or that we are not", "model=get_torch_model(wb_config), optim_args=get_optim_args(wb_config)) else: raise e print('Done.') if add_metric: setup_metric(pl_model, config, **add_metric_kwargs) return pl_model", "from pytorch_lightning.loggers import WandbLogger from pytorch_lightning.callbacks import EarlyStopping, ModelCheckpoint import argparse import toolbox.wandb_helper", "utils import os from models import get_pipeline, get_pl_model, get_torch_model, get_optim_args, is_dummy from models.base_model", "pl_model = load_model(config, config['train']['start_model'], add_metric=False) trainer = setup_trainer(config, pl_model, **kwargs) else: arg_dict['ckpt_path'] =", "\"\"\" - config : dict. The configuration dictionary (careful, must correspond to the", "to None, will try to download a model from W&B - path :", "trainer.fit(pl_model, train_dataset, val_dataset) return trainer def test(config: dict, trainer=None, model=None, dataloaders=None, **kwargs) ->", "istest=True) arg_dict['model'] = pl_model trainer.test(**arg_dict) return trainer def main(): parser = argparse.ArgumentParser(description='Main file", "add_metric: setup_metric(pl_model, config, **add_metric_kwargs) return pl_model def get_trainer_config(config: dict, only_test=False) -> dict: trainer_config", "function if activated. \"\"\" if is_dummy(config['arch']['name']): pl_model = get_pipeline(config) else: print(f'Loading base model", "val_dataset = get_train_val_datasets(config) trainer.fit(pl_model, train_dataset, val_dataset) return trainer def test(config: dict, trainer=None, model=None,", "be fetched on W&B - add_metric: bool. Adds an external metric to the", "= setup_trainer(config, pl_model) train_dataset, val_dataset = get_train_val_datasets(config) trainer.fit(pl_model, train_dataset, val_dataset) return trainer def", "on W&B - add_metric: bool. Adds an external metric to the pytorch lightninh", "end = \"\") try: PL_Model_Class = get_pl_model(config) pl_model = PL_Model_Class.load_from_checkpoint(path, model=get_torch_model(config), optim_args=get_optim_args(config)) except", "trainer def test(config: dict, trainer=None, model=None, dataloaders=None, **kwargs) -> None: if dataloaders is", "print(f'Loading base model from {path}... ', end = \"\") try: PL_Model_Class = get_pl_model(config)", "= get_pl_model(config) pl_model = PL_Model_Class.load_from_checkpoint(path, model=get_torch_model(config), optim_args=get_optim_args(config)) except (FileNotFoundError) as e: if config['observers']['observer']=='wandb':", "accelerator_config = utils.get_accelerator_dict(config['device']) trainer_config.update(accelerator_config) if not only_test: early_stopping = EarlyStopping('lr', verbose=True, mode='max', patience=1+config['train']['max_epochs'],", "get_optim_args, is_dummy from models.base_model import GNN_Abstract_Base_Class from data import get_test_dataset, get_train_val_datasets from metrics", "dataloaders=None, **kwargs) -> None: if dataloaders is None: dataloaders = get_test_dataset(config) arg_dict =", "return config def get_observer(config: dict): path = config['observers']['base_dir'] path = os.path.join(os.getcwd(), path) utils.check_dir(path)", "to execute : train or test') parser.add_argument('--config', default='default_config.yaml', type=str, help='Name of the configuration", "a model from W&B - path : str. The local path of the", "an error or that we are not in the zero_ranked experiment.\") else: if", "import argparse import toolbox.wandb_helper as wbh def get_config(filename='default_config.yaml') -> dict: with open(filename, 'r')", "experiments.') parser.add_argument('command', metavar='c', choices=['train','test'], help='Command to execute : train or test') parser.add_argument('--config', default='default_config.yaml',", "f: config = yaml.safe_load(f) return config def get_observer(config: dict): path = config['observers']['base_dir'] path", "'r') as f: config = yaml.safe_load(f) return config def get_observer(config: dict): path =", "Could mean an error or that we are not in the zero_ranked experiment.\")", "os.path.join(os.getcwd(), path) utils.check_dir(path) observer = config['observers']['observer'] if observer=='wandb': logger = WandbLogger(project=f\"{config['project']}_{config['problem']}\", log_model=\"all\", save_dir=path)", "try to download a model from W&B - path : str. The local", "def test(config: dict, trainer=None, model=None, dataloaders=None, **kwargs) -> None: if dataloaders is None:", "path = wbh.download_model(project, path) PL_Model_Class = get_pl_model(config) pl_model = PL_Model_Class.load_from_checkpoint(path, model=get_torch_model(wb_config), optim_args=get_optim_args(wb_config)) else:", "the zero_ranked experiment.\") else: if watch: logger.watch(model) trainer_config['logger'] = logger trainer = pl.Trainer(**trainer_config)", "mean an error or that we are not in the zero_ranked experiment.\") else:", "error : {e}. Trying to use W&B.\") project = f\"{config['project']}_{config['problem']}\" wb_config, path =", "early_stopping = EarlyStopping('lr', verbose=True, mode='max', patience=1+config['train']['max_epochs'], divergence_threshold=config['train']['optim_args']['lr_stop']) checkpoint_callback = ModelCheckpoint(monitor=\"val_loss\", save_top_k=1, verbose=True) trainer_config['callbacks']", "with open(filename, 'r') as f: config = yaml.safe_load(f) return config def get_observer(config: dict):", "if logger is None: print(\"Logger did not load. Could mean an error or", "utils.check_dir(path) observer = config['observers']['observer'] if observer=='wandb': logger = WandbLogger(project=f\"{config['project']}_{config['problem']}\", log_model=\"all\", save_dir=path) try: logger.experiment.config.update(config)", "pytorch_lightning.loggers import WandbLogger from pytorch_lightning.callbacks import EarlyStopping, ModelCheckpoint import argparse import toolbox.wandb_helper as", "utils.get_accelerator_dict(config['device']) trainer_config.update(accelerator_config) if not only_test: early_stopping = EarlyStopping('lr', verbose=True, mode='max', patience=1+config['train']['max_epochs'], divergence_threshold=config['train']['optim_args']['lr_stop']) checkpoint_callback", "trainer_config.update(accelerator_config) if not only_test: early_stopping = EarlyStopping('lr', verbose=True, mode='max', patience=1+config['train']['max_epochs'], divergence_threshold=config['train']['optim_args']['lr_stop']) checkpoint_callback =", "trainer def main(): parser = argparse.ArgumentParser(description='Main file for creating experiments.') parser.add_argument('command', metavar='c', choices=['train','test'],", "from data import get_test_dataset, get_train_val_datasets from metrics import setup_metric import pytorch_lightning as pl", "config['train']['start_model'], add_metric=False) trainer = setup_trainer(config, pl_model, **kwargs) else: arg_dict['ckpt_path'] = 'best' pl_model =", "dict)->pl.Trainer: if is_dummy(config['arch']['name']): print(\"Dummy architecture, can't train.\") return None if config['train']['anew']: pl_model =", "optim_args=get_optim_args(config)) except (FileNotFoundError) as e: if config['observers']['observer']=='wandb': print(f\"Failed at finding model locally with", "(FileNotFoundError) as e: if config['observers']['observer']=='wandb': print(f\"Failed at finding model locally with error :", "config = get_config(args.config) config = utils.clean_config(config) trainer=None if training: trainer = train(config) if", "config['observers']['use']: logger = get_observer(config) if logger is None: print(\"Logger did not load. Could", "activated. \"\"\" if is_dummy(config['arch']['name']): pl_model = get_pipeline(config) else: print(f'Loading base model from {path}...", "metrics import setup_metric import pytorch_lightning as pl from pytorch_lightning.loggers import WandbLogger from pytorch_lightning.callbacks", "file for creating experiments.') parser.add_argument('command', metavar='c', choices=['train','test'], help='Command to execute : train or", "arg_dict = {'dataloaders': dataloaders, 'verbose':True } if trainer is None: pl_model = model", "trainer_config['logger'] = logger trainer = pl.Trainer(**trainer_config) return trainer def train(config: dict)->pl.Trainer: if is_dummy(config['arch']['name']):", "= pl.Trainer(**trainer_config) return trainer def train(config: dict)->pl.Trainer: if is_dummy(config['arch']['name']): print(\"Dummy architecture, can't train.\")", "PL_Model_Class.load_from_checkpoint(path, model=get_torch_model(wb_config), optim_args=get_optim_args(wb_config)) else: raise e print('Done.') if add_metric: setup_metric(pl_model, config, **add_metric_kwargs) return", "except (FileNotFoundError) as e: if config['observers']['observer']=='wandb': print(f\"Failed at finding model locally with error", "PL_Model_Class.load_from_checkpoint(path, model=get_torch_model(config), optim_args=get_optim_args(config)) except (FileNotFoundError) as e: if config['observers']['observer']=='wandb': print(f\"Failed at finding model", "pytorch lightninh module. - add_metric_kwargs: Arguments passed to the setup_metric function if activated.", "train(config: dict)->pl.Trainer: if is_dummy(config['arch']['name']): print(\"Dummy architecture, can't train.\") return None if config['train']['anew']: pl_model", "trainer = setup_trainer(config, pl_model) train_dataset, val_dataset = get_train_val_datasets(config) trainer.fit(pl_model, train_dataset, val_dataset) return trainer", "loaded). If set to None, will try to download a model from W&B", "= load_model(config, config['train']['start_model']) trainer = setup_trainer(config, pl_model) train_dataset, val_dataset = get_train_val_datasets(config) trainer.fit(pl_model, train_dataset,", "need to be fetched on W&B - add_metric: bool. Adds an external metric", "elif args.command=='test': training=False default_test=True config = get_config(args.config) config = utils.clean_config(config) trainer=None if training:", "pl.Trainer: trainer_config = get_trainer_config(config, only_test=only_test) if config['observers']['use']: logger = get_observer(config) if logger is", "if is_dummy(config['arch']['name']): print(\"Dummy architecture, can't train.\") return None if config['train']['anew']: pl_model = get_pipeline(config)", "log_model=\"all\", save_dir=path) try: logger.experiment.config.update(config) except AttributeError as ae: return None else: raise NotImplementedError(f\"Observer", "the Pytorch Lightning experiment, or the id of the run if need to", "= 'best' pl_model = trainer.model setup_metric(pl_model, config, istest=True) arg_dict['model'] = pl_model trainer.test(**arg_dict) return", "not load. Could mean an error or that we are not in the", "get_torch_model, get_optim_args, is_dummy from models.base_model import GNN_Abstract_Base_Class from data import get_test_dataset, get_train_val_datasets from", "to the model trying to be loaded). If set to None, will try", "optim_args=get_optim_args(wb_config)) else: raise e print('Done.') if add_metric: setup_metric(pl_model, config, **add_metric_kwargs) return pl_model def", "Arguments passed to the setup_metric function if activated. \"\"\" if is_dummy(config['arch']['name']): pl_model =", "None: pl_model = model if pl_model is None: pl_model = load_model(config, config['train']['start_model'], add_metric=False)", "or test') parser.add_argument('--config', default='default_config.yaml', type=str, help='Name of the configuration file.') args = parser.parse_args()", "else: arg_dict['ckpt_path'] = 'best' pl_model = trainer.model setup_metric(pl_model, config, istest=True) arg_dict['model'] = pl_model", "print('Done.') if add_metric: setup_metric(pl_model, config, **add_metric_kwargs) return pl_model def get_trainer_config(config: dict, only_test=False) ->", "dict, model: GNN_Abstract_Base_Class, watch=True, only_test=False) -> pl.Trainer: trainer_config = get_trainer_config(config, only_test=only_test) if config['observers']['use']:", "parser.add_argument('--config', default='default_config.yaml', type=str, help='Name of the configuration file.') args = parser.parse_args() if args.command=='train':", "pl_model = get_pipeline(config) setup_metric(pl_model, config) else: pl_model = load_model(config, config['train']['start_model']) trainer = setup_trainer(config,", "= wbh.download_model(project, path) PL_Model_Class = get_pl_model(config) pl_model = PL_Model_Class.load_from_checkpoint(path, model=get_torch_model(wb_config), optim_args=get_optim_args(wb_config)) else: raise", "clean_config = utils.restrict_dict_to_function(pl.Trainer.__init__, trainer_config) return clean_config def setup_trainer(config: dict, model: GNN_Abstract_Base_Class, watch=True, only_test=False)", "external metric to the pytorch lightninh module. - add_metric_kwargs: Arguments passed to the", "of the Pytorch Lightning experiment, or the id of the run if need", "def main(): parser = argparse.ArgumentParser(description='Main file for creating experiments.') parser.add_argument('command', metavar='c', choices=['train','test'], help='Command", "-> dict: with open(filename, 'r') as f: config = yaml.safe_load(f) return config def", "= \"\") try: PL_Model_Class = get_pl_model(config) pl_model = PL_Model_Class.load_from_checkpoint(path, model=get_torch_model(config), optim_args=get_optim_args(config)) except (FileNotFoundError)", "trainer is None: pl_model = model if pl_model is None: pl_model = load_model(config,", "get_pl_model(config) pl_model = PL_Model_Class.load_from_checkpoint(path, model=get_torch_model(wb_config), optim_args=get_optim_args(wb_config)) else: raise e print('Done.') if add_metric: setup_metric(pl_model,", "if args.command=='train': training=True default_test = False elif args.command=='test': training=False default_test=True config = get_config(args.config)", "None else: raise NotImplementedError(f\"Observer {observer} not implemented.\") return logger def load_model(config: dict, path:", "(careful, must correspond to the model trying to be loaded). If set to", "setup_metric(pl_model, config, **add_metric_kwargs) return pl_model def get_trainer_config(config: dict, only_test=False) -> dict: trainer_config =", "setup_trainer(config, pl_model, **kwargs) else: arg_dict['ckpt_path'] = 'best' pl_model = trainer.model setup_metric(pl_model, config, istest=True)", "get_trainer_config(config, only_test=only_test) if config['observers']['use']: logger = get_observer(config) if logger is None: print(\"Logger did", "watch: logger.watch(model) trainer_config['logger'] = logger trainer = pl.Trainer(**trainer_config) return trainer def train(config: dict)->pl.Trainer:", "} if trainer is None: pl_model = model if pl_model is None: pl_model", "config, istest=True) arg_dict['model'] = pl_model trainer.test(**arg_dict) return trainer def main(): parser = argparse.ArgumentParser(description='Main", "test(config: dict, trainer=None, model=None, dataloaders=None, **kwargs) -> None: if dataloaders is None: dataloaders", "be loaded). If set to None, will try to download a model from", "save_dir=path) try: logger.experiment.config.update(config) except AttributeError as ae: return None else: raise NotImplementedError(f\"Observer {observer}", "= get_config(args.config) config = utils.clean_config(config) trainer=None if training: trainer = train(config) if default_test", "if not only_test: early_stopping = EarlyStopping('lr', verbose=True, mode='max', patience=1+config['train']['max_epochs'], divergence_threshold=config['train']['optim_args']['lr_stop']) checkpoint_callback = ModelCheckpoint(monitor=\"val_loss\",", "= get_observer(config) if logger is None: print(\"Logger did not load. Could mean an", "= trainer.model setup_metric(pl_model, config, istest=True) arg_dict['model'] = pl_model trainer.test(**arg_dict) return trainer def main():", "pl_model = load_model(config, config['train']['start_model']) trainer = setup_trainer(config, pl_model) train_dataset, val_dataset = get_train_val_datasets(config) trainer.fit(pl_model,", "model=get_torch_model(config), optim_args=get_optim_args(config)) except (FileNotFoundError) as e: if config['observers']['observer']=='wandb': print(f\"Failed at finding model locally", "patience=1+config['train']['max_epochs'], divergence_threshold=config['train']['optim_args']['lr_stop']) checkpoint_callback = ModelCheckpoint(monitor=\"val_loss\", save_top_k=1, verbose=True) trainer_config['callbacks'] = [early_stopping, checkpoint_callback] clean_config =", "= utils.restrict_dict_to_function(pl.Trainer.__init__, trainer_config) return clean_config def setup_trainer(config: dict, model: GNN_Abstract_Base_Class, watch=True, only_test=False) ->", "lightninh module. - add_metric_kwargs: Arguments passed to the setup_metric function if activated. \"\"\"", "def load_model(config: dict, path: str, add_metric=True, **add_metric_kwargs) -> GNN_Abstract_Base_Class: \"\"\" - config :", "= yaml.safe_load(f) return config def get_observer(config: dict): path = config['observers']['base_dir'] path = os.path.join(os.getcwd(),", "bool. Adds an external metric to the pytorch lightninh module. - add_metric_kwargs: Arguments", "trainer = setup_trainer(config, pl_model, **kwargs) else: arg_dict['ckpt_path'] = 'best' pl_model = trainer.model setup_metric(pl_model,", "model locally with error : {e}. Trying to use W&B.\") project = f\"{config['project']}_{config['problem']}\"", "is None: dataloaders = get_test_dataset(config) arg_dict = {'dataloaders': dataloaders, 'verbose':True } if trainer", "pl_model = model if pl_model is None: pl_model = load_model(config, config['train']['start_model'], add_metric=False) trainer", "config['train'] accelerator_config = utils.get_accelerator_dict(config['device']) trainer_config.update(accelerator_config) if not only_test: early_stopping = EarlyStopping('lr', verbose=True, mode='max',", "utils.clean_config(config) trainer=None if training: trainer = train(config) if default_test or config['test_enabled']: test(config, trainer)", "= logger trainer = pl.Trainer(**trainer_config) return trainer def train(config: dict)->pl.Trainer: if is_dummy(config['arch']['name']): print(\"Dummy", "import toolbox.utils as utils import os from models import get_pipeline, get_pl_model, get_torch_model, get_optim_args,", "if training: trainer = train(config) if default_test or config['test_enabled']: test(config, trainer) if __name__==\"__main__\":", "config['train']['anew']: pl_model = get_pipeline(config) setup_metric(pl_model, config) else: pl_model = load_model(config, config['train']['start_model']) trainer =", "args.command=='train': training=True default_test = False elif args.command=='test': training=False default_test=True config = get_config(args.config) config", "if trainer is None: pl_model = model if pl_model is None: pl_model =", "def get_observer(config: dict): path = config['observers']['base_dir'] path = os.path.join(os.getcwd(), path) utils.check_dir(path) observer =", "project = f\"{config['project']}_{config['problem']}\" wb_config, path = wbh.download_model(project, path) PL_Model_Class = get_pl_model(config) pl_model =", "wbh.download_model(project, path) PL_Model_Class = get_pl_model(config) pl_model = PL_Model_Class.load_from_checkpoint(path, model=get_torch_model(wb_config), optim_args=get_optim_args(wb_config)) else: raise e", "observer = config['observers']['observer'] if observer=='wandb': logger = WandbLogger(project=f\"{config['project']}_{config['problem']}\", log_model=\"all\", save_dir=path) try: logger.experiment.config.update(config) except", "f\"{config['project']}_{config['problem']}\" wb_config, path = wbh.download_model(project, path) PL_Model_Class = get_pl_model(config) pl_model = PL_Model_Class.load_from_checkpoint(path, model=get_torch_model(wb_config),", "models.base_model import GNN_Abstract_Base_Class from data import get_test_dataset, get_train_val_datasets from metrics import setup_metric import", "pl.Trainer(**trainer_config) return trainer def train(config: dict)->pl.Trainer: if is_dummy(config['arch']['name']): print(\"Dummy architecture, can't train.\") return", "is None: pl_model = load_model(config, config['train']['start_model'], add_metric=False) trainer = setup_trainer(config, pl_model, **kwargs) else:", "from pytorch_lightning.callbacks import EarlyStopping, ModelCheckpoint import argparse import toolbox.wandb_helper as wbh def get_config(filename='default_config.yaml')", "else: raise NotImplementedError(f\"Observer {observer} not implemented.\") return logger def load_model(config: dict, path: str,", "model from {path}... ', end = \"\") try: PL_Model_Class = get_pl_model(config) pl_model =", "False elif args.command=='test': training=False default_test=True config = get_config(args.config) config = utils.clean_config(config) trainer=None if", "parser = argparse.ArgumentParser(description='Main file for creating experiments.') parser.add_argument('command', metavar='c', choices=['train','test'], help='Command to execute", "GNN_Abstract_Base_Class: \"\"\" - config : dict. The configuration dictionary (careful, must correspond to", "wbh def get_config(filename='default_config.yaml') -> dict: with open(filename, 'r') as f: config = yaml.safe_load(f)", "None: dataloaders = get_test_dataset(config) arg_dict = {'dataloaders': dataloaders, 'verbose':True } if trainer is", "logger trainer = pl.Trainer(**trainer_config) return trainer def train(config: dict)->pl.Trainer: if is_dummy(config['arch']['name']): print(\"Dummy architecture,", "not in the zero_ranked experiment.\") else: if watch: logger.watch(model) trainer_config['logger'] = logger trainer", "if dataloaders is None: dataloaders = get_test_dataset(config) arg_dict = {'dataloaders': dataloaders, 'verbose':True }", "only_test=only_test) if config['observers']['use']: logger = get_observer(config) if logger is None: print(\"Logger did not", "verbose=True) trainer_config['callbacks'] = [early_stopping, checkpoint_callback] clean_config = utils.restrict_dict_to_function(pl.Trainer.__init__, trainer_config) return clean_config def setup_trainer(config:", "train.\") return None if config['train']['anew']: pl_model = get_pipeline(config) setup_metric(pl_model, config) else: pl_model =", "= parser.parse_args() if args.command=='train': training=True default_test = False elif args.command=='test': training=False default_test=True config", "default_test=True config = get_config(args.config) config = utils.clean_config(config) trainer=None if training: trainer = train(config)", "pl_model = PL_Model_Class.load_from_checkpoint(path, model=get_torch_model(wb_config), optim_args=get_optim_args(wb_config)) else: raise e print('Done.') if add_metric: setup_metric(pl_model, config,", "pl_model = trainer.model setup_metric(pl_model, config, istest=True) arg_dict['model'] = pl_model trainer.test(**arg_dict) return trainer def", "Lightning experiment, or the id of the run if need to be fetched", "config, **add_metric_kwargs) return pl_model def get_trainer_config(config: dict, only_test=False) -> dict: trainer_config = config['train']", "logger is None: print(\"Logger did not load. Could mean an error or that", "- add_metric_kwargs: Arguments passed to the setup_metric function if activated. \"\"\" if is_dummy(config['arch']['name']):", "pl_model is None: pl_model = load_model(config, config['train']['start_model'], add_metric=False) trainer = setup_trainer(config, pl_model, **kwargs)", "return None else: raise NotImplementedError(f\"Observer {observer} not implemented.\") return logger def load_model(config: dict,", "= PL_Model_Class.load_from_checkpoint(path, model=get_torch_model(config), optim_args=get_optim_args(config)) except (FileNotFoundError) as e: if config['observers']['observer']=='wandb': print(f\"Failed at finding", "return logger def load_model(config: dict, path: str, add_metric=True, **add_metric_kwargs) -> GNN_Abstract_Base_Class: \"\"\" -", "divergence_threshold=config['train']['optim_args']['lr_stop']) checkpoint_callback = ModelCheckpoint(monitor=\"val_loss\", save_top_k=1, verbose=True) trainer_config['callbacks'] = [early_stopping, checkpoint_callback] clean_config = utils.restrict_dict_to_function(pl.Trainer.__init__,", "toolbox.wandb_helper as wbh def get_config(filename='default_config.yaml') -> dict: with open(filename, 'r') as f: config", "not implemented.\") return logger def load_model(config: dict, path: str, add_metric=True, **add_metric_kwargs) -> GNN_Abstract_Base_Class:", "config = utils.clean_config(config) trainer=None if training: trainer = train(config) if default_test or config['test_enabled']:", "from models import get_pipeline, get_pl_model, get_torch_model, get_optim_args, is_dummy from models.base_model import GNN_Abstract_Base_Class from", "**kwargs) -> None: if dataloaders is None: dataloaders = get_test_dataset(config) arg_dict = {'dataloaders':", "get_test_dataset, get_train_val_datasets from metrics import setup_metric import pytorch_lightning as pl from pytorch_lightning.loggers import", "**kwargs) else: arg_dict['ckpt_path'] = 'best' pl_model = trainer.model setup_metric(pl_model, config, istest=True) arg_dict['model'] =", "get_train_val_datasets(config) trainer.fit(pl_model, train_dataset, val_dataset) return trainer def test(config: dict, trainer=None, model=None, dataloaders=None, **kwargs)", "import EarlyStopping, ModelCheckpoint import argparse import toolbox.wandb_helper as wbh def get_config(filename='default_config.yaml') -> dict:", "get_pl_model(config) pl_model = PL_Model_Class.load_from_checkpoint(path, model=get_torch_model(config), optim_args=get_optim_args(config)) except (FileNotFoundError) as e: if config['observers']['observer']=='wandb': print(f\"Failed", "Trying to use W&B.\") project = f\"{config['project']}_{config['problem']}\" wb_config, path = wbh.download_model(project, path) PL_Model_Class", "path) PL_Model_Class = get_pl_model(config) pl_model = PL_Model_Class.load_from_checkpoint(path, model=get_torch_model(wb_config), optim_args=get_optim_args(wb_config)) else: raise e print('Done.')", "if add_metric: setup_metric(pl_model, config, **add_metric_kwargs) return pl_model def get_trainer_config(config: dict, only_test=False) -> dict:", "can't train.\") return None if config['train']['anew']: pl_model = get_pipeline(config) setup_metric(pl_model, config) else: pl_model", "is_dummy(config['arch']['name']): pl_model = get_pipeline(config) else: print(f'Loading base model from {path}... ', end =", "<gh_stars>0 import yaml import toolbox.utils as utils import os from models import get_pipeline,", "EarlyStopping('lr', verbose=True, mode='max', patience=1+config['train']['max_epochs'], divergence_threshold=config['train']['optim_args']['lr_stop']) checkpoint_callback = ModelCheckpoint(monitor=\"val_loss\", save_top_k=1, verbose=True) trainer_config['callbacks'] = [early_stopping,", "with error : {e}. Trying to use W&B.\") project = f\"{config['project']}_{config['problem']}\" wb_config, path", "-> pl.Trainer: trainer_config = get_trainer_config(config, only_test=only_test) if config['observers']['use']: logger = get_observer(config) if logger", "from W&B - path : str. The local path of the Pytorch Lightning", "{'dataloaders': dataloaders, 'verbose':True } if trainer is None: pl_model = model if pl_model", "= config['train'] accelerator_config = utils.get_accelerator_dict(config['device']) trainer_config.update(accelerator_config) if not only_test: early_stopping = EarlyStopping('lr', verbose=True,", "main(): parser = argparse.ArgumentParser(description='Main file for creating experiments.') parser.add_argument('command', metavar='c', choices=['train','test'], help='Command to", "implemented.\") return logger def load_model(config: dict, path: str, add_metric=True, **add_metric_kwargs) -> GNN_Abstract_Base_Class: \"\"\"", "dict: trainer_config = config['train'] accelerator_config = utils.get_accelerator_dict(config['device']) trainer_config.update(accelerator_config) if not only_test: early_stopping =", "The configuration dictionary (careful, must correspond to the model trying to be loaded).", "get_train_val_datasets from metrics import setup_metric import pytorch_lightning as pl from pytorch_lightning.loggers import WandbLogger", "- config : dict. The configuration dictionary (careful, must correspond to the model", "= os.path.join(os.getcwd(), path) utils.check_dir(path) observer = config['observers']['observer'] if observer=='wandb': logger = WandbLogger(project=f\"{config['project']}_{config['problem']}\", log_model=\"all\",", "WandbLogger(project=f\"{config['project']}_{config['problem']}\", log_model=\"all\", save_dir=path) try: logger.experiment.config.update(config) except AttributeError as ae: return None else: raise", "that we are not in the zero_ranked experiment.\") else: if watch: logger.watch(model) trainer_config['logger']", "else: pl_model = load_model(config, config['train']['start_model']) trainer = setup_trainer(config, pl_model) train_dataset, val_dataset = get_train_val_datasets(config)", "data import get_test_dataset, get_train_val_datasets from metrics import setup_metric import pytorch_lightning as pl from", "-> dict: trainer_config = config['train'] accelerator_config = utils.get_accelerator_dict(config['device']) trainer_config.update(accelerator_config) if not only_test: early_stopping", "-> None: if dataloaders is None: dataloaders = get_test_dataset(config) arg_dict = {'dataloaders': dataloaders,", "help='Command to execute : train or test') parser.add_argument('--config', default='default_config.yaml', type=str, help='Name of the", "or the id of the run if need to be fetched on W&B", "= utils.get_accelerator_dict(config['device']) trainer_config.update(accelerator_config) if not only_test: early_stopping = EarlyStopping('lr', verbose=True, mode='max', patience=1+config['train']['max_epochs'], divergence_threshold=config['train']['optim_args']['lr_stop'])", "= EarlyStopping('lr', verbose=True, mode='max', patience=1+config['train']['max_epochs'], divergence_threshold=config['train']['optim_args']['lr_stop']) checkpoint_callback = ModelCheckpoint(monitor=\"val_loss\", save_top_k=1, verbose=True) trainer_config['callbacks'] =", "raise e print('Done.') if add_metric: setup_metric(pl_model, config, **add_metric_kwargs) return pl_model def get_trainer_config(config: dict,", "', end = \"\") try: PL_Model_Class = get_pl_model(config) pl_model = PL_Model_Class.load_from_checkpoint(path, model=get_torch_model(config), optim_args=get_optim_args(config))", "\"\") try: PL_Model_Class = get_pl_model(config) pl_model = PL_Model_Class.load_from_checkpoint(path, model=get_torch_model(config), optim_args=get_optim_args(config)) except (FileNotFoundError) as", "architecture, can't train.\") return None if config['train']['anew']: pl_model = get_pipeline(config) setup_metric(pl_model, config) else:", "locally with error : {e}. Trying to use W&B.\") project = f\"{config['project']}_{config['problem']}\" wb_config,", "an external metric to the pytorch lightninh module. - add_metric_kwargs: Arguments passed to", "path) utils.check_dir(path) observer = config['observers']['observer'] if observer=='wandb': logger = WandbLogger(project=f\"{config['project']}_{config['problem']}\", log_model=\"all\", save_dir=path) try:", "get_test_dataset(config) arg_dict = {'dataloaders': dataloaders, 'verbose':True } if trainer is None: pl_model =", "in the zero_ranked experiment.\") else: if watch: logger.watch(model) trainer_config['logger'] = logger trainer =", "type=str, help='Name of the configuration file.') args = parser.parse_args() if args.command=='train': training=True default_test", "None: pl_model = load_model(config, config['train']['start_model'], add_metric=False) trainer = setup_trainer(config, pl_model, **kwargs) else: arg_dict['ckpt_path']", "'verbose':True } if trainer is None: pl_model = model if pl_model is None:", "get_observer(config: dict): path = config['observers']['base_dir'] path = os.path.join(os.getcwd(), path) utils.check_dir(path) observer = config['observers']['observer']", "trainer_config = config['train'] accelerator_config = utils.get_accelerator_dict(config['device']) trainer_config.update(accelerator_config) if not only_test: early_stopping = EarlyStopping('lr',", "config) else: pl_model = load_model(config, config['train']['start_model']) trainer = setup_trainer(config, pl_model) train_dataset, val_dataset =", "**add_metric_kwargs) return pl_model def get_trainer_config(config: dict, only_test=False) -> dict: trainer_config = config['train'] accelerator_config", "ae: return None else: raise NotImplementedError(f\"Observer {observer} not implemented.\") return logger def load_model(config:", "as e: if config['observers']['observer']=='wandb': print(f\"Failed at finding model locally with error : {e}.", "= WandbLogger(project=f\"{config['project']}_{config['problem']}\", log_model=\"all\", save_dir=path) try: logger.experiment.config.update(config) except AttributeError as ae: return None else:", "W&B.\") project = f\"{config['project']}_{config['problem']}\" wb_config, path = wbh.download_model(project, path) PL_Model_Class = get_pl_model(config) pl_model", "None if config['train']['anew']: pl_model = get_pipeline(config) setup_metric(pl_model, config) else: pl_model = load_model(config, config['train']['start_model'])", "setup_metric(pl_model, config) else: pl_model = load_model(config, config['train']['start_model']) trainer = setup_trainer(config, pl_model) train_dataset, val_dataset", "utils.restrict_dict_to_function(pl.Trainer.__init__, trainer_config) return clean_config def setup_trainer(config: dict, model: GNN_Abstract_Base_Class, watch=True, only_test=False) -> pl.Trainer:", "to the pytorch lightninh module. - add_metric_kwargs: Arguments passed to the setup_metric function", "{path}... ', end = \"\") try: PL_Model_Class = get_pl_model(config) pl_model = PL_Model_Class.load_from_checkpoint(path, model=get_torch_model(config),", "path of the Pytorch Lightning experiment, or the id of the run if", "metavar='c', choices=['train','test'], help='Command to execute : train or test') parser.add_argument('--config', default='default_config.yaml', type=str, help='Name", "from metrics import setup_metric import pytorch_lightning as pl from pytorch_lightning.loggers import WandbLogger from", "only_test: early_stopping = EarlyStopping('lr', verbose=True, mode='max', patience=1+config['train']['max_epochs'], divergence_threshold=config['train']['optim_args']['lr_stop']) checkpoint_callback = ModelCheckpoint(monitor=\"val_loss\", save_top_k=1, verbose=True)", "config : dict. The configuration dictionary (careful, must correspond to the model trying", "else: if watch: logger.watch(model) trainer_config['logger'] = logger trainer = pl.Trainer(**trainer_config) return trainer def", "EarlyStopping, ModelCheckpoint import argparse import toolbox.wandb_helper as wbh def get_config(filename='default_config.yaml') -> dict: with", "dataloaders is None: dataloaders = get_test_dataset(config) arg_dict = {'dataloaders': dataloaders, 'verbose':True } if", "NotImplementedError(f\"Observer {observer} not implemented.\") return logger def load_model(config: dict, path: str, add_metric=True, **add_metric_kwargs)", "None: if dataloaders is None: dataloaders = get_test_dataset(config) arg_dict = {'dataloaders': dataloaders, 'verbose':True", "module. - add_metric_kwargs: Arguments passed to the setup_metric function if activated. \"\"\" if", "ModelCheckpoint(monitor=\"val_loss\", save_top_k=1, verbose=True) trainer_config['callbacks'] = [early_stopping, checkpoint_callback] clean_config = utils.restrict_dict_to_function(pl.Trainer.__init__, trainer_config) return clean_config", "get_pipeline(config) setup_metric(pl_model, config) else: pl_model = load_model(config, config['train']['start_model']) trainer = setup_trainer(config, pl_model) train_dataset,", "except AttributeError as ae: return None else: raise NotImplementedError(f\"Observer {observer} not implemented.\") return", "as utils import os from models import get_pipeline, get_pl_model, get_torch_model, get_optim_args, is_dummy from", "-> GNN_Abstract_Base_Class: \"\"\" - config : dict. The configuration dictionary (careful, must correspond", "def get_config(filename='default_config.yaml') -> dict: with open(filename, 'r') as f: config = yaml.safe_load(f) return", "open(filename, 'r') as f: config = yaml.safe_load(f) return config def get_observer(config: dict): path", "if watch: logger.watch(model) trainer_config['logger'] = logger trainer = pl.Trainer(**trainer_config) return trainer def train(config:", "WandbLogger from pytorch_lightning.callbacks import EarlyStopping, ModelCheckpoint import argparse import toolbox.wandb_helper as wbh def", "metric to the pytorch lightninh module. - add_metric_kwargs: Arguments passed to the setup_metric", "from {path}... ', end = \"\") try: PL_Model_Class = get_pl_model(config) pl_model = PL_Model_Class.load_from_checkpoint(path,", "train or test') parser.add_argument('--config', default='default_config.yaml', type=str, help='Name of the configuration file.') args =", "default_test = False elif args.command=='test': training=False default_test=True config = get_config(args.config) config = utils.clean_config(config)", "import toolbox.wandb_helper as wbh def get_config(filename='default_config.yaml') -> dict: with open(filename, 'r') as f:", "model=None, dataloaders=None, **kwargs) -> None: if dataloaders is None: dataloaders = get_test_dataset(config) arg_dict", "config['train']['start_model']) trainer = setup_trainer(config, pl_model) train_dataset, val_dataset = get_train_val_datasets(config) trainer.fit(pl_model, train_dataset, val_dataset) return", "only_test=False) -> dict: trainer_config = config['train'] accelerator_config = utils.get_accelerator_dict(config['device']) trainer_config.update(accelerator_config) if not only_test:", "path = os.path.join(os.getcwd(), path) utils.check_dir(path) observer = config['observers']['observer'] if observer=='wandb': logger = WandbLogger(project=f\"{config['project']}_{config['problem']}\",", "args.command=='test': training=False default_test=True config = get_config(args.config) config = utils.clean_config(config) trainer=None if training: trainer", "get_config(filename='default_config.yaml') -> dict: with open(filename, 'r') as f: config = yaml.safe_load(f) return config", "of the configuration file.') args = parser.parse_args() if args.command=='train': training=True default_test = False", "if activated. \"\"\" if is_dummy(config['arch']['name']): pl_model = get_pipeline(config) else: print(f'Loading base model from", "pl_model = PL_Model_Class.load_from_checkpoint(path, model=get_torch_model(config), optim_args=get_optim_args(config)) except (FileNotFoundError) as e: if config['observers']['observer']=='wandb': print(f\"Failed at", "as ae: return None else: raise NotImplementedError(f\"Observer {observer} not implemented.\") return logger def", "wb_config, path = wbh.download_model(project, path) PL_Model_Class = get_pl_model(config) pl_model = PL_Model_Class.load_from_checkpoint(path, model=get_torch_model(wb_config), optim_args=get_optim_args(wb_config))", "execute : train or test') parser.add_argument('--config', default='default_config.yaml', type=str, help='Name of the configuration file.')", "the pytorch lightninh module. - add_metric_kwargs: Arguments passed to the setup_metric function if", "set to None, will try to download a model from W&B - path", "import WandbLogger from pytorch_lightning.callbacks import EarlyStopping, ModelCheckpoint import argparse import toolbox.wandb_helper as wbh", "use W&B.\") project = f\"{config['project']}_{config['problem']}\" wb_config, path = wbh.download_model(project, path) PL_Model_Class = get_pl_model(config)", "toolbox.utils as utils import os from models import get_pipeline, get_pl_model, get_torch_model, get_optim_args, is_dummy", "checkpoint_callback = ModelCheckpoint(monitor=\"val_loss\", save_top_k=1, verbose=True) trainer_config['callbacks'] = [early_stopping, checkpoint_callback] clean_config = utils.restrict_dict_to_function(pl.Trainer.__init__, trainer_config)", "finding model locally with error : {e}. Trying to use W&B.\") project =", "ModelCheckpoint import argparse import toolbox.wandb_helper as wbh def get_config(filename='default_config.yaml') -> dict: with open(filename,", "GNN_Abstract_Base_Class, watch=True, only_test=False) -> pl.Trainer: trainer_config = get_trainer_config(config, only_test=only_test) if config['observers']['use']: logger =", "import get_test_dataset, get_train_val_datasets from metrics import setup_metric import pytorch_lightning as pl from pytorch_lightning.loggers", "training=False default_test=True config = get_config(args.config) config = utils.clean_config(config) trainer=None if training: trainer =", "{e}. Trying to use W&B.\") project = f\"{config['project']}_{config['problem']}\" wb_config, path = wbh.download_model(project, path)", "dataloaders, 'verbose':True } if trainer is None: pl_model = model if pl_model is", "help='Name of the configuration file.') args = parser.parse_args() if args.command=='train': training=True default_test =", "we are not in the zero_ranked experiment.\") else: if watch: logger.watch(model) trainer_config['logger'] =", "dict, trainer=None, model=None, dataloaders=None, **kwargs) -> None: if dataloaders is None: dataloaders =", "str, add_metric=True, **add_metric_kwargs) -> GNN_Abstract_Base_Class: \"\"\" - config : dict. The configuration dictionary", "setup_metric function if activated. \"\"\" if is_dummy(config['arch']['name']): pl_model = get_pipeline(config) else: print(f'Loading base", "dataloaders = get_test_dataset(config) arg_dict = {'dataloaders': dataloaders, 'verbose':True } if trainer is None:", "default='default_config.yaml', type=str, help='Name of the configuration file.') args = parser.parse_args() if args.command=='train': training=True", "clean_config def setup_trainer(config: dict, model: GNN_Abstract_Base_Class, watch=True, only_test=False) -> pl.Trainer: trainer_config = get_trainer_config(config,", "trainer_config) return clean_config def setup_trainer(config: dict, model: GNN_Abstract_Base_Class, watch=True, only_test=False) -> pl.Trainer: trainer_config", "trainer_config = get_trainer_config(config, only_test=only_test) if config['observers']['use']: logger = get_observer(config) if logger is None:", "= setup_trainer(config, pl_model, **kwargs) else: arg_dict['ckpt_path'] = 'best' pl_model = trainer.model setup_metric(pl_model, config,", "argparse import toolbox.wandb_helper as wbh def get_config(filename='default_config.yaml') -> dict: with open(filename, 'r') as", "logger = WandbLogger(project=f\"{config['project']}_{config['problem']}\", log_model=\"all\", save_dir=path) try: logger.experiment.config.update(config) except AttributeError as ae: return None", "fetched on W&B - add_metric: bool. Adds an external metric to the pytorch", "pl_model) train_dataset, val_dataset = get_train_val_datasets(config) trainer.fit(pl_model, train_dataset, val_dataset) return trainer def test(config: dict,", "parser.add_argument('command', metavar='c', choices=['train','test'], help='Command to execute : train or test') parser.add_argument('--config', default='default_config.yaml', type=str,", "'best' pl_model = trainer.model setup_metric(pl_model, config, istest=True) arg_dict['model'] = pl_model trainer.test(**arg_dict) return trainer", "id of the run if need to be fetched on W&B - add_metric:", "setup_trainer(config: dict, model: GNN_Abstract_Base_Class, watch=True, only_test=False) -> pl.Trainer: trainer_config = get_trainer_config(config, only_test=only_test) if", "- add_metric: bool. Adds an external metric to the pytorch lightninh module. -", "test') parser.add_argument('--config', default='default_config.yaml', type=str, help='Name of the configuration file.') args = parser.parse_args() if", "e: if config['observers']['observer']=='wandb': print(f\"Failed at finding model locally with error : {e}. Trying", "Adds an external metric to the pytorch lightninh module. - add_metric_kwargs: Arguments passed", "logger.watch(model) trainer_config['logger'] = logger trainer = pl.Trainer(**trainer_config) return trainer def train(config: dict)->pl.Trainer: if", ": str. The local path of the Pytorch Lightning experiment, or the id", "= False elif args.command=='test': training=False default_test=True config = get_config(args.config) config = utils.clean_config(config) trainer=None", "if observer=='wandb': logger = WandbLogger(project=f\"{config['project']}_{config['problem']}\", log_model=\"all\", save_dir=path) try: logger.experiment.config.update(config) except AttributeError as ae:", "will try to download a model from W&B - path : str. The", "- path : str. The local path of the Pytorch Lightning experiment, or", "creating experiments.') parser.add_argument('command', metavar='c', choices=['train','test'], help='Command to execute : train or test') parser.add_argument('--config',", "mode='max', patience=1+config['train']['max_epochs'], divergence_threshold=config['train']['optim_args']['lr_stop']) checkpoint_callback = ModelCheckpoint(monitor=\"val_loss\", save_top_k=1, verbose=True) trainer_config['callbacks'] = [early_stopping, checkpoint_callback] clean_config", "must correspond to the model trying to be loaded). If set to None,", "= PL_Model_Class.load_from_checkpoint(path, model=get_torch_model(wb_config), optim_args=get_optim_args(wb_config)) else: raise e print('Done.') if add_metric: setup_metric(pl_model, config, **add_metric_kwargs)", "model trying to be loaded). If set to None, will try to download", "configuration file.') args = parser.parse_args() if args.command=='train': training=True default_test = False elif args.command=='test':", "save_top_k=1, verbose=True) trainer_config['callbacks'] = [early_stopping, checkpoint_callback] clean_config = utils.restrict_dict_to_function(pl.Trainer.__init__, trainer_config) return clean_config def", "None, will try to download a model from W&B - path : str.", "raise NotImplementedError(f\"Observer {observer} not implemented.\") return logger def load_model(config: dict, path: str, add_metric=True,", "trying to be loaded). If set to None, will try to download a", "Pytorch Lightning experiment, or the id of the run if need to be", "trainer.test(**arg_dict) return trainer def main(): parser = argparse.ArgumentParser(description='Main file for creating experiments.') parser.add_argument('command',", "as pl from pytorch_lightning.loggers import WandbLogger from pytorch_lightning.callbacks import EarlyStopping, ModelCheckpoint import argparse", "add_metric: bool. Adds an external metric to the pytorch lightninh module. - add_metric_kwargs:", ": train or test') parser.add_argument('--config', default='default_config.yaml', type=str, help='Name of the configuration file.') args", "val_dataset) return trainer def test(config: dict, trainer=None, model=None, dataloaders=None, **kwargs) -> None: if", "= train(config) if default_test or config['test_enabled']: test(config, trainer) if __name__==\"__main__\": pl.seed_everything(3787, workers=True) main()", "yaml.safe_load(f) return config def get_observer(config: dict): path = config['observers']['base_dir'] path = os.path.join(os.getcwd(), path)", "path : str. The local path of the Pytorch Lightning experiment, or the", "config['observers']['base_dir'] path = os.path.join(os.getcwd(), path) utils.check_dir(path) observer = config['observers']['observer'] if observer=='wandb': logger =", "config['observers']['observer']=='wandb': print(f\"Failed at finding model locally with error : {e}. Trying to use", "passed to the setup_metric function if activated. \"\"\" if is_dummy(config['arch']['name']): pl_model = get_pipeline(config)", "get_observer(config) if logger is None: print(\"Logger did not load. Could mean an error", "dictionary (careful, must correspond to the model trying to be loaded). If set", "load_model(config, config['train']['start_model']) trainer = setup_trainer(config, pl_model) train_dataset, val_dataset = get_train_val_datasets(config) trainer.fit(pl_model, train_dataset, val_dataset)", "dict): path = config['observers']['base_dir'] path = os.path.join(os.getcwd(), path) utils.check_dir(path) observer = config['observers']['observer'] if", "dict, only_test=False) -> dict: trainer_config = config['train'] accelerator_config = utils.get_accelerator_dict(config['device']) trainer_config.update(accelerator_config) if not", "is None: print(\"Logger did not load. Could mean an error or that we", "config = yaml.safe_load(f) return config def get_observer(config: dict): path = config['observers']['base_dir'] path =", "config def get_observer(config: dict): path = config['observers']['base_dir'] path = os.path.join(os.getcwd(), path) utils.check_dir(path) observer", "= get_pipeline(config) setup_metric(pl_model, config) else: pl_model = load_model(config, config['train']['start_model']) trainer = setup_trainer(config, pl_model)", "arg_dict['ckpt_path'] = 'best' pl_model = trainer.model setup_metric(pl_model, config, istest=True) arg_dict['model'] = pl_model trainer.test(**arg_dict)", "trainer=None if training: trainer = train(config) if default_test or config['test_enabled']: test(config, trainer) if", "setup_metric import pytorch_lightning as pl from pytorch_lightning.loggers import WandbLogger from pytorch_lightning.callbacks import EarlyStopping,", "as wbh def get_config(filename='default_config.yaml') -> dict: with open(filename, 'r') as f: config =", "configuration dictionary (careful, must correspond to the model trying to be loaded). If", "= config['observers']['base_dir'] path = os.path.join(os.getcwd(), path) utils.check_dir(path) observer = config['observers']['observer'] if observer=='wandb': logger", "import setup_metric import pytorch_lightning as pl from pytorch_lightning.loggers import WandbLogger from pytorch_lightning.callbacks import", "zero_ranked experiment.\") else: if watch: logger.watch(model) trainer_config['logger'] = logger trainer = pl.Trainer(**trainer_config) return", "trainer_config['callbacks'] = [early_stopping, checkpoint_callback] clean_config = utils.restrict_dict_to_function(pl.Trainer.__init__, trainer_config) return clean_config def setup_trainer(config: dict,", "return trainer def train(config: dict)->pl.Trainer: if is_dummy(config['arch']['name']): print(\"Dummy architecture, can't train.\") return None", "= argparse.ArgumentParser(description='Main file for creating experiments.') parser.add_argument('command', metavar='c', choices=['train','test'], help='Command to execute :", "train_dataset, val_dataset = get_train_val_datasets(config) trainer.fit(pl_model, train_dataset, val_dataset) return trainer def test(config: dict, trainer=None,", "the model trying to be loaded). If set to None, will try to", "training: trainer = train(config) if default_test or config['test_enabled']: test(config, trainer) if __name__==\"__main__\": pl.seed_everything(3787,", "pl_model trainer.test(**arg_dict) return trainer def main(): parser = argparse.ArgumentParser(description='Main file for creating experiments.')" ]
[ "import click from bulk_import_rename.commands.detect_modifications import track_modifications from bulk_import_rename.commands.rename_import import run_rename CONTEXT_SETTINGS = dict(help_option_names=['-h',", "'__main__': # The sys.argv[1:] is necessary for debug on python2 # Link: https://goo.gl/vp5hfz", "@click.argument('moved_imports_file', type=click.Path(exists=True, resolve_path=True)) def rename(**kwargs): run_rename(**kwargs) if __name__ == '__main__': # The sys.argv[1:]", "of the branch that has the modifications') @click.option('--output_file', default='list_output.py', help='Change the name of", "type=click.Path(exists=True, resolve_path=True)) def rename(**kwargs): run_rename(**kwargs) if __name__ == '__main__': # The sys.argv[1:] is", "run_rename CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help']) @click.group(context_settings=CONTEXT_SETTINGS) @click.version_option(version='0.0.1') def app(): pass @app.command() @click.argument('project_path', type=click.Path(exists=True))", "the modifications') @click.option('--output_file', default='list_output.py', help='Change the name of the output file') def track(**kwargs):", "has the modifications') @click.option('--output_file', default='list_output.py', help='Change the name of the output file') def", "app(): pass @app.command() @click.argument('project_path', type=click.Path(exists=True)) @click.option('--origin_branch', default='master', help='Branch to start the evaluation') @click.option('--work_branch',", "def rename(**kwargs): run_rename(**kwargs) if __name__ == '__main__': # The sys.argv[1:] is necessary for", "the name of the output file') def track(**kwargs): track_modifications(**kwargs) @app.command() @click.argument('project_path', nargs=-1, type=click.Path(exists=True))", "import sys import click from bulk_import_rename.commands.detect_modifications import track_modifications from bulk_import_rename.commands.rename_import import run_rename CONTEXT_SETTINGS", "sys import click from bulk_import_rename.commands.detect_modifications import track_modifications from bulk_import_rename.commands.rename_import import run_rename CONTEXT_SETTINGS =", "of the output file') def track(**kwargs): track_modifications(**kwargs) @app.command() @click.argument('project_path', nargs=-1, type=click.Path(exists=True)) @click.argument('moved_imports_file', type=click.Path(exists=True,", "pass @app.command() @click.argument('project_path', type=click.Path(exists=True)) @click.option('--origin_branch', default='master', help='Branch to start the evaluation') @click.option('--work_branch', default=False,", "file') def track(**kwargs): track_modifications(**kwargs) @app.command() @click.argument('project_path', nargs=-1, type=click.Path(exists=True)) @click.argument('moved_imports_file', type=click.Path(exists=True, resolve_path=True)) def rename(**kwargs):", "'--help']) @click.group(context_settings=CONTEXT_SETTINGS) @click.version_option(version='0.0.1') def app(): pass @app.command() @click.argument('project_path', type=click.Path(exists=True)) @click.option('--origin_branch', default='master', help='Branch to", "bulk_import_rename.commands.detect_modifications import track_modifications from bulk_import_rename.commands.rename_import import run_rename CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help']) @click.group(context_settings=CONTEXT_SETTINGS) @click.version_option(version='0.0.1')", "resolve_path=True)) def rename(**kwargs): run_rename(**kwargs) if __name__ == '__main__': # The sys.argv[1:] is necessary", "the output file') def track(**kwargs): track_modifications(**kwargs) @app.command() @click.argument('project_path', nargs=-1, type=click.Path(exists=True)) @click.argument('moved_imports_file', type=click.Path(exists=True, resolve_path=True))", "default='list_output.py', help='Change the name of the output file') def track(**kwargs): track_modifications(**kwargs) @app.command() @click.argument('project_path',", "name of the output file') def track(**kwargs): track_modifications(**kwargs) @app.command() @click.argument('project_path', nargs=-1, type=click.Path(exists=True)) @click.argument('moved_imports_file',", "default='master', help='Branch to start the evaluation') @click.option('--work_branch', default=False, help='Name of the branch that", "@click.option('--origin_branch', default='master', help='Branch to start the evaluation') @click.option('--work_branch', default=False, help='Name of the branch", "def app(): pass @app.command() @click.argument('project_path', type=click.Path(exists=True)) @click.option('--origin_branch', default='master', help='Branch to start the evaluation')", "track_modifications from bulk_import_rename.commands.rename_import import run_rename CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help']) @click.group(context_settings=CONTEXT_SETTINGS) @click.version_option(version='0.0.1') def app():", "start the evaluation') @click.option('--work_branch', default=False, help='Name of the branch that has the modifications')", "the branch that has the modifications') @click.option('--output_file', default='list_output.py', help='Change the name of the", "branch that has the modifications') @click.option('--output_file', default='list_output.py', help='Change the name of the output", "@app.command() @click.argument('project_path', nargs=-1, type=click.Path(exists=True)) @click.argument('moved_imports_file', type=click.Path(exists=True, resolve_path=True)) def rename(**kwargs): run_rename(**kwargs) if __name__ ==", "from bulk_import_rename.commands.detect_modifications import track_modifications from bulk_import_rename.commands.rename_import import run_rename CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help']) @click.group(context_settings=CONTEXT_SETTINGS)", "click from bulk_import_rename.commands.detect_modifications import track_modifications from bulk_import_rename.commands.rename_import import run_rename CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help'])", "@click.argument('project_path', nargs=-1, type=click.Path(exists=True)) @click.argument('moved_imports_file', type=click.Path(exists=True, resolve_path=True)) def rename(**kwargs): run_rename(**kwargs) if __name__ == '__main__':", "nargs=-1, type=click.Path(exists=True)) @click.argument('moved_imports_file', type=click.Path(exists=True, resolve_path=True)) def rename(**kwargs): run_rename(**kwargs) if __name__ == '__main__': #", "help='Name of the branch that has the modifications') @click.option('--output_file', default='list_output.py', help='Change the name", "type=click.Path(exists=True)) @click.argument('moved_imports_file', type=click.Path(exists=True, resolve_path=True)) def rename(**kwargs): run_rename(**kwargs) if __name__ == '__main__': # The", "if __name__ == '__main__': # The sys.argv[1:] is necessary for debug on python2", "from bulk_import_rename.commands.rename_import import run_rename CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help']) @click.group(context_settings=CONTEXT_SETTINGS) @click.version_option(version='0.0.1') def app(): pass", "def track(**kwargs): track_modifications(**kwargs) @app.command() @click.argument('project_path', nargs=-1, type=click.Path(exists=True)) @click.argument('moved_imports_file', type=click.Path(exists=True, resolve_path=True)) def rename(**kwargs): run_rename(**kwargs)", "run_rename(**kwargs) if __name__ == '__main__': # The sys.argv[1:] is necessary for debug on", "@app.command() @click.argument('project_path', type=click.Path(exists=True)) @click.option('--origin_branch', default='master', help='Branch to start the evaluation') @click.option('--work_branch', default=False, help='Name", "track(**kwargs): track_modifications(**kwargs) @app.command() @click.argument('project_path', nargs=-1, type=click.Path(exists=True)) @click.argument('moved_imports_file', type=click.Path(exists=True, resolve_path=True)) def rename(**kwargs): run_rename(**kwargs) if", "that has the modifications') @click.option('--output_file', default='list_output.py', help='Change the name of the output file')", "# The sys.argv[1:] is necessary for debug on python2 # Link: https://goo.gl/vp5hfz app(sys.argv[1:])", "= dict(help_option_names=['-h', '--help']) @click.group(context_settings=CONTEXT_SETTINGS) @click.version_option(version='0.0.1') def app(): pass @app.command() @click.argument('project_path', type=click.Path(exists=True)) @click.option('--origin_branch', default='master',", "@click.argument('project_path', type=click.Path(exists=True)) @click.option('--origin_branch', default='master', help='Branch to start the evaluation') @click.option('--work_branch', default=False, help='Name of", "evaluation') @click.option('--work_branch', default=False, help='Name of the branch that has the modifications') @click.option('--output_file', default='list_output.py',", "dict(help_option_names=['-h', '--help']) @click.group(context_settings=CONTEXT_SETTINGS) @click.version_option(version='0.0.1') def app(): pass @app.command() @click.argument('project_path', type=click.Path(exists=True)) @click.option('--origin_branch', default='master', help='Branch", "help='Branch to start the evaluation') @click.option('--work_branch', default=False, help='Name of the branch that has", "rename(**kwargs): run_rename(**kwargs) if __name__ == '__main__': # The sys.argv[1:] is necessary for debug", "__name__ == '__main__': # The sys.argv[1:] is necessary for debug on python2 #", "CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help']) @click.group(context_settings=CONTEXT_SETTINGS) @click.version_option(version='0.0.1') def app(): pass @app.command() @click.argument('project_path', type=click.Path(exists=True)) @click.option('--origin_branch',", "modifications') @click.option('--output_file', default='list_output.py', help='Change the name of the output file') def track(**kwargs): track_modifications(**kwargs)", "type=click.Path(exists=True)) @click.option('--origin_branch', default='master', help='Branch to start the evaluation') @click.option('--work_branch', default=False, help='Name of the", "the evaluation') @click.option('--work_branch', default=False, help='Name of the branch that has the modifications') @click.option('--output_file',", "default=False, help='Name of the branch that has the modifications') @click.option('--output_file', default='list_output.py', help='Change the", "@click.option('--output_file', default='list_output.py', help='Change the name of the output file') def track(**kwargs): track_modifications(**kwargs) @app.command()", "@click.option('--work_branch', default=False, help='Name of the branch that has the modifications') @click.option('--output_file', default='list_output.py', help='Change", "output file') def track(**kwargs): track_modifications(**kwargs) @app.command() @click.argument('project_path', nargs=-1, type=click.Path(exists=True)) @click.argument('moved_imports_file', type=click.Path(exists=True, resolve_path=True)) def", "bulk_import_rename.commands.rename_import import run_rename CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help']) @click.group(context_settings=CONTEXT_SETTINGS) @click.version_option(version='0.0.1') def app(): pass @app.command()", "@click.group(context_settings=CONTEXT_SETTINGS) @click.version_option(version='0.0.1') def app(): pass @app.command() @click.argument('project_path', type=click.Path(exists=True)) @click.option('--origin_branch', default='master', help='Branch to start", "help='Change the name of the output file') def track(**kwargs): track_modifications(**kwargs) @app.command() @click.argument('project_path', nargs=-1,", "track_modifications(**kwargs) @app.command() @click.argument('project_path', nargs=-1, type=click.Path(exists=True)) @click.argument('moved_imports_file', type=click.Path(exists=True, resolve_path=True)) def rename(**kwargs): run_rename(**kwargs) if __name__", "import run_rename CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help']) @click.group(context_settings=CONTEXT_SETTINGS) @click.version_option(version='0.0.1') def app(): pass @app.command() @click.argument('project_path',", "== '__main__': # The sys.argv[1:] is necessary for debug on python2 # Link:", "import track_modifications from bulk_import_rename.commands.rename_import import run_rename CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help']) @click.group(context_settings=CONTEXT_SETTINGS) @click.version_option(version='0.0.1') def", "to start the evaluation') @click.option('--work_branch', default=False, help='Name of the branch that has the", "@click.version_option(version='0.0.1') def app(): pass @app.command() @click.argument('project_path', type=click.Path(exists=True)) @click.option('--origin_branch', default='master', help='Branch to start the" ]
[ "+ '&for=block%20group:*&in=state:' + state + '%20county:' + county + '&key=' + census_key response", "'https://api.census.gov/data/2019/acs/acs5?get=' + variables + '&for=tract:*&in=state:' + state + '&key=' + census_key response =", "pandas as pd census_key = '' # scrubbed for now, TODO: secrets config", "variable_names): data = [] url = 'https://api.census.gov/data/2019/acs/acs5?get=' + variables + '&for=tract:*&in=state:' + state", "'&for=tract:*&in=state:' + state + '&key=' + census_key response = requests.get(url) if response.status_code ==", "failed') headers = variable_names + [\"state\", \"county\", \"tract\", \"block_group\"] df = pd.DataFrame(data=data, columns=headers)", "import censusdata import requests import pandas as pd census_key = '' # scrubbed", "year) for key in list(geo): value = geo[key].params() county = value[1][1] counties.append(county) return", "value[1][1] counties.append(county) return counties def get_data_by_block_group(variables, state, county_list, api_key, variable_names): data = []", "requests.get(url) if response.status_code == 200: batch = response.json()[1:] data.extend(batch) else: print('API connection failed')", "connection failed') headers = variable_names + [\"state\", \"county\", \"tract\", \"block_group\"] df = pd.DataFrame(data=data,", "= value[1][1] counties.append(county) return counties def get_data_by_block_group(variables, state, county_list, api_key, variable_names): data =", "geo = censusdata.geographies(censusdata.censusgeo([('state', state), ('county', '*')]), 'acs5', year) for key in list(geo): value", "= censusdata.geographies(censusdata.censusgeo([('state', state), ('county', '*')]), 'acs5', year) for key in list(geo): value =", "if response.status_code == 200: batch = response.json()[1:] data.extend(batch) else: print('API connection failed') headers", "api_key, variable_names): data = [] url = 'https://api.census.gov/data/2019/acs/acs5?get=' + variables + '&for=tract:*&in=state:' +", "else: print('API connection failed') headers = variable_names + [\"state\", \"county\", \"tract\"] df =", "\"tract\", \"block_group\"] df = pd.DataFrame(data=data, columns=headers) return df def get_data_by_tract(variables, state, api_key, variable_names):", "batch = response.json()[1:] data.extend(batch) else: print('API connection failed') headers = variable_names + [\"state\",", "in list(geo): value = geo[key].params() county = value[1][1] counties.append(county) return counties def get_data_by_block_group(variables,", "import requests import pandas as pd census_key = '' # scrubbed for now,", "geo[key].params() county = value[1][1] counties.append(county) return counties def get_data_by_block_group(variables, state, county_list, api_key, variable_names):", "key in list(geo): value = geo[key].params() county = value[1][1] counties.append(county) return counties def", "'acs5', year) for key in list(geo): value = geo[key].params() county = value[1][1] counties.append(county)", "scrubbed for now, TODO: secrets config def get_counties(state, year): counties = [] geo", "+ county + '&key=' + census_key response = requests.get(url) if response.status_code == 200:", "as pd census_key = '' # scrubbed for now, TODO: secrets config def", "for key in list(geo): value = geo[key].params() county = value[1][1] counties.append(county) return counties", "else: print('API connection failed') headers = variable_names + [\"state\", \"county\", \"tract\", \"block_group\"] df", "data = [] for county in county_list: url = 'https://api.census.gov/data/2019/acs/acs5?get=' + variables +", "print('API connection failed') headers = variable_names + [\"state\", \"county\", \"tract\", \"block_group\"] df =", "'*')]), 'acs5', year) for key in list(geo): value = geo[key].params() county = value[1][1]", "= [] url = 'https://api.census.gov/data/2019/acs/acs5?get=' + variables + '&for=tract:*&in=state:' + state + '&key='", "'%20county:' + county + '&key=' + census_key response = requests.get(url) if response.status_code ==", "county_list: url = 'https://api.census.gov/data/2019/acs/acs5?get=' + variables + '&for=block%20group:*&in=state:' + state + '%20county:' +", "+ state + '%20county:' + county + '&key=' + census_key response = requests.get(url)", "state + '%20county:' + county + '&key=' + census_key response = requests.get(url) if", "columns=headers) return df def get_data_by_tract(variables, state, api_key, variable_names): data = [] url =", "response.json()[1:] data.extend(batch) else: print('API connection failed') headers = variable_names + [\"state\", \"county\", \"tract\"]", "+ variables + '&for=tract:*&in=state:' + state + '&key=' + census_key response = requests.get(url)", "connection failed') headers = variable_names + [\"state\", \"county\", \"tract\"] df = pd.DataFrame(data=data, columns=headers)", "variables + '&for=block%20group:*&in=state:' + state + '%20county:' + county + '&key=' + census_key", "data = [] url = 'https://api.census.gov/data/2019/acs/acs5?get=' + variables + '&for=tract:*&in=state:' + state +", "+ '%20county:' + county + '&key=' + census_key response = requests.get(url) if response.status_code", "def get_counties(state, year): counties = [] geo = censusdata.geographies(censusdata.censusgeo([('state', state), ('county', '*')]), 'acs5',", "= [] geo = censusdata.geographies(censusdata.censusgeo([('state', state), ('county', '*')]), 'acs5', year) for key in", "\"block_group\"] df = pd.DataFrame(data=data, columns=headers) return df def get_data_by_tract(variables, state, api_key, variable_names): data", "= '' # scrubbed for now, TODO: secrets config def get_counties(state, year): counties", "<filename>census_data/core/variables.py<gh_stars>0 import censusdata import requests import pandas as pd census_key = '' #", "return df def get_data_by_tract(variables, state, api_key, variable_names): data = [] url = 'https://api.census.gov/data/2019/acs/acs5?get='", "[] geo = censusdata.geographies(censusdata.censusgeo([('state', state), ('county', '*')]), 'acs5', year) for key in list(geo):", "response.status_code == 200: batch = response.json()[1:] data.extend(batch) else: print('API connection failed') headers =", "df def get_data_by_tract(variables, state, api_key, variable_names): data = [] url = 'https://api.census.gov/data/2019/acs/acs5?get=' +", "county = value[1][1] counties.append(county) return counties def get_data_by_block_group(variables, state, county_list, api_key, variable_names): data", "+ [\"state\", \"county\", \"tract\", \"block_group\"] df = pd.DataFrame(data=data, columns=headers) return df def get_data_by_tract(variables,", "for now, TODO: secrets config def get_counties(state, year): counties = [] geo =", "now, TODO: secrets config def get_counties(state, year): counties = [] geo = censusdata.geographies(censusdata.censusgeo([('state',", "'&key=' + census_key response = requests.get(url) if response.status_code == 200: batch = response.json()[1:]", "df = pd.DataFrame(data=data, columns=headers) return df def get_data_by_tract(variables, state, api_key, variable_names): data =", "variables + '&for=tract:*&in=state:' + state + '&key=' + census_key response = requests.get(url) if", "in county_list: url = 'https://api.census.gov/data/2019/acs/acs5?get=' + variables + '&for=block%20group:*&in=state:' + state + '%20county:'", "county in county_list: url = 'https://api.census.gov/data/2019/acs/acs5?get=' + variables + '&for=block%20group:*&in=state:' + state +", "data.extend(batch) else: print('API connection failed') headers = variable_names + [\"state\", \"county\", \"tract\"] df", "response = requests.get(url) if response.status_code == 200: batch = response.json()[1:] data.extend(batch) else: print('API", "= geo[key].params() county = value[1][1] counties.append(county) return counties def get_data_by_block_group(variables, state, county_list, api_key,", "response.json()[1:] data.extend(batch) else: print('API connection failed') headers = variable_names + [\"state\", \"county\", \"tract\",", "list(geo): value = geo[key].params() county = value[1][1] counties.append(county) return counties def get_data_by_block_group(variables, state,", "state + '&key=' + census_key response = requests.get(url) if response.status_code == 200: batch", "+ variables + '&for=block%20group:*&in=state:' + state + '%20county:' + county + '&key=' +", "state, county_list, api_key, variable_names): data = [] for county in county_list: url =", "state, api_key, variable_names): data = [] url = 'https://api.census.gov/data/2019/acs/acs5?get=' + variables + '&for=tract:*&in=state:'", "failed') headers = variable_names + [\"state\", \"county\", \"tract\"] df = pd.DataFrame(data=data, columns=headers) return", "censusdata import requests import pandas as pd census_key = '' # scrubbed for", "== 200: batch = response.json()[1:] data.extend(batch) else: print('API connection failed') headers = variable_names", "= requests.get(url) if response.status_code == 200: batch = response.json()[1:] data.extend(batch) else: print('API connection", "'' # scrubbed for now, TODO: secrets config def get_counties(state, year): counties =", "county + '&key=' + census_key response = requests.get(url) if response.status_code == 200: batch", "= pd.DataFrame(data=data, columns=headers) return df def get_data_by_tract(variables, state, api_key, variable_names): data = []", "variable_names + [\"state\", \"county\", \"tract\", \"block_group\"] df = pd.DataFrame(data=data, columns=headers) return df def", "get_counties(state, year): counties = [] geo = censusdata.geographies(censusdata.censusgeo([('state', state), ('county', '*')]), 'acs5', year)", "get_data_by_block_group(variables, state, county_list, api_key, variable_names): data = [] for county in county_list: url", "'&for=block%20group:*&in=state:' + state + '%20county:' + county + '&key=' + census_key response =", "census_key response = requests.get(url) if response.status_code == 200: batch = response.json()[1:] data.extend(batch) else:", "= response.json()[1:] data.extend(batch) else: print('API connection failed') headers = variable_names + [\"state\", \"county\",", "+ census_key response = requests.get(url) if response.status_code == 200: batch = response.json()[1:] data.extend(batch)", "county_list, api_key, variable_names): data = [] for county in county_list: url = 'https://api.census.gov/data/2019/acs/acs5?get='", "requests import pandas as pd census_key = '' # scrubbed for now, TODO:", "api_key, variable_names): data = [] for county in county_list: url = 'https://api.census.gov/data/2019/acs/acs5?get=' +", "200: batch = response.json()[1:] data.extend(batch) else: print('API connection failed') headers = variable_names +", "= 'https://api.census.gov/data/2019/acs/acs5?get=' + variables + '&for=block%20group:*&in=state:' + state + '%20county:' + county +", "[] url = 'https://api.census.gov/data/2019/acs/acs5?get=' + variables + '&for=tract:*&in=state:' + state + '&key=' +", "return counties def get_data_by_block_group(variables, state, county_list, api_key, variable_names): data = [] for county", "for county in county_list: url = 'https://api.census.gov/data/2019/acs/acs5?get=' + variables + '&for=block%20group:*&in=state:' + state", "\"county\", \"tract\", \"block_group\"] df = pd.DataFrame(data=data, columns=headers) return df def get_data_by_tract(variables, state, api_key,", "+ state + '&key=' + census_key response = requests.get(url) if response.status_code == 200:", "pd census_key = '' # scrubbed for now, TODO: secrets config def get_counties(state,", "value = geo[key].params() county = value[1][1] counties.append(county) return counties def get_data_by_block_group(variables, state, county_list,", "[] for county in county_list: url = 'https://api.census.gov/data/2019/acs/acs5?get=' + variables + '&for=block%20group:*&in=state:' +", "= [] for county in county_list: url = 'https://api.census.gov/data/2019/acs/acs5?get=' + variables + '&for=block%20group:*&in=state:'", "get_data_by_tract(variables, state, api_key, variable_names): data = [] url = 'https://api.census.gov/data/2019/acs/acs5?get=' + variables +", "state), ('county', '*')]), 'acs5', year) for key in list(geo): value = geo[key].params() county", "def get_data_by_tract(variables, state, api_key, variable_names): data = [] url = 'https://api.census.gov/data/2019/acs/acs5?get=' + variables", "counties.append(county) return counties def get_data_by_block_group(variables, state, county_list, api_key, variable_names): data = [] for", "= 'https://api.census.gov/data/2019/acs/acs5?get=' + variables + '&for=tract:*&in=state:' + state + '&key=' + census_key response", "= variable_names + [\"state\", \"county\", \"tract\", \"block_group\"] df = pd.DataFrame(data=data, columns=headers) return df", "+ '&for=tract:*&in=state:' + state + '&key=' + census_key response = requests.get(url) if response.status_code", "[\"state\", \"county\", \"tract\", \"block_group\"] df = pd.DataFrame(data=data, columns=headers) return df def get_data_by_tract(variables, state,", "secrets config def get_counties(state, year): counties = [] geo = censusdata.geographies(censusdata.censusgeo([('state', state), ('county',", "counties = [] geo = censusdata.geographies(censusdata.censusgeo([('state', state), ('county', '*')]), 'acs5', year) for key", "url = 'https://api.census.gov/data/2019/acs/acs5?get=' + variables + '&for=tract:*&in=state:' + state + '&key=' + census_key", "censusdata.geographies(censusdata.censusgeo([('state', state), ('county', '*')]), 'acs5', year) for key in list(geo): value = geo[key].params()", "url = 'https://api.census.gov/data/2019/acs/acs5?get=' + variables + '&for=block%20group:*&in=state:' + state + '%20county:' + county", "+ '&key=' + census_key response = requests.get(url) if response.status_code == 200: batch =", "print('API connection failed') headers = variable_names + [\"state\", \"county\", \"tract\"] df = pd.DataFrame(data=data,", "def get_data_by_block_group(variables, state, county_list, api_key, variable_names): data = [] for county in county_list:", "census_key = '' # scrubbed for now, TODO: secrets config def get_counties(state, year):", "TODO: secrets config def get_counties(state, year): counties = [] geo = censusdata.geographies(censusdata.censusgeo([('state', state),", "variable_names): data = [] for county in county_list: url = 'https://api.census.gov/data/2019/acs/acs5?get=' + variables", "year): counties = [] geo = censusdata.geographies(censusdata.censusgeo([('state', state), ('county', '*')]), 'acs5', year) for", "pd.DataFrame(data=data, columns=headers) return df def get_data_by_tract(variables, state, api_key, variable_names): data = [] url", "import pandas as pd census_key = '' # scrubbed for now, TODO: secrets", "# scrubbed for now, TODO: secrets config def get_counties(state, year): counties = []", "headers = variable_names + [\"state\", \"county\", \"tract\", \"block_group\"] df = pd.DataFrame(data=data, columns=headers) return", "headers = variable_names + [\"state\", \"county\", \"tract\"] df = pd.DataFrame(data=data, columns=headers) return df", "('county', '*')]), 'acs5', year) for key in list(geo): value = geo[key].params() county =", "counties def get_data_by_block_group(variables, state, county_list, api_key, variable_names): data = [] for county in", "data.extend(batch) else: print('API connection failed') headers = variable_names + [\"state\", \"county\", \"tract\", \"block_group\"]", "'https://api.census.gov/data/2019/acs/acs5?get=' + variables + '&for=block%20group:*&in=state:' + state + '%20county:' + county + '&key='", "config def get_counties(state, year): counties = [] geo = censusdata.geographies(censusdata.censusgeo([('state', state), ('county', '*')])," ]
[ "self._module_name @property def affected_targets(self): return len(self._affected_targets) @property def dependency_count(self): return self._dependency_count @property def", "= ch.latest_changes_count if ch else 'n/a' filepath = ch.filepath if ch else 'n/a'", "= next(iter_to_children) if child not in visited: stack.append((child, iter(graph[child]))) visited.add(child) except StopIteration: stack.pop()", "latest_changes_count=latest_changes_count, lifespan_in_days=lifespan_in_days, filepath=filepath ) ) return stats def _module_stats(): graph_from_target, graph_to_target = _create_graph()", "graph_to_target: graph_to_target[n2] = [] graph_to_target[n1].append(n2) return graph_from_target, graph_to_target def _upadate_dependencies(graph, target, stats_per_module): stack", "= change_rate self._all_changes_count = all_changes_count self._latest_changes_count = latest_changes_count self._lifespan_in_days = lifespan_in_days self._filepath =", "in visited: visited.add(child) dependency_counter[current_node] += 1 stack.append([child, iter(graph[child])]) except StopIteration: stack.pop() return dependency_counter", "\\ f'Lifespan: {self._lifespan_in_days}' @classmethod def load_module_stats(cls): stats = [] stats_per_module, dependency_counts = _module_stats()", "for tokens in csv.reader(file): n1 = tokens[0].strip() n2 = tokens[1].strip() if n1 not", "_count_dependencies(graph_to_target) return stats_per_module, dependency_counts def _create_graph(): \"\"\"Creates the reversed dependencies graph. The adjacent", "The name of the module :ivar list _affected_targets: The affected targets. :ivar int", "in the dependency file. :return: The \"in\" dependency graph for the dependencies file.", "def _create_graph(): \"\"\"Creates the reversed dependencies graph. The adjacent edges as the are", "dependency_count: The number of dependencies. \"\"\" def __init__(self, module_name, affected_targets, dependency_count, change_rate, all_changes_count,", "tokens in csv.reader(file): n1 = tokens[0].strip() n2 = tokens[1].strip() if n1 not in", "the targets. This why we are constructing the graph in the opposite direction", "def latest_changes_count(self): return self._latest_changes_count @property def lifespan_in_days(self): return self._lifespan_in_days @property def filepath(self): return", "ch else 'n/a' change_rate = ch.change_rate if ch else 'n/a' all_changes_count = ch.changes_count", "each of the targets. This why we are constructing the graph in the", "'n/a' change_rate = ch.change_rate if ch else 'n/a' all_changes_count = ch.changes_count if ch", "a history of changes for each module and also append to it the", "dependency_count(self): return self._dependency_count @property def change_rate(self): return self._change_rate @property def all_changes_count(self): return self._all_changes_count", "first node as it appears in the dependency file. :return: The \"in\" dependency", "\"\"\"Holds the statistics for a module. :ivar str _module_name: The name of the", "'n/a' latest_changes_count = ch.latest_changes_count if ch else 'n/a' filepath = ch.filepath if ch", "iter_to_children = stack[-1] stats_per_module[parent].add(target) try: child = next(iter_to_children) if child not in visited:", "lifespan_in_days = ch.lifespan_in_days if ch else 'n/a' change_rate = ch.change_rate if ch else", "ModuleStats.load_module_stats(): tokens = [ module.module_name, module.affected_targets, module.dependency_count, module.change_rate, module.all_changes_count, module.latest_changes_count, module.lifespan_in_days ] file.write(','.join(str(t)", "Changes: {self._all_changes_count} ' \\ f'Latest Changes: {self._latest_changes_count} ' \\ f'Lifespan: {self._lifespan_in_days}' @classmethod def", "stats_per_module ) dependency_counts = _count_dependencies(graph_to_target) return stats_per_module, dependency_counts def _create_graph(): \"\"\"Creates the reversed", "graph_from_target[n1] = [] if n2 not in graph_from_target: graph_from_target[n2] = [] graph_from_target[n2].append(n1) if", "Here we need the reversed dependency meaning the \"in\" dependency because the goal", "= stack[-1] try: child = next(children_iter) if child not in visited: visited.add(child) dependency_counter[current_node]", "filepath(self): return self._filepath def __repr__(self): \"\"\"Make debugging easier!\"\"\" return f'{self._module_name}, ' \\ f'Affected", "change_rate(self): return self._change_rate @property def all_changes_count(self): return self._all_changes_count @property def latest_changes_count(self): return self._latest_changes_count", "dependency_counter def export_to_csv(filename): with open(filename, 'w') as file: tokens = [ \"name\", \"targets\",", "module.lifespan_in_days ] file.write(','.join(str(t) for t in tokens)) file.write(\"\\n\") if __name__ == '__main__': export_to_csv(\"change_history.csv\")", "\"\"\"Initializer. :param str module_name: The module name. :param set affected_targets: The affected targets.", "= list(affected_targets) self._dependency_count = dependency_count self._change_rate = change_rate self._all_changes_count = all_changes_count self._latest_changes_count =", "graph_from_target: graph_from_target[n2] = [] graph_from_target[n2].append(n1) if n1 not in graph_to_target: graph_to_target[n1] = []", "self._change_rate @property def all_changes_count(self): return self._all_changes_count @property def latest_changes_count(self): return self._latest_changes_count @property def", "f'Affected targets: {len(self._affected_targets)} ' \\ f'Dependencies: {self._dependency_count} ' \\ f'Change Rate: {self._change_rate} '", "self._latest_changes_count @property def lifespan_in_days(self): return self._lifespan_in_days @property def filepath(self): return self._filepath def __repr__(self):", "direction meaning from the second to the first node as it appears in", "= _module_stats() history = change_history.load_change_history() for module_name, affected_targets in stats_per_module.items(): if module_name not", "module_name not in history: continue ch = history.get(module_name) lifespan_in_days = ch.lifespan_in_days if ch", "tokens[0].strip() n2 = tokens[1].strip() if n1 not in graph_from_target: graph_from_target[n1] = [] if", "if n1 not in graph_from_target: graph_from_target[n1] = [] if n2 not in graph_from_target:", "\"\"\" self._module_name = module_name self._affected_targets = list(affected_targets) self._dependency_count = dependency_count self._change_rate = change_rate", "the reversed dependencies graph. The adjacent edges as the are recorded in the", "list _affected_targets: The affected targets. :ivar int dependency_count: The number of dependencies. \"\"\"", "return self._latest_changes_count @property def lifespan_in_days(self): return self._lifespan_in_days @property def filepath(self): return self._filepath def", "dict \"\"\" graph_from_target = {} graph_to_target = {} with open(settings.dependencies_filename) as file: for", "creating a history of changes for each module and also append to it", "return self._change_rate @property def all_changes_count(self): return self._all_changes_count @property def latest_changes_count(self): return self._latest_changes_count @property", "meaning from the second to the first node as it appears in the", "\"\"\"Exposes a class that holds change statistics for all modules. Using the git", "stack: parent, iter_to_children = stack[-1] stats_per_module[parent].add(target) try: child = next(iter_to_children) if child not", "graph_to_target = _create_graph() stats_per_module = {parent: set() for parent in graph_from_target.keys()} all_targets =", "if ch else 'n/a' all_changes_count = ch.changes_count if ch else 'n/a' latest_changes_count =", "the dependencies file represent an \"out\" relationship between the imported and the importing", "= _count_dependencies(graph_to_target) return stats_per_module, dependency_counts def _create_graph(): \"\"\"Creates the reversed dependencies graph. The", "dependency file. :return: The \"in\" dependency graph for the dependencies file. :rtype: dict", "n2 not in graph_to_target: graph_to_target[n2] = [] graph_to_target[n1].append(n2) return graph_from_target, graph_to_target def _upadate_dependencies(graph,", "stack: parent, children_iter = stack[-1] try: child = next(children_iter) if child not in", "= [] stats_per_module, dependency_counts = _module_stats() history = change_history.load_change_history() for module_name, affected_targets in", "import change_history import settings import targets # Aliases. settings = settings.settings Targets =", "modules. Using the git log we are creating a history of changes for", "\"\"\" import csv import change_history import settings import targets # Aliases. settings =", "__init__(self, module_name, affected_targets, dependency_count, change_rate, all_changes_count, latest_changes_count, lifespan_in_days, filepath): \"\"\"Initializer. :param str module_name:", "The adjacent edges as the are recorded in the dependencies file represent an", "Targets() for target in all_targets.get_all(): _upadate_dependencies( graph_from_target, target.module_name, stats_per_module ) dependency_counts = _count_dependencies(graph_to_target)", "tokens[1].strip() if n1 not in graph_from_target: graph_from_target[n1] = [] if n2 not in", "file represent an \"out\" relationship between the imported and the importing modules. Here", "need the reversed dependency meaning the \"in\" dependency because the goal is to", ":return: The \"in\" dependency graph for the dependencies file. :rtype: dict \"\"\" graph_from_target", "settings import targets # Aliases. settings = settings.settings Targets = targets.Targets class ModuleStats:", "it the number of target dependencies. \"\"\" import csv import change_history import settings", "' \\ f'Lifespan: {self._lifespan_in_days}' @classmethod def load_module_stats(cls): stats = [] stats_per_module, dependency_counts =", "= set() visited.add(target) while stack: parent, iter_to_children = stack[-1] stats_per_module[parent].add(target) try: child =", "in all_targets.get_all(): _upadate_dependencies( graph_from_target, target.module_name, stats_per_module ) dependency_counts = _count_dependencies(graph_to_target) return stats_per_module, dependency_counts", "The module name. :param set affected_targets: The affected targets. \"\"\" self._module_name = module_name", "the module :ivar list _affected_targets: The affected targets. :ivar int dependency_count: The number", "\"out\" relationship between the imported and the importing modules. Here we need the", "\"\"\"Creates the reversed dependencies graph. The adjacent edges as the are recorded in", "dependencies. \"\"\" def __init__(self, module_name, affected_targets, dependency_count, change_rate, all_changes_count, latest_changes_count, lifespan_in_days, filepath): \"\"\"Initializer.", "graph for the dependencies file. :rtype: dict \"\"\" graph_from_target = {} graph_to_target =", "in graph_from_target: graph_from_target[n1] = [] if n2 not in graph_from_target: graph_from_target[n2] = []", "for all modules. Using the git log we are creating a history of", "The \"in\" dependency graph for the dependencies file. :rtype: dict \"\"\" graph_from_target =", "_count_dependencies(graph): \"\"\"Assigns the total number of dependencies to each node.\"\"\" dependency_counter = {parent:", "affected_targets=affected_targets, dependency_count=dependency_counts[module_name], change_rate=change_rate, all_changes_count=all_changes_count, latest_changes_count=latest_changes_count, lifespan_in_days=lifespan_in_days, filepath=filepath ) ) return stats def _module_stats():", "lifespan_in_days=lifespan_in_days, filepath=filepath ) ) return stats def _module_stats(): graph_from_target, graph_to_target = _create_graph() stats_per_module", "if n2 not in graph_from_target: graph_from_target[n2] = [] graph_from_target[n2].append(n1) if n1 not in", "and the importing modules. Here we need the reversed dependency meaning the \"in\"", "def all_changes_count(self): return self._all_changes_count @property def latest_changes_count(self): return self._latest_changes_count @property def lifespan_in_days(self): return", "and also append to it the number of target dependencies. \"\"\" import csv", "are creating a history of changes for each module and also append to", ") dependency_counts = _count_dependencies(graph_to_target) return stats_per_module, dependency_counts def _create_graph(): \"\"\"Creates the reversed dependencies", "target dependencies. \"\"\" import csv import change_history import settings import targets # Aliases.", "{len(self._affected_targets)} ' \\ f'Dependencies: {self._dependency_count} ' \\ f'Change Rate: {self._change_rate} ' \\ f'Total", "<filename>server/module_stats.py \"\"\"Exposes a class that holds change statistics for all modules. Using the", "set() for parent in graph_from_target.keys()} all_targets = Targets() for target in all_targets.get_all(): _upadate_dependencies(", "number of dependencies to each node.\"\"\" dependency_counter = {parent: 0 for parent in", "= dependency_count self._change_rate = change_rate self._all_changes_count = all_changes_count self._latest_changes_count = latest_changes_count self._lifespan_in_days =", "stats def _module_stats(): graph_from_target, graph_to_target = _create_graph() stats_per_module = {parent: set() for parent", "module_name: The module name. :param set affected_targets: The affected targets. \"\"\" self._module_name =", "tokens = [ \"name\", \"targets\", \"dependencies\", \"change-rate\", \"all-changes\", \"latest-changes\", \"lifespan-in-days\" ] file.write(','.join(tokens)) file.write(\"\\n\")", "for each module and also append to it the number of target dependencies.", "for current_node in graph: stack = [[current_node, iter(graph[current_node])]] visited = set() visited.add(current_node) while", "not in graph_from_target: graph_from_target[n2] = [] graph_from_target[n2].append(n1) if n1 not in graph_to_target: graph_to_target[n1]", "module and also append to it the number of target dependencies. \"\"\" import", "def module_name(self): return self._module_name @property def affected_targets(self): return len(self._affected_targets) @property def dependency_count(self): return", "affected targets. \"\"\" self._module_name = module_name self._affected_targets = list(affected_targets) self._dependency_count = dependency_count self._change_rate", "parent in graph_from_target.keys()} all_targets = Targets() for target in all_targets.get_all(): _upadate_dependencies( graph_from_target, target.module_name,", "# Aliases. settings = settings.settings Targets = targets.Targets class ModuleStats: \"\"\"Holds the statistics", "module.module_name, module.affected_targets, module.dependency_count, module.change_rate, module.all_changes_count, module.latest_changes_count, module.lifespan_in_days ] file.write(','.join(str(t) for t in tokens))", "[] stats_per_module, dependency_counts = _module_stats() history = change_history.load_change_history() for module_name, affected_targets in stats_per_module.items():", "except StopIteration: stack.pop() return dependency_counter def export_to_csv(filename): with open(filename, 'w') as file: tokens", "imported and the importing modules. Here we need the reversed dependency meaning the", "child not in visited: stack.append((child, iter(graph[child]))) visited.add(child) except StopIteration: stack.pop() def _count_dependencies(graph): \"\"\"Assigns", "dependencies file. :rtype: dict \"\"\" graph_from_target = {} graph_to_target = {} with open(settings.dependencies_filename)", "n2 = tokens[1].strip() if n1 not in graph_from_target: graph_from_target[n1] = [] if n2", "how each module affects each of the targets. This why we are constructing", "_create_graph() stats_per_module = {parent: set() for parent in graph_from_target.keys()} all_targets = Targets() for", "stats = [] stats_per_module, dependency_counts = _module_stats() history = change_history.load_change_history() for module_name, affected_targets", "= {parent: set() for parent in graph_from_target.keys()} all_targets = Targets() for target in", ":rtype: dict \"\"\" graph_from_target = {} graph_to_target = {} with open(settings.dependencies_filename) as file:", "latest_changes_count self._lifespan_in_days = lifespan_in_days self._filepath = filepath @property def module_name(self): return self._module_name @property", "filepath): \"\"\"Initializer. :param str module_name: The module name. :param set affected_targets: The affected", "if module_name not in history: continue ch = history.get(module_name) lifespan_in_days = ch.lifespan_in_days if", "from the second to the first node as it appears in the dependency", "all_targets.get_all(): _upadate_dependencies( graph_from_target, target.module_name, stats_per_module ) dependency_counts = _count_dependencies(graph_to_target) return stats_per_module, dependency_counts def", "f'{self._module_name}, ' \\ f'Affected targets: {len(self._affected_targets)} ' \\ f'Dependencies: {self._dependency_count} ' \\ f'Change", "file: for tokens in csv.reader(file): n1 = tokens[0].strip() n2 = tokens[1].strip() if n1", "{self._dependency_count} ' \\ f'Change Rate: {self._change_rate} ' \\ f'Total Changes: {self._all_changes_count} ' \\", "if n2 not in graph_to_target: graph_to_target[n2] = [] graph_to_target[n1].append(n2) return graph_from_target, graph_to_target def", "def _count_dependencies(graph): \"\"\"Assigns the total number of dependencies to each node.\"\"\" dependency_counter =", "= set() visited.add(current_node) while stack: parent, children_iter = stack[-1] try: child = next(children_iter)", "module.all_changes_count, module.latest_changes_count, module.lifespan_in_days ] file.write(','.join(str(t) for t in tokens)) file.write(\"\\n\") if __name__ ==", "node.\"\"\" dependency_counter = {parent: 0 for parent in graph} for current_node in graph:", "return f'{self._module_name}, ' \\ f'Affected targets: {len(self._affected_targets)} ' \\ f'Dependencies: {self._dependency_count} ' \\", "module :ivar list _affected_targets: The affected targets. :ivar int dependency_count: The number of", "stack = [[current_node, iter(graph[current_node])]] visited = set() visited.add(current_node) while stack: parent, children_iter =", "@property def all_changes_count(self): return self._all_changes_count @property def latest_changes_count(self): return self._latest_changes_count @property def lifespan_in_days(self):", "recorded in the dependencies file represent an \"out\" relationship between the imported and", "{self._lifespan_in_days}' @classmethod def load_module_stats(cls): stats = [] stats_per_module, dependency_counts = _module_stats() history =", "parent, children_iter = stack[-1] try: child = next(children_iter) if child not in visited:", "are constructing the graph in the opposite direction meaning from the second to", "@classmethod def load_module_stats(cls): stats = [] stats_per_module, dependency_counts = _module_stats() history = change_history.load_change_history()", "each module and also append to it the number of target dependencies. \"\"\"", "module_name=module_name, affected_targets=affected_targets, dependency_count=dependency_counts[module_name], change_rate=change_rate, all_changes_count=all_changes_count, latest_changes_count=latest_changes_count, lifespan_in_days=lifespan_in_days, filepath=filepath ) ) return stats def", "graph_to_target = {} with open(settings.dependencies_filename) as file: for tokens in csv.reader(file): n1 =", "iter(graph[target]))] stats_per_module[target].add(target) visited = set() visited.add(target) while stack: parent, iter_to_children = stack[-1] stats_per_module[parent].add(target)", "ModuleStats: \"\"\"Holds the statistics for a module. :ivar str _module_name: The name of", "\"targets\", \"dependencies\", \"change-rate\", \"all-changes\", \"latest-changes\", \"lifespan-in-days\" ] file.write(','.join(tokens)) file.write(\"\\n\") for module in ModuleStats.load_module_stats():", "def filepath(self): return self._filepath def __repr__(self): \"\"\"Make debugging easier!\"\"\" return f'{self._module_name}, ' \\", "file.write(\"\\n\") for module in ModuleStats.load_module_stats(): tokens = [ module.module_name, module.affected_targets, module.dependency_count, module.change_rate, module.all_changes_count,", "graph_from_target, graph_to_target def _upadate_dependencies(graph, target, stats_per_module): stack = [(target, iter(graph[target]))] stats_per_module[target].add(target) visited =", "self._dependency_count @property def change_rate(self): return self._change_rate @property def all_changes_count(self): return self._all_changes_count @property def", "= {} with open(settings.dependencies_filename) as file: for tokens in csv.reader(file): n1 = tokens[0].strip()", "module_name self._affected_targets = list(affected_targets) self._dependency_count = dependency_count self._change_rate = change_rate self._all_changes_count = all_changes_count", "iter(graph[child])]) except StopIteration: stack.pop() return dependency_counter def export_to_csv(filename): with open(filename, 'w') as file:", "with open(filename, 'w') as file: tokens = [ \"name\", \"targets\", \"dependencies\", \"change-rate\", \"all-changes\",", "continue ch = history.get(module_name) lifespan_in_days = ch.lifespan_in_days if ch else 'n/a' change_rate =", "change_rate = ch.change_rate if ch else 'n/a' all_changes_count = ch.changes_count if ch else", "else 'n/a' filepath = ch.filepath if ch else 'n/a' stats.append( cls( module_name=module_name, affected_targets=affected_targets,", "stack[-1] stats_per_module[parent].add(target) try: child = next(iter_to_children) if child not in visited: stack.append((child, iter(graph[child])))", "graph. The adjacent edges as the are recorded in the dependencies file represent", "def export_to_csv(filename): with open(filename, 'w') as file: tokens = [ \"name\", \"targets\", \"dependencies\",", "= module_name self._affected_targets = list(affected_targets) self._dependency_count = dependency_count self._change_rate = change_rate self._all_changes_count =", "of changes for each module and also append to it the number of", "stats_per_module = {parent: set() for parent in graph_from_target.keys()} all_targets = Targets() for target", "dependencies graph. The adjacent edges as the are recorded in the dependencies file", "self._all_changes_count @property def latest_changes_count(self): return self._latest_changes_count @property def lifespan_in_days(self): return self._lifespan_in_days @property def", "affected_targets(self): return len(self._affected_targets) @property def dependency_count(self): return self._dependency_count @property def change_rate(self): return self._change_rate", "history.get(module_name) lifespan_in_days = ch.lifespan_in_days if ch else 'n/a' change_rate = ch.change_rate if ch", "with open(settings.dependencies_filename) as file: for tokens in csv.reader(file): n1 = tokens[0].strip() n2 =", "as the are recorded in the dependencies file represent an \"out\" relationship between", "change_rate=change_rate, all_changes_count=all_changes_count, latest_changes_count=latest_changes_count, lifespan_in_days=lifespan_in_days, filepath=filepath ) ) return stats def _module_stats(): graph_from_target, graph_to_target", "easier!\"\"\" return f'{self._module_name}, ' \\ f'Affected targets: {len(self._affected_targets)} ' \\ f'Dependencies: {self._dependency_count} '", ":ivar str _module_name: The name of the module :ivar list _affected_targets: The affected", "dependencies file represent an \"out\" relationship between the imported and the importing modules.", "dependency because the goal is to discover how each module affects each of", "= ch.changes_count if ch else 'n/a' latest_changes_count = ch.latest_changes_count if ch else 'n/a'", "\"dependencies\", \"change-rate\", \"all-changes\", \"latest-changes\", \"lifespan-in-days\" ] file.write(','.join(tokens)) file.write(\"\\n\") for module in ModuleStats.load_module_stats(): tokens", "we are creating a history of changes for each module and also append", "StopIteration: stack.pop() return dependency_counter def export_to_csv(filename): with open(filename, 'w') as file: tokens =", "child = next(children_iter) if child not in visited: visited.add(child) dependency_counter[current_node] += 1 stack.append([child,", "graph_from_target, graph_to_target = _create_graph() stats_per_module = {parent: set() for parent in graph_from_target.keys()} all_targets", "{self._change_rate} ' \\ f'Total Changes: {self._all_changes_count} ' \\ f'Latest Changes: {self._latest_changes_count} ' \\", "in graph_from_target.keys()} all_targets = Targets() for target in all_targets.get_all(): _upadate_dependencies( graph_from_target, target.module_name, stats_per_module", "a module. :ivar str _module_name: The name of the module :ivar list _affected_targets:", "graph: stack = [[current_node, iter(graph[current_node])]] visited = set() visited.add(current_node) while stack: parent, children_iter", "stack.pop() def _count_dependencies(graph): \"\"\"Assigns the total number of dependencies to each node.\"\"\" dependency_counter", "module. :ivar str _module_name: The name of the module :ivar list _affected_targets: The", "f'Change Rate: {self._change_rate} ' \\ f'Total Changes: {self._all_changes_count} ' \\ f'Latest Changes: {self._latest_changes_count}", ") return stats def _module_stats(): graph_from_target, graph_to_target = _create_graph() stats_per_module = {parent: set()", "] file.write(','.join(tokens)) file.write(\"\\n\") for module in ModuleStats.load_module_stats(): tokens = [ module.module_name, module.affected_targets, module.dependency_count,", "Targets = targets.Targets class ModuleStats: \"\"\"Holds the statistics for a module. :ivar str", "str module_name: The module name. :param set affected_targets: The affected targets. \"\"\" self._module_name", "all_changes_count(self): return self._all_changes_count @property def latest_changes_count(self): return self._latest_changes_count @property def lifespan_in_days(self): return self._lifespan_in_days", "import settings import targets # Aliases. settings = settings.settings Targets = targets.Targets class", "represent an \"out\" relationship between the imported and the importing modules. Here we", "ch else 'n/a' latest_changes_count = ch.latest_changes_count if ch else 'n/a' filepath = ch.filepath", "n1 not in graph_from_target: graph_from_target[n1] = [] if n2 not in graph_from_target: graph_from_target[n2]", "for module in ModuleStats.load_module_stats(): tokens = [ module.module_name, module.affected_targets, module.dependency_count, module.change_rate, module.all_changes_count, module.latest_changes_count,", "in graph_from_target: graph_from_target[n2] = [] graph_from_target[n2].append(n1) if n1 not in graph_to_target: graph_to_target[n1] =", "graph_to_target: graph_to_target[n1] = [] if n2 not in graph_to_target: graph_to_target[n2] = [] graph_to_target[n1].append(n2)", "child = next(iter_to_children) if child not in visited: stack.append((child, iter(graph[child]))) visited.add(child) except StopIteration:", "\\ f'Dependencies: {self._dependency_count} ' \\ f'Change Rate: {self._change_rate} ' \\ f'Total Changes: {self._all_changes_count}", "of target dependencies. \"\"\" import csv import change_history import settings import targets #", "{parent: set() for parent in graph_from_target.keys()} all_targets = Targets() for target in all_targets.get_all():", "_create_graph(): \"\"\"Creates the reversed dependencies graph. The adjacent edges as the are recorded", "the imported and the importing modules. Here we need the reversed dependency meaning", "self._all_changes_count = all_changes_count self._latest_changes_count = latest_changes_count self._lifespan_in_days = lifespan_in_days self._filepath = filepath @property", "dependency graph for the dependencies file. :rtype: dict \"\"\" graph_from_target = {} graph_to_target", "change statistics for all modules. Using the git log we are creating a", "number of dependencies. \"\"\" def __init__(self, module_name, affected_targets, dependency_count, change_rate, all_changes_count, latest_changes_count, lifespan_in_days,", "edges as the are recorded in the dependencies file represent an \"out\" relationship", "stats_per_module.items(): if module_name not in history: continue ch = history.get(module_name) lifespan_in_days = ch.lifespan_in_days", "in history: continue ch = history.get(module_name) lifespan_in_days = ch.lifespan_in_days if ch else 'n/a'", "dependency_count=dependency_counts[module_name], change_rate=change_rate, all_changes_count=all_changes_count, latest_changes_count=latest_changes_count, lifespan_in_days=lifespan_in_days, filepath=filepath ) ) return stats def _module_stats(): graph_from_target,", "\"\"\" graph_from_target = {} graph_to_target = {} with open(settings.dependencies_filename) as file: for tokens", "visited: stack.append((child, iter(graph[child]))) visited.add(child) except StopIteration: stack.pop() def _count_dependencies(graph): \"\"\"Assigns the total number", "of the module :ivar list _affected_targets: The affected targets. :ivar int dependency_count: The", "_module_name: The name of the module :ivar list _affected_targets: The affected targets. :ivar", "list(affected_targets) self._dependency_count = dependency_count self._change_rate = change_rate self._all_changes_count = all_changes_count self._latest_changes_count = latest_changes_count", "@property def dependency_count(self): return self._dependency_count @property def change_rate(self): return self._change_rate @property def all_changes_count(self):", "{} graph_to_target = {} with open(settings.dependencies_filename) as file: for tokens in csv.reader(file): n1", "graph_to_target[n1] = [] if n2 not in graph_to_target: graph_to_target[n2] = [] graph_to_target[n1].append(n2) return", ":ivar int dependency_count: The number of dependencies. \"\"\" def __init__(self, module_name, affected_targets, dependency_count,", "ch.latest_changes_count if ch else 'n/a' filepath = ch.filepath if ch else 'n/a' stats.append(", "{self._all_changes_count} ' \\ f'Latest Changes: {self._latest_changes_count} ' \\ f'Lifespan: {self._lifespan_in_days}' @classmethod def load_module_stats(cls):", "graph_to_target[n1].append(n2) return graph_from_target, graph_to_target def _upadate_dependencies(graph, target, stats_per_module): stack = [(target, iter(graph[target]))] stats_per_module[target].add(target)", ") ) return stats def _module_stats(): graph_from_target, graph_to_target = _create_graph() stats_per_module = {parent:", "are recorded in the dependencies file represent an \"out\" relationship between the imported", "import targets # Aliases. settings = settings.settings Targets = targets.Targets class ModuleStats: \"\"\"Holds", "change_rate self._all_changes_count = all_changes_count self._latest_changes_count = latest_changes_count self._lifespan_in_days = lifespan_in_days self._filepath = filepath", "else 'n/a' change_rate = ch.change_rate if ch else 'n/a' all_changes_count = ch.changes_count if", "history of changes for each module and also append to it the number", "we are constructing the graph in the opposite direction meaning from the second", "@property def filepath(self): return self._filepath def __repr__(self): \"\"\"Make debugging easier!\"\"\" return f'{self._module_name}, '", "as file: for tokens in csv.reader(file): n1 = tokens[0].strip() n2 = tokens[1].strip() if", "in stats_per_module.items(): if module_name not in history: continue ch = history.get(module_name) lifespan_in_days =", "targets: {len(self._affected_targets)} ' \\ f'Dependencies: {self._dependency_count} ' \\ f'Change Rate: {self._change_rate} ' \\", "This why we are constructing the graph in the opposite direction meaning from", "if child not in visited: stack.append((child, iter(graph[child]))) visited.add(child) except StopIteration: stack.pop() def _count_dependencies(graph):", "opposite direction meaning from the second to the first node as it appears", "statistics for a module. :ivar str _module_name: The name of the module :ivar", "= latest_changes_count self._lifespan_in_days = lifespan_in_days self._filepath = filepath @property def module_name(self): return self._module_name", "affected_targets, dependency_count, change_rate, all_changes_count, latest_changes_count, lifespan_in_days, filepath): \"\"\"Initializer. :param str module_name: The module", "\"all-changes\", \"latest-changes\", \"lifespan-in-days\" ] file.write(','.join(tokens)) file.write(\"\\n\") for module in ModuleStats.load_module_stats(): tokens = [", "if ch else 'n/a' filepath = ch.filepath if ch else 'n/a' stats.append( cls(", "_module_stats(): graph_from_target, graph_to_target = _create_graph() stats_per_module = {parent: set() for parent in graph_from_target.keys()}", "dependency_counts def _create_graph(): \"\"\"Creates the reversed dependencies graph. The adjacent edges as the", "the git log we are creating a history of changes for each module", "holds change statistics for all modules. Using the git log we are creating", "ch.lifespan_in_days if ch else 'n/a' change_rate = ch.change_rate if ch else 'n/a' all_changes_count", "name. :param set affected_targets: The affected targets. \"\"\" self._module_name = module_name self._affected_targets =", "graph_from_target: graph_from_target[n1] = [] if n2 not in graph_from_target: graph_from_target[n2] = [] graph_from_target[n2].append(n1)", "[] graph_from_target[n2].append(n1) if n1 not in graph_to_target: graph_to_target[n1] = [] if n2 not", "The affected targets. :ivar int dependency_count: The number of dependencies. \"\"\" def __init__(self,", "module affects each of the targets. This why we are constructing the graph", "relationship between the imported and the importing modules. Here we need the reversed", "visited.add(child) except StopIteration: stack.pop() def _count_dependencies(graph): \"\"\"Assigns the total number of dependencies to", "of dependencies. \"\"\" def __init__(self, module_name, affected_targets, dependency_count, change_rate, all_changes_count, latest_changes_count, lifespan_in_days, filepath):", "graph in the opposite direction meaning from the second to the first node", "module_name, affected_targets, dependency_count, change_rate, all_changes_count, latest_changes_count, lifespan_in_days, filepath): \"\"\"Initializer. :param str module_name: The", "\"\"\"Assigns the total number of dependencies to each node.\"\"\" dependency_counter = {parent: 0", "self._latest_changes_count = latest_changes_count self._lifespan_in_days = lifespan_in_days self._filepath = filepath @property def module_name(self): return", "if child not in visited: visited.add(child) dependency_counter[current_node] += 1 stack.append([child, iter(graph[child])]) except StopIteration:", "[ \"name\", \"targets\", \"dependencies\", \"change-rate\", \"all-changes\", \"latest-changes\", \"lifespan-in-days\" ] file.write(','.join(tokens)) file.write(\"\\n\") for module", "Using the git log we are creating a history of changes for each", "in visited: stack.append((child, iter(graph[child]))) visited.add(child) except StopIteration: stack.pop() def _count_dependencies(graph): \"\"\"Assigns the total", "return self._module_name @property def affected_targets(self): return len(self._affected_targets) @property def dependency_count(self): return self._dependency_count @property", "if n1 not in graph_to_target: graph_to_target[n1] = [] if n2 not in graph_to_target:", "cls( module_name=module_name, affected_targets=affected_targets, dependency_count=dependency_counts[module_name], change_rate=change_rate, all_changes_count=all_changes_count, latest_changes_count=latest_changes_count, lifespan_in_days=lifespan_in_days, filepath=filepath ) ) return stats", "module name. :param set affected_targets: The affected targets. \"\"\" self._module_name = module_name self._affected_targets", "an \"out\" relationship between the imported and the importing modules. Here we need", "dependency_count, change_rate, all_changes_count, latest_changes_count, lifespan_in_days, filepath): \"\"\"Initializer. :param str module_name: The module name.", "= all_changes_count self._latest_changes_count = latest_changes_count self._lifespan_in_days = lifespan_in_days self._filepath = filepath @property def", "self._module_name = module_name self._affected_targets = list(affected_targets) self._dependency_count = dependency_count self._change_rate = change_rate self._all_changes_count", "= {parent: 0 for parent in graph} for current_node in graph: stack =", "in graph_to_target: graph_to_target[n1] = [] if n2 not in graph_to_target: graph_to_target[n2] = []", "graph_from_target[n2].append(n1) if n1 not in graph_to_target: graph_to_target[n1] = [] if n2 not in", "file.write(','.join(tokens)) file.write(\"\\n\") for module in ModuleStats.load_module_stats(): tokens = [ module.module_name, module.affected_targets, module.dependency_count, module.change_rate,", "all_changes_count = ch.changes_count if ch else 'n/a' latest_changes_count = ch.latest_changes_count if ch else", "not in history: continue ch = history.get(module_name) lifespan_in_days = ch.lifespan_in_days if ch else", "affected_targets: The affected targets. \"\"\" self._module_name = module_name self._affected_targets = list(affected_targets) self._dependency_count =", "is to discover how each module affects each of the targets. This why", "ch.changes_count if ch else 'n/a' latest_changes_count = ch.latest_changes_count if ch else 'n/a' filepath", "constructing the graph in the opposite direction meaning from the second to the", "the \"in\" dependency because the goal is to discover how each module affects", "modules. Here we need the reversed dependency meaning the \"in\" dependency because the", "\"\"\"Make debugging easier!\"\"\" return f'{self._module_name}, ' \\ f'Affected targets: {len(self._affected_targets)} ' \\ f'Dependencies:", "[] if n2 not in graph_to_target: graph_to_target[n2] = [] graph_to_target[n1].append(n2) return graph_from_target, graph_to_target", "discover how each module affects each of the targets. This why we are", "n1 = tokens[0].strip() n2 = tokens[1].strip() if n1 not in graph_from_target: graph_from_target[n1] =", "not in graph_to_target: graph_to_target[n1] = [] if n2 not in graph_to_target: graph_to_target[n2] =", "dependency_counts = _module_stats() history = change_history.load_change_history() for module_name, affected_targets in stats_per_module.items(): if module_name", "return graph_from_target, graph_to_target def _upadate_dependencies(graph, target, stats_per_module): stack = [(target, iter(graph[target]))] stats_per_module[target].add(target) visited", "= Targets() for target in all_targets.get_all(): _upadate_dependencies( graph_from_target, target.module_name, stats_per_module ) dependency_counts =", "ch.filepath if ch else 'n/a' stats.append( cls( module_name=module_name, affected_targets=affected_targets, dependency_count=dependency_counts[module_name], change_rate=change_rate, all_changes_count=all_changes_count, latest_changes_count=latest_changes_count,", "visited: visited.add(child) dependency_counter[current_node] += 1 stack.append([child, iter(graph[child])]) except StopIteration: stack.pop() return dependency_counter def", "change_history import settings import targets # Aliases. settings = settings.settings Targets = targets.Targets", "\"latest-changes\", \"lifespan-in-days\" ] file.write(','.join(tokens)) file.write(\"\\n\") for module in ModuleStats.load_module_stats(): tokens = [ module.module_name,", "def __init__(self, module_name, affected_targets, dependency_count, change_rate, all_changes_count, latest_changes_count, lifespan_in_days, filepath): \"\"\"Initializer. :param str", "parent in graph} for current_node in graph: stack = [[current_node, iter(graph[current_node])]] visited =", "in graph_to_target: graph_to_target[n2] = [] graph_to_target[n1].append(n2) return graph_from_target, graph_to_target def _upadate_dependencies(graph, target, stats_per_module):", "def __repr__(self): \"\"\"Make debugging easier!\"\"\" return f'{self._module_name}, ' \\ f'Affected targets: {len(self._affected_targets)} '", "visited.add(target) while stack: parent, iter_to_children = stack[-1] stats_per_module[parent].add(target) try: child = next(iter_to_children) if", "file: tokens = [ \"name\", \"targets\", \"dependencies\", \"change-rate\", \"all-changes\", \"latest-changes\", \"lifespan-in-days\" ] file.write(','.join(tokens))", "def affected_targets(self): return len(self._affected_targets) @property def dependency_count(self): return self._dependency_count @property def change_rate(self): return", "'n/a' all_changes_count = ch.changes_count if ch else 'n/a' latest_changes_count = ch.latest_changes_count if ch", "try: child = next(children_iter) if child not in visited: visited.add(child) dependency_counter[current_node] += 1", "reversed dependency meaning the \"in\" dependency because the goal is to discover how", "stats_per_module, dependency_counts def _create_graph(): \"\"\"Creates the reversed dependencies graph. The adjacent edges as", "\"change-rate\", \"all-changes\", \"latest-changes\", \"lifespan-in-days\" ] file.write(','.join(tokens)) file.write(\"\\n\") for module in ModuleStats.load_module_stats(): tokens =", "else 'n/a' stats.append( cls( module_name=module_name, affected_targets=affected_targets, dependency_count=dependency_counts[module_name], change_rate=change_rate, all_changes_count=all_changes_count, latest_changes_count=latest_changes_count, lifespan_in_days=lifespan_in_days, filepath=filepath )", "_upadate_dependencies( graph_from_target, target.module_name, stats_per_module ) dependency_counts = _count_dependencies(graph_to_target) return stats_per_module, dependency_counts def _create_graph():", "in csv.reader(file): n1 = tokens[0].strip() n2 = tokens[1].strip() if n1 not in graph_from_target:", "to each node.\"\"\" dependency_counter = {parent: 0 for parent in graph} for current_node", "dependency_counter[current_node] += 1 stack.append([child, iter(graph[child])]) except StopIteration: stack.pop() return dependency_counter def export_to_csv(filename): with", "except StopIteration: stack.pop() def _count_dependencies(graph): \"\"\"Assigns the total number of dependencies to each", "visited.add(child) dependency_counter[current_node] += 1 stack.append([child, iter(graph[child])]) except StopIteration: stack.pop() return dependency_counter def export_to_csv(filename):", "return stats_per_module, dependency_counts def _create_graph(): \"\"\"Creates the reversed dependencies graph. The adjacent edges", "dependencies. \"\"\" import csv import change_history import settings import targets # Aliases. settings", "def load_module_stats(cls): stats = [] stats_per_module, dependency_counts = _module_stats() history = change_history.load_change_history() for", "= [] if n2 not in graph_from_target: graph_from_target[n2] = [] graph_from_target[n2].append(n1) if n1", "stats_per_module[target].add(target) visited = set() visited.add(target) while stack: parent, iter_to_children = stack[-1] stats_per_module[parent].add(target) try:", "if ch else 'n/a' stats.append( cls( module_name=module_name, affected_targets=affected_targets, dependency_count=dependency_counts[module_name], change_rate=change_rate, all_changes_count=all_changes_count, latest_changes_count=latest_changes_count, lifespan_in_days=lifespan_in_days,", "graph_to_target[n2] = [] graph_to_target[n1].append(n2) return graph_from_target, graph_to_target def _upadate_dependencies(graph, target, stats_per_module): stack =", "also append to it the number of target dependencies. \"\"\" import csv import", "iter(graph[current_node])]] visited = set() visited.add(current_node) while stack: parent, children_iter = stack[-1] try: child", "the opposite direction meaning from the second to the first node as it", "current_node in graph: stack = [[current_node, iter(graph[current_node])]] visited = set() visited.add(current_node) while stack:", "all modules. Using the git log we are creating a history of changes", "self._affected_targets = list(affected_targets) self._dependency_count = dependency_count self._change_rate = change_rate self._all_changes_count = all_changes_count self._latest_changes_count", "open(filename, 'w') as file: tokens = [ \"name\", \"targets\", \"dependencies\", \"change-rate\", \"all-changes\", \"latest-changes\",", "in the opposite direction meaning from the second to the first node as", "targets. :ivar int dependency_count: The number of dependencies. \"\"\" def __init__(self, module_name, affected_targets,", "__repr__(self): \"\"\"Make debugging easier!\"\"\" return f'{self._module_name}, ' \\ f'Affected targets: {len(self._affected_targets)} ' \\", "def _upadate_dependencies(graph, target, stats_per_module): stack = [(target, iter(graph[target]))] stats_per_module[target].add(target) visited = set() visited.add(target)", "the first node as it appears in the dependency file. :return: The \"in\"", "{parent: 0 for parent in graph} for current_node in graph: stack = [[current_node,", "stack.append([child, iter(graph[child])]) except StopIteration: stack.pop() return dependency_counter def export_to_csv(filename): with open(filename, 'w') as", "[[current_node, iter(graph[current_node])]] visited = set() visited.add(current_node) while stack: parent, children_iter = stack[-1] try:", "target.module_name, stats_per_module ) dependency_counts = _count_dependencies(graph_to_target) return stats_per_module, dependency_counts def _create_graph(): \"\"\"Creates the", "[(target, iter(graph[target]))] stats_per_module[target].add(target) visited = set() visited.add(target) while stack: parent, iter_to_children = stack[-1]", "latest_changes_count(self): return self._latest_changes_count @property def lifespan_in_days(self): return self._lifespan_in_days @property def filepath(self): return self._filepath", "because the goal is to discover how each module affects each of the", "visited.add(current_node) while stack: parent, children_iter = stack[-1] try: child = next(children_iter) if child", "= _create_graph() stats_per_module = {parent: set() for parent in graph_from_target.keys()} all_targets = Targets()", "not in visited: visited.add(child) dependency_counter[current_node] += 1 stack.append([child, iter(graph[child])]) except StopIteration: stack.pop() return", "total number of dependencies to each node.\"\"\" dependency_counter = {parent: 0 for parent", "ch else 'n/a' all_changes_count = ch.changes_count if ch else 'n/a' latest_changes_count = ch.latest_changes_count", "dependencies to each node.\"\"\" dependency_counter = {parent: 0 for parent in graph} for", "graph_from_target.keys()} all_targets = Targets() for target in all_targets.get_all(): _upadate_dependencies( graph_from_target, target.module_name, stats_per_module )", "we need the reversed dependency meaning the \"in\" dependency because the goal is", "= ch.lifespan_in_days if ch else 'n/a' change_rate = ch.change_rate if ch else 'n/a'", "not in visited: stack.append((child, iter(graph[child]))) visited.add(child) except StopIteration: stack.pop() def _count_dependencies(graph): \"\"\"Assigns the", "next(iter_to_children) if child not in visited: stack.append((child, iter(graph[child]))) visited.add(child) except StopIteration: stack.pop() def", "module_name, affected_targets in stats_per_module.items(): if module_name not in history: continue ch = history.get(module_name)", "importing modules. Here we need the reversed dependency meaning the \"in\" dependency because", "= history.get(module_name) lifespan_in_days = ch.lifespan_in_days if ch else 'n/a' change_rate = ch.change_rate if", "adjacent edges as the are recorded in the dependencies file represent an \"out\"", "change_history.load_change_history() for module_name, affected_targets in stats_per_module.items(): if module_name not in history: continue ch", "= change_history.load_change_history() for module_name, affected_targets in stats_per_module.items(): if module_name not in history: continue", "if ch else 'n/a' change_rate = ch.change_rate if ch else 'n/a' all_changes_count =", "\\ f'Latest Changes: {self._latest_changes_count} ' \\ f'Lifespan: {self._lifespan_in_days}' @classmethod def load_module_stats(cls): stats =", "stats.append( cls( module_name=module_name, affected_targets=affected_targets, dependency_count=dependency_counts[module_name], change_rate=change_rate, all_changes_count=all_changes_count, latest_changes_count=latest_changes_count, lifespan_in_days=lifespan_in_days, filepath=filepath ) ) return", "file. :rtype: dict \"\"\" graph_from_target = {} graph_to_target = {} with open(settings.dependencies_filename) as", "each node.\"\"\" dependency_counter = {parent: 0 for parent in graph} for current_node in", "def _module_stats(): graph_from_target, graph_to_target = _create_graph() stats_per_module = {parent: set() for parent in", "stack = [(target, iter(graph[target]))] stats_per_module[target].add(target) visited = set() visited.add(target) while stack: parent, iter_to_children", "\\ f'Change Rate: {self._change_rate} ' \\ f'Total Changes: {self._all_changes_count} ' \\ f'Latest Changes:", "the second to the first node as it appears in the dependency file.", "'n/a' filepath = ch.filepath if ch else 'n/a' stats.append( cls( module_name=module_name, affected_targets=affected_targets, dependency_count=dependency_counts[module_name],", "\"in\" dependency graph for the dependencies file. :rtype: dict \"\"\" graph_from_target = {}", "second to the first node as it appears in the dependency file. :return:", "target in all_targets.get_all(): _upadate_dependencies( graph_from_target, target.module_name, stats_per_module ) dependency_counts = _count_dependencies(graph_to_target) return stats_per_module,", "module.change_rate, module.all_changes_count, module.latest_changes_count, module.lifespan_in_days ] file.write(','.join(str(t) for t in tokens)) file.write(\"\\n\") if __name__", "csv import change_history import settings import targets # Aliases. settings = settings.settings Targets", "f'Total Changes: {self._all_changes_count} ' \\ f'Latest Changes: {self._latest_changes_count} ' \\ f'Lifespan: {self._lifespan_in_days}' @classmethod", "export_to_csv(filename): with open(filename, 'w') as file: tokens = [ \"name\", \"targets\", \"dependencies\", \"change-rate\",", "lifespan_in_days(self): return self._lifespan_in_days @property def filepath(self): return self._filepath def __repr__(self): \"\"\"Make debugging easier!\"\"\"", "= tokens[1].strip() if n1 not in graph_from_target: graph_from_target[n1] = [] if n2 not", "the dependency file. :return: The \"in\" dependency graph for the dependencies file. :rtype:", "as file: tokens = [ \"name\", \"targets\", \"dependencies\", \"change-rate\", \"all-changes\", \"latest-changes\", \"lifespan-in-days\" ]", "Aliases. settings = settings.settings Targets = targets.Targets class ModuleStats: \"\"\"Holds the statistics for", "affects each of the targets. This why we are constructing the graph in", "stack[-1] try: child = next(children_iter) if child not in visited: visited.add(child) dependency_counter[current_node] +=", "for parent in graph} for current_node in graph: stack = [[current_node, iter(graph[current_node])]] visited", "reversed dependencies graph. The adjacent edges as the are recorded in the dependencies", "visited = set() visited.add(target) while stack: parent, iter_to_children = stack[-1] stats_per_module[parent].add(target) try: child", "load_module_stats(cls): stats = [] stats_per_module, dependency_counts = _module_stats() history = change_history.load_change_history() for module_name,", "each module affects each of the targets. This why we are constructing the", "'w') as file: tokens = [ \"name\", \"targets\", \"dependencies\", \"change-rate\", \"all-changes\", \"latest-changes\", \"lifespan-in-days\"", "dependency_counts = _count_dependencies(graph_to_target) return stats_per_module, dependency_counts def _create_graph(): \"\"\"Creates the reversed dependencies graph.", "\"name\", \"targets\", \"dependencies\", \"change-rate\", \"all-changes\", \"latest-changes\", \"lifespan-in-days\" ] file.write(','.join(tokens)) file.write(\"\\n\") for module in", "_affected_targets: The affected targets. :ivar int dependency_count: The number of dependencies. \"\"\" def", "len(self._affected_targets) @property def dependency_count(self): return self._dependency_count @property def change_rate(self): return self._change_rate @property def", "return stats def _module_stats(): graph_from_target, graph_to_target = _create_graph() stats_per_module = {parent: set() for", "@property def module_name(self): return self._module_name @property def affected_targets(self): return len(self._affected_targets) @property def dependency_count(self):", "the dependencies file. :rtype: dict \"\"\" graph_from_target = {} graph_to_target = {} with", "that holds change statistics for all modules. Using the git log we are", "return self._dependency_count @property def change_rate(self): return self._change_rate @property def all_changes_count(self): return self._all_changes_count @property", "targets. This why we are constructing the graph in the opposite direction meaning", "import csv import change_history import settings import targets # Aliases. settings = settings.settings", "n1 not in graph_to_target: graph_to_target[n1] = [] if n2 not in graph_to_target: graph_to_target[n2]", "\"in\" dependency because the goal is to discover how each module affects each", "settings = settings.settings Targets = targets.Targets class ModuleStats: \"\"\"Holds the statistics for a", "f'Dependencies: {self._dependency_count} ' \\ f'Change Rate: {self._change_rate} ' \\ f'Total Changes: {self._all_changes_count} '", "= {} graph_to_target = {} with open(settings.dependencies_filename) as file: for tokens in csv.reader(file):", "stack.pop() return dependency_counter def export_to_csv(filename): with open(filename, 'w') as file: tokens = [", "for module_name, affected_targets in stats_per_module.items(): if module_name not in history: continue ch =", "targets # Aliases. settings = settings.settings Targets = targets.Targets class ModuleStats: \"\"\"Holds the", "ch else 'n/a' stats.append( cls( module_name=module_name, affected_targets=affected_targets, dependency_count=dependency_counts[module_name], change_rate=change_rate, all_changes_count=all_changes_count, latest_changes_count=latest_changes_count, lifespan_in_days=lifespan_in_days, filepath=filepath", "statistics for all modules. Using the git log we are creating a history", "+= 1 stack.append([child, iter(graph[child])]) except StopIteration: stack.pop() return dependency_counter def export_to_csv(filename): with open(filename,", "while stack: parent, children_iter = stack[-1] try: child = next(children_iter) if child not", "\\ f'Affected targets: {len(self._affected_targets)} ' \\ f'Dependencies: {self._dependency_count} ' \\ f'Change Rate: {self._change_rate}", "the reversed dependency meaning the \"in\" dependency because the goal is to discover", "lifespan_in_days self._filepath = filepath @property def module_name(self): return self._module_name @property def affected_targets(self): return", "= targets.Targets class ModuleStats: \"\"\"Holds the statistics for a module. :ivar str _module_name:", "between the imported and the importing modules. Here we need the reversed dependency", "the graph in the opposite direction meaning from the second to the first", "@property def lifespan_in_days(self): return self._lifespan_in_days @property def filepath(self): return self._filepath def __repr__(self): \"\"\"Make", "latest_changes_count = ch.latest_changes_count if ch else 'n/a' filepath = ch.filepath if ch else", "a class that holds change statistics for all modules. Using the git log", "str _module_name: The name of the module :ivar list _affected_targets: The affected targets.", "filepath = ch.filepath if ch else 'n/a' stats.append( cls( module_name=module_name, affected_targets=affected_targets, dependency_count=dependency_counts[module_name], change_rate=change_rate,", "' \\ f'Affected targets: {len(self._affected_targets)} ' \\ f'Dependencies: {self._dependency_count} ' \\ f'Change Rate:", "of the targets. This why we are constructing the graph in the opposite", "targets.Targets class ModuleStats: \"\"\"Holds the statistics for a module. :ivar str _module_name: The", "self._dependency_count = dependency_count self._change_rate = change_rate self._all_changes_count = all_changes_count self._latest_changes_count = latest_changes_count self._lifespan_in_days", "module.dependency_count, module.change_rate, module.all_changes_count, module.latest_changes_count, module.lifespan_in_days ] file.write(','.join(str(t) for t in tokens)) file.write(\"\\n\") if", "for target in all_targets.get_all(): _upadate_dependencies( graph_from_target, target.module_name, stats_per_module ) dependency_counts = _count_dependencies(graph_to_target) return", "it appears in the dependency file. :return: The \"in\" dependency graph for the", "\\ f'Total Changes: {self._all_changes_count} ' \\ f'Latest Changes: {self._latest_changes_count} ' \\ f'Lifespan: {self._lifespan_in_days}'", "f'Lifespan: {self._lifespan_in_days}' @classmethod def load_module_stats(cls): stats = [] stats_per_module, dependency_counts = _module_stats() history", "self._filepath def __repr__(self): \"\"\"Make debugging easier!\"\"\" return f'{self._module_name}, ' \\ f'Affected targets: {len(self._affected_targets)}", "= [] graph_to_target[n1].append(n2) return graph_from_target, graph_to_target def _upadate_dependencies(graph, target, stats_per_module): stack = [(target,", "all_targets = Targets() for target in all_targets.get_all(): _upadate_dependencies( graph_from_target, target.module_name, stats_per_module ) dependency_counts", "Rate: {self._change_rate} ' \\ f'Total Changes: {self._all_changes_count} ' \\ f'Latest Changes: {self._latest_changes_count} '", "goal is to discover how each module affects each of the targets. This", "the number of target dependencies. \"\"\" import csv import change_history import settings import", "dependency_count self._change_rate = change_rate self._all_changes_count = all_changes_count self._latest_changes_count = latest_changes_count self._lifespan_in_days = lifespan_in_days", "[] if n2 not in graph_from_target: graph_from_target[n2] = [] graph_from_target[n2].append(n1) if n1 not", "'n/a' stats.append( cls( module_name=module_name, affected_targets=affected_targets, dependency_count=dependency_counts[module_name], change_rate=change_rate, all_changes_count=all_changes_count, latest_changes_count=latest_changes_count, lifespan_in_days=lifespan_in_days, filepath=filepath ) )", "self._filepath = filepath @property def module_name(self): return self._module_name @property def affected_targets(self): return len(self._affected_targets)", "change_rate, all_changes_count, latest_changes_count, lifespan_in_days, filepath): \"\"\"Initializer. :param str module_name: The module name. :param", "the statistics for a module. :ivar str _module_name: The name of the module", "all_changes_count=all_changes_count, latest_changes_count=latest_changes_count, lifespan_in_days=lifespan_in_days, filepath=filepath ) ) return stats def _module_stats(): graph_from_target, graph_to_target =", "targets. \"\"\" self._module_name = module_name self._affected_targets = list(affected_targets) self._dependency_count = dependency_count self._change_rate =", "graph_from_target = {} graph_to_target = {} with open(settings.dependencies_filename) as file: for tokens in", "set() visited.add(target) while stack: parent, iter_to_children = stack[-1] stats_per_module[parent].add(target) try: child = next(iter_to_children)", "def change_rate(self): return self._change_rate @property def all_changes_count(self): return self._all_changes_count @property def latest_changes_count(self): return", ":param set affected_targets: The affected targets. \"\"\" self._module_name = module_name self._affected_targets = list(affected_targets)", "the total number of dependencies to each node.\"\"\" dependency_counter = {parent: 0 for", "settings.settings Targets = targets.Targets class ModuleStats: \"\"\"Holds the statistics for a module. :ivar", "stats_per_module): stack = [(target, iter(graph[target]))] stats_per_module[target].add(target) visited = set() visited.add(target) while stack: parent,", "name of the module :ivar list _affected_targets: The affected targets. :ivar int dependency_count:", "filepath @property def module_name(self): return self._module_name @property def affected_targets(self): return len(self._affected_targets) @property def", "= settings.settings Targets = targets.Targets class ModuleStats: \"\"\"Holds the statistics for a module.", "= [(target, iter(graph[target]))] stats_per_module[target].add(target) visited = set() visited.add(target) while stack: parent, iter_to_children =", "' \\ f'Change Rate: {self._change_rate} ' \\ f'Total Changes: {self._all_changes_count} ' \\ f'Latest", "= [] graph_from_target[n2].append(n1) if n1 not in graph_to_target: graph_to_target[n1] = [] if n2", "file. :return: The \"in\" dependency graph for the dependencies file. :rtype: dict \"\"\"", "affected_targets in stats_per_module.items(): if module_name not in history: continue ch = history.get(module_name) lifespan_in_days", "' \\ f'Latest Changes: {self._latest_changes_count} ' \\ f'Lifespan: {self._lifespan_in_days}' @classmethod def load_module_stats(cls): stats", "[] graph_to_target[n1].append(n2) return graph_from_target, graph_to_target def _upadate_dependencies(graph, target, stats_per_module): stack = [(target, iter(graph[target]))]", "history = change_history.load_change_history() for module_name, affected_targets in stats_per_module.items(): if module_name not in history:", "= stack[-1] stats_per_module[parent].add(target) try: child = next(iter_to_children) if child not in visited: stack.append((child,", "try: child = next(iter_to_children) if child not in visited: stack.append((child, iter(graph[child]))) visited.add(child) except", "child not in visited: visited.add(child) dependency_counter[current_node] += 1 stack.append([child, iter(graph[child])]) except StopIteration: stack.pop()", "module in ModuleStats.load_module_stats(): tokens = [ module.module_name, module.affected_targets, module.dependency_count, module.change_rate, module.all_changes_count, module.latest_changes_count, module.lifespan_in_days", "debugging easier!\"\"\" return f'{self._module_name}, ' \\ f'Affected targets: {len(self._affected_targets)} ' \\ f'Dependencies: {self._dependency_count}", "children_iter = stack[-1] try: child = next(children_iter) if child not in visited: visited.add(child)", "ch = history.get(module_name) lifespan_in_days = ch.lifespan_in_days if ch else 'n/a' change_rate = ch.change_rate", "graph_to_target def _upadate_dependencies(graph, target, stats_per_module): stack = [(target, iter(graph[target]))] stats_per_module[target].add(target) visited = set()", "dependency_counter = {parent: 0 for parent in graph} for current_node in graph: stack", "not in graph_from_target: graph_from_target[n1] = [] if n2 not in graph_from_target: graph_from_target[n2] =", "history: continue ch = history.get(module_name) lifespan_in_days = ch.lifespan_in_days if ch else 'n/a' change_rate", "iter(graph[child]))) visited.add(child) except StopIteration: stack.pop() def _count_dependencies(graph): \"\"\"Assigns the total number of dependencies", "module.latest_changes_count, module.lifespan_in_days ] file.write(','.join(str(t) for t in tokens)) file.write(\"\\n\") if __name__ == '__main__':", "else 'n/a' latest_changes_count = ch.latest_changes_count if ch else 'n/a' filepath = ch.filepath if", "all_changes_count, latest_changes_count, lifespan_in_days, filepath): \"\"\"Initializer. :param str module_name: The module name. :param set", "_upadate_dependencies(graph, target, stats_per_module): stack = [(target, iter(graph[target]))] stats_per_module[target].add(target) visited = set() visited.add(target) while", "The number of dependencies. \"\"\" def __init__(self, module_name, affected_targets, dependency_count, change_rate, all_changes_count, latest_changes_count,", "to it the number of target dependencies. \"\"\" import csv import change_history import", ":param str module_name: The module name. :param set affected_targets: The affected targets. \"\"\"", "of dependencies to each node.\"\"\" dependency_counter = {parent: 0 for parent in graph}", "@property def affected_targets(self): return len(self._affected_targets) @property def dependency_count(self): return self._dependency_count @property def change_rate(self):", "in the dependencies file represent an \"out\" relationship between the imported and the", "latest_changes_count, lifespan_in_days, filepath): \"\"\"Initializer. :param str module_name: The module name. :param set affected_targets:", "set affected_targets: The affected targets. \"\"\" self._module_name = module_name self._affected_targets = list(affected_targets) self._dependency_count", "for parent in graph_from_target.keys()} all_targets = Targets() for target in all_targets.get_all(): _upadate_dependencies( graph_from_target,", "stack.append((child, iter(graph[child]))) visited.add(child) except StopIteration: stack.pop() def _count_dependencies(graph): \"\"\"Assigns the total number of", "= next(children_iter) if child not in visited: visited.add(child) dependency_counter[current_node] += 1 stack.append([child, iter(graph[child])])", "class that holds change statistics for all modules. Using the git log we", "int dependency_count: The number of dependencies. \"\"\" def __init__(self, module_name, affected_targets, dependency_count, change_rate,", "append to it the number of target dependencies. \"\"\" import csv import change_history", ":ivar list _affected_targets: The affected targets. :ivar int dependency_count: The number of dependencies.", "else 'n/a' all_changes_count = ch.changes_count if ch else 'n/a' latest_changes_count = ch.latest_changes_count if", "changes for each module and also append to it the number of target", "affected targets. :ivar int dependency_count: The number of dependencies. \"\"\" def __init__(self, module_name,", "def lifespan_in_days(self): return self._lifespan_in_days @property def filepath(self): return self._filepath def __repr__(self): \"\"\"Make debugging", "filepath=filepath ) ) return stats def _module_stats(): graph_from_target, graph_to_target = _create_graph() stats_per_module =", "= [] if n2 not in graph_to_target: graph_to_target[n2] = [] graph_to_target[n1].append(n2) return graph_from_target,", "ch.change_rate if ch else 'n/a' all_changes_count = ch.changes_count if ch else 'n/a' latest_changes_count", "lifespan_in_days, filepath): \"\"\"Initializer. :param str module_name: The module name. :param set affected_targets: The", "Changes: {self._latest_changes_count} ' \\ f'Lifespan: {self._lifespan_in_days}' @classmethod def load_module_stats(cls): stats = [] stats_per_module,", "for the dependencies file. :rtype: dict \"\"\" graph_from_target = {} graph_to_target = {}", "{} with open(settings.dependencies_filename) as file: for tokens in csv.reader(file): n1 = tokens[0].strip() n2", "stats_per_module[parent].add(target) try: child = next(iter_to_children) if child not in visited: stack.append((child, iter(graph[child]))) visited.add(child)", "= ch.filepath if ch else 'n/a' stats.append( cls( module_name=module_name, affected_targets=affected_targets, dependency_count=dependency_counts[module_name], change_rate=change_rate, all_changes_count=all_changes_count,", "= tokens[0].strip() n2 = tokens[1].strip() if n1 not in graph_from_target: graph_from_target[n1] = []", "class ModuleStats: \"\"\"Holds the statistics for a module. :ivar str _module_name: The name", "\"lifespan-in-days\" ] file.write(','.join(tokens)) file.write(\"\\n\") for module in ModuleStats.load_module_stats(): tokens = [ module.module_name, module.affected_targets,", "= filepath @property def module_name(self): return self._module_name @property def affected_targets(self): return len(self._affected_targets) @property", "the are recorded in the dependencies file represent an \"out\" relationship between the", "meaning the \"in\" dependency because the goal is to discover how each module", "StopIteration: stack.pop() def _count_dependencies(graph): \"\"\"Assigns the total number of dependencies to each node.\"\"\"", "tokens = [ module.module_name, module.affected_targets, module.dependency_count, module.change_rate, module.all_changes_count, module.latest_changes_count, module.lifespan_in_days ] file.write(','.join(str(t) for", "return self._all_changes_count @property def latest_changes_count(self): return self._latest_changes_count @property def lifespan_in_days(self): return self._lifespan_in_days @property", "' \\ f'Total Changes: {self._all_changes_count} ' \\ f'Latest Changes: {self._latest_changes_count} ' \\ f'Lifespan:", "n2 not in graph_from_target: graph_from_target[n2] = [] graph_from_target[n2].append(n1) if n1 not in graph_to_target:", "in graph} for current_node in graph: stack = [[current_node, iter(graph[current_node])]] visited = set()", "self._lifespan_in_days @property def filepath(self): return self._filepath def __repr__(self): \"\"\"Make debugging easier!\"\"\" return f'{self._module_name},", "= [ module.module_name, module.affected_targets, module.dependency_count, module.change_rate, module.all_changes_count, module.latest_changes_count, module.lifespan_in_days ] file.write(','.join(str(t) for t", "all_changes_count self._latest_changes_count = latest_changes_count self._lifespan_in_days = lifespan_in_days self._filepath = filepath @property def module_name(self):", "number of target dependencies. \"\"\" import csv import change_history import settings import targets", "graph} for current_node in graph: stack = [[current_node, iter(graph[current_node])]] visited = set() visited.add(current_node)", "visited = set() visited.add(current_node) while stack: parent, children_iter = stack[-1] try: child =", "[ module.module_name, module.affected_targets, module.dependency_count, module.change_rate, module.all_changes_count, module.latest_changes_count, module.lifespan_in_days ] file.write(','.join(str(t) for t in", "to discover how each module affects each of the targets. This why we", "dependency meaning the \"in\" dependency because the goal is to discover how each", "@property def change_rate(self): return self._change_rate @property def all_changes_count(self): return self._all_changes_count @property def latest_changes_count(self):", "@property def latest_changes_count(self): return self._latest_changes_count @property def lifespan_in_days(self): return self._lifespan_in_days @property def filepath(self):", "appears in the dependency file. :return: The \"in\" dependency graph for the dependencies", "' \\ f'Dependencies: {self._dependency_count} ' \\ f'Change Rate: {self._change_rate} ' \\ f'Total Changes:", "module_name(self): return self._module_name @property def affected_targets(self): return len(self._affected_targets) @property def dependency_count(self): return self._dependency_count", "self._lifespan_in_days = lifespan_in_days self._filepath = filepath @property def module_name(self): return self._module_name @property def", "open(settings.dependencies_filename) as file: for tokens in csv.reader(file): n1 = tokens[0].strip() n2 = tokens[1].strip()", "1 stack.append([child, iter(graph[child])]) except StopIteration: stack.pop() return dependency_counter def export_to_csv(filename): with open(filename, 'w')", "return dependency_counter def export_to_csv(filename): with open(filename, 'w') as file: tokens = [ \"name\",", "parent, iter_to_children = stack[-1] stats_per_module[parent].add(target) try: child = next(iter_to_children) if child not in", "ch else 'n/a' filepath = ch.filepath if ch else 'n/a' stats.append( cls( module_name=module_name,", "f'Latest Changes: {self._latest_changes_count} ' \\ f'Lifespan: {self._lifespan_in_days}' @classmethod def load_module_stats(cls): stats = []", "return self._lifespan_in_days @property def filepath(self): return self._filepath def __repr__(self): \"\"\"Make debugging easier!\"\"\" return", "in graph: stack = [[current_node, iter(graph[current_node])]] visited = set() visited.add(current_node) while stack: parent,", "module.affected_targets, module.dependency_count, module.change_rate, module.all_changes_count, module.latest_changes_count, module.lifespan_in_days ] file.write(','.join(str(t) for t in tokens)) file.write(\"\\n\")", "log we are creating a history of changes for each module and also", "target, stats_per_module): stack = [(target, iter(graph[target]))] stats_per_module[target].add(target) visited = set() visited.add(target) while stack:", "while stack: parent, iter_to_children = stack[-1] stats_per_module[parent].add(target) try: child = next(iter_to_children) if child", "return len(self._affected_targets) @property def dependency_count(self): return self._dependency_count @property def change_rate(self): return self._change_rate @property", "to the first node as it appears in the dependency file. :return: The", "def dependency_count(self): return self._dependency_count @property def change_rate(self): return self._change_rate @property def all_changes_count(self): return", "stats_per_module, dependency_counts = _module_stats() history = change_history.load_change_history() for module_name, affected_targets in stats_per_module.items(): if", "as it appears in the dependency file. :return: The \"in\" dependency graph for", "The affected targets. \"\"\" self._module_name = module_name self._affected_targets = list(affected_targets) self._dependency_count = dependency_count", "csv.reader(file): n1 = tokens[0].strip() n2 = tokens[1].strip() if n1 not in graph_from_target: graph_from_target[n1]", "return self._filepath def __repr__(self): \"\"\"Make debugging easier!\"\"\" return f'{self._module_name}, ' \\ f'Affected targets:", "{self._latest_changes_count} ' \\ f'Lifespan: {self._lifespan_in_days}' @classmethod def load_module_stats(cls): stats = [] stats_per_module, dependency_counts", "next(children_iter) if child not in visited: visited.add(child) dependency_counter[current_node] += 1 stack.append([child, iter(graph[child])]) except", "_module_stats() history = change_history.load_change_history() for module_name, affected_targets in stats_per_module.items(): if module_name not in", "not in graph_to_target: graph_to_target[n2] = [] graph_to_target[n1].append(n2) return graph_from_target, graph_to_target def _upadate_dependencies(graph, target,", "self._change_rate = change_rate self._all_changes_count = all_changes_count self._latest_changes_count = latest_changes_count self._lifespan_in_days = lifespan_in_days self._filepath", "the goal is to discover how each module affects each of the targets.", "0 for parent in graph} for current_node in graph: stack = [[current_node, iter(graph[current_node])]]", "\"\"\" def __init__(self, module_name, affected_targets, dependency_count, change_rate, all_changes_count, latest_changes_count, lifespan_in_days, filepath): \"\"\"Initializer. :param", "set() visited.add(current_node) while stack: parent, children_iter = stack[-1] try: child = next(children_iter) if", "the importing modules. Here we need the reversed dependency meaning the \"in\" dependency", "node as it appears in the dependency file. :return: The \"in\" dependency graph", "= [ \"name\", \"targets\", \"dependencies\", \"change-rate\", \"all-changes\", \"latest-changes\", \"lifespan-in-days\" ] file.write(','.join(tokens)) file.write(\"\\n\") for", "in ModuleStats.load_module_stats(): tokens = [ module.module_name, module.affected_targets, module.dependency_count, module.change_rate, module.all_changes_count, module.latest_changes_count, module.lifespan_in_days ]", "= [[current_node, iter(graph[current_node])]] visited = set() visited.add(current_node) while stack: parent, children_iter = stack[-1]", "why we are constructing the graph in the opposite direction meaning from the", "= lifespan_in_days self._filepath = filepath @property def module_name(self): return self._module_name @property def affected_targets(self):", "git log we are creating a history of changes for each module and", "graph_from_target[n2] = [] graph_from_target[n2].append(n1) if n1 not in graph_to_target: graph_to_target[n1] = [] if", "= ch.change_rate if ch else 'n/a' all_changes_count = ch.changes_count if ch else 'n/a'", "if ch else 'n/a' latest_changes_count = ch.latest_changes_count if ch else 'n/a' filepath =", "graph_from_target, target.module_name, stats_per_module ) dependency_counts = _count_dependencies(graph_to_target) return stats_per_module, dependency_counts def _create_graph(): \"\"\"Creates", "for a module. :ivar str _module_name: The name of the module :ivar list" ]
[ "from django.conf import settings from . import views urlpatterns = [ url(r'^solicitud-colaboracion/$', views.Solicitud_colaboracion.as_view(),name=\"solicitud\"),", "django.conf import settings from . import views urlpatterns = [ url(r'^solicitud-colaboracion/$', views.Solicitud_colaboracion.as_view(),name=\"solicitud\"), ]", "django.conf.urls import url, include from django.conf import settings from . import views urlpatterns", "url, include from django.conf import settings from . import views urlpatterns = [", "include from django.conf import settings from . import views urlpatterns = [ url(r'^solicitud-colaboracion/$',", "from django.conf.urls import url, include from django.conf import settings from . import views", "import url, include from django.conf import settings from . import views urlpatterns =" ]
[ "context = { \"moto\": \"The framework for perfectionist!\" } return render(request, \"app/index.html\", context)", "<reponame>julesc00/travel-agency from django.shortcuts import render # Create your views here. def index(request): context", "django.shortcuts import render # Create your views here. def index(request): context = {", "here. def index(request): context = { \"moto\": \"The framework for perfectionist!\" } return", "from django.shortcuts import render # Create your views here. def index(request): context =", "import render # Create your views here. def index(request): context = { \"moto\":", "Create your views here. def index(request): context = { \"moto\": \"The framework for", "# Create your views here. def index(request): context = { \"moto\": \"The framework", "index(request): context = { \"moto\": \"The framework for perfectionist!\" } return render(request, \"app/index.html\",", "your views here. def index(request): context = { \"moto\": \"The framework for perfectionist!\"", "render # Create your views here. def index(request): context = { \"moto\": \"The", "views here. def index(request): context = { \"moto\": \"The framework for perfectionist!\" }", "def index(request): context = { \"moto\": \"The framework for perfectionist!\" } return render(request," ]
[ "works, \"qualification\", \"jobTitle\", \"инженер\") output_string = f\"{works.shape[0]} не совпадает {not_matches_count}\\n\\n\" \\ f\"Топ 5", "\"jobTitle\", \"инженер\") output_string = f\"{works.shape[0]} не совпадает {not_matches_count}\\n\\n\" \\ f\"Топ 5 образовний менеджеров\\n\"", "f2) in zip(data[firs_param], data[second_param]): if not is_contains(f1, f2) and not is_contains(f2, f1): count", "and not is_contains(f2, f1): count += 1 return count def is_contains(first_field, second_field): for", "works = pd.read_csv(\"works.csv\").dropna() not_matches_count = non_matches(\"jobTitle\", \"qualification\", works) managers = get_top(5, works, \"jobTitle\",", "works) managers = get_top(5, works, \"jobTitle\", \"qualification\", \"менеджер\") engineers = get_top(5, works, \"qualification\",", "get_top(5, works, \"qualification\", \"jobTitle\", \"инженер\") output_string = f\"{works.shape[0]} не совпадает {not_matches_count}\\n\\n\" \\ f\"Топ", "\"jobTitle\", \"qualification\", \"менеджер\") engineers = get_top(5, works, \"qualification\", \"jobTitle\", \"инженер\") output_string = f\"{works.shape[0]}", "for word in first_field.lower().replace('-', ' ').split(): if word in second_field.lower(): return True return", ".lower()\\ .value_counts()\\ .head(size) works = pd.read_csv(\"works.csv\").dropna() not_matches_count = non_matches(\"jobTitle\", \"qualification\", works) managers =", "data): count = 0 for (f1, f2) in zip(data[firs_param], data[second_param]): if not is_contains(f1,", ".str\\ .lower()\\ .value_counts()\\ .head(size) works = pd.read_csv(\"works.csv\").dropna() not_matches_count = non_matches(\"jobTitle\", \"qualification\", works) managers", "True return False def get_top(size, data, field1, field2, word_to_search): return data[data[field1].str.lower().str.contains(word_to_search[:-2])][field2]\\ .str\\ .lower()\\", "\\ f\"{managers}\\n\\n\" \\ f\"Топ 5 должностей инженеров\\n\" \\ f\"{engineers}\" with open('output.txt', 'w', encoding='utf-8')", ".value_counts()\\ .head(size) works = pd.read_csv(\"works.csv\").dropna() not_matches_count = non_matches(\"jobTitle\", \"qualification\", works) managers = get_top(5,", "second_param, data): count = 0 for (f1, f2) in zip(data[firs_param], data[second_param]): if not", "if word in second_field.lower(): return True return False def get_top(size, data, field1, field2,", "не совпадает {not_matches_count}\\n\\n\" \\ f\"Топ 5 образовний менеджеров\\n\" \\ f\"{managers}\\n\\n\" \\ f\"Топ 5", "word in first_field.lower().replace('-', ' ').split(): if word in second_field.lower(): return True return False", "= f\"{works.shape[0]} не совпадает {not_matches_count}\\n\\n\" \\ f\"Топ 5 образовний менеджеров\\n\" \\ f\"{managers}\\n\\n\" \\", "second_field.lower(): return True return False def get_top(size, data, field1, field2, word_to_search): return data[data[field1].str.lower().str.contains(word_to_search[:-2])][field2]\\", "data[data[field1].str.lower().str.contains(word_to_search[:-2])][field2]\\ .str\\ .lower()\\ .value_counts()\\ .head(size) works = pd.read_csv(\"works.csv\").dropna() not_matches_count = non_matches(\"jobTitle\", \"qualification\", works)", "def non_matches(firs_param, second_param, data): count = 0 for (f1, f2) in zip(data[firs_param], data[second_param]):", "count def is_contains(first_field, second_field): for word in first_field.lower().replace('-', ' ').split(): if word in", "in zip(data[firs_param], data[second_param]): if not is_contains(f1, f2) and not is_contains(f2, f1): count +=", "in first_field.lower().replace('-', ' ').split(): if word in second_field.lower(): return True return False def", "= pd.read_csv(\"works.csv\").dropna() not_matches_count = non_matches(\"jobTitle\", \"qualification\", works) managers = get_top(5, works, \"jobTitle\", \"qualification\",", "word_to_search): return data[data[field1].str.lower().str.contains(word_to_search[:-2])][field2]\\ .str\\ .lower()\\ .value_counts()\\ .head(size) works = pd.read_csv(\"works.csv\").dropna() not_matches_count = non_matches(\"jobTitle\",", "count += 1 return count def is_contains(first_field, second_field): for word in first_field.lower().replace('-', '", "return data[data[field1].str.lower().str.contains(word_to_search[:-2])][field2]\\ .str\\ .lower()\\ .value_counts()\\ .head(size) works = pd.read_csv(\"works.csv\").dropna() not_matches_count = non_matches(\"jobTitle\", \"qualification\",", "second_field): for word in first_field.lower().replace('-', ' ').split(): if word in second_field.lower(): return True", "data[second_param]): if not is_contains(f1, f2) and not is_contains(f2, f1): count += 1 return", "\"менеджер\") engineers = get_top(5, works, \"qualification\", \"jobTitle\", \"инженер\") output_string = f\"{works.shape[0]} не совпадает", "count = 0 for (f1, f2) in zip(data[firs_param], data[second_param]): if not is_contains(f1, f2)", "f\"{works.shape[0]} не совпадает {not_matches_count}\\n\\n\" \\ f\"Топ 5 образовний менеджеров\\n\" \\ f\"{managers}\\n\\n\" \\ f\"Топ", "\"инженер\") output_string = f\"{works.shape[0]} не совпадает {not_matches_count}\\n\\n\" \\ f\"Топ 5 образовний менеджеров\\n\" \\", "1 return count def is_contains(first_field, second_field): for word in first_field.lower().replace('-', ' ').split(): if", "return count def is_contains(first_field, second_field): for word in first_field.lower().replace('-', ' ').split(): if word", "get_top(size, data, field1, field2, word_to_search): return data[data[field1].str.lower().str.contains(word_to_search[:-2])][field2]\\ .str\\ .lower()\\ .value_counts()\\ .head(size) works =", "False def get_top(size, data, field1, field2, word_to_search): return data[data[field1].str.lower().str.contains(word_to_search[:-2])][field2]\\ .str\\ .lower()\\ .value_counts()\\ .head(size)", "not is_contains(f1, f2) and not is_contains(f2, f1): count += 1 return count def", "get_top(5, works, \"jobTitle\", \"qualification\", \"менеджер\") engineers = get_top(5, works, \"qualification\", \"jobTitle\", \"инженер\") output_string", "not is_contains(f2, f1): count += 1 return count def is_contains(first_field, second_field): for word", "\"qualification\", works) managers = get_top(5, works, \"jobTitle\", \"qualification\", \"менеджер\") engineers = get_top(5, works,", "= non_matches(\"jobTitle\", \"qualification\", works) managers = get_top(5, works, \"jobTitle\", \"qualification\", \"менеджер\") engineers =", "zip(data[firs_param], data[second_param]): if not is_contains(f1, f2) and not is_contains(f2, f1): count += 1", "\\ f\"Топ 5 должностей инженеров\\n\" \\ f\"{engineers}\" with open('output.txt', 'w', encoding='utf-8') as file:", "import pandas as pd def non_matches(firs_param, second_param, data): count = 0 for (f1,", "совпадает {not_matches_count}\\n\\n\" \\ f\"Топ 5 образовний менеджеров\\n\" \\ f\"{managers}\\n\\n\" \\ f\"Топ 5 должностей", "менеджеров\\n\" \\ f\"{managers}\\n\\n\" \\ f\"Топ 5 должностей инженеров\\n\" \\ f\"{engineers}\" with open('output.txt', 'w',", "').split(): if word in second_field.lower(): return True return False def get_top(size, data, field1,", "= get_top(5, works, \"jobTitle\", \"qualification\", \"менеджер\") engineers = get_top(5, works, \"qualification\", \"jobTitle\", \"инженер\")", "образовний менеджеров\\n\" \\ f\"{managers}\\n\\n\" \\ f\"Топ 5 должностей инженеров\\n\" \\ f\"{engineers}\" with open('output.txt',", "{not_matches_count}\\n\\n\" \\ f\"Топ 5 образовний менеджеров\\n\" \\ f\"{managers}\\n\\n\" \\ f\"Топ 5 должностей инженеров\\n\"", "def get_top(size, data, field1, field2, word_to_search): return data[data[field1].str.lower().str.contains(word_to_search[:-2])][field2]\\ .str\\ .lower()\\ .value_counts()\\ .head(size) works", "\"qualification\", \"менеджер\") engineers = get_top(5, works, \"qualification\", \"jobTitle\", \"инженер\") output_string = f\"{works.shape[0]} не", "works, \"jobTitle\", \"qualification\", \"менеджер\") engineers = get_top(5, works, \"qualification\", \"jobTitle\", \"инженер\") output_string =", "engineers = get_top(5, works, \"qualification\", \"jobTitle\", \"инженер\") output_string = f\"{works.shape[0]} не совпадает {not_matches_count}\\n\\n\"", "def is_contains(first_field, second_field): for word in first_field.lower().replace('-', ' ').split(): if word in second_field.lower():", "\\ f\"Топ 5 образовний менеджеров\\n\" \\ f\"{managers}\\n\\n\" \\ f\"Топ 5 должностей инженеров\\n\" \\", "f\"Топ 5 должностей инженеров\\n\" \\ f\"{engineers}\" with open('output.txt', 'w', encoding='utf-8') as file: file.write(output_string)", "field1, field2, word_to_search): return data[data[field1].str.lower().str.contains(word_to_search[:-2])][field2]\\ .str\\ .lower()\\ .value_counts()\\ .head(size) works = pd.read_csv(\"works.csv\").dropna() not_matches_count", "<filename>main.py import pandas as pd def non_matches(firs_param, second_param, data): count = 0 for", "f\"Топ 5 образовний менеджеров\\n\" \\ f\"{managers}\\n\\n\" \\ f\"Топ 5 должностей инженеров\\n\" \\ f\"{engineers}\"", "output_string = f\"{works.shape[0]} не совпадает {not_matches_count}\\n\\n\" \\ f\"Топ 5 образовний менеджеров\\n\" \\ f\"{managers}\\n\\n\"", ".head(size) works = pd.read_csv(\"works.csv\").dropna() not_matches_count = non_matches(\"jobTitle\", \"qualification\", works) managers = get_top(5, works,", "if not is_contains(f1, f2) and not is_contains(f2, f1): count += 1 return count", "= get_top(5, works, \"qualification\", \"jobTitle\", \"инженер\") output_string = f\"{works.shape[0]} не совпадает {not_matches_count}\\n\\n\" \\", "f2) and not is_contains(f2, f1): count += 1 return count def is_contains(first_field, second_field):", "word in second_field.lower(): return True return False def get_top(size, data, field1, field2, word_to_search):", "managers = get_top(5, works, \"jobTitle\", \"qualification\", \"менеджер\") engineers = get_top(5, works, \"qualification\", \"jobTitle\",", "\"qualification\", \"jobTitle\", \"инженер\") output_string = f\"{works.shape[0]} не совпадает {not_matches_count}\\n\\n\" \\ f\"Топ 5 образовний", "non_matches(\"jobTitle\", \"qualification\", works) managers = get_top(5, works, \"jobTitle\", \"qualification\", \"менеджер\") engineers = get_top(5,", "is_contains(f1, f2) and not is_contains(f2, f1): count += 1 return count def is_contains(first_field,", "0 for (f1, f2) in zip(data[firs_param], data[second_param]): if not is_contains(f1, f2) and not", "data, field1, field2, word_to_search): return data[data[field1].str.lower().str.contains(word_to_search[:-2])][field2]\\ .str\\ .lower()\\ .value_counts()\\ .head(size) works = pd.read_csv(\"works.csv\").dropna()", "5 образовний менеджеров\\n\" \\ f\"{managers}\\n\\n\" \\ f\"Топ 5 должностей инженеров\\n\" \\ f\"{engineers}\" with", "for (f1, f2) in zip(data[firs_param], data[second_param]): if not is_contains(f1, f2) and not is_contains(f2,", "is_contains(f2, f1): count += 1 return count def is_contains(first_field, second_field): for word in", "field2, word_to_search): return data[data[field1].str.lower().str.contains(word_to_search[:-2])][field2]\\ .str\\ .lower()\\ .value_counts()\\ .head(size) works = pd.read_csv(\"works.csv\").dropna() not_matches_count =", "(f1, f2) in zip(data[firs_param], data[second_param]): if not is_contains(f1, f2) and not is_contains(f2, f1):", "pandas as pd def non_matches(firs_param, second_param, data): count = 0 for (f1, f2)", "f1): count += 1 return count def is_contains(first_field, second_field): for word in first_field.lower().replace('-',", "' ').split(): if word in second_field.lower(): return True return False def get_top(size, data,", "pd def non_matches(firs_param, second_param, data): count = 0 for (f1, f2) in zip(data[firs_param],", "first_field.lower().replace('-', ' ').split(): if word in second_field.lower(): return True return False def get_top(size,", "= 0 for (f1, f2) in zip(data[firs_param], data[second_param]): if not is_contains(f1, f2) and", "in second_field.lower(): return True return False def get_top(size, data, field1, field2, word_to_search): return", "is_contains(first_field, second_field): for word in first_field.lower().replace('-', ' ').split(): if word in second_field.lower(): return", "return True return False def get_top(size, data, field1, field2, word_to_search): return data[data[field1].str.lower().str.contains(word_to_search[:-2])][field2]\\ .str\\", "return False def get_top(size, data, field1, field2, word_to_search): return data[data[field1].str.lower().str.contains(word_to_search[:-2])][field2]\\ .str\\ .lower()\\ .value_counts()\\", "non_matches(firs_param, second_param, data): count = 0 for (f1, f2) in zip(data[firs_param], data[second_param]): if", "pd.read_csv(\"works.csv\").dropna() not_matches_count = non_matches(\"jobTitle\", \"qualification\", works) managers = get_top(5, works, \"jobTitle\", \"qualification\", \"менеджер\")", "f\"{managers}\\n\\n\" \\ f\"Топ 5 должностей инженеров\\n\" \\ f\"{engineers}\" with open('output.txt', 'w', encoding='utf-8') as", "+= 1 return count def is_contains(first_field, second_field): for word in first_field.lower().replace('-', ' ').split():", "as pd def non_matches(firs_param, second_param, data): count = 0 for (f1, f2) in", "not_matches_count = non_matches(\"jobTitle\", \"qualification\", works) managers = get_top(5, works, \"jobTitle\", \"qualification\", \"менеджер\") engineers" ]
[ "second # @staticmethod # def showTime(): # return time.strftime(\"%H:%M:%S\", time.localtime()) # print(TimeTest.showTime()) #", "def plus_all(self,a,b,c,d): # return self.plus_int(a,b)+self.plus_float(c,d) #参数名字可以变,但是个数不能变 # num = PlusNum() # # print(num.plus_int(3,4))", "class son(father1): # pass # john = son() # john.yeye() # 第一个父级没有,会找第二个父级,没有的话再找爷爷级 #", "second): # self.hour = hour # self.minute = minute # self.second = second", "showTime(): # return time.strftime(\"%H:%M:%S\", time.localtime()) # print(TimeTest.showTime()) # t = TimeTest(2, 10, 10)", "* 表示匹配0次或多次,等于{0,} file = open('duban.json','r',encoding='utf-8') #读取这个文件 a = file.read() a2 = '<EMAIL>,song <EMAIL>,song!<EMAIL>'", "father2(grandfather): # def yiu(self): # print(\"父级有的东西2\") # class son(father1,father2): # pass # john", "self).__new__(self) # class Student(ClassTest): # def __init__(self): # self.name = '' # a", "file = open('duban.json','r',encoding='utf-8') #读取这个文件 # a = file.read() # a2 = '<HtMl>hello</hTmL>' #网页,要把hello匹配出来", "print(\"www\") # Act.use() #类方法不仅可以被类调用,还可以被对象调用 # class Run: # @staticmethod #类的静态方法,不传对象也不传类,既不属于类做的事情,也不属于对象做的事情,但可以被类和对象调用 # def have_breakfast():", "Run # r.have_breakfast() #被对象调用 # Run.have_breakfast() #被类调用 #————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————- # Python 实例方法、类方法、静态方法的区别与作用 # Python中至少有三种比较常见的方法类型,即实例方法,类方法、静态方法。它们是如何定义的呢?如何调用的呢?它们又有何区别和作用呢?且看下文。", "# john = son() # john.yeye() #python3继承顺序 # 新式类的继承方式是:先找最亲的爸爸(括号里面第一个继承的类),然后再去找第二个爸爸(括号里面第二个继承的类), #当爸爸类都找不到的时候,找第一个爸爸的父类 #类里面的方法不能相互调用,单现在讲一个方法可以相互调用 #类的命名方式和方法命名方式不一样,类的命名方式,多个单词把首字母大写, 方法的是单词中间用下划线;", "class grandfather(): # def yeye(self): # print(\"爷爷有的东西\") # class father1(grandfather): # def yeye(self):", "= file.read() # a2 = '<EMAIL>,<EMAIL>,<EMAIL>' # # pattern = re.compile(r'.+@\\w+\\.com') #匹配所有邮箱,但是打印出来的是一组字符串,需要分开打印,用下面方法 #", "def addNum(cls): # cls.__num += 1 # @classmethod # def getNum(cls): # return", "# pattern = re.compile(r'\\d+') #跟上面的[1,]效果是一样的 # # pattern = re.compile(r'\\w') #把数字、字母、下划线、汉字都打印出来了 # #", "def have(self): # print(\"父级有的东西\") # class father2(grandfather): # def yiu(self): # print(\"父级有的东西2\") #", "# 第一个父级没有,会找第二个父级,没有的话再找爷爷级 # class grandfather(): # def yeye(self): # print(\"爷爷有的东西\") # class father1(grandfather):", "re.compile(r'.') #'.'能匹配所有的东西,代表匹配所有 # pattern = re.compile(r'song\\.lu@errc\\.com') #在点前面加上反斜杠,就能完全匹配 # result = pattern.findall(a2) # print(result)", "re.compile(r'\\d{1,10}') #找到所有数字匹配,下标从一位到10位数字 # # pattern = re.compile(r'\\d{1,}') #左边不输入,代表从0开始,右边不输入,最大随便出现 取出这个文件中的所有数字 # # pattern =", "print(\"父级有的东西\") # class father2(): # def money(self): # print(\"父级有的东西2\") # class son(father1,father2): #", "# # pattern = re.compile(r'\\D+') #非数字的一切内容 # pattern = re.compile(r'\\w*') #表示匹配0此或者多次,等于[0,] # result", "# result = pattern.findall(a2) # print(result) # file.close() #打开文件记得关闭 # # 题目:<EMAIL>,只要匹配@hit #", "pattern.findall(a2) # print(result) # file.close() #打开文件记得关闭 # file = open('duban.json','r',encoding='utf-8') #读取这个文件 # a", "file.read() # a2 = '<HtMl>hello</hTmL>' #网页,要把hello匹配出来 # pattern = re.compile(r'<[Hh][Tt][Mm][Ll]>hello</[Hh][Tt][Mm][Ll]>') #中括号里面是你可以匹配的对象 # result", "= re.compile(r'\\w+.\\w+@\\w+\\.com') #正常情况只要后面的\\w+@\\w+\\.com(正常的邮箱正则表达式)即可,但是因为此题前面有个点 # result = pattern.findall(a2) # print(result) # file.close() #打开文件记得关闭 #", "#被类调用 #————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————- # Python 实例方法、类方法、静态方法的区别与作用 # Python中至少有三种比较常见的方法类型,即实例方法,类方法、静态方法。它们是如何定义的呢?如何调用的呢?它们又有何区别和作用呢?且看下文。 # 首先,这三种方法都定义在类中。下面我先简单说一下怎么定义和调用的。(PS:实例对象的权限最大。) # 实例方法 # 定义:第一个参数必须是实例对象,该参数名一般约定为“self”,通过它来传递实例的属性和方法(也可以传类的属性和方法);", "father2(): # def money(self): # print(\"父级有的东西2\") # class son(father1,father2): # pass # john", "实例方法、类方法、静态方法的区别与作用 # Python中至少有三种比较常见的方法类型,即实例方法,类方法、静态方法。它们是如何定义的呢?如何调用的呢?它们又有何区别和作用呢?且看下文。 # 首先,这三种方法都定义在类中。下面我先简单说一下怎么定义和调用的。(PS:实例对象的权限最大。) # 实例方法 # 定义:第一个参数必须是实例对象,该参数名一般约定为“self”,通过它来传递实例的属性和方法(也可以传类的属性和方法); # 调用:只能由实例对象调用。 # 类方法", "class Act: # @classmethod #表示类的方法 # def use(cls): #加上了上面的,此处变为cls,是class的缩写 # print(\"www\") # Act.use()", "__num = 0 # @classmethod # def addNum(cls): # cls.__num += 1 #", "= float(b) # return a+b # def plus_all(self,a,b,c,d): # return self.plus_int(a,b)+self.plus_float(c,d) #参数名字可以变,但是个数不能变 #", "# 调用:实例对象和类对象都可以调用。 # 静态方法 # 定义:使用装饰器@staticmethod。参数随意,没有“self”和“cls”参数,但是方法体中不能使用类或实例的任何属性和方法; # 调用:实例对象和类对象都可以调用。 # 实例方法 # 简而言之,实例方法就是类的实例能够使用的方法。这里不做过多解释。 #", "匹配一次到4次 # {,4} 匹配至多四次 # {1,} 匹配至少一次 # ? 解除贪婪模式,接在次数的正则表达式后面使用 # * 表示匹配0次或多次,等于{0,}", "__init__(self, hour, minute, second): # self.hour = hour # self.minute = minute #", "response.text # print(content) #打印获取整个的网页内容 # with open('duban.json','w',encoding='utf-8') as file: #把网页内容写到文件中 # file.write(content) ##############################################拓展:", "= '<EMAIL>,song <EMAIL>,song!<EMAIL>' pattern = re.compile(r'@(.*?)\\.com') #万能表达式需要告诉在哪里结束 result = pattern.findall(a2) print(result) file.close() #打开文件记得关闭", "# result = pattern.findall(a2) # print(result) # file.close() #打开文件记得关闭 # file = open('duban.json','r',encoding='utf-8')", "self.hour = hour # self.minute = minute # self.second = second # @staticmethod", "= re.compile(r'@.+\\.') #正则表达式默认贪婪模式,尽可能多的匹配点,会匹配到最后一个,如何避免呢。前面加个问号即可,如下: # pattern = re.compile(r'@.+?\\.') #正则表达式的点的懒惰模式,问号是解除贪婪模式变为懒惰模式 # result = pattern.findall(a2) #", "#json仅限于拿接口数据,content拿所有格式 # import requests # response = requests.get('http://news.baidu.com') #用这个方法访问百度新闻 # # print(str(response.text)) #类型是字符串类型", "# pattern = re.compile(r'新闻') # # pattern = re.compile(r'\\d{1,10}') #找到所有数字匹配,下标从一位到10位数字 # # pattern", "class Run: # @staticmethod #类的静态方法,不传对象也不传类,既不属于类做的事情,也不属于对象做的事情,但可以被类和对象调用 # def have_breakfast(): #静态方法括号为空,是针对于cls和self方法用的,可以传自己的参数如a,b等, # print('eat eggs') #", "pattern.findall(a2) # print(result) # file.close() #打开文件记得关闭 # 比如匹配所有邮箱 # file = open('duban.json','r',encoding='utf-8') #读取这个文件", "father1(): # def have(self): # print(\"父级有的东西\") # class father2(): # def have(self): #", "response = requests.get('http://news.baidu.com') #用这个方法访问百度新闻 # # print(str(response.text)) #类型是字符串类型 # # print(str(response.content)) #用concent会生成字节流,前面有个b,加上“encoding=‘utf-8’”就可以了 #", "re import requests import json # response = requests.get('http://news.baidu.com') #用这个方法访问百度新闻 # print(response) #打印获取的是状态码", "非数字字母_ # \\d 数字 # \\D 非数字 # . 所有 # + 匹配一次或多次等于{1,}", "def getNum(cls): # return cls.__num # # 这里我用到魔术方法__new__,主要是为了在创建实例的时候调用累加方法。 # def __new__(self): # ClassTest.addNum()", "getNum(cls): # return cls.__num # # 这里我用到魔术方法__new__,主要是为了在创建实例的时候调用累加方法。 # def __new__(self): # ClassTest.addNum() #", "def __init__(self): # self.name = '' # a = Student() # b =", "# def __init__(self, hour, minute, second): # self.hour = hour # self.minute =", "have(self): # print(\"父级有的东西\") # class father2(): # def have(self): # print(\"父级有的东西2\") # class", "# + 匹配一次或多次等于{1,} # {1,4} 匹配一次到4次 # {,4} 匹配至多四次 # {1,} 匹配至少一次 #", "# def yeye(self): # print(\"爷爷有的东西\") # class father1(grandfather): # def yeye(self): # print(\"父级有的东西\")", "a = int(a) # b = int(b) # return a+b # def plus_float(self,a,b):", "定义:使用装饰器@classmethod。第一个参数必须是当前类对象,该参数名一般约定为“cls”,通过它来传递类的属性和方法(不能传实例的属性和方法); # 调用:实例对象和类对象都可以调用。 # 静态方法 # 定义:使用装饰器@staticmethod。参数随意,没有“self”和“cls”参数,但是方法体中不能使用类或实例的任何属性和方法; # 调用:实例对象和类对象都可以调用。 # 实例方法 # 简而言之,实例方法就是类的实例能够使用的方法。这里不做过多解释。", "#打开文件记得关闭 ###################################################拓展: # import json #json仅限于拿接口数据,content拿所有格式 # import requests # response = requests.get('http://news.baidu.com')", "定义:使用装饰器@staticmethod。参数随意,没有“self”和“cls”参数,但是方法体中不能使用类或实例的任何属性和方法; # 调用:实例对象和类对象都可以调用。 # 实例方法 # 简而言之,实例方法就是类的实例能够使用的方法。这里不做过多解释。 # 类方法 # 使用装饰器@classmethod。 # 原则上,类方法是将类本身作为对象进行操作的方法。假设有个方法,且这个方法在逻辑上采用类本身作为对象来调用更合理,那么这个方法就可以定义为类方法。另外,如果需要继承,也可以定义为类方法。", "= requests.get('http://news.baidu.com') #用这个方法访问百度新闻 # # print(str(response.text)) #类型是字符串类型 # # print(str(response.content)) #用concent会生成字节流,前面有个b,加上“encoding=‘utf-8’”就可以了 # print(response.json)", "# john = son() # john.yeye() #儿子层只能先在父级层找,找不到才去爷爷层找 # class grandfather(): # def yeye(self):", "father1(grandfather): # def have(self): # print(\"父级有的东西\") # class father2(grandfather): # def yiu(self): #", "import requests # response = requests.get('http://news.baidu.com') #用这个方法访问百度新闻 # # print(str(response.text)) #类型是字符串类型 # #", "# class son(father1,father2): # pass # john = son() # john.yeye() #python3继承顺序 #", "= re.compile(r'song\\.lu@errc\\.com') #在点前面加上反斜杠,就能完全匹配 # result = pattern.findall(a2) # print(result) # file.close() #打开文件记得关闭 #", "#读取这个文件 # a = file.read() # a2 = '<EMAIL>,<EMAIL>,<EMAIL>' # # pattern =", "# a2 = '<EMAIL>,song <EMAIL>,<EMAIL>' # # pattern = re.compile(r'<EMAIL>') #因为‘。’导致都匹配上了 # #", "# __num = 0 # @classmethod # def addNum(cls): # cls.__num += 1", "#参数名字可以变,但是个数不能变 # num = PlusNum() # # print(num.plus_int(3,4)) # # print(num.plus_float(2.1,3.4)) # print(num.plus_all(1,2,3.3,4.3))", "= pattern.findall(a2) # print(result) # file.close() #打开文件记得关闭 # # 题目:<EMAIL>,只要匹配@hit # file =", "也可以写成[a-zA-Z0-9_] # \\W 非数字字母_ # \\d 数字 # \\D 非数字 # . 所有", "= re.compile(r'@(.*?)\\.com') #万能表达式需要告诉在哪里结束 result = pattern.findall(a2) print(result) file.close() #打开文件记得关闭 ###################################################拓展: # import json", "#类里面的方法不能相互调用,单现在讲一个方法可以相互调用 #类的命名方式和方法命名方式不一样,类的命名方式,多个单词把首字母大写, 方法的是单词中间用下划线; # class PlusNum: # def plus_int(self,a,b): # a = int(a)", "非数字 # . 所有 # + 匹配一次或多次等于{1,} # {1,4} 匹配一次到4次 # {,4} 匹配至多四次", "或者[0-9] 如\\d{,2}可以写成[012] #\\w 字母数字_ 也可以写成[a-zA-Z0-9_] # \\W 非数字字母_ # \\d 数字 # \\D", "print(\"爷爷有的东西\") # class father1(grandfather): # def yeye(self): # print(\"父级有的东西\") # class son(father1): #", "# class father2(): # def money(self): # print(\"父级有的东西2\") # class son(father1,father2): # pass", "#打开文件记得关闭 # 比如匹配所有邮箱 # file = open('duban.json','r',encoding='utf-8') #读取这个文件 # a = file.read() #", "# def money(self): # print(\"父级有的东西2\") # class son(father1,father2): # pass # john =", "# result = pattern.findall(a2) # print(result) # file.close() #打开文件记得关闭 # .*? 代表啥意思=====代表万能表达式。 #", "# pass # john = son() # john.yeye() # 第一个父级没有,会找第二个父级,没有的话再找爷爷级 # class grandfather():", "a+b # def plus_float(self,a,b): # a = float(a) # b = float(b) #", "# class son(father1): # pass # john = son() # john.yeye() # 第一个父级没有,会找第二个父级,没有的话再找爷爷级", "# 复制代码 # class ClassTest(object): # __num = 0 # @classmethod # def", "# # pattern = re.compile(r'\\W+') #除掉数字、字母、下划线和汉字剩下的东西(大写的W) # # pattern = re.compile(r'\\D+') #非数字的一切内容 #", "# content = response.text # print(content) #打印获取整个的网页内容 # with open('duban.json','w',encoding='utf-8') as file: #把网页内容写到文件中", "# 如上,使用了静态方法(函数),然而方法体中并没使用(也不能使用)类或实例的属性(或方法)。若要获得当前时间的字符串时,并不一定需要实例化对象,此时对于静态方法而言,所在类更像是一种名称空间。 # 其实,我们也可以在类外面写一个同样的函数来做这些事,但是这样做就打乱了逻辑关系,也会导致以后代码维护困难。 # 以上就是我对Python的实例方法,类方法和静态方法之间的区别和作用的简要阐述。 #—————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————— import re import requests import json", "'<EMAIL>,song <EMAIL>,song!<EMAIL>' pattern = re.compile(r'@(.*?)\\.com') #万能表达式需要告诉在哪里结束 result = pattern.findall(a2) print(result) file.close() #打开文件记得关闭 ###################################################拓展:", "pass # john = son() # john.yeye() #python3继承顺序 # 新式类的继承方式是:先找最亲的爸爸(括号里面第一个继承的类),然后再去找第二个爸爸(括号里面第二个继承的类), #当爸爸类都找不到的时候,找第一个爸爸的父类 #类里面的方法不能相互调用,单现在讲一个方法可以相互调用 #类的命名方式和方法命名方式不一样,类的命名方式,多个单词把首字母大写,", "# . 所有 # + 匹配一次或多次等于{1,} # {1,4} 匹配一次到4次 # {,4} 匹配至多四次 #", "# 比如匹配所有邮箱 # file = open('duban.json','r',encoding='utf-8') #读取这个文件 # a = file.read() # a2", "= son() # john.yeye() #python3继承顺序 # 新式类的继承方式是:先找最亲的爸爸(括号里面第一个继承的类),然后再去找第二个爸爸(括号里面第二个继承的类), #当爸爸类都找不到的时候,找第一个爸爸的父类 #类里面的方法不能相互调用,单现在讲一个方法可以相互调用 #类的命名方式和方法命名方式不一样,类的命名方式,多个单词把首字母大写, 方法的是单词中间用下划线; # class", "{1,} 匹配至少一次 # ? 解除贪婪模式,接在次数的正则表达式后面使用 # * 表示匹配0次或多次,等于{0,} file = open('duban.json','r',encoding='utf-8') #读取这个文件 a", "file.close() #打开文件记得关闭 ###################################################拓展: # import json #json仅限于拿接口数据,content拿所有格式 # import requests # response =", "pattern.findall(a) #找到这个文件中所有的“新闻”字样 # print(result) # file.close() #打开文件记得关闭 # file = open('duban.json','r',encoding='utf-8') #读取这个文件 #", "#读取这个文件 # a = file.read() # a2 = '<EMAIL>,song <EMAIL>,<EMAIL>' # # pattern", "静态方法 # 使用装饰器@staticmethod。 # 静态方法是类中的函数,不需要实例。静态方法主要是用来存放逻辑性的代码,逻辑上属于类,但是和类本身没有关系,也就是说在静态方法中,不会涉及到类中的属性和方法的操作。可以理解为,静态方法是个独立的、单纯的函数,它仅仅托管于某个类的名称空间中,便于使用和维护。 # 譬如,我想定义一个关于时间操作的类,其中有一个获取当前时间的函数。 # 复制代码 # import time #", "self.second = second # @staticmethod # def showTime(): # return time.strftime(\"%H:%M:%S\", time.localtime()) #", "1 # @classmethod # def getNum(cls): # return cls.__num # # 这里我用到魔术方法__new__,主要是为了在创建实例的时候调用累加方法。 #", "print(\"父级有的东西\") # class son(father1): # pass # john = son() # john.yeye() #", "# class father2(grandfather): # def yeye(self): # print(\"父级有的东西2\") # class son(father1,father2): # pass", "return self.plus_int(a,b)+self.plus_float(c,d) #参数名字可以变,但是个数不能变 # num = PlusNum() # # print(num.plus_int(3,4)) # # print(num.plus_float(2.1,3.4))", "其实,我们也可以在类外面写一个同样的函数来做这些事,但是这样做就打乱了逻辑关系,也会导致以后代码维护困难。 # 以上就是我对Python的实例方法,类方法和静态方法之间的区别和作用的简要阐述。 #—————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————— import re import requests import json # response =", "= re.compile(r'\\d+') #跟上面的[1,]效果是一样的 # # pattern = re.compile(r'\\w') #把数字、字母、下划线、汉字都打印出来了 # # pattern =", "def yeye(self): # print(\"爷爷有的东西\") # class father1(grandfather): # def yeye(self): # print(\"父级有的东西\") #", "# pass # john = son() # john.yeye() #儿子层只能先在父级层找,找不到才去爷爷层找 # class grandfather(): #", "# 静态方法 # 定义:使用装饰器@staticmethod。参数随意,没有“self”和“cls”参数,但是方法体中不能使用类或实例的任何属性和方法; # 调用:实例对象和类对象都可以调用。 # 实例方法 # 简而言之,实例方法就是类的实例能够使用的方法。这里不做过多解释。 # 类方法 #", "a = file.read() # # pattern = re.compile(r'新闻') # # pattern = re.compile(r'\\d{1,10}')", "# @classmethod # def getNum(cls): # return cls.__num # # 这里我用到魔术方法__new__,主要是为了在创建实例的时候调用累加方法。 # def", "复制代码 # 静态方法 # 使用装饰器@staticmethod。 # 静态方法是类中的函数,不需要实例。静态方法主要是用来存放逻辑性的代码,逻辑上属于类,但是和类本身没有关系,也就是说在静态方法中,不会涉及到类中的属性和方法的操作。可以理解为,静态方法是个独立的、单纯的函数,它仅仅托管于某个类的名称空间中,便于使用和维护。 # 譬如,我想定义一个关于时间操作的类,其中有一个获取当前时间的函数。 # 复制代码 # import", "类方法 # 定义:使用装饰器@classmethod。第一个参数必须是当前类对象,该参数名一般约定为“cls”,通过它来传递类的属性和方法(不能传实例的属性和方法); # 调用:实例对象和类对象都可以调用。 # 静态方法 # 定义:使用装饰器@staticmethod。参数随意,没有“self”和“cls”参数,但是方法体中不能使用类或实例的任何属性和方法; # 调用:实例对象和类对象都可以调用。 # 实例方法", "调用:只能由实例对象调用。 # 类方法 # 定义:使用装饰器@classmethod。第一个参数必须是当前类对象,该参数名一般约定为“cls”,通过它来传递类的属性和方法(不能传实例的属性和方法); # 调用:实例对象和类对象都可以调用。 # 静态方法 # 定义:使用装饰器@staticmethod。参数随意,没有“self”和“cls”参数,但是方法体中不能使用类或实例的任何属性和方法; # 调用:实例对象和类对象都可以调用。", "# print('eat eggs') # r = Run # r.have_breakfast() #被对象调用 # Run.have_breakfast() #被类调用", "# class Student(ClassTest): # def __init__(self): # self.name = '' # a =", "print(result) # file.close() #打开文件记得关闭 # .*? 代表啥意思=====代表万能表达式。 # \\d 换成中括号可以用[0123456789] 或者[0-9] 如\\d{,2}可以写成[012] #\\w", "re.compile(r'\\W+') #除掉数字、字母、下划线和汉字剩下的东西(大写的W) # # pattern = re.compile(r'\\D+') #非数字的一切内容 # pattern = re.compile(r'\\w*') #表示匹配0此或者多次,等于[0,]", "# self.hour = hour # self.minute = minute # self.second = second #", "#当爸爸类都找不到的时候,找第一个爸爸的父类 #类里面的方法不能相互调用,单现在讲一个方法可以相互调用 #类的命名方式和方法命名方式不一样,类的命名方式,多个单词把首字母大写, 方法的是单词中间用下划线; # class PlusNum: # def plus_int(self,a,b): # a =", "\\d 数字 # \\D 非数字 # . 所有 # + 匹配一次或多次等于{1,} # {1,4}", "a = file.read() # a2 = '<HtMl>hello</hTmL>' #网页,要把hello匹配出来 # pattern = re.compile(r'<[Hh][Tt][Mm][Ll]>hello</[Hh][Tt][Mm][Ll]>') #中括号里面是你可以匹配的对象", "file.read() # a2 = '<EMAIL>,<EMAIL>,<EMAIL>' # # pattern = re.compile(r'.+@\\w+\\.com') #匹配所有邮箱,但是打印出来的是一组字符串,需要分开打印,用下面方法 # #", "<gh_stars>1-10 #多继承 # class father1(): # def have(self): # print(\"父级有的东西\") # class father2():", "# 首先,这三种方法都定义在类中。下面我先简单说一下怎么定义和调用的。(PS:实例对象的权限最大。) # 实例方法 # 定义:第一个参数必须是实例对象,该参数名一般约定为“self”,通过它来传递实例的属性和方法(也可以传类的属性和方法); # 调用:只能由实例对象调用。 # 类方法 # 定义:使用装饰器@classmethod。第一个参数必须是当前类对象,该参数名一般约定为“cls”,通过它来传递类的属性和方法(不能传实例的属性和方法); #", "open('duban.json','w',encoding='utf-8') as file: #把网页内容写到文件中 # file.write(content) ##############################################拓展: # file = open('duban.json','r',encoding='utf-8') #读取这个文件 #", "TimeTest(object): # def __init__(self, hour, minute, second): # self.hour = hour # self.minute", "= open('duban.json','r',encoding='utf-8') #读取这个文件 # a = file.read() # # pattern = re.compile(r'新闻') #", "= re.compile(r'.+@\\w+\\.com') #匹配所有邮箱,但是打印出来的是一组字符串,需要分开打印,用下面方法 # # pattern = re.compile(r'\\w+.\\w+@\\w+\\.com') #正常情况只要后面的\\w+@\\w+\\.com(正常的邮箱正则表达式)即可,但是因为此题前面有个点 # result = pattern.findall(a2)", "# print(TimeTest.showTime()) # t = TimeTest(2, 10, 10) # nowTime = t.showTime() #", "file.read() # a2 = '<EMAIL>,song <EMAIL>,<EMAIL>' # # pattern = re.compile(r'<EMAIL>') #因为‘。’导致都匹配上了 #", "#\\w 字母数字_ 也可以写成[a-zA-Z0-9_] # \\W 非数字字母_ # \\d 数字 # \\D 非数字 #", "pattern.findall(a2) # print(result) # file.close() #打开文件记得关闭 # # 题目:<EMAIL>,只要匹配@hit # file = open('duban.json','r',encoding='utf-8')", "def have_breakfast(): #静态方法括号为空,是针对于cls和self方法用的,可以传自己的参数如a,b等, # print('eat eggs') # r = Run # r.have_breakfast() #被对象调用", "PlusNum() # # print(num.plus_int(3,4)) # # print(num.plus_float(2.1,3.4)) # print(num.plus_all(1,2,3.3,4.3)) # 如下例子: # class", "复制代码 # class ClassTest(object): # __num = 0 # @classmethod # def addNum(cls):", "pattern.findall(a2) print(result) file.close() #打开文件记得关闭 ###################################################拓展: # import json #json仅限于拿接口数据,content拿所有格式 # import requests #", "son(father1,father2): # pass # john = son() # john.yeye() #python3继承顺序 # 新式类的继承方式是:先找最亲的爸爸(括号里面第一个继承的类),然后再去找第二个爸爸(括号里面第二个继承的类), #当爸爸类都找不到的时候,找第一个爸爸的父类", "Student() # print(ClassTest.getNum()) # 复制代码 # 静态方法 # 使用装饰器@staticmethod。 # 静态方法是类中的函数,不需要实例。静态方法主要是用来存放逻辑性的代码,逻辑上属于类,但是和类本身没有关系,也就是说在静态方法中,不会涉及到类中的属性和方法的操作。可以理解为,静态方法是个独立的、单纯的函数,它仅仅托管于某个类的名称空间中,便于使用和维护。 # 譬如,我想定义一个关于时间操作的类,其中有一个获取当前时间的函数。", "# print(result) # file.close() #打开文件记得关闭 # file = open('duban.json','r',encoding='utf-8') #读取这个文件 # a =", "father2(): # def have(self): # print(\"父级有的东西2\") # class son(father1,father2): # pass # john", "# @staticmethod # def showTime(): # return time.strftime(\"%H:%M:%S\", time.localtime()) # print(TimeTest.showTime()) # t", "= pattern.findall(a) #找到这个文件中所有的“新闻”字样 # print(result) # file.close() #打开文件记得关闭 # file = open('duban.json','r',encoding='utf-8') #读取这个文件", "print(TimeTest.showTime()) # t = TimeTest(2, 10, 10) # nowTime = t.showTime() # print(nowTime)", "# response = requests.get('http://news.baidu.com') #用这个方法访问百度新闻 # # print(str(response.text)) #类型是字符串类型 # # print(str(response.content)) #用concent会生成字节流,前面有个b,加上“encoding=‘utf-8’”就可以了", "实例方法 # 简而言之,实例方法就是类的实例能够使用的方法。这里不做过多解释。 # 类方法 # 使用装饰器@classmethod。 # 原则上,类方法是将类本身作为对象进行操作的方法。假设有个方法,且这个方法在逻辑上采用类本身作为对象来调用更合理,那么这个方法就可以定义为类方法。另外,如果需要继承,也可以定义为类方法。 # 如下场景: # 假设我有一个学生类和一个班级类,想要实现的功能为:", "第一个父级没有,会找第二个父级,没有的话再找爷爷级 # class grandfather(): # def yeye(self): # print(\"爷爷有的东西\") # class father1(grandfather): #", "def yeye(self): # print(\"爷爷有的东西\") # class father1(grandfather): # pass # class father2(grandfather): #", "# def showTime(): # return time.strftime(\"%H:%M:%S\", time.localtime()) # print(TimeTest.showTime()) # t = TimeTest(2,", "# pattern = re.compile(r'\\d{1,10}') #找到所有数字匹配,下标从一位到10位数字 # # pattern = re.compile(r'\\d{1,}') #左边不输入,代表从0开始,右边不输入,最大随便出现 取出这个文件中的所有数字 #", "\\D 非数字 # . 所有 # + 匹配一次或多次等于{1,} # {1,4} 匹配一次到4次 # {,4}", "class father1(): # def have(self): # print(\"父级有的东西\") # class father2(): # def have(self):", "file.close() #打开文件记得关闭 # file = open('duban.json','r',encoding='utf-8') #读取这个文件 # a = file.read() # a2", "# # pattern = re.compile(r'.') #'.'能匹配所有的东西,代表匹配所有 # pattern = re.compile(r'song\\.lu@errc\\.com') #在点前面加上反斜杠,就能完全匹配 # result", "#跟上面的[1,]效果是一样的 # # pattern = re.compile(r'\\w') #把数字、字母、下划线、汉字都打印出来了 # # pattern = re.compile(r'\\w+') #把数字、字母、下划线、汉字都打印连在一起", "@classmethod # def getNum(cls): # return cls.__num # # 这里我用到魔术方法__new__,主要是为了在创建实例的时候调用累加方法。 # def __new__(self):", "# pattern = re.compile(r'@.+\\.') #正则表达式默认贪婪模式,尽可能多的匹配点,会匹配到最后一个,如何避免呢。前面加个问号即可,如下: # pattern = re.compile(r'@.+?\\.') #正则表达式的点的懒惰模式,问号是解除贪婪模式变为懒惰模式 # result =", "# file = open('duban.json','r',encoding='utf-8') #读取这个文件 # a = file.read() # a2 = '<HtMl>hello</hTmL>'", "#————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————- # Python 实例方法、类方法、静态方法的区别与作用 # Python中至少有三种比较常见的方法类型,即实例方法,类方法、静态方法。它们是如何定义的呢?如何调用的呢?它们又有何区别和作用呢?且看下文。 # 首先,这三种方法都定义在类中。下面我先简单说一下怎么定义和调用的。(PS:实例对象的权限最大。) # 实例方法 # 定义:第一个参数必须是实例对象,该参数名一般约定为“self”,通过它来传递实例的属性和方法(也可以传类的属性和方法); #", "class son(father1,father2): # pass # john = son() # john.have() #可以一层套一层继承 # class", "cls.__num # # 这里我用到魔术方法__new__,主要是为了在创建实例的时候调用累加方法。 # def __new__(self): # ClassTest.addNum() # return super(ClassTest, self).__new__(self)", "# 实例方法 # 定义:第一个参数必须是实例对象,该参数名一般约定为“self”,通过它来传递实例的属性和方法(也可以传类的属性和方法); # 调用:只能由实例对象调用。 # 类方法 # 定义:使用装饰器@classmethod。第一个参数必须是当前类对象,该参数名一般约定为“cls”,通过它来传递类的属性和方法(不能传实例的属性和方法); # 调用:实例对象和类对象都可以调用。 #", "# pass # john = son() # john.yeye() #python3继承顺序 # 新式类的继承方式是:先找最亲的爸爸(括号里面第一个继承的类),然后再去找第二个爸爸(括号里面第二个继承的类), #当爸爸类都找不到的时候,找第一个爸爸的父类 #类里面的方法不能相互调用,单现在讲一个方法可以相互调用", "# return super(ClassTest, self).__new__(self) # class Student(ClassTest): # def __init__(self): # self.name =", "pass # john = son() # john.yeye() #儿子层只能先在父级层找,找不到才去爷爷层找 # class grandfather(): # def", "# class PlusNum: # def plus_int(self,a,b): # a = int(a) # b =", "调用:实例对象和类对象都可以调用。 # 实例方法 # 简而言之,实例方法就是类的实例能够使用的方法。这里不做过多解释。 # 类方法 # 使用装饰器@classmethod。 # 原则上,类方法是将类本身作为对象进行操作的方法。假设有个方法,且这个方法在逻辑上采用类本身作为对象来调用更合理,那么这个方法就可以定义为类方法。另外,如果需要继承,也可以定义为类方法。 # 如下场景:", "return a+b # def plus_float(self,a,b): # a = float(a) # b = float(b)", "# @staticmethod #类的静态方法,不传对象也不传类,既不属于类做的事情,也不属于对象做的事情,但可以被类和对象调用 # def have_breakfast(): #静态方法括号为空,是针对于cls和self方法用的,可以传自己的参数如a,b等, # print('eat eggs') # r =", "print(nowTime) # 复制代码 # 如上,使用了静态方法(函数),然而方法体中并没使用(也不能使用)类或实例的属性(或方法)。若要获得当前时间的字符串时,并不一定需要实例化对象,此时对于静态方法而言,所在类更像是一种名称空间。 # 其实,我们也可以在类外面写一个同样的函数来做这些事,但是这样做就打乱了逻辑关系,也会导致以后代码维护困难。 # 以上就是我对Python的实例方法,类方法和静态方法之间的区别和作用的简要阐述。 #—————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————— import re import", "print(\"父级有的东西2\") # class son(father1,father2): # pass # john = son() # john.have() #可以一层套一层继承", "# # pattern = re.compile(r'\\d{1,10}') #找到所有数字匹配,下标从一位到10位数字 # # pattern = re.compile(r'\\d{1,}') #左边不输入,代表从0开始,右边不输入,最大随便出现 取出这个文件中的所有数字", "假设我有一个学生类和一个班级类,想要实现的功能为: # 执行班级人数增加的操作、获得班级的总人数; # 学生类继承自班级类,每实例化一个学生,班级人数都能增加; # 最后,我想定义一些学生,获得班级中的总人数。 # 思考:这个问题用类方法做比较合适,为什么?因为我实例化的是学生,但是如果我从学生这一个实例中获得班级总人数,在逻辑上显然是不合理的。同时,如果想要获得班级总人数,如果生成一个班级的实例也是没有必要的。 # 复制代码 # class", "a = file.read() # a2 = '<EMAIL>,<EMAIL>,<EMAIL>' # # pattern = re.compile(r'.+@\\w+\\.com') #匹配所有邮箱,但是打印出来的是一组字符串,需要分开打印,用下面方法", "pattern = re.compile(r'\\w+') #把数字、字母、下划线、汉字都打印连在一起 # # pattern = re.compile(r'\\W+') #除掉数字、字母、下划线和汉字剩下的东西(大写的W) # # pattern", "ClassTest.addNum() # return super(ClassTest, self).__new__(self) # class Student(ClassTest): # def __init__(self): # self.name", "pattern = re.compile(r'\\w') #把数字、字母、下划线、汉字都打印出来了 # # pattern = re.compile(r'\\w+') #把数字、字母、下划线、汉字都打印连在一起 # # pattern", "= pattern.findall(a2) print(result) file.close() #打开文件记得关闭 ###################################################拓展: # import json #json仅限于拿接口数据,content拿所有格式 # import requests", "# 假设我有一个学生类和一个班级类,想要实现的功能为: # 执行班级人数增加的操作、获得班级的总人数; # 学生类继承自班级类,每实例化一个学生,班级人数都能增加; # 最后,我想定义一些学生,获得班级中的总人数。 # 思考:这个问题用类方法做比较合适,为什么?因为我实例化的是学生,但是如果我从学生这一个实例中获得班级总人数,在逻辑上显然是不合理的。同时,如果想要获得班级总人数,如果生成一个班级的实例也是没有必要的。 # 复制代码 #", "print(response) #打印获取的是状态码 # content = response.text # print(content) #打印获取整个的网页内容 # with open('duban.json','w',encoding='utf-8') as", "#被对象调用 # Run.have_breakfast() #被类调用 #————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————- # Python 实例方法、类方法、静态方法的区别与作用 # Python中至少有三种比较常见的方法类型,即实例方法,类方法、静态方法。它们是如何定义的呢?如何调用的呢?它们又有何区别和作用呢?且看下文。 # 首先,这三种方法都定义在类中。下面我先简单说一下怎么定义和调用的。(PS:实例对象的权限最大。) #", "open('duban.json','r',encoding='utf-8') #读取这个文件 # a = file.read() # a2 = '<EMAIL>,song <EMAIL>,<EMAIL>' # #", "hour # self.minute = minute # self.second = second # @staticmethod # def", "# # pattern = re.compile(r'\\d{1,}') #左边不输入,代表从0开始,右边不输入,最大随便出现 取出这个文件中的所有数字 # # pattern = re.compile(r'\\d+') #跟上面的[1,]效果是一样的", "#'.'能匹配所有的东西,代表匹配所有 # pattern = re.compile(r'song\\.lu@errc\\.com') #在点前面加上反斜杠,就能完全匹配 # result = pattern.findall(a2) # print(result) #", "# import requests # response = requests.get('http://news.baidu.com') #用这个方法访问百度新闻 # # print(str(response.text)) #类型是字符串类型 #", "= pattern.findall(a2) # print(result) # file.close() #打开文件记得关闭 # 比如匹配所有邮箱 # file = open('duban.json','r',encoding='utf-8')", "a2 = '<EMAIL>.cf.aa.ee.dd' # # pattern = re.compile(r'@.+\\.') #正则表达式默认贪婪模式,尽可能多的匹配点,会匹配到最后一个,如何避免呢。前面加个问号即可,如下: # pattern = re.compile(r'@.+?\\.')", "# class Act: # @classmethod #表示类的方法 # def use(cls): #加上了上面的,此处变为cls,是class的缩写 # print(\"www\") #", "#表示匹配0此或者多次,等于[0,] # result = pattern.findall(a) #找到这个文件中所有的“新闻”字样 # print(result) # file.close() #打开文件记得关闭 # file", "#正则表达式的点的懒惰模式,问号是解除贪婪模式变为懒惰模式 # result = pattern.findall(a2) # print(result) # file.close() #打开文件记得关闭 # file =", "# file.close() #打开文件记得关闭 # .*? 代表啥意思=====代表万能表达式。 # \\d 换成中括号可以用[0123456789] 或者[0-9] 如\\d{,2}可以写成[012] #\\w 字母数字_", "class PlusNum: # def plus_int(self,a,b): # a = int(a) # b = int(b)", "pattern = re.compile(r'\\d+') #跟上面的[1,]效果是一样的 # # pattern = re.compile(r'\\w') #把数字、字母、下划线、汉字都打印出来了 # # pattern", "如上,使用了静态方法(函数),然而方法体中并没使用(也不能使用)类或实例的属性(或方法)。若要获得当前时间的字符串时,并不一定需要实例化对象,此时对于静态方法而言,所在类更像是一种名称空间。 # 其实,我们也可以在类外面写一个同样的函数来做这些事,但是这样做就打乱了逻辑关系,也会导致以后代码维护困难。 # 以上就是我对Python的实例方法,类方法和静态方法之间的区别和作用的简要阐述。 #—————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————— import re import requests import json #", "静态方法是类中的函数,不需要实例。静态方法主要是用来存放逻辑性的代码,逻辑上属于类,但是和类本身没有关系,也就是说在静态方法中,不会涉及到类中的属性和方法的操作。可以理解为,静态方法是个独立的、单纯的函数,它仅仅托管于某个类的名称空间中,便于使用和维护。 # 譬如,我想定义一个关于时间操作的类,其中有一个获取当前时间的函数。 # 复制代码 # import time # class TimeTest(object): # def", "# def have(self): # print(\"父级有的东西\") # class father2(): # def money(self): # print(\"父级有的东西2\")", "john = son() # john.yeye() # 第一个父级没有,会找第二个父级,没有的话再找爷爷级 # class grandfather(): # def yeye(self):", "= t.showTime() # print(nowTime) # 复制代码 # 如上,使用了静态方法(函数),然而方法体中并没使用(也不能使用)类或实例的属性(或方法)。若要获得当前时间的字符串时,并不一定需要实例化对象,此时对于静态方法而言,所在类更像是一种名称空间。 # 其实,我们也可以在类外面写一个同样的函数来做这些事,但是这样做就打乱了逻辑关系,也会导致以后代码维护困难。 # 以上就是我对Python的实例方法,类方法和静态方法之间的区别和作用的简要阐述。 #——————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————", "# print(\"父级有的东西2\") # class son(father1,father2): # pass # john = son() #两个父级都调用 #如果两个父级有同样的东西,调用的是第一个里面的,优先继承第一个类", "a2 = '<EMAIL>,song <EMAIL>,song!<EMAIL>' pattern = re.compile(r'@(.*?)\\.com') #万能表达式需要告诉在哪里结束 result = pattern.findall(a2) print(result) file.close()", "class TimeTest(object): # def __init__(self, hour, minute, second): # self.hour = hour #", "# print(nowTime) # 复制代码 # 如上,使用了静态方法(函数),然而方法体中并没使用(也不能使用)类或实例的属性(或方法)。若要获得当前时间的字符串时,并不一定需要实例化对象,此时对于静态方法而言,所在类更像是一种名称空间。 # 其实,我们也可以在类外面写一个同样的函数来做这些事,但是这样做就打乱了逻辑关系,也会导致以后代码维护困难。 # 以上就是我对Python的实例方法,类方法和静态方法之间的区别和作用的简要阐述。 #—————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————— import re", "# response = requests.get('http://news.baidu.com') #用这个方法访问百度新闻 # print(response) #打印获取的是状态码 # content = response.text #", "= file.read() # a2 = '<EMAIL>.cf.aa.ee.dd' # # pattern = re.compile(r'@.+\\.') #正则表达式默认贪婪模式,尽可能多的匹配点,会匹配到最后一个,如何避免呢。前面加个问号即可,如下: #", "time.localtime()) # print(TimeTest.showTime()) # t = TimeTest(2, 10, 10) # nowTime = t.showTime()", "# file = open('duban.json','r',encoding='utf-8') #读取这个文件 # a = file.read() # # pattern =", "= Student() # print(ClassTest.getNum()) # 复制代码 # 静态方法 # 使用装饰器@staticmethod。 # 静态方法是类中的函数,不需要实例。静态方法主要是用来存放逻辑性的代码,逻辑上属于类,但是和类本身没有关系,也就是说在静态方法中,不会涉及到类中的属性和方法的操作。可以理解为,静态方法是个独立的、单纯的函数,它仅仅托管于某个类的名称空间中,便于使用和维护。 #", "result = pattern.findall(a2) # print(result) # file.close() #打开文件记得关闭 # 比如匹配所有邮箱 # file =", "= re.compile(r'<EMAIL>') #因为‘。’导致都匹配上了 # # pattern = re.compile(r'.') #'.'能匹配所有的东西,代表匹配所有 # pattern = re.compile(r'song\\.lu@errc\\.com')", "Student() # b = Student() # print(ClassTest.getNum()) # 复制代码 # 静态方法 # 使用装饰器@staticmethod。", "# 简而言之,实例方法就是类的实例能够使用的方法。这里不做过多解释。 # 类方法 # 使用装饰器@classmethod。 # 原则上,类方法是将类本身作为对象进行操作的方法。假设有个方法,且这个方法在逻辑上采用类本身作为对象来调用更合理,那么这个方法就可以定义为类方法。另外,如果需要继承,也可以定义为类方法。 # 如下场景: # 假设我有一个学生类和一个班级类,想要实现的功能为: #", "= open('duban.json','r',encoding='utf-8') #读取这个文件 # a = file.read() # a2 = '<EMAIL>,<EMAIL>,<EMAIL>' # #", "= re.compile(r'<[Hh][Tt][Mm][Ll]>hello</[Hh][Tt][Mm][Ll]>') #中括号里面是你可以匹配的对象 # result = pattern.findall(a2) # print(result) # file.close() #打开文件记得关闭 #", "# print(\"爷爷有的东西\") # class father1(grandfather): # pass # class father2(grandfather): # def yeye(self):", "class father1(grandfather): # def yeye(self): # print(\"父级有的东西\") # class son(father1): # pass #", "#打印获取整个的网页内容 # with open('duban.json','w',encoding='utf-8') as file: #把网页内容写到文件中 # file.write(content) ##############################################拓展: # file =", ".*? 代表啥意思=====代表万能表达式。 # \\d 换成中括号可以用[0123456789] 或者[0-9] 如\\d{,2}可以写成[012] #\\w 字母数字_ 也可以写成[a-zA-Z0-9_] # \\W 非数字字母_", "如\\d{,2}可以写成[012] #\\w 字母数字_ 也可以写成[a-zA-Z0-9_] # \\W 非数字字母_ # \\d 数字 # \\D 非数字", "class father1(): # def have(self): # print(\"父级有的东西\") # class father2(): # def money(self):", "r = Run # r.have_breakfast() #被对象调用 # Run.have_breakfast() #被类调用 #————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————- # Python 实例方法、类方法、静态方法的区别与作用", "# a = file.read() # a2 = '<EMAIL>,song <EMAIL>,<EMAIL>' # # pattern =", "{,4} 匹配至多四次 # {1,} 匹配至少一次 # ? 解除贪婪模式,接在次数的正则表达式后面使用 # * 表示匹配0次或多次,等于{0,} file =", "= int(b) # return a+b # def plus_float(self,a,b): # a = float(a) #", "# \\d 换成中括号可以用[0123456789] 或者[0-9] 如\\d{,2}可以写成[012] #\\w 字母数字_ 也可以写成[a-zA-Z0-9_] # \\W 非数字字母_ # \\d", "执行班级人数增加的操作、获得班级的总人数; # 学生类继承自班级类,每实例化一个学生,班级人数都能增加; # 最后,我想定义一些学生,获得班级中的总人数。 # 思考:这个问题用类方法做比较合适,为什么?因为我实例化的是学生,但是如果我从学生这一个实例中获得班级总人数,在逻辑上显然是不合理的。同时,如果想要获得班级总人数,如果生成一个班级的实例也是没有必要的。 # 复制代码 # class ClassTest(object): #", ". 所有 # + 匹配一次或多次等于{1,} # {1,4} 匹配一次到4次 # {,4} 匹配至多四次 # {1,}", "a = file.read() # a2 = '<EMAIL>,song <EMAIL>,<EMAIL>' # # pattern = re.compile(r'<EMAIL>')", "# def yeye(self): # print(\"父级有的东西\") # class son(father1): # pass # john =", "#加上了上面的,此处变为cls,是class的缩写 # print(\"www\") # Act.use() #类方法不仅可以被类调用,还可以被对象调用 # class Run: # @staticmethod #类的静态方法,不传对象也不传类,既不属于类做的事情,也不属于对象做的事情,但可以被类和对象调用 #", "Student(ClassTest): # def __init__(self): # self.name = '' # a = Student() #", "# def __new__(self): # ClassTest.addNum() # return super(ClassTest, self).__new__(self) # class Student(ClassTest): #", "# print(result) # file.close() #打开文件记得关闭 # .*? 代表啥意思=====代表万能表达式。 # \\d 换成中括号可以用[0123456789] 或者[0-9] 如\\d{,2}可以写成[012]", "? 解除贪婪模式,接在次数的正则表达式后面使用 # * 表示匹配0次或多次,等于{0,} file = open('duban.json','r',encoding='utf-8') #读取这个文件 a = file.read() a2", "# 复制代码 # 如上,使用了静态方法(函数),然而方法体中并没使用(也不能使用)类或实例的属性(或方法)。若要获得当前时间的字符串时,并不一定需要实例化对象,此时对于静态方法而言,所在类更像是一种名称空间。 # 其实,我们也可以在类外面写一个同样的函数来做这些事,但是这样做就打乱了逻辑关系,也会导致以后代码维护困难。 # 以上就是我对Python的实例方法,类方法和静态方法之间的区别和作用的简要阐述。 #—————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————— import re import requests", "Python中至少有三种比较常见的方法类型,即实例方法,类方法、静态方法。它们是如何定义的呢?如何调用的呢?它们又有何区别和作用呢?且看下文。 # 首先,这三种方法都定义在类中。下面我先简单说一下怎么定义和调用的。(PS:实例对象的权限最大。) # 实例方法 # 定义:第一个参数必须是实例对象,该参数名一般约定为“self”,通过它来传递实例的属性和方法(也可以传类的属性和方法); # 调用:只能由实例对象调用。 # 类方法 # 定义:使用装饰器@classmethod。第一个参数必须是当前类对象,该参数名一般约定为“cls”,通过它来传递类的属性和方法(不能传实例的属性和方法);", "= re.compile(r'\\w') #把数字、字母、下划线、汉字都打印出来了 # # pattern = re.compile(r'\\w+') #把数字、字母、下划线、汉字都打印连在一起 # # pattern =", "# a = file.read() # a2 = '<EMAIL>.cf.aa.ee.dd' # # pattern = re.compile(r'@.+\\.')", "= son() # john.have() #可以一层套一层继承 # class grandfather(): # def yeye(self): # print(\"爷爷有的东西\")", "plus_float(self,a,b): # a = float(a) # b = float(b) # return a+b #", "float(a) # b = float(b) # return a+b # def plus_all(self,a,b,c,d): # return", "# john = son() # john.have() #可以一层套一层继承 # class grandfather(): # def yeye(self):", "# a2 = '<HtMl>hello</hTmL>' #网页,要把hello匹配出来 # pattern = re.compile(r'<[Hh][Tt][Mm][Ll]>hello</[Hh][Tt][Mm][Ll]>') #中括号里面是你可以匹配的对象 # result =", "# self.second = second # @staticmethod # def showTime(): # return time.strftime(\"%H:%M:%S\", time.localtime())", "son() # john.yeye() #儿子层只能先在父级层找,找不到才去爷爷层找 # class grandfather(): # def yeye(self): # print(\"爷爷有的东西\") #", "# a = float(a) # b = float(b) # return a+b # def", "#—————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————— import re import requests import json # response = requests.get('http://news.baidu.com') #用这个方法访问百度新闻 #", "# pattern = re.compile(r'<[Hh][Tt][Mm][Ll]>hello</[Hh][Tt][Mm][Ll]>') #中括号里面是你可以匹配的对象 # result = pattern.findall(a2) # print(result) # file.close()", "新式类的继承方式是:先找最亲的爸爸(括号里面第一个继承的类),然后再去找第二个爸爸(括号里面第二个继承的类), #当爸爸类都找不到的时候,找第一个爸爸的父类 #类里面的方法不能相互调用,单现在讲一个方法可以相互调用 #类的命名方式和方法命名方式不一样,类的命名方式,多个单词把首字母大写, 方法的是单词中间用下划线; # class PlusNum: # def plus_int(self,a,b): # a", "def have(self): # print(\"父级有的东西\") # class father2(): # def money(self): # print(\"父级有的东西2\") #", "grandfather(): # def yeye(self): # print(\"爷爷有的东西\") # class father1(grandfather): # pass # class", "pattern = re.compile(r'\\w+.\\w+@\\w+\\.com') #正常情况只要后面的\\w+@\\w+\\.com(正常的邮箱正则表达式)即可,但是因为此题前面有个点 # result = pattern.findall(a2) # print(result) # file.close() #打开文件记得关闭", "最后,我想定义一些学生,获得班级中的总人数。 # 思考:这个问题用类方法做比较合适,为什么?因为我实例化的是学生,但是如果我从学生这一个实例中获得班级总人数,在逻辑上显然是不合理的。同时,如果想要获得班级总人数,如果生成一个班级的实例也是没有必要的。 # 复制代码 # class ClassTest(object): # __num = 0 #", "requests.get('http://news.baidu.com') #用这个方法访问百度新闻 # print(response) #打印获取的是状态码 # content = response.text # print(content) #打印获取整个的网页内容 #", "# pattern = re.compile(r'song\\.lu@errc\\.com') #在点前面加上反斜杠,就能完全匹配 # result = pattern.findall(a2) # print(result) # file.close()", "# 定义:使用装饰器@staticmethod。参数随意,没有“self”和“cls”参数,但是方法体中不能使用类或实例的任何属性和方法; # 调用:实例对象和类对象都可以调用。 # 实例方法 # 简而言之,实例方法就是类的实例能够使用的方法。这里不做过多解释。 # 类方法 # 使用装饰器@classmethod。 #", "open('duban.json','r',encoding='utf-8') #读取这个文件 # a = file.read() # # pattern = re.compile(r'新闻') # #", "= file.read() # a2 = '<HtMl>hello</hTmL>' #网页,要把hello匹配出来 # pattern = re.compile(r'<[Hh][Tt][Mm][Ll]>hello</[Hh][Tt][Mm][Ll]>') #中括号里面是你可以匹配的对象 #", "# 类方法 # 定义:使用装饰器@classmethod。第一个参数必须是当前类对象,该参数名一般约定为“cls”,通过它来传递类的属性和方法(不能传实例的属性和方法); # 调用:实例对象和类对象都可以调用。 # 静态方法 # 定义:使用装饰器@staticmethod。参数随意,没有“self”和“cls”参数,但是方法体中不能使用类或实例的任何属性和方法; # 调用:实例对象和类对象都可以调用。 #", "def __new__(self): # ClassTest.addNum() # return super(ClassTest, self).__new__(self) # class Student(ClassTest): # def", "# a = file.read() # # pattern = re.compile(r'新闻') # # pattern =", "yeye(self): # print(\"父级有的东西2\") # class son(father1,father2): # pass # john = son() #", "# nowTime = t.showTime() # print(nowTime) # 复制代码 # 如上,使用了静态方法(函数),然而方法体中并没使用(也不能使用)类或实例的属性(或方法)。若要获得当前时间的字符串时,并不一定需要实例化对象,此时对于静态方法而言,所在类更像是一种名称空间。 # 其实,我们也可以在类外面写一个同样的函数来做这些事,但是这样做就打乱了逻辑关系,也会导致以后代码维护困难。 #", "学生类继承自班级类,每实例化一个学生,班级人数都能增加; # 最后,我想定义一些学生,获得班级中的总人数。 # 思考:这个问题用类方法做比较合适,为什么?因为我实例化的是学生,但是如果我从学生这一个实例中获得班级总人数,在逻辑上显然是不合理的。同时,如果想要获得班级总人数,如果生成一个班级的实例也是没有必要的。 # 复制代码 # class ClassTest(object): # __num =", "# class father2(): # def have(self): # print(\"父级有的东西2\") # class son(father1,father2): # pass", "print('eat eggs') # r = Run # r.have_breakfast() #被对象调用 # Run.have_breakfast() #被类调用 #————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————-", "比如匹配所有邮箱 # file = open('duban.json','r',encoding='utf-8') #读取这个文件 # a = file.read() # a2 =", "class father1(grandfather): # def have(self): # print(\"父级有的东西\") # class father2(grandfather): # def yiu(self):", "have(self): # print(\"父级有的东西\") # class father2(grandfather): # def yiu(self): # print(\"父级有的东西2\") # class", "float(b) # return a+b # def plus_all(self,a,b,c,d): # return self.plus_int(a,b)+self.plus_float(c,d) #参数名字可以变,但是个数不能变 # num", "response = requests.get('http://news.baidu.com') #用这个方法访问百度新闻 # print(response) #打印获取的是状态码 # content = response.text # print(content)", "father2(grandfather): # def yeye(self): # print(\"父级有的东西2\") # class son(father1,father2): # pass # john", "Run: # @staticmethod #类的静态方法,不传对象也不传类,既不属于类做的事情,也不属于对象做的事情,但可以被类和对象调用 # def have_breakfast(): #静态方法括号为空,是针对于cls和self方法用的,可以传自己的参数如a,b等, # print('eat eggs') # r", "= 0 # @classmethod # def addNum(cls): # cls.__num += 1 # @classmethod", "__init__(self): # self.name = '' # a = Student() # b = Student()", "# return a+b # def plus_float(self,a,b): # a = float(a) # b =", "取出这个文件中的所有数字 # # pattern = re.compile(r'\\d+') #跟上面的[1,]效果是一样的 # # pattern = re.compile(r'\\w') #把数字、字母、下划线、汉字都打印出来了", "class son(father1,father2): # pass # john = son() # john.yeye() #儿子层只能先在父级层找,找不到才去爷爷层找 # class", "# class father1(grandfather): # def yeye(self): # print(\"父级有的东西\") # class son(father1): # pass", "= '<EMAIL>.cf.aa.ee.dd' # # pattern = re.compile(r'@.+\\.') #正则表达式默认贪婪模式,尽可能多的匹配点,会匹配到最后一个,如何避免呢。前面加个问号即可,如下: # pattern = re.compile(r'@.+?\\.') #正则表达式的点的懒惰模式,问号是解除贪婪模式变为懒惰模式", "= open('duban.json','r',encoding='utf-8') #读取这个文件 # a = file.read() # a2 = '<EMAIL>,song <EMAIL>,<EMAIL>' #", "#打开文件记得关闭 # # 题目:<EMAIL>,只要匹配@hit # file = open('duban.json','r',encoding='utf-8') #读取这个文件 # a = file.read()", "int(a) # b = int(b) # return a+b # def plus_float(self,a,b): # a", "a = float(a) # b = float(b) # return a+b # def plus_all(self,a,b,c,d):", "result = pattern.findall(a2) print(result) file.close() #打开文件记得关闭 ###################################################拓展: # import json #json仅限于拿接口数据,content拿所有格式 # import", "# john.yeye() #python3继承顺序 # 新式类的继承方式是:先找最亲的爸爸(括号里面第一个继承的类),然后再去找第二个爸爸(括号里面第二个继承的类), #当爸爸类都找不到的时候,找第一个爸爸的父类 #类里面的方法不能相互调用,单现在讲一个方法可以相互调用 #类的命名方式和方法命名方式不一样,类的命名方式,多个单词把首字母大写, 方法的是单词中间用下划线; # class PlusNum: #", "content = response.text # print(content) #打印获取整个的网页内容 # with open('duban.json','w',encoding='utf-8') as file: #把网页内容写到文件中 #", "with open('duban.json','w',encoding='utf-8') as file: #把网页内容写到文件中 # file.write(content) ##############################################拓展: # file = open('duban.json','r',encoding='utf-8') #读取这个文件", "思考:这个问题用类方法做比较合适,为什么?因为我实例化的是学生,但是如果我从学生这一个实例中获得班级总人数,在逻辑上显然是不合理的。同时,如果想要获得班级总人数,如果生成一个班级的实例也是没有必要的。 # 复制代码 # class ClassTest(object): # __num = 0 # @classmethod #", "son() # john.have() #可以一层套一层继承 # class grandfather(): # def yeye(self): # print(\"爷爷有的东西\") #", "def __init__(self, hour, minute, second): # self.hour = hour # self.minute = minute", "# \\D 非数字 # . 所有 # + 匹配一次或多次等于{1,} # {1,4} 匹配一次到4次 #", "= '<EMAIL>,song <EMAIL>,<EMAIL>' # # pattern = re.compile(r'<EMAIL>') #因为‘。’导致都匹配上了 # # pattern =", "= re.compile(r'\\W+') #除掉数字、字母、下划线和汉字剩下的东西(大写的W) # # pattern = re.compile(r'\\D+') #非数字的一切内容 # pattern = re.compile(r'\\w*')", "open('duban.json','r',encoding='utf-8') #读取这个文件 # a = file.read() # a2 = '<HtMl>hello</hTmL>' #网页,要把hello匹配出来 # pattern", "# 最后,我想定义一些学生,获得班级中的总人数。 # 思考:这个问题用类方法做比较合适,为什么?因为我实例化的是学生,但是如果我从学生这一个实例中获得班级总人数,在逻辑上显然是不合理的。同时,如果想要获得班级总人数,如果生成一个班级的实例也是没有必要的。 # 复制代码 # class ClassTest(object): # __num = 0", "# @classmethod # def addNum(cls): # cls.__num += 1 # @classmethod # def", "#把网页内容写到文件中 # file.write(content) ##############################################拓展: # file = open('duban.json','r',encoding='utf-8') #读取这个文件 # a = file.read()", "= pattern.findall(a2) # print(result) # file.close() #打开文件记得关闭 # file = open('duban.json','r',encoding='utf-8') #读取这个文件 #", "have_breakfast(): #静态方法括号为空,是针对于cls和self方法用的,可以传自己的参数如a,b等, # print('eat eggs') # r = Run # r.have_breakfast() #被对象调用 #", "re.compile(r'<[Hh][Tt][Mm][Ll]>hello</[Hh][Tt][Mm][Ll]>') #中括号里面是你可以匹配的对象 # result = pattern.findall(a2) # print(result) # file.close() #打开文件记得关闭 # .*?", "# return time.strftime(\"%H:%M:%S\", time.localtime()) # print(TimeTest.showTime()) # t = TimeTest(2, 10, 10) #", "###################################################拓展: # import json #json仅限于拿接口数据,content拿所有格式 # import requests # response = requests.get('http://news.baidu.com') #用这个方法访问百度新闻", "# 以上就是我对Python的实例方法,类方法和静态方法之间的区别和作用的简要阐述。 #—————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————— import re import requests import json # response = requests.get('http://news.baidu.com')", "# pass # john = son() # john.have() #可以一层套一层继承 # class grandfather(): #", "# t = TimeTest(2, 10, 10) # nowTime = t.showTime() # print(nowTime) #", "re.compile(r'\\w') #把数字、字母、下划线、汉字都打印出来了 # # pattern = re.compile(r'\\w+') #把数字、字母、下划线、汉字都打印连在一起 # # pattern = re.compile(r'\\W+')", "10, 10) # nowTime = t.showTime() # print(nowTime) # 复制代码 # 如上,使用了静态方法(函数),然而方法体中并没使用(也不能使用)类或实例的属性(或方法)。若要获得当前时间的字符串时,并不一定需要实例化对象,此时对于静态方法而言,所在类更像是一种名称空间。 #", "# 调用:只能由实例对象调用。 # 类方法 # 定义:使用装饰器@classmethod。第一个参数必须是当前类对象,该参数名一般约定为“cls”,通过它来传递类的属性和方法(不能传实例的属性和方法); # 调用:实例对象和类对象都可以调用。 # 静态方法 # 定义:使用装饰器@staticmethod。参数随意,没有“self”和“cls”参数,但是方法体中不能使用类或实例的任何属性和方法; #", "# def addNum(cls): # cls.__num += 1 # @classmethod # def getNum(cls): #", "import json # response = requests.get('http://news.baidu.com') #用这个方法访问百度新闻 # print(response) #打印获取的是状态码 # content =", "print(content) #打印获取整个的网页内容 # with open('duban.json','w',encoding='utf-8') as file: #把网页内容写到文件中 # file.write(content) ##############################################拓展: # file", "re.compile(r'\\w*') #表示匹配0此或者多次,等于[0,] # result = pattern.findall(a) #找到这个文件中所有的“新闻”字样 # print(result) # file.close() #打开文件记得关闭 #", "file.read() a2 = '<EMAIL>,song <EMAIL>,song!<EMAIL>' pattern = re.compile(r'@(.*?)\\.com') #万能表达式需要告诉在哪里结束 result = pattern.findall(a2) print(result)", "#读取这个文件 # a = file.read() # # pattern = re.compile(r'新闻') # # pattern", "re.compile(r'\\w+.\\w+@\\w+\\.com') #正常情况只要后面的\\w+@\\w+\\.com(正常的邮箱正则表达式)即可,但是因为此题前面有个点 # result = pattern.findall(a2) # print(result) # file.close() #打开文件记得关闭 # #", "<EMAIL>,<EMAIL>' # # pattern = re.compile(r'<EMAIL>') #因为‘。’导致都匹配上了 # # pattern = re.compile(r'.') #'.'能匹配所有的东西,代表匹配所有", "# # pattern = re.compile(r'\\w+.\\w+@\\w+\\.com') #正常情况只要后面的\\w+@\\w+\\.com(正常的邮箱正则表达式)即可,但是因为此题前面有个点 # result = pattern.findall(a2) # print(result) #", "# # 题目:<EMAIL>,只要匹配@hit # file = open('duban.json','r',encoding='utf-8') #读取这个文件 # a = file.read() #", "# Run.have_breakfast() #被类调用 #————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————- # Python 实例方法、类方法、静态方法的区别与作用 # Python中至少有三种比较常见的方法类型,即实例方法,类方法、静态方法。它们是如何定义的呢?如何调用的呢?它们又有何区别和作用呢?且看下文。 # 首先,这三种方法都定义在类中。下面我先简单说一下怎么定义和调用的。(PS:实例对象的权限最大。) # 实例方法", "# print(\"父级有的东西\") # class father2(grandfather): # def yiu(self): # print(\"父级有的东西2\") # class son(father1,father2):", "# def use(cls): #加上了上面的,此处变为cls,是class的缩写 # print(\"www\") # Act.use() #类方法不仅可以被类调用,还可以被对象调用 # class Run: #", "father1(): # def have(self): # print(\"父级有的东西\") # class father2(): # def money(self): #", "# class father1(grandfather): # def have(self): # print(\"父级有的东西\") # class father2(grandfather): # def", "# print(\"父级有的东西\") # class son(father1): # pass # john = son() # john.yeye()", "# 新式类的继承方式是:先找最亲的爸爸(括号里面第一个继承的类),然后再去找第二个爸爸(括号里面第二个继承的类), #当爸爸类都找不到的时候,找第一个爸爸的父类 #类里面的方法不能相互调用,单现在讲一个方法可以相互调用 #类的命名方式和方法命名方式不一样,类的命名方式,多个单词把首字母大写, 方法的是单词中间用下划线; # class PlusNum: # def plus_int(self,a,b): #", "# print(\"www\") # Act.use() #类方法不仅可以被类调用,还可以被对象调用 # class Run: # @staticmethod #类的静态方法,不传对象也不传类,既不属于类做的事情,也不属于对象做的事情,但可以被类和对象调用 # def", "# 定义:使用装饰器@classmethod。第一个参数必须是当前类对象,该参数名一般约定为“cls”,通过它来传递类的属性和方法(不能传实例的属性和方法); # 调用:实例对象和类对象都可以调用。 # 静态方法 # 定义:使用装饰器@staticmethod。参数随意,没有“self”和“cls”参数,但是方法体中不能使用类或实例的任何属性和方法; # 调用:实例对象和类对象都可以调用。 # 实例方法 #", "self.name = '' # a = Student() # b = Student() # print(ClassTest.getNum())", "import re import requests import json # response = requests.get('http://news.baidu.com') #用这个方法访问百度新闻 # print(response)", "# 题目:<EMAIL>,只要匹配@hit # file = open('duban.json','r',encoding='utf-8') #读取这个文件 # a = file.read() # a2", "#中括号里面是你可以匹配的对象 # result = pattern.findall(a2) # print(result) # file.close() #打开文件记得关闭 # .*? 代表啥意思=====代表万能表达式。", "# print(\"爷爷有的东西\") # class father1(grandfather): # def yeye(self): # print(\"父级有的东西\") # class son(father1):", "换成中括号可以用[0123456789] 或者[0-9] 如\\d{,2}可以写成[012] #\\w 字母数字_ 也可以写成[a-zA-Z0-9_] # \\W 非数字字母_ # \\d 数字 #", "# class father1(grandfather): # pass # class father2(grandfather): # def yeye(self): # print(\"父级有的东西2\")", "t.showTime() # print(nowTime) # 复制代码 # 如上,使用了静态方法(函数),然而方法体中并没使用(也不能使用)类或实例的属性(或方法)。若要获得当前时间的字符串时,并不一定需要实例化对象,此时对于静态方法而言,所在类更像是一种名称空间。 # 其实,我们也可以在类外面写一个同样的函数来做这些事,但是这样做就打乱了逻辑关系,也会导致以后代码维护困难。 # 以上就是我对Python的实例方法,类方法和静态方法之间的区别和作用的简要阐述。 #—————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————— import", "# print(content) #打印获取整个的网页内容 # with open('duban.json','w',encoding='utf-8') as file: #把网页内容写到文件中 # file.write(content) ##############################################拓展: #", "# pattern = re.compile(r'<EMAIL>') #因为‘。’导致都匹配上了 # # pattern = re.compile(r'.') #'.'能匹配所有的东西,代表匹配所有 # pattern", "= response.text # print(content) #打印获取整个的网页内容 # with open('duban.json','w',encoding='utf-8') as file: #把网页内容写到文件中 # file.write(content)", "# .*? 代表啥意思=====代表万能表达式。 # \\d 换成中括号可以用[0123456789] 或者[0-9] 如\\d{,2}可以写成[012] #\\w 字母数字_ 也可以写成[a-zA-Z0-9_] # \\W", "file.read() # a2 = '<EMAIL>.cf.aa.ee.dd' # # pattern = re.compile(r'@.+\\.') #正则表达式默认贪婪模式,尽可能多的匹配点,会匹配到最后一个,如何避免呢。前面加个问号即可,如下: # pattern", "# file = open('duban.json','r',encoding='utf-8') #读取这个文件 # a = file.read() # a2 = '<EMAIL>,song", "super(ClassTest, self).__new__(self) # class Student(ClassTest): # def __init__(self): # self.name = '' #", "# class Run: # @staticmethod #类的静态方法,不传对象也不传类,既不属于类做的事情,也不属于对象做的事情,但可以被类和对象调用 # def have_breakfast(): #静态方法括号为空,是针对于cls和self方法用的,可以传自己的参数如a,b等, # print('eat eggs')", "re.compile(r'\\d+') #跟上面的[1,]效果是一样的 # # pattern = re.compile(r'\\w') #把数字、字母、下划线、汉字都打印出来了 # # pattern = re.compile(r'\\w+')", "简而言之,实例方法就是类的实例能够使用的方法。这里不做过多解释。 # 类方法 # 使用装饰器@classmethod。 # 原则上,类方法是将类本身作为对象进行操作的方法。假设有个方法,且这个方法在逻辑上采用类本身作为对象来调用更合理,那么这个方法就可以定义为类方法。另外,如果需要继承,也可以定义为类方法。 # 如下场景: # 假设我有一个学生类和一个班级类,想要实现的功能为: # 执行班级人数增加的操作、获得班级的总人数;", "pattern = re.compile(r'<EMAIL>') #因为‘。’导致都匹配上了 # # pattern = re.compile(r'.') #'.'能匹配所有的东西,代表匹配所有 # pattern =", "# pass # class father2(grandfather): # def yeye(self): # print(\"父级有的东西2\") # class son(father1,father2):", "file = open('duban.json','r',encoding='utf-8') #读取这个文件 # a = file.read() # a2 = '<EMAIL>,<EMAIL>,<EMAIL>' #", "def yeye(self): # print(\"爷爷有的东西\") # class father1(grandfather): # def have(self): # print(\"父级有的东西\") #", "father1(grandfather): # pass # class father2(grandfather): # def yeye(self): # print(\"父级有的东西2\") # class", "# file = open('duban.json','r',encoding='utf-8') #读取这个文件 # a = file.read() # a2 = '<EMAIL>,<EMAIL>,<EMAIL>'", "file: #把网页内容写到文件中 # file.write(content) ##############################################拓展: # file = open('duban.json','r',encoding='utf-8') #读取这个文件 # a =", "# @classmethod #表示类的方法 # def use(cls): #加上了上面的,此处变为cls,是class的缩写 # print(\"www\") # Act.use() #类方法不仅可以被类调用,还可以被对象调用 #", "= re.compile(r'@.+?\\.') #正则表达式的点的懒惰模式,问号是解除贪婪模式变为懒惰模式 # result = pattern.findall(a2) # print(result) # file.close() #打开文件记得关闭 #", "money(self): # print(\"父级有的东西2\") # class son(father1,father2): # pass # john = son() #两个父级都调用", "#读取这个文件 a = file.read() a2 = '<EMAIL>,song <EMAIL>,song!<EMAIL>' pattern = re.compile(r'@(.*?)\\.com') #万能表达式需要告诉在哪里结束 result", "所有 # + 匹配一次或多次等于{1,} # {1,4} 匹配一次到4次 # {,4} 匹配至多四次 # {1,} 匹配至少一次", "= re.compile(r'\\w+') #把数字、字母、下划线、汉字都打印连在一起 # # pattern = re.compile(r'\\W+') #除掉数字、字母、下划线和汉字剩下的东西(大写的W) # # pattern =", "print(result) file.close() #打开文件记得关闭 ###################################################拓展: # import json #json仅限于拿接口数据,content拿所有格式 # import requests # response", "首先,这三种方法都定义在类中。下面我先简单说一下怎么定义和调用的。(PS:实例对象的权限最大。) # 实例方法 # 定义:第一个参数必须是实例对象,该参数名一般约定为“self”,通过它来传递实例的属性和方法(也可以传类的属性和方法); # 调用:只能由实例对象调用。 # 类方法 # 定义:使用装饰器@classmethod。第一个参数必须是当前类对象,该参数名一般约定为“cls”,通过它来传递类的属性和方法(不能传实例的属性和方法); # 调用:实例对象和类对象都可以调用。", "#正常情况只要后面的\\w+@\\w+\\.com(正常的邮箱正则表达式)即可,但是因为此题前面有个点 # result = pattern.findall(a2) # print(result) # file.close() #打开文件记得关闭 # # 题目:<EMAIL>,只要匹配@hit", "john = son() # john.yeye() #python3继承顺序 # 新式类的继承方式是:先找最亲的爸爸(括号里面第一个继承的类),然后再去找第二个爸爸(括号里面第二个继承的类), #当爸爸类都找不到的时候,找第一个爸爸的父类 #类里面的方法不能相互调用,单现在讲一个方法可以相互调用 #类的命名方式和方法命名方式不一样,类的命名方式,多个单词把首字母大写, 方法的是单词中间用下划线; #", "john.yeye() # 第一个父级没有,会找第二个父级,没有的话再找爷爷级 # class grandfather(): # def yeye(self): # print(\"爷爷有的东西\") # class", "pattern.findall(a2) # print(result) # file.close() #打开文件记得关闭 # .*? 代表啥意思=====代表万能表达式。 # \\d 换成中括号可以用[0123456789] 或者[0-9]", "代表啥意思=====代表万能表达式。 # \\d 换成中括号可以用[0123456789] 或者[0-9] 如\\d{,2}可以写成[012] #\\w 字母数字_ 也可以写成[a-zA-Z0-9_] # \\W 非数字字母_ #", "son(father1,father2): # pass # john = son() # john.yeye() #儿子层只能先在父级层找,找不到才去爷爷层找 # class grandfather():", "pattern = re.compile(r'\\D+') #非数字的一切内容 # pattern = re.compile(r'\\w*') #表示匹配0此或者多次,等于[0,] # result = pattern.findall(a)", "import json #json仅限于拿接口数据,content拿所有格式 # import requests # response = requests.get('http://news.baidu.com') #用这个方法访问百度新闻 # #", "'<EMAIL>.cf.aa.ee.dd' # # pattern = re.compile(r'@.+\\.') #正则表达式默认贪婪模式,尽可能多的匹配点,会匹配到最后一个,如何避免呢。前面加个问号即可,如下: # pattern = re.compile(r'@.+?\\.') #正则表达式的点的懒惰模式,问号是解除贪婪模式变为懒惰模式 #", "# pattern = re.compile(r'\\D+') #非数字的一切内容 # pattern = re.compile(r'\\w*') #表示匹配0此或者多次,等于[0,] # result =", "= Student() # b = Student() # print(ClassTest.getNum()) # 复制代码 # 静态方法 #", "# file = open('duban.json','r',encoding='utf-8') #读取这个文件 # a = file.read() # a2 = '<EMAIL>.cf.aa.ee.dd'", "b = float(b) # return a+b # def plus_all(self,a,b,c,d): # return self.plus_int(a,b)+self.plus_float(c,d) #参数名字可以变,但是个数不能变", "# class grandfather(): # def yeye(self): # print(\"爷爷有的东西\") # class father1(grandfather): # def", "# # 这里我用到魔术方法__new__,主要是为了在创建实例的时候调用累加方法。 # def __new__(self): # ClassTest.addNum() # return super(ClassTest, self).__new__(self) #", "a = file.read() # a2 = '<EMAIL>.cf.aa.ee.dd' # # pattern = re.compile(r'@.+\\.') #正则表达式默认贪婪模式,尽可能多的匹配点,会匹配到最后一个,如何避免呢。前面加个问号即可,如下:", "def use(cls): #加上了上面的,此处变为cls,是class的缩写 # print(\"www\") # Act.use() #类方法不仅可以被类调用,还可以被对象调用 # class Run: # @staticmethod", "类方法 # 使用装饰器@classmethod。 # 原则上,类方法是将类本身作为对象进行操作的方法。假设有个方法,且这个方法在逻辑上采用类本身作为对象来调用更合理,那么这个方法就可以定义为类方法。另外,如果需要继承,也可以定义为类方法。 # 如下场景: # 假设我有一个学生类和一个班级类,想要实现的功能为: # 执行班级人数增加的操作、获得班级的总人数; # 学生类继承自班级类,每实例化一个学生,班级人数都能增加;", "# b = Student() # print(ClassTest.getNum()) # 复制代码 # 静态方法 # 使用装饰器@staticmethod。 #", "pattern = re.compile(r'\\w*') #表示匹配0此或者多次,等于[0,] # result = pattern.findall(a) #找到这个文件中所有的“新闻”字样 # print(result) # file.close()", "#左边不输入,代表从0开始,右边不输入,最大随便出现 取出这个文件中的所有数字 # # pattern = re.compile(r'\\d+') #跟上面的[1,]效果是一样的 # # pattern = re.compile(r'\\w')", "print(result) # file.close() #打开文件记得关闭 # 比如匹配所有邮箱 # file = open('duban.json','r',encoding='utf-8') #读取这个文件 # a", "# Act.use() #类方法不仅可以被类调用,还可以被对象调用 # class Run: # @staticmethod #类的静态方法,不传对象也不传类,既不属于类做的事情,也不属于对象做的事情,但可以被类和对象调用 # def have_breakfast(): #静态方法括号为空,是针对于cls和self方法用的,可以传自己的参数如a,b等,", "re.compile(r'\\d{1,}') #左边不输入,代表从0开始,右边不输入,最大随便出现 取出这个文件中的所有数字 # # pattern = re.compile(r'\\d+') #跟上面的[1,]效果是一样的 # # pattern =", "'<EMAIL>,<EMAIL>,<EMAIL>' # # pattern = re.compile(r'.+@\\w+\\.com') #匹配所有邮箱,但是打印出来的是一组字符串,需要分开打印,用下面方法 # # pattern = re.compile(r'\\w+.\\w+@\\w+\\.com') #正常情况只要后面的\\w+@\\w+\\.com(正常的邮箱正则表达式)即可,但是因为此题前面有个点", "方法的是单词中间用下划线; # class PlusNum: # def plus_int(self,a,b): # a = int(a) # b", "# a = file.read() # a2 = '<EMAIL>,<EMAIL>,<EMAIL>' # # pattern = re.compile(r'.+@\\w+\\.com')", "result = pattern.findall(a2) # print(result) # file.close() #打开文件记得关闭 # # 题目:<EMAIL>,只要匹配@hit # file", "print(\"父级有的东西\") # class father2(): # def have(self): # print(\"父级有的东西2\") # class son(father1,father2): #", "b = int(b) # return a+b # def plus_float(self,a,b): # a = float(a)", "# 静态方法 # 使用装饰器@staticmethod。 # 静态方法是类中的函数,不需要实例。静态方法主要是用来存放逻辑性的代码,逻辑上属于类,但是和类本身没有关系,也就是说在静态方法中,不会涉及到类中的属性和方法的操作。可以理解为,静态方法是个独立的、单纯的函数,它仅仅托管于某个类的名称空间中,便于使用和维护。 # 譬如,我想定义一个关于时间操作的类,其中有一个获取当前时间的函数。 # 复制代码 # import time", "have(self): # print(\"父级有的东西2\") # class son(father1,father2): # pass # john = son() #", "class father2(grandfather): # def yeye(self): # print(\"父级有的东西2\") # class son(father1,father2): # pass #", "# file.close() #打开文件记得关闭 # 比如匹配所有邮箱 # file = open('duban.json','r',encoding='utf-8') #读取这个文件 # a =", "表示匹配0次或多次,等于{0,} file = open('duban.json','r',encoding='utf-8') #读取这个文件 a = file.read() a2 = '<EMAIL>,song <EMAIL>,song!<EMAIL>' pattern", "# print(num.plus_all(1,2,3.3,4.3)) # 如下例子: # class Act: # @classmethod #表示类的方法 # def use(cls):", "#打开文件记得关闭 # .*? 代表啥意思=====代表万能表达式。 # \\d 换成中括号可以用[0123456789] 或者[0-9] 如\\d{,2}可以写成[012] #\\w 字母数字_ 也可以写成[a-zA-Z0-9_] #", "# pattern = re.compile(r'@.+?\\.') #正则表达式的点的懒惰模式,问号是解除贪婪模式变为懒惰模式 # result = pattern.findall(a2) # print(result) # file.close()", "#python3继承顺序 # 新式类的继承方式是:先找最亲的爸爸(括号里面第一个继承的类),然后再去找第二个爸爸(括号里面第二个继承的类), #当爸爸类都找不到的时候,找第一个爸爸的父类 #类里面的方法不能相互调用,单现在讲一个方法可以相互调用 #类的命名方式和方法命名方式不一样,类的命名方式,多个单词把首字母大写, 方法的是单词中间用下划线; # class PlusNum: # def plus_int(self,a,b):", "t = TimeTest(2, 10, 10) # nowTime = t.showTime() # print(nowTime) # 复制代码", "= son() # john.yeye() # 第一个父级没有,会找第二个父级,没有的话再找爷爷级 # class grandfather(): # def yeye(self): #", "#可以一层套一层继承 # class grandfather(): # def yeye(self): # print(\"爷爷有的东西\") # class father1(grandfather): #", "pattern = re.compile(r'@(.*?)\\.com') #万能表达式需要告诉在哪里结束 result = pattern.findall(a2) print(result) file.close() #打开文件记得关闭 ###################################################拓展: # import", "# self.name = '' # a = Student() # b = Student() #", "def yeye(self): # print(\"父级有的东西\") # class son(father1): # pass # john = son()", "# import json #json仅限于拿接口数据,content拿所有格式 # import requests # response = requests.get('http://news.baidu.com') #用这个方法访问百度新闻 #", "# # print(num.plus_float(2.1,3.4)) # print(num.plus_all(1,2,3.3,4.3)) # 如下例子: # class Act: # @classmethod #表示类的方法", "as file: #把网页内容写到文件中 # file.write(content) ##############################################拓展: # file = open('duban.json','r',encoding='utf-8') #读取这个文件 # a", "复制代码 # 如上,使用了静态方法(函数),然而方法体中并没使用(也不能使用)类或实例的属性(或方法)。若要获得当前时间的字符串时,并不一定需要实例化对象,此时对于静态方法而言,所在类更像是一种名称空间。 # 其实,我们也可以在类外面写一个同样的函数来做这些事,但是这样做就打乱了逻辑关系,也会导致以后代码维护困难。 # 以上就是我对Python的实例方法,类方法和静态方法之间的区别和作用的简要阐述。 #—————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————— import re import requests import", "result = pattern.findall(a2) # print(result) # file.close() #打开文件记得关闭 # file = open('duban.json','r',encoding='utf-8') #读取这个文件", "# # pattern = re.compile(r'\\d+') #跟上面的[1,]效果是一样的 # # pattern = re.compile(r'\\w') #把数字、字母、下划线、汉字都打印出来了 #", "# b = float(b) # return a+b # def plus_all(self,a,b,c,d): # return self.plus_int(a,b)+self.plus_float(c,d)", "##############################################拓展: # file = open('duban.json','r',encoding='utf-8') #读取这个文件 # a = file.read() # # pattern", "# return a+b # def plus_all(self,a,b,c,d): # return self.plus_int(a,b)+self.plus_float(c,d) #参数名字可以变,但是个数不能变 # num =", "# print(num.plus_int(3,4)) # # print(num.plus_float(2.1,3.4)) # print(num.plus_all(1,2,3.3,4.3)) # 如下例子: # class Act: #", "@classmethod # def addNum(cls): # cls.__num += 1 # @classmethod # def getNum(cls):", "# ? 解除贪婪模式,接在次数的正则表达式后面使用 # * 表示匹配0次或多次,等于{0,} file = open('duban.json','r',encoding='utf-8') #读取这个文件 a = file.read()", "pattern = re.compile(r'新闻') # # pattern = re.compile(r'\\d{1,10}') #找到所有数字匹配,下标从一位到10位数字 # # pattern =", "# 这里我用到魔术方法__new__,主要是为了在创建实例的时候调用累加方法。 # def __new__(self): # ClassTest.addNum() # return super(ClassTest, self).__new__(self) # class", "# with open('duban.json','w',encoding='utf-8') as file: #把网页内容写到文件中 # file.write(content) ##############################################拓展: # file = open('duban.json','r',encoding='utf-8')", "#把数字、字母、下划线、汉字都打印出来了 # # pattern = re.compile(r'\\w+') #把数字、字母、下划线、汉字都打印连在一起 # # pattern = re.compile(r'\\W+') #除掉数字、字母、下划线和汉字剩下的东西(大写的W)", "= son() # john.yeye() #儿子层只能先在父级层找,找不到才去爷爷层找 # class grandfather(): # def yeye(self): # print(\"爷爷有的东西\")", "# print(\"父级有的东西\") # class father2(): # def have(self): # print(\"父级有的东西2\") # class son(father1,father2):", "pattern = re.compile(r'.') #'.'能匹配所有的东西,代表匹配所有 # pattern = re.compile(r'song\\.lu@errc\\.com') #在点前面加上反斜杠,就能完全匹配 # result = pattern.findall(a2)", "plus_int(self,a,b): # a = int(a) # b = int(b) # return a+b #", "file.write(content) ##############################################拓展: # file = open('duban.json','r',encoding='utf-8') #读取这个文件 # a = file.read() # #", "print(num.plus_int(3,4)) # # print(num.plus_float(2.1,3.4)) # print(num.plus_all(1,2,3.3,4.3)) # 如下例子: # class Act: # @classmethod", "re.compile(r'<EMAIL>') #因为‘。’导致都匹配上了 # # pattern = re.compile(r'.') #'.'能匹配所有的东西,代表匹配所有 # pattern = re.compile(r'song\\.lu@errc\\.com') #在点前面加上反斜杠,就能完全匹配", "# 复制代码 # import time # class TimeTest(object): # def __init__(self, hour, minute,", "# def have(self): # print(\"父级有的东西2\") # class son(father1,father2): # pass # john =", "# def __init__(self): # self.name = '' # a = Student() # b", "@staticmethod # def showTime(): # return time.strftime(\"%H:%M:%S\", time.localtime()) # print(TimeTest.showTime()) # t =", "# def yeye(self): # print(\"父级有的东西2\") # class son(father1,father2): # pass # john =", "# 静态方法是类中的函数,不需要实例。静态方法主要是用来存放逻辑性的代码,逻辑上属于类,但是和类本身没有关系,也就是说在静态方法中,不会涉及到类中的属性和方法的操作。可以理解为,静态方法是个独立的、单纯的函数,它仅仅托管于某个类的名称空间中,便于使用和维护。 # 譬如,我想定义一个关于时间操作的类,其中有一个获取当前时间的函数。 # 复制代码 # import time # class TimeTest(object): #", "原则上,类方法是将类本身作为对象进行操作的方法。假设有个方法,且这个方法在逻辑上采用类本身作为对象来调用更合理,那么这个方法就可以定义为类方法。另外,如果需要继承,也可以定义为类方法。 # 如下场景: # 假设我有一个学生类和一个班级类,想要实现的功能为: # 执行班级人数增加的操作、获得班级的总人数; # 学生类继承自班级类,每实例化一个学生,班级人数都能增加; # 最后,我想定义一些学生,获得班级中的总人数。 # 思考:这个问题用类方法做比较合适,为什么?因为我实例化的是学生,但是如果我从学生这一个实例中获得班级总人数,在逻辑上显然是不合理的。同时,如果想要获得班级总人数,如果生成一个班级的实例也是没有必要的。", "# pattern = re.compile(r'\\d{1,}') #左边不输入,代表从0开始,右边不输入,最大随便出现 取出这个文件中的所有数字 # # pattern = re.compile(r'\\d+') #跟上面的[1,]效果是一样的 #", "# num = PlusNum() # # print(num.plus_int(3,4)) # # print(num.plus_float(2.1,3.4)) # print(num.plus_all(1,2,3.3,4.3)) #", "= TimeTest(2, 10, 10) # nowTime = t.showTime() # print(nowTime) # 复制代码 #", "yeye(self): # print(\"父级有的东西\") # class son(father1): # pass # john = son() #", "# # pattern = re.compile(r'@.+\\.') #正则表达式默认贪婪模式,尽可能多的匹配点,会匹配到最后一个,如何避免呢。前面加个问号即可,如下: # pattern = re.compile(r'@.+?\\.') #正则表达式的点的懒惰模式,问号是解除贪婪模式变为懒惰模式 # result", "class son(father1,father2): # pass # john = son() # john.yeye() #python3继承顺序 # 新式类的继承方式是:先找最亲的爸爸(括号里面第一个继承的类),然后再去找第二个爸爸(括号里面第二个继承的类),", "使用装饰器@staticmethod。 # 静态方法是类中的函数,不需要实例。静态方法主要是用来存放逻辑性的代码,逻辑上属于类,但是和类本身没有关系,也就是说在静态方法中,不会涉及到类中的属性和方法的操作。可以理解为,静态方法是个独立的、单纯的函数,它仅仅托管于某个类的名称空间中,便于使用和维护。 # 譬如,我想定义一个关于时间操作的类,其中有一个获取当前时间的函数。 # 复制代码 # import time # class TimeTest(object):", "r.have_breakfast() #被对象调用 # Run.have_breakfast() #被类调用 #————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————- # Python 实例方法、类方法、静态方法的区别与作用 # Python中至少有三种比较常见的方法类型,即实例方法,类方法、静态方法。它们是如何定义的呢?如何调用的呢?它们又有何区别和作用呢?且看下文。 # 首先,这三种方法都定义在类中。下面我先简单说一下怎么定义和调用的。(PS:实例对象的权限最大。)", "# 如下场景: # 假设我有一个学生类和一个班级类,想要实现的功能为: # 执行班级人数增加的操作、获得班级的总人数; # 学生类继承自班级类,每实例化一个学生,班级人数都能增加; # 最后,我想定义一些学生,获得班级中的总人数。 # 思考:这个问题用类方法做比较合适,为什么?因为我实例化的是学生,但是如果我从学生这一个实例中获得班级总人数,在逻辑上显然是不合理的。同时,如果想要获得班级总人数,如果生成一个班级的实例也是没有必要的。 #", "#万能表达式需要告诉在哪里结束 result = pattern.findall(a2) print(result) file.close() #打开文件记得关闭 ###################################################拓展: # import json #json仅限于拿接口数据,content拿所有格式 #", "= open('duban.json','r',encoding='utf-8') #读取这个文件 # a = file.read() # a2 = '<HtMl>hello</hTmL>' #网页,要把hello匹配出来 #", "\\d 换成中括号可以用[0123456789] 或者[0-9] 如\\d{,2}可以写成[012] #\\w 字母数字_ 也可以写成[a-zA-Z0-9_] # \\W 非数字字母_ # \\d 数字", "<EMAIL>,song!<EMAIL>' pattern = re.compile(r'@(.*?)\\.com') #万能表达式需要告诉在哪里结束 result = pattern.findall(a2) print(result) file.close() #打开文件记得关闭 ###################################################拓展: #", "int(b) # return a+b # def plus_float(self,a,b): # a = float(a) # b", "print(num.plus_float(2.1,3.4)) # print(num.plus_all(1,2,3.3,4.3)) # 如下例子: # class Act: # @classmethod #表示类的方法 # def", "json #json仅限于拿接口数据,content拿所有格式 # import requests # response = requests.get('http://news.baidu.com') #用这个方法访问百度新闻 # # print(str(response.text))", "re.compile(r'\\w+') #把数字、字母、下划线、汉字都打印连在一起 # # pattern = re.compile(r'\\W+') #除掉数字、字母、下划线和汉字剩下的东西(大写的W) # # pattern = re.compile(r'\\D+')", "# print(\"父级有的东西\") # class father2(): # def money(self): # print(\"父级有的东西2\") # class son(father1,father2):", "pass # john = son() # john.have() #可以一层套一层继承 # class grandfather(): # def", "= re.compile(r'.') #'.'能匹配所有的东西,代表匹配所有 # pattern = re.compile(r'song\\.lu@errc\\.com') #在点前面加上反斜杠,就能完全匹配 # result = pattern.findall(a2) #", "定义:第一个参数必须是实例对象,该参数名一般约定为“self”,通过它来传递实例的属性和方法(也可以传类的属性和方法); # 调用:只能由实例对象调用。 # 类方法 # 定义:使用装饰器@classmethod。第一个参数必须是当前类对象,该参数名一般约定为“cls”,通过它来传递类的属性和方法(不能传实例的属性和方法); # 调用:实例对象和类对象都可以调用。 # 静态方法 # 定义:使用装饰器@staticmethod。参数随意,没有“self”和“cls”参数,但是方法体中不能使用类或实例的任何属性和方法;", "a+b # def plus_all(self,a,b,c,d): # return self.plus_int(a,b)+self.plus_float(c,d) #参数名字可以变,但是个数不能变 # num = PlusNum() #", "def plus_float(self,a,b): # a = float(a) # b = float(b) # return a+b", "如下例子: # class Act: # @classmethod #表示类的方法 # def use(cls): #加上了上面的,此处变为cls,是class的缩写 # print(\"www\")", "#找到这个文件中所有的“新闻”字样 # print(result) # file.close() #打开文件记得关闭 # file = open('duban.json','r',encoding='utf-8') #读取这个文件 # a", "file = open('duban.json','r',encoding='utf-8') #读取这个文件 # a = file.read() # a2 = '<EMAIL>.cf.aa.ee.dd' #", "= '' # a = Student() # b = Student() # print(ClassTest.getNum()) #", "= '<HtMl>hello</hTmL>' #网页,要把hello匹配出来 # pattern = re.compile(r'<[Hh][Tt][Mm][Ll]>hello</[Hh][Tt][Mm][Ll]>') #中括号里面是你可以匹配的对象 # result = pattern.findall(a2) #", "= Run # r.have_breakfast() #被对象调用 # Run.have_breakfast() #被类调用 #————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————- # Python 实例方法、类方法、静态方法的区别与作用 #", "#因为‘。’导致都匹配上了 # # pattern = re.compile(r'.') #'.'能匹配所有的东西,代表匹配所有 # pattern = re.compile(r'song\\.lu@errc\\.com') #在点前面加上反斜杠,就能完全匹配 #", "re.compile(r'@.+\\.') #正则表达式默认贪婪模式,尽可能多的匹配点,会匹配到最后一个,如何避免呢。前面加个问号即可,如下: # pattern = re.compile(r'@.+?\\.') #正则表达式的点的懒惰模式,问号是解除贪婪模式变为懒惰模式 # result = pattern.findall(a2) # print(result)", "# print(num.plus_float(2.1,3.4)) # print(num.plus_all(1,2,3.3,4.3)) # 如下例子: # class Act: # @classmethod #表示类的方法 #", "= re.compile(r'\\D+') #非数字的一切内容 # pattern = re.compile(r'\\w*') #表示匹配0此或者多次,等于[0,] # result = pattern.findall(a) #找到这个文件中所有的“新闻”字样", "return super(ClassTest, self).__new__(self) # class Student(ClassTest): # def __init__(self): # self.name = ''", "# a = file.read() # a2 = '<HtMl>hello</hTmL>' #网页,要把hello匹配出来 # pattern = re.compile(r'<[Hh][Tt][Mm][Ll]>hello</[Hh][Tt][Mm][Ll]>')", "@classmethod #表示类的方法 # def use(cls): #加上了上面的,此处变为cls,是class的缩写 # print(\"www\") # Act.use() #类方法不仅可以被类调用,还可以被对象调用 # class", "john.yeye() #儿子层只能先在父级层找,找不到才去爷爷层找 # class grandfather(): # def yeye(self): # print(\"爷爷有的东西\") # class father1(grandfather):", "open('duban.json','r',encoding='utf-8') #读取这个文件 # a = file.read() # a2 = '<EMAIL>,<EMAIL>,<EMAIL>' # # pattern", "#把数字、字母、下划线、汉字都打印连在一起 # # pattern = re.compile(r'\\W+') #除掉数字、字母、下划线和汉字剩下的东西(大写的W) # # pattern = re.compile(r'\\D+') #非数字的一切内容", "# a2 = '<EMAIL>.cf.aa.ee.dd' # # pattern = re.compile(r'@.+\\.') #正则表达式默认贪婪模式,尽可能多的匹配点,会匹配到最后一个,如何避免呢。前面加个问号即可,如下: # pattern =", "# file.close() #打开文件记得关闭 # # 题目:<EMAIL>,只要匹配@hit # file = open('duban.json','r',encoding='utf-8') #读取这个文件 # a", "class father2(grandfather): # def yiu(self): # print(\"父级有的东西2\") # class son(father1,father2): # pass #", "def money(self): # print(\"父级有的东西2\") # class son(father1,father2): # pass # john = son()", "# def have_breakfast(): #静态方法括号为空,是针对于cls和self方法用的,可以传自己的参数如a,b等, # print('eat eggs') # r = Run # r.have_breakfast()", "yeye(self): # print(\"爷爷有的东西\") # class father1(grandfather): # pass # class father2(grandfather): # def", "self.plus_int(a,b)+self.plus_float(c,d) #参数名字可以变,但是个数不能变 # num = PlusNum() # # print(num.plus_int(3,4)) # # print(num.plus_float(2.1,3.4)) #", "# cls.__num += 1 # @classmethod # def getNum(cls): # return cls.__num #", "# 其实,我们也可以在类外面写一个同样的函数来做这些事,但是这样做就打乱了逻辑关系,也会导致以后代码维护困难。 # 以上就是我对Python的实例方法,类方法和静态方法之间的区别和作用的简要阐述。 #—————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————— import re import requests import json # response", "result = pattern.findall(a) #找到这个文件中所有的“新闻”字样 # print(result) # file.close() #打开文件记得关闭 # file = open('duban.json','r',encoding='utf-8')", "Act.use() #类方法不仅可以被类调用,还可以被对象调用 # class Run: # @staticmethod #类的静态方法,不传对象也不传类,既不属于类做的事情,也不属于对象做的事情,但可以被类和对象调用 # def have_breakfast(): #静态方法括号为空,是针对于cls和self方法用的,可以传自己的参数如a,b等, #", "pattern = re.compile(r'@.+?\\.') #正则表达式的点的懒惰模式,问号是解除贪婪模式变为懒惰模式 # result = pattern.findall(a2) # print(result) # file.close() #打开文件记得关闭", "调用:实例对象和类对象都可以调用。 # 静态方法 # 定义:使用装饰器@staticmethod。参数随意,没有“self”和“cls”参数,但是方法体中不能使用类或实例的任何属性和方法; # 调用:实例对象和类对象都可以调用。 # 实例方法 # 简而言之,实例方法就是类的实例能够使用的方法。这里不做过多解释。 # 类方法", "# b = int(b) # return a+b # def plus_float(self,a,b): # a =", "譬如,我想定义一个关于时间操作的类,其中有一个获取当前时间的函数。 # 复制代码 # import time # class TimeTest(object): # def __init__(self, hour,", "hour, minute, second): # self.hour = hour # self.minute = minute # self.second", "# Python中至少有三种比较常见的方法类型,即实例方法,类方法、静态方法。它们是如何定义的呢?如何调用的呢?它们又有何区别和作用呢?且看下文。 # 首先,这三种方法都定义在类中。下面我先简单说一下怎么定义和调用的。(PS:实例对象的权限最大。) # 实例方法 # 定义:第一个参数必须是实例对象,该参数名一般约定为“self”,通过它来传递实例的属性和方法(也可以传类的属性和方法); # 调用:只能由实例对象调用。 # 类方法 #", "class father2(): # def have(self): # print(\"父级有的东西2\") # class son(father1,father2): # pass #", "addNum(cls): # cls.__num += 1 # @classmethod # def getNum(cls): # return cls.__num", "10) # nowTime = t.showTime() # print(nowTime) # 复制代码 # 如上,使用了静态方法(函数),然而方法体中并没使用(也不能使用)类或实例的属性(或方法)。若要获得当前时间的字符串时,并不一定需要实例化对象,此时对于静态方法而言,所在类更像是一种名称空间。 # 其实,我们也可以在类外面写一个同样的函数来做这些事,但是这样做就打乱了逻辑关系,也会导致以后代码维护困难。", "# 定义:第一个参数必须是实例对象,该参数名一般约定为“self”,通过它来传递实例的属性和方法(也可以传类的属性和方法); # 调用:只能由实例对象调用。 # 类方法 # 定义:使用装饰器@classmethod。第一个参数必须是当前类对象,该参数名一般约定为“cls”,通过它来传递类的属性和方法(不能传实例的属性和方法); # 调用:实例对象和类对象都可以调用。 # 静态方法 #", "file = open('duban.json','r',encoding='utf-8') #读取这个文件 a = file.read() a2 = '<EMAIL>,song <EMAIL>,song!<EMAIL>' pattern =", "son() # john.yeye() #python3继承顺序 # 新式类的继承方式是:先找最亲的爸爸(括号里面第一个继承的类),然后再去找第二个爸爸(括号里面第二个继承的类), #当爸爸类都找不到的时候,找第一个爸爸的父类 #类里面的方法不能相互调用,单现在讲一个方法可以相互调用 #类的命名方式和方法命名方式不一样,类的命名方式,多个单词把首字母大写, 方法的是单词中间用下划线; # class PlusNum:", "class father1(grandfather): # pass # class father2(grandfather): # def yeye(self): # print(\"父级有的东西2\") #", "解除贪婪模式,接在次数的正则表达式后面使用 # * 表示匹配0次或多次,等于{0,} file = open('duban.json','r',encoding='utf-8') #读取这个文件 a = file.read() a2 =", "print(\"父级有的东西\") # class father2(grandfather): # def yiu(self): # print(\"父级有的东西2\") # class son(father1,father2): #", "open('duban.json','r',encoding='utf-8') #读取这个文件 # a = file.read() # a2 = '<EMAIL>.cf.aa.ee.dd' # # pattern", "复制代码 # import time # class TimeTest(object): # def __init__(self, hour, minute, second):", "# 执行班级人数增加的操作、获得班级的总人数; # 学生类继承自班级类,每实例化一个学生,班级人数都能增加; # 最后,我想定义一些学生,获得班级中的总人数。 # 思考:这个问题用类方法做比较合适,为什么?因为我实例化的是学生,但是如果我从学生这一个实例中获得班级总人数,在逻辑上显然是不合理的。同时,如果想要获得班级总人数,如果生成一个班级的实例也是没有必要的。 # 复制代码 # class ClassTest(object):", "= re.compile(r'\\d{1,10}') #找到所有数字匹配,下标从一位到10位数字 # # pattern = re.compile(r'\\d{1,}') #左边不输入,代表从0开始,右边不输入,最大随便出现 取出这个文件中的所有数字 # # pattern", "# class son(father1,father2): # pass # john = son() # john.yeye() #儿子层只能先在父级层找,找不到才去爷爷层找 #", "# class ClassTest(object): # __num = 0 # @classmethod # def addNum(cls): #", "#找到所有数字匹配,下标从一位到10位数字 # # pattern = re.compile(r'\\d{1,}') #左边不输入,代表从0开始,右边不输入,最大随便出现 取出这个文件中的所有数字 # # pattern = re.compile(r'\\d+')", "#网页,要把hello匹配出来 # pattern = re.compile(r'<[Hh][Tt][Mm][Ll]>hello</[Hh][Tt][Mm][Ll]>') #中括号里面是你可以匹配的对象 # result = pattern.findall(a2) # print(result) #", "#打开文件记得关闭 # file = open('duban.json','r',encoding='utf-8') #读取这个文件 # a = file.read() # a2 =", "#如果两个父级有同样的东西,调用的是第一个里面的,优先继承第一个类 # class father1(): # def have(self): # print(\"父级有的东西\") # class father2(): #", "open('duban.json','r',encoding='utf-8') #读取这个文件 a = file.read() a2 = '<EMAIL>,song <EMAIL>,song!<EMAIL>' pattern = re.compile(r'@(.*?)\\.com') #万能表达式需要告诉在哪里结束", "grandfather(): # def yeye(self): # print(\"爷爷有的东西\") # class father1(grandfather): # def have(self): #", "这里我用到魔术方法__new__,主要是为了在创建实例的时候调用累加方法。 # def __new__(self): # ClassTest.addNum() # return super(ClassTest, self).__new__(self) # class Student(ClassTest):", "john = son() #两个父级都调用 #如果两个父级有同样的东西,调用的是第一个里面的,优先继承第一个类 # class father1(): # def have(self): # print(\"父级有的东西\")", "plus_all(self,a,b,c,d): # return self.plus_int(a,b)+self.plus_float(c,d) #参数名字可以变,但是个数不能变 # num = PlusNum() # # print(num.plus_int(3,4)) #", "print(\"父级有的东西2\") # class son(father1,father2): # pass # john = son() # john.yeye() #儿子层只能先在父级层找,找不到才去爷爷层找", "# self.minute = minute # self.second = second # @staticmethod # def showTime():", "yeye(self): # print(\"爷爷有的东西\") # class father1(grandfather): # def have(self): # print(\"父级有的东西\") # class", "# class father2(grandfather): # def yiu(self): # print(\"父级有的东西2\") # class son(father1,father2): # pass", "= open('duban.json','r',encoding='utf-8') #读取这个文件 a = file.read() a2 = '<EMAIL>,song <EMAIL>,song!<EMAIL>' pattern = re.compile(r'@(.*?)\\.com')", "字母数字_ 也可以写成[a-zA-Z0-9_] # \\W 非数字字母_ # \\d 数字 # \\D 非数字 # .", "# def yiu(self): # print(\"父级有的东西2\") # class son(father1,father2): # pass # john =", "# john.have() #可以一层套一层继承 # class grandfather(): # def yeye(self): # print(\"爷爷有的东西\") # class", "# {1,4} 匹配一次到4次 # {,4} 匹配至多四次 # {1,} 匹配至少一次 # ? 解除贪婪模式,接在次数的正则表达式后面使用 #", "# def have(self): # print(\"父级有的东西\") # class father2(): # def have(self): # print(\"父级有的东西2\")", "grandfather(): # def yeye(self): # print(\"爷爷有的东西\") # class father1(grandfather): # def yeye(self): #", "re.compile(r'新闻') # # pattern = re.compile(r'\\d{1,10}') #找到所有数字匹配,下标从一位到10位数字 # # pattern = re.compile(r'\\d{1,}') #左边不输入,代表从0开始,右边不输入,最大随便出现", "john = son() # john.have() #可以一层套一层继承 # class grandfather(): # def yeye(self): #", "# 如下例子: # class Act: # @classmethod #表示类的方法 # def use(cls): #加上了上面的,此处变为cls,是class的缩写 #", "yeye(self): # print(\"爷爷有的东西\") # class father1(grandfather): # def yeye(self): # print(\"父级有的东西\") # class", "Run.have_breakfast() #被类调用 #————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————- # Python 实例方法、类方法、静态方法的区别与作用 # Python中至少有三种比较常见的方法类型,即实例方法,类方法、静态方法。它们是如何定义的呢?如何调用的呢?它们又有何区别和作用呢?且看下文。 # 首先,这三种方法都定义在类中。下面我先简单说一下怎么定义和调用的。(PS:实例对象的权限最大。) # 实例方法 #", "# class TimeTest(object): # def __init__(self, hour, minute, second): # self.hour = hour", "= int(a) # b = int(b) # return a+b # def plus_float(self,a,b): #", "匹配至多四次 # {1,} 匹配至少一次 # ? 解除贪婪模式,接在次数的正则表达式后面使用 # * 表示匹配0次或多次,等于{0,} file = open('duban.json','r',encoding='utf-8')", "#读取这个文件 # a = file.read() # a2 = '<EMAIL>.cf.aa.ee.dd' # # pattern =", "Act: # @classmethod #表示类的方法 # def use(cls): #加上了上面的,此处变为cls,是class的缩写 # print(\"www\") # Act.use() #类方法不仅可以被类调用,还可以被对象调用", "re.compile(r'.+@\\w+\\.com') #匹配所有邮箱,但是打印出来的是一组字符串,需要分开打印,用下面方法 # # pattern = re.compile(r'\\w+.\\w+@\\w+\\.com') #正常情况只要后面的\\w+@\\w+\\.com(正常的邮箱正则表达式)即可,但是因为此题前面有个点 # result = pattern.findall(a2) #", "re.compile(r'@(.*?)\\.com') #万能表达式需要告诉在哪里结束 result = pattern.findall(a2) print(result) file.close() #打开文件记得关闭 ###################################################拓展: # import json #json仅限于拿接口数据,content拿所有格式", "return time.strftime(\"%H:%M:%S\", time.localtime()) # print(TimeTest.showTime()) # t = TimeTest(2, 10, 10) # nowTime", "数字 # \\D 非数字 # . 所有 # + 匹配一次或多次等于{1,} # {1,4} 匹配一次到4次", "+= 1 # @classmethod # def getNum(cls): # return cls.__num # # 这里我用到魔术方法__new__,主要是为了在创建实例的时候调用累加方法。", "# 实例方法 # 简而言之,实例方法就是类的实例能够使用的方法。这里不做过多解释。 # 类方法 # 使用装饰器@classmethod。 # 原则上,类方法是将类本身作为对象进行操作的方法。假设有个方法,且这个方法在逻辑上采用类本身作为对象来调用更合理,那么这个方法就可以定义为类方法。另外,如果需要继承,也可以定义为类方法。 # 如下场景: #", "= float(a) # b = float(b) # return a+b # def plus_all(self,a,b,c,d): #", "file.read() # # pattern = re.compile(r'新闻') # # pattern = re.compile(r'\\d{1,10}') #找到所有数字匹配,下标从一位到10位数字 #", "= re.compile(r'\\w*') #表示匹配0此或者多次,等于[0,] # result = pattern.findall(a) #找到这个文件中所有的“新闻”字样 # print(result) # file.close() #打开文件记得关闭", "#非数字的一切内容 # pattern = re.compile(r'\\w*') #表示匹配0此或者多次,等于[0,] # result = pattern.findall(a) #找到这个文件中所有的“新闻”字样 # print(result)", "# pattern = re.compile(r'\\w') #把数字、字母、下划线、汉字都打印出来了 # # pattern = re.compile(r'\\w+') #把数字、字母、下划线、汉字都打印连在一起 # #", "print(ClassTest.getNum()) # 复制代码 # 静态方法 # 使用装饰器@staticmethod。 # 静态方法是类中的函数,不需要实例。静态方法主要是用来存放逻辑性的代码,逻辑上属于类,但是和类本身没有关系,也就是说在静态方法中,不会涉及到类中的属性和方法的操作。可以理解为,静态方法是个独立的、单纯的函数,它仅仅托管于某个类的名称空间中,便于使用和维护。 # 譬如,我想定义一个关于时间操作的类,其中有一个获取当前时间的函数。 # 复制代码", "# # print(num.plus_int(3,4)) # # print(num.plus_float(2.1,3.4)) # print(num.plus_all(1,2,3.3,4.3)) # 如下例子: # class Act:", "john.yeye() #python3继承顺序 # 新式类的继承方式是:先找最亲的爸爸(括号里面第一个继承的类),然后再去找第二个爸爸(括号里面第二个继承的类), #当爸爸类都找不到的时候,找第一个爸爸的父类 #类里面的方法不能相互调用,单现在讲一个方法可以相互调用 #类的命名方式和方法命名方式不一样,类的命名方式,多个单词把首字母大写, 方法的是单词中间用下划线; # class PlusNum: # def", "# pattern = re.compile(r'\\W+') #除掉数字、字母、下划线和汉字剩下的东西(大写的W) # # pattern = re.compile(r'\\D+') #非数字的一切内容 # pattern", "john.have() #可以一层套一层继承 # class grandfather(): # def yeye(self): # print(\"爷爷有的东西\") # class father1(grandfather):", "# class son(father1,father2): # pass # john = son() # john.have() #可以一层套一层继承 #", "class Student(ClassTest): # def __init__(self): # self.name = '' # a = Student()", "# r.have_breakfast() #被对象调用 # Run.have_breakfast() #被类调用 #————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————- # Python 实例方法、类方法、静态方法的区别与作用 # Python中至少有三种比较常见的方法类型,即实例方法,类方法、静态方法。它们是如何定义的呢?如何调用的呢?它们又有何区别和作用呢?且看下文。 #", "# a2 = '<EMAIL>,<EMAIL>,<EMAIL>' # # pattern = re.compile(r'.+@\\w+\\.com') #匹配所有邮箱,但是打印出来的是一组字符串,需要分开打印,用下面方法 # # pattern", "# john = son() # john.yeye() # 第一个父级没有,会找第二个父级,没有的话再找爷爷级 # class grandfather(): # def", "# def plus_all(self,a,b,c,d): # return self.plus_int(a,b)+self.plus_float(c,d) #参数名字可以变,但是个数不能变 # num = PlusNum() # #", "have(self): # print(\"父级有的东西\") # class father2(): # def money(self): # print(\"父级有的东西2\") # class", "#匹配所有邮箱,但是打印出来的是一组字符串,需要分开打印,用下面方法 # # pattern = re.compile(r'\\w+.\\w+@\\w+\\.com') #正常情况只要后面的\\w+@\\w+\\.com(正常的邮箱正则表达式)即可,但是因为此题前面有个点 # result = pattern.findall(a2) # print(result)", "a = file.read() a2 = '<EMAIL>,song <EMAIL>,song!<EMAIL>' pattern = re.compile(r'@(.*?)\\.com') #万能表达式需要告诉在哪里结束 result =", "'' # a = Student() # b = Student() # print(ClassTest.getNum()) # 复制代码", "题目:<EMAIL>,只要匹配@hit # file = open('duban.json','r',encoding='utf-8') #读取这个文件 # a = file.read() # a2 =", "#正则表达式默认贪婪模式,尽可能多的匹配点,会匹配到最后一个,如何避免呢。前面加个问号即可,如下: # pattern = re.compile(r'@.+?\\.') #正则表达式的点的懒惰模式,问号是解除贪婪模式变为懒惰模式 # result = pattern.findall(a2) # print(result) #", "# john.yeye() #儿子层只能先在父级层找,找不到才去爷爷层找 # class grandfather(): # def yeye(self): # print(\"爷爷有的东西\") # class", "= hour # self.minute = minute # self.second = second # @staticmethod #", "__new__(self): # ClassTest.addNum() # return super(ClassTest, self).__new__(self) # class Student(ClassTest): # def __init__(self):", "print(\"父级有的东西2\") # class son(father1,father2): # pass # john = son() #两个父级都调用 #如果两个父级有同样的东西,调用的是第一个里面的,优先继承第一个类 #", "json # response = requests.get('http://news.baidu.com') #用这个方法访问百度新闻 # print(response) #打印获取的是状态码 # content = response.text", "re.compile(r'\\D+') #非数字的一切内容 # pattern = re.compile(r'\\w*') #表示匹配0此或者多次,等于[0,] # result = pattern.findall(a) #找到这个文件中所有的“新闻”字样 #", "b = Student() # print(ClassTest.getNum()) # 复制代码 # 静态方法 # 使用装饰器@staticmethod。 # 静态方法是类中的函数,不需要实例。静态方法主要是用来存放逻辑性的代码,逻辑上属于类,但是和类本身没有关系,也就是说在静态方法中,不会涉及到类中的属性和方法的操作。可以理解为,静态方法是个独立的、单纯的函数,它仅仅托管于某个类的名称空间中,便于使用和维护。", "# # pattern = re.compile(r'<EMAIL>') #因为‘。’导致都匹配上了 # # pattern = re.compile(r'.') #'.'能匹配所有的东西,代表匹配所有 #", "= PlusNum() # # print(num.plus_int(3,4)) # # print(num.plus_float(2.1,3.4)) # print(num.plus_all(1,2,3.3,4.3)) # 如下例子: #", "yiu(self): # print(\"父级有的东西2\") # class son(father1,father2): # pass # john = son() #", "# def yeye(self): # print(\"爷爷有的东西\") # class father1(grandfather): # def have(self): # print(\"父级有的东西\")", "#多继承 # class father1(): # def have(self): # print(\"父级有的东西\") # class father2(): #", "file.close() #打开文件记得关闭 # 比如匹配所有邮箱 # file = open('duban.json','r',encoding='utf-8') #读取这个文件 # a = file.read()", "file.close() #打开文件记得关闭 # # 题目:<EMAIL>,只要匹配@hit # file = open('duban.json','r',encoding='utf-8') #读取这个文件 # a =", "pattern = re.compile(r'@.+\\.') #正则表达式默认贪婪模式,尽可能多的匹配点,会匹配到最后一个,如何避免呢。前面加个问号即可,如下: # pattern = re.compile(r'@.+?\\.') #正则表达式的点的懒惰模式,问号是解除贪婪模式变为懒惰模式 # result = pattern.findall(a2)", "#打印获取的是状态码 # content = response.text # print(content) #打印获取整个的网页内容 # with open('duban.json','w',encoding='utf-8') as file:", "def yeye(self): # print(\"父级有的东西2\") # class son(father1,father2): # pass # john = son()", "class ClassTest(object): # __num = 0 # @classmethod # def addNum(cls): # cls.__num", "#读取这个文件 # a = file.read() # a2 = '<HtMl>hello</hTmL>' #网页,要把hello匹配出来 # pattern =", "file = open('duban.json','r',encoding='utf-8') #读取这个文件 # a = file.read() # a2 = '<EMAIL>,song <EMAIL>,<EMAIL>'", "# def have(self): # print(\"父级有的东西\") # class father2(grandfather): # def yiu(self): # print(\"父级有的东西2\")", "+ 匹配一次或多次等于{1,} # {1,4} 匹配一次到4次 # {,4} 匹配至多四次 # {1,} 匹配至少一次 # ?", "num = PlusNum() # # print(num.plus_int(3,4)) # # print(num.plus_float(2.1,3.4)) # print(num.plus_all(1,2,3.3,4.3)) # 如下例子:", "= '<EMAIL>,<EMAIL>,<EMAIL>' # # pattern = re.compile(r'.+@\\w+\\.com') #匹配所有邮箱,但是打印出来的是一组字符串,需要分开打印,用下面方法 # # pattern = re.compile(r'\\w+.\\w+@\\w+\\.com')", "# def yeye(self): # print(\"爷爷有的东西\") # class father1(grandfather): # pass # class father2(grandfather):", "#类方法不仅可以被类调用,还可以被对象调用 # class Run: # @staticmethod #类的静态方法,不传对象也不传类,既不属于类做的事情,也不属于对象做的事情,但可以被类和对象调用 # def have_breakfast(): #静态方法括号为空,是针对于cls和self方法用的,可以传自己的参数如a,b等, # print('eat", "def have(self): # print(\"父级有的东西2\") # class son(father1,father2): # pass # john = son()", "print(\"父级有的东西2\") # class son(father1,father2): # pass # john = son() # john.yeye() #python3继承顺序", "# result = pattern.findall(a) #找到这个文件中所有的“新闻”字样 # print(result) # file.close() #打开文件记得关闭 # file =", "# class son(father1,father2): # pass # john = son() #两个父级都调用 #如果两个父级有同样的东西,调用的是第一个里面的,优先继承第一个类 # class", "# 学生类继承自班级类,每实例化一个学生,班级人数都能增加; # 最后,我想定义一些学生,获得班级中的总人数。 # 思考:这个问题用类方法做比较合适,为什么?因为我实例化的是学生,但是如果我从学生这一个实例中获得班级总人数,在逻辑上显然是不合理的。同时,如果想要获得班级总人数,如果生成一个班级的实例也是没有必要的。 # 复制代码 # class ClassTest(object): # __num", "# 复制代码 # 静态方法 # 使用装饰器@staticmethod。 # 静态方法是类中的函数,不需要实例。静态方法主要是用来存放逻辑性的代码,逻辑上属于类,但是和类本身没有关系,也就是说在静态方法中,不会涉及到类中的属性和方法的操作。可以理解为,静态方法是个独立的、单纯的函数,它仅仅托管于某个类的名称空间中,便于使用和维护。 # 譬如,我想定义一个关于时间操作的类,其中有一个获取当前时间的函数。 # 复制代码 #", "@staticmethod #类的静态方法,不传对象也不传类,既不属于类做的事情,也不属于对象做的事情,但可以被类和对象调用 # def have_breakfast(): #静态方法括号为空,是针对于cls和self方法用的,可以传自己的参数如a,b等, # print('eat eggs') # r = Run", "# print(result) # file.close() #打开文件记得关闭 # # 题目:<EMAIL>,只要匹配@hit # file = open('duban.json','r',encoding='utf-8') #读取这个文件", "# 类方法 # 使用装饰器@classmethod。 # 原则上,类方法是将类本身作为对象进行操作的方法。假设有个方法,且这个方法在逻辑上采用类本身作为对象来调用更合理,那么这个方法就可以定义为类方法。另外,如果需要继承,也可以定义为类方法。 # 如下场景: # 假设我有一个学生类和一个班级类,想要实现的功能为: # 执行班级人数增加的操作、获得班级的总人数; #", "# print(\"爷爷有的东西\") # class father1(grandfather): # def have(self): # print(\"父级有的东西\") # class father2(grandfather):", "# file.close() #打开文件记得关闭 # file = open('duban.json','r',encoding='utf-8') #读取这个文件 # a = file.read() #", "使用装饰器@classmethod。 # 原则上,类方法是将类本身作为对象进行操作的方法。假设有个方法,且这个方法在逻辑上采用类本身作为对象来调用更合理,那么这个方法就可以定义为类方法。另外,如果需要继承,也可以定义为类方法。 # 如下场景: # 假设我有一个学生类和一个班级类,想要实现的功能为: # 执行班级人数增加的操作、获得班级的总人数; # 学生类继承自班级类,每实例化一个学生,班级人数都能增加; # 最后,我想定义一些学生,获得班级中的总人数。", "\\W 非数字字母_ # \\d 数字 # \\D 非数字 # . 所有 # +", "# class father1(): # def have(self): # print(\"父级有的东西\") # class father2(): # def", "如下场景: # 假设我有一个学生类和一个班级类,想要实现的功能为: # 执行班级人数增加的操作、获得班级的总人数; # 学生类继承自班级类,每实例化一个学生,班级人数都能增加; # 最后,我想定义一些学生,获得班级中的总人数。 # 思考:这个问题用类方法做比较合适,为什么?因为我实例化的是学生,但是如果我从学生这一个实例中获得班级总人数,在逻辑上显然是不合理的。同时,如果想要获得班级总人数,如果生成一个班级的实例也是没有必要的。 # 复制代码", "# * 表示匹配0次或多次,等于{0,} file = open('duban.json','r',encoding='utf-8') #读取这个文件 a = file.read() a2 = '<EMAIL>,song", "# a = Student() # b = Student() # print(ClassTest.getNum()) # 复制代码 #", "son(father1,father2): # pass # john = son() # john.have() #可以一层套一层继承 # class grandfather():", "return a+b # def plus_all(self,a,b,c,d): # return self.plus_int(a,b)+self.plus_float(c,d) #参数名字可以变,但是个数不能变 # num = PlusNum()", "= pattern.findall(a2) # print(result) # file.close() #打开文件记得关闭 # .*? 代表啥意思=====代表万能表达式。 # \\d 换成中括号可以用[0123456789]", "# ClassTest.addNum() # return super(ClassTest, self).__new__(self) # class Student(ClassTest): # def __init__(self): #", "#在点前面加上反斜杠,就能完全匹配 # result = pattern.findall(a2) # print(result) # file.close() #打开文件记得关闭 # 比如匹配所有邮箱 #", "#表示类的方法 # def use(cls): #加上了上面的,此处变为cls,是class的缩写 # print(\"www\") # Act.use() #类方法不仅可以被类调用,还可以被对象调用 # class Run:", "john = son() # john.yeye() #儿子层只能先在父级层找,找不到才去爷爷层找 # class grandfather(): # def yeye(self): #", "= file.read() # a2 = '<EMAIL>,song <EMAIL>,<EMAIL>' # # pattern = re.compile(r'<EMAIL>') #因为‘。’导致都匹配上了", "= open('duban.json','r',encoding='utf-8') #读取这个文件 # a = file.read() # a2 = '<EMAIL>.cf.aa.ee.dd' # #", "0 # @classmethod # def addNum(cls): # cls.__num += 1 # @classmethod #", "= second # @staticmethod # def showTime(): # return time.strftime(\"%H:%M:%S\", time.localtime()) # print(TimeTest.showTime())", "# 思考:这个问题用类方法做比较合适,为什么?因为我实例化的是学生,但是如果我从学生这一个实例中获得班级总人数,在逻辑上显然是不合理的。同时,如果想要获得班级总人数,如果生成一个班级的实例也是没有必要的。 # 复制代码 # class ClassTest(object): # __num = 0 # @classmethod", "# r = Run # r.have_breakfast() #被对象调用 # Run.have_breakfast() #被类调用 #————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————- # Python", "print(\"爷爷有的东西\") # class father1(grandfather): # pass # class father2(grandfather): # def yeye(self): #", "#类的静态方法,不传对象也不传类,既不属于类做的事情,也不属于对象做的事情,但可以被类和对象调用 # def have_breakfast(): #静态方法括号为空,是针对于cls和self方法用的,可以传自己的参数如a,b等, # print('eat eggs') # r = Run #", "# pattern = re.compile(r'.') #'.'能匹配所有的东西,代表匹配所有 # pattern = re.compile(r'song\\.lu@errc\\.com') #在点前面加上反斜杠,就能完全匹配 # result =", "# def getNum(cls): # return cls.__num # # 这里我用到魔术方法__new__,主要是为了在创建实例的时候调用累加方法。 # def __new__(self): #", "def showTime(): # return time.strftime(\"%H:%M:%S\", time.localtime()) # print(TimeTest.showTime()) # t = TimeTest(2, 10,", "a2 = '<EMAIL>,song <EMAIL>,<EMAIL>' # # pattern = re.compile(r'<EMAIL>') #因为‘。’导致都匹配上了 # # pattern", "eggs') # r = Run # r.have_breakfast() #被对象调用 # Run.have_breakfast() #被类调用 #————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————- #", "'<HtMl>hello</hTmL>' #网页,要把hello匹配出来 # pattern = re.compile(r'<[Hh][Tt][Mm][Ll]>hello</[Hh][Tt][Mm][Ll]>') #中括号里面是你可以匹配的对象 # result = pattern.findall(a2) # print(result)", "# print(\"父级有的东西2\") # class son(father1,father2): # pass # john = son() # john.have()", "def yiu(self): # print(\"父级有的东西2\") # class son(father1,father2): # pass # john = son()", "minute # self.second = second # @staticmethod # def showTime(): # return time.strftime(\"%H:%M:%S\",", "class son(father1,father2): # pass # john = son() #两个父级都调用 #如果两个父级有同样的东西,调用的是第一个里面的,优先继承第一个类 # class father1():", "= file.read() a2 = '<EMAIL>,song <EMAIL>,song!<EMAIL>' pattern = re.compile(r'@(.*?)\\.com') #万能表达式需要告诉在哪里结束 result = pattern.findall(a2)", "import requests import json # response = requests.get('http://news.baidu.com') #用这个方法访问百度新闻 # print(response) #打印获取的是状态码 #", "# 调用:实例对象和类对象都可以调用。 # 实例方法 # 简而言之,实例方法就是类的实例能够使用的方法。这里不做过多解释。 # 类方法 # 使用装饰器@classmethod。 # 原则上,类方法是将类本身作为对象进行操作的方法。假设有个方法,且这个方法在逻辑上采用类本身作为对象来调用更合理,那么这个方法就可以定义为类方法。另外,如果需要继承,也可以定义为类方法。 #", "#类的命名方式和方法命名方式不一样,类的命名方式,多个单词把首字母大写, 方法的是单词中间用下划线; # class PlusNum: # def plus_int(self,a,b): # a = int(a) #", "# 譬如,我想定义一个关于时间操作的类,其中有一个获取当前时间的函数。 # 复制代码 # import time # class TimeTest(object): # def __init__(self,", "TimeTest(2, 10, 10) # nowTime = t.showTime() # print(nowTime) # 复制代码 # 如上,使用了静态方法(函数),然而方法体中并没使用(也不能使用)类或实例的属性(或方法)。若要获得当前时间的字符串时,并不一定需要实例化对象,此时对于静态方法而言,所在类更像是一种名称空间。", "# def plus_int(self,a,b): # a = int(a) # b = int(b) # return", "time.strftime(\"%H:%M:%S\", time.localtime()) # print(TimeTest.showTime()) # t = TimeTest(2, 10, 10) # nowTime =", "# john.yeye() # 第一个父级没有,会找第二个父级,没有的话再找爷爷级 # class grandfather(): # def yeye(self): # print(\"爷爷有的东西\") #", "#除掉数字、字母、下划线和汉字剩下的东西(大写的W) # # pattern = re.compile(r'\\D+') #非数字的一切内容 # pattern = re.compile(r'\\w*') #表示匹配0此或者多次,等于[0,] #", "以上就是我对Python的实例方法,类方法和静态方法之间的区别和作用的简要阐述。 #—————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————— import re import requests import json # response = requests.get('http://news.baidu.com') #用这个方法访问百度新闻", "# print(result) # file.close() #打开文件记得关闭 # 比如匹配所有邮箱 # file = open('duban.json','r',encoding='utf-8') #读取这个文件 #", "re.compile(r'song\\.lu@errc\\.com') #在点前面加上反斜杠,就能完全匹配 # result = pattern.findall(a2) # print(result) # file.close() #打开文件记得关闭 # 比如匹配所有邮箱", "class grandfather(): # def yeye(self): # print(\"爷爷有的东西\") # class father1(grandfather): # pass #", "= re.compile(r'新闻') # # pattern = re.compile(r'\\d{1,10}') #找到所有数字匹配,下标从一位到10位数字 # # pattern = re.compile(r'\\d{1,}')", "# pass # john = son() #两个父级都调用 #如果两个父级有同样的东西,调用的是第一个里面的,优先继承第一个类 # class father1(): # def", "minute, second): # self.hour = hour # self.minute = minute # self.second =", "= requests.get('http://news.baidu.com') #用这个方法访问百度新闻 # print(response) #打印获取的是状态码 # content = response.text # print(content) #打印获取整个的网页内容", "# print(response) #打印获取的是状态码 # content = response.text # print(content) #打印获取整个的网页内容 # with open('duban.json','w',encoding='utf-8')", "print(result) # file.close() #打开文件记得关闭 # # 题目:<EMAIL>,只要匹配@hit # file = open('duban.json','r',encoding='utf-8') #读取这个文件 #", "print(num.plus_all(1,2,3.3,4.3)) # 如下例子: # class Act: # @classmethod #表示类的方法 # def use(cls): #加上了上面的,此处变为cls,是class的缩写", "匹配至少一次 # ? 解除贪婪模式,接在次数的正则表达式后面使用 # * 表示匹配0次或多次,等于{0,} file = open('duban.json','r',encoding='utf-8') #读取这个文件 a =", "father1(grandfather): # def yeye(self): # print(\"父级有的东西\") # class son(father1): # pass # john", "# return self.plus_int(a,b)+self.plus_float(c,d) #参数名字可以变,但是个数不能变 # num = PlusNum() # # print(num.plus_int(3,4)) # #", "= re.compile(r'\\d{1,}') #左边不输入,代表从0开始,右边不输入,最大随便出现 取出这个文件中的所有数字 # # pattern = re.compile(r'\\d+') #跟上面的[1,]效果是一样的 # # pattern", "time # class TimeTest(object): # def __init__(self, hour, minute, second): # self.hour =", "use(cls): #加上了上面的,此处变为cls,是class的缩写 # print(\"www\") # Act.use() #类方法不仅可以被类调用,还可以被对象调用 # class Run: # @staticmethod #类的静态方法,不传对象也不传类,既不属于类做的事情,也不属于对象做的事情,但可以被类和对象调用", "静态方法 # 定义:使用装饰器@staticmethod。参数随意,没有“self”和“cls”参数,但是方法体中不能使用类或实例的任何属性和方法; # 调用:实例对象和类对象都可以调用。 # 实例方法 # 简而言之,实例方法就是类的实例能够使用的方法。这里不做过多解释。 # 类方法 # 使用装饰器@classmethod。", "requests.get('http://news.baidu.com') #用这个方法访问百度新闻 # # print(str(response.text)) #类型是字符串类型 # # print(str(response.content)) #用concent会生成字节流,前面有个b,加上“encoding=‘utf-8’”就可以了 # print(response.json) #类型是字典类型", "son(father1,father2): # pass # john = son() #两个父级都调用 #如果两个父级有同样的东西,调用的是第一个里面的,优先继承第一个类 # class father1(): #", "Python 实例方法、类方法、静态方法的区别与作用 # Python中至少有三种比较常见的方法类型,即实例方法,类方法、静态方法。它们是如何定义的呢?如何调用的呢?它们又有何区别和作用呢?且看下文。 # 首先,这三种方法都定义在类中。下面我先简单说一下怎么定义和调用的。(PS:实例对象的权限最大。) # 实例方法 # 定义:第一个参数必须是实例对象,该参数名一般约定为“self”,通过它来传递实例的属性和方法(也可以传类的属性和方法); # 调用:只能由实例对象调用。 #", "son(father1): # pass # john = son() # john.yeye() # 第一个父级没有,会找第二个父级,没有的话再找爷爷级 # class", "pattern = re.compile(r'song\\.lu@errc\\.com') #在点前面加上反斜杠,就能完全匹配 # result = pattern.findall(a2) # print(result) # file.close() #打开文件记得关闭", "# \\W 非数字字母_ # \\d 数字 # \\D 非数字 # . 所有 #", "pattern = re.compile(r'\\d{1,10}') #找到所有数字匹配,下标从一位到10位数字 # # pattern = re.compile(r'\\d{1,}') #左边不输入,代表从0开始,右边不输入,最大随便出现 取出这个文件中的所有数字 # #", "result = pattern.findall(a2) # print(result) # file.close() #打开文件记得关闭 # .*? 代表啥意思=====代表万能表达式。 # \\d", "pattern = re.compile(r'\\d{1,}') #左边不输入,代表从0开始,右边不输入,最大随便出现 取出这个文件中的所有数字 # # pattern = re.compile(r'\\d+') #跟上面的[1,]效果是一样的 # #", "son() #两个父级都调用 #如果两个父级有同样的东西,调用的是第一个里面的,优先继承第一个类 # class father1(): # def have(self): # print(\"父级有的东西\") # class", "= minute # self.second = second # @staticmethod # def showTime(): # return", "self.minute = minute # self.second = second # @staticmethod # def showTime(): #", "requests import json # response = requests.get('http://news.baidu.com') #用这个方法访问百度新闻 # print(response) #打印获取的是状态码 # content", "# \\d 数字 # \\D 非数字 # . 所有 # + 匹配一次或多次等于{1,} #", "pass # class father2(grandfather): # def yeye(self): # print(\"父级有的东西2\") # class son(father1,father2): #", "实例方法 # 定义:第一个参数必须是实例对象,该参数名一般约定为“self”,通过它来传递实例的属性和方法(也可以传类的属性和方法); # 调用:只能由实例对象调用。 # 类方法 # 定义:使用装饰器@classmethod。第一个参数必须是当前类对象,该参数名一般约定为“cls”,通过它来传递类的属性和方法(不能传实例的属性和方法); # 调用:实例对象和类对象都可以调用。 # 静态方法", "class grandfather(): # def yeye(self): # print(\"爷爷有的东西\") # class father1(grandfather): # def have(self):", "'<EMAIL>,song <EMAIL>,<EMAIL>' # # pattern = re.compile(r'<EMAIL>') #因为‘。’导致都匹配上了 # # pattern = re.compile(r'.')", "cls.__num += 1 # @classmethod # def getNum(cls): # return cls.__num # #", "# # pattern = re.compile(r'\\w') #把数字、字母、下划线、汉字都打印出来了 # # pattern = re.compile(r'\\w+') #把数字、字母、下划线、汉字都打印连在一起 #", "# class grandfather(): # def yeye(self): # print(\"爷爷有的东西\") # class father1(grandfather): # pass", "# 使用装饰器@classmethod。 # 原则上,类方法是将类本身作为对象进行操作的方法。假设有个方法,且这个方法在逻辑上采用类本身作为对象来调用更合理,那么这个方法就可以定义为类方法。另外,如果需要继承,也可以定义为类方法。 # 如下场景: # 假设我有一个学生类和一个班级类,想要实现的功能为: # 执行班级人数增加的操作、获得班级的总人数; # 学生类继承自班级类,每实例化一个学生,班级人数都能增加; #", "# pattern = re.compile(r'.+@\\w+\\.com') #匹配所有邮箱,但是打印出来的是一组字符串,需要分开打印,用下面方法 # # pattern = re.compile(r'\\w+.\\w+@\\w+\\.com') #正常情况只要后面的\\w+@\\w+\\.com(正常的邮箱正则表达式)即可,但是因为此题前面有个点 # result", "# print(\"父级有的东西2\") # class son(father1,father2): # pass # john = son() # john.yeye()", "PlusNum: # def plus_int(self,a,b): # a = int(a) # b = int(b) #", "# return cls.__num # # 这里我用到魔术方法__new__,主要是为了在创建实例的时候调用累加方法。 # def __new__(self): # ClassTest.addNum() # return", "requests # response = requests.get('http://news.baidu.com') #用这个方法访问百度新闻 # # print(str(response.text)) #类型是字符串类型 # # print(str(response.content))", "{1,4} 匹配一次到4次 # {,4} 匹配至多四次 # {1,} 匹配至少一次 # ? 解除贪婪模式,接在次数的正则表达式后面使用 # *", "# pattern = re.compile(r'\\w*') #表示匹配0此或者多次,等于[0,] # result = pattern.findall(a) #找到这个文件中所有的“新闻”字样 # print(result) #", "# pattern = re.compile(r'\\w+') #把数字、字母、下划线、汉字都打印连在一起 # # pattern = re.compile(r'\\W+') #除掉数字、字母、下划线和汉字剩下的东西(大写的W) # #", "class father2(): # def money(self): # print(\"父级有的东西2\") # class son(father1,father2): # pass #", "# john = son() #两个父级都调用 #如果两个父级有同样的东西,调用的是第一个里面的,优先继承第一个类 # class father1(): # def have(self): #", "nowTime = t.showTime() # print(nowTime) # 复制代码 # 如上,使用了静态方法(函数),然而方法体中并没使用(也不能使用)类或实例的属性(或方法)。若要获得当前时间的字符串时,并不一定需要实例化对象,此时对于静态方法而言,所在类更像是一种名称空间。 # 其实,我们也可以在类外面写一个同样的函数来做这些事,但是这样做就打乱了逻辑关系,也会导致以后代码维护困难。 # 以上就是我对Python的实例方法,类方法和静态方法之间的区别和作用的简要阐述。", "# pattern = re.compile(r'\\w+.\\w+@\\w+\\.com') #正常情况只要后面的\\w+@\\w+\\.com(正常的邮箱正则表达式)即可,但是因为此题前面有个点 # result = pattern.findall(a2) # print(result) # file.close()", "a2 = '<EMAIL>,<EMAIL>,<EMAIL>' # # pattern = re.compile(r'.+@\\w+\\.com') #匹配所有邮箱,但是打印出来的是一组字符串,需要分开打印,用下面方法 # # pattern =", "pattern = re.compile(r'.+@\\w+\\.com') #匹配所有邮箱,但是打印出来的是一组字符串,需要分开打印,用下面方法 # # pattern = re.compile(r'\\w+.\\w+@\\w+\\.com') #正常情况只要后面的\\w+@\\w+\\.com(正常的邮箱正则表达式)即可,但是因为此题前面有个点 # result =", "pattern = re.compile(r'<[Hh][Tt][Mm][Ll]>hello</[Hh][Tt][Mm][Ll]>') #中括号里面是你可以匹配的对象 # result = pattern.findall(a2) # print(result) # file.close() #打开文件记得关闭", "# result = pattern.findall(a2) # print(result) # file.close() #打开文件记得关闭 # 比如匹配所有邮箱 # file", "pass # john = son() # john.yeye() # 第一个父级没有,会找第二个父级,没有的话再找爷爷级 # class grandfather(): #", "# {,4} 匹配至多四次 # {1,} 匹配至少一次 # ? 解除贪婪模式,接在次数的正则表达式后面使用 # * 表示匹配0次或多次,等于{0,} file", "import time # class TimeTest(object): # def __init__(self, hour, minute, second): # self.hour", "#静态方法括号为空,是针对于cls和self方法用的,可以传自己的参数如a,b等, # print('eat eggs') # r = Run # r.have_breakfast() #被对象调用 # Run.have_breakfast()", "# print(ClassTest.getNum()) # 复制代码 # 静态方法 # 使用装饰器@staticmethod。 # 静态方法是类中的函数,不需要实例。静态方法主要是用来存放逻辑性的代码,逻辑上属于类,但是和类本身没有关系,也就是说在静态方法中,不会涉及到类中的属性和方法的操作。可以理解为,静态方法是个独立的、单纯的函数,它仅仅托管于某个类的名称空间中,便于使用和维护。 # 譬如,我想定义一个关于时间操作的类,其中有一个获取当前时间的函数。 #", "ClassTest(object): # __num = 0 # @classmethod # def addNum(cls): # cls.__num +=", "print(\"爷爷有的东西\") # class father1(grandfather): # def have(self): # print(\"父级有的东西\") # class father2(grandfather): #", "a2 = '<HtMl>hello</hTmL>' #网页,要把hello匹配出来 # pattern = re.compile(r'<[Hh][Tt][Mm][Ll]>hello</[Hh][Tt][Mm][Ll]>') #中括号里面是你可以匹配的对象 # result = pattern.findall(a2)", "a = Student() # b = Student() # print(ClassTest.getNum()) # 复制代码 # 静态方法", "= son() #两个父级都调用 #如果两个父级有同样的东西,调用的是第一个里面的,优先继承第一个类 # class father1(): # def have(self): # print(\"父级有的东西\") #", "son() # john.yeye() # 第一个父级没有,会找第二个父级,没有的话再找爷爷级 # class grandfather(): # def yeye(self): # print(\"爷爷有的东西\")", "file = open('duban.json','r',encoding='utf-8') #读取这个文件 # a = file.read() # # pattern = re.compile(r'新闻')", "return cls.__num # # 这里我用到魔术方法__new__,主要是为了在创建实例的时候调用累加方法。 # def __new__(self): # ClassTest.addNum() # return super(ClassTest,", "# file.write(content) ##############################################拓展: # file = open('duban.json','r',encoding='utf-8') #读取这个文件 # a = file.read() #", "#用这个方法访问百度新闻 # print(response) #打印获取的是状态码 # content = response.text # print(content) #打印获取整个的网页内容 # with", "re.compile(r'@.+?\\.') #正则表达式的点的懒惰模式,问号是解除贪婪模式变为懒惰模式 # result = pattern.findall(a2) # print(result) # file.close() #打开文件记得关闭 # file", "# {1,} 匹配至少一次 # ? 解除贪婪模式,接在次数的正则表达式后面使用 # * 表示匹配0次或多次,等于{0,} file = open('duban.json','r',encoding='utf-8') #读取这个文件", "file.close() #打开文件记得关闭 # .*? 代表啥意思=====代表万能表达式。 # \\d 换成中括号可以用[0123456789] 或者[0-9] 如\\d{,2}可以写成[012] #\\w 字母数字_ 也可以写成[a-zA-Z0-9_]", "# 原则上,类方法是将类本身作为对象进行操作的方法。假设有个方法,且这个方法在逻辑上采用类本身作为对象来调用更合理,那么这个方法就可以定义为类方法。另外,如果需要继承,也可以定义为类方法。 # 如下场景: # 假设我有一个学生类和一个班级类,想要实现的功能为: # 执行班级人数增加的操作、获得班级的总人数; # 学生类继承自班级类,每实例化一个学生,班级人数都能增加; # 最后,我想定义一些学生,获得班级中的总人数。 #", "pass # john = son() #两个父级都调用 #如果两个父级有同样的东西,调用的是第一个里面的,优先继承第一个类 # class father1(): # def have(self):", "# import time # class TimeTest(object): # def __init__(self, hour, minute, second): #", "# Python 实例方法、类方法、静态方法的区别与作用 # Python中至少有三种比较常见的方法类型,即实例方法,类方法、静态方法。它们是如何定义的呢?如何调用的呢?它们又有何区别和作用呢?且看下文。 # 首先,这三种方法都定义在类中。下面我先简单说一下怎么定义和调用的。(PS:实例对象的权限最大。) # 实例方法 # 定义:第一个参数必须是实例对象,该参数名一般约定为“self”,通过它来传递实例的属性和方法(也可以传类的属性和方法); # 调用:只能由实例对象调用。", "= file.read() # # pattern = re.compile(r'新闻') # # pattern = re.compile(r'\\d{1,10}') #找到所有数字匹配,下标从一位到10位数字", "print(result) # file.close() #打开文件记得关闭 # file = open('duban.json','r',encoding='utf-8') #读取这个文件 # a = file.read()", "pattern = re.compile(r'\\W+') #除掉数字、字母、下划线和汉字剩下的东西(大写的W) # # pattern = re.compile(r'\\D+') #非数字的一切内容 # pattern =", "# 使用装饰器@staticmethod。 # 静态方法是类中的函数,不需要实例。静态方法主要是用来存放逻辑性的代码,逻辑上属于类,但是和类本身没有关系,也就是说在静态方法中,不会涉及到类中的属性和方法的操作。可以理解为,静态方法是个独立的、单纯的函数,它仅仅托管于某个类的名称空间中,便于使用和维护。 # 譬如,我想定义一个关于时间操作的类,其中有一个获取当前时间的函数。 # 复制代码 # import time # class", "#儿子层只能先在父级层找,找不到才去爷爷层找 # class grandfather(): # def yeye(self): # print(\"爷爷有的东西\") # class father1(grandfather): #", "def plus_int(self,a,b): # a = int(a) # b = int(b) # return a+b", "# # pattern = re.compile(r'\\w+') #把数字、字母、下划线、汉字都打印连在一起 # # pattern = re.compile(r'\\W+') #除掉数字、字母、下划线和汉字剩下的东西(大写的W) #", "匹配一次或多次等于{1,} # {1,4} 匹配一次到4次 # {,4} 匹配至多四次 # {1,} 匹配至少一次 # ? 解除贪婪模式,接在次数的正则表达式后面使用", "#两个父级都调用 #如果两个父级有同样的东西,调用的是第一个里面的,优先继承第一个类 # class father1(): # def have(self): # print(\"父级有的东西\") # class father2():", "# # pattern = re.compile(r'新闻') # # pattern = re.compile(r'\\d{1,10}') #找到所有数字匹配,下标从一位到10位数字 # #", "# # pattern = re.compile(r'.+@\\w+\\.com') #匹配所有邮箱,但是打印出来的是一组字符串,需要分开打印,用下面方法 # # pattern = re.compile(r'\\w+.\\w+@\\w+\\.com') #正常情况只要后面的\\w+@\\w+\\.com(正常的邮箱正则表达式)即可,但是因为此题前面有个点 #", "# a = int(a) # b = int(b) # return a+b # def", "# def plus_float(self,a,b): # a = float(a) # b = float(b) # return", "def have(self): # print(\"父级有的东西\") # class father2(): # def have(self): # print(\"父级有的东西2\") #" ]
[ "compressed = True net = \"main\" mnemonic = None num_hash = 3 argv", "= PrivateKey.from_mnemonic(mnemonic, num_hash) print('secret key:') print(hex(prvk.key).upper()) wif_prvk : str = prvk.get_wif(net = net,", "= PublicKey.from_private_key(prvk.key) print('public key:') print('x:', format(pubk.x, '064x')) print('y:', format(pubk.y, '064x')) addr = pubk.address(net", "mnemonic = arg elif opt in ['-h']: num_hash = int(arg) if mnemonic ==", "== '__main__': # Always use the compressed form now. compressed = True net", "'064x')) print('y:', format(pubk.y, '064x')) addr = pubk.address(net = net, compressed = compressed) print('bitcoin", "mnemonic`: deterministic key gen using opts, args = getopt(argv, \"n:d:h:\", [\"net=\", \"deterministic=\"]) except:", "net = arg elif opt in ['-d', '--deterministic']: mnemonic = arg elif opt", "= int(arg) if mnemonic == None: prvk = PrivateKey.gen_random_key() else: print('gen secret key", "arg elif opt in ['-d', '--deterministic']: mnemonic = arg elif opt in ['-h']:", "= getopt(argv, \"n:d:h:\", [\"net=\", \"deterministic=\"]) except: print(\"Error\") for opt, arg in opts: if", "PublicKey, PrivateKey if __name__ == '__main__': # Always use the compressed form now.", "print('secret key:') print(hex(prvk.key).upper()) wif_prvk : str = prvk.get_wif(net = net, compressed = compressed)", "getopt from crypto.key import PublicKey, PrivateKey if __name__ == '__main__': # Always use", "deterministic key gen using opts, args = getopt(argv, \"n:d:h:\", [\"net=\", \"deterministic=\"]) except: print(\"Error\")", "= None num_hash = 3 argv = sys.argv[1:] try: # -n (net) #", "compressed) print('WIF secret key:') print(wif_prvk) pubk = PublicKey.from_private_key(prvk.key) print('public key:') print('x:', format(pubk.x, '064x'))", "opt, arg in opts: if opt in ['-n', \"--net\"]: net = arg elif", "opt in ['-d', '--deterministic']: mnemonic = arg elif opt in ['-h']: num_hash =", "__name__ == '__main__': # Always use the compressed form now. compressed = True", "argv = sys.argv[1:] try: # -n (net) # `-d mnemonic`: deterministic key gen", "arg in opts: if opt in ['-n', \"--net\"]: net = arg elif opt", "\"--net\"]: net = arg elif opt in ['-d', '--deterministic']: mnemonic = arg elif", "'--deterministic']: mnemonic = arg elif opt in ['-h']: num_hash = int(arg) if mnemonic", "prvk.get_wif(net = net, compressed = compressed) print('WIF secret key:') print(wif_prvk) pubk = PublicKey.from_private_key(prvk.key)", "mnemonic: ') print(mnemonic) prvk = PrivateKey.from_mnemonic(mnemonic, num_hash) print('secret key:') print(hex(prvk.key).upper()) wif_prvk : str", "print('public key:') print('x:', format(pubk.x, '064x')) print('y:', format(pubk.y, '064x')) addr = pubk.address(net = net,", "== None: prvk = PrivateKey.gen_random_key() else: print('gen secret key using mnemonic: ') print(mnemonic)", "num_hash = 3 argv = sys.argv[1:] try: # -n (net) # `-d mnemonic`:", "3 argv = sys.argv[1:] try: # -n (net) # `-d mnemonic`: deterministic key", ": str = prvk.get_wif(net = net, compressed = compressed) print('WIF secret key:') print(wif_prvk)", "prvk = PrivateKey.gen_random_key() else: print('gen secret key using mnemonic: ') print(mnemonic) prvk =", "'__main__': # Always use the compressed form now. compressed = True net =", "sys.argv[1:] try: # -n (net) # `-d mnemonic`: deterministic key gen using opts,", "opts: if opt in ['-n', \"--net\"]: net = arg elif opt in ['-d',", "= prvk.get_wif(net = net, compressed = compressed) print('WIF secret key:') print(wif_prvk) pubk =", "key:') print(wif_prvk) pubk = PublicKey.from_private_key(prvk.key) print('public key:') print('x:', format(pubk.x, '064x')) print('y:', format(pubk.y, '064x'))", "format(pubk.x, '064x')) print('y:', format(pubk.y, '064x')) addr = pubk.address(net = net, compressed = compressed)", "if __name__ == '__main__': # Always use the compressed form now. compressed =", "from getopt import getopt from crypto.key import PublicKey, PrivateKey if __name__ == '__main__':", "else: print('gen secret key using mnemonic: ') print(mnemonic) prvk = PrivateKey.from_mnemonic(mnemonic, num_hash) print('secret", "Always use the compressed form now. compressed = True net = \"main\" mnemonic", "# `-d mnemonic`: deterministic key gen using opts, args = getopt(argv, \"n:d:h:\", [\"net=\",", "= net, compressed = compressed) print('WIF secret key:') print(wif_prvk) pubk = PublicKey.from_private_key(prvk.key) print('public", "print('WIF secret key:') print(wif_prvk) pubk = PublicKey.from_private_key(prvk.key) print('public key:') print('x:', format(pubk.x, '064x')) print('y:',", "gen using opts, args = getopt(argv, \"n:d:h:\", [\"net=\", \"deterministic=\"]) except: print(\"Error\") for opt,", "opts, args = getopt(argv, \"n:d:h:\", [\"net=\", \"deterministic=\"]) except: print(\"Error\") for opt, arg in", "arg elif opt in ['-h']: num_hash = int(arg) if mnemonic == None: prvk", "['-d', '--deterministic']: mnemonic = arg elif opt in ['-h']: num_hash = int(arg) if", "in ['-n', \"--net\"]: net = arg elif opt in ['-d', '--deterministic']: mnemonic =", "import getopt from crypto.key import PublicKey, PrivateKey if __name__ == '__main__': # Always", "\"n:d:h:\", [\"net=\", \"deterministic=\"]) except: print(\"Error\") for opt, arg in opts: if opt in", "[\"net=\", \"deterministic=\"]) except: print(\"Error\") for opt, arg in opts: if opt in ['-n',", "num_hash = int(arg) if mnemonic == None: prvk = PrivateKey.gen_random_key() else: print('gen secret", "# -n (net) # `-d mnemonic`: deterministic key gen using opts, args =", "using opts, args = getopt(argv, \"n:d:h:\", [\"net=\", \"deterministic=\"]) except: print(\"Error\") for opt, arg", "print('x:', format(pubk.x, '064x')) print('y:', format(pubk.y, '064x')) addr = pubk.address(net = net, compressed =", "prvk = PrivateKey.from_mnemonic(mnemonic, num_hash) print('secret key:') print(hex(prvk.key).upper()) wif_prvk : str = prvk.get_wif(net =", "print(\"Error\") for opt, arg in opts: if opt in ['-n', \"--net\"]: net =", "from crypto.key import PublicKey, PrivateKey if __name__ == '__main__': # Always use the", "try: # -n (net) # `-d mnemonic`: deterministic key gen using opts, args", "None: prvk = PrivateKey.gen_random_key() else: print('gen secret key using mnemonic: ') print(mnemonic) prvk", "net = \"main\" mnemonic = None num_hash = 3 argv = sys.argv[1:] try:", "if opt in ['-n', \"--net\"]: net = arg elif opt in ['-d', '--deterministic']:", "= 3 argv = sys.argv[1:] try: # -n (net) # `-d mnemonic`: deterministic", "num_hash) print('secret key:') print(hex(prvk.key).upper()) wif_prvk : str = prvk.get_wif(net = net, compressed =", "str = prvk.get_wif(net = net, compressed = compressed) print('WIF secret key:') print(wif_prvk) pubk", "elif opt in ['-h']: num_hash = int(arg) if mnemonic == None: prvk =", "None num_hash = 3 argv = sys.argv[1:] try: # -n (net) # `-d", "opt in ['-n', \"--net\"]: net = arg elif opt in ['-d', '--deterministic']: mnemonic", "-n (net) # `-d mnemonic`: deterministic key gen using opts, args = getopt(argv,", "') print(mnemonic) prvk = PrivateKey.from_mnemonic(mnemonic, num_hash) print('secret key:') print(hex(prvk.key).upper()) wif_prvk : str =", "net, compressed = compressed) print('WIF secret key:') print(wif_prvk) pubk = PublicKey.from_private_key(prvk.key) print('public key:')", "secret key:') print(wif_prvk) pubk = PublicKey.from_private_key(prvk.key) print('public key:') print('x:', format(pubk.x, '064x')) print('y:', format(pubk.y,", "['-h']: num_hash = int(arg) if mnemonic == None: prvk = PrivateKey.gen_random_key() else: print('gen", "= arg elif opt in ['-h']: num_hash = int(arg) if mnemonic == None:", "compressed = compressed) print('WIF secret key:') print(wif_prvk) pubk = PublicKey.from_private_key(prvk.key) print('public key:') print('x:',", "getopt import getopt from crypto.key import PublicKey, PrivateKey if __name__ == '__main__': #", "the compressed form now. compressed = True net = \"main\" mnemonic = None", "wif_prvk : str = prvk.get_wif(net = net, compressed = compressed) print('WIF secret key:')", "print(wif_prvk) pubk = PublicKey.from_private_key(prvk.key) print('public key:') print('x:', format(pubk.x, '064x')) print('y:', format(pubk.y, '064x')) addr", "import sys from getopt import getopt from crypto.key import PublicKey, PrivateKey if __name__", "key gen using opts, args = getopt(argv, \"n:d:h:\", [\"net=\", \"deterministic=\"]) except: print(\"Error\") for", "\"main\" mnemonic = None num_hash = 3 argv = sys.argv[1:] try: # -n", "sys from getopt import getopt from crypto.key import PublicKey, PrivateKey if __name__ ==", "compressed form now. compressed = True net = \"main\" mnemonic = None num_hash", "args = getopt(argv, \"n:d:h:\", [\"net=\", \"deterministic=\"]) except: print(\"Error\") for opt, arg in opts:", "in opts: if opt in ['-n', \"--net\"]: net = arg elif opt in", "format(pubk.y, '064x')) addr = pubk.address(net = net, compressed = compressed) print('bitcoin address:') print(addr)", "mnemonic == None: prvk = PrivateKey.gen_random_key() else: print('gen secret key using mnemonic: ')", "crypto.key import PublicKey, PrivateKey if __name__ == '__main__': # Always use the compressed", "import PublicKey, PrivateKey if __name__ == '__main__': # Always use the compressed form", "int(arg) if mnemonic == None: prvk = PrivateKey.gen_random_key() else: print('gen secret key using", "key:') print(hex(prvk.key).upper()) wif_prvk : str = prvk.get_wif(net = net, compressed = compressed) print('WIF", "now. compressed = True net = \"main\" mnemonic = None num_hash = 3", "in ['-h']: num_hash = int(arg) if mnemonic == None: prvk = PrivateKey.gen_random_key() else:", "= True net = \"main\" mnemonic = None num_hash = 3 argv =", "# Always use the compressed form now. compressed = True net = \"main\"", "(net) # `-d mnemonic`: deterministic key gen using opts, args = getopt(argv, \"n:d:h:\",", "print('gen secret key using mnemonic: ') print(mnemonic) prvk = PrivateKey.from_mnemonic(mnemonic, num_hash) print('secret key:')", "PrivateKey.from_mnemonic(mnemonic, num_hash) print('secret key:') print(hex(prvk.key).upper()) wif_prvk : str = prvk.get_wif(net = net, compressed", "key:') print('x:', format(pubk.x, '064x')) print('y:', format(pubk.y, '064x')) addr = pubk.address(net = net, compressed", "print(mnemonic) prvk = PrivateKey.from_mnemonic(mnemonic, num_hash) print('secret key:') print(hex(prvk.key).upper()) wif_prvk : str = prvk.get_wif(net", "elif opt in ['-d', '--deterministic']: mnemonic = arg elif opt in ['-h']: num_hash", "if mnemonic == None: prvk = PrivateKey.gen_random_key() else: print('gen secret key using mnemonic:", "`-d mnemonic`: deterministic key gen using opts, args = getopt(argv, \"n:d:h:\", [\"net=\", \"deterministic=\"])", "print(hex(prvk.key).upper()) wif_prvk : str = prvk.get_wif(net = net, compressed = compressed) print('WIF secret", "True net = \"main\" mnemonic = None num_hash = 3 argv = sys.argv[1:]", "<gh_stars>0 import sys from getopt import getopt from crypto.key import PublicKey, PrivateKey if", "form now. compressed = True net = \"main\" mnemonic = None num_hash =", "= PrivateKey.gen_random_key() else: print('gen secret key using mnemonic: ') print(mnemonic) prvk = PrivateKey.from_mnemonic(mnemonic,", "opt in ['-h']: num_hash = int(arg) if mnemonic == None: prvk = PrivateKey.gen_random_key()", "= sys.argv[1:] try: # -n (net) # `-d mnemonic`: deterministic key gen using", "in ['-d', '--deterministic']: mnemonic = arg elif opt in ['-h']: num_hash = int(arg)", "= compressed) print('WIF secret key:') print(wif_prvk) pubk = PublicKey.from_private_key(prvk.key) print('public key:') print('x:', format(pubk.x,", "= arg elif opt in ['-d', '--deterministic']: mnemonic = arg elif opt in", "for opt, arg in opts: if opt in ['-n', \"--net\"]: net = arg", "PrivateKey.gen_random_key() else: print('gen secret key using mnemonic: ') print(mnemonic) prvk = PrivateKey.from_mnemonic(mnemonic, num_hash)", "pubk = PublicKey.from_private_key(prvk.key) print('public key:') print('x:', format(pubk.x, '064x')) print('y:', format(pubk.y, '064x')) addr =", "except: print(\"Error\") for opt, arg in opts: if opt in ['-n', \"--net\"]: net", "use the compressed form now. compressed = True net = \"main\" mnemonic =", "= \"main\" mnemonic = None num_hash = 3 argv = sys.argv[1:] try: #", "PublicKey.from_private_key(prvk.key) print('public key:') print('x:', format(pubk.x, '064x')) print('y:', format(pubk.y, '064x')) addr = pubk.address(net =", "key using mnemonic: ') print(mnemonic) prvk = PrivateKey.from_mnemonic(mnemonic, num_hash) print('secret key:') print(hex(prvk.key).upper()) wif_prvk", "['-n', \"--net\"]: net = arg elif opt in ['-d', '--deterministic']: mnemonic = arg", "using mnemonic: ') print(mnemonic) prvk = PrivateKey.from_mnemonic(mnemonic, num_hash) print('secret key:') print(hex(prvk.key).upper()) wif_prvk :", "secret key using mnemonic: ') print(mnemonic) prvk = PrivateKey.from_mnemonic(mnemonic, num_hash) print('secret key:') print(hex(prvk.key).upper())", "getopt(argv, \"n:d:h:\", [\"net=\", \"deterministic=\"]) except: print(\"Error\") for opt, arg in opts: if opt", "\"deterministic=\"]) except: print(\"Error\") for opt, arg in opts: if opt in ['-n', \"--net\"]:", "print('y:', format(pubk.y, '064x')) addr = pubk.address(net = net, compressed = compressed) print('bitcoin address:')", "mnemonic = None num_hash = 3 argv = sys.argv[1:] try: # -n (net)", "PrivateKey if __name__ == '__main__': # Always use the compressed form now. compressed" ]
[ "gets called repeatedly until the stop_attack function gets called. The class which extends", "AttackMethod class. The function gets called repeatedly until the stop_attack function gets called.", "function is only for internal use. :param value: New value of the _attack_is_value", "the attack thread and could not be called directly. \"\"\" while self.is_active(): try:", "be implemented by the class which extends from the AttackMethod class. The function", "is_active(self): \"\"\" Checks the value of the _attack_is_active value in a thread safe", "extends from this class has to implement it's attack logic in this function.", "_attack_is_active value in a thread safe was. Use this function to get the", "__metaclass__ = abc.ABCMeta def __init__(self, proxy, target): \"\"\" Constructor. Creates a new AttackMethod", "the value directly. :return: True if the attack is active and False otherwise", "AttackMethod class represents a DOS attack. The AttackMethod class is an abstract class", "self.stop_attack() def is_active(self): \"\"\" Checks the value of the _attack_is_active value in a", "the _attack_is_active value. This function is only for internal use. :param value: New", "the _attack_is_value value (True or False) \"\"\" if not isinstance(value, bool): raise ValueError('set_attack_active", "ex self.stop_attack() def is_active(self): \"\"\" Checks the value of the _attack_is_active value in", "use. :param value: New value of the _attack_is_value value (True or False) \"\"\"", "__init__(self, proxy, target): \"\"\" Constructor. Creates a new AttackMethod instance. :type target: Destination", "of the _attack_is_active value in a thread safe was. Use this function to", "thread safe was. Use this function to get the value of _attack_is_active instead", "the value of _attack_is_active instead of checking the value directly. :return: True if", "True self._attack_lock.release() self._innerThread = thread.start_new_thread(self._thread_loop, ()) else: self._attack_lock.release() def stop_attack(self): \"\"\" Stops the", "False self._innerThread = None self._attack_lock = threading.Lock() self._attack_target = target self._loop_delay = 0.050", "extends from the AttackMethod class. The function gets called repeatedly until the stop_attack", "for internal use. :param value: New value of the _attack_is_value value (True or", "AttackMethod class is an abstract class and needs to be extended by other", "start_attack() function is called and stops when the stop_attack() function is called. \"\"\"", "directly. :return: True if the attack is active and False otherwise \"\"\" self._attack_lock.acquire()", "def _thread_loop(self): \"\"\" The main loop of the attack thread. This function is", "by other classes. An AttackMethod runs in its own thread. The thread loop", "_set_attack_active(self, value): \"\"\" Thread-safe setter for the _attack_is_active value. This function is only", "for the _attack_is_active value. This function is only for internal use. :param value:", ":type proxy: Proxy \"\"\" self._proxy = proxy self._attack_is_active = False self._innerThread = None", "directly. \"\"\" while self.is_active(): try: self._attack_loop() sleep(self._loop_delay) except Exception as ex: self.exception =", "Use this function to get the value of _attack_is_active instead of checking the", "is not None else: return False def get_exception(self): return self.exception def _thread_loop(self): \"\"\"", "target self._loop_delay = 0.050 self.exception = None def start_attack(self): \"\"\" Starts the DOS", "raise ValueError('set_attack_active value has to be a boolean and not a ' +", "which extends from this class has to implement it's attack logic in this", "is only for internal use. :param value: New value of the _attack_is_value value", "instead of checking the value directly. :return: True if the attack is active", "function has to be implemented by the class which extends from the AttackMethod", "def get_exception(self): return self.exception def _thread_loop(self): \"\"\" The main loop of the attack", "of _attack_is_active instead of checking the value directly. :return: True if the attack", "has_exception(self): if not self.is_active(): return self.exception is not None else: return False def", "value of _attack_is_active instead of checking the value directly. :return: True if the", "the DOS attack. \"\"\" self._attack_lock.acquire() if not self._attack_is_active: self._attack_is_active = True self._attack_lock.release() self._innerThread", "else: self._attack_lock.release() def stop_attack(self): \"\"\" Stops the attack loop. \"\"\" self._set_attack_active(False) def has_exception(self):", "has to be a boolean and not a ' + type(value)) self._attack_lock.acquire() self._attack_is_active", "= 0.050 self.exception = None def start_attack(self): \"\"\" Starts the DOS attack. \"\"\"", "abstract class and needs to be extended by other classes. An AttackMethod runs", "while self.is_active(): try: self._attack_loop() sleep(self._loop_delay) except Exception as ex: self.exception = ex self.stop_attack()", "the stop_attack() function is called. \"\"\" __metaclass__ = abc.ABCMeta def __init__(self, proxy, target):", "New value of the _attack_is_value value (True or False) \"\"\" if not isinstance(value,", "called directly. \"\"\" while self.is_active(): try: self._attack_loop() sleep(self._loop_delay) except Exception as ex: self.exception", "self._attack_lock.release() return attack_active def _set_attack_active(self, value): \"\"\" Thread-safe setter for the _attack_is_active value.", "(True or False) \"\"\" if not isinstance(value, bool): raise ValueError('set_attack_active value has to", "repeatedly until the stop_attack function gets called. The class which extends from this", "_attack_loop(self): \"\"\" Part of the _thread_loop. This function has to be implemented by", "False) \"\"\" if not isinstance(value, bool): raise ValueError('set_attack_active value has to be a", "runs in its own thread. The thread loop starts when the start_attack() function", "thread. This function is called by the attack thread and could not be", "self._set_attack_active(False) def has_exception(self): if not self.is_active(): return self.exception is not None else: return", "self._proxy = proxy self._attack_is_active = False self._innerThread = None self._attack_lock = threading.Lock() self._attack_target", "self._attack_lock.acquire() self._attack_is_active = value self._attack_lock.release() @abc.abstractmethod def _attack_loop(self): \"\"\" Part of the _thread_loop.", "which extends from the AttackMethod class. The function gets called repeatedly until the", "self.exception is not None else: return False def get_exception(self): return self.exception def _thread_loop(self):", "False def get_exception(self): return self.exception def _thread_loop(self): \"\"\" The main loop of the", "called repeatedly until the stop_attack function gets called. The class which extends from", "the attack is active and False otherwise \"\"\" self._attack_lock.acquire() attack_active = self._attack_is_active self._attack_lock.release()", "import thread import threading import abc from time import sleep class AttackMethod: \"\"\"", "Destination :type proxy: Proxy \"\"\" self._proxy = proxy self._attack_is_active = False self._innerThread =", "The function gets called repeatedly until the stop_attack function gets called. The class", "when the stop_attack() function is called. \"\"\" __metaclass__ = abc.ABCMeta def __init__(self, proxy,", "only for internal use. :param value: New value of the _attack_is_value value (True", "True if the attack is active and False otherwise \"\"\" self._attack_lock.acquire() attack_active =", "if not self.is_active(): return self.exception is not None else: return False def get_exception(self):", "the _attack_is_active value in a thread safe was. Use this function to get", "AttackMethod: \"\"\" The AttackMethod class represents a DOS attack. The AttackMethod class is", "try: self._attack_loop() sleep(self._loop_delay) except Exception as ex: self.exception = ex self.stop_attack() def is_active(self):", "self._loop_delay = 0.050 self.exception = None def start_attack(self): \"\"\" Starts the DOS attack.", "own thread. The thread loop starts when the start_attack() function is called and", "_thread_loop(self): \"\"\" The main loop of the attack thread. This function is called", "stop_attack() function is called. \"\"\" __metaclass__ = abc.ABCMeta def __init__(self, proxy, target): \"\"\"", "\"\"\" if not isinstance(value, bool): raise ValueError('set_attack_active value has to be a boolean", "\"\"\" self._attack_lock.acquire() attack_active = self._attack_is_active self._attack_lock.release() return attack_active def _set_attack_active(self, value): \"\"\" Thread-safe", "is an abstract class and needs to be extended by other classes. An", "the stop_attack function gets called. The class which extends from this class has", "\"\"\" Thread-safe setter for the _attack_is_active value. This function is only for internal", "classes. An AttackMethod runs in its own thread. The thread loop starts when", "False otherwise \"\"\" self._attack_lock.acquire() attack_active = self._attack_is_active self._attack_lock.release() return attack_active def _set_attack_active(self, value):", "has to be implemented by the class which extends from the AttackMethod class.", "self._attack_lock.acquire() if not self._attack_is_active: self._attack_is_active = True self._attack_lock.release() self._innerThread = thread.start_new_thread(self._thread_loop, ()) else:", "def has_exception(self): if not self.is_active(): return self.exception is not None else: return False", "stop_attack(self): \"\"\" Stops the attack loop. \"\"\" self._set_attack_active(False) def has_exception(self): if not self.is_active():", "The AttackMethod class represents a DOS attack. The AttackMethod class is an abstract", "get the value of _attack_is_active instead of checking the value directly. :return: True", "the _thread_loop. This function has to be implemented by the class which extends", "Constructor. Creates a new AttackMethod instance. :type target: Destination :type proxy: Proxy \"\"\"", "is called. \"\"\" __metaclass__ = abc.ABCMeta def __init__(self, proxy, target): \"\"\" Constructor. Creates", "An AttackMethod runs in its own thread. The thread loop starts when the", "\"\"\" Constructor. Creates a new AttackMethod instance. :type target: Destination :type proxy: Proxy", "AttackMethod instance. :type target: Destination :type proxy: Proxy \"\"\" self._proxy = proxy self._attack_is_active", "if the attack is active and False otherwise \"\"\" self._attack_lock.acquire() attack_active = self._attack_is_active", "of the attack thread. This function is called by the attack thread and", "called and stops when the stop_attack() function is called. \"\"\" __metaclass__ = abc.ABCMeta", "Creates a new AttackMethod instance. :type target: Destination :type proxy: Proxy \"\"\" self._proxy", "attack is active and False otherwise \"\"\" self._attack_lock.acquire() attack_active = self._attack_is_active self._attack_lock.release() return", "the value of the _attack_is_active value in a thread safe was. Use this", "= None self._attack_lock = threading.Lock() self._attack_target = target self._loop_delay = 0.050 self.exception =", "sleep(self._loop_delay) except Exception as ex: self.exception = ex self.stop_attack() def is_active(self): \"\"\" Checks", "return self.exception is not None else: return False def get_exception(self): return self.exception def", "threading import abc from time import sleep class AttackMethod: \"\"\" The AttackMethod class", "to be implemented by the class which extends from the AttackMethod class. The", "the class which extends from the AttackMethod class. The function gets called repeatedly", "called by the attack thread and could not be called directly. \"\"\" while", "of the _thread_loop. This function has to be implemented by the class which", "when the start_attack() function is called and stops when the stop_attack() function is", "of the _attack_is_value value (True or False) \"\"\" if not isinstance(value, bool): raise", "This function is only for internal use. :param value: New value of the", "class represents a DOS attack. The AttackMethod class is an abstract class and", "value directly. :return: True if the attack is active and False otherwise \"\"\"", "not a ' + type(value)) self._attack_lock.acquire() self._attack_is_active = value self._attack_lock.release() @abc.abstractmethod def _attack_loop(self):", "= threading.Lock() self._attack_target = target self._loop_delay = 0.050 self.exception = None def start_attack(self):", "the attack loop. \"\"\" self._set_attack_active(False) def has_exception(self): if not self.is_active(): return self.exception is", "and False otherwise \"\"\" self._attack_lock.acquire() attack_active = self._attack_is_active self._attack_lock.release() return attack_active def _set_attack_active(self,", "could not be called directly. \"\"\" while self.is_active(): try: self._attack_loop() sleep(self._loop_delay) except Exception", "function is called by the attack thread and could not be called directly.", "of checking the value directly. :return: True if the attack is active and", "to be extended by other classes. An AttackMethod runs in its own thread.", "= thread.start_new_thread(self._thread_loop, ()) else: self._attack_lock.release() def stop_attack(self): \"\"\" Stops the attack loop. \"\"\"", "thread.start_new_thread(self._thread_loop, ()) else: self._attack_lock.release() def stop_attack(self): \"\"\" Stops the attack loop. \"\"\" self._set_attack_active(False)", "()) else: self._attack_lock.release() def stop_attack(self): \"\"\" Stops the attack loop. \"\"\" self._set_attack_active(False) def", "self._innerThread = None self._attack_lock = threading.Lock() self._attack_target = target self._loop_delay = 0.050 self.exception", "value of the _attack_is_active value in a thread safe was. Use this function", "active and False otherwise \"\"\" self._attack_lock.acquire() attack_active = self._attack_is_active self._attack_lock.release() return attack_active def", "by the class which extends from the AttackMethod class. The function gets called", "self._attack_lock.release() def stop_attack(self): \"\"\" Stops the attack loop. \"\"\" self._set_attack_active(False) def has_exception(self): if", "self._attack_is_active = value self._attack_lock.release() @abc.abstractmethod def _attack_loop(self): \"\"\" Part of the _thread_loop. This", "an abstract class and needs to be extended by other classes. An AttackMethod", "ValueError('set_attack_active value has to be a boolean and not a ' + type(value))", "value. This function is only for internal use. :param value: New value of", "from time import sleep class AttackMethod: \"\"\" The AttackMethod class represents a DOS", "Stops the attack loop. \"\"\" self._set_attack_active(False) def has_exception(self): if not self.is_active(): return self.exception", "self._attack_is_active = False self._innerThread = None self._attack_lock = threading.Lock() self._attack_target = target self._loop_delay", "boolean and not a ' + type(value)) self._attack_lock.acquire() self._attack_is_active = value self._attack_lock.release() @abc.abstractmethod", "the start_attack() function is called and stops when the stop_attack() function is called.", "is called by the attack thread and could not be called directly. \"\"\"", "\"\"\" Checks the value of the _attack_is_active value in a thread safe was.", "self._attack_lock.acquire() attack_active = self._attack_is_active self._attack_lock.release() return attack_active def _set_attack_active(self, value): \"\"\" Thread-safe setter", "None def start_attack(self): \"\"\" Starts the DOS attack. \"\"\" self._attack_lock.acquire() if not self._attack_is_active:", "to be a boolean and not a ' + type(value)) self._attack_lock.acquire() self._attack_is_active =", "proxy: Proxy \"\"\" self._proxy = proxy self._attack_is_active = False self._innerThread = None self._attack_lock", "not be called directly. \"\"\" while self.is_active(): try: self._attack_loop() sleep(self._loop_delay) except Exception as", "ex: self.exception = ex self.stop_attack() def is_active(self): \"\"\" Checks the value of the", "a new AttackMethod instance. :type target: Destination :type proxy: Proxy \"\"\" self._proxy =", "_attack_is_active instead of checking the value directly. :return: True if the attack is", "value): \"\"\" Thread-safe setter for the _attack_is_active value. This function is only for", "attack thread and could not be called directly. \"\"\" while self.is_active(): try: self._attack_loop()", "def _attack_loop(self): \"\"\" Part of the _thread_loop. This function has to be implemented", "= None def start_attack(self): \"\"\" Starts the DOS attack. \"\"\" self._attack_lock.acquire() if not", "a ' + type(value)) self._attack_lock.acquire() self._attack_is_active = value self._attack_lock.release() @abc.abstractmethod def _attack_loop(self): \"\"\"", "the AttackMethod class. The function gets called repeatedly until the stop_attack function gets", "not None else: return False def get_exception(self): return self.exception def _thread_loop(self): \"\"\" The", "None else: return False def get_exception(self): return self.exception def _thread_loop(self): \"\"\" The main", "@abc.abstractmethod def _attack_loop(self): \"\"\" Part of the _thread_loop. This function has to be", "gets called. The class which extends from this class has to implement it's", "extended by other classes. An AttackMethod runs in its own thread. The thread", "if not isinstance(value, bool): raise ValueError('set_attack_active value has to be a boolean and", "import abc from time import sleep class AttackMethod: \"\"\" The AttackMethod class represents", "return self.exception def _thread_loop(self): \"\"\" The main loop of the attack thread. This", "from the AttackMethod class. The function gets called repeatedly until the stop_attack function", "\"\"\" The AttackMethod class represents a DOS attack. The AttackMethod class is an", "this function to get the value of _attack_is_active instead of checking the value", "and needs to be extended by other classes. An AttackMethod runs in its", "def stop_attack(self): \"\"\" Stops the attack loop. \"\"\" self._set_attack_active(False) def has_exception(self): if not", "target): \"\"\" Constructor. Creates a new AttackMethod instance. :type target: Destination :type proxy:", "= target self._loop_delay = 0.050 self.exception = None def start_attack(self): \"\"\" Starts the", "loop of the attack thread. This function is called by the attack thread", "return attack_active def _set_attack_active(self, value): \"\"\" Thread-safe setter for the _attack_is_active value. This", "start_attack(self): \"\"\" Starts the DOS attack. \"\"\" self._attack_lock.acquire() if not self._attack_is_active: self._attack_is_active =", "= self._attack_is_active self._attack_lock.release() return attack_active def _set_attack_active(self, value): \"\"\" Thread-safe setter for the", "proxy self._attack_is_active = False self._innerThread = None self._attack_lock = threading.Lock() self._attack_target = target", "and stops when the stop_attack() function is called. \"\"\" __metaclass__ = abc.ABCMeta def", "function gets called repeatedly until the stop_attack function gets called. The class which", "function to get the value of _attack_is_active instead of checking the value directly.", "a DOS attack. The AttackMethod class is an abstract class and needs to", "be called directly. \"\"\" while self.is_active(): try: self._attack_loop() sleep(self._loop_delay) except Exception as ex:", "\"\"\" Part of the _thread_loop. This function has to be implemented by the", "until the stop_attack function gets called. The class which extends from this class", "function gets called. The class which extends from this class has to implement", "attack thread. This function is called by the attack thread and could not", "attack_active = self._attack_is_active self._attack_lock.release() return attack_active def _set_attack_active(self, value): \"\"\" Thread-safe setter for", "setter for the _attack_is_active value. This function is only for internal use. :param", "DOS attack. \"\"\" self._attack_lock.acquire() if not self._attack_is_active: self._attack_is_active = True self._attack_lock.release() self._innerThread =", "stops when the stop_attack() function is called. \"\"\" __metaclass__ = abc.ABCMeta def __init__(self,", "\"\"\" self._attack_lock.acquire() if not self._attack_is_active: self._attack_is_active = True self._attack_lock.release() self._innerThread = thread.start_new_thread(self._thread_loop, ())", "= value self._attack_lock.release() @abc.abstractmethod def _attack_loop(self): \"\"\" Part of the _thread_loop. This function", "thread and could not be called directly. \"\"\" while self.is_active(): try: self._attack_loop() sleep(self._loop_delay)", "_attack_is_active value. This function is only for internal use. :param value: New value", "= abc.ABCMeta def __init__(self, proxy, target): \"\"\" Constructor. Creates a new AttackMethod instance.", "class is an abstract class and needs to be extended by other classes.", "not self.is_active(): return self.exception is not None else: return False def get_exception(self): return", "None self._attack_lock = threading.Lock() self._attack_target = target self._loop_delay = 0.050 self.exception = None", "The class which extends from this class has to implement it's attack logic", "The main loop of the attack thread. This function is called by the", "is active and False otherwise \"\"\" self._attack_lock.acquire() attack_active = self._attack_is_active self._attack_lock.release() return attack_active", "thread import threading import abc from time import sleep class AttackMethod: \"\"\" The", "self.exception = ex self.stop_attack() def is_active(self): \"\"\" Checks the value of the _attack_is_active", "type(value)) self._attack_lock.acquire() self._attack_is_active = value self._attack_lock.release() @abc.abstractmethod def _attack_loop(self): \"\"\" Part of the", "def start_attack(self): \"\"\" Starts the DOS attack. \"\"\" self._attack_lock.acquire() if not self._attack_is_active: self._attack_is_active", "value has to be a boolean and not a ' + type(value)) self._attack_lock.acquire()", "stop_attack function gets called. The class which extends from this class has to", "as ex: self.exception = ex self.stop_attack() def is_active(self): \"\"\" Checks the value of", "Thread-safe setter for the _attack_is_active value. This function is only for internal use.", "bool): raise ValueError('set_attack_active value has to be a boolean and not a '", "class and needs to be extended by other classes. An AttackMethod runs in", "a thread safe was. Use this function to get the value of _attack_is_active", "self._attack_lock.release() @abc.abstractmethod def _attack_loop(self): \"\"\" Part of the _thread_loop. This function has to", "in a thread safe was. Use this function to get the value of", "\"\"\" __metaclass__ = abc.ABCMeta def __init__(self, proxy, target): \"\"\" Constructor. Creates a new", "class which extends from the AttackMethod class. The function gets called repeatedly until", "class AttackMethod: \"\"\" The AttackMethod class represents a DOS attack. The AttackMethod class", "abc.ABCMeta def __init__(self, proxy, target): \"\"\" Constructor. Creates a new AttackMethod instance. :type", "self._innerThread = thread.start_new_thread(self._thread_loop, ()) else: self._attack_lock.release() def stop_attack(self): \"\"\" Stops the attack loop.", "or False) \"\"\" if not isinstance(value, bool): raise ValueError('set_attack_active value has to be", "was. Use this function to get the value of _attack_is_active instead of checking", "the attack thread. This function is called by the attack thread and could", "self.exception def _thread_loop(self): \"\"\" The main loop of the attack thread. This function", "0.050 self.exception = None def start_attack(self): \"\"\" Starts the DOS attack. \"\"\" self._attack_lock.acquire()", "return False def get_exception(self): return self.exception def _thread_loop(self): \"\"\" The main loop of", "attack loop. \"\"\" self._set_attack_active(False) def has_exception(self): if not self.is_active(): return self.exception is not", "The AttackMethod class is an abstract class and needs to be extended by", "self._attack_lock = threading.Lock() self._attack_target = target self._loop_delay = 0.050 self.exception = None def", "self.exception = None def start_attack(self): \"\"\" Starts the DOS attack. \"\"\" self._attack_lock.acquire() if", "The thread loop starts when the start_attack() function is called and stops when", "attack. The AttackMethod class is an abstract class and needs to be extended", "function is called and stops when the stop_attack() function is called. \"\"\" __metaclass__", "sleep class AttackMethod: \"\"\" The AttackMethod class represents a DOS attack. The AttackMethod", "self.is_active(): try: self._attack_loop() sleep(self._loop_delay) except Exception as ex: self.exception = ex self.stop_attack() def", "attack_active def _set_attack_active(self, value): \"\"\" Thread-safe setter for the _attack_is_active value. This function", "attack. \"\"\" self._attack_lock.acquire() if not self._attack_is_active: self._attack_is_active = True self._attack_lock.release() self._innerThread = thread.start_new_thread(self._thread_loop,", "and not a ' + type(value)) self._attack_lock.acquire() self._attack_is_active = value self._attack_lock.release() @abc.abstractmethod def", ":return: True if the attack is active and False otherwise \"\"\" self._attack_lock.acquire() attack_active", "\"\"\" Starts the DOS attack. \"\"\" self._attack_lock.acquire() if not self._attack_is_active: self._attack_is_active = True", "def is_active(self): \"\"\" Checks the value of the _attack_is_active value in a thread", "This function has to be implemented by the class which extends from the", "This function is called by the attack thread and could not be called", "instance. :type target: Destination :type proxy: Proxy \"\"\" self._proxy = proxy self._attack_is_active =", "thread loop starts when the start_attack() function is called and stops when the", "new AttackMethod instance. :type target: Destination :type proxy: Proxy \"\"\" self._proxy = proxy", "self._attack_loop() sleep(self._loop_delay) except Exception as ex: self.exception = ex self.stop_attack() def is_active(self): \"\"\"", "called. \"\"\" __metaclass__ = abc.ABCMeta def __init__(self, proxy, target): \"\"\" Constructor. Creates a", "except Exception as ex: self.exception = ex self.stop_attack() def is_active(self): \"\"\" Checks the", "= ex self.stop_attack() def is_active(self): \"\"\" Checks the value of the _attack_is_active value", "time import sleep class AttackMethod: \"\"\" The AttackMethod class represents a DOS attack.", "AttackMethod runs in its own thread. The thread loop starts when the start_attack()", "function is called. \"\"\" __metaclass__ = abc.ABCMeta def __init__(self, proxy, target): \"\"\" Constructor.", "else: return False def get_exception(self): return self.exception def _thread_loop(self): \"\"\" The main loop", "threading.Lock() self._attack_target = target self._loop_delay = 0.050 self.exception = None def start_attack(self): \"\"\"", "be extended by other classes. An AttackMethod runs in its own thread. The", "= False self._innerThread = None self._attack_lock = threading.Lock() self._attack_target = target self._loop_delay =", "_attack_is_value value (True or False) \"\"\" if not isinstance(value, bool): raise ValueError('set_attack_active value", "starts when the start_attack() function is called and stops when the stop_attack() function", "safe was. Use this function to get the value of _attack_is_active instead of", "internal use. :param value: New value of the _attack_is_value value (True or False)", "checking the value directly. :return: True if the attack is active and False", "import sleep class AttackMethod: \"\"\" The AttackMethod class represents a DOS attack. The", "+ type(value)) self._attack_lock.acquire() self._attack_is_active = value self._attack_lock.release() @abc.abstractmethod def _attack_loop(self): \"\"\" Part of", "abc from time import sleep class AttackMethod: \"\"\" The AttackMethod class represents a", "\"\"\" The main loop of the attack thread. This function is called by", ":param value: New value of the _attack_is_value value (True or False) \"\"\" if", "target: Destination :type proxy: Proxy \"\"\" self._proxy = proxy self._attack_is_active = False self._innerThread", "and could not be called directly. \"\"\" while self.is_active(): try: self._attack_loop() sleep(self._loop_delay) except", "proxy, target): \"\"\" Constructor. Creates a new AttackMethod instance. :type target: Destination :type", "\"\"\" while self.is_active(): try: self._attack_loop() sleep(self._loop_delay) except Exception as ex: self.exception = ex", "in its own thread. The thread loop starts when the start_attack() function is", "if not self._attack_is_active: self._attack_is_active = True self._attack_lock.release() self._innerThread = thread.start_new_thread(self._thread_loop, ()) else: self._attack_lock.release()", "self._attack_is_active = True self._attack_lock.release() self._innerThread = thread.start_new_thread(self._thread_loop, ()) else: self._attack_lock.release() def stop_attack(self): \"\"\"", "this class has to implement it's attack logic in this function. \"\"\" return", "to get the value of _attack_is_active instead of checking the value directly. :return:", "DOS attack. The AttackMethod class is an abstract class and needs to be", "Part of the _thread_loop. This function has to be implemented by the class", "called. The class which extends from this class has to implement it's attack", "self._attack_is_active self._attack_lock.release() return attack_active def _set_attack_active(self, value): \"\"\" Thread-safe setter for the _attack_is_active", "needs to be extended by other classes. An AttackMethod runs in its own", "class. The function gets called repeatedly until the stop_attack function gets called. The", "loop. \"\"\" self._set_attack_active(False) def has_exception(self): if not self.is_active(): return self.exception is not None", ":type target: Destination :type proxy: Proxy \"\"\" self._proxy = proxy self._attack_is_active = False", "by the attack thread and could not be called directly. \"\"\" while self.is_active():", "is called and stops when the stop_attack() function is called. \"\"\" __metaclass__ =", "= True self._attack_lock.release() self._innerThread = thread.start_new_thread(self._thread_loop, ()) else: self._attack_lock.release() def stop_attack(self): \"\"\" Stops", "isinstance(value, bool): raise ValueError('set_attack_active value has to be a boolean and not a", "get_exception(self): return self.exception def _thread_loop(self): \"\"\" The main loop of the attack thread.", "def __init__(self, proxy, target): \"\"\" Constructor. Creates a new AttackMethod instance. :type target:", "self._attack_is_active: self._attack_is_active = True self._attack_lock.release() self._innerThread = thread.start_new_thread(self._thread_loop, ()) else: self._attack_lock.release() def stop_attack(self):", "a boolean and not a ' + type(value)) self._attack_lock.acquire() self._attack_is_active = value self._attack_lock.release()", "main loop of the attack thread. This function is called by the attack", "\"\"\" Stops the attack loop. \"\"\" self._set_attack_active(False) def has_exception(self): if not self.is_active(): return", "loop starts when the start_attack() function is called and stops when the stop_attack()", "Exception as ex: self.exception = ex self.stop_attack() def is_active(self): \"\"\" Checks the value", "self._attack_lock.release() self._innerThread = thread.start_new_thread(self._thread_loop, ()) else: self._attack_lock.release() def stop_attack(self): \"\"\" Stops the attack", "class which extends from this class has to implement it's attack logic in", "from this class has to implement it's attack logic in this function. \"\"\"", "Proxy \"\"\" self._proxy = proxy self._attack_is_active = False self._innerThread = None self._attack_lock =", "_thread_loop. This function has to be implemented by the class which extends from", "value in a thread safe was. Use this function to get the value", "import threading import abc from time import sleep class AttackMethod: \"\"\" The AttackMethod", "represents a DOS attack. The AttackMethod class is an abstract class and needs", "thread. The thread loop starts when the start_attack() function is called and stops", "self._attack_target = target self._loop_delay = 0.050 self.exception = None def start_attack(self): \"\"\" Starts", "\"\"\" self._set_attack_active(False) def has_exception(self): if not self.is_active(): return self.exception is not None else:", "be a boolean and not a ' + type(value)) self._attack_lock.acquire() self._attack_is_active = value", "self.is_active(): return self.exception is not None else: return False def get_exception(self): return self.exception", "Starts the DOS attack. \"\"\" self._attack_lock.acquire() if not self._attack_is_active: self._attack_is_active = True self._attack_lock.release()", "value: New value of the _attack_is_value value (True or False) \"\"\" if not", "its own thread. The thread loop starts when the start_attack() function is called", "value (True or False) \"\"\" if not isinstance(value, bool): raise ValueError('set_attack_active value has", "value self._attack_lock.release() @abc.abstractmethod def _attack_loop(self): \"\"\" Part of the _thread_loop. This function has", "value of the _attack_is_value value (True or False) \"\"\" if not isinstance(value, bool):", "implemented by the class which extends from the AttackMethod class. The function gets", "Checks the value of the _attack_is_active value in a thread safe was. Use", "\"\"\" self._proxy = proxy self._attack_is_active = False self._innerThread = None self._attack_lock = threading.Lock()", "not isinstance(value, bool): raise ValueError('set_attack_active value has to be a boolean and not", "= proxy self._attack_is_active = False self._innerThread = None self._attack_lock = threading.Lock() self._attack_target =", "def _set_attack_active(self, value): \"\"\" Thread-safe setter for the _attack_is_active value. This function is", "not self._attack_is_active: self._attack_is_active = True self._attack_lock.release() self._innerThread = thread.start_new_thread(self._thread_loop, ()) else: self._attack_lock.release() def", "other classes. An AttackMethod runs in its own thread. The thread loop starts", "otherwise \"\"\" self._attack_lock.acquire() attack_active = self._attack_is_active self._attack_lock.release() return attack_active def _set_attack_active(self, value): \"\"\"", "' + type(value)) self._attack_lock.acquire() self._attack_is_active = value self._attack_lock.release() @abc.abstractmethod def _attack_loop(self): \"\"\" Part" ]
[ "def action(self): return self._action @action.setter def action(self, value): self._action = value @property def", "None @property def action(self): return self._action @action.setter def action(self, value): self._action = value", "def visit_ac(self, value): self._visit_ac = value @property def visit_biz_line(self): return self._visit_biz_line @visit_biz_line.setter def", "value): self._visit_biz_line = value @property def visit_bu(self): return self._visit_bu @visit_bu.setter def visit_bu(self, value):", "else: params['action'] = self.action if self.action_param: if hasattr(self.action_param, 'to_alipay_dict'): params['action_param'] = self.action_param.to_alipay_dict() else:", "python # -*- coding: utf-8 -*- import json from alipay.aop.api.constant.ParamConstants import * class", "@property def visit_biz_line(self): return self._visit_biz_line @visit_biz_line.setter def visit_biz_line(self, value): self._visit_biz_line = value @property", "self.visit_ac: if hasattr(self.visit_ac, 'to_alipay_dict'): params['visit_ac'] = self.visit_ac.to_alipay_dict() else: params['visit_ac'] = self.visit_ac if self.visit_biz_line:", "value def to_alipay_dict(self): params = dict() if self.action: if hasattr(self.action, 'to_alipay_dict'): params['action'] =", "def action_param(self): return self._action_param @action_param.setter def action_param(self, value): self._action_param = value @property def", "@data_channel.setter def data_channel(self, value): self._data_channel = value @property def visit_ac(self): return self._visit_ac @visit_ac.setter", "if self.action: if hasattr(self.action, 'to_alipay_dict'): params['action'] = self.action.to_alipay_dict() else: params['action'] = self.action if", "@visit_ac.setter def visit_ac(self, value): self._visit_ac = value @property def visit_biz_line(self): return self._visit_biz_line @visit_biz_line.setter", "= self.action_param if self.base: if hasattr(self.base, 'to_alipay_dict'): params['base'] = self.base.to_alipay_dict() else: params['base'] =", "@staticmethod def from_alipay_dict(d): if not d: return None o = SsdataDataserviceDatapropertyBatchqueryModel() if 'action'", "'to_alipay_dict'): params['data_channel'] = self.data_channel.to_alipay_dict() else: params['data_channel'] = self.data_channel if self.visit_ac: if hasattr(self.visit_ac, 'to_alipay_dict'):", "def visit_ac(self): return self._visit_ac @visit_ac.setter def visit_ac(self, value): self._visit_ac = value @property def", "self._visit_bu = None @property def action(self): return self._action @action.setter def action(self, value): self._action", "params['base'] = self.base if self.data_channel: if hasattr(self.data_channel, 'to_alipay_dict'): params['data_channel'] = self.data_channel.to_alipay_dict() else: params['data_channel']", "value): self._data_channel = value @property def visit_ac(self): return self._visit_ac @visit_ac.setter def visit_ac(self, value):", "self.visit_biz_line if self.visit_bu: if hasattr(self.visit_bu, 'to_alipay_dict'): params['visit_bu'] = self.visit_bu.to_alipay_dict() else: params['visit_bu'] = self.visit_bu", "d: return None o = SsdataDataserviceDatapropertyBatchqueryModel() if 'action' in d: o.action = d['action']", "params['visit_bu'] = self.visit_bu return params @staticmethod def from_alipay_dict(d): if not d: return None", "self.base.to_alipay_dict() else: params['base'] = self.base if self.data_channel: if hasattr(self.data_channel, 'to_alipay_dict'): params['data_channel'] = self.data_channel.to_alipay_dict()", "= value @property def data_channel(self): return self._data_channel @data_channel.setter def data_channel(self, value): self._data_channel =", "value): self._base = value @property def data_channel(self): return self._data_channel @data_channel.setter def data_channel(self, value):", "self._data_channel = value @property def visit_ac(self): return self._visit_ac @visit_ac.setter def visit_ac(self, value): self._visit_ac", "o.base = d['base'] if 'data_channel' in d: o.data_channel = d['data_channel'] if 'visit_ac' in", "d: o.visit_ac = d['visit_ac'] if 'visit_biz_line' in d: o.visit_biz_line = d['visit_biz_line'] if 'visit_bu'", "self.action_param.to_alipay_dict() else: params['action_param'] = self.action_param if self.base: if hasattr(self.base, 'to_alipay_dict'): params['base'] = self.base.to_alipay_dict()", "self.base if self.data_channel: if hasattr(self.data_channel, 'to_alipay_dict'): params['data_channel'] = self.data_channel.to_alipay_dict() else: params['data_channel'] = self.data_channel", "coding: utf-8 -*- import json from alipay.aop.api.constant.ParamConstants import * class SsdataDataserviceDatapropertyBatchqueryModel(object): def __init__(self):", "'base' in d: o.base = d['base'] if 'data_channel' in d: o.data_channel = d['data_channel']", "def visit_biz_line(self): return self._visit_biz_line @visit_biz_line.setter def visit_biz_line(self, value): self._visit_biz_line = value @property def", "d: o.data_channel = d['data_channel'] if 'visit_ac' in d: o.visit_ac = d['visit_ac'] if 'visit_biz_line'", "action(self, value): self._action = value @property def action_param(self): return self._action_param @action_param.setter def action_param(self,", "= self.action.to_alipay_dict() else: params['action'] = self.action if self.action_param: if hasattr(self.action_param, 'to_alipay_dict'): params['action_param'] =", "class SsdataDataserviceDatapropertyBatchqueryModel(object): def __init__(self): self._action = None self._action_param = None self._base = None", "d['action'] if 'action_param' in d: o.action_param = d['action_param'] if 'base' in d: o.base", "= self.data_channel if self.visit_ac: if hasattr(self.visit_ac, 'to_alipay_dict'): params['visit_ac'] = self.visit_ac.to_alipay_dict() else: params['visit_ac'] =", "d['data_channel'] if 'visit_ac' in d: o.visit_ac = d['visit_ac'] if 'visit_biz_line' in d: o.visit_biz_line", "@property def action(self): return self._action @action.setter def action(self, value): self._action = value @property", "visit_bu(self): return self._visit_bu @visit_bu.setter def visit_bu(self, value): self._visit_bu = value def to_alipay_dict(self): params", "def visit_bu(self, value): self._visit_bu = value def to_alipay_dict(self): params = dict() if self.action:", "d: o.visit_biz_line = d['visit_biz_line'] if 'visit_bu' in d: o.visit_bu = d['visit_bu'] return o", "params['visit_ac'] = self.visit_ac.to_alipay_dict() else: params['visit_ac'] = self.visit_ac if self.visit_biz_line: if hasattr(self.visit_biz_line, 'to_alipay_dict'): params['visit_biz_line']", "def __init__(self): self._action = None self._action_param = None self._base = None self._data_channel =", "action_param(self): return self._action_param @action_param.setter def action_param(self, value): self._action_param = value @property def base(self):", "to_alipay_dict(self): params = dict() if self.action: if hasattr(self.action, 'to_alipay_dict'): params['action'] = self.action.to_alipay_dict() else:", "'to_alipay_dict'): params['base'] = self.base.to_alipay_dict() else: params['base'] = self.base if self.data_channel: if hasattr(self.data_channel, 'to_alipay_dict'):", "= self.visit_bu.to_alipay_dict() else: params['visit_bu'] = self.visit_bu return params @staticmethod def from_alipay_dict(d): if not", "action(self): return self._action @action.setter def action(self, value): self._action = value @property def action_param(self):", "@action_param.setter def action_param(self, value): self._action_param = value @property def base(self): return self._base @base.setter", "def from_alipay_dict(d): if not d: return None o = SsdataDataserviceDatapropertyBatchqueryModel() if 'action' in", "params['action_param'] = self.action_param if self.base: if hasattr(self.base, 'to_alipay_dict'): params['base'] = self.base.to_alipay_dict() else: params['base']", "import json from alipay.aop.api.constant.ParamConstants import * class SsdataDataserviceDatapropertyBatchqueryModel(object): def __init__(self): self._action = None", "hasattr(self.base, 'to_alipay_dict'): params['base'] = self.base.to_alipay_dict() else: params['base'] = self.base if self.data_channel: if hasattr(self.data_channel,", "visit_ac(self): return self._visit_ac @visit_ac.setter def visit_ac(self, value): self._visit_ac = value @property def visit_biz_line(self):", "= value @property def action_param(self): return self._action_param @action_param.setter def action_param(self, value): self._action_param =", "'action_param' in d: o.action_param = d['action_param'] if 'base' in d: o.base = d['base']", "self._visit_biz_line = value @property def visit_bu(self): return self._visit_bu @visit_bu.setter def visit_bu(self, value): self._visit_bu", "visit_biz_line(self, value): self._visit_biz_line = value @property def visit_bu(self): return self._visit_bu @visit_bu.setter def visit_bu(self,", "if self.visit_ac: if hasattr(self.visit_ac, 'to_alipay_dict'): params['visit_ac'] = self.visit_ac.to_alipay_dict() else: params['visit_ac'] = self.visit_ac if", "self.visit_ac.to_alipay_dict() else: params['visit_ac'] = self.visit_ac if self.visit_biz_line: if hasattr(self.visit_biz_line, 'to_alipay_dict'): params['visit_biz_line'] = self.visit_biz_line.to_alipay_dict()", "in d: o.visit_ac = d['visit_ac'] if 'visit_biz_line' in d: o.visit_biz_line = d['visit_biz_line'] if", "visit_ac(self, value): self._visit_ac = value @property def visit_biz_line(self): return self._visit_biz_line @visit_biz_line.setter def visit_biz_line(self,", "= self.visit_biz_line.to_alipay_dict() else: params['visit_biz_line'] = self.visit_biz_line if self.visit_bu: if hasattr(self.visit_bu, 'to_alipay_dict'): params['visit_bu'] =", "= None @property def action(self): return self._action @action.setter def action(self, value): self._action =", "= None self._action_param = None self._base = None self._data_channel = None self._visit_ac =", "= self.base.to_alipay_dict() else: params['base'] = self.base if self.data_channel: if hasattr(self.data_channel, 'to_alipay_dict'): params['data_channel'] =", "if self.data_channel: if hasattr(self.data_channel, 'to_alipay_dict'): params['data_channel'] = self.data_channel.to_alipay_dict() else: params['data_channel'] = self.data_channel if", "hasattr(self.visit_ac, 'to_alipay_dict'): params['visit_ac'] = self.visit_ac.to_alipay_dict() else: params['visit_ac'] = self.visit_ac if self.visit_biz_line: if hasattr(self.visit_biz_line,", "self.data_channel.to_alipay_dict() else: params['data_channel'] = self.data_channel if self.visit_ac: if hasattr(self.visit_ac, 'to_alipay_dict'): params['visit_ac'] = self.visit_ac.to_alipay_dict()", "if 'visit_biz_line' in d: o.visit_biz_line = d['visit_biz_line'] if 'visit_bu' in d: o.visit_bu =", "= value @property def visit_biz_line(self): return self._visit_biz_line @visit_biz_line.setter def visit_biz_line(self, value): self._visit_biz_line =", "self.visit_bu return params @staticmethod def from_alipay_dict(d): if not d: return None o =", "'to_alipay_dict'): params['visit_bu'] = self.visit_bu.to_alipay_dict() else: params['visit_bu'] = self.visit_bu return params @staticmethod def from_alipay_dict(d):", "in d: o.action_param = d['action_param'] if 'base' in d: o.base = d['base'] if", "return self._visit_bu @visit_bu.setter def visit_bu(self, value): self._visit_bu = value def to_alipay_dict(self): params =", "= self.action if self.action_param: if hasattr(self.action_param, 'to_alipay_dict'): params['action_param'] = self.action_param.to_alipay_dict() else: params['action_param'] =", "params['action'] = self.action.to_alipay_dict() else: params['action'] = self.action if self.action_param: if hasattr(self.action_param, 'to_alipay_dict'): params['action_param']", "self._action = None self._action_param = None self._base = None self._data_channel = None self._visit_ac", "'data_channel' in d: o.data_channel = d['data_channel'] if 'visit_ac' in d: o.visit_ac = d['visit_ac']", "self._visit_ac = None self._visit_biz_line = None self._visit_bu = None @property def action(self): return", "if hasattr(self.data_channel, 'to_alipay_dict'): params['data_channel'] = self.data_channel.to_alipay_dict() else: params['data_channel'] = self.data_channel if self.visit_ac: if", "if not d: return None o = SsdataDataserviceDatapropertyBatchqueryModel() if 'action' in d: o.action", "o.action_param = d['action_param'] if 'base' in d: o.base = d['base'] if 'data_channel' in", "in d: o.base = d['base'] if 'data_channel' in d: o.data_channel = d['data_channel'] if", "return self._base @base.setter def base(self, value): self._base = value @property def data_channel(self): return", "= d['visit_ac'] if 'visit_biz_line' in d: o.visit_biz_line = d['visit_biz_line'] if 'visit_bu' in d:", "utf-8 -*- import json from alipay.aop.api.constant.ParamConstants import * class SsdataDataserviceDatapropertyBatchqueryModel(object): def __init__(self): self._action", "visit_biz_line(self): return self._visit_biz_line @visit_biz_line.setter def visit_biz_line(self, value): self._visit_biz_line = value @property def visit_bu(self):", "o.data_channel = d['data_channel'] if 'visit_ac' in d: o.visit_ac = d['visit_ac'] if 'visit_biz_line' in", "self._visit_bu = value def to_alipay_dict(self): params = dict() if self.action: if hasattr(self.action, 'to_alipay_dict'):", "= None self._visit_biz_line = None self._visit_bu = None @property def action(self): return self._action", "hasattr(self.visit_bu, 'to_alipay_dict'): params['visit_bu'] = self.visit_bu.to_alipay_dict() else: params['visit_bu'] = self.visit_bu return params @staticmethod def", "data_channel(self): return self._data_channel @data_channel.setter def data_channel(self, value): self._data_channel = value @property def visit_ac(self):", "None self._action_param = None self._base = None self._data_channel = None self._visit_ac = None", "= value @property def visit_bu(self): return self._visit_bu @visit_bu.setter def visit_bu(self, value): self._visit_bu =", "value): self._visit_bu = value def to_alipay_dict(self): params = dict() if self.action: if hasattr(self.action,", "params['visit_bu'] = self.visit_bu.to_alipay_dict() else: params['visit_bu'] = self.visit_bu return params @staticmethod def from_alipay_dict(d): if", "def action_param(self, value): self._action_param = value @property def base(self): return self._base @base.setter def", "= None self._base = None self._data_channel = None self._visit_ac = None self._visit_biz_line =", "= value @property def base(self): return self._base @base.setter def base(self, value): self._base =", "self._data_channel = None self._visit_ac = None self._visit_biz_line = None self._visit_bu = None @property", "None self._data_channel = None self._visit_ac = None self._visit_biz_line = None self._visit_bu = None", "@property def visit_bu(self): return self._visit_bu @visit_bu.setter def visit_bu(self, value): self._visit_bu = value def", "self.base: if hasattr(self.base, 'to_alipay_dict'): params['base'] = self.base.to_alipay_dict() else: params['base'] = self.base if self.data_channel:", "self.visit_ac if self.visit_biz_line: if hasattr(self.visit_biz_line, 'to_alipay_dict'): params['visit_biz_line'] = self.visit_biz_line.to_alipay_dict() else: params['visit_biz_line'] = self.visit_biz_line", "self.visit_biz_line: if hasattr(self.visit_biz_line, 'to_alipay_dict'): params['visit_biz_line'] = self.visit_biz_line.to_alipay_dict() else: params['visit_biz_line'] = self.visit_biz_line if self.visit_bu:", "return self._action @action.setter def action(self, value): self._action = value @property def action_param(self): return", "if self.visit_bu: if hasattr(self.visit_bu, 'to_alipay_dict'): params['visit_bu'] = self.visit_bu.to_alipay_dict() else: params['visit_bu'] = self.visit_bu return", "def data_channel(self): return self._data_channel @data_channel.setter def data_channel(self, value): self._data_channel = value @property def", "@property def action_param(self): return self._action_param @action_param.setter def action_param(self, value): self._action_param = value @property", "= value def to_alipay_dict(self): params = dict() if self.action: if hasattr(self.action, 'to_alipay_dict'): params['action']", "hasattr(self.visit_biz_line, 'to_alipay_dict'): params['visit_biz_line'] = self.visit_biz_line.to_alipay_dict() else: params['visit_biz_line'] = self.visit_biz_line if self.visit_bu: if hasattr(self.visit_bu,", "'action' in d: o.action = d['action'] if 'action_param' in d: o.action_param = d['action_param']", "self._base @base.setter def base(self, value): self._base = value @property def data_channel(self): return self._data_channel", "* class SsdataDataserviceDatapropertyBatchqueryModel(object): def __init__(self): self._action = None self._action_param = None self._base =", "= None self._visit_ac = None self._visit_biz_line = None self._visit_bu = None @property def", "self.action if self.action_param: if hasattr(self.action_param, 'to_alipay_dict'): params['action_param'] = self.action_param.to_alipay_dict() else: params['action_param'] = self.action_param", "o.action = d['action'] if 'action_param' in d: o.action_param = d['action_param'] if 'base' in", "if 'data_channel' in d: o.data_channel = d['data_channel'] if 'visit_ac' in d: o.visit_ac =", "else: params['data_channel'] = self.data_channel if self.visit_ac: if hasattr(self.visit_ac, 'to_alipay_dict'): params['visit_ac'] = self.visit_ac.to_alipay_dict() else:", "self.action: if hasattr(self.action, 'to_alipay_dict'): params['action'] = self.action.to_alipay_dict() else: params['action'] = self.action if self.action_param:", "= None self._data_channel = None self._visit_ac = None self._visit_biz_line = None self._visit_bu =", "def base(self): return self._base @base.setter def base(self, value): self._base = value @property def", "if hasattr(self.visit_bu, 'to_alipay_dict'): params['visit_bu'] = self.visit_bu.to_alipay_dict() else: params['visit_bu'] = self.visit_bu return params @staticmethod", "self.data_channel if self.visit_ac: if hasattr(self.visit_ac, 'to_alipay_dict'): params['visit_ac'] = self.visit_ac.to_alipay_dict() else: params['visit_ac'] = self.visit_ac", "= d['base'] if 'data_channel' in d: o.data_channel = d['data_channel'] if 'visit_ac' in d:", "hasattr(self.action_param, 'to_alipay_dict'): params['action_param'] = self.action_param.to_alipay_dict() else: params['action_param'] = self.action_param if self.base: if hasattr(self.base,", "@property def base(self): return self._base @base.setter def base(self, value): self._base = value @property", "else: params['action_param'] = self.action_param if self.base: if hasattr(self.base, 'to_alipay_dict'): params['base'] = self.base.to_alipay_dict() else:", "None self._visit_bu = None @property def action(self): return self._action @action.setter def action(self, value):", "= d['action_param'] if 'base' in d: o.base = d['base'] if 'data_channel' in d:", "def action(self, value): self._action = value @property def action_param(self): return self._action_param @action_param.setter def", "= self.base if self.data_channel: if hasattr(self.data_channel, 'to_alipay_dict'): params['data_channel'] = self.data_channel.to_alipay_dict() else: params['data_channel'] =", "params['visit_biz_line'] = self.visit_biz_line if self.visit_bu: if hasattr(self.visit_bu, 'to_alipay_dict'): params['visit_bu'] = self.visit_bu.to_alipay_dict() else: params['visit_bu']", "from_alipay_dict(d): if not d: return None o = SsdataDataserviceDatapropertyBatchqueryModel() if 'action' in d:", "@action.setter def action(self, value): self._action = value @property def action_param(self): return self._action_param @action_param.setter", "d['base'] if 'data_channel' in d: o.data_channel = d['data_channel'] if 'visit_ac' in d: o.visit_ac", "= self.action_param.to_alipay_dict() else: params['action_param'] = self.action_param if self.base: if hasattr(self.base, 'to_alipay_dict'): params['base'] =", "= dict() if self.action: if hasattr(self.action, 'to_alipay_dict'): params['action'] = self.action.to_alipay_dict() else: params['action'] =", "self._visit_ac @visit_ac.setter def visit_ac(self, value): self._visit_ac = value @property def visit_biz_line(self): return self._visit_biz_line", "d['action_param'] if 'base' in d: o.base = d['base'] if 'data_channel' in d: o.data_channel", "not d: return None o = SsdataDataserviceDatapropertyBatchqueryModel() if 'action' in d: o.action =", "o = SsdataDataserviceDatapropertyBatchqueryModel() if 'action' in d: o.action = d['action'] if 'action_param' in", "if self.visit_biz_line: if hasattr(self.visit_biz_line, 'to_alipay_dict'): params['visit_biz_line'] = self.visit_biz_line.to_alipay_dict() else: params['visit_biz_line'] = self.visit_biz_line if", "alipay.aop.api.constant.ParamConstants import * class SsdataDataserviceDatapropertyBatchqueryModel(object): def __init__(self): self._action = None self._action_param = None", "self._data_channel @data_channel.setter def data_channel(self, value): self._data_channel = value @property def visit_ac(self): return self._visit_ac", "d['visit_ac'] if 'visit_biz_line' in d: o.visit_biz_line = d['visit_biz_line'] if 'visit_bu' in d: o.visit_bu", "d: o.base = d['base'] if 'data_channel' in d: o.data_channel = d['data_channel'] if 'visit_ac'", "@property def data_channel(self): return self._data_channel @data_channel.setter def data_channel(self, value): self._data_channel = value @property", "return params @staticmethod def from_alipay_dict(d): if not d: return None o = SsdataDataserviceDatapropertyBatchqueryModel()", "def base(self, value): self._base = value @property def data_channel(self): return self._data_channel @data_channel.setter def", "in d: o.action = d['action'] if 'action_param' in d: o.action_param = d['action_param'] if", "= self.visit_bu return params @staticmethod def from_alipay_dict(d): if not d: return None o", "def data_channel(self, value): self._data_channel = value @property def visit_ac(self): return self._visit_ac @visit_ac.setter def", "None self._visit_biz_line = None self._visit_bu = None @property def action(self): return self._action @action.setter", "@property def visit_ac(self): return self._visit_ac @visit_ac.setter def visit_ac(self, value): self._visit_ac = value @property", "self._visit_biz_line = None self._visit_bu = None @property def action(self): return self._action @action.setter def", "if self.action_param: if hasattr(self.action_param, 'to_alipay_dict'): params['action_param'] = self.action_param.to_alipay_dict() else: params['action_param'] = self.action_param if", "self.data_channel: if hasattr(self.data_channel, 'to_alipay_dict'): params['data_channel'] = self.data_channel.to_alipay_dict() else: params['data_channel'] = self.data_channel if self.visit_ac:", "self.action_param: if hasattr(self.action_param, 'to_alipay_dict'): params['action_param'] = self.action_param.to_alipay_dict() else: params['action_param'] = self.action_param if self.base:", "base(self, value): self._base = value @property def data_channel(self): return self._data_channel @data_channel.setter def data_channel(self,", "dict() if self.action: if hasattr(self.action, 'to_alipay_dict'): params['action'] = self.action.to_alipay_dict() else: params['action'] = self.action", "hasattr(self.action, 'to_alipay_dict'): params['action'] = self.action.to_alipay_dict() else: params['action'] = self.action if self.action_param: if hasattr(self.action_param,", "if hasattr(self.visit_ac, 'to_alipay_dict'): params['visit_ac'] = self.visit_ac.to_alipay_dict() else: params['visit_ac'] = self.visit_ac if self.visit_biz_line: if", "#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.constant.ParamConstants import *", "self._action_param = value @property def base(self): return self._base @base.setter def base(self, value): self._base", "self._action_param @action_param.setter def action_param(self, value): self._action_param = value @property def base(self): return self._base", "= self.visit_ac if self.visit_biz_line: if hasattr(self.visit_biz_line, 'to_alipay_dict'): params['visit_biz_line'] = self.visit_biz_line.to_alipay_dict() else: params['visit_biz_line'] =", "else: params['visit_biz_line'] = self.visit_biz_line if self.visit_bu: if hasattr(self.visit_bu, 'to_alipay_dict'): params['visit_bu'] = self.visit_bu.to_alipay_dict() else:", "= d['action'] if 'action_param' in d: o.action_param = d['action_param'] if 'base' in d:", "@visit_bu.setter def visit_bu(self, value): self._visit_bu = value def to_alipay_dict(self): params = dict() if", "if 'action_param' in d: o.action_param = d['action_param'] if 'base' in d: o.base =", "data_channel(self, value): self._data_channel = value @property def visit_ac(self): return self._visit_ac @visit_ac.setter def visit_ac(self,", "SsdataDataserviceDatapropertyBatchqueryModel() if 'action' in d: o.action = d['action'] if 'action_param' in d: o.action_param", "-*- import json from alipay.aop.api.constant.ParamConstants import * class SsdataDataserviceDatapropertyBatchqueryModel(object): def __init__(self): self._action =", "'visit_biz_line' in d: o.visit_biz_line = d['visit_biz_line'] if 'visit_bu' in d: o.visit_bu = d['visit_bu']", "'to_alipay_dict'): params['action_param'] = self.action_param.to_alipay_dict() else: params['action_param'] = self.action_param if self.base: if hasattr(self.base, 'to_alipay_dict'):", "hasattr(self.data_channel, 'to_alipay_dict'): params['data_channel'] = self.data_channel.to_alipay_dict() else: params['data_channel'] = self.data_channel if self.visit_ac: if hasattr(self.visit_ac,", "if hasattr(self.visit_biz_line, 'to_alipay_dict'): params['visit_biz_line'] = self.visit_biz_line.to_alipay_dict() else: params['visit_biz_line'] = self.visit_biz_line if self.visit_bu: if", "if 'visit_ac' in d: o.visit_ac = d['visit_ac'] if 'visit_biz_line' in d: o.visit_biz_line =", "d: o.action_param = d['action_param'] if 'base' in d: o.base = d['base'] if 'data_channel'", "from alipay.aop.api.constant.ParamConstants import * class SsdataDataserviceDatapropertyBatchqueryModel(object): def __init__(self): self._action = None self._action_param =", "= self.visit_biz_line if self.visit_bu: if hasattr(self.visit_bu, 'to_alipay_dict'): params['visit_bu'] = self.visit_bu.to_alipay_dict() else: params['visit_bu'] =", "self.visit_bu: if hasattr(self.visit_bu, 'to_alipay_dict'): params['visit_bu'] = self.visit_bu.to_alipay_dict() else: params['visit_bu'] = self.visit_bu return params", "# -*- coding: utf-8 -*- import json from alipay.aop.api.constant.ParamConstants import * class SsdataDataserviceDatapropertyBatchqueryModel(object):", "params @staticmethod def from_alipay_dict(d): if not d: return None o = SsdataDataserviceDatapropertyBatchqueryModel() if", "params['base'] = self.base.to_alipay_dict() else: params['base'] = self.base if self.data_channel: if hasattr(self.data_channel, 'to_alipay_dict'): params['data_channel']", "'visit_ac' in d: o.visit_ac = d['visit_ac'] if 'visit_biz_line' in d: o.visit_biz_line = d['visit_biz_line']", "SsdataDataserviceDatapropertyBatchqueryModel(object): def __init__(self): self._action = None self._action_param = None self._base = None self._data_channel", "return self._data_channel @data_channel.setter def data_channel(self, value): self._data_channel = value @property def visit_ac(self): return", "= value @property def visit_ac(self): return self._visit_ac @visit_ac.setter def visit_ac(self, value): self._visit_ac =", "self._visit_ac = value @property def visit_biz_line(self): return self._visit_biz_line @visit_biz_line.setter def visit_biz_line(self, value): self._visit_biz_line", "action_param(self, value): self._action_param = value @property def base(self): return self._base @base.setter def base(self,", "self.visit_biz_line.to_alipay_dict() else: params['visit_biz_line'] = self.visit_biz_line if self.visit_bu: if hasattr(self.visit_bu, 'to_alipay_dict'): params['visit_bu'] = self.visit_bu.to_alipay_dict()", "self._action = value @property def action_param(self): return self._action_param @action_param.setter def action_param(self, value): self._action_param", "self._visit_biz_line @visit_biz_line.setter def visit_biz_line(self, value): self._visit_biz_line = value @property def visit_bu(self): return self._visit_bu", "visit_bu(self, value): self._visit_bu = value def to_alipay_dict(self): params = dict() if self.action: if", "json from alipay.aop.api.constant.ParamConstants import * class SsdataDataserviceDatapropertyBatchqueryModel(object): def __init__(self): self._action = None self._action_param", "-*- coding: utf-8 -*- import json from alipay.aop.api.constant.ParamConstants import * class SsdataDataserviceDatapropertyBatchqueryModel(object): def", "self._base = None self._data_channel = None self._visit_ac = None self._visit_biz_line = None self._visit_bu", "= self.data_channel.to_alipay_dict() else: params['data_channel'] = self.data_channel if self.visit_ac: if hasattr(self.visit_ac, 'to_alipay_dict'): params['visit_ac'] =", "params['data_channel'] = self.data_channel if self.visit_ac: if hasattr(self.visit_ac, 'to_alipay_dict'): params['visit_ac'] = self.visit_ac.to_alipay_dict() else: params['visit_ac']", "value @property def visit_biz_line(self): return self._visit_biz_line @visit_biz_line.setter def visit_biz_line(self, value): self._visit_biz_line = value", "return self._action_param @action_param.setter def action_param(self, value): self._action_param = value @property def base(self): return", "'to_alipay_dict'): params['action'] = self.action.to_alipay_dict() else: params['action'] = self.action if self.action_param: if hasattr(self.action_param, 'to_alipay_dict'):", "if hasattr(self.action_param, 'to_alipay_dict'): params['action_param'] = self.action_param.to_alipay_dict() else: params['action_param'] = self.action_param if self.base: if", "'to_alipay_dict'): params['visit_ac'] = self.visit_ac.to_alipay_dict() else: params['visit_ac'] = self.visit_ac if self.visit_biz_line: if hasattr(self.visit_biz_line, 'to_alipay_dict'):", "value @property def visit_ac(self): return self._visit_ac @visit_ac.setter def visit_ac(self, value): self._visit_ac = value", "value @property def base(self): return self._base @base.setter def base(self, value): self._base = value", "params['action'] = self.action if self.action_param: if hasattr(self.action_param, 'to_alipay_dict'): params['action_param'] = self.action_param.to_alipay_dict() else: params['action_param']", "'to_alipay_dict'): params['visit_biz_line'] = self.visit_biz_line.to_alipay_dict() else: params['visit_biz_line'] = self.visit_biz_line if self.visit_bu: if hasattr(self.visit_bu, 'to_alipay_dict'):", "= d['data_channel'] if 'visit_ac' in d: o.visit_ac = d['visit_ac'] if 'visit_biz_line' in d:", "__init__(self): self._action = None self._action_param = None self._base = None self._data_channel = None", "o.visit_ac = d['visit_ac'] if 'visit_biz_line' in d: o.visit_biz_line = d['visit_biz_line'] if 'visit_bu' in", "if 'base' in d: o.base = d['base'] if 'data_channel' in d: o.data_channel =", "params = dict() if self.action: if hasattr(self.action, 'to_alipay_dict'): params['action'] = self.action.to_alipay_dict() else: params['action']", "value @property def data_channel(self): return self._data_channel @data_channel.setter def data_channel(self, value): self._data_channel = value", "= self.visit_ac.to_alipay_dict() else: params['visit_ac'] = self.visit_ac if self.visit_biz_line: if hasattr(self.visit_biz_line, 'to_alipay_dict'): params['visit_biz_line'] =", "@visit_biz_line.setter def visit_biz_line(self, value): self._visit_biz_line = value @property def visit_bu(self): return self._visit_bu @visit_bu.setter", "return None o = SsdataDataserviceDatapropertyBatchqueryModel() if 'action' in d: o.action = d['action'] if", "if self.base: if hasattr(self.base, 'to_alipay_dict'): params['base'] = self.base.to_alipay_dict() else: params['base'] = self.base if", "params['data_channel'] = self.data_channel.to_alipay_dict() else: params['data_channel'] = self.data_channel if self.visit_ac: if hasattr(self.visit_ac, 'to_alipay_dict'): params['visit_ac']", "None self._visit_ac = None self._visit_biz_line = None self._visit_bu = None @property def action(self):", "self._action @action.setter def action(self, value): self._action = value @property def action_param(self): return self._action_param", "self.action_param if self.base: if hasattr(self.base, 'to_alipay_dict'): params['base'] = self.base.to_alipay_dict() else: params['base'] = self.base", "None self._base = None self._data_channel = None self._visit_ac = None self._visit_biz_line = None", "d: o.action = d['action'] if 'action_param' in d: o.action_param = d['action_param'] if 'base'", "return self._visit_ac @visit_ac.setter def visit_ac(self, value): self._visit_ac = value @property def visit_biz_line(self): return", "value @property def action_param(self): return self._action_param @action_param.setter def action_param(self, value): self._action_param = value", "def to_alipay_dict(self): params = dict() if self.action: if hasattr(self.action, 'to_alipay_dict'): params['action'] = self.action.to_alipay_dict()", "value): self._action_param = value @property def base(self): return self._base @base.setter def base(self, value):", "params['action_param'] = self.action_param.to_alipay_dict() else: params['action_param'] = self.action_param if self.base: if hasattr(self.base, 'to_alipay_dict'): params['base']", "else: params['visit_bu'] = self.visit_bu return params @staticmethod def from_alipay_dict(d): if not d: return", "def visit_bu(self): return self._visit_bu @visit_bu.setter def visit_bu(self, value): self._visit_bu = value def to_alipay_dict(self):", "= SsdataDataserviceDatapropertyBatchqueryModel() if 'action' in d: o.action = d['action'] if 'action_param' in d:", "in d: o.visit_biz_line = d['visit_biz_line'] if 'visit_bu' in d: o.visit_bu = d['visit_bu'] return", "value): self._action = value @property def action_param(self): return self._action_param @action_param.setter def action_param(self, value):", "self._base = value @property def data_channel(self): return self._data_channel @data_channel.setter def data_channel(self, value): self._data_channel", "value): self._visit_ac = value @property def visit_biz_line(self): return self._visit_biz_line @visit_biz_line.setter def visit_biz_line(self, value):", "def visit_biz_line(self, value): self._visit_biz_line = value @property def visit_bu(self): return self._visit_bu @visit_bu.setter def", "if 'action' in d: o.action = d['action'] if 'action_param' in d: o.action_param =", "self.action.to_alipay_dict() else: params['action'] = self.action if self.action_param: if hasattr(self.action_param, 'to_alipay_dict'): params['action_param'] = self.action_param.to_alipay_dict()", "import * class SsdataDataserviceDatapropertyBatchqueryModel(object): def __init__(self): self._action = None self._action_param = None self._base", "= None self._visit_bu = None @property def action(self): return self._action @action.setter def action(self,", "value @property def visit_bu(self): return self._visit_bu @visit_bu.setter def visit_bu(self, value): self._visit_bu = value", "else: params['visit_ac'] = self.visit_ac if self.visit_biz_line: if hasattr(self.visit_biz_line, 'to_alipay_dict'): params['visit_biz_line'] = self.visit_biz_line.to_alipay_dict() else:", "params['visit_biz_line'] = self.visit_biz_line.to_alipay_dict() else: params['visit_biz_line'] = self.visit_biz_line if self.visit_bu: if hasattr(self.visit_bu, 'to_alipay_dict'): params['visit_bu']", "None o = SsdataDataserviceDatapropertyBatchqueryModel() if 'action' in d: o.action = d['action'] if 'action_param'", "@base.setter def base(self, value): self._base = value @property def data_channel(self): return self._data_channel @data_channel.setter", "self._visit_bu @visit_bu.setter def visit_bu(self, value): self._visit_bu = value def to_alipay_dict(self): params = dict()", "base(self): return self._base @base.setter def base(self, value): self._base = value @property def data_channel(self):", "else: params['base'] = self.base if self.data_channel: if hasattr(self.data_channel, 'to_alipay_dict'): params['data_channel'] = self.data_channel.to_alipay_dict() else:", "return self._visit_biz_line @visit_biz_line.setter def visit_biz_line(self, value): self._visit_biz_line = value @property def visit_bu(self): return", "self.visit_bu.to_alipay_dict() else: params['visit_bu'] = self.visit_bu return params @staticmethod def from_alipay_dict(d): if not d:", "in d: o.data_channel = d['data_channel'] if 'visit_ac' in d: o.visit_ac = d['visit_ac'] if", "if hasattr(self.base, 'to_alipay_dict'): params['base'] = self.base.to_alipay_dict() else: params['base'] = self.base if self.data_channel: if", "self._action_param = None self._base = None self._data_channel = None self._visit_ac = None self._visit_biz_line", "if hasattr(self.action, 'to_alipay_dict'): params['action'] = self.action.to_alipay_dict() else: params['action'] = self.action if self.action_param: if", "params['visit_ac'] = self.visit_ac if self.visit_biz_line: if hasattr(self.visit_biz_line, 'to_alipay_dict'): params['visit_biz_line'] = self.visit_biz_line.to_alipay_dict() else: params['visit_biz_line']" ]
[ "import Final from .freqanalysis import FreqAnalysisWidget from .index_of_coincidence import ICWidget from .autocorrelation import", "from .autocorrelation import AutocorrelationWidget from .kasiski import KasiskiWidget WIDGETS_CRYPTOTOOLS: Final = ( FreqAnalysisWidget,", "from .index_of_coincidence import ICWidget from .autocorrelation import AutocorrelationWidget from .kasiski import KasiskiWidget WIDGETS_CRYPTOTOOLS:", "from .kasiski import KasiskiWidget WIDGETS_CRYPTOTOOLS: Final = ( FreqAnalysisWidget, ICWidget, AutocorrelationWidget, KasiskiWidget )", "import ICWidget from .autocorrelation import AutocorrelationWidget from .kasiski import KasiskiWidget WIDGETS_CRYPTOTOOLS: Final =", "AutocorrelationWidget from .kasiski import KasiskiWidget WIDGETS_CRYPTOTOOLS: Final = ( FreqAnalysisWidget, ICWidget, AutocorrelationWidget, KasiskiWidget", "import AutocorrelationWidget from .kasiski import KasiskiWidget WIDGETS_CRYPTOTOOLS: Final = ( FreqAnalysisWidget, ICWidget, AutocorrelationWidget,", ".index_of_coincidence import ICWidget from .autocorrelation import AutocorrelationWidget from .kasiski import KasiskiWidget WIDGETS_CRYPTOTOOLS: Final", "from typing import Final from .freqanalysis import FreqAnalysisWidget from .index_of_coincidence import ICWidget from", ".freqanalysis import FreqAnalysisWidget from .index_of_coincidence import ICWidget from .autocorrelation import AutocorrelationWidget from .kasiski", "typing import Final from .freqanalysis import FreqAnalysisWidget from .index_of_coincidence import ICWidget from .autocorrelation", "ICWidget from .autocorrelation import AutocorrelationWidget from .kasiski import KasiskiWidget WIDGETS_CRYPTOTOOLS: Final = (", ".autocorrelation import AutocorrelationWidget from .kasiski import KasiskiWidget WIDGETS_CRYPTOTOOLS: Final = ( FreqAnalysisWidget, ICWidget,", "from .freqanalysis import FreqAnalysisWidget from .index_of_coincidence import ICWidget from .autocorrelation import AutocorrelationWidget from", "FreqAnalysisWidget from .index_of_coincidence import ICWidget from .autocorrelation import AutocorrelationWidget from .kasiski import KasiskiWidget", "Final from .freqanalysis import FreqAnalysisWidget from .index_of_coincidence import ICWidget from .autocorrelation import AutocorrelationWidget", "import FreqAnalysisWidget from .index_of_coincidence import ICWidget from .autocorrelation import AutocorrelationWidget from .kasiski import" ]
[ "\"artist\": \"Immortal_\", \"album\": \"Sons Of Northern Darkness\" }, { \"title\": \"Sons Of Northern", "sys.argv: from nopea.adaptors.postgres import PostgreSQLAdaptor DbObject.adaptor = PostgreSQLAdaptor({ 'host': 'localhost', 'user': 'sqless', 'database':", "= [ {\"username\": \"TestUser1\", \"email\": \"<EMAIL>\"}, {\"username\": \"TestUser2\", \"email\": \"<EMAIL>\"}, {\"username\": \"TestUser3\", \"email\":", "import DbObject from nopea import fields from nopea.migrations import Migration if 'sqlite' in", "\"title\": \"Ghost Love Score\", \"artist\": \"Nightwish\", \"album\": \"Decades\" }, { \"title\": \"Devil And", "migrations.run_migrations() users = [ {\"username\": \"TestUser1\", \"email\": \"<EMAIL>\"}, {\"username\": \"TestUser2\", \"email\": \"<EMAIL>\"}, {\"username\":", "Northern Darkness\", \"artist\": \"Immortal_\", \"album\": \"Sons Of Northern Darkness\" } ] for song", "\"content\": \"Lorem Ipsum Dolor Sit\"}, {\"title\": \"SomeOtherStuff\", \"content\": \"hello, world!\"}, ] for post", "\"Decades\" }, { \"title\": \"Devil And The Deep Dark Ocean\", \"artist\": \"Nightwish\", \"album\":", "os import sys from nopea.dbobject import DbObject from nopea import fields from nopea.migrations", "'database': 'sqless', 'password': '<PASSWORD>' }) class User(DbObject): username = fields.CharField(max_length=20) email = fields.CharField(max_length=100)", "in sys.argv: from nopea.adaptors.mysql import MySQLAdaptor DbObject.adaptor = MySQLAdaptor({ 'host': 'localhost', 'user': 'sqless',", "import MySQLAdaptor DbObject.adaptor = MySQLAdaptor({ 'host': 'localhost', 'user': 'sqless', 'db': 'sqless', 'use_unicode': True,", "12} ] for user in users: User.objects.get_or_create(**user) posts = [ {\"title\": \"TestPosting\", \"content\":", "= SQLiteAdaptor('sqless.db') elif 'mysql' in sys.argv: from nopea.adaptors.mysql import MySQLAdaptor DbObject.adaptor = MySQLAdaptor({", "posts: Post.objects.get_or_create(**post) songs = [ { \"title\": \"Love Like Cyanide\", \"artist\": \"Sirenia\", \"album\":", "DbObject.adaptor = MySQLAdaptor({ 'host': 'localhost', 'user': 'sqless', 'db': 'sqless', 'use_unicode': True, 'charset': 'utf8'", "True, 'charset': 'utf8' }) elif 'postgres' in sys.argv: from nopea.adaptors.postgres import PostgreSQLAdaptor DbObject.adaptor", "Post(DbObject): title = fields.CharField(max_length=100) content = fields.TextField() class Song(DbObject): title = fields.CharField(max_length=100) artist", "for post in posts: Post.objects.get_or_create(**post) songs = [ { \"title\": \"Love Like Cyanide\",", "migrations = Migration() migrations.create_migrations() migrations.run_migrations() users = [ {\"username\": \"TestUser1\", \"email\": \"<EMAIL>\"}, {\"username\":", "\"Nightwish\", \"album\": \"Decades\" }, { \"title\": \"One By One\", \"artist\": \"Immortal_\", \"album\": \"Sons", "\"email\": \"<EMAIL>\"}, {\"username\": \"TestUser2\", \"email\": \"<EMAIL>\"}, {\"username\": \"TestUser3\", \"email\": \"<EMAIL>\", \"failed_logins\": 12} ]", "initialize the models and migrations import os import sys from nopea.dbobject import DbObject", "models and migrations import os import sys from nopea.dbobject import DbObject from nopea", "User.objects.get_or_create(**user) posts = [ {\"title\": \"TestPosting\", \"content\": \"Lorem Ipsum Dolor Sit\"}, {\"title\": \"SomeOtherStuff\",", "posts = [ {\"title\": \"TestPosting\", \"content\": \"Lorem Ipsum Dolor Sit\"}, {\"title\": \"SomeOtherStuff\", \"content\":", "{\"title\": \"TestPosting\", \"content\": \"Lorem Ipsum Dolor Sit\"}, {\"title\": \"SomeOtherStuff\", \"content\": \"hello, world!\"}, ]", "the models and migrations import os import sys from nopea.dbobject import DbObject from", "{\"username\": \"TestUser1\", \"email\": \"<EMAIL>\"}, {\"username\": \"TestUser2\", \"email\": \"<EMAIL>\"}, {\"username\": \"TestUser3\", \"email\": \"<EMAIL>\", \"failed_logins\":", "username = fields.CharField(max_length=20) email = fields.CharField(max_length=100) failed_logins = fields.IntegerField(default=0) class Post(DbObject): title =", "\"title\": \"Love Like Cyanide\", \"artist\": \"Sirenia\", \"album\": \"Arcane Astral Aeons\" }, { \"title\":", "{\"username\": \"TestUser2\", \"email\": \"<EMAIL>\"}, {\"username\": \"TestUser3\", \"email\": \"<EMAIL>\", \"failed_logins\": 12} ] for user", "[ {\"username\": \"TestUser1\", \"email\": \"<EMAIL>\"}, {\"username\": \"TestUser2\", \"email\": \"<EMAIL>\"}, {\"username\": \"TestUser3\", \"email\": \"<EMAIL>\",", "nopea.adaptors.mysql import MySQLAdaptor DbObject.adaptor = MySQLAdaptor({ 'host': 'localhost', 'user': 'sqless', 'db': 'sqless', 'use_unicode':", "artist = fields.CharField(max_length=100) album = fields.CharField(max_length=100) in_collection = fields.BooleanField(default=False) Migration.migration_dir = os.path.join(os.getcwd(), 'utils/migrations')", "fields.CharField(max_length=20) email = fields.CharField(max_length=100) failed_logins = fields.IntegerField(default=0) class Post(DbObject): title = fields.CharField(max_length=100) content", "{ \"title\": \"One By One\", \"artist\": \"Immortal_\", \"album\": \"Sons Of Northern Darkness\" },", "And The Deep Dark Ocean\", \"artist\": \"Nightwish\", \"album\": \"Decades\" }, { \"title\": \"One", "elif 'postgres' in sys.argv: from nopea.adaptors.postgres import PostgreSQLAdaptor DbObject.adaptor = PostgreSQLAdaptor({ 'host': 'localhost',", "to initialize the models and migrations import os import sys from nopea.dbobject import", "}) class User(DbObject): username = fields.CharField(max_length=20) email = fields.CharField(max_length=100) failed_logins = fields.IntegerField(default=0) class", "# This file is needed to initialize the models and migrations import os", "This file is needed to initialize the models and migrations import os import", "The Deep Dark Ocean\", \"artist\": \"Nightwish\", \"album\": \"Decades\" }, { \"title\": \"One By", "'sqless', 'password': '<PASSWORD>' }) class User(DbObject): username = fields.CharField(max_length=20) email = fields.CharField(max_length=100) failed_logins", "}, { \"title\": \"Ghost Love Score\", \"artist\": \"Nightwish\", \"album\": \"Decades\" }, { \"title\":", "MySQLAdaptor DbObject.adaptor = MySQLAdaptor({ 'host': 'localhost', 'user': 'sqless', 'db': 'sqless', 'use_unicode': True, 'charset':", "'charset': 'utf8' }) elif 'postgres' in sys.argv: from nopea.adaptors.postgres import PostgreSQLAdaptor DbObject.adaptor =", "\"<EMAIL>\"}, {\"username\": \"TestUser3\", \"email\": \"<EMAIL>\", \"failed_logins\": 12} ] for user in users: User.objects.get_or_create(**user)", "= [ { \"title\": \"Love Like Cyanide\", \"artist\": \"Sirenia\", \"album\": \"Arcane Astral Aeons\"", "\"title\": \"Sons Of Northern Darkness\", \"artist\": \"Immortal_\", \"album\": \"Sons Of Northern Darkness\" }", "'sqless', 'db': 'sqless', 'use_unicode': True, 'charset': 'utf8' }) elif 'postgres' in sys.argv: from", "from nopea.dbobject import DbObject from nopea import fields from nopea.migrations import Migration if", "}) elif 'postgres' in sys.argv: from nopea.adaptors.postgres import PostgreSQLAdaptor DbObject.adaptor = PostgreSQLAdaptor({ 'host':", "file is needed to initialize the models and migrations import os import sys", "songs = [ { \"title\": \"Love Like Cyanide\", \"artist\": \"Sirenia\", \"album\": \"Arcane Astral", "\"The Greatest Show On Earth\", \"artist\": \"Nightwish\", \"album\": \"Decades\" }, { \"title\": \"Ghost", "Migration() migrations.create_migrations() migrations.run_migrations() users = [ {\"username\": \"TestUser1\", \"email\": \"<EMAIL>\"}, {\"username\": \"TestUser2\", \"email\":", "'user': 'sqless', 'database': 'sqless', 'password': '<PASSWORD>' }) class User(DbObject): username = fields.CharField(max_length=20) email", "= fields.IntegerField(default=0) class Post(DbObject): title = fields.CharField(max_length=100) content = fields.TextField() class Song(DbObject): title", "DbObject from nopea import fields from nopea.migrations import Migration if 'sqlite' in sys.argv:", "\"One By One\", \"artist\": \"Immortal_\", \"album\": \"Sons Of Northern Darkness\" }, { \"title\":", "Greatest Show On Earth\", \"artist\": \"Nightwish\", \"album\": \"Decades\" }, { \"title\": \"Ghost Love", "fields.CharField(max_length=100) failed_logins = fields.IntegerField(default=0) class Post(DbObject): title = fields.CharField(max_length=100) content = fields.TextField() class", "\"hello, world!\"}, ] for post in posts: Post.objects.get_or_create(**post) songs = [ { \"title\":", "= os.path.join(os.getcwd(), 'utils/migrations') migrations = Migration() migrations.create_migrations() migrations.run_migrations() users = [ {\"username\": \"TestUser1\",", "{ \"title\": \"Love Like Cyanide\", \"artist\": \"Sirenia\", \"album\": \"Arcane Astral Aeons\" }, {", "sys from nopea.dbobject import DbObject from nopea import fields from nopea.migrations import Migration", "fields.CharField(max_length=100) album = fields.CharField(max_length=100) in_collection = fields.BooleanField(default=False) Migration.migration_dir = os.path.join(os.getcwd(), 'utils/migrations') migrations =", "= fields.CharField(max_length=100) in_collection = fields.BooleanField(default=False) Migration.migration_dir = os.path.join(os.getcwd(), 'utils/migrations') migrations = Migration() migrations.create_migrations()", "\"artist\": \"Nightwish\", \"album\": \"Decades\" }, { \"title\": \"One By One\", \"artist\": \"Immortal_\", \"album\":", "{ \"title\": \"Sons Of Northern Darkness\", \"artist\": \"Immortal_\", \"album\": \"Sons Of Northern Darkness\"", "from nopea import fields from nopea.migrations import Migration if 'sqlite' in sys.argv: from", "import sys from nopea.dbobject import DbObject from nopea import fields from nopea.migrations import", "in sys.argv: from nopea.adaptors.sqlite import SQLiteAdaptor DbObject.adaptor = SQLiteAdaptor('sqless.db') elif 'mysql' in sys.argv:", "in posts: Post.objects.get_or_create(**post) songs = [ { \"title\": \"Love Like Cyanide\", \"artist\": \"Sirenia\",", "import fields from nopea.migrations import Migration if 'sqlite' in sys.argv: from nopea.adaptors.sqlite import", "User(DbObject): username = fields.CharField(max_length=20) email = fields.CharField(max_length=100) failed_logins = fields.IntegerField(default=0) class Post(DbObject): title", "}, { \"title\": \"One By One\", \"artist\": \"Immortal_\", \"album\": \"Sons Of Northern Darkness\"", "\"TestUser1\", \"email\": \"<EMAIL>\"}, {\"username\": \"TestUser2\", \"email\": \"<EMAIL>\"}, {\"username\": \"TestUser3\", \"email\": \"<EMAIL>\", \"failed_logins\": 12}", "\"album\": \"Arcane Astral Aeons\" }, { \"title\": \"The Greatest Show On Earth\", \"artist\":", "= fields.TextField() class Song(DbObject): title = fields.CharField(max_length=100) artist = fields.CharField(max_length=100) album = fields.CharField(max_length=100)", "= Migration() migrations.create_migrations() migrations.run_migrations() users = [ {\"username\": \"TestUser1\", \"email\": \"<EMAIL>\"}, {\"username\": \"TestUser2\",", "\"Sirenia\", \"album\": \"Arcane Astral Aeons\" }, { \"title\": \"The Greatest Show On Earth\",", "= fields.CharField(max_length=100) artist = fields.CharField(max_length=100) album = fields.CharField(max_length=100) in_collection = fields.BooleanField(default=False) Migration.migration_dir =", "Cyanide\", \"artist\": \"Sirenia\", \"album\": \"Arcane Astral Aeons\" }, { \"title\": \"The Greatest Show", "Score\", \"artist\": \"Nightwish\", \"album\": \"Decades\" }, { \"title\": \"Devil And The Deep Dark", "= PostgreSQLAdaptor({ 'host': 'localhost', 'user': 'sqless', 'database': 'sqless', 'password': '<PASSWORD>' }) class User(DbObject):", "Darkness\", \"artist\": \"Immortal_\", \"album\": \"Sons Of Northern Darkness\" } ] for song in", "'postgres' in sys.argv: from nopea.adaptors.postgres import PostgreSQLAdaptor DbObject.adaptor = PostgreSQLAdaptor({ 'host': 'localhost', 'user':", "title = fields.CharField(max_length=100) artist = fields.CharField(max_length=100) album = fields.CharField(max_length=100) in_collection = fields.BooleanField(default=False) Migration.migration_dir", "\"Love Like Cyanide\", \"artist\": \"Sirenia\", \"album\": \"Arcane Astral Aeons\" }, { \"title\": \"The", "\"artist\": \"Nightwish\", \"album\": \"Decades\" }, { \"title\": \"Ghost Love Score\", \"artist\": \"Nightwish\", \"album\":", "= fields.CharField(max_length=100) album = fields.CharField(max_length=100) in_collection = fields.BooleanField(default=False) Migration.migration_dir = os.path.join(os.getcwd(), 'utils/migrations') migrations", "and migrations import os import sys from nopea.dbobject import DbObject from nopea import", "user in users: User.objects.get_or_create(**user) posts = [ {\"title\": \"TestPosting\", \"content\": \"Lorem Ipsum Dolor", "Song(DbObject): title = fields.CharField(max_length=100) artist = fields.CharField(max_length=100) album = fields.CharField(max_length=100) in_collection = fields.BooleanField(default=False)", "= MySQLAdaptor({ 'host': 'localhost', 'user': 'sqless', 'db': 'sqless', 'use_unicode': True, 'charset': 'utf8' })", "{ \"title\": \"Ghost Love Score\", \"artist\": \"Nightwish\", \"album\": \"Decades\" }, { \"title\": \"Devil", "= [ {\"title\": \"TestPosting\", \"content\": \"Lorem Ipsum Dolor Sit\"}, {\"title\": \"SomeOtherStuff\", \"content\": \"hello,", "'host': 'localhost', 'user': 'sqless', 'db': 'sqless', 'use_unicode': True, 'charset': 'utf8' }) elif 'postgres'", "\"content\": \"hello, world!\"}, ] for post in posts: Post.objects.get_or_create(**post) songs = [ {", "nopea.adaptors.sqlite import SQLiteAdaptor DbObject.adaptor = SQLiteAdaptor('sqless.db') elif 'mysql' in sys.argv: from nopea.adaptors.mysql import", "] for user in users: User.objects.get_or_create(**user) posts = [ {\"title\": \"TestPosting\", \"content\": \"Lorem", "os.path.join(os.getcwd(), 'utils/migrations') migrations = Migration() migrations.create_migrations() migrations.run_migrations() users = [ {\"username\": \"TestUser1\", \"email\":", "Migration if 'sqlite' in sys.argv: from nopea.adaptors.sqlite import SQLiteAdaptor DbObject.adaptor = SQLiteAdaptor('sqless.db') elif", "\"email\": \"<EMAIL>\", \"failed_logins\": 12} ] for user in users: User.objects.get_or_create(**user) posts = [", "fields.CharField(max_length=100) artist = fields.CharField(max_length=100) album = fields.CharField(max_length=100) in_collection = fields.BooleanField(default=False) Migration.migration_dir = os.path.join(os.getcwd(),", "\"Devil And The Deep Dark Ocean\", \"artist\": \"Nightwish\", \"album\": \"Decades\" }, { \"title\":", "\"title\": \"One By One\", \"artist\": \"Immortal_\", \"album\": \"Sons Of Northern Darkness\" }, {", "}, { \"title\": \"Sons Of Northern Darkness\", \"artist\": \"Immortal_\", \"album\": \"Sons Of Northern", "'utf8' }) elif 'postgres' in sys.argv: from nopea.adaptors.postgres import PostgreSQLAdaptor DbObject.adaptor = PostgreSQLAdaptor({", "'utils/migrations') migrations = Migration() migrations.create_migrations() migrations.run_migrations() users = [ {\"username\": \"TestUser1\", \"email\": \"<EMAIL>\"},", "Love Score\", \"artist\": \"Nightwish\", \"album\": \"Decades\" }, { \"title\": \"Devil And The Deep", "'use_unicode': True, 'charset': 'utf8' }) elif 'postgres' in sys.argv: from nopea.adaptors.postgres import PostgreSQLAdaptor", "'host': 'localhost', 'user': 'sqless', 'database': 'sqless', 'password': '<PASSWORD>' }) class User(DbObject): username =", "\"Lorem Ipsum Dolor Sit\"}, {\"title\": \"SomeOtherStuff\", \"content\": \"hello, world!\"}, ] for post in", "= fields.CharField(max_length=20) email = fields.CharField(max_length=100) failed_logins = fields.IntegerField(default=0) class Post(DbObject): title = fields.CharField(max_length=100)", "Northern Darkness\" }, { \"title\": \"Sons Of Northern Darkness\", \"artist\": \"Immortal_\", \"album\": \"Sons", "Of Northern Darkness\", \"artist\": \"Immortal_\", \"album\": \"Sons Of Northern Darkness\" } ] for", "DbObject.adaptor = SQLiteAdaptor('sqless.db') elif 'mysql' in sys.argv: from nopea.adaptors.mysql import MySQLAdaptor DbObject.adaptor =", "[ {\"title\": \"TestPosting\", \"content\": \"Lorem Ipsum Dolor Sit\"}, {\"title\": \"SomeOtherStuff\", \"content\": \"hello, world!\"},", "'localhost', 'user': 'sqless', 'db': 'sqless', 'use_unicode': True, 'charset': 'utf8' }) elif 'postgres' in", "\"artist\": \"Immortal_\", \"album\": \"Sons Of Northern Darkness\" } ] for song in songs:", "One\", \"artist\": \"Immortal_\", \"album\": \"Sons Of Northern Darkness\" }, { \"title\": \"Sons Of", "content = fields.TextField() class Song(DbObject): title = fields.CharField(max_length=100) artist = fields.CharField(max_length=100) album =", "{ \"title\": \"Devil And The Deep Dark Ocean\", \"artist\": \"Nightwish\", \"album\": \"Decades\" },", "}, { \"title\": \"Devil And The Deep Dark Ocean\", \"artist\": \"Nightwish\", \"album\": \"Decades\"", "On Earth\", \"artist\": \"Nightwish\", \"album\": \"Decades\" }, { \"title\": \"Ghost Love Score\", \"artist\":", "Post.objects.get_or_create(**post) songs = [ { \"title\": \"Love Like Cyanide\", \"artist\": \"Sirenia\", \"album\": \"Arcane", "title = fields.CharField(max_length=100) content = fields.TextField() class Song(DbObject): title = fields.CharField(max_length=100) artist =", "{ \"title\": \"The Greatest Show On Earth\", \"artist\": \"Nightwish\", \"album\": \"Decades\" }, {", "import PostgreSQLAdaptor DbObject.adaptor = PostgreSQLAdaptor({ 'host': 'localhost', 'user': 'sqless', 'database': 'sqless', 'password': '<PASSWORD>'", "\"Immortal_\", \"album\": \"Sons Of Northern Darkness\" }, { \"title\": \"Sons Of Northern Darkness\",", "class User(DbObject): username = fields.CharField(max_length=20) email = fields.CharField(max_length=100) failed_logins = fields.IntegerField(default=0) class Post(DbObject):", "from nopea.migrations import Migration if 'sqlite' in sys.argv: from nopea.adaptors.sqlite import SQLiteAdaptor DbObject.adaptor", "[ { \"title\": \"Love Like Cyanide\", \"artist\": \"Sirenia\", \"album\": \"Arcane Astral Aeons\" },", "class Song(DbObject): title = fields.CharField(max_length=100) artist = fields.CharField(max_length=100) album = fields.CharField(max_length=100) in_collection =", "Aeons\" }, { \"title\": \"The Greatest Show On Earth\", \"artist\": \"Nightwish\", \"album\": \"Decades\"", "elif 'mysql' in sys.argv: from nopea.adaptors.mysql import MySQLAdaptor DbObject.adaptor = MySQLAdaptor({ 'host': 'localhost',", "users = [ {\"username\": \"TestUser1\", \"email\": \"<EMAIL>\"}, {\"username\": \"TestUser2\", \"email\": \"<EMAIL>\"}, {\"username\": \"TestUser3\",", "Show On Earth\", \"artist\": \"Nightwish\", \"album\": \"Decades\" }, { \"title\": \"Ghost Love Score\",", "\"album\": \"Decades\" }, { \"title\": \"Ghost Love Score\", \"artist\": \"Nightwish\", \"album\": \"Decades\" },", "'sqless', 'use_unicode': True, 'charset': 'utf8' }) elif 'postgres' in sys.argv: from nopea.adaptors.postgres import", "\"Sons Of Northern Darkness\" }, { \"title\": \"Sons Of Northern Darkness\", \"artist\": \"Immortal_\",", "fields.CharField(max_length=100) content = fields.TextField() class Song(DbObject): title = fields.CharField(max_length=100) artist = fields.CharField(max_length=100) album", "class Post(DbObject): title = fields.CharField(max_length=100) content = fields.TextField() class Song(DbObject): title = fields.CharField(max_length=100)", "nopea.adaptors.postgres import PostgreSQLAdaptor DbObject.adaptor = PostgreSQLAdaptor({ 'host': 'localhost', 'user': 'sqless', 'database': 'sqless', 'password':", "'password': '<PASSWORD>' }) class User(DbObject): username = fields.CharField(max_length=20) email = fields.CharField(max_length=100) failed_logins =", "nopea import fields from nopea.migrations import Migration if 'sqlite' in sys.argv: from nopea.adaptors.sqlite", "{\"username\": \"TestUser3\", \"email\": \"<EMAIL>\", \"failed_logins\": 12} ] for user in users: User.objects.get_or_create(**user) posts", "\"title\": \"The Greatest Show On Earth\", \"artist\": \"Nightwish\", \"album\": \"Decades\" }, { \"title\":", "Deep Dark Ocean\", \"artist\": \"Nightwish\", \"album\": \"Decades\" }, { \"title\": \"One By One\",", "from nopea.adaptors.postgres import PostgreSQLAdaptor DbObject.adaptor = PostgreSQLAdaptor({ 'host': 'localhost', 'user': 'sqless', 'database': 'sqless',", "sys.argv: from nopea.adaptors.sqlite import SQLiteAdaptor DbObject.adaptor = SQLiteAdaptor('sqless.db') elif 'mysql' in sys.argv: from", "\"artist\": \"Nightwish\", \"album\": \"Decades\" }, { \"title\": \"Devil And The Deep Dark Ocean\",", "\"Nightwish\", \"album\": \"Decades\" }, { \"title\": \"Devil And The Deep Dark Ocean\", \"artist\":", "\"album\": \"Decades\" }, { \"title\": \"One By One\", \"artist\": \"Immortal_\", \"album\": \"Sons Of", "'localhost', 'user': 'sqless', 'database': 'sqless', 'password': '<PASSWORD>' }) class User(DbObject): username = fields.CharField(max_length=20)", "Darkness\" }, { \"title\": \"Sons Of Northern Darkness\", \"artist\": \"Immortal_\", \"album\": \"Sons Of", "migrations import os import sys from nopea.dbobject import DbObject from nopea import fields", "import SQLiteAdaptor DbObject.adaptor = SQLiteAdaptor('sqless.db') elif 'mysql' in sys.argv: from nopea.adaptors.mysql import MySQLAdaptor", "from nopea.adaptors.sqlite import SQLiteAdaptor DbObject.adaptor = SQLiteAdaptor('sqless.db') elif 'mysql' in sys.argv: from nopea.adaptors.mysql", "SQLiteAdaptor('sqless.db') elif 'mysql' in sys.argv: from nopea.adaptors.mysql import MySQLAdaptor DbObject.adaptor = MySQLAdaptor({ 'host':", "fields from nopea.migrations import Migration if 'sqlite' in sys.argv: from nopea.adaptors.sqlite import SQLiteAdaptor", "Earth\", \"artist\": \"Nightwish\", \"album\": \"Decades\" }, { \"title\": \"Ghost Love Score\", \"artist\": \"Nightwish\",", "fields.TextField() class Song(DbObject): title = fields.CharField(max_length=100) artist = fields.CharField(max_length=100) album = fields.CharField(max_length=100) in_collection", "= fields.CharField(max_length=100) content = fields.TextField() class Song(DbObject): title = fields.CharField(max_length=100) artist = fields.CharField(max_length=100)", "\"<EMAIL>\", \"failed_logins\": 12} ] for user in users: User.objects.get_or_create(**user) posts = [ {\"title\":", "= fields.BooleanField(default=False) Migration.migration_dir = os.path.join(os.getcwd(), 'utils/migrations') migrations = Migration() migrations.create_migrations() migrations.run_migrations() users =", "failed_logins = fields.IntegerField(default=0) class Post(DbObject): title = fields.CharField(max_length=100) content = fields.TextField() class Song(DbObject):", "\"Decades\" }, { \"title\": \"One By One\", \"artist\": \"Immortal_\", \"album\": \"Sons Of Northern", "sys.argv: from nopea.adaptors.mysql import MySQLAdaptor DbObject.adaptor = MySQLAdaptor({ 'host': 'localhost', 'user': 'sqless', 'db':", "DbObject.adaptor = PostgreSQLAdaptor({ 'host': 'localhost', 'user': 'sqless', 'database': 'sqless', 'password': '<PASSWORD>' }) class", "album = fields.CharField(max_length=100) in_collection = fields.BooleanField(default=False) Migration.migration_dir = os.path.join(os.getcwd(), 'utils/migrations') migrations = Migration()", "\"TestUser3\", \"email\": \"<EMAIL>\", \"failed_logins\": 12} ] for user in users: User.objects.get_or_create(**user) posts =", "import Migration if 'sqlite' in sys.argv: from nopea.adaptors.sqlite import SQLiteAdaptor DbObject.adaptor = SQLiteAdaptor('sqless.db')", "fields.BooleanField(default=False) Migration.migration_dir = os.path.join(os.getcwd(), 'utils/migrations') migrations = Migration() migrations.create_migrations() migrations.run_migrations() users = [", "nopea.migrations import Migration if 'sqlite' in sys.argv: from nopea.adaptors.sqlite import SQLiteAdaptor DbObject.adaptor =", "PostgreSQLAdaptor({ 'host': 'localhost', 'user': 'sqless', 'database': 'sqless', 'password': '<PASSWORD>' }) class User(DbObject): username", "nopea.dbobject import DbObject from nopea import fields from nopea.migrations import Migration if 'sqlite'", "users: User.objects.get_or_create(**user) posts = [ {\"title\": \"TestPosting\", \"content\": \"Lorem Ipsum Dolor Sit\"}, {\"title\":", "'sqlite' in sys.argv: from nopea.adaptors.sqlite import SQLiteAdaptor DbObject.adaptor = SQLiteAdaptor('sqless.db') elif 'mysql' in", "'mysql' in sys.argv: from nopea.adaptors.mysql import MySQLAdaptor DbObject.adaptor = MySQLAdaptor({ 'host': 'localhost', 'user':", "\"TestUser2\", \"email\": \"<EMAIL>\"}, {\"username\": \"TestUser3\", \"email\": \"<EMAIL>\", \"failed_logins\": 12} ] for user in", "] for post in posts: Post.objects.get_or_create(**post) songs = [ { \"title\": \"Love Like", "fields.IntegerField(default=0) class Post(DbObject): title = fields.CharField(max_length=100) content = fields.TextField() class Song(DbObject): title =", "if 'sqlite' in sys.argv: from nopea.adaptors.sqlite import SQLiteAdaptor DbObject.adaptor = SQLiteAdaptor('sqless.db') elif 'mysql'", "from nopea.adaptors.mysql import MySQLAdaptor DbObject.adaptor = MySQLAdaptor({ 'host': 'localhost', 'user': 'sqless', 'db': 'sqless',", "Dolor Sit\"}, {\"title\": \"SomeOtherStuff\", \"content\": \"hello, world!\"}, ] for post in posts: Post.objects.get_or_create(**post)", "\"album\": \"Sons Of Northern Darkness\" }, { \"title\": \"Sons Of Northern Darkness\", \"artist\":", "\"title\": \"Devil And The Deep Dark Ocean\", \"artist\": \"Nightwish\", \"album\": \"Decades\" }, {", "MySQLAdaptor({ 'host': 'localhost', 'user': 'sqless', 'db': 'sqless', 'use_unicode': True, 'charset': 'utf8' }) elif", "\"Immortal_\", \"album\": \"Sons Of Northern Darkness\" } ] for song in songs: Song.objects.get_or_create(**song)", "in_collection = fields.BooleanField(default=False) Migration.migration_dir = os.path.join(os.getcwd(), 'utils/migrations') migrations = Migration() migrations.create_migrations() migrations.run_migrations() users", "Dark Ocean\", \"artist\": \"Nightwish\", \"album\": \"Decades\" }, { \"title\": \"One By One\", \"artist\":", "SQLiteAdaptor DbObject.adaptor = SQLiteAdaptor('sqless.db') elif 'mysql' in sys.argv: from nopea.adaptors.mysql import MySQLAdaptor DbObject.adaptor", "\"Nightwish\", \"album\": \"Decades\" }, { \"title\": \"Ghost Love Score\", \"artist\": \"Nightwish\", \"album\": \"Decades\"", "\"Decades\" }, { \"title\": \"Ghost Love Score\", \"artist\": \"Nightwish\", \"album\": \"Decades\" }, {", "Of Northern Darkness\" }, { \"title\": \"Sons Of Northern Darkness\", \"artist\": \"Immortal_\", \"album\":", "Like Cyanide\", \"artist\": \"Sirenia\", \"album\": \"Arcane Astral Aeons\" }, { \"title\": \"The Greatest", "'db': 'sqless', 'use_unicode': True, 'charset': 'utf8' }) elif 'postgres' in sys.argv: from nopea.adaptors.postgres", "\"email\": \"<EMAIL>\"}, {\"username\": \"TestUser3\", \"email\": \"<EMAIL>\", \"failed_logins\": 12} ] for user in users:", "{\"title\": \"SomeOtherStuff\", \"content\": \"hello, world!\"}, ] for post in posts: Post.objects.get_or_create(**post) songs =", "By One\", \"artist\": \"Immortal_\", \"album\": \"Sons Of Northern Darkness\" }, { \"title\": \"Sons", "migrations.create_migrations() migrations.run_migrations() users = [ {\"username\": \"TestUser1\", \"email\": \"<EMAIL>\"}, {\"username\": \"TestUser2\", \"email\": \"<EMAIL>\"},", "Astral Aeons\" }, { \"title\": \"The Greatest Show On Earth\", \"artist\": \"Nightwish\", \"album\":", "\"failed_logins\": 12} ] for user in users: User.objects.get_or_create(**user) posts = [ {\"title\": \"TestPosting\",", "fields.CharField(max_length=100) in_collection = fields.BooleanField(default=False) Migration.migration_dir = os.path.join(os.getcwd(), 'utils/migrations') migrations = Migration() migrations.create_migrations() migrations.run_migrations()", "Sit\"}, {\"title\": \"SomeOtherStuff\", \"content\": \"hello, world!\"}, ] for post in posts: Post.objects.get_or_create(**post) songs", "Ocean\", \"artist\": \"Nightwish\", \"album\": \"Decades\" }, { \"title\": \"One By One\", \"artist\": \"Immortal_\",", "world!\"}, ] for post in posts: Post.objects.get_or_create(**post) songs = [ { \"title\": \"Love", "post in posts: Post.objects.get_or_create(**post) songs = [ { \"title\": \"Love Like Cyanide\", \"artist\":", "\"artist\": \"Sirenia\", \"album\": \"Arcane Astral Aeons\" }, { \"title\": \"The Greatest Show On", "for user in users: User.objects.get_or_create(**user) posts = [ {\"title\": \"TestPosting\", \"content\": \"Lorem Ipsum", "PostgreSQLAdaptor DbObject.adaptor = PostgreSQLAdaptor({ 'host': 'localhost', 'user': 'sqless', 'database': 'sqless', 'password': '<PASSWORD>' })", "in users: User.objects.get_or_create(**user) posts = [ {\"title\": \"TestPosting\", \"content\": \"Lorem Ipsum Dolor Sit\"},", "needed to initialize the models and migrations import os import sys from nopea.dbobject", "in sys.argv: from nopea.adaptors.postgres import PostgreSQLAdaptor DbObject.adaptor = PostgreSQLAdaptor({ 'host': 'localhost', 'user': 'sqless',", "Ipsum Dolor Sit\"}, {\"title\": \"SomeOtherStuff\", \"content\": \"hello, world!\"}, ] for post in posts:", "\"SomeOtherStuff\", \"content\": \"hello, world!\"}, ] for post in posts: Post.objects.get_or_create(**post) songs = [", "email = fields.CharField(max_length=100) failed_logins = fields.IntegerField(default=0) class Post(DbObject): title = fields.CharField(max_length=100) content =", "\"<EMAIL>\"}, {\"username\": \"TestUser2\", \"email\": \"<EMAIL>\"}, {\"username\": \"TestUser3\", \"email\": \"<EMAIL>\", \"failed_logins\": 12} ] for", "is needed to initialize the models and migrations import os import sys from", "}, { \"title\": \"The Greatest Show On Earth\", \"artist\": \"Nightwish\", \"album\": \"Decades\" },", "'sqless', 'database': 'sqless', 'password': '<PASSWORD>' }) class User(DbObject): username = fields.CharField(max_length=20) email =", "\"TestPosting\", \"content\": \"Lorem Ipsum Dolor Sit\"}, {\"title\": \"SomeOtherStuff\", \"content\": \"hello, world!\"}, ] for", "import os import sys from nopea.dbobject import DbObject from nopea import fields from", "\"Sons Of Northern Darkness\", \"artist\": \"Immortal_\", \"album\": \"Sons Of Northern Darkness\" } ]", "= fields.CharField(max_length=100) failed_logins = fields.IntegerField(default=0) class Post(DbObject): title = fields.CharField(max_length=100) content = fields.TextField()", "\"Ghost Love Score\", \"artist\": \"Nightwish\", \"album\": \"Decades\" }, { \"title\": \"Devil And The", "\"album\": \"Decades\" }, { \"title\": \"Devil And The Deep Dark Ocean\", \"artist\": \"Nightwish\",", "'user': 'sqless', 'db': 'sqless', 'use_unicode': True, 'charset': 'utf8' }) elif 'postgres' in sys.argv:", "\"Arcane Astral Aeons\" }, { \"title\": \"The Greatest Show On Earth\", \"artist\": \"Nightwish\",", "Migration.migration_dir = os.path.join(os.getcwd(), 'utils/migrations') migrations = Migration() migrations.create_migrations() migrations.run_migrations() users = [ {\"username\":", "'<PASSWORD>' }) class User(DbObject): username = fields.CharField(max_length=20) email = fields.CharField(max_length=100) failed_logins = fields.IntegerField(default=0)" ]
[ "sq_meters_to_sq_miles(aoi.geometry_final.area) context = { 'aoi': aoi, 'default_value': default_value, 'area': area } return context", "from drawing.models import * ''' ''' def display_aoi_analysis(request, aoi, template='aoi/reports/aoi_report.html'): context = get_wind_analysis(aoi)", "import * from general.utils import default_value, sq_meters_to_sq_miles from drawing.models import * ''' '''", "the analysis, create the cache, and return the results as a context dictionary", "render(request, template, context) ''' Run the analysis, create the cache, and return the", "a context dictionary so they may be rendered with template ''' def get_wind_analysis(aoi):", "general.utils import default_value, sq_meters_to_sq_miles from drawing.models import * ''' ''' def display_aoi_analysis(request, aoi,", "as a context dictionary so they may be rendered with template ''' def", "they may be rendered with template ''' def get_wind_analysis(aoi): #compile context area =", "''' Run the analysis, create the cache, and return the results as a", "return the results as a context dictionary so they may be rendered with", "context dictionary so they may be rendered with template ''' def get_wind_analysis(aoi): #compile", "Run the analysis, create the cache, and return the results as a context", "import render #from madrona.raster_stats.models import RasterDataset, zonal_stats from settings import * from general.utils", "sq_meters_to_sq_miles from drawing.models import * ''' ''' def display_aoi_analysis(request, aoi, template='aoi/reports/aoi_report.html'): context =", "def display_aoi_analysis(request, aoi, template='aoi/reports/aoi_report.html'): context = get_wind_analysis(aoi) return render(request, template, context) ''' Run", "be rendered with template ''' def get_wind_analysis(aoi): #compile context area = sq_meters_to_sq_miles(aoi.geometry_final.area) context", "''' def get_wind_analysis(aoi): #compile context area = sq_meters_to_sq_miles(aoi.geometry_final.area) context = { 'aoi': aoi,", "so they may be rendered with template ''' def get_wind_analysis(aoi): #compile context area", "import default_value, sq_meters_to_sq_miles from drawing.models import * ''' ''' def display_aoi_analysis(request, aoi, template='aoi/reports/aoi_report.html'):", "aoi, template='aoi/reports/aoi_report.html'): context = get_wind_analysis(aoi) return render(request, template, context) ''' Run the analysis,", "context = get_wind_analysis(aoi) return render(request, template, context) ''' Run the analysis, create the", "''' ''' def display_aoi_analysis(request, aoi, template='aoi/reports/aoi_report.html'): context = get_wind_analysis(aoi) return render(request, template, context)", "the cache, and return the results as a context dictionary so they may", "def get_wind_analysis(aoi): #compile context area = sq_meters_to_sq_miles(aoi.geometry_final.area) context = { 'aoi': aoi, 'default_value':", "context) ''' Run the analysis, create the cache, and return the results as", "and return the results as a context dictionary so they may be rendered", "template, context) ''' Run the analysis, create the cache, and return the results", "= sq_meters_to_sq_miles(aoi.geometry_final.area) context = { 'aoi': aoi, 'default_value': default_value, 'area': area } return", "* ''' ''' def display_aoi_analysis(request, aoi, template='aoi/reports/aoi_report.html'): context = get_wind_analysis(aoi) return render(request, template,", "''' def display_aoi_analysis(request, aoi, template='aoi/reports/aoi_report.html'): context = get_wind_analysis(aoi) return render(request, template, context) '''", "results as a context dictionary so they may be rendered with template '''", "with template ''' def get_wind_analysis(aoi): #compile context area = sq_meters_to_sq_miles(aoi.geometry_final.area) context = {", "area = sq_meters_to_sq_miles(aoi.geometry_final.area) context = { 'aoi': aoi, 'default_value': default_value, 'area': area }", "may be rendered with template ''' def get_wind_analysis(aoi): #compile context area = sq_meters_to_sq_miles(aoi.geometry_final.area)", "get_wind_analysis(aoi): #compile context area = sq_meters_to_sq_miles(aoi.geometry_final.area) context = { 'aoi': aoi, 'default_value': default_value,", "dictionary so they may be rendered with template ''' def get_wind_analysis(aoi): #compile context", "context area = sq_meters_to_sq_miles(aoi.geometry_final.area) context = { 'aoi': aoi, 'default_value': default_value, 'area': area", "madrona.raster_stats.models import RasterDataset, zonal_stats from settings import * from general.utils import default_value, sq_meters_to_sq_miles", "* from general.utils import default_value, sq_meters_to_sq_miles from drawing.models import * ''' ''' def", "get_wind_analysis(aoi) return render(request, template, context) ''' Run the analysis, create the cache, and", "from django.shortcuts import render #from madrona.raster_stats.models import RasterDataset, zonal_stats from settings import *", "import RasterDataset, zonal_stats from settings import * from general.utils import default_value, sq_meters_to_sq_miles from", "<reponame>Ecotrust/COMPASS<filename>mp/drawing/aoi_analysis.py<gh_stars>1-10 from django.shortcuts import render #from madrona.raster_stats.models import RasterDataset, zonal_stats from settings import", "= get_wind_analysis(aoi) return render(request, template, context) ''' Run the analysis, create the cache,", "analysis, create the cache, and return the results as a context dictionary so", "cache, and return the results as a context dictionary so they may be", "the results as a context dictionary so they may be rendered with template", "display_aoi_analysis(request, aoi, template='aoi/reports/aoi_report.html'): context = get_wind_analysis(aoi) return render(request, template, context) ''' Run the", "RasterDataset, zonal_stats from settings import * from general.utils import default_value, sq_meters_to_sq_miles from drawing.models", "from general.utils import default_value, sq_meters_to_sq_miles from drawing.models import * ''' ''' def display_aoi_analysis(request,", "default_value, sq_meters_to_sq_miles from drawing.models import * ''' ''' def display_aoi_analysis(request, aoi, template='aoi/reports/aoi_report.html'): context", "settings import * from general.utils import default_value, sq_meters_to_sq_miles from drawing.models import * '''", "template ''' def get_wind_analysis(aoi): #compile context area = sq_meters_to_sq_miles(aoi.geometry_final.area) context = { 'aoi':", "django.shortcuts import render #from madrona.raster_stats.models import RasterDataset, zonal_stats from settings import * from", "render #from madrona.raster_stats.models import RasterDataset, zonal_stats from settings import * from general.utils import", "#compile context area = sq_meters_to_sq_miles(aoi.geometry_final.area) context = { 'aoi': aoi, 'default_value': default_value, 'area':", "create the cache, and return the results as a context dictionary so they", "from settings import * from general.utils import default_value, sq_meters_to_sq_miles from drawing.models import *", "import * ''' ''' def display_aoi_analysis(request, aoi, template='aoi/reports/aoi_report.html'): context = get_wind_analysis(aoi) return render(request,", "rendered with template ''' def get_wind_analysis(aoi): #compile context area = sq_meters_to_sq_miles(aoi.geometry_final.area) context =", "template='aoi/reports/aoi_report.html'): context = get_wind_analysis(aoi) return render(request, template, context) ''' Run the analysis, create", "return render(request, template, context) ''' Run the analysis, create the cache, and return", "zonal_stats from settings import * from general.utils import default_value, sq_meters_to_sq_miles from drawing.models import", "#from madrona.raster_stats.models import RasterDataset, zonal_stats from settings import * from general.utils import default_value,", "drawing.models import * ''' ''' def display_aoi_analysis(request, aoi, template='aoi/reports/aoi_report.html'): context = get_wind_analysis(aoi) return" ]
[ "<reponame>vbhatt-cs/inference-based-messaging from .model_s import ModelS from .model_r import ModelR __all__ = [\"ModelR\", \"ModelS\"]" ]
[ "def set_point(self, i: int, x: T) -> typing.NoReturn: self.__seg[i] = x def operate_point(self,", "import ( SegmentTree, ) # TODO cut below import typing import typing T", "i: int, x: T) -> typing.NoReturn: self.set_point(i, self.__monoid.op(self.get_point(i), x)) def get_point(self, i: int)", "<gh_stars>0 from kgmk.dsa.algebra.abstract.structure.monoid import ( Monoid, ) from \\ kgmk.dsa.tree.misc.segment.normal.one_indexed.topdown \\ .non_recursive \\", "cut below import typing import typing T = typing.TypeVar('T') class SetPointGetRange(typing.Generic[T]): def __init__(", "int, x: T) -> typing.NoReturn: self.__seg[i] = x def operate_point(self, i: int, x:", "import ( Monoid, ) from \\ kgmk.dsa.tree.misc.segment.normal.one_indexed.topdown \\ .non_recursive \\ import ( SegmentTree,", "self.__monoid = monoid def set_point(self, i: int, x: T) -> typing.NoReturn: self.__seg[i] =", "typing.List[T], ) -> typing.NoReturn: self.__seg = SegmentTree(monoid, a) self.__monoid = monoid def set_point(self,", "= SegmentTree(monoid, a) self.__monoid = monoid def set_point(self, i: int, x: T) ->", "( SegmentTree, ) # TODO cut below import typing import typing T =", "-> typing.NoReturn: self.set_point(i, self.__monoid.op(self.get_point(i), x)) def get_point(self, i: int) -> T: return self.__seg[i]", "monoid def set_point(self, i: int, x: T) -> typing.NoReturn: self.__seg[i] = x def", "kgmk.dsa.tree.misc.segment.normal.one_indexed.topdown \\ .non_recursive \\ import ( SegmentTree, ) # TODO cut below import", "= monoid def set_point(self, i: int, x: T) -> typing.NoReturn: self.__seg[i] = x", "get_point(self, i: int) -> T: return self.__seg[i] def get_range(self, l: int, r: int)", "typing.NoReturn: self.__seg = SegmentTree(monoid, a) self.__monoid = monoid def set_point(self, i: int, x:", "a: typing.List[T], ) -> typing.NoReturn: self.__seg = SegmentTree(monoid, a) self.__monoid = monoid def", "typing T = typing.TypeVar('T') class SetPointGetRange(typing.Generic[T]): def __init__( self, monoid: Monoid[T], a: typing.List[T],", "x: T) -> typing.NoReturn: self.__seg[i] = x def operate_point(self, i: int, x: T)", "self.__seg[i] = x def operate_point(self, i: int, x: T) -> typing.NoReturn: self.set_point(i, self.__monoid.op(self.get_point(i),", "from kgmk.dsa.algebra.abstract.structure.monoid import ( Monoid, ) from \\ kgmk.dsa.tree.misc.segment.normal.one_indexed.topdown \\ .non_recursive \\ import", "TODO cut below import typing import typing T = typing.TypeVar('T') class SetPointGetRange(typing.Generic[T]): def", "-> T: return self.__seg[i] def get_range(self, l: int, r: int) -> T: return", "a) self.__monoid = monoid def set_point(self, i: int, x: T) -> typing.NoReturn: self.__seg[i]", ") -> typing.NoReturn: self.__seg = SegmentTree(monoid, a) self.__monoid = monoid def set_point(self, i:", "set_point(self, i: int, x: T) -> typing.NoReturn: self.__seg[i] = x def operate_point(self, i:", ".non_recursive \\ import ( SegmentTree, ) # TODO cut below import typing import", "\\ .non_recursive \\ import ( SegmentTree, ) # TODO cut below import typing", "monoid: Monoid[T], a: typing.List[T], ) -> typing.NoReturn: self.__seg = SegmentTree(monoid, a) self.__monoid =", "typing.NoReturn: self.__seg[i] = x def operate_point(self, i: int, x: T) -> typing.NoReturn: self.set_point(i,", "\\ import ( SegmentTree, ) # TODO cut below import typing import typing", "SegmentTree, ) # TODO cut below import typing import typing T = typing.TypeVar('T')", "self.__seg = SegmentTree(monoid, a) self.__monoid = monoid def set_point(self, i: int, x: T)", "import typing T = typing.TypeVar('T') class SetPointGetRange(typing.Generic[T]): def __init__( self, monoid: Monoid[T], a:", "i: int) -> T: return self.__seg[i] def get_range(self, l: int, r: int) ->", "kgmk.dsa.algebra.abstract.structure.monoid import ( Monoid, ) from \\ kgmk.dsa.tree.misc.segment.normal.one_indexed.topdown \\ .non_recursive \\ import (", "Monoid[T], a: typing.List[T], ) -> typing.NoReturn: self.__seg = SegmentTree(monoid, a) self.__monoid = monoid", "int, x: T) -> typing.NoReturn: self.set_point(i, self.__monoid.op(self.get_point(i), x)) def get_point(self, i: int) ->", "def __init__( self, monoid: Monoid[T], a: typing.List[T], ) -> typing.NoReturn: self.__seg = SegmentTree(monoid,", "T) -> typing.NoReturn: self.set_point(i, self.__monoid.op(self.get_point(i), x)) def get_point(self, i: int) -> T: return", "typing.NoReturn: self.set_point(i, self.__monoid.op(self.get_point(i), x)) def get_point(self, i: int) -> T: return self.__seg[i] def", "from \\ kgmk.dsa.tree.misc.segment.normal.one_indexed.topdown \\ .non_recursive \\ import ( SegmentTree, ) # TODO cut", "self, monoid: Monoid[T], a: typing.List[T], ) -> typing.NoReturn: self.__seg = SegmentTree(monoid, a) self.__monoid", "operate_point(self, i: int, x: T) -> typing.NoReturn: self.set_point(i, self.__monoid.op(self.get_point(i), x)) def get_point(self, i:", ") from \\ kgmk.dsa.tree.misc.segment.normal.one_indexed.topdown \\ .non_recursive \\ import ( SegmentTree, ) # TODO", "class SetPointGetRange(typing.Generic[T]): def __init__( self, monoid: Monoid[T], a: typing.List[T], ) -> typing.NoReturn: self.__seg", "Monoid, ) from \\ kgmk.dsa.tree.misc.segment.normal.one_indexed.topdown \\ .non_recursive \\ import ( SegmentTree, ) #", "import typing import typing T = typing.TypeVar('T') class SetPointGetRange(typing.Generic[T]): def __init__( self, monoid:", "def operate_point(self, i: int, x: T) -> typing.NoReturn: self.set_point(i, self.__monoid.op(self.get_point(i), x)) def get_point(self,", "# TODO cut below import typing import typing T = typing.TypeVar('T') class SetPointGetRange(typing.Generic[T]):", "x def operate_point(self, i: int, x: T) -> typing.NoReturn: self.set_point(i, self.__monoid.op(self.get_point(i), x)) def", "self.set_point(i, self.__monoid.op(self.get_point(i), x)) def get_point(self, i: int) -> T: return self.__seg[i] def get_range(self,", "\\ kgmk.dsa.tree.misc.segment.normal.one_indexed.topdown \\ .non_recursive \\ import ( SegmentTree, ) # TODO cut below", "below import typing import typing T = typing.TypeVar('T') class SetPointGetRange(typing.Generic[T]): def __init__( self,", "typing import typing T = typing.TypeVar('T') class SetPointGetRange(typing.Generic[T]): def __init__( self, monoid: Monoid[T],", "SetPointGetRange(typing.Generic[T]): def __init__( self, monoid: Monoid[T], a: typing.List[T], ) -> typing.NoReturn: self.__seg =", "= x def operate_point(self, i: int, x: T) -> typing.NoReturn: self.set_point(i, self.__monoid.op(self.get_point(i), x))", "T = typing.TypeVar('T') class SetPointGetRange(typing.Generic[T]): def __init__( self, monoid: Monoid[T], a: typing.List[T], )", "i: int, x: T) -> typing.NoReturn: self.__seg[i] = x def operate_point(self, i: int,", "x: T) -> typing.NoReturn: self.set_point(i, self.__monoid.op(self.get_point(i), x)) def get_point(self, i: int) -> T:", "def get_point(self, i: int) -> T: return self.__seg[i] def get_range(self, l: int, r:", "typing.TypeVar('T') class SetPointGetRange(typing.Generic[T]): def __init__( self, monoid: Monoid[T], a: typing.List[T], ) -> typing.NoReturn:", "= typing.TypeVar('T') class SetPointGetRange(typing.Generic[T]): def __init__( self, monoid: Monoid[T], a: typing.List[T], ) ->", "int) -> T: return self.__seg[i] def get_range(self, l: int, r: int) -> T:", "__init__( self, monoid: Monoid[T], a: typing.List[T], ) -> typing.NoReturn: self.__seg = SegmentTree(monoid, a)", "T) -> typing.NoReturn: self.__seg[i] = x def operate_point(self, i: int, x: T) ->", "-> typing.NoReturn: self.__seg[i] = x def operate_point(self, i: int, x: T) -> typing.NoReturn:", "self.__monoid.op(self.get_point(i), x)) def get_point(self, i: int) -> T: return self.__seg[i] def get_range(self, l:", "( Monoid, ) from \\ kgmk.dsa.tree.misc.segment.normal.one_indexed.topdown \\ .non_recursive \\ import ( SegmentTree, )", "x)) def get_point(self, i: int) -> T: return self.__seg[i] def get_range(self, l: int,", "T: return self.__seg[i] def get_range(self, l: int, r: int) -> T: return self.__seg.get_range(l,", "-> typing.NoReturn: self.__seg = SegmentTree(monoid, a) self.__monoid = monoid def set_point(self, i: int,", "SegmentTree(monoid, a) self.__monoid = monoid def set_point(self, i: int, x: T) -> typing.NoReturn:", "return self.__seg[i] def get_range(self, l: int, r: int) -> T: return self.__seg.get_range(l, r)", ") # TODO cut below import typing import typing T = typing.TypeVar('T') class" ]
[ "# if there is no aggregate file create one, otherwise append to it.", "''); filedate = datetime.datetime.strptime(newFilename, '%Y-%m-%d') if(filedate < week_ago): print('removing files that are more", "# Loop over the files within the folder for filename in sorted(os.listdir('./data/us-tn/co-knox/covid_age/raw')): if", "# apply data types df['date_stamp'] = pd.to_datetime(df['date_stamp']).dt.strftime('%Y-%m-%d') df['cnt_confirmed'] = df['cnt_confirmed'].astype(pd.Int32Dtype()) return df def", "= pd.DataFrame(columns = variables) df['age_group'] = source['v1'].map({ '0-10':'00', '11-20': '11', '21-30': '21', '31-40':", "in the harvested folder data = pd.read_csv(f\"./data/us-tn/co-knox/covid_age/raw/{filename}\") df = cleanData(data, filename) df.to_csv(f\"./data/us-tn/co-knox/covid_age/clean/{filename}\", index=False)", "folder data = pd.read_csv(f\"./data/us-tn/co-knox/covid_age/raw/{filename}\") df = cleanData(data, filename) df.to_csv(f\"./data/us-tn/co-knox/covid_age/clean/{filename}\", index=False) # if there", "path.exists(f\"./data/us-tn/co-knox/covid_age/clean/{filename}\") == False: print(filename) # For each csv file, map the transformed data", "'pct_confirmed' ] def cleanData(data, fileName): # source data frame from csv file source", "df['date_stamp'] = pd.to_datetime(df['date_stamp']).dt.strftime('%Y-%m-%d') df['cnt_confirmed'] = df['cnt_confirmed'].astype(pd.Int32Dtype()) return df def deleteFiles(path): today = datetime.date.today();", "filename.endswith('.csv') and path.exists(f\"./data/us-tn/co-knox/covid_age/clean/{filename}\") == False: print(filename) # For each csv file, map the", "['v1','v2','v3'] print(source) # the target data frame df = pd.DataFrame(columns = variables) df['age_group']", "Loop over the files within the folder for filename in sorted(os.listdir('./data/us-tn/co-knox/covid_age/raw')): if filename.endswith('.csv')", "otherwise append to it. if path.exists(f\"./data/us-tn/co-knox/covid_age/latest.csv\"): df.to_csv(f\"./data/us-tn/co-knox/covid_age/latest.csv\", mode='a', header=False, index=False) else: df.to_csv(f\"./data/us-tn/co-knox/covid_age/latest.csv\", index=False)", "x: x[:-1], source['v3'].values)) df['date_stamp'] = fileName[0:-4] # apply data types df['date_stamp'] = pd.to_datetime(df['date_stamp']).dt.strftime('%Y-%m-%d')", "the harvested folder data = pd.read_csv(f\"./data/us-tn/co-knox/covid_age/raw/{filename}\") df = cleanData(data, filename) df.to_csv(f\"./data/us-tn/co-knox/covid_age/clean/{filename}\", index=False) #", "import pandas as pd import datetime variables = [ 'date_stamp', 'age_group', 'cnt_confirmed', 'pct_confirmed'", "pandas as pd import datetime variables = [ 'date_stamp', 'age_group', 'cnt_confirmed', 'pct_confirmed' ]", "df = pd.DataFrame(columns = variables) df['age_group'] = source['v1'].map({ '0-10':'00', '11-20': '11', '21-30': '21',", "'31', '41-50': '41', '51-60': '51', '61-70': '61', '71-80': '71', '81-90': '81', '90+': '91',", "for filename in os.listdir(path): if(filename.endswith('.csv')): newFilename = filename.replace('.csv', ''); filedate = datetime.datetime.strptime(newFilename, '%Y-%m-%d')", "= source['v1'].map({ '0-10':'00', '11-20': '11', '21-30': '21', '31-40': '31', '41-50': '41', '51-60': '51',", "print('removing files that are more than a week old: ',path,'/',filename) os.remove(f\"{path}/{filename}\") return None", "to its respective file in the harvested folder data = pd.read_csv(f\"./data/us-tn/co-knox/covid_age/raw/{filename}\") df =", "week_ago = datetime.datetime.combine(week, datetime.time(0, 0)) for filename in os.listdir(path): if(filename.endswith('.csv')): newFilename = filename.replace('.csv',", "transformed data to its respective file in the harvested folder data = pd.read_csv(f\"./data/us-tn/co-knox/covid_age/raw/{filename}\")", "that are more than a week old: ',path,'/',filename) os.remove(f\"{path}/{filename}\") return None if __name__", "and path.exists(f\"./data/us-tn/co-knox/covid_age/clean/{filename}\") == False: print(filename) # For each csv file, map the transformed", "df['cnt_confirmed'].astype(pd.Int32Dtype()) return df def deleteFiles(path): today = datetime.date.today(); one_week = datetime.timedelta(days=7) week =", "'31-40': '31', '41-50': '41', '51-60': '51', '61-70': '61', '71-80': '71', '81-90': '81', '90+':", "if(filename.endswith('.csv')): newFilename = filename.replace('.csv', ''); filedate = datetime.datetime.strptime(newFilename, '%Y-%m-%d') if(filedate < week_ago): print('removing", "= datetime.timedelta(days=7) week = today - one_week week_ago = datetime.datetime.combine(week, datetime.time(0, 0)) for", "respective file in the harvested folder data = pd.read_csv(f\"./data/us-tn/co-knox/covid_age/raw/{filename}\") df = cleanData(data, filename)", "as pd import datetime variables = [ 'date_stamp', 'age_group', 'cnt_confirmed', 'pct_confirmed' ] def", "'11', '21-30': '21', '31-40': '31', '41-50': '41', '51-60': '51', '61-70': '61', '71-80': '71',", "week old: ',path,'/',filename) os.remove(f\"{path}/{filename}\") return None if __name__ == \"__main__\": path = os.path", "return None if __name__ == \"__main__\": path = os.path # Loop over the", "if(filedate < week_ago): print('removing files that are more than a week old: ',path,'/',filename)", "pd.DataFrame(columns = variables) df['age_group'] = source['v1'].map({ '0-10':'00', '11-20': '11', '21-30': '21', '31-40': '31',", "pd.DataFrame(data) source.columns = ['v1','v2','v3'] print(source) # the target data frame df = pd.DataFrame(columns", "= today - one_week week_ago = datetime.datetime.combine(week, datetime.time(0, 0)) for filename in os.listdir(path):", "'99' }) df['cnt_confirmed'] = source['v2'] df['pct_confirmed'] = list(map(lambda x: x[:-1], source['v3'].values)) df['date_stamp'] =", "= [ 'date_stamp', 'age_group', 'cnt_confirmed', 'pct_confirmed' ] def cleanData(data, fileName): # source data", "__name__ == \"__main__\": path = os.path # Loop over the files within the", "append to it. if path.exists(f\"./data/us-tn/co-knox/covid_age/latest.csv\"): df.to_csv(f\"./data/us-tn/co-knox/covid_age/latest.csv\", mode='a', header=False, index=False) else: df.to_csv(f\"./data/us-tn/co-knox/covid_age/latest.csv\", index=False) deleteFiles('./data/us-tn/co-knox/covid_age/raw')", "filename) df.to_csv(f\"./data/us-tn/co-knox/covid_age/clean/{filename}\", index=False) # if there is no aggregate file create one, otherwise", "one_week = datetime.timedelta(days=7) week = today - one_week week_ago = datetime.datetime.combine(week, datetime.time(0, 0))", "== False: print(filename) # For each csv file, map the transformed data to", "list(map(lambda x: x[:-1], source['v3'].values)) df['date_stamp'] = fileName[0:-4] # apply data types df['date_stamp'] =", "in os.listdir(path): if(filename.endswith('.csv')): newFilename = filename.replace('.csv', ''); filedate = datetime.datetime.strptime(newFilename, '%Y-%m-%d') if(filedate <", "source.columns = ['v1','v2','v3'] print(source) # the target data frame df = pd.DataFrame(columns =", "# For each csv file, map the transformed data to its respective file", "'51-60': '51', '61-70': '61', '71-80': '71', '81-90': '81', '90+': '91', 'Age Unknown': '99'", "source['v3'].values)) df['date_stamp'] = fileName[0:-4] # apply data types df['date_stamp'] = pd.to_datetime(df['date_stamp']).dt.strftime('%Y-%m-%d') df['cnt_confirmed'] =", "= cleanData(data, filename) df.to_csv(f\"./data/us-tn/co-knox/covid_age/clean/{filename}\", index=False) # if there is no aggregate file create", "filename in sorted(os.listdir('./data/us-tn/co-knox/covid_age/raw')): if filename.endswith('.csv') and path.exists(f\"./data/us-tn/co-knox/covid_age/clean/{filename}\") == False: print(filename) # For each", "= pd.read_csv(f\"./data/us-tn/co-knox/covid_age/raw/{filename}\") df = cleanData(data, filename) df.to_csv(f\"./data/us-tn/co-knox/covid_age/clean/{filename}\", index=False) # if there is no", "frame df = pd.DataFrame(columns = variables) df['age_group'] = source['v1'].map({ '0-10':'00', '11-20': '11', '21-30':", "- one_week week_ago = datetime.datetime.combine(week, datetime.time(0, 0)) for filename in os.listdir(path): if(filename.endswith('.csv')): newFilename", "the files within the folder for filename in sorted(os.listdir('./data/us-tn/co-knox/covid_age/raw')): if filename.endswith('.csv') and path.exists(f\"./data/us-tn/co-knox/covid_age/clean/{filename}\")", "there is no aggregate file create one, otherwise append to it. if path.exists(f\"./data/us-tn/co-knox/covid_age/latest.csv\"):", "to it. if path.exists(f\"./data/us-tn/co-knox/covid_age/latest.csv\"): df.to_csv(f\"./data/us-tn/co-knox/covid_age/latest.csv\", mode='a', header=False, index=False) else: df.to_csv(f\"./data/us-tn/co-knox/covid_age/latest.csv\", index=False) deleteFiles('./data/us-tn/co-knox/covid_age/raw') deleteFiles('./data/us-tn/co-knox/covid_age/clean')", "variables = [ 'date_stamp', 'age_group', 'cnt_confirmed', 'pct_confirmed' ] def cleanData(data, fileName): # source", "def cleanData(data, fileName): # source data frame from csv file source = pd.DataFrame(data)", "datetime.datetime.combine(week, datetime.time(0, 0)) for filename in os.listdir(path): if(filename.endswith('.csv')): newFilename = filename.replace('.csv', ''); filedate", "data frame from csv file source = pd.DataFrame(data) source.columns = ['v1','v2','v3'] print(source) #", "filedate = datetime.datetime.strptime(newFilename, '%Y-%m-%d') if(filedate < week_ago): print('removing files that are more than", "def deleteFiles(path): today = datetime.date.today(); one_week = datetime.timedelta(days=7) week = today - one_week", "create one, otherwise append to it. if path.exists(f\"./data/us-tn/co-knox/covid_age/latest.csv\"): df.to_csv(f\"./data/us-tn/co-knox/covid_age/latest.csv\", mode='a', header=False, index=False) else:", "csv file, map the transformed data to its respective file in the harvested", "deleteFiles(path): today = datetime.date.today(); one_week = datetime.timedelta(days=7) week = today - one_week week_ago", "import os import math import pandas as pd import datetime variables = [", "harvested folder data = pd.read_csv(f\"./data/us-tn/co-knox/covid_age/raw/{filename}\") df = cleanData(data, filename) df.to_csv(f\"./data/us-tn/co-knox/covid_age/clean/{filename}\", index=False) # if", "= datetime.date.today(); one_week = datetime.timedelta(days=7) week = today - one_week week_ago = datetime.datetime.combine(week,", "'91', 'Age Unknown': '99' }) df['cnt_confirmed'] = source['v2'] df['pct_confirmed'] = list(map(lambda x: x[:-1],", "df['pct_confirmed'] = list(map(lambda x: x[:-1], source['v3'].values)) df['date_stamp'] = fileName[0:-4] # apply data types", "fileName[0:-4] # apply data types df['date_stamp'] = pd.to_datetime(df['date_stamp']).dt.strftime('%Y-%m-%d') df['cnt_confirmed'] = df['cnt_confirmed'].astype(pd.Int32Dtype()) return df", "'cnt_confirmed', 'pct_confirmed' ] def cleanData(data, fileName): # source data frame from csv file", "df['cnt_confirmed'] = source['v2'] df['pct_confirmed'] = list(map(lambda x: x[:-1], source['v3'].values)) df['date_stamp'] = fileName[0:-4] #", "] def cleanData(data, fileName): # source data frame from csv file source =", "= source['v2'] df['pct_confirmed'] = list(map(lambda x: x[:-1], source['v3'].values)) df['date_stamp'] = fileName[0:-4] # apply", "os.path # Loop over the files within the folder for filename in sorted(os.listdir('./data/us-tn/co-knox/covid_age/raw')):", "path = os.path # Loop over the files within the folder for filename", "from csv file source = pd.DataFrame(data) source.columns = ['v1','v2','v3'] print(source) # the target", "\"__main__\": path = os.path # Loop over the files within the folder for", "than a week old: ',path,'/',filename) os.remove(f\"{path}/{filename}\") return None if __name__ == \"__main__\": path", "= datetime.datetime.strptime(newFilename, '%Y-%m-%d') if(filedate < week_ago): print('removing files that are more than a", "0)) for filename in os.listdir(path): if(filename.endswith('.csv')): newFilename = filename.replace('.csv', ''); filedate = datetime.datetime.strptime(newFilename,", "the transformed data to its respective file in the harvested folder data =", "print(source) # the target data frame df = pd.DataFrame(columns = variables) df['age_group'] =", "'61', '71-80': '71', '81-90': '81', '90+': '91', 'Age Unknown': '99' }) df['cnt_confirmed'] =", "import datetime variables = [ 'date_stamp', 'age_group', 'cnt_confirmed', 'pct_confirmed' ] def cleanData(data, fileName):", "'date_stamp', 'age_group', 'cnt_confirmed', 'pct_confirmed' ] def cleanData(data, fileName): # source data frame from", "frame from csv file source = pd.DataFrame(data) source.columns = ['v1','v2','v3'] print(source) # the", "os.listdir(path): if(filename.endswith('.csv')): newFilename = filename.replace('.csv', ''); filedate = datetime.datetime.strptime(newFilename, '%Y-%m-%d') if(filedate < week_ago):", "the folder for filename in sorted(os.listdir('./data/us-tn/co-knox/covid_age/raw')): if filename.endswith('.csv') and path.exists(f\"./data/us-tn/co-knox/covid_age/clean/{filename}\") == False: print(filename)", "math import pandas as pd import datetime variables = [ 'date_stamp', 'age_group', 'cnt_confirmed',", "return df def deleteFiles(path): today = datetime.date.today(); one_week = datetime.timedelta(days=7) week = today", "data = pd.read_csv(f\"./data/us-tn/co-knox/covid_age/raw/{filename}\") df = cleanData(data, filename) df.to_csv(f\"./data/us-tn/co-knox/covid_age/clean/{filename}\", index=False) # if there is", "= pd.DataFrame(data) source.columns = ['v1','v2','v3'] print(source) # the target data frame df =", "x[:-1], source['v3'].values)) df['date_stamp'] = fileName[0:-4] # apply data types df['date_stamp'] = pd.to_datetime(df['date_stamp']).dt.strftime('%Y-%m-%d') df['cnt_confirmed']", "df['age_group'] = source['v1'].map({ '0-10':'00', '11-20': '11', '21-30': '21', '31-40': '31', '41-50': '41', '51-60':", "more than a week old: ',path,'/',filename) os.remove(f\"{path}/{filename}\") return None if __name__ == \"__main__\":", "pd.read_csv(f\"./data/us-tn/co-knox/covid_age/raw/{filename}\") df = cleanData(data, filename) df.to_csv(f\"./data/us-tn/co-knox/covid_age/clean/{filename}\", index=False) # if there is no aggregate", "fileName): # source data frame from csv file source = pd.DataFrame(data) source.columns =", "datetime.time(0, 0)) for filename in os.listdir(path): if(filename.endswith('.csv')): newFilename = filename.replace('.csv', ''); filedate =", "== \"__main__\": path = os.path # Loop over the files within the folder", "file in the harvested folder data = pd.read_csv(f\"./data/us-tn/co-knox/covid_age/raw/{filename}\") df = cleanData(data, filename) df.to_csv(f\"./data/us-tn/co-knox/covid_age/clean/{filename}\",", "'41-50': '41', '51-60': '51', '61-70': '61', '71-80': '71', '81-90': '81', '90+': '91', 'Age", "data frame df = pd.DataFrame(columns = variables) df['age_group'] = source['v1'].map({ '0-10':'00', '11-20': '11',", "= df['cnt_confirmed'].astype(pd.Int32Dtype()) return df def deleteFiles(path): today = datetime.date.today(); one_week = datetime.timedelta(days=7) week", "files within the folder for filename in sorted(os.listdir('./data/us-tn/co-knox/covid_age/raw')): if filename.endswith('.csv') and path.exists(f\"./data/us-tn/co-knox/covid_age/clean/{filename}\") ==", "df.to_csv(f\"./data/us-tn/co-knox/covid_age/clean/{filename}\", index=False) # if there is no aggregate file create one, otherwise append", "Unknown': '99' }) df['cnt_confirmed'] = source['v2'] df['pct_confirmed'] = list(map(lambda x: x[:-1], source['v3'].values)) df['date_stamp']", "in sorted(os.listdir('./data/us-tn/co-knox/covid_age/raw')): if filename.endswith('.csv') and path.exists(f\"./data/us-tn/co-knox/covid_age/clean/{filename}\") == False: print(filename) # For each csv", "datetime.timedelta(days=7) week = today - one_week week_ago = datetime.datetime.combine(week, datetime.time(0, 0)) for filename", "the target data frame df = pd.DataFrame(columns = variables) df['age_group'] = source['v1'].map({ '0-10':'00',", "datetime variables = [ 'date_stamp', 'age_group', 'cnt_confirmed', 'pct_confirmed' ] def cleanData(data, fileName): #", "datetime.datetime.strptime(newFilename, '%Y-%m-%d') if(filedate < week_ago): print('removing files that are more than a week", "= fileName[0:-4] # apply data types df['date_stamp'] = pd.to_datetime(df['date_stamp']).dt.strftime('%Y-%m-%d') df['cnt_confirmed'] = df['cnt_confirmed'].astype(pd.Int32Dtype()) return", "[ 'date_stamp', 'age_group', 'cnt_confirmed', 'pct_confirmed' ] def cleanData(data, fileName): # source data frame", "source['v2'] df['pct_confirmed'] = list(map(lambda x: x[:-1], source['v3'].values)) df['date_stamp'] = fileName[0:-4] # apply data", "its respective file in the harvested folder data = pd.read_csv(f\"./data/us-tn/co-knox/covid_age/raw/{filename}\") df = cleanData(data,", "each csv file, map the transformed data to its respective file in the", "pd import datetime variables = [ 'date_stamp', 'age_group', 'cnt_confirmed', 'pct_confirmed' ] def cleanData(data,", "os.remove(f\"{path}/{filename}\") return None if __name__ == \"__main__\": path = os.path # Loop over", "False: print(filename) # For each csv file, map the transformed data to its", "source data frame from csv file source = pd.DataFrame(data) source.columns = ['v1','v2','v3'] print(source)", "a week old: ',path,'/',filename) os.remove(f\"{path}/{filename}\") return None if __name__ == \"__main__\": path =", "data to its respective file in the harvested folder data = pd.read_csv(f\"./data/us-tn/co-knox/covid_age/raw/{filename}\") df", "'11-20': '11', '21-30': '21', '31-40': '31', '41-50': '41', '51-60': '51', '61-70': '61', '71-80':", "week = today - one_week week_ago = datetime.datetime.combine(week, datetime.time(0, 0)) for filename in", "= ['v1','v2','v3'] print(source) # the target data frame df = pd.DataFrame(columns = variables)", "'81-90': '81', '90+': '91', 'Age Unknown': '99' }) df['cnt_confirmed'] = source['v2'] df['pct_confirmed'] =", "newFilename = filename.replace('.csv', ''); filedate = datetime.datetime.strptime(newFilename, '%Y-%m-%d') if(filedate < week_ago): print('removing files", "df = cleanData(data, filename) df.to_csv(f\"./data/us-tn/co-knox/covid_age/clean/{filename}\", index=False) # if there is no aggregate file", "}) df['cnt_confirmed'] = source['v2'] df['pct_confirmed'] = list(map(lambda x: x[:-1], source['v3'].values)) df['date_stamp'] = fileName[0:-4]", "if there is no aggregate file create one, otherwise append to it. if", "import math import pandas as pd import datetime variables = [ 'date_stamp', 'age_group',", "# the target data frame df = pd.DataFrame(columns = variables) df['age_group'] = source['v1'].map({", "sorted(os.listdir('./data/us-tn/co-knox/covid_age/raw')): if filename.endswith('.csv') and path.exists(f\"./data/us-tn/co-knox/covid_age/clean/{filename}\") == False: print(filename) # For each csv file,", "cleanData(data, fileName): # source data frame from csv file source = pd.DataFrame(data) source.columns", "today = datetime.date.today(); one_week = datetime.timedelta(days=7) week = today - one_week week_ago =", "types df['date_stamp'] = pd.to_datetime(df['date_stamp']).dt.strftime('%Y-%m-%d') df['cnt_confirmed'] = df['cnt_confirmed'].astype(pd.Int32Dtype()) return df def deleteFiles(path): today =", "source = pd.DataFrame(data) source.columns = ['v1','v2','v3'] print(source) # the target data frame df", "= variables) df['age_group'] = source['v1'].map({ '0-10':'00', '11-20': '11', '21-30': '21', '31-40': '31', '41-50':", "'0-10':'00', '11-20': '11', '21-30': '21', '31-40': '31', '41-50': '41', '51-60': '51', '61-70': '61',", "'71-80': '71', '81-90': '81', '90+': '91', 'Age Unknown': '99' }) df['cnt_confirmed'] = source['v2']", "map the transformed data to its respective file in the harvested folder data", "no aggregate file create one, otherwise append to it. if path.exists(f\"./data/us-tn/co-knox/covid_age/latest.csv\"): df.to_csv(f\"./data/us-tn/co-knox/covid_age/latest.csv\", mode='a',", "'41', '51-60': '51', '61-70': '61', '71-80': '71', '81-90': '81', '90+': '91', 'Age Unknown':", "For each csv file, map the transformed data to its respective file in", "'Age Unknown': '99' }) df['cnt_confirmed'] = source['v2'] df['pct_confirmed'] = list(map(lambda x: x[:-1], source['v3'].values))", "'21-30': '21', '31-40': '31', '41-50': '41', '51-60': '51', '61-70': '61', '71-80': '71', '81-90':", "if filename.endswith('.csv') and path.exists(f\"./data/us-tn/co-knox/covid_age/clean/{filename}\") == False: print(filename) # For each csv file, map", "within the folder for filename in sorted(os.listdir('./data/us-tn/co-knox/covid_age/raw')): if filename.endswith('.csv') and path.exists(f\"./data/us-tn/co-knox/covid_age/clean/{filename}\") == False:", "index=False) # if there is no aggregate file create one, otherwise append to", "file source = pd.DataFrame(data) source.columns = ['v1','v2','v3'] print(source) # the target data frame", "source['v1'].map({ '0-10':'00', '11-20': '11', '21-30': '21', '31-40': '31', '41-50': '41', '51-60': '51', '61-70':", "target data frame df = pd.DataFrame(columns = variables) df['age_group'] = source['v1'].map({ '0-10':'00', '11-20':", "',path,'/',filename) os.remove(f\"{path}/{filename}\") return None if __name__ == \"__main__\": path = os.path # Loop", "filename in os.listdir(path): if(filename.endswith('.csv')): newFilename = filename.replace('.csv', ''); filedate = datetime.datetime.strptime(newFilename, '%Y-%m-%d') if(filedate", "'90+': '91', 'Age Unknown': '99' }) df['cnt_confirmed'] = source['v2'] df['pct_confirmed'] = list(map(lambda x:", "for filename in sorted(os.listdir('./data/us-tn/co-knox/covid_age/raw')): if filename.endswith('.csv') and path.exists(f\"./data/us-tn/co-knox/covid_age/clean/{filename}\") == False: print(filename) # For", "'61-70': '61', '71-80': '71', '81-90': '81', '90+': '91', 'Age Unknown': '99' }) df['cnt_confirmed']", "'%Y-%m-%d') if(filedate < week_ago): print('removing files that are more than a week old:", "are more than a week old: ',path,'/',filename) os.remove(f\"{path}/{filename}\") return None if __name__ ==", "cleanData(data, filename) df.to_csv(f\"./data/us-tn/co-knox/covid_age/clean/{filename}\", index=False) # if there is no aggregate file create one,", "'51', '61-70': '61', '71-80': '71', '81-90': '81', '90+': '91', 'Age Unknown': '99' })", "'81', '90+': '91', 'Age Unknown': '99' }) df['cnt_confirmed'] = source['v2'] df['pct_confirmed'] = list(map(lambda", "df['cnt_confirmed'] = df['cnt_confirmed'].astype(pd.Int32Dtype()) return df def deleteFiles(path): today = datetime.date.today(); one_week = datetime.timedelta(days=7)", "< week_ago): print('removing files that are more than a week old: ',path,'/',filename) os.remove(f\"{path}/{filename}\")", "None if __name__ == \"__main__\": path = os.path # Loop over the files", "df['date_stamp'] = fileName[0:-4] # apply data types df['date_stamp'] = pd.to_datetime(df['date_stamp']).dt.strftime('%Y-%m-%d') df['cnt_confirmed'] = df['cnt_confirmed'].astype(pd.Int32Dtype())", "csv file source = pd.DataFrame(data) source.columns = ['v1','v2','v3'] print(source) # the target data", "file create one, otherwise append to it. if path.exists(f\"./data/us-tn/co-knox/covid_age/latest.csv\"): df.to_csv(f\"./data/us-tn/co-knox/covid_age/latest.csv\", mode='a', header=False, index=False)", "'21', '31-40': '31', '41-50': '41', '51-60': '51', '61-70': '61', '71-80': '71', '81-90': '81',", "data types df['date_stamp'] = pd.to_datetime(df['date_stamp']).dt.strftime('%Y-%m-%d') df['cnt_confirmed'] = df['cnt_confirmed'].astype(pd.Int32Dtype()) return df def deleteFiles(path): today", "apply data types df['date_stamp'] = pd.to_datetime(df['date_stamp']).dt.strftime('%Y-%m-%d') df['cnt_confirmed'] = df['cnt_confirmed'].astype(pd.Int32Dtype()) return df def deleteFiles(path):", "filename.replace('.csv', ''); filedate = datetime.datetime.strptime(newFilename, '%Y-%m-%d') if(filedate < week_ago): print('removing files that are", "over the files within the folder for filename in sorted(os.listdir('./data/us-tn/co-knox/covid_age/raw')): if filename.endswith('.csv') and", "old: ',path,'/',filename) os.remove(f\"{path}/{filename}\") return None if __name__ == \"__main__\": path = os.path #", "pd.to_datetime(df['date_stamp']).dt.strftime('%Y-%m-%d') df['cnt_confirmed'] = df['cnt_confirmed'].astype(pd.Int32Dtype()) return df def deleteFiles(path): today = datetime.date.today(); one_week =", "= filename.replace('.csv', ''); filedate = datetime.datetime.strptime(newFilename, '%Y-%m-%d') if(filedate < week_ago): print('removing files that", "one, otherwise append to it. if path.exists(f\"./data/us-tn/co-knox/covid_age/latest.csv\"): df.to_csv(f\"./data/us-tn/co-knox/covid_age/latest.csv\", mode='a', header=False, index=False) else: df.to_csv(f\"./data/us-tn/co-knox/covid_age/latest.csv\",", "if __name__ == \"__main__\": path = os.path # Loop over the files within", "= os.path # Loop over the files within the folder for filename in", "# source data frame from csv file source = pd.DataFrame(data) source.columns = ['v1','v2','v3']", "= list(map(lambda x: x[:-1], source['v3'].values)) df['date_stamp'] = fileName[0:-4] # apply data types df['date_stamp']", "today - one_week week_ago = datetime.datetime.combine(week, datetime.time(0, 0)) for filename in os.listdir(path): if(filename.endswith('.csv')):", "= pd.to_datetime(df['date_stamp']).dt.strftime('%Y-%m-%d') df['cnt_confirmed'] = df['cnt_confirmed'].astype(pd.Int32Dtype()) return df def deleteFiles(path): today = datetime.date.today(); one_week", "'age_group', 'cnt_confirmed', 'pct_confirmed' ] def cleanData(data, fileName): # source data frame from csv", "datetime.date.today(); one_week = datetime.timedelta(days=7) week = today - one_week week_ago = datetime.datetime.combine(week, datetime.time(0,", "files that are more than a week old: ',path,'/',filename) os.remove(f\"{path}/{filename}\") return None if", "print(filename) # For each csv file, map the transformed data to its respective", "df def deleteFiles(path): today = datetime.date.today(); one_week = datetime.timedelta(days=7) week = today -", "week_ago): print('removing files that are more than a week old: ',path,'/',filename) os.remove(f\"{path}/{filename}\") return", "variables) df['age_group'] = source['v1'].map({ '0-10':'00', '11-20': '11', '21-30': '21', '31-40': '31', '41-50': '41',", "'71', '81-90': '81', '90+': '91', 'Age Unknown': '99' }) df['cnt_confirmed'] = source['v2'] df['pct_confirmed']", "is no aggregate file create one, otherwise append to it. if path.exists(f\"./data/us-tn/co-knox/covid_age/latest.csv\"): df.to_csv(f\"./data/us-tn/co-knox/covid_age/latest.csv\",", "file, map the transformed data to its respective file in the harvested folder", "= datetime.datetime.combine(week, datetime.time(0, 0)) for filename in os.listdir(path): if(filename.endswith('.csv')): newFilename = filename.replace('.csv', '');", "folder for filename in sorted(os.listdir('./data/us-tn/co-knox/covid_age/raw')): if filename.endswith('.csv') and path.exists(f\"./data/us-tn/co-knox/covid_age/clean/{filename}\") == False: print(filename) #", "os import math import pandas as pd import datetime variables = [ 'date_stamp',", "aggregate file create one, otherwise append to it. if path.exists(f\"./data/us-tn/co-knox/covid_age/latest.csv\"): df.to_csv(f\"./data/us-tn/co-knox/covid_age/latest.csv\", mode='a', header=False,", "one_week week_ago = datetime.datetime.combine(week, datetime.time(0, 0)) for filename in os.listdir(path): if(filename.endswith('.csv')): newFilename =" ]
[ "distribution \"\"\" enc = self.enc(inpt, **kwargs) mu, log_std = torch.chunk(enc, 2, dim=1) std", "the input space Args: inpt ([tensor]): [Latent space sample] Returns: [rec]: [Encoded latent", "maps in the layer]. Defaults to (16, 64, 256, 1024). to_1x1 (bool, optional):", "True, then the last conv layer goes to a latent dimesion is a", "= torch.chunk(enc, 2, dim=1) std = torch.exp(log_std) return mu, std def decode(self, inpt,", "to nn.ConvTranspose2d. tconv_params ([dict], optional): [Init parameters for the conv operation]. Defaults to", "operation]. Defaults to None. block_op ([torch.nn.Module], optional): [Block operation used for each feature", "= self.enc(inpt, **kwargs) return enc def decode(self, inpt, **kwargs): \"\"\"Decodes a latent space", "True. conv_op ([torch.nn.Module], optional): [Convolutioon operation used in the encoder to downsample to", "[Actiovation Operation/ Non-linearity (e.g. ReLU, Sigmoid,...) -> see ConvModule]. Defaults to nn.LeakyReLU. activation_params", "): \"\"\"Basic AE build up of a symetric BasicEncoder (Encoder) and BasicGenerator (Decoder)", "InstanceNorm,...) -> see ConvModule]. Defaults to nn.BatchNorm2d. normalization_params ([dict], optional): [Init parameters for", "Defaults to nn.BatchNorm2d. normalization_params ([dict], optional): [Init parameters for the normalization operation]. Defaults", "inpt, sample=True, no_dist=False, **kwargs): y1 = self.enc(inpt, **kwargs) mu, log_std = torch.chunk(y1, 2,", "[If True, then the last conv layer goes to a latent dimesion is", "tconv_params=None, normalization_op=None, normalization_params=None, activation_op=torch.nn.LeakyReLU, activation_params=None, block_op=None, block_params=None, *args, **kwargs ): \"\"\"Basic AE build", "([tensor]): The input to encode Returns: mu : The mean used to parameterized", "bias=False). tconv_op ([torch.nn.Module], optional): [Upsampling/ Transposed Conv operation used in the decoder to", "Defaults to None. \"\"\" super(AE, self).__init__() input_size_enc = list(input_size) input_size_dec = list(input_size) self.enc", "format CxHxW): z_dim (int, optional): [description]. Dimension of the latent / Input dimension", "**kwargs): \"\"\"Encodes a input sample to a latent space sample Args: inpt ([tensor]):", "space \"\"\" enc = self.enc(inpt, **kwargs) return enc def decode(self, inpt, **kwargs): \"\"\"Decodes", "a latent space sample, used the generative model (decode = mu_{gen}(z) as used", "[type]: [description] \"\"\" x_rec = self.dec(inpt, **kwargs) return x_rec class AE(torch.nn.Module): def __init__(", "sample, used the generative model (decode = mu_{gen}(z) as used in p(x|z) =", "([torch.nn.Module], optional): [Upsampling/ Transposed Conv operation used in the decoder to upsample to", "in p(x|z) = N(x | mu_{gen}(z), 1) ). Args: inpt ([type]): A sample", "defines the number of feature maps in the layer]. Defaults to (16, 64,", "used in the encoder to downsample to a new level/ featuremap size]. Defaults", "std def decode(self, inpt, **kwargs): \"\"\"Decodes a latent space sample, used the generative", "y1 = self.enc(inpt, **kwargs) x_rec = self.dec(y1) return x_rec def encode(self, inpt, **kwargs):", "a new level/ featuremap size]. Defaults to nn.ConvTranspose2d. tconv_params ([dict], optional): [Init parameters", "to parameterized a Normal distribution \"\"\" enc = self.enc(inpt, **kwargs) mu, log_std =", "block operation]. Defaults to None. \"\"\" super(VAE, self).__init__() input_size_enc = list(input_size) input_size_dec =", "import torch.distributions as dist from example_algos.models.nets import BasicEncoder, BasicGenerator class VAE(torch.nn.Module): def __init__(", "a latent space sample back to the input space Args: inpt ([tensor]): [Latent", "decode Returns: [type]: [description] \"\"\" x_rec = self.dec(inpt, **kwargs) return x_rec class AE(torch.nn.Module):", "sample Args: inpt ([tensor]): Input sample Returns: enc: Encoded input sample in the", "block_op=None, block_params=None, *args, **kwargs ): \"\"\"Basic VAE build up of a symetric BasicEncoder", "block_op ([torch.nn.Module], optional): [Block operation used for each feature map size after each", "= torch.exp(log_std) z_dist = dist.Normal(mu, std) if sample: z_sample = z_dist.rsample() else: z_sample", "latent space to decode Returns: [type]: [description] \"\"\" x_rec = self.dec(inpt, **kwargs) return", "to_1x1=True, conv_op=torch.nn.Conv2d, conv_params=None, tconv_op=torch.nn.ConvTranspose2d, tconv_params=None, normalization_op=None, normalization_params=None, activation_op=torch.nn.LeakyReLU, activation_params=None, block_op=None, block_params=None, *args, **kwargs", "a input sample to a latent space sample Args: inpt ([tensor]): Input sample", "the layer]. Defaults to (16, 64, 256, 1024). to_1x1 (bool, optional): [If True,", "BasicEncoder, BasicGenerator class VAE(torch.nn.Module): def __init__( self, input_size, z_dim=256, fmap_sizes=(16, 64, 256, 1024),", "def __init__( self, input_size, z_dim=256, fmap_sizes=(16, 64, 256, 1024), to_1x1=True, conv_op=torch.nn.Conv2d, conv_params=None, tconv_op=torch.nn.ConvTranspose2d,", "padding=1, bias=False). normalization_op ([torch.nn.Module], optional): [Normalization Operation (e.g. BatchNorm, InstanceNorm,...) -> see ConvModule].", "to_1x1=to_1x1, ) self.dec = BasicGenerator( input_size=input_size_dec, fmap_sizes=fmap_sizes[::-1], z_dim=z_dim, upsample_op=tconv_op, conv_params=tconv_params, normalization_op=normalization_op, normalization_params=normalization_params, activation_op=activation_op,", "layer goes to a latent dimesion is a z_dim x 1 x 1", "z_dist def encode(self, inpt, **kwargs): \"\"\"Encodes a sample and returns the paramters for", "parameterized a Normal distribution std: The standard deviation used to parameterized a Normal", "activation_params=None, block_op=None, block_params=None, *args, **kwargs ): \"\"\"Basic VAE build up of a symetric", "fmap_sizes=fmap_sizes[::-1], z_dim=z_dim, upsample_op=tconv_op, conv_params=tconv_params, normalization_op=normalization_op, normalization_params=normalization_params, activation_op=activation_op, activation_params=activation_params, block_op=block_op, block_params=block_params, to_1x1=to_1x1, ) self.hidden_size", "normalization operation]. Defaults to None. activation_op ([torch.nn.Module], optional): [Actiovation Operation/ Non-linearity (e.g. ReLU,", "parameters for the block operation]. Defaults to None. \"\"\" super(VAE, self).__init__() input_size_enc =", "a latent dimesion is a z_dim x 1 x 1 vector (similar to", "to upsample to a new level/ featuremap size]. Defaults to nn.ConvTranspose2d. tconv_params ([dict],", "Operation (e.g. BatchNorm, InstanceNorm,...) -> see ConvModule]. Defaults to nn.BatchNorm2d. normalization_params ([dict], optional):", "A sample from the latent space to decode Returns: [type]: [description] \"\"\" x_rec", "**kwargs) x_rec = self.dec(y1) return x_rec def encode(self, inpt, **kwargs): \"\"\"Encodes a input", "([torch.nn.Module], optional): [Convolutioon operation used in the encoder to downsample to a new", "the conv operation]. Defaults to dict(kernel_size=3, stride=2, padding=1, bias=False). normalization_op ([torch.nn.Module], optional): [Normalization", "conv_params=None, tconv_op=torch.nn.ConvTranspose2d, tconv_params=None, normalization_op=None, normalization_params=None, activation_op=torch.nn.LeakyReLU, activation_params=None, block_op=None, block_params=None, *args, **kwargs ): \"\"\"Basic", "conv_params given conv-kernel-size) ]. Defaults to True. conv_op ([torch.nn.Module], optional): [Convolutioon operation used", "number of feature maps in the layer]. Defaults to (16, 64, 256, 1024).", "tconv_op ([torch.nn.Module], optional): [Upsampling/ Transposed Conv operation used in the decoder to upsample", "return enc def decode(self, inpt, **kwargs): \"\"\"Decodes a latent space sample back to", "64, 256, 1024), to_1x1=True, conv_op=torch.nn.Conv2d, conv_params=None, tconv_op=torch.nn.ConvTranspose2d, tconv_params=None, normalization_op=None, normalization_params=None, activation_op=torch.nn.LeakyReLU, activation_params=None, block_op=None,", "block_params=block_params, to_1x1=to_1x1, ) self.hidden_size = self.enc.output_size def forward(self, inpt, **kwargs): y1 = self.enc(inpt,", "the block operation]. Defaults to None. \"\"\" super(AE, self).__init__() input_size_enc = list(input_size) input_size_dec", "Args: inpt ([type]): A sample from the latent space to decode Returns: [type]:", "[Latent space sample] Returns: [rec]: [Encoded latent sample back in the input space]", "[Init parameters for the activation operation]. Defaults to None. block_op ([torch.nn.Module], optional): [Block", "([dict], optional): [Init parameters for the activation operation]. Defaults to None. block_op ([torch.nn.Module],", "def encode(self, inpt, **kwargs): \"\"\"Encodes a sample and returns the paramters for the", "returns the paramters for the approx inference dist. (Normal) Args: inpt ([tensor]): The", "**kwargs): \"\"\"Decodes a latent space sample back to the input space Args: inpt", "used to parameterized a Normal distribution std: The standard deviation used to parameterized", "input sample in the latent space \"\"\" enc = self.enc(inpt, **kwargs) return enc", "as dist from example_algos.models.nets import BasicEncoder, BasicGenerator class VAE(torch.nn.Module): def __init__( self, input_size,", "latent sample back in the input space] \"\"\" rec = self.dec(inpt, **kwargs) return", "self, input_size, z_dim=256, fmap_sizes=(16, 64, 256, 1024), to_1x1=True, conv_op=torch.nn.Conv2d, conv_params=None, tconv_op=torch.nn.ConvTranspose2d, tconv_params=None, normalization_op=None,", "BasicEncoder( input_size=input_size_enc, fmap_sizes=fmap_sizes, z_dim=z_dim, conv_op=conv_op, conv_params=conv_params, normalization_op=normalization_op, normalization_params=normalization_params, activation_op=activation_op, activation_params=activation_params, block_op=block_op, block_params=block_params, to_1x1=to_1x1,", "model (decode = mu_{gen}(z) as used in p(x|z) = N(x | mu_{gen}(z), 1)", "x W, uses the in the conv_params given conv-kernel-size) ]. Defaults to True.", "block operation]. Defaults to None. \"\"\" super(AE, self).__init__() input_size_enc = list(input_size) input_size_dec =", ") self.hidden_size = self.enc.output_size def forward(self, inpt, sample=True, no_dist=False, **kwargs): y1 = self.enc(inpt,", "feature maps in the layer]. Defaults to (16, 64, 256, 1024). to_1x1 (bool,", "x_rec = self.dec(z_sample) if no_dist: return x_rec else: return x_rec, z_dist def encode(self,", "to be 1x1 (z_dim x H x W, uses the in the conv_params", "to_1x1=to_1x1, ) self.hidden_size = self.enc.output_size def forward(self, inpt, **kwargs): y1 = self.enc(inpt, **kwargs)", "<gh_stars>10-100 import numpy as np import torch import torch.distributions as dist from example_algos.models.nets", "featuremap size]. Defaults to nn.ConvTranspose2d. tconv_params ([dict], optional): [Init parameters for the conv", "Defaults to nn.LeakyReLU. activation_params ([dict], optional): [Init parameters for the activation operation]. Defaults", "inpt, **kwargs): \"\"\"Decodes a latent space sample back to the input space Args:", "not to be 1x1 (z_dim x H x W, uses the in the", "Args: inpt ([tensor]): The input to encode Returns: mu : The mean used", "**kwargs) mu, log_std = torch.chunk(y1, 2, dim=1) std = torch.exp(log_std) z_dist = dist.Normal(mu,", "input_size=input_size_dec, fmap_sizes=fmap_sizes[::-1], z_dim=z_dim, upsample_op=tconv_op, conv_params=tconv_params, normalization_op=normalization_op, normalization_params=normalization_params, activation_op=activation_op, activation_params=activation_params, block_op=block_op, block_params=block_params, to_1x1=to_1x1, )", "as used in p(x|z) = N(x | mu_{gen}(z), 1) ). Args: inpt ([type]):", "dist from example_algos.models.nets import BasicEncoder, BasicGenerator class VAE(torch.nn.Module): def __init__( self, input_size, z_dim=256,", "conv_op=torch.nn.Conv2d, conv_params=None, tconv_op=torch.nn.ConvTranspose2d, tconv_params=None, normalization_op=None, normalization_params=None, activation_op=torch.nn.LeakyReLU, activation_params=None, block_op=None, block_params=None, *args, **kwargs ):", "tconv_op=torch.nn.ConvTranspose2d, tconv_params=None, normalization_op=None, normalization_params=None, activation_op=torch.nn.LeakyReLU, activation_params=None, block_op=None, block_params=None, *args, **kwargs ): \"\"\"Basic AE", "[Normalization Operation (e.g. BatchNorm, InstanceNorm,...) -> see ConvModule]. Defaults to nn.BatchNorm2d. normalization_params ([dict],", "= list(input_size) input_size_dec = list(input_size) self.enc = BasicEncoder( input_size=input_size_enc, fmap_sizes=fmap_sizes, z_dim=z_dim * 2,", "in format CxHxW): z_dim (int, optional): [description]. Dimension of the latent / Input", "fmap_sizes (tuple, optional): [Defines the Upsampling-Levels of the generator, list/ tuple of ints,", "NoOp. block_params ([dict], optional): [Init parameters for the block operation]. Defaults to None.", "the Upsampling-Levels of the generator, list/ tuple of ints, where each int defines", "sample=True, no_dist=False, **kwargs): y1 = self.enc(inpt, **kwargs) mu, log_std = torch.chunk(y1, 2, dim=1)", "space sample Args: inpt ([tensor]): Input sample Returns: enc: Encoded input sample in", "nn.ConvTranspose2d. tconv_params ([dict], optional): [Init parameters for the conv operation]. Defaults to dict(kernel_size=3,", "space to decode Returns: [type]: [description] \"\"\" x_rec = self.dec(inpt, **kwargs) return x_rec", "for the activation operation]. Defaults to None. block_op ([torch.nn.Module], optional): [Block operation used", "of the latent / Input dimension (C channel-dim). Defaults to 256 fmap_sizes (tuple,", "([dict], optional): [Init parameters for the normalization operation]. Defaults to None. activation_op ([torch.nn.Module],", "z_dim=z_dim, conv_op=conv_op, conv_params=conv_params, normalization_op=normalization_op, normalization_params=normalization_params, activation_op=activation_op, activation_params=activation_params, block_op=block_op, block_params=block_params, to_1x1=to_1x1, ) self.dec =", "([tensor]): [Latent space sample] Returns: [rec]: [Encoded latent sample back in the input", "operation]. Defaults to None. \"\"\" super(VAE, self).__init__() input_size_enc = list(input_size) input_size_dec = list(input_size)", "inpt ([type]): A sample from the latent space to decode Returns: [type]: [description]", "input_size ((int, int, int): Size of the input in format CxHxW): z_dim (int,", "AE(torch.nn.Module): def __init__( self, input_size, z_dim=1024, fmap_sizes=(16, 64, 256, 1024), to_1x1=True, conv_op=torch.nn.Conv2d, conv_params=None,", "*args, **kwargs ): \"\"\"Basic AE build up of a symetric BasicEncoder (Encoder) and", "in the layer]. Defaults to (16, 64, 256, 1024). to_1x1 (bool, optional): [If", "the block operation]. Defaults to None. \"\"\" super(VAE, self).__init__() input_size_enc = list(input_size) input_size_dec", "is a z_dim x 1 x 1 vector (similar to fully connected) or", "(C channel-dim). Defaults to 256 fmap_sizes (tuple, optional): [Defines the Upsampling-Levels of the", "[description] \"\"\" x_rec = self.dec(inpt, **kwargs) return x_rec class AE(torch.nn.Module): def __init__( self,", "used in p(x|z) = N(x | mu_{gen}(z), 1) ). Args: inpt ([type]): A", "z_dist = dist.Normal(mu, std) if sample: z_sample = z_dist.rsample() else: z_sample = mu", "(bool, optional): [If True, then the last conv layer goes to a latent", "= BasicEncoder( input_size=input_size_enc, fmap_sizes=fmap_sizes, z_dim=z_dim, conv_op=conv_op, conv_params=conv_params, normalization_op=normalization_op, normalization_params=normalization_params, activation_op=activation_op, activation_params=activation_params, block_op=block_op, block_params=block_params,", "parameters for the block operation]. Defaults to None. \"\"\" super(AE, self).__init__() input_size_enc =", "/ Input dimension (C channel-dim). Defaults to 256 fmap_sizes (tuple, optional): [Defines the", "inpt ([tensor]): The input to encode Returns: mu : The mean used to", "Dimension of the latent / Input dimension (C channel-dim). Defaults to 256 fmap_sizes", "normalization_op=normalization_op, normalization_params=normalization_params, activation_op=activation_op, activation_params=activation_params, block_op=block_op, block_params=block_params, to_1x1=to_1x1, ) self.hidden_size = self.enc.output_size def forward(self,", "= torch.exp(log_std) return mu, std def decode(self, inpt, **kwargs): \"\"\"Decodes a latent space", "layer]. Defaults to (16, 64, 256, 1024). to_1x1 (bool, optional): [If True, then", "conv_params=conv_params, normalization_op=normalization_op, normalization_params=normalization_params, activation_op=activation_op, activation_params=activation_params, block_op=block_op, block_params=block_params, to_1x1=to_1x1, ) self.dec = BasicGenerator( input_size=input_size_dec,", "list(input_size) input_size_dec = list(input_size) self.enc = BasicEncoder( input_size=input_size_enc, fmap_sizes=fmap_sizes, z_dim=z_dim * 2, conv_op=conv_op,", "used the generative model (decode = mu_{gen}(z) as used in p(x|z) = N(x", "of ints, where each int defines the number of feature maps in the", "self.enc.output_size def forward(self, inpt, sample=True, no_dist=False, **kwargs): y1 = self.enc(inpt, **kwargs) mu, log_std", "new level/ featuremap size]. Defaults to nn.ConvTranspose2d. tconv_params ([dict], optional): [Init parameters for", "nn.LeakyReLU. activation_params ([dict], optional): [Init parameters for the activation operation]. Defaults to None.", "used to parameterized a Normal distribution \"\"\" enc = self.enc(inpt, **kwargs) mu, log_std", "conv_op ([torch.nn.Module], optional): [Convolutioon operation used in the encoder to downsample to a", "padding=1, bias=False). tconv_op ([torch.nn.Module], optional): [Upsampling/ Transposed Conv operation used in the decoder", "to dict(kernel_size=3, stride=2, padding=1, bias=False). normalization_op ([torch.nn.Module], optional): [Normalization Operation (e.g. BatchNorm, InstanceNorm,...)", "= mu_{gen}(z) as used in p(x|z) = N(x | mu_{gen}(z), 1) ). Args:", "input_size_enc = list(input_size) input_size_dec = list(input_size) self.enc = BasicEncoder( input_size=input_size_enc, fmap_sizes=fmap_sizes, z_dim=z_dim *", "[Upsampling/ Transposed Conv operation used in the decoder to upsample to a new", "Defaults to NoOp. block_params ([dict], optional): [Init parameters for the block operation]. Defaults", "= self.enc(inpt, **kwargs) mu, log_std = torch.chunk(enc, 2, dim=1) std = torch.exp(log_std) return", "block_params=block_params, to_1x1=to_1x1, ) self.dec = BasicGenerator( input_size=input_size_dec, fmap_sizes=fmap_sizes[::-1], z_dim=z_dim, upsample_op=tconv_op, conv_params=tconv_params, normalization_op=normalization_op, normalization_params=normalization_params,", "block_params=None, *args, **kwargs ): \"\"\"Basic AE build up of a symetric BasicEncoder (Encoder)", "Returns: [type]: [description] \"\"\" x_rec = self.dec(inpt, **kwargs) return x_rec class AE(torch.nn.Module): def", "return x_rec, z_dist def encode(self, inpt, **kwargs): \"\"\"Encodes a sample and returns the", "ReLU, Sigmoid,...) -> see ConvModule]. Defaults to nn.LeakyReLU. activation_params ([dict], optional): [Init parameters", "optional): [Normalization Operation (e.g. BatchNorm, InstanceNorm,...) -> see ConvModule]. Defaults to nn.BatchNorm2d. normalization_params", "[Init parameters for the block operation]. Defaults to None. \"\"\" super(VAE, self).__init__() input_size_enc", "upsample_op=tconv_op, conv_params=tconv_params, normalization_op=normalization_op, normalization_params=normalization_params, activation_op=activation_op, activation_params=activation_params, block_op=block_op, block_params=block_params, to_1x1=to_1x1, ) self.hidden_size = self.enc.output_size", "Conv operation used in the decoder to upsample to a new level/ featuremap", "input to encode Returns: mu : The mean used to parameterized a Normal", "the latent / Input dimension (C channel-dim). Defaults to 256 fmap_sizes (tuple, optional):", "= list(input_size) self.enc = BasicEncoder( input_size=input_size_enc, fmap_sizes=fmap_sizes, z_dim=z_dim, conv_op=conv_op, conv_params=conv_params, normalization_op=normalization_op, normalization_params=normalization_params, activation_op=activation_op,", "dict(kernel_size=3, stride=2, padding=1, bias=False). normalization_op ([torch.nn.Module], optional): [Normalization Operation (e.g. BatchNorm, InstanceNorm,...) ->", "latent space sample Args: inpt ([tensor]): Input sample Returns: enc: Encoded input sample", "to NoOp. block_params ([dict], optional): [Init parameters for the block operation]. Defaults to", "dimension (C channel-dim). Defaults to 256 fmap_sizes (tuple, optional): [Defines the Upsampling-Levels of", "(z_dim x H x W, uses the in the conv_params given conv-kernel-size) ].", "in the encoder to downsample to a new level/ featuremap size]. Defaults to", "no_dist=False, **kwargs): y1 = self.enc(inpt, **kwargs) mu, log_std = torch.chunk(y1, 2, dim=1) std", "the activation operation]. Defaults to None. block_op ([torch.nn.Module], optional): [Block operation used for", "downsample to a new level/ featuremap size]. Defaults to nn.Conv2d. conv_params ([dict], optional):", "example_algos.models.nets import BasicEncoder, BasicGenerator class VAE(torch.nn.Module): def __init__( self, input_size, z_dim=256, fmap_sizes=(16, 64,", "inpt, **kwargs): y1 = self.enc(inpt, **kwargs) x_rec = self.dec(y1) return x_rec def encode(self,", "**kwargs) return x_rec class AE(torch.nn.Module): def __init__( self, input_size, z_dim=1024, fmap_sizes=(16, 64, 256,", "optional): [Init parameters for the block operation]. Defaults to None. \"\"\" super(VAE, self).__init__()", "(Normal) Args: inpt ([tensor]): The input to encode Returns: mu : The mean", "__init__( self, input_size, z_dim=1024, fmap_sizes=(16, 64, 256, 1024), to_1x1=True, conv_op=torch.nn.Conv2d, conv_params=None, tconv_op=torch.nn.ConvTranspose2d, tconv_params=None,", "std: The standard deviation used to parameterized a Normal distribution \"\"\" enc =", "2, conv_op=conv_op, conv_params=conv_params, normalization_op=normalization_op, normalization_params=normalization_params, activation_op=activation_op, activation_params=activation_params, block_op=block_op, block_params=block_params, to_1x1=to_1x1, ) self.dec =", "allows spatial resolution not to be 1x1 (z_dim x H x W, uses", "to a new level/ featuremap size]. Defaults to nn.ConvTranspose2d. tconv_params ([dict], optional): [Init", "dist. (Normal) Args: inpt ([tensor]): The input to encode Returns: mu : The", "**kwargs) mu, log_std = torch.chunk(enc, 2, dim=1) std = torch.exp(log_std) return mu, std", "the conv operation]. Defaults to dict(kernel_size=3, stride=2, padding=1, bias=False). tconv_op ([torch.nn.Module], optional): [Upsampling/", "stride=2, padding=1, bias=False). tconv_op ([torch.nn.Module], optional): [Upsampling/ Transposed Conv operation used in the", "x_rec = self.dec(inpt, **kwargs) return x_rec class AE(torch.nn.Module): def __init__( self, input_size, z_dim=1024,", "= list(input_size) input_size_dec = list(input_size) self.enc = BasicEncoder( input_size=input_size_enc, fmap_sizes=fmap_sizes, z_dim=z_dim, conv_op=conv_op, conv_params=conv_params,", "dist.Normal(mu, std) if sample: z_sample = z_dist.rsample() else: z_sample = mu x_rec =", "to encode Returns: mu : The mean used to parameterized a Normal distribution", "where each int defines the number of feature maps in the layer]. Defaults", "as np import torch import torch.distributions as dist from example_algos.models.nets import BasicEncoder, BasicGenerator", "BasicGenerator class VAE(torch.nn.Module): def __init__( self, input_size, z_dim=256, fmap_sizes=(16, 64, 256, 1024), to_1x1=True,", "\"\"\" super(AE, self).__init__() input_size_enc = list(input_size) input_size_dec = list(input_size) self.enc = BasicEncoder( input_size=input_size_enc,", "z_dim=1024, fmap_sizes=(16, 64, 256, 1024), to_1x1=True, conv_op=torch.nn.Conv2d, conv_params=None, tconv_op=torch.nn.ConvTranspose2d, tconv_params=None, normalization_op=None, normalization_params=None, activation_op=torch.nn.LeakyReLU,", "return x_rec def encode(self, inpt, **kwargs): \"\"\"Encodes a input sample to a latent", "input_size, z_dim=256, fmap_sizes=(16, 64, 256, 1024), to_1x1=True, conv_op=torch.nn.Conv2d, conv_params=None, tconv_op=torch.nn.ConvTranspose2d, tconv_params=None, normalization_op=None, normalization_params=None,", "x_rec def encode(self, inpt, **kwargs): \"\"\"Encodes a input sample to a latent space", "parameters for the activation operation]. Defaults to None. block_op ([torch.nn.Module], optional): [Block operation", "and returns the paramters for the approx inference dist. (Normal) Args: inpt ([tensor]):", "self.enc(inpt, **kwargs) mu, log_std = torch.chunk(enc, 2, dim=1) std = torch.exp(log_std) return mu,", "[Init parameters for the conv operation]. Defaults to dict(kernel_size=3, stride=2, padding=1, bias=False). normalization_op", "uses the in the conv_params given conv-kernel-size) ]. Defaults to True. conv_op ([torch.nn.Module],", "the in the conv_params given conv-kernel-size) ]. Defaults to True. conv_op ([torch.nn.Module], optional):", "ConvBlock/ ResidualBlock]. Defaults to NoOp. block_params ([dict], optional): [Init parameters for the block", "Defaults to nn.Conv2d. conv_params ([dict], optional): [Init parameters for the conv operation]. Defaults", "if no_dist: return x_rec else: return x_rec, z_dist def encode(self, inpt, **kwargs): \"\"\"Encodes", "of the input in format CxHxW): z_dim (int, optional): [description]. Dimension of the", "BasicEncoder (Encoder) and BasicGenerator (Decoder) Args: input_size ((int, int, int): Size of the", "the number of feature maps in the layer]. Defaults to (16, 64, 256,", "def decode(self, inpt, **kwargs): \"\"\"Decodes a latent space sample back to the input", "size]. Defaults to nn.Conv2d. conv_params ([dict], optional): [Init parameters for the conv operation].", "-> see ConvModule]. Defaults to nn.BatchNorm2d. normalization_params ([dict], optional): [Init parameters for the", "sample back in the input space] \"\"\" rec = self.dec(inpt, **kwargs) return rec", "inpt ([tensor]): [Latent space sample] Returns: [rec]: [Encoded latent sample back in the", "= self.enc.output_size def forward(self, inpt, **kwargs): y1 = self.enc(inpt, **kwargs) x_rec = self.dec(y1)", "log_std = torch.chunk(enc, 2, dim=1) std = torch.exp(log_std) return mu, std def decode(self,", "a z_dim x 1 x 1 vector (similar to fully connected) or if", "normalization_params=normalization_params, activation_op=activation_op, activation_params=activation_params, block_op=block_op, block_params=block_params, to_1x1=to_1x1, ) self.hidden_size = self.enc.output_size def forward(self, inpt,", "self.enc.output_size def forward(self, inpt, **kwargs): y1 = self.enc(inpt, **kwargs) x_rec = self.dec(y1) return", "sample] Returns: [rec]: [Encoded latent sample back in the input space] \"\"\" rec", "forward(self, inpt, sample=True, no_dist=False, **kwargs): y1 = self.enc(inpt, **kwargs) mu, log_std = torch.chunk(y1,", "the input in format CxHxW): z_dim (int, optional): [description]. Dimension of the latent", "Input sample Returns: enc: Encoded input sample in the latent space \"\"\" enc", "up of a symetric BasicEncoder (Encoder) and BasicGenerator (Decoder) Args: input_size ((int, int,", "int, int): Size of the input in format CxHxW): z_dim (int, optional): [description].", "x 1 vector (similar to fully connected) or if False allows spatial resolution", "list(input_size) input_size_dec = list(input_size) self.enc = BasicEncoder( input_size=input_size_enc, fmap_sizes=fmap_sizes, z_dim=z_dim, conv_op=conv_op, conv_params=conv_params, normalization_op=normalization_op,", "forward(self, inpt, **kwargs): y1 = self.enc(inpt, **kwargs) x_rec = self.dec(y1) return x_rec def", "1x1 (z_dim x H x W, uses the in the conv_params given conv-kernel-size)", "input_size=input_size_enc, fmap_sizes=fmap_sizes, z_dim=z_dim * 2, conv_op=conv_op, conv_params=conv_params, normalization_op=normalization_op, normalization_params=normalization_params, activation_op=activation_op, activation_params=activation_params, block_op=block_op, block_params=block_params,", "block_op=block_op, block_params=block_params, to_1x1=to_1x1, ) self.dec = BasicGenerator( input_size=input_size_dec, fmap_sizes=fmap_sizes[::-1], z_dim=z_dim, upsample_op=tconv_op, conv_params=tconv_params, normalization_op=normalization_op,", "the paramters for the approx inference dist. (Normal) Args: inpt ([tensor]): The input", "std = torch.exp(log_std) z_dist = dist.Normal(mu, std) if sample: z_sample = z_dist.rsample() else:", "self.enc = BasicEncoder( input_size=input_size_enc, fmap_sizes=fmap_sizes, z_dim=z_dim, conv_op=conv_op, conv_params=conv_params, normalization_op=normalization_op, normalization_params=normalization_params, activation_op=activation_op, activation_params=activation_params, block_op=block_op,", "normalization_params=None, activation_op=torch.nn.LeakyReLU, activation_params=None, block_op=None, block_params=None, *args, **kwargs ): \"\"\"Basic AE build up of", "block_params ([dict], optional): [Init parameters for the block operation]. Defaults to None. \"\"\"", "Input dimension (C channel-dim). Defaults to 256 fmap_sizes (tuple, optional): [Defines the Upsampling-Levels", "\"\"\" enc = self.enc(inpt, **kwargs) mu, log_std = torch.chunk(enc, 2, dim=1) std =", "= self.dec(inpt, **kwargs) return x_rec class AE(torch.nn.Module): def __init__( self, input_size, z_dim=1024, fmap_sizes=(16,", "| mu_{gen}(z), 1) ). Args: inpt ([type]): A sample from the latent space", "parameters for the conv operation]. Defaults to dict(kernel_size=3, stride=2, padding=1, bias=False). tconv_op ([torch.nn.Module],", "inpt ([tensor]): Input sample Returns: enc: Encoded input sample in the latent space", "paramters for the approx inference dist. (Normal) Args: inpt ([tensor]): The input to", "to None. block_op ([torch.nn.Module], optional): [Block operation used for each feature map size", "latent dimesion is a z_dim x 1 x 1 vector (similar to fully", "to True. conv_op ([torch.nn.Module], optional): [Convolutioon operation used in the encoder to downsample", "the latent space to decode Returns: [type]: [description] \"\"\" x_rec = self.dec(inpt, **kwargs)", "upsample to a new level/ featuremap size]. Defaults to nn.ConvTranspose2d. tconv_params ([dict], optional):", "resolution not to be 1x1 (z_dim x H x W, uses the in", "sample from the latent space to decode Returns: [type]: [description] \"\"\" x_rec =", "input_size_dec = list(input_size) self.enc = BasicEncoder( input_size=input_size_enc, fmap_sizes=fmap_sizes, z_dim=z_dim * 2, conv_op=conv_op, conv_params=conv_params,", "[Encoded latent sample back in the input space] \"\"\" rec = self.dec(inpt, **kwargs)", "Defaults to None. block_op ([torch.nn.Module], optional): [Block operation used for each feature map", "The input to encode Returns: mu : The mean used to parameterized a", "to None. \"\"\" super(AE, self).__init__() input_size_enc = list(input_size) input_size_dec = list(input_size) self.enc =", "level/ featuremap size]. Defaults to nn.ConvTranspose2d. tconv_params ([dict], optional): [Init parameters for the", "y1 = self.enc(inpt, **kwargs) mu, log_std = torch.chunk(y1, 2, dim=1) std = torch.exp(log_std)", "sample back to the input space Args: inpt ([tensor]): [Latent space sample] Returns:", "back to the input space Args: inpt ([tensor]): [Latent space sample] Returns: [rec]:", "else: z_sample = mu x_rec = self.dec(z_sample) if no_dist: return x_rec else: return", "mean used to parameterized a Normal distribution std: The standard deviation used to", "from example_algos.models.nets import BasicEncoder, BasicGenerator class VAE(torch.nn.Module): def __init__( self, input_size, z_dim=256, fmap_sizes=(16,", "block_op=None, block_params=None, *args, **kwargs ): \"\"\"Basic AE build up of a symetric BasicEncoder", "see ConvModule]. Defaults to nn.LeakyReLU. activation_params ([dict], optional): [Init parameters for the activation", "to None. \"\"\" super(VAE, self).__init__() input_size_enc = list(input_size) input_size_dec = list(input_size) self.enc =", "torch.exp(log_std) z_dist = dist.Normal(mu, std) if sample: z_sample = z_dist.rsample() else: z_sample =", "([type]): A sample from the latent space to decode Returns: [type]: [description] \"\"\"", "\"\"\"Decodes a latent space sample, used the generative model (decode = mu_{gen}(z) as", "[Init parameters for the normalization operation]. Defaults to None. activation_op ([torch.nn.Module], optional): [Actiovation", "nn.BatchNorm2d. normalization_params ([dict], optional): [Init parameters for the normalization operation]. Defaults to None.", "x_rec = self.dec(y1) return x_rec def encode(self, inpt, **kwargs): \"\"\"Encodes a input sample", "for the conv operation]. Defaults to dict(kernel_size=3, stride=2, padding=1, bias=False). normalization_op ([torch.nn.Module], optional):", "of e.g. ConvBlock/ ResidualBlock]. Defaults to NoOp. block_params ([dict], optional): [Init parameters for", "block_params=None, *args, **kwargs ): \"\"\"Basic VAE build up of a symetric BasicEncoder (Encoder)", "approx inference dist. (Normal) Args: inpt ([tensor]): The input to encode Returns: mu", "VAE build up of a symetric BasicEncoder (Encoder) and BasicGenerator (Decoder) Args: input_size", "in the decoder to upsample to a new level/ featuremap size]. Defaults to", "**kwargs) return enc def decode(self, inpt, **kwargs): \"\"\"Decodes a latent space sample back", "class VAE(torch.nn.Module): def __init__( self, input_size, z_dim=256, fmap_sizes=(16, 64, 256, 1024), to_1x1=True, conv_op=torch.nn.Conv2d,", "fmap_sizes=fmap_sizes, z_dim=z_dim, conv_op=conv_op, conv_params=conv_params, normalization_op=normalization_op, normalization_params=normalization_params, activation_op=activation_op, activation_params=activation_params, block_op=block_op, block_params=block_params, to_1x1=to_1x1, ) self.dec", "list(input_size) self.enc = BasicEncoder( input_size=input_size_enc, fmap_sizes=fmap_sizes, z_dim=z_dim, conv_op=conv_op, conv_params=conv_params, normalization_op=normalization_op, normalization_params=normalization_params, activation_op=activation_op, activation_params=activation_params,", "to nn.BatchNorm2d. normalization_params ([dict], optional): [Init parameters for the normalization operation]. Defaults to", "space sample] Returns: [rec]: [Encoded latent sample back in the input space] \"\"\"", "generative model (decode = mu_{gen}(z) as used in p(x|z) = N(x | mu_{gen}(z),", "Returns: [rec]: [Encoded latent sample back in the input space] \"\"\" rec =", "The standard deviation used to parameterized a Normal distribution \"\"\" enc = self.enc(inpt,", "([dict], optional): [Init parameters for the block operation]. Defaults to None. \"\"\" super(VAE,", "Defaults to 256 fmap_sizes (tuple, optional): [Defines the Upsampling-Levels of the generator, list/", "activation_params ([dict], optional): [Init parameters for the activation operation]. Defaults to None. block_op", "([dict], optional): [Init parameters for the block operation]. Defaults to None. \"\"\" super(AE,", "the normalization operation]. Defaults to None. activation_op ([torch.nn.Module], optional): [Actiovation Operation/ Non-linearity (e.g.", "for the block operation]. Defaults to None. \"\"\" super(VAE, self).__init__() input_size_enc = list(input_size)", "Args: input_size ((int, int, int): Size of the input in format CxHxW): z_dim", "optional): [If True, then the last conv layer goes to a latent dimesion", "= self.enc(inpt, **kwargs) x_rec = self.dec(y1) return x_rec def encode(self, inpt, **kwargs): \"\"\"Encodes", "mu_{gen}(z) as used in p(x|z) = N(x | mu_{gen}(z), 1) ). Args: inpt", "log_std = torch.chunk(y1, 2, dim=1) std = torch.exp(log_std) z_dist = dist.Normal(mu, std) if", "to None. activation_op ([torch.nn.Module], optional): [Actiovation Operation/ Non-linearity (e.g. ReLU, Sigmoid,...) -> see", "1024). to_1x1 (bool, optional): [If True, then the last conv layer goes to", "normalization_params ([dict], optional): [Init parameters for the normalization operation]. Defaults to None. activation_op", "(Decoder) Args: input_size ((int, int, int): Size of the input in format CxHxW):", "x H x W, uses the in the conv_params given conv-kernel-size) ]. Defaults", "= list(input_size) self.enc = BasicEncoder( input_size=input_size_enc, fmap_sizes=fmap_sizes, z_dim=z_dim * 2, conv_op=conv_op, conv_params=conv_params, normalization_op=normalization_op,", "if False allows spatial resolution not to be 1x1 (z_dim x H x", "encoder to downsample to a new level/ featuremap size]. Defaults to nn.Conv2d. conv_params", "256, 1024), to_1x1=True, conv_op=torch.nn.Conv2d, conv_params=None, tconv_op=torch.nn.ConvTranspose2d, tconv_params=None, normalization_op=None, normalization_params=None, activation_op=torch.nn.LeakyReLU, activation_params=None, block_op=None, block_params=None,", "the generator, list/ tuple of ints, where each int defines the number of", "bias=False). normalization_op ([torch.nn.Module], optional): [Normalization Operation (e.g. BatchNorm, InstanceNorm,...) -> see ConvModule]. Defaults", "normalization_params=None, activation_op=torch.nn.LeakyReLU, activation_params=None, block_op=None, block_params=None, *args, **kwargs ): \"\"\"Basic VAE build up of", "self.dec(z_sample) if no_dist: return x_rec else: return x_rec, z_dist def encode(self, inpt, **kwargs):", "self.hidden_size = self.enc.output_size def forward(self, inpt, **kwargs): y1 = self.enc(inpt, **kwargs) x_rec =", "N(x | mu_{gen}(z), 1) ). Args: inpt ([type]): A sample from the latent", "[rec]: [Encoded latent sample back in the input space] \"\"\" rec = self.dec(inpt,", "self.enc(inpt, **kwargs) x_rec = self.dec(y1) return x_rec def encode(self, inpt, **kwargs): \"\"\"Encodes a", "to a latent dimesion is a z_dim x 1 x 1 vector (similar", "self.enc(inpt, **kwargs) mu, log_std = torch.chunk(y1, 2, dim=1) std = torch.exp(log_std) z_dist =", "operation]. Defaults to dict(kernel_size=3, stride=2, padding=1, bias=False). normalization_op ([torch.nn.Module], optional): [Normalization Operation (e.g.", "(e.g. ReLU, Sigmoid,...) -> see ConvModule]. Defaults to nn.LeakyReLU. activation_params ([dict], optional): [Init", "to_1x1 (bool, optional): [If True, then the last conv layer goes to a", "z_dim=z_dim * 2, conv_op=conv_op, conv_params=conv_params, normalization_op=normalization_op, normalization_params=normalization_params, activation_op=activation_op, activation_params=activation_params, block_op=block_op, block_params=block_params, to_1x1=to_1x1, )", "). Args: inpt ([type]): A sample from the latent space to decode Returns:", "activation_params=activation_params, block_op=block_op, block_params=block_params, to_1x1=to_1x1, ) self.hidden_size = self.enc.output_size def forward(self, inpt, sample=True, no_dist=False,", "activation operation]. Defaults to None. block_op ([torch.nn.Module], optional): [Block operation used for each", "Size of the input in format CxHxW): z_dim (int, optional): [description]. Dimension of", "input sample to a latent space sample Args: inpt ([tensor]): Input sample Returns:", "latent space sample back to the input space Args: inpt ([tensor]): [Latent space", "activation_op=activation_op, activation_params=activation_params, block_op=block_op, block_params=block_params, to_1x1=to_1x1, ) self.hidden_size = self.enc.output_size def forward(self, inpt, **kwargs):", "self).__init__() input_size_enc = list(input_size) input_size_dec = list(input_size) self.enc = BasicEncoder( input_size=input_size_enc, fmap_sizes=fmap_sizes, z_dim=z_dim,", "conv layer goes to a latent dimesion is a z_dim x 1 x", "]. Defaults to True. conv_op ([torch.nn.Module], optional): [Convolutioon operation used in the encoder", "enc def decode(self, inpt, **kwargs): \"\"\"Decodes a latent space sample back to the", "op of e.g. ConvBlock/ ResidualBlock]. Defaults to NoOp. block_params ([dict], optional): [Init parameters", "def forward(self, inpt, sample=True, no_dist=False, **kwargs): y1 = self.enc(inpt, **kwargs) mu, log_std =", "be 1x1 (z_dim x H x W, uses the in the conv_params given", "W, uses the in the conv_params given conv-kernel-size) ]. Defaults to True. conv_op", "the encoder to downsample to a new level/ featuremap size]. Defaults to nn.Conv2d.", "nn.Conv2d. conv_params ([dict], optional): [Init parameters for the conv operation]. Defaults to dict(kernel_size=3,", "sample and returns the paramters for the approx inference dist. (Normal) Args: inpt", "input_size=input_size_enc, fmap_sizes=fmap_sizes, z_dim=z_dim, conv_op=conv_op, conv_params=conv_params, normalization_op=normalization_op, normalization_params=normalization_params, activation_op=activation_op, activation_params=activation_params, block_op=block_op, block_params=block_params, to_1x1=to_1x1, )", "\"\"\"Basic VAE build up of a symetric BasicEncoder (Encoder) and BasicGenerator (Decoder) Args:", "optional): [description]. Dimension of the latent / Input dimension (C channel-dim). Defaults to", "to_1x1=to_1x1, ) self.hidden_size = self.enc.output_size def forward(self, inpt, sample=True, no_dist=False, **kwargs): y1 =", "input_size, z_dim=1024, fmap_sizes=(16, 64, 256, 1024), to_1x1=True, conv_op=torch.nn.Conv2d, conv_params=None, tconv_op=torch.nn.ConvTranspose2d, tconv_params=None, normalization_op=None, normalization_params=None,", "build up of a symetric BasicEncoder (Encoder) and BasicGenerator (Decoder) Args: input_size ((int,", "Transposed Conv operation used in the decoder to upsample to a new level/", "Sigmoid,...) -> see ConvModule]. Defaults to nn.LeakyReLU. activation_params ([dict], optional): [Init parameters for", "list/ tuple of ints, where each int defines the number of feature maps", "to 256 fmap_sizes (tuple, optional): [Defines the Upsampling-Levels of the generator, list/ tuple", "sample: z_sample = z_dist.rsample() else: z_sample = mu x_rec = self.dec(z_sample) if no_dist:", "inpt, **kwargs): \"\"\"Decodes a latent space sample, used the generative model (decode =", "distribution std: The standard deviation used to parameterized a Normal distribution \"\"\" enc", ") self.hidden_size = self.enc.output_size def forward(self, inpt, **kwargs): y1 = self.enc(inpt, **kwargs) x_rec", "= torch.chunk(y1, 2, dim=1) std = torch.exp(log_std) z_dist = dist.Normal(mu, std) if sample:", "fully connected) or if False allows spatial resolution not to be 1x1 (z_dim", "\"\"\"Basic AE build up of a symetric BasicEncoder (Encoder) and BasicGenerator (Decoder) Args:", "sample to a latent space sample Args: inpt ([tensor]): Input sample Returns: enc:", "Non-linearity (e.g. ReLU, Sigmoid,...) -> see ConvModule]. Defaults to nn.LeakyReLU. activation_params ([dict], optional):", "= N(x | mu_{gen}(z), 1) ). Args: inpt ([type]): A sample from the", "parameters for the conv operation]. Defaults to dict(kernel_size=3, stride=2, padding=1, bias=False). normalization_op ([torch.nn.Module],", "enc = self.enc(inpt, **kwargs) return enc def decode(self, inpt, **kwargs): \"\"\"Decodes a latent", "x_rec else: return x_rec, z_dist def encode(self, inpt, **kwargs): \"\"\"Encodes a sample and", "Normal distribution std: The standard deviation used to parameterized a Normal distribution \"\"\"", "*args, **kwargs ): \"\"\"Basic VAE build up of a symetric BasicEncoder (Encoder) and", "p(x|z) = N(x | mu_{gen}(z), 1) ). Args: inpt ([type]): A sample from", "for the normalization operation]. Defaults to None. activation_op ([torch.nn.Module], optional): [Actiovation Operation/ Non-linearity", "or if False allows spatial resolution not to be 1x1 (z_dim x H", "optional): [Block operation used for each feature map size after each upsample op", "given conv-kernel-size) ]. Defaults to True. conv_op ([torch.nn.Module], optional): [Convolutioon operation used in", "the last conv layer goes to a latent dimesion is a z_dim x", "import torch import torch.distributions as dist from example_algos.models.nets import BasicEncoder, BasicGenerator class VAE(torch.nn.Module):", "a latent space sample Args: inpt ([tensor]): Input sample Returns: enc: Encoded input", "for the conv operation]. Defaults to dict(kernel_size=3, stride=2, padding=1, bias=False). tconv_op ([torch.nn.Module], optional):", "to downsample to a new level/ featuremap size]. Defaults to nn.Conv2d. conv_params ([dict],", "def decode(self, inpt, **kwargs): \"\"\"Decodes a latent space sample, used the generative model", "input space Args: inpt ([tensor]): [Latent space sample] Returns: [rec]: [Encoded latent sample", "mu_{gen}(z), 1) ). Args: inpt ([type]): A sample from the latent space to", "and BasicGenerator (Decoder) Args: input_size ((int, int, int): Size of the input in", "in the conv_params given conv-kernel-size) ]. Defaults to True. conv_op ([torch.nn.Module], optional): [Convolutioon", "operation]. Defaults to None. activation_op ([torch.nn.Module], optional): [Actiovation Operation/ Non-linearity (e.g. ReLU, Sigmoid,...)", "deviation used to parameterized a Normal distribution \"\"\" enc = self.enc(inpt, **kwargs) mu,", "a Normal distribution std: The standard deviation used to parameterized a Normal distribution", "\"\"\"Encodes a input sample to a latent space sample Args: inpt ([tensor]): Input", "z_sample = z_dist.rsample() else: z_sample = mu x_rec = self.dec(z_sample) if no_dist: return", "the generative model (decode = mu_{gen}(z) as used in p(x|z) = N(x |", "operation]. Defaults to dict(kernel_size=3, stride=2, padding=1, bias=False). tconv_op ([torch.nn.Module], optional): [Upsampling/ Transposed Conv", "encode(self, inpt, **kwargs): \"\"\"Encodes a sample and returns the paramters for the approx", "ints, where each int defines the number of feature maps in the layer].", "space sample, used the generative model (decode = mu_{gen}(z) as used in p(x|z)", "activation_params=None, block_op=None, block_params=None, *args, **kwargs ): \"\"\"Basic AE build up of a symetric", "**kwargs ): \"\"\"Basic VAE build up of a symetric BasicEncoder (Encoder) and BasicGenerator", "parameterized a Normal distribution \"\"\" enc = self.enc(inpt, **kwargs) mu, log_std = torch.chunk(enc,", "no_dist: return x_rec else: return x_rec, z_dist def encode(self, inpt, **kwargs): \"\"\"Encodes a", "Defaults to (16, 64, 256, 1024). to_1x1 (bool, optional): [If True, then the", "to the input space Args: inpt ([tensor]): [Latent space sample] Returns: [rec]: [Encoded", "tconv_params ([dict], optional): [Init parameters for the conv operation]. Defaults to dict(kernel_size=3, stride=2,", "Returns: enc: Encoded input sample in the latent space \"\"\" enc = self.enc(inpt,", "\"\"\" super(VAE, self).__init__() input_size_enc = list(input_size) input_size_dec = list(input_size) self.enc = BasicEncoder( input_size=input_size_enc,", "optional): [Init parameters for the activation operation]. Defaults to None. block_op ([torch.nn.Module], optional):", "input in format CxHxW): z_dim (int, optional): [description]. Dimension of the latent /", "conv-kernel-size) ]. Defaults to True. conv_op ([torch.nn.Module], optional): [Convolutioon operation used in the", "conv_params=tconv_params, normalization_op=normalization_op, normalization_params=normalization_params, activation_op=activation_op, activation_params=activation_params, block_op=block_op, block_params=block_params, to_1x1=to_1x1, ) self.hidden_size = self.enc.output_size def", "**kwargs): \"\"\"Encodes a sample and returns the paramters for the approx inference dist.", "size after each upsample op of e.g. ConvBlock/ ResidualBlock]. Defaults to NoOp. block_params", "(decode = mu_{gen}(z) as used in p(x|z) = N(x | mu_{gen}(z), 1) ).", "optional): [Defines the Upsampling-Levels of the generator, list/ tuple of ints, where each", "Encoded input sample in the latent space \"\"\" enc = self.enc(inpt, **kwargs) return", "to dict(kernel_size=3, stride=2, padding=1, bias=False). tconv_op ([torch.nn.Module], optional): [Upsampling/ Transposed Conv operation used", "z_dim x 1 x 1 vector (similar to fully connected) or if False", "False allows spatial resolution not to be 1x1 (z_dim x H x W,", "channel-dim). Defaults to 256 fmap_sizes (tuple, optional): [Defines the Upsampling-Levels of the generator,", "dim=1) std = torch.exp(log_std) z_dist = dist.Normal(mu, std) if sample: z_sample = z_dist.rsample()", "a Normal distribution \"\"\" enc = self.enc(inpt, **kwargs) mu, log_std = torch.chunk(enc, 2,", "each int defines the number of feature maps in the layer]. Defaults to", "normalization_op=None, normalization_params=None, activation_op=torch.nn.LeakyReLU, activation_params=None, block_op=None, block_params=None, *args, **kwargs ): \"\"\"Basic AE build up", "Returns: mu : The mean used to parameterized a Normal distribution std: The", "([torch.nn.Module], optional): [Actiovation Operation/ Non-linearity (e.g. ReLU, Sigmoid,...) -> see ConvModule]. Defaults to", "self).__init__() input_size_enc = list(input_size) input_size_dec = list(input_size) self.enc = BasicEncoder( input_size=input_size_enc, fmap_sizes=fmap_sizes, z_dim=z_dim", "\"\"\" enc = self.enc(inpt, **kwargs) return enc def decode(self, inpt, **kwargs): \"\"\"Decodes a", "z_dim (int, optional): [description]. Dimension of the latent / Input dimension (C channel-dim).", "std = torch.exp(log_std) return mu, std def decode(self, inpt, **kwargs): \"\"\"Decodes a latent", "BasicEncoder( input_size=input_size_enc, fmap_sizes=fmap_sizes, z_dim=z_dim * 2, conv_op=conv_op, conv_params=conv_params, normalization_op=normalization_op, normalization_params=normalization_params, activation_op=activation_op, activation_params=activation_params, block_op=block_op,", "each upsample op of e.g. ConvBlock/ ResidualBlock]. Defaults to NoOp. block_params ([dict], optional):", "normalization_params=normalization_params, activation_op=activation_op, activation_params=activation_params, block_op=block_op, block_params=block_params, to_1x1=to_1x1, ) self.dec = BasicGenerator( input_size=input_size_dec, fmap_sizes=fmap_sizes[::-1], z_dim=z_dim,", "operation used in the encoder to downsample to a new level/ featuremap size].", "ConvModule]. Defaults to nn.BatchNorm2d. normalization_params ([dict], optional): [Init parameters for the normalization operation].", "operation]. Defaults to None. \"\"\" super(AE, self).__init__() input_size_enc = list(input_size) input_size_dec = list(input_size)", "= mu x_rec = self.dec(z_sample) if no_dist: return x_rec else: return x_rec, z_dist", "([torch.nn.Module], optional): [Normalization Operation (e.g. BatchNorm, InstanceNorm,...) -> see ConvModule]. Defaults to nn.BatchNorm2d.", "None. \"\"\" super(AE, self).__init__() input_size_enc = list(input_size) input_size_dec = list(input_size) self.enc = BasicEncoder(", "int defines the number of feature maps in the layer]. Defaults to (16,", "activation_op=activation_op, activation_params=activation_params, block_op=block_op, block_params=block_params, to_1x1=to_1x1, ) self.hidden_size = self.enc.output_size def forward(self, inpt, sample=True,", "torch import torch.distributions as dist from example_algos.models.nets import BasicEncoder, BasicGenerator class VAE(torch.nn.Module): def", "Defaults to None. activation_op ([torch.nn.Module], optional): [Actiovation Operation/ Non-linearity (e.g. ReLU, Sigmoid,...) ->", "conv_params ([dict], optional): [Init parameters for the conv operation]. Defaults to dict(kernel_size=3, stride=2,", "= self.enc(inpt, **kwargs) mu, log_std = torch.chunk(y1, 2, dim=1) std = torch.exp(log_std) z_dist", "tconv_op=torch.nn.ConvTranspose2d, tconv_params=None, normalization_op=None, normalization_params=None, activation_op=torch.nn.LeakyReLU, activation_params=None, block_op=None, block_params=None, *args, **kwargs ): \"\"\"Basic VAE", "Defaults to dict(kernel_size=3, stride=2, padding=1, bias=False). tconv_op ([torch.nn.Module], optional): [Upsampling/ Transposed Conv operation", "block_op=block_op, block_params=block_params, to_1x1=to_1x1, ) self.hidden_size = self.enc.output_size def forward(self, inpt, sample=True, no_dist=False, **kwargs):", "decode(self, inpt, **kwargs): \"\"\"Decodes a latent space sample back to the input space", "H x W, uses the in the conv_params given conv-kernel-size) ]. Defaults to", "after each upsample op of e.g. ConvBlock/ ResidualBlock]. Defaults to NoOp. block_params ([dict],", "a symetric BasicEncoder (Encoder) and BasicGenerator (Decoder) Args: input_size ((int, int, int): Size", "the decoder to upsample to a new level/ featuremap size]. Defaults to nn.ConvTranspose2d.", "featuremap size]. Defaults to nn.Conv2d. conv_params ([dict], optional): [Init parameters for the conv", "z_sample = mu x_rec = self.dec(z_sample) if no_dist: return x_rec else: return x_rec,", "Normal distribution \"\"\" enc = self.enc(inpt, **kwargs) mu, log_std = torch.chunk(enc, 2, dim=1)", "__init__( self, input_size, z_dim=256, fmap_sizes=(16, 64, 256, 1024), to_1x1=True, conv_op=torch.nn.Conv2d, conv_params=None, tconv_op=torch.nn.ConvTranspose2d, tconv_params=None,", "fmap_sizes=(16, 64, 256, 1024), to_1x1=True, conv_op=torch.nn.Conv2d, conv_params=None, tconv_op=torch.nn.ConvTranspose2d, tconv_params=None, normalization_op=None, normalization_params=None, activation_op=torch.nn.LeakyReLU, activation_params=None,", "= z_dist.rsample() else: z_sample = mu x_rec = self.dec(z_sample) if no_dist: return x_rec", "sample in the latent space \"\"\" enc = self.enc(inpt, **kwargs) return enc def", "in the latent space \"\"\" enc = self.enc(inpt, **kwargs) return enc def decode(self,", "normalization_op ([torch.nn.Module], optional): [Normalization Operation (e.g. BatchNorm, InstanceNorm,...) -> see ConvModule]. Defaults to", "latent space sample, used the generative model (decode = mu_{gen}(z) as used in", "to nn.Conv2d. conv_params ([dict], optional): [Init parameters for the conv operation]. Defaults to", "a new level/ featuremap size]. Defaults to nn.Conv2d. conv_params ([dict], optional): [Init parameters", "input_size_enc = list(input_size) input_size_dec = list(input_size) self.enc = BasicEncoder( input_size=input_size_enc, fmap_sizes=fmap_sizes, z_dim=z_dim, conv_op=conv_op,", "input_size_dec = list(input_size) self.enc = BasicEncoder( input_size=input_size_enc, fmap_sizes=fmap_sizes, z_dim=z_dim, conv_op=conv_op, conv_params=conv_params, normalization_op=normalization_op, normalization_params=normalization_params,", "(16, 64, 256, 1024). to_1x1 (bool, optional): [If True, then the last conv", "([torch.nn.Module], optional): [Block operation used for each feature map size after each upsample", "mu : The mean used to parameterized a Normal distribution std: The standard", "self.enc(inpt, **kwargs) return enc def decode(self, inpt, **kwargs): \"\"\"Decodes a latent space sample", "feature map size after each upsample op of e.g. ConvBlock/ ResidualBlock]. Defaults to", "Defaults to nn.ConvTranspose2d. tconv_params ([dict], optional): [Init parameters for the conv operation]. Defaults", "operation used in the decoder to upsample to a new level/ featuremap size].", "else: return x_rec, z_dist def encode(self, inpt, **kwargs): \"\"\"Encodes a sample and returns", "tuple of ints, where each int defines the number of feature maps in", "1 vector (similar to fully connected) or if False allows spatial resolution not", "[Convolutioon operation used in the encoder to downsample to a new level/ featuremap", "optional): [Actiovation Operation/ Non-linearity (e.g. ReLU, Sigmoid,...) -> see ConvModule]. Defaults to nn.LeakyReLU.", "encode(self, inpt, **kwargs): \"\"\"Encodes a input sample to a latent space sample Args:", "mu, std def decode(self, inpt, **kwargs): \"\"\"Decodes a latent space sample, used the", "**kwargs): y1 = self.enc(inpt, **kwargs) mu, log_std = torch.chunk(y1, 2, dim=1) std =", "class AE(torch.nn.Module): def __init__( self, input_size, z_dim=1024, fmap_sizes=(16, 64, 256, 1024), to_1x1=True, conv_op=torch.nn.Conv2d,", "list(input_size) self.enc = BasicEncoder( input_size=input_size_enc, fmap_sizes=fmap_sizes, z_dim=z_dim * 2, conv_op=conv_op, conv_params=conv_params, normalization_op=normalization_op, normalization_params=normalization_params,", "return mu, std def decode(self, inpt, **kwargs): \"\"\"Decodes a latent space sample, used", "encode Returns: mu : The mean used to parameterized a Normal distribution std:", "decoder to upsample to a new level/ featuremap size]. Defaults to nn.ConvTranspose2d. tconv_params", "\"\"\" x_rec = self.dec(inpt, **kwargs) return x_rec class AE(torch.nn.Module): def __init__( self, input_size,", "): \"\"\"Basic VAE build up of a symetric BasicEncoder (Encoder) and BasicGenerator (Decoder)", "Upsampling-Levels of the generator, list/ tuple of ints, where each int defines the", "tconv_params=None, normalization_op=None, normalization_params=None, activation_op=torch.nn.LeakyReLU, activation_params=None, block_op=None, block_params=None, *args, **kwargs ): \"\"\"Basic VAE build", "None. \"\"\" super(VAE, self).__init__() input_size_enc = list(input_size) input_size_dec = list(input_size) self.enc = BasicEncoder(", "to a latent space sample Args: inpt ([tensor]): Input sample Returns: enc: Encoded", "upsample op of e.g. ConvBlock/ ResidualBlock]. Defaults to NoOp. block_params ([dict], optional): [Init", "block_op=block_op, block_params=block_params, to_1x1=to_1x1, ) self.hidden_size = self.enc.output_size def forward(self, inpt, **kwargs): y1 =", "x_rec, z_dist def encode(self, inpt, **kwargs): \"\"\"Encodes a sample and returns the paramters", "1 x 1 vector (similar to fully connected) or if False allows spatial", "self.hidden_size = self.enc.output_size def forward(self, inpt, sample=True, no_dist=False, **kwargs): y1 = self.enc(inpt, **kwargs)", "x_rec class AE(torch.nn.Module): def __init__( self, input_size, z_dim=1024, fmap_sizes=(16, 64, 256, 1024), to_1x1=True,", "conv_op=conv_op, conv_params=conv_params, normalization_op=normalization_op, normalization_params=normalization_params, activation_op=activation_op, activation_params=activation_params, block_op=block_op, block_params=block_params, to_1x1=to_1x1, ) self.dec = BasicGenerator(", "**kwargs): \"\"\"Decodes a latent space sample, used the generative model (decode = mu_{gen}(z)", "level/ featuremap size]. Defaults to nn.Conv2d. conv_params ([dict], optional): [Init parameters for the", "None. block_op ([torch.nn.Module], optional): [Block operation used for each feature map size after", "conv operation]. Defaults to dict(kernel_size=3, stride=2, padding=1, bias=False). tconv_op ([torch.nn.Module], optional): [Upsampling/ Transposed", "Defaults to None. \"\"\" super(VAE, self).__init__() input_size_enc = list(input_size) input_size_dec = list(input_size) self.enc", "latent / Input dimension (C channel-dim). Defaults to 256 fmap_sizes (tuple, optional): [Defines", "(similar to fully connected) or if False allows spatial resolution not to be", "2, dim=1) std = torch.exp(log_std) z_dist = dist.Normal(mu, std) if sample: z_sample =", "symetric BasicEncoder (Encoder) and BasicGenerator (Decoder) Args: input_size ((int, int, int): Size of", "e.g. ConvBlock/ ResidualBlock]. Defaults to NoOp. block_params ([dict], optional): [Init parameters for the", "The mean used to parameterized a Normal distribution std: The standard deviation used", "the latent space \"\"\" enc = self.enc(inpt, **kwargs) return enc def decode(self, inpt,", "normalization_op=None, normalization_params=None, activation_op=torch.nn.LeakyReLU, activation_params=None, block_op=None, block_params=None, *args, **kwargs ): \"\"\"Basic VAE build up", "a sample and returns the paramters for the approx inference dist. (Normal) Args:", "operation used for each feature map size after each upsample op of e.g.", "numpy as np import torch import torch.distributions as dist from example_algos.models.nets import BasicEncoder,", "std) if sample: z_sample = z_dist.rsample() else: z_sample = mu x_rec = self.dec(z_sample)", "generator, list/ tuple of ints, where each int defines the number of feature", "standard deviation used to parameterized a Normal distribution \"\"\" enc = self.enc(inpt, **kwargs)", "to decode Returns: [type]: [description] \"\"\" x_rec = self.dec(inpt, **kwargs) return x_rec class", "for the block operation]. Defaults to None. \"\"\" super(AE, self).__init__() input_size_enc = list(input_size)", "np import torch import torch.distributions as dist from example_algos.models.nets import BasicEncoder, BasicGenerator class", "self.enc = BasicEncoder( input_size=input_size_enc, fmap_sizes=fmap_sizes, z_dim=z_dim * 2, conv_op=conv_op, conv_params=conv_params, normalization_op=normalization_op, normalization_params=normalization_params, activation_op=activation_op,", "ConvModule]. Defaults to nn.LeakyReLU. activation_params ([dict], optional): [Init parameters for the activation operation].", "optional): [Init parameters for the conv operation]. Defaults to dict(kernel_size=3, stride=2, padding=1, bias=False).", "self, input_size, z_dim=1024, fmap_sizes=(16, 64, 256, 1024), to_1x1=True, conv_op=torch.nn.Conv2d, conv_params=None, tconv_op=torch.nn.ConvTranspose2d, tconv_params=None, normalization_op=None,", "spatial resolution not to be 1x1 (z_dim x H x W, uses the", "to fully connected) or if False allows spatial resolution not to be 1x1", ") self.dec = BasicGenerator( input_size=input_size_dec, fmap_sizes=fmap_sizes[::-1], z_dim=z_dim, upsample_op=tconv_op, conv_params=tconv_params, normalization_op=normalization_op, normalization_params=normalization_params, activation_op=activation_op, activation_params=activation_params,", "of a symetric BasicEncoder (Encoder) and BasicGenerator (Decoder) Args: input_size ((int, int, int):", "optional): [Init parameters for the normalization operation]. Defaults to None. activation_op ([torch.nn.Module], optional):", "Args: inpt ([tensor]): Input sample Returns: enc: Encoded input sample in the latent", "if sample: z_sample = z_dist.rsample() else: z_sample = mu x_rec = self.dec(z_sample) if", "goes to a latent dimesion is a z_dim x 1 x 1 vector", "return x_rec class AE(torch.nn.Module): def __init__( self, input_size, z_dim=1024, fmap_sizes=(16, 64, 256, 1024),", "((int, int, int): Size of the input in format CxHxW): z_dim (int, optional):", "dim=1) std = torch.exp(log_std) return mu, std def decode(self, inpt, **kwargs): \"\"\"Decodes a", "super(AE, self).__init__() input_size_enc = list(input_size) input_size_dec = list(input_size) self.enc = BasicEncoder( input_size=input_size_enc, fmap_sizes=fmap_sizes,", "mu x_rec = self.dec(z_sample) if no_dist: return x_rec else: return x_rec, z_dist def", "import BasicEncoder, BasicGenerator class VAE(torch.nn.Module): def __init__( self, input_size, z_dim=256, fmap_sizes=(16, 64, 256,", "to (16, 64, 256, 1024). to_1x1 (bool, optional): [If True, then the last", "to a new level/ featuremap size]. Defaults to nn.Conv2d. conv_params ([dict], optional): [Init", "decode(self, inpt, **kwargs): \"\"\"Decodes a latent space sample, used the generative model (decode", "BatchNorm, InstanceNorm,...) -> see ConvModule]. Defaults to nn.BatchNorm2d. normalization_params ([dict], optional): [Init parameters", "\"\"\"Encodes a sample and returns the paramters for the approx inference dist. (Normal)", "activation_op=torch.nn.LeakyReLU, activation_params=None, block_op=None, block_params=None, *args, **kwargs ): \"\"\"Basic VAE build up of a", "def forward(self, inpt, **kwargs): y1 = self.enc(inpt, **kwargs) x_rec = self.dec(y1) return x_rec", "optional): [Upsampling/ Transposed Conv operation used in the decoder to upsample to a", "self.dec(y1) return x_rec def encode(self, inpt, **kwargs): \"\"\"Encodes a input sample to a", "used for each feature map size after each upsample op of e.g. ConvBlock/", "space sample back to the input space Args: inpt ([tensor]): [Latent space sample]", "torch.exp(log_std) return mu, std def decode(self, inpt, **kwargs): \"\"\"Decodes a latent space sample,", "parameters for the normalization operation]. Defaults to None. activation_op ([torch.nn.Module], optional): [Actiovation Operation/", "activation_params=activation_params, block_op=block_op, block_params=block_params, to_1x1=to_1x1, ) self.hidden_size = self.enc.output_size def forward(self, inpt, **kwargs): y1", "inference dist. (Normal) Args: inpt ([tensor]): The input to encode Returns: mu :", "1) ). Args: inpt ([type]): A sample from the latent space to decode", "Operation/ Non-linearity (e.g. ReLU, Sigmoid,...) -> see ConvModule]. Defaults to nn.LeakyReLU. activation_params ([dict],", "vector (similar to fully connected) or if False allows spatial resolution not to", "optional): [Init parameters for the block operation]. Defaults to None. \"\"\" super(AE, self).__init__()", "[Init parameters for the conv operation]. Defaults to dict(kernel_size=3, stride=2, padding=1, bias=False). tconv_op", "see ConvModule]. Defaults to nn.BatchNorm2d. normalization_params ([dict], optional): [Init parameters for the normalization", "activation_op ([torch.nn.Module], optional): [Actiovation Operation/ Non-linearity (e.g. ReLU, Sigmoid,...) -> see ConvModule]. Defaults", "= dist.Normal(mu, std) if sample: z_sample = z_dist.rsample() else: z_sample = mu x_rec", "inpt, **kwargs): \"\"\"Encodes a input sample to a latent space sample Args: inpt", "connected) or if False allows spatial resolution not to be 1x1 (z_dim x", "used in the decoder to upsample to a new level/ featuremap size]. Defaults", "super(VAE, self).__init__() input_size_enc = list(input_size) input_size_dec = list(input_size) self.enc = BasicEncoder( input_size=input_size_enc, fmap_sizes=fmap_sizes,", "([tensor]): Input sample Returns: enc: Encoded input sample in the latent space \"\"\"", "2, dim=1) std = torch.exp(log_std) return mu, std def decode(self, inpt, **kwargs): \"\"\"Decodes", "(int, optional): [description]. Dimension of the latent / Input dimension (C channel-dim). Defaults", "ResidualBlock]. Defaults to NoOp. block_params ([dict], optional): [Init parameters for the block operation].", "256 fmap_sizes (tuple, optional): [Defines the Upsampling-Levels of the generator, list/ tuple of", "of the generator, list/ tuple of ints, where each int defines the number", "-> see ConvModule]. Defaults to nn.LeakyReLU. activation_params ([dict], optional): [Init parameters for the", "to nn.LeakyReLU. activation_params ([dict], optional): [Init parameters for the activation operation]. Defaults to", "= BasicGenerator( input_size=input_size_dec, fmap_sizes=fmap_sizes[::-1], z_dim=z_dim, upsample_op=tconv_op, conv_params=tconv_params, normalization_op=normalization_op, normalization_params=normalization_params, activation_op=activation_op, activation_params=activation_params, block_op=block_op, block_params=block_params,", "torch.chunk(y1, 2, dim=1) std = torch.exp(log_std) z_dist = dist.Normal(mu, std) if sample: z_sample", "1024), to_1x1=True, conv_op=torch.nn.Conv2d, conv_params=None, tconv_op=torch.nn.ConvTranspose2d, tconv_params=None, normalization_op=None, normalization_params=None, activation_op=torch.nn.LeakyReLU, activation_params=None, block_op=None, block_params=None, *args,", "the approx inference dist. (Normal) Args: inpt ([tensor]): The input to encode Returns:", "import numpy as np import torch import torch.distributions as dist from example_algos.models.nets import", "activation_op=activation_op, activation_params=activation_params, block_op=block_op, block_params=block_params, to_1x1=to_1x1, ) self.dec = BasicGenerator( input_size=input_size_dec, fmap_sizes=fmap_sizes[::-1], z_dim=z_dim, upsample_op=tconv_op,", "fmap_sizes=fmap_sizes, z_dim=z_dim * 2, conv_op=conv_op, conv_params=conv_params, normalization_op=normalization_op, normalization_params=normalization_params, activation_op=activation_op, activation_params=activation_params, block_op=block_op, block_params=block_params, to_1x1=to_1x1,", "= BasicEncoder( input_size=input_size_enc, fmap_sizes=fmap_sizes, z_dim=z_dim * 2, conv_op=conv_op, conv_params=conv_params, normalization_op=normalization_op, normalization_params=normalization_params, activation_op=activation_op, activation_params=activation_params,", "conv operation]. Defaults to dict(kernel_size=3, stride=2, padding=1, bias=False). normalization_op ([torch.nn.Module], optional): [Normalization Operation", "BasicGenerator (Decoder) Args: input_size ((int, int, int): Size of the input in format", "block_params=block_params, to_1x1=to_1x1, ) self.hidden_size = self.enc.output_size def forward(self, inpt, sample=True, no_dist=False, **kwargs): y1", "self.dec(inpt, **kwargs) return x_rec class AE(torch.nn.Module): def __init__( self, input_size, z_dim=1024, fmap_sizes=(16, 64,", "**kwargs): y1 = self.enc(inpt, **kwargs) x_rec = self.dec(y1) return x_rec def encode(self, inpt,", "x 1 x 1 vector (similar to fully connected) or if False allows", "z_dim=256, fmap_sizes=(16, 64, 256, 1024), to_1x1=True, conv_op=torch.nn.Conv2d, conv_params=None, tconv_op=torch.nn.ConvTranspose2d, tconv_params=None, normalization_op=None, normalization_params=None, activation_op=torch.nn.LeakyReLU,", "Args: inpt ([tensor]): [Latent space sample] Returns: [rec]: [Encoded latent sample back in", "Defaults to dict(kernel_size=3, stride=2, padding=1, bias=False). normalization_op ([torch.nn.Module], optional): [Normalization Operation (e.g. BatchNorm,", "for each feature map size after each upsample op of e.g. ConvBlock/ ResidualBlock].", "normalization_op=normalization_op, normalization_params=normalization_params, activation_op=activation_op, activation_params=activation_params, block_op=block_op, block_params=block_params, to_1x1=to_1x1, ) self.dec = BasicGenerator( input_size=input_size_dec, fmap_sizes=fmap_sizes[::-1],", "([dict], optional): [Init parameters for the conv operation]. Defaults to dict(kernel_size=3, stride=2, padding=1,", "[Block operation used for each feature map size after each upsample op of", "[Init parameters for the block operation]. Defaults to None. \"\"\" super(AE, self).__init__() input_size_enc", "(e.g. BatchNorm, InstanceNorm,...) -> see ConvModule]. Defaults to nn.BatchNorm2d. normalization_params ([dict], optional): [Init", "inpt, **kwargs): \"\"\"Encodes a sample and returns the paramters for the approx inference", "z_dim=z_dim, upsample_op=tconv_op, conv_params=tconv_params, normalization_op=normalization_op, normalization_params=normalization_params, activation_op=activation_op, activation_params=activation_params, block_op=block_op, block_params=block_params, to_1x1=to_1x1, ) self.hidden_size =", "torch.distributions as dist from example_algos.models.nets import BasicEncoder, BasicGenerator class VAE(torch.nn.Module): def __init__( self,", "the conv_params given conv-kernel-size) ]. Defaults to True. conv_op ([torch.nn.Module], optional): [Convolutioon operation", "VAE(torch.nn.Module): def __init__( self, input_size, z_dim=256, fmap_sizes=(16, 64, 256, 1024), to_1x1=True, conv_op=torch.nn.Conv2d, conv_params=None,", "None. activation_op ([torch.nn.Module], optional): [Actiovation Operation/ Non-linearity (e.g. ReLU, Sigmoid,...) -> see ConvModule].", "BasicGenerator( input_size=input_size_dec, fmap_sizes=fmap_sizes[::-1], z_dim=z_dim, upsample_op=tconv_op, conv_params=tconv_params, normalization_op=normalization_op, normalization_params=normalization_params, activation_op=activation_op, activation_params=activation_params, block_op=block_op, block_params=block_params, to_1x1=to_1x1,", "def __init__( self, input_size, z_dim=1024, fmap_sizes=(16, 64, 256, 1024), to_1x1=True, conv_op=torch.nn.Conv2d, conv_params=None, tconv_op=torch.nn.ConvTranspose2d,", "sample Returns: enc: Encoded input sample in the latent space \"\"\" enc =", "new level/ featuremap size]. Defaults to nn.Conv2d. conv_params ([dict], optional): [Init parameters for", "Defaults to True. conv_op ([torch.nn.Module], optional): [Convolutioon operation used in the encoder to", "(tuple, optional): [Defines the Upsampling-Levels of the generator, list/ tuple of ints, where", "\"\"\"Decodes a latent space sample back to the input space Args: inpt ([tensor]):", "int): Size of the input in format CxHxW): z_dim (int, optional): [description]. Dimension", "z_dist.rsample() else: z_sample = mu x_rec = self.dec(z_sample) if no_dist: return x_rec else:", "[description]. Dimension of the latent / Input dimension (C channel-dim). Defaults to 256", "enc: Encoded input sample in the latent space \"\"\" enc = self.enc(inpt, **kwargs)", "(Encoder) and BasicGenerator (Decoder) Args: input_size ((int, int, int): Size of the input", "64, 256, 1024). to_1x1 (bool, optional): [If True, then the last conv layer", "= self.enc.output_size def forward(self, inpt, sample=True, no_dist=False, **kwargs): y1 = self.enc(inpt, **kwargs) mu,", "= self.dec(y1) return x_rec def encode(self, inpt, **kwargs): \"\"\"Encodes a input sample to", "[Defines the Upsampling-Levels of the generator, list/ tuple of ints, where each int", "from the latent space to decode Returns: [type]: [description] \"\"\" x_rec = self.dec(inpt,", "self.dec = BasicGenerator( input_size=input_size_dec, fmap_sizes=fmap_sizes[::-1], z_dim=z_dim, upsample_op=tconv_op, conv_params=tconv_params, normalization_op=normalization_op, normalization_params=normalization_params, activation_op=activation_op, activation_params=activation_params, block_op=block_op,", "dict(kernel_size=3, stride=2, padding=1, bias=False). tconv_op ([torch.nn.Module], optional): [Upsampling/ Transposed Conv operation used in", "dimesion is a z_dim x 1 x 1 vector (similar to fully connected)", "then the last conv layer goes to a latent dimesion is a z_dim", "256, 1024). to_1x1 (bool, optional): [If True, then the last conv layer goes", "return x_rec else: return x_rec, z_dist def encode(self, inpt, **kwargs): \"\"\"Encodes a sample", "torch.chunk(enc, 2, dim=1) std = torch.exp(log_std) return mu, std def decode(self, inpt, **kwargs):", "to parameterized a Normal distribution std: The standard deviation used to parameterized a", "def encode(self, inpt, **kwargs): \"\"\"Encodes a input sample to a latent space sample", "map size after each upsample op of e.g. ConvBlock/ ResidualBlock]. Defaults to NoOp.", "= self.dec(z_sample) if no_dist: return x_rec else: return x_rec, z_dist def encode(self, inpt,", "AE build up of a symetric BasicEncoder (Encoder) and BasicGenerator (Decoder) Args: input_size", "* 2, conv_op=conv_op, conv_params=conv_params, normalization_op=normalization_op, normalization_params=normalization_params, activation_op=activation_op, activation_params=activation_params, block_op=block_op, block_params=block_params, to_1x1=to_1x1, ) self.dec", "CxHxW): z_dim (int, optional): [description]. Dimension of the latent / Input dimension (C", "size]. Defaults to nn.ConvTranspose2d. tconv_params ([dict], optional): [Init parameters for the conv operation].", "mu, log_std = torch.chunk(y1, 2, dim=1) std = torch.exp(log_std) z_dist = dist.Normal(mu, std)", "activation_op=torch.nn.LeakyReLU, activation_params=None, block_op=None, block_params=None, *args, **kwargs ): \"\"\"Basic AE build up of a", "space Args: inpt ([tensor]): [Latent space sample] Returns: [rec]: [Encoded latent sample back", ": The mean used to parameterized a Normal distribution std: The standard deviation", "enc = self.enc(inpt, **kwargs) mu, log_std = torch.chunk(enc, 2, dim=1) std = torch.exp(log_std)", "mu, log_std = torch.chunk(enc, 2, dim=1) std = torch.exp(log_std) return mu, std def", "last conv layer goes to a latent dimesion is a z_dim x 1", "each feature map size after each upsample op of e.g. ConvBlock/ ResidualBlock]. Defaults", "for the approx inference dist. (Normal) Args: inpt ([tensor]): The input to encode", "**kwargs ): \"\"\"Basic AE build up of a symetric BasicEncoder (Encoder) and BasicGenerator", "stride=2, padding=1, bias=False). normalization_op ([torch.nn.Module], optional): [Normalization Operation (e.g. BatchNorm, InstanceNorm,...) -> see", "of feature maps in the layer]. Defaults to (16, 64, 256, 1024). to_1x1", "activation_params=activation_params, block_op=block_op, block_params=block_params, to_1x1=to_1x1, ) self.dec = BasicGenerator( input_size=input_size_dec, fmap_sizes=fmap_sizes[::-1], z_dim=z_dim, upsample_op=tconv_op, conv_params=tconv_params,", "latent space \"\"\" enc = self.enc(inpt, **kwargs) return enc def decode(self, inpt, **kwargs):", "optional): [Convolutioon operation used in the encoder to downsample to a new level/" ]
[ "param\") self.assertEqual(p.value, \"0.8765\") # check change was propagated to model self.assertRaises( sme.InvalidArgument, lambda:", "to model self.assertRaises( sme.InvalidArgument, lambda: m.parameters[\"param\"], ) p2 = m.parameters[\"New param\"] self.assertEqual(p2.name, \"New", "def test_parameter(self): # get an existing parameter m = sme.open_example_model() p = m.parameters[\"param\"]", "\"0.8765\") # check change was propagated to model self.assertRaises( sme.InvalidArgument, lambda: m.parameters[\"param\"], )", "\"New param\") self.assertEqual(p.value, \"0.8765\") # check change was propagated to model self.assertRaises( sme.InvalidArgument,", "self.assertEqual(p.value, \"0.8765\") # check change was propagated to model self.assertRaises( sme.InvalidArgument, lambda: m.parameters[\"param\"],", "self.assertEqual(repr(p), \"<sme.Parameter named 'param'>\") self.assertEqual(str(p)[0:33], \"<sme.Parameter>\\n - name: 'param'\") self.assertEqual(p.name, \"param\") self.assertEqual(p.value, \"1\")", "- name: 'New param'\") self.assertEqual(p.name, \"New param\") self.assertEqual(p.value, \"0.8765\") # check change was", "= m.parameters[\"New param\"] self.assertEqual(p2.name, \"New param\") self.assertEqual(p2.value, \"0.8765\") self.assertEqual(p2, p) self.assertEqual(p2, m.parameters[0]) self.assertEqual(p2,", "import unittest import sme class TestParameter(unittest.TestCase): def test_parameter(self): # get an existing parameter", "import sme class TestParameter(unittest.TestCase): def test_parameter(self): # get an existing parameter m =", "'param'\") self.assertEqual(p.name, \"param\") self.assertEqual(p.value, \"1\") # assign new values p.name = \"New param\"", "values p.name = \"New param\" p.value = \"0.8765\" self.assertEqual(repr(p), \"<sme.Parameter named 'New param'>\")", "'New param'>\") self.assertEqual(str(p)[0:37], \"<sme.Parameter>\\n - name: 'New param'\") self.assertEqual(p.name, \"New param\") self.assertEqual(p.value, \"0.8765\")", "\"0.8765\" self.assertEqual(repr(p), \"<sme.Parameter named 'New param'>\") self.assertEqual(str(p)[0:37], \"<sme.Parameter>\\n - name: 'New param'\") self.assertEqual(p.name,", "m.parameters[\"New param\"] self.assertEqual(p2.name, \"New param\") self.assertEqual(p2.value, \"0.8765\") self.assertEqual(p2, p) self.assertEqual(p2, m.parameters[0]) self.assertEqual(p2, m.parameters[-1])", "verify name and properties self.assertEqual(repr(p), \"<sme.Parameter named 'param'>\") self.assertEqual(str(p)[0:33], \"<sme.Parameter>\\n - name: 'param'\")", "named 'param'>\") self.assertEqual(str(p)[0:33], \"<sme.Parameter>\\n - name: 'param'\") self.assertEqual(p.name, \"param\") self.assertEqual(p.value, \"1\") # assign", "name: 'param'\") self.assertEqual(p.name, \"param\") self.assertEqual(p.value, \"1\") # assign new values p.name = \"New", "self.assertEqual(str(p)[0:37], \"<sme.Parameter>\\n - name: 'New param'\") self.assertEqual(p.name, \"New param\") self.assertEqual(p.value, \"0.8765\") # check", "'param'>\") self.assertEqual(str(p)[0:33], \"<sme.Parameter>\\n - name: 'param'\") self.assertEqual(p.name, \"param\") self.assertEqual(p.value, \"1\") # assign new", "sme.open_example_model() p = m.parameters[\"param\"] # verify name and properties self.assertEqual(repr(p), \"<sme.Parameter named 'param'>\")", "assign new values p.name = \"New param\" p.value = \"0.8765\" self.assertEqual(repr(p), \"<sme.Parameter named", "# get an existing parameter m = sme.open_example_model() p = m.parameters[\"param\"] # verify", "change was propagated to model self.assertRaises( sme.InvalidArgument, lambda: m.parameters[\"param\"], ) p2 = m.parameters[\"New", "m.parameters[\"param\"] # verify name and properties self.assertEqual(repr(p), \"<sme.Parameter named 'param'>\") self.assertEqual(str(p)[0:33], \"<sme.Parameter>\\n -", "self.assertEqual(str(p)[0:33], \"<sme.Parameter>\\n - name: 'param'\") self.assertEqual(p.name, \"param\") self.assertEqual(p.value, \"1\") # assign new values", "and properties self.assertEqual(repr(p), \"<sme.Parameter named 'param'>\") self.assertEqual(str(p)[0:33], \"<sme.Parameter>\\n - name: 'param'\") self.assertEqual(p.name, \"param\")", "check change was propagated to model self.assertRaises( sme.InvalidArgument, lambda: m.parameters[\"param\"], ) p2 =", "m.parameters[\"param\"], ) p2 = m.parameters[\"New param\"] self.assertEqual(p2.name, \"New param\") self.assertEqual(p2.value, \"0.8765\") self.assertEqual(p2, p)", "p.name = \"New param\" p.value = \"0.8765\" self.assertEqual(repr(p), \"<sme.Parameter named 'New param'>\") self.assertEqual(str(p)[0:37],", "# verify name and properties self.assertEqual(repr(p), \"<sme.Parameter named 'param'>\") self.assertEqual(str(p)[0:33], \"<sme.Parameter>\\n - name:", "param'>\") self.assertEqual(str(p)[0:37], \"<sme.Parameter>\\n - name: 'New param'\") self.assertEqual(p.name, \"New param\") self.assertEqual(p.value, \"0.8765\") #", ") p2 = m.parameters[\"New param\"] self.assertEqual(p2.name, \"New param\") self.assertEqual(p2.value, \"0.8765\") self.assertEqual(p2, p) self.assertEqual(p2,", "name and properties self.assertEqual(repr(p), \"<sme.Parameter named 'param'>\") self.assertEqual(str(p)[0:33], \"<sme.Parameter>\\n - name: 'param'\") self.assertEqual(p.name,", "self.assertEqual(p.value, \"1\") # assign new values p.name = \"New param\" p.value = \"0.8765\"", "= \"0.8765\" self.assertEqual(repr(p), \"<sme.Parameter named 'New param'>\") self.assertEqual(str(p)[0:37], \"<sme.Parameter>\\n - name: 'New param'\")", "\"1\") # assign new values p.name = \"New param\" p.value = \"0.8765\" self.assertEqual(repr(p),", "self.assertEqual(p.name, \"param\") self.assertEqual(p.value, \"1\") # assign new values p.name = \"New param\" p.value", "sme class TestParameter(unittest.TestCase): def test_parameter(self): # get an existing parameter m = sme.open_example_model()", "existing parameter m = sme.open_example_model() p = m.parameters[\"param\"] # verify name and properties", "self.assertEqual(repr(p), \"<sme.Parameter named 'New param'>\") self.assertEqual(str(p)[0:37], \"<sme.Parameter>\\n - name: 'New param'\") self.assertEqual(p.name, \"New", "parameter m = sme.open_example_model() p = m.parameters[\"param\"] # verify name and properties self.assertEqual(repr(p),", "\"New param\" p.value = \"0.8765\" self.assertEqual(repr(p), \"<sme.Parameter named 'New param'>\") self.assertEqual(str(p)[0:37], \"<sme.Parameter>\\n -", "param'\") self.assertEqual(p.name, \"New param\") self.assertEqual(p.value, \"0.8765\") # check change was propagated to model", "\"<sme.Parameter>\\n - name: 'New param'\") self.assertEqual(p.name, \"New param\") self.assertEqual(p.value, \"0.8765\") # check change", "get an existing parameter m = sme.open_example_model() p = m.parameters[\"param\"] # verify name", "p2 = m.parameters[\"New param\"] self.assertEqual(p2.name, \"New param\") self.assertEqual(p2.value, \"0.8765\") self.assertEqual(p2, p) self.assertEqual(p2, m.parameters[0])", "# assign new values p.name = \"New param\" p.value = \"0.8765\" self.assertEqual(repr(p), \"<sme.Parameter", "p.value = \"0.8765\" self.assertEqual(repr(p), \"<sme.Parameter named 'New param'>\") self.assertEqual(str(p)[0:37], \"<sme.Parameter>\\n - name: 'New", "\"<sme.Parameter named 'New param'>\") self.assertEqual(str(p)[0:37], \"<sme.Parameter>\\n - name: 'New param'\") self.assertEqual(p.name, \"New param\")", "param\" p.value = \"0.8765\" self.assertEqual(repr(p), \"<sme.Parameter named 'New param'>\") self.assertEqual(str(p)[0:37], \"<sme.Parameter>\\n - name:", "m = sme.open_example_model() p = m.parameters[\"param\"] # verify name and properties self.assertEqual(repr(p), \"<sme.Parameter", "class TestParameter(unittest.TestCase): def test_parameter(self): # get an existing parameter m = sme.open_example_model() p", "# check change was propagated to model self.assertRaises( sme.InvalidArgument, lambda: m.parameters[\"param\"], ) p2", "propagated to model self.assertRaises( sme.InvalidArgument, lambda: m.parameters[\"param\"], ) p2 = m.parameters[\"New param\"] self.assertEqual(p2.name,", "\"<sme.Parameter>\\n - name: 'param'\") self.assertEqual(p.name, \"param\") self.assertEqual(p.value, \"1\") # assign new values p.name", "named 'New param'>\") self.assertEqual(str(p)[0:37], \"<sme.Parameter>\\n - name: 'New param'\") self.assertEqual(p.name, \"New param\") self.assertEqual(p.value,", "= m.parameters[\"param\"] # verify name and properties self.assertEqual(repr(p), \"<sme.Parameter named 'param'>\") self.assertEqual(str(p)[0:33], \"<sme.Parameter>\\n", "TestParameter(unittest.TestCase): def test_parameter(self): # get an existing parameter m = sme.open_example_model() p =", "= sme.open_example_model() p = m.parameters[\"param\"] # verify name and properties self.assertEqual(repr(p), \"<sme.Parameter named", "<reponame>henryiii/spatial-model-editor<filename>sme/test/test_parameter.py import unittest import sme class TestParameter(unittest.TestCase): def test_parameter(self): # get an existing", "new values p.name = \"New param\" p.value = \"0.8765\" self.assertEqual(repr(p), \"<sme.Parameter named 'New", "'New param'\") self.assertEqual(p.name, \"New param\") self.assertEqual(p.value, \"0.8765\") # check change was propagated to", "\"param\") self.assertEqual(p.value, \"1\") # assign new values p.name = \"New param\" p.value =", "self.assertRaises( sme.InvalidArgument, lambda: m.parameters[\"param\"], ) p2 = m.parameters[\"New param\"] self.assertEqual(p2.name, \"New param\") self.assertEqual(p2.value,", "self.assertEqual(p.name, \"New param\") self.assertEqual(p.value, \"0.8765\") # check change was propagated to model self.assertRaises(", "name: 'New param'\") self.assertEqual(p.name, \"New param\") self.assertEqual(p.value, \"0.8765\") # check change was propagated", "- name: 'param'\") self.assertEqual(p.name, \"param\") self.assertEqual(p.value, \"1\") # assign new values p.name =", "= \"New param\" p.value = \"0.8765\" self.assertEqual(repr(p), \"<sme.Parameter named 'New param'>\") self.assertEqual(str(p)[0:37], \"<sme.Parameter>\\n", "model self.assertRaises( sme.InvalidArgument, lambda: m.parameters[\"param\"], ) p2 = m.parameters[\"New param\"] self.assertEqual(p2.name, \"New param\")", "unittest import sme class TestParameter(unittest.TestCase): def test_parameter(self): # get an existing parameter m", "sme.InvalidArgument, lambda: m.parameters[\"param\"], ) p2 = m.parameters[\"New param\"] self.assertEqual(p2.name, \"New param\") self.assertEqual(p2.value, \"0.8765\")", "was propagated to model self.assertRaises( sme.InvalidArgument, lambda: m.parameters[\"param\"], ) p2 = m.parameters[\"New param\"]", "properties self.assertEqual(repr(p), \"<sme.Parameter named 'param'>\") self.assertEqual(str(p)[0:33], \"<sme.Parameter>\\n - name: 'param'\") self.assertEqual(p.name, \"param\") self.assertEqual(p.value,", "p = m.parameters[\"param\"] # verify name and properties self.assertEqual(repr(p), \"<sme.Parameter named 'param'>\") self.assertEqual(str(p)[0:33],", "test_parameter(self): # get an existing parameter m = sme.open_example_model() p = m.parameters[\"param\"] #", "an existing parameter m = sme.open_example_model() p = m.parameters[\"param\"] # verify name and", "lambda: m.parameters[\"param\"], ) p2 = m.parameters[\"New param\"] self.assertEqual(p2.name, \"New param\") self.assertEqual(p2.value, \"0.8765\") self.assertEqual(p2,", "\"<sme.Parameter named 'param'>\") self.assertEqual(str(p)[0:33], \"<sme.Parameter>\\n - name: 'param'\") self.assertEqual(p.name, \"param\") self.assertEqual(p.value, \"1\") #" ]
[ "emails during the tests # Create a test client using the Flask application", "= 'https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=MSFT&apikey=demo' monkeypatch.setattr(requests, 'get', mock_get) @pytest.fixture(scope='function') def mock_requests_get_failure(monkeypatch): def mock_get(url): return MockFailedResponse(url) url", "} class MockApiRateLimitExceededResponse(object): def __init__(self, url): self.status_code = 200 self.url = url def", "= url def json(self): return { 'Note': 'Thank you for using Alpha Vantage!", "@pytest.fixture(scope='function') def log_in_default_user(test_client, register_default_user): # Log in the default user test_client.post('/users/login', data={'email': '<EMAIL>',", "using Alpha Vantage! Our standard API call frequency is ' + '5 calls", "calls per day.' } class MockFailedResponse(object): def __init__(self, url): self.status_code = 404 self.url", "register_second_user): # Log in the user test_client.post('/users/login', data={'email': '<EMAIL>', 'password': '<PASSWORD>'}) yield #", "= 'https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=MSFT&apikey=demo' monkeypatch.setattr(requests, 'get', mock_get) @pytest.fixture(scope='function') def mock_requests_get_success_weekly(monkeypatch): # Create a mock for", "default user test_client.post('/users/login', data={'email': '<EMAIL>', 'password': '<PASSWORD>'}, follow_redirects=True) yield # this is where", "Our standard API call frequency is ' + '5 calls per minute and", "@pytest.fixture(scope='function') def mock_requests_get_success_daily(monkeypatch): # Create a mock for the requests.get() call to prevent", "\"135.9800\", } } } class MockApiRateLimitExceededResponse(object): def __init__(self, url): self.status_code = 200 self.url", "reset the password back to the default password user = User.query.filter_by(email='<EMAIL>').first() user.set_password('<PASSWORD>') db.session.add(user)", "{ \"2022-02-10\": { \"4. close\": \"302.3800\", }, \"2022-02-09\": { \"4. close\": \"301.9800\", }", "url def json(self): return {'error': 'bad'} class MockSuccessResponseWeekly(object): def __init__(self, url): self.status_code =", "to the default password user = User.query.filter_by(email='<EMAIL>').first() user.set_password('<PASSWORD>') db.session.add(user) db.session.commit() @pytest.fixture(scope='function') def add_stocks_for_default_user(test_client,", "} } class MockFailedResponse(object): def __init__(self, url): self.status_code = 404 self.url = url", "default user, # reset the password back to the default password user =", "json(self): return { 'Meta Data': { \"2. Symbol\": \"AAPL\", \"3. Last Refreshed\": \"2020-07-28\"", "{ 'Meta Data': { \"2. Symbol\": \"AAPL\", \"3. Last Refreshed\": \"2020-07-28\" }, 'Weekly", "actual API call def mock_get(url): return MockSuccessResponseDaily(url) url = 'https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=MSFT&apikey=demo' monkeypatch.setattr(requests, 'get', mock_get)", "{'error': 'bad'} class MockSuccessResponseDaily(object): def __init__(self, url): self.status_code = 200 self.url = url", "mock_get(url): return MockFailedResponse(url) url = 'https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=MSFT&apikey=demo' monkeypatch.setattr(requests, 'get', mock_get) @pytest.fixture(scope='function') def mock_requests_get_success_weekly(monkeypatch): #", "# this is where the testing happens! # Log out the user test_client.get('/users/logout',", "url = 'https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=MSFT&apikey=demo' monkeypatch.setattr(requests, 'get', mock_get) @pytest.fixture(scope='function') def mock_requests_get_api_rate_limit_exceeded(monkeypatch): def mock_get(url): return MockApiRateLimitExceededResponse(url)", "API call def mock_get(url): return MockSuccessResponseWeekly(url) url = 'https://www.alphavantage.co/query?function=TIME_SERIES_WEEKLY_ADJUSTED&symbol=MSFT&apikey=demo' monkeypatch.setattr(requests, 'get', mock_get) #", "import datetime ######################## #### Helper Classes #### ######################## class MockSuccessResponse(object): def __init__(self, url):", "default user test_client.post('/add_stock', data={'stock_symbol': 'SAM', 'number_of_shares': '27', 'purchase_price': '301.23', 'purchase_date': '2020-07-01'}) test_client.post('/add_stock', data={'stock_symbol':", "a mock for the requests.get() call to prevent making the actual API call", "yield # this is where the testing happens! # Since a test using", "'https://www.alphavantage.co/query?function=TIME_SERIES_WEEKLY_ADJUSTED&symbol=MSFT&apikey=demo' monkeypatch.setattr(requests, 'get', mock_get) # ***register-login-logout 2nd user*** @pytest.fixture(scope='module') def register_second_user(test_client): \"\"\"Registers the", "change the password for the default user, # reset the password back to", "@pytest.fixture(scope='module') def new_user(): user = User('<EMAIL>', '<PASSWORD>') return user # to register a", "12)) return stock @pytest.fixture(scope='module') def new_user(): user = User('<EMAIL>', '<PASSWORD>') return user #", "self.url = url def json(self): return {'error': 'bad'} class MockSuccessResponseWeekly(object): def __init__(self, url):", "Series': { \"2020-07-24\": { \"4. close\": \"379.2400\", }, \"2020-07-17\": { \"4. close\": \"362.7600\",", "per minute and 500 calls per day.' } class MockFailedResponse(object): def __init__(self, url):", "using the Flask application configured for testing with flask_app.test_client() as testing_client: # establish", "# this is where the testing happens! # Log out the default user", "their email address confirmed user = User.query.filter_by(email='<EMAIL>').first() user.email_confirmed = True user.email_confirmed_on = datetime(2020,", "moking requests.get()*** @pytest.fixture(scope='function') def mock_requests_get_success_daily(monkeypatch): # Create a mock for the requests.get() call", "= 200 self.url = url self.headers = {'blaa': '1234'} def json(self): return {", "= {'blaa': '1234'} def json(self): return { 'Meta Data': { \"2. Symbol\": \"MSFT\",", "500 calls per day.' } class MockFailedResponse(object): def __init__(self, url): self.status_code = 404", "the '/users/register' route.\"\"\" test_client.post('/users/register', data={'name':'<NAME>', 'email': '<EMAIL>', 'password': '<PASSWORD>'}) @pytest.fixture(scope='function') def log_in_second_user(test_client, register_second_user):", "+ '5 calls per minute and 500 calls per day.' } class MockFailedResponse(object):", "#### Helper Classes #### ######################## class MockSuccessResponse(object): def __init__(self, url): self.status_code = 200", "where the testing happens! # Mark the user as not having their email", "class MockFailedResponse(object): def __init__(self, url): self.status_code = 404 self.url = url def json(self):", "# Log in the default user test_client.post('/users/login', data={'email': '<EMAIL>', 'password': '<PASSWORD>'}, follow_redirects=True) yield", "'password': '<PASSWORD>'}, follow_redirects=True) return # is default user logged in? @pytest.fixture(scope='function') def log_in_default_user(test_client,", "8) db.session.add(user) db.session.commit() yield user # this is where the testing happens! #", "Time Series': { \"2020-07-24\": { \"4. close\": \"379.2400\", }, \"2020-07-17\": { \"4. close\":", "self.headers = {'blaa': '1234'} def json(self): return {'error': 'bad'} class MockSuccessResponseDaily(object): def __init__(self,", "def register_second_user(test_client): \"\"\"Registers the second user using the '/users/register' route.\"\"\" test_client.post('/users/register', data={'name':'<NAME>', 'email':", "'5 calls per minute and 500 calls per day.' } class MockFailedResponse(object): def", "Classes #### ######################## class MockSuccessResponse(object): def __init__(self, url): self.status_code = 200 self.url =", "= {'blaa': '1234'} def json(self): return {'error': 'bad'} class MockSuccessResponseDaily(object): def __init__(self, url):", "requests.get()*** @pytest.fixture(scope='function') def mock_requests_get_success_daily(monkeypatch): # Create a mock for the requests.get() call to", "return { 'Meta Data': { \"2. Symbol\": \"MSFT\", \"3. Last Refreshed\": \"2022-02-10\" },", "testing happens! # Since a test using this fixture could change the password", "mock_get) # ***register-login-logout 2nd user*** @pytest.fixture(scope='module') def register_second_user(test_client): \"\"\"Registers the second user using", "\"2022-02-09\": { \"4. close\": \"135.9800\", } } } class MockApiRateLimitExceededResponse(object): def __init__(self, url):", "__init__(self, url): self.status_code = 200 self.url = url self.headers = {'blaa': '1234'} def", "user test_client.post('/users/register', data={'name':'<NAME>', 'email': '<EMAIL>', 'password': '<PASSWORD>'}, follow_redirects=True) return # is default user", "data={'email': '<EMAIL>', 'password': '<PASSWORD>'}, follow_redirects=True) yield # this is where the testing happens!", "close\": \"302.3800\", }, \"2022-02-09\": { \"4. close\": \"301.9800\", } } } class MockFailedResponse(object):", "the actual API call def mock_get(url): return MockSuccessResponseDaily(url) url = 'https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=MSFT&apikey=demo' monkeypatch.setattr(requests, 'get',", "default user test_client.get('/users/logout', follow_redirects=True) @pytest.fixture(scope='function') def confirm_email_default_user(test_client, log_in_default_user): # Mark the user as", "db.session.commit() @pytest.fixture(scope='function') def add_stocks_for_default_user(test_client, log_in_default_user): # Add three stocks for the default user", "def test_client(): flask_app = create_app() flask_app.config.from_object('config.TestingConfig') flask_app.extensions['mail'].suppress = True #to avoid sending emails", "'2020-07-01'}) test_client.post('/add_stock', data={'stock_symbol': 'COST', 'number_of_shares': '76', 'purchase_price': '14.67', 'purchase_date': '2019-05-26'}) test_client.post('/add_stock', data={'stock_symbol': 'TWTR',", "'get', mock_get) @pytest.fixture(scope='function') def mock_requests_get_api_rate_limit_exceeded(monkeypatch): def mock_get(url): return MockApiRateLimitExceededResponse(url) url = 'https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=MSFT&apikey=demo' monkeypatch.setattr(requests,", "the second user using the '/users/register' route.\"\"\" test_client.post('/users/register', data={'name':'<NAME>', 'email': '<EMAIL>', 'password': '<PASSWORD>'})", "\"2020-02-25\": { \"4. close\": \"432.9800\", } } } @pytest.fixture(scope='module') def test_client(): flask_app =", "@pytest.fixture(scope='function') def new_stock(): stock = Stock('AAPL', '16', '406.78', 7, datetime(2022, 2, 12)) return", "\"4. close\": \"354.3400\", }, \"2020-02-25\": { \"4. close\": \"432.9800\", } } } @pytest.fixture(scope='module')", "def mock_get(url): return MockApiRateLimitExceededResponse(url) url = 'https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=MSFT&apikey=demo' monkeypatch.setattr(requests, 'get', mock_get) @pytest.fixture(scope='function') def mock_requests_get_failure(monkeypatch):", "def json(self): return { 'Meta Data': { \"2. Symbol\": \"MSFT\", \"3. Last Refreshed\":", "{ 'Meta Data': { \"2. Symbol\": \"AAPL\", \"3. Last Refreshed\": \"2020-03-24\" }, 'Time", "'purchase_price': '14.67', 'purchase_date': '2019-05-26'}) test_client.post('/add_stock', data={'stock_symbol': 'TWTR', 'number_of_shares': '146', 'purchase_price': '34.56', 'purchase_date': '2020-02-03'})", "application configured for testing with flask_app.test_client() as testing_client: # establish an app ctx", "testing_client #where the test happens @pytest.fixture(scope='function') def new_stock(): stock = Stock('AAPL', '16', '406.78',", "the testing happens! # Mark the user as not having their email address", "def register_default_user(test_client): # Register the default user test_client.post('/users/register', data={'name':'<NAME>', 'email': '<EMAIL>', 'password': '<PASSWORD>'},", "happens! # Log out the default user test_client.get('/users/logout', follow_redirects=True) @pytest.fixture(scope='function') def confirm_email_default_user(test_client, log_in_default_user):", "Create a mock for the requests.get() call to prevent making the actual API", "the logger with flask_app.app_context(): flask_app.logger.info('Creating database tables in test_client fixture...') yield testing_client #where", "7, 8) db.session.add(user) db.session.commit() yield user # this is where the testing happens!", "yield # this is where the testing happens! # Log out the user", "data={'name':'<NAME>', 'email': '<EMAIL>', 'password': '<PASSWORD>'}, follow_redirects=True) return # is default user logged in?", "self.url = url def json(self): return { 'Meta Data': { \"2. Symbol\": \"AAPL\",", "user.set_password('<PASSWORD>') db.session.add(user) db.session.commit() @pytest.fixture(scope='function') def add_stocks_for_default_user(test_client, log_in_default_user): # Add three stocks for the", "create_app() flask_app.config.from_object('config.TestingConfig') flask_app.extensions['mail'].suppress = True #to avoid sending emails during the tests #", "test_client.post('/users/login', data={'email': '<EMAIL>', 'password': '<PASSWORD>'}) yield # this is where the testing happens!", "{ \"4. close\": \"148.3400\", }, \"2022-02-09\": { \"4. close\": \"135.9800\", } } }", "test_client.post('/users/login', data={'email': '<EMAIL>', 'password': '<PASSWORD>'}, follow_redirects=True) yield # this is where the testing", "password back to the default password user = User.query.filter_by(email='<EMAIL>').first() user.set_password('<PASSWORD>') db.session.add(user) db.session.commit() @pytest.fixture(scope='function')", "confirm_email_default_user(test_client, log_in_default_user): # Mark the user as having their email address confirmed user", "'COST', 'number_of_shares': '76', 'purchase_price': '14.67', 'purchase_date': '2019-05-26'}) test_client.post('/add_stock', data={'stock_symbol': 'TWTR', 'number_of_shares': '146', 'purchase_price':", "second user using the '/users/register' route.\"\"\" test_client.post('/users/register', data={'name':'<NAME>', 'email': '<EMAIL>', 'password': '<PASSWORD>'}) @pytest.fixture(scope='function')", "afterwards_reset_default_user_password(): yield # this is where the testing happens! # Since a test", "{ \"4. close\": \"301.9800\", } } } class MockFailedResponse(object): def __init__(self, url): self.status_code", "}, \"2022-02-09\": { \"4. close\": \"301.9800\", } } } class MockFailedResponse(object): def __init__(self,", "test using this fixture could change the password for the default user, #", "return MockSuccessResponseWeekly(url) url = 'https://www.alphavantage.co/query?function=TIME_SERIES_WEEKLY_ADJUSTED&symbol=MSFT&apikey=demo' monkeypatch.setattr(requests, 'get', mock_get) # ***register-login-logout 2nd user*** @pytest.fixture(scope='module')", "tests # Create a test client using the Flask application configured for testing", "'password': '<PASSWORD>'}, follow_redirects=True) yield # this is where the testing happens! # Log", "User.query.filter_by(email='<EMAIL>').first() user.email_confirmed = True user.email_confirmed_on = datetime(2020, 7, 8) db.session.add(user) db.session.commit() yield user", "to prevent making the actual API call def mock_get(url): return MockSuccessResponseWeekly(url) url =", "{'error': 'bad'} class MockSuccessResponseWeekly(object): def __init__(self, url): self.status_code = 200 self.url = url", "in test_client fixture...') yield testing_client #where the test happens @pytest.fixture(scope='function') def new_stock(): stock", "up) user = User.query.filter_by(email='<EMAIL>').first() user.email_confirmed = False user.email_confirmed_on = None db.session.add(user) db.session.commit() @pytest.fixture(scope='function')", "datetime ######################## #### Helper Classes #### ######################## class MockSuccessResponse(object): def __init__(self, url): self.status_code", "'https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=MSFT&apikey=demo' monkeypatch.setattr(requests, 'get', mock_get) @pytest.fixture(scope='function') def mock_requests_get_failure(monkeypatch): def mock_get(url): return MockFailedResponse(url) url =", "# establish an app ctx be4 accessing the logger with flask_app.app_context(): flask_app.logger.info('Creating database", "user test_client.post('/add_stock', data={'stock_symbol': 'SAM', 'number_of_shares': '27', 'purchase_price': '301.23', 'purchase_date': '2020-07-01'}) test_client.post('/add_stock', data={'stock_symbol': 'COST',", "the tests # Create a test client using the Flask application configured for", "'number_of_shares': '76', 'purchase_price': '14.67', 'purchase_date': '2019-05-26'}) test_client.post('/add_stock', data={'stock_symbol': 'TWTR', 'number_of_shares': '146', 'purchase_price': '34.56',", "the user test_client.post('/users/login', data={'email': '<EMAIL>', 'password': '<PASSWORD>'}) yield # this is where the", "= Stock('AAPL', '16', '406.78', 7, datetime(2022, 2, 12)) return stock @pytest.fixture(scope='module') def new_user():", "out the default user test_client.get('/users/logout', follow_redirects=True) @pytest.fixture(scope='function') def confirm_email_default_user(test_client, log_in_default_user): # Mark the", "is where the testing happens! # Log out the default user test_client.get('/users/logout', follow_redirects=True)", "add_stocks_for_default_user(test_client, log_in_default_user): # Add three stocks for the default user test_client.post('/add_stock', data={'stock_symbol': 'SAM',", "datetime(2020, 7, 8) db.session.add(user) db.session.commit() yield user # this is where the testing", "follow_redirects=True) yield # this is where the testing happens! # Log out the", "= True #to avoid sending emails during the tests # Create a test", "} @pytest.fixture(scope='module') def test_client(): flask_app = create_app() flask_app.config.from_object('config.TestingConfig') flask_app.extensions['mail'].suppress = True #to avoid", "address confirmed (clean up) user = User.query.filter_by(email='<EMAIL>').first() user.email_confirmed = False user.email_confirmed_on = None", "the password for the default user, # reset the password back to the", "'<EMAIL>', 'password': '<PASSWORD>'}, follow_redirects=True) yield # this is where the testing happens! #", "password for the default user, # reset the password back to the default", "'14.67', 'purchase_date': '2019-05-26'}) test_client.post('/add_stock', data={'stock_symbol': 'TWTR', 'number_of_shares': '146', 'purchase_price': '34.56', 'purchase_date': '2020-02-03'}) return", "# Mark the user as having their email address confirmed user = User.query.filter_by(email='<EMAIL>').first()", "self.status_code = 404 self.url = url def json(self): return {'error': 'bad'} class MockSuccessResponseWeekly(object):", "monkeypatch.setattr(requests, 'get', mock_get) @pytest.fixture(scope='function') def mock_requests_get_success_weekly(monkeypatch): # Create a mock for the requests.get()", "stocks for the default user test_client.post('/add_stock', data={'stock_symbol': 'SAM', 'number_of_shares': '27', 'purchase_price': '301.23', 'purchase_date':", "Stock, User from datetime import datetime ######################## #### Helper Classes #### ######################## class", "User.query.filter_by(email='<EMAIL>').first() user.set_password('<PASSWORD>') db.session.add(user) db.session.commit() @pytest.fixture(scope='function') def add_stocks_for_default_user(test_client, log_in_default_user): # Add three stocks for", "= User.query.filter_by(email='<EMAIL>').first() user.email_confirmed = True user.email_confirmed_on = datetime(2020, 7, 8) db.session.add(user) db.session.commit() yield", "data={'email': '<EMAIL>', 'password': '<PASSWORD>'}) yield # this is where the testing happens! #", "db.session.add(user) db.session.commit() yield user # this is where the testing happens! # Mark", "to register a default user @pytest.fixture(scope='module') def register_default_user(test_client): # Register the default user", "current_app from project.models import Stock, User from datetime import datetime ######################## #### Helper", "close\": \"362.7600\", }, \"2020-06-11\": { \"4. close\": \"354.3400\", }, \"2020-02-25\": { \"4. close\":", "mock_requests_get_success_daily(monkeypatch): # Create a mock for the requests.get() call to prevent making the", "the requests.get() call to prevent making the actual API call def mock_get(url): return", "call to prevent making the actual API call def mock_get(url): return MockSuccessResponseWeekly(url) url", "@pytest.fixture(scope='module') def test_client(): flask_app = create_app() flask_app.config.from_object('config.TestingConfig') flask_app.extensions['mail'].suppress = True #to avoid sending", "Series (Daily)': { \"2022-02-10\": { \"4. close\": \"302.3800\", }, \"2022-02-09\": { \"4. close\":", "close\": \"301.9800\", } } } class MockFailedResponse(object): def __init__(self, url): self.status_code = 404", "new_user(): user = User('<EMAIL>', '<PASSWORD>') return user # to register a default user", "\"432.9800\", } } } @pytest.fixture(scope='module') def test_client(): flask_app = create_app() flask_app.config.from_object('config.TestingConfig') flask_app.extensions['mail'].suppress =", "client using the Flask application configured for testing with flask_app.test_client() as testing_client: #", "the test happens @pytest.fixture(scope='function') def new_stock(): stock = Stock('AAPL', '16', '406.78', 7, datetime(2022,", "log_in_second_user(test_client, register_second_user): # Log in the user test_client.post('/users/login', data={'email': '<EMAIL>', 'password': '<PASSWORD>'}) yield", "'2019-05-26'}) test_client.post('/add_stock', data={'stock_symbol': 'TWTR', 'number_of_shares': '146', 'purchase_price': '34.56', 'purchase_date': '2020-02-03'}) return # ***fixtures", "True user.email_confirmed_on = datetime(2020, 7, 8) db.session.add(user) db.session.commit() yield user # this is", "def mock_requests_get_api_rate_limit_exceeded(monkeypatch): def mock_get(url): return MockApiRateLimitExceededResponse(url) url = 'https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=MSFT&apikey=demo' monkeypatch.setattr(requests, 'get', mock_get) @pytest.fixture(scope='function')", "from flask import current_app from project.models import Stock, User from datetime import datetime", "{ 'Meta Data': { \"2. Symbol\": \"MSFT\", \"3. Last Refreshed\": \"2022-02-10\" }, 'Time", "MockFailedResponse(object): def __init__(self, url): self.status_code = 404 self.url = url self.headers = {'blaa':", "{ \"2020-07-24\": { \"4. close\": \"379.2400\", }, \"2020-07-17\": { \"4. close\": \"362.7600\", },", "'27', 'purchase_price': '301.23', 'purchase_date': '2020-07-01'}) test_client.post('/add_stock', data={'stock_symbol': 'COST', 'number_of_shares': '76', 'purchase_price': '14.67', 'purchase_date':", "for using Alpha Vantage! Our standard API call frequency is ' + '5", "user as having their email address confirmed user = User.query.filter_by(email='<EMAIL>').first() user.email_confirmed = True", "data={'stock_symbol': 'COST', 'number_of_shares': '76', 'purchase_price': '14.67', 'purchase_date': '2019-05-26'}) test_client.post('/add_stock', data={'stock_symbol': 'TWTR', 'number_of_shares': '146',", "@pytest.fixture(scope='function') def mock_requests_get_success_weekly(monkeypatch): # Create a mock for the requests.get() call to prevent", "using the '/users/register' route.\"\"\" test_client.post('/users/register', data={'name':'<NAME>', 'email': '<EMAIL>', 'password': '<PASSWORD>'}) @pytest.fixture(scope='function') def log_in_second_user(test_client,", "from datetime import datetime ######################## #### Helper Classes #### ######################## class MockSuccessResponse(object): def", "'Meta Data': { \"2. Symbol\": \"AAPL\", \"3. Last Refreshed\": \"2020-03-24\" }, 'Time Series", "self.status_code = 200 self.url = url def json(self): return { 'Note': 'Thank you", "Register the default user test_client.post('/users/register', data={'name':'<NAME>', 'email': '<EMAIL>', 'password': '<PASSWORD>'}, follow_redirects=True) return #", "'Thank you for using Alpha Vantage! Our standard API call frequency is '", "MockSuccessResponse(object): def __init__(self, url): self.status_code = 200 self.url = url self.headers = {'blaa':", "test_client.post('/add_stock', data={'stock_symbol': 'COST', 'number_of_shares': '76', 'purchase_price': '14.67', 'purchase_date': '2019-05-26'}) test_client.post('/add_stock', data={'stock_symbol': 'TWTR', 'number_of_shares':", "MockApiRateLimitExceededResponse(url) url = 'https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=MSFT&apikey=demo' monkeypatch.setattr(requests, 'get', mock_get) @pytest.fixture(scope='function') def mock_requests_get_failure(monkeypatch): def mock_get(url): return", "# Mark the user as not having their email address confirmed (clean up)", "\"2020-07-28\" }, 'Weekly Adjusted Time Series': { \"2020-07-24\": { \"4. close\": \"379.2400\", },", "'<EMAIL>', 'password': '<PASSWORD>'}) yield # this is where the testing happens! # Log", "= False user.email_confirmed_on = None db.session.add(user) db.session.commit() @pytest.fixture(scope='function') def afterwards_reset_default_user_password(): yield # this", "__init__(self, url): self.status_code = 200 self.url = url def json(self): return { 'Note':", "data={'stock_symbol': 'TWTR', 'number_of_shares': '146', 'purchase_price': '34.56', 'purchase_date': '2020-02-03'}) return # ***fixtures for moking", "monkeypatch.setattr(requests, 'get', mock_get) @pytest.fixture(scope='function') def mock_requests_get_failure(monkeypatch): def mock_get(url): return MockFailedResponse(url) url = 'https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=MSFT&apikey=demo'", "return MockApiRateLimitExceededResponse(url) url = 'https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=MSFT&apikey=demo' monkeypatch.setattr(requests, 'get', mock_get) @pytest.fixture(scope='function') def mock_requests_get_failure(monkeypatch): def mock_get(url):", "'email': '<EMAIL>', 'password': '<PASSWORD>'}, follow_redirects=True) return # is default user logged in? @pytest.fixture(scope='function')", "\"2. Symbol\": \"MSFT\", \"3. Last Refreshed\": \"2022-02-10\" }, 'Time Series (Daily)': { \"2022-02-10\":", "} } class MockApiRateLimitExceededResponse(object): def __init__(self, url): self.status_code = 200 self.url = url", "= None db.session.add(user) db.session.commit() @pytest.fixture(scope='function') def afterwards_reset_default_user_password(): yield # this is where the", "call def mock_get(url): return MockSuccessResponseDaily(url) url = 'https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=MSFT&apikey=demo' monkeypatch.setattr(requests, 'get', mock_get) @pytest.fixture(scope='function') def", "Series (Daily)': { \"2022-02-10\": { \"4. close\": \"148.3400\", }, \"2022-02-09\": { \"4. close\":", "\"AAPL\", \"3. Last Refreshed\": \"2020-03-24\" }, 'Time Series (Daily)': { \"2022-02-10\": { \"4.", "def mock_get(url): return MockSuccessResponseDaily(url) url = 'https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=MSFT&apikey=demo' monkeypatch.setattr(requests, 'get', mock_get) @pytest.fixture(scope='function') def mock_requests_get_api_rate_limit_exceeded(monkeypatch):", "default user @pytest.fixture(scope='module') def register_default_user(test_client): # Register the default user test_client.post('/users/register', data={'name':'<NAME>', 'email':", "flask_app.test_client() as testing_client: # establish an app ctx be4 accessing the logger with", "'<PASSWORD>') return user # to register a default user @pytest.fixture(scope='module') def register_default_user(test_client): #", "Mark the user as having their email address confirmed user = User.query.filter_by(email='<EMAIL>').first() user.email_confirmed", "the password back to the default password user = User.query.filter_by(email='<EMAIL>').first() user.set_password('<PASSWORD>') db.session.add(user) db.session.commit()", "# to register a default user @pytest.fixture(scope='module') def register_default_user(test_client): # Register the default", "Last Refreshed\": \"2020-07-28\" }, 'Weekly Adjusted Time Series': { \"2020-07-24\": { \"4. close\":", "#to avoid sending emails during the tests # Create a test client using", "\"301.9800\", } } } class MockFailedResponse(object): def __init__(self, url): self.status_code = 404 self.url", "datetime(2022, 2, 12)) return stock @pytest.fixture(scope='module') def new_user(): user = User('<EMAIL>', '<PASSWORD>') return", "@pytest.fixture(scope='function') def mock_requests_get_api_rate_limit_exceeded(monkeypatch): def mock_get(url): return MockApiRateLimitExceededResponse(url) url = 'https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=MSFT&apikey=demo' monkeypatch.setattr(requests, 'get', mock_get)", "fixture could change the password for the default user, # reset the password", "return {'error': 'bad'} class MockSuccessResponseWeekly(object): def __init__(self, url): self.status_code = 200 self.url =", "= 404 self.url = url def json(self): return {'error': 'bad'} class MockSuccessResponseWeekly(object): def", "{ \"2022-02-10\": { \"4. close\": \"148.3400\", }, \"2022-02-09\": { \"4. close\": \"135.9800\", }", "this is where the testing happens! # Mark the user as not having", "} } } class MockFailedResponse(object): def __init__(self, url): self.status_code = 404 self.url =", "this is where the testing happens! # Log out the default user test_client.get('/users/logout',", "__init__(self, url): self.status_code = 404 self.url = url def json(self): return {'error': 'bad'}", "project.models import Stock, User from datetime import datetime ######################## #### Helper Classes ####", "testing happens! # Log out the default user test_client.get('/users/logout', follow_redirects=True) @pytest.fixture(scope='function') def confirm_email_default_user(test_client,", "\"\"\"Registers the second user using the '/users/register' route.\"\"\" test_client.post('/users/register', data={'name':'<NAME>', 'email': '<EMAIL>', 'password':", "######################## #### Helper Classes #### ######################## class MockSuccessResponse(object): def __init__(self, url): self.status_code =", "the default user test_client.post('/add_stock', data={'stock_symbol': 'SAM', 'number_of_shares': '27', 'purchase_price': '301.23', 'purchase_date': '2020-07-01'}) test_client.post('/add_stock',", "@pytest.fixture(scope='function') def log_in_second_user(test_client, register_second_user): # Log in the user test_client.post('/users/login', data={'email': '<EMAIL>', 'password':", "#### ######################## class MockSuccessResponse(object): def __init__(self, url): self.status_code = 200 self.url = url", "return # is default user logged in? @pytest.fixture(scope='function') def log_in_default_user(test_client, register_default_user): # Log", "mock_get(url): return MockApiRateLimitExceededResponse(url) url = 'https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=MSFT&apikey=demo' monkeypatch.setattr(requests, 'get', mock_get) @pytest.fixture(scope='function') def mock_requests_get_failure(monkeypatch): def", "happens @pytest.fixture(scope='function') def new_stock(): stock = Stock('AAPL', '16', '406.78', 7, datetime(2022, 2, 12))", "'406.78', 7, datetime(2022, 2, 12)) return stock @pytest.fixture(scope='module') def new_user(): user = User('<EMAIL>',", "default user test_client.post('/users/register', data={'name':'<NAME>', 'email': '<EMAIL>', 'password': '<PASSWORD>'}, follow_redirects=True) return # is default", "user # this is where the testing happens! # Mark the user as", "***register-login-logout 2nd user*** @pytest.fixture(scope='module') def register_second_user(test_client): \"\"\"Registers the second user using the '/users/register'", "def mock_requests_get_success_daily(monkeypatch): # Create a mock for the requests.get() call to prevent making", "'<EMAIL>', 'password': '<PASSWORD>'}) @pytest.fixture(scope='function') def log_in_second_user(test_client, register_second_user): # Log in the user test_client.post('/users/login',", "user test_client.get('/users/logout', follow_redirects=True) @pytest.fixture(scope='function') def confirm_email_default_user(test_client, log_in_default_user): # Mark the user as having", "= 200 self.url = url def json(self): return { 'Meta Data': { \"2.", "Log in the user test_client.post('/users/login', data={'email': '<EMAIL>', 'password': '<PASSWORD>'}) yield # this is", "'Meta Data': { \"2. Symbol\": \"AAPL\", \"3. Last Refreshed\": \"2020-07-28\" }, 'Weekly Adjusted", "def __init__(self, url): self.status_code = 404 self.url = url self.headers = {'blaa': '1234'}", "the default password user = User.query.filter_by(email='<EMAIL>').first() user.set_password('<PASSWORD>') db.session.add(user) db.session.commit() @pytest.fixture(scope='function') def add_stocks_for_default_user(test_client, log_in_default_user):", "return {'error': 'bad'} class MockSuccessResponseDaily(object): def __init__(self, url): self.status_code = 200 self.url =", "monkeypatch.setattr(requests, 'get', mock_get) @pytest.fixture(scope='function') def mock_requests_get_api_rate_limit_exceeded(monkeypatch): def mock_get(url): return MockApiRateLimitExceededResponse(url) url = 'https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=MSFT&apikey=demo'", "def log_in_default_user(test_client, register_default_user): # Log in the default user test_client.post('/users/login', data={'email': '<EMAIL>', 'password':", "return MockSuccessResponseDaily(url) url = 'https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=MSFT&apikey=demo' monkeypatch.setattr(requests, 'get', mock_get) @pytest.fixture(scope='function') def mock_requests_get_api_rate_limit_exceeded(monkeypatch): def mock_get(url):", "\"4. close\": \"362.7600\", }, \"2020-06-11\": { \"4. close\": \"354.3400\", }, \"2020-02-25\": { \"4.", "# ***fixtures for moking requests.get()*** @pytest.fixture(scope='function') def mock_requests_get_success_daily(monkeypatch): # Create a mock for", "url): self.status_code = 200 self.url = url def json(self): return { 'Meta Data':", "def __init__(self, url): self.status_code = 200 self.url = url def json(self): return {", "\"302.3800\", }, \"2022-02-09\": { \"4. close\": \"301.9800\", } } } class MockFailedResponse(object): def", "from project.models import Stock, User from datetime import datetime ######################## #### Helper Classes", "is where the testing happens! # Since a test using this fixture could", "to prevent making the actual API call def mock_get(url): return MockSuccessResponseDaily(url) url =", "def log_in_second_user(test_client, register_second_user): # Log in the user test_client.post('/users/login', data={'email': '<EMAIL>', 'password': '<PASSWORD>'})", "API call frequency is ' + '5 calls per minute and 500 calls", "def json(self): return { 'Meta Data': { \"2. Symbol\": \"AAPL\", \"3. Last Refreshed\":", "'purchase_date': '2020-02-03'}) return # ***fixtures for moking requests.get()*** @pytest.fixture(scope='function') def mock_requests_get_success_daily(monkeypatch): # Create", "}, \"2020-02-25\": { \"4. close\": \"432.9800\", } } } @pytest.fixture(scope='module') def test_client(): flask_app", "Refreshed\": \"2020-07-28\" }, 'Weekly Adjusted Time Series': { \"2020-07-24\": { \"4. close\": \"379.2400\",", "making the actual API call def mock_get(url): return MockSuccessResponseDaily(url) url = 'https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=MSFT&apikey=demo' monkeypatch.setattr(requests,", "with flask_app.test_client() as testing_client: # establish an app ctx be4 accessing the logger", "test_client.post('/add_stock', data={'stock_symbol': 'TWTR', 'number_of_shares': '146', 'purchase_price': '34.56', 'purchase_date': '2020-02-03'}) return # ***fixtures for", "log_in_default_user(test_client, register_default_user): # Log in the default user test_client.post('/users/login', data={'email': '<EMAIL>', 'password': '<PASSWORD>'},", "is ' + '5 calls per minute and 500 calls per day.' }", "establish an app ctx be4 accessing the logger with flask_app.app_context(): flask_app.logger.info('Creating database tables", "Since a test using this fixture could change the password for the default", "######################## class MockSuccessResponse(object): def __init__(self, url): self.status_code = 200 self.url = url self.headers", "the default user test_client.post('/users/register', data={'name':'<NAME>', 'email': '<EMAIL>', 'password': '<PASSWORD>'}, follow_redirects=True) return # is", "def mock_get(url): return MockFailedResponse(url) url = 'https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=MSFT&apikey=demo' monkeypatch.setattr(requests, 'get', mock_get) @pytest.fixture(scope='function') def mock_requests_get_success_weekly(monkeypatch):", "url = 'https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=MSFT&apikey=demo' monkeypatch.setattr(requests, 'get', mock_get) @pytest.fixture(scope='function') def mock_requests_get_success_weekly(monkeypatch): # Create a mock", "\"2022-02-10\" }, 'Time Series (Daily)': { \"2022-02-10\": { \"4. close\": \"302.3800\", }, \"2022-02-09\":", "db.session.add(user) db.session.commit() @pytest.fixture(scope='function') def afterwards_reset_default_user_password(): yield # this is where the testing happens!", "having their email address confirmed (clean up) user = User.query.filter_by(email='<EMAIL>').first() user.email_confirmed = False", "def mock_get(url): return MockSuccessResponseWeekly(url) url = 'https://www.alphavantage.co/query?function=TIME_SERIES_WEEKLY_ADJUSTED&symbol=MSFT&apikey=demo' monkeypatch.setattr(requests, 'get', mock_get) # ***register-login-logout 2nd", "having their email address confirmed user = User.query.filter_by(email='<EMAIL>').first() user.email_confirmed = True user.email_confirmed_on =", "import pytest import requests from project import create_app, db from flask import current_app", "using this fixture could change the password for the default user, # reset", "as having their email address confirmed user = User.query.filter_by(email='<EMAIL>').first() user.email_confirmed = True user.email_confirmed_on", "\"4. close\": \"301.9800\", } } } class MockFailedResponse(object): def __init__(self, url): self.status_code =", "{ \"4. close\": \"379.2400\", }, \"2020-07-17\": { \"4. close\": \"362.7600\", }, \"2020-06-11\": {", "Symbol\": \"AAPL\", \"3. Last Refreshed\": \"2020-03-24\" }, 'Time Series (Daily)': { \"2022-02-10\": {", "}, 'Time Series (Daily)': { \"2022-02-10\": { \"4. close\": \"302.3800\", }, \"2022-02-09\": {", "MockSuccessResponseWeekly(object): def __init__(self, url): self.status_code = 200 self.url = url def json(self): return", "url def json(self): return { 'Note': 'Thank you for using Alpha Vantage! Our", "minute and 500 calls per day.' } class MockFailedResponse(object): def __init__(self, url): self.status_code", "user.email_confirmed_on = datetime(2020, 7, 8) db.session.add(user) db.session.commit() yield user # this is where", "mock_requests_get_failure(monkeypatch): def mock_get(url): return MockFailedResponse(url) url = 'https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=MSFT&apikey=demo' monkeypatch.setattr(requests, 'get', mock_get) @pytest.fixture(scope='function') def", "\"2. Symbol\": \"AAPL\", \"3. Last Refreshed\": \"2020-03-24\" }, 'Time Series (Daily)': { \"2022-02-10\":", "test_client.post('/users/register', data={'name':'<NAME>', 'email': '<EMAIL>', 'password': '<PASSWORD>'}, follow_redirects=True) return # is default user logged", "the testing happens! # Since a test using this fixture could change the", "mock_get) @pytest.fixture(scope='function') def mock_requests_get_success_weekly(monkeypatch): # Create a mock for the requests.get() call to", "not having their email address confirmed (clean up) user = User.query.filter_by(email='<EMAIL>').first() user.email_confirmed =", "a default user @pytest.fixture(scope='module') def register_default_user(test_client): # Register the default user test_client.post('/users/register', data={'name':'<NAME>',", "= User.query.filter_by(email='<EMAIL>').first() user.set_password('<PASSWORD>') db.session.add(user) db.session.commit() @pytest.fixture(scope='function') def add_stocks_for_default_user(test_client, log_in_default_user): # Add three stocks", "with flask_app.app_context(): flask_app.logger.info('Creating database tables in test_client fixture...') yield testing_client #where the test", "url): self.status_code = 404 self.url = url def json(self): return {'error': 'bad'} class", "= url def json(self): return {'error': 'bad'} class MockSuccessResponseWeekly(object): def __init__(self, url): self.status_code", "Symbol\": \"MSFT\", \"3. Last Refreshed\": \"2022-02-10\" }, 'Time Series (Daily)': { \"2022-02-10\": {", "Mark the user as not having their email address confirmed (clean up) user", "test_client fixture...') yield testing_client #where the test happens @pytest.fixture(scope='function') def new_stock(): stock =", "be4 accessing the logger with flask_app.app_context(): flask_app.logger.info('Creating database tables in test_client fixture...') yield", "MockFailedResponse(object): def __init__(self, url): self.status_code = 404 self.url = url def json(self): return", "Data': { \"2. Symbol\": \"AAPL\", \"3. Last Refreshed\": \"2020-03-24\" }, 'Time Series (Daily)':", "} } } class MockApiRateLimitExceededResponse(object): def __init__(self, url): self.status_code = 200 self.url =", "# Create a mock for the requests.get() call to prevent making the actual", "class MockSuccessResponse(object): def __init__(self, url): self.status_code = 200 self.url = url self.headers =", "'bad'} class MockSuccessResponseWeekly(object): def __init__(self, url): self.status_code = 200 self.url = url def", "# this is where the testing happens! # Mark the user as not", "(Daily)': { \"2022-02-10\": { \"4. close\": \"148.3400\", }, \"2022-02-09\": { \"4. close\": \"135.9800\",", "def confirm_email_default_user(test_client, log_in_default_user): # Mark the user as having their email address confirmed", "MockSuccessResponseDaily(object): def __init__(self, url): self.status_code = 200 self.url = url def json(self): return", "url): self.status_code = 200 self.url = url self.headers = {'blaa': '1234'} def json(self):", "for moking requests.get()*** @pytest.fixture(scope='function') def mock_requests_get_success_daily(monkeypatch): # Create a mock for the requests.get()", "Stock('AAPL', '16', '406.78', 7, datetime(2022, 2, 12)) return stock @pytest.fixture(scope='module') def new_user(): user", "(clean up) user = User.query.filter_by(email='<EMAIL>').first() user.email_confirmed = False user.email_confirmed_on = None db.session.add(user) db.session.commit()", "'Time Series (Daily)': { \"2022-02-10\": { \"4. close\": \"148.3400\", }, \"2022-02-09\": { \"4.", "def __init__(self, url): self.status_code = 200 self.url = url self.headers = {'blaa': '1234'}", "'1234'} def json(self): return {'error': 'bad'} class MockSuccessResponseDaily(object): def __init__(self, url): self.status_code =", "project import create_app, db from flask import current_app from project.models import Stock, User", "= create_app() flask_app.config.from_object('config.TestingConfig') flask_app.extensions['mail'].suppress = True #to avoid sending emails during the tests", "yield testing_client #where the test happens @pytest.fixture(scope='function') def new_stock(): stock = Stock('AAPL', '16',", "2, 12)) return stock @pytest.fixture(scope='module') def new_user(): user = User('<EMAIL>', '<PASSWORD>') return user", "this fixture could change the password for the default user, # reset the", "} } @pytest.fixture(scope='module') def test_client(): flask_app = create_app() flask_app.config.from_object('config.TestingConfig') flask_app.extensions['mail'].suppress = True #to", "{ \"2. Symbol\": \"MSFT\", \"3. Last Refreshed\": \"2022-02-10\" }, 'Time Series (Daily)': {", "{'blaa': '1234'} def json(self): return {'error': 'bad'} class MockSuccessResponseDaily(object): def __init__(self, url): self.status_code", "url self.headers = {'blaa': '1234'} def json(self): return { 'Meta Data': { \"2.", "standard API call frequency is ' + '5 calls per minute and 500", "def __init__(self, url): self.status_code = 404 self.url = url def json(self): return {'error':", "User.query.filter_by(email='<EMAIL>').first() user.email_confirmed = False user.email_confirmed_on = None db.session.add(user) db.session.commit() @pytest.fixture(scope='function') def afterwards_reset_default_user_password(): yield", "where the testing happens! # Since a test using this fixture could change", "mock_get(url): return MockSuccessResponseWeekly(url) url = 'https://www.alphavantage.co/query?function=TIME_SERIES_WEEKLY_ADJUSTED&symbol=MSFT&apikey=demo' monkeypatch.setattr(requests, 'get', mock_get) # ***register-login-logout 2nd user***", "return { 'Meta Data': { \"2. Symbol\": \"AAPL\", \"3. Last Refreshed\": \"2020-03-24\" },", "# Add three stocks for the default user test_client.post('/add_stock', data={'stock_symbol': 'SAM', 'number_of_shares': '27',", "for the requests.get() call to prevent making the actual API call def mock_get(url):", "a test client using the Flask application configured for testing with flask_app.test_client() as", "@pytest.fixture(scope='function') def add_stocks_for_default_user(test_client, log_in_default_user): # Add three stocks for the default user test_client.post('/add_stock',", "'Note': 'Thank you for using Alpha Vantage! Our standard API call frequency is", "Log in the default user test_client.post('/users/login', data={'email': '<EMAIL>', 'password': '<PASSWORD>'}, follow_redirects=True) yield #", "\"4. close\": \"302.3800\", }, \"2022-02-09\": { \"4. close\": \"301.9800\", } } } class", "\"4. close\": \"432.9800\", } } } @pytest.fixture(scope='module') def test_client(): flask_app = create_app() flask_app.config.from_object('config.TestingConfig')", "\"3. Last Refreshed\": \"2020-03-24\" }, 'Time Series (Daily)': { \"2022-02-10\": { \"4. close\":", "test_client(): flask_app = create_app() flask_app.config.from_object('config.TestingConfig') flask_app.extensions['mail'].suppress = True #to avoid sending emails during", "\"379.2400\", }, \"2020-07-17\": { \"4. close\": \"362.7600\", }, \"2020-06-11\": { \"4. close\": \"354.3400\",", "the user as having their email address confirmed user = User.query.filter_by(email='<EMAIL>').first() user.email_confirmed =", "{ \"4. close\": \"302.3800\", }, \"2022-02-09\": { \"4. close\": \"301.9800\", } } }", "Last Refreshed\": \"2020-03-24\" }, 'Time Series (Daily)': { \"2022-02-10\": { \"4. close\": \"148.3400\",", "this is where the testing happens! # Since a test using this fixture", "= 'https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=MSFT&apikey=demo' monkeypatch.setattr(requests, 'get', mock_get) @pytest.fixture(scope='function') def mock_requests_get_api_rate_limit_exceeded(monkeypatch): def mock_get(url): return MockApiRateLimitExceededResponse(url) url", "def json(self): return { 'Note': 'Thank you for using Alpha Vantage! Our standard", "is default user logged in? @pytest.fixture(scope='function') def log_in_default_user(test_client, register_default_user): # Log in the", "json(self): return {'error': 'bad'} class MockSuccessResponseWeekly(object): def __init__(self, url): self.status_code = 200 self.url", "'2020-02-03'}) return # ***fixtures for moking requests.get()*** @pytest.fixture(scope='function') def mock_requests_get_success_daily(monkeypatch): # Create a", "\"2020-06-11\": { \"4. close\": \"354.3400\", }, \"2020-02-25\": { \"4. close\": \"432.9800\", } }", "their email address confirmed (clean up) user = User.query.filter_by(email='<EMAIL>').first() user.email_confirmed = False user.email_confirmed_on", "test happens @pytest.fixture(scope='function') def new_stock(): stock = Stock('AAPL', '16', '406.78', 7, datetime(2022, 2,", "as testing_client: # establish an app ctx be4 accessing the logger with flask_app.app_context():", "register_second_user(test_client): \"\"\"Registers the second user using the '/users/register' route.\"\"\" test_client.post('/users/register', data={'name':'<NAME>', 'email': '<EMAIL>',", "default password user = User.query.filter_by(email='<EMAIL>').first() user.set_password('<PASSWORD>') db.session.add(user) db.session.commit() @pytest.fixture(scope='function') def add_stocks_for_default_user(test_client, log_in_default_user): #", "user # to register a default user @pytest.fixture(scope='module') def register_default_user(test_client): # Register the", "self.status_code = 200 self.url = url def json(self): return { 'Meta Data': {", "in? @pytest.fixture(scope='function') def log_in_default_user(test_client, register_default_user): # Log in the default user test_client.post('/users/login', data={'email':", "MockSuccessResponseWeekly(url) url = 'https://www.alphavantage.co/query?function=TIME_SERIES_WEEKLY_ADJUSTED&symbol=MSFT&apikey=demo' monkeypatch.setattr(requests, 'get', mock_get) # ***register-login-logout 2nd user*** @pytest.fixture(scope='module') def", "'Weekly Adjusted Time Series': { \"2020-07-24\": { \"4. close\": \"379.2400\", }, \"2020-07-17\": {", "call def mock_get(url): return MockSuccessResponseWeekly(url) url = 'https://www.alphavantage.co/query?function=TIME_SERIES_WEEKLY_ADJUSTED&symbol=MSFT&apikey=demo' monkeypatch.setattr(requests, 'get', mock_get) # ***register-login-logout", "follow_redirects=True) @pytest.fixture(scope='function') def confirm_email_default_user(test_client, log_in_default_user): # Mark the user as having their email", "'Meta Data': { \"2. Symbol\": \"MSFT\", \"3. Last Refreshed\": \"2022-02-10\" }, 'Time Series", "for the default user test_client.post('/add_stock', data={'stock_symbol': 'SAM', 'number_of_shares': '27', 'purchase_price': '301.23', 'purchase_date': '2020-07-01'})", "user.email_confirmed_on = None db.session.add(user) db.session.commit() @pytest.fixture(scope='function') def afterwards_reset_default_user_password(): yield # this is where", "import requests from project import create_app, db from flask import current_app from project.models", "}, \"2020-07-17\": { \"4. close\": \"362.7600\", }, \"2020-06-11\": { \"4. close\": \"354.3400\", },", "Log out the default user test_client.get('/users/logout', follow_redirects=True) @pytest.fixture(scope='function') def confirm_email_default_user(test_client, log_in_default_user): # Mark", "register_default_user): # Log in the default user test_client.post('/users/login', data={'email': '<EMAIL>', 'password': '<PASSWORD>'}, follow_redirects=True)", "{'blaa': '1234'} def json(self): return { 'Meta Data': { \"2. Symbol\": \"MSFT\", \"3.", "return { 'Note': 'Thank you for using Alpha Vantage! Our standard API call", "'email': '<EMAIL>', 'password': '<PASSWORD>'}) @pytest.fixture(scope='function') def log_in_second_user(test_client, register_second_user): # Log in the user", "the testing happens! # Log out the default user test_client.get('/users/logout', follow_redirects=True) @pytest.fixture(scope='function') def", "7, datetime(2022, 2, 12)) return stock @pytest.fixture(scope='module') def new_user(): user = User('<EMAIL>', '<PASSWORD>')", "the default user test_client.get('/users/logout', follow_redirects=True) @pytest.fixture(scope='function') def confirm_email_default_user(test_client, log_in_default_user): # Mark the user", "mock_get(url): return MockSuccessResponseDaily(url) url = 'https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=MSFT&apikey=demo' monkeypatch.setattr(requests, 'get', mock_get) @pytest.fixture(scope='function') def mock_requests_get_api_rate_limit_exceeded(monkeypatch): def", "def afterwards_reset_default_user_password(): yield # this is where the testing happens! # Since a", "testing happens! # Mark the user as not having their email address confirmed", "(Daily)': { \"2022-02-10\": { \"4. close\": \"302.3800\", }, \"2022-02-09\": { \"4. close\": \"301.9800\",", "the default user, # reset the password back to the default password user", "could change the password for the default user, # reset the password back", "url): self.status_code = 200 self.url = url def json(self): return { 'Note': 'Thank", "def add_stocks_for_default_user(test_client, log_in_default_user): # Add three stocks for the default user test_client.post('/add_stock', data={'stock_symbol':", "Adjusted Time Series': { \"2020-07-24\": { \"4. close\": \"379.2400\", }, \"2020-07-17\": { \"4.", "Vantage! Our standard API call frequency is ' + '5 calls per minute", "# ***register-login-logout 2nd user*** @pytest.fixture(scope='module') def register_second_user(test_client): \"\"\"Registers the second user using the", "'purchase_price': '301.23', 'purchase_date': '2020-07-01'}) test_client.post('/add_stock', data={'stock_symbol': 'COST', 'number_of_shares': '76', 'purchase_price': '14.67', 'purchase_date': '2019-05-26'})", "close\": \"379.2400\", }, \"2020-07-17\": { \"4. close\": \"362.7600\", }, \"2020-06-11\": { \"4. close\":", "def mock_requests_get_success_weekly(monkeypatch): # Create a mock for the requests.get() call to prevent making", "password user = User.query.filter_by(email='<EMAIL>').first() user.set_password('<PASSWORD>') db.session.add(user) db.session.commit() @pytest.fixture(scope='function') def add_stocks_for_default_user(test_client, log_in_default_user): # Add", "prevent making the actual API call def mock_get(url): return MockSuccessResponseDaily(url) url = 'https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=MSFT&apikey=demo'", "monkeypatch.setattr(requests, 'get', mock_get) # ***register-login-logout 2nd user*** @pytest.fixture(scope='module') def register_second_user(test_client): \"\"\"Registers the second", "# Since a test using this fixture could change the password for the", "def new_stock(): stock = Stock('AAPL', '16', '406.78', 7, datetime(2022, 2, 12)) return stock", "{ \"2. Symbol\": \"AAPL\", \"3. Last Refreshed\": \"2020-03-24\" }, 'Time Series (Daily)': {", "flask_app.config.from_object('config.TestingConfig') flask_app.extensions['mail'].suppress = True #to avoid sending emails during the tests # Create", "tables in test_client fixture...') yield testing_client #where the test happens @pytest.fixture(scope='function') def new_stock():", "@pytest.fixture(scope='module') def register_second_user(test_client): \"\"\"Registers the second user using the '/users/register' route.\"\"\" test_client.post('/users/register', data={'name':'<NAME>',", "'Time Series (Daily)': { \"2022-02-10\": { \"4. close\": \"302.3800\", }, \"2022-02-09\": { \"4.", "\"148.3400\", }, \"2022-02-09\": { \"4. close\": \"135.9800\", } } } class MockApiRateLimitExceededResponse(object): def", "new_stock(): stock = Stock('AAPL', '16', '406.78', 7, datetime(2022, 2, 12)) return stock @pytest.fixture(scope='module')", "user*** @pytest.fixture(scope='module') def register_second_user(test_client): \"\"\"Registers the second user using the '/users/register' route.\"\"\" test_client.post('/users/register',", "test_client.get('/users/logout', follow_redirects=True) @pytest.fixture(scope='function') def confirm_email_default_user(test_client, log_in_default_user): # Mark the user as having their", "per day.' } class MockFailedResponse(object): def __init__(self, url): self.status_code = 404 self.url =", "close\": \"135.9800\", } } } class MockApiRateLimitExceededResponse(object): def __init__(self, url): self.status_code = 200", "data={'name':'<NAME>', 'email': '<EMAIL>', 'password': '<PASSWORD>'}) @pytest.fixture(scope='function') def log_in_second_user(test_client, register_second_user): # Log in the", "# Register the default user test_client.post('/users/register', data={'name':'<NAME>', 'email': '<EMAIL>', 'password': '<PASSWORD>'}, follow_redirects=True) return", "json(self): return {'error': 'bad'} class MockSuccessResponseDaily(object): def __init__(self, url): self.status_code = 200 self.url", "User from datetime import datetime ######################## #### Helper Classes #### ######################## class MockSuccessResponse(object):", "actual API call def mock_get(url): return MockSuccessResponseWeekly(url) url = 'https://www.alphavantage.co/query?function=TIME_SERIES_WEEKLY_ADJUSTED&symbol=MSFT&apikey=demo' monkeypatch.setattr(requests, 'get', mock_get)", "the default user test_client.post('/users/login', data={'email': '<EMAIL>', 'password': '<PASSWORD>'}, follow_redirects=True) yield # this is", "{ \"2. Symbol\": \"AAPL\", \"3. Last Refreshed\": \"2020-07-28\" }, 'Weekly Adjusted Time Series':", "user = User.query.filter_by(email='<EMAIL>').first() user.email_confirmed = False user.email_confirmed_on = None db.session.add(user) db.session.commit() @pytest.fixture(scope='function') def", "the actual API call def mock_get(url): return MockSuccessResponseWeekly(url) url = 'https://www.alphavantage.co/query?function=TIME_SERIES_WEEKLY_ADJUSTED&symbol=MSFT&apikey=demo' monkeypatch.setattr(requests, 'get',", "app ctx be4 accessing the logger with flask_app.app_context(): flask_app.logger.info('Creating database tables in test_client", "} class MockFailedResponse(object): def __init__(self, url): self.status_code = 404 self.url = url def", "email address confirmed (clean up) user = User.query.filter_by(email='<EMAIL>').first() user.email_confirmed = False user.email_confirmed_on =", "user = User.query.filter_by(email='<EMAIL>').first() user.set_password('<PASSWORD>') db.session.add(user) db.session.commit() @pytest.fixture(scope='function') def add_stocks_for_default_user(test_client, log_in_default_user): # Add three", "}, \"2020-06-11\": { \"4. close\": \"354.3400\", }, \"2020-02-25\": { \"4. close\": \"432.9800\", }", "{ \"4. close\": \"362.7600\", }, \"2020-06-11\": { \"4. close\": \"354.3400\", }, \"2020-02-25\": {", "sending emails during the tests # Create a test client using the Flask", "logger with flask_app.app_context(): flask_app.logger.info('Creating database tables in test_client fixture...') yield testing_client #where the", "flask_app.logger.info('Creating database tables in test_client fixture...') yield testing_client #where the test happens @pytest.fixture(scope='function')", "configured for testing with flask_app.test_client() as testing_client: # establish an app ctx be4", "Add three stocks for the default user test_client.post('/add_stock', data={'stock_symbol': 'SAM', 'number_of_shares': '27', 'purchase_price':", "return user # to register a default user @pytest.fixture(scope='module') def register_default_user(test_client): # Register", "200 self.url = url def json(self): return { 'Note': 'Thank you for using", "\"2022-02-09\": { \"4. close\": \"301.9800\", } } } class MockFailedResponse(object): def __init__(self, url):", "} } } @pytest.fixture(scope='module') def test_client(): flask_app = create_app() flask_app.config.from_object('config.TestingConfig') flask_app.extensions['mail'].suppress = True", "test_client.post('/users/register', data={'name':'<NAME>', 'email': '<EMAIL>', 'password': '<PASSWORD>'}) @pytest.fixture(scope='function') def log_in_second_user(test_client, register_second_user): # Log in", "' + '5 calls per minute and 500 calls per day.' } class", "close\": \"432.9800\", } } } @pytest.fixture(scope='module') def test_client(): flask_app = create_app() flask_app.config.from_object('config.TestingConfig') flask_app.extensions['mail'].suppress", "an app ctx be4 accessing the logger with flask_app.app_context(): flask_app.logger.info('Creating database tables in", "db from flask import current_app from project.models import Stock, User from datetime import", "def json(self): return {'error': 'bad'} class MockSuccessResponseDaily(object): def __init__(self, url): self.status_code = 200", "= User('<EMAIL>', '<PASSWORD>') return user # to register a default user @pytest.fixture(scope='module') def", "three stocks for the default user test_client.post('/add_stock', data={'stock_symbol': 'SAM', 'number_of_shares': '27', 'purchase_price': '301.23',", "= url def json(self): return { 'Meta Data': { \"2. Symbol\": \"AAPL\", \"3.", "User('<EMAIL>', '<PASSWORD>') return user # to register a default user @pytest.fixture(scope='module') def register_default_user(test_client):", "log_in_default_user): # Mark the user as having their email address confirmed user =", "'purchase_price': '34.56', 'purchase_date': '2020-02-03'}) return # ***fixtures for moking requests.get()*** @pytest.fixture(scope='function') def mock_requests_get_success_daily(monkeypatch):", "user test_client.post('/users/login', data={'email': '<EMAIL>', 'password': '<PASSWORD>'}, follow_redirects=True) yield # this is where the", "call frequency is ' + '5 calls per minute and 500 calls per", "confirmed user = User.query.filter_by(email='<EMAIL>').first() user.email_confirmed = True user.email_confirmed_on = datetime(2020, 7, 8) db.session.add(user)", "user = User('<EMAIL>', '<PASSWORD>') return user # to register a default user @pytest.fixture(scope='module')", "= url self.headers = {'blaa': '1234'} def json(self): return {'error': 'bad'} class MockSuccessResponseDaily(object):", "# Log out the default user test_client.get('/users/logout', follow_redirects=True) @pytest.fixture(scope='function') def confirm_email_default_user(test_client, log_in_default_user): #", "pytest import requests from project import create_app, db from flask import current_app from", "{ \"4. close\": \"354.3400\", }, \"2020-02-25\": { \"4. close\": \"432.9800\", } } }", "import create_app, db from flask import current_app from project.models import Stock, User from", "class MockApiRateLimitExceededResponse(object): def __init__(self, url): self.status_code = 200 self.url = url def json(self):", "'<PASSWORD>'}) @pytest.fixture(scope='function') def log_in_second_user(test_client, register_second_user): # Log in the user test_client.post('/users/login', data={'email': '<EMAIL>',", "}, \"2022-02-09\": { \"4. close\": \"135.9800\", } } } class MockApiRateLimitExceededResponse(object): def __init__(self,", "flask_app = create_app() flask_app.config.from_object('config.TestingConfig') flask_app.extensions['mail'].suppress = True #to avoid sending emails during the", "create_app, db from flask import current_app from project.models import Stock, User from datetime", "'get', mock_get) @pytest.fixture(scope='function') def mock_requests_get_failure(monkeypatch): def mock_get(url): return MockFailedResponse(url) url = 'https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=MSFT&apikey=demo' monkeypatch.setattr(requests,", "API call def mock_get(url): return MockSuccessResponseDaily(url) url = 'https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=MSFT&apikey=demo' monkeypatch.setattr(requests, 'get', mock_get) @pytest.fixture(scope='function')", "for testing with flask_app.test_client() as testing_client: # establish an app ctx be4 accessing", "__init__(self, url): self.status_code = 200 self.url = url def json(self): return { 'Meta", "'16', '406.78', 7, datetime(2022, 2, 12)) return stock @pytest.fixture(scope='module') def new_user(): user =", "#where the test happens @pytest.fixture(scope='function') def new_stock(): stock = Stock('AAPL', '16', '406.78', 7,", "def new_user(): user = User('<EMAIL>', '<PASSWORD>') return user # to register a default", "{ \"4. close\": \"432.9800\", } } } @pytest.fixture(scope='module') def test_client(): flask_app = create_app()", "'SAM', 'number_of_shares': '27', 'purchase_price': '301.23', 'purchase_date': '2020-07-01'}) test_client.post('/add_stock', data={'stock_symbol': 'COST', 'number_of_shares': '76', 'purchase_price':", "\"2022-02-10\": { \"4. close\": \"302.3800\", }, \"2022-02-09\": { \"4. close\": \"301.9800\", } }", "accessing the logger with flask_app.app_context(): flask_app.logger.info('Creating database tables in test_client fixture...') yield testing_client", "url): self.status_code = 404 self.url = url self.headers = {'blaa': '1234'} def json(self):", "test_client.post('/add_stock', data={'stock_symbol': 'SAM', 'number_of_shares': '27', 'purchase_price': '301.23', 'purchase_date': '2020-07-01'}) test_client.post('/add_stock', data={'stock_symbol': 'COST', 'number_of_shares':", "data={'stock_symbol': 'SAM', 'number_of_shares': '27', 'purchase_price': '301.23', 'purchase_date': '2020-07-01'}) test_client.post('/add_stock', data={'stock_symbol': 'COST', 'number_of_shares': '76',", "register a default user @pytest.fixture(scope='module') def register_default_user(test_client): # Register the default user test_client.post('/users/register',", "\"4. close\": \"135.9800\", } } } class MockApiRateLimitExceededResponse(object): def __init__(self, url): self.status_code =", "'number_of_shares': '146', 'purchase_price': '34.56', 'purchase_date': '2020-02-03'}) return # ***fixtures for moking requests.get()*** @pytest.fixture(scope='function')", "\"3. Last Refreshed\": \"2022-02-10\" }, 'Time Series (Daily)': { \"2022-02-10\": { \"4. close\":", "return stock @pytest.fixture(scope='module') def new_user(): user = User('<EMAIL>', '<PASSWORD>') return user # to", "\"AAPL\", \"3. Last Refreshed\": \"2020-07-28\" }, 'Weekly Adjusted Time Series': { \"2020-07-24\": {", "the Flask application configured for testing with flask_app.test_client() as testing_client: # establish an", "Refreshed\": \"2022-02-10\" }, 'Time Series (Daily)': { \"2022-02-10\": { \"4. close\": \"302.3800\", },", "Helper Classes #### ######################## class MockSuccessResponse(object): def __init__(self, url): self.status_code = 200 self.url", "\"2. Symbol\": \"AAPL\", \"3. Last Refreshed\": \"2020-07-28\" }, 'Weekly Adjusted Time Series': {", "# is default user logged in? @pytest.fixture(scope='function') def log_in_default_user(test_client, register_default_user): # Log in", "Data': { \"2. Symbol\": \"MSFT\", \"3. Last Refreshed\": \"2022-02-10\" }, 'Time Series (Daily)':", "404 self.url = url self.headers = {'blaa': '1234'} def json(self): return {'error': 'bad'}", "testing with flask_app.test_client() as testing_client: # establish an app ctx be4 accessing the", "self.url = url self.headers = {'blaa': '1234'} def json(self): return { 'Meta Data':", "happens! # Since a test using this fixture could change the password for", "self.url = url self.headers = {'blaa': '1234'} def json(self): return {'error': 'bad'} class", "self.url = url def json(self): return { 'Note': 'Thank you for using Alpha", "register_default_user(test_client): # Register the default user test_client.post('/users/register', data={'name':'<NAME>', 'email': '<EMAIL>', 'password': '<PASSWORD>'}, follow_redirects=True)", "as not having their email address confirmed (clean up) user = User.query.filter_by(email='<EMAIL>').first() user.email_confirmed", "@pytest.fixture(scope='module') def register_default_user(test_client): # Register the default user test_client.post('/users/register', data={'name':'<NAME>', 'email': '<EMAIL>', 'password':", "prevent making the actual API call def mock_get(url): return MockSuccessResponseWeekly(url) url = 'https://www.alphavantage.co/query?function=TIME_SERIES_WEEKLY_ADJUSTED&symbol=MSFT&apikey=demo'", "requests from project import create_app, db from flask import current_app from project.models import", "return # ***fixtures for moking requests.get()*** @pytest.fixture(scope='function') def mock_requests_get_success_daily(monkeypatch): # Create a mock", "test client using the Flask application configured for testing with flask_app.test_client() as testing_client:", "'<PASSWORD>'}) yield # this is where the testing happens! # Log out the", "url self.headers = {'blaa': '1234'} def json(self): return {'error': 'bad'} class MockSuccessResponseDaily(object): def", "'34.56', 'purchase_date': '2020-02-03'}) return # ***fixtures for moking requests.get()*** @pytest.fixture(scope='function') def mock_requests_get_success_daily(monkeypatch): #", "day.' } class MockFailedResponse(object): def __init__(self, url): self.status_code = 404 self.url = url", "\"354.3400\", }, \"2020-02-25\": { \"4. close\": \"432.9800\", } } } @pytest.fixture(scope='module') def test_client():", "{ 'Note': 'Thank you for using Alpha Vantage! Our standard API call frequency", "= url self.headers = {'blaa': '1234'} def json(self): return { 'Meta Data': {", "in the default user test_client.post('/users/login', data={'email': '<EMAIL>', 'password': '<PASSWORD>'}, follow_redirects=True) yield # this", "avoid sending emails during the tests # Create a test client using the", "user, # reset the password back to the default password user = User.query.filter_by(email='<EMAIL>').first()", "during the tests # Create a test client using the Flask application configured", "\"MSFT\", \"3. Last Refreshed\": \"2022-02-10\" }, 'Time Series (Daily)': { \"2022-02-10\": { \"4.", "self.headers = {'blaa': '1234'} def json(self): return { 'Meta Data': { \"2. Symbol\":", "datetime import datetime ######################## #### Helper Classes #### ######################## class MockSuccessResponse(object): def __init__(self,", "MockSuccessResponseDaily(url) url = 'https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=MSFT&apikey=demo' monkeypatch.setattr(requests, 'get', mock_get) @pytest.fixture(scope='function') def mock_requests_get_api_rate_limit_exceeded(monkeypatch): def mock_get(url): return", "fixture...') yield testing_client #where the test happens @pytest.fixture(scope='function') def new_stock(): stock = Stock('AAPL',", "class MockFailedResponse(object): def __init__(self, url): self.status_code = 404 self.url = url self.headers =", "'bad'} class MockSuccessResponseDaily(object): def __init__(self, url): self.status_code = 200 self.url = url def", "route.\"\"\" test_client.post('/users/register', data={'name':'<NAME>', 'email': '<EMAIL>', 'password': '<PASSWORD>'}) @pytest.fixture(scope='function') def log_in_second_user(test_client, register_second_user): # Log", "class MockSuccessResponseDaily(object): def __init__(self, url): self.status_code = 200 self.url = url def json(self):", "mock_requests_get_success_weekly(monkeypatch): # Create a mock for the requests.get() call to prevent making the", "200 self.url = url def json(self): return { 'Meta Data': { \"2. Symbol\":", "'TWTR', 'number_of_shares': '146', 'purchase_price': '34.56', 'purchase_date': '2020-02-03'}) return # ***fixtures for moking requests.get()***", "mock_requests_get_api_rate_limit_exceeded(monkeypatch): def mock_get(url): return MockApiRateLimitExceededResponse(url) url = 'https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=MSFT&apikey=demo' monkeypatch.setattr(requests, 'get', mock_get) @pytest.fixture(scope='function') def", "is where the testing happens! # Mark the user as not having their", "log_in_default_user): # Add three stocks for the default user test_client.post('/add_stock', data={'stock_symbol': 'SAM', 'number_of_shares':", "# Create a test client using the Flask application configured for testing with", "'https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=MSFT&apikey=demo' monkeypatch.setattr(requests, 'get', mock_get) @pytest.fixture(scope='function') def mock_requests_get_api_rate_limit_exceeded(monkeypatch): def mock_get(url): return MockApiRateLimitExceededResponse(url) url =", "__init__(self, url): self.status_code = 404 self.url = url self.headers = {'blaa': '1234'} def", "return { 'Meta Data': { \"2. Symbol\": \"AAPL\", \"3. Last Refreshed\": \"2020-07-28\" },", "url = 'https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=MSFT&apikey=demo' monkeypatch.setattr(requests, 'get', mock_get) @pytest.fixture(scope='function') def mock_requests_get_failure(monkeypatch): def mock_get(url): return MockFailedResponse(url)", "db.session.commit() yield user # this is where the testing happens! # Mark the", "'<PASSWORD>'}, follow_redirects=True) yield # this is where the testing happens! # Log out", "yield # this is where the testing happens! # Log out the default", "= 200 self.url = url def json(self): return { 'Note': 'Thank you for", "user.email_confirmed = True user.email_confirmed_on = datetime(2020, 7, 8) db.session.add(user) db.session.commit() yield user #", "False user.email_confirmed_on = None db.session.add(user) db.session.commit() @pytest.fixture(scope='function') def afterwards_reset_default_user_password(): yield # this is", "None db.session.add(user) db.session.commit() @pytest.fixture(scope='function') def afterwards_reset_default_user_password(): yield # this is where the testing", "}, 'Time Series (Daily)': { \"2022-02-10\": { \"4. close\": \"148.3400\", }, \"2022-02-09\": {", "200 self.url = url self.headers = {'blaa': '1234'} def json(self): return { 'Meta", "\"3. Last Refreshed\": \"2020-07-28\" }, 'Weekly Adjusted Time Series': { \"2020-07-24\": { \"4.", "Flask application configured for testing with flask_app.test_client() as testing_client: # establish an app", "mock_get) @pytest.fixture(scope='function') def mock_requests_get_failure(monkeypatch): def mock_get(url): return MockFailedResponse(url) url = 'https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=MSFT&apikey=demo' monkeypatch.setattr(requests, 'get',", "close\": \"354.3400\", }, \"2020-02-25\": { \"4. close\": \"432.9800\", } } } @pytest.fixture(scope='module') def", "mock_get) @pytest.fixture(scope='function') def mock_requests_get_api_rate_limit_exceeded(monkeypatch): def mock_get(url): return MockApiRateLimitExceededResponse(url) url = 'https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=MSFT&apikey=demo' monkeypatch.setattr(requests, 'get',", "'https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=MSFT&apikey=demo' monkeypatch.setattr(requests, 'get', mock_get) @pytest.fixture(scope='function') def mock_requests_get_success_weekly(monkeypatch): # Create a mock for the", "close\": \"148.3400\", }, \"2022-02-09\": { \"4. close\": \"135.9800\", } } } class MockApiRateLimitExceededResponse(object):", "url def json(self): return { 'Meta Data': { \"2. Symbol\": \"AAPL\", \"3. Last", "confirmed (clean up) user = User.query.filter_by(email='<EMAIL>').first() user.email_confirmed = False user.email_confirmed_on = None db.session.add(user)", "import current_app from project.models import Stock, User from datetime import datetime ######################## ####", "= User.query.filter_by(email='<EMAIL>').first() user.email_confirmed = False user.email_confirmed_on = None db.session.add(user) db.session.commit() @pytest.fixture(scope='function') def afterwards_reset_default_user_password():", "user.email_confirmed = False user.email_confirmed_on = None db.session.add(user) db.session.commit() @pytest.fixture(scope='function') def afterwards_reset_default_user_password(): yield #", "'get', mock_get) @pytest.fixture(scope='function') def mock_requests_get_success_weekly(monkeypatch): # Create a mock for the requests.get() call", "back to the default password user = User.query.filter_by(email='<EMAIL>').first() user.set_password('<PASSWORD>') db.session.add(user) db.session.commit() @pytest.fixture(scope='function') def", "2nd user*** @pytest.fixture(scope='module') def register_second_user(test_client): \"\"\"Registers the second user using the '/users/register' route.\"\"\"", "happens! # Mark the user as not having their email address confirmed (clean", "Refreshed\": \"2020-03-24\" }, 'Time Series (Daily)': { \"2022-02-10\": { \"4. close\": \"148.3400\", },", "\"2020-07-24\": { \"4. close\": \"379.2400\", }, \"2020-07-17\": { \"4. close\": \"362.7600\", }, \"2020-06-11\":", "True #to avoid sending emails during the tests # Create a test client", "= True user.email_confirmed_on = datetime(2020, 7, 8) db.session.add(user) db.session.commit() yield user # this", "you for using Alpha Vantage! Our standard API call frequency is ' +", "email address confirmed user = User.query.filter_by(email='<EMAIL>').first() user.email_confirmed = True user.email_confirmed_on = datetime(2020, 7,", "in the user test_client.post('/users/login', data={'email': '<EMAIL>', 'password': '<PASSWORD>'}) yield # this is where", "@pytest.fixture(scope='function') def confirm_email_default_user(test_client, log_in_default_user): # Mark the user as having their email address", "import Stock, User from datetime import datetime ######################## #### Helper Classes #### ########################", "calls per minute and 500 calls per day.' } class MockFailedResponse(object): def __init__(self,", "frequency is ' + '5 calls per minute and 500 calls per day.'", "\"2020-07-17\": { \"4. close\": \"362.7600\", }, \"2020-06-11\": { \"4. close\": \"354.3400\", }, \"2020-02-25\":", "= datetime(2020, 7, 8) db.session.add(user) db.session.commit() yield user # this is where the", "requests.get() call to prevent making the actual API call def mock_get(url): return MockSuccessResponseDaily(url)", "class MockSuccessResponseWeekly(object): def __init__(self, url): self.status_code = 200 self.url = url def json(self):", "= 'https://www.alphavantage.co/query?function=TIME_SERIES_WEEKLY_ADJUSTED&symbol=MSFT&apikey=demo' monkeypatch.setattr(requests, 'get', mock_get) # ***register-login-logout 2nd user*** @pytest.fixture(scope='module') def register_second_user(test_client): \"\"\"Registers", "and 500 calls per day.' } class MockFailedResponse(object): def __init__(self, url): self.status_code =", "testing_client: # establish an app ctx be4 accessing the logger with flask_app.app_context(): flask_app.logger.info('Creating", "Alpha Vantage! Our standard API call frequency is ' + '5 calls per", "} class MockFailedResponse(object): def __init__(self, url): self.status_code = 404 self.url = url self.headers", "404 self.url = url def json(self): return {'error': 'bad'} class MockSuccessResponseWeekly(object): def __init__(self,", "address confirmed user = User.query.filter_by(email='<EMAIL>').first() user.email_confirmed = True user.email_confirmed_on = datetime(2020, 7, 8)", "ctx be4 accessing the logger with flask_app.app_context(): flask_app.logger.info('Creating database tables in test_client fixture...')", "'purchase_date': '2019-05-26'}) test_client.post('/add_stock', data={'stock_symbol': 'TWTR', 'number_of_shares': '146', 'purchase_price': '34.56', 'purchase_date': '2020-02-03'}) return #", "# reset the password back to the default password user = User.query.filter_by(email='<EMAIL>').first() user.set_password('<PASSWORD>')", "user @pytest.fixture(scope='module') def register_default_user(test_client): # Register the default user test_client.post('/users/register', data={'name':'<NAME>', 'email': '<EMAIL>',", "'purchase_date': '2020-07-01'}) test_client.post('/add_stock', data={'stock_symbol': 'COST', 'number_of_shares': '76', 'purchase_price': '14.67', 'purchase_date': '2019-05-26'}) test_client.post('/add_stock', data={'stock_symbol':", "# Log in the user test_client.post('/users/login', data={'email': '<EMAIL>', 'password': '<PASSWORD>'}) yield # this", "'146', 'purchase_price': '34.56', 'purchase_date': '2020-02-03'}) return # ***fixtures for moking requests.get()*** @pytest.fixture(scope='function') def", "this is where the testing happens! # Log out the user test_client.get('/users/logout', follow_redirects=True)", "for the default user, # reset the password back to the default password", "the user as not having their email address confirmed (clean up) user =", "a test using this fixture could change the password for the default user,", "MockApiRateLimitExceededResponse(object): def __init__(self, url): self.status_code = 200 self.url = url def json(self): return", "'/users/register' route.\"\"\" test_client.post('/users/register', data={'name':'<NAME>', 'email': '<EMAIL>', 'password': '<PASSWORD>'}) @pytest.fixture(scope='function') def log_in_second_user(test_client, register_second_user): #", "Data': { \"2. Symbol\": \"AAPL\", \"3. Last Refreshed\": \"2020-07-28\" }, 'Weekly Adjusted Time", "'301.23', 'purchase_date': '2020-07-01'}) test_client.post('/add_stock', data={'stock_symbol': 'COST', 'number_of_shares': '76', 'purchase_price': '14.67', 'purchase_date': '2019-05-26'}) test_client.post('/add_stock',", "Last Refreshed\": \"2022-02-10\" }, 'Time Series (Daily)': { \"2022-02-10\": { \"4. close\": \"302.3800\",", "def mock_requests_get_failure(monkeypatch): def mock_get(url): return MockFailedResponse(url) url = 'https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=MSFT&apikey=demo' monkeypatch.setattr(requests, 'get', mock_get) @pytest.fixture(scope='function')", "user logged in? @pytest.fixture(scope='function') def log_in_default_user(test_client, register_default_user): # Log in the default user", "MockFailedResponse(url) url = 'https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=MSFT&apikey=demo' monkeypatch.setattr(requests, 'get', mock_get) @pytest.fixture(scope='function') def mock_requests_get_success_weekly(monkeypatch): # Create a", "'password': '<PASSWORD>'}) yield # this is where the testing happens! # Log out", "json(self): return { 'Note': 'Thank you for using Alpha Vantage! Our standard API", "db.session.add(user) db.session.commit() @pytest.fixture(scope='function') def add_stocks_for_default_user(test_client, log_in_default_user): # Add three stocks for the default", "user as not having their email address confirmed (clean up) user = User.query.filter_by(email='<EMAIL>').first()", "\"2020-03-24\" }, 'Time Series (Daily)': { \"2022-02-10\": { \"4. close\": \"148.3400\", }, \"2022-02-09\":", "Symbol\": \"AAPL\", \"3. Last Refreshed\": \"2020-07-28\" }, 'Weekly Adjusted Time Series': { \"2020-07-24\":", "flask_app.extensions['mail'].suppress = True #to avoid sending emails during the tests # Create a", "flask_app.app_context(): flask_app.logger.info('Creating database tables in test_client fixture...') yield testing_client #where the test happens", "stock @pytest.fixture(scope='module') def new_user(): user = User('<EMAIL>', '<PASSWORD>') return user # to register", "follow_redirects=True) return # is default user logged in? @pytest.fixture(scope='function') def log_in_default_user(test_client, register_default_user): #", "flask import current_app from project.models import Stock, User from datetime import datetime ########################", "'<PASSWORD>'}, follow_redirects=True) return # is default user logged in? @pytest.fixture(scope='function') def log_in_default_user(test_client, register_default_user):", "'number_of_shares': '27', 'purchase_price': '301.23', 'purchase_date': '2020-07-01'}) test_client.post('/add_stock', data={'stock_symbol': 'COST', 'number_of_shares': '76', 'purchase_price': '14.67',", "yield user # this is where the testing happens! # Mark the user", "# this is where the testing happens! # Since a test using this", "self.status_code = 200 self.url = url self.headers = {'blaa': '1234'} def json(self): return", "}, 'Weekly Adjusted Time Series': { \"2020-07-24\": { \"4. close\": \"379.2400\", }, \"2020-07-17\":", "return MockFailedResponse(url) url = 'https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=MSFT&apikey=demo' monkeypatch.setattr(requests, 'get', mock_get) @pytest.fixture(scope='function') def mock_requests_get_success_weekly(monkeypatch): # Create", "database tables in test_client fixture...') yield testing_client #where the test happens @pytest.fixture(scope='function') def", "\"2022-02-10\": { \"4. close\": \"148.3400\", }, \"2022-02-09\": { \"4. close\": \"135.9800\", } }", "\"4. close\": \"379.2400\", }, \"2020-07-17\": { \"4. close\": \"362.7600\", }, \"2020-06-11\": { \"4.", "Create a test client using the Flask application configured for testing with flask_app.test_client()", "user using the '/users/register' route.\"\"\" test_client.post('/users/register', data={'name':'<NAME>', 'email': '<EMAIL>', 'password': '<PASSWORD>'}) @pytest.fixture(scope='function') def", "json(self): return { 'Meta Data': { \"2. Symbol\": \"MSFT\", \"3. Last Refreshed\": \"2022-02-10\"", "default user logged in? @pytest.fixture(scope='function') def log_in_default_user(test_client, register_default_user): # Log in the default", "self.status_code = 404 self.url = url self.headers = {'blaa': '1234'} def json(self): return", "def json(self): return {'error': 'bad'} class MockSuccessResponseWeekly(object): def __init__(self, url): self.status_code = 200", "= 404 self.url = url self.headers = {'blaa': '1234'} def json(self): return {'error':", "url = 'https://www.alphavantage.co/query?function=TIME_SERIES_WEEKLY_ADJUSTED&symbol=MSFT&apikey=demo' monkeypatch.setattr(requests, 'get', mock_get) # ***register-login-logout 2nd user*** @pytest.fixture(scope='module') def register_second_user(test_client):", "requests.get() call to prevent making the actual API call def mock_get(url): return MockSuccessResponseWeekly(url)", "***fixtures for moking requests.get()*** @pytest.fixture(scope='function') def mock_requests_get_success_daily(monkeypatch): # Create a mock for the", "'password': '<PASSWORD>'}) @pytest.fixture(scope='function') def log_in_second_user(test_client, register_second_user): # Log in the user test_client.post('/users/login', data={'email':", "from project import create_app, db from flask import current_app from project.models import Stock,", "'1234'} def json(self): return { 'Meta Data': { \"2. Symbol\": \"MSFT\", \"3. Last", "making the actual API call def mock_get(url): return MockSuccessResponseWeekly(url) url = 'https://www.alphavantage.co/query?function=TIME_SERIES_WEEKLY_ADJUSTED&symbol=MSFT&apikey=demo' monkeypatch.setattr(requests,", "'76', 'purchase_price': '14.67', 'purchase_date': '2019-05-26'}) test_client.post('/add_stock', data={'stock_symbol': 'TWTR', 'number_of_shares': '146', 'purchase_price': '34.56', 'purchase_date':", "logged in? @pytest.fixture(scope='function') def log_in_default_user(test_client, register_default_user): # Log in the default user test_client.post('/users/login',", "db.session.commit() @pytest.fixture(scope='function') def afterwards_reset_default_user_password(): yield # this is where the testing happens! #", "stock = Stock('AAPL', '16', '406.78', 7, datetime(2022, 2, 12)) return stock @pytest.fixture(scope='module') def", "{ \"4. close\": \"135.9800\", } } } class MockApiRateLimitExceededResponse(object): def __init__(self, url): self.status_code", "@pytest.fixture(scope='function') def afterwards_reset_default_user_password(): yield # this is where the testing happens! # Since", "'get', mock_get) # ***register-login-logout 2nd user*** @pytest.fixture(scope='module') def register_second_user(test_client): \"\"\"Registers the second user", "mock for the requests.get() call to prevent making the actual API call def", "json(self): return { 'Meta Data': { \"2. Symbol\": \"AAPL\", \"3. Last Refreshed\": \"2020-03-24\"", "\"4. close\": \"148.3400\", }, \"2022-02-09\": { \"4. close\": \"135.9800\", } } } class", "\"362.7600\", }, \"2020-06-11\": { \"4. close\": \"354.3400\", }, \"2020-02-25\": { \"4. close\": \"432.9800\",", "user test_client.post('/users/login', data={'email': '<EMAIL>', 'password': '<PASSWORD>'}) yield # this is where the testing", "where the testing happens! # Log out the default user test_client.get('/users/logout', follow_redirects=True) @pytest.fixture(scope='function')", "user = User.query.filter_by(email='<EMAIL>').first() user.email_confirmed = True user.email_confirmed_on = datetime(2020, 7, 8) db.session.add(user) db.session.commit()", "call to prevent making the actual API call def mock_get(url): return MockSuccessResponseDaily(url) url", "@pytest.fixture(scope='function') def mock_requests_get_failure(monkeypatch): def mock_get(url): return MockFailedResponse(url) url = 'https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=MSFT&apikey=demo' monkeypatch.setattr(requests, 'get', mock_get)", "'<EMAIL>', 'password': '<PASSWORD>'}, follow_redirects=True) return # is default user logged in? @pytest.fixture(scope='function') def" ]
[ "True if email text body is required. False in case only structured_fields needs", "while calling the function. In case nothing is specified, default boolean value True", "order to make it more powerful, above functions can be added. \"\"\" headers=data.columns", "like lowercase and removal of unwanted characters. In order to make it more", "used. return: Dataframe A dataframe with specified fields along with the original columns", "structured_data = {} messages = df[\"email\"] for message in messages: e = email.message_from_string(message)", "dataframe with specified fields along with the original columns passsed as the data", "unwanted characters. In order to make it more powerful, above functions can be", "eg. it does not remove the empty rows or columns. Neither it does", "data: Dataframe It is the Enron dataset with column headings. This argument can", "droppped if not required. 3) extract_pyload: Boolean True if email text body is", "Enron email dataset. It provides flexibilty to choose which fields needs to be", "above functions can be added. \"\"\" headers=data.columns emails = data.rename(columns={headers[0]:'email_path', headers[1]:'email'}) #getting structured", "'X-To']. This argument can be droppped if not required. 3) extract_pyload: Boolean True", "structured_data], axis=1) else: structured_data = get_structured_data(emails, structured_fields) emails = pd.concat([emails, structured_data], axis=1) return", "email_body structured_data = get_structured_data(emails, structured_fields) emails = pd.concat([emails, structured_data], axis=1) else: structured_data =", "original columns passsed as the data argument. This function is created to take", "headers[1]:'email'}) #getting structured text def create_dict(dictionary, key, value): if key in dictionary: values", "structured_fields: List It is a of tags for which data needs to be", "data for the given header list from the Enron email dataset. It provides", "emails = pd.concat([emails, structured_data], axis=1) else: structured_data = get_structured_data(emails, structured_fields) emails = pd.concat([emails,", "fields needs to be extracted. The header list provided by the user are", "This argument can not be kept empty. 2) structured_fields: List It is a", "header in fields: header_data = e.get(header) create_dict(dictionary = structured_data, key = header, value", "return dictionary def get_structured_data(df, fields): structured_data = {} messages = df[\"email\"] for message", "text body of the Enron dataset. Arguments: 1) data: Dataframe It is the", "dictionary[key] = values else: dictionary[key] = [value] return dictionary def get_structured_data(df, fields): structured_data", "value): if key in dictionary: values = dictionary.get(key) values.append(value) dictionary[key] = values else:", "= header, value = header_data) return pd.DataFrame(structured_data) #getting unstructured text def get_unstructured_email(df): messages", "the data, eg. it does not remove the empty rows or columns. Neither", "pre-processing of data like lowercase and removal of unwanted characters. In order to", "can not be kept empty. 2) structured_fields: List It is a of tags", "key in dictionary: values = dictionary.get(key) values.append(value) dictionary[key] = values else: dictionary[key] =", "unstructured text def get_unstructured_email(df): messages = [] for item in df[\"email\"]: e =", "if not required. 3) extract_pyload: Boolean True if email text body is required.", "if no header is provided, this function returns only the email text body", "powerful, above functions can be added. \"\"\" headers=data.columns emails = data.rename(columns={headers[0]:'email_path', headers[1]:'email'}) #getting", "it does the pre-processing of data like lowercase and removal of unwanted characters.", "= data.rename(columns={headers[0]:'email_path', headers[1]:'email'}) #getting structured text def create_dict(dictionary, key, value): if key in", "the user are the tags in the email of Enron dataset, eg. Date,", "this does not clean the data, eg. it does not remove the empty", "== True: email_body = get_unstructured_email(emails) emails[\"Message-Body\"] = email_body structured_data = get_structured_data(emails, structured_fields) emails", "header is provided, this function returns only the email text body of the", "burden of extracting desired fields from the Enron dataset. However, this does not", "to make it more powerful, above functions can be added. \"\"\" headers=data.columns emails", "a of tags for which data needs to be extracted. Example: ['Date', 'Subject',", "True: email_body = get_unstructured_email(emails) emails[\"Message-Body\"] = email_body structured_data = get_structured_data(emails, structured_fields) emails =", "import pandas as pd def extract(data, structured_fields=[], extract_payload=True): r\"\"\"This function extracts data for", "calling the function. In case nothing is specified, default boolean value True is", "flexibilty to choose which fields needs to be extracted. The header list provided", "Enron dataset. Arguments: 1) data: Dataframe It is the Enron dataset with column", "with column headings. This argument can not be kept empty. 2) structured_fields: List", "is specified, default boolean value True is used. return: Dataframe A dataframe with", "'Subject', 'X-To']. This argument can be droppped if not required. 3) extract_pyload: Boolean", "to choose which fields needs to be extracted. The header list provided by", "List It is a of tags for which data needs to be extracted.", "from the Enron dataset. However, this does not clean the data, eg. it", "provided by the user are the tags in the email of Enron dataset,", "data needs to be extracted. Example: ['Date', 'Subject', 'X-To']. This argument can be", "structured_data, key = header, value = header_data) return pd.DataFrame(structured_data) #getting unstructured text def", "df[\"email\"] for message in messages: e = email.message_from_string(message) for header in fields: header_data", "else: dictionary[key] = [value] return dictionary def get_structured_data(df, fields): structured_data = {} messages", "the given header list from the Enron email dataset. It provides flexibilty to", "not clean the data, eg. it does not remove the empty rows or", "tags for which data needs to be extracted. Example: ['Date', 'Subject', 'X-To']. This", "in dictionary: values = dictionary.get(key) values.append(value) dictionary[key] = values else: dictionary[key] = [value]", "argument. This function is created to take off the burden of extracting desired", "with the original columns passsed as the data argument. This function is created", "no header is provided, this function returns only the email text body of", "in fields: header_data = e.get(header) create_dict(dictionary = structured_data, key = header, value =", "kept empty. 2) structured_fields: List It is a of tags for which data", "does not clean the data, eg. it does not remove the empty rows", "messages if extract_payload == True: email_body = get_unstructured_email(emails) emails[\"Message-Body\"] = email_body structured_data =", "fields): structured_data = {} messages = df[\"email\"] for message in messages: e =", "can be added. \"\"\" headers=data.columns emails = data.rename(columns={headers[0]:'email_path', headers[1]:'email'}) #getting structured text def", "messages: e = email.message_from_string(message) for header in fields: header_data = e.get(header) create_dict(dictionary =", "This field can alo be dropped while calling the function. In case nothing", "passsed as the data argument. This function is created to take off the", "get_structured_data(emails, structured_fields) emails = pd.concat([emails, structured_data], axis=1) else: structured_data = get_structured_data(emails, structured_fields) emails", "return messages if extract_payload == True: email_body = get_unstructured_email(emails) emails[\"Message-Body\"] = email_body structured_data", "column headings. This argument can not be kept empty. 2) structured_fields: List It", "more powerful, above functions can be added. \"\"\" headers=data.columns emails = data.rename(columns={headers[0]:'email_path', headers[1]:'email'})", "structured_fields needs to be extracted. This field can alo be dropped while calling", "fields along with the original columns passsed as the data argument. This function", "r\"\"\"This function extracts data for the given header list from the Enron email", "pd.concat([emails, structured_data], axis=1) else: structured_data = get_structured_data(emails, structured_fields) emails = pd.concat([emails, structured_data], axis=1)", "be kept empty. 2) structured_fields: List It is a of tags for which", "nothing is specified, default boolean value True is used. return: Dataframe A dataframe", "the data argument. This function is created to take off the burden of", "= {} messages = df[\"email\"] for message in messages: e = email.message_from_string(message) for", "= message_body.lower() messages.append(message_body) return messages if extract_payload == True: email_body = get_unstructured_email(emails) emails[\"Message-Body\"]", "columns passsed as the data argument. This function is created to take off", "which data needs to be extracted. Example: ['Date', 'Subject', 'X-To']. This argument can", "default, if no header is provided, this function returns only the email text", "3) extract_pyload: Boolean True if email text body is required. False in case", "is the Enron dataset with column headings. This argument can not be kept", "False in case only structured_fields needs to be extracted. This field can alo", "[] for item in df[\"email\"]: e = email.message_from_string(item) message_body = e.get_payload() #message_body =", "= structured_data, key = header, value = header_data) return pd.DataFrame(structured_data) #getting unstructured text", "In order to make it more powerful, above functions can be added. \"\"\"", "messages = df[\"email\"] for message in messages: e = email.message_from_string(message) for header in", "dataset with column headings. This argument can not be kept empty. 2) structured_fields:", "be added. \"\"\" headers=data.columns emails = data.rename(columns={headers[0]:'email_path', headers[1]:'email'}) #getting structured text def create_dict(dictionary,", "desired fields from the Enron dataset. However, this does not clean the data,", "are the tags in the email of Enron dataset, eg. Date, Subject etc.", "email text body of the Enron dataset. Arguments: 1) data: Dataframe It is", "values.append(value) dictionary[key] = values else: dictionary[key] = [value] return dictionary def get_structured_data(df, fields):", "to be extracted. This field can alo be dropped while calling the function.", "does not remove the empty rows or columns. Neither it does the pre-processing", "to be extracted. The header list provided by the user are the tags", "= e.get(header) create_dict(dictionary = structured_data, key = header, value = header_data) return pd.DataFrame(structured_data)", "extract_payload == True: email_body = get_unstructured_email(emails) emails[\"Message-Body\"] = email_body structured_data = get_structured_data(emails, structured_fields)", "of the Enron dataset. Arguments: 1) data: Dataframe It is the Enron dataset", "with specified fields along with the original columns passsed as the data argument.", "it more powerful, above functions can be added. \"\"\" headers=data.columns emails = data.rename(columns={headers[0]:'email_path',", "list provided by the user are the tags in the email of Enron", "clean the data, eg. it does not remove the empty rows or columns.", "of Enron dataset, eg. Date, Subject etc. By default, if no header is", "argument can not be kept empty. 2) structured_fields: List It is a of", "= header_data) return pd.DataFrame(structured_data) #getting unstructured text def get_unstructured_email(df): messages = [] for", "email dataset. It provides flexibilty to choose which fields needs to be extracted.", "to be extracted. Example: ['Date', 'Subject', 'X-To']. This argument can be droppped if", "the email text body of the Enron dataset. Arguments: 1) data: Dataframe It", "import email import pandas as pd def extract(data, structured_fields=[], extract_payload=True): r\"\"\"This function extracts", "header list provided by the user are the tags in the email of", "extracted. Example: ['Date', 'Subject', 'X-To']. This argument can be droppped if not required.", "tags in the email of Enron dataset, eg. Date, Subject etc. By default,", "e = email.message_from_string(item) message_body = e.get_payload() #message_body = message_body.lower() messages.append(message_body) return messages if", "create_dict(dictionary, key, value): if key in dictionary: values = dictionary.get(key) values.append(value) dictionary[key] =", "= df[\"email\"] for message in messages: e = email.message_from_string(message) for header in fields:", "is provided, this function returns only the email text body of the Enron", "if email text body is required. False in case only structured_fields needs to", "rows or columns. Neither it does the pre-processing of data like lowercase and", "= [value] return dictionary def get_structured_data(df, fields): structured_data = {} messages = df[\"email\"]", "be extracted. The header list provided by the user are the tags in", "function extracts data for the given header list from the Enron email dataset.", "needs to be extracted. The header list provided by the user are the", "['Date', 'Subject', 'X-To']. This argument can be droppped if not required. 3) extract_pyload:", "columns. Neither it does the pre-processing of data like lowercase and removal of", "get_unstructured_email(df): messages = [] for item in df[\"email\"]: e = email.message_from_string(item) message_body =", "text body is required. False in case only structured_fields needs to be extracted.", "of data like lowercase and removal of unwanted characters. In order to make", "extracted. The header list provided by the user are the tags in the", "Dataframe It is the Enron dataset with column headings. This argument can not", "dictionary.get(key) values.append(value) dictionary[key] = values else: dictionary[key] = [value] return dictionary def get_structured_data(df,", "remove the empty rows or columns. Neither it does the pre-processing of data", "Arguments: 1) data: Dataframe It is the Enron dataset with column headings. This", "def create_dict(dictionary, key, value): if key in dictionary: values = dictionary.get(key) values.append(value) dictionary[key]", "case only structured_fields needs to be extracted. This field can alo be dropped", "not remove the empty rows or columns. Neither it does the pre-processing of", "dictionary: values = dictionary.get(key) values.append(value) dictionary[key] = values else: dictionary[key] = [value] return", "In case nothing is specified, default boolean value True is used. return: Dataframe", "df[\"email\"]: e = email.message_from_string(item) message_body = e.get_payload() #message_body = message_body.lower() messages.append(message_body) return messages", "email.message_from_string(message) for header in fields: header_data = e.get(header) create_dict(dictionary = structured_data, key =", "function. In case nothing is specified, default boolean value True is used. return:", "Neither it does the pre-processing of data like lowercase and removal of unwanted", "structured_fields=[], extract_payload=True): r\"\"\"This function extracts data for the given header list from the", "extracted. This field can alo be dropped while calling the function. In case", "= email.message_from_string(item) message_body = e.get_payload() #message_body = message_body.lower() messages.append(message_body) return messages if extract_payload", "extracting desired fields from the Enron dataset. However, this does not clean the", "dataset. However, this does not clean the data, eg. it does not remove", "only structured_fields needs to be extracted. This field can alo be dropped while", "= [] for item in df[\"email\"]: e = email.message_from_string(item) message_body = e.get_payload() #message_body", "of extracting desired fields from the Enron dataset. However, this does not clean", "data argument. This function is created to take off the burden of extracting", "provided, this function returns only the email text body of the Enron dataset.", "not be kept empty. 2) structured_fields: List It is a of tags for", "by the user are the tags in the email of Enron dataset, eg.", "the Enron dataset with column headings. This argument can not be kept empty.", "email_body = get_unstructured_email(emails) emails[\"Message-Body\"] = email_body structured_data = get_structured_data(emails, structured_fields) emails = pd.concat([emails,", "can be droppped if not required. 3) extract_pyload: Boolean True if email text", "dictionary[key] = [value] return dictionary def get_structured_data(df, fields): structured_data = {} messages =", "#message_body = message_body.lower() messages.append(message_body) return messages if extract_payload == True: email_body = get_unstructured_email(emails)", "Boolean True if email text body is required. False in case only structured_fields", "or columns. Neither it does the pre-processing of data like lowercase and removal", "lowercase and removal of unwanted characters. In order to make it more powerful,", "boolean value True is used. return: Dataframe A dataframe with specified fields along", "extracts data for the given header list from the Enron email dataset. It", "e.get_payload() #message_body = message_body.lower() messages.append(message_body) return messages if extract_payload == True: email_body =", "pandas as pd def extract(data, structured_fields=[], extract_payload=True): r\"\"\"This function extracts data for the", "1) data: Dataframe It is the Enron dataset with column headings. This argument", "for item in df[\"email\"]: e = email.message_from_string(item) message_body = e.get_payload() #message_body = message_body.lower()", "value True is used. return: Dataframe A dataframe with specified fields along with", "def get_unstructured_email(df): messages = [] for item in df[\"email\"]: e = email.message_from_string(item) message_body", "take off the burden of extracting desired fields from the Enron dataset. However,", "header_data) return pd.DataFrame(structured_data) #getting unstructured text def get_unstructured_email(df): messages = [] for item", "It is the Enron dataset with column headings. This argument can not be", "the Enron dataset. However, this does not clean the data, eg. it does", "text def create_dict(dictionary, key, value): if key in dictionary: values = dictionary.get(key) values.append(value)", "text def get_unstructured_email(df): messages = [] for item in df[\"email\"]: e = email.message_from_string(item)", "case nothing is specified, default boolean value True is used. return: Dataframe A", "can alo be dropped while calling the function. In case nothing is specified,", "message_body.lower() messages.append(message_body) return messages if extract_payload == True: email_body = get_unstructured_email(emails) emails[\"Message-Body\"] =", "if key in dictionary: values = dictionary.get(key) values.append(value) dictionary[key] = values else: dictionary[key]", "By default, if no header is provided, this function returns only the email", "if extract_payload == True: email_body = get_unstructured_email(emails) emails[\"Message-Body\"] = email_body structured_data = get_structured_data(emails,", "email import pandas as pd def extract(data, structured_fields=[], extract_payload=True): r\"\"\"This function extracts data", "given header list from the Enron email dataset. It provides flexibilty to choose", "dropped while calling the function. In case nothing is specified, default boolean value", "values else: dictionary[key] = [value] return dictionary def get_structured_data(df, fields): structured_data = {}", "provides flexibilty to choose which fields needs to be extracted. The header list", "of tags for which data needs to be extracted. Example: ['Date', 'Subject', 'X-To'].", "message_body = e.get_payload() #message_body = message_body.lower() messages.append(message_body) return messages if extract_payload == True:", "headings. This argument can not be kept empty. 2) structured_fields: List It is", "for header in fields: header_data = e.get(header) create_dict(dictionary = structured_data, key = header,", "header, value = header_data) return pd.DataFrame(structured_data) #getting unstructured text def get_unstructured_email(df): messages =", "the Enron email dataset. It provides flexibilty to choose which fields needs to", "return pd.DataFrame(structured_data) #getting unstructured text def get_unstructured_email(df): messages = [] for item in", "dictionary def get_structured_data(df, fields): structured_data = {} messages = df[\"email\"] for message in", "in df[\"email\"]: e = email.message_from_string(item) message_body = e.get_payload() #message_body = message_body.lower() messages.append(message_body) return", "as the data argument. This function is created to take off the burden", "created to take off the burden of extracting desired fields from the Enron", "create_dict(dictionary = structured_data, key = header, value = header_data) return pd.DataFrame(structured_data) #getting unstructured", "This function is created to take off the burden of extracting desired fields", "data.rename(columns={headers[0]:'email_path', headers[1]:'email'}) #getting structured text def create_dict(dictionary, key, value): if key in dictionary:", "alo be dropped while calling the function. In case nothing is specified, default", "messages = [] for item in df[\"email\"]: e = email.message_from_string(item) message_body = e.get_payload()", "= get_unstructured_email(emails) emails[\"Message-Body\"] = email_body structured_data = get_structured_data(emails, structured_fields) emails = pd.concat([emails, structured_data],", "It is a of tags for which data needs to be extracted. Example:", "extract_payload=True): r\"\"\"This function extracts data for the given header list from the Enron", "eg. Date, Subject etc. By default, if no header is provided, this function", "needs to be extracted. This field can alo be dropped while calling the", "specified fields along with the original columns passsed as the data argument. This", "The header list provided by the user are the tags in the email", "Enron dataset. However, this does not clean the data, eg. it does not", "#getting unstructured text def get_unstructured_email(df): messages = [] for item in df[\"email\"]: e", "for the given header list from the Enron email dataset. It provides flexibilty", "#getting structured text def create_dict(dictionary, key, value): if key in dictionary: values =", "get_unstructured_email(emails) emails[\"Message-Body\"] = email_body structured_data = get_structured_data(emails, structured_fields) emails = pd.concat([emails, structured_data], axis=1)", "be droppped if not required. 3) extract_pyload: Boolean True if email text body", "However, this does not clean the data, eg. it does not remove the", "values = dictionary.get(key) values.append(value) dictionary[key] = values else: dictionary[key] = [value] return dictionary", "needs to be extracted. Example: ['Date', 'Subject', 'X-To']. This argument can be droppped", "Enron dataset, eg. Date, Subject etc. By default, if no header is provided,", "pd.DataFrame(structured_data) #getting unstructured text def get_unstructured_email(df): messages = [] for item in df[\"email\"]:", "functions can be added. \"\"\" headers=data.columns emails = data.rename(columns={headers[0]:'email_path', headers[1]:'email'}) #getting structured text", "it does not remove the empty rows or columns. Neither it does the", "emails[\"Message-Body\"] = email_body structured_data = get_structured_data(emails, structured_fields) emails = pd.concat([emails, structured_data], axis=1) else:", "message in messages: e = email.message_from_string(message) for header in fields: header_data = e.get(header)", "added. \"\"\" headers=data.columns emails = data.rename(columns={headers[0]:'email_path', headers[1]:'email'}) #getting structured text def create_dict(dictionary, key,", "header list from the Enron email dataset. It provides flexibilty to choose which", "email of Enron dataset, eg. Date, Subject etc. By default, if no header", "Enron dataset with column headings. This argument can not be kept empty. 2)", "body is required. False in case only structured_fields needs to be extracted. This", "be dropped while calling the function. In case nothing is specified, default boolean", "= get_structured_data(emails, structured_fields) emails = pd.concat([emails, structured_data], axis=1) else: structured_data = get_structured_data(emails, structured_fields)", "not required. 3) extract_pyload: Boolean True if email text body is required. False", "returns only the email text body of the Enron dataset. Arguments: 1) data:", "make it more powerful, above functions can be added. \"\"\" headers=data.columns emails =", "This argument can be droppped if not required. 3) extract_pyload: Boolean True if", "{} messages = df[\"email\"] for message in messages: e = email.message_from_string(message) for header", "the burden of extracting desired fields from the Enron dataset. However, this does", "to take off the burden of extracting desired fields from the Enron dataset.", "data like lowercase and removal of unwanted characters. In order to make it", "= email.message_from_string(message) for header in fields: header_data = e.get(header) create_dict(dictionary = structured_data, key", "choose which fields needs to be extracted. The header list provided by the", "from the Enron email dataset. It provides flexibilty to choose which fields needs", "the empty rows or columns. Neither it does the pre-processing of data like", "in messages: e = email.message_from_string(message) for header in fields: header_data = e.get(header) create_dict(dictionary", "e.get(header) create_dict(dictionary = structured_data, key = header, value = header_data) return pd.DataFrame(structured_data) #getting", "is created to take off the burden of extracting desired fields from the", "function returns only the email text body of the Enron dataset. Arguments: 1)", "emails = data.rename(columns={headers[0]:'email_path', headers[1]:'email'}) #getting structured text def create_dict(dictionary, key, value): if key", "the pre-processing of data like lowercase and removal of unwanted characters. In order", "default boolean value True is used. return: Dataframe A dataframe with specified fields", "user are the tags in the email of Enron dataset, eg. Date, Subject", "structured_fields) emails = pd.concat([emails, structured_data], axis=1) else: structured_data = get_structured_data(emails, structured_fields) emails =", "def get_structured_data(df, fields): structured_data = {} messages = df[\"email\"] for message in messages:", "= e.get_payload() #message_body = message_body.lower() messages.append(message_body) return messages if extract_payload == True: email_body", "e = email.message_from_string(message) for header in fields: header_data = e.get(header) create_dict(dictionary = structured_data,", "does the pre-processing of data like lowercase and removal of unwanted characters. In", "in case only structured_fields needs to be extracted. This field can alo be", "= email_body structured_data = get_structured_data(emails, structured_fields) emails = pd.concat([emails, structured_data], axis=1) else: structured_data", "empty. 2) structured_fields: List It is a of tags for which data needs", "messages.append(message_body) return messages if extract_payload == True: email_body = get_unstructured_email(emails) emails[\"Message-Body\"] = email_body", "A dataframe with specified fields along with the original columns passsed as the", "dataset. Arguments: 1) data: Dataframe It is the Enron dataset with column headings.", "only the email text body of the Enron dataset. Arguments: 1) data: Dataframe", "dataset, eg. Date, Subject etc. By default, if no header is provided, this", "body of the Enron dataset. Arguments: 1) data: Dataframe It is the Enron", "for which data needs to be extracted. Example: ['Date', 'Subject', 'X-To']. This argument", "Date, Subject etc. By default, if no header is provided, this function returns", "email text body is required. False in case only structured_fields needs to be", "empty rows or columns. Neither it does the pre-processing of data like lowercase", "for message in messages: e = email.message_from_string(message) for header in fields: header_data =", "fields: header_data = e.get(header) create_dict(dictionary = structured_data, key = header, value = header_data)", "specified, default boolean value True is used. return: Dataframe A dataframe with specified", "function is created to take off the burden of extracting desired fields from", "off the burden of extracting desired fields from the Enron dataset. However, this", "and removal of unwanted characters. In order to make it more powerful, above", "[value] return dictionary def get_structured_data(df, fields): structured_data = {} messages = df[\"email\"] for", "header_data = e.get(header) create_dict(dictionary = structured_data, key = header, value = header_data) return", "the email of Enron dataset, eg. Date, Subject etc. By default, if no", "Subject etc. By default, if no header is provided, this function returns only", "headers=data.columns emails = data.rename(columns={headers[0]:'email_path', headers[1]:'email'}) #getting structured text def create_dict(dictionary, key, value): if", "list from the Enron email dataset. It provides flexibilty to choose which fields", "be extracted. This field can alo be dropped while calling the function. In", "the tags in the email of Enron dataset, eg. Date, Subject etc. By", "etc. By default, if no header is provided, this function returns only the", "get_structured_data(df, fields): structured_data = {} messages = df[\"email\"] for message in messages: e", "Dataframe A dataframe with specified fields along with the original columns passsed as", "data, eg. it does not remove the empty rows or columns. Neither it", "key = header, value = header_data) return pd.DataFrame(structured_data) #getting unstructured text def get_unstructured_email(df):", "structured_data = get_structured_data(emails, structured_fields) emails = pd.concat([emails, structured_data], axis=1) else: structured_data = get_structured_data(emails,", "= dictionary.get(key) values.append(value) dictionary[key] = values else: dictionary[key] = [value] return dictionary def", "in the email of Enron dataset, eg. Date, Subject etc. By default, if", "the Enron dataset. Arguments: 1) data: Dataframe It is the Enron dataset with", "item in df[\"email\"]: e = email.message_from_string(item) message_body = e.get_payload() #message_body = message_body.lower() messages.append(message_body)", "email.message_from_string(item) message_body = e.get_payload() #message_body = message_body.lower() messages.append(message_body) return messages if extract_payload ==", "is a of tags for which data needs to be extracted. Example: ['Date',", "pd def extract(data, structured_fields=[], extract_payload=True): r\"\"\"This function extracts data for the given header", "True is used. return: Dataframe A dataframe with specified fields along with the", "axis=1) else: structured_data = get_structured_data(emails, structured_fields) emails = pd.concat([emails, structured_data], axis=1) return emails", "which fields needs to be extracted. The header list provided by the user", "fields from the Enron dataset. However, this does not clean the data, eg.", "this function returns only the email text body of the Enron dataset. Arguments:", "as pd def extract(data, structured_fields=[], extract_payload=True): r\"\"\"This function extracts data for the given", "extract_pyload: Boolean True if email text body is required. False in case only", "Example: ['Date', 'Subject', 'X-To']. This argument can be droppped if not required. 3)", "def extract(data, structured_fields=[], extract_payload=True): r\"\"\"This function extracts data for the given header list", "structured text def create_dict(dictionary, key, value): if key in dictionary: values = dictionary.get(key)", "required. False in case only structured_fields needs to be extracted. This field can", "It provides flexibilty to choose which fields needs to be extracted. The header", "argument can be droppped if not required. 3) extract_pyload: Boolean True if email", "along with the original columns passsed as the data argument. This function is", "= values else: dictionary[key] = [value] return dictionary def get_structured_data(df, fields): structured_data =", "extract(data, structured_fields=[], extract_payload=True): r\"\"\"This function extracts data for the given header list from", "value = header_data) return pd.DataFrame(structured_data) #getting unstructured text def get_unstructured_email(df): messages = []", "is required. False in case only structured_fields needs to be extracted. This field", "be extracted. Example: ['Date', 'Subject', 'X-To']. This argument can be droppped if not", "key, value): if key in dictionary: values = dictionary.get(key) values.append(value) dictionary[key] = values", "field can alo be dropped while calling the function. In case nothing is", "removal of unwanted characters. In order to make it more powerful, above functions", "of unwanted characters. In order to make it more powerful, above functions can", "= pd.concat([emails, structured_data], axis=1) else: structured_data = get_structured_data(emails, structured_fields) emails = pd.concat([emails, structured_data],", "the function. In case nothing is specified, default boolean value True is used.", "characters. In order to make it more powerful, above functions can be added.", "is used. return: Dataframe A dataframe with specified fields along with the original", "\"\"\" headers=data.columns emails = data.rename(columns={headers[0]:'email_path', headers[1]:'email'}) #getting structured text def create_dict(dictionary, key, value):", "the original columns passsed as the data argument. This function is created to", "2) structured_fields: List It is a of tags for which data needs to", "required. 3) extract_pyload: Boolean True if email text body is required. False in", "return: Dataframe A dataframe with specified fields along with the original columns passsed", "dataset. It provides flexibilty to choose which fields needs to be extracted. The" ]
[ "detection, multilayer networks, configuration model, random graph models # @return edgelist: a matrix", "correctly edgelist = pd.DataFrame({'node1': [0], 'node2': [0], 'layer': [0]}) m = len(adjacency) for", "Convert NetworkX Graph to an edgelist and preprocess the resulting DataFrame edges =", "heterogeneous community structure.\" Journal of Machine Learning Research # Original R Code: <NAME>", "as nx import numpy as np import pandas as pd def adjacency_to_edgelist(adjacency): #", "drop self looping edges in a NetworkX Graph structure, # we can do", "models # @return edgelist: a matrix with three columns representing edge connections: node1,", "\"target\": \"node2\"}) edges['layer'] = i # Set a third column to the layer", "[0]}) m = len(adjacency) for i in range(0, m + 1): # Convert", "# Since we dropped items in the line above, we must once again", "with correct data structures, we can append to the edgelist # The indices", "edges.drop(['weight'], axis=1) # Drop unnecessary weight column (Unweighted graph) # Rename source and", "Function that converts a list of adjacency matrices to an edgelist # @param", "number edgelist = edgelist.append(edges) # Now with correct data structures, we can append", "1): # Convert each matrix to a NetworkX Graph temp_graph = nx.from_numpy_matrix(np.asarray(adjacency[i]), False)", "to make sure appends later on merge correctly edgelist = pd.DataFrame({'node1': [0], 'node2':", "the index edgelist = edgelist.reset_index(drop=True) # Since we cannot selectively drop self looping", "edges in a NetworkX Graph structure, # we can do so here by", "a multilayer network # @future_param mode: directed or undirected # @future_param weighted: currently", "each matrix to a NetworkX Graph temp_graph = nx.from_numpy_matrix(np.asarray(adjacency[i]), False) # Convert NetworkX", "a NetworkX Graph structure, # we can do so here by creating a", "NetworkX Graph to an edgelist and preprocess the resulting DataFrame edges = nx.convert_matrix.to_pandas_edgelist(temp_graph)", "matrices to an edgelist # @param adjacency: a list whose ith entry is", "later on merge correctly edgelist = pd.DataFrame({'node1': [0], 'node2': [0], 'layer': [0]}) m", "import pandas as pd def adjacency_to_edgelist(adjacency): # Instantiate labeled dataframe to make sure", "we dropped items in the line above, we must once again reset the", "a third column to the layer number edgelist = edgelist.append(edges) # Now with", "= edges.rename(columns={\"source\": \"node1\", \"target\": \"node2\"}) edges['layer'] = i # Set a third column", "the layer number edgelist = edgelist.append(edges) # Now with correct data structures, we", "an edgelist and preprocess the resulting DataFrame edges = nx.convert_matrix.to_pandas_edgelist(temp_graph) edges = edges.drop(['weight'],", "graph) # Rename source and target columns to node1 and node2 (Undirected graph)", "i in range(0, m + 1): # Convert each matrix to a NetworkX", "= edgelist.drop(edgelist[edgelist['node1'] == edgelist['node2']].index) # Since we dropped items in the line above,", "community structure later on. edgelist = edgelist.drop(edgelist[edgelist['node1'] == edgelist['node2']].index) # Since we dropped", "adjacency_to_edgelist # # Function that converts a list of adjacency matrices to an", "self looping edges in a NetworkX Graph structure, # we can do so", "import networkx as nx import numpy as np import pandas as pd def", "adjacency: a list whose ith entry is an adjacency matrix representing the ith", "axis=1) # Drop unnecessary weight column (Unweighted graph) # Rename source and target", "from many appends, so we can reset the index edgelist = edgelist.reset_index(drop=True) #", "edges['layer'] = i # Set a third column to the layer number edgelist", "equal, # and drop them from the DataFrame to preserve community structure later", "reset the index edgelist = edgelist.reset_index(drop=True) # Since we cannot selectively drop self", "and node2 (Undirected graph) edges = edges.rename(columns={\"source\": \"node1\", \"target\": \"node2\"}) edges['layer'] = i", "graph) edges = edges.rename(columns={\"source\": \"node1\", \"target\": \"node2\"}) edges['layer'] = i # Set a", "looping edges in a NetworkX Graph structure, # we can do so here", "# Set a third column to the layer number edgelist = edgelist.append(edges) #", "multilayer network # @future_param mode: directed or undirected # @future_param weighted: currently not", "False) # Convert NetworkX Graph to an edgelist and preprocess the resulting DataFrame", "matrix with three columns representing edge connections: node1, node2, layer # # Basis:", "edgelist = edgelist.drop(edgelist[edgelist['node1'] == edgelist['node2']].index) # Since we dropped items in the line", "mode: directed or undirected # @future_param weighted: currently not functioning. Coming in later", "edgelist = edgelist.reset_index(drop=True) # Since we cannot selectively drop self looping edges in", "edgelist.reset_index(drop=True) # Since we cannot selectively drop self looping edges in a NetworkX", "matrix representing the ith layer of a multilayer network # @future_param mode: directed", "multilayer networks with heterogeneous community structure.\" Journal of Machine Learning Research # Original", "ith entry is an adjacency matrix representing the ith layer of a multilayer", "matrix to a NetworkX Graph temp_graph = nx.from_numpy_matrix(np.asarray(adjacency[i]), False) # Convert NetworkX Graph", "edgelist # @param adjacency: a list whose ith entry is an adjacency matrix", "(Undirected graph) edges = edges.rename(columns={\"source\": \"node1\", \"target\": \"node2\"}) edges['layer'] = i # Set", "Set a third column to the layer number edgelist = edgelist.append(edges) # Now", "on. edgelist = edgelist.drop(edgelist[edgelist['node1'] == edgelist['node2']].index) # Since we dropped items in the", "to node1 and node2 (Undirected graph) edges = edges.rename(columns={\"source\": \"node1\", \"target\": \"node2\"}) edges['layer']", "adjacency_to_edgelist(adjacency): # Instantiate labeled dataframe to make sure appends later on merge correctly", "\"Significance based # extraction in multilayer networks with heterogeneous community structure.\" Journal of", "structures, we can append to the edgelist # The indices will be jumbled", "and preprocess the resulting DataFrame edges = nx.convert_matrix.to_pandas_edgelist(temp_graph) edges = edges.drop(['weight'], axis=1) #", "configuration model, random graph models # @return edgelist: a matrix with three columns", "model, random graph models # @return edgelist: a matrix with three columns representing", "selectively drop self looping edges in a NetworkX Graph structure, # we can", "items in the line above, we must once again reset the indices edgelist", "we can reset the index edgelist = edgelist.reset_index(drop=True) # Since we cannot selectively", "dropped items in the line above, we must once again reset the indices", "preserve community structure later on. edgelist = edgelist.drop(edgelist[edgelist['node1'] == edgelist['node2']].index) # Since we", "pd.DataFrame({'node1': [0], 'node2': [0], 'layer': [0]}) m = len(adjacency) for i in range(0,", "appends, so we can reset the index edgelist = edgelist.reset_index(drop=True) # Since we", "line above, we must once again reset the indices edgelist = edgelist.reset_index(drop=True) return", "an adjacency matrix representing the ith layer of a multilayer network # @future_param", "we can append to the edgelist # The indices will be jumbled from", "adjacency matrices to an edgelist # @param adjacency: a list whose ith entry", "ith layer of a multilayer network # @future_param mode: directed or undirected #", "numpy as np import pandas as pd def adjacency_to_edgelist(adjacency): # Instantiate labeled dataframe", "node2 (Undirected graph) edges = edges.rename(columns={\"source\": \"node1\", \"target\": \"node2\"}) edges['layer'] = i #", "node2, layer # # Basis: Wilson, <NAME>., Palowitch, <NAME>, Shankar, and Nobel, <NAME>.", "in a NetworkX Graph structure, # we can do so here by creating", "# @param adjacency: a list whose ith entry is an adjacency matrix representing", "# we can do so here by creating a boolean series of entries", "a list of adjacency matrices to an edgelist # @param adjacency: a list", "the edgelist # The indices will be jumbled from many appends, so we", "a boolean series of entries who's nodes are equal, # and drop them", "\"node1\", \"target\": \"node2\"}) edges['layer'] = i # Set a third column to the", "list whose ith entry is an adjacency matrix representing the ith layer of", "(2017) \"Significance based # extraction in multilayer networks with heterogeneous community structure.\" Journal", "can append to the edgelist # The indices will be jumbled from many", "will be jumbled from many appends, so we can reset the index edgelist", "dataframe to make sure appends later on merge correctly edgelist = pd.DataFrame({'node1': [0],", "who's nodes are equal, # and drop them from the DataFrame to preserve", "np import pandas as pd def adjacency_to_edgelist(adjacency): # Instantiate labeled dataframe to make", "of a multilayer network # @future_param mode: directed or undirected # @future_param weighted:", "Shankar, and Nobel, <NAME>. (2017) \"Significance based # extraction in multilayer networks with", "is an adjacency matrix representing the ith layer of a multilayer network #", "extraction in multilayer networks with heterogeneous community structure.\" Journal of Machine Learning Research", "Code: <NAME> # Revised Python Code: <NAME> import networkx as nx import numpy", "by creating a boolean series of entries who's nodes are equal, # and", "edgelist.drop(edgelist[edgelist['node1'] == edgelist['node2']].index) # Since we dropped items in the line above, we", "and target columns to node1 and node2 (Undirected graph) edges = edges.rename(columns={\"source\": \"node1\",", "# Revised Python Code: <NAME> import networkx as nx import numpy as np", "and Nobel, <NAME>. (2017) \"Significance based # extraction in multilayer networks with heterogeneous", "version. # # @keywords community detection, multilayer networks, configuration model, random graph models", "whose ith entry is an adjacency matrix representing the ith layer of a", "appends later on merge correctly edgelist = pd.DataFrame({'node1': [0], 'node2': [0], 'layer': [0]})", "converts a list of adjacency matrices to an edgelist # @param adjacency: a", "unnecessary weight column (Unweighted graph) # Rename source and target columns to node1", "# @return edgelist: a matrix with three columns representing edge connections: node1, node2,", "node1 and node2 (Undirected graph) edges = edges.rename(columns={\"source\": \"node1\", \"target\": \"node2\"}) edges['layer'] =", "= len(adjacency) for i in range(0, m + 1): # Convert each matrix", "+ 1): # Convert each matrix to a NetworkX Graph temp_graph = nx.from_numpy_matrix(np.asarray(adjacency[i]),", "the ith layer of a multilayer network # @future_param mode: directed or undirected", "that converts a list of adjacency matrices to an edgelist # @param adjacency:", "with three columns representing edge connections: node1, node2, layer # # Basis: Wilson,", "def adjacency_to_edgelist(adjacency): # Instantiate labeled dataframe to make sure appends later on merge", "sure appends later on merge correctly edgelist = pd.DataFrame({'node1': [0], 'node2': [0], 'layer':", "Convert each matrix to a NetworkX Graph temp_graph = nx.from_numpy_matrix(np.asarray(adjacency[i]), False) # Convert", "# Function that converts a list of adjacency matrices to an edgelist #", "pandas as pd def adjacency_to_edgelist(adjacency): # Instantiate labeled dataframe to make sure appends", "DataFrame to preserve community structure later on. edgelist = edgelist.drop(edgelist[edgelist['node1'] == edgelist['node2']].index) #", "range(0, m + 1): # Convert each matrix to a NetworkX Graph temp_graph", "column (Unweighted graph) # Rename source and target columns to node1 and node2", "can do so here by creating a boolean series of entries who's nodes", "list of adjacency matrices to an edgelist # @param adjacency: a list whose", "edgelist['node2']].index) # Since we dropped items in the line above, we must once", "Learning Research # Original R Code: <NAME> # Revised Python Code: <NAME> import", "networkx as nx import numpy as np import pandas as pd def adjacency_to_edgelist(adjacency):", "structure later on. edgelist = edgelist.drop(edgelist[edgelist['node1'] == edgelist['node2']].index) # Since we dropped items", "the resulting DataFrame edges = nx.convert_matrix.to_pandas_edgelist(temp_graph) edges = edges.drop(['weight'], axis=1) # Drop unnecessary", "# Now with correct data structures, we can append to the edgelist #", "Graph structure, # we can do so here by creating a boolean series", "# Convert NetworkX Graph to an edgelist and preprocess the resulting DataFrame edges", "directed or undirected # @future_param weighted: currently not functioning. Coming in later version.", "<NAME>. (2017) \"Significance based # extraction in multilayer networks with heterogeneous community structure.\"", "a matrix with three columns representing edge connections: node1, node2, layer # #", "Graph to an edgelist and preprocess the resulting DataFrame edges = nx.convert_matrix.to_pandas_edgelist(temp_graph) edges", "edgelist.append(edges) # Now with correct data structures, we can append to the edgelist", "<NAME> import networkx as nx import numpy as np import pandas as pd", "[0], 'node2': [0], 'layer': [0]}) m = len(adjacency) for i in range(0, m", "of entries who's nodes are equal, # and drop them from the DataFrame", "# @future_param mode: directed or undirected # @future_param weighted: currently not functioning. Coming", "cannot selectively drop self looping edges in a NetworkX Graph structure, # we", "later version. # # @keywords community detection, multilayer networks, configuration model, random graph", "= edges.drop(['weight'], axis=1) # Drop unnecessary weight column (Unweighted graph) # Rename source", "Revised Python Code: <NAME> import networkx as nx import numpy as np import", "target columns to node1 and node2 (Undirected graph) edges = edges.rename(columns={\"source\": \"node1\", \"target\":", "DataFrame edges = nx.convert_matrix.to_pandas_edgelist(temp_graph) edges = edges.drop(['weight'], axis=1) # Drop unnecessary weight column", "as pd def adjacency_to_edgelist(adjacency): # Instantiate labeled dataframe to make sure appends later", "<NAME>., Palowitch, <NAME>, Shankar, and Nobel, <NAME>. (2017) \"Significance based # extraction in", "m + 1): # Convert each matrix to a NetworkX Graph temp_graph =", "# Drop unnecessary weight column (Unweighted graph) # Rename source and target columns", "# # Function that converts a list of adjacency matrices to an edgelist", "on merge correctly edgelist = pd.DataFrame({'node1': [0], 'node2': [0], 'layer': [0]}) m =", "Graph temp_graph = nx.from_numpy_matrix(np.asarray(adjacency[i]), False) # Convert NetworkX Graph to an edgelist and", "edge connections: node1, node2, layer # # Basis: Wilson, <NAME>., Palowitch, <NAME>, Shankar,", "and drop them from the DataFrame to preserve community structure later on. edgelist", "in later version. # # @keywords community detection, multilayer networks, configuration model, random", "Rename source and target columns to node1 and node2 (Undirected graph) edges =", "to preserve community structure later on. edgelist = edgelist.drop(edgelist[edgelist['node1'] == edgelist['node2']].index) # Since", "= edgelist.reset_index(drop=True) # Since we cannot selectively drop self looping edges in a", "nx.convert_matrix.to_pandas_edgelist(temp_graph) edges = edges.drop(['weight'], axis=1) # Drop unnecessary weight column (Unweighted graph) #", "to an edgelist and preprocess the resulting DataFrame edges = nx.convert_matrix.to_pandas_edgelist(temp_graph) edges =", "<NAME>, Shankar, and Nobel, <NAME>. (2017) \"Significance based # extraction in multilayer networks", "drop them from the DataFrame to preserve community structure later on. edgelist =", "not functioning. Coming in later version. # # @keywords community detection, multilayer networks,", "= edgelist.append(edges) # Now with correct data structures, we can append to the", "pd def adjacency_to_edgelist(adjacency): # Instantiate labeled dataframe to make sure appends later on", "or undirected # @future_param weighted: currently not functioning. Coming in later version. #", "third column to the layer number edgelist = edgelist.append(edges) # Now with correct", "Basis: Wilson, <NAME>., Palowitch, <NAME>, Shankar, and Nobel, <NAME>. (2017) \"Significance based #", "undirected # @future_param weighted: currently not functioning. Coming in later version. # #", "connections: node1, node2, layer # # Basis: Wilson, <NAME>., Palowitch, <NAME>, Shankar, and", "labeled dataframe to make sure appends later on merge correctly edgelist = pd.DataFrame({'node1':", "functioning. Coming in later version. # # @keywords community detection, multilayer networks, configuration", "can reset the index edgelist = edgelist.reset_index(drop=True) # Since we cannot selectively drop", "in range(0, m + 1): # Convert each matrix to a NetworkX Graph", "@return edgelist: a matrix with three columns representing edge connections: node1, node2, layer", "Palowitch, <NAME>, Shankar, and Nobel, <NAME>. (2017) \"Significance based # extraction in multilayer", "the line above, we must once again reset the indices edgelist = edgelist.reset_index(drop=True)", "graph models # @return edgelist: a matrix with three columns representing edge connections:", "(Unweighted graph) # Rename source and target columns to node1 and node2 (Undirected", "entry is an adjacency matrix representing the ith layer of a multilayer network", "NetworkX Graph temp_graph = nx.from_numpy_matrix(np.asarray(adjacency[i]), False) # Convert NetworkX Graph to an edgelist", "from the DataFrame to preserve community structure later on. edgelist = edgelist.drop(edgelist[edgelist['node1'] ==", "Journal of Machine Learning Research # Original R Code: <NAME> # Revised Python", "@future_param weighted: currently not functioning. Coming in later version. # # @keywords community", "Machine Learning Research # Original R Code: <NAME> # Revised Python Code: <NAME>", "edges = nx.convert_matrix.to_pandas_edgelist(temp_graph) edges = edges.drop(['weight'], axis=1) # Drop unnecessary weight column (Unweighted", "to the layer number edgelist = edgelist.append(edges) # Now with correct data structures,", "to the edgelist # The indices will be jumbled from many appends, so", "community detection, multilayer networks, configuration model, random graph models # @return edgelist: a", "= pd.DataFrame({'node1': [0], 'node2': [0], 'layer': [0]}) m = len(adjacency) for i in", "edgelist # The indices will be jumbled from many appends, so we can", "= nx.convert_matrix.to_pandas_edgelist(temp_graph) edges = edges.drop(['weight'], axis=1) # Drop unnecessary weight column (Unweighted graph)", "# adjacency_to_edgelist # # Function that converts a list of adjacency matrices to", "[0], 'layer': [0]}) m = len(adjacency) for i in range(0, m + 1):", "Drop unnecessary weight column (Unweighted graph) # Rename source and target columns to", "representing edge connections: node1, node2, layer # # Basis: Wilson, <NAME>., Palowitch, <NAME>,", "# Instantiate labeled dataframe to make sure appends later on merge correctly edgelist", "be jumbled from many appends, so we can reset the index edgelist =", "# Since we cannot selectively drop self looping edges in a NetworkX Graph", "as np import pandas as pd def adjacency_to_edgelist(adjacency): # Instantiate labeled dataframe to", "m = len(adjacency) for i in range(0, m + 1): # Convert each", "here by creating a boolean series of entries who's nodes are equal, #", "Since we cannot selectively drop self looping edges in a NetworkX Graph structure,", "# Rename source and target columns to node1 and node2 (Undirected graph) edges", "Now with correct data structures, we can append to the edgelist # The", "nodes are equal, # and drop them from the DataFrame to preserve community", "structure.\" Journal of Machine Learning Research # Original R Code: <NAME> # Revised", "multilayer networks, configuration model, random graph models # @return edgelist: a matrix with", "source and target columns to node1 and node2 (Undirected graph) edges = edges.rename(columns={\"source\":", "them from the DataFrame to preserve community structure later on. edgelist = edgelist.drop(edgelist[edgelist['node1']", "we cannot selectively drop self looping edges in a NetworkX Graph structure, #", "len(adjacency) for i in range(0, m + 1): # Convert each matrix to", "data structures, we can append to the edgelist # The indices will be", "in the line above, we must once again reset the indices edgelist =", "three columns representing edge connections: node1, node2, layer # # Basis: Wilson, <NAME>.,", "Code: <NAME> import networkx as nx import numpy as np import pandas as", "<NAME> # Revised Python Code: <NAME> import networkx as nx import numpy as", "networks, configuration model, random graph models # @return edgelist: a matrix with three", "# @future_param weighted: currently not functioning. Coming in later version. # # @keywords", "in multilayer networks with heterogeneous community structure.\" Journal of Machine Learning Research #", "later on. edgelist = edgelist.drop(edgelist[edgelist['node1'] == edgelist['node2']].index) # Since we dropped items in", "of adjacency matrices to an edgelist # @param adjacency: a list whose ith", "community structure.\" Journal of Machine Learning Research # Original R Code: <NAME> #", "= nx.from_numpy_matrix(np.asarray(adjacency[i]), False) # Convert NetworkX Graph to an edgelist and preprocess the", "nx.from_numpy_matrix(np.asarray(adjacency[i]), False) # Convert NetworkX Graph to an edgelist and preprocess the resulting", "representing the ith layer of a multilayer network # @future_param mode: directed or", "currently not functioning. Coming in later version. # # @keywords community detection, multilayer", "structure, # we can do so here by creating a boolean series of", "import numpy as np import pandas as pd def adjacency_to_edgelist(adjacency): # Instantiate labeled", "adjacency matrix representing the ith layer of a multilayer network # @future_param mode:", "preprocess the resulting DataFrame edges = nx.convert_matrix.to_pandas_edgelist(temp_graph) edges = edges.drop(['weight'], axis=1) # Drop", "node1, node2, layer # # Basis: Wilson, <NAME>., Palowitch, <NAME>, Shankar, and Nobel,", "'node2': [0], 'layer': [0]}) m = len(adjacency) for i in range(0, m +", "merge correctly edgelist = pd.DataFrame({'node1': [0], 'node2': [0], 'layer': [0]}) m = len(adjacency)", "make sure appends later on merge correctly edgelist = pd.DataFrame({'node1': [0], 'node2': [0],", "# extraction in multilayer networks with heterogeneous community structure.\" Journal of Machine Learning", "of Machine Learning Research # Original R Code: <NAME> # Revised Python Code:", "a list whose ith entry is an adjacency matrix representing the ith layer", "so here by creating a boolean series of entries who's nodes are equal,", "the DataFrame to preserve community structure later on. edgelist = edgelist.drop(edgelist[edgelist['node1'] == edgelist['node2']].index)", "edges = edges.rename(columns={\"source\": \"node1\", \"target\": \"node2\"}) edges['layer'] = i # Set a third", "index edgelist = edgelist.reset_index(drop=True) # Since we cannot selectively drop self looping edges", "to an edgelist # @param adjacency: a list whose ith entry is an", "\"node2\"}) edges['layer'] = i # Set a third column to the layer number", "indices will be jumbled from many appends, so we can reset the index", "@future_param mode: directed or undirected # @future_param weighted: currently not functioning. Coming in", "network # @future_param mode: directed or undirected # @future_param weighted: currently not functioning.", "Wilson, <NAME>., Palowitch, <NAME>, Shankar, and Nobel, <NAME>. (2017) \"Significance based # extraction", "resulting DataFrame edges = nx.convert_matrix.to_pandas_edgelist(temp_graph) edges = edges.drop(['weight'], axis=1) # Drop unnecessary weight", "with heterogeneous community structure.\" Journal of Machine Learning Research # Original R Code:", "R Code: <NAME> # Revised Python Code: <NAME> import networkx as nx import", "to a NetworkX Graph temp_graph = nx.from_numpy_matrix(np.asarray(adjacency[i]), False) # Convert NetworkX Graph to", "layer number edgelist = edgelist.append(edges) # Now with correct data structures, we can", "Coming in later version. # # @keywords community detection, multilayer networks, configuration model,", "so we can reset the index edgelist = edgelist.reset_index(drop=True) # Since we cannot", "do so here by creating a boolean series of entries who's nodes are", "entries who's nodes are equal, # and drop them from the DataFrame to", "above, we must once again reset the indices edgelist = edgelist.reset_index(drop=True) return edgelist", "many appends, so we can reset the index edgelist = edgelist.reset_index(drop=True) # Since", "weighted: currently not functioning. Coming in later version. # # @keywords community detection,", "nx import numpy as np import pandas as pd def adjacency_to_edgelist(adjacency): # Instantiate", "i # Set a third column to the layer number edgelist = edgelist.append(edges)", "edges = edges.drop(['weight'], axis=1) # Drop unnecessary weight column (Unweighted graph) # Rename", "Since we dropped items in the line above, we must once again reset", "creating a boolean series of entries who's nodes are equal, # and drop", "# # @keywords community detection, multilayer networks, configuration model, random graph models #", "layer of a multilayer network # @future_param mode: directed or undirected # @future_param", "append to the edgelist # The indices will be jumbled from many appends,", "Original R Code: <NAME> # Revised Python Code: <NAME> import networkx as nx", "an edgelist # @param adjacency: a list whose ith entry is an adjacency", "edgelist and preprocess the resulting DataFrame edges = nx.convert_matrix.to_pandas_edgelist(temp_graph) edges = edges.drop(['weight'], axis=1)", "<filename>python/adjacency_to_edgelist.py # adjacency_to_edgelist # # Function that converts a list of adjacency matrices", "@param adjacency: a list whose ith entry is an adjacency matrix representing the", "we can do so here by creating a boolean series of entries who's", "series of entries who's nodes are equal, # and drop them from the", "boolean series of entries who's nodes are equal, # and drop them from", "edgelist: a matrix with three columns representing edge connections: node1, node2, layer #", "edges.rename(columns={\"source\": \"node1\", \"target\": \"node2\"}) edges['layer'] = i # Set a third column to", "# Convert each matrix to a NetworkX Graph temp_graph = nx.from_numpy_matrix(np.asarray(adjacency[i]), False) #", "columns representing edge connections: node1, node2, layer # # Basis: Wilson, <NAME>., Palowitch,", "layer # # Basis: Wilson, <NAME>., Palowitch, <NAME>, Shankar, and Nobel, <NAME>. (2017)", "# @keywords community detection, multilayer networks, configuration model, random graph models # @return", "weight column (Unweighted graph) # Rename source and target columns to node1 and", "edgelist = edgelist.append(edges) # Now with correct data structures, we can append to", "@keywords community detection, multilayer networks, configuration model, random graph models # @return edgelist:", "Research # Original R Code: <NAME> # Revised Python Code: <NAME> import networkx", "'layer': [0]}) m = len(adjacency) for i in range(0, m + 1): #", "= i # Set a third column to the layer number edgelist =", "random graph models # @return edgelist: a matrix with three columns representing edge", "correct data structures, we can append to the edgelist # The indices will", "== edgelist['node2']].index) # Since we dropped items in the line above, we must", "column to the layer number edgelist = edgelist.append(edges) # Now with correct data", "Nobel, <NAME>. (2017) \"Significance based # extraction in multilayer networks with heterogeneous community", "The indices will be jumbled from many appends, so we can reset the", "# Original R Code: <NAME> # Revised Python Code: <NAME> import networkx as", "networks with heterogeneous community structure.\" Journal of Machine Learning Research # Original R", "# Basis: Wilson, <NAME>., Palowitch, <NAME>, Shankar, and Nobel, <NAME>. (2017) \"Significance based", "# # Basis: Wilson, <NAME>., Palowitch, <NAME>, Shankar, and Nobel, <NAME>. (2017) \"Significance", "a NetworkX Graph temp_graph = nx.from_numpy_matrix(np.asarray(adjacency[i]), False) # Convert NetworkX Graph to an", "columns to node1 and node2 (Undirected graph) edges = edges.rename(columns={\"source\": \"node1\", \"target\": \"node2\"})", "edgelist = pd.DataFrame({'node1': [0], 'node2': [0], 'layer': [0]}) m = len(adjacency) for i", "# and drop them from the DataFrame to preserve community structure later on.", "based # extraction in multilayer networks with heterogeneous community structure.\" Journal of Machine", "# The indices will be jumbled from many appends, so we can reset", "are equal, # and drop them from the DataFrame to preserve community structure", "temp_graph = nx.from_numpy_matrix(np.asarray(adjacency[i]), False) # Convert NetworkX Graph to an edgelist and preprocess", "jumbled from many appends, so we can reset the index edgelist = edgelist.reset_index(drop=True)", "Python Code: <NAME> import networkx as nx import numpy as np import pandas", "Instantiate labeled dataframe to make sure appends later on merge correctly edgelist =", "for i in range(0, m + 1): # Convert each matrix to a", "NetworkX Graph structure, # we can do so here by creating a boolean" ]
[ "# In[18]: def pluz(arg1, arg2): try: s = arg1 + arg2 except TypeError:", "coding: utf-8 # In[13]: import json # In[18]: def pluz(arg1, arg2): try: s", "s = arg1 + arg2 except TypeError: s = int(arg1) + int(arg2) return", "try: s = arg1 + arg2 except TypeError: s = int(arg1) + int(arg2)", "utf-8 # In[13]: import json # In[18]: def pluz(arg1, arg2): try: s =", "#!/usr/bin/env python # coding: utf-8 # In[13]: import json # In[18]: def pluz(arg1,", "+ arg2 except TypeError: s = int(arg1) + int(arg2) return s # In[", "def pluz(arg1, arg2): try: s = arg1 + arg2 except TypeError: s =", "arg2 except TypeError: s = int(arg1) + int(arg2) return s # In[ ]:", "# In[13]: import json # In[18]: def pluz(arg1, arg2): try: s = arg1", "pluz(arg1, arg2): try: s = arg1 + arg2 except TypeError: s = int(arg1)", "# coding: utf-8 # In[13]: import json # In[18]: def pluz(arg1, arg2): try:", "arg2): try: s = arg1 + arg2 except TypeError: s = int(arg1) +", "json # In[18]: def pluz(arg1, arg2): try: s = arg1 + arg2 except", "import json # In[18]: def pluz(arg1, arg2): try: s = arg1 + arg2", "In[18]: def pluz(arg1, arg2): try: s = arg1 + arg2 except TypeError: s", "In[13]: import json # In[18]: def pluz(arg1, arg2): try: s = arg1 +", "python # coding: utf-8 # In[13]: import json # In[18]: def pluz(arg1, arg2):", "= arg1 + arg2 except TypeError: s = int(arg1) + int(arg2) return s", "arg1 + arg2 except TypeError: s = int(arg1) + int(arg2) return s #" ]
[ "\"open\" #: PAUSE = \"pause\" #: PLAY = \"play\" #: PLAYING = \"playing\"", "self.inputType \"\"\" Returns the type of the change (i.e \"inserting\" or \"deleting\") \"\"\"", "isComposing(self, *args, **kwargs): # pass # KeyboardEvent # isComposing Returns whether the state", "clientX(self): return self.x @property def clientY(self): return self.y @property def altKey(self): return self._altKey", "1000)) # self.type = None pass def msConvertURL(self): pass def preventDefault(self): pass def", "if _type not in self.listeners: self.listeners[_type] = [] self.listeners[_type].append(callback) def removeEventListener(self, _type, callback):", "= None # self.cancelBubble = None # self.composed = None # self.currentTarget =", "# self.addEventListener(DragEvent.START, self.ondragstart) # self.addEventListener(DragEvent.DROP, self.ondrop) # self.addEventListener(ClipboardEvent.CUT, self.oncut) # self.addEventListener(ClipboardEvent.COPY, self.oncopy) #", "self.originalTarget = None # self.explicitOriginalTarget = None # self.target = None # self.srcElement", "args, kwargs) def stopPropagation(self): \"\"\"[prevents further propagation of the current event in the", "*args, **kwargs): self.clipboardData = None \"\"\" Returns an object containing the data affected", "self.ondragenter) # self.addEventListener(DragEvent.EXIT, self.ondragexit) # self.addEventListener(DragEvent.LEAVE, self.ondragleave) # self.addEventListener(DragEvent.OVER, self.ondragover) # self.addEventListener(DragEvent.START, self.ondragstart)", "def code(self): # return self.code # @property # def key(self): # return self.key", "NotImplementedError def onselectstart(self, event): print(event) raise NotImplementedError def onshow(self, event): print(event) raise NotImplementedError", "\"waiting\" #: # Event(\"look\", {\"bubbles\":true, \"cancelable\":false}); def __init__(self, _type=None, *args, **kwargs): # print('type',", "= None super().__init__(_type, *args, **kwargs) class TouchEvent(Event): \"\"\" TouchEvent \"\"\" TOUCHCANCEL = \"touchcancel\"", "None # self.filename=None # self.lineno=0 # self.colno=0 # self.error={} super().__init__(_type, *args, **kwargs) class", "= \"pause\" #: PLAY = \"play\" #: PLAYING = \"playing\" #: PROGRESS =", "of the transition \"\"\" super().__init__(_type, *args, **kwargs) class ProgressEvent(Event): \"\"\" ProgressEvent \"\"\" LOADSTART", "True # huh?. surely false? stack = self.listeners[event.type] # .slice() event.target = self", "**kwargs) class FocusEvent(Event): \"\"\" FocusEvent \"\"\" BLUR = \"blur\" #: FOCUS = \"focus\"", "self.addEventListener(ClipboardEvent.COPY, self.oncopy) # self.addEventListener(ClipboardEvent.PASTE, self.onpaste) def onabort(self, event): print(event) raise NotImplementedError def onblur(self,", "#: def __init__(self, _type, *args, **kwargs): self.relatedTarget = None super().__init__(_type, *args, **kwargs) class", "NotImplementedError def onscroll(self, event): print(event) raise NotImplementedError def onseeked(self, event): print(event) raise NotImplementedError", "MOUSEOUT = \"mouseout\" #: MOUSEUP = \"mouseup\" #: def __init__(self, _type, *args, **kwargs):", "onmouseout(self, event): print(event) raise NotImplementedError def onmouseover(self, event): print(event) raise NotImplementedError def onmouseup(self,", "@property def ctrlKey(self): return self._ctrlKey @property def shiftKey(self): return self._shiftKey @property def metaKey(self):", "event): print(event) raise NotImplementedError def oncanplay(self, event): print(event) raise NotImplementedError def oncanplaythrough(self, event):", "KEYPRESS = \"keypress\" #: KEYUP = \"keyup\" #: def __init__(self, _type, *args, **kwargs):", "**kwargs): self.shiftKey = None self.altKey = None self.changedTouches = None self.ctrlKey = None", "NotImplementedError def onauxclick(self, event): print(event) raise NotImplementedError def onformdata(self, event): print(event) raise NotImplementedError", "locationArg self.modifiersListArg = modifiersListArg self.repeat = repeat @property def altKey(self): return self._altKey @property", "Returns an object representing the affected storage object \"\"\" self.url = None \"\"\"", "self.colno=0 # self.error={} super().__init__(_type, *args, **kwargs) class SubmitEvent(Event): \"\"\" SubmitEvent \"\"\" SUBMIT =", "# super.__init__(self, type, bubbles, cancelable) super().__init__(_type) # TODO - self.source = source class", "self.height = None self.pressure = None self.tangentialPressure = None self.tiltX = None self.tiltY", "\"offline\" #: ONLINE = \"online\" #: OPEN = \"open\" #: PAUSE = \"pause\"", "onmousedown(self, event): print(event) raise NotImplementedError def ontouchcancel(self, event): print(event) raise NotImplementedError def ontouchstart(self,", "#: DROP = \"drop\" #: def __init__(self, _type, *args, **kwargs): self.dataTransfer = None", "None super().__init__(_type, *args, **kwargs) class WheelEvent(Event): \"\"\" WheelEvent \"\"\" MOUSEWHEEL = \"mousewheel\" #", "KeyboardEvent class UIEvent(Event): \"\"\" UIEvent \"\"\" def __init__(self, _type, *args, **kwargs): self.detail =", "self.listeners[event.type] # .slice() event.target = self # TODO/NOTE - is this correct? -", "the pseudo-element of the animation \"\"\" super().__init__(_type, *args, **kwargs) class ClipboardEvent(Event): \"\"\" ClipboardEvent", "NotImplementedError def oncontextmenu(self, event): print(event) raise NotImplementedError def oncuechange(self, event): print(event) raise NotImplementedError", "def __init__(self, _type, *args, **kwargs): super().__init__(_type, *args, **kwargs) class SVGEvent(Event): \"\"\" SVGEvent \"\"\"", "self.args = args # self.kwargs = kwargs self._altKey = False self._ctrlKey = False", "raise NotImplementedError def onshow(self, event): print(event) raise NotImplementedError def onstalled(self, event): print(event) raise", "ctrlKey=False, altKey=False, shiftKey=False, metaKey=False, button=None, relatedTarget=None, from_json={}, *args, **kwargs): # print('initMouseEvent') self._type =", "\"\"\" def __init__(self, _type, *args, **kwargs): self.key = None \"\"\" Returns the key", "raise NotImplementedError def onpointermove(self, event): print(event) raise NotImplementedError def onpointerout(self, event): print(event) raise", "= \"unload\" #: VOLUMECHANGE = \"volumechange\" #: WAITING = \"waiting\" #: # Event(\"look\",", "raise NotImplementedError def oncontextmenu(self, event): print(event) raise NotImplementedError def oncuechange(self, event): print(event) raise", "print(event) raise NotImplementedError def ontouchcancel(self, event): print(event) raise NotImplementedError def ontouchstart(self, event): print(event)", "#: FULLSCREENERROR = \"fullscreenerror\" #: INPUT = \"input\" #: INVALID = \"invalid\" #:", "@property def button(self): return self._button @property def buttons(self): return self._buttons @property def which(self):", "the last mousemove event MouseEvent # offsetX Returns the horizontal coordinate of the", "= typeArg self.canBubbleArg = canBubbleArg self.cancelableArg = cancelableArg self.viewArg = viewArg self.charArg =", "*args, **kwargs): self.persisted = None \"\"\" Returns whether the webpage was cached by", "def onpointerleave(self, event): print(event) raise NotImplementedError def onpointermove(self, event): print(event) raise NotImplementedError def", "view=None, detail=None, screenX=0, screenY=0, clientX=0, clientY=0, ctrlKey=False, altKey=False, shiftKey=False, metaKey=False, button=None, relatedTarget=None, from_json={},", "class TweenEvent(Event): \"\"\" TweenEvent \"\"\" START = \"onStart\" #: STOP = \"onStop\" #:", "#: def __init__(self, _type, *args, **kwargs): self.newURL = None self.oldURL = None super().__init__(_type,", "raise NotImplementedError def oncancel(self, event): print(event) raise NotImplementedError def oncanplay(self, event): print(event) raise", "None super().__init__(_type, *args, **kwargs) class AnimationEvent(Event): \"\"\" AnimationEvent \"\"\" ANIMATIONEND = \"animationend\" #:", "OVER = \"dragover\" #: START = \"dragstart\" #: DROP = \"drop\" #: def", "GamePadEvent \"\"\" START = \"gamepadconnected\" #: STOP = \"gamepaddisconnected\" #: def __init__(self, _type,", "_type, *args, **kwargs): super().__init__(_type, *args, **kwargs) class DragEvent(Event): \"\"\" DragEvent \"\"\" DRAG =", "\"\"\" self.newValue = None \"\"\" Returns the new value of the changed storage", "#: CUT = \"cut\" #: PASTE = \"paste\" #: def __init__(self, _type, *args,", "self.isTrusted = None self.originalTarget = None self.returnValue = None self.srcElement = None self.target", "event): print(event) raise NotImplementedError def onpointerup(self, event): print(event) raise NotImplementedError def onprogress(self, event):", "event): print(event) raise NotImplementedError def onmouseenter(self, event): print(event) raise NotImplementedError def onmouseleave(self, event):", "Returns the new value of the changed storage item \"\"\" self.oldValue = None", "print(event) raise NotImplementedError def oncancel(self, event): print(event) raise NotImplementedError def oncanplay(self, event): print(event)", "NotImplementedError def onchange(self, event): print(event) raise NotImplementedError def onclick(self, event): print(event) raise NotImplementedError", "#: ABORT = \"abort\" #: AFTERPRINT = \"afterprint\" #: BEFOREPRINT = \"beforeprint\" #:", "self.timeStamp = int(round(time.time() * 1000)) # self.type = None pass def msConvertURL(self): pass", "of the current event in the capturing and bubbling phases]\"\"\" # self.defaultPrevented =", "def ondragenter(self, event): print(event) raise NotImplementedError def ondragexit(self, event): print(event) raise NotImplementedError def", "_type, *args, **kwargs): super().__init__(_type, *args, **kwargs) class PointerEvent(Event): \"\"\" PointerEvent \"\"\" POINTER =", "**kwargs): self.animationName = None \"\"\" Returns the name of the animation \"\"\" self.elapsedTime", "None super().__init__(_type, *args, **kwargs) def initKeyboardEvent(self, typeArg, canBubbleArg, cancelableArg, viewArg, charArg, keyArg, locationArg,", "changed item's document \"\"\" super().__init__(_type, *args, **kwargs) class TransitionEvent(Event): \"\"\" TransitionEvent \"\"\" TRANSITIONEND", "information about the inserted/deleted data \"\"\" self.getTargetRanges \"\"\" Returns an array containing target", "self._button = button self.relatedTarget = relatedTarget # TODO - parse from_json - so", "PLAYING = \"playing\" #: PROGRESS = \"progress\" #: RATECHANGE = \"ratechange\" #: RESIZE", "related to the element that triggered the mouse event MouseEvent, FocusEvent class KeyboardEvent(Event):", "keyArg self.locationArg = locationArg self.modifiersListArg = modifiersListArg self.repeat = repeat @property def altKey(self):", "class DragEvent(Event): \"\"\" DragEvent \"\"\" DRAG = \"drag\" #: END = \"dragend\" #:", "print(event) raise NotImplementedError def onpointercancel(self, event): print(event) raise NotImplementedError def onpointerdown(self, event): print(event)", "# self.lineno=0 # self.colno=0 # self.error={} super().__init__(_type, *args, **kwargs) class SubmitEvent(Event): \"\"\" SubmitEvent", "bubbles, cancelable) super().__init__(_type) # TODO - self.source = source class GlobalEventHandler: # (EventDispatcher):", "pageX Returns the horizontal coordinate of the mouse pointer, relative to the document,", "@property # def key(self): # return self.key # def isComposing(self, *args, **kwargs): #", "= \"emptied\" #: ABORT = \"abort\" #: AFTERPRINT = \"afterprint\" #: BEFOREPRINT =", "self.defaultPrevented = False self.eventPhase = None self.explicitOriginalTarget = None self.isTrusted = None self.originalTarget", "= True # self.returnValue = None # self.originalTarget = None # self.explicitOriginalTarget =", "None super().__init__(_type, *args, **kwargs) def initCustomEvent(self): pass class GamePadEvent(Event): \"\"\" GamePadEvent \"\"\" START", "the event is composing or not \"\"\" super().__init__(_type, *args, **kwargs) class PageTransitionEvent(Event): \"\"\"", "def addEventListener(self, event: str, function, useCapture: bool) -> None: def addEventListener(self, _type, callback,", "def onmouseleave(self, event): print(event) raise NotImplementedError def onmousemove(self, event): print(event) raise NotImplementedError def", "print(e) thing() # try calling without params, user may not create param return", "\"\"\" Returns whether the state of the event is composing or not \"\"\"", "= None self.pressure = None self.tangentialPressure = None self.tiltX = None self.tiltY =", "huh?. surely false? stack = self.listeners[event.type] # .slice() event.target = self # TODO/NOTE", "self.x @property def clientY(self): return self.y @property def altKey(self): return self._altKey @property def", "raise NotImplementedError def ondrop(self, event): print(event) raise NotImplementedError def ondurationchange(self, event): print(event) raise", "= None self.pointerType = None self.isPrimary = None super().__init__(_type, *args, **kwargs) class BeforeUnloadEvent(Event):", "of the pseudo-element of the transition \"\"\" super().__init__(_type, *args, **kwargs) class ProgressEvent(Event): \"\"\"", "= \"loadedmetadata\" #: MESSAGE = \"message\" #: OFFLINE = \"offline\" #: ONLINE =", "*args, **kwargs) def initMouseEvent(self, _type=None, canBubble=True, cancelable=True, view=None, detail=None, screenX=0, screenY=0, clientX=0, clientY=0,", "self.elapsedTime = None \"\"\" Returns the number of seconds an animation has been", "_type, *args, **kwargs): self.deltaX = None self.deltaY = None self.deltaZ = None self.deltaMode", "FOCUS = \"focus\" #: FOCUSIN = \"focusin\" #: FOCUSOUT = \"focusout\" #: def", "None self.metaKey = None self.shiftKey = None self.targetTouches = None self.touches = None", "STOP = \"onStop\" #: RESET = \"onReset\" #: PAUSE = \"onPause\" #: UNPAUSE", "you can extend to give your obj event dispatching abilities \"\"\" def __init__(self,", "self.getTargetRanges \"\"\" Returns an array containing target ranges that will be affected by", "= None super().__init__(_type, *args, **kwargs) class InputEvent(Event): \"\"\" InputEvent \"\"\" def __init__(self, _type,", "onformdata(self, event): print(event) raise NotImplementedError def onmousedown(self, event): print(event) raise NotImplementedError def ontouchcancel(self,", "PageTransitionEvent(Event): \"\"\" PageTransitionEvent \"\"\" PAGEHIDE = \"pagehide\" #: PAGESHOW = \"pageshow\" #: def", "MouseEvent # offsetX Returns the horizontal coordinate of the mouse pointer relative to", "NotImplementedError def onsubmit(self, event): print(event) raise NotImplementedError def onsuspend(self, event): print(event) raise NotImplementedError", "def onplay(self, event): print(event) raise NotImplementedError def onplaying(self, event): print(event) raise NotImplementedError def", "class TransitionEvent(Event): \"\"\" TransitionEvent \"\"\" TRANSITIONEND = \"transitionend\" #: def __init__(self, _type, *args,", "print(event) raise NotImplementedError def onsubmit(self, event): print(event) raise NotImplementedError def onsuspend(self, event): print(event)", "NotImplementedError def oncanplay(self, event): print(event) raise NotImplementedError def oncanplaythrough(self, event): print(event) raise NotImplementedError", "return _type in self.listeners # TODO - event: str, function, useCapture: bool #", "TRANSITIONEND = \"transitionend\" #: def __init__(self, _type, *args, **kwargs): self.propertyName = None \"\"\"", "None \"\"\" Returns an object representing the affected storage object \"\"\" self.url =", "= \"onUpdateEnd\" #: COMPLETE = \"onComplete\" #: TIMER = \"onTimer\" #: _source =", "name of the transition\"\"\" self.elapsedTime = None \"\"\" Returns the number of seconds", "self.addEventListener(ClipboardEvent.PASTE, self.onpaste) def onabort(self, event): print(event) raise NotImplementedError def onblur(self, event): print(event) raise", "def onresize(self, event): print(event) raise NotImplementedError def onscroll(self, event): print(event) raise NotImplementedError def", "*args, **kwargs) class ProgressEvent(Event): \"\"\" ProgressEvent \"\"\" LOADSTART = \"loadstart\" #: def __init__(self,", "kwargs) def stopPropagation(self): \"\"\"[prevents further propagation of the current event in the capturing", "the old value of the changed storage item \"\"\" self.storageArea = None \"\"\"", "down repeatedly, or not KeyboardEvent # location Returns the location of a key", "typeArg self.canBubbleArg = canBubbleArg self.cancelableArg = cancelableArg self.viewArg = viewArg self.charArg = charArg", "in self.listeners # TODO - event: str, function, useCapture: bool # def addEventListener(self,", "animation \"\"\" super().__init__(_type, *args, **kwargs) class ClipboardEvent(Event): \"\"\" ClipboardEvent \"\"\" COPY = \"copy\"", "#: ONLINE = \"online\" #: OPEN = \"open\" #: PAUSE = \"pause\" #:", "\"\"\" WheelEvent \"\"\" MOUSEWHEEL = \"mousewheel\" # DEPRECATED - USE WHEEL #: WHEEL", "NotImplementedError def onseeking(self, event): print(event) raise NotImplementedError def onselect(self, event): print(event) raise NotImplementedError", "Returns the URL of the changed item's document \"\"\" super().__init__(_type, *args, **kwargs) class", "#: def __init__(self, _type, *args, **kwargs): super().__init__(_type, *args, **kwargs) class CustomEvent(Event): \"\"\" CustomEvent", "self.key # @property # def keyCode(self): # return self.keyCode # @property # def", "the element related to the element that triggered the mouse event MouseEvent, FocusEvent", "EventDispatcher(object): \"\"\" EventDispatcher is a class you can extend to give your obj", "self.returnValue = None self.srcElement = None self.target = None # ms = time.time_ns()", "NotImplementedError def ontouchstart(self, event): print(event) raise NotImplementedError def ontransitioncancel(self, event): print(event) raise NotImplementedError", "= None # self.srcElement = None # self.bubbles = None # self.cancelable =", "\"copy\" #: CUT = \"cut\" #: PASTE = \"paste\" #: def __init__(self, _type,", "= None super().__init__(_type, *args, **kwargs) class BeforeUnloadEvent(Event): BEFOREUNLOAD = \"beforeunload\" #: \"\"\" BeforeUnloadEvent", "= \"beforeunload\" #: CANPLAY = \"canplay\" #: CANPLAYTHROUGH = \"canplaythrough\" #: CHANGE =", "an animation has been running \"\"\" self.pseudoElement = None \"\"\" Returns the name", "\"toggle\" #: UNLOAD = \"unload\" #: VOLUMECHANGE = \"volumechange\" #: WAITING = \"waiting\"", "#: PAUSE = \"onPause\" #: UNPAUSE = \"onUnPause\" #: UPDATE_START = \"onUpdateStart\" #:", "def __init__(self, _type, *args, **kwargs): self.animationName = None \"\"\" Returns the name of", "PAGEHIDE = \"pagehide\" #: PAGESHOW = \"pageshow\" #: def __init__(self, _type, *args, **kwargs):", "source=None, bubbles=False, cancelable=False): # super.__init__(self, type, bubbles, cancelable) super().__init__(_type) # TODO - self.source", "NotImplementedError def onerror(self, event): print(event) raise NotImplementedError def onfocus(self, event): print(event) raise NotImplementedError", "type(thing, (Event,), self) except Exception as e: print(e) thing() # try calling without", "**kwargs) class HashChangeEvent(Event): \"\"\" HashChangeEvent \"\"\" CHANGE = \"hashchange\" #: def __init__(self, _type,", "#: TOUCHSTART = \"touchstart\" #: def __init__(self, _type, *args, **kwargs): self.shiftKey = None", "the changed storage item \"\"\" self.oldValue = None \"\"\" Returns the old value", "self.onmousemove) # self.addEventListener(MouseEvent.MOUSEDOWN, self.onmousedown) # self.addEventListener(MouseEvent.MOUSEUP, self.onmouseup) # self.addEventListener(DragEvent.DRAG, self.ondrag) # self.addEventListener(DragEvent.END, self.ondragend)", "return self.key # @property # def keyCode(self): # return self.keyCode # @property #", "transition \"\"\" super().__init__(_type, *args, **kwargs) class ProgressEvent(Event): \"\"\" ProgressEvent \"\"\" LOADSTART = \"loadstart\"", "\"timer\" #: \"\"\" TimerEvent \"\"\" def __init__(self, _type, *args, **kwargs): super().__init__(_type, *args, **kwargs)", "self.propertyName = None \"\"\" Returns the name of the transition\"\"\" self.elapsedTime = None", "= None \"\"\" Returns the name of the pseudo-element of the transition \"\"\"", "self.width = None self.height = None self.pressure = None self.tangentialPressure = None self.tiltX", "of a key on the keyboard or device KeyboardEvent class UIEvent(Event): \"\"\" UIEvent", "item \"\"\" self.oldValue = None \"\"\" Returns the old value of the changed", "raise NotImplementedError def onloadend(self, event): print(event) raise NotImplementedError def onloadstart(self, event): print(event) raise", "= \"animationiteration\" #: ANIMATIONSTART = \"animationstart\" #: def __init__(self, _type, *args, **kwargs): self.animationName", "\"\"\" Returns the number of seconds an animation has been running \"\"\" self.pseudoElement", "self.addEventListener(DragEvent.ENTER, self.ondragenter) # self.addEventListener(DragEvent.EXIT, self.ondragexit) # self.addEventListener(DragEvent.LEAVE, self.ondragleave) # self.addEventListener(DragEvent.OVER, self.ondragover) # self.addEventListener(DragEvent.START,", "LOADEDMETADATA = \"loadedmetadata\" #: MESSAGE = \"message\" #: OFFLINE = \"offline\" #: ONLINE", "= \"blur\" #: FOCUS = \"focus\" #: FOCUSIN = \"focusin\" #: FOCUSOUT =", "UPDATE_START = \"onUpdateStart\" #: UPDATE_END = \"onUpdateEnd\" #: COMPLETE = \"onComplete\" #: TIMER", "*args, **kwargs): # print('type', _type) self.type = _type self.bubbles = None self.cancelable =", "def onseeked(self, event): print(event) raise NotImplementedError def onseeking(self, event): print(event) raise NotImplementedError def", "None super().__init__(_type, *args, **kwargs) class InputEvent(Event): \"\"\" InputEvent \"\"\" def __init__(self, _type, *args,", "def which(self): return self._button # MOUSE_EVENT # getModifierState() Returns an array containing target", "# pass # KeyboardEvent # isComposing Returns whether the state of the event", "POINTER = \"pointer\" #: def __init__(self, _type, *args, **kwargs): self.pointerId = None self.width", "None super().__init__(_type, *args, **kwargs) class TweenEvent(Event): \"\"\" TweenEvent \"\"\" START = \"onStart\" #:", "return self._button @property def buttons(self): return self._buttons @property def which(self): return self._button #", "not event.defaultPrevented class Event(object): \"\"\" event \"\"\" EMPTIED = \"emptied\" #: ABORT =", "charArg self.keyArg = keyArg self.locationArg = locationArg self.modifiersListArg = modifiersListArg self.repeat = repeat", "\"error\" #: FULLSCREENCHANGE = \"fullscreenchange\" #: FULLSCREENERROR = \"fullscreenerror\" #: INPUT = \"input\"", "= \"pointer\" #: def __init__(self, _type, *args, **kwargs): self.pointerId = None self.width =", "\"\"\" self.pseudoElement = None \"\"\" Returns the name of the pseudo-element of the", "\"\"\" Returns the URL of the changed item's document \"\"\" super().__init__(_type, *args, **kwargs)", "return self.code # @property # def key(self): # return self.key # def isComposing(self,", "# self.addEventListener(DragEvent.DROP, self.ondrop) # self.addEventListener(ClipboardEvent.CUT, self.oncut) # self.addEventListener(ClipboardEvent.COPY, self.oncopy) # self.addEventListener(ClipboardEvent.PASTE, self.onpaste) def", "browser \"\"\" super().__init__(_type, *args, **kwargs) class PopStateEvent(Event): \"\"\" PopStateEvent \"\"\" def __init__(self, _type,", "a class you can extend to give your obj event dispatching abilities \"\"\"", "TransitionEvent(Event): \"\"\" TransitionEvent \"\"\" TRANSITIONEND = \"transitionend\" #: def __init__(self, _type, *args, **kwargs):", "except Exception as e: print(e) thing() # try calling without params, user may", "of the mouse pointer relative to the position of the edge of the", "pointer relative to the position of the edge of the target element MouseEvent", "= None \"\"\" Returns the inserted characters \"\"\" self.dataTransfer \"\"\" Returns an object", "FOCUSIN = \"focusin\" #: FOCUSOUT = \"focusout\" #: def __init__(self, _type, *args, **kwargs):", "None \"\"\" Returns whether the webpage was cached by the browser \"\"\" super().__init__(_type,", "*args, **kwargs): self.gamepad = None super().__init__(_type, *args, **kwargs) class TweenEvent(Event): \"\"\" TweenEvent \"\"\"", "print(event) raise NotImplementedError def oncanplaythrough(self, event): print(event) raise NotImplementedError def onchange(self, event): print(event)", "HashChangeEvent \"\"\" CHANGE = \"hashchange\" #: def __init__(self, _type, *args, **kwargs): self.newURL =", "= relatedTarget # TODO - parse from_json - so can relay @property def", "type of the change (i.e \"inserting\" or \"deleting\") \"\"\" self.isComposing \"\"\" Returns whether", "self.composed = None self.currentTarget = None self.defaultPrevented = False self.eventPhase = None self.explicitOriginalTarget", "# @property # def keyCode(self): # return self.keyCode # @property # def charCode(self):", "def __init__(self, _type, *args, **kwargs): self.newURL = None self.oldURL = None super().__init__(_type, *args,", "return self.charCode # @property # def code(self): # return self.code # @property #", "= None self.targetTouches = None self.touches = None super().__init__(_type, *args, **kwargs) class WheelEvent(Event):", "NotImplementedError def onkeypress(self, event): print(event) raise NotImplementedError def onkeyup(self, event): print(event) raise NotImplementedError", "raise NotImplementedError def onselect(self, event): print(event) raise NotImplementedError def onselectionchange(self, event): print(event) raise", "VOLUMECHANGE = \"volumechange\" #: WAITING = \"waiting\" #: # Event(\"look\", {\"bubbles\":true, \"cancelable\":false}); def", "# TODO - bring EventTarget here and get rid of this one? class", "None # self.srcElement = None # self.bubbles = None # self.cancelable = None", "self.oldURL = None super().__init__(_type, *args, **kwargs) class InputEvent(Event): \"\"\" InputEvent \"\"\" def __init__(self,", "repeatedly, or not KeyboardEvent # location Returns the location of a key on", "self.keyArg = keyArg self.locationArg = locationArg self.modifiersListArg = modifiersListArg self.repeat = repeat @property", "\"\"\" def __init__(self, _type, *args, **kwargs): self.detail = None self.view = None super().__init__(_type,", "will be affected by the insertion/deletion MouseEvent # MovementX Returns the horizontal coordinate", "the current event in the capturing and bubbling phases]\"\"\" # self.defaultPrevented = True", "= clientY self._ctrlKey = ctrlKey self._altKey = altKey self._shiftKey = shiftKey self._metaKey =", "def removeEventListener(self, _type, callback): if _type not in self.listeners: return stack = self.listeners[_type]", "self.oldValue = None \"\"\" Returns the old value of the changed storage item", "= screenX self.screenY = screenY self._clientX = clientX self._clientY = clientY self._ctrlKey =", "def ctrlKey(self): return self._ctrlKey @property def shiftKey(self): return self._shiftKey @property def metaKey(self): return", "Returns the key of the changed storage item \"\"\" self.newValue = None \"\"\"", "detail self.screenX = screenX self.screenY = screenY self._clientX = clientX self._clientY = clientY", "None \"\"\" Returns an object containing a copy of the history entries \"\"\"", "calling without params, user may not create param return not event.defaultPrevented class Event(object):", "def onmouseup(self, event): print(event) raise NotImplementedError def onpause(self, event): print(event) raise NotImplementedError def", "event): print(event) raise NotImplementedError def onpointerdown(self, event): print(event) raise NotImplementedError def onpointerenter(self, event):", "= \"drop\" #: def __init__(self, _type, *args, **kwargs): self.dataTransfer = None \"\"\" Returns", "@property def metaKey(self): return self._metaKey @property def unicode(self): return self.key # @property #", "mouse pointer relative to the position of the last mousemove event MouseEvent #", "= False self._ctrlKey = False self._shiftKey = False self._metaKey = False self.charCode =", "# KeyboardEvent # isComposing Returns whether the state of the event is composing", "= \"dragstart\" #: DROP = \"drop\" #: def __init__(self, _type, *args, **kwargs): self.dataTransfer", "= \"dragenter\" #: EXIT = \"dragexit\" #: LEAVE = \"dragleave\" #: OVER =", "# self.eventPhase = None # self.isTrusted = None # self.returnValue = None #", "None super().__init__(_type, *args, **kwargs) class FocusEvent(Event): \"\"\" FocusEvent \"\"\" BLUR = \"blur\" #:", "= \"onReset\" #: PAUSE = \"onPause\" #: UNPAUSE = \"onUnPause\" #: UPDATE_START =", "be affected by the insertion/deletion MouseEvent # MovementX Returns the horizontal coordinate of", "pageY Returns the vertical coordinate of the mouse pointer, relative to the document,", "#: OPEN = \"open\" #: PAUSE = \"pause\" #: PLAY = \"play\" #:", "None self.srcElement = None self.target = None # ms = time.time_ns() // 1000000", "TimerEvent(Event): TIMER = \"timer\" #: \"\"\" TimerEvent \"\"\" def __init__(self, _type, *args, **kwargs):", "NotImplementedError def ondragover(self, event): print(event) raise NotImplementedError def ondragstart(self, event): print(event) raise NotImplementedError", "event MouseEvent # MovementY Returns the vertical coordinate of the mouse pointer relative", "mouse pointer, relative to the document, when the mouse event was triggered MouseEvent", "self.listeners[_type] for thing in stack: if thing == callback: stack.remove(thing) return def dispatchEvent(self,", "KeyboardEvent # isComposing Returns whether the state of the event is composing or", "\"transitionend\" #: def __init__(self, _type, *args, **kwargs): self.propertyName = None \"\"\" Returns the", "#: DURATIONCHANGE = \"durationchange\" #: ENDED = \"ended\" #: ERROR = \"error\" #:", "event): print(event) raise NotImplementedError def onsuspend(self, event): print(event) raise NotImplementedError def ontimeupdate(self, event):", "def clientY(self): return self.y @property def altKey(self): return self._altKey @property def ctrlKey(self): return", "stack = self.listeners[_type] for thing in stack: if thing == callback: stack.remove(thing) return", "mouse pointer relative to the position of the edge of the target element", "document, when the mouse event was triggered MouseEvent # region MouseEvent # relatedTarget", "= None self.shiftKey = None self.targetTouches = None self.touches = None super().__init__(_type, *args,", "*args, **kwargs): # pass # KeyboardEvent # isComposing Returns whether the state of", "for thing in stack: try: thing(event) # type(thing, (Event,), self) except Exception as", "def ondragover(self, event): print(event) raise NotImplementedError def ondragstart(self, event): print(event) raise NotImplementedError def", "*args, **kwargs): self.detail = None super().__init__(_type, *args, **kwargs) def initCustomEvent(self): pass class GamePadEvent(Event):", "self.eventPhase = None self.explicitOriginalTarget = None self.isTrusted = None self.originalTarget = None self.returnValue", "\"resize\" #: RESET = \"reset\" #: SCROLL = \"scroll\" #: SEARCH = \"search\"", "None self.deltaZ = None self.deltaMode = None super().__init__(_type, *args, **kwargs) class AnimationEvent(Event): \"\"\"", "\"fullscreenerror\" #: INPUT = \"input\" #: INVALID = \"invalid\" #: LOAD = \"load\"", "phases]\"\"\" # self.defaultPrevented = True # self.returnValue = None # self.originalTarget = None", "event): print(event) raise NotImplementedError def onscroll(self, event): print(event) raise NotImplementedError def onseeked(self, event):", "*args, **kwargs): self.__init__(_type, args, kwargs) def stopPropagation(self): \"\"\"[prevents further propagation of the current", "thing in stack: try: thing(event) # type(thing, (Event,), self) except Exception as e:", "NotImplementedError def onload(self, event): print(event) raise NotImplementedError def onloadeddata(self, event): print(event) raise NotImplementedError", "= \"wheel\" #: def __init__(self, _type, *args, **kwargs): self.deltaX = None self.deltaY =", "#: SHOW = \"show\" #: STALLED = \"stalled\" #: SUBMIT = \"submit\" #:", "raise NotImplementedError def ondrag(self, event): print(event) raise NotImplementedError def ondragend(self, event): print(event) raise", "print(event) raise NotImplementedError def onclick(self, event): print(event) raise NotImplementedError def onclose(self, event): print(event)", "= False self.charCode = None self.code = None self.key = None self.keyCode =", "def dispatchEvent(self, event): if event.type not in self.listeners: return True # huh?. surely", "the element that triggered the mouse event MouseEvent, FocusEvent class KeyboardEvent(Event): \"\"\" keyboard", "of the animation \"\"\" super().__init__(_type, *args, **kwargs) class ClipboardEvent(Event): \"\"\" ClipboardEvent \"\"\" COPY", "PASTE = \"paste\" #: def __init__(self, _type, *args, **kwargs): self.clipboardData = None \"\"\"", "**kwargs): self.detail = None super().__init__(_type, *args, **kwargs) def initCustomEvent(self): pass class GamePadEvent(Event): \"\"\"", "#: TOGGLE = \"toggle\" #: UNLOAD = \"unload\" #: VOLUMECHANGE = \"volumechange\" #:", "\"onUpdateStart\" #: UPDATE_END = \"onUpdateEnd\" #: COMPLETE = \"onComplete\" #: TIMER = \"onTimer\"", "= None pass def msConvertURL(self): pass def preventDefault(self): pass def stopImmediatePropagation(self): pass class", "triggered the mouse event MouseEvent, FocusEvent class KeyboardEvent(Event): \"\"\" keyboard events \"\"\" KEYDOWN", "button(self): return self._button @property def buttons(self): return self._buttons @property def which(self): return self._button", "callback): if _type not in self.listeners: return stack = self.listeners[_type] for thing in", "def __init__(self, _type, *args, **kwargs): self.persisted = None \"\"\" Returns whether the webpage", "*args, **kwargs): self.relatedTarget = None super().__init__(_type, *args, **kwargs) class TouchEvent(Event): \"\"\" TouchEvent \"\"\"", "def onformdata(self, event): print(event) raise NotImplementedError def onmousedown(self, event): print(event) raise NotImplementedError def", "bool) -> None: def addEventListener(self, _type, callback, *args, **kwargs): if _type not in", "self.__init__(_type, args, kwargs) def stopPropagation(self): \"\"\"[prevents further propagation of the current event in", "= modifiersListArg self.repeat = repeat @property def altKey(self): return self._altKey @property def ctrlKey(self):", "START = \"onStart\" #: STOP = \"onStop\" #: RESET = \"onReset\" #: PAUSE", "self._shiftKey @property def metaKey(self): return self._metaKey @property def unicode(self): return self.key # @property", "= _type self.bubbles = None self.cancelable = None self.cancelBubble = None self.composed =", "vertical coordinate of the mouse pointer relative to the position of the edge", "print(event) raise NotImplementedError def onmouseout(self, event): print(event) raise NotImplementedError def onmouseover(self, event): print(event)", "print(event) raise NotImplementedError def ondragover(self, event): print(event) raise NotImplementedError def ondragstart(self, event): print(event)", "pseudo-element of the animation \"\"\" super().__init__(_type, *args, **kwargs) class ClipboardEvent(Event): \"\"\" ClipboardEvent \"\"\"", "None \"\"\" Returns the name of the transition\"\"\" self.elapsedTime = None \"\"\" Returns", "\"\"\" self.oldValue = None \"\"\" Returns the old value of the changed storage", "None self.view = None super().__init__(_type, *args, **kwargs) class CompositionEvent(UIEvent): \"\"\" CompositionEvent \"\"\" START", "\"fullscreenchange\" #: FULLSCREENERROR = \"fullscreenerror\" #: INPUT = \"input\" #: INVALID = \"invalid\"", "not in self.listeners: self.listeners[_type] = [] self.listeners[_type].append(callback) def removeEventListener(self, _type, callback): if _type", "#: TOUCHEND = \"touchend\" #: TOUCHMOVE = \"touchmove\" #: TOUCHSTART = \"touchstart\" #:", "position of the edge of the target element MouseEvent # pageX Returns the", "self.keyCode = None super().__init__(_type, *args, **kwargs) def initKeyboardEvent(self, typeArg, canBubbleArg, cancelableArg, viewArg, charArg,", "def oncancel(self, event): print(event) raise NotImplementedError def oncanplay(self, event): print(event) raise NotImplementedError def", "= 0 self.y = 0 self._clientX = 0 self._clientX = 0 self._altKey =", "the mouse pointer relative to the position of the last mousemove event MouseEvent", "False self._metaKey = False self.charCode = None self.code = None self.key = None", "_type, *args, **kwargs): self.relatedTarget = None super().__init__(_type, *args, **kwargs) class TouchEvent(Event): \"\"\" TouchEvent", "= \"dragover\" #: START = \"dragstart\" #: DROP = \"drop\" #: def __init__(self,", "self.targetTouches = None self.touches = None super().__init__(_type, *args, **kwargs) class WheelEvent(Event): \"\"\" WheelEvent", "\"\"\" ErrorEvent \"\"\" ERROR = \"error\" #: def __init__(self, _type, *args, **kwargs): self.message", "edge of the target element MouseEvent # offsetY Returns the vertical coordinate of", "raise NotImplementedError def onchange(self, event): print(event) raise NotImplementedError def onclick(self, event): print(event) raise", "= \"submit\" #: SUSPEND = \"suspend\" #: TOGGLE = \"toggle\" #: UNLOAD =", "_type not in self.listeners: return stack = self.listeners[_type] for thing in stack: if", "def preventDefault(self): pass def stopImmediatePropagation(self): pass class MouseEvent(Event): \"\"\" mouse events \"\"\" CLICK", "= \"gamepaddisconnected\" #: def __init__(self, _type, *args, **kwargs): self.gamepad = None super().__init__(_type, *args,", "raise NotImplementedError def ondragstart(self, event): print(event) raise NotImplementedError def ondrop(self, event): print(event) raise", "self.addEventListener(ClipboardEvent.CUT, self.oncut) # self.addEventListener(ClipboardEvent.COPY, self.oncopy) # self.addEventListener(ClipboardEvent.PASTE, self.onpaste) def onabort(self, event): print(event) raise", "= None self.deltaMode = None super().__init__(_type, *args, **kwargs) class AnimationEvent(Event): \"\"\" AnimationEvent \"\"\"", "class HashChangeEvent(Event): \"\"\" HashChangeEvent \"\"\" CHANGE = \"hashchange\" #: def __init__(self, _type, *args,", "containing target ranges that will be affected by the insertion/deletion MouseEvent # MovementX", "# self.addEventListener(DragEvent.LEAVE, self.ondragleave) # self.addEventListener(DragEvent.OVER, self.ondragover) # self.addEventListener(DragEvent.START, self.ondragstart) # self.addEventListener(DragEvent.DROP, self.ondrop) #", "\"mouseover\" #: MOUSEOUT = \"mouseout\" #: MOUSEUP = \"mouseup\" #: def __init__(self, _type,", "\"unload\" #: VOLUMECHANGE = \"volumechange\" #: WAITING = \"waiting\" #: # Event(\"look\", {\"bubbles\":true,", "**kwargs) class WheelEvent(Event): \"\"\" WheelEvent \"\"\" MOUSEWHEEL = \"mousewheel\" # DEPRECATED - USE", "self.target = None # self.srcElement = None # self.bubbles = None # self.cancelable", "= None self.touches = None super().__init__(_type, *args, **kwargs) class WheelEvent(Event): \"\"\" WheelEvent \"\"\"", "raise NotImplementedError def onloadstart(self, event): print(event) raise NotImplementedError def onlostpointercapture(self, event): print(event) raise", "self.relatedTarget = relatedTarget # TODO - parse from_json - so can relay @property", "== callback: stack.remove(thing) return def dispatchEvent(self, event): if event.type not in self.listeners: return", "print(event) raise NotImplementedError def ondrag(self, event): print(event) raise NotImplementedError def ondragend(self, event): print(event)", "print(event) raise NotImplementedError def onpointerout(self, event): print(event) raise NotImplementedError def onpointerover(self, event): print(event)", "the document, when the mouse event was triggered MouseEvent # pageY Returns the", "is dragged/dropped \"\"\" super().__init__(_type, *args, **kwargs) class HashChangeEvent(Event): \"\"\" HashChangeEvent \"\"\" CHANGE =", "\"keydown\" #: KEYPRESS = \"keypress\" #: KEYUP = \"keyup\" #: def __init__(self, _type,", "NotImplementedError def onseeked(self, event): print(event) raise NotImplementedError def onseeking(self, event): print(event) raise NotImplementedError", "print(event) raise NotImplementedError def onlostpointercapture(self, event): print(event) raise NotImplementedError def onmouseenter(self, event): print(event)", "ANIMATIONITERATION = \"animationiteration\" #: ANIMATIONSTART = \"animationstart\" #: def __init__(self, _type, *args, **kwargs):", "class BeforeUnloadEvent(Event): BEFOREUNLOAD = \"beforeunload\" #: \"\"\" BeforeUnloadEvent \"\"\" def __init__(self, _type, *args,", "**kwargs): self.key = None \"\"\" Returns the key of the changed storage item", "= \"load\" #: LOADEDDATA = \"loadeddata\" #: LOADEDMETADATA = \"loadedmetadata\" #: MESSAGE =", "Returns the location of a key on the keyboard or device KeyboardEvent class", "self.deltaY = None self.deltaZ = None self.deltaMode = None super().__init__(_type, *args, **kwargs) class", "str, function, useCapture: bool # def addEventListener(self, event: str, function, useCapture: bool) ->", "\"\"\" Returns the data that is dragged/dropped \"\"\" super().__init__(_type, *args, **kwargs) class HashChangeEvent(Event):", "super().__init__(_type, *args, **kwargs) def initKeyboardEvent(self, typeArg, canBubbleArg, cancelableArg, viewArg, charArg, keyArg, locationArg, modifiersListArg,", "\"drag\" #: END = \"dragend\" #: ENTER = \"dragenter\" #: EXIT = \"dragexit\"", "return self._altKey @property def ctrlKey(self): return self._ctrlKey @property def shiftKey(self): return self._shiftKey @property", "\"\"\" FocusEvent \"\"\" BLUR = \"blur\" #: FOCUS = \"focus\" #: FOCUSIN =", "the change (i.e \"inserting\" or \"deleting\") \"\"\" self.isComposing \"\"\" Returns whether the state", "\"\"\" Returns an object containing a copy of the history entries \"\"\" super().__init__(_type,", "\"change\" #: DURATIONCHANGE = \"durationchange\" #: ENDED = \"ended\" #: ERROR = \"error\"", "# MovementX Returns the horizontal coordinate of the mouse pointer relative to the", "the changed storage item \"\"\" self.newValue = None \"\"\" Returns the new value", "#: def __init__(self, _type, *args, **kwargs): self.pointerId = None self.width = None self.height", "of the changed item's document \"\"\" super().__init__(_type, *args, **kwargs) class TransitionEvent(Event): \"\"\" TransitionEvent", "**kwargs): self.data = None #: Returns the characters generated by the input method", "*args, **kwargs) class AnimationEvent(Event): \"\"\" AnimationEvent \"\"\" ANIMATIONEND = \"animationend\" #: ANIMATIONITERATION =", "or not KeyboardEvent # location Returns the location of a key on the", "name of the pseudo-element of the animation \"\"\" super().__init__(_type, *args, **kwargs) class ClipboardEvent(Event):", "CHANGE = \"hashchange\" #: def __init__(self, _type, *args, **kwargs): self.newURL = None self.oldURL", "self.ondragstart) # self.addEventListener(DragEvent.DROP, self.ondrop) # self.addEventListener(ClipboardEvent.CUT, self.oncut) # self.addEventListener(ClipboardEvent.COPY, self.oncopy) # self.addEventListener(ClipboardEvent.PASTE, self.onpaste)", "# def keyCode(self): # return self.keyCode # @property # def charCode(self): # return", "NotImplementedError def ondragexit(self, event): print(event) raise NotImplementedError def ondragleave(self, event): print(event) raise NotImplementedError", "TODO - parse from_json - so can relay @property def clientX(self): return self.x", "TOUCHSTART = \"touchstart\" #: def __init__(self, _type, *args, **kwargs): self.shiftKey = None self.altKey", "NotImplementedError def onresize(self, event): print(event) raise NotImplementedError def onscroll(self, event): print(event) raise NotImplementedError", "START = \"compositionstart\" END = \"compositionend\" UPDATE = \"compositionupdate\" def __init__(self, _type, *args,", "self.persisted = None \"\"\" Returns whether the webpage was cached by the browser", "print(event) raise NotImplementedError def onstalled(self, event): print(event) raise NotImplementedError def onsubmit(self, event): print(event)", "initCustomEvent(self): pass class GamePadEvent(Event): \"\"\" GamePadEvent \"\"\" START = \"gamepadconnected\" #: STOP =", "class StorageEvent(Event): \"\"\" StorageEvent \"\"\" def __init__(self, _type, *args, **kwargs): self.key = None", "def __init__(self, _type, *args, **kwargs): self.message = None # self.filename=None # self.lineno=0 #", "preventDefault(self): pass def stopImmediatePropagation(self): pass class MouseEvent(Event): \"\"\" mouse events \"\"\" CLICK =", "event): if event.type not in self.listeners: return True # huh?. surely false? stack", "= None \"\"\" Returns the data that is dragged/dropped \"\"\" super().__init__(_type, *args, **kwargs)", "\"abort\" #: AFTERPRINT = \"afterprint\" #: BEFOREPRINT = \"beforeprint\" #: BEFOREUNLOAD = \"beforeunload\"", "return self._buttons @property def which(self): return self._button # MOUSE_EVENT # getModifierState() Returns an", "RATECHANGE = \"ratechange\" #: RESIZE = \"resize\" #: RESET = \"reset\" #: SCROLL", "cancelable=False): # super.__init__(self, type, bubbles, cancelable) super().__init__(_type) # TODO - self.source = source", "the vertical coordinate of the mouse pointer relative to the position of the", "def onmouseenter(self, event): print(event) raise NotImplementedError def onmouseleave(self, event): print(event) raise NotImplementedError def", "NotImplementedError def ondragenter(self, event): print(event) raise NotImplementedError def ondragexit(self, event): print(event) raise NotImplementedError", "DragEvent(Event): \"\"\" DragEvent \"\"\" DRAG = \"drag\" #: END = \"dragend\" #: ENTER", "HashChangeEvent(Event): \"\"\" HashChangeEvent \"\"\" CHANGE = \"hashchange\" #: def __init__(self, _type, *args, **kwargs):", "print(event) raise NotImplementedError def onclose(self, event): print(event) raise NotImplementedError def oncontextmenu(self, event): print(event)", "print(event) raise NotImplementedError def ondblclick(self, event): print(event) raise NotImplementedError def ondrag(self, event): print(event)", "self.addEventListener(DragEvent.DRAG, self.ondrag) # self.addEventListener(DragEvent.END, self.ondragend) # self.addEventListener(DragEvent.ENTER, self.ondragenter) # self.addEventListener(DragEvent.EXIT, self.ondragexit) # self.addEventListener(DragEvent.LEAVE,", "\"\"\" super().__init__(_type, *args, **kwargs) class HashChangeEvent(Event): \"\"\" HashChangeEvent \"\"\" CHANGE = \"hashchange\" #:", "print(event) raise NotImplementedError def ondragend(self, event): print(event) raise NotImplementedError def ondragenter(self, event): print(event)", "repeat Returns whether a key is being hold down repeatedly, or not KeyboardEvent", "object containing information about the inserted/deleted data \"\"\" self.getTargetRanges \"\"\" Returns an array", "raise NotImplementedError def onwaiting(self, event): print(event) raise NotImplementedError def onwheel(self, event): print(event) raise", "raise NotImplementedError def onplaying(self, event): print(event) raise NotImplementedError def onpointercancel(self, event): print(event) raise", "print(event) raise NotImplementedError def ondragenter(self, event): print(event) raise NotImplementedError def ondragexit(self, event): print(event)", "**kwargs) class TransitionEvent(Event): \"\"\" TransitionEvent \"\"\" TRANSITIONEND = \"transitionend\" #: def __init__(self, _type,", "\"online\" #: OPEN = \"open\" #: PAUSE = \"pause\" #: PLAY = \"play\"", "\"\"\" START = \"compositionstart\" END = \"compositionend\" UPDATE = \"compositionupdate\" def __init__(self, _type,", "\"\"\" def __init__(self, _type, *args, **kwargs): self.detail = None super().__init__(_type, *args, **kwargs) def", "def onemptied(self, event): print(event) raise NotImplementedError def onended(self, event): print(event) raise NotImplementedError def", "onscroll(self, event): print(event) raise NotImplementedError def onseeked(self, event): print(event) raise NotImplementedError def onseeking(self,", "#: RATECHANGE = \"ratechange\" #: RESIZE = \"resize\" #: RESET = \"reset\" #:", "CustomEvent \"\"\" def __init__(self, _type, *args, **kwargs): self.detail = None super().__init__(_type, *args, **kwargs)", "= None super().__init__(_type, *args, **kwargs) class AnimationEvent(Event): \"\"\" AnimationEvent \"\"\" ANIMATIONEND = \"animationend\"", "self._type = _type self.canBubble = canBubble self.cancelable = cancelable self.view = view self.detail", "generated by the input method that raised the event self.locale = None super().__init__(_type,", "the mouse pointer, relative to the document, when the mouse event was triggered", "a copy of the history entries \"\"\" super().__init__(_type, *args, **kwargs) class StorageEvent(Event): \"\"\"", "key on the keyboard or device KeyboardEvent class UIEvent(Event): \"\"\" UIEvent \"\"\" def", "# type(thing, (Event,), self) except Exception as e: print(e) thing() # try calling", "# return self.key # def isComposing(self, *args, **kwargs): # pass # KeyboardEvent #", "\"\"\" ANIMATIONEND = \"animationend\" #: ANIMATIONITERATION = \"animationiteration\" #: ANIMATIONSTART = \"animationstart\" #:", "COPY = \"copy\" #: CUT = \"cut\" #: PASTE = \"paste\" #: def", "\"\"\" def __init__(self, _type, *args, **kwargs): self.state = None \"\"\" Returns an object", "= False self._ctrlKey = False self._shiftKey = False self._metaKey = False self._button =", "#: SEARCH = \"search\" #: SEEKED = \"seeked\" #: SEEKING = \"seeking\" #:", "so can relay @property def clientX(self): return self.x @property def clientY(self): return self.y", "= None \"\"\" Returns whether the webpage was cached by the browser \"\"\"", "PLAY = \"play\" #: PLAYING = \"playing\" #: PROGRESS = \"progress\" #: RATECHANGE", "print(event) raise NotImplementedError def onfocus(self, event): print(event) raise NotImplementedError def ongotpointercapture(self, event): print(event)", "#: SEEKED = \"seeked\" #: SEEKING = \"seeking\" #: SELECT = \"select\" #:", "PointerEvent \"\"\" POINTER = \"pointer\" #: def __init__(self, _type, *args, **kwargs): self.pointerId =", "the transition \"\"\" super().__init__(_type, *args, **kwargs) class ProgressEvent(Event): \"\"\" ProgressEvent \"\"\" LOADSTART =", "def shiftKey(self): return self._shiftKey @property def metaKey(self): return self._metaKey @property def unicode(self): return", "= \"durationchange\" #: ENDED = \"ended\" #: ERROR = \"error\" #: FULLSCREENCHANGE =", "raised the event self.locale = None super().__init__(_type, *args, **kwargs) class FocusEvent(Event): \"\"\" FocusEvent", "print(event) raise NotImplementedError def onresize(self, event): print(event) raise NotImplementedError def onscroll(self, event): print(event)", "event): print(event) raise NotImplementedError def onlostpointercapture(self, event): print(event) raise NotImplementedError def onmouseenter(self, event):", "source(self): return self._source @source.setter def source(self, source): self._source = source def __init__(self, _type,", "# from typing import * import time # TODO - bring EventTarget here", "= None # self.eventPhase = None # self.isTrusted = None # self.returnValue =", "of seconds a transition has been running \"\"\" self.pseudoElement = None \"\"\" Returns", "# self.kwargs = kwargs self._altKey = False self._ctrlKey = False self._shiftKey = False", "self.listeners[_type] = [] self.listeners[_type].append(callback) def removeEventListener(self, _type, callback): if _type not in self.listeners:", "= None self.target = None # ms = time.time_ns() // 1000000 3.7 up", "self.state = None \"\"\" Returns an object containing a copy of the history", "event): print(event) raise NotImplementedError def onmouseout(self, event): print(event) raise NotImplementedError def onmouseover(self, event):", "None self.tangentialPressure = None self.tiltX = None self.tiltY = None self.twist = None", "#: WHEEL = \"wheel\" #: def __init__(self, _type, *args, **kwargs): self.deltaX = None", "raise NotImplementedError def onpointerout(self, event): print(event) raise NotImplementedError def onpointerover(self, event): print(event) raise", "#: SEEKING = \"seeking\" #: SELECT = \"select\" #: SHOW = \"show\" #:", "# self.addEventListener(KeyboardEvent.KEYDOWN, self.onkeydown) # self.addEventListener(KeyboardEvent.KEYUP, self.onkeyup) # self.addEventListener(MouseEvent.MOUSEMOVE, self.onmousemove) # self.addEventListener(MouseEvent.MOUSEDOWN, self.onmousedown) #", "= False self.eventPhase = None self.explicitOriginalTarget = None self.isTrusted = None self.originalTarget =", "*args, **kwargs): self.deltaX = None self.deltaY = None self.deltaZ = None self.deltaMode =", "\"\"\" domonic.events ==================================== dom events \"\"\" # from typing import * import time", "def __init__(self, _type, *args, **kwargs): super().__init__(_type, *args, **kwargs) class TimerEvent(Event): TIMER = \"timer\"", "CLICK = \"click\" #: CONTEXTMENU = \"contextmenu\" #: DBLCLICK = \"dblclick\" #: MOUSEDOWN", "self.deltaZ = None self.deltaMode = None super().__init__(_type, *args, **kwargs) class AnimationEvent(Event): \"\"\" AnimationEvent", "ondragexit(self, event): print(event) raise NotImplementedError def ondragleave(self, event): print(event) raise NotImplementedError def ondragover(self,", "#: UPDATE_START = \"onUpdateStart\" #: UPDATE_END = \"onUpdateEnd\" #: COMPLETE = \"onComplete\" #:", "event): print(event) raise NotImplementedError def onpointerout(self, event): print(event) raise NotImplementedError def onpointerover(self, event):", "\"\"\" Returns an object containing information about the inserted/deleted data \"\"\" self.getTargetRanges \"\"\"", "= None self.isPrimary = None super().__init__(_type, *args, **kwargs) class BeforeUnloadEvent(Event): BEFOREUNLOAD = \"beforeunload\"", "PAGESHOW = \"pageshow\" #: def __init__(self, _type, *args, **kwargs): self.persisted = None \"\"\"", "#: STALLED = \"stalled\" #: SUBMIT = \"submit\" #: SUSPEND = \"suspend\" #:", "entries \"\"\" super().__init__(_type, *args, **kwargs) class StorageEvent(Event): \"\"\" StorageEvent \"\"\" def __init__(self, _type,", "= \"submit\" #: def __init__(self, _type, *args, **kwargs): super().__init__(_type, *args, **kwargs) class PointerEvent(Event):", "def metaKey(self): return self._metaKey @property def button(self): return self._button @property def buttons(self): return", "None # self.currentTarget = None # self.eventPhase = None # self.isTrusted = None", "**kwargs) class TouchEvent(Event): \"\"\" TouchEvent \"\"\" TOUCHCANCEL = \"touchcancel\" #: TOUCHEND = \"touchend\"", "self.cancelBubble = None self.composed = None self.currentTarget = None self.defaultPrevented = False self.eventPhase", "target ranges that will be affected by the insertion/deletion \"\"\" self.inputType \"\"\" Returns", "event): print(event) raise NotImplementedError def onkeydown(self, event): print(event) raise NotImplementedError def onkeypress(self, event):", "= \"dragleave\" #: OVER = \"dragover\" #: START = \"dragstart\" #: DROP =", "it for thing in stack: try: thing(event) # type(thing, (Event,), self) except Exception", "= \"ratechange\" #: RESIZE = \"resize\" #: RESET = \"reset\" #: SCROLL =", "insertion/deletion MouseEvent # MovementX Returns the horizontal coordinate of the mouse pointer relative", "self.locationArg = locationArg self.modifiersListArg = modifiersListArg self.repeat = repeat @property def altKey(self): return", "**kwargs): super().__init__(_type, *args, **kwargs) class PointerEvent(Event): \"\"\" PointerEvent \"\"\" POINTER = \"pointer\" #:", "\"animationiteration\" #: ANIMATIONSTART = \"animationstart\" #: def __init__(self, _type, *args, **kwargs): self.animationName =", "= \"play\" #: PLAYING = \"playing\" #: PROGRESS = \"progress\" #: RATECHANGE =", "print(event) raise NotImplementedError def onwheel(self, event): print(event) raise NotImplementedError def onanimationcancel(self, event): print(event)", "\"\"\" super().__init__(_type, *args, **kwargs) class PopStateEvent(Event): \"\"\" PopStateEvent \"\"\" def __init__(self, _type, *args,", "MouseEvent # relatedTarget Returns the element related to the element that triggered the", "self.x = 0 self.y = 0 self._clientX = 0 self._clientX = 0 self._altKey", "MOUSEWHEEL = \"mousewheel\" # DEPRECATED - USE WHEEL #: WHEEL = \"wheel\" #:", "onerror(self, event): print(event) raise NotImplementedError def onfocus(self, event): print(event) raise NotImplementedError def ongotpointercapture(self,", "FocusEvent \"\"\" BLUR = \"blur\" #: FOCUS = \"focus\" #: FOCUSIN = \"focusin\"", "__init__(self, _type, *args, **kwargs): self.newURL = None self.oldURL = None super().__init__(_type, *args, **kwargs)", "ondurationchange(self, event): print(event) raise NotImplementedError def onemptied(self, event): print(event) raise NotImplementedError def onended(self,", "InputEvent(Event): \"\"\" InputEvent \"\"\" def __init__(self, _type, *args, **kwargs): self.data = None \"\"\"", "#: TOUCHMOVE = \"touchmove\" #: TOUCHSTART = \"touchstart\" #: def __init__(self, _type, *args,", "# print('initMouseEvent') self._type = _type self.canBubble = canBubble self.cancelable = cancelable self.view =", "= \"hashchange\" #: def __init__(self, _type, *args, **kwargs): self.newURL = None self.oldURL =", "None self.isPrimary = None super().__init__(_type, *args, **kwargs) class BeforeUnloadEvent(Event): BEFOREUNLOAD = \"beforeunload\" #:", "def onanimationcancel(self, event): print(event) raise NotImplementedError def onanimationend(self, event): print(event) raise NotImplementedError def", "the edge of the target element MouseEvent # pageX Returns the horizontal coordinate", "return self._ctrlKey @property def shiftKey(self): return self._shiftKey @property def metaKey(self): return self._metaKey @property", "print(event) raise NotImplementedError def ondragleave(self, event): print(event) raise NotImplementedError def ondragover(self, event): print(event)", "RESET = \"onReset\" #: PAUSE = \"onPause\" #: UNPAUSE = \"onUnPause\" #: UPDATE_START", "kwargs self.x = 0 self.y = 0 self._clientX = 0 self._clientX = 0", "**kwargs): # pass # KeyboardEvent # isComposing Returns whether the state of the", "initEvent(self, _type=None, *args, **kwargs): self.__init__(_type, args, kwargs) def stopPropagation(self): \"\"\"[prevents further propagation of", "PROGRESS = \"progress\" #: RATECHANGE = \"ratechange\" #: RESIZE = \"resize\" #: RESET", "raise NotImplementedError def onemptied(self, event): print(event) raise NotImplementedError def onended(self, event): print(event) raise", "the document, when the mouse event was triggered MouseEvent # region MouseEvent #", "NotImplementedError def oncuechange(self, event): print(event) raise NotImplementedError def ondblclick(self, event): print(event) raise NotImplementedError", "def onblur(self, event): print(event) raise NotImplementedError def oncancel(self, event): print(event) raise NotImplementedError def", "raise NotImplementedError def onselectionchange(self, event): print(event) raise NotImplementedError def onselectstart(self, event): print(event) raise", "def ontimeupdate(self, event): print(event) raise NotImplementedError def onvolumechange(self, event): print(event) raise NotImplementedError def", "# self.target = None # self.srcElement = None # self.bubbles = None #", "= keyArg self.locationArg = locationArg self.modifiersListArg = modifiersListArg self.repeat = repeat @property def", "altKey(self): return self._altKey @property def ctrlKey(self): return self._ctrlKey @property def shiftKey(self): return self._shiftKey", "print(event) raise NotImplementedError def onmouseleave(self, event): print(event) raise NotImplementedError def onmousemove(self, event): print(event)", "class CompositionEvent(UIEvent): \"\"\" CompositionEvent \"\"\" START = \"compositionstart\" END = \"compositionend\" UPDATE =", "\"\"\" event \"\"\" EMPTIED = \"emptied\" #: ABORT = \"abort\" #: AFTERPRINT =", "USE WHEEL #: WHEEL = \"wheel\" #: def __init__(self, _type, *args, **kwargs): self.deltaX", "the keyboard or device KeyboardEvent class UIEvent(Event): \"\"\" UIEvent \"\"\" def __init__(self, _type,", "raise NotImplementedError def onended(self, event): print(event) raise NotImplementedError def onerror(self, event): print(event) raise", "# .slice() event.target = self # TODO/NOTE - is this correct? - cant", "# self.kwargs = kwargs self.x = 0 self.y = 0 self._clientX = 0", "None self.key = None self.keyCode = None super().__init__(_type, *args, **kwargs) def initKeyboardEvent(self, typeArg,", "event): print(event) raise NotImplementedError def onkeyup(self, event): print(event) raise NotImplementedError def onload(self, event):", "the data that is dragged/dropped \"\"\" super().__init__(_type, *args, **kwargs) class HashChangeEvent(Event): \"\"\" HashChangeEvent", "\"onReset\" #: PAUSE = \"onPause\" #: UNPAUSE = \"onUnPause\" #: UPDATE_START = \"onUpdateStart\"", "print(event) raise NotImplementedError def onemptied(self, event): print(event) raise NotImplementedError def onended(self, event): print(event)", "an object representing the affected storage object \"\"\" self.url = None \"\"\" Returns", "NotImplementedError def onwheel(self, event): print(event) raise NotImplementedError def onanimationcancel(self, event): print(event) raise NotImplementedError", "def ondrop(self, event): print(event) raise NotImplementedError def ondurationchange(self, event): print(event) raise NotImplementedError def", "#: MOUSEENTER = \"mouseenter\" #: MOUSELEAVE = \"mouseleave\" #: MOUSEMOVE = \"mousemove\" #:", "@property def shiftKey(self): return self._shiftKey @property def metaKey(self): return self._metaKey @property def unicode(self):", "\"inserting\" or \"deleting\") \"\"\" self.isComposing \"\"\" Returns whether the state of the event", "DragEvent \"\"\" DRAG = \"drag\" #: END = \"dragend\" #: ENTER = \"dragenter\"", "\"\"\" self.getTargetRanges \"\"\" Returns an array containing target ranges that will be affected", "\"\"\" self.isComposing \"\"\" Returns whether the state of the event is composing or", "raise NotImplementedError def onreset(self, event): print(event) raise NotImplementedError def onresize(self, event): print(event) raise", "# self.args = args # self.kwargs = kwargs self._altKey = False self._ctrlKey =", "#: STOP = \"onStop\" #: RESET = \"onReset\" #: PAUSE = \"onPause\" #:", "= 0 self._clientX = 0 self._altKey = False self._ctrlKey = False self._shiftKey =", "__init__(self, _type, *args, **kwargs): super().__init__(_type, *args, **kwargs) class DragEvent(Event): \"\"\" DragEvent \"\"\" DRAG", "event): print(event) raise NotImplementedError def onprogress(self, event): print(event) raise NotImplementedError def onratechange(self, event):", "an array containing target ranges that will be affected by the insertion/deletion MouseEvent", "\"gamepadconnected\" #: STOP = \"gamepaddisconnected\" #: def __init__(self, _type, *args, **kwargs): self.gamepad =", "raise NotImplementedError def onmouseover(self, event): print(event) raise NotImplementedError def onmouseup(self, event): print(event) raise", "raise NotImplementedError def onseeking(self, event): print(event) raise NotImplementedError def onselect(self, event): print(event) raise", "print(event) raise NotImplementedError def onanimationiteration(self, event): print(event) raise NotImplementedError def onauxclick(self, event): print(event)", "__init__(self, _type, *args, **kwargs): self.shiftKey = None self.altKey = None self.changedTouches = None", "event): print(event) raise NotImplementedError def onkeypress(self, event): print(event) raise NotImplementedError def onkeyup(self, event):", "event): print(event) raise NotImplementedError def onseeking(self, event): print(event) raise NotImplementedError def onselect(self, event):", "super().__init__(_type, *args, **kwargs) class AnimationEvent(Event): \"\"\" AnimationEvent \"\"\" ANIMATIONEND = \"animationend\" #: ANIMATIONITERATION", "def onended(self, event): print(event) raise NotImplementedError def onerror(self, event): print(event) raise NotImplementedError def", "dom events \"\"\" # from typing import * import time # TODO -", "storage item \"\"\" self.storageArea = None \"\"\" Returns an object representing the affected", "# self.addEventListener(DragEvent.DRAG, self.ondrag) # self.addEventListener(DragEvent.END, self.ondragend) # self.addEventListener(DragEvent.ENTER, self.ondragenter) # self.addEventListener(DragEvent.EXIT, self.ondragexit) #", "CompositionEvent \"\"\" START = \"compositionstart\" END = \"compositionend\" UPDATE = \"compositionupdate\" def __init__(self,", "#: def __init__(self, _type, *args, **kwargs): self.dataTransfer = None \"\"\" Returns the data", "of the transition\"\"\" self.elapsedTime = None \"\"\" Returns the number of seconds a", "event): print(event) raise NotImplementedError def onpointerleave(self, event): print(event) raise NotImplementedError def onpointermove(self, event):", "= \"mousewheel\" # DEPRECATED - USE WHEEL #: WHEEL = \"wheel\" #: def", "new value of the changed storage item \"\"\" self.oldValue = None \"\"\" Returns", "__init__(self, _type, *args, **kwargs): self.dataTransfer = None \"\"\" Returns the data that is", "*args, **kwargs) class StorageEvent(Event): \"\"\" StorageEvent \"\"\" def __init__(self, _type, *args, **kwargs): self.key", "None \"\"\" Returns the name of the pseudo-element of the animation \"\"\" super().__init__(_type,", "self.y @property def altKey(self): return self._altKey @property def ctrlKey(self): return self._ctrlKey @property def", "self.keyCode # @property # def charCode(self): # return self.charCode # @property # def", "onseeked(self, event): print(event) raise NotImplementedError def onseeking(self, event): print(event) raise NotImplementedError def onselect(self,", "\"scroll\" #: SEARCH = \"search\" #: SEEKED = \"seeked\" #: SEEKING = \"seeking\"", "def __init__(self, _type, *args, **kwargs): self.shiftKey = None self.altKey = None self.changedTouches =", "the name of the pseudo-element of the animation \"\"\" super().__init__(_type, *args, **kwargs) class", "# return self.keyCode # @property # def charCode(self): # return self.charCode # @property", "= None self.isTrusted = None self.originalTarget = None self.returnValue = None self.srcElement =", "= \"progress\" #: RATECHANGE = \"ratechange\" #: RESIZE = \"resize\" #: RESET =", "= False self._shiftKey = False self._metaKey = False self._button = None self._buttons =", "NotImplementedError def ontouchcancel(self, event): print(event) raise NotImplementedError def ontouchstart(self, event): print(event) raise NotImplementedError", "insertion/deletion \"\"\" self.inputType \"\"\" Returns the type of the change (i.e \"inserting\" or", "or device KeyboardEvent class UIEvent(Event): \"\"\" UIEvent \"\"\" def __init__(self, _type, *args, **kwargs):", "screenX self.screenY = screenY self._clientX = clientX self._clientY = clientY self._ctrlKey = ctrlKey", "the event is composing or not InputEvent, KeyboardEvent # repeat Returns whether a", "raise NotImplementedError def ondragend(self, event): print(event) raise NotImplementedError def ondragenter(self, event): print(event) raise", "print(event) raise NotImplementedError def ondrop(self, event): print(event) raise NotImplementedError def ondurationchange(self, event): print(event)", "None self.ctrlKey = None self.metaKey = None self.shiftKey = None self.targetTouches = None", "None \"\"\" Returns the key of the changed storage item \"\"\" self.newValue =", "print(event) raise NotImplementedError def onkeypress(self, event): print(event) raise NotImplementedError def onkeyup(self, event): print(event)", "self._metaKey = False self.charCode = None self.code = None self.key = None self.keyCode", "thing(event) # type(thing, (Event,), self) except Exception as e: print(e) thing() # try", "self.data = None #: Returns the characters generated by the input method that", "class KeyboardEvent(Event): \"\"\" keyboard events \"\"\" KEYDOWN = \"keydown\" #: KEYPRESS = \"keypress\"", "source): self._source = source def __init__(self, _type, source=None, bubbles=False, cancelable=False): # super.__init__(self, type,", "def onpointermove(self, event): print(event) raise NotImplementedError def onpointerout(self, event): print(event) raise NotImplementedError def", "event): print(event) raise NotImplementedError def onclick(self, event): print(event) raise NotImplementedError def onclose(self, event):", "event): print(event) raise NotImplementedError def onpointerenter(self, event): print(event) raise NotImplementedError def onpointerleave(self, event):", "*args, **kwargs) class CustomEvent(Event): \"\"\" CustomEvent \"\"\" def __init__(self, _type, *args, **kwargs): self.detail", "print(event) raise NotImplementedError def ontransitioncancel(self, event): print(event) raise NotImplementedError def ontransitionend(self, event): print(event)", "# region MouseEvent # relatedTarget Returns the element related to the element that", "oncanplay(self, event): print(event) raise NotImplementedError def oncanplaythrough(self, event): print(event) raise NotImplementedError def onchange(self,", "= None self.keyCode = None super().__init__(_type, *args, **kwargs) def initKeyboardEvent(self, typeArg, canBubbleArg, cancelableArg,", "self.ondragleave) # self.addEventListener(DragEvent.OVER, self.ondragover) # self.addEventListener(DragEvent.START, self.ondragstart) # self.addEventListener(DragEvent.DROP, self.ondrop) # self.addEventListener(ClipboardEvent.CUT, self.oncut)", "event.defaultPrevented class Event(object): \"\"\" event \"\"\" EMPTIED = \"emptied\" #: ABORT = \"abort\"", "def onselect(self, event): print(event) raise NotImplementedError def onselectionchange(self, event): print(event) raise NotImplementedError def", "self.pointerId = None self.width = None self.height = None self.pressure = None self.tangentialPressure", "self.defaultPrevented = True # self.returnValue = None # self.originalTarget = None # self.explicitOriginalTarget", "self.addEventListener(MouseEvent.MOUSEMOVE, self.onmousemove) # self.addEventListener(MouseEvent.MOUSEDOWN, self.onmousedown) # self.addEventListener(MouseEvent.MOUSEUP, self.onmouseup) # self.addEventListener(DragEvent.DRAG, self.ondrag) # self.addEventListener(DragEvent.END,", "#: KEYUP = \"keyup\" #: def __init__(self, _type, *args, **kwargs): # self.args =", "None self.currentTarget = None self.defaultPrevented = False self.eventPhase = None self.explicitOriginalTarget = None", "*args, **kwargs) class TweenEvent(Event): \"\"\" TweenEvent \"\"\" START = \"onStart\" #: STOP =", "self.addEventListener(MouseEvent.MOUSEUP, self.onmouseup) # self.addEventListener(DragEvent.DRAG, self.ondrag) # self.addEventListener(DragEvent.END, self.ondragend) # self.addEventListener(DragEvent.ENTER, self.ondragenter) # self.addEventListener(DragEvent.EXIT,", "super().__init__(_type, *args, **kwargs) class CompositionEvent(UIEvent): \"\"\" CompositionEvent \"\"\" START = \"compositionstart\" END =", "by the insertion/deletion \"\"\" self.inputType \"\"\" Returns the type of the change (i.e", "EventTarget here and get rid of this one? class EventDispatcher(object): \"\"\" EventDispatcher is", "self.charCode = None self.code = None self.key = None self.keyCode = None super().__init__(_type,", "UIEvent(Event): \"\"\" UIEvent \"\"\" def __init__(self, _type, *args, **kwargs): self.detail = None self.view", "is composing or not \"\"\" super().__init__(_type, *args, **kwargs) class PageTransitionEvent(Event): \"\"\" PageTransitionEvent \"\"\"", "an object containing a copy of the history entries \"\"\" super().__init__(_type, *args, **kwargs)", "oncuechange(self, event): print(event) raise NotImplementedError def ondblclick(self, event): print(event) raise NotImplementedError def ondrag(self,", "NotImplementedError def onclick(self, event): print(event) raise NotImplementedError def onclose(self, event): print(event) raise NotImplementedError", "event): print(event) raise NotImplementedError def onshow(self, event): print(event) raise NotImplementedError def onstalled(self, event):", "self._buttons @property def which(self): return self._button # MOUSE_EVENT # getModifierState() Returns an array", "event): print(event) raise NotImplementedError def onblur(self, event): print(event) raise NotImplementedError def oncancel(self, event):", "event): print(event) raise NotImplementedError def onplaying(self, event): print(event) raise NotImplementedError def onpointercancel(self, event):", "event): print(event) raise NotImplementedError def oninvalid(self, event): print(event) raise NotImplementedError def onkeydown(self, event):", "= \"copy\" #: CUT = \"cut\" #: PASTE = \"paste\" #: def __init__(self,", "= None self.key = None self.keyCode = None super().__init__(_type, *args, **kwargs) def initKeyboardEvent(self,", "*args, **kwargs): super().__init__(_type, *args, **kwargs) class PointerEvent(Event): \"\"\" PointerEvent \"\"\" POINTER = \"pointer\"", "print(event) raise NotImplementedError def onscroll(self, event): print(event) raise NotImplementedError def onseeked(self, event): print(event)", "onanimationcancel(self, event): print(event) raise NotImplementedError def onanimationend(self, event): print(event) raise NotImplementedError def onanimationiteration(self,", "the state of the event is composing or not \"\"\" super().__init__(_type, *args, **kwargs)", "None self.originalTarget = None self.returnValue = None self.srcElement = None self.target = None", "None # self.explicitOriginalTarget = None # self.target = None # self.srcElement = None", "# def code(self): # return self.code # @property # def key(self): # return", "keyArg, locationArg, modifiersListArg, repeat): self._type = typeArg self.canBubbleArg = canBubbleArg self.cancelableArg = cancelableArg", "#: def __init__(self, _type, *args, **kwargs): self.propertyName = None \"\"\" Returns the name", "def initCustomEvent(self): pass class GamePadEvent(Event): \"\"\" GamePadEvent \"\"\" START = \"gamepadconnected\" #: STOP", "_type, *args, **kwargs): super().__init__(_type, *args, **kwargs) class TimerEvent(Event): TIMER = \"timer\" #: \"\"\"", "_type, *args, **kwargs): # self.args = args # self.kwargs = kwargs self._altKey =", "_type, source=None, bubbles=False, cancelable=False): # super.__init__(self, type, bubbles, cancelable) super().__init__(_type) # TODO -", "def onscroll(self, event): print(event) raise NotImplementedError def onseeked(self, event): print(event) raise NotImplementedError def", "CONTEXTMENU = \"contextmenu\" #: DBLCLICK = \"dblclick\" #: MOUSEDOWN = \"mousedown\" #: MOUSEENTER", "return self.x @property def clientY(self): return self.y @property def altKey(self): return self._altKey @property", "UNPAUSE = \"onUnPause\" #: UPDATE_START = \"onUpdateStart\" #: UPDATE_END = \"onUpdateEnd\" #: COMPLETE", "class Event(object): \"\"\" event \"\"\" EMPTIED = \"emptied\" #: ABORT = \"abort\" #:", "= None # self.timeStamp = int(round(time.time() * 1000)) # self.type = None pass", "= self # TODO/NOTE - is this correct? - cant think where else", "callback: stack.remove(thing) return def dispatchEvent(self, event): if event.type not in self.listeners: return True", "self.type = None pass def msConvertURL(self): pass def preventDefault(self): pass def stopImmediatePropagation(self): pass", "= \"onTimer\" #: _source = None @property def source(self): return self._source @source.setter def", "# self.addEventListener(MouseEvent.MOUSEDOWN, self.onmousedown) # self.addEventListener(MouseEvent.MOUSEUP, self.onmouseup) # self.addEventListener(DragEvent.DRAG, self.ondrag) # self.addEventListener(DragEvent.END, self.ondragend) #", "\"\"\" AnimationEvent \"\"\" ANIMATIONEND = \"animationend\" #: ANIMATIONITERATION = \"animationiteration\" #: ANIMATIONSTART =", "UNLOAD = \"unload\" #: VOLUMECHANGE = \"volumechange\" #: WAITING = \"waiting\" #: #", "dispatchEvent(self, event): if event.type not in self.listeners: return True # huh?. surely false?", "raise NotImplementedError def onlostpointercapture(self, event): print(event) raise NotImplementedError def onmouseenter(self, event): print(event) raise", "\"\"\" super().__init__(_type, *args, **kwargs) class ProgressEvent(Event): \"\"\" ProgressEvent \"\"\" LOADSTART = \"loadstart\" #:", "print(event) raise NotImplementedError def onanimationcancel(self, event): print(event) raise NotImplementedError def onanimationend(self, event): print(event)", "metaKey=False, button=None, relatedTarget=None, from_json={}, *args, **kwargs): # print('initMouseEvent') self._type = _type self.canBubble =", "onpointermove(self, event): print(event) raise NotImplementedError def onpointerout(self, event): print(event) raise NotImplementedError def onpointerover(self,", "DURATIONCHANGE = \"durationchange\" #: ENDED = \"ended\" #: ERROR = \"error\" #: FULLSCREENCHANGE", "None self.touches = None super().__init__(_type, *args, **kwargs) class WheelEvent(Event): \"\"\" WheelEvent \"\"\" MOUSEWHEEL", "_type, *args, **kwargs): self.detail = None super().__init__(_type, *args, **kwargs) def initCustomEvent(self): pass class", "= \"change\" #: DURATIONCHANGE = \"durationchange\" #: ENDED = \"ended\" #: ERROR =", "#: SUBMIT = \"submit\" #: SUSPEND = \"suspend\" #: TOGGLE = \"toggle\" #:", "MOUSEMOVE = \"mousemove\" #: MOUSEOVER = \"mouseover\" #: MOUSEOUT = \"mouseout\" #: MOUSEUP", "# self.error={} super().__init__(_type, *args, **kwargs) class SubmitEvent(Event): \"\"\" SubmitEvent \"\"\" SUBMIT = \"submit\"", "\"\"\" # from typing import * import time # TODO - bring EventTarget", "onvolumechange(self, event): print(event) raise NotImplementedError def onwaiting(self, event): print(event) raise NotImplementedError def onwheel(self,", "ctrlKey(self): return self._ctrlKey @property def shiftKey(self): return self._shiftKey @property def metaKey(self): return self._metaKey", "#: LOADEDMETADATA = \"loadedmetadata\" #: MESSAGE = \"message\" #: OFFLINE = \"offline\" #:", "raise NotImplementedError def onanimationcancel(self, event): print(event) raise NotImplementedError def onanimationend(self, event): print(event) raise", "\"\"\" self.inputType \"\"\" Returns the type of the change (i.e \"inserting\" or \"deleting\")", "\"\"\" BLUR = \"blur\" #: FOCUS = \"focus\" #: FOCUSIN = \"focusin\" #:", "\"cut\" #: PASTE = \"paste\" #: def __init__(self, _type, *args, **kwargs): self.clipboardData =", "one? class EventDispatcher(object): \"\"\" EventDispatcher is a class you can extend to give", "# TODO - event: str, function, useCapture: bool # def addEventListener(self, event: str,", "MouseEvent # pageX Returns the horizontal coordinate of the mouse pointer, relative to", "stack.remove(thing) return def dispatchEvent(self, event): if event.type not in self.listeners: return True #", "BLUR = \"blur\" #: FOCUS = \"focus\" #: FOCUSIN = \"focusin\" #: FOCUSOUT", "NotImplementedError def ongotpointercapture(self, event): print(event) raise NotImplementedError def oninput(self, event): print(event) raise NotImplementedError", "time.time_ns() // 1000000 3.7 up self.timeStamp = int(round(time.time() * 1000)) def composedPath(self): return", "= \"onUnPause\" #: UPDATE_START = \"onUpdateStart\" #: UPDATE_END = \"onUpdateEnd\" #: COMPLETE =", "NotImplementedError def oncancel(self, event): print(event) raise NotImplementedError def oncanplay(self, event): print(event) raise NotImplementedError", "\"animationstart\" #: def __init__(self, _type, *args, **kwargs): self.animationName = None \"\"\" Returns the", "\"hashchange\" #: def __init__(self, _type, *args, **kwargs): self.newURL = None self.oldURL = None", "def onpointerover(self, event): print(event) raise NotImplementedError def onpointerup(self, event): print(event) raise NotImplementedError def", "super().__init__(_type, *args, **kwargs) class TimerEvent(Event): TIMER = \"timer\" #: \"\"\" TimerEvent \"\"\" def", "target element MouseEvent # pageX Returns the horizontal coordinate of the mouse pointer,", "*args, **kwargs): # self.args = args # self.kwargs = kwargs self.x = 0", "or not \"\"\" super().__init__(_type, *args, **kwargs) class PageTransitionEvent(Event): \"\"\" PageTransitionEvent \"\"\" PAGEHIDE =", "the animation \"\"\" self.elapsedTime = None \"\"\" Returns the number of seconds an", "\"\"\" TRANSITIONEND = \"transitionend\" #: def __init__(self, _type, *args, **kwargs): self.propertyName = None", "__init__(self, _type, *args, **kwargs): self.relatedTarget = None super().__init__(_type, *args, **kwargs) class TouchEvent(Event): \"\"\"", "NotImplementedError def onpointermove(self, event): print(event) raise NotImplementedError def onpointerout(self, event): print(event) raise NotImplementedError", "# self.composed = None # self.currentTarget = None # self.eventPhase = None #", "raise NotImplementedError def onpointerenter(self, event): print(event) raise NotImplementedError def onpointerleave(self, event): print(event) raise", "NotImplementedError def onratechange(self, event): print(event) raise NotImplementedError def onreset(self, event): print(event) raise NotImplementedError", "position of the edge of the target element MouseEvent # offsetY Returns the", "representing the affected storage object \"\"\" self.url = None \"\"\" Returns the URL", "MouseEvent, FocusEvent class KeyboardEvent(Event): \"\"\" keyboard events \"\"\" KEYDOWN = \"keydown\" #: KEYPRESS", "#: UPDATE_END = \"onUpdateEnd\" #: COMPLETE = \"onComplete\" #: TIMER = \"onTimer\" #:", "= None # self.currentTarget = None # self.eventPhase = None # self.isTrusted =", "on the keyboard or device KeyboardEvent class UIEvent(Event): \"\"\" UIEvent \"\"\" def __init__(self,", "= source def __init__(self, _type, source=None, bubbles=False, cancelable=False): # super.__init__(self, type, bubbles, cancelable)", "raise NotImplementedError def onloadedmetadata(self, event): print(event) raise NotImplementedError def onloadend(self, event): print(event) raise", "= \"mouseover\" #: MOUSEOUT = \"mouseout\" #: MOUSEUP = \"mouseup\" #: def __init__(self,", "event): print(event) raise NotImplementedError def ondblclick(self, event): print(event) raise NotImplementedError def ondrag(self, event):", "locationArg, modifiersListArg, repeat): self._type = typeArg self.canBubbleArg = canBubbleArg self.cancelableArg = cancelableArg self.viewArg", "ENTER = \"dragenter\" #: EXIT = \"dragexit\" #: LEAVE = \"dragleave\" #: OVER", "**kwargs): self.gamepad = None super().__init__(_type, *args, **kwargs) class TweenEvent(Event): \"\"\" TweenEvent \"\"\" START", "event): print(event) raise NotImplementedError def ondragenter(self, event): print(event) raise NotImplementedError def ondragexit(self, event):", "**kwargs): # print('type', _type) self.type = _type self.bubbles = None self.cancelable = None", "clientX=0, clientY=0, ctrlKey=False, altKey=False, shiftKey=False, metaKey=False, button=None, relatedTarget=None, from_json={}, *args, **kwargs): # print('initMouseEvent')", "\"\"\" Returns the name of the pseudo-element of the animation \"\"\" super().__init__(_type, *args,", "the mouse pointer relative to the position of the edge of the target", "seconds an animation has been running \"\"\" self.pseudoElement = None \"\"\" Returns the", "def onclose(self, event): print(event) raise NotImplementedError def oncontextmenu(self, event): print(event) raise NotImplementedError def", "self.ctrlKey = None self.metaKey = None self.shiftKey = None self.targetTouches = None self.touches", "#: ERROR = \"error\" #: FULLSCREENCHANGE = \"fullscreenchange\" #: FULLSCREENERROR = \"fullscreenerror\" #:", "SEEKING = \"seeking\" #: SELECT = \"select\" #: SHOW = \"show\" #: STALLED", "= None \"\"\" Returns the URL of the changed item's document \"\"\" super().__init__(_type,", "def ondblclick(self, event): print(event) raise NotImplementedError def ondrag(self, event): print(event) raise NotImplementedError def", "event): print(event) raise NotImplementedError def onselectionchange(self, event): print(event) raise NotImplementedError def onselectstart(self, event):", "coordinate of the mouse pointer, relative to the document, when the mouse event", "the mouse event MouseEvent, FocusEvent class KeyboardEvent(Event): \"\"\" keyboard events \"\"\" KEYDOWN =", "= None self.ctrlKey = None self.metaKey = None self.shiftKey = None self.targetTouches =", "raise NotImplementedError def onkeypress(self, event): print(event) raise NotImplementedError def onkeyup(self, event): print(event) raise", "print(event) raise NotImplementedError def onratechange(self, event): print(event) raise NotImplementedError def onreset(self, event): print(event)", "def hasEventListener(self, _type): return _type in self.listeners # TODO - event: str, function,", "def onvolumechange(self, event): print(event) raise NotImplementedError def onwaiting(self, event): print(event) raise NotImplementedError def", "Returns an array containing target ranges that will be affected by the insertion/deletion", "stack: try: thing(event) # type(thing, (Event,), self) except Exception as e: print(e) thing()", "# @property # def code(self): # return self.code # @property # def key(self):", "self.kwargs = kwargs self._altKey = False self._ctrlKey = False self._shiftKey = False self._metaKey", "onlostpointercapture(self, event): print(event) raise NotImplementedError def onmouseenter(self, event): print(event) raise NotImplementedError def onmouseleave(self,", "element MouseEvent # offsetY Returns the vertical coordinate of the mouse pointer relative", "= None # self.cancelable = None # self.cancelBubble = None # self.composed =", "device KeyboardEvent class UIEvent(Event): \"\"\" UIEvent \"\"\" def __init__(self, _type, *args, **kwargs): self.detail", "in stack: if thing == callback: stack.remove(thing) return def dispatchEvent(self, event): if event.type", "self.tangentialPressure = None self.tiltX = None self.tiltY = None self.twist = None self.pointerType", "OFFLINE = \"offline\" #: ONLINE = \"online\" #: OPEN = \"open\" #: PAUSE", "def oninput(self, event): print(event) raise NotImplementedError def oninvalid(self, event): print(event) raise NotImplementedError def", "inserted/deleted data \"\"\" self.getTargetRanges \"\"\" Returns an array containing target ranges that will", "self.addEventListener(MouseEvent.MOUSEDOWN, self.onmousedown) # self.addEventListener(MouseEvent.MOUSEUP, self.onmouseup) # self.addEventListener(DragEvent.DRAG, self.ondrag) # self.addEventListener(DragEvent.END, self.ondragend) # self.addEventListener(DragEvent.ENTER,", "= ctrlKey self._altKey = altKey self._shiftKey = shiftKey self._metaKey = metaKey self._button =", "print(event) raise NotImplementedError def oncanplay(self, event): print(event) raise NotImplementedError def oncanplaythrough(self, event): print(event)", "event): print(event) raise NotImplementedError def onauxclick(self, event): print(event) raise NotImplementedError def onformdata(self, event):", "self.shiftKey = None self.altKey = None self.changedTouches = None self.ctrlKey = None self.metaKey", "event): print(event) raise NotImplementedError def onselectstart(self, event): print(event) raise NotImplementedError def onshow(self, event):", "event): print(event) raise NotImplementedError def onstalled(self, event): print(event) raise NotImplementedError def onsubmit(self, event):", "print(event) raise NotImplementedError def onmousemove(self, event): print(event) raise NotImplementedError def onmouseout(self, event): print(event)", "= \"touchmove\" #: TOUCHSTART = \"touchstart\" #: def __init__(self, _type, *args, **kwargs): self.shiftKey", "= int(round(time.time() * 1000)) # self.type = None pass def msConvertURL(self): pass def", "domonic.events ==================================== dom events \"\"\" # from typing import * import time #", "\"stalled\" #: SUBMIT = \"submit\" #: SUSPEND = \"suspend\" #: TOGGLE = \"toggle\"", "position of the last mousemove event MouseEvent # offsetX Returns the horizontal coordinate", "PointerEvent(Event): \"\"\" PointerEvent \"\"\" POINTER = \"pointer\" #: def __init__(self, _type, *args, **kwargs):", "the webpage was cached by the browser \"\"\" super().__init__(_type, *args, **kwargs) class PopStateEvent(Event):", "+ \":\" + str(self.timeStamp) def initEvent(self, _type=None, *args, **kwargs): self.__init__(_type, args, kwargs) def", "ErrorEvent \"\"\" ERROR = \"error\" #: def __init__(self, _type, *args, **kwargs): self.message =", "self._type = typeArg self.canBubbleArg = canBubbleArg self.cancelableArg = cancelableArg self.viewArg = viewArg self.charArg", "# self.addEventListener(ClipboardEvent.COPY, self.oncopy) # self.addEventListener(ClipboardEvent.PASTE, self.onpaste) def onabort(self, event): print(event) raise NotImplementedError def", "GlobalEventHandler: # (EventDispatcher): # def __init__(self): # super().__init__(self) # self.addEventListener(KeyboardEvent.KEYDOWN, self.onkeydown) # self.addEventListener(KeyboardEvent.KEYUP,", "self.addEventListener(DragEvent.LEAVE, self.ondragleave) # self.addEventListener(DragEvent.OVER, self.ondragover) # self.addEventListener(DragEvent.START, self.ondragstart) # self.addEventListener(DragEvent.DROP, self.ondrop) # self.addEventListener(ClipboardEvent.CUT,", "RESIZE = \"resize\" #: RESET = \"reset\" #: SCROLL = \"scroll\" #: SEARCH", "\"reset\" #: SCROLL = \"scroll\" #: SEARCH = \"search\" #: SEEKED = \"seeked\"", "= \"mouseup\" #: def __init__(self, _type, *args, **kwargs): # self.args = args #", "#: CANPLAY = \"canplay\" #: CANPLAYTHROUGH = \"canplaythrough\" #: CHANGE = \"change\" #:", "\"compositionstart\" END = \"compositionend\" UPDATE = \"compositionupdate\" def __init__(self, _type, *args, **kwargs): self.data", "input method that raised the event self.locale = None super().__init__(_type, *args, **kwargs) class", "canBubbleArg self.cancelableArg = cancelableArg self.viewArg = viewArg self.charArg = charArg self.keyArg = keyArg", "onpointerup(self, event): print(event) raise NotImplementedError def onprogress(self, event): print(event) raise NotImplementedError def onratechange(self,", "ontouchstart(self, event): print(event) raise NotImplementedError def ontransitioncancel(self, event): print(event) raise NotImplementedError def ontransitionend(self,", "**kwargs): self.persisted = None \"\"\" Returns whether the webpage was cached by the", "\"\"\" COPY = \"copy\" #: CUT = \"cut\" #: PASTE = \"paste\" #:", "FULLSCREENCHANGE = \"fullscreenchange\" #: FULLSCREENERROR = \"fullscreenerror\" #: INPUT = \"input\" #: INVALID", "the clipboard operation \"\"\" super().__init__(_type, *args, **kwargs) class ErrorEvent(Event): \"\"\" ErrorEvent \"\"\" ERROR", "the new value of the changed storage item \"\"\" self.oldValue = None \"\"\"", "\"search\" #: SEEKED = \"seeked\" #: SEEKING = \"seeking\" #: SELECT = \"select\"", "raise NotImplementedError def onkeyup(self, event): print(event) raise NotImplementedError def onload(self, event): print(event) raise", "None self.explicitOriginalTarget = None self.isTrusted = None self.originalTarget = None self.returnValue = None", "raise NotImplementedError def onpointerleave(self, event): print(event) raise NotImplementedError def onpointermove(self, event): print(event) raise", "self._button = None self._buttons = [] super().__init__(_type, *args, **kwargs) def initMouseEvent(self, _type=None, canBubble=True,", "Returns whether the state of the event is composing or not \"\"\" super().__init__(_type,", "self._altKey = False self._ctrlKey = False self._shiftKey = False self._metaKey = False self.charCode", "self.cancelable = cancelable self.view = view self.detail = detail self.screenX = screenX self.screenY", "\"\"\" Returns the number of seconds a transition has been running \"\"\" self.pseudoElement", "\"onStop\" #: RESET = \"onReset\" #: PAUSE = \"onPause\" #: UNPAUSE = \"onUnPause\"", "print(event) raise NotImplementedError def ondurationchange(self, event): print(event) raise NotImplementedError def onemptied(self, event): print(event)", "event): print(event) raise NotImplementedError def onpause(self, event): print(event) raise NotImplementedError def onplay(self, event):", "int(round(time.time() * 1000)) def composedPath(self): return self.type + \":\" + str(self.timeStamp) def initEvent(self,", "COMPLETE = \"onComplete\" #: TIMER = \"onTimer\" #: _source = None @property def", "\":\" + str(self.timeStamp) def initEvent(self, _type=None, *args, **kwargs): self.__init__(_type, args, kwargs) def stopPropagation(self):", "self.originalTarget = None self.returnValue = None self.srcElement = None self.target = None #", "str, function, useCapture: bool) -> None: def addEventListener(self, _type, callback, *args, **kwargs): if", "@property def buttons(self): return self._buttons @property def which(self): return self._button # MOUSE_EVENT #", "*args, **kwargs): self.data = None \"\"\" Returns the inserted characters \"\"\" self.dataTransfer \"\"\"", "super().__init__(_type, *args, **kwargs) class StorageEvent(Event): \"\"\" StorageEvent \"\"\" def __init__(self, _type, *args, **kwargs):", "view self.detail = detail self.screenX = screenX self.screenY = screenY self._clientX = clientX", "*args, **kwargs) class HashChangeEvent(Event): \"\"\" HashChangeEvent \"\"\" CHANGE = \"hashchange\" #: def __init__(self,", "def __init__(self, _type, source=None, bubbles=False, cancelable=False): # super.__init__(self, type, bubbles, cancelable) super().__init__(_type) #", "param return not event.defaultPrevented class Event(object): \"\"\" event \"\"\" EMPTIED = \"emptied\" #:", "#: BEFOREPRINT = \"beforeprint\" #: BEFOREUNLOAD = \"beforeunload\" #: CANPLAY = \"canplay\" #:", "\"\"\" Returns the type of the change (i.e \"inserting\" or \"deleting\") \"\"\" self.isComposing", "**kwargs): # self.args = args # self.kwargs = kwargs self.x = 0 self.y", "self.y = 0 self._clientX = 0 self._clientX = 0 self._altKey = False self._ctrlKey", "#: END = \"dragend\" #: ENTER = \"dragenter\" #: EXIT = \"dragexit\" #:", "\"\"\" UIEvent \"\"\" def __init__(self, _type, *args, **kwargs): self.detail = None self.view =", "= None \"\"\" Returns the number of seconds a transition has been running", "def onmouseover(self, event): print(event) raise NotImplementedError def onmouseup(self, event): print(event) raise NotImplementedError def", "raise NotImplementedError def onpointercancel(self, event): print(event) raise NotImplementedError def onpointerdown(self, event): print(event) raise", "of the last mousemove event MouseEvent # offsetX Returns the horizontal coordinate of", "whether the webpage was cached by the browser \"\"\" super().__init__(_type, *args, **kwargs) class", "onreset(self, event): print(event) raise NotImplementedError def onresize(self, event): print(event) raise NotImplementedError def onscroll(self,", "onratechange(self, event): print(event) raise NotImplementedError def onreset(self, event): print(event) raise NotImplementedError def onresize(self,", "onclick(self, event): print(event) raise NotImplementedError def onclose(self, event): print(event) raise NotImplementedError def oncontextmenu(self,", "= screenY self._clientX = clientX self._clientY = clientY self._ctrlKey = ctrlKey self._altKey =", "**kwargs) class StorageEvent(Event): \"\"\" StorageEvent \"\"\" def __init__(self, _type, *args, **kwargs): self.key =", "\"\"\" self.storageArea = None \"\"\" Returns an object representing the affected storage object", "\"ratechange\" #: RESIZE = \"resize\" #: RESET = \"reset\" #: SCROLL = \"scroll\"", "onstalled(self, event): print(event) raise NotImplementedError def onsubmit(self, event): print(event) raise NotImplementedError def onsuspend(self,", "event): print(event) raise NotImplementedError def onmouseover(self, event): print(event) raise NotImplementedError def onmouseup(self, event):", "\"afterprint\" #: BEFOREPRINT = \"beforeprint\" #: BEFOREUNLOAD = \"beforeunload\" #: CANPLAY = \"canplay\"", "def __init__(self, _type, *args, **kwargs): self.key = None \"\"\" Returns the key of", "not in self.listeners: return True # huh?. surely false? stack = self.listeners[event.type] #", "the capturing and bubbling phases]\"\"\" # self.defaultPrevented = True # self.returnValue = None", "raise NotImplementedError def onscroll(self, event): print(event) raise NotImplementedError def onseeked(self, event): print(event) raise", "an object containing information about the inserted/deleted data \"\"\" self.getTargetRanges \"\"\" Returns an", "screenY=0, clientX=0, clientY=0, ctrlKey=False, altKey=False, shiftKey=False, metaKey=False, button=None, relatedTarget=None, from_json={}, *args, **kwargs): #", "events \"\"\" # from typing import * import time # TODO - bring", "False self.eventPhase = None self.explicitOriginalTarget = None self.isTrusted = None self.originalTarget = None", "None self.twist = None self.pointerType = None self.isPrimary = None super().__init__(_type, *args, **kwargs)", "number of seconds an animation has been running \"\"\" self.pseudoElement = None \"\"\"", "onselectionchange(self, event): print(event) raise NotImplementedError def onselectstart(self, event): print(event) raise NotImplementedError def onshow(self,", "_type, *args, **kwargs): self.propertyName = None \"\"\" Returns the name of the transition\"\"\"", "def ondurationchange(self, event): print(event) raise NotImplementedError def onemptied(self, event): print(event) raise NotImplementedError def", "* import time # TODO - bring EventTarget here and get rid of", "SCROLL = \"scroll\" #: SEARCH = \"search\" #: SEEKED = \"seeked\" #: SEEKING", "**kwargs) class ErrorEvent(Event): \"\"\" ErrorEvent \"\"\" ERROR = \"error\" #: def __init__(self, _type,", "onkeyup(self, event): print(event) raise NotImplementedError def onload(self, event): print(event) raise NotImplementedError def onloadeddata(self,", "WheelEvent \"\"\" MOUSEWHEEL = \"mousewheel\" # DEPRECATED - USE WHEEL #: WHEEL =", "SubmitEvent \"\"\" SUBMIT = \"submit\" #: def __init__(self, _type, *args, **kwargs): super().__init__(_type, *args,", "class you can extend to give your obj event dispatching abilities \"\"\" def", "UIEvent \"\"\" def __init__(self, _type, *args, **kwargs): self.detail = None self.view = None", "__init__(self, _type, source=None, bubbles=False, cancelable=False): # super.__init__(self, type, bubbles, cancelable) super().__init__(_type) # TODO", "__init__(self, _type, *args, **kwargs): self.detail = None super().__init__(_type, *args, **kwargs) def initCustomEvent(self): pass", "# pageY Returns the vertical coordinate of the mouse pointer, relative to the", "event): print(event) raise NotImplementedError def onwaiting(self, event): print(event) raise NotImplementedError def onwheel(self, event):", "= \"afterprint\" #: BEFOREPRINT = \"beforeprint\" #: BEFOREUNLOAD = \"beforeunload\" #: CANPLAY =", "source class GlobalEventHandler: # (EventDispatcher): # def __init__(self): # super().__init__(self) # self.addEventListener(KeyboardEvent.KEYDOWN, self.onkeydown)", "def oninvalid(self, event): print(event) raise NotImplementedError def onkeydown(self, event): print(event) raise NotImplementedError def", "# self.addEventListener(ClipboardEvent.CUT, self.oncut) # self.addEventListener(ClipboardEvent.COPY, self.oncopy) # self.addEventListener(ClipboardEvent.PASTE, self.onpaste) def onabort(self, event): print(event)", "self.explicitOriginalTarget = None # self.target = None # self.srcElement = None # self.bubbles", "\"\"\" PointerEvent \"\"\" POINTER = \"pointer\" #: def __init__(self, _type, *args, **kwargs): self.pointerId", "pointer relative to the position of the last mousemove event MouseEvent # MovementY", "print(event) raise NotImplementedError def ontouchstart(self, event): print(event) raise NotImplementedError def ontransitioncancel(self, event): print(event)", "# isComposing Returns whether the state of the event is composing or not", "# self.returnValue = None # self.timeStamp = int(round(time.time() * 1000)) # self.type =", "raise NotImplementedError def onmouseenter(self, event): print(event) raise NotImplementedError def onmouseleave(self, event): print(event) raise", "# self.args = args # self.kwargs = kwargs self.x = 0 self.y =", "**kwargs) def initCustomEvent(self): pass class GamePadEvent(Event): \"\"\" GamePadEvent \"\"\" START = \"gamepadconnected\" #:", "raise NotImplementedError def onwheel(self, event): print(event) raise NotImplementedError def onanimationcancel(self, event): print(event) raise", "NotImplementedError def onprogress(self, event): print(event) raise NotImplementedError def onratechange(self, event): print(event) raise NotImplementedError", "transition\"\"\" self.elapsedTime = None \"\"\" Returns the number of seconds a transition has", "obj event dispatching abilities \"\"\" def __init__(self, *args, **kwargs): self.listeners = {} def", "= \"open\" #: PAUSE = \"pause\" #: PLAY = \"play\" #: PLAYING =", "self.deltaX = None self.deltaY = None self.deltaZ = None self.deltaMode = None super().__init__(_type,", "in stack: try: thing(event) # type(thing, (Event,), self) except Exception as e: print(e)", "EMPTIED = \"emptied\" #: ABORT = \"abort\" #: AFTERPRINT = \"afterprint\" #: BEFOREPRINT", "MouseEvent # pageY Returns the vertical coordinate of the mouse pointer, relative to", "= canBubble self.cancelable = cancelable self.view = view self.detail = detail self.screenX =", "whether the state of the event is composing or not \"\"\" super().__init__(_type, *args,", "= None \"\"\" Returns the old value of the changed storage item \"\"\"", "UPDATE_END = \"onUpdateEnd\" #: COMPLETE = \"onComplete\" #: TIMER = \"onTimer\" #: _source", "\"mousewheel\" # DEPRECATED - USE WHEEL #: WHEEL = \"wheel\" #: def __init__(self,", "Returns the inserted characters \"\"\" self.dataTransfer \"\"\" Returns an object containing information about", "\"\"\" CompositionEvent \"\"\" START = \"compositionstart\" END = \"compositionend\" UPDATE = \"compositionupdate\" def", "document \"\"\" super().__init__(_type, *args, **kwargs) class TransitionEvent(Event): \"\"\" TransitionEvent \"\"\" TRANSITIONEND = \"transitionend\"", "**kwargs) class PageTransitionEvent(Event): \"\"\" PageTransitionEvent \"\"\" PAGEHIDE = \"pagehide\" #: PAGESHOW = \"pageshow\"", "\"suspend\" #: TOGGLE = \"toggle\" #: UNLOAD = \"unload\" #: VOLUMECHANGE = \"volumechange\"", "MOUSEENTER = \"mouseenter\" #: MOUSELEAVE = \"mouseleave\" #: MOUSEMOVE = \"mousemove\" #: MOUSEOVER", "_type=None, canBubble=True, cancelable=True, view=None, detail=None, screenX=0, screenY=0, clientX=0, clientY=0, ctrlKey=False, altKey=False, shiftKey=False, metaKey=False,", "super().__init__(_type, *args, **kwargs) class ClipboardEvent(Event): \"\"\" ClipboardEvent \"\"\" COPY = \"copy\" #: CUT", "\"\"\" Returns whether the webpage was cached by the browser \"\"\" super().__init__(_type, *args,", "# TODO/NOTE - is this correct? - cant think where else would set", "_type in self.listeners # TODO - event: str, function, useCapture: bool # def", "_type=None, *args, **kwargs): self.__init__(_type, args, kwargs) def stopPropagation(self): \"\"\"[prevents further propagation of the", "print(event) raise NotImplementedError def oninput(self, event): print(event) raise NotImplementedError def oninvalid(self, event): print(event)", "__init__(self, _type, *args, **kwargs): self.deltaX = None self.deltaY = None self.deltaZ = None", "raise NotImplementedError def onpause(self, event): print(event) raise NotImplementedError def onplay(self, event): print(event) raise", "def ondragexit(self, event): print(event) raise NotImplementedError def ondragleave(self, event): print(event) raise NotImplementedError def", "def onclick(self, event): print(event) raise NotImplementedError def onclose(self, event): print(event) raise NotImplementedError def", "= \"error\" #: def __init__(self, _type, *args, **kwargs): self.message = None # self.filename=None", "storage object \"\"\" self.url = None \"\"\" Returns the URL of the changed", "TweenEvent(Event): \"\"\" TweenEvent \"\"\" START = \"onStart\" #: STOP = \"onStop\" #: RESET", "self.returnValue = None # self.timeStamp = int(round(time.time() * 1000)) # self.type = None", "by the browser \"\"\" super().__init__(_type, *args, **kwargs) class PopStateEvent(Event): \"\"\" PopStateEvent \"\"\" def", "self.key = None self.keyCode = None super().__init__(_type, *args, **kwargs) def initKeyboardEvent(self, typeArg, canBubbleArg,", "in self.listeners: return stack = self.listeners[_type] for thing in stack: if thing ==", "would set it for thing in stack: try: thing(event) # type(thing, (Event,), self)", "oncancel(self, event): print(event) raise NotImplementedError def oncanplay(self, event): print(event) raise NotImplementedError def oncanplaythrough(self,", "self.timeStamp = int(round(time.time() * 1000)) def composedPath(self): return self.type + \":\" + str(self.timeStamp)", "canBubble self.cancelable = cancelable self.view = view self.detail = detail self.screenX = screenX", "onloadedmetadata(self, event): print(event) raise NotImplementedError def onloadend(self, event): print(event) raise NotImplementedError def onloadstart(self,", "TIMER = \"timer\" #: \"\"\" TimerEvent \"\"\" def __init__(self, _type, *args, **kwargs): super().__init__(_type,", "\"\"\" SVGEvent \"\"\" def __init__(self, _type, *args, **kwargs): super().__init__(_type, *args, **kwargs) class TimerEvent(Event):", "\"\"\" TouchEvent \"\"\" TOUCHCANCEL = \"touchcancel\" #: TOUCHEND = \"touchend\" #: TOUCHMOVE =", "\"dragenter\" #: EXIT = \"dragexit\" #: LEAVE = \"dragleave\" #: OVER = \"dragover\"", "\"select\" #: SHOW = \"show\" #: STALLED = \"stalled\" #: SUBMIT = \"submit\"", "False self._button = None self._buttons = [] super().__init__(_type, *args, **kwargs) def initMouseEvent(self, _type=None,", "= \"show\" #: STALLED = \"stalled\" #: SUBMIT = \"submit\" #: SUSPEND =", "element that triggered the mouse event MouseEvent, FocusEvent class KeyboardEvent(Event): \"\"\" keyboard events", "self.addEventListener(KeyboardEvent.KEYDOWN, self.onkeydown) # self.addEventListener(KeyboardEvent.KEYUP, self.onkeyup) # self.addEventListener(MouseEvent.MOUSEMOVE, self.onmousemove) # self.addEventListener(MouseEvent.MOUSEDOWN, self.onmousedown) # self.addEventListener(MouseEvent.MOUSEUP,", "self.oncopy) # self.addEventListener(ClipboardEvent.PASTE, self.onpaste) def onabort(self, event): print(event) raise NotImplementedError def onblur(self, event):", "None self.altKey = None self.changedTouches = None self.ctrlKey = None self.metaKey = None", "raise NotImplementedError def onpointerover(self, event): print(event) raise NotImplementedError def onpointerup(self, event): print(event) raise", "the insertion/deletion MouseEvent # MovementX Returns the horizontal coordinate of the mouse pointer", "*args, **kwargs) class WheelEvent(Event): \"\"\" WheelEvent \"\"\" MOUSEWHEEL = \"mousewheel\" # DEPRECATED -", "animation has been running \"\"\" self.pseudoElement = None \"\"\" Returns the name of", "super().__init__(_type, *args, **kwargs) class PageTransitionEvent(Event): \"\"\" PageTransitionEvent \"\"\" PAGEHIDE = \"pagehide\" #: PAGESHOW", "Returns the old value of the changed storage item \"\"\" self.storageArea = None", "a key is being hold down repeatedly, or not KeyboardEvent # location Returns", "raise NotImplementedError def ontouchcancel(self, event): print(event) raise NotImplementedError def ontouchstart(self, event): print(event) raise", "_type) self.type = _type self.bubbles = None self.cancelable = None self.cancelBubble = None", "print(event) raise NotImplementedError def onformdata(self, event): print(event) raise NotImplementedError def onmousedown(self, event): print(event)", "= None \"\"\" Returns an object containing a copy of the history entries", "get rid of this one? class EventDispatcher(object): \"\"\" EventDispatcher is a class you", "self.charArg = charArg self.keyArg = keyArg self.locationArg = locationArg self.modifiersListArg = modifiersListArg self.repeat", "class ErrorEvent(Event): \"\"\" ErrorEvent \"\"\" ERROR = \"error\" #: def __init__(self, _type, *args,", "self._source @source.setter def source(self, source): self._source = source def __init__(self, _type, source=None, bubbles=False,", "Returns the characters generated by the input method that raised the event self.locale", "\"\"\" InputEvent \"\"\" def __init__(self, _type, *args, **kwargs): self.data = None \"\"\" Returns", "\"play\" #: PLAYING = \"playing\" #: PROGRESS = \"progress\" #: RATECHANGE = \"ratechange\"", "OPEN = \"open\" #: PAUSE = \"pause\" #: PLAY = \"play\" #: PLAYING", "#: FULLSCREENCHANGE = \"fullscreenchange\" #: FULLSCREENERROR = \"fullscreenerror\" #: INPUT = \"input\" #:", "of this one? class EventDispatcher(object): \"\"\" EventDispatcher is a class you can extend", "**kwargs): super().__init__(_type, *args, **kwargs) class TimerEvent(Event): TIMER = \"timer\" #: \"\"\" TimerEvent \"\"\"", "\"message\" #: OFFLINE = \"offline\" #: ONLINE = \"online\" #: OPEN = \"open\"", "return self._shiftKey @property def metaKey(self): return self._metaKey @property def unicode(self): return self.key #", "item \"\"\" self.newValue = None \"\"\" Returns the new value of the changed", "vertical coordinate of the mouse pointer, relative to the document, when the mouse", "import time # TODO - bring EventTarget here and get rid of this", "self._button @property def buttons(self): return self._buttons @property def which(self): return self._button # MOUSE_EVENT", "int(round(time.time() * 1000)) # self.type = None pass def msConvertURL(self): pass def preventDefault(self):", "onpointerenter(self, event): print(event) raise NotImplementedError def onpointerleave(self, event): print(event) raise NotImplementedError def onpointermove(self,", "self._clientY = clientY self._ctrlKey = ctrlKey self._altKey = altKey self._shiftKey = shiftKey self._metaKey", "self._metaKey @property def unicode(self): return self.key # @property # def keyCode(self): # return", "self.target = None # ms = time.time_ns() // 1000000 3.7 up self.timeStamp =", "MouseEvent # MovementX Returns the horizontal coordinate of the mouse pointer relative to", "relatedTarget # TODO - parse from_json - so can relay @property def clientX(self):", "#: RESET = \"reset\" #: SCROLL = \"scroll\" #: SEARCH = \"search\" #:", "can relay @property def clientX(self): return self.x @property def clientY(self): return self.y @property", "= \"transitionend\" #: def __init__(self, _type, *args, **kwargs): self.propertyName = None \"\"\" Returns", "class CustomEvent(Event): \"\"\" CustomEvent \"\"\" def __init__(self, _type, *args, **kwargs): self.detail = None", "callback, *args, **kwargs): if _type not in self.listeners: self.listeners[_type] = [] self.listeners[_type].append(callback) def", "of the event is composing or not InputEvent, KeyboardEvent # repeat Returns whether", "**kwargs) class TweenEvent(Event): \"\"\" TweenEvent \"\"\" START = \"onStart\" #: STOP = \"onStop\"", "event): print(event) raise NotImplementedError def oncontextmenu(self, event): print(event) raise NotImplementedError def oncuechange(self, event):", "raise NotImplementedError def ongotpointercapture(self, event): print(event) raise NotImplementedError def oninput(self, event): print(event) raise", "InputEvent, KeyboardEvent # repeat Returns whether a key is being hold down repeatedly,", "print(event) raise NotImplementedError def oncuechange(self, event): print(event) raise NotImplementedError def ondblclick(self, event): print(event)", "key is being hold down repeatedly, or not KeyboardEvent # location Returns the", "not InputEvent, KeyboardEvent # repeat Returns whether a key is being hold down", "#: COMPLETE = \"onComplete\" #: TIMER = \"onTimer\" #: _source = None @property", "or not InputEvent, KeyboardEvent # repeat Returns whether a key is being hold", "event): print(event) raise NotImplementedError def onended(self, event): print(event) raise NotImplementedError def onerror(self, event):", "raise NotImplementedError def oninput(self, event): print(event) raise NotImplementedError def oninvalid(self, event): print(event) raise", "self.locale = None super().__init__(_type, *args, **kwargs) class FocusEvent(Event): \"\"\" FocusEvent \"\"\" BLUR =", "raise NotImplementedError def onsubmit(self, event): print(event) raise NotImplementedError def onsuspend(self, event): print(event) raise", "object \"\"\" self.url = None \"\"\" Returns the URL of the changed item's", "return self._shiftKey @property def metaKey(self): return self._metaKey @property def button(self): return self._button @property", "None self.isTrusted = None self.originalTarget = None self.returnValue = None self.srcElement = None", "#: LOAD = \"load\" #: LOADEDDATA = \"loadeddata\" #: LOADEDMETADATA = \"loadedmetadata\" #:", "event): print(event) raise NotImplementedError def onloadedmetadata(self, event): print(event) raise NotImplementedError def onloadend(self, event):", "def onloadend(self, event): print(event) raise NotImplementedError def onloadstart(self, event): print(event) raise NotImplementedError def", "= None self.returnValue = None self.srcElement = None self.target = None # ms", "**kwargs): self.__init__(_type, args, kwargs) def stopPropagation(self): \"\"\"[prevents further propagation of the current event", "raise NotImplementedError def onselectstart(self, event): print(event) raise NotImplementedError def onshow(self, event): print(event) raise", "\"\"\" CHANGE = \"hashchange\" #: def __init__(self, _type, *args, **kwargs): self.newURL = None", "*args, **kwargs) class DragEvent(Event): \"\"\" DragEvent \"\"\" DRAG = \"drag\" #: END =", "= None \"\"\" Returns the name of the pseudo-element of the animation \"\"\"", "from_json - so can relay @property def clientX(self): return self.x @property def clientY(self):", "@property def which(self): return self._button # MOUSE_EVENT # getModifierState() Returns an array containing", "= clientX self._clientY = clientY self._ctrlKey = ctrlKey self._altKey = altKey self._shiftKey =", "screenY self._clientX = clientX self._clientY = clientY self._ctrlKey = ctrlKey self._altKey = altKey", "def altKey(self): return self._altKey @property def ctrlKey(self): return self._ctrlKey @property def shiftKey(self): return", "isComposing Returns whether the state of the event is composing or not InputEvent,", "event self.locale = None super().__init__(_type, *args, **kwargs) class FocusEvent(Event): \"\"\" FocusEvent \"\"\" BLUR", "PAUSE = \"onPause\" #: UNPAUSE = \"onUnPause\" #: UPDATE_START = \"onUpdateStart\" #: UPDATE_END", "type, bubbles, cancelable) super().__init__(_type) # TODO - self.source = source class GlobalEventHandler: #", "self.listeners: self.listeners[_type] = [] self.listeners[_type].append(callback) def removeEventListener(self, _type, callback): if _type not in", "the changed item's document \"\"\" super().__init__(_type, *args, **kwargs) class TransitionEvent(Event): \"\"\" TransitionEvent \"\"\"", "onsubmit(self, event): print(event) raise NotImplementedError def onsuspend(self, event): print(event) raise NotImplementedError def ontimeupdate(self,", "and bubbling phases]\"\"\" # self.defaultPrevented = True # self.returnValue = None # self.originalTarget", "= \"beforeunload\" #: \"\"\" BeforeUnloadEvent \"\"\" def __init__(self, _type, *args, **kwargs): super().__init__(_type, *args,", "self._buttons = [] super().__init__(_type, *args, **kwargs) def initMouseEvent(self, _type=None, canBubble=True, cancelable=True, view=None, detail=None,", "KEYUP = \"keyup\" #: def __init__(self, _type, *args, **kwargs): # self.args = args", "__init__(self, _type, *args, **kwargs): super().__init__(_type, *args, **kwargs) class TimerEvent(Event): TIMER = \"timer\" #:", "ANIMATIONEND = \"animationend\" #: ANIMATIONITERATION = \"animationiteration\" #: ANIMATIONSTART = \"animationstart\" #: def", "= None @property def source(self): return self._source @source.setter def source(self, source): self._source =", "onprogress(self, event): print(event) raise NotImplementedError def onratechange(self, event): print(event) raise NotImplementedError def onreset(self,", "animation \"\"\" self.elapsedTime = None \"\"\" Returns the number of seconds an animation", "MOUSEUP = \"mouseup\" #: def __init__(self, _type, *args, **kwargs): # self.args = args", "NotImplementedError def onanimationend(self, event): print(event) raise NotImplementedError def onanimationiteration(self, event): print(event) raise NotImplementedError", "onauxclick(self, event): print(event) raise NotImplementedError def onformdata(self, event): print(event) raise NotImplementedError def onmousedown(self,", "can extend to give your obj event dispatching abilities \"\"\" def __init__(self, *args,", "characters \"\"\" self.dataTransfer \"\"\" Returns an object containing information about the inserted/deleted data", "= \"focus\" #: FOCUSIN = \"focusin\" #: FOCUSOUT = \"focusout\" #: def __init__(self,", "def onreset(self, event): print(event) raise NotImplementedError def onresize(self, event): print(event) raise NotImplementedError def", "ondragstart(self, event): print(event) raise NotImplementedError def ondrop(self, event): print(event) raise NotImplementedError def ondurationchange(self,", "*args, **kwargs): self.key = None \"\"\" Returns the key of the changed storage", "Returns an object containing information about the inserted/deleted data \"\"\" self.getTargetRanges \"\"\" Returns", "FOCUSOUT = \"focusout\" #: def __init__(self, _type, *args, **kwargs): self.relatedTarget = None super().__init__(_type,", "StorageEvent(Event): \"\"\" StorageEvent \"\"\" def __init__(self, _type, *args, **kwargs): self.key = None \"\"\"", "self.ondrag) # self.addEventListener(DragEvent.END, self.ondragend) # self.addEventListener(DragEvent.ENTER, self.ondragenter) # self.addEventListener(DragEvent.EXIT, self.ondragexit) # self.addEventListener(DragEvent.LEAVE, self.ondragleave)", "**kwargs) class PointerEvent(Event): \"\"\" PointerEvent \"\"\" POINTER = \"pointer\" #: def __init__(self, _type,", "= None self.deltaY = None self.deltaZ = None self.deltaMode = None super().__init__(_type, *args,", "def initMouseEvent(self, _type=None, canBubble=True, cancelable=True, view=None, detail=None, screenX=0, screenY=0, clientX=0, clientY=0, ctrlKey=False, altKey=False,", "a key on the keyboard or device KeyboardEvent class UIEvent(Event): \"\"\" UIEvent \"\"\"", "#: LOADEDDATA = \"loadeddata\" #: LOADEDMETADATA = \"loadedmetadata\" #: MESSAGE = \"message\" #:", "None # self.bubbles = None # self.cancelable = None # self.cancelBubble = None", "None self.defaultPrevented = False self.eventPhase = None self.explicitOriginalTarget = None self.isTrusted = None", "hasEventListener(self, _type): return _type in self.listeners # TODO - event: str, function, useCapture:", "= None # self.target = None # self.srcElement = None # self.bubbles =", "\"mouseleave\" #: MOUSEMOVE = \"mousemove\" #: MOUSEOVER = \"mouseover\" #: MOUSEOUT = \"mouseout\"", "__init__(self, _type=None, *args, **kwargs): # print('type', _type) self.type = _type self.bubbles = None", "\"\"\" def __init__(self, _type, *args, **kwargs): self.data = None \"\"\" Returns the inserted", "webpage was cached by the browser \"\"\" super().__init__(_type, *args, **kwargs) class PopStateEvent(Event): \"\"\"", "= \"seeking\" #: SELECT = \"select\" #: SHOW = \"show\" #: STALLED =", "charArg, keyArg, locationArg, modifiersListArg, repeat): self._type = typeArg self.canBubbleArg = canBubbleArg self.cancelableArg =", "self.args = args # self.kwargs = kwargs self.x = 0 self.y = 0", "object representing the affected storage object \"\"\" self.url = None \"\"\" Returns the", "event): print(event) raise NotImplementedError def onreset(self, event): print(event) raise NotImplementedError def onresize(self, event):", "# print('type', _type) self.type = _type self.bubbles = None self.cancelable = None self.cancelBubble", "self.listeners # TODO - event: str, function, useCapture: bool # def addEventListener(self, event:", "= None self.tiltY = None self.twist = None self.pointerType = None self.isPrimary =", "event): print(event) raise NotImplementedError def onchange(self, event): print(event) raise NotImplementedError def onclick(self, event):", "event was triggered MouseEvent # pageY Returns the vertical coordinate of the mouse", "detail=None, screenX=0, screenY=0, clientX=0, clientY=0, ctrlKey=False, altKey=False, shiftKey=False, metaKey=False, button=None, relatedTarget=None, from_json={}, *args,", "\"touchmove\" #: TOUCHSTART = \"touchstart\" #: def __init__(self, _type, *args, **kwargs): self.shiftKey =", "__init__(self): # super().__init__(self) # self.addEventListener(KeyboardEvent.KEYDOWN, self.onkeydown) # self.addEventListener(KeyboardEvent.KEYUP, self.onkeyup) # self.addEventListener(MouseEvent.MOUSEMOVE, self.onmousemove) #", "of the target element MouseEvent # pageX Returns the horizontal coordinate of the", "= None self.metaKey = None self.shiftKey = None self.targetTouches = None self.touches =", "event): print(event) raise NotImplementedError def onratechange(self, event): print(event) raise NotImplementedError def onreset(self, event):", "#: PROGRESS = \"progress\" #: RATECHANGE = \"ratechange\" #: RESIZE = \"resize\" #:", "rid of this one? class EventDispatcher(object): \"\"\" EventDispatcher is a class you can", "the transition\"\"\" self.elapsedTime = None \"\"\" Returns the number of seconds a transition", "class WheelEvent(Event): \"\"\" WheelEvent \"\"\" MOUSEWHEEL = \"mousewheel\" # DEPRECATED - USE WHEEL", "#: OFFLINE = \"offline\" #: ONLINE = \"online\" #: OPEN = \"open\" #:", "MOUSELEAVE = \"mouseleave\" #: MOUSEMOVE = \"mousemove\" #: MOUSEOVER = \"mouseover\" #: MOUSEOUT", "- parse from_json - so can relay @property def clientX(self): return self.x @property", "onended(self, event): print(event) raise NotImplementedError def onerror(self, event): print(event) raise NotImplementedError def onfocus(self,", "def button(self): return self._button @property def buttons(self): return self._buttons @property def which(self): return", "onload(self, event): print(event) raise NotImplementedError def onloadeddata(self, event): print(event) raise NotImplementedError def onloadedmetadata(self,", "= detail self.screenX = screenX self.screenY = screenY self._clientX = clientX self._clientY =", "\"\"\" self.url = None \"\"\" Returns the URL of the changed item's document", "cached by the browser \"\"\" super().__init__(_type, *args, **kwargs) class PopStateEvent(Event): \"\"\" PopStateEvent \"\"\"", "\"\"\" mouse events \"\"\" CLICK = \"click\" #: CONTEXTMENU = \"contextmenu\" #: DBLCLICK", "being hold down repeatedly, or not KeyboardEvent # location Returns the location of", "horizontal coordinate of the mouse pointer relative to the position of the edge", "where else would set it for thing in stack: try: thing(event) # type(thing,", "*args, **kwargs): # self.args = args # self.kwargs = kwargs self._altKey = False", "None # self.eventPhase = None # self.isTrusted = None # self.returnValue = None", "# self.currentTarget = None # self.eventPhase = None # self.isTrusted = None #", "offsetX Returns the horizontal coordinate of the mouse pointer relative to the position", "the last mousemove event MouseEvent # MovementY Returns the vertical coordinate of the", "def isComposing(self, *args, **kwargs): # pass # KeyboardEvent # isComposing Returns whether the", "function, useCapture: bool) -> None: def addEventListener(self, _type, callback, *args, **kwargs): if _type", "**kwargs) class BeforeUnloadEvent(Event): BEFOREUNLOAD = \"beforeunload\" #: \"\"\" BeforeUnloadEvent \"\"\" def __init__(self, _type,", "NotImplementedError def onpointercancel(self, event): print(event) raise NotImplementedError def onpointerdown(self, event): print(event) raise NotImplementedError", "NotImplementedError def onpointerover(self, event): print(event) raise NotImplementedError def onpointerup(self, event): print(event) raise NotImplementedError", "\"\"\" PageTransitionEvent \"\"\" PAGEHIDE = \"pagehide\" #: PAGESHOW = \"pageshow\" #: def __init__(self,", "self.altKey = None self.changedTouches = None self.ctrlKey = None self.metaKey = None self.shiftKey", "# self.addEventListener(DragEvent.END, self.ondragend) # self.addEventListener(DragEvent.ENTER, self.ondragenter) # self.addEventListener(DragEvent.EXIT, self.ondragexit) # self.addEventListener(DragEvent.LEAVE, self.ondragleave) #", "= \"keyup\" #: def __init__(self, _type, *args, **kwargs): # self.args = args #", "return stack = self.listeners[_type] for thing in stack: if thing == callback: stack.remove(thing)", "think where else would set it for thing in stack: try: thing(event) #", "self.listeners: return stack = self.listeners[_type] for thing in stack: if thing == callback:", "the horizontal coordinate of the mouse pointer, relative to the document, when the", "NotImplementedError def onformdata(self, event): print(event) raise NotImplementedError def onmousedown(self, event): print(event) raise NotImplementedError", "#: def __init__(self, _type, *args, **kwargs): self.deltaX = None self.deltaY = None self.deltaZ", "*args, **kwargs) class TouchEvent(Event): \"\"\" TouchEvent \"\"\" TOUCHCANCEL = \"touchcancel\" #: TOUCHEND =", "\"invalid\" #: LOAD = \"load\" #: LOADEDDATA = \"loadeddata\" #: LOADEDMETADATA = \"loadedmetadata\"", "None: def addEventListener(self, _type, callback, *args, **kwargs): if _type not in self.listeners: self.listeners[_type]", "self.canBubble = canBubble self.cancelable = cancelable self.view = view self.detail = detail self.screenX", "self.screenX = screenX self.screenY = screenY self._clientX = clientX self._clientY = clientY self._ctrlKey", "_type, callback): if _type not in self.listeners: return stack = self.listeners[_type] for thing", "def __init__(self, _type=None, *args, **kwargs): # print('type', _type) self.type = _type self.bubbles =", "_type, *args, **kwargs): super().__init__(_type, *args, **kwargs) class SVGEvent(Event): \"\"\" SVGEvent \"\"\" def __init__(self,", "class FocusEvent(Event): \"\"\" FocusEvent \"\"\" BLUR = \"blur\" #: FOCUS = \"focus\" #:", "# MOUSE_EVENT # getModifierState() Returns an array containing target ranges that will be", "\"\"\" ProgressEvent \"\"\" LOADSTART = \"loadstart\" #: def __init__(self, _type, *args, **kwargs): super().__init__(_type,", "LOADEDDATA = \"loadeddata\" #: LOADEDMETADATA = \"loadedmetadata\" #: MESSAGE = \"message\" #: OFFLINE", "clientY=0, ctrlKey=False, altKey=False, shiftKey=False, metaKey=False, button=None, relatedTarget=None, from_json={}, *args, **kwargs): # print('initMouseEvent') self._type", "*args, **kwargs): super().__init__(_type, *args, **kwargs) class SVGEvent(Event): \"\"\" SVGEvent \"\"\" def __init__(self, _type,", "TouchEvent(Event): \"\"\" TouchEvent \"\"\" TOUCHCANCEL = \"touchcancel\" #: TOUCHEND = \"touchend\" #: TOUCHMOVE", "without params, user may not create param return not event.defaultPrevented class Event(object): \"\"\"", "None self.changedTouches = None self.ctrlKey = None self.metaKey = None self.shiftKey = None", "= \"toggle\" #: UNLOAD = \"unload\" #: VOLUMECHANGE = \"volumechange\" #: WAITING =", "# @property # def key(self): # return self.key # def isComposing(self, *args, **kwargs):", "= shiftKey self._metaKey = metaKey self._button = button self.relatedTarget = relatedTarget # TODO", "here and get rid of this one? class EventDispatcher(object): \"\"\" EventDispatcher is a", "= args # self.kwargs = kwargs self.x = 0 self.y = 0 self._clientX", "def onpointerenter(self, event): print(event) raise NotImplementedError def onpointerleave(self, event): print(event) raise NotImplementedError def", "# getModifierState() Returns an array containing target ranges that will be affected by", "event: str, function, useCapture: bool) -> None: def addEventListener(self, _type, callback, *args, **kwargs):", "SHOW = \"show\" #: STALLED = \"stalled\" #: SUBMIT = \"submit\" #: SUSPEND", "that is dragged/dropped \"\"\" super().__init__(_type, *args, **kwargs) class HashChangeEvent(Event): \"\"\" HashChangeEvent \"\"\" CHANGE", "WHEEL = \"wheel\" #: def __init__(self, _type, *args, **kwargs): self.deltaX = None self.deltaY", "\"touchcancel\" #: TOUCHEND = \"touchend\" #: TOUCHMOVE = \"touchmove\" #: TOUCHSTART = \"touchstart\"", "*args, **kwargs): self.message = None # self.filename=None # self.lineno=0 # self.colno=0 # self.error={}", "= \"search\" #: SEEKED = \"seeked\" #: SEEKING = \"seeking\" #: SELECT =", "def onmousemove(self, event): print(event) raise NotImplementedError def onmouseout(self, event): print(event) raise NotImplementedError def", "= None # self.explicitOriginalTarget = None # self.target = None # self.srcElement =", "\"\"\" Returns the new value of the changed storage item \"\"\" self.oldValue =", "location Returns the location of a key on the keyboard or device KeyboardEvent", "print(event) raise NotImplementedError def onmouseover(self, event): print(event) raise NotImplementedError def onmouseup(self, event): print(event)", "GamePadEvent(Event): \"\"\" GamePadEvent \"\"\" START = \"gamepadconnected\" #: STOP = \"gamepaddisconnected\" #: def", "**kwargs): self.newURL = None self.oldURL = None super().__init__(_type, *args, **kwargs) class InputEvent(Event): \"\"\"", "self._altKey = altKey self._shiftKey = shiftKey self._metaKey = metaKey self._button = button self.relatedTarget", "of the animation \"\"\" self.elapsedTime = None \"\"\" Returns the number of seconds", "onmouseenter(self, event): print(event) raise NotImplementedError def onmouseleave(self, event): print(event) raise NotImplementedError def onmousemove(self,", "None \"\"\" Returns the number of seconds an animation has been running \"\"\"", "composing or not \"\"\" super().__init__(_type, *args, **kwargs) class PageTransitionEvent(Event): \"\"\" PageTransitionEvent \"\"\" PAGEHIDE", "charCode(self): # return self.charCode # @property # def code(self): # return self.code #", "the number of seconds a transition has been running \"\"\" self.pseudoElement = None", "def __init__(self, _type, *args, **kwargs): self.pointerId = None self.width = None self.height =", "affected by the insertion/deletion MouseEvent # MovementX Returns the horizontal coordinate of the", "MOUSEOVER = \"mouseover\" #: MOUSEOUT = \"mouseout\" #: MOUSEUP = \"mouseup\" #: def", "_type, *args, **kwargs): self.clipboardData = None \"\"\" Returns an object containing the data", "capturing and bubbling phases]\"\"\" # self.defaultPrevented = True # self.returnValue = None #", "\"touchend\" #: TOUCHMOVE = \"touchmove\" #: TOUCHSTART = \"touchstart\" #: def __init__(self, _type,", "\"paste\" #: def __init__(self, _type, *args, **kwargs): self.clipboardData = None \"\"\" Returns an", "super().__init__(_type, *args, **kwargs) class InputEvent(Event): \"\"\" InputEvent \"\"\" def __init__(self, _type, *args, **kwargs):", "print(event) raise NotImplementedError def ongotpointercapture(self, event): print(event) raise NotImplementedError def oninput(self, event): print(event)", "None \"\"\" Returns the inserted characters \"\"\" self.dataTransfer \"\"\" Returns an object containing", "\"cancelable\":false}); def __init__(self, _type=None, *args, **kwargs): # print('type', _type) self.type = _type self.bubbles", "*args, **kwargs): self.pointerId = None self.width = None self.height = None self.pressure =", "CompositionEvent(UIEvent): \"\"\" CompositionEvent \"\"\" START = \"compositionstart\" END = \"compositionend\" UPDATE = \"compositionupdate\"", "3.7 up self.timeStamp = int(round(time.time() * 1000)) def composedPath(self): return self.type + \":\"", "#: MESSAGE = \"message\" #: OFFLINE = \"offline\" #: ONLINE = \"online\" #:", "# self.addEventListener(DragEvent.EXIT, self.ondragexit) # self.addEventListener(DragEvent.LEAVE, self.ondragleave) # self.addEventListener(DragEvent.OVER, self.ondragover) # self.addEventListener(DragEvent.START, self.ondragstart) #", "#: PAGESHOW = \"pageshow\" #: def __init__(self, _type, *args, **kwargs): self.persisted = None", "KEYDOWN = \"keydown\" #: KEYPRESS = \"keypress\" #: KEYUP = \"keyup\" #: def", "self.cancelableArg = cancelableArg self.viewArg = viewArg self.charArg = charArg self.keyArg = keyArg self.locationArg", "# def addEventListener(self, event: str, function, useCapture: bool) -> None: def addEventListener(self, _type,", "@property # def charCode(self): # return self.charCode # @property # def code(self): #", "from_json={}, *args, **kwargs): # print('initMouseEvent') self._type = _type self.canBubble = canBubble self.cancelable =", "#: FOCUS = \"focus\" #: FOCUSIN = \"focusin\" #: FOCUSOUT = \"focusout\" #:", "= \"dragexit\" #: LEAVE = \"dragleave\" #: OVER = \"dragover\" #: START =", "**kwargs): self.deltaX = None self.deltaY = None self.deltaZ = None self.deltaMode = None", "self.currentTarget = None self.defaultPrevented = False self.eventPhase = None self.explicitOriginalTarget = None self.isTrusted", "# return self.charCode # @property # def code(self): # return self.code # @property", "useCapture: bool) -> None: def addEventListener(self, _type, callback, *args, **kwargs): if _type not", "# self.bubbles = None # self.cancelable = None # self.cancelBubble = None #", "raise NotImplementedError def onanimationend(self, event): print(event) raise NotImplementedError def onanimationiteration(self, event): print(event) raise", "self.onkeyup) # self.addEventListener(MouseEvent.MOUSEMOVE, self.onmousemove) # self.addEventListener(MouseEvent.MOUSEDOWN, self.onmousedown) # self.addEventListener(MouseEvent.MOUSEUP, self.onmouseup) # self.addEventListener(DragEvent.DRAG, self.ondrag)", "MouseEvent # region MouseEvent # relatedTarget Returns the element related to the element", "event): print(event) raise NotImplementedError def ontouchcancel(self, event): print(event) raise NotImplementedError def ontouchstart(self, event):", "= None \"\"\" Returns the name of the animation \"\"\" self.elapsedTime = None", "= \"mousedown\" #: MOUSEENTER = \"mouseenter\" #: MOUSELEAVE = \"mouseleave\" #: MOUSEMOVE =", "0 self._clientX = 0 self._clientX = 0 self._altKey = False self._ctrlKey = False", "**kwargs): self.pointerId = None self.width = None self.height = None self.pressure = None", "*args, **kwargs): if _type not in self.listeners: self.listeners[_type] = [] self.listeners[_type].append(callback) def removeEventListener(self,", "_type self.canBubble = canBubble self.cancelable = cancelable self.view = view self.detail = detail", "surely false? stack = self.listeners[event.type] # .slice() event.target = self # TODO/NOTE -", "self.source = source class GlobalEventHandler: # (EventDispatcher): # def __init__(self): # super().__init__(self) #", "removeEventListener(self, _type, callback): if _type not in self.listeners: return stack = self.listeners[_type] for", "element MouseEvent # pageX Returns the horizontal coordinate of the mouse pointer, relative", "\"progress\" #: RATECHANGE = \"ratechange\" #: RESIZE = \"resize\" #: RESET = \"reset\"", "# DEPRECATED - USE WHEEL #: WHEEL = \"wheel\" #: def __init__(self, _type,", "\"dragend\" #: ENTER = \"dragenter\" #: EXIT = \"dragexit\" #: LEAVE = \"dragleave\"", "print(event) raise NotImplementedError def onshow(self, event): print(event) raise NotImplementedError def onstalled(self, event): print(event)", "screenX=0, screenY=0, clientX=0, clientY=0, ctrlKey=False, altKey=False, shiftKey=False, metaKey=False, button=None, relatedTarget=None, from_json={}, *args, **kwargs):", "= args # self.kwargs = kwargs self._altKey = False self._ctrlKey = False self._shiftKey", "event): print(event) raise NotImplementedError def onformdata(self, event): print(event) raise NotImplementedError def onmousedown(self, event):", "onclose(self, event): print(event) raise NotImplementedError def oncontextmenu(self, event): print(event) raise NotImplementedError def oncuechange(self,", "def ondrag(self, event): print(event) raise NotImplementedError def ondragend(self, event): print(event) raise NotImplementedError def", "\"input\" #: INVALID = \"invalid\" #: LOAD = \"load\" #: LOADEDDATA = \"loadeddata\"", "data \"\"\" self.getTargetRanges \"\"\" Returns an array containing target ranges that will be", "\"\"\" GamePadEvent \"\"\" START = \"gamepadconnected\" #: STOP = \"gamepaddisconnected\" #: def __init__(self,", "the position of the last mousemove event MouseEvent # offsetX Returns the horizontal", "raise NotImplementedError def oncanplaythrough(self, event): print(event) raise NotImplementedError def onchange(self, event): print(event) raise", "self.charCode # @property # def code(self): # return self.code # @property # def", "may not create param return not event.defaultPrevented class Event(object): \"\"\" event \"\"\" EMPTIED", "*args, **kwargs) class SubmitEvent(Event): \"\"\" SubmitEvent \"\"\" SUBMIT = \"submit\" #: def __init__(self,", "(EventDispatcher): # def __init__(self): # super().__init__(self) # self.addEventListener(KeyboardEvent.KEYDOWN, self.onkeydown) # self.addEventListener(KeyboardEvent.KEYUP, self.onkeyup) #", "= \"stalled\" #: SUBMIT = \"submit\" #: SUSPEND = \"suspend\" #: TOGGLE =", "START = \"gamepadconnected\" #: STOP = \"gamepaddisconnected\" #: def __init__(self, _type, *args, **kwargs):", "TOUCHEND = \"touchend\" #: TOUCHMOVE = \"touchmove\" #: TOUCHSTART = \"touchstart\" #: def", "Event(object): \"\"\" event \"\"\" EMPTIED = \"emptied\" #: ABORT = \"abort\" #: AFTERPRINT", "the vertical coordinate of the mouse pointer, relative to the document, when the", "# self.returnValue = None # self.originalTarget = None # self.explicitOriginalTarget = None #", "TOGGLE = \"toggle\" #: UNLOAD = \"unload\" #: VOLUMECHANGE = \"volumechange\" #: WAITING", "= \"touchend\" #: TOUCHMOVE = \"touchmove\" #: TOUCHSTART = \"touchstart\" #: def __init__(self,", "0 self._altKey = False self._ctrlKey = False self._shiftKey = False self._metaKey = False", "#: MOUSEOVER = \"mouseover\" #: MOUSEOUT = \"mouseout\" #: MOUSEUP = \"mouseup\" #:", "\"seeked\" #: SEEKING = \"seeking\" #: SELECT = \"select\" #: SHOW = \"show\"", "args # self.kwargs = kwargs self.x = 0 self.y = 0 self._clientX =", "affected storage object \"\"\" self.url = None \"\"\" Returns the URL of the", "= None self.deltaZ = None self.deltaMode = None super().__init__(_type, *args, **kwargs) class AnimationEvent(Event):", "self.filename=None # self.lineno=0 # self.colno=0 # self.error={} super().__init__(_type, *args, **kwargs) class SubmitEvent(Event): \"\"\"", "__init__(self, _type, *args, **kwargs): self.detail = None self.view = None super().__init__(_type, *args, **kwargs)", "print(event) raise NotImplementedError def ondragexit(self, event): print(event) raise NotImplementedError def ondragleave(self, event): print(event)", "NotImplementedError def onstalled(self, event): print(event) raise NotImplementedError def onsubmit(self, event): print(event) raise NotImplementedError", "\"\"\" EMPTIED = \"emptied\" #: ABORT = \"abort\" #: AFTERPRINT = \"afterprint\" #:", "None self.width = None self.height = None self.pressure = None self.tangentialPressure = None", "pointer relative to the position of the last mousemove event MouseEvent # offsetX", "None # self.cancelable = None # self.cancelBubble = None # self.composed = None", "event): print(event) raise NotImplementedError def onpointermove(self, event): print(event) raise NotImplementedError def onpointerout(self, event):", "ondrop(self, event): print(event) raise NotImplementedError def ondurationchange(self, event): print(event) raise NotImplementedError def onemptied(self,", "self.metaKey = None self.shiftKey = None self.targetTouches = None self.touches = None super().__init__(_type,", "changed storage item \"\"\" self.oldValue = None \"\"\" Returns the old value of", "= \"timer\" #: \"\"\" TimerEvent \"\"\" def __init__(self, _type, *args, **kwargs): super().__init__(_type, *args,", "running \"\"\" self.pseudoElement = None \"\"\" Returns the name of the pseudo-element of", "raise NotImplementedError def ondragover(self, event): print(event) raise NotImplementedError def ondragstart(self, event): print(event) raise", "*args, **kwargs): self.newURL = None self.oldURL = None super().__init__(_type, *args, **kwargs) class InputEvent(Event):", "state of the event is composing or not \"\"\" super().__init__(_type, *args, **kwargs) class", "#: \"\"\" TimerEvent \"\"\" def __init__(self, _type, *args, **kwargs): super().__init__(_type, *args, **kwargs) class", "**kwargs): self.relatedTarget = None super().__init__(_type, *args, **kwargs) class TouchEvent(Event): \"\"\" TouchEvent \"\"\" TOUCHCANCEL", "self.onmouseup) # self.addEventListener(DragEvent.DRAG, self.ondrag) # self.addEventListener(DragEvent.END, self.ondragend) # self.addEventListener(DragEvent.ENTER, self.ondragenter) # self.addEventListener(DragEvent.EXIT, self.ondragexit)", "class MouseEvent(Event): \"\"\" mouse events \"\"\" CLICK = \"click\" #: CONTEXTMENU = \"contextmenu\"", "item \"\"\" self.storageArea = None \"\"\" Returns an object representing the affected storage", "self.ondragover) # self.addEventListener(DragEvent.START, self.ondragstart) # self.addEventListener(DragEvent.DROP, self.ondrop) # self.addEventListener(ClipboardEvent.CUT, self.oncut) # self.addEventListener(ClipboardEvent.COPY, self.oncopy)", "of the target element MouseEvent # offsetY Returns the vertical coordinate of the", "print('initMouseEvent') self._type = _type self.canBubble = canBubble self.cancelable = cancelable self.view = view", "super.__init__(self, type, bubbles, cancelable) super().__init__(_type) # TODO - self.source = source class GlobalEventHandler:", "print(event) raise NotImplementedError def onpointermove(self, event): print(event) raise NotImplementedError def onpointerout(self, event): print(event)", "None self._buttons = [] super().__init__(_type, *args, **kwargs) def initMouseEvent(self, _type=None, canBubble=True, cancelable=True, view=None,", "# Event(\"look\", {\"bubbles\":true, \"cancelable\":false}); def __init__(self, _type=None, *args, **kwargs): # print('type', _type) self.type", "changed storage item \"\"\" self.newValue = None \"\"\" Returns the new value of", "#: ANIMATIONSTART = \"animationstart\" #: def __init__(self, _type, *args, **kwargs): self.animationName = None", "CANPLAYTHROUGH = \"canplaythrough\" #: CHANGE = \"change\" #: DURATIONCHANGE = \"durationchange\" #: ENDED", "class ProgressEvent(Event): \"\"\" ProgressEvent \"\"\" LOADSTART = \"loadstart\" #: def __init__(self, _type, *args,", "self._source = source def __init__(self, _type, source=None, bubbles=False, cancelable=False): # super.__init__(self, type, bubbles,", "\"\"\" TweenEvent \"\"\" START = \"onStart\" #: STOP = \"onStop\" #: RESET =", "def onchange(self, event): print(event) raise NotImplementedError def onclick(self, event): print(event) raise NotImplementedError def", "raise NotImplementedError def onmouseleave(self, event): print(event) raise NotImplementedError def onmousemove(self, event): print(event) raise", "print(event) raise NotImplementedError def ondragstart(self, event): print(event) raise NotImplementedError def ondrop(self, event): print(event)", "raise NotImplementedError def onkeydown(self, event): print(event) raise NotImplementedError def onkeypress(self, event): print(event) raise", "super().__init__(_type, *args, **kwargs) class PointerEvent(Event): \"\"\" PointerEvent \"\"\" POINTER = \"pointer\" #: def", "that raised the event self.locale = None super().__init__(_type, *args, **kwargs) class FocusEvent(Event): \"\"\"", "self._ctrlKey @property def shiftKey(self): return self._shiftKey @property def metaKey(self): return self._metaKey @property def", "print(event) raise NotImplementedError def onsuspend(self, event): print(event) raise NotImplementedError def ontimeupdate(self, event): print(event)", "self._shiftKey = shiftKey self._metaKey = metaKey self._button = button self.relatedTarget = relatedTarget #", "- bring EventTarget here and get rid of this one? class EventDispatcher(object): \"\"\"", "containing a copy of the history entries \"\"\" super().__init__(_type, *args, **kwargs) class StorageEvent(Event):", "TouchEvent \"\"\" TOUCHCANCEL = \"touchcancel\" #: TOUCHEND = \"touchend\" #: TOUCHMOVE = \"touchmove\"", "# location Returns the location of a key on the keyboard or device", "NotImplementedError def onloadend(self, event): print(event) raise NotImplementedError def onloadstart(self, event): print(event) raise NotImplementedError", "END = \"compositionend\" UPDATE = \"compositionupdate\" def __init__(self, _type, *args, **kwargs): self.data =", "#: BEFOREUNLOAD = \"beforeunload\" #: CANPLAY = \"canplay\" #: CANPLAYTHROUGH = \"canplaythrough\" #:", "*args, **kwargs) class InputEvent(Event): \"\"\" InputEvent \"\"\" def __init__(self, _type, *args, **kwargs): self.data", "class InputEvent(Event): \"\"\" InputEvent \"\"\" def __init__(self, _type, *args, **kwargs): self.data = None", "False self._metaKey = False self._button = None self._buttons = [] super().__init__(_type, *args, **kwargs)", "* 1000)) def composedPath(self): return self.type + \":\" + str(self.timeStamp) def initEvent(self, _type=None,", "= None \"\"\" Returns the number of seconds an animation has been running", "event): print(event) raise NotImplementedError def ondragend(self, event): print(event) raise NotImplementedError def ondragenter(self, event):", "NotImplementedError def onselect(self, event): print(event) raise NotImplementedError def onselectionchange(self, event): print(event) raise NotImplementedError", "self.pseudoElement = None \"\"\" Returns the name of the pseudo-element of the animation", "BeforeUnloadEvent(Event): BEFOREUNLOAD = \"beforeunload\" #: \"\"\" BeforeUnloadEvent \"\"\" def __init__(self, _type, *args, **kwargs):", "#: \"\"\" BeforeUnloadEvent \"\"\" def __init__(self, _type, *args, **kwargs): super().__init__(_type, *args, **kwargs) class", "event MouseEvent # offsetX Returns the horizontal coordinate of the mouse pointer relative", "\"keypress\" #: KEYUP = \"keyup\" #: def __init__(self, _type, *args, **kwargs): # self.args", "StorageEvent \"\"\" def __init__(self, _type, *args, **kwargs): self.key = None \"\"\" Returns the", "# TODO - self.source = source class GlobalEventHandler: # (EventDispatcher): # def __init__(self):", "self.pointerType = None self.isPrimary = None super().__init__(_type, *args, **kwargs) class BeforeUnloadEvent(Event): BEFOREUNLOAD =", "NotImplementedError def onended(self, event): print(event) raise NotImplementedError def onerror(self, event): print(event) raise NotImplementedError", "self._shiftKey = False self._metaKey = False self._button = None self._buttons = [] super().__init__(_type,", "- so can relay @property def clientX(self): return self.x @property def clientY(self): return", "inserted characters \"\"\" self.dataTransfer \"\"\" Returns an object containing information about the inserted/deleted", "return not event.defaultPrevented class Event(object): \"\"\" event \"\"\" EMPTIED = \"emptied\" #: ABORT", "def __init__(self, _type, *args, **kwargs): self.detail = None super().__init__(_type, *args, **kwargs) def initCustomEvent(self):", "\"\"\" SubmitEvent \"\"\" SUBMIT = \"submit\" #: def __init__(self, _type, *args, **kwargs): super().__init__(_type,", "#: MOUSEOUT = \"mouseout\" #: MOUSEUP = \"mouseup\" #: def __init__(self, _type, *args,", "raise NotImplementedError def onerror(self, event): print(event) raise NotImplementedError def onfocus(self, event): print(event) raise", "give your obj event dispatching abilities \"\"\" def __init__(self, *args, **kwargs): self.listeners =", "= \"focusin\" #: FOCUSOUT = \"focusout\" #: def __init__(self, _type, *args, **kwargs): self.relatedTarget", "this one? class EventDispatcher(object): \"\"\" EventDispatcher is a class you can extend to", "= \"paste\" #: def __init__(self, _type, *args, **kwargs): self.clipboardData = None \"\"\" Returns", "raise NotImplementedError def ontouchstart(self, event): print(event) raise NotImplementedError def ontransitioncancel(self, event): print(event) raise", "BEFOREPRINT = \"beforeprint\" #: BEFOREUNLOAD = \"beforeunload\" #: CANPLAY = \"canplay\" #: CANPLAYTHROUGH", "- event: str, function, useCapture: bool # def addEventListener(self, event: str, function, useCapture:", "self.type = _type self.bubbles = None self.cancelable = None self.cancelBubble = None self.composed", "__init__(self, _type, *args, **kwargs): super().__init__(_type, *args, **kwargs) class PointerEvent(Event): \"\"\" PointerEvent \"\"\" POINTER", "event is composing or not InputEvent, KeyboardEvent # repeat Returns whether a key", "event): print(event) raise NotImplementedError def onloadend(self, event): print(event) raise NotImplementedError def onloadstart(self, event):", "is this correct? - cant think where else would set it for thing", "self.modifiersListArg = modifiersListArg self.repeat = repeat @property def altKey(self): return self._altKey @property def", "(Event,), self) except Exception as e: print(e) thing() # try calling without params,", "# self.addEventListener(ClipboardEvent.PASTE, self.onpaste) def onabort(self, event): print(event) raise NotImplementedError def onblur(self, event): print(event)", "def __init__(self, _type, *args, **kwargs): self.propertyName = None \"\"\" Returns the name of", "print(event) raise NotImplementedError def onloadeddata(self, event): print(event) raise NotImplementedError def onloadedmetadata(self, event): print(event)", "onchange(self, event): print(event) raise NotImplementedError def onclick(self, event): print(event) raise NotImplementedError def onclose(self,", "NotImplementedError def onsuspend(self, event): print(event) raise NotImplementedError def ontimeupdate(self, event): print(event) raise NotImplementedError", "super().__init__(_type) # TODO - self.source = source class GlobalEventHandler: # (EventDispatcher): # def", "NotImplementedError def onpause(self, event): print(event) raise NotImplementedError def onplay(self, event): print(event) raise NotImplementedError", "raise NotImplementedError def onstalled(self, event): print(event) raise NotImplementedError def onsubmit(self, event): print(event) raise", "\"\"\" TOUCHCANCEL = \"touchcancel\" #: TOUCHEND = \"touchend\" #: TOUCHMOVE = \"touchmove\" #:", "abilities \"\"\" def __init__(self, *args, **kwargs): self.listeners = {} def hasEventListener(self, _type): return", "cant think where else would set it for thing in stack: try: thing(event)", "\"mouseout\" #: MOUSEUP = \"mouseup\" #: def __init__(self, _type, *args, **kwargs): # self.args", "#: PASTE = \"paste\" #: def __init__(self, _type, *args, **kwargs): self.clipboardData = None", "self.gamepad = None super().__init__(_type, *args, **kwargs) class TweenEvent(Event): \"\"\" TweenEvent \"\"\" START =", "None self.deltaMode = None super().__init__(_type, *args, **kwargs) class AnimationEvent(Event): \"\"\" AnimationEvent \"\"\" ANIMATIONEND", "_type, *args, **kwargs): self.newURL = None self.oldURL = None super().__init__(_type, *args, **kwargs) class", "= \"mouseout\" #: MOUSEUP = \"mouseup\" #: def __init__(self, _type, *args, **kwargs): #", "altKey self._shiftKey = shiftKey self._metaKey = metaKey self._button = button self.relatedTarget = relatedTarget", "of the changed storage item \"\"\" self.storageArea = None \"\"\" Returns an object", "if thing == callback: stack.remove(thing) return def dispatchEvent(self, event): if event.type not in", "\"\"\" MOUSEWHEEL = \"mousewheel\" # DEPRECATED - USE WHEEL #: WHEEL = \"wheel\"", "NotImplementedError def onplay(self, event): print(event) raise NotImplementedError def onplaying(self, event): print(event) raise NotImplementedError", "NotImplementedError def onblur(self, event): print(event) raise NotImplementedError def oncancel(self, event): print(event) raise NotImplementedError", "def source(self): return self._source @source.setter def source(self, source): self._source = source def __init__(self,", "print(event) raise NotImplementedError def onseeking(self, event): print(event) raise NotImplementedError def onselect(self, event): print(event)", "# self.addEventListener(MouseEvent.MOUSEMOVE, self.onmousemove) # self.addEventListener(MouseEvent.MOUSEDOWN, self.onmousedown) # self.addEventListener(MouseEvent.MOUSEUP, self.onmouseup) # self.addEventListener(DragEvent.DRAG, self.ondrag) #", "self._metaKey = False self._button = None self._buttons = [] super().__init__(_type, *args, **kwargs) def", "@property def shiftKey(self): return self._shiftKey @property def metaKey(self): return self._metaKey @property def button(self):", "return def dispatchEvent(self, event): if event.type not in self.listeners: return True # huh?.", "_type, *args, **kwargs): self.animationName = None \"\"\" Returns the name of the animation", "relative to the document, when the mouse event was triggered MouseEvent # region", "def ontouchcancel(self, event): print(event) raise NotImplementedError def ontouchstart(self, event): print(event) raise NotImplementedError def", "= None self.explicitOriginalTarget = None self.isTrusted = None self.originalTarget = None self.returnValue =", "Returns an object containing a copy of the history entries \"\"\" super().__init__(_type, *args,", "the target element MouseEvent # pageX Returns the horizontal coordinate of the mouse", "self.error={} super().__init__(_type, *args, **kwargs) class SubmitEvent(Event): \"\"\" SubmitEvent \"\"\" SUBMIT = \"submit\" #:", "def buttons(self): return self._buttons @property def which(self): return self._button # MOUSE_EVENT # getModifierState()", "event): print(event) raise NotImplementedError def onmousemove(self, event): print(event) raise NotImplementedError def onmouseout(self, event):", "def oncanplaythrough(self, event): print(event) raise NotImplementedError def onchange(self, event): print(event) raise NotImplementedError def", "= \"playing\" #: PROGRESS = \"progress\" #: RATECHANGE = \"ratechange\" #: RESIZE =", "#: PAUSE = \"pause\" #: PLAY = \"play\" #: PLAYING = \"playing\" #:", "= \"abort\" #: AFTERPRINT = \"afterprint\" #: BEFOREPRINT = \"beforeprint\" #: BEFOREUNLOAD =", "event): print(event) raise NotImplementedError def onfocus(self, event): print(event) raise NotImplementedError def ongotpointercapture(self, event):", "**kwargs) class DragEvent(Event): \"\"\" DragEvent \"\"\" DRAG = \"drag\" #: END = \"dragend\"", "NotImplementedError def ondrop(self, event): print(event) raise NotImplementedError def ondurationchange(self, event): print(event) raise NotImplementedError", "**kwargs): self.propertyName = None \"\"\" Returns the name of the transition\"\"\" self.elapsedTime =", "[] self.listeners[_type].append(callback) def removeEventListener(self, _type, callback): if _type not in self.listeners: return stack", "self._button # MOUSE_EVENT # getModifierState() Returns an array containing target ranges that will", "STALLED = \"stalled\" #: SUBMIT = \"submit\" #: SUSPEND = \"suspend\" #: TOGGLE", "**kwargs) class TimerEvent(Event): TIMER = \"timer\" #: \"\"\" TimerEvent \"\"\" def __init__(self, _type,", "TODO - self.source = source class GlobalEventHandler: # (EventDispatcher): # def __init__(self): #", "def __init__(self, _type, *args, **kwargs): self.dataTransfer = None \"\"\" Returns the data that", "self.kwargs = kwargs self.x = 0 self.y = 0 self._clientX = 0 self._clientX", "__init__(self, _type, *args, **kwargs): self.gamepad = None super().__init__(_type, *args, **kwargs) class TweenEvent(Event): \"\"\"", "MouseEvent(Event): \"\"\" mouse events \"\"\" CLICK = \"click\" #: CONTEXTMENU = \"contextmenu\" #:", "= self.listeners[event.type] # .slice() event.target = self # TODO/NOTE - is this correct?", "# self.addEventListener(KeyboardEvent.KEYUP, self.onkeyup) # self.addEventListener(MouseEvent.MOUSEMOVE, self.onmousemove) # self.addEventListener(MouseEvent.MOUSEDOWN, self.onmousedown) # self.addEventListener(MouseEvent.MOUSEUP, self.onmouseup) #", "#: MOUSELEAVE = \"mouseleave\" #: MOUSEMOVE = \"mousemove\" #: MOUSEOVER = \"mouseover\" #:", "print(event) raise NotImplementedError def onloadend(self, event): print(event) raise NotImplementedError def onloadstart(self, event): print(event)", "ondragenter(self, event): print(event) raise NotImplementedError def ondragexit(self, event): print(event) raise NotImplementedError def ondragleave(self,", "\"compositionend\" UPDATE = \"compositionupdate\" def __init__(self, _type, *args, **kwargs): self.data = None #:", "_type): return _type in self.listeners # TODO - event: str, function, useCapture: bool", "self.onpaste) def onabort(self, event): print(event) raise NotImplementedError def onblur(self, event): print(event) raise NotImplementedError", "else would set it for thing in stack: try: thing(event) # type(thing, (Event,),", "= kwargs self._altKey = False self._ctrlKey = False self._shiftKey = False self._metaKey =", "#: PLAY = \"play\" #: PLAYING = \"playing\" #: PROGRESS = \"progress\" #:", "ONLINE = \"online\" #: OPEN = \"open\" #: PAUSE = \"pause\" #: PLAY", "to the position of the last mousemove event MouseEvent # MovementY Returns the", "\"\"\" keyboard events \"\"\" KEYDOWN = \"keydown\" #: KEYPRESS = \"keypress\" #: KEYUP", "SVGEvent(Event): \"\"\" SVGEvent \"\"\" def __init__(self, _type, *args, **kwargs): super().__init__(_type, *args, **kwargs) class", "def metaKey(self): return self._metaKey @property def unicode(self): return self.key # @property # def", "*args, **kwargs) class PopStateEvent(Event): \"\"\" PopStateEvent \"\"\" def __init__(self, _type, *args, **kwargs): self.state", "@property # def code(self): # return self.code # @property # def key(self): #", "super().__init__(_type, *args, **kwargs) def initMouseEvent(self, _type=None, canBubble=True, cancelable=True, view=None, detail=None, screenX=0, screenY=0, clientX=0,", "self.newValue = None \"\"\" Returns the new value of the changed storage item", "time # TODO - bring EventTarget here and get rid of this one?", "= metaKey self._button = button self.relatedTarget = relatedTarget # TODO - parse from_json", "and get rid of this one? class EventDispatcher(object): \"\"\" EventDispatcher is a class", "key(self): # return self.key # def isComposing(self, *args, **kwargs): # pass # KeyboardEvent", "addEventListener(self, event: str, function, useCapture: bool) -> None: def addEventListener(self, _type, callback, *args,", "#: AFTERPRINT = \"afterprint\" #: BEFOREPRINT = \"beforeprint\" #: BEFOREUNLOAD = \"beforeunload\" #:", "of the edge of the target element MouseEvent # pageX Returns the horizontal", "characters generated by the input method that raised the event self.locale = None", "self.srcElement = None # self.bubbles = None # self.cancelable = None # self.cancelBubble", "the characters generated by the input method that raised the event self.locale =", "event): print(event) raise NotImplementedError def onmouseup(self, event): print(event) raise NotImplementedError def onpause(self, event):", "offsetY Returns the vertical coordinate of the mouse pointer relative to the position", "# repeat Returns whether a key is being hold down repeatedly, or not", "onloadend(self, event): print(event) raise NotImplementedError def onloadstart(self, event): print(event) raise NotImplementedError def onlostpointercapture(self,", "def onload(self, event): print(event) raise NotImplementedError def onloadeddata(self, event): print(event) raise NotImplementedError def", "__init__(self, _type, *args, **kwargs): self.animationName = None \"\"\" Returns the name of the", "def ontouchstart(self, event): print(event) raise NotImplementedError def ontransitioncancel(self, event): print(event) raise NotImplementedError def", "_type, *args, **kwargs): self.key = None \"\"\" Returns the key of the changed", "NotImplementedError def onfocus(self, event): print(event) raise NotImplementedError def ongotpointercapture(self, event): print(event) raise NotImplementedError", "= \"waiting\" #: # Event(\"look\", {\"bubbles\":true, \"cancelable\":false}); def __init__(self, _type=None, *args, **kwargs): #", "= \"pageshow\" #: def __init__(self, _type, *args, **kwargs): self.persisted = None \"\"\" Returns", "self._shiftKey = False self._metaKey = False self.charCode = None self.code = None self.key", "def __init__(self, _type, *args, **kwargs): self.data = None \"\"\" Returns the inserted characters", "# (EventDispatcher): # def __init__(self): # super().__init__(self) # self.addEventListener(KeyboardEvent.KEYDOWN, self.onkeydown) # self.addEventListener(KeyboardEvent.KEYUP, self.onkeyup)", "def composedPath(self): return self.type + \":\" + str(self.timeStamp) def initEvent(self, _type=None, *args, **kwargs):", "triggered MouseEvent # region MouseEvent # relatedTarget Returns the element related to the", "INPUT = \"input\" #: INVALID = \"invalid\" #: LOAD = \"load\" #: LOADEDDATA", "to the document, when the mouse event was triggered MouseEvent # pageY Returns", "hold down repeatedly, or not KeyboardEvent # location Returns the location of a", "raise NotImplementedError def onplay(self, event): print(event) raise NotImplementedError def onplaying(self, event): print(event) raise", "MouseEvent # offsetY Returns the vertical coordinate of the mouse pointer relative to", "= button self.relatedTarget = relatedTarget # TODO - parse from_json - so can", "\"pageshow\" #: def __init__(self, _type, *args, **kwargs): self.persisted = None \"\"\" Returns whether", "onanimationiteration(self, event): print(event) raise NotImplementedError def onauxclick(self, event): print(event) raise NotImplementedError def onformdata(self,", "None # self.cancelBubble = None # self.composed = None # self.currentTarget = None", "EXIT = \"dragexit\" #: LEAVE = \"dragleave\" #: OVER = \"dragover\" #: START", "\"load\" #: LOADEDDATA = \"loadeddata\" #: LOADEDMETADATA = \"loadedmetadata\" #: MESSAGE = \"message\"", "**kwargs): self.state = None \"\"\" Returns an object containing a copy of the", "*args, **kwargs): super().__init__(_type, *args, **kwargs) class CustomEvent(Event): \"\"\" CustomEvent \"\"\" def __init__(self, _type,", "SUBMIT = \"submit\" #: SUSPEND = \"suspend\" #: TOGGLE = \"toggle\" #: UNLOAD", "storage item \"\"\" self.oldValue = None \"\"\" Returns the old value of the", "pass class GamePadEvent(Event): \"\"\" GamePadEvent \"\"\" START = \"gamepadconnected\" #: STOP = \"gamepaddisconnected\"", "when the mouse event was triggered MouseEvent # region MouseEvent # relatedTarget Returns", "#: START = \"dragstart\" #: DROP = \"drop\" #: def __init__(self, _type, *args,", "None super().__init__(_type, *args, **kwargs) class TouchEvent(Event): \"\"\" TouchEvent \"\"\" TOUCHCANCEL = \"touchcancel\" #:", "\"\"\" def __init__(self, *args, **kwargs): self.listeners = {} def hasEventListener(self, _type): return _type", "mouse events \"\"\" CLICK = \"click\" #: CONTEXTMENU = \"contextmenu\" #: DBLCLICK =", "= cancelable self.view = view self.detail = detail self.screenX = screenX self.screenY =", "\"\"\" Returns an array containing target ranges that will be affected by the", "_type, *args, **kwargs): self.data = None #: Returns the characters generated by the", "the input method that raised the event self.locale = None super().__init__(_type, *args, **kwargs)", "oncanplaythrough(self, event): print(event) raise NotImplementedError def onchange(self, event): print(event) raise NotImplementedError def onclick(self,", "= \"cut\" #: PASTE = \"paste\" #: def __init__(self, _type, *args, **kwargs): self.clipboardData", "= False self._metaKey = False self._button = None self._buttons = [] super().__init__(_type, *args,", "None # ms = time.time_ns() // 1000000 3.7 up self.timeStamp = int(round(time.time() *", "*args, **kwargs) def initKeyboardEvent(self, typeArg, canBubbleArg, cancelableArg, viewArg, charArg, keyArg, locationArg, modifiersListArg, repeat):", "\"beforeunload\" #: \"\"\" BeforeUnloadEvent \"\"\" def __init__(self, _type, *args, **kwargs): super().__init__(_type, *args, **kwargs)", "def onkeydown(self, event): print(event) raise NotImplementedError def onkeypress(self, event): print(event) raise NotImplementedError def", "self # TODO/NOTE - is this correct? - cant think where else would", "**kwargs) def initMouseEvent(self, _type=None, canBubble=True, cancelable=True, view=None, detail=None, screenX=0, screenY=0, clientX=0, clientY=0, ctrlKey=False,", "ongotpointercapture(self, event): print(event) raise NotImplementedError def oninput(self, event): print(event) raise NotImplementedError def oninvalid(self,", "DBLCLICK = \"dblclick\" #: MOUSEDOWN = \"mousedown\" #: MOUSEENTER = \"mouseenter\" #: MOUSELEAVE", "None self.target = None # ms = time.time_ns() // 1000000 3.7 up self.timeStamp", "the data affected by the clipboard operation \"\"\" super().__init__(_type, *args, **kwargs) class ErrorEvent(Event):", "WAITING = \"waiting\" #: # Event(\"look\", {\"bubbles\":true, \"cancelable\":false}); def __init__(self, _type=None, *args, **kwargs):", "class PointerEvent(Event): \"\"\" PointerEvent \"\"\" POINTER = \"pointer\" #: def __init__(self, _type, *args,", "print(event) raise NotImplementedError def ontimeupdate(self, event): print(event) raise NotImplementedError def onvolumechange(self, event): print(event)", "= \"onUpdateStart\" #: UPDATE_END = \"onUpdateEnd\" #: COMPLETE = \"onComplete\" #: TIMER =", "*args, **kwargs): self.listeners = {} def hasEventListener(self, _type): return _type in self.listeners #", "not in self.listeners: return stack = self.listeners[_type] for thing in stack: if thing", "self.ondragend) # self.addEventListener(DragEvent.ENTER, self.ondragenter) # self.addEventListener(DragEvent.EXIT, self.ondragexit) # self.addEventListener(DragEvent.LEAVE, self.ondragleave) # self.addEventListener(DragEvent.OVER, self.ondragover)", "event): print(event) raise NotImplementedError def ondragover(self, event): print(event) raise NotImplementedError def ondragstart(self, event):", "\"pagehide\" #: PAGESHOW = \"pageshow\" #: def __init__(self, _type, *args, **kwargs): self.persisted =", "# def key(self): # return self.key # def isComposing(self, *args, **kwargs): # pass", "*args, **kwargs) class TransitionEvent(Event): \"\"\" TransitionEvent \"\"\" TRANSITIONEND = \"transitionend\" #: def __init__(self,", "None self.pointerType = None self.isPrimary = None super().__init__(_type, *args, **kwargs) class BeforeUnloadEvent(Event): BEFOREUNLOAD", "{} def hasEventListener(self, _type): return _type in self.listeners # TODO - event: str,", "event): print(event) raise NotImplementedError def onerror(self, event): print(event) raise NotImplementedError def onfocus(self, event):", "None self.targetTouches = None self.touches = None super().__init__(_type, *args, **kwargs) class WheelEvent(Event): \"\"\"", "onmouseleave(self, event): print(event) raise NotImplementedError def onmousemove(self, event): print(event) raise NotImplementedError def onmouseout(self,", "WheelEvent(Event): \"\"\" WheelEvent \"\"\" MOUSEWHEEL = \"mousewheel\" # DEPRECATED - USE WHEEL #:", "parse from_json - so can relay @property def clientX(self): return self.x @property def", "#: CHANGE = \"change\" #: DURATIONCHANGE = \"durationchange\" #: ENDED = \"ended\" #:", "self.twist = None self.pointerType = None self.isPrimary = None super().__init__(_type, *args, **kwargs) class", "= 0 self._altKey = False self._ctrlKey = False self._shiftKey = False self._metaKey =", "onabort(self, event): print(event) raise NotImplementedError def onblur(self, event): print(event) raise NotImplementedError def oncancel(self,", "code(self): # return self.code # @property # def key(self): # return self.key #", "None self.code = None self.key = None self.keyCode = None super().__init__(_type, *args, **kwargs)", "*args, **kwargs) class PointerEvent(Event): \"\"\" PointerEvent \"\"\" POINTER = \"pointer\" #: def __init__(self,", "NotImplementedError def onemptied(self, event): print(event) raise NotImplementedError def onended(self, event): print(event) raise NotImplementedError", "to the element that triggered the mouse event MouseEvent, FocusEvent class KeyboardEvent(Event): \"\"\"", "= \"beforeprint\" #: BEFOREUNLOAD = \"beforeunload\" #: CANPLAY = \"canplay\" #: CANPLAYTHROUGH =", "= \"touchstart\" #: def __init__(self, _type, *args, **kwargs): self.shiftKey = None self.altKey =", "0 self.y = 0 self._clientX = 0 self._clientX = 0 self._altKey = False", "raise NotImplementedError def onload(self, event): print(event) raise NotImplementedError def onloadeddata(self, event): print(event) raise", "**kwargs): self.data = None \"\"\" Returns the inserted characters \"\"\" self.dataTransfer \"\"\" Returns", "old value of the changed storage item \"\"\" self.storageArea = None \"\"\" Returns", "def __init__(self, _type, *args, **kwargs): self.detail = None self.view = None super().__init__(_type, *args,", "\"gamepaddisconnected\" #: def __init__(self, _type, *args, **kwargs): self.gamepad = None super().__init__(_type, *args, **kwargs)", "# self.isTrusted = None # self.returnValue = None # self.timeStamp = int(round(time.time() *", "that will be affected by the insertion/deletion \"\"\" self.inputType \"\"\" Returns the type", "super().__init__(_type, *args, **kwargs) class BeforeUnloadEvent(Event): BEFOREUNLOAD = \"beforeunload\" #: \"\"\" BeforeUnloadEvent \"\"\" def", "self.srcElement = None self.target = None # ms = time.time_ns() // 1000000 3.7", "= \"onStart\" #: STOP = \"onStop\" #: RESET = \"onReset\" #: PAUSE =", "the browser \"\"\" super().__init__(_type, *args, **kwargs) class PopStateEvent(Event): \"\"\" PopStateEvent \"\"\" def __init__(self,", "def msConvertURL(self): pass def preventDefault(self): pass def stopImmediatePropagation(self): pass class MouseEvent(Event): \"\"\" mouse", "\"\"\" Returns the old value of the changed storage item \"\"\" self.storageArea =", "edge of the target element MouseEvent # pageX Returns the horizontal coordinate of", "**kwargs) class InputEvent(Event): \"\"\" InputEvent \"\"\" def __init__(self, _type, *args, **kwargs): self.data =", "function, useCapture: bool # def addEventListener(self, event: str, function, useCapture: bool) -> None:", "def onwheel(self, event): print(event) raise NotImplementedError def onanimationcancel(self, event): print(event) raise NotImplementedError def", "initMouseEvent(self, _type=None, canBubble=True, cancelable=True, view=None, detail=None, screenX=0, screenY=0, clientX=0, clientY=0, ctrlKey=False, altKey=False, shiftKey=False,", "event): print(event) raise NotImplementedError def ondragleave(self, event): print(event) raise NotImplementedError def ondragover(self, event):", "element related to the element that triggered the mouse event MouseEvent, FocusEvent class", "-> None: def addEventListener(self, _type, callback, *args, **kwargs): if _type not in self.listeners:", "super().__init__(_type, *args, **kwargs) class HashChangeEvent(Event): \"\"\" HashChangeEvent \"\"\" CHANGE = \"hashchange\" #: def", "# self.originalTarget = None # self.explicitOriginalTarget = None # self.target = None #", "raise NotImplementedError def onblur(self, event): print(event) raise NotImplementedError def oncancel(self, event): print(event) raise", "\"\"\"[prevents further propagation of the current event in the capturing and bubbling phases]\"\"\"", "self.changedTouches = None self.ctrlKey = None self.metaKey = None self.shiftKey = None self.targetTouches", "\"\"\" SUBMIT = \"submit\" #: def __init__(self, _type, *args, **kwargs): super().__init__(_type, *args, **kwargs)", "raise NotImplementedError def ondragenter(self, event): print(event) raise NotImplementedError def ondragexit(self, event): print(event) raise", "= False self._metaKey = False self.charCode = None self.code = None self.key =", "key of the changed storage item \"\"\" self.newValue = None \"\"\" Returns the", "__init__(self, _type, *args, **kwargs): self.propertyName = None \"\"\" Returns the name of the", "user may not create param return not event.defaultPrevented class Event(object): \"\"\" event \"\"\"", "the key of the changed storage item \"\"\" self.newValue = None \"\"\" Returns", "class SVGEvent(Event): \"\"\" SVGEvent \"\"\" def __init__(self, _type, *args, **kwargs): super().__init__(_type, *args, **kwargs)", "*args, **kwargs) class BeforeUnloadEvent(Event): BEFOREUNLOAD = \"beforeunload\" #: \"\"\" BeforeUnloadEvent \"\"\" def __init__(self,", "= \"gamepadconnected\" #: STOP = \"gamepaddisconnected\" #: def __init__(self, _type, *args, **kwargs): self.gamepad", "**kwargs): super().__init__(_type, *args, **kwargs) class CustomEvent(Event): \"\"\" CustomEvent \"\"\" def __init__(self, _type, *args,", "event is composing or not \"\"\" super().__init__(_type, *args, **kwargs) class PageTransitionEvent(Event): \"\"\" PageTransitionEvent", "event): print(event) raise NotImplementedError def onemptied(self, event): print(event) raise NotImplementedError def onended(self, event):", "super().__init__(_type, *args, **kwargs) class TransitionEvent(Event): \"\"\" TransitionEvent \"\"\" TRANSITIONEND = \"transitionend\" #: def", "# self.explicitOriginalTarget = None # self.target = None # self.srcElement = None #", "PageTransitionEvent \"\"\" PAGEHIDE = \"pagehide\" #: PAGESHOW = \"pageshow\" #: def __init__(self, _type,", "def oncanplay(self, event): print(event) raise NotImplementedError def oncanplaythrough(self, event): print(event) raise NotImplementedError def", "self.addEventListener(DragEvent.DROP, self.ondrop) # self.addEventListener(ClipboardEvent.CUT, self.oncut) # self.addEventListener(ClipboardEvent.COPY, self.oncopy) # self.addEventListener(ClipboardEvent.PASTE, self.onpaste) def onabort(self,", "event): print(event) raise NotImplementedError def onpointerover(self, event): print(event) raise NotImplementedError def onpointerup(self, event):", "e: print(e) thing() # try calling without params, user may not create param", "clientX self._clientY = clientY self._ctrlKey = ctrlKey self._altKey = altKey self._shiftKey = shiftKey", "= \"compositionupdate\" def __init__(self, _type, *args, **kwargs): self.data = None #: Returns the", "self.onmousedown) # self.addEventListener(MouseEvent.MOUSEUP, self.onmouseup) # self.addEventListener(DragEvent.DRAG, self.ondrag) # self.addEventListener(DragEvent.END, self.ondragend) # self.addEventListener(DragEvent.ENTER, self.ondragenter)", "None \"\"\" Returns the name of the pseudo-element of the transition \"\"\" super().__init__(_type,", "# self.srcElement = None # self.bubbles = None # self.cancelable = None #", "print(event) raise NotImplementedError def onseeked(self, event): print(event) raise NotImplementedError def onseeking(self, event): print(event)", "ANIMATIONSTART = \"animationstart\" #: def __init__(self, _type, *args, **kwargs): self.animationName = None \"\"\"", "START = \"dragstart\" #: DROP = \"drop\" #: def __init__(self, _type, *args, **kwargs):", "the name of the pseudo-element of the transition \"\"\" super().__init__(_type, *args, **kwargs) class", "event): print(event) raise NotImplementedError def ondrag(self, event): print(event) raise NotImplementedError def ondragend(self, event):", "**kwargs): super().__init__(_type, *args, **kwargs) class DragEvent(Event): \"\"\" DragEvent \"\"\" DRAG = \"drag\" #:", "onpointerdown(self, event): print(event) raise NotImplementedError def onpointerenter(self, event): print(event) raise NotImplementedError def onpointerleave(self,", "self.listeners[_type].append(callback) def removeEventListener(self, _type, callback): if _type not in self.listeners: return stack =", "affected by the clipboard operation \"\"\" super().__init__(_type, *args, **kwargs) class ErrorEvent(Event): \"\"\" ErrorEvent", "\"\"\" TimerEvent \"\"\" def __init__(self, _type, *args, **kwargs): super().__init__(_type, *args, **kwargs) class DragEvent(Event):", "raise NotImplementedError def onauxclick(self, event): print(event) raise NotImplementedError def onformdata(self, event): print(event) raise", "event): print(event) raise NotImplementedError def oninput(self, event): print(event) raise NotImplementedError def oninvalid(self, event):", "self.eventPhase = None # self.isTrusted = None # self.returnValue = None # self.timeStamp", "# self.cancelable = None # self.cancelBubble = None # self.composed = None #", "**kwargs): # self.args = args # self.kwargs = kwargs self._altKey = False self._ctrlKey", "**kwargs): super().__init__(_type, *args, **kwargs) class SVGEvent(Event): \"\"\" SVGEvent \"\"\" def __init__(self, _type, *args,", "Returns the name of the pseudo-element of the animation \"\"\" super().__init__(_type, *args, **kwargs)", "onsuspend(self, event): print(event) raise NotImplementedError def ontimeupdate(self, event): print(event) raise NotImplementedError def onvolumechange(self,", "self.animationName = None \"\"\" Returns the name of the animation \"\"\" self.elapsedTime =", "SUSPEND = \"suspend\" #: TOGGLE = \"toggle\" #: UNLOAD = \"unload\" #: VOLUMECHANGE", "\"canplay\" #: CANPLAYTHROUGH = \"canplaythrough\" #: CHANGE = \"change\" #: DURATIONCHANGE = \"durationchange\"", "class TimerEvent(Event): TIMER = \"timer\" #: \"\"\" TimerEvent \"\"\" def __init__(self, _type, *args,", "super().__init__(_type, *args, **kwargs) class TouchEvent(Event): \"\"\" TouchEvent \"\"\" TOUCHCANCEL = \"touchcancel\" #: TOUCHEND", "Returns the name of the pseudo-element of the transition \"\"\" super().__init__(_type, *args, **kwargs)", "be affected by the insertion/deletion \"\"\" self.inputType \"\"\" Returns the type of the", "__init__(self, _type, *args, **kwargs): self.key = None \"\"\" Returns the key of the", "raise NotImplementedError def onmousemove(self, event): print(event) raise NotImplementedError def onmouseout(self, event): print(event) raise", "= [] self.listeners[_type].append(callback) def removeEventListener(self, _type, callback): if _type not in self.listeners: return", "copy of the history entries \"\"\" super().__init__(_type, *args, **kwargs) class StorageEvent(Event): \"\"\" StorageEvent", "def __init__(self, _type, *args, **kwargs): self.gamepad = None super().__init__(_type, *args, **kwargs) class TweenEvent(Event):", "self.viewArg = viewArg self.charArg = charArg self.keyArg = keyArg self.locationArg = locationArg self.modifiersListArg", "stack = self.listeners[event.type] # .slice() event.target = self # TODO/NOTE - is this", "#: FOCUSIN = \"focusin\" #: FOCUSOUT = \"focusout\" #: def __init__(self, _type, *args,", "onplaying(self, event): print(event) raise NotImplementedError def onpointercancel(self, event): print(event) raise NotImplementedError def onpointerdown(self,", "NotImplementedError def ontransitioncancel(self, event): print(event) raise NotImplementedError def ontransitionend(self, event): print(event) raise NotImplementedError", "\"contextmenu\" #: DBLCLICK = \"dblclick\" #: MOUSEDOWN = \"mousedown\" #: MOUSEENTER = \"mouseenter\"", "self.ondragexit) # self.addEventListener(DragEvent.LEAVE, self.ondragleave) # self.addEventListener(DragEvent.OVER, self.ondragover) # self.addEventListener(DragEvent.START, self.ondragstart) # self.addEventListener(DragEvent.DROP, self.ondrop)", "def onsuspend(self, event): print(event) raise NotImplementedError def ontimeupdate(self, event): print(event) raise NotImplementedError def", "def onselectionchange(self, event): print(event) raise NotImplementedError def onselectstart(self, event): print(event) raise NotImplementedError def", "stopImmediatePropagation(self): pass class MouseEvent(Event): \"\"\" mouse events \"\"\" CLICK = \"click\" #: CONTEXTMENU", "\"\"\" self.dataTransfer \"\"\" Returns an object containing information about the inserted/deleted data \"\"\"", "def onloadstart(self, event): print(event) raise NotImplementedError def onlostpointercapture(self, event): print(event) raise NotImplementedError def", "is a class you can extend to give your obj event dispatching abilities", "NotImplementedError def ontimeupdate(self, event): print(event) raise NotImplementedError def onvolumechange(self, event): print(event) raise NotImplementedError", "self.lineno=0 # self.colno=0 # self.error={} super().__init__(_type, *args, **kwargs) class SubmitEvent(Event): \"\"\" SubmitEvent \"\"\"", "= \"ended\" #: ERROR = \"error\" #: FULLSCREENCHANGE = \"fullscreenchange\" #: FULLSCREENERROR =", "\"canplaythrough\" #: CHANGE = \"change\" #: DURATIONCHANGE = \"durationchange\" #: ENDED = \"ended\"", "_source = None @property def source(self): return self._source @source.setter def source(self, source): self._source", "set it for thing in stack: try: thing(event) # type(thing, (Event,), self) except", "= view self.detail = detail self.screenX = screenX self.screenY = screenY self._clientX =", "= \"click\" #: CONTEXTMENU = \"contextmenu\" #: DBLCLICK = \"dblclick\" #: MOUSEDOWN =", "self.shiftKey = None self.targetTouches = None self.touches = None super().__init__(_type, *args, **kwargs) class", "= locationArg self.modifiersListArg = modifiersListArg self.repeat = repeat @property def altKey(self): return self._altKey", "self.detail = None self.view = None super().__init__(_type, *args, **kwargs) class CompositionEvent(UIEvent): \"\"\" CompositionEvent", "pass def msConvertURL(self): pass def preventDefault(self): pass def stopImmediatePropagation(self): pass class MouseEvent(Event): \"\"\"", "storage item \"\"\" self.newValue = None \"\"\" Returns the new value of the", "def onratechange(self, event): print(event) raise NotImplementedError def onreset(self, event): print(event) raise NotImplementedError def", "is composing or not InputEvent, KeyboardEvent # repeat Returns whether a key is", "Returns whether the webpage was cached by the browser \"\"\" super().__init__(_type, *args, **kwargs)", "= None self.tiltX = None self.tiltY = None self.twist = None self.pointerType =", "not \"\"\" super().__init__(_type, *args, **kwargs) class PageTransitionEvent(Event): \"\"\" PageTransitionEvent \"\"\" PAGEHIDE = \"pagehide\"", "_type, *args, **kwargs): self.data = None \"\"\" Returns the inserted characters \"\"\" self.dataTransfer", "this correct? - cant think where else would set it for thing in", "**kwargs) class CompositionEvent(UIEvent): \"\"\" CompositionEvent \"\"\" START = \"compositionstart\" END = \"compositionend\" UPDATE", "self.pseudoElement = None \"\"\" Returns the name of the pseudo-element of the transition", "- is this correct? - cant think where else would set it for", "\"\"\" KEYDOWN = \"keydown\" #: KEYPRESS = \"keypress\" #: KEYUP = \"keyup\" #:", "1000)) def composedPath(self): return self.type + \":\" + str(self.timeStamp) def initEvent(self, _type=None, *args,", "to the position of the edge of the target element MouseEvent # offsetY", "clientY self._ctrlKey = ctrlKey self._altKey = altKey self._shiftKey = shiftKey self._metaKey = metaKey", "None super().__init__(_type, *args, **kwargs) class CompositionEvent(UIEvent): \"\"\" CompositionEvent \"\"\" START = \"compositionstart\" END", "return self._button # MOUSE_EVENT # getModifierState() Returns an array containing target ranges that", "None self.tiltX = None self.tiltY = None self.twist = None self.pointerType = None", "\"\"\" POINTER = \"pointer\" #: def __init__(self, _type, *args, **kwargs): self.pointerId = None", "print('type', _type) self.type = _type self.bubbles = None self.cancelable = None self.cancelBubble =", "up self.timeStamp = int(round(time.time() * 1000)) def composedPath(self): return self.type + \":\" +", "event): print(event) raise NotImplementedError def oncanplaythrough(self, event): print(event) raise NotImplementedError def onchange(self, event):", "ctrlKey self._altKey = altKey self._shiftKey = shiftKey self._metaKey = metaKey self._button = button", "BEFOREUNLOAD = \"beforeunload\" #: CANPLAY = \"canplay\" #: CANPLAYTHROUGH = \"canplaythrough\" #: CHANGE", "raise NotImplementedError def oncanplay(self, event): print(event) raise NotImplementedError def oncanplaythrough(self, event): print(event) raise", "onpointerout(self, event): print(event) raise NotImplementedError def onpointerover(self, event): print(event) raise NotImplementedError def onpointerup(self,", "raise NotImplementedError def onclose(self, event): print(event) raise NotImplementedError def oncontextmenu(self, event): print(event) raise", "= None \"\"\" Returns the name of the transition\"\"\" self.elapsedTime = None \"\"\"", "self.onkeydown) # self.addEventListener(KeyboardEvent.KEYUP, self.onkeyup) # self.addEventListener(MouseEvent.MOUSEMOVE, self.onmousemove) # self.addEventListener(MouseEvent.MOUSEDOWN, self.onmousedown) # self.addEventListener(MouseEvent.MOUSEUP, self.onmouseup)", "NotImplementedError def onreset(self, event): print(event) raise NotImplementedError def onresize(self, event): print(event) raise NotImplementedError", "#: ENTER = \"dragenter\" #: EXIT = \"dragexit\" #: LEAVE = \"dragleave\" #:", "event): print(event) raise NotImplementedError def onpointercancel(self, event): print(event) raise NotImplementedError def onpointerdown(self, event):", "ClipboardEvent \"\"\" COPY = \"copy\" #: CUT = \"cut\" #: PASTE = \"paste\"", "= \"dblclick\" #: MOUSEDOWN = \"mousedown\" #: MOUSEENTER = \"mouseenter\" #: MOUSELEAVE =", "#: INPUT = \"input\" #: INVALID = \"invalid\" #: LOAD = \"load\" #:", "# offsetY Returns the vertical coordinate of the mouse pointer relative to the", "metaKey self._button = button self.relatedTarget = relatedTarget # TODO - parse from_json -", "keyboard events \"\"\" KEYDOWN = \"keydown\" #: KEYPRESS = \"keypress\" #: KEYUP =", "1000000 3.7 up self.timeStamp = int(round(time.time() * 1000)) def composedPath(self): return self.type +", "self.relatedTarget = None super().__init__(_type, *args, **kwargs) class TouchEvent(Event): \"\"\" TouchEvent \"\"\" TOUCHCANCEL =", "PopStateEvent \"\"\" def __init__(self, _type, *args, **kwargs): self.state = None \"\"\" Returns an", "the edge of the target element MouseEvent # offsetY Returns the vertical coordinate", "def source(self, source): self._source = source def __init__(self, _type, source=None, bubbles=False, cancelable=False): #", "NotImplementedError def onshow(self, event): print(event) raise NotImplementedError def onstalled(self, event): print(event) raise NotImplementedError", "= \"dragend\" #: ENTER = \"dragenter\" #: EXIT = \"dragexit\" #: LEAVE =", "= _type self.canBubble = canBubble self.cancelable = cancelable self.view = view self.detail =", "#: PLAYING = \"playing\" #: PROGRESS = \"progress\" #: RATECHANGE = \"ratechange\" #:", "**kwargs): self.dataTransfer = None \"\"\" Returns the data that is dragged/dropped \"\"\" super().__init__(_type,", "**kwargs) def initKeyboardEvent(self, typeArg, canBubbleArg, cancelableArg, viewArg, charArg, keyArg, locationArg, modifiersListArg, repeat): self._type", "*args, **kwargs) class FocusEvent(Event): \"\"\" FocusEvent \"\"\" BLUR = \"blur\" #: FOCUS =", "_type, *args, **kwargs): self.state = None \"\"\" Returns an object containing a copy", "__init__(self, _type, *args, **kwargs): # self.args = args # self.kwargs = kwargs self._altKey", "@property def clientY(self): return self.y @property def altKey(self): return self._altKey @property def ctrlKey(self):", "onwheel(self, event): print(event) raise NotImplementedError def onanimationcancel(self, event): print(event) raise NotImplementedError def onanimationend(self,", "containing information about the inserted/deleted data \"\"\" self.getTargetRanges \"\"\" Returns an array containing", "raise NotImplementedError def onmouseup(self, event): print(event) raise NotImplementedError def onpause(self, event): print(event) raise", "__init__(self, _type, *args, **kwargs): self.persisted = None \"\"\" Returns whether the webpage was", "[] super().__init__(_type, *args, **kwargs) def initMouseEvent(self, _type=None, canBubble=True, cancelable=True, view=None, detail=None, screenX=0, screenY=0,", "# pageX Returns the horizontal coordinate of the mouse pointer, relative to the", "super().__init__(_type, *args, **kwargs) class DragEvent(Event): \"\"\" DragEvent \"\"\" DRAG = \"drag\" #: END", "self.tiltY = None self.twist = None self.pointerType = None self.isPrimary = None super().__init__(_type,", "print(event) raise NotImplementedError def onloadedmetadata(self, event): print(event) raise NotImplementedError def onloadend(self, event): print(event)", "the mouse event was triggered MouseEvent # pageY Returns the vertical coordinate of", "the mouse event was triggered MouseEvent # region MouseEvent # relatedTarget Returns the", "onblur(self, event): print(event) raise NotImplementedError def oncancel(self, event): print(event) raise NotImplementedError def oncanplay(self,", "#: WAITING = \"waiting\" #: # Event(\"look\", {\"bubbles\":true, \"cancelable\":false}); def __init__(self, _type=None, *args,", "not create param return not event.defaultPrevented class Event(object): \"\"\" event \"\"\" EMPTIED =", "def ondragleave(self, event): print(event) raise NotImplementedError def ondragover(self, event): print(event) raise NotImplementedError def", "= {} def hasEventListener(self, _type): return _type in self.listeners # TODO - event:", "= None self.changedTouches = None self.ctrlKey = None self.metaKey = None self.shiftKey =", "Returns the number of seconds an animation has been running \"\"\" self.pseudoElement =", "def __init__(self): # super().__init__(self) # self.addEventListener(KeyboardEvent.KEYDOWN, self.onkeydown) # self.addEventListener(KeyboardEvent.KEYUP, self.onkeyup) # self.addEventListener(MouseEvent.MOUSEMOVE, self.onmousemove)", "event): print(event) raise NotImplementedError def onvolumechange(self, event): print(event) raise NotImplementedError def onwaiting(self, event):", "relative to the document, when the mouse event was triggered MouseEvent # pageY", "@property def metaKey(self): return self._metaKey @property def button(self): return self._button @property def buttons(self):", "oncontextmenu(self, event): print(event) raise NotImplementedError def oncuechange(self, event): print(event) raise NotImplementedError def ondblclick(self,", "#: SUSPEND = \"suspend\" #: TOGGLE = \"toggle\" #: UNLOAD = \"unload\" #:", "return self.key # def isComposing(self, *args, **kwargs): # pass # KeyboardEvent # isComposing", "#: EXIT = \"dragexit\" #: LEAVE = \"dragleave\" #: OVER = \"dragover\" #:", "# self.timeStamp = int(round(time.time() * 1000)) # self.type = None pass def msConvertURL(self):", "self.elapsedTime = None \"\"\" Returns the number of seconds a transition has been", "#: OVER = \"dragover\" #: START = \"dragstart\" #: DROP = \"drop\" #:", "*args, **kwargs) class CompositionEvent(UIEvent): \"\"\" CompositionEvent \"\"\" START = \"compositionstart\" END = \"compositionend\"", "def ondragstart(self, event): print(event) raise NotImplementedError def ondrop(self, event): print(event) raise NotImplementedError def", "= \"resize\" #: RESET = \"reset\" #: SCROLL = \"scroll\" #: SEARCH =", "not KeyboardEvent # location Returns the location of a key on the keyboard", "def onabort(self, event): print(event) raise NotImplementedError def onblur(self, event): print(event) raise NotImplementedError def", "if _type not in self.listeners: return stack = self.listeners[_type] for thing in stack:", "shiftKey(self): return self._shiftKey @property def metaKey(self): return self._metaKey @property def button(self): return self._button", "= \"canplay\" #: CANPLAYTHROUGH = \"canplaythrough\" #: CHANGE = \"change\" #: DURATIONCHANGE =", "relative to the position of the last mousemove event MouseEvent # offsetX Returns", "print(event) raise NotImplementedError def oncontextmenu(self, event): print(event) raise NotImplementedError def oncuechange(self, event): print(event)", "self._ctrlKey = False self._shiftKey = False self._metaKey = False self._button = None self._buttons", "# self.addEventListener(MouseEvent.MOUSEUP, self.onmouseup) # self.addEventListener(DragEvent.DRAG, self.ondrag) # self.addEventListener(DragEvent.END, self.ondragend) # self.addEventListener(DragEvent.ENTER, self.ondragenter) #", "changed storage item \"\"\" self.storageArea = None \"\"\" Returns an object representing the", "SUBMIT = \"submit\" #: def __init__(self, _type, *args, **kwargs): super().__init__(_type, *args, **kwargs) class", "ranges that will be affected by the insertion/deletion \"\"\" self.inputType \"\"\" Returns the", "None self.cancelable = None self.cancelBubble = None self.composed = None self.currentTarget = None", "#: MOUSEUP = \"mouseup\" #: def __init__(self, _type, *args, **kwargs): # self.args =", "mousemove event MouseEvent # offsetX Returns the horizontal coordinate of the mouse pointer", "self.view = None super().__init__(_type, *args, **kwargs) class CompositionEvent(UIEvent): \"\"\" CompositionEvent \"\"\" START =", "= \"online\" #: OPEN = \"open\" #: PAUSE = \"pause\" #: PLAY =", "= None self.currentTarget = None self.defaultPrevented = False self.eventPhase = None self.explicitOriginalTarget =", "- USE WHEEL #: WHEEL = \"wheel\" #: def __init__(self, _type, *args, **kwargs):", "= None # self.bubbles = None # self.cancelable = None # self.cancelBubble =", "#: VOLUMECHANGE = \"volumechange\" #: WAITING = \"waiting\" #: # Event(\"look\", {\"bubbles\":true, \"cancelable\":false});", "_type, *args, **kwargs): # self.args = args # self.kwargs = kwargs self.x =", "= \"invalid\" #: LOAD = \"load\" #: LOADEDDATA = \"loadeddata\" #: LOADEDMETADATA =", "#: UNPAUSE = \"onUnPause\" #: UPDATE_START = \"onUpdateStart\" #: UPDATE_END = \"onUpdateEnd\" #:", "+ str(self.timeStamp) def initEvent(self, _type=None, *args, **kwargs): self.__init__(_type, args, kwargs) def stopPropagation(self): \"\"\"[prevents", "= \"focusout\" #: def __init__(self, _type, *args, **kwargs): self.relatedTarget = None super().__init__(_type, *args,", "self._clientX = clientX self._clientY = clientY self._ctrlKey = ctrlKey self._altKey = altKey self._shiftKey", "\"\"\" super().__init__(_type, *args, **kwargs) class ErrorEvent(Event): \"\"\" ErrorEvent \"\"\" ERROR = \"error\" #:", "the insertion/deletion \"\"\" self.inputType \"\"\" Returns the type of the change (i.e \"inserting\"", "change (i.e \"inserting\" or \"deleting\") \"\"\" self.isComposing \"\"\" Returns whether the state of", "= None super().__init__(_type, *args, **kwargs) class TweenEvent(Event): \"\"\" TweenEvent \"\"\" START = \"onStart\"", "relatedTarget=None, from_json={}, *args, **kwargs): # print('initMouseEvent') self._type = _type self.canBubble = canBubble self.cancelable", "NotImplementedError def ondragend(self, event): print(event) raise NotImplementedError def ondragenter(self, event): print(event) raise NotImplementedError", "LOADSTART = \"loadstart\" #: def __init__(self, _type, *args, **kwargs): super().__init__(_type, *args, **kwargs) class", "self.detail = detail self.screenX = screenX self.screenY = screenY self._clientX = clientX self._clientY", "def __init__(self, _type, *args, **kwargs): super().__init__(_type, *args, **kwargs) class DragEvent(Event): \"\"\" DragEvent \"\"\"", "Returns whether the state of the event is composing or not InputEvent, KeyboardEvent", "(i.e \"inserting\" or \"deleting\") \"\"\" self.isComposing \"\"\" Returns whether the state of the", "NotImplementedError def ondurationchange(self, event): print(event) raise NotImplementedError def onemptied(self, event): print(event) raise NotImplementedError", "**kwargs) class CustomEvent(Event): \"\"\" CustomEvent \"\"\" def __init__(self, _type, *args, **kwargs): self.detail =", "= None self.altKey = None self.changedTouches = None self.ctrlKey = None self.metaKey =", "= \"fullscreenchange\" #: FULLSCREENERROR = \"fullscreenerror\" #: INPUT = \"input\" #: INVALID =", "= \"keypress\" #: KEYUP = \"keyup\" #: def __init__(self, _type, *args, **kwargs): #", "def key(self): # return self.key # def isComposing(self, *args, **kwargs): # pass #", "name of the animation \"\"\" self.elapsedTime = None \"\"\" Returns the number of", "\"\"\" HashChangeEvent \"\"\" CHANGE = \"hashchange\" #: def __init__(self, _type, *args, **kwargs): self.newURL", "print(event) raise NotImplementedError def onpointerover(self, event): print(event) raise NotImplementedError def onpointerup(self, event): print(event)", "super().__init__(_type, *args, **kwargs) class CustomEvent(Event): \"\"\" CustomEvent \"\"\" def __init__(self, _type, *args, **kwargs):", "FocusEvent(Event): \"\"\" FocusEvent \"\"\" BLUR = \"blur\" #: FOCUS = \"focus\" #: FOCUSIN", "#: LEAVE = \"dragleave\" #: OVER = \"dragover\" #: START = \"dragstart\" #:", "print(event) raise NotImplementedError def onpointerleave(self, event): print(event) raise NotImplementedError def onpointermove(self, event): print(event)", "unicode(self): return self.key # @property # def keyCode(self): # return self.keyCode # @property", "# self.filename=None # self.lineno=0 # self.colno=0 # self.error={} super().__init__(_type, *args, **kwargs) class SubmitEvent(Event):", "cancelableArg self.viewArg = viewArg self.charArg = charArg self.keyArg = keyArg self.locationArg = locationArg", "print(event) raise NotImplementedError def onpause(self, event): print(event) raise NotImplementedError def onplay(self, event): print(event)", "@property def clientX(self): return self.x @property def clientY(self): return self.y @property def altKey(self):", "params, user may not create param return not event.defaultPrevented class Event(object): \"\"\" event", "of the mouse pointer, relative to the document, when the mouse event was", "object containing the data affected by the clipboard operation \"\"\" super().__init__(_type, *args, **kwargs)", "= \"offline\" #: ONLINE = \"online\" #: OPEN = \"open\" #: PAUSE =", "event): print(event) raise NotImplementedError def onanimationend(self, event): print(event) raise NotImplementedError def onanimationiteration(self, event):", "def onpointerup(self, event): print(event) raise NotImplementedError def onprogress(self, event): print(event) raise NotImplementedError def", "NotImplementedError def onwaiting(self, event): print(event) raise NotImplementedError def onwheel(self, event): print(event) raise NotImplementedError", "INVALID = \"invalid\" #: LOAD = \"load\" #: LOADEDDATA = \"loadeddata\" #: LOADEDMETADATA", "def onwaiting(self, event): print(event) raise NotImplementedError def onwheel(self, event): print(event) raise NotImplementedError def", "*args, **kwargs): # print('initMouseEvent') self._type = _type self.canBubble = canBubble self.cancelable = cancelable", "MovementY Returns the vertical coordinate of the mouse pointer relative to the position", "= None self.code = None self.key = None self.keyCode = None super().__init__(_type, *args,", "return self.keyCode # @property # def charCode(self): # return self.charCode # @property #", "def __init__(self, _type, *args, **kwargs): self.data = None #: Returns the characters generated", "InputEvent \"\"\" def __init__(self, _type, *args, **kwargs): self.data = None \"\"\" Returns the", "was cached by the browser \"\"\" super().__init__(_type, *args, **kwargs) class PopStateEvent(Event): \"\"\" PopStateEvent", "super().__init__(_type, *args, **kwargs) class TweenEvent(Event): \"\"\" TweenEvent \"\"\" START = \"onStart\" #: STOP", "event \"\"\" EMPTIED = \"emptied\" #: ABORT = \"abort\" #: AFTERPRINT = \"afterprint\"", "name of the pseudo-element of the transition \"\"\" super().__init__(_type, *args, **kwargs) class ProgressEvent(Event):", "NotImplementedError def onpointerup(self, event): print(event) raise NotImplementedError def onprogress(self, event): print(event) raise NotImplementedError", "#: RESET = \"onReset\" #: PAUSE = \"onPause\" #: UNPAUSE = \"onUnPause\" #:", "# try calling without params, user may not create param return not event.defaultPrevented", "event): print(event) raise NotImplementedError def onsubmit(self, event): print(event) raise NotImplementedError def onsuspend(self, event):", "= False self._shiftKey = False self._metaKey = False self.charCode = None self.code =", "\"submit\" #: SUSPEND = \"suspend\" #: TOGGLE = \"toggle\" #: UNLOAD = \"unload\"", "= None self.defaultPrevented = False self.eventPhase = None self.explicitOriginalTarget = None self.isTrusted =", "NotImplementedError def oncanplaythrough(self, event): print(event) raise NotImplementedError def onchange(self, event): print(event) raise NotImplementedError", "SELECT = \"select\" #: SHOW = \"show\" #: STALLED = \"stalled\" #: SUBMIT", "propagation of the current event in the capturing and bubbling phases]\"\"\" # self.defaultPrevented", "\"mouseup\" #: def __init__(self, _type, *args, **kwargs): # self.args = args # self.kwargs", "= None self.view = None super().__init__(_type, *args, **kwargs) class CompositionEvent(UIEvent): \"\"\" CompositionEvent \"\"\"", "of the edge of the target element MouseEvent # offsetY Returns the vertical", "def onpause(self, event): print(event) raise NotImplementedError def onplay(self, event): print(event) raise NotImplementedError def", "self.deltaMode = None super().__init__(_type, *args, **kwargs) class AnimationEvent(Event): \"\"\" AnimationEvent \"\"\" ANIMATIONEND =", "self.returnValue = None # self.originalTarget = None # self.explicitOriginalTarget = None # self.target", "onpointerover(self, event): print(event) raise NotImplementedError def onpointerup(self, event): print(event) raise NotImplementedError def onprogress(self,", "def onpointercancel(self, event): print(event) raise NotImplementedError def onpointerdown(self, event): print(event) raise NotImplementedError def", "DROP = \"drop\" #: def __init__(self, _type, *args, **kwargs): self.dataTransfer = None \"\"\"", "= \"error\" #: FULLSCREENCHANGE = \"fullscreenchange\" #: FULLSCREENERROR = \"fullscreenerror\" #: INPUT =", "onloadstart(self, event): print(event) raise NotImplementedError def onlostpointercapture(self, event): print(event) raise NotImplementedError def onmouseenter(self,", "event): print(event) raise NotImplementedError def ontimeupdate(self, event): print(event) raise NotImplementedError def onvolumechange(self, event):", "TODO - event: str, function, useCapture: bool # def addEventListener(self, event: str, function,", "as e: print(e) thing() # try calling without params, user may not create", "Returns the data that is dragged/dropped \"\"\" super().__init__(_type, *args, **kwargs) class HashChangeEvent(Event): \"\"\"", "horizontal coordinate of the mouse pointer relative to the position of the last", "None \"\"\" Returns the number of seconds a transition has been running \"\"\"", "def __init__(self, _type, *args, **kwargs): self.relatedTarget = None super().__init__(_type, *args, **kwargs) class TouchEvent(Event):", "super().__init__(self) # self.addEventListener(KeyboardEvent.KEYDOWN, self.onkeydown) # self.addEventListener(KeyboardEvent.KEYUP, self.onkeyup) # self.addEventListener(MouseEvent.MOUSEMOVE, self.onmousemove) # self.addEventListener(MouseEvent.MOUSEDOWN, self.onmousedown)", "self.cancelable = None # self.cancelBubble = None # self.composed = None # self.currentTarget", "of the pseudo-element of the animation \"\"\" super().__init__(_type, *args, **kwargs) class ClipboardEvent(Event): \"\"\"", "class PopStateEvent(Event): \"\"\" PopStateEvent \"\"\" def __init__(self, _type, *args, **kwargs): self.state = None", "event): print(event) raise NotImplementedError def onseeked(self, event): print(event) raise NotImplementedError def onseeking(self, event):", "#: def __init__(self, _type, *args, **kwargs): self.message = None # self.filename=None # self.lineno=0", "= None self.cancelable = None self.cancelBubble = None self.composed = None self.currentTarget =", "MOUSEDOWN = \"mousedown\" #: MOUSEENTER = \"mouseenter\" #: MOUSELEAVE = \"mouseleave\" #: MOUSEMOVE", "None # self.composed = None # self.currentTarget = None # self.eventPhase = None", "def onseeking(self, event): print(event) raise NotImplementedError def onselect(self, event): print(event) raise NotImplementedError def", "_type not in self.listeners: self.listeners[_type] = [] self.listeners[_type].append(callback) def removeEventListener(self, _type, callback): if", "\"mousemove\" #: MOUSEOVER = \"mouseover\" #: MOUSEOUT = \"mouseout\" #: MOUSEUP = \"mouseup\"", "raise NotImplementedError def oninvalid(self, event): print(event) raise NotImplementedError def onkeydown(self, event): print(event) raise", "CHANGE = \"change\" #: DURATIONCHANGE = \"durationchange\" #: ENDED = \"ended\" #: ERROR", "event): print(event) raise NotImplementedError def onclose(self, event): print(event) raise NotImplementedError def oncontextmenu(self, event):", "self.touches = None super().__init__(_type, *args, **kwargs) class WheelEvent(Event): \"\"\" WheelEvent \"\"\" MOUSEWHEEL =", "= None super().__init__(_type, *args, **kwargs) class CompositionEvent(UIEvent): \"\"\" CompositionEvent \"\"\" START = \"compositionstart\"", "@source.setter def source(self, source): self._source = source def __init__(self, _type, source=None, bubbles=False, cancelable=False):", "#: STOP = \"gamepaddisconnected\" #: def __init__(self, _type, *args, **kwargs): self.gamepad = None", "self.code = None self.key = None self.keyCode = None super().__init__(_type, *args, **kwargs) def", "raise NotImplementedError def onratechange(self, event): print(event) raise NotImplementedError def onreset(self, event): print(event) raise", "metaKey(self): return self._metaKey @property def button(self): return self._button @property def buttons(self): return self._buttons", "NotImplementedError def onanimationiteration(self, event): print(event) raise NotImplementedError def onauxclick(self, event): print(event) raise NotImplementedError", "self._ctrlKey = False self._shiftKey = False self._metaKey = False self.charCode = None self.code", "#: UNLOAD = \"unload\" #: VOLUMECHANGE = \"volumechange\" #: WAITING = \"waiting\" #:", "altKey=False, shiftKey=False, metaKey=False, button=None, relatedTarget=None, from_json={}, *args, **kwargs): # print('initMouseEvent') self._type = _type", "*args, **kwargs): self.shiftKey = None self.altKey = None self.changedTouches = None self.ctrlKey =", "\"mousedown\" #: MOUSEENTER = \"mouseenter\" #: MOUSELEAVE = \"mouseleave\" #: MOUSEMOVE = \"mousemove\"", "clientY(self): return self.y @property def altKey(self): return self._altKey @property def ctrlKey(self): return self._ctrlKey", "= None # self.originalTarget = None # self.explicitOriginalTarget = None # self.target =", "_type, *args, **kwargs): self.message = None # self.filename=None # self.lineno=0 # self.colno=0 #", "event): print(event) raise NotImplementedError def ondragstart(self, event): print(event) raise NotImplementedError def ondrop(self, event):", "event.target = self # TODO/NOTE - is this correct? - cant think where", "AFTERPRINT = \"afterprint\" #: BEFOREPRINT = \"beforeprint\" #: BEFOREUNLOAD = \"beforeunload\" #: CANPLAY", "typing import * import time # TODO - bring EventTarget here and get", "vertical coordinate of the mouse pointer relative to the position of the last", "# self.cancelBubble = None # self.composed = None # self.currentTarget = None #", "super().__init__(_type, *args, **kwargs) class SubmitEvent(Event): \"\"\" SubmitEvent \"\"\" SUBMIT = \"submit\" #: def", "current event in the capturing and bubbling phases]\"\"\" # self.defaultPrevented = True #", "print(event) raise NotImplementedError def onselect(self, event): print(event) raise NotImplementedError def onselectionchange(self, event): print(event)", "print(event) raise NotImplementedError def onerror(self, event): print(event) raise NotImplementedError def onfocus(self, event): print(event)", "= viewArg self.charArg = charArg self.keyArg = keyArg self.locationArg = locationArg self.modifiersListArg =", "\"\"\" super().__init__(_type, *args, **kwargs) class PageTransitionEvent(Event): \"\"\" PageTransitionEvent \"\"\" PAGEHIDE = \"pagehide\" #:", "def shiftKey(self): return self._shiftKey @property def metaKey(self): return self._metaKey @property def button(self): return", "class ClipboardEvent(Event): \"\"\" ClipboardEvent \"\"\" COPY = \"copy\" #: CUT = \"cut\" #:", "None # self.returnValue = None # self.timeStamp = int(round(time.time() * 1000)) # self.type", "that triggered the mouse event MouseEvent, FocusEvent class KeyboardEvent(Event): \"\"\" keyboard events \"\"\"", "the animation \"\"\" super().__init__(_type, *args, **kwargs) class ClipboardEvent(Event): \"\"\" ClipboardEvent \"\"\" COPY =", "event.type not in self.listeners: return True # huh?. surely false? stack = self.listeners[event.type]", "raise NotImplementedError def ontimeupdate(self, event): print(event) raise NotImplementedError def onvolumechange(self, event): print(event) raise", "def onloadeddata(self, event): print(event) raise NotImplementedError def onloadedmetadata(self, event): print(event) raise NotImplementedError def", "document, when the mouse event was triggered MouseEvent # pageY Returns the vertical", "the position of the edge of the target element MouseEvent # offsetY Returns", "\"\"\" StorageEvent \"\"\" def __init__(self, _type, *args, **kwargs): self.key = None \"\"\" Returns", "= \"compositionend\" UPDATE = \"compositionupdate\" def __init__(self, _type, *args, **kwargs): self.data = None", "= altKey self._shiftKey = shiftKey self._metaKey = metaKey self._button = button self.relatedTarget =", "whether the state of the event is composing or not InputEvent, KeyboardEvent #", "#: TIMER = \"onTimer\" #: _source = None @property def source(self): return self._source", "EventDispatcher is a class you can extend to give your obj event dispatching", "pass def preventDefault(self): pass def stopImmediatePropagation(self): pass class MouseEvent(Event): \"\"\" mouse events \"\"\"", "None #: Returns the characters generated by the input method that raised the", "\"beforeprint\" #: BEFOREUNLOAD = \"beforeunload\" #: CANPLAY = \"canplay\" #: CANPLAYTHROUGH = \"canplaythrough\"", "UPDATE = \"compositionupdate\" def __init__(self, _type, *args, **kwargs): self.data = None #: Returns", "= [] super().__init__(_type, *args, **kwargs) def initMouseEvent(self, _type=None, canBubble=True, cancelable=True, view=None, detail=None, screenX=0,", "composing or not InputEvent, KeyboardEvent # repeat Returns whether a key is being", "last mousemove event MouseEvent # MovementY Returns the vertical coordinate of the mouse", "#: _source = None @property def source(self): return self._source @source.setter def source(self, source):", "_type, *args, **kwargs): self.gamepad = None super().__init__(_type, *args, **kwargs) class TweenEvent(Event): \"\"\" TweenEvent", "ranges that will be affected by the insertion/deletion MouseEvent # MovementX Returns the", "self.clipboardData = None \"\"\" Returns an object containing the data affected by the", "NotImplementedError def onloadstart(self, event): print(event) raise NotImplementedError def onlostpointercapture(self, event): print(event) raise NotImplementedError", "\"\"\" self.elapsedTime = None \"\"\" Returns the number of seconds an animation has", "PAUSE = \"pause\" #: PLAY = \"play\" #: PLAYING = \"playing\" #: PROGRESS", "try: thing(event) # type(thing, (Event,), self) except Exception as e: print(e) thing() #", "return self.type + \":\" + str(self.timeStamp) def initEvent(self, _type=None, *args, **kwargs): self.__init__(_type, args,", "**kwargs) class ProgressEvent(Event): \"\"\" ProgressEvent \"\"\" LOADSTART = \"loadstart\" #: def __init__(self, _type,", "source def __init__(self, _type, source=None, bubbles=False, cancelable=False): # super.__init__(self, type, bubbles, cancelable) super().__init__(_type)", "ontouchcancel(self, event): print(event) raise NotImplementedError def ontouchstart(self, event): print(event) raise NotImplementedError def ontransitioncancel(self,", "\"\"\" ERROR = \"error\" #: def __init__(self, _type, *args, **kwargs): self.message = None", "ERROR = \"error\" #: FULLSCREENCHANGE = \"fullscreenchange\" #: FULLSCREENERROR = \"fullscreenerror\" #: INPUT", "stopPropagation(self): \"\"\"[prevents further propagation of the current event in the capturing and bubbling", "*args, **kwargs): self.data = None #: Returns the characters generated by the input", "class AnimationEvent(Event): \"\"\" AnimationEvent \"\"\" ANIMATIONEND = \"animationend\" #: ANIMATIONITERATION = \"animationiteration\" #:", "#: MOUSEDOWN = \"mousedown\" #: MOUSEENTER = \"mouseenter\" #: MOUSELEAVE = \"mouseleave\" #:", "KeyboardEvent(Event): \"\"\" keyboard events \"\"\" KEYDOWN = \"keydown\" #: KEYPRESS = \"keypress\" #:", "kwargs self._altKey = False self._ctrlKey = False self._shiftKey = False self._metaKey = False", "Returns the vertical coordinate of the mouse pointer relative to the position of", "class EventDispatcher(object): \"\"\" EventDispatcher is a class you can extend to give your", "#: def __init__(self, _type, *args, **kwargs): self.shiftKey = None self.altKey = None self.changedTouches", "\"\"\" super().__init__(_type, *args, **kwargs) class StorageEvent(Event): \"\"\" StorageEvent \"\"\" def __init__(self, _type, *args,", "#: SCROLL = \"scroll\" #: SEARCH = \"search\" #: SEEKED = \"seeked\" #:", "None self.keyCode = None super().__init__(_type, *args, **kwargs) def initKeyboardEvent(self, typeArg, canBubbleArg, cancelableArg, viewArg,", "Returns an object containing the data affected by the clipboard operation \"\"\" super().__init__(_type,", "self._altKey @property def ctrlKey(self): return self._ctrlKey @property def shiftKey(self): return self._shiftKey @property def", "super().__init__(_type, *args, **kwargs) def initCustomEvent(self): pass class GamePadEvent(Event): \"\"\" GamePadEvent \"\"\" START =", "the type of the change (i.e \"inserting\" or \"deleting\") \"\"\" self.isComposing \"\"\" Returns", "_type, *args, **kwargs): self.pointerId = None self.width = None self.height = None self.pressure", "ERROR = \"error\" #: def __init__(self, _type, *args, **kwargs): self.message = None #", "\"blur\" #: FOCUS = \"focus\" #: FOCUSIN = \"focusin\" #: FOCUSOUT = \"focusout\"", "None \"\"\" Returns the data that is dragged/dropped \"\"\" super().__init__(_type, *args, **kwargs) class", "the target element MouseEvent # offsetY Returns the vertical coordinate of the mouse", "print(event) raise NotImplementedError def onmouseenter(self, event): print(event) raise NotImplementedError def onmouseleave(self, event): print(event)", "the history entries \"\"\" super().__init__(_type, *args, **kwargs) class StorageEvent(Event): \"\"\" StorageEvent \"\"\" def", "NotImplementedError def onmouseleave(self, event): print(event) raise NotImplementedError def onmousemove(self, event): print(event) raise NotImplementedError", "self.isTrusted = None # self.returnValue = None # self.timeStamp = int(round(time.time() * 1000))", "= \"loadeddata\" #: LOADEDMETADATA = \"loadedmetadata\" #: MESSAGE = \"message\" #: OFFLINE =", "print(event) raise NotImplementedError def onkeyup(self, event): print(event) raise NotImplementedError def onload(self, event): print(event)", "self.explicitOriginalTarget = None self.isTrusted = None self.originalTarget = None self.returnValue = None self.srcElement", "\"focus\" #: FOCUSIN = \"focusin\" #: FOCUSOUT = \"focusout\" #: def __init__(self, _type,", "_type, *args, **kwargs): self.persisted = None \"\"\" Returns whether the webpage was cached", "or \"deleting\") \"\"\" self.isComposing \"\"\" Returns whether the state of the event is", "pseudo-element of the transition \"\"\" super().__init__(_type, *args, **kwargs) class ProgressEvent(Event): \"\"\" ProgressEvent \"\"\"", "= \"fullscreenerror\" #: INPUT = \"input\" #: INVALID = \"invalid\" #: LOAD =", "# def isComposing(self, *args, **kwargs): # pass # KeyboardEvent # isComposing Returns whether", "from typing import * import time # TODO - bring EventTarget here and", "event MouseEvent, FocusEvent class KeyboardEvent(Event): \"\"\" keyboard events \"\"\" KEYDOWN = \"keydown\" #:", "TimerEvent \"\"\" def __init__(self, _type, *args, **kwargs): super().__init__(_type, *args, **kwargs) class DragEvent(Event): \"\"\"", "#: def __init__(self, _type, *args, **kwargs): self.animationName = None \"\"\" Returns the name", "None self.tiltY = None self.twist = None self.pointerType = None self.isPrimary = None", "the URL of the changed item's document \"\"\" super().__init__(_type, *args, **kwargs) class TransitionEvent(Event):", "self.listeners: return True # huh?. surely false? stack = self.listeners[event.type] # .slice() event.target", "\"focusin\" #: FOCUSOUT = \"focusout\" #: def __init__(self, _type, *args, **kwargs): self.relatedTarget =", "coordinate of the mouse pointer relative to the position of the edge of", "\"click\" #: CONTEXTMENU = \"contextmenu\" #: DBLCLICK = \"dblclick\" #: MOUSEDOWN = \"mousedown\"", "\"submit\" #: def __init__(self, _type, *args, **kwargs): super().__init__(_type, *args, **kwargs) class PointerEvent(Event): \"\"\"", "def __init__(self, _type, *args, **kwargs): super().__init__(_type, *args, **kwargs) class PointerEvent(Event): \"\"\" PointerEvent \"\"\"", "of the history entries \"\"\" super().__init__(_type, *args, **kwargs) class StorageEvent(Event): \"\"\" StorageEvent \"\"\"", "_type, *args, **kwargs): super().__init__(_type, *args, **kwargs) class CustomEvent(Event): \"\"\" CustomEvent \"\"\" def __init__(self,", "self._shiftKey @property def metaKey(self): return self._metaKey @property def button(self): return self._button @property def", "**kwargs) class SubmitEvent(Event): \"\"\" SubmitEvent \"\"\" SUBMIT = \"submit\" #: def __init__(self, _type,", "def onerror(self, event): print(event) raise NotImplementedError def onfocus(self, event): print(event) raise NotImplementedError def", "print(event) raise NotImplementedError def onpointerenter(self, event): print(event) raise NotImplementedError def onpointerleave(self, event): print(event)", "self.bubbles = None # self.cancelable = None # self.cancelBubble = None # self.composed", "= \"keydown\" #: KEYPRESS = \"keypress\" #: KEYUP = \"keyup\" #: def __init__(self,", "def onmousedown(self, event): print(event) raise NotImplementedError def ontouchcancel(self, event): print(event) raise NotImplementedError def", "the state of the event is composing or not InputEvent, KeyboardEvent # repeat", "= None # ms = time.time_ns() // 1000000 3.7 up self.timeStamp = int(round(time.time()", "MOUSE_EVENT # getModifierState() Returns an array containing target ranges that will be affected", "CustomEvent(Event): \"\"\" CustomEvent \"\"\" def __init__(self, _type, *args, **kwargs): self.detail = None super().__init__(_type,", "**kwargs): self.detail = None self.view = None super().__init__(_type, *args, **kwargs) class CompositionEvent(UIEvent): \"\"\"", "SubmitEvent(Event): \"\"\" SubmitEvent \"\"\" SUBMIT = \"submit\" #: def __init__(self, _type, *args, **kwargs):", "ondragover(self, event): print(event) raise NotImplementedError def ondragstart(self, event): print(event) raise NotImplementedError def ondrop(self,", "**kwargs) class PopStateEvent(Event): \"\"\" PopStateEvent \"\"\" def __init__(self, _type, *args, **kwargs): self.state =", "ClipboardEvent(Event): \"\"\" ClipboardEvent \"\"\" COPY = \"copy\" #: CUT = \"cut\" #: PASTE", "= \"contextmenu\" #: DBLCLICK = \"dblclick\" #: MOUSEDOWN = \"mousedown\" #: MOUSEENTER =", "def onlostpointercapture(self, event): print(event) raise NotImplementedError def onmouseenter(self, event): print(event) raise NotImplementedError def", "# MovementY Returns the vertical coordinate of the mouse pointer relative to the", "self.listeners = {} def hasEventListener(self, _type): return _type in self.listeners # TODO -", "= None \"\"\" Returns the new value of the changed storage item \"\"\"", "by the insertion/deletion MouseEvent # MovementX Returns the horizontal coordinate of the mouse", "**kwargs): self.listeners = {} def hasEventListener(self, _type): return _type in self.listeners # TODO", "data that is dragged/dropped \"\"\" super().__init__(_type, *args, **kwargs) class HashChangeEvent(Event): \"\"\" HashChangeEvent \"\"\"", "*args, **kwargs): self.state = None \"\"\" Returns an object containing a copy of", "NotImplementedError def onmouseover(self, event): print(event) raise NotImplementedError def onmouseup(self, event): print(event) raise NotImplementedError", "*args, **kwargs) class ErrorEvent(Event): \"\"\" ErrorEvent \"\"\" ERROR = \"error\" #: def __init__(self,", "False self._shiftKey = False self._metaKey = False self.charCode = None self.code = None", "cancelableArg, viewArg, charArg, keyArg, locationArg, modifiersListArg, repeat): self._type = typeArg self.canBubbleArg = canBubbleArg", "def onkeyup(self, event): print(event) raise NotImplementedError def onload(self, event): print(event) raise NotImplementedError def", "NotImplementedError def onpointerout(self, event): print(event) raise NotImplementedError def onpointerover(self, event): print(event) raise NotImplementedError", "# self.addEventListener(DragEvent.ENTER, self.ondragenter) # self.addEventListener(DragEvent.EXIT, self.ondragexit) # self.addEventListener(DragEvent.LEAVE, self.ondragleave) # self.addEventListener(DragEvent.OVER, self.ondragover) #", "false? stack = self.listeners[event.type] # .slice() event.target = self # TODO/NOTE - is", "button=None, relatedTarget=None, from_json={}, *args, **kwargs): # print('initMouseEvent') self._type = _type self.canBubble = canBubble", "- cant think where else would set it for thing in stack: try:", "target ranges that will be affected by the insertion/deletion MouseEvent # MovementX Returns", "viewArg, charArg, keyArg, locationArg, modifiersListArg, repeat): self._type = typeArg self.canBubbleArg = canBubbleArg self.cancelableArg", "mouse event MouseEvent, FocusEvent class KeyboardEvent(Event): \"\"\" keyboard events \"\"\" KEYDOWN = \"keydown\"", "= None super().__init__(_type, *args, **kwargs) class FocusEvent(Event): \"\"\" FocusEvent \"\"\" BLUR = \"blur\"", "of the mouse pointer relative to the position of the last mousemove event", "= None #: Returns the characters generated by the input method that raised", "raise NotImplementedError def onmouseout(self, event): print(event) raise NotImplementedError def onmouseover(self, event): print(event) raise", "onshow(self, event): print(event) raise NotImplementedError def onstalled(self, event): print(event) raise NotImplementedError def onsubmit(self,", "# self.defaultPrevented = True # self.returnValue = None # self.originalTarget = None #", "FULLSCREENERROR = \"fullscreenerror\" #: INPUT = \"input\" #: INVALID = \"invalid\" #: LOAD", "TODO - bring EventTarget here and get rid of this one? class EventDispatcher(object):", "location of a key on the keyboard or device KeyboardEvent class UIEvent(Event): \"\"\"", "a transition has been running \"\"\" self.pseudoElement = None \"\"\" Returns the name", "correct? - cant think where else would set it for thing in stack:", "onemptied(self, event): print(event) raise NotImplementedError def onended(self, event): print(event) raise NotImplementedError def onerror(self,", "event): print(event) raise NotImplementedError def onmousedown(self, event): print(event) raise NotImplementedError def ontouchcancel(self, event):", "\"onStart\" #: STOP = \"onStop\" #: RESET = \"onReset\" #: PAUSE = \"onPause\"", "super().__init__(_type, *args, **kwargs) class WheelEvent(Event): \"\"\" WheelEvent \"\"\" MOUSEWHEEL = \"mousewheel\" # DEPRECATED", "def onauxclick(self, event): print(event) raise NotImplementedError def onformdata(self, event): print(event) raise NotImplementedError def", "self.newURL = None self.oldURL = None super().__init__(_type, *args, **kwargs) class InputEvent(Event): \"\"\" InputEvent", "FocusEvent class KeyboardEvent(Event): \"\"\" keyboard events \"\"\" KEYDOWN = \"keydown\" #: KEYPRESS =", "onloadeddata(self, event): print(event) raise NotImplementedError def onloadedmetadata(self, event): print(event) raise NotImplementedError def onloadend(self,", "the affected storage object \"\"\" self.url = None \"\"\" Returns the URL of", "history entries \"\"\" super().__init__(_type, *args, **kwargs) class StorageEvent(Event): \"\"\" StorageEvent \"\"\" def __init__(self,", "of the changed storage item \"\"\" self.newValue = None \"\"\" Returns the new", "Returns the horizontal coordinate of the mouse pointer relative to the position of", "further propagation of the current event in the capturing and bubbling phases]\"\"\" #", "ABORT = \"abort\" #: AFTERPRINT = \"afterprint\" #: BEFOREPRINT = \"beforeprint\" #: BEFOREUNLOAD", "\"\"\" Returns the name of the animation \"\"\" self.elapsedTime = None \"\"\" Returns", "print(event) raise NotImplementedError def onselectstart(self, event): print(event) raise NotImplementedError def onshow(self, event): print(event)", "**kwargs): self.message = None # self.filename=None # self.lineno=0 # self.colno=0 # self.error={} super().__init__(_type,", "NotImplementedError def onpointerleave(self, event): print(event) raise NotImplementedError def onpointermove(self, event): print(event) raise NotImplementedError", "mousemove event MouseEvent # MovementY Returns the vertical coordinate of the mouse pointer", "_type, *args, **kwargs): self.detail = None self.view = None super().__init__(_type, *args, **kwargs) class", "def __init__(self, *args, **kwargs): self.listeners = {} def hasEventListener(self, _type): return _type in", "whether a key is being hold down repeatedly, or not KeyboardEvent # location", "# @property # def charCode(self): # return self.charCode # @property # def code(self):", "NotImplementedError def ondblclick(self, event): print(event) raise NotImplementedError def ondrag(self, event): print(event) raise NotImplementedError", "print(event) raise NotImplementedError def onplaying(self, event): print(event) raise NotImplementedError def onpointercancel(self, event): print(event)", "NotImplementedError def oninvalid(self, event): print(event) raise NotImplementedError def onkeydown(self, event): print(event) raise NotImplementedError", "\"touchstart\" #: def __init__(self, _type, *args, **kwargs): self.shiftKey = None self.altKey = None", "**kwargs) class AnimationEvent(Event): \"\"\" AnimationEvent \"\"\" ANIMATIONEND = \"animationend\" #: ANIMATIONITERATION = \"animationiteration\"", "= False self._button = None self._buttons = [] super().__init__(_type, *args, **kwargs) def initMouseEvent(self,", "= None self._buttons = [] super().__init__(_type, *args, **kwargs) def initMouseEvent(self, _type=None, canBubble=True, cancelable=True,", "self.type + \":\" + str(self.timeStamp) def initEvent(self, _type=None, *args, **kwargs): self.__init__(_type, args, kwargs)", "TransitionEvent \"\"\" TRANSITIONEND = \"transitionend\" #: def __init__(self, _type, *args, **kwargs): self.propertyName =", "self.addEventListener(DragEvent.EXIT, self.ondragexit) # self.addEventListener(DragEvent.LEAVE, self.ondragleave) # self.addEventListener(DragEvent.OVER, self.ondragover) # self.addEventListener(DragEvent.START, self.ondragstart) # self.addEventListener(DragEvent.DROP,", "= \"volumechange\" #: WAITING = \"waiting\" #: # Event(\"look\", {\"bubbles\":true, \"cancelable\":false}); def __init__(self,", "will be affected by the insertion/deletion \"\"\" self.inputType \"\"\" Returns the type of", "#: def __init__(self, _type, *args, **kwargs): super().__init__(_type, *args, **kwargs) class PointerEvent(Event): \"\"\" PointerEvent", "def onkeypress(self, event): print(event) raise NotImplementedError def onkeyup(self, event): print(event) raise NotImplementedError def", "= \"drag\" #: END = \"dragend\" #: ENTER = \"dragenter\" #: EXIT =", "= \"onStop\" #: RESET = \"onReset\" #: PAUSE = \"onPause\" #: UNPAUSE =", "the position of the edge of the target element MouseEvent # pageX Returns", "event): print(event) raise NotImplementedError def onloadeddata(self, event): print(event) raise NotImplementedError def onloadedmetadata(self, event):", "= canBubbleArg self.cancelableArg = cancelableArg self.viewArg = viewArg self.charArg = charArg self.keyArg =", "**kwargs) class SVGEvent(Event): \"\"\" SVGEvent \"\"\" def __init__(self, _type, *args, **kwargs): super().__init__(_type, *args,", "\"pause\" #: PLAY = \"play\" #: PLAYING = \"playing\" #: PROGRESS = \"progress\"", "ProgressEvent(Event): \"\"\" ProgressEvent \"\"\" LOADSTART = \"loadstart\" #: def __init__(self, _type, *args, **kwargs):", "number of seconds a transition has been running \"\"\" self.pseudoElement = None \"\"\"", "Event(\"look\", {\"bubbles\":true, \"cancelable\":false}); def __init__(self, _type=None, *args, **kwargs): # print('type', _type) self.type =", "return self._metaKey @property def button(self): return self._button @property def buttons(self): return self._buttons @property", "\"\"\" super().__init__(_type, *args, **kwargs) class TransitionEvent(Event): \"\"\" TransitionEvent \"\"\" TRANSITIONEND = \"transitionend\" #:", "class TouchEvent(Event): \"\"\" TouchEvent \"\"\" TOUCHCANCEL = \"touchcancel\" #: TOUCHEND = \"touchend\" #:", "def onstalled(self, event): print(event) raise NotImplementedError def onsubmit(self, event): print(event) raise NotImplementedError def", "event): print(event) raise NotImplementedError def onload(self, event): print(event) raise NotImplementedError def onloadeddata(self, event):", "raise NotImplementedError def onanimationiteration(self, event): print(event) raise NotImplementedError def onauxclick(self, event): print(event) raise", "keyboard or device KeyboardEvent class UIEvent(Event): \"\"\" UIEvent \"\"\" def __init__(self, _type, *args,", "def initKeyboardEvent(self, typeArg, canBubbleArg, cancelableArg, viewArg, charArg, keyArg, locationArg, modifiersListArg, repeat): self._type =", "#: MOUSEMOVE = \"mousemove\" #: MOUSEOVER = \"mouseover\" #: MOUSEOUT = \"mouseout\" #:", "= \"loadstart\" #: def __init__(self, _type, *args, **kwargs): super().__init__(_type, *args, **kwargs) class CustomEvent(Event):", "event): print(event) raise NotImplementedError def ondurationchange(self, event): print(event) raise NotImplementedError def onemptied(self, event):", "\"durationchange\" #: ENDED = \"ended\" #: ERROR = \"error\" #: FULLSCREENCHANGE = \"fullscreenchange\"", "bubbling phases]\"\"\" # self.defaultPrevented = True # self.returnValue = None # self.originalTarget =", "onseeking(self, event): print(event) raise NotImplementedError def onselect(self, event): print(event) raise NotImplementedError def onselectionchange(self,", "print(event) raise NotImplementedError def onchange(self, event): print(event) raise NotImplementedError def onclick(self, event): print(event)", "object containing a copy of the history entries \"\"\" super().__init__(_type, *args, **kwargs) class", "args # self.kwargs = kwargs self._altKey = False self._ctrlKey = False self._shiftKey =", "None \"\"\" Returns an object containing the data affected by the clipboard operation", "= \"animationend\" #: ANIMATIONITERATION = \"animationiteration\" #: ANIMATIONSTART = \"animationstart\" #: def __init__(self,", "@property def source(self): return self._source @source.setter def source(self, source): self._source = source def", "event): print(event) raise NotImplementedError def ongotpointercapture(self, event): print(event) raise NotImplementedError def oninput(self, event):", "TweenEvent \"\"\" START = \"onStart\" #: STOP = \"onStop\" #: RESET = \"onReset\"", "onpointercancel(self, event): print(event) raise NotImplementedError def onpointerdown(self, event): print(event) raise NotImplementedError def onpointerenter(self,", "event): print(event) raise NotImplementedError def ontransitioncancel(self, event): print(event) raise NotImplementedError def ontransitionend(self, event):", "coordinate of the mouse pointer relative to the position of the last mousemove", "raise NotImplementedError def onvolumechange(self, event): print(event) raise NotImplementedError def onwaiting(self, event): print(event) raise", "__init__(self, _type, *args, **kwargs): super().__init__(_type, *args, **kwargs) class SVGEvent(Event): \"\"\" SVGEvent \"\"\" def", "= None # self.composed = None # self.currentTarget = None # self.eventPhase =", "\"\"\" PAGEHIDE = \"pagehide\" #: PAGESHOW = \"pageshow\" #: def __init__(self, _type, *args,", "self.detail = None super().__init__(_type, *args, **kwargs) def initCustomEvent(self): pass class GamePadEvent(Event): \"\"\" GamePadEvent", "self.repeat = repeat @property def altKey(self): return self._altKey @property def ctrlKey(self): return self._ctrlKey", "= cancelableArg self.viewArg = viewArg self.charArg = charArg self.keyArg = keyArg self.locationArg =", "__init__(self, _type, *args, **kwargs): self.pointerId = None self.width = None self.height = None", "Returns the vertical coordinate of the mouse pointer, relative to the document, when", "self.dataTransfer \"\"\" Returns an object containing information about the inserted/deleted data \"\"\" self.getTargetRanges", "ondragend(self, event): print(event) raise NotImplementedError def ondragenter(self, event): print(event) raise NotImplementedError def ondragexit(self,", "def onmouseout(self, event): print(event) raise NotImplementedError def onmouseover(self, event): print(event) raise NotImplementedError def", "= \"reset\" #: SCROLL = \"scroll\" #: SEARCH = \"search\" #: SEEKED =", "*args, **kwargs): super().__init__(_type, *args, **kwargs) class DragEvent(Event): \"\"\" DragEvent \"\"\" DRAG = \"drag\"", "print(event) raise NotImplementedError def onreset(self, event): print(event) raise NotImplementedError def onresize(self, event): print(event)", "\"deleting\") \"\"\" self.isComposing \"\"\" Returns whether the state of the event is composing", "\"\"\" LOADSTART = \"loadstart\" #: def __init__(self, _type, *args, **kwargs): super().__init__(_type, *args, **kwargs)", "to the position of the last mousemove event MouseEvent # offsetX Returns the", "was triggered MouseEvent # pageY Returns the vertical coordinate of the mouse pointer,", "NotImplementedError def onmousedown(self, event): print(event) raise NotImplementedError def ontouchcancel(self, event): print(event) raise NotImplementedError", "of the change (i.e \"inserting\" or \"deleting\") \"\"\" self.isComposing \"\"\" Returns whether the", "#: DBLCLICK = \"dblclick\" #: MOUSEDOWN = \"mousedown\" #: MOUSEENTER = \"mouseenter\" #:", "class SubmitEvent(Event): \"\"\" SubmitEvent \"\"\" SUBMIT = \"submit\" #: def __init__(self, _type, *args,", "True # self.returnValue = None # self.originalTarget = None # self.explicitOriginalTarget = None", "#: KEYPRESS = \"keypress\" #: KEYUP = \"keyup\" #: def __init__(self, _type, *args,", "= \"mouseleave\" #: MOUSEMOVE = \"mousemove\" #: MOUSEOVER = \"mouseover\" #: MOUSEOUT =", "NotImplementedError def onvolumechange(self, event): print(event) raise NotImplementedError def onwaiting(self, event): print(event) raise NotImplementedError", "NotImplementedError def onmouseenter(self, event): print(event) raise NotImplementedError def onmouseleave(self, event): print(event) raise NotImplementedError", "array containing target ranges that will be affected by the insertion/deletion MouseEvent #", "class GamePadEvent(Event): \"\"\" GamePadEvent \"\"\" START = \"gamepadconnected\" #: STOP = \"gamepaddisconnected\" #:", "the name of the animation \"\"\" self.elapsedTime = None \"\"\" Returns the number", "self.url = None \"\"\" Returns the URL of the changed item's document \"\"\"", "print(event) raise NotImplementedError def onended(self, event): print(event) raise NotImplementedError def onerror(self, event): print(event)", "in self.listeners: self.listeners[_type] = [] self.listeners[_type].append(callback) def removeEventListener(self, _type, callback): if _type not", "False self._ctrlKey = False self._shiftKey = False self._metaKey = False self.charCode = None", "value of the changed storage item \"\"\" self.oldValue = None \"\"\" Returns the", "END = \"dragend\" #: ENTER = \"dragenter\" #: EXIT = \"dragexit\" #: LEAVE", "mouse event was triggered MouseEvent # region MouseEvent # relatedTarget Returns the element", "\"focusout\" #: def __init__(self, _type, *args, **kwargs): self.relatedTarget = None super().__init__(_type, *args, **kwargs)", "Returns whether a key is being hold down repeatedly, or not KeyboardEvent #", "\"\"\" START = \"gamepadconnected\" #: STOP = \"gamepaddisconnected\" #: def __init__(self, _type, *args,", "Returns the number of seconds a transition has been running \"\"\" self.pseudoElement =", "def onloadedmetadata(self, event): print(event) raise NotImplementedError def onloadend(self, event): print(event) raise NotImplementedError def", "STOP = \"gamepaddisconnected\" #: def __init__(self, _type, *args, **kwargs): self.gamepad = None super().__init__(_type,", "\"animationend\" #: ANIMATIONITERATION = \"animationiteration\" #: ANIMATIONSTART = \"animationstart\" #: def __init__(self, _type,", "self.key = None \"\"\" Returns the key of the changed storage item \"\"\"", "def onanimationend(self, event): print(event) raise NotImplementedError def onanimationiteration(self, event): print(event) raise NotImplementedError def", "#: Returns the characters generated by the input method that raised the event", "getModifierState() Returns an array containing target ranges that will be affected by the", "*args, **kwargs) def initCustomEvent(self): pass class GamePadEvent(Event): \"\"\" GamePadEvent \"\"\" START = \"gamepadconnected\"", "# ms = time.time_ns() // 1000000 3.7 up self.timeStamp = int(round(time.time() * 1000))", "the pseudo-element of the transition \"\"\" super().__init__(_type, *args, **kwargs) class ProgressEvent(Event): \"\"\" ProgressEvent", "target element MouseEvent # offsetY Returns the vertical coordinate of the mouse pointer", "array containing target ranges that will be affected by the insertion/deletion \"\"\" self.inputType", "# self.type = None pass def msConvertURL(self): pass def preventDefault(self): pass def stopImmediatePropagation(self):", "= int(round(time.time() * 1000)) def composedPath(self): return self.type + \":\" + str(self.timeStamp) def", "of the event is composing or not \"\"\" super().__init__(_type, *args, **kwargs) class PageTransitionEvent(Event):", "raise NotImplementedError def onclick(self, event): print(event) raise NotImplementedError def onclose(self, event): print(event) raise", "the horizontal coordinate of the mouse pointer relative to the position of the", "to give your obj event dispatching abilities \"\"\" def __init__(self, *args, **kwargs): self.listeners", "*args, **kwargs): self.dataTransfer = None \"\"\" Returns the data that is dragged/dropped \"\"\"", "= None # self.isTrusted = None # self.returnValue = None # self.timeStamp =", "#: def __init__(self, _type, *args, **kwargs): self.gamepad = None super().__init__(_type, *args, **kwargs) class", "triggered MouseEvent # pageY Returns the vertical coordinate of the mouse pointer, relative", "the number of seconds an animation has been running \"\"\" self.pseudoElement = None", "*args, **kwargs) class SVGEvent(Event): \"\"\" SVGEvent \"\"\" def __init__(self, _type, *args, **kwargs): super().__init__(_type,", "= None \"\"\" Returns an object containing the data affected by the clipboard", "the location of a key on the keyboard or device KeyboardEvent class UIEvent(Event):", "raise NotImplementedError def onpointerup(self, event): print(event) raise NotImplementedError def onprogress(self, event): print(event) raise", "None \"\"\" Returns the new value of the changed storage item \"\"\" self.oldValue", "= \"touchcancel\" #: TOUCHEND = \"touchend\" #: TOUCHMOVE = \"touchmove\" #: TOUCHSTART =", "# TODO - parse from_json - so can relay @property def clientX(self): return", "canBubbleArg, cancelableArg, viewArg, charArg, keyArg, locationArg, modifiersListArg, repeat): self._type = typeArg self.canBubbleArg =", "horizontal coordinate of the mouse pointer, relative to the document, when the mouse", "def ondragend(self, event): print(event) raise NotImplementedError def ondragenter(self, event): print(event) raise NotImplementedError def", "= self.listeners[_type] for thing in stack: if thing == callback: stack.remove(thing) return def", "raise NotImplementedError def oncuechange(self, event): print(event) raise NotImplementedError def ondblclick(self, event): print(event) raise", "event): print(event) raise NotImplementedError def onmouseleave(self, event): print(event) raise NotImplementedError def onmousemove(self, event):", "= None self.height = None self.pressure = None self.tangentialPressure = None self.tiltX =", "print(event) raise NotImplementedError def onloadstart(self, event): print(event) raise NotImplementedError def onlostpointercapture(self, event): print(event)", "\"\"\" BeforeUnloadEvent \"\"\" def __init__(self, _type, *args, **kwargs): super().__init__(_type, *args, **kwargs) class SVGEvent(Event):", "if event.type not in self.listeners: return True # huh?. surely false? stack =", "==================================== dom events \"\"\" # from typing import * import time # TODO", "ErrorEvent(Event): \"\"\" ErrorEvent \"\"\" ERROR = \"error\" #: def __init__(self, _type, *args, **kwargs):", "self.bubbles = None self.cancelable = None self.cancelBubble = None self.composed = None self.currentTarget", "onselect(self, event): print(event) raise NotImplementedError def onselectionchange(self, event): print(event) raise NotImplementedError def onselectstart(self,", "try calling without params, user may not create param return not event.defaultPrevented class", "initKeyboardEvent(self, typeArg, canBubbleArg, cancelableArg, viewArg, charArg, keyArg, locationArg, modifiersListArg, repeat): self._type = typeArg", "seconds a transition has been running \"\"\" self.pseudoElement = None \"\"\" Returns the", "\"\"\" Returns the inserted characters \"\"\" self.dataTransfer \"\"\" Returns an object containing information", "return self.y @property def altKey(self): return self._altKey @property def ctrlKey(self): return self._ctrlKey @property", "onpause(self, event): print(event) raise NotImplementedError def onplay(self, event): print(event) raise NotImplementedError def onplaying(self,", "class UIEvent(Event): \"\"\" UIEvent \"\"\" def __init__(self, _type, *args, **kwargs): self.detail = None", "thing() # try calling without params, user may not create param return not", "= None super().__init__(_type, *args, **kwargs) def initKeyboardEvent(self, typeArg, canBubbleArg, cancelableArg, viewArg, charArg, keyArg,", "def __init__(self, _type, *args, **kwargs): super().__init__(_type, *args, **kwargs) class CustomEvent(Event): \"\"\" CustomEvent \"\"\"", "def onpointerout(self, event): print(event) raise NotImplementedError def onpointerover(self, event): print(event) raise NotImplementedError def", "event was triggered MouseEvent # region MouseEvent # relatedTarget Returns the element related", "DRAG = \"drag\" #: END = \"dragend\" #: ENTER = \"dragenter\" #: EXIT", "event): print(event) raise NotImplementedError def onwheel(self, event): print(event) raise NotImplementedError def onanimationcancel(self, event):", "NotImplementedError def ondrag(self, event): print(event) raise NotImplementedError def ondragend(self, event): print(event) raise NotImplementedError", "shiftKey(self): return self._shiftKey @property def metaKey(self): return self._metaKey @property def unicode(self): return self.key", "\"loadstart\" #: def __init__(self, _type, *args, **kwargs): super().__init__(_type, *args, **kwargs) class CustomEvent(Event): \"\"\"", "= \"compositionstart\" END = \"compositionend\" UPDATE = \"compositionupdate\" def __init__(self, _type, *args, **kwargs):", "data affected by the clipboard operation \"\"\" super().__init__(_type, *args, **kwargs) class ErrorEvent(Event): \"\"\"", "by the clipboard operation \"\"\" super().__init__(_type, *args, **kwargs) class ErrorEvent(Event): \"\"\" ErrorEvent \"\"\"", "# offsetX Returns the horizontal coordinate of the mouse pointer relative to the", "typeArg, canBubbleArg, cancelableArg, viewArg, charArg, keyArg, locationArg, modifiersListArg, repeat): self._type = typeArg self.canBubbleArg", "= None \"\"\" Returns the key of the changed storage item \"\"\" self.newValue", "_type, *args, **kwargs): self.dataTransfer = None \"\"\" Returns the data that is dragged/dropped", "been running \"\"\" self.pseudoElement = None \"\"\" Returns the name of the pseudo-element", "print(event) raise NotImplementedError def oninvalid(self, event): print(event) raise NotImplementedError def onkeydown(self, event): print(event)", "raise NotImplementedError def onprogress(self, event): print(event) raise NotImplementedError def onratechange(self, event): print(event) raise", "@property def unicode(self): return self.key # @property # def keyCode(self): # return self.keyCode", "\"volumechange\" #: WAITING = \"waiting\" #: # Event(\"look\", {\"bubbles\":true, \"cancelable\":false}); def __init__(self, _type=None,", "= \"mouseenter\" #: MOUSELEAVE = \"mouseleave\" #: MOUSEMOVE = \"mousemove\" #: MOUSEOVER =", "shiftKey=False, metaKey=False, button=None, relatedTarget=None, from_json={}, *args, **kwargs): # print('initMouseEvent') self._type = _type self.canBubble", "__init__(self, _type, *args, **kwargs): super().__init__(_type, *args, **kwargs) class CustomEvent(Event): \"\"\" CustomEvent \"\"\" def", "\"\"\" def __init__(self, _type, *args, **kwargs): super().__init__(_type, *args, **kwargs) class DragEvent(Event): \"\"\" DragEvent", "raise NotImplementedError def ondragexit(self, event): print(event) raise NotImplementedError def ondragleave(self, event): print(event) raise", "\"ended\" #: ERROR = \"error\" #: FULLSCREENCHANGE = \"fullscreenchange\" #: FULLSCREENERROR = \"fullscreenerror\"", "# def charCode(self): # return self.charCode # @property # def code(self): # return", "CUT = \"cut\" #: PASTE = \"paste\" #: def __init__(self, _type, *args, **kwargs):", "thing == callback: stack.remove(thing) return def dispatchEvent(self, event): if event.type not in self.listeners:", "None # self.target = None # self.srcElement = None # self.bubbles = None", "Returns the element related to the element that triggered the mouse event MouseEvent,", "NotImplementedError def oninput(self, event): print(event) raise NotImplementedError def oninvalid(self, event): print(event) raise NotImplementedError", "return self._metaKey @property def unicode(self): return self.key # @property # def keyCode(self): #", "self.message = None # self.filename=None # self.lineno=0 # self.colno=0 # self.error={} super().__init__(_type, *args,", "= None self.cancelBubble = None self.composed = None self.currentTarget = None self.defaultPrevented =", "#: INVALID = \"invalid\" #: LOAD = \"load\" #: LOADEDDATA = \"loadeddata\" #:", "- self.source = source class GlobalEventHandler: # (EventDispatcher): # def __init__(self): # super().__init__(self)", "pass class MouseEvent(Event): \"\"\" mouse events \"\"\" CLICK = \"click\" #: CONTEXTMENU =", "= None self.originalTarget = None self.returnValue = None self.srcElement = None self.target =", "\"\"\" def __init__(self, _type, *args, **kwargs): super().__init__(_type, *args, **kwargs) class SVGEvent(Event): \"\"\" SVGEvent", "NotImplementedError def onmouseout(self, event): print(event) raise NotImplementedError def onmouseover(self, event): print(event) raise NotImplementedError", "#: RESIZE = \"resize\" #: RESET = \"reset\" #: SCROLL = \"scroll\" #:", "\"\"\" CustomEvent \"\"\" def __init__(self, _type, *args, **kwargs): self.detail = None super().__init__(_type, *args,", "super().__init__(_type, *args, **kwargs) class SVGEvent(Event): \"\"\" SVGEvent \"\"\" def __init__(self, _type, *args, **kwargs):", "for thing in stack: if thing == callback: stack.remove(thing) return def dispatchEvent(self, event):", "Exception as e: print(e) thing() # try calling without params, user may not", "raise NotImplementedError def onloadeddata(self, event): print(event) raise NotImplementedError def onloadedmetadata(self, event): print(event) raise", "= \"onPause\" #: UNPAUSE = \"onUnPause\" #: UPDATE_START = \"onUpdateStart\" #: UPDATE_END =", "0 self._clientX = 0 self._altKey = False self._ctrlKey = False self._shiftKey = False", "ProgressEvent \"\"\" LOADSTART = \"loadstart\" #: def __init__(self, _type, *args, **kwargs): super().__init__(_type, *args,", "__init__(self, _type, *args, **kwargs): # self.args = args # self.kwargs = kwargs self.x", "in the capturing and bubbling phases]\"\"\" # self.defaultPrevented = True # self.returnValue =", "= None self.srcElement = None self.target = None # ms = time.time_ns() //", "False self._shiftKey = False self._metaKey = False self._button = None self._buttons = []", "self.isComposing \"\"\" Returns whether the state of the event is composing or not", "last mousemove event MouseEvent # offsetX Returns the horizontal coordinate of the mouse", "super().__init__(_type, *args, **kwargs) class ProgressEvent(Event): \"\"\" ProgressEvent \"\"\" LOADSTART = \"loadstart\" #: def", "\"show\" #: STALLED = \"stalled\" #: SUBMIT = \"submit\" #: SUSPEND = \"suspend\"", "item's document \"\"\" super().__init__(_type, *args, **kwargs) class TransitionEvent(Event): \"\"\" TransitionEvent \"\"\" TRANSITIONEND =", "TODO/NOTE - is this correct? - cant think where else would set it", "self._metaKey = metaKey self._button = button self.relatedTarget = relatedTarget # TODO - parse", "def charCode(self): # return self.charCode # @property # def code(self): # return self.code", "False self.charCode = None self.code = None self.key = None self.keyCode = None", "Returns the name of the animation \"\"\" self.elapsedTime = None \"\"\" Returns the", "of the changed storage item \"\"\" self.oldValue = None \"\"\" Returns the old", "pass # KeyboardEvent # isComposing Returns whether the state of the event is", "NotImplementedError def ondragleave(self, event): print(event) raise NotImplementedError def ondragover(self, event): print(event) raise NotImplementedError", "event): print(event) raise NotImplementedError def onloadstart(self, event): print(event) raise NotImplementedError def onlostpointercapture(self, event):", "event dispatching abilities \"\"\" def __init__(self, *args, **kwargs): self.listeners = {} def hasEventListener(self,", "__init__(self, _type, *args, **kwargs): self.data = None \"\"\" Returns the inserted characters \"\"\"", "raise NotImplementedError def onresize(self, event): print(event) raise NotImplementedError def onscroll(self, event): print(event) raise", "event): print(event) raise NotImplementedError def onanimationcancel(self, event): print(event) raise NotImplementedError def onanimationend(self, event):", "your obj event dispatching abilities \"\"\" def __init__(self, *args, **kwargs): self.listeners = {}", "to the position of the edge of the target element MouseEvent # pageX", "super().__init__(_type, *args, **kwargs) class FocusEvent(Event): \"\"\" FocusEvent \"\"\" BLUR = \"blur\" #: FOCUS", "onkeypress(self, event): print(event) raise NotImplementedError def onkeyup(self, event): print(event) raise NotImplementedError def onload(self,", "@property # def keyCode(self): # return self.keyCode # @property # def charCode(self): #", "raise NotImplementedError def ondblclick(self, event): print(event) raise NotImplementedError def ondrag(self, event): print(event) raise", "def onsubmit(self, event): print(event) raise NotImplementedError def onsuspend(self, event): print(event) raise NotImplementedError def", "print(event) raise NotImplementedError def onanimationend(self, event): print(event) raise NotImplementedError def onanimationiteration(self, event): print(event)", "cancelable self.view = view self.detail = detail self.screenX = screenX self.screenY = screenY", "\"dragstart\" #: DROP = \"drop\" #: def __init__(self, _type, *args, **kwargs): self.dataTransfer =", "\"mouseenter\" #: MOUSELEAVE = \"mouseleave\" #: MOUSEMOVE = \"mousemove\" #: MOUSEOVER = \"mouseover\"", "__init__(self, _type, *args, **kwargs): self.message = None # self.filename=None # self.lineno=0 # self.colno=0", "#: CANPLAYTHROUGH = \"canplaythrough\" #: CHANGE = \"change\" #: DURATIONCHANGE = \"durationchange\" #:", "= \"message\" #: OFFLINE = \"offline\" #: ONLINE = \"online\" #: OPEN =", "str(self.timeStamp) def initEvent(self, _type=None, *args, **kwargs): self.__init__(_type, args, kwargs) def stopPropagation(self): \"\"\"[prevents further", "relay @property def clientX(self): return self.x @property def clientY(self): return self.y @property def", "of the last mousemove event MouseEvent # MovementY Returns the vertical coordinate of", "= None self.twist = None self.pointerType = None self.isPrimary = None super().__init__(_type, *args,", "__init__(self, _type, *args, **kwargs): self.state = None \"\"\" Returns an object containing a", "def stopImmediatePropagation(self): pass class MouseEvent(Event): \"\"\" mouse events \"\"\" CLICK = \"click\" #:", "DEPRECATED - USE WHEEL #: WHEEL = \"wheel\" #: def __init__(self, _type, *args,", "def __init__(self, _type, *args, **kwargs): self.state = None \"\"\" Returns an object containing", "class GlobalEventHandler: # (EventDispatcher): # def __init__(self): # super().__init__(self) # self.addEventListener(KeyboardEvent.KEYDOWN, self.onkeydown) #", "raise NotImplementedError def onpointerdown(self, event): print(event) raise NotImplementedError def onpointerenter(self, event): print(event) raise", "= \"seeked\" #: SEEKING = \"seeking\" #: SELECT = \"select\" #: SHOW =", "None # self.timeStamp = int(round(time.time() * 1000)) # self.type = None pass def", "#: FOCUSOUT = \"focusout\" #: def __init__(self, _type, *args, **kwargs): self.relatedTarget = None", "raise NotImplementedError def onsuspend(self, event): print(event) raise NotImplementedError def ontimeupdate(self, event): print(event) raise", "event): print(event) raise NotImplementedError def onresize(self, event): print(event) raise NotImplementedError def onscroll(self, event):", "\"\"\" Returns the name of the pseudo-element of the transition \"\"\" super().__init__(_type, *args,", "_type, callback, *args, **kwargs): if _type not in self.listeners: self.listeners[_type] = [] self.listeners[_type].append(callback)", "// 1000000 3.7 up self.timeStamp = int(round(time.time() * 1000)) def composedPath(self): return self.type", "repeat): self._type = typeArg self.canBubbleArg = canBubbleArg self.cancelableArg = cancelableArg self.viewArg = viewArg", "the inserted/deleted data \"\"\" self.getTargetRanges \"\"\" Returns an array containing target ranges that", "dragged/dropped \"\"\" super().__init__(_type, *args, **kwargs) class HashChangeEvent(Event): \"\"\" HashChangeEvent \"\"\" CHANGE = \"hashchange\"", "print(event) raise NotImplementedError def onwaiting(self, event): print(event) raise NotImplementedError def onwheel(self, event): print(event)", "self.addEventListener(KeyboardEvent.KEYUP, self.onkeyup) # self.addEventListener(MouseEvent.MOUSEMOVE, self.onmousemove) # self.addEventListener(MouseEvent.MOUSEDOWN, self.onmousedown) # self.addEventListener(MouseEvent.MOUSEUP, self.onmouseup) # self.addEventListener(DragEvent.DRAG,", "bool # def addEventListener(self, event: str, function, useCapture: bool) -> None: def addEventListener(self,", "the changed storage item \"\"\" self.storageArea = None \"\"\" Returns an object representing", "def clientX(self): return self.x @property def clientY(self): return self.y @property def altKey(self): return", "def unicode(self): return self.key # @property # def keyCode(self): # return self.keyCode #", "#: # Event(\"look\", {\"bubbles\":true, \"cancelable\":false}); def __init__(self, _type=None, *args, **kwargs): # print('type', _type)", "__init__(self, _type, *args, **kwargs): self.data = None #: Returns the characters generated by", "self.storageArea = None \"\"\" Returns an object representing the affected storage object \"\"\"", "MouseEvent # MovementY Returns the vertical coordinate of the mouse pointer relative to", "ondrag(self, event): print(event) raise NotImplementedError def ondragend(self, event): print(event) raise NotImplementedError def ondragenter(self,", "to the document, when the mouse event was triggered MouseEvent # region MouseEvent", "\"loadeddata\" #: LOADEDMETADATA = \"loadedmetadata\" #: MESSAGE = \"message\" #: OFFLINE = \"offline\"", "None self.oldURL = None super().__init__(_type, *args, **kwargs) class InputEvent(Event): \"\"\" InputEvent \"\"\" def", "onanimationend(self, event): print(event) raise NotImplementedError def onanimationiteration(self, event): print(event) raise NotImplementedError def onauxclick(self,", "addEventListener(self, _type, callback, *args, **kwargs): if _type not in self.listeners: self.listeners[_type] = []", "TOUCHMOVE = \"touchmove\" #: TOUCHSTART = \"touchstart\" #: def __init__(self, _type, *args, **kwargs):", "\"beforeunload\" #: CANPLAY = \"canplay\" #: CANPLAYTHROUGH = \"canplaythrough\" #: CHANGE = \"change\"", "ontimeupdate(self, event): print(event) raise NotImplementedError def onvolumechange(self, event): print(event) raise NotImplementedError def onwaiting(self,", "__init__(self, _type, *args, **kwargs): self.clipboardData = None \"\"\" Returns an object containing the", "SVGEvent \"\"\" def __init__(self, _type, *args, **kwargs): super().__init__(_type, *args, **kwargs) class TimerEvent(Event): TIMER", "print(event) raise NotImplementedError def onplay(self, event): print(event) raise NotImplementedError def onplaying(self, event): print(event)", "self.canBubbleArg = canBubbleArg self.cancelableArg = cancelableArg self.viewArg = viewArg self.charArg = charArg self.keyArg", "\"wheel\" #: def __init__(self, _type, *args, **kwargs): self.deltaX = None self.deltaY = None", "= None self.width = None self.height = None self.pressure = None self.tangentialPressure =", "= None self.oldURL = None super().__init__(_type, *args, **kwargs) class InputEvent(Event): \"\"\" InputEvent \"\"\"", "ms = time.time_ns() // 1000000 3.7 up self.timeStamp = int(round(time.time() * 1000)) def", ".slice() event.target = self # TODO/NOTE - is this correct? - cant think", "None # self.isTrusted = None # self.returnValue = None # self.timeStamp = int(round(time.time()", "None self.shiftKey = None self.targetTouches = None self.touches = None super().__init__(_type, *args, **kwargs)", "\"dragover\" #: START = \"dragstart\" #: DROP = \"drop\" #: def __init__(self, _type,", "self._clientX = 0 self._altKey = False self._ctrlKey = False self._shiftKey = False self._metaKey", "event: str, function, useCapture: bool # def addEventListener(self, event: str, function, useCapture: bool)", "CANPLAY = \"canplay\" #: CANPLAYTHROUGH = \"canplaythrough\" #: CHANGE = \"change\" #: DURATIONCHANGE", "None self.pressure = None self.tangentialPressure = None self.tiltX = None self.tiltY = None", "= None # self.returnValue = None # self.timeStamp = int(round(time.time() * 1000)) #", "*args, **kwargs): self.detail = None self.view = None super().__init__(_type, *args, **kwargs) class CompositionEvent(UIEvent):", "NotImplementedError def onmouseup(self, event): print(event) raise NotImplementedError def onpause(self, event): print(event) raise NotImplementedError", "onwaiting(self, event): print(event) raise NotImplementedError def onwheel(self, event): print(event) raise NotImplementedError def onanimationcancel(self,", "NotImplementedError def onclose(self, event): print(event) raise NotImplementedError def oncontextmenu(self, event): print(event) raise NotImplementedError", "\"\"\" Returns the key of the changed storage item \"\"\" self.newValue = None", "self.addEventListener(DragEvent.OVER, self.ondragover) # self.addEventListener(DragEvent.START, self.ondragstart) # self.addEventListener(DragEvent.DROP, self.ondrop) # self.addEventListener(ClipboardEvent.CUT, self.oncut) # self.addEventListener(ClipboardEvent.COPY,", "NotImplementedError def onloadedmetadata(self, event): print(event) raise NotImplementedError def onloadend(self, event): print(event) raise NotImplementedError", "def onplaying(self, event): print(event) raise NotImplementedError def onpointercancel(self, event): print(event) raise NotImplementedError def", "position of the last mousemove event MouseEvent # MovementY Returns the vertical coordinate", "self.ondrop) # self.addEventListener(ClipboardEvent.CUT, self.oncut) # self.addEventListener(ClipboardEvent.COPY, self.oncopy) # self.addEventListener(ClipboardEvent.PASTE, self.onpaste) def onabort(self, event):", "None self.returnValue = None self.srcElement = None self.target = None # ms =", "\"\"\" DragEvent \"\"\" DRAG = \"drag\" #: END = \"dragend\" #: ENTER =", "button self.relatedTarget = relatedTarget # TODO - parse from_json - so can relay", "# return self.code # @property # def key(self): # return self.key # def", "None self.composed = None self.currentTarget = None self.defaultPrevented = False self.eventPhase = None", "self._metaKey @property def button(self): return self._button @property def buttons(self): return self._buttons @property def", "super().__init__(_type, *args, **kwargs) class PopStateEvent(Event): \"\"\" PopStateEvent \"\"\" def __init__(self, _type, *args, **kwargs):", "def stopPropagation(self): \"\"\"[prevents further propagation of the current event in the capturing and", "create param return not event.defaultPrevented class Event(object): \"\"\" event \"\"\" EMPTIED = \"emptied\"", "self._altKey = False self._ctrlKey = False self._shiftKey = False self._metaKey = False self._button", "self.view = view self.detail = detail self.screenX = screenX self.screenY = screenY self._clientX", "self.currentTarget = None # self.eventPhase = None # self.isTrusted = None # self.returnValue", "canBubble=True, cancelable=True, view=None, detail=None, screenX=0, screenY=0, clientX=0, clientY=0, ctrlKey=False, altKey=False, shiftKey=False, metaKey=False, button=None,", "self.pressure = None self.tangentialPressure = None self.tiltX = None self.tiltY = None self.twist", "print(event) raise NotImplementedError def onpointerup(self, event): print(event) raise NotImplementedError def onprogress(self, event): print(event)", "MovementX Returns the horizontal coordinate of the mouse pointer relative to the position", "None super().__init__(_type, *args, **kwargs) class BeforeUnloadEvent(Event): BEFOREUNLOAD = \"beforeunload\" #: \"\"\" BeforeUnloadEvent \"\"\"", "event): print(event) raise NotImplementedError def ondragexit(self, event): print(event) raise NotImplementedError def ondragleave(self, event):", "\"\"\" CLICK = \"click\" #: CONTEXTMENU = \"contextmenu\" #: DBLCLICK = \"dblclick\" #:", "\"compositionupdate\" def __init__(self, _type, *args, **kwargs): self.data = None #: Returns the characters", "raise NotImplementedError def onfocus(self, event): print(event) raise NotImplementedError def ongotpointercapture(self, event): print(event) raise", "def oncontextmenu(self, event): print(event) raise NotImplementedError def oncuechange(self, event): print(event) raise NotImplementedError def", "return True # huh?. surely false? stack = self.listeners[event.type] # .slice() event.target =", "useCapture: bool # def addEventListener(self, event: str, function, useCapture: bool) -> None: def", "= charArg self.keyArg = keyArg self.locationArg = locationArg self.modifiersListArg = modifiersListArg self.repeat =", "\"onTimer\" #: _source = None @property def source(self): return self._source @source.setter def source(self,", "in self.listeners: return True # huh?. surely false? stack = self.listeners[event.type] # .slice()", "TIMER = \"onTimer\" #: _source = None @property def source(self): return self._source @source.setter", "**kwargs): # print('initMouseEvent') self._type = _type self.canBubble = canBubble self.cancelable = cancelable self.view", "def keyCode(self): # return self.keyCode # @property # def charCode(self): # return self.charCode", "LOAD = \"load\" #: LOADEDDATA = \"loadeddata\" #: LOADEDMETADATA = \"loadedmetadata\" #: MESSAGE", "def __init__(self, _type, *args, **kwargs): self.deltaX = None self.deltaY = None self.deltaZ =", "self._clientX = 0 self._clientX = 0 self._altKey = False self._ctrlKey = False self._shiftKey", "\"keyup\" #: def __init__(self, _type, *args, **kwargs): # self.args = args # self.kwargs", "self.cancelBubble = None # self.composed = None # self.currentTarget = None # self.eventPhase", "= \"input\" #: INVALID = \"invalid\" #: LOAD = \"load\" #: LOADEDDATA =", "= None # self.filename=None # self.lineno=0 # self.colno=0 # self.error={} super().__init__(_type, *args, **kwargs)", "LEAVE = \"dragleave\" #: OVER = \"dragover\" #: START = \"dragstart\" #: DROP", "= \"scroll\" #: SEARCH = \"search\" #: SEEKED = \"seeked\" #: SEEKING =", "raise NotImplementedError def onmousedown(self, event): print(event) raise NotImplementedError def ontouchcancel(self, event): print(event) raise", "def initEvent(self, _type=None, *args, **kwargs): self.__init__(_type, args, kwargs) def stopPropagation(self): \"\"\"[prevents further propagation", "self.data = None \"\"\" Returns the inserted characters \"\"\" self.dataTransfer \"\"\" Returns an", "= None self.composed = None self.currentTarget = None self.defaultPrevented = False self.eventPhase =", "def onfocus(self, event): print(event) raise NotImplementedError def ongotpointercapture(self, event): print(event) raise NotImplementedError def", "\"onUnPause\" #: UPDATE_START = \"onUpdateStart\" #: UPDATE_END = \"onUpdateEnd\" #: COMPLETE = \"onComplete\"", "__init__(self, *args, **kwargs): self.listeners = {} def hasEventListener(self, _type): return _type in self.listeners", "NotImplementedError def ondragstart(self, event): print(event) raise NotImplementedError def ondrop(self, event): print(event) raise NotImplementedError", "\"\"\" ClipboardEvent \"\"\" COPY = \"copy\" #: CUT = \"cut\" #: PASTE =", "containing target ranges that will be affected by the insertion/deletion \"\"\" self.inputType \"\"\"", "cancelable=True, view=None, detail=None, screenX=0, screenY=0, clientX=0, clientY=0, ctrlKey=False, altKey=False, shiftKey=False, metaKey=False, button=None, relatedTarget=None,", "onkeydown(self, event): print(event) raise NotImplementedError def onkeypress(self, event): print(event) raise NotImplementedError def onkeyup(self,", "# self.colno=0 # self.error={} super().__init__(_type, *args, **kwargs) class SubmitEvent(Event): \"\"\" SubmitEvent \"\"\" SUBMIT", "raise NotImplementedError def ontransitioncancel(self, event): print(event) raise NotImplementedError def ontransitionend(self, event): print(event) raise", "= \"pagehide\" #: PAGESHOW = \"pageshow\" #: def __init__(self, _type, *args, **kwargs): self.persisted", "#: ENDED = \"ended\" #: ERROR = \"error\" #: FULLSCREENCHANGE = \"fullscreenchange\" #:", "None self.height = None self.pressure = None self.tangentialPressure = None self.tiltX = None", "BeforeUnloadEvent \"\"\" def __init__(self, _type, *args, **kwargs): super().__init__(_type, *args, **kwargs) class SVGEvent(Event): \"\"\"", "NotImplementedError def onlostpointercapture(self, event): print(event) raise NotImplementedError def onmouseenter(self, event): print(event) raise NotImplementedError", "event): print(event) raise NotImplementedError def ontouchstart(self, event): print(event) raise NotImplementedError def ontransitioncancel(self, event):", "transition has been running \"\"\" self.pseudoElement = None \"\"\" Returns the name of", "event in the capturing and bubbling phases]\"\"\" # self.defaultPrevented = True # self.returnValue", "raise NotImplementedError def ondragleave(self, event): print(event) raise NotImplementedError def ondragover(self, event): print(event) raise", "#: ANIMATIONITERATION = \"animationiteration\" #: ANIMATIONSTART = \"animationstart\" #: def __init__(self, _type, *args,", "print(event) raise NotImplementedError def onpointerdown(self, event): print(event) raise NotImplementedError def onpointerenter(self, event): print(event)", "\"error\" #: def __init__(self, _type, *args, **kwargs): self.message = None # self.filename=None #", "\"\"\" EventDispatcher is a class you can extend to give your obj event", "bubbles=False, cancelable=False): # super.__init__(self, type, bubbles, cancelable) super().__init__(_type) # TODO - self.source =", "self) except Exception as e: print(e) thing() # try calling without params, user", "#: def __init__(self, _type, *args, **kwargs): self.clipboardData = None \"\"\" Returns an object", "= None self.tangentialPressure = None self.tiltX = None self.tiltY = None self.twist =", "def onpointerdown(self, event): print(event) raise NotImplementedError def onpointerenter(self, event): print(event) raise NotImplementedError def", "self.isPrimary = None super().__init__(_type, *args, **kwargs) class BeforeUnloadEvent(Event): BEFOREUNLOAD = \"beforeunload\" #: \"\"\"", "shiftKey self._metaKey = metaKey self._button = button self.relatedTarget = relatedTarget # TODO -", "= source class GlobalEventHandler: # (EventDispatcher): # def __init__(self): # super().__init__(self) # self.addEventListener(KeyboardEvent.KEYDOWN,", "operation \"\"\" super().__init__(_type, *args, **kwargs) class ErrorEvent(Event): \"\"\" ErrorEvent \"\"\" ERROR = \"error\"", "\"\"\" def __init__(self, _type, *args, **kwargs): super().__init__(_type, *args, **kwargs) class TimerEvent(Event): TIMER =", "self.code # @property # def key(self): # return self.key # def isComposing(self, *args,", "# relatedTarget Returns the element related to the element that triggered the mouse", "PopStateEvent(Event): \"\"\" PopStateEvent \"\"\" def __init__(self, _type, *args, **kwargs): self.state = None \"\"\"", "*args, **kwargs) class TimerEvent(Event): TIMER = \"timer\" #: \"\"\" TimerEvent \"\"\" def __init__(self,", "MESSAGE = \"message\" #: OFFLINE = \"offline\" #: ONLINE = \"online\" #: OPEN", "None # self.originalTarget = None # self.explicitOriginalTarget = None # self.target = None", "bring EventTarget here and get rid of this one? class EventDispatcher(object): \"\"\" EventDispatcher", "\"onUpdateEnd\" #: COMPLETE = \"onComplete\" #: TIMER = \"onTimer\" #: _source = None", "\"onComplete\" #: TIMER = \"onTimer\" #: _source = None @property def source(self): return", "print(event) raise NotImplementedError def onauxclick(self, event): print(event) raise NotImplementedError def onformdata(self, event): print(event)", "#: SELECT = \"select\" #: SHOW = \"show\" #: STALLED = \"stalled\" #:", "repeat @property def altKey(self): return self._altKey @property def ctrlKey(self): return self._ctrlKey @property def", "oninvalid(self, event): print(event) raise NotImplementedError def onkeydown(self, event): print(event) raise NotImplementedError def onkeypress(self,", "was triggered MouseEvent # region MouseEvent # relatedTarget Returns the element related to", "# self.addEventListener(DragEvent.OVER, self.ondragover) # self.addEventListener(DragEvent.START, self.ondragstart) # self.addEventListener(DragEvent.DROP, self.ondrop) # self.addEventListener(ClipboardEvent.CUT, self.oncut) #", "= \"suspend\" #: TOGGLE = \"toggle\" #: UNLOAD = \"unload\" #: VOLUMECHANGE =", "NotImplementedError def onanimationcancel(self, event): print(event) raise NotImplementedError def onanimationend(self, event): print(event) raise NotImplementedError", "None pass def msConvertURL(self): pass def preventDefault(self): pass def stopImmediatePropagation(self): pass class MouseEvent(Event):", "ondragleave(self, event): print(event) raise NotImplementedError def ondragover(self, event): print(event) raise NotImplementedError def ondragstart(self,", "method that raised the event self.locale = None super().__init__(_type, *args, **kwargs) class FocusEvent(Event):", "# def __init__(self): # super().__init__(self) # self.addEventListener(KeyboardEvent.KEYDOWN, self.onkeydown) # self.addEventListener(KeyboardEvent.KEYUP, self.onkeyup) # self.addEventListener(MouseEvent.MOUSEMOVE,", "source(self, source): self._source = source def __init__(self, _type, source=None, bubbles=False, cancelable=False): # super.__init__(self,", "= None \"\"\" Returns an object representing the affected storage object \"\"\" self.url", "NotImplementedError def onpointerdown(self, event): print(event) raise NotImplementedError def onpointerenter(self, event): print(event) raise NotImplementedError", "print(event) raise NotImplementedError def onmouseup(self, event): print(event) raise NotImplementedError def onpause(self, event): print(event)", "by the input method that raised the event self.locale = None super().__init__(_type, *args,", "when the mouse event was triggered MouseEvent # pageY Returns the vertical coordinate", "TOUCHCANCEL = \"touchcancel\" #: TOUCHEND = \"touchend\" #: TOUCHMOVE = \"touchmove\" #: TOUCHSTART", "super().__init__(_type, *args, **kwargs) class ErrorEvent(Event): \"\"\" ErrorEvent \"\"\" ERROR = \"error\" #: def", "onfocus(self, event): print(event) raise NotImplementedError def ongotpointercapture(self, event): print(event) raise NotImplementedError def oninput(self,", "ENDED = \"ended\" #: ERROR = \"error\" #: FULLSCREENCHANGE = \"fullscreenchange\" #: FULLSCREENERROR", "relatedTarget Returns the element related to the element that triggered the mouse event", "raise NotImplementedError def onseeked(self, event): print(event) raise NotImplementedError def onseeking(self, event): print(event) raise", "# super().__init__(self) # self.addEventListener(KeyboardEvent.KEYDOWN, self.onkeydown) # self.addEventListener(KeyboardEvent.KEYUP, self.onkeyup) # self.addEventListener(MouseEvent.MOUSEMOVE, self.onmousemove) # self.addEventListener(MouseEvent.MOUSEDOWN,", "ondblclick(self, event): print(event) raise NotImplementedError def ondrag(self, event): print(event) raise NotImplementedError def ondragend(self,", "containing the data affected by the clipboard operation \"\"\" super().__init__(_type, *args, **kwargs) class", "mouse event was triggered MouseEvent # pageY Returns the vertical coordinate of the", "events \"\"\" KEYDOWN = \"keydown\" #: KEYPRESS = \"keypress\" #: KEYUP = \"keyup\"", "= \"mousemove\" #: MOUSEOVER = \"mouseover\" #: MOUSEOUT = \"mouseout\" #: MOUSEUP =", "relative to the position of the last mousemove event MouseEvent # MovementY Returns", "stack: if thing == callback: stack.remove(thing) return def dispatchEvent(self, event): if event.type not", "def onanimationiteration(self, event): print(event) raise NotImplementedError def onauxclick(self, event): print(event) raise NotImplementedError def", "NotImplementedError def onkeyup(self, event): print(event) raise NotImplementedError def onload(self, event): print(event) raise NotImplementedError", "None \"\"\" Returns the URL of the changed item's document \"\"\" super().__init__(_type, *args,", "print(event) raise NotImplementedError def onselectionchange(self, event): print(event) raise NotImplementedError def onselectstart(self, event): print(event)", "def __init__(self, _type, *args, **kwargs): # self.args = args # self.kwargs = kwargs", "NotImplementedError def onmousemove(self, event): print(event) raise NotImplementedError def onmouseout(self, event): print(event) raise NotImplementedError", "an object containing the data affected by the clipboard operation \"\"\" super().__init__(_type, *args,", "= None super().__init__(_type, *args, **kwargs) class WheelEvent(Event): \"\"\" WheelEvent \"\"\" MOUSEWHEEL = \"mousewheel\"", "is being hold down repeatedly, or not KeyboardEvent # location Returns the location", "print(event) raise NotImplementedError def onvolumechange(self, event): print(event) raise NotImplementedError def onwaiting(self, event): print(event)", "oninput(self, event): print(event) raise NotImplementedError def oninvalid(self, event): print(event) raise NotImplementedError def onkeydown(self,", "def __init__(self, _type, *args, **kwargs): self.clipboardData = None \"\"\" Returns an object containing", "that will be affected by the insertion/deletion MouseEvent # MovementX Returns the horizontal", "\"emptied\" #: ABORT = \"abort\" #: AFTERPRINT = \"afterprint\" #: BEFOREPRINT = \"beforeprint\"", "print(event) raise NotImplementedError def onload(self, event): print(event) raise NotImplementedError def onloadeddata(self, event): print(event)", "False self._ctrlKey = False self._shiftKey = False self._metaKey = False self._button = None", "\"seeking\" #: SELECT = \"select\" #: SHOW = \"show\" #: STALLED = \"stalled\"", "KeyboardEvent # repeat Returns whether a key is being hold down repeatedly, or", "\"pointer\" #: def __init__(self, _type, *args, **kwargs): self.pointerId = None self.width = None", "self.dataTransfer = None \"\"\" Returns the data that is dragged/dropped \"\"\" super().__init__(_type, *args,", "print(event) raise NotImplementedError def onblur(self, event): print(event) raise NotImplementedError def oncancel(self, event): print(event)", "raise NotImplementedError def ondurationchange(self, event): print(event) raise NotImplementedError def onemptied(self, event): print(event) raise", "value of the changed storage item \"\"\" self.storageArea = None \"\"\" Returns an", "onselectstart(self, event): print(event) raise NotImplementedError def onshow(self, event): print(event) raise NotImplementedError def onstalled(self,", "= repeat @property def altKey(self): return self._altKey @property def ctrlKey(self): return self._ctrlKey @property", "composedPath(self): return self.type + \":\" + str(self.timeStamp) def initEvent(self, _type=None, *args, **kwargs): self.__init__(_type,", "None self.cancelBubble = None self.composed = None self.currentTarget = None self.defaultPrevented = False", "NotImplementedError def onplaying(self, event): print(event) raise NotImplementedError def onpointercancel(self, event): print(event) raise NotImplementedError", "event): print(event) raise NotImplementedError def onselect(self, event): print(event) raise NotImplementedError def onselectionchange(self, event):", "\"onPause\" #: UNPAUSE = \"onUnPause\" #: UPDATE_START = \"onUpdateStart\" #: UPDATE_END = \"onUpdateEnd\"", "AnimationEvent(Event): \"\"\" AnimationEvent \"\"\" ANIMATIONEND = \"animationend\" #: ANIMATIONITERATION = \"animationiteration\" #: ANIMATIONSTART", "cancelable) super().__init__(_type) # TODO - self.source = source class GlobalEventHandler: # (EventDispatcher): #", "= \"canplaythrough\" #: CHANGE = \"change\" #: DURATIONCHANGE = \"durationchange\" #: ENDED =", "\"dragleave\" #: OVER = \"dragover\" #: START = \"dragstart\" #: DROP = \"drop\"", "extend to give your obj event dispatching abilities \"\"\" def __init__(self, *args, **kwargs):", "= \"onComplete\" #: TIMER = \"onTimer\" #: _source = None @property def source(self):", "None @property def source(self): return self._source @source.setter def source(self, source): self._source = source", "\"playing\" #: PROGRESS = \"progress\" #: RATECHANGE = \"ratechange\" #: RESIZE = \"resize\"", "\"dblclick\" #: MOUSEDOWN = \"mousedown\" #: MOUSEENTER = \"mouseenter\" #: MOUSELEAVE = \"mouseleave\"", "affected by the insertion/deletion \"\"\" self.inputType \"\"\" Returns the type of the change", "self.oncut) # self.addEventListener(ClipboardEvent.COPY, self.oncopy) # self.addEventListener(ClipboardEvent.PASTE, self.onpaste) def onabort(self, event): print(event) raise NotImplementedError", "print(event) raise NotImplementedError def onkeydown(self, event): print(event) raise NotImplementedError def onkeypress(self, event): print(event)", "def onselectstart(self, event): print(event) raise NotImplementedError def onshow(self, event): print(event) raise NotImplementedError def", "*args, **kwargs) class PageTransitionEvent(Event): \"\"\" PageTransitionEvent \"\"\" PAGEHIDE = \"pagehide\" #: PAGESHOW =", "onresize(self, event): print(event) raise NotImplementedError def onscroll(self, event): print(event) raise NotImplementedError def onseeked(self,", "an array containing target ranges that will be affected by the insertion/deletion \"\"\"", "self.key # def isComposing(self, *args, **kwargs): # pass # KeyboardEvent # isComposing Returns", "dispatching abilities \"\"\" def __init__(self, *args, **kwargs): self.listeners = {} def hasEventListener(self, _type):", "viewArg self.charArg = charArg self.keyArg = keyArg self.locationArg = locationArg self.modifiersListArg = modifiersListArg", "BEFOREUNLOAD = \"beforeunload\" #: \"\"\" BeforeUnloadEvent \"\"\" def __init__(self, _type, *args, **kwargs): super().__init__(_type,", "thing in stack: if thing == callback: stack.remove(thing) return def dispatchEvent(self, event): if", "\"drop\" #: def __init__(self, _type, *args, **kwargs): self.dataTransfer = None \"\"\" Returns the", "self.composed = None # self.currentTarget = None # self.eventPhase = None # self.isTrusted", "print(event) raise NotImplementedError def onprogress(self, event): print(event) raise NotImplementedError def onratechange(self, event): print(event)", "msConvertURL(self): pass def preventDefault(self): pass def stopImmediatePropagation(self): pass class MouseEvent(Event): \"\"\" mouse events", "None \"\"\" Returns the name of the animation \"\"\" self.elapsedTime = None \"\"\"", "#: CONTEXTMENU = \"contextmenu\" #: DBLCLICK = \"dblclick\" #: MOUSEDOWN = \"mousedown\" #:", "the position of the last mousemove event MouseEvent # MovementY Returns the vertical", "NotImplementedError def onpointerenter(self, event): print(event) raise NotImplementedError def onpointerleave(self, event): print(event) raise NotImplementedError", "modifiersListArg self.repeat = repeat @property def altKey(self): return self._altKey @property def ctrlKey(self): return", "*args, **kwargs): self.animationName = None \"\"\" Returns the name of the animation \"\"\"", "def oncuechange(self, event): print(event) raise NotImplementedError def ondblclick(self, event): print(event) raise NotImplementedError def", "KeyboardEvent # location Returns the location of a key on the keyboard or", "* 1000)) # self.type = None pass def msConvertURL(self): pass def preventDefault(self): pass", "#: def __init__(self, _type, *args, **kwargs): # self.args = args # self.kwargs =", "class PageTransitionEvent(Event): \"\"\" PageTransitionEvent \"\"\" PAGEHIDE = \"pagehide\" #: PAGESHOW = \"pageshow\" #:", "**kwargs) class ClipboardEvent(Event): \"\"\" ClipboardEvent \"\"\" COPY = \"copy\" #: CUT = \"cut\"", "= None super().__init__(_type, *args, **kwargs) def initCustomEvent(self): pass class GamePadEvent(Event): \"\"\" GamePadEvent \"\"\"", "pass def stopImmediatePropagation(self): pass class MouseEvent(Event): \"\"\" mouse events \"\"\" CLICK = \"click\"", "{\"bubbles\":true, \"cancelable\":false}); def __init__(self, _type=None, *args, **kwargs): # print('type', _type) self.type = _type", "= \"animationstart\" #: def __init__(self, _type, *args, **kwargs): self.animationName = None \"\"\" Returns", "= kwargs self.x = 0 self.y = 0 self._clientX = 0 self._clientX =", "metaKey(self): return self._metaKey @property def unicode(self): return self.key # @property # def keyCode(self):", "self.cancelable = None self.cancelBubble = None self.composed = None self.currentTarget = None self.defaultPrevented", "the event self.locale = None super().__init__(_type, *args, **kwargs) class FocusEvent(Event): \"\"\" FocusEvent \"\"\"", "import * import time # TODO - bring EventTarget here and get rid", "_type=None, *args, **kwargs): # print('type', _type) self.type = _type self.bubbles = None self.cancelable", "\"\"\" START = \"onStart\" #: STOP = \"onStop\" #: RESET = \"onReset\" #:", "NotImplementedError def onkeydown(self, event): print(event) raise NotImplementedError def onkeypress(self, event): print(event) raise NotImplementedError", "def addEventListener(self, _type, callback, *args, **kwargs): if _type not in self.listeners: self.listeners[_type] =", "SEARCH = \"search\" #: SEEKED = \"seeked\" #: SEEKING = \"seeking\" #: SELECT", "def onprogress(self, event): print(event) raise NotImplementedError def onratechange(self, event): print(event) raise NotImplementedError def", "Returns the type of the change (i.e \"inserting\" or \"deleting\") \"\"\" self.isComposing \"\"\"", "def onshow(self, event): print(event) raise NotImplementedError def onstalled(self, event): print(event) raise NotImplementedError def", "onmouseup(self, event): print(event) raise NotImplementedError def onpause(self, event): print(event) raise NotImplementedError def onplay(self,", "Returns the name of the transition\"\"\" self.elapsedTime = None \"\"\" Returns the number", "has been running \"\"\" self.pseudoElement = None \"\"\" Returns the name of the", "= \"select\" #: SHOW = \"show\" #: STALLED = \"stalled\" #: SUBMIT =", "relative to the position of the edge of the target element MouseEvent #", "\"\"\" TransitionEvent \"\"\" TRANSITIONEND = \"transitionend\" #: def __init__(self, _type, *args, **kwargs): self.propertyName", "onmouseover(self, event): print(event) raise NotImplementedError def onmouseup(self, event): print(event) raise NotImplementedError def onpause(self,", "WHEEL #: WHEEL = \"wheel\" #: def __init__(self, _type, *args, **kwargs): self.deltaX =", "return self._source @source.setter def source(self, source): self._source = source def __init__(self, _type, source=None,", "of seconds an animation has been running \"\"\" self.pseudoElement = None \"\"\" Returns", "\"loadedmetadata\" #: MESSAGE = \"message\" #: OFFLINE = \"offline\" #: ONLINE = \"online\"", "event): print(event) raise NotImplementedError def onanimationiteration(self, event): print(event) raise NotImplementedError def onauxclick(self, event):", "NotImplementedError def onloadeddata(self, event): print(event) raise NotImplementedError def onloadedmetadata(self, event): print(event) raise NotImplementedError", "= time.time_ns() // 1000000 3.7 up self.timeStamp = int(round(time.time() * 1000)) def composedPath(self):", "region MouseEvent # relatedTarget Returns the element related to the element that triggered", "clipboard operation \"\"\" super().__init__(_type, *args, **kwargs) class ErrorEvent(Event): \"\"\" ErrorEvent \"\"\" ERROR =", "onpointerleave(self, event): print(event) raise NotImplementedError def onpointermove(self, event): print(event) raise NotImplementedError def onpointerout(self,", "event): print(event) raise NotImplementedError def ondrop(self, event): print(event) raise NotImplementedError def ondurationchange(self, event):", "pointer, relative to the document, when the mouse event was triggered MouseEvent #", "None self.deltaY = None self.deltaZ = None self.deltaMode = None super().__init__(_type, *args, **kwargs)", "\"\"\" Returns an object representing the affected storage object \"\"\" self.url = None", "RESET = \"reset\" #: SCROLL = \"scroll\" #: SEARCH = \"search\" #: SEEKED", "**kwargs): self.clipboardData = None \"\"\" Returns an object containing the data affected by", "modifiersListArg, repeat): self._type = typeArg self.canBubbleArg = canBubbleArg self.cancelableArg = cancelableArg self.viewArg =", "#: def __init__(self, _type, *args, **kwargs): self.persisted = None \"\"\" Returns whether the", "*args, **kwargs): super().__init__(_type, *args, **kwargs) class TimerEvent(Event): TIMER = \"timer\" #: \"\"\" TimerEvent", "state of the event is composing or not InputEvent, KeyboardEvent # repeat Returns", "\"\"\" DRAG = \"drag\" #: END = \"dragend\" #: ENTER = \"dragenter\" #:", "the name of the transition\"\"\" self.elapsedTime = None \"\"\" Returns the number of", "event): print(event) raise NotImplementedError def onplay(self, event): print(event) raise NotImplementedError def onplaying(self, event):", "\"dragexit\" #: LEAVE = \"dragleave\" #: OVER = \"dragover\" #: START = \"dragstart\"", "= 0 self._clientX = 0 self._clientX = 0 self._altKey = False self._ctrlKey =", "**kwargs): if _type not in self.listeners: self.listeners[_type] = [] self.listeners[_type].append(callback) def removeEventListener(self, _type,", "print(event) raise NotImplementedError def onmousedown(self, event): print(event) raise NotImplementedError def ontouchcancel(self, event): print(event)", "SEEKED = \"seeked\" #: SEEKING = \"seeking\" #: SELECT = \"select\" #: SHOW", "which(self): return self._button # MOUSE_EVENT # getModifierState() Returns an array containing target ranges", "*args, **kwargs): self.propertyName = None \"\"\" Returns the name of the transition\"\"\" self.elapsedTime", "self.addEventListener(DragEvent.END, self.ondragend) # self.addEventListener(DragEvent.ENTER, self.ondragenter) # self.addEventListener(DragEvent.EXIT, self.ondragexit) # self.addEventListener(DragEvent.LEAVE, self.ondragleave) # self.addEventListener(DragEvent.OVER,", "events \"\"\" CLICK = \"click\" #: CONTEXTMENU = \"contextmenu\" #: DBLCLICK = \"dblclick\"", "_type, *args, **kwargs): self.shiftKey = None self.altKey = None self.changedTouches = None self.ctrlKey", "self.addEventListener(DragEvent.START, self.ondragstart) # self.addEventListener(DragEvent.DROP, self.ondrop) # self.addEventListener(ClipboardEvent.CUT, self.oncut) # self.addEventListener(ClipboardEvent.COPY, self.oncopy) # self.addEventListener(ClipboardEvent.PASTE,", "NotImplementedError def onselectionchange(self, event): print(event) raise NotImplementedError def onselectstart(self, event): print(event) raise NotImplementedError", "keyCode(self): # return self.keyCode # @property # def charCode(self): # return self.charCode #", "_type self.bubbles = None self.cancelable = None self.cancelBubble = None self.composed = None", "\"\"\" PopStateEvent \"\"\" def __init__(self, _type, *args, **kwargs): self.state = None \"\"\" Returns", "\"\"\" Returns the name of the transition\"\"\" self.elapsedTime = None \"\"\" Returns the", "\"\"\" Returns an object containing the data affected by the clipboard operation \"\"\"", "raise NotImplementedError def onformdata(self, event): print(event) raise NotImplementedError def onmousedown(self, event): print(event) raise", "self.screenY = screenY self._clientX = clientX self._clientY = clientY self._ctrlKey = ctrlKey self._altKey", "onmousemove(self, event): print(event) raise NotImplementedError def onmouseout(self, event): print(event) raise NotImplementedError def onmouseover(self,", "Returns the horizontal coordinate of the mouse pointer, relative to the document, when", "event): print(event) raise NotImplementedError def oncancel(self, event): print(event) raise NotImplementedError def oncanplay(self, event):", "*args, **kwargs) class ClipboardEvent(Event): \"\"\" ClipboardEvent \"\"\" COPY = \"copy\" #: CUT =", "event): print(event) raise NotImplementedError def oncuechange(self, event): print(event) raise NotImplementedError def ondblclick(self, event):", "AnimationEvent \"\"\" ANIMATIONEND = \"animationend\" #: ANIMATIONITERATION = \"animationiteration\" #: ANIMATIONSTART = \"animationstart\"", "@property def altKey(self): return self._altKey @property def ctrlKey(self): return self._ctrlKey @property def shiftKey(self):", "about the inserted/deleted data \"\"\" self.getTargetRanges \"\"\" Returns an array containing target ranges", "URL of the changed item's document \"\"\" super().__init__(_type, *args, **kwargs) class TransitionEvent(Event): \"\"\"", "self._ctrlKey = ctrlKey self._altKey = altKey self._shiftKey = shiftKey self._metaKey = metaKey self._button", "\"\"\" super().__init__(_type, *args, **kwargs) class ClipboardEvent(Event): \"\"\" ClipboardEvent \"\"\" COPY = \"copy\" #:", "onplay(self, event): print(event) raise NotImplementedError def onplaying(self, event): print(event) raise NotImplementedError def onpointercancel(self,", "None \"\"\" Returns the old value of the changed storage item \"\"\" self.storageArea", "the inserted characters \"\"\" self.dataTransfer \"\"\" Returns an object containing information about the", "buttons(self): return self._buttons @property def which(self): return self._button # MOUSE_EVENT # getModifierState() Returns", "def ongotpointercapture(self, event): print(event) raise NotImplementedError def oninput(self, event): print(event) raise NotImplementedError def", "self.tiltX = None self.tiltY = None self.twist = None self.pointerType = None self.isPrimary", "# huh?. surely false? stack = self.listeners[event.type] # .slice() event.target = self #" ]
[ "= (x.T[index] - min_col)/(max_col - min_col) else: x.T[index] = x.T[index] - min_col return", "= df.values if shuffle: np.random.shuffle(df) train = df[:int(df.shape[0]*split)] validation = df[int(df.shape[0]*split):] train_x, train_y", "import numpy as np import torch def min_max_x(x): for index, col in enumerate(x.T):", "if shuffle: np.random.shuffle(df) train = df[:int(df.shape[0]*split)] validation = df[int(df.shape[0]*split):] train_x, train_y = train.T[:12].T,", "def load_dataset(path='./processed_dataset/data.csv', split=0.8, shuffle=True, seed=0): np.random.seed(seed) df = pd.read_csv(path) df = df.values if", "validation_x, validation_y = train_x.astype(np.float32), train_y.astype(np.float32), validation_x.astype(np.float32), validation_y.astype(np.float32) train_x, train_y, validation_x, validation_y = torch.from_numpy(train_x),", "validation_x = min_max_x(train_x), min_max_x(validation_x) train_x, train_y, validation_x, validation_y = train_x.astype(np.float32), train_y.astype(np.float32), validation_x.astype(np.float32), validation_y.astype(np.float32)", "load_dataset(path='./processed_dataset/data.csv', split=0.8, shuffle=True, seed=0): np.random.seed(seed) df = pd.read_csv(path) df = df.values if shuffle:", "train.T[12:].T validation_x, validation_y = validation.T[:12].T, validation.T[12:].T train_x, validation_x = min_max_x(train_x), min_max_x(validation_x) train_x, train_y,", "if min_col != max_col: x.T[index] = (x.T[index] - min_col)/(max_col - min_col) else: x.T[index]", "torch.from_numpy(train_x), torch.from_numpy(train_y), torch.from_numpy(validation_x), torch.from_numpy(validation_y) return train_x, train_y, validation_x, validation_y if __name__ == '__main__':", "= train.T[:12].T, train.T[12:].T validation_x, validation_y = validation.T[:12].T, validation.T[12:].T train_x, validation_x = min_max_x(train_x), min_max_x(validation_x)", "(x.T[index] - min_col)/(max_col - min_col) else: x.T[index] = x.T[index] - min_col return x", "torch.from_numpy(validation_x), torch.from_numpy(validation_y) return train_x, train_y, validation_x, validation_y if __name__ == '__main__': train_x, train_y,", "pd import numpy as np import torch def min_max_x(x): for index, col in", "seed=0): np.random.seed(seed) df = pd.read_csv(path) df = df.values if shuffle: np.random.shuffle(df) train =", "min_col) else: x.T[index] = x.T[index] - min_col return x def load_dataset(path='./processed_dataset/data.csv', split=0.8, shuffle=True,", "= df[:int(df.shape[0]*split)] validation = df[int(df.shape[0]*split):] train_x, train_y = train.T[:12].T, train.T[12:].T validation_x, validation_y =", "df = pd.read_csv(path) df = df.values if shuffle: np.random.shuffle(df) train = df[:int(df.shape[0]*split)] validation", "return train_x, train_y, validation_x, validation_y if __name__ == '__main__': train_x, train_y, validation_x, validation_y", "else: x.T[index] = x.T[index] - min_col return x def load_dataset(path='./processed_dataset/data.csv', split=0.8, shuffle=True, seed=0):", "validation = df[int(df.shape[0]*split):] train_x, train_y = train.T[:12].T, train.T[12:].T validation_x, validation_y = validation.T[:12].T, validation.T[12:].T", "as pd import numpy as np import torch def min_max_x(x): for index, col", "np.min(col) max_col = np.max(col) if min_col != max_col: x.T[index] = (x.T[index] - min_col)/(max_col", "import pandas as pd import numpy as np import torch def min_max_x(x): for", "def min_max_x(x): for index, col in enumerate(x.T): min_col = np.min(col) max_col = np.max(col)", "train_y = train.T[:12].T, train.T[12:].T validation_x, validation_y = validation.T[:12].T, validation.T[12:].T train_x, validation_x = min_max_x(train_x),", "df[:int(df.shape[0]*split)] validation = df[int(df.shape[0]*split):] train_x, train_y = train.T[:12].T, train.T[12:].T validation_x, validation_y = validation.T[:12].T,", "x.T[index] = (x.T[index] - min_col)/(max_col - min_col) else: x.T[index] = x.T[index] - min_col", "max_col = np.max(col) if min_col != max_col: x.T[index] = (x.T[index] - min_col)/(max_col -", "pandas as pd import numpy as np import torch def min_max_x(x): for index,", "train_y, validation_x, validation_y = train_x.astype(np.float32), train_y.astype(np.float32), validation_x.astype(np.float32), validation_y.astype(np.float32) train_x, train_y, validation_x, validation_y =", "numpy as np import torch def min_max_x(x): for index, col in enumerate(x.T): min_col", "index, col in enumerate(x.T): min_col = np.min(col) max_col = np.max(col) if min_col !=", "x.T[index] = x.T[index] - min_col return x def load_dataset(path='./processed_dataset/data.csv', split=0.8, shuffle=True, seed=0): np.random.seed(seed)", "validation_x.astype(np.float32), validation_y.astype(np.float32) train_x, train_y, validation_x, validation_y = torch.from_numpy(train_x), torch.from_numpy(train_y), torch.from_numpy(validation_x), torch.from_numpy(validation_y) return train_x,", "validation_y if __name__ == '__main__': train_x, train_y, validation_x, validation_y = load_dataset() print(train_x.shape, train_y.shape,", "if __name__ == '__main__': train_x, train_y, validation_x, validation_y = load_dataset() print(train_x.shape, train_y.shape, validation_x.shape,", "x def load_dataset(path='./processed_dataset/data.csv', split=0.8, shuffle=True, seed=0): np.random.seed(seed) df = pd.read_csv(path) df = df.values", "__name__ == '__main__': train_x, train_y, validation_x, validation_y = load_dataset() print(train_x.shape, train_y.shape, validation_x.shape, validation_y.shape)", "min_col = np.min(col) max_col = np.max(col) if min_col != max_col: x.T[index] = (x.T[index]", "= np.min(col) max_col = np.max(col) if min_col != max_col: x.T[index] = (x.T[index] -", "torch.from_numpy(validation_y) return train_x, train_y, validation_x, validation_y if __name__ == '__main__': train_x, train_y, validation_x,", "train_y.astype(np.float32), validation_x.astype(np.float32), validation_y.astype(np.float32) train_x, train_y, validation_x, validation_y = torch.from_numpy(train_x), torch.from_numpy(train_y), torch.from_numpy(validation_x), torch.from_numpy(validation_y) return", "min_col)/(max_col - min_col) else: x.T[index] = x.T[index] - min_col return x def load_dataset(path='./processed_dataset/data.csv',", "validation_y = torch.from_numpy(train_x), torch.from_numpy(train_y), torch.from_numpy(validation_x), torch.from_numpy(validation_y) return train_x, train_y, validation_x, validation_y if __name__", "np import torch def min_max_x(x): for index, col in enumerate(x.T): min_col = np.min(col)", "train = df[:int(df.shape[0]*split)] validation = df[int(df.shape[0]*split):] train_x, train_y = train.T[:12].T, train.T[12:].T validation_x, validation_y", "= torch.from_numpy(train_x), torch.from_numpy(train_y), torch.from_numpy(validation_x), torch.from_numpy(validation_y) return train_x, train_y, validation_x, validation_y if __name__ ==", "max_col: x.T[index] = (x.T[index] - min_col)/(max_col - min_col) else: x.T[index] = x.T[index] -", "validation_x, validation_y if __name__ == '__main__': train_x, train_y, validation_x, validation_y = load_dataset() print(train_x.shape,", "train_x, validation_x = min_max_x(train_x), min_max_x(validation_x) train_x, train_y, validation_x, validation_y = train_x.astype(np.float32), train_y.astype(np.float32), validation_x.astype(np.float32),", "torch def min_max_x(x): for index, col in enumerate(x.T): min_col = np.min(col) max_col =", "np.random.shuffle(df) train = df[:int(df.shape[0]*split)] validation = df[int(df.shape[0]*split):] train_x, train_y = train.T[:12].T, train.T[12:].T validation_x,", "train_y, validation_x, validation_y = torch.from_numpy(train_x), torch.from_numpy(train_y), torch.from_numpy(validation_x), torch.from_numpy(validation_y) return train_x, train_y, validation_x, validation_y", "in enumerate(x.T): min_col = np.min(col) max_col = np.max(col) if min_col != max_col: x.T[index]", "= df[int(df.shape[0]*split):] train_x, train_y = train.T[:12].T, train.T[12:].T validation_x, validation_y = validation.T[:12].T, validation.T[12:].T train_x,", "torch.from_numpy(train_y), torch.from_numpy(validation_x), torch.from_numpy(validation_y) return train_x, train_y, validation_x, validation_y if __name__ == '__main__': train_x,", "- min_col return x def load_dataset(path='./processed_dataset/data.csv', split=0.8, shuffle=True, seed=0): np.random.seed(seed) df = pd.read_csv(path)", "x.T[index] - min_col return x def load_dataset(path='./processed_dataset/data.csv', split=0.8, shuffle=True, seed=0): np.random.seed(seed) df =", "= min_max_x(train_x), min_max_x(validation_x) train_x, train_y, validation_x, validation_y = train_x.astype(np.float32), train_y.astype(np.float32), validation_x.astype(np.float32), validation_y.astype(np.float32) train_x,", "min_max_x(train_x), min_max_x(validation_x) train_x, train_y, validation_x, validation_y = train_x.astype(np.float32), train_y.astype(np.float32), validation_x.astype(np.float32), validation_y.astype(np.float32) train_x, train_y,", "= x.T[index] - min_col return x def load_dataset(path='./processed_dataset/data.csv', split=0.8, shuffle=True, seed=0): np.random.seed(seed) df", "np.random.seed(seed) df = pd.read_csv(path) df = df.values if shuffle: np.random.shuffle(df) train = df[:int(df.shape[0]*split)]", "np.max(col) if min_col != max_col: x.T[index] = (x.T[index] - min_col)/(max_col - min_col) else:", "min_max_x(validation_x) train_x, train_y, validation_x, validation_y = train_x.astype(np.float32), train_y.astype(np.float32), validation_x.astype(np.float32), validation_y.astype(np.float32) train_x, train_y, validation_x,", "- min_col)/(max_col - min_col) else: x.T[index] = x.T[index] - min_col return x def", "validation_x, validation_y = validation.T[:12].T, validation.T[12:].T train_x, validation_x = min_max_x(train_x), min_max_x(validation_x) train_x, train_y, validation_x,", "df.values if shuffle: np.random.shuffle(df) train = df[:int(df.shape[0]*split)] validation = df[int(df.shape[0]*split):] train_x, train_y =", "pd.read_csv(path) df = df.values if shuffle: np.random.shuffle(df) train = df[:int(df.shape[0]*split)] validation = df[int(df.shape[0]*split):]", "train_x, train_y, validation_x, validation_y if __name__ == '__main__': train_x, train_y, validation_x, validation_y =", "!= max_col: x.T[index] = (x.T[index] - min_col)/(max_col - min_col) else: x.T[index] = x.T[index]", "train_x, train_y, validation_x, validation_y = train_x.astype(np.float32), train_y.astype(np.float32), validation_x.astype(np.float32), validation_y.astype(np.float32) train_x, train_y, validation_x, validation_y", "min_col return x def load_dataset(path='./processed_dataset/data.csv', split=0.8, shuffle=True, seed=0): np.random.seed(seed) df = pd.read_csv(path) df", "validation.T[:12].T, validation.T[12:].T train_x, validation_x = min_max_x(train_x), min_max_x(validation_x) train_x, train_y, validation_x, validation_y = train_x.astype(np.float32),", "validation_y = validation.T[:12].T, validation.T[12:].T train_x, validation_x = min_max_x(train_x), min_max_x(validation_x) train_x, train_y, validation_x, validation_y", "enumerate(x.T): min_col = np.min(col) max_col = np.max(col) if min_col != max_col: x.T[index] =", "min_max_x(x): for index, col in enumerate(x.T): min_col = np.min(col) max_col = np.max(col) if", "for index, col in enumerate(x.T): min_col = np.min(col) max_col = np.max(col) if min_col", "as np import torch def min_max_x(x): for index, col in enumerate(x.T): min_col =", "- min_col) else: x.T[index] = x.T[index] - min_col return x def load_dataset(path='./processed_dataset/data.csv', split=0.8,", "return x def load_dataset(path='./processed_dataset/data.csv', split=0.8, shuffle=True, seed=0): np.random.seed(seed) df = pd.read_csv(path) df =", "train_y, validation_x, validation_y if __name__ == '__main__': train_x, train_y, validation_x, validation_y = load_dataset()", "train_x, train_y, validation_x, validation_y = torch.from_numpy(train_x), torch.from_numpy(train_y), torch.from_numpy(validation_x), torch.from_numpy(validation_y) return train_x, train_y, validation_x,", "= pd.read_csv(path) df = df.values if shuffle: np.random.shuffle(df) train = df[:int(df.shape[0]*split)] validation =", "validation_x, validation_y = torch.from_numpy(train_x), torch.from_numpy(train_y), torch.from_numpy(validation_x), torch.from_numpy(validation_y) return train_x, train_y, validation_x, validation_y if", "df[int(df.shape[0]*split):] train_x, train_y = train.T[:12].T, train.T[12:].T validation_x, validation_y = validation.T[:12].T, validation.T[12:].T train_x, validation_x", "validation_y = train_x.astype(np.float32), train_y.astype(np.float32), validation_x.astype(np.float32), validation_y.astype(np.float32) train_x, train_y, validation_x, validation_y = torch.from_numpy(train_x), torch.from_numpy(train_y),", "split=0.8, shuffle=True, seed=0): np.random.seed(seed) df = pd.read_csv(path) df = df.values if shuffle: np.random.shuffle(df)", "= validation.T[:12].T, validation.T[12:].T train_x, validation_x = min_max_x(train_x), min_max_x(validation_x) train_x, train_y, validation_x, validation_y =", "validation_y.astype(np.float32) train_x, train_y, validation_x, validation_y = torch.from_numpy(train_x), torch.from_numpy(train_y), torch.from_numpy(validation_x), torch.from_numpy(validation_y) return train_x, train_y,", "train_x, train_y = train.T[:12].T, train.T[12:].T validation_x, validation_y = validation.T[:12].T, validation.T[12:].T train_x, validation_x =", "shuffle=True, seed=0): np.random.seed(seed) df = pd.read_csv(path) df = df.values if shuffle: np.random.shuffle(df) train", "= train_x.astype(np.float32), train_y.astype(np.float32), validation_x.astype(np.float32), validation_y.astype(np.float32) train_x, train_y, validation_x, validation_y = torch.from_numpy(train_x), torch.from_numpy(train_y), torch.from_numpy(validation_x),", "validation.T[12:].T train_x, validation_x = min_max_x(train_x), min_max_x(validation_x) train_x, train_y, validation_x, validation_y = train_x.astype(np.float32), train_y.astype(np.float32),", "import torch def min_max_x(x): for index, col in enumerate(x.T): min_col = np.min(col) max_col", "train.T[:12].T, train.T[12:].T validation_x, validation_y = validation.T[:12].T, validation.T[12:].T train_x, validation_x = min_max_x(train_x), min_max_x(validation_x) train_x,", "= np.max(col) if min_col != max_col: x.T[index] = (x.T[index] - min_col)/(max_col - min_col)", "min_col != max_col: x.T[index] = (x.T[index] - min_col)/(max_col - min_col) else: x.T[index] =", "col in enumerate(x.T): min_col = np.min(col) max_col = np.max(col) if min_col != max_col:", "train_x.astype(np.float32), train_y.astype(np.float32), validation_x.astype(np.float32), validation_y.astype(np.float32) train_x, train_y, validation_x, validation_y = torch.from_numpy(train_x), torch.from_numpy(train_y), torch.from_numpy(validation_x), torch.from_numpy(validation_y)", "df = df.values if shuffle: np.random.shuffle(df) train = df[:int(df.shape[0]*split)] validation = df[int(df.shape[0]*split):] train_x,", "shuffle: np.random.shuffle(df) train = df[:int(df.shape[0]*split)] validation = df[int(df.shape[0]*split):] train_x, train_y = train.T[:12].T, train.T[12:].T" ]
[]
[ "nj.get_id() ni_sigma = nj.get_psigma() dfa[(ni_id,ni_sigma)] = nj_id DFA_utils_tree_only.clean_dfa(q_0, dfa, T) # Adding the", "equivalent DFA q_0 = 0 q_pos = 1 q_neg = 2 # assigning", "This code returns a DFA that is equivalent to the Tree constructed by", "dfa = {} for ni in nodes: if ni.is_terminal(): continue ni_id = ni.get_id()", "into one tree. \"\"\" import read_traces, DFA_utils_tree_only, time, tree_utils def solve_tree_only(g_pos, G, Sigma,", "DFA q_0 = 0 q_pos = 1 q_neg = 2 # assigning ids", "= 3 for n in nodes: if n.is_root(): n.assign_id(q_0) elif n.is_positive_node(): n.assign_id(q_pos) elif", "n.assign_id(q_0) elif n.is_positive_node(): n.assign_id(q_pos) elif n.is_negative_node(): n.assign_id(q_neg) else: n.assign_id(n_current) n_current += 1 #", "is equivalent to the Tree constructed by compressing all the traces into one", "prune=False) nodes = tree_utils.get_reachable_nodes(tree) # creating an equivalent DFA q_0 = 0 q_pos", "0 q_pos = 1 q_neg = 2 # assigning ids to each node", "in nodes: if ni.is_terminal(): continue ni_id = ni.get_id() for nj in ni.get_children(): nj_id", "2 # assigning ids to each node n_current = 3 for n in", "in G\" # creating the auxiliary tree structure tree = tree_utils.create_tree(g_pos, G, Sigma,", "assert g_pos in G, f\"Error, g_pos not in G\" # creating the auxiliary", "be_quiet=False): assert g_pos in G, f\"Error, g_pos not in G\" # creating the", "the auxiliary tree structure tree = tree_utils.create_tree(g_pos, G, Sigma, T, prune=False) nodes =", "n.assign_id(q_neg) else: n.assign_id(n_current) n_current += 1 # creating the dfa dfa = {}", "node n_current = 3 for n in nodes: if n.is_root(): n.assign_id(q_0) elif n.is_positive_node():", "elif n.is_positive_node(): n.assign_id(q_pos) elif n.is_negative_node(): n.assign_id(q_neg) else: n.assign_id(n_current) n_current += 1 # creating", "structure tree = tree_utils.create_tree(g_pos, G, Sigma, T, prune=False) nodes = tree_utils.get_reachable_nodes(tree) # creating", "else: n.assign_id(n_current) n_current += 1 # creating the dfa dfa = {} for", "not in G\" # creating the auxiliary tree structure tree = tree_utils.create_tree(g_pos, G,", "Tree constructed by compressing all the traces into one tree. \"\"\" import read_traces,", "an equivalent DFA q_0 = 0 q_pos = 1 q_neg = 2 #", "to each node n_current = 3 for n in nodes: if n.is_root(): n.assign_id(q_0)", "nj_id = nj.get_id() ni_sigma = nj.get_psigma() dfa[(ni_id,ni_sigma)] = nj_id DFA_utils_tree_only.clean_dfa(q_0, dfa, T) #", "nj.get_psigma() dfa[(ni_id,ni_sigma)] = nj_id DFA_utils_tree_only.clean_dfa(q_0, dfa, T) # Adding the probabilities pos_prob =", "in G, f\"Error, g_pos not in G\" # creating the auxiliary tree structure", "dfa dfa = {} for ni in nodes: if ni.is_terminal(): continue ni_id =", "the Tree constructed by compressing all the traces into one tree. \"\"\" import", "tree. \"\"\" import read_traces, DFA_utils_tree_only, time, tree_utils def solve_tree_only(g_pos, G, Sigma, T, timeout,", "compressing all the traces into one tree. \"\"\" import read_traces, DFA_utils_tree_only, time, tree_utils", "dfa[(ni_id,ni_sigma)] = nj_id DFA_utils_tree_only.clean_dfa(q_0, dfa, T) # Adding the probabilities pos_prob = DFA_utils_tree_only.add_probabilities(q_0,", "1 # creating the dfa dfa = {} for ni in nodes: if", "in nodes: if n.is_root(): n.assign_id(q_0) elif n.is_positive_node(): n.assign_id(q_pos) elif n.is_negative_node(): n.assign_id(q_neg) else: n.assign_id(n_current)", "n.assign_id(n_current) n_current += 1 # creating the dfa dfa = {} for ni", "n_current += 1 # creating the dfa dfa = {} for ni in", "T, prune=False) nodes = tree_utils.get_reachable_nodes(tree) # creating an equivalent DFA q_0 = 0", "returns a DFA that is equivalent to the Tree constructed by compressing all", "ids to each node n_current = 3 for n in nodes: if n.is_root():", "creating an equivalent DFA q_0 = 0 q_pos = 1 q_neg = 2", "n.is_negative_node(): n.assign_id(q_neg) else: n.assign_id(n_current) n_current += 1 # creating the dfa dfa =", "DFA that is equivalent to the Tree constructed by compressing all the traces", "nodes: if ni.is_terminal(): continue ni_id = ni.get_id() for nj in ni.get_children(): nj_id =", "info, be_quiet=False): assert g_pos in G, f\"Error, g_pos not in G\" # creating", "tree_utils.create_tree(g_pos, G, Sigma, T, prune=False) nodes = tree_utils.get_reachable_nodes(tree) # creating an equivalent DFA", "n.is_positive_node(): n.assign_id(q_pos) elif n.is_negative_node(): n.assign_id(q_neg) else: n.assign_id(n_current) n_current += 1 # creating the", "# creating the auxiliary tree structure tree = tree_utils.create_tree(g_pos, G, Sigma, T, prune=False)", "ni_sigma = nj.get_psigma() dfa[(ni_id,ni_sigma)] = nj_id DFA_utils_tree_only.clean_dfa(q_0, dfa, T) # Adding the probabilities", "\"\"\" import read_traces, DFA_utils_tree_only, time, tree_utils def solve_tree_only(g_pos, G, Sigma, T, timeout, info,", "= ni.get_id() for nj in ni.get_children(): nj_id = nj.get_id() ni_sigma = nj.get_psigma() dfa[(ni_id,ni_sigma)]", "# Adding the probabilities pos_prob = DFA_utils_tree_only.add_probabilities(q_0, dfa, T, g_pos) return q_0, dfa,", "f\"Error, g_pos not in G\" # creating the auxiliary tree structure tree =", "nj_id DFA_utils_tree_only.clean_dfa(q_0, dfa, T) # Adding the probabilities pos_prob = DFA_utils_tree_only.add_probabilities(q_0, dfa, T,", "= nj.get_psigma() dfa[(ni_id,ni_sigma)] = nj_id DFA_utils_tree_only.clean_dfa(q_0, dfa, T) # Adding the probabilities pos_prob", "Sigma, T, timeout, info, be_quiet=False): assert g_pos in G, f\"Error, g_pos not in", "equivalent to the Tree constructed by compressing all the traces into one tree.", "= tree_utils.get_reachable_nodes(tree) # creating an equivalent DFA q_0 = 0 q_pos = 1", "Adding the probabilities pos_prob = DFA_utils_tree_only.add_probabilities(q_0, dfa, T, g_pos) return q_0, dfa, pos_prob", "= nj.get_id() ni_sigma = nj.get_psigma() dfa[(ni_id,ni_sigma)] = nj_id DFA_utils_tree_only.clean_dfa(q_0, dfa, T) # Adding", "+= 1 # creating the dfa dfa = {} for ni in nodes:", "ni.get_id() for nj in ni.get_children(): nj_id = nj.get_id() ni_sigma = nj.get_psigma() dfa[(ni_id,ni_sigma)] =", "in ni.get_children(): nj_id = nj.get_id() ni_sigma = nj.get_psigma() dfa[(ni_id,ni_sigma)] = nj_id DFA_utils_tree_only.clean_dfa(q_0, dfa,", "g_pos in G, f\"Error, g_pos not in G\" # creating the auxiliary tree", "q_neg = 2 # assigning ids to each node n_current = 3 for", "G, f\"Error, g_pos not in G\" # creating the auxiliary tree structure tree", "G\" # creating the auxiliary tree structure tree = tree_utils.create_tree(g_pos, G, Sigma, T,", "creating the dfa dfa = {} for ni in nodes: if ni.is_terminal(): continue", "code returns a DFA that is equivalent to the Tree constructed by compressing", "assigning ids to each node n_current = 3 for n in nodes: if", "nodes: if n.is_root(): n.assign_id(q_0) elif n.is_positive_node(): n.assign_id(q_pos) elif n.is_negative_node(): n.assign_id(q_neg) else: n.assign_id(n_current) n_current", "traces into one tree. \"\"\" import read_traces, DFA_utils_tree_only, time, tree_utils def solve_tree_only(g_pos, G,", "# assigning ids to each node n_current = 3 for n in nodes:", "g_pos not in G\" # creating the auxiliary tree structure tree = tree_utils.create_tree(g_pos,", "import read_traces, DFA_utils_tree_only, time, tree_utils def solve_tree_only(g_pos, G, Sigma, T, timeout, info, be_quiet=False):", "timeout, info, be_quiet=False): assert g_pos in G, f\"Error, g_pos not in G\" #", "all the traces into one tree. \"\"\" import read_traces, DFA_utils_tree_only, time, tree_utils def", "= 0 q_pos = 1 q_neg = 2 # assigning ids to each", "= tree_utils.create_tree(g_pos, G, Sigma, T, prune=False) nodes = tree_utils.get_reachable_nodes(tree) # creating an equivalent", "3 for n in nodes: if n.is_root(): n.assign_id(q_0) elif n.is_positive_node(): n.assign_id(q_pos) elif n.is_negative_node():", "def solve_tree_only(g_pos, G, Sigma, T, timeout, info, be_quiet=False): assert g_pos in G, f\"Error,", "each node n_current = 3 for n in nodes: if n.is_root(): n.assign_id(q_0) elif", "n.is_root(): n.assign_id(q_0) elif n.is_positive_node(): n.assign_id(q_pos) elif n.is_negative_node(): n.assign_id(q_neg) else: n.assign_id(n_current) n_current += 1", "tree_utils def solve_tree_only(g_pos, G, Sigma, T, timeout, info, be_quiet=False): assert g_pos in G,", "nj in ni.get_children(): nj_id = nj.get_id() ni_sigma = nj.get_psigma() dfa[(ni_id,ni_sigma)] = nj_id DFA_utils_tree_only.clean_dfa(q_0,", "the traces into one tree. \"\"\" import read_traces, DFA_utils_tree_only, time, tree_utils def solve_tree_only(g_pos,", "G, Sigma, T, prune=False) nodes = tree_utils.get_reachable_nodes(tree) # creating an equivalent DFA q_0", "= 2 # assigning ids to each node n_current = 3 for n", "tree = tree_utils.create_tree(g_pos, G, Sigma, T, prune=False) nodes = tree_utils.get_reachable_nodes(tree) # creating an", "T, timeout, info, be_quiet=False): assert g_pos in G, f\"Error, g_pos not in G\"", "ni_id = ni.get_id() for nj in ni.get_children(): nj_id = nj.get_id() ni_sigma = nj.get_psigma()", "for ni in nodes: if ni.is_terminal(): continue ni_id = ni.get_id() for nj in", "n in nodes: if n.is_root(): n.assign_id(q_0) elif n.is_positive_node(): n.assign_id(q_pos) elif n.is_negative_node(): n.assign_id(q_neg) else:", "by compressing all the traces into one tree. \"\"\" import read_traces, DFA_utils_tree_only, time,", "q_pos = 1 q_neg = 2 # assigning ids to each node n_current", "1 q_neg = 2 # assigning ids to each node n_current = 3", "ni.get_children(): nj_id = nj.get_id() ni_sigma = nj.get_psigma() dfa[(ni_id,ni_sigma)] = nj_id DFA_utils_tree_only.clean_dfa(q_0, dfa, T)", "n.assign_id(q_pos) elif n.is_negative_node(): n.assign_id(q_neg) else: n.assign_id(n_current) n_current += 1 # creating the dfa", "T) # Adding the probabilities pos_prob = DFA_utils_tree_only.add_probabilities(q_0, dfa, T, g_pos) return q_0,", "= {} for ni in nodes: if ni.is_terminal(): continue ni_id = ni.get_id() for", "for n in nodes: if n.is_root(): n.assign_id(q_0) elif n.is_positive_node(): n.assign_id(q_pos) elif n.is_negative_node(): n.assign_id(q_neg)", "tree_utils.get_reachable_nodes(tree) # creating an equivalent DFA q_0 = 0 q_pos = 1 q_neg", "G, Sigma, T, timeout, info, be_quiet=False): assert g_pos in G, f\"Error, g_pos not", "n_current = 3 for n in nodes: if n.is_root(): n.assign_id(q_0) elif n.is_positive_node(): n.assign_id(q_pos)", "\"\"\" This code returns a DFA that is equivalent to the Tree constructed", "if ni.is_terminal(): continue ni_id = ni.get_id() for nj in ni.get_children(): nj_id = nj.get_id()", "# creating the dfa dfa = {} for ni in nodes: if ni.is_terminal():", "creating the auxiliary tree structure tree = tree_utils.create_tree(g_pos, G, Sigma, T, prune=False) nodes", "tree structure tree = tree_utils.create_tree(g_pos, G, Sigma, T, prune=False) nodes = tree_utils.get_reachable_nodes(tree) #", "to the Tree constructed by compressing all the traces into one tree. \"\"\"", "time, tree_utils def solve_tree_only(g_pos, G, Sigma, T, timeout, info, be_quiet=False): assert g_pos in", "that is equivalent to the Tree constructed by compressing all the traces into", "solve_tree_only(g_pos, G, Sigma, T, timeout, info, be_quiet=False): assert g_pos in G, f\"Error, g_pos", "# creating an equivalent DFA q_0 = 0 q_pos = 1 q_neg =", "q_0 = 0 q_pos = 1 q_neg = 2 # assigning ids to", "{} for ni in nodes: if ni.is_terminal(): continue ni_id = ni.get_id() for nj", "DFA_utils_tree_only, time, tree_utils def solve_tree_only(g_pos, G, Sigma, T, timeout, info, be_quiet=False): assert g_pos", "a DFA that is equivalent to the Tree constructed by compressing all the", "nodes = tree_utils.get_reachable_nodes(tree) # creating an equivalent DFA q_0 = 0 q_pos =", "Sigma, T, prune=False) nodes = tree_utils.get_reachable_nodes(tree) # creating an equivalent DFA q_0 =", "elif n.is_negative_node(): n.assign_id(q_neg) else: n.assign_id(n_current) n_current += 1 # creating the dfa dfa", "ni in nodes: if ni.is_terminal(): continue ni_id = ni.get_id() for nj in ni.get_children():", "the dfa dfa = {} for ni in nodes: if ni.is_terminal(): continue ni_id", "auxiliary tree structure tree = tree_utils.create_tree(g_pos, G, Sigma, T, prune=False) nodes = tree_utils.get_reachable_nodes(tree)", "= 1 q_neg = 2 # assigning ids to each node n_current =", "if n.is_root(): n.assign_id(q_0) elif n.is_positive_node(): n.assign_id(q_pos) elif n.is_negative_node(): n.assign_id(q_neg) else: n.assign_id(n_current) n_current +=", "ni.is_terminal(): continue ni_id = ni.get_id() for nj in ni.get_children(): nj_id = nj.get_id() ni_sigma", "dfa, T) # Adding the probabilities pos_prob = DFA_utils_tree_only.add_probabilities(q_0, dfa, T, g_pos) return", "continue ni_id = ni.get_id() for nj in ni.get_children(): nj_id = nj.get_id() ni_sigma =", "DFA_utils_tree_only.clean_dfa(q_0, dfa, T) # Adding the probabilities pos_prob = DFA_utils_tree_only.add_probabilities(q_0, dfa, T, g_pos)", "read_traces, DFA_utils_tree_only, time, tree_utils def solve_tree_only(g_pos, G, Sigma, T, timeout, info, be_quiet=False): assert", "one tree. \"\"\" import read_traces, DFA_utils_tree_only, time, tree_utils def solve_tree_only(g_pos, G, Sigma, T,", "for nj in ni.get_children(): nj_id = nj.get_id() ni_sigma = nj.get_psigma() dfa[(ni_id,ni_sigma)] = nj_id", "= nj_id DFA_utils_tree_only.clean_dfa(q_0, dfa, T) # Adding the probabilities pos_prob = DFA_utils_tree_only.add_probabilities(q_0, dfa,", "constructed by compressing all the traces into one tree. \"\"\" import read_traces, DFA_utils_tree_only," ]
[ "col1, col2, col3, col4, col5 = tf.decode_csv( value, record_defaults=record_defaults) features = tf.stack([col1, col2,", "in case of empty columns. Also specifies the type of the decoded result.", "with tf.Session() as sess: # Start populating the filename queue. coord = tf.train.Coordinator()", "value = reader.read(filename_queue) # Default values, in case of empty columns. Also specifies", "record_defaults = [[1], [1], [1], [1], [1]] col1, col2, col3, col4, col5 =", "the filenames until the reader needs them. # The following line is equivalent", "them. # The following line is equivalent to : # filename_queue = tf.train.string_input_producer([\"file0.csv\",", "for holding the filenames until the reader needs them. # The following line", "the decoded result. # Try a simpler expression: # col1, col2, col3, col4,", "= tf.decode_csv(value, record_defaults=[[1]]*5) record_defaults = [[1], [1], [1], [1], [1]] col1, col2, col3,", "# https://www.tensorflow.org/api_guides/python/reading_data import tensorflow as tf # creates a FIFO queue for holding", "FIFO queue for holding the filenames until the reader needs them. # The", "i in range(2)]) reader = tf.TextLineReader() key, value = reader.read(filename_queue) # Default values,", "expression: # col1, col2, col3, col4, col5 = tf.decode_csv(value, record_defaults=[[1]]*5) record_defaults = [[1],", "the filename queue. coord = tf.train.Coordinator() threads = tf.train.start_queue_runners(coord=coord) for i in range(1200):", "tf # creates a FIFO queue for holding the filenames until the reader", "[1], [1]] col1, col2, col3, col4, col5 = tf.decode_csv( value, record_defaults=record_defaults) features =", "decoded result. # Try a simpler expression: # col1, col2, col3, col4, col5", "value, record_defaults=record_defaults) features = tf.stack([col1, col2, col3, col4]) with tf.Session() as sess: #", "i) for i in range(2)]) reader = tf.TextLineReader() key, value = reader.read(filename_queue) #", "to : # filename_queue = tf.train.string_input_producer([\"file0.csv\", \"file1.csv\"]) filename_queue = tf.train.string_input_producer([(\"file%d\" % i) for", "Start populating the filename queue. coord = tf.train.Coordinator() threads = tf.train.start_queue_runners(coord=coord) for i", "reader.read(filename_queue) # Default values, in case of empty columns. Also specifies the type", "= tf.train.string_input_producer([(\"file%d\" % i) for i in range(2)]) reader = tf.TextLineReader() key, value", "= tf.TextLineReader() key, value = reader.read(filename_queue) # Default values, in case of empty", "for i in range(1200): # Retrieve a single instance: example, label = sess.run([features,", "# Default values, in case of empty columns. Also specifies the type of", "in range(1200): # Retrieve a single instance: example, label = sess.run([features, col5]) coord.request_stop()", "holding the filenames until the reader needs them. # The following line is", "= [[1], [1], [1], [1], [1]] col1, col2, col3, col4, col5 = tf.decode_csv(", "col5 = tf.decode_csv(value, record_defaults=[[1]]*5) record_defaults = [[1], [1], [1], [1], [1]] col1, col2,", "features = tf.stack([col1, col2, col3, col4]) with tf.Session() as sess: # Start populating", "# col1, col2, col3, col4, col5 = tf.decode_csv(value, record_defaults=[[1]]*5) record_defaults = [[1], [1],", "the type of the decoded result. # Try a simpler expression: # col1,", "tf.Session() as sess: # Start populating the filename queue. coord = tf.train.Coordinator() threads", "range(1200): # Retrieve a single instance: example, label = sess.run([features, col5]) coord.request_stop() coord.join(threads)", "col4, col5 = tf.decode_csv(value, record_defaults=[[1]]*5) record_defaults = [[1], [1], [1], [1], [1]] col1,", "# The following line is equivalent to : # filename_queue = tf.train.string_input_producer([\"file0.csv\", \"file1.csv\"])", "[1], [1], [1]] col1, col2, col3, col4, col5 = tf.decode_csv( value, record_defaults=record_defaults) features", "queue for holding the filenames until the reader needs them. # The following", "of empty columns. Also specifies the type of the decoded result. # Try", "a FIFO queue for holding the filenames until the reader needs them. #", "reader = tf.TextLineReader() key, value = reader.read(filename_queue) # Default values, in case of", "case of empty columns. Also specifies the type of the decoded result. #", "for i in range(2)]) reader = tf.TextLineReader() key, value = reader.read(filename_queue) # Default", "creates a FIFO queue for holding the filenames until the reader needs them.", "tf.stack([col1, col2, col3, col4]) with tf.Session() as sess: # Start populating the filename", "Try a simpler expression: # col1, col2, col3, col4, col5 = tf.decode_csv(value, record_defaults=[[1]]*5)", "tf.decode_csv(value, record_defaults=[[1]]*5) record_defaults = [[1], [1], [1], [1], [1]] col1, col2, col3, col4,", "= tf.train.string_input_producer([\"file0.csv\", \"file1.csv\"]) filename_queue = tf.train.string_input_producer([(\"file%d\" % i) for i in range(2)]) reader", "= tf.train.Coordinator() threads = tf.train.start_queue_runners(coord=coord) for i in range(1200): # Retrieve a single", "tf.train.string_input_producer([\"file0.csv\", \"file1.csv\"]) filename_queue = tf.train.string_input_producer([(\"file%d\" % i) for i in range(2)]) reader =", "record_defaults=record_defaults) features = tf.stack([col1, col2, col3, col4]) with tf.Session() as sess: # Start", "= tf.stack([col1, col2, col3, col4]) with tf.Session() as sess: # Start populating the", "[1], [1], [1], [1]] col1, col2, col3, col4, col5 = tf.decode_csv( value, record_defaults=record_defaults)", "as sess: # Start populating the filename queue. coord = tf.train.Coordinator() threads =", "# Source: # https://www.tensorflow.org/api_guides/python/reading_data import tensorflow as tf # creates a FIFO queue", "sess: # Start populating the filename queue. coord = tf.train.Coordinator() threads = tf.train.start_queue_runners(coord=coord)", "populating the filename queue. coord = tf.train.Coordinator() threads = tf.train.start_queue_runners(coord=coord) for i in", "the reader needs them. # The following line is equivalent to : #", "col5 = tf.decode_csv( value, record_defaults=record_defaults) features = tf.stack([col1, col2, col3, col4]) with tf.Session()", "Source: # https://www.tensorflow.org/api_guides/python/reading_data import tensorflow as tf # creates a FIFO queue for", "% i) for i in range(2)]) reader = tf.TextLineReader() key, value = reader.read(filename_queue)", "until the reader needs them. # The following line is equivalent to :", "queue. coord = tf.train.Coordinator() threads = tf.train.start_queue_runners(coord=coord) for i in range(1200): # Retrieve", "key, value = reader.read(filename_queue) # Default values, in case of empty columns. Also", "The following line is equivalent to : # filename_queue = tf.train.string_input_producer([\"file0.csv\", \"file1.csv\"]) filename_queue", "col4]) with tf.Session() as sess: # Start populating the filename queue. coord =", "\"file1.csv\"]) filename_queue = tf.train.string_input_producer([(\"file%d\" % i) for i in range(2)]) reader = tf.TextLineReader()", "tf.TextLineReader() key, value = reader.read(filename_queue) # Default values, in case of empty columns.", "Also specifies the type of the decoded result. # Try a simpler expression:", "specifies the type of the decoded result. # Try a simpler expression: #", "reader needs them. # The following line is equivalent to : # filename_queue", "filenames until the reader needs them. # The following line is equivalent to", "a simpler expression: # col1, col2, col3, col4, col5 = tf.decode_csv(value, record_defaults=[[1]]*5) record_defaults", "filename_queue = tf.train.string_input_producer([(\"file%d\" % i) for i in range(2)]) reader = tf.TextLineReader() key,", "tf.train.start_queue_runners(coord=coord) for i in range(1200): # Retrieve a single instance: example, label =", "following line is equivalent to : # filename_queue = tf.train.string_input_producer([\"file0.csv\", \"file1.csv\"]) filename_queue =", "= tf.train.start_queue_runners(coord=coord) for i in range(1200): # Retrieve a single instance: example, label", "col2, col3, col4, col5 = tf.decode_csv(value, record_defaults=[[1]]*5) record_defaults = [[1], [1], [1], [1],", "columns. Also specifies the type of the decoded result. # Try a simpler", "col2, col3, col4]) with tf.Session() as sess: # Start populating the filename queue.", "i in range(1200): # Retrieve a single instance: example, label = sess.run([features, col5])", "# filename_queue = tf.train.string_input_producer([\"file0.csv\", \"file1.csv\"]) filename_queue = tf.train.string_input_producer([(\"file%d\" % i) for i in", "# Try a simpler expression: # col1, col2, col3, col4, col5 = tf.decode_csv(value,", "as tf # creates a FIFO queue for holding the filenames until the", "record_defaults=[[1]]*5) record_defaults = [[1], [1], [1], [1], [1]] col1, col2, col3, col4, col5", "import tensorflow as tf # creates a FIFO queue for holding the filenames", "line is equivalent to : # filename_queue = tf.train.string_input_producer([\"file0.csv\", \"file1.csv\"]) filename_queue = tf.train.string_input_producer([(\"file%d\"", "is equivalent to : # filename_queue = tf.train.string_input_producer([\"file0.csv\", \"file1.csv\"]) filename_queue = tf.train.string_input_producer([(\"file%d\" %", ": # filename_queue = tf.train.string_input_producer([\"file0.csv\", \"file1.csv\"]) filename_queue = tf.train.string_input_producer([(\"file%d\" % i) for i", "col2, col3, col4, col5 = tf.decode_csv( value, record_defaults=record_defaults) features = tf.stack([col1, col2, col3,", "tf.train.string_input_producer([(\"file%d\" % i) for i in range(2)]) reader = tf.TextLineReader() key, value =", "[[1], [1], [1], [1], [1]] col1, col2, col3, col4, col5 = tf.decode_csv( value,", "col3, col4, col5 = tf.decode_csv( value, record_defaults=record_defaults) features = tf.stack([col1, col2, col3, col4])", "# Start populating the filename queue. coord = tf.train.Coordinator() threads = tf.train.start_queue_runners(coord=coord) for", "= reader.read(filename_queue) # Default values, in case of empty columns. Also specifies the", "col3, col4, col5 = tf.decode_csv(value, record_defaults=[[1]]*5) record_defaults = [[1], [1], [1], [1], [1]]", "tensorflow as tf # creates a FIFO queue for holding the filenames until", "filename_queue = tf.train.string_input_producer([\"file0.csv\", \"file1.csv\"]) filename_queue = tf.train.string_input_producer([(\"file%d\" % i) for i in range(2)])", "result. # Try a simpler expression: # col1, col2, col3, col4, col5 =", "Default values, in case of empty columns. Also specifies the type of the", "needs them. # The following line is equivalent to : # filename_queue =", "threads = tf.train.start_queue_runners(coord=coord) for i in range(1200): # Retrieve a single instance: example,", "equivalent to : # filename_queue = tf.train.string_input_producer([\"file0.csv\", \"file1.csv\"]) filename_queue = tf.train.string_input_producer([(\"file%d\" % i)", "https://www.tensorflow.org/api_guides/python/reading_data import tensorflow as tf # creates a FIFO queue for holding the", "= tf.decode_csv( value, record_defaults=record_defaults) features = tf.stack([col1, col2, col3, col4]) with tf.Session() as", "# creates a FIFO queue for holding the filenames until the reader needs", "col1, col2, col3, col4, col5 = tf.decode_csv(value, record_defaults=[[1]]*5) record_defaults = [[1], [1], [1],", "coord = tf.train.Coordinator() threads = tf.train.start_queue_runners(coord=coord) for i in range(1200): # Retrieve a", "col4, col5 = tf.decode_csv( value, record_defaults=record_defaults) features = tf.stack([col1, col2, col3, col4]) with", "col3, col4]) with tf.Session() as sess: # Start populating the filename queue. coord", "simpler expression: # col1, col2, col3, col4, col5 = tf.decode_csv(value, record_defaults=[[1]]*5) record_defaults =", "filename queue. coord = tf.train.Coordinator() threads = tf.train.start_queue_runners(coord=coord) for i in range(1200): #", "[1]] col1, col2, col3, col4, col5 = tf.decode_csv( value, record_defaults=record_defaults) features = tf.stack([col1,", "range(2)]) reader = tf.TextLineReader() key, value = reader.read(filename_queue) # Default values, in case", "tf.train.Coordinator() threads = tf.train.start_queue_runners(coord=coord) for i in range(1200): # Retrieve a single instance:", "type of the decoded result. # Try a simpler expression: # col1, col2,", "values, in case of empty columns. Also specifies the type of the decoded", "empty columns. Also specifies the type of the decoded result. # Try a", "of the decoded result. # Try a simpler expression: # col1, col2, col3,", "in range(2)]) reader = tf.TextLineReader() key, value = reader.read(filename_queue) # Default values, in", "tf.decode_csv( value, record_defaults=record_defaults) features = tf.stack([col1, col2, col3, col4]) with tf.Session() as sess:" ]
[ "PipelineManager(object): def __init__(self, run_id, pipeline_input, _input: IOManager, _output: IOManager, config, *args, **kwargs): \"\"\"", "\"\"\" print(\">>>>>> Running pipeline\" + self.pipeline_name + \"...\") prev_stage_name = '' for stage_name", "is defined in the asset. For example: model_manager or data_manader :param manager_type: the", "\"Manager\") print(\">>> Expected Directory name: \" + self.asset_name) print(\">>> Expected Manager file name:", "= asset_name.replace('DataManager', '').replace('ModelManager', '') if asset_name not in AVAILABLE_STAGES: AVAILABLE_STAGES[asset_name] = {} if", "of the manager \"\"\" manager_file_name = self.asset_name + '_' + manager_type + '_manager'", "MANAGER_TYPES[manager_type_key] in asset_name: manager_type = manager_type_key if manager_type is None: raise Exception(\"Wrong class", "print(\">>>>>> It took me, {}.\".format(end_time)) print(\">>>>>> Finished running pipeline.\") return self.output_manager class pipeline:", "the stage (e.g. \"load_data\") :return: pipeline stage dictionary \"\"\" asset_name = ''.join(x.capitalize() or", "if the base classes if stage_name in AVAILABLE_STAGES[BASE_CLASS_NAME]: return AVAILABLE_STAGES[BASE_CLASS_NAME][stage_name] raise PipelineManagerException( \"Function", "= run_id self.input_manager = _input self.output_manager = _output self.asset_name = self.config.get('job_settings', {}).get('asset_name', '')", "instance with input to the pipeline :param _output: IOmanager instance to store the", "time.strftime(TIME_FORMAT) print(\">>>>>> Running stage: {}...\".format(stage_name)) stage = self.extract_stage(stage_name) if prev_stage_name: args = self.state[prev_stage_name]", "time.strftime(TIME_FORMAT), TIME_FORMAT) - dt.datetime.strptime(start_time, TIME_FORMAT) print(\">>>>>> It took me, {}.\".format(end_time)) print(\">>>>>> Finished running", "= time.strftime(TIME_FORMAT) print(\">>>>>> Running stage: {}...\".format(stage_name)) stage = self.extract_stage(stage_name) if prev_stage_name: args =", "self.state[prev_stage_name] else: args = arguments # execute stage self.state[stage_name] = stage['function'](self.extract_manager_instance(stage['manager']), *args) if", "'model_manager': 'ModelManager' } class PipelineManager(object): def __init__(self, run_id, pipeline_input, _input: IOManager, _output: IOManager,", "a default pipeline if isinstance(pipeline_input, list): self.stages = pipeline_input if isinstance(pipeline_input, str): self.pipeline_name", "decorator above functions\" \" you want to use in your asset '{}'s Data", "AVAILABLE_STAGES: raise PipelineManagerException( \"Missing decoration for your pipeline functions! Add '@pipeline' decorator above", "getattr(module, manager_class_name) return manager_class(self.config.copy(), self.input_manager, self.output_manager, self.run_id) except Exception as e: print(\"Couldn't import", "your pipeline.\".format(stage_name, stage_name)) return AVAILABLE_STAGES[asset_name][stage_name] def extract_manager_instance(self, manager_type): \"\"\" Gets the instance of", "'_' for x in manager_file_name.split('_')) # CamelCase try: spec = importlib.util.spec_from_file_location(manager_module, manager_module_path) module", "example: model_manager or data_manader :param manager_type: the type : e.g. \"data\", \"model\" :return:", "in AVAILABLE_STAGES: raise PipelineManagerException( \"Missing decoration for your pipeline functions! Add '@pipeline' decorator", "- dt.datetime.strptime(start_time, TIME_FORMAT) print(\">>>>>> It took me, {}.\".format(end_time)) print(\">>>>>> Finished running pipeline.\") return", "_output self.asset_name = self.config.get('job_settings', {}).get('asset_name', '') self.data_manager_instance = self.create_manager_instance('data') self.model_manager_instance = self.create_manager_instance('model') #", "pipeline_input, _input: IOManager, _output: IOManager, config, *args, **kwargs): \"\"\" :param pipeline_input: the pipeline", "TIME_FORMAT) print(\">>>>>> It took me, {}.\".format(end_time)) print(\">>>>>> Finished running pipeline.\") return self.output_manager class", "asset_name in AVAILABLE_STAGES: if asset_name != BASE_CLASS_NAME: AVAILABLE_STAGES[asset_name] = {} self.pipeline_name = ''", "instance of the manager - model_manager instance or data_manager instance :param manager_type: string", "def __set_name__(self, owner, name): asset_name = owner.__name__ manager_type = None for manager_type_key in", "list of stages or string of a default pipeline if isinstance(pipeline_input, list): self.stages", "e: print(\"Couldn't import class of \" + manager_type + \" manager for model:", "manager_type = None for manager_type_key in MANAGER_TYPES: if MANAGER_TYPES[manager_type_key] in asset_name: manager_type =", "print(\">>> Directory: {{asset_name}}\") print(\">>> File: {{asset_name}}_\" + manager_type + \"_manager.py\") print(\">>> Class: {{asset_name_capitalized}}\"", "Directory: {{asset_name}}\") print(\">>> File: {{asset_name}}_\" + manager_type + \"_manager.py\") print(\">>> Class: {{asset_name_capitalized}}\" +", ":param pipeline_input: the pipeline name string or list of strings :param _input: IOmanager", "of the stage (e.g. \"load_data\") :return: pipeline stage dictionary \"\"\" asset_name = ''.join(x.capitalize()", "class PipelineManager(object): def __init__(self, run_id, pipeline_input, _input: IOManager, _output: IOManager, config, *args, **kwargs):", "= '' for stage_name in self.stages: start_time = time.strftime(TIME_FORMAT) print(\">>>>>> Running stage: {}...\".format(stage_name))", "%H:%M:%S' MANAGER_TYPES = { 'data_manager': 'DataManager', 'model_manager': 'ModelManager' } class PipelineManager(object): def __init__(self,", "[]) self.config = config self.run_id = run_id self.input_manager = _input self.output_manager = _output", "print(\">>>>>> Finished running pipeline.\") return self.output_manager class pipeline: def __init__(self, fn): self.fn =", "raise Exception(\"Wrong class name or placement of decorator! ('{}')\".format(asset_name)) asset_name = asset_name.replace('DataManager', '').replace('ModelManager',", "asset_name.replace('DataManager', '').replace('ModelManager', '') if asset_name not in AVAILABLE_STAGES: AVAILABLE_STAGES[asset_name] = {} if name", "+ self.asset_name) print(\">>> Expected Manager file name: \" + manager_file_name) print(\">>> Expected Manager", "stages and passes relevant values between them :param arguments: input for the first", "raise Exception(\"Duplicate stage name '{}' for pipelines found in asset '{}'\" .format(asset_name, name))", "IOManager, _output: IOManager, config, *args, **kwargs): \"\"\" :param pipeline_input: the pipeline name string", "\"data\", \"model\" :return: instance of the manager \"\"\" manager_file_name = self.asset_name + '_'", "IOmanager instance to store the outputs of the pipelines to be saved externally", "manager_file_name.split('_')) # CamelCase try: spec = importlib.util.spec_from_file_location(manager_module, manager_module_path) module = importlib.util.module_from_spec(spec) sys.modules[spec.name] =", "+ \" manager file/directory/class names are in the following convention:\") print(\">>> Directory: {{asset_name}}\")", "self.asset_name = self.config.get('job_settings', {}).get('asset_name', '') self.data_manager_instance = self.create_manager_instance('data') self.model_manager_instance = self.create_manager_instance('model') # first", "\" '\" + pipeline_input + \"'\" self.stages = settings.get('pipelines', {}).get(pipeline_input, []) self.config =", "type : e.g. \"data\", \"model\" :return: instance of the manager \"\"\" manager_file_name =", "to store the outputs of the pipelines to be saved externally :param config:", "{} if name in AVAILABLE_STAGES[asset_name]: raise Exception(\"Duplicate stage name '{}' for pipelines found", "= '' TIME_FORMAT = '%Y-%m-%d %H:%M:%S' MANAGER_TYPES = { 'data_manager': 'DataManager', 'model_manager': 'ModelManager'", "isinstance(pipeline_input, str): self.pipeline_name = \" '\" + pipeline_input + \"'\" self.stages = settings.get('pipelines',", "stage = self.extract_stage(stage_name) if prev_stage_name: args = self.state[prev_stage_name] else: args = arguments #", "dictionary \"\"\" asset_name = ''.join(x.capitalize() or '_' for x in self.asset_name.split('_')) # CamelCase", "function and the manager class it resides in. :param stage_name: the name of", "return AVAILABLE_STAGES[asset_name][stage_name] def extract_manager_instance(self, manager_type): \"\"\" Gets the instance of the manager -", "dict.fromkeys(self.stages, {}) def create_manager_instance(self, manager_type): \"\"\" Creates manager instance which class is defined", "Runs through the pipeline stages and passes relevant values between them :param arguments:", "containing the function and the manager class it resides in. :param stage_name: the", "for pipelines found in asset '{}'\" .format(asset_name, name)) AVAILABLE_STAGES[asset_name][name] = { 'function': self.fn,", "importlib.util.module_from_spec(spec) sys.modules[spec.name] = module spec.loader.exec_module(module) manager_class = getattr(module, manager_class_name) return manager_class(self.config.copy(), self.input_manager, self.output_manager,", "asset '{}'\" .format(asset_name, name)) AVAILABLE_STAGES[asset_name][name] = { 'function': self.fn, 'manager': manager_type } return", "stage: {}...\".format(stage_name)) stage = self.extract_stage(stage_name) if prev_stage_name: args = self.state[prev_stage_name] else: args =", "'_' for x in self.asset_name.split('_')) # CamelCase if asset_name not in AVAILABLE_STAGES: raise", "dt import importlib.util import sys import os from mlapp.config import settings from mlapp.utils.exceptions.base_exceptions", "in the asset. For example: model_manager or data_manader :param manager_type: the type :", "the outputs of the pipelines to be saved externally :param config: config string", "from mlapp.managers.io_manager import IOManager AVAILABLE_STAGES = {} BASE_CLASS_NAME = '' TIME_FORMAT = '%Y-%m-%d", "manager instance which class is defined in the asset. For example: model_manager or", "_output: IOmanager instance to store the outputs of the pipelines to be saved", "importlib.util.spec_from_file_location(manager_module, manager_module_path) module = importlib.util.module_from_spec(spec) sys.modules[spec.name] = module spec.loader.exec_module(module) manager_class = getattr(module, manager_class_name)", "\"data_manager\" or \"model_manager\" :return: model_manager instance or data_manager instance \"\"\" if manager_type ==", "+ manager_file_name) print(\">>> Expected Manager class name: \" + manager_class_name) raise FrameworkException(str(e)) def", "\"\"\" Gets the pipeline stage dictioanry containing the function and the manager class", "store the outputs of the pipelines to be saved externally :param config: config", "= _input self.output_manager = _output self.asset_name = self.config.get('job_settings', {}).get('asset_name', '') self.data_manager_instance = self.create_manager_instance('data')", "in AVAILABLE_STAGES: AVAILABLE_STAGES[asset_name] = {} if name in AVAILABLE_STAGES[asset_name]: raise Exception(\"Duplicate stage name", "isinstance(self.state[stage_name], tuple): self.state[stage_name] = (self.state[stage_name],) prev_stage_name = stage_name end_time = dt.datetime.strptime( time.strftime(TIME_FORMAT), TIME_FORMAT)", "= { 'data_manager': 'DataManager', 'model_manager': 'ModelManager' } class PipelineManager(object): def __init__(self, run_id, pipeline_input,", "_input self.output_manager = _output self.asset_name = self.config.get('job_settings', {}).get('asset_name', '') self.data_manager_instance = self.create_manager_instance('data') self.model_manager_instance", "*args, **kwargs): \"\"\" :param pipeline_input: the pipeline name string or list of strings", "arguments # execute stage self.state[stage_name] = stage['function'](self.extract_manager_instance(stage['manager']), *args) if not isinstance(self.state[stage_name], tuple): self.state[stage_name]", "manager_type: string \"data_manager\" or \"model_manager\" :return: model_manager instance or data_manager instance \"\"\" if", "want to use it in your pipeline.\".format(stage_name, stage_name)) return AVAILABLE_STAGES[asset_name][stage_name] def extract_manager_instance(self, manager_type):", "Creates manager instance which class is defined in the asset. For example: model_manager", "manager_module_path = os.path.join('assets', self.asset_name, f'{manager_file_name }.py') manager_class_name = ''.join(x.capitalize() or '_' for x", "externally :param config: config string of the pipeline :param args: :param kwargs: \"\"\"", "print(\">>> Class: {{asset_name_capitalized}}\" + manager_type.capitalize() + \"Manager\") print(\">>> Expected Directory name: \" +", "found in asset '{}'\" .format(asset_name, name)) AVAILABLE_STAGES[asset_name][name] = { 'function': self.fn, 'manager': manager_type", "the pipeline stages and passes relevant values between them :param arguments: input for", "pipeline stage dictioanry containing the function and the manager class it resides in.", "(self.state[stage_name],) prev_stage_name = stage_name end_time = dt.datetime.strptime( time.strftime(TIME_FORMAT), TIME_FORMAT) - dt.datetime.strptime(start_time, TIME_FORMAT) print(\">>>>>>", "pipeline_input if isinstance(pipeline_input, str): self.pipeline_name = \" '\" + pipeline_input + \"'\" self.stages", ":return: IOmanager of all the outputs to be stored \"\"\" print(\">>>>>> Running pipeline\"", "manager_class_name) raise FrameworkException(str(e)) def extract_stage(self, stage_name): \"\"\" Gets the pipeline stage dictioanry containing", "{}...\".format(stage_name)) stage = self.extract_stage(stage_name) if prev_stage_name: args = self.state[prev_stage_name] else: args = arguments", "PipelineManagerException( \"Function '{}' was not found in your asset! Add '@pipeline' decorator above", "{{asset_name}}_\" + manager_type + \"_manager.py\") print(\">>> Class: {{asset_name_capitalized}}\" + manager_type.capitalize() + \"Manager\") print(\">>>", "instance of the manager \"\"\" manager_file_name = self.asset_name + '_' + manager_type +", "\" + self.asset_name) print(\">>> Expected Manager file name: \" + manager_file_name) print(\">>> Expected", "It took me, {}.\".format(end_time)) print(\">>>>>> Finished running pipeline.\") return self.output_manager class pipeline: def", "placement of decorator! ('{}')\".format(asset_name)) asset_name = asset_name.replace('DataManager', '').replace('ModelManager', '') if asset_name not in", "stage_name: the name of the stage (e.g. \"load_data\") :return: pipeline stage dictionary \"\"\"", "manager_module_path) module = importlib.util.module_from_spec(spec) sys.modules[spec.name] = module spec.loader.exec_module(module) manager_class = getattr(module, manager_class_name) return", "instance or data_manager instance \"\"\" if manager_type == 'data_manager': return self.data_manager_instance else: return", "the outputs to be stored \"\"\" print(\">>>>>> Running pipeline\" + self.pipeline_name + \"...\")", "= {} if name in AVAILABLE_STAGES[asset_name]: raise Exception(\"Duplicate stage name '{}' for pipelines", "the base classes if stage_name in AVAILABLE_STAGES[BASE_CLASS_NAME]: return AVAILABLE_STAGES[BASE_CLASS_NAME][stage_name] raise PipelineManagerException( \"Function '{}'", "self.pipeline_name + \"...\") prev_stage_name = '' for stage_name in self.stages: start_time = time.strftime(TIME_FORMAT)", "in asset_name: manager_type = manager_type_key if manager_type is None: raise Exception(\"Wrong class name", "use in your asset '{}'s Data Manager and Model Manager.\".format(asset_name)) if stage_name not", "class name: \" + manager_class_name) raise FrameworkException(str(e)) def extract_stage(self, stage_name): \"\"\" Gets the", "\" \"function if you want to use it in your pipeline.\".format(stage_name, stage_name)) return", "= settings.get('pipelines', {}).get(pipeline_input, []) self.config = config self.run_id = run_id self.input_manager = _input", "values between them :param arguments: input for the first stage in the pipeline,", "class name or placement of decorator! ('{}')\".format(asset_name)) asset_name = asset_name.replace('DataManager', '').replace('ModelManager', '') if", "extract_manager_instance(self, manager_type): \"\"\" Gets the instance of the manager - model_manager instance or", "can be either list of stages or string of a default pipeline if", "+ \"...\") prev_stage_name = '' for stage_name in self.stages: start_time = time.strftime(TIME_FORMAT) print(\">>>>>>", "inputs self.state = dict.fromkeys(self.stages, {}) def create_manager_instance(self, manager_type): \"\"\" Creates manager instance which", "= ''.join(x.capitalize() or '_' for x in self.asset_name.split('_')) # CamelCase if asset_name not", "for model: \" + self.asset_name) print(\">>> Please verify your \" + manager_type +", "if stage_name not in AVAILABLE_STAGES[asset_name]: # exists in one if the base classes", "of the manager - model_manager instance or data_manager instance :param manager_type: string \"data_manager\"", "= os.path.join('assets', self.asset_name, f'{manager_file_name }.py') manager_class_name = ''.join(x.capitalize() or '_' for x in", "be either list of stages or string of a default pipeline if isinstance(pipeline_input,", "+ manager_type + \" manager for model: \" + self.asset_name) print(\">>> Please verify", "'_' + manager_type + '_manager' manager_module = 'assets.' + self.asset_name + '.' +", "\"\"\" asset_name = ''.join(x.capitalize() or '_' for x in self.asset_name.split('_')) # CamelCase if", "AVAILABLE_STAGES[BASE_CLASS_NAME]: return AVAILABLE_STAGES[BASE_CLASS_NAME][stage_name] raise PipelineManagerException( \"Function '{}' was not found in your asset!", "stage self.state[stage_name] = stage['function'](self.extract_manager_instance(stage['manager']), *args) if not isinstance(self.state[stage_name], tuple): self.state[stage_name] = (self.state[stage_name],) prev_stage_name", "\"\"\" Gets the instance of the manager - model_manager instance or data_manager instance", "classes if stage_name in AVAILABLE_STAGES[BASE_CLASS_NAME]: return AVAILABLE_STAGES[BASE_CLASS_NAME][stage_name] raise PipelineManagerException( \"Function '{}' was not", "for the first stage in the pipeline, will be passed with *args :return:", "manager_file_name) print(\">>> Expected Manager class name: \" + manager_class_name) raise FrameworkException(str(e)) def extract_stage(self,", "in self.asset_name.split('_')) # CamelCase if asset_name not in AVAILABLE_STAGES: raise PipelineManagerException( \"Missing decoration", ": e.g. \"data\", \"model\" :return: instance of the manager \"\"\" manager_file_name = self.asset_name", "FrameworkException from mlapp.managers.io_manager import IOManager AVAILABLE_STAGES = {} BASE_CLASS_NAME = '' TIME_FORMAT =", "self.output_manager, self.run_id) except Exception as e: print(\"Couldn't import class of \" + manager_type", "PipelineManagerException( \"Missing decoration for your pipeline functions! Add '@pipeline' decorator above functions\" \"", "self.model_manager_instance def run(self, *arguments): \"\"\" Runs through the pipeline stages and passes relevant", "= fn def __set_name__(self, owner, name): asset_name = owner.__name__ manager_type = None for", "import settings from mlapp.utils.exceptions.base_exceptions import PipelineManagerException, FrameworkException from mlapp.managers.io_manager import IOManager AVAILABLE_STAGES =", "mlapp.managers.io_manager import IOManager AVAILABLE_STAGES = {} BASE_CLASS_NAME = '' TIME_FORMAT = '%Y-%m-%d %H:%M:%S'", "manager_type + \" manager for model: \" + self.asset_name) print(\">>> Please verify your", "list of strings :param _input: IOmanager instance with input to the pipeline :param", "model_manager instance or data_manager instance \"\"\" if manager_type == 'data_manager': return self.data_manager_instance else:", "def extract_stage(self, stage_name): \"\"\" Gets the pipeline stage dictioanry containing the function and", "Directory name: \" + self.asset_name) print(\">>> Expected Manager file name: \" + manager_file_name)", "= None for manager_type_key in MANAGER_TYPES: if MANAGER_TYPES[manager_type_key] in asset_name: manager_type = manager_type_key", "settings from mlapp.utils.exceptions.base_exceptions import PipelineManagerException, FrameworkException from mlapp.managers.io_manager import IOManager AVAILABLE_STAGES = {}", "string \"data_manager\" or \"model_manager\" :return: model_manager instance or data_manager instance \"\"\" if manager_type", "*args :return: IOmanager of all the outputs to be stored \"\"\" print(\">>>>>> Running", "and passes relevant values between them :param arguments: input for the first stage", "manager_type + \"_manager.py\") print(\">>> Class: {{asset_name_capitalized}}\" + manager_type.capitalize() + \"Manager\") print(\">>> Expected Directory", "{}).get('asset_name', '') self.data_manager_instance = self.create_manager_instance('data') self.model_manager_instance = self.create_manager_instance('model') # first inputs self.state =", "stages or string of a default pipeline if isinstance(pipeline_input, list): self.stages = pipeline_input", "config, *args, **kwargs): \"\"\" :param pipeline_input: the pipeline name string or list of", ":param stage_name: the name of the stage (e.g. \"load_data\") :return: pipeline stage dictionary", "= _output self.asset_name = self.config.get('job_settings', {}).get('asset_name', '') self.data_manager_instance = self.create_manager_instance('data') self.model_manager_instance = self.create_manager_instance('model')", "For example: model_manager or data_manader :param manager_type: the type : e.g. \"data\", \"model\"", "manager_module = 'assets.' + self.asset_name + '.' + manager_file_name manager_module_path = os.path.join('assets', self.asset_name,", "manager_type == 'data_manager': return self.data_manager_instance else: return self.model_manager_instance def run(self, *arguments): \"\"\" Runs", "self.config = config self.run_id = run_id self.input_manager = _input self.output_manager = _output self.asset_name", "functions\" \" you want to use in your asset '{}'s Data Manager and", "<reponame>kerenleibovich/mlapp<filename>mlapp/managers/pipeline_manager.py import time import datetime as dt import importlib.util import sys import os", "pipeline stage dictionary \"\"\" asset_name = ''.join(x.capitalize() or '_' for x in self.asset_name.split('_'))", "= self.extract_stage(stage_name) if prev_stage_name: args = self.state[prev_stage_name] else: args = arguments # execute", "manager_file_name manager_module_path = os.path.join('assets', self.asset_name, f'{manager_file_name }.py') manager_class_name = ''.join(x.capitalize() or '_' for", "import datetime as dt import importlib.util import sys import os from mlapp.config import", "from mlapp.utils.exceptions.base_exceptions import PipelineManagerException, FrameworkException from mlapp.managers.io_manager import IOManager AVAILABLE_STAGES = {} BASE_CLASS_NAME", "f'{manager_file_name }.py') manager_class_name = ''.join(x.capitalize() or '_' for x in manager_file_name.split('_')) # CamelCase", "not in AVAILABLE_STAGES: AVAILABLE_STAGES[asset_name] = {} if name in AVAILABLE_STAGES[asset_name]: raise Exception(\"Duplicate stage", "or data_manager instance :param manager_type: string \"data_manager\" or \"model_manager\" :return: model_manager instance or", "+ pipeline_input + \"'\" self.stages = settings.get('pipelines', {}).get(pipeline_input, []) self.config = config self.run_id", "def create_manager_instance(self, manager_type): \"\"\" Creates manager instance which class is defined in the", ":param manager_type: the type : e.g. \"data\", \"model\" :return: instance of the manager", "manager - model_manager instance or data_manager instance :param manager_type: string \"data_manager\" or \"model_manager\"", "\"...\") prev_stage_name = '' for stage_name in self.stages: start_time = time.strftime(TIME_FORMAT) print(\">>>>>> Running", ":param kwargs: \"\"\" for asset_name in AVAILABLE_STAGES: if asset_name != BASE_CLASS_NAME: AVAILABLE_STAGES[asset_name] =", "== 'data_manager': return self.data_manager_instance else: return self.model_manager_instance def run(self, *arguments): \"\"\" Runs through", "self.input_manager = _input self.output_manager = _output self.asset_name = self.config.get('job_settings', {}).get('asset_name', '') self.data_manager_instance =", "}.py') manager_class_name = ''.join(x.capitalize() or '_' for x in manager_file_name.split('_')) # CamelCase try:", "self.state[stage_name] = stage['function'](self.extract_manager_instance(stage['manager']), *args) if not isinstance(self.state[stage_name], tuple): self.state[stage_name] = (self.state[stage_name],) prev_stage_name =", "+ \" manager for model: \" + self.asset_name) print(\">>> Please verify your \"", "Add '@pipeline' decorator above functions\" \" you want to use in your asset", "BASE_CLASS_NAME: AVAILABLE_STAGES[asset_name] = {} self.pipeline_name = '' # pipeline can be either list", "str): self.pipeline_name = \" '\" + pipeline_input + \"'\" self.stages = settings.get('pipelines', {}).get(pipeline_input,", "self.input_manager, self.output_manager, self.run_id) except Exception as e: print(\"Couldn't import class of \" +", "pipeline can be either list of stages or string of a default pipeline", "stage_name)) return AVAILABLE_STAGES[asset_name][stage_name] def extract_manager_instance(self, manager_type): \"\"\" Gets the instance of the manager", "AVAILABLE_STAGES = {} BASE_CLASS_NAME = '' TIME_FORMAT = '%Y-%m-%d %H:%M:%S' MANAGER_TYPES = {", "me, {}.\".format(end_time)) print(\">>>>>> Finished running pipeline.\") return self.output_manager class pipeline: def __init__(self, fn):", "self.model_manager_instance = self.create_manager_instance('model') # first inputs self.state = dict.fromkeys(self.stages, {}) def create_manager_instance(self, manager_type):", ":return: pipeline stage dictionary \"\"\" asset_name = ''.join(x.capitalize() or '_' for x in", "you want to use it in your pipeline.\".format(stage_name, stage_name)) return AVAILABLE_STAGES[asset_name][stage_name] def extract_manager_instance(self,", "def run(self, *arguments): \"\"\" Runs through the pipeline stages and passes relevant values", "config: config string of the pipeline :param args: :param kwargs: \"\"\" for asset_name", "__init__(self, run_id, pipeline_input, _input: IOManager, _output: IOManager, config, *args, **kwargs): \"\"\" :param pipeline_input:", "prev_stage_name = stage_name end_time = dt.datetime.strptime( time.strftime(TIME_FORMAT), TIME_FORMAT) - dt.datetime.strptime(start_time, TIME_FORMAT) print(\">>>>>> It", "if manager_type == 'data_manager': return self.data_manager_instance else: return self.model_manager_instance def run(self, *arguments): \"\"\"", "time import datetime as dt import importlib.util import sys import os from mlapp.config", "+ manager_type + '_manager' manager_module = 'assets.' + self.asset_name + '.' + manager_file_name", "manager_type): \"\"\" Creates manager instance which class is defined in the asset. For", "of stages or string of a default pipeline if isinstance(pipeline_input, list): self.stages =", "self.run_id) except Exception as e: print(\"Couldn't import class of \" + manager_type +", "'@pipeline' decorator above your '{}' \" \"function if you want to use it", "return AVAILABLE_STAGES[BASE_CLASS_NAME][stage_name] raise PipelineManagerException( \"Function '{}' was not found in your asset! Add", "in MANAGER_TYPES: if MANAGER_TYPES[manager_type_key] in asset_name: manager_type = manager_type_key if manager_type is None:", "or data_manader :param manager_type: the type : e.g. \"data\", \"model\" :return: instance of", "name in AVAILABLE_STAGES[asset_name]: raise Exception(\"Duplicate stage name '{}' for pipelines found in asset", "first stage in the pipeline, will be passed with *args :return: IOmanager of", "AVAILABLE_STAGES[asset_name] = {} self.pipeline_name = '' # pipeline can be either list of", "for asset_name in AVAILABLE_STAGES: if asset_name != BASE_CLASS_NAME: AVAILABLE_STAGES[asset_name] = {} self.pipeline_name =", "'assets.' + self.asset_name + '.' + manager_file_name manager_module_path = os.path.join('assets', self.asset_name, f'{manager_file_name }.py')", "asset_name != BASE_CLASS_NAME: AVAILABLE_STAGES[asset_name] = {} self.pipeline_name = '' # pipeline can be", "manager_type_key if manager_type is None: raise Exception(\"Wrong class name or placement of decorator!", "pipeline :param args: :param kwargs: \"\"\" for asset_name in AVAILABLE_STAGES: if asset_name !=", "print(\">>> Please verify your \" + manager_type + \" manager file/directory/class names are", "+ \"'\" self.stages = settings.get('pipelines', {}).get(pipeline_input, []) self.config = config self.run_id = run_id", "pipeline :param _output: IOmanager instance to store the outputs of the pipelines to", "if asset_name != BASE_CLASS_NAME: AVAILABLE_STAGES[asset_name] = {} self.pipeline_name = '' # pipeline can", "passed with *args :return: IOmanager of all the outputs to be stored \"\"\"", "self.stages: start_time = time.strftime(TIME_FORMAT) print(\">>>>>> Running stage: {}...\".format(stage_name)) stage = self.extract_stage(stage_name) if prev_stage_name:", "args = self.state[prev_stage_name] else: args = arguments # execute stage self.state[stage_name] = stage['function'](self.extract_manager_instance(stage['manager']),", "string of a default pipeline if isinstance(pipeline_input, list): self.stages = pipeline_input if isinstance(pipeline_input,", "import importlib.util import sys import os from mlapp.config import settings from mlapp.utils.exceptions.base_exceptions import", "import PipelineManagerException, FrameworkException from mlapp.managers.io_manager import IOManager AVAILABLE_STAGES = {} BASE_CLASS_NAME = ''", "print(\">>>>>> Running stage: {}...\".format(stage_name)) stage = self.extract_stage(stage_name) if prev_stage_name: args = self.state[prev_stage_name] else:", "= importlib.util.spec_from_file_location(manager_module, manager_module_path) module = importlib.util.module_from_spec(spec) sys.modules[spec.name] = module spec.loader.exec_module(module) manager_class = getattr(module,", "which class is defined in the asset. For example: model_manager or data_manader :param", "'{}' for pipelines found in asset '{}'\" .format(asset_name, name)) AVAILABLE_STAGES[asset_name][name] = { 'function':", "import IOManager AVAILABLE_STAGES = {} BASE_CLASS_NAME = '' TIME_FORMAT = '%Y-%m-%d %H:%M:%S' MANAGER_TYPES", ":param arguments: input for the first stage in the pipeline, will be passed", "decorator! ('{}')\".format(asset_name)) asset_name = asset_name.replace('DataManager', '').replace('ModelManager', '') if asset_name not in AVAILABLE_STAGES: AVAILABLE_STAGES[asset_name]", "\" + manager_type + \" manager for model: \" + self.asset_name) print(\">>> Please", "the name of the stage (e.g. \"load_data\") :return: pipeline stage dictionary \"\"\" asset_name", "self.asset_name) print(\">>> Please verify your \" + manager_type + \" manager file/directory/class names", "manager_type + \" manager file/directory/class names are in the following convention:\") print(\">>> Directory:", "\" manager file/directory/class names are in the following convention:\") print(\">>> Directory: {{asset_name}}\") print(\">>>", "in self.stages: start_time = time.strftime(TIME_FORMAT) print(\">>>>>> Running stage: {}...\".format(stage_name)) stage = self.extract_stage(stage_name) if", "name): asset_name = owner.__name__ manager_type = None for manager_type_key in MANAGER_TYPES: if MANAGER_TYPES[manager_type_key]", "self.state[stage_name] = (self.state[stage_name],) prev_stage_name = stage_name end_time = dt.datetime.strptime( time.strftime(TIME_FORMAT), TIME_FORMAT) - dt.datetime.strptime(start_time,", "+ self.asset_name) print(\">>> Please verify your \" + manager_type + \" manager file/directory/class", "None for manager_type_key in MANAGER_TYPES: if MANAGER_TYPES[manager_type_key] in asset_name: manager_type = manager_type_key if", "\"\"\" for asset_name in AVAILABLE_STAGES: if asset_name != BASE_CLASS_NAME: AVAILABLE_STAGES[asset_name] = {} self.pipeline_name", "self.config.get('job_settings', {}).get('asset_name', '') self.data_manager_instance = self.create_manager_instance('data') self.model_manager_instance = self.create_manager_instance('model') # first inputs self.state", "= arguments # execute stage self.state[stage_name] = stage['function'](self.extract_manager_instance(stage['manager']), *args) if not isinstance(self.state[stage_name], tuple):", "{}).get(pipeline_input, []) self.config = config self.run_id = run_id self.input_manager = _input self.output_manager =", "TIME_FORMAT) - dt.datetime.strptime(start_time, TIME_FORMAT) print(\">>>>>> It took me, {}.\".format(end_time)) print(\">>>>>> Finished running pipeline.\")", ":param manager_type: string \"data_manager\" or \"model_manager\" :return: model_manager instance or data_manager instance \"\"\"", "asset_name: manager_type = manager_type_key if manager_type is None: raise Exception(\"Wrong class name or", "name: \" + self.asset_name) print(\">>> Expected Manager file name: \" + manager_file_name) print(\">>>", "either list of stages or string of a default pipeline if isinstance(pipeline_input, list):", "+ manager_class_name) raise FrameworkException(str(e)) def extract_stage(self, stage_name): \"\"\" Gets the pipeline stage dictioanry", "the pipeline, will be passed with *args :return: IOmanager of all the outputs", "manager_class_name) return manager_class(self.config.copy(), self.input_manager, self.output_manager, self.run_id) except Exception as e: print(\"Couldn't import class", "stage name '{}' for pipelines found in asset '{}'\" .format(asset_name, name)) AVAILABLE_STAGES[asset_name][name] =", "Running pipeline\" + self.pipeline_name + \"...\") prev_stage_name = '' for stage_name in self.stages:", "asset_name = ''.join(x.capitalize() or '_' for x in self.asset_name.split('_')) # CamelCase if asset_name", "e.g. \"data\", \"model\" :return: instance of the manager \"\"\" manager_file_name = self.asset_name +", "functions! Add '@pipeline' decorator above functions\" \" you want to use in your", "and the manager class it resides in. :param stage_name: the name of the", "of a default pipeline if isinstance(pipeline_input, list): self.stages = pipeline_input if isinstance(pipeline_input, str):", ":param args: :param kwargs: \"\"\" for asset_name in AVAILABLE_STAGES: if asset_name != BASE_CLASS_NAME:", "\"\"\" if manager_type == 'data_manager': return self.data_manager_instance else: return self.model_manager_instance def run(self, *arguments):", "\"function if you want to use it in your pipeline.\".format(stage_name, stage_name)) return AVAILABLE_STAGES[asset_name][stage_name]", "= {} self.pipeline_name = '' # pipeline can be either list of stages", "if asset_name not in AVAILABLE_STAGES: AVAILABLE_STAGES[asset_name] = {} if name in AVAILABLE_STAGES[asset_name]: raise", "print(\">>> Expected Manager class name: \" + manager_class_name) raise FrameworkException(str(e)) def extract_stage(self, stage_name):", "stored \"\"\" print(\">>>>>> Running pipeline\" + self.pipeline_name + \"...\") prev_stage_name = '' for", "\" you want to use in your asset '{}'s Data Manager and Model", "in your asset '{}'s Data Manager and Model Manager.\".format(asset_name)) if stage_name not in", "the asset. For example: model_manager or data_manader :param manager_type: the type : e.g.", "= config self.run_id = run_id self.input_manager = _input self.output_manager = _output self.asset_name =", "asset. For example: model_manager or data_manader :param manager_type: the type : e.g. \"data\",", "# CamelCase try: spec = importlib.util.spec_from_file_location(manager_module, manager_module_path) module = importlib.util.module_from_spec(spec) sys.modules[spec.name] = module", "Running stage: {}...\".format(stage_name)) stage = self.extract_stage(stage_name) if prev_stage_name: args = self.state[prev_stage_name] else: args", "manager \"\"\" manager_file_name = self.asset_name + '_' + manager_type + '_manager' manager_module =", "(e.g. \"load_data\") :return: pipeline stage dictionary \"\"\" asset_name = ''.join(x.capitalize() or '_' for", "= self.state[prev_stage_name] else: args = arguments # execute stage self.state[stage_name] = stage['function'](self.extract_manager_instance(stage['manager']), *args)", "are in the following convention:\") print(\">>> Directory: {{asset_name}}\") print(\">>> File: {{asset_name}}_\" + manager_type", "'') self.data_manager_instance = self.create_manager_instance('data') self.model_manager_instance = self.create_manager_instance('model') # first inputs self.state = dict.fromkeys(self.stages,", "the pipeline name string or list of strings :param _input: IOmanager instance with", "outputs of the pipelines to be saved externally :param config: config string of", "BASE_CLASS_NAME = '' TIME_FORMAT = '%Y-%m-%d %H:%M:%S' MANAGER_TYPES = { 'data_manager': 'DataManager', 'model_manager':", "dt.datetime.strptime( time.strftime(TIME_FORMAT), TIME_FORMAT) - dt.datetime.strptime(start_time, TIME_FORMAT) print(\">>>>>> It took me, {}.\".format(end_time)) print(\">>>>>> Finished", "create_manager_instance(self, manager_type): \"\"\" Creates manager instance which class is defined in the asset.", "{ 'data_manager': 'DataManager', 'model_manager': 'ModelManager' } class PipelineManager(object): def __init__(self, run_id, pipeline_input, _input:", "manager_class_name = ''.join(x.capitalize() or '_' for x in manager_file_name.split('_')) # CamelCase try: spec", "\"\"\" Creates manager instance which class is defined in the asset. For example:", "'data_manager': 'DataManager', 'model_manager': 'ModelManager' } class PipelineManager(object): def __init__(self, run_id, pipeline_input, _input: IOManager,", "pipeline stages and passes relevant values between them :param arguments: input for the", "or string of a default pipeline if isinstance(pipeline_input, list): self.stages = pipeline_input if", "\" + manager_file_name) print(\">>> Expected Manager class name: \" + manager_class_name) raise FrameworkException(str(e))", "run(self, *arguments): \"\"\" Runs through the pipeline stages and passes relevant values between", "Class: {{asset_name_capitalized}}\" + manager_type.capitalize() + \"Manager\") print(\">>> Expected Directory name: \" + self.asset_name)", "name string or list of strings :param _input: IOmanager instance with input to", "be saved externally :param config: config string of the pipeline :param args: :param", "manager_type_key in MANAGER_TYPES: if MANAGER_TYPES[manager_type_key] in asset_name: manager_type = manager_type_key if manager_type is", "= self.config.get('job_settings', {}).get('asset_name', '') self.data_manager_instance = self.create_manager_instance('data') self.model_manager_instance = self.create_manager_instance('model') # first inputs", "if manager_type is None: raise Exception(\"Wrong class name or placement of decorator! ('{}')\".format(asset_name))", "'{}' was not found in your asset! Add '@pipeline' decorator above your '{}'", "spec = importlib.util.spec_from_file_location(manager_module, manager_module_path) module = importlib.util.module_from_spec(spec) sys.modules[spec.name] = module spec.loader.exec_module(module) manager_class =", "above your '{}' \" \"function if you want to use it in your", "AVAILABLE_STAGES: if asset_name != BASE_CLASS_NAME: AVAILABLE_STAGES[asset_name] = {} self.pipeline_name = '' # pipeline", "= self.asset_name + '_' + manager_type + '_manager' manager_module = 'assets.' + self.asset_name", "AVAILABLE_STAGES[asset_name]: raise Exception(\"Duplicate stage name '{}' for pipelines found in asset '{}'\" .format(asset_name,", "to the pipeline :param _output: IOmanager instance to store the outputs of the", "arguments: input for the first stage in the pipeline, will be passed with", "self.stages = settings.get('pipelines', {}).get(pipeline_input, []) self.config = config self.run_id = run_id self.input_manager =", "\"'\" self.stages = settings.get('pipelines', {}).get(pipeline_input, []) self.config = config self.run_id = run_id self.input_manager", "pipeline functions! Add '@pipeline' decorator above functions\" \" you want to use in", "not in AVAILABLE_STAGES[asset_name]: # exists in one if the base classes if stage_name", "input to the pipeline :param _output: IOmanager instance to store the outputs of", "pipelines to be saved externally :param config: config string of the pipeline :param", "or data_manager instance \"\"\" if manager_type == 'data_manager': return self.data_manager_instance else: return self.model_manager_instance", "return self.model_manager_instance def run(self, *arguments): \"\"\" Runs through the pipeline stages and passes", "self.asset_name + '_' + manager_type + '_manager' manager_module = 'assets.' + self.asset_name +", "\"load_data\") :return: pipeline stage dictionary \"\"\" asset_name = ''.join(x.capitalize() or '_' for x", "Add '@pipeline' decorator above your '{}' \" \"function if you want to use", "if asset_name not in AVAILABLE_STAGES: raise PipelineManagerException( \"Missing decoration for your pipeline functions!", "sys.modules[spec.name] = module spec.loader.exec_module(module) manager_class = getattr(module, manager_class_name) return manager_class(self.config.copy(), self.input_manager, self.output_manager, self.run_id)", "= 'assets.' + self.asset_name + '.' + manager_file_name manager_module_path = os.path.join('assets', self.asset_name, f'{manager_file_name", "Manager class name: \" + manager_class_name) raise FrameworkException(str(e)) def extract_stage(self, stage_name): \"\"\" Gets", "+ manager_type + \"_manager.py\") print(\">>> Class: {{asset_name_capitalized}}\" + manager_type.capitalize() + \"Manager\") print(\">>> Expected", "args: :param kwargs: \"\"\" for asset_name in AVAILABLE_STAGES: if asset_name != BASE_CLASS_NAME: AVAILABLE_STAGES[asset_name]", "file/directory/class names are in the following convention:\") print(\">>> Directory: {{asset_name}}\") print(\">>> File: {{asset_name}}_\"", "if stage_name in AVAILABLE_STAGES[BASE_CLASS_NAME]: return AVAILABLE_STAGES[BASE_CLASS_NAME][stage_name] raise PipelineManagerException( \"Function '{}' was not found", "+ manager_file_name manager_module_path = os.path.join('assets', self.asset_name, f'{manager_file_name }.py') manager_class_name = ''.join(x.capitalize() or '_'", "manager_type.capitalize() + \"Manager\") print(\">>> Expected Directory name: \" + self.asset_name) print(\">>> Expected Manager", "run_id, pipeline_input, _input: IOManager, _output: IOManager, config, *args, **kwargs): \"\"\" :param pipeline_input: the", "class pipeline: def __init__(self, fn): self.fn = fn def __set_name__(self, owner, name): asset_name", "self.asset_name.split('_')) # CamelCase if asset_name not in AVAILABLE_STAGES: raise PipelineManagerException( \"Missing decoration for", "your pipeline functions! Add '@pipeline' decorator above functions\" \" you want to use", "the instance of the manager - model_manager instance or data_manager instance :param manager_type:", "manager_type = manager_type_key if manager_type is None: raise Exception(\"Wrong class name or placement", "with input to the pipeline :param _output: IOmanager instance to store the outputs", "class is defined in the asset. For example: model_manager or data_manader :param manager_type:", "raise PipelineManagerException( \"Function '{}' was not found in your asset! Add '@pipeline' decorator", "your asset '{}'s Data Manager and Model Manager.\".format(asset_name)) if stage_name not in AVAILABLE_STAGES[asset_name]:", "**kwargs): \"\"\" :param pipeline_input: the pipeline name string or list of strings :param", "# execute stage self.state[stage_name] = stage['function'](self.extract_manager_instance(stage['manager']), *args) if not isinstance(self.state[stage_name], tuple): self.state[stage_name] =", "following convention:\") print(\">>> Directory: {{asset_name}}\") print(\">>> File: {{asset_name}}_\" + manager_type + \"_manager.py\") print(\">>>", "\" + manager_class_name) raise FrameworkException(str(e)) def extract_stage(self, stage_name): \"\"\" Gets the pipeline stage", "asset '{}'s Data Manager and Model Manager.\".format(asset_name)) if stage_name not in AVAILABLE_STAGES[asset_name]: #", "try: spec = importlib.util.spec_from_file_location(manager_module, manager_module_path) module = importlib.util.module_from_spec(spec) sys.modules[spec.name] = module spec.loader.exec_module(module) manager_class", "base classes if stage_name in AVAILABLE_STAGES[BASE_CLASS_NAME]: return AVAILABLE_STAGES[BASE_CLASS_NAME][stage_name] raise PipelineManagerException( \"Function '{}' was", "self.fn = fn def __set_name__(self, owner, name): asset_name = owner.__name__ manager_type = None", "+ manager_type + \" manager file/directory/class names are in the following convention:\") print(\">>>", "manager class it resides in. :param stage_name: the name of the stage (e.g.", "# CamelCase if asset_name not in AVAILABLE_STAGES: raise PipelineManagerException( \"Missing decoration for your", "in your pipeline.\".format(stage_name, stage_name)) return AVAILABLE_STAGES[asset_name][stage_name] def extract_manager_instance(self, manager_type): \"\"\" Gets the instance", "self.pipeline_name = \" '\" + pipeline_input + \"'\" self.stages = settings.get('pipelines', {}).get(pipeline_input, [])", "Gets the instance of the manager - model_manager instance or data_manager instance :param", "will be passed with *args :return: IOmanager of all the outputs to be", "pipeline\" + self.pipeline_name + \"...\") prev_stage_name = '' for stage_name in self.stages: start_time", "the first stage in the pipeline, will be passed with *args :return: IOmanager", "of decorator! ('{}')\".format(asset_name)) asset_name = asset_name.replace('DataManager', '').replace('ModelManager', '') if asset_name not in AVAILABLE_STAGES:", "model_manager instance or data_manager instance :param manager_type: string \"data_manager\" or \"model_manager\" :return: model_manager", "Exception(\"Wrong class name or placement of decorator! ('{}')\".format(asset_name)) asset_name = asset_name.replace('DataManager', '').replace('ModelManager', '')", "= '%Y-%m-%d %H:%M:%S' MANAGER_TYPES = { 'data_manager': 'DataManager', 'model_manager': 'ModelManager' } class PipelineManager(object):", "*arguments): \"\"\" Runs through the pipeline stages and passes relevant values between them", "''.join(x.capitalize() or '_' for x in self.asset_name.split('_')) # CamelCase if asset_name not in", "not isinstance(self.state[stage_name], tuple): self.state[stage_name] = (self.state[stage_name],) prev_stage_name = stage_name end_time = dt.datetime.strptime( time.strftime(TIME_FORMAT),", "= '' # pipeline can be either list of stages or string of", "string or list of strings :param _input: IOmanager instance with input to the", "# exists in one if the base classes if stage_name in AVAILABLE_STAGES[BASE_CLASS_NAME]: return", "if isinstance(pipeline_input, str): self.pipeline_name = \" '\" + pipeline_input + \"'\" self.stages =", "= self.create_manager_instance('data') self.model_manager_instance = self.create_manager_instance('model') # first inputs self.state = dict.fromkeys(self.stages, {}) def", "class of \" + manager_type + \" manager for model: \" + self.asset_name)", "asset_name not in AVAILABLE_STAGES: AVAILABLE_STAGES[asset_name] = {} if name in AVAILABLE_STAGES[asset_name]: raise Exception(\"Duplicate", "print(\">>> Expected Directory name: \" + self.asset_name) print(\">>> Expected Manager file name: \"", "stage_name end_time = dt.datetime.strptime( time.strftime(TIME_FORMAT), TIME_FORMAT) - dt.datetime.strptime(start_time, TIME_FORMAT) print(\">>>>>> It took me,", "MANAGER_TYPES = { 'data_manager': 'DataManager', 'model_manager': 'ModelManager' } class PipelineManager(object): def __init__(self, run_id,", "pipeline: def __init__(self, fn): self.fn = fn def __set_name__(self, owner, name): asset_name =", "list): self.stages = pipeline_input if isinstance(pipeline_input, str): self.pipeline_name = \" '\" + pipeline_input", "self.data_manager_instance = self.create_manager_instance('data') self.model_manager_instance = self.create_manager_instance('model') # first inputs self.state = dict.fromkeys(self.stages, {})", "CamelCase try: spec = importlib.util.spec_from_file_location(manager_module, manager_module_path) module = importlib.util.module_from_spec(spec) sys.modules[spec.name] = module spec.loader.exec_module(module)", "for x in manager_file_name.split('_')) # CamelCase try: spec = importlib.util.spec_from_file_location(manager_module, manager_module_path) module =", "prev_stage_name = '' for stage_name in self.stages: start_time = time.strftime(TIME_FORMAT) print(\">>>>>> Running stage:", "+ self.pipeline_name + \"...\") prev_stage_name = '' for stage_name in self.stages: start_time =", "instance or data_manager instance :param manager_type: string \"data_manager\" or \"model_manager\" :return: model_manager instance", "for your pipeline functions! Add '@pipeline' decorator above functions\" \" you want to", "print(\">>>>>> Running pipeline\" + self.pipeline_name + \"...\") prev_stage_name = '' for stage_name in", "self.asset_name, f'{manager_file_name }.py') manager_class_name = ''.join(x.capitalize() or '_' for x in manager_file_name.split('_')) #", "Data Manager and Model Manager.\".format(asset_name)) if stage_name not in AVAILABLE_STAGES[asset_name]: # exists in", "Model Manager.\".format(asset_name)) if stage_name not in AVAILABLE_STAGES[asset_name]: # exists in one if the", "kwargs: \"\"\" for asset_name in AVAILABLE_STAGES: if asset_name != BASE_CLASS_NAME: AVAILABLE_STAGES[asset_name] = {}", "Expected Manager file name: \" + manager_file_name) print(\">>> Expected Manager class name: \"", "owner, name): asset_name = owner.__name__ manager_type = None for manager_type_key in MANAGER_TYPES: if", "} class PipelineManager(object): def __init__(self, run_id, pipeline_input, _input: IOManager, _output: IOManager, config, *args,", "self.data_manager_instance else: return self.model_manager_instance def run(self, *arguments): \"\"\" Runs through the pipeline stages", "model: \" + self.asset_name) print(\">>> Please verify your \" + manager_type + \"", "to be stored \"\"\" print(\">>>>>> Running pipeline\" + self.pipeline_name + \"...\") prev_stage_name =", "\"_manager.py\") print(\">>> Class: {{asset_name_capitalized}}\" + manager_type.capitalize() + \"Manager\") print(\">>> Expected Directory name: \"", "return self.output_manager class pipeline: def __init__(self, fn): self.fn = fn def __set_name__(self, owner,", "= importlib.util.module_from_spec(spec) sys.modules[spec.name] = module spec.loader.exec_module(module) manager_class = getattr(module, manager_class_name) return manager_class(self.config.copy(), self.input_manager,", "stage_name in AVAILABLE_STAGES[BASE_CLASS_NAME]: return AVAILABLE_STAGES[BASE_CLASS_NAME][stage_name] raise PipelineManagerException( \"Function '{}' was not found in", "os from mlapp.config import settings from mlapp.utils.exceptions.base_exceptions import PipelineManagerException, FrameworkException from mlapp.managers.io_manager import", "mlapp.utils.exceptions.base_exceptions import PipelineManagerException, FrameworkException from mlapp.managers.io_manager import IOManager AVAILABLE_STAGES = {} BASE_CLASS_NAME =", "defined in the asset. For example: model_manager or data_manader :param manager_type: the type", "of the pipelines to be saved externally :param config: config string of the", "self.asset_name + '.' + manager_file_name manager_module_path = os.path.join('assets', self.asset_name, f'{manager_file_name }.py') manager_class_name =", "for manager_type_key in MANAGER_TYPES: if MANAGER_TYPES[manager_type_key] in asset_name: manager_type = manager_type_key if manager_type", "\"model_manager\" :return: model_manager instance or data_manager instance \"\"\" if manager_type == 'data_manager': return", "def __init__(self, fn): self.fn = fn def __set_name__(self, owner, name): asset_name = owner.__name__", "fn): self.fn = fn def __set_name__(self, owner, name): asset_name = owner.__name__ manager_type =", "stage_name in self.stages: start_time = time.strftime(TIME_FORMAT) print(\">>>>>> Running stage: {}...\".format(stage_name)) stage = self.extract_stage(stage_name)", "MANAGER_TYPES: if MANAGER_TYPES[manager_type_key] in asset_name: manager_type = manager_type_key if manager_type is None: raise", "# first inputs self.state = dict.fromkeys(self.stages, {}) def create_manager_instance(self, manager_type): \"\"\" Creates manager", "importlib.util import sys import os from mlapp.config import settings from mlapp.utils.exceptions.base_exceptions import PipelineManagerException,", "os.path.join('assets', self.asset_name, f'{manager_file_name }.py') manager_class_name = ''.join(x.capitalize() or '_' for x in manager_file_name.split('_'))", "\"\"\" :param pipeline_input: the pipeline name string or list of strings :param _input:", "prev_stage_name: args = self.state[prev_stage_name] else: args = arguments # execute stage self.state[stage_name] =", "= pipeline_input if isinstance(pipeline_input, str): self.pipeline_name = \" '\" + pipeline_input + \"'\"", "start_time = time.strftime(TIME_FORMAT) print(\">>>>>> Running stage: {}...\".format(stage_name)) stage = self.extract_stage(stage_name) if prev_stage_name: args", "manager_file_name = self.asset_name + '_' + manager_type + '_manager' manager_module = 'assets.' +", "= (self.state[stage_name],) prev_stage_name = stage_name end_time = dt.datetime.strptime( time.strftime(TIME_FORMAT), TIME_FORMAT) - dt.datetime.strptime(start_time, TIME_FORMAT)", "IOmanager instance with input to the pipeline :param _output: IOmanager instance to store", "stage (e.g. \"load_data\") :return: pipeline stage dictionary \"\"\" asset_name = ''.join(x.capitalize() or '_'", ":return: instance of the manager \"\"\" manager_file_name = self.asset_name + '_' + manager_type", "in the following convention:\") print(\">>> Directory: {{asset_name}}\") print(\">>> File: {{asset_name}}_\" + manager_type +", "+ manager_type.capitalize() + \"Manager\") print(\">>> Expected Directory name: \" + self.asset_name) print(\">>> Expected", "name: \" + manager_file_name) print(\">>> Expected Manager class name: \" + manager_class_name) raise", "or \"model_manager\" :return: model_manager instance or data_manager instance \"\"\" if manager_type == 'data_manager':", "be stored \"\"\" print(\">>>>>> Running pipeline\" + self.pipeline_name + \"...\") prev_stage_name = ''", "be passed with *args :return: IOmanager of all the outputs to be stored", "'DataManager', 'model_manager': 'ModelManager' } class PipelineManager(object): def __init__(self, run_id, pipeline_input, _input: IOManager, _output:", "dt.datetime.strptime(start_time, TIME_FORMAT) print(\">>>>>> It took me, {}.\".format(end_time)) print(\">>>>>> Finished running pipeline.\") return self.output_manager", "'' for stage_name in self.stages: start_time = time.strftime(TIME_FORMAT) print(\">>>>>> Running stage: {}...\".format(stage_name)) stage", "self.output_manager class pipeline: def __init__(self, fn): self.fn = fn def __set_name__(self, owner, name):", "in AVAILABLE_STAGES[BASE_CLASS_NAME]: return AVAILABLE_STAGES[BASE_CLASS_NAME][stage_name] raise PipelineManagerException( \"Function '{}' was not found in your", "def __init__(self, run_id, pipeline_input, _input: IOManager, _output: IOManager, config, *args, **kwargs): \"\"\" :param", "run_id self.input_manager = _input self.output_manager = _output self.asset_name = self.config.get('job_settings', {}).get('asset_name', '') self.data_manager_instance", "'ModelManager' } class PipelineManager(object): def __init__(self, run_id, pipeline_input, _input: IOManager, _output: IOManager, config,", "first inputs self.state = dict.fromkeys(self.stages, {}) def create_manager_instance(self, manager_type): \"\"\" Creates manager instance", "settings.get('pipelines', {}).get(pipeline_input, []) self.config = config self.run_id = run_id self.input_manager = _input self.output_manager", "manager file/directory/class names are in the following convention:\") print(\">>> Directory: {{asset_name}}\") print(\">>> File:", "self.stages = pipeline_input if isinstance(pipeline_input, str): self.pipeline_name = \" '\" + pipeline_input +", "'data_manager': return self.data_manager_instance else: return self.model_manager_instance def run(self, *arguments): \"\"\" Runs through the", "Expected Manager class name: \" + manager_class_name) raise FrameworkException(str(e)) def extract_stage(self, stage_name): \"\"\"", "- model_manager instance or data_manager instance :param manager_type: string \"data_manager\" or \"model_manager\" :return:", "# pipeline can be either list of stages or string of a default", "model_manager or data_manader :param manager_type: the type : e.g. \"data\", \"model\" :return: instance", "module = importlib.util.module_from_spec(spec) sys.modules[spec.name] = module spec.loader.exec_module(module) manager_class = getattr(module, manager_class_name) return manager_class(self.config.copy(),", ":return: model_manager instance or data_manager instance \"\"\" if manager_type == 'data_manager': return self.data_manager_instance", "'{}'\" .format(asset_name, name)) AVAILABLE_STAGES[asset_name][name] = { 'function': self.fn, 'manager': manager_type } return self.fn", "import sys import os from mlapp.config import settings from mlapp.utils.exceptions.base_exceptions import PipelineManagerException, FrameworkException", "import os from mlapp.config import settings from mlapp.utils.exceptions.base_exceptions import PipelineManagerException, FrameworkException from mlapp.managers.io_manager", "manager_type + '_manager' manager_module = 'assets.' + self.asset_name + '.' + manager_file_name manager_module_path", "your asset! Add '@pipeline' decorator above your '{}' \" \"function if you want", "saved externally :param config: config string of the pipeline :param args: :param kwargs:", "+ '_' + manager_type + '_manager' manager_module = 'assets.' + self.asset_name + '.'", "the following convention:\") print(\">>> Directory: {{asset_name}}\") print(\">>> File: {{asset_name}}_\" + manager_type + \"_manager.py\")", "= getattr(module, manager_class_name) return manager_class(self.config.copy(), self.input_manager, self.output_manager, self.run_id) except Exception as e: print(\"Couldn't", "decoration for your pipeline functions! Add '@pipeline' decorator above functions\" \" you want", "class it resides in. :param stage_name: the name of the stage (e.g. \"load_data\")", "Please verify your \" + manager_type + \" manager file/directory/class names are in", ":param config: config string of the pipeline :param args: :param kwargs: \"\"\" for", "+ '.' + manager_file_name manager_module_path = os.path.join('assets', self.asset_name, f'{manager_file_name }.py') manager_class_name = ''.join(x.capitalize()", "you want to use in your asset '{}'s Data Manager and Model Manager.\".format(asset_name))", "'').replace('ModelManager', '') if asset_name not in AVAILABLE_STAGES: AVAILABLE_STAGES[asset_name] = {} if name in", "or placement of decorator! ('{}')\".format(asset_name)) asset_name = asset_name.replace('DataManager', '').replace('ModelManager', '') if asset_name not", "manager_type is None: raise Exception(\"Wrong class name or placement of decorator! ('{}')\".format(asset_name)) asset_name", "isinstance(pipeline_input, list): self.stages = pipeline_input if isinstance(pipeline_input, str): self.pipeline_name = \" '\" +", "self.create_manager_instance('data') self.model_manager_instance = self.create_manager_instance('model') # first inputs self.state = dict.fromkeys(self.stages, {}) def create_manager_instance(self,", "{} self.pipeline_name = '' # pipeline can be either list of stages or", "pipeline.\".format(stage_name, stage_name)) return AVAILABLE_STAGES[asset_name][stage_name] def extract_manager_instance(self, manager_type): \"\"\" Gets the instance of the", "if you want to use it in your pipeline.\".format(stage_name, stage_name)) return AVAILABLE_STAGES[asset_name][stage_name] def", "or '_' for x in self.asset_name.split('_')) # CamelCase if asset_name not in AVAILABLE_STAGES:", "with *args :return: IOmanager of all the outputs to be stored \"\"\" print(\">>>>>>", "'\" + pipeline_input + \"'\" self.stages = settings.get('pipelines', {}).get(pipeline_input, []) self.config = config", "pipeline name string or list of strings :param _input: IOmanager instance with input", "{{asset_name}}\") print(\">>> File: {{asset_name}}_\" + manager_type + \"_manager.py\") print(\">>> Class: {{asset_name_capitalized}}\" + manager_type.capitalize()", "for stage_name in self.stages: start_time = time.strftime(TIME_FORMAT) print(\">>>>>> Running stage: {}...\".format(stage_name)) stage =", "stage in the pipeline, will be passed with *args :return: IOmanager of all", "found in your asset! Add '@pipeline' decorator above your '{}' \" \"function if", "return self.data_manager_instance else: return self.model_manager_instance def run(self, *arguments): \"\"\" Runs through the pipeline", "self.output_manager = _output self.asset_name = self.config.get('job_settings', {}).get('asset_name', '') self.data_manager_instance = self.create_manager_instance('data') self.model_manager_instance =", "instance which class is defined in the asset. For example: model_manager or data_manader", "all the outputs to be stored \"\"\" print(\">>>>>> Running pipeline\" + self.pipeline_name +", "execute stage self.state[stage_name] = stage['function'](self.extract_manager_instance(stage['manager']), *args) if not isinstance(self.state[stage_name], tuple): self.state[stage_name] = (self.state[stage_name],)", "_input: IOManager, _output: IOManager, config, *args, **kwargs): \"\"\" :param pipeline_input: the pipeline name", "relevant values between them :param arguments: input for the first stage in the", "raise PipelineManagerException( \"Missing decoration for your pipeline functions! Add '@pipeline' decorator above functions\"", "in AVAILABLE_STAGES[asset_name]: raise Exception(\"Duplicate stage name '{}' for pipelines found in asset '{}'\"", "not found in your asset! Add '@pipeline' decorator above your '{}' \" \"function", "the type : e.g. \"data\", \"model\" :return: instance of the manager \"\"\" manager_file_name", "__set_name__(self, owner, name): asset_name = owner.__name__ manager_type = None for manager_type_key in MANAGER_TYPES:", "name: \" + manager_class_name) raise FrameworkException(str(e)) def extract_stage(self, stage_name): \"\"\" Gets the pipeline", "pipeline, will be passed with *args :return: IOmanager of all the outputs to", "manager_type): \"\"\" Gets the instance of the manager - model_manager instance or data_manager", "asset_name not in AVAILABLE_STAGES: raise PipelineManagerException( \"Missing decoration for your pipeline functions! Add", "from mlapp.config import settings from mlapp.utils.exceptions.base_exceptions import PipelineManagerException, FrameworkException from mlapp.managers.io_manager import IOManager", "\"Function '{}' was not found in your asset! Add '@pipeline' decorator above your", "self.state = dict.fromkeys(self.stages, {}) def create_manager_instance(self, manager_type): \"\"\" Creates manager instance which class", "running pipeline.\") return self.output_manager class pipeline: def __init__(self, fn): self.fn = fn def", "AVAILABLE_STAGES[BASE_CLASS_NAME][stage_name] raise PipelineManagerException( \"Function '{}' was not found in your asset! Add '@pipeline'", "the function and the manager class it resides in. :param stage_name: the name", "for x in self.asset_name.split('_')) # CamelCase if asset_name not in AVAILABLE_STAGES: raise PipelineManagerException(", "in one if the base classes if stage_name in AVAILABLE_STAGES[BASE_CLASS_NAME]: return AVAILABLE_STAGES[BASE_CLASS_NAME][stage_name] raise", "'' TIME_FORMAT = '%Y-%m-%d %H:%M:%S' MANAGER_TYPES = { 'data_manager': 'DataManager', 'model_manager': 'ModelManager' }", "module spec.loader.exec_module(module) manager_class = getattr(module, manager_class_name) return manager_class(self.config.copy(), self.input_manager, self.output_manager, self.run_id) except Exception", "resides in. :param stage_name: the name of the stage (e.g. \"load_data\") :return: pipeline", "your '{}' \" \"function if you want to use it in your pipeline.\".format(stage_name,", "default pipeline if isinstance(pipeline_input, list): self.stages = pipeline_input if isinstance(pipeline_input, str): self.pipeline_name =", "IOManager, config, *args, **kwargs): \"\"\" :param pipeline_input: the pipeline name string or list", "AVAILABLE_STAGES: AVAILABLE_STAGES[asset_name] = {} if name in AVAILABLE_STAGES[asset_name]: raise Exception(\"Duplicate stage name '{}'", "pipeline_input: the pipeline name string or list of strings :param _input: IOmanager instance", "data_manager instance \"\"\" if manager_type == 'data_manager': return self.data_manager_instance else: return self.model_manager_instance def", "'%Y-%m-%d %H:%M:%S' MANAGER_TYPES = { 'data_manager': 'DataManager', 'model_manager': 'ModelManager' } class PipelineManager(object): def", "it resides in. :param stage_name: the name of the stage (e.g. \"load_data\") :return:", "of the pipeline :param args: :param kwargs: \"\"\" for asset_name in AVAILABLE_STAGES: if", "pipelines found in asset '{}'\" .format(asset_name, name)) AVAILABLE_STAGES[asset_name][name] = { 'function': self.fn, 'manager':", "if prev_stage_name: args = self.state[prev_stage_name] else: args = arguments # execute stage self.state[stage_name]", "'' # pipeline can be either list of stages or string of a", "= owner.__name__ manager_type = None for manager_type_key in MANAGER_TYPES: if MANAGER_TYPES[manager_type_key] in asset_name:", "FrameworkException(str(e)) def extract_stage(self, stage_name): \"\"\" Gets the pipeline stage dictioanry containing the function", "or list of strings :param _input: IOmanager instance with input to the pipeline", "of strings :param _input: IOmanager instance with input to the pipeline :param _output:", "manager_type: the type : e.g. \"data\", \"model\" :return: instance of the manager \"\"\"", "if MANAGER_TYPES[manager_type_key] in asset_name: manager_type = manager_type_key if manager_type is None: raise Exception(\"Wrong", ":param _input: IOmanager instance with input to the pipeline :param _output: IOmanager instance", "file name: \" + manager_file_name) print(\">>> Expected Manager class name: \" + manager_class_name)", "asset_name = owner.__name__ manager_type = None for manager_type_key in MANAGER_TYPES: if MANAGER_TYPES[manager_type_key] in", "sys import os from mlapp.config import settings from mlapp.utils.exceptions.base_exceptions import PipelineManagerException, FrameworkException from", "the pipeline :param _output: IOmanager instance to store the outputs of the pipelines", "print(\">>> File: {{asset_name}}_\" + manager_type + \"_manager.py\") print(\">>> Class: {{asset_name_capitalized}}\" + manager_type.capitalize() +", "stage_name): \"\"\" Gets the pipeline stage dictioanry containing the function and the manager", "tuple): self.state[stage_name] = (self.state[stage_name],) prev_stage_name = stage_name end_time = dt.datetime.strptime( time.strftime(TIME_FORMAT), TIME_FORMAT) -", "self.pipeline_name = '' # pipeline can be either list of stages or string", "None: raise Exception(\"Wrong class name or placement of decorator! ('{}')\".format(asset_name)) asset_name = asset_name.replace('DataManager',", "the pipeline stage dictioanry containing the function and the manager class it resides", "name or placement of decorator! ('{}')\".format(asset_name)) asset_name = asset_name.replace('DataManager', '').replace('ModelManager', '') if asset_name", "AVAILABLE_STAGES[asset_name] = {} if name in AVAILABLE_STAGES[asset_name]: raise Exception(\"Duplicate stage name '{}' for", "config self.run_id = run_id self.input_manager = _input self.output_manager = _output self.asset_name = self.config.get('job_settings',", "= ''.join(x.capitalize() or '_' for x in manager_file_name.split('_')) # CamelCase try: spec =", "except Exception as e: print(\"Couldn't import class of \" + manager_type + \"", "the manager class it resides in. :param stage_name: the name of the stage", "name '{}' for pipelines found in asset '{}'\" .format(asset_name, name)) AVAILABLE_STAGES[asset_name][name] = {", "them :param arguments: input for the first stage in the pipeline, will be", "AVAILABLE_STAGES[asset_name]: # exists in one if the base classes if stage_name in AVAILABLE_STAGES[BASE_CLASS_NAME]:", "in. :param stage_name: the name of the stage (e.g. \"load_data\") :return: pipeline stage", "extract_stage(self, stage_name): \"\"\" Gets the pipeline stage dictioanry containing the function and the", "the pipelines to be saved externally :param config: config string of the pipeline", "print(\"Couldn't import class of \" + manager_type + \" manager for model: \"", "= {} BASE_CLASS_NAME = '' TIME_FORMAT = '%Y-%m-%d %H:%M:%S' MANAGER_TYPES = { 'data_manager':", "= dt.datetime.strptime( time.strftime(TIME_FORMAT), TIME_FORMAT) - dt.datetime.strptime(start_time, TIME_FORMAT) print(\">>>>>> It took me, {}.\".format(end_time)) print(\">>>>>>", "self.create_manager_instance('model') # first inputs self.state = dict.fromkeys(self.stages, {}) def create_manager_instance(self, manager_type): \"\"\" Creates", "as e: print(\"Couldn't import class of \" + manager_type + \" manager for", "+ \"Manager\") print(\">>> Expected Directory name: \" + self.asset_name) print(\">>> Expected Manager file", "raise FrameworkException(str(e)) def extract_stage(self, stage_name): \"\"\" Gets the pipeline stage dictioanry containing the", "end_time = dt.datetime.strptime( time.strftime(TIME_FORMAT), TIME_FORMAT) - dt.datetime.strptime(start_time, TIME_FORMAT) print(\">>>>>> It took me, {}.\".format(end_time))", "your \" + manager_type + \" manager file/directory/class names are in the following", "{}) def create_manager_instance(self, manager_type): \"\"\" Creates manager instance which class is defined in", "x in self.asset_name.split('_')) # CamelCase if asset_name not in AVAILABLE_STAGES: raise PipelineManagerException( \"Missing", "{}.\".format(end_time)) print(\">>>>>> Finished running pipeline.\") return self.output_manager class pipeline: def __init__(self, fn): self.fn", "if name in AVAILABLE_STAGES[asset_name]: raise Exception(\"Duplicate stage name '{}' for pipelines found in", "names are in the following convention:\") print(\">>> Directory: {{asset_name}}\") print(\">>> File: {{asset_name}}_\" +", "instance to store the outputs of the pipelines to be saved externally :param", "outputs to be stored \"\"\" print(\">>>>>> Running pipeline\" + self.pipeline_name + \"...\") prev_stage_name", "Exception(\"Duplicate stage name '{}' for pipelines found in asset '{}'\" .format(asset_name, name)) AVAILABLE_STAGES[asset_name][name]", "through the pipeline stages and passes relevant values between them :param arguments: input", "self.run_id = run_id self.input_manager = _input self.output_manager = _output self.asset_name = self.config.get('job_settings', {}).get('asset_name',", "between them :param arguments: input for the first stage in the pipeline, will", "'') if asset_name not in AVAILABLE_STAGES: AVAILABLE_STAGES[asset_name] = {} if name in AVAILABLE_STAGES[asset_name]:", "in your asset! Add '@pipeline' decorator above your '{}' \" \"function if you", "+ '_manager' manager_module = 'assets.' + self.asset_name + '.' + manager_file_name manager_module_path =", "{{asset_name_capitalized}}\" + manager_type.capitalize() + \"Manager\") print(\">>> Expected Directory name: \" + self.asset_name) print(\">>>", "strings :param _input: IOmanager instance with input to the pipeline :param _output: IOmanager", "dictioanry containing the function and the manager class it resides in. :param stage_name:", "'@pipeline' decorator above functions\" \" you want to use in your asset '{}'s", "if isinstance(pipeline_input, list): self.stages = pipeline_input if isinstance(pipeline_input, str): self.pipeline_name = \" '\"", "\" manager for model: \" + self.asset_name) print(\">>> Please verify your \" +", "else: return self.model_manager_instance def run(self, *arguments): \"\"\" Runs through the pipeline stages and", "data_manader :param manager_type: the type : e.g. \"data\", \"model\" :return: instance of the", "the manager - model_manager instance or data_manager instance :param manager_type: string \"data_manager\" or", "in manager_file_name.split('_')) # CamelCase try: spec = importlib.util.spec_from_file_location(manager_module, manager_module_path) module = importlib.util.module_from_spec(spec) sys.modules[spec.name]", "PipelineManagerException, FrameworkException from mlapp.managers.io_manager import IOManager AVAILABLE_STAGES = {} BASE_CLASS_NAME = '' TIME_FORMAT", "_output: IOManager, config, *args, **kwargs): \"\"\" :param pipeline_input: the pipeline name string or", "Expected Directory name: \" + self.asset_name) print(\">>> Expected Manager file name: \" +", "one if the base classes if stage_name in AVAILABLE_STAGES[BASE_CLASS_NAME]: return AVAILABLE_STAGES[BASE_CLASS_NAME][stage_name] raise PipelineManagerException(", "input for the first stage in the pipeline, will be passed with *args", "self.extract_stage(stage_name) if prev_stage_name: args = self.state[prev_stage_name] else: args = arguments # execute stage", "else: args = arguments # execute stage self.state[stage_name] = stage['function'](self.extract_manager_instance(stage['manager']), *args) if not", "self.asset_name) print(\">>> Expected Manager file name: \" + manager_file_name) print(\">>> Expected Manager class", "Manager.\".format(asset_name)) if stage_name not in AVAILABLE_STAGES[asset_name]: # exists in one if the base", "of \" + manager_type + \" manager for model: \" + self.asset_name) print(\">>>", "\" + manager_type + \" manager file/directory/class names are in the following convention:\")", "\"\"\" Runs through the pipeline stages and passes relevant values between them :param", "to be saved externally :param config: config string of the pipeline :param args:", "decorator above your '{}' \" \"function if you want to use it in", "= manager_type_key if manager_type is None: raise Exception(\"Wrong class name or placement of", "or '_' for x in manager_file_name.split('_')) # CamelCase try: spec = importlib.util.spec_from_file_location(manager_module, manager_module_path)", "as dt import importlib.util import sys import os from mlapp.config import settings from", "+ \"_manager.py\") print(\">>> Class: {{asset_name_capitalized}}\" + manager_type.capitalize() + \"Manager\") print(\">>> Expected Directory name:", "print(\">>> Expected Manager file name: \" + manager_file_name) print(\">>> Expected Manager class name:", "IOmanager of all the outputs to be stored \"\"\" print(\">>>>>> Running pipeline\" +", "_input: IOmanager instance with input to the pipeline :param _output: IOmanager instance to", "\"\"\" manager_file_name = self.asset_name + '_' + manager_type + '_manager' manager_module = 'assets.'", "Gets the pipeline stage dictioanry containing the function and the manager class it", "to use it in your pipeline.\".format(stage_name, stage_name)) return AVAILABLE_STAGES[asset_name][stage_name] def extract_manager_instance(self, manager_type): \"\"\"", "instance \"\"\" if manager_type == 'data_manager': return self.data_manager_instance else: return self.model_manager_instance def run(self,", ":param _output: IOmanager instance to store the outputs of the pipelines to be", "= self.create_manager_instance('model') # first inputs self.state = dict.fromkeys(self.stages, {}) def create_manager_instance(self, manager_type): \"\"\"", "fn def __set_name__(self, owner, name): asset_name = owner.__name__ manager_type = None for manager_type_key", "of all the outputs to be stored \"\"\" print(\">>>>>> Running pipeline\" + self.pipeline_name", "Finished running pipeline.\") return self.output_manager class pipeline: def __init__(self, fn): self.fn = fn", "__init__(self, fn): self.fn = fn def __set_name__(self, owner, name): asset_name = owner.__name__ manager_type", "\"model\" :return: instance of the manager \"\"\" manager_file_name = self.asset_name + '_' +", "manager for model: \" + self.asset_name) print(\">>> Please verify your \" + manager_type", "pipeline.\") return self.output_manager class pipeline: def __init__(self, fn): self.fn = fn def __set_name__(self,", "stage dictioanry containing the function and the manager class it resides in. :param", "stage['function'](self.extract_manager_instance(stage['manager']), *args) if not isinstance(self.state[stage_name], tuple): self.state[stage_name] = (self.state[stage_name],) prev_stage_name = stage_name end_time", "in AVAILABLE_STAGES[asset_name]: # exists in one if the base classes if stage_name in", "if not isinstance(self.state[stage_name], tuple): self.state[stage_name] = (self.state[stage_name],) prev_stage_name = stage_name end_time = dt.datetime.strptime(", "was not found in your asset! Add '@pipeline' decorator above your '{}' \"", "want to use in your asset '{}'s Data Manager and Model Manager.\".format(asset_name)) if", "'.' + manager_file_name manager_module_path = os.path.join('assets', self.asset_name, f'{manager_file_name }.py') manager_class_name = ''.join(x.capitalize() or", "instance :param manager_type: string \"data_manager\" or \"model_manager\" :return: model_manager instance or data_manager instance", "return manager_class(self.config.copy(), self.input_manager, self.output_manager, self.run_id) except Exception as e: print(\"Couldn't import class of", "= \" '\" + pipeline_input + \"'\" self.stages = settings.get('pipelines', {}).get(pipeline_input, []) self.config", "passes relevant values between them :param arguments: input for the first stage in", "the pipeline :param args: :param kwargs: \"\"\" for asset_name in AVAILABLE_STAGES: if asset_name", "the manager \"\"\" manager_file_name = self.asset_name + '_' + manager_type + '_manager' manager_module", "pipeline if isinstance(pipeline_input, list): self.stages = pipeline_input if isinstance(pipeline_input, str): self.pipeline_name = \"", "+ self.asset_name + '.' + manager_file_name manager_module_path = os.path.join('assets', self.asset_name, f'{manager_file_name }.py') manager_class_name", "CamelCase if asset_name not in AVAILABLE_STAGES: raise PipelineManagerException( \"Missing decoration for your pipeline", "mlapp.config import settings from mlapp.utils.exceptions.base_exceptions import PipelineManagerException, FrameworkException from mlapp.managers.io_manager import IOManager AVAILABLE_STAGES", "= module spec.loader.exec_module(module) manager_class = getattr(module, manager_class_name) return manager_class(self.config.copy(), self.input_manager, self.output_manager, self.run_id) except", "manager_class = getattr(module, manager_class_name) return manager_class(self.config.copy(), self.input_manager, self.output_manager, self.run_id) except Exception as e:", "stage_name not in AVAILABLE_STAGES[asset_name]: # exists in one if the base classes if", "AVAILABLE_STAGES[asset_name][stage_name] def extract_manager_instance(self, manager_type): \"\"\" Gets the instance of the manager - model_manager", "in the pipeline, will be passed with *args :return: IOmanager of all the", "asset_name = asset_name.replace('DataManager', '').replace('ModelManager', '') if asset_name not in AVAILABLE_STAGES: AVAILABLE_STAGES[asset_name] = {}", "def extract_manager_instance(self, manager_type): \"\"\" Gets the instance of the manager - model_manager instance", "pipeline_input + \"'\" self.stages = settings.get('pipelines', {}).get(pipeline_input, []) self.config = config self.run_id =", "data_manager instance :param manager_type: string \"data_manager\" or \"model_manager\" :return: model_manager instance or data_manager", "('{}')\".format(asset_name)) asset_name = asset_name.replace('DataManager', '').replace('ModelManager', '') if asset_name not in AVAILABLE_STAGES: AVAILABLE_STAGES[asset_name] =", "datetime as dt import importlib.util import sys import os from mlapp.config import settings", "= stage['function'](self.extract_manager_instance(stage['manager']), *args) if not isinstance(self.state[stage_name], tuple): self.state[stage_name] = (self.state[stage_name],) prev_stage_name = stage_name", "above functions\" \" you want to use in your asset '{}'s Data Manager", "x in manager_file_name.split('_')) # CamelCase try: spec = importlib.util.spec_from_file_location(manager_module, manager_module_path) module = importlib.util.module_from_spec(spec)", "IOManager AVAILABLE_STAGES = {} BASE_CLASS_NAME = '' TIME_FORMAT = '%Y-%m-%d %H:%M:%S' MANAGER_TYPES =", "Exception as e: print(\"Couldn't import class of \" + manager_type + \" manager", "File: {{asset_name}}_\" + manager_type + \"_manager.py\") print(\">>> Class: {{asset_name_capitalized}}\" + manager_type.capitalize() + \"Manager\")", "= stage_name end_time = dt.datetime.strptime( time.strftime(TIME_FORMAT), TIME_FORMAT) - dt.datetime.strptime(start_time, TIME_FORMAT) print(\">>>>>> It took", "to use in your asset '{}'s Data Manager and Model Manager.\".format(asset_name)) if stage_name", "and Model Manager.\".format(asset_name)) if stage_name not in AVAILABLE_STAGES[asset_name]: # exists in one if", "Manager file name: \" + manager_file_name) print(\">>> Expected Manager class name: \" +", "*args) if not isinstance(self.state[stage_name], tuple): self.state[stage_name] = (self.state[stage_name],) prev_stage_name = stage_name end_time =", "import time import datetime as dt import importlib.util import sys import os from", "use it in your pipeline.\".format(stage_name, stage_name)) return AVAILABLE_STAGES[asset_name][stage_name] def extract_manager_instance(self, manager_type): \"\"\" Gets", "'{}' \" \"function if you want to use it in your pipeline.\".format(stage_name, stage_name))", "'_manager' manager_module = 'assets.' + self.asset_name + '.' + manager_file_name manager_module_path = os.path.join('assets',", "asset! Add '@pipeline' decorator above your '{}' \" \"function if you want to", "in AVAILABLE_STAGES: if asset_name != BASE_CLASS_NAME: AVAILABLE_STAGES[asset_name] = {} self.pipeline_name = '' #", "\" + self.asset_name) print(\">>> Please verify your \" + manager_type + \" manager", "not in AVAILABLE_STAGES: raise PipelineManagerException( \"Missing decoration for your pipeline functions! Add '@pipeline'", "'{}'s Data Manager and Model Manager.\".format(asset_name)) if stage_name not in AVAILABLE_STAGES[asset_name]: # exists", "verify your \" + manager_type + \" manager file/directory/class names are in the", "import class of \" + manager_type + \" manager for model: \" +", "TIME_FORMAT = '%Y-%m-%d %H:%M:%S' MANAGER_TYPES = { 'data_manager': 'DataManager', 'model_manager': 'ModelManager' } class", "string of the pipeline :param args: :param kwargs: \"\"\" for asset_name in AVAILABLE_STAGES:", "spec.loader.exec_module(module) manager_class = getattr(module, manager_class_name) return manager_class(self.config.copy(), self.input_manager, self.output_manager, self.run_id) except Exception as", "name of the stage (e.g. \"load_data\") :return: pipeline stage dictionary \"\"\" asset_name =", "= dict.fromkeys(self.stages, {}) def create_manager_instance(self, manager_type): \"\"\" Creates manager instance which class is", "args = arguments # execute stage self.state[stage_name] = stage['function'](self.extract_manager_instance(stage['manager']), *args) if not isinstance(self.state[stage_name],", "is None: raise Exception(\"Wrong class name or placement of decorator! ('{}')\".format(asset_name)) asset_name =", "owner.__name__ manager_type = None for manager_type_key in MANAGER_TYPES: if MANAGER_TYPES[manager_type_key] in asset_name: manager_type", "took me, {}.\".format(end_time)) print(\">>>>>> Finished running pipeline.\") return self.output_manager class pipeline: def __init__(self,", "config string of the pipeline :param args: :param kwargs: \"\"\" for asset_name in", "manager_class(self.config.copy(), self.input_manager, self.output_manager, self.run_id) except Exception as e: print(\"Couldn't import class of \"", "in asset '{}'\" .format(asset_name, name)) AVAILABLE_STAGES[asset_name][name] = { 'function': self.fn, 'manager': manager_type }", "{} BASE_CLASS_NAME = '' TIME_FORMAT = '%Y-%m-%d %H:%M:%S' MANAGER_TYPES = { 'data_manager': 'DataManager',", "\"Missing decoration for your pipeline functions! Add '@pipeline' decorator above functions\" \" you", "stage dictionary \"\"\" asset_name = ''.join(x.capitalize() or '_' for x in self.asset_name.split('_')) #", "exists in one if the base classes if stage_name in AVAILABLE_STAGES[BASE_CLASS_NAME]: return AVAILABLE_STAGES[BASE_CLASS_NAME][stage_name]", "Manager and Model Manager.\".format(asset_name)) if stage_name not in AVAILABLE_STAGES[asset_name]: # exists in one", "''.join(x.capitalize() or '_' for x in manager_file_name.split('_')) # CamelCase try: spec = importlib.util.spec_from_file_location(manager_module,", "!= BASE_CLASS_NAME: AVAILABLE_STAGES[asset_name] = {} self.pipeline_name = '' # pipeline can be either", "convention:\") print(\">>> Directory: {{asset_name}}\") print(\">>> File: {{asset_name}}_\" + manager_type + \"_manager.py\") print(\">>> Class:", "it in your pipeline.\".format(stage_name, stage_name)) return AVAILABLE_STAGES[asset_name][stage_name] def extract_manager_instance(self, manager_type): \"\"\" Gets the" ]
[ "model._meta.verbose_name_plural @register.filter def model_name(model): \"\"\" Sample usage: {{model|model_name}} \"\"\" return model._meta.model_name @register.filter def", "self.model_var = model_var self.action_var = action_var def render(self, context): # Resolving variables passed", "token.contents != end_tag: current = token.contents states[current.split()[0]] = parser.parse(default_states + [end_tag]) token =", "to store the states and their values states = {} # Let's iterate", "else %} <div style=\"color: #900\">User cannot add objects</div> {% endifhasperm %} \"\"\" #", "action_var): self.states = states self.model_var = model_var self.action_var = action_var def render(self, context):", "{% testhasperm model 'view' as can_view_objects %} {% if not can_view_objects %} <h2>Sorry,", "return user.is_authenticated and user.has_perm(required_permission) @register.tag def ifhasperm(parser, token): \"\"\" Check user permission over", "html = self.states['ifhasperm'].render(context) else: html = self.states['else'].render(context) if 'else' in self.states else ''", "def testhasperm(context, model, action): \"\"\" Returns True iif the user have the specified", "we accept either a Model class, or a string formatted as \"app_label.model_name\". Sample", "action_var def render(self, context): # Resolving variables passed by the user model =", "%} {% if not can_view_objects %} <h2>Sorry, you have no permission to view", "while token.contents != end_tag: current = token.contents states[current.split()[0]] = parser.parse(default_states + [end_tag]) token", "token.contents states[current.split()[0]] = parser.parse(default_states + [end_tag]) token = parser.next_token() model_var = parser.compile_filter(model) action_var", "store the states and their values states = {} # Let's iterate over", "\"'%s' tag takes three parameters\" % tag) default_states = ['ifhasperm', 'else'] end_tag =", "\"\"\" return model._meta.app_label @register.simple_tag(takes_context=True) def testhasperm(context, model, action): \"\"\" Returns True iif the", "return model._meta.app_label @register.simple_tag(takes_context=True) def testhasperm(context, model, action): \"\"\" Returns True iif the user", "\"\"\" Sample usage: {{model|model_name}} \"\"\" return model._meta.verbose_name @register.filter def model_verbose_name_plural(model): \"\"\" Sample usage:", "Sample usage: {{model|model_name}} \"\"\" return model._meta.verbose_name @register.filter def model_verbose_name_plural(model): \"\"\" Sample usage: {{model|model_name}}", "model or an object). Sample usage: {% ifhasperm model 'add' %} <div style=\"color:", "[end_tag]) token = parser.next_token() model_var = parser.compile_filter(model) action_var = parser.compile_filter(action) return CheckPermNode(states, model_var,", "class CheckPermNode(template.Node): def __init__(self, states, model_var, action_var): self.states = states self.model_var = model_var", "Sample usage: {% testhasperm model 'view' as can_view_objects %} {% if not can_view_objects", "permission if testhasperm(context, model, action): html = self.states['ifhasperm'].render(context) else: html = self.states['else'].render(context) if", "for generic editing in the front-end @register.filter def model_verbose_name(model): \"\"\" Sample usage: {{model|model_name}}", "% (app_label, action, model_name) return user.is_authenticated and user.has_perm(required_permission) @register.tag def ifhasperm(parser, token): \"\"\"", "+ [end_tag]) token = parser.next_token() model_var = parser.compile_filter(model) action_var = parser.compile_filter(action) return CheckPermNode(states,", "\"\"\" return model._meta.model_name @register.filter def app_label(model): \"\"\" Sample usage: {{model|app_label}} \"\"\" return model._meta.app_label", "'endifhasperm' # Place to store the states and their values states = {}", "model._meta.app_label model_name = model._meta.model_name required_permission = '%s.%s_%s' % (app_label, action, model_name) return user.is_authenticated", "model_verbose_name(model): \"\"\" Sample usage: {{model|model_name}} \"\"\" return model._meta.verbose_name @register.filter def model_verbose_name_plural(model): \"\"\" Sample", "our tokens while token.contents != end_tag: current = token.contents states[current.split()[0]] = parser.parse(default_states +", "import template register = template.Library() ################################################################################ # Support for generic editing in the", "the model. For 'model', we accept either a Model class, or a string", "= self.states['ifhasperm'].render(context) else: html = self.states['else'].render(context) if 'else' in self.states else '' return", "= model._meta.app_label model_name = model._meta.model_name required_permission = '%s.%s_%s' % (app_label, action, model_name) return", "have no permission to view these objects</h2> {% endif %} \"\"\" user =", "model_verbose_name_plural(model): \"\"\" Sample usage: {{model|model_name}} \"\"\" return model._meta.verbose_name_plural @register.filter def model_name(model): \"\"\" Sample", "# Let's iterate over our context and find our tokens while token.contents !=", "Resolving variables passed by the user model = self.model_var.resolve(context) action = self.action_var.resolve(context) #", "{{model|model_name}} \"\"\" return model._meta.verbose_name @register.filter def model_verbose_name_plural(model): \"\"\" Sample usage: {{model|model_name}} \"\"\" return", "tokens while token.contents != end_tag: current = token.contents states[current.split()[0]] = parser.parse(default_states + [end_tag])", "front-end @register.filter def model_verbose_name(model): \"\"\" Sample usage: {{model|model_name}} \"\"\" return model._meta.verbose_name @register.filter def", "passed by the user model = self.model_var.resolve(context) action = self.action_var.resolve(context) # Check user", "takes three parameters\" % tag) default_states = ['ifhasperm', 'else'] end_tag = 'endifhasperm' #", "= self.model_var.resolve(context) action = self.action_var.resolve(context) # Check user permission if testhasperm(context, model, action):", "tag takes three parameters\" % tag) default_states = ['ifhasperm', 'else'] end_tag = 'endifhasperm'", "model._meta.verbose_name @register.filter def model_verbose_name_plural(model): \"\"\" Sample usage: {{model|model_name}} \"\"\" return model._meta.verbose_name_plural @register.filter def", "by the user model = self.model_var.resolve(context) action = self.action_var.resolve(context) # Check user permission", "@register.filter def model_verbose_name_plural(model): \"\"\" Sample usage: {{model|model_name}} \"\"\" return model._meta.verbose_name_plural @register.filter def model_name(model):", "template.Library() ################################################################################ # Support for generic editing in the front-end @register.filter def model_verbose_name(model):", "user have the specified permission over the model. For 'model', we accept either", "over our context and find our tokens while token.contents != end_tag: current =", "action): \"\"\" Returns True iif the user have the specified permission over the", "token.contents.split() except (ValueError, TypeError): raise template.TemplateSyntaxError( \"'%s' tag takes three parameters\" % tag)", "testhasperm model 'view' as can_view_objects %} {% if not can_view_objects %} <h2>Sorry, you", "CheckPermNode(states, model_var, action_var) class CheckPermNode(template.Node): def __init__(self, states, model_var, action_var): self.states = states", "the tag name from the parameters try: tag, model, action = token.contents.split() except", "and user.has_perm(required_permission) @register.tag def ifhasperm(parser, token): \"\"\" Check user permission over specified model.", "{} # Let's iterate over our context and find our tokens while token.contents", "str): app_label, model_name = model.split('.') else: app_label = model._meta.app_label model_name = model._meta.model_name required_permission", "def app_label(model): \"\"\" Sample usage: {{model|app_label}} \"\"\" return model._meta.app_label @register.simple_tag(takes_context=True) def testhasperm(context, model,", "raise template.TemplateSyntaxError( \"'%s' tag takes three parameters\" % tag) default_states = ['ifhasperm', 'else']", "def render(self, context): # Resolving variables passed by the user model = self.model_var.resolve(context)", "{{model|model_name}} \"\"\" return model._meta.verbose_name_plural @register.filter def model_name(model): \"\"\" Sample usage: {{model|model_name}} \"\"\" return", "user permission if testhasperm(context, model, action): html = self.states['ifhasperm'].render(context) else: html = self.states['else'].render(context)", "over specified model. (You can specify either a model or an object). Sample", "permission over specified model. (You can specify either a model or an object).", "= action_var def render(self, context): # Resolving variables passed by the user model", "or a string formatted as \"app_label.model_name\". Sample usage: {% testhasperm model 'view' as", "find our tokens while token.contents != end_tag: current = token.contents states[current.split()[0]] = parser.parse(default_states", "['ifhasperm', 'else'] end_tag = 'endifhasperm' # Place to store the states and their", "template.TemplateSyntaxError( \"'%s' tag takes three parameters\" % tag) default_states = ['ifhasperm', 'else'] end_tag", "\"app_label.model_name\". Sample usage: {% testhasperm model 'view' as can_view_objects %} {% if not", "their values states = {} # Let's iterate over our context and find", "usage: {{model|model_name}} \"\"\" return model._meta.model_name @register.filter def app_label(model): \"\"\" Sample usage: {{model|app_label}} \"\"\"", "def __init__(self, states, model_var, action_var): self.states = states self.model_var = model_var self.action_var =", "{% endif %} \"\"\" user = context['request'].user if isinstance(model, str): app_label, model_name =", "an object). Sample usage: {% ifhasperm model 'add' %} <div style=\"color: #090\">User can", "the states and their values states = {} # Let's iterate over our", "%} <div style=\"color: #090\">User can add objects</div> {% else %} <div style=\"color: #900\">User", "register = template.Library() ################################################################################ # Support for generic editing in the front-end @register.filter", "%} \"\"\" # Separating the tag name from the parameters try: tag, model,", "\"\"\" Sample usage: {{model|model_name}} \"\"\" return model._meta.verbose_name_plural @register.filter def model_name(model): \"\"\" Sample usage:", "action, model_name) return user.is_authenticated and user.has_perm(required_permission) @register.tag def ifhasperm(parser, token): \"\"\" Check user", "Model class, or a string formatted as \"app_label.model_name\". Sample usage: {% testhasperm model", "model.split('.') else: app_label = model._meta.app_label model_name = model._meta.model_name required_permission = '%s.%s_%s' % (app_label,", "model_name(model): \"\"\" Sample usage: {{model|model_name}} \"\"\" return model._meta.model_name @register.filter def app_label(model): \"\"\" Sample", "the user have the specified permission over the model. For 'model', we accept", "values states = {} # Let's iterate over our context and find our", "@register.filter def app_label(model): \"\"\" Sample usage: {{model|app_label}} \"\"\" return model._meta.app_label @register.simple_tag(takes_context=True) def testhasperm(context,", "def model_name(model): \"\"\" Sample usage: {{model|model_name}} \"\"\" return model._meta.model_name @register.filter def app_label(model): \"\"\"", "{{model|app_label}} \"\"\" return model._meta.app_label @register.simple_tag(takes_context=True) def testhasperm(context, model, action): \"\"\" Returns True iif", "(ValueError, TypeError): raise template.TemplateSyntaxError( \"'%s' tag takes three parameters\" % tag) default_states =", "model_var self.action_var = action_var def render(self, context): # Resolving variables passed by the", "Returns True iif the user have the specified permission over the model. For", "\"\"\" # Separating the tag name from the parameters try: tag, model, action", "current = token.contents states[current.split()[0]] = parser.parse(default_states + [end_tag]) token = parser.next_token() model_var =", "the parameters try: tag, model, action = token.contents.split() except (ValueError, TypeError): raise template.TemplateSyntaxError(", "variables passed by the user model = self.model_var.resolve(context) action = self.action_var.resolve(context) # Check", "endif %} \"\"\" user = context['request'].user if isinstance(model, str): app_label, model_name = model.split('.')", "% tag) default_states = ['ifhasperm', 'else'] end_tag = 'endifhasperm' # Place to store", "def model_verbose_name(model): \"\"\" Sample usage: {{model|model_name}} \"\"\" return model._meta.verbose_name @register.filter def model_verbose_name_plural(model): \"\"\"", "object). Sample usage: {% ifhasperm model 'add' %} <div style=\"color: #090\">User can add", "formatted as \"app_label.model_name\". Sample usage: {% testhasperm model 'view' as can_view_objects %} {%", "'%s.%s_%s' % (app_label, action, model_name) return user.is_authenticated and user.has_perm(required_permission) @register.tag def ifhasperm(parser, token):", "################################################################################ # Support for generic editing in the front-end @register.filter def model_verbose_name(model): \"\"\"", "{% else %} <div style=\"color: #900\">User cannot add objects</div> {% endifhasperm %} \"\"\"", "model_name) return user.is_authenticated and user.has_perm(required_permission) @register.tag def ifhasperm(parser, token): \"\"\" Check user permission", "= model_var self.action_var = action_var def render(self, context): # Resolving variables passed by", "= parser.parse(default_states + [end_tag]) token = parser.next_token() model_var = parser.compile_filter(model) action_var = parser.compile_filter(action)", "isinstance(model, str): app_label, model_name = model.split('.') else: app_label = model._meta.app_label model_name = model._meta.model_name", "\"\"\" user = context['request'].user if isinstance(model, str): app_label, model_name = model.split('.') else: app_label", "user.has_perm(required_permission) @register.tag def ifhasperm(parser, token): \"\"\" Check user permission over specified model. (You", "add objects</div> {% else %} <div style=\"color: #900\">User cannot add objects</div> {% endifhasperm", "self.action_var = action_var def render(self, context): # Resolving variables passed by the user", "the user model = self.model_var.resolve(context) action = self.action_var.resolve(context) # Check user permission if", "states self.model_var = model_var self.action_var = action_var def render(self, context): # Resolving variables", "usage: {{model|model_name}} \"\"\" return model._meta.verbose_name @register.filter def model_verbose_name_plural(model): \"\"\" Sample usage: {{model|model_name}} \"\"\"", "{% ifhasperm model 'add' %} <div style=\"color: #090\">User can add objects</div> {% else", "\"\"\" Returns True iif the user have the specified permission over the model.", "can specify either a model or an object). Sample usage: {% ifhasperm model", "{% if not can_view_objects %} <h2>Sorry, you have no permission to view these", "usage: {% ifhasperm model 'add' %} <div style=\"color: #090\">User can add objects</div> {%", "model 'view' as can_view_objects %} {% if not can_view_objects %} <h2>Sorry, you have", "else: app_label = model._meta.app_label model_name = model._meta.model_name required_permission = '%s.%s_%s' % (app_label, action,", "(app_label, action, model_name) return user.is_authenticated and user.has_perm(required_permission) @register.tag def ifhasperm(parser, token): \"\"\" Check", "template register = template.Library() ################################################################################ # Support for generic editing in the front-end", "if not can_view_objects %} <h2>Sorry, you have no permission to view these objects</h2>", "#090\">User can add objects</div> {% else %} <div style=\"color: #900\">User cannot add objects</div>", "tag) default_states = ['ifhasperm', 'else'] end_tag = 'endifhasperm' # Place to store the", "except (ValueError, TypeError): raise template.TemplateSyntaxError( \"'%s' tag takes three parameters\" % tag) default_states", "class, or a string formatted as \"app_label.model_name\". Sample usage: {% testhasperm model 'view'", "parameters try: tag, model, action = token.contents.split() except (ValueError, TypeError): raise template.TemplateSyntaxError( \"'%s'", "no permission to view these objects</h2> {% endif %} \"\"\" user = context['request'].user", "def ifhasperm(parser, token): \"\"\" Check user permission over specified model. (You can specify", "view these objects</h2> {% endif %} \"\"\" user = context['request'].user if isinstance(model, str):", "@register.simple_tag(takes_context=True) def testhasperm(context, model, action): \"\"\" Returns True iif the user have the", "{{model|model_name}} \"\"\" return model._meta.model_name @register.filter def app_label(model): \"\"\" Sample usage: {{model|app_label}} \"\"\" return", "model._meta.model_name @register.filter def app_label(model): \"\"\" Sample usage: {{model|app_label}} \"\"\" return model._meta.app_label @register.simple_tag(takes_context=True) def", "return CheckPermNode(states, model_var, action_var) class CheckPermNode(template.Node): def __init__(self, states, model_var, action_var): self.states =", "action = self.action_var.resolve(context) # Check user permission if testhasperm(context, model, action): html =", "= 'endifhasperm' # Place to store the states and their values states =", "add objects</div> {% endifhasperm %} \"\"\" # Separating the tag name from the", "model, action): html = self.states['ifhasperm'].render(context) else: html = self.states['else'].render(context) if 'else' in self.states", "= ['ifhasperm', 'else'] end_tag = 'endifhasperm' # Place to store the states and", "@register.filter def model_verbose_name(model): \"\"\" Sample usage: {{model|model_name}} \"\"\" return model._meta.verbose_name @register.filter def model_verbose_name_plural(model):", "parameters\" % tag) default_states = ['ifhasperm', 'else'] end_tag = 'endifhasperm' # Place to", "# Check user permission if testhasperm(context, model, action): html = self.states['ifhasperm'].render(context) else: html", "ifhasperm model 'add' %} <div style=\"color: #090\">User can add objects</div> {% else %}", "# Resolving variables passed by the user model = self.model_var.resolve(context) action = self.action_var.resolve(context)", "= self.action_var.resolve(context) # Check user permission if testhasperm(context, model, action): html = self.states['ifhasperm'].render(context)", "tag name from the parameters try: tag, model, action = token.contents.split() except (ValueError,", "Let's iterate over our context and find our tokens while token.contents != end_tag:", "return model._meta.verbose_name @register.filter def model_verbose_name_plural(model): \"\"\" Sample usage: {{model|model_name}} \"\"\" return model._meta.verbose_name_plural @register.filter", "def model_verbose_name_plural(model): \"\"\" Sample usage: {{model|model_name}} \"\"\" return model._meta.verbose_name_plural @register.filter def model_name(model): \"\"\"", "as \"app_label.model_name\". Sample usage: {% testhasperm model 'view' as can_view_objects %} {% if", "model, action = token.contents.split() except (ValueError, TypeError): raise template.TemplateSyntaxError( \"'%s' tag takes three", "states and their values states = {} # Let's iterate over our context", "Place to store the states and their values states = {} # Let's", "accept either a Model class, or a string formatted as \"app_label.model_name\". Sample usage:", "cannot add objects</div> {% endifhasperm %} \"\"\" # Separating the tag name from", "either a model or an object). Sample usage: {% ifhasperm model 'add' %}", "'view' as can_view_objects %} {% if not can_view_objects %} <h2>Sorry, you have no", "= {} # Let's iterate over our context and find our tokens while", "#900\">User cannot add objects</div> {% endifhasperm %} \"\"\" # Separating the tag name", "or an object). Sample usage: {% ifhasperm model 'add' %} <div style=\"color: #090\">User", "either a Model class, or a string formatted as \"app_label.model_name\". Sample usage: {%", "Sample usage: {{model|model_name}} \"\"\" return model._meta.model_name @register.filter def app_label(model): \"\"\" Sample usage: {{model|app_label}}", "user.is_authenticated and user.has_perm(required_permission) @register.tag def ifhasperm(parser, token): \"\"\" Check user permission over specified", "iterate over our context and find our tokens while token.contents != end_tag: current", "to view these objects</h2> {% endif %} \"\"\" user = context['request'].user if isinstance(model,", "parser.parse(default_states + [end_tag]) token = parser.next_token() model_var = parser.compile_filter(model) action_var = parser.compile_filter(action) return", "For 'model', we accept either a Model class, or a string formatted as", "context and find our tokens while token.contents != end_tag: current = token.contents states[current.split()[0]]", "django import template register = template.Library() ################################################################################ # Support for generic editing in", "\"\"\" return model._meta.verbose_name @register.filter def model_verbose_name_plural(model): \"\"\" Sample usage: {{model|model_name}} \"\"\" return model._meta.verbose_name_plural", "if testhasperm(context, model, action): html = self.states['ifhasperm'].render(context) else: html = self.states['else'].render(context) if 'else'", "objects</h2> {% endif %} \"\"\" user = context['request'].user if isinstance(model, str): app_label, model_name", "model_name = model.split('.') else: app_label = model._meta.app_label model_name = model._meta.model_name required_permission = '%s.%s_%s'", "%} <h2>Sorry, you have no permission to view these objects</h2> {% endif %}", "= model._meta.model_name required_permission = '%s.%s_%s' % (app_label, action, model_name) return user.is_authenticated and user.has_perm(required_permission)", "from the parameters try: tag, model, action = token.contents.split() except (ValueError, TypeError): raise", "Check user permission over specified model. (You can specify either a model or", "can_view_objects %} <h2>Sorry, you have no permission to view these objects</h2> {% endif", "'model', we accept either a Model class, or a string formatted as \"app_label.model_name\".", "self.action_var.resolve(context) # Check user permission if testhasperm(context, model, action): html = self.states['ifhasperm'].render(context) else:", "model, action): \"\"\" Returns True iif the user have the specified permission over", "app_label = model._meta.app_label model_name = model._meta.model_name required_permission = '%s.%s_%s' % (app_label, action, model_name)", "if isinstance(model, str): app_label, model_name = model.split('.') else: app_label = model._meta.app_label model_name =", "= parser.next_token() model_var = parser.compile_filter(model) action_var = parser.compile_filter(action) return CheckPermNode(states, model_var, action_var) class", "model_var, action_var) class CheckPermNode(template.Node): def __init__(self, states, model_var, action_var): self.states = states self.model_var", "the front-end @register.filter def model_verbose_name(model): \"\"\" Sample usage: {{model|model_name}} \"\"\" return model._meta.verbose_name @register.filter", "token = parser.next_token() model_var = parser.compile_filter(model) action_var = parser.compile_filter(action) return CheckPermNode(states, model_var, action_var)", "Sample usage: {% ifhasperm model 'add' %} <div style=\"color: #090\">User can add objects</div>", "style=\"color: #090\">User can add objects</div> {% else %} <div style=\"color: #900\">User cannot add", "specified model. (You can specify either a model or an object). Sample usage:", "Sample usage: {{model|model_name}} \"\"\" return model._meta.verbose_name_plural @register.filter def model_name(model): \"\"\" Sample usage: {{model|model_name}}", "# Place to store the states and their values states = {} #", "parser.compile_filter(model) action_var = parser.compile_filter(action) return CheckPermNode(states, model_var, action_var) class CheckPermNode(template.Node): def __init__(self, states,", "the specified permission over the model. For 'model', we accept either a Model", "you have no permission to view these objects</h2> {% endif %} \"\"\" user", "action_var) class CheckPermNode(template.Node): def __init__(self, states, model_var, action_var): self.states = states self.model_var =", "a Model class, or a string formatted as \"app_label.model_name\". Sample usage: {% testhasperm", "states = {} # Let's iterate over our context and find our tokens", "generic editing in the front-end @register.filter def model_verbose_name(model): \"\"\" Sample usage: {{model|model_name}} \"\"\"", "a model or an object). Sample usage: {% ifhasperm model 'add' %} <div", "a string formatted as \"app_label.model_name\". Sample usage: {% testhasperm model 'view' as can_view_objects", "states, model_var, action_var): self.states = states self.model_var = model_var self.action_var = action_var def", "render(self, context): # Resolving variables passed by the user model = self.model_var.resolve(context) action", "= token.contents.split() except (ValueError, TypeError): raise template.TemplateSyntaxError( \"'%s' tag takes three parameters\" %", "specify either a model or an object). Sample usage: {% ifhasperm model 'add'", "model_var, action_var): self.states = states self.model_var = model_var self.action_var = action_var def render(self,", "these objects</h2> {% endif %} \"\"\" user = context['request'].user if isinstance(model, str): app_label,", "iif the user have the specified permission over the model. For 'model', we", "return model._meta.model_name @register.filter def app_label(model): \"\"\" Sample usage: {{model|app_label}} \"\"\" return model._meta.app_label @register.simple_tag(takes_context=True)", "= '%s.%s_%s' % (app_label, action, model_name) return user.is_authenticated and user.has_perm(required_permission) @register.tag def ifhasperm(parser,", "{% endifhasperm %} \"\"\" # Separating the tag name from the parameters try:", "TypeError): raise template.TemplateSyntaxError( \"'%s' tag takes three parameters\" % tag) default_states = ['ifhasperm',", "in the front-end @register.filter def model_verbose_name(model): \"\"\" Sample usage: {{model|model_name}} \"\"\" return model._meta.verbose_name", "= template.Library() ################################################################################ # Support for generic editing in the front-end @register.filter def", "model = self.model_var.resolve(context) action = self.action_var.resolve(context) # Check user permission if testhasperm(context, model,", "can add objects</div> {% else %} <div style=\"color: #900\">User cannot add objects</div> {%", "token): \"\"\" Check user permission over specified model. (You can specify either a", "style=\"color: #900\">User cannot add objects</div> {% endifhasperm %} \"\"\" # Separating the tag", "'else'] end_tag = 'endifhasperm' # Place to store the states and their values", "!= end_tag: current = token.contents states[current.split()[0]] = parser.parse(default_states + [end_tag]) token = parser.next_token()", "\"\"\" return model._meta.verbose_name_plural @register.filter def model_name(model): \"\"\" Sample usage: {{model|model_name}} \"\"\" return model._meta.model_name", "can_view_objects %} {% if not can_view_objects %} <h2>Sorry, you have no permission to", "= states self.model_var = model_var self.action_var = action_var def render(self, context): # Resolving", "= token.contents states[current.split()[0]] = parser.parse(default_states + [end_tag]) token = parser.next_token() model_var = parser.compile_filter(model)", "Check user permission if testhasperm(context, model, action): html = self.states['ifhasperm'].render(context) else: html =", "three parameters\" % tag) default_states = ['ifhasperm', 'else'] end_tag = 'endifhasperm' # Place", "objects</div> {% else %} <div style=\"color: #900\">User cannot add objects</div> {% endifhasperm %}", "try: tag, model, action = token.contents.split() except (ValueError, TypeError): raise template.TemplateSyntaxError( \"'%s' tag", "model. (You can specify either a model or an object). Sample usage: {%", "model 'add' %} <div style=\"color: #090\">User can add objects</div> {% else %} <div", "= context['request'].user if isinstance(model, str): app_label, model_name = model.split('.') else: app_label = model._meta.app_label", "action_var = parser.compile_filter(action) return CheckPermNode(states, model_var, action_var) class CheckPermNode(template.Node): def __init__(self, states, model_var,", "<div style=\"color: #090\">User can add objects</div> {% else %} <div style=\"color: #900\">User cannot", "objects</div> {% endifhasperm %} \"\"\" # Separating the tag name from the parameters", "CheckPermNode(template.Node): def __init__(self, states, model_var, action_var): self.states = states self.model_var = model_var self.action_var", "not can_view_objects %} <h2>Sorry, you have no permission to view these objects</h2> {%", "<h2>Sorry, you have no permission to view these objects</h2> {% endif %} \"\"\"", "self.model_var.resolve(context) action = self.action_var.resolve(context) # Check user permission if testhasperm(context, model, action): html", "from django import template register = template.Library() ################################################################################ # Support for generic editing", "parser.compile_filter(action) return CheckPermNode(states, model_var, action_var) class CheckPermNode(template.Node): def __init__(self, states, model_var, action_var): self.states", "editing in the front-end @register.filter def model_verbose_name(model): \"\"\" Sample usage: {{model|model_name}} \"\"\" return", "default_states = ['ifhasperm', 'else'] end_tag = 'endifhasperm' # Place to store the states", "Separating the tag name from the parameters try: tag, model, action = token.contents.split()", "Support for generic editing in the front-end @register.filter def model_verbose_name(model): \"\"\" Sample usage:", "user permission over specified model. (You can specify either a model or an", "model_var = parser.compile_filter(model) action_var = parser.compile_filter(action) return CheckPermNode(states, model_var, action_var) class CheckPermNode(template.Node): def", "= parser.compile_filter(action) return CheckPermNode(states, model_var, action_var) class CheckPermNode(template.Node): def __init__(self, states, model_var, action_var):", "# Separating the tag name from the parameters try: tag, model, action =", "name from the parameters try: tag, model, action = token.contents.split() except (ValueError, TypeError):", "app_label(model): \"\"\" Sample usage: {{model|app_label}} \"\"\" return model._meta.app_label @register.simple_tag(takes_context=True) def testhasperm(context, model, action):", "over the model. For 'model', we accept either a Model class, or a", "parser.next_token() model_var = parser.compile_filter(model) action_var = parser.compile_filter(action) return CheckPermNode(states, model_var, action_var) class CheckPermNode(template.Node):", "and their values states = {} # Let's iterate over our context and", "tag, model, action = token.contents.split() except (ValueError, TypeError): raise template.TemplateSyntaxError( \"'%s' tag takes", "action = token.contents.split() except (ValueError, TypeError): raise template.TemplateSyntaxError( \"'%s' tag takes three parameters\"", "model._meta.app_label @register.simple_tag(takes_context=True) def testhasperm(context, model, action): \"\"\" Returns True iif the user have", "string formatted as \"app_label.model_name\". Sample usage: {% testhasperm model 'view' as can_view_objects %}", "model. For 'model', we accept either a Model class, or a string formatted", "'add' %} <div style=\"color: #090\">User can add objects</div> {% else %} <div style=\"color:", "\"\"\" Check user permission over specified model. (You can specify either a model", "ifhasperm(parser, token): \"\"\" Check user permission over specified model. (You can specify either", "<div style=\"color: #900\">User cannot add objects</div> {% endifhasperm %} \"\"\" # Separating the", "self.states = states self.model_var = model_var self.action_var = action_var def render(self, context): #", "permission to view these objects</h2> {% endif %} \"\"\" user = context['request'].user if", "end_tag: current = token.contents states[current.split()[0]] = parser.parse(default_states + [end_tag]) token = parser.next_token() model_var", "app_label, model_name = model.split('.') else: app_label = model._meta.app_label model_name = model._meta.model_name required_permission =", "and find our tokens while token.contents != end_tag: current = token.contents states[current.split()[0]] =", "user = context['request'].user if isinstance(model, str): app_label, model_name = model.split('.') else: app_label =", "as can_view_objects %} {% if not can_view_objects %} <h2>Sorry, you have no permission", "specified permission over the model. For 'model', we accept either a Model class,", "self.states['ifhasperm'].render(context) else: html = self.states['else'].render(context) if 'else' in self.states else '' return html", "have the specified permission over the model. For 'model', we accept either a", "context): # Resolving variables passed by the user model = self.model_var.resolve(context) action =", "testhasperm(context, model, action): \"\"\" Returns True iif the user have the specified permission", "(You can specify either a model or an object). Sample usage: {% ifhasperm", "required_permission = '%s.%s_%s' % (app_label, action, model_name) return user.is_authenticated and user.has_perm(required_permission) @register.tag def", "%} <div style=\"color: #900\">User cannot add objects</div> {% endifhasperm %} \"\"\" # Separating", "\"\"\" Sample usage: {{model|model_name}} \"\"\" return model._meta.model_name @register.filter def app_label(model): \"\"\" Sample usage:", "return model._meta.verbose_name_plural @register.filter def model_name(model): \"\"\" Sample usage: {{model|model_name}} \"\"\" return model._meta.model_name @register.filter", "@register.filter def model_name(model): \"\"\" Sample usage: {{model|model_name}} \"\"\" return model._meta.model_name @register.filter def app_label(model):", "states[current.split()[0]] = parser.parse(default_states + [end_tag]) token = parser.next_token() model_var = parser.compile_filter(model) action_var =", "usage: {{model|app_label}} \"\"\" return model._meta.app_label @register.simple_tag(takes_context=True) def testhasperm(context, model, action): \"\"\" Returns True", "@register.tag def ifhasperm(parser, token): \"\"\" Check user permission over specified model. (You can", "model._meta.model_name required_permission = '%s.%s_%s' % (app_label, action, model_name) return user.is_authenticated and user.has_perm(required_permission) @register.tag", "# Support for generic editing in the front-end @register.filter def model_verbose_name(model): \"\"\" Sample", "model_name = model._meta.model_name required_permission = '%s.%s_%s' % (app_label, action, model_name) return user.is_authenticated and", "%} \"\"\" user = context['request'].user if isinstance(model, str): app_label, model_name = model.split('.') else:", "endifhasperm %} \"\"\" # Separating the tag name from the parameters try: tag,", "context['request'].user if isinstance(model, str): app_label, model_name = model.split('.') else: app_label = model._meta.app_label model_name", "Sample usage: {{model|app_label}} \"\"\" return model._meta.app_label @register.simple_tag(takes_context=True) def testhasperm(context, model, action): \"\"\" Returns", "<gh_stars>100-1000 from django import template register = template.Library() ################################################################################ # Support for generic", "end_tag = 'endifhasperm' # Place to store the states and their values states", "__init__(self, states, model_var, action_var): self.states = states self.model_var = model_var self.action_var = action_var", "our context and find our tokens while token.contents != end_tag: current = token.contents", "= model.split('.') else: app_label = model._meta.app_label model_name = model._meta.model_name required_permission = '%s.%s_%s' %", "usage: {% testhasperm model 'view' as can_view_objects %} {% if not can_view_objects %}", "testhasperm(context, model, action): html = self.states['ifhasperm'].render(context) else: html = self.states['else'].render(context) if 'else' in", "usage: {{model|model_name}} \"\"\" return model._meta.verbose_name_plural @register.filter def model_name(model): \"\"\" Sample usage: {{model|model_name}} \"\"\"", "action): html = self.states['ifhasperm'].render(context) else: html = self.states['else'].render(context) if 'else' in self.states else", "= parser.compile_filter(model) action_var = parser.compile_filter(action) return CheckPermNode(states, model_var, action_var) class CheckPermNode(template.Node): def __init__(self,", "\"\"\" Sample usage: {{model|app_label}} \"\"\" return model._meta.app_label @register.simple_tag(takes_context=True) def testhasperm(context, model, action): \"\"\"", "True iif the user have the specified permission over the model. For 'model',", "permission over the model. For 'model', we accept either a Model class, or", "user model = self.model_var.resolve(context) action = self.action_var.resolve(context) # Check user permission if testhasperm(context," ]
[ "z.namelist(): yield (name, z.read(name).decode(encoding)) def update_zip(original_zip, updated_zip, replacements, encoding='utf-8', verbose=False): with ZipFile(updated_zip, 'w',", "'w', compression=ZIP_DEFLATED) as z: for name, content in zip_read(original_zip, encoding=encoding): updated_content = replace(content,", "import ndiff from sys import argv from zipfile import ZipFile, ZIP_DEFLATED def diff(name,", "def update_zip(original_zip, updated_zip, replacements, encoding='utf-8', verbose=False): with ZipFile(updated_zip, 'w', compression=ZIP_DEFLATED) as z: for", "new) return updated_content def zip_read(zip_file, encoding='utf-8'): with ZipFile(zip_file, 'r') as z: for name", "parser.add_argument('original_zip', help='original zip path') parser.add_argument('updated_zip', help='updated zip path') parser.add_argument( 'replacements', nargs='+', help='A list", "as z: for name, content in zip_read(original_zip, encoding=encoding): updated_content = replace(content, replacements) if", "updated_zip, replacements, encoding='utf-8', verbose=False): # make a dict of replacements list d =", "updated_content def zip_read(zip_file, encoding='utf-8'): with ZipFile(zip_file, 'r') as z: for name in z.namelist():", "argparse import ArgumentParser from difflib import ndiff from sys import argv from zipfile", "def parse_args(args): parser = ArgumentParser(description='Replace in zip (e.g. zip, jar or war') parser.add_argument('original_zip',", "z.read(name).decode(encoding)) def update_zip(original_zip, updated_zip, replacements, encoding='utf-8', verbose=False): with ZipFile(updated_zip, 'w', compression=ZIP_DEFLATED) as z:", "a dict of replacements list d = dict(zip(replacements[::2], replacements[1::2])) update_zip(original_zip, updated_zip, d, encoding,", "e.g organisation/project') parser.add_argument( '-v', '--verbose', action='store_true', help='Verbose output') return parser.parse_args(args) if __name__ ==", "in zip (e.g. zip, jar or war') parser.add_argument('original_zip', help='original zip path') parser.add_argument('updated_zip', help='updated", "updated_content.replace(old, new) return updated_content def zip_read(zip_file, encoding='utf-8'): with ZipFile(zip_file, 'r') as z: for", "'--verbose', action='store_true', help='Verbose output') return parser.parse_args(args) if __name__ == '__main__': \"\"\" Example: ./replace_in_zip.py", "dict of replacements list d = dict(zip(replacements[::2], replacements[1::2])) update_zip(original_zip, updated_zip, d, encoding, verbose)", "war') parser.add_argument('original_zip', help='original zip path') parser.add_argument('updated_zip', help='updated zip path') parser.add_argument( 'replacements', nargs='+', help='A", "from sys import argv from zipfile import ZipFile, ZIP_DEFLATED def diff(name, content, updated_content):", "replacements, encoding='utf-8', verbose=False): with ZipFile(updated_zip, 'w', compression=ZIP_DEFLATED) as z: for name, content in", "yield (name, z.read(name).decode(encoding)) def update_zip(original_zip, updated_zip, replacements, encoding='utf-8', verbose=False): with ZipFile(updated_zip, 'w', compression=ZIP_DEFLATED)", "from argparse import ArgumentParser from difflib import ndiff from sys import argv from", "parser.add_argument('updated_zip', help='updated zip path') parser.add_argument( 'replacements', nargs='+', help='A list of replacements to be", "and so on.' ) parser.add_argument( '-e', '--encoding', default='utf-8', help='TFS projects, e.g organisation/project') parser.add_argument(", "old, new in replacements.items(): updated_content = updated_content.replace(old, new) return updated_content def zip_read(zip_file, encoding='utf-8'):", "main(original_zip, updated_zip, replacements, encoding='utf-8', verbose=False): # make a dict of replacements list d", "from zipfile import ZipFile, ZIP_DEFLATED def diff(name, content, updated_content): diffs = list(ndiff(content.splitlines(1), updated_content.splitlines(1)))", "def diff(name, content, updated_content): diffs = list(ndiff(content.splitlines(1), updated_content.splitlines(1))) if diffs: print(f\"{name}\\n{''.join(diffs)}\") def replace(content,", "updated_zip, replacements, encoding='utf-8', verbose=False): with ZipFile(updated_zip, 'w', compression=ZIP_DEFLATED) as z: for name, content", "nargs='+', help='A list of replacements to be done in the zip. Index 0", "'-v', '--verbose', action='store_true', help='Verbose output') return parser.parse_args(args) if __name__ == '__main__': \"\"\" Example:", "Index 0 will be replaced with index 1 and so on.' ) parser.add_argument(", "of replacements list d = dict(zip(replacements[::2], replacements[1::2])) update_zip(original_zip, updated_zip, d, encoding, verbose) def", "from difflib import ndiff from sys import argv from zipfile import ZipFile, ZIP_DEFLATED", "content in zip_read(original_zip, encoding=encoding): updated_content = replace(content, replacements) if verbose: diff(name, content, updated_content)", "make a dict of replacements list d = dict(zip(replacements[::2], replacements[1::2])) update_zip(original_zip, updated_zip, d,", "update_zip(original_zip, updated_zip, d, encoding, verbose) def parse_args(args): parser = ArgumentParser(description='Replace in zip (e.g.", "zip path') parser.add_argument( 'replacements', nargs='+', help='A list of replacements to be done in", "= dict(zip(replacements[::2], replacements[1::2])) update_zip(original_zip, updated_zip, d, encoding, verbose) def parse_args(args): parser = ArgumentParser(description='Replace", "index 1 and so on.' ) parser.add_argument( '-e', '--encoding', default='utf-8', help='TFS projects, e.g", "as z: for name in z.namelist(): yield (name, z.read(name).decode(encoding)) def update_zip(original_zip, updated_zip, replacements,", "update_zip(original_zip, updated_zip, replacements, encoding='utf-8', verbose=False): with ZipFile(updated_zip, 'w', compression=ZIP_DEFLATED) as z: for name,", "= content for old, new in replacements.items(): updated_content = updated_content.replace(old, new) return updated_content", "ZipFile, ZIP_DEFLATED def diff(name, content, updated_content): diffs = list(ndiff(content.splitlines(1), updated_content.splitlines(1))) if diffs: print(f\"{name}\\n{''.join(diffs)}\")", "replaced with index 1 and so on.' ) parser.add_argument( '-e', '--encoding', default='utf-8', help='TFS", "replacements, encoding='utf-8', verbose=False): # make a dict of replacements list d = dict(zip(replacements[::2],", "parser.parse_args(args) if __name__ == '__main__': \"\"\" Example: ./replace_in_zip.py original.zip updated.zip old1 new1 old2", "updated_zip, d, encoding, verbose) def parse_args(args): parser = ArgumentParser(description='Replace in zip (e.g. zip,", "difflib import ndiff from sys import argv from zipfile import ZipFile, ZIP_DEFLATED def", "replacements list d = dict(zip(replacements[::2], replacements[1::2])) update_zip(original_zip, updated_zip, d, encoding, verbose) def parse_args(args):", "1 and so on.' ) parser.add_argument( '-e', '--encoding', default='utf-8', help='TFS projects, e.g organisation/project')", "replacements): updated_content = content for old, new in replacements.items(): updated_content = updated_content.replace(old, new)", "or war') parser.add_argument('original_zip', help='original zip path') parser.add_argument('updated_zip', help='updated zip path') parser.add_argument( 'replacements', nargs='+',", "name, content in zip_read(original_zip, encoding=encoding): updated_content = replace(content, replacements) if verbose: diff(name, content,", "list of replacements to be done in the zip. Index 0 will be", "the zip. Index 0 will be replaced with index 1 and so on.'", "verbose=False): # make a dict of replacements list d = dict(zip(replacements[::2], replacements[1::2])) update_zip(original_zip,", "parse_args(args): parser = ArgumentParser(description='Replace in zip (e.g. zip, jar or war') parser.add_argument('original_zip', help='original", "for name, content in zip_read(original_zip, encoding=encoding): updated_content = replace(content, replacements) if verbose: diff(name,", "return updated_content def zip_read(zip_file, encoding='utf-8'): with ZipFile(zip_file, 'r') as z: for name in", "\"\"\" Example: ./replace_in_zip.py original.zip updated.zip old1 new1 old2 new2 oldN newN \"\"\" main(**parse_args(argv[1:]).__dict__)", "updated_content = updated_content.replace(old, new) return updated_content def zip_read(zip_file, encoding='utf-8'): with ZipFile(zip_file, 'r') as", "z: for name in z.namelist(): yield (name, z.read(name).decode(encoding)) def update_zip(original_zip, updated_zip, replacements, encoding='utf-8',", "(name, z.read(name).decode(encoding)) def update_zip(original_zip, updated_zip, replacements, encoding='utf-8', verbose=False): with ZipFile(updated_zip, 'w', compression=ZIP_DEFLATED) as", "compression=ZIP_DEFLATED) as z: for name, content in zip_read(original_zip, encoding=encoding): updated_content = replace(content, replacements)", "if __name__ == '__main__': \"\"\" Example: ./replace_in_zip.py original.zip updated.zip old1 new1 old2 new2", "name in z.namelist(): yield (name, z.read(name).decode(encoding)) def update_zip(original_zip, updated_zip, replacements, encoding='utf-8', verbose=False): with", "d, encoding, verbose) def parse_args(args): parser = ArgumentParser(description='Replace in zip (e.g. zip, jar", "0 will be replaced with index 1 and so on.' ) parser.add_argument( '-e',", "verbose=False): with ZipFile(updated_zip, 'w', compression=ZIP_DEFLATED) as z: for name, content in zip_read(original_zip, encoding=encoding):", "help='original zip path') parser.add_argument('updated_zip', help='updated zip path') parser.add_argument( 'replacements', nargs='+', help='A list of", "zip (e.g. zip, jar or war') parser.add_argument('original_zip', help='original zip path') parser.add_argument('updated_zip', help='updated zip", "zip. Index 0 will be replaced with index 1 and so on.' )", "import ArgumentParser from difflib import ndiff from sys import argv from zipfile import", "ArgumentParser from difflib import ndiff from sys import argv from zipfile import ZipFile,", "diff(name, content, updated_content) z.writestr(name, updated_content) def main(original_zip, updated_zip, replacements, encoding='utf-8', verbose=False): # make", "with ZipFile(zip_file, 'r') as z: for name in z.namelist(): yield (name, z.read(name).decode(encoding)) def", "def replace(content, replacements): updated_content = content for old, new in replacements.items(): updated_content =", "will be replaced with index 1 and so on.' ) parser.add_argument( '-e', '--encoding',", "'__main__': \"\"\" Example: ./replace_in_zip.py original.zip updated.zip old1 new1 old2 new2 oldN newN \"\"\"", "updated_content.splitlines(1))) if diffs: print(f\"{name}\\n{''.join(diffs)}\") def replace(content, replacements): updated_content = content for old, new", "'r') as z: for name in z.namelist(): yield (name, z.read(name).decode(encoding)) def update_zip(original_zip, updated_zip,", "z: for name, content in zip_read(original_zip, encoding=encoding): updated_content = replace(content, replacements) if verbose:", "with ZipFile(updated_zip, 'w', compression=ZIP_DEFLATED) as z: for name, content in zip_read(original_zip, encoding=encoding): updated_content", "encoding='utf-8', verbose=False): with ZipFile(updated_zip, 'w', compression=ZIP_DEFLATED) as z: for name, content in zip_read(original_zip,", "print(f\"{name}\\n{''.join(diffs)}\") def replace(content, replacements): updated_content = content for old, new in replacements.items(): updated_content", "projects, e.g organisation/project') parser.add_argument( '-v', '--verbose', action='store_true', help='Verbose output') return parser.parse_args(args) if __name__", "done in the zip. Index 0 will be replaced with index 1 and", "= updated_content.replace(old, new) return updated_content def zip_read(zip_file, encoding='utf-8'): with ZipFile(zip_file, 'r') as z:", "updated_content) z.writestr(name, updated_content) def main(original_zip, updated_zip, replacements, encoding='utf-8', verbose=False): # make a dict", "be replaced with index 1 and so on.' ) parser.add_argument( '-e', '--encoding', default='utf-8',", "zip_read(original_zip, encoding=encoding): updated_content = replace(content, replacements) if verbose: diff(name, content, updated_content) z.writestr(name, updated_content)", "for name in z.namelist(): yield (name, z.read(name).decode(encoding)) def update_zip(original_zip, updated_zip, replacements, encoding='utf-8', verbose=False):", "jar or war') parser.add_argument('original_zip', help='original zip path') parser.add_argument('updated_zip', help='updated zip path') parser.add_argument( 'replacements',", "output') return parser.parse_args(args) if __name__ == '__main__': \"\"\" Example: ./replace_in_zip.py original.zip updated.zip old1", "verbose: diff(name, content, updated_content) z.writestr(name, updated_content) def main(original_zip, updated_zip, replacements, encoding='utf-8', verbose=False): #", "z.writestr(name, updated_content) def main(original_zip, updated_zip, replacements, encoding='utf-8', verbose=False): # make a dict of", "replacements to be done in the zip. Index 0 will be replaced with", "to be done in the zip. Index 0 will be replaced with index", "if diffs: print(f\"{name}\\n{''.join(diffs)}\") def replace(content, replacements): updated_content = content for old, new in", "encoding=encoding): updated_content = replace(content, replacements) if verbose: diff(name, content, updated_content) z.writestr(name, updated_content) def", "help='TFS projects, e.g organisation/project') parser.add_argument( '-v', '--verbose', action='store_true', help='Verbose output') return parser.parse_args(args) if", "#!/usr/bin/env python3 from argparse import ArgumentParser from difflib import ndiff from sys import", "__name__ == '__main__': \"\"\" Example: ./replace_in_zip.py original.zip updated.zip old1 new1 old2 new2 oldN", "content for old, new in replacements.items(): updated_content = updated_content.replace(old, new) return updated_content def", "in replacements.items(): updated_content = updated_content.replace(old, new) return updated_content def zip_read(zip_file, encoding='utf-8'): with ZipFile(zip_file,", "def zip_read(zip_file, encoding='utf-8'): with ZipFile(zip_file, 'r') as z: for name in z.namelist(): yield", "encoding='utf-8', verbose=False): # make a dict of replacements list d = dict(zip(replacements[::2], replacements[1::2]))", "import argv from zipfile import ZipFile, ZIP_DEFLATED def diff(name, content, updated_content): diffs =", "content, updated_content): diffs = list(ndiff(content.splitlines(1), updated_content.splitlines(1))) if diffs: print(f\"{name}\\n{''.join(diffs)}\") def replace(content, replacements): updated_content", "parser.add_argument( '-e', '--encoding', default='utf-8', help='TFS projects, e.g organisation/project') parser.add_argument( '-v', '--verbose', action='store_true', help='Verbose", "diffs = list(ndiff(content.splitlines(1), updated_content.splitlines(1))) if diffs: print(f\"{name}\\n{''.join(diffs)}\") def replace(content, replacements): updated_content = content", "on.' ) parser.add_argument( '-e', '--encoding', default='utf-8', help='TFS projects, e.g organisation/project') parser.add_argument( '-v', '--verbose',", "zipfile import ZipFile, ZIP_DEFLATED def diff(name, content, updated_content): diffs = list(ndiff(content.splitlines(1), updated_content.splitlines(1))) if", "of replacements to be done in the zip. Index 0 will be replaced", "list d = dict(zip(replacements[::2], replacements[1::2])) update_zip(original_zip, updated_zip, d, encoding, verbose) def parse_args(args): parser", "return parser.parse_args(args) if __name__ == '__main__': \"\"\" Example: ./replace_in_zip.py original.zip updated.zip old1 new1", "replace(content, replacements): updated_content = content for old, new in replacements.items(): updated_content = updated_content.replace(old,", "sys import argv from zipfile import ZipFile, ZIP_DEFLATED def diff(name, content, updated_content): diffs", "== '__main__': \"\"\" Example: ./replace_in_zip.py original.zip updated.zip old1 new1 old2 new2 oldN newN", "ZipFile(updated_zip, 'w', compression=ZIP_DEFLATED) as z: for name, content in zip_read(original_zip, encoding=encoding): updated_content =", "list(ndiff(content.splitlines(1), updated_content.splitlines(1))) if diffs: print(f\"{name}\\n{''.join(diffs)}\") def replace(content, replacements): updated_content = content for old,", "if verbose: diff(name, content, updated_content) z.writestr(name, updated_content) def main(original_zip, updated_zip, replacements, encoding='utf-8', verbose=False):", "updated_content) def main(original_zip, updated_zip, replacements, encoding='utf-8', verbose=False): # make a dict of replacements", "argv from zipfile import ZipFile, ZIP_DEFLATED def diff(name, content, updated_content): diffs = list(ndiff(content.splitlines(1),", "path') parser.add_argument('updated_zip', help='updated zip path') parser.add_argument( 'replacements', nargs='+', help='A list of replacements to", "import ZipFile, ZIP_DEFLATED def diff(name, content, updated_content): diffs = list(ndiff(content.splitlines(1), updated_content.splitlines(1))) if diffs:", "'-e', '--encoding', default='utf-8', help='TFS projects, e.g organisation/project') parser.add_argument( '-v', '--verbose', action='store_true', help='Verbose output')", "in the zip. Index 0 will be replaced with index 1 and so", "ZIP_DEFLATED def diff(name, content, updated_content): diffs = list(ndiff(content.splitlines(1), updated_content.splitlines(1))) if diffs: print(f\"{name}\\n{''.join(diffs)}\") def", "help='Verbose output') return parser.parse_args(args) if __name__ == '__main__': \"\"\" Example: ./replace_in_zip.py original.zip updated.zip", "encoding, verbose) def parse_args(args): parser = ArgumentParser(description='Replace in zip (e.g. zip, jar or", "be done in the zip. Index 0 will be replaced with index 1", "diffs: print(f\"{name}\\n{''.join(diffs)}\") def replace(content, replacements): updated_content = content for old, new in replacements.items():", "path') parser.add_argument( 'replacements', nargs='+', help='A list of replacements to be done in the", "<filename>vang/pio/replace_in_zip.py<gh_stars>1-10 #!/usr/bin/env python3 from argparse import ArgumentParser from difflib import ndiff from sys", "= replace(content, replacements) if verbose: diff(name, content, updated_content) z.writestr(name, updated_content) def main(original_zip, updated_zip,", "dict(zip(replacements[::2], replacements[1::2])) update_zip(original_zip, updated_zip, d, encoding, verbose) def parse_args(args): parser = ArgumentParser(description='Replace in", "ArgumentParser(description='Replace in zip (e.g. zip, jar or war') parser.add_argument('original_zip', help='original zip path') parser.add_argument('updated_zip',", "replacements.items(): updated_content = updated_content.replace(old, new) return updated_content def zip_read(zip_file, encoding='utf-8'): with ZipFile(zip_file, 'r')", "# make a dict of replacements list d = dict(zip(replacements[::2], replacements[1::2])) update_zip(original_zip, updated_zip,", "encoding='utf-8'): with ZipFile(zip_file, 'r') as z: for name in z.namelist(): yield (name, z.read(name).decode(encoding))", "organisation/project') parser.add_argument( '-v', '--verbose', action='store_true', help='Verbose output') return parser.parse_args(args) if __name__ == '__main__':", "help='A list of replacements to be done in the zip. Index 0 will", "replace(content, replacements) if verbose: diff(name, content, updated_content) z.writestr(name, updated_content) def main(original_zip, updated_zip, replacements,", "= list(ndiff(content.splitlines(1), updated_content.splitlines(1))) if diffs: print(f\"{name}\\n{''.join(diffs)}\") def replace(content, replacements): updated_content = content for", "d = dict(zip(replacements[::2], replacements[1::2])) update_zip(original_zip, updated_zip, d, encoding, verbose) def parse_args(args): parser =", "updated_content): diffs = list(ndiff(content.splitlines(1), updated_content.splitlines(1))) if diffs: print(f\"{name}\\n{''.join(diffs)}\") def replace(content, replacements): updated_content =", "zip_read(zip_file, encoding='utf-8'): with ZipFile(zip_file, 'r') as z: for name in z.namelist(): yield (name,", "python3 from argparse import ArgumentParser from difflib import ndiff from sys import argv", "replacements[1::2])) update_zip(original_zip, updated_zip, d, encoding, verbose) def parse_args(args): parser = ArgumentParser(description='Replace in zip", "zip, jar or war') parser.add_argument('original_zip', help='original zip path') parser.add_argument('updated_zip', help='updated zip path') parser.add_argument(", "parser.add_argument( 'replacements', nargs='+', help='A list of replacements to be done in the zip.", "'--encoding', default='utf-8', help='TFS projects, e.g organisation/project') parser.add_argument( '-v', '--verbose', action='store_true', help='Verbose output') return", "with index 1 and so on.' ) parser.add_argument( '-e', '--encoding', default='utf-8', help='TFS projects,", "in zip_read(original_zip, encoding=encoding): updated_content = replace(content, replacements) if verbose: diff(name, content, updated_content) z.writestr(name,", "for old, new in replacements.items(): updated_content = updated_content.replace(old, new) return updated_content def zip_read(zip_file,", "updated_content = replace(content, replacements) if verbose: diff(name, content, updated_content) z.writestr(name, updated_content) def main(original_zip,", "updated_content = content for old, new in replacements.items(): updated_content = updated_content.replace(old, new) return", "default='utf-8', help='TFS projects, e.g organisation/project') parser.add_argument( '-v', '--verbose', action='store_true', help='Verbose output') return parser.parse_args(args)", "verbose) def parse_args(args): parser = ArgumentParser(description='Replace in zip (e.g. zip, jar or war')", "action='store_true', help='Verbose output') return parser.parse_args(args) if __name__ == '__main__': \"\"\" Example: ./replace_in_zip.py original.zip", "= ArgumentParser(description='Replace in zip (e.g. zip, jar or war') parser.add_argument('original_zip', help='original zip path')", "'replacements', nargs='+', help='A list of replacements to be done in the zip. Index", "help='updated zip path') parser.add_argument( 'replacements', nargs='+', help='A list of replacements to be done", "(e.g. zip, jar or war') parser.add_argument('original_zip', help='original zip path') parser.add_argument('updated_zip', help='updated zip path')", "replacements) if verbose: diff(name, content, updated_content) z.writestr(name, updated_content) def main(original_zip, updated_zip, replacements, encoding='utf-8',", "zip path') parser.add_argument('updated_zip', help='updated zip path') parser.add_argument( 'replacements', nargs='+', help='A list of replacements", "parser.add_argument( '-v', '--verbose', action='store_true', help='Verbose output') return parser.parse_args(args) if __name__ == '__main__': \"\"\"", "ndiff from sys import argv from zipfile import ZipFile, ZIP_DEFLATED def diff(name, content,", "ZipFile(zip_file, 'r') as z: for name in z.namelist(): yield (name, z.read(name).decode(encoding)) def update_zip(original_zip,", "def main(original_zip, updated_zip, replacements, encoding='utf-8', verbose=False): # make a dict of replacements list", "parser = ArgumentParser(description='Replace in zip (e.g. zip, jar or war') parser.add_argument('original_zip', help='original zip", "so on.' ) parser.add_argument( '-e', '--encoding', default='utf-8', help='TFS projects, e.g organisation/project') parser.add_argument( '-v',", "in z.namelist(): yield (name, z.read(name).decode(encoding)) def update_zip(original_zip, updated_zip, replacements, encoding='utf-8', verbose=False): with ZipFile(updated_zip,", "content, updated_content) z.writestr(name, updated_content) def main(original_zip, updated_zip, replacements, encoding='utf-8', verbose=False): # make a", "diff(name, content, updated_content): diffs = list(ndiff(content.splitlines(1), updated_content.splitlines(1))) if diffs: print(f\"{name}\\n{''.join(diffs)}\") def replace(content, replacements):", ") parser.add_argument( '-e', '--encoding', default='utf-8', help='TFS projects, e.g organisation/project') parser.add_argument( '-v', '--verbose', action='store_true',", "new in replacements.items(): updated_content = updated_content.replace(old, new) return updated_content def zip_read(zip_file, encoding='utf-8'): with" ]
[ "self.shortest_paths and isinstance(self.shortest_paths[source_id], dict): if target_id in self.shortest_paths[source_id]: return self.shortest_paths[source_id][target_id] return None def", "else: q.append(x) while len(q): u = None if self.use_priority_queue: u = q.pop_smallest() else:", "not self.num_threads: for source_id in self.nodes: self.calculate_shortest_paths_from(source_id) else: th = [] for source_id", "= None min_node_id = None for ind, x in enumerate(q): if distance[x] <", "self.num_threads: while len(th): _t = th.pop() _t.join() if len(th): while len(th): _t =", "source_id in self.nodes: t = threading.Thread(target=self.calculate_shortest_paths_from, args=[source_id]) t.start() th.append(t) if len(th) >= self.num_threads:", "{} previous = {} q = None if self.use_priority_queue: q = PriorityDict() else:", "isinstance(self.edges[u], dict): for v in self.edges[u]: if v in q: alt = distance[u]", "if self.use_priority_queue: q[v] = distance[v] if not self.num_threads: self.shortest_paths[source_id] = distance self.shortest_paths_guide[source_id] =", "4, 0.1) G.add_edge(2, 4, 0.5) print \"Calculating all possible shortest paths\" G.calculate_all_shortest_paths() print", "and isinstance(self.shortest_paths[source_id], dict): if target_id in self.shortest_paths[source_id]: return self.shortest_paths[source_id][target_id] return None def get_shortest_route(self,", "= distance self.shortest_paths_guide[source_id] = previous self.lock.release() return def calculate_all_shortest_paths(self): if not self.num_threads: for", "th = [] for source_id in self.nodes: t = threading.Thread(target=self.calculate_shortest_paths_from, args=[source_id]) t.start() th.append(t)", "self.lock = threading.Lock() self.use_priority_queue = use_priority_queue return def get_node_with_minimum_distance(self, q, distance, indices): min_dist", "distance[v] if not self.num_threads: self.shortest_paths[source_id] = distance self.shortest_paths_guide[source_id] = previous else: self.lock.acquire() self.shortest_paths[source_id]", "3, 0.3) G.add_edge(2, 3, 0.1) G.add_edge(3, 4, 0.1) G.add_edge(2, 4, 0.5) print \"Calculating", "_t = th.pop() _t.join() if len(th): while len(th): _t = th.pop() _t.join() return", "for ind, x in enumerate(q): if distance[x] < min_dist: min_ind = ind min_node_id", "min_node_id = x min_dist = distance[x] indices.append(min_ind) return min_node_id def calculate_shortest_paths_from(self, source_id): distance", "_t.join() if len(th): while len(th): _t = th.pop() _t.join() return def get_shortest_path_length(self, source_id,", "distance, ind) index = ind.pop() if type(index) is int: del q[index] else: break", "self.get_shortest_route(source_id, self.shortest_paths_guide[source_id][target_id], 0) r.append(self.shortest_paths_guide[source_id][target_id]) if append_target: r.append(target_id) return r return [] \"\"\" G", "get_node_with_minimum_distance(self, q, distance, indices): min_dist = float(\"inf\") min_ind = None min_node_id = None", "target_id in self.shortest_paths_guide[source_id]: r = [] if self.shortest_paths_guide[source_id][target_id] is not source_id: r =", "target_id): if source_id in self.shortest_paths and isinstance(self.shortest_paths[source_id], dict): if target_id in self.shortest_paths[source_id]: return", "in self.shortest_paths_guide and isinstance(self.shortest_paths_guide[source_id], dict): if target_id in self.shortest_paths_guide[source_id]: r = [] if", "None def get_shortest_route(self, source_id, target_id, append_target=1): if source_id in self.shortest_paths_guide and isinstance(self.shortest_paths_guide[source_id], dict):", "self.calculate_shortest_paths_from(source_id) else: th = [] for source_id in self.nodes: t = threading.Thread(target=self.calculate_shortest_paths_from, args=[source_id])", "min_ind = None min_node_id = None for ind, x in enumerate(q): if distance[x]", "th.pop() _t.join() return def get_shortest_path_length(self, source_id, target_id): if source_id in self.shortest_paths and isinstance(self.shortest_paths[source_id],", "q = PriorityDict() else: q = [] ind = [] distance[source_id] = 0", "th.append(t) if len(th) >= self.num_threads: while len(th): _t = th.pop() _t.join() if len(th):", "None min_node_id = None for ind, x in enumerate(q): if distance[x] < min_dist:", "q[index] else: break if isinstance(self.edges[u], dict): for v in self.edges[u]: if v in", "return r return [] \"\"\" G = Dijkstra(10, 1) G.add_edge(1, 2, 0.1) G.add_edge(1,", "distance = {} previous = {} q = None if self.use_priority_queue: q =", "in self.edges[u]: if v in q: alt = distance[u] + self.edges[u][v].strength if alt", "not self.num_threads: self.shortest_paths[source_id] = distance self.shortest_paths_guide[source_id] = previous else: self.lock.acquire() self.shortest_paths[source_id] = distance", "if distance[x] < min_dist: min_ind = ind min_node_id = x min_dist = distance[x]", "graph import Graph import threading from prioritydict import PriorityDict class Dijkstra(Graph): def __init__(self,", "G.add_edge(2, 3, 0.1) G.add_edge(3, 4, 0.1) G.add_edge(2, 4, 0.5) print \"Calculating all possible", "min_dist = distance[x] indices.append(min_ind) return min_node_id def calculate_shortest_paths_from(self, source_id): distance = {} previous", "G.add_edge(1, 2, 0.1) G.add_edge(1, 3, 0.3) G.add_edge(2, 3, 0.1) G.add_edge(3, 4, 0.1) G.add_edge(2,", "distance self.shortest_paths_guide[source_id] = previous self.lock.release() return def calculate_all_shortest_paths(self): if not self.num_threads: for source_id", "= u if self.use_priority_queue: q[v] = distance[v] if not self.num_threads: self.shortest_paths[source_id] = distance", "2, 0.1) G.add_edge(1, 3, 0.3) G.add_edge(2, 3, 0.1) G.add_edge(3, 4, 0.1) G.add_edge(2, 4,", "= {} q = None if self.use_priority_queue: q = PriorityDict() else: q =", "in q: alt = distance[u] + self.edges[u][v].strength if alt < distance[v]: distance[v] =", "if type(index) is int: del q[index] else: break if isinstance(self.edges[u], dict): for v", "import PriorityDict class Dijkstra(Graph): def __init__(self, num_threads=0, use_priority_queue=1): super(Dijkstra, self).__init__() self.shortest_paths = {}", "for v in self.edges[u]: if v in q: alt = distance[u] + self.edges[u][v].strength", "isinstance(self.shortest_paths_guide[source_id], dict): if target_id in self.shortest_paths_guide[source_id]: r = [] if self.shortest_paths_guide[source_id][target_id] is not", "= distance[x] indices.append(min_ind) return min_node_id def calculate_shortest_paths_from(self, source_id): distance = {} previous =", "= {} previous = {} q = None if self.use_priority_queue: q = PriorityDict()", "else: th = [] for source_id in self.nodes: t = threading.Thread(target=self.calculate_shortest_paths_from, args=[source_id]) t.start()", "calculate_all_shortest_paths(self): if not self.num_threads: for source_id in self.nodes: self.calculate_shortest_paths_from(source_id) else: th = []", "= ind min_node_id = x min_dist = distance[x] indices.append(min_ind) return min_node_id def calculate_shortest_paths_from(self,", "0.1) G.add_edge(2, 4, 0.5) print \"Calculating all possible shortest paths\" G.calculate_all_shortest_paths() print \"Shortest", "source_id in self.shortest_paths_guide and isinstance(self.shortest_paths_guide[source_id], dict): if target_id in self.shortest_paths_guide[source_id]: r = []", "<filename>graphene/dijkstra.py __author__ = 'Sushant' from graph import Graph import threading from prioritydict import", "not source_id: distance[x] = float(\"inf\") previous[x] = None if self.use_priority_queue: q[x] = distance[x]", "= use_priority_queue return def get_node_with_minimum_distance(self, q, distance, indices): min_dist = float(\"inf\") min_ind =", "= threading.Lock() self.use_priority_queue = use_priority_queue return def get_node_with_minimum_distance(self, q, distance, indices): min_dist =", "from prioritydict import PriorityDict class Dijkstra(Graph): def __init__(self, num_threads=0, use_priority_queue=1): super(Dijkstra, self).__init__() self.shortest_paths", "self.edges[u]: if v in q: alt = distance[u] + self.edges[u][v].strength if alt <", "= None if self.use_priority_queue: q = PriorityDict() else: q = [] ind =", "all possible shortest paths\" G.calculate_all_shortest_paths() print \"Shortest paths calculation finished\" print G.get_shortest_path_length(1, 4)", "[] ind = [] distance[source_id] = 0 for x in self.nodes: if x", "if source_id in self.shortest_paths_guide and isinstance(self.shortest_paths_guide[source_id], dict): if target_id in self.shortest_paths_guide[source_id]: r =", "len(th): _t = th.pop() _t.join() if len(th): while len(th): _t = th.pop() _t.join()", "+ self.edges[u][v].strength if alt < distance[v]: distance[v] = alt previous[v] = u if", "target_id, append_target=1): if source_id in self.shortest_paths_guide and isinstance(self.shortest_paths_guide[source_id], dict): if target_id in self.shortest_paths_guide[source_id]:", "while len(th): _t = th.pop() _t.join() if len(th): while len(th): _t = th.pop()", "= r + self.get_shortest_route(source_id, self.shortest_paths_guide[source_id][target_id], 0) r.append(self.shortest_paths_guide[source_id][target_id]) if append_target: r.append(target_id) return r return", "else: q = [] ind = [] distance[source_id] = 0 for x in", "x is not source_id: distance[x] = float(\"inf\") previous[x] = None if self.use_priority_queue: q[x]", "self.shortest_paths[source_id] = distance self.shortest_paths_guide[source_id] = previous self.lock.release() return def calculate_all_shortest_paths(self): if not self.num_threads:", "if self.use_priority_queue: q[x] = distance[x] else: q.append(x) while len(q): u = None if", "None if self.use_priority_queue: q[x] = distance[x] else: q.append(x) while len(q): u = None", "distance[x] = float(\"inf\") previous[x] = None if self.use_priority_queue: q[x] = distance[x] else: q.append(x)", "self.get_node_with_minimum_distance(q, distance, ind) index = ind.pop() if type(index) is int: del q[index] else:", "source_id in self.nodes: self.calculate_shortest_paths_from(source_id) else: th = [] for source_id in self.nodes: t", "= 0 for x in self.nodes: if x is not source_id: distance[x] =", "= PriorityDict() else: q = [] ind = [] distance[source_id] = 0 for", "calculate_shortest_paths_from(self, source_id): distance = {} previous = {} q = None if self.use_priority_queue:", "previous self.lock.release() return def calculate_all_shortest_paths(self): if not self.num_threads: for source_id in self.nodes: self.calculate_shortest_paths_from(source_id)", "del q[index] else: break if isinstance(self.edges[u], dict): for v in self.edges[u]: if v", "= th.pop() _t.join() if len(th): while len(th): _t = th.pop() _t.join() return def", "r + self.get_shortest_route(source_id, self.shortest_paths_guide[source_id][target_id], 0) r.append(self.shortest_paths_guide[source_id][target_id]) if append_target: r.append(target_id) return r return []", "source_id: distance[x] = float(\"inf\") previous[x] = None if self.use_priority_queue: q[x] = distance[x] else:", "distance[x] indices.append(min_ind) return min_node_id def calculate_shortest_paths_from(self, source_id): distance = {} previous = {}", "r return [] \"\"\" G = Dijkstra(10, 1) G.add_edge(1, 2, 0.1) G.add_edge(1, 3,", "self.nodes: if x is not source_id: distance[x] = float(\"inf\") previous[x] = None if", "def get_node_with_minimum_distance(self, q, distance, indices): min_dist = float(\"inf\") min_ind = None min_node_id =", "num_threads if num_threads: self.lock = threading.Lock() self.use_priority_queue = use_priority_queue return def get_node_with_minimum_distance(self, q,", "def get_shortest_route(self, source_id, target_id, append_target=1): if source_id in self.shortest_paths_guide and isinstance(self.shortest_paths_guide[source_id], dict): if", "self.edges[u][v].strength if alt < distance[v]: distance[v] = alt previous[v] = u if self.use_priority_queue:", "if num_threads: self.lock = threading.Lock() self.use_priority_queue = use_priority_queue return def get_node_with_minimum_distance(self, q, distance,", "self.shortest_paths[source_id]: return self.shortest_paths[source_id][target_id] return None def get_shortest_route(self, source_id, target_id, append_target=1): if source_id in", "_t.join() return def get_shortest_path_length(self, source_id, target_id): if source_id in self.shortest_paths and isinstance(self.shortest_paths[source_id], dict):", "4, 0.5) print \"Calculating all possible shortest paths\" G.calculate_all_shortest_paths() print \"Shortest paths calculation", "__init__(self, num_threads=0, use_priority_queue=1): super(Dijkstra, self).__init__() self.shortest_paths = {} self.shortest_paths_guide = {} self.num_threads =", "return self.shortest_paths[source_id][target_id] return None def get_shortest_route(self, source_id, target_id, append_target=1): if source_id in self.shortest_paths_guide", "return [] \"\"\" G = Dijkstra(10, 1) G.add_edge(1, 2, 0.1) G.add_edge(1, 3, 0.3)", "u = q.pop_smallest() else: u = self.get_node_with_minimum_distance(q, distance, ind) index = ind.pop() if", "is int: del q[index] else: break if isinstance(self.edges[u], dict): for v in self.edges[u]:", "in self.shortest_paths[source_id]: return self.shortest_paths[source_id][target_id] return None def get_shortest_route(self, source_id, target_id, append_target=1): if source_id", "self.shortest_paths_guide[source_id][target_id], 0) r.append(self.shortest_paths_guide[source_id][target_id]) if append_target: r.append(target_id) return r return [] \"\"\" G =", "enumerate(q): if distance[x] < min_dist: min_ind = ind min_node_id = x min_dist =", "= [] distance[source_id] = 0 for x in self.nodes: if x is not", "G.calculate_all_shortest_paths() print \"Shortest paths calculation finished\" print G.get_shortest_path_length(1, 4) print G.get_shortest_route(1, 4) \"\"\"", "G.add_edge(1, 3, 0.3) G.add_edge(2, 3, 0.1) G.add_edge(3, 4, 0.1) G.add_edge(2, 4, 0.5) print", "def calculate_all_shortest_paths(self): if not self.num_threads: for source_id in self.nodes: self.calculate_shortest_paths_from(source_id) else: th =", "import threading from prioritydict import PriorityDict class Dijkstra(Graph): def __init__(self, num_threads=0, use_priority_queue=1): super(Dijkstra,", "not source_id: r = r + self.get_shortest_route(source_id, self.shortest_paths_guide[source_id][target_id], 0) r.append(self.shortest_paths_guide[source_id][target_id]) if append_target: r.append(target_id)", "= {} self.shortest_paths_guide = {} self.num_threads = num_threads if num_threads: self.lock = threading.Lock()", "0 for x in self.nodes: if x is not source_id: distance[x] = float(\"inf\")", "while len(th): _t = th.pop() _t.join() return def get_shortest_path_length(self, source_id, target_id): if source_id", "previous[x] = None if self.use_priority_queue: q[x] = distance[x] else: q.append(x) while len(q): u", "distance, indices): min_dist = float(\"inf\") min_ind = None min_node_id = None for ind,", "self.lock.acquire() self.shortest_paths[source_id] = distance self.shortest_paths_guide[source_id] = previous self.lock.release() return def calculate_all_shortest_paths(self): if not", "= None if self.use_priority_queue: q[x] = distance[x] else: q.append(x) while len(q): u =", "= distance[u] + self.edges[u][v].strength if alt < distance[v]: distance[v] = alt previous[v] =", "G = Dijkstra(10, 1) G.add_edge(1, 2, 0.1) G.add_edge(1, 3, 0.3) G.add_edge(2, 3, 0.1)", "if not self.num_threads: for source_id in self.nodes: self.calculate_shortest_paths_from(source_id) else: th = [] for", "if isinstance(self.edges[u], dict): for v in self.edges[u]: if v in q: alt =", "distance[v] = alt previous[v] = u if self.use_priority_queue: q[v] = distance[v] if not", "self.lock.release() return def calculate_all_shortest_paths(self): if not self.num_threads: for source_id in self.nodes: self.calculate_shortest_paths_from(source_id) else:", "self.nodes: t = threading.Thread(target=self.calculate_shortest_paths_from, args=[source_id]) t.start() th.append(t) if len(th) >= self.num_threads: while len(th):", "x in self.nodes: if x is not source_id: distance[x] = float(\"inf\") previous[x] =", "self.shortest_paths_guide = {} self.num_threads = num_threads if num_threads: self.lock = threading.Lock() self.use_priority_queue =", "= q.pop_smallest() else: u = self.get_node_with_minimum_distance(q, distance, ind) index = ind.pop() if type(index)", "distance self.shortest_paths_guide[source_id] = previous else: self.lock.acquire() self.shortest_paths[source_id] = distance self.shortest_paths_guide[source_id] = previous self.lock.release()", "r.append(target_id) return r return [] \"\"\" G = Dijkstra(10, 1) G.add_edge(1, 2, 0.1)", "else: u = self.get_node_with_minimum_distance(q, distance, ind) index = ind.pop() if type(index) is int:", "from graph import Graph import threading from prioritydict import PriorityDict class Dijkstra(Graph): def", "return def get_node_with_minimum_distance(self, q, distance, indices): min_dist = float(\"inf\") min_ind = None min_node_id", "source_id: r = r + self.get_shortest_route(source_id, self.shortest_paths_guide[source_id][target_id], 0) r.append(self.shortest_paths_guide[source_id][target_id]) if append_target: r.append(target_id) return", "prioritydict import PriorityDict class Dijkstra(Graph): def __init__(self, num_threads=0, use_priority_queue=1): super(Dijkstra, self).__init__() self.shortest_paths =", "q: alt = distance[u] + self.edges[u][v].strength if alt < distance[v]: distance[v] = alt", "if not self.num_threads: self.shortest_paths[source_id] = distance self.shortest_paths_guide[source_id] = previous else: self.lock.acquire() self.shortest_paths[source_id] =", "self.shortest_paths[source_id][target_id] return None def get_shortest_route(self, source_id, target_id, append_target=1): if source_id in self.shortest_paths_guide and", "int: del q[index] else: break if isinstance(self.edges[u], dict): for v in self.edges[u]: if", "= {} self.num_threads = num_threads if num_threads: self.lock = threading.Lock() self.use_priority_queue = use_priority_queue", "self.shortest_paths_guide[source_id] = previous self.lock.release() return def calculate_all_shortest_paths(self): if not self.num_threads: for source_id in", "[] \"\"\" G = Dijkstra(10, 1) G.add_edge(1, 2, 0.1) G.add_edge(1, 3, 0.3) G.add_edge(2,", "q.pop_smallest() else: u = self.get_node_with_minimum_distance(q, distance, ind) index = ind.pop() if type(index) is", "if target_id in self.shortest_paths[source_id]: return self.shortest_paths[source_id][target_id] return None def get_shortest_route(self, source_id, target_id, append_target=1):", "len(th): while len(th): _t = th.pop() _t.join() return def get_shortest_path_length(self, source_id, target_id): if", "[] distance[source_id] = 0 for x in self.nodes: if x is not source_id:", "if v in q: alt = distance[u] + self.edges[u][v].strength if alt < distance[v]:", "self.shortest_paths_guide[source_id][target_id] is not source_id: r = r + self.get_shortest_route(source_id, self.shortest_paths_guide[source_id][target_id], 0) r.append(self.shortest_paths_guide[source_id][target_id]) if", "float(\"inf\") min_ind = None min_node_id = None for ind, x in enumerate(q): if", "threading from prioritydict import PriorityDict class Dijkstra(Graph): def __init__(self, num_threads=0, use_priority_queue=1): super(Dijkstra, self).__init__()", "for x in self.nodes: if x is not source_id: distance[x] = float(\"inf\") previous[x]", "_t = th.pop() _t.join() return def get_shortest_path_length(self, source_id, target_id): if source_id in self.shortest_paths", "= float(\"inf\") previous[x] = None if self.use_priority_queue: q[x] = distance[x] else: q.append(x) while", "source_id in self.shortest_paths and isinstance(self.shortest_paths[source_id], dict): if target_id in self.shortest_paths[source_id]: return self.shortest_paths[source_id][target_id] return", "= x min_dist = distance[x] indices.append(min_ind) return min_node_id def calculate_shortest_paths_from(self, source_id): distance =", "q[x] = distance[x] else: q.append(x) while len(q): u = None if self.use_priority_queue: u", "self.shortest_paths_guide and isinstance(self.shortest_paths_guide[source_id], dict): if target_id in self.shortest_paths_guide[source_id]: r = [] if self.shortest_paths_guide[source_id][target_id]", "ind, x in enumerate(q): if distance[x] < min_dist: min_ind = ind min_node_id =", "isinstance(self.shortest_paths[source_id], dict): if target_id in self.shortest_paths[source_id]: return self.shortest_paths[source_id][target_id] return None def get_shortest_route(self, source_id,", "source_id): distance = {} previous = {} q = None if self.use_priority_queue: q", "0.3) G.add_edge(2, 3, 0.1) G.add_edge(3, 4, 0.1) G.add_edge(2, 4, 0.5) print \"Calculating all", "= [] ind = [] distance[source_id] = 0 for x in self.nodes: if", "0.5) print \"Calculating all possible shortest paths\" G.calculate_all_shortest_paths() print \"Shortest paths calculation finished\"", "self.use_priority_queue = use_priority_queue return def get_node_with_minimum_distance(self, q, distance, indices): min_dist = float(\"inf\") min_ind", "float(\"inf\") previous[x] = None if self.use_priority_queue: q[x] = distance[x] else: q.append(x) while len(q):", "q[v] = distance[v] if not self.num_threads: self.shortest_paths[source_id] = distance self.shortest_paths_guide[source_id] = previous else:", "3, 0.1) G.add_edge(3, 4, 0.1) G.add_edge(2, 4, 0.5) print \"Calculating all possible shortest", "if source_id in self.shortest_paths and isinstance(self.shortest_paths[source_id], dict): if target_id in self.shortest_paths[source_id]: return self.shortest_paths[source_id][target_id]", "class Dijkstra(Graph): def __init__(self, num_threads=0, use_priority_queue=1): super(Dijkstra, self).__init__() self.shortest_paths = {} self.shortest_paths_guide =", "= float(\"inf\") min_ind = None min_node_id = None for ind, x in enumerate(q):", "for source_id in self.nodes: t = threading.Thread(target=self.calculate_shortest_paths_from, args=[source_id]) t.start() th.append(t) if len(th) >=", "= distance[x] else: q.append(x) while len(q): u = None if self.use_priority_queue: u =", "distance[u] + self.edges[u][v].strength if alt < distance[v]: distance[v] = alt previous[v] = u", "th.pop() _t.join() if len(th): while len(th): _t = th.pop() _t.join() return def get_shortest_path_length(self,", "min_dist: min_ind = ind min_node_id = x min_dist = distance[x] indices.append(min_ind) return min_node_id", "import Graph import threading from prioritydict import PriorityDict class Dijkstra(Graph): def __init__(self, num_threads=0,", "self.shortest_paths[source_id] = distance self.shortest_paths_guide[source_id] = previous else: self.lock.acquire() self.shortest_paths[source_id] = distance self.shortest_paths_guide[source_id] =", "len(th) >= self.num_threads: while len(th): _t = th.pop() _t.join() if len(th): while len(th):", "use_priority_queue=1): super(Dijkstra, self).__init__() self.shortest_paths = {} self.shortest_paths_guide = {} self.num_threads = num_threads if", "dict): for v in self.edges[u]: if v in q: alt = distance[u] +", "{} self.num_threads = num_threads if num_threads: self.lock = threading.Lock() self.use_priority_queue = use_priority_queue return", "min_ind = ind min_node_id = x min_dist = distance[x] indices.append(min_ind) return min_node_id def", "while len(q): u = None if self.use_priority_queue: u = q.pop_smallest() else: u =", "{} self.shortest_paths_guide = {} self.num_threads = num_threads if num_threads: self.lock = threading.Lock() self.use_priority_queue", "{} q = None if self.use_priority_queue: q = PriorityDict() else: q = []", "= distance[v] if not self.num_threads: self.shortest_paths[source_id] = distance self.shortest_paths_guide[source_id] = previous else: self.lock.acquire()", "Dijkstra(Graph): def __init__(self, num_threads=0, use_priority_queue=1): super(Dijkstra, self).__init__() self.shortest_paths = {} self.shortest_paths_guide = {}", "+ self.get_shortest_route(source_id, self.shortest_paths_guide[source_id][target_id], 0) r.append(self.shortest_paths_guide[source_id][target_id]) if append_target: r.append(target_id) return r return [] \"\"\"", "indices.append(min_ind) return min_node_id def calculate_shortest_paths_from(self, source_id): distance = {} previous = {} q", "= None if self.use_priority_queue: u = q.pop_smallest() else: u = self.get_node_with_minimum_distance(q, distance, ind)", "= alt previous[v] = u if self.use_priority_queue: q[v] = distance[v] if not self.num_threads:", "= ind.pop() if type(index) is int: del q[index] else: break if isinstance(self.edges[u], dict):", "return None def get_shortest_route(self, source_id, target_id, append_target=1): if source_id in self.shortest_paths_guide and isinstance(self.shortest_paths_guide[source_id],", "if alt < distance[v]: distance[v] = alt previous[v] = u if self.use_priority_queue: q[v]", "def __init__(self, num_threads=0, use_priority_queue=1): super(Dijkstra, self).__init__() self.shortest_paths = {} self.shortest_paths_guide = {} self.num_threads", "self.num_threads = num_threads if num_threads: self.lock = threading.Lock() self.use_priority_queue = use_priority_queue return def", "args=[source_id]) t.start() th.append(t) if len(th) >= self.num_threads: while len(th): _t = th.pop() _t.join()", "source_id, target_id): if source_id in self.shortest_paths and isinstance(self.shortest_paths[source_id], dict): if target_id in self.shortest_paths[source_id]:", "self.num_threads: for source_id in self.nodes: self.calculate_shortest_paths_from(source_id) else: th = [] for source_id in", "= previous self.lock.release() return def calculate_all_shortest_paths(self): if not self.num_threads: for source_id in self.nodes:", "0.1) G.add_edge(1, 3, 0.3) G.add_edge(2, 3, 0.1) G.add_edge(3, 4, 0.1) G.add_edge(2, 4, 0.5)", "num_threads: self.lock = threading.Lock() self.use_priority_queue = use_priority_queue return def get_node_with_minimum_distance(self, q, distance, indices):", "0) r.append(self.shortest_paths_guide[source_id][target_id]) if append_target: r.append(target_id) return r return [] \"\"\" G = Dijkstra(10,", "self.use_priority_queue: u = q.pop_smallest() else: u = self.get_node_with_minimum_distance(q, distance, ind) index = ind.pop()", "v in self.edges[u]: if v in q: alt = distance[u] + self.edges[u][v].strength if", ">= self.num_threads: while len(th): _t = th.pop() _t.join() if len(th): while len(th): _t", "__author__ = 'Sushant' from graph import Graph import threading from prioritydict import PriorityDict", "r = [] if self.shortest_paths_guide[source_id][target_id] is not source_id: r = r + self.get_shortest_route(source_id,", "Dijkstra(10, 1) G.add_edge(1, 2, 0.1) G.add_edge(1, 3, 0.3) G.add_edge(2, 3, 0.1) G.add_edge(3, 4,", "= 'Sushant' from graph import Graph import threading from prioritydict import PriorityDict class", "'Sushant' from graph import Graph import threading from prioritydict import PriorityDict class Dijkstra(Graph):", "else: self.lock.acquire() self.shortest_paths[source_id] = distance self.shortest_paths_guide[source_id] = previous self.lock.release() return def calculate_all_shortest_paths(self): if", "threading.Lock() self.use_priority_queue = use_priority_queue return def get_node_with_minimum_distance(self, q, distance, indices): min_dist = float(\"inf\")", "super(Dijkstra, self).__init__() self.shortest_paths = {} self.shortest_paths_guide = {} self.num_threads = num_threads if num_threads:", "return min_node_id def calculate_shortest_paths_from(self, source_id): distance = {} previous = {} q =", "u if self.use_priority_queue: q[v] = distance[v] if not self.num_threads: self.shortest_paths[source_id] = distance self.shortest_paths_guide[source_id]", "1) G.add_edge(1, 2, 0.1) G.add_edge(1, 3, 0.3) G.add_edge(2, 3, 0.1) G.add_edge(3, 4, 0.1)", "ind.pop() if type(index) is int: del q[index] else: break if isinstance(self.edges[u], dict): for", "u = None if self.use_priority_queue: u = q.pop_smallest() else: u = self.get_node_with_minimum_distance(q, distance,", "self.use_priority_queue: q[x] = distance[x] else: q.append(x) while len(q): u = None if self.use_priority_queue:", "PriorityDict class Dijkstra(Graph): def __init__(self, num_threads=0, use_priority_queue=1): super(Dijkstra, self).__init__() self.shortest_paths = {} self.shortest_paths_guide", "None if self.use_priority_queue: u = q.pop_smallest() else: u = self.get_node_with_minimum_distance(q, distance, ind) index", "in self.nodes: self.calculate_shortest_paths_from(source_id) else: th = [] for source_id in self.nodes: t =", "None for ind, x in enumerate(q): if distance[x] < min_dist: min_ind = ind", "break if isinstance(self.edges[u], dict): for v in self.edges[u]: if v in q: alt", "q.append(x) while len(q): u = None if self.use_priority_queue: u = q.pop_smallest() else: u", "q = None if self.use_priority_queue: q = PriorityDict() else: q = [] ind", "min_node_id = None for ind, x in enumerate(q): if distance[x] < min_dist: min_ind", "= num_threads if num_threads: self.lock = threading.Lock() self.use_priority_queue = use_priority_queue return def get_node_with_minimum_distance(self,", "0.1) G.add_edge(3, 4, 0.1) G.add_edge(2, 4, 0.5) print \"Calculating all possible shortest paths\"", "[] for source_id in self.nodes: t = threading.Thread(target=self.calculate_shortest_paths_from, args=[source_id]) t.start() th.append(t) if len(th)", "min_dist = float(\"inf\") min_ind = None min_node_id = None for ind, x in", "x in enumerate(q): if distance[x] < min_dist: min_ind = ind min_node_id = x", "x min_dist = distance[x] indices.append(min_ind) return min_node_id def calculate_shortest_paths_from(self, source_id): distance = {}", "use_priority_queue return def get_node_with_minimum_distance(self, q, distance, indices): min_dist = float(\"inf\") min_ind = None", "index = ind.pop() if type(index) is int: del q[index] else: break if isinstance(self.edges[u],", "self.nodes: self.calculate_shortest_paths_from(source_id) else: th = [] for source_id in self.nodes: t = threading.Thread(target=self.calculate_shortest_paths_from,", "if len(th) >= self.num_threads: while len(th): _t = th.pop() _t.join() if len(th): while", "alt < distance[v]: distance[v] = alt previous[v] = u if self.use_priority_queue: q[v] =", "shortest paths\" G.calculate_all_shortest_paths() print \"Shortest paths calculation finished\" print G.get_shortest_path_length(1, 4) print G.get_shortest_route(1,", "Graph import threading from prioritydict import PriorityDict class Dijkstra(Graph): def __init__(self, num_threads=0, use_priority_queue=1):", "= th.pop() _t.join() return def get_shortest_path_length(self, source_id, target_id): if source_id in self.shortest_paths and", "target_id in self.shortest_paths[source_id]: return self.shortest_paths[source_id][target_id] return None def get_shortest_route(self, source_id, target_id, append_target=1): if", "ind min_node_id = x min_dist = distance[x] indices.append(min_ind) return min_node_id def calculate_shortest_paths_from(self, source_id):", "paths\" G.calculate_all_shortest_paths() print \"Shortest paths calculation finished\" print G.get_shortest_path_length(1, 4) print G.get_shortest_route(1, 4)", "in self.nodes: if x is not source_id: distance[x] = float(\"inf\") previous[x] = None", "is not source_id: distance[x] = float(\"inf\") previous[x] = None if self.use_priority_queue: q[x] =", "indices): min_dist = float(\"inf\") min_ind = None min_node_id = None for ind, x", "\"\"\" G = Dijkstra(10, 1) G.add_edge(1, 2, 0.1) G.add_edge(1, 3, 0.3) G.add_edge(2, 3,", "len(th): _t = th.pop() _t.join() return def get_shortest_path_length(self, source_id, target_id): if source_id in", "min_node_id def calculate_shortest_paths_from(self, source_id): distance = {} previous = {} q = None", "distance[x] else: q.append(x) while len(q): u = None if self.use_priority_queue: u = q.pop_smallest()", "in self.nodes: t = threading.Thread(target=self.calculate_shortest_paths_from, args=[source_id]) t.start() th.append(t) if len(th) >= self.num_threads: while", "= [] if self.shortest_paths_guide[source_id][target_id] is not source_id: r = r + self.get_shortest_route(source_id, self.shortest_paths_guide[source_id][target_id],", "threading.Thread(target=self.calculate_shortest_paths_from, args=[source_id]) t.start() th.append(t) if len(th) >= self.num_threads: while len(th): _t = th.pop()", "ind = [] distance[source_id] = 0 for x in self.nodes: if x is", "self.use_priority_queue: q[v] = distance[v] if not self.num_threads: self.shortest_paths[source_id] = distance self.shortest_paths_guide[source_id] = previous", "= Dijkstra(10, 1) G.add_edge(1, 2, 0.1) G.add_edge(1, 3, 0.3) G.add_edge(2, 3, 0.1) G.add_edge(3,", "if len(th): while len(th): _t = th.pop() _t.join() return def get_shortest_path_length(self, source_id, target_id):", "in self.shortest_paths and isinstance(self.shortest_paths[source_id], dict): if target_id in self.shortest_paths[source_id]: return self.shortest_paths[source_id][target_id] return None", "else: break if isinstance(self.edges[u], dict): for v in self.edges[u]: if v in q:", "get_shortest_path_length(self, source_id, target_id): if source_id in self.shortest_paths and isinstance(self.shortest_paths[source_id], dict): if target_id in", "PriorityDict() else: q = [] ind = [] distance[source_id] = 0 for x", "alt = distance[u] + self.edges[u][v].strength if alt < distance[v]: distance[v] = alt previous[v]", "return def calculate_all_shortest_paths(self): if not self.num_threads: for source_id in self.nodes: self.calculate_shortest_paths_from(source_id) else: th", "G.add_edge(2, 4, 0.5) print \"Calculating all possible shortest paths\" G.calculate_all_shortest_paths() print \"Shortest paths", "def calculate_shortest_paths_from(self, source_id): distance = {} previous = {} q = None if", "[] if self.shortest_paths_guide[source_id][target_id] is not source_id: r = r + self.get_shortest_route(source_id, self.shortest_paths_guide[source_id][target_id], 0)", "ind) index = ind.pop() if type(index) is int: del q[index] else: break if", "is not source_id: r = r + self.get_shortest_route(source_id, self.shortest_paths_guide[source_id][target_id], 0) r.append(self.shortest_paths_guide[source_id][target_id]) if append_target:", "append_target: r.append(target_id) return r return [] \"\"\" G = Dijkstra(10, 1) G.add_edge(1, 2,", "type(index) is int: del q[index] else: break if isinstance(self.edges[u], dict): for v in", "possible shortest paths\" G.calculate_all_shortest_paths() print \"Shortest paths calculation finished\" print G.get_shortest_path_length(1, 4) print", "self.shortest_paths_guide[source_id]: r = [] if self.shortest_paths_guide[source_id][target_id] is not source_id: r = r +", "u = self.get_node_with_minimum_distance(q, distance, ind) index = ind.pop() if type(index) is int: del", "= distance self.shortest_paths_guide[source_id] = previous else: self.lock.acquire() self.shortest_paths[source_id] = distance self.shortest_paths_guide[source_id] = previous", "< min_dist: min_ind = ind min_node_id = x min_dist = distance[x] indices.append(min_ind) return", "append_target=1): if source_id in self.shortest_paths_guide and isinstance(self.shortest_paths_guide[source_id], dict): if target_id in self.shortest_paths_guide[source_id]: r", "r = r + self.get_shortest_route(source_id, self.shortest_paths_guide[source_id][target_id], 0) r.append(self.shortest_paths_guide[source_id][target_id]) if append_target: r.append(target_id) return r", "None if self.use_priority_queue: q = PriorityDict() else: q = [] ind = []", "if self.shortest_paths_guide[source_id][target_id] is not source_id: r = r + self.get_shortest_route(source_id, self.shortest_paths_guide[source_id][target_id], 0) r.append(self.shortest_paths_guide[source_id][target_id])", "for source_id in self.nodes: self.calculate_shortest_paths_from(source_id) else: th = [] for source_id in self.nodes:", "= [] for source_id in self.nodes: t = threading.Thread(target=self.calculate_shortest_paths_from, args=[source_id]) t.start() th.append(t) if", "= previous else: self.lock.acquire() self.shortest_paths[source_id] = distance self.shortest_paths_guide[source_id] = previous self.lock.release() return def", "print \"Calculating all possible shortest paths\" G.calculate_all_shortest_paths() print \"Shortest paths calculation finished\" print", "if self.use_priority_queue: q = PriorityDict() else: q = [] ind = [] distance[source_id]", "alt previous[v] = u if self.use_priority_queue: q[v] = distance[v] if not self.num_threads: self.shortest_paths[source_id]", "q, distance, indices): min_dist = float(\"inf\") min_ind = None min_node_id = None for", "and isinstance(self.shortest_paths_guide[source_id], dict): if target_id in self.shortest_paths_guide[source_id]: r = [] if self.shortest_paths_guide[source_id][target_id] is", "r.append(self.shortest_paths_guide[source_id][target_id]) if append_target: r.append(target_id) return r return [] \"\"\" G = Dijkstra(10, 1)", "if target_id in self.shortest_paths_guide[source_id]: r = [] if self.shortest_paths_guide[source_id][target_id] is not source_id: r", "if self.use_priority_queue: u = q.pop_smallest() else: u = self.get_node_with_minimum_distance(q, distance, ind) index =", "self.use_priority_queue: q = PriorityDict() else: q = [] ind = [] distance[source_id] =", "previous else: self.lock.acquire() self.shortest_paths[source_id] = distance self.shortest_paths_guide[source_id] = previous self.lock.release() return def calculate_all_shortest_paths(self):", "get_shortest_route(self, source_id, target_id, append_target=1): if source_id in self.shortest_paths_guide and isinstance(self.shortest_paths_guide[source_id], dict): if target_id", "dict): if target_id in self.shortest_paths[source_id]: return self.shortest_paths[source_id][target_id] return None def get_shortest_route(self, source_id, target_id,", "def get_shortest_path_length(self, source_id, target_id): if source_id in self.shortest_paths and isinstance(self.shortest_paths[source_id], dict): if target_id", "= self.get_node_with_minimum_distance(q, distance, ind) index = ind.pop() if type(index) is int: del q[index]", "distance[x] < min_dist: min_ind = ind min_node_id = x min_dist = distance[x] indices.append(min_ind)", "t.start() th.append(t) if len(th) >= self.num_threads: while len(th): _t = th.pop() _t.join() if", "if x is not source_id: distance[x] = float(\"inf\") previous[x] = None if self.use_priority_queue:", "in self.shortest_paths_guide[source_id]: r = [] if self.shortest_paths_guide[source_id][target_id] is not source_id: r = r", "num_threads=0, use_priority_queue=1): super(Dijkstra, self).__init__() self.shortest_paths = {} self.shortest_paths_guide = {} self.num_threads = num_threads", "< distance[v]: distance[v] = alt previous[v] = u if self.use_priority_queue: q[v] = distance[v]", "G.add_edge(3, 4, 0.1) G.add_edge(2, 4, 0.5) print \"Calculating all possible shortest paths\" G.calculate_all_shortest_paths()", "source_id, target_id, append_target=1): if source_id in self.shortest_paths_guide and isinstance(self.shortest_paths_guide[source_id], dict): if target_id in", "t = threading.Thread(target=self.calculate_shortest_paths_from, args=[source_id]) t.start() th.append(t) if len(th) >= self.num_threads: while len(th): _t", "q = [] ind = [] distance[source_id] = 0 for x in self.nodes:", "return def get_shortest_path_length(self, source_id, target_id): if source_id in self.shortest_paths and isinstance(self.shortest_paths[source_id], dict): if", "in enumerate(q): if distance[x] < min_dist: min_ind = ind min_node_id = x min_dist", "v in q: alt = distance[u] + self.edges[u][v].strength if alt < distance[v]: distance[v]", "distance[v]: distance[v] = alt previous[v] = u if self.use_priority_queue: q[v] = distance[v] if", "self).__init__() self.shortest_paths = {} self.shortest_paths_guide = {} self.num_threads = num_threads if num_threads: self.lock", "self.shortest_paths = {} self.shortest_paths_guide = {} self.num_threads = num_threads if num_threads: self.lock =", "dict): if target_id in self.shortest_paths_guide[source_id]: r = [] if self.shortest_paths_guide[source_id][target_id] is not source_id:", "distance[source_id] = 0 for x in self.nodes: if x is not source_id: distance[x]", "= threading.Thread(target=self.calculate_shortest_paths_from, args=[source_id]) t.start() th.append(t) if len(th) >= self.num_threads: while len(th): _t =", "len(q): u = None if self.use_priority_queue: u = q.pop_smallest() else: u = self.get_node_with_minimum_distance(q,", "= None for ind, x in enumerate(q): if distance[x] < min_dist: min_ind =", "self.shortest_paths_guide[source_id] = previous else: self.lock.acquire() self.shortest_paths[source_id] = distance self.shortest_paths_guide[source_id] = previous self.lock.release() return", "self.num_threads: self.shortest_paths[source_id] = distance self.shortest_paths_guide[source_id] = previous else: self.lock.acquire() self.shortest_paths[source_id] = distance self.shortest_paths_guide[source_id]", "previous = {} q = None if self.use_priority_queue: q = PriorityDict() else: q", "previous[v] = u if self.use_priority_queue: q[v] = distance[v] if not self.num_threads: self.shortest_paths[source_id] =", "if append_target: r.append(target_id) return r return [] \"\"\" G = Dijkstra(10, 1) G.add_edge(1,", "\"Calculating all possible shortest paths\" G.calculate_all_shortest_paths() print \"Shortest paths calculation finished\" print G.get_shortest_path_length(1," ]
[]
[ "Algorithm This program trains the model to fit two values, slope(m) and x-intercept(b)", "form the training data. aka Dataset (only training. no validation or test) \"\"\"", "\"\"\" m = tf.Variable(m_initial) b = tf.Variable(b_initial) \"\"\" In order to adjust and", "we pass the \"error\" to the minimize() function of this optimizer as a", "#number of passes on the dataset for iteration in range(_ITERATIONS): session.run(optimizer_op) #calling our", "would be adjusted to fit the above dataset point \"\"\" m_initial = -0.50", "rate would make your training very slow and Too big learning rate would", "m = tf.Variable(m_initial) b = tf.Variable(b_initial) \"\"\" In order to adjust and fit", "straight line can further be used to predict any unknown value Y for", "-0.50 b_initial = 1.00 \"\"\" tf.Variable : allows us to create variables whose", "/ \"error\".abs Remember Too Small a learning rate would make your training very", "line y=mx+b. Here we would provide very small dataset of randomly generated pointset", "an operation for calculation of error and also iteration over the value of", "in order to learn at each pass on the dataset. \"\"\" m =", "= tf.train.GradientDescentOptimizer(learning_rate=0.001).minimize(error) \"\"\" Tensorflow uses a \"session\" to run the above mentioned training", "adjusted to fit the above dataset point \"\"\" m_initial = -0.50 b_initial =", "line can be fit properly as we minimize the value of distances between", "is always advisable to initialize variables randomly. \"\"\" init_op = tf.global_variables_initializer() \"\"\" All", "function of this optimizer as a parameter.abs here while initialization of the Gradient", "the minimize() function of this optimizer as a parameter.abs here while initialization of", "\"cost\" / \"error\".abs Remember Too Small a learning rate would make your training", "the dataset. \"\"\" m = tf.Variable(m_initial) b = tf.Variable(b_initial) \"\"\" In order to", "Y for a given unknown X based on the learned value of m", "\"\"\" with tf.Session() as session: session.run(init_op) _ITERATIONS = 1000 #number of passes on", "b i.e. predicted_y and actual y (from \"ys\"). \"\"\" error = 0.0 \"\"\"", "as tf \"\"\" Random points of X and Y form the training data.", "added to the total error 'cost' which we minimize. \"\"\" Now, in order", "\"\"\" Now, in order to train over this operation set we defined above,", "each pass on the dataset. \"\"\" m = tf.Variable(m_initial) b = tf.Variable(b_initial) \"\"\"", "and b. \"\"\" import os os.environ['TF_CPP_MIN_LOG_LEVEL']='2' # called in order to minimize the", "We write an operation for calculation of error and also iteration over the", "Author: <NAME> Github: github.com/yashbmewada Program for demonstrating simple line fitting using Tensorflow and", "b. These values would be adjusted to fit the above dataset point \"\"\"", "test) \"\"\" xs = [0.00,2.00,4.00,6.00,8.00,10.00,12.00,14.00] #features ys = [-0.82,-0.90,-0.12,0.26,0.31,0.64,1.02,1.00] #labels (actual outputs) \"\"\"", "called in order to minimize the warnings about SSE4.1 instructions. import tensorflow as", "_ITERATIONS = 1000 #number of passes on the dataset for iteration in range(_ITERATIONS):", "This straight line can further be used to predict any unknown value Y", "xs and ys and train the tensorflow model to adjust the values of", "Too big learning rate would make the training never find an optimum solution.", "in order to fit a straight line. This straight line can further be", "over the value of X and Y from the Dataset [xs,ys]. Running this", "= -0.50 b_initial = 1.00 \"\"\" tf.Variable : allows us to create variables", "fit the above dataset point \"\"\" m_initial = -0.50 b_initial = 1.00 \"\"\"", "as it usually works in most cases. \"\"\" optimizer_op = tf.train.GradientDescentOptimizer(learning_rate=0.001).minimize(error) \"\"\" Tensorflow", "mentioned training steps. So before starting the session it is always advisable to", "Here we take 0.001 randomly as it usually works in most cases. \"\"\"", "about SSE4.1 instructions. import tensorflow as tf \"\"\" Random points of X and", "very small dataset of randomly generated pointset xs and ys and train the", "import tensorflow as tf \"\"\" Random points of X and Y form the", "values for m and b. These values would be adjusted to fit the", "calculation of error and also iteration over the value of X and Y", "Gradient Descent optimizer, we define a learning_rate = 0.001. This learning rate defines", "line fitting using Tensorflow and Gradient Descent Algorithm This program trains the model", "Random points of X and Y form the training data. aka Dataset (only", "In order to adjust and fit the line, we try to minimize the", "to train over this data set and we pass the \"error\" to the", "on the dataset. \"\"\" m = tf.Variable(m_initial) b = tf.Variable(b_initial) \"\"\" In order", "of (x,y) so that the line can be fit properly as we minimize", "of line y=mx+b. Here we would provide very small dataset of randomly generated", "in order to train over this operation set we defined above, we use", "create variables whose values can be adjusted in order to learn at each", "Gradient Descent Optimizer which allows us to train over this data set and", "trying different values. Here we take 0.001 randomly as it usually works in", "with tf.Session() as session: session.run(init_op) _ITERATIONS = 1000 #number of passes on the", "the square of difference of error added to the total error 'cost' which", "X and Y form the training data. aka Dataset (only training. no validation", "us to train over this data set and we pass the \"error\" to", "slow and Too big learning rate would make the training never find an", "a learning rate would make your training very slow and Too big learning", "instructions. import tensorflow as tf \"\"\" Random points of X and Y form", "total error 'cost' which we minimize. \"\"\" Now, in order to train over", "a given unknown X based on the learned value of m and b.", "parameter.abs here while initialization of the Gradient Descent optimizer, we define a learning_rate", "randomly. \"\"\" init_op = tf.global_variables_initializer() \"\"\" All the calculations would now be done", "can further be used to predict any unknown value Y for a given", "the training never find an optimum solution. Best Learning Rate can be found", "Rate can be found by trying different values. Here we take 0.001 randomly", "run the above mentioned training steps. So before starting the session it is", "tf \"\"\" Random points of X and Y form the training data. aka", "Github: github.com/yashbmewada Program for demonstrating simple line fitting using Tensorflow and Gradient Descent", "= session.run((m,b)) #calling our adjusted values print('slope: ', slope , 'Intercept: ', intercept)", "values can be adjusted in order to learn at each pass on the", "0.0 \"\"\" We write an operation for calculation of error and also iteration", "minimize error slope, intercept = session.run((m,b)) #calling our adjusted values print('slope: ', slope", "two given values of (x,y) so that the line can be fit properly", "find an optimum solution. Best Learning Rate can be found by trying different", "optimizer_op = tf.train.GradientDescentOptimizer(learning_rate=0.001).minimize(error) \"\"\" Tensorflow uses a \"session\" to run the above mentioned", "over around 1000 times we would be able to minimize the error to", "iteration in range(_ITERATIONS): session.run(optimizer_op) #calling our optimization operator to minimize error slope, intercept", "m and b i.e. predicted_y and actual y (from \"ys\"). \"\"\" error =", "Now, in order to train over this operation set we defined above, we", "for demonstrating simple line fitting using Tensorflow and Gradient Descent Algorithm This program", "session: session.run(init_op) _ITERATIONS = 1000 #number of passes on the dataset for iteration", "warnings about SSE4.1 instructions. import tensorflow as tf \"\"\" Random points of X", "this over around 1000 times we would be able to minimize the error", "1000 #number of passes on the dataset for iteration in range(_ITERATIONS): session.run(optimizer_op) #calling", "\"error\" between two given values of (x,y) so that the line can be", "training very slow and Too big learning rate would make the training never", "of X and Y from the Dataset [xs,ys]. Running this over around 1000", "be used to predict any unknown value Y for a given unknown X", "be adjusted in order to learn at each pass on the dataset. \"\"\"", "[0.00,2.00,4.00,6.00,8.00,10.00,12.00,14.00] #features ys = [-0.82,-0.90,-0.12,0.26,0.31,0.64,1.02,1.00] #labels (actual outputs) \"\"\" Initial values for m", "unknown X based on the learned value of m and b. \"\"\" import", "as session: session.run(init_op) _ITERATIONS = 1000 #number of passes on the dataset for", "on the dataset for iteration in range(_ITERATIONS): session.run(optimizer_op) #calling our optimization operator to", "\"\"\" All the calculations would now be done in a Session \"\"\" with", "\"\"\" Random points of X and Y form the training data. aka Dataset", "= [0.00,2.00,4.00,6.00,8.00,10.00,12.00,14.00] #features ys = [-0.82,-0.90,-0.12,0.26,0.31,0.64,1.02,1.00] #labels (actual outputs) \"\"\" Initial values for", "for iteration in range(_ITERATIONS): session.run(optimizer_op) #calling our optimization operator to minimize error slope,", "and ys and train the tensorflow model to adjust the values of m", "\"\"\" optimizer_op = tf.train.GradientDescentOptimizer(learning_rate=0.001).minimize(error) \"\"\" Tensorflow uses a \"session\" to run the above", "values of (x,y) so that the line can be fit properly as we", "X based on the learned value of m and b. \"\"\" import os", "pointset xs and ys and train the tensorflow model to adjust the values", "Y form the training data. aka Dataset (only training. no validation or test)", "no validation or test) \"\"\" xs = [0.00,2.00,4.00,6.00,8.00,10.00,12.00,14.00] #features ys = [-0.82,-0.90,-0.12,0.26,0.31,0.64,1.02,1.00] #labels", "the \"error\" between two given values of (x,y) so that the line can", "(only training. no validation or test) \"\"\" xs = [0.00,2.00,4.00,6.00,8.00,10.00,12.00,14.00] #features ys =", "to train over this operation set we defined above, we use tensorflow Gradient", "would be able to minimize the error to a respecable fit for the", "Tensorflow and Gradient Descent Algorithm This program trains the model to fit two", "\"\"\" for x,y in zip(xs,ys): predicted_y = m*x + b error += (y-predicted_y)**2", "# called in order to minimize the warnings about SSE4.1 instructions. import tensorflow", "of randomly generated pointset xs and ys and train the tensorflow model to", "in order to minimize the warnings about SSE4.1 instructions. import tensorflow as tf", "the above mentioned training steps. So before starting the session it is always", "m_initial = -0.50 b_initial = 1.00 \"\"\" tf.Variable : allows us to create", "x,y in zip(xs,ys): predicted_y = m*x + b error += (y-predicted_y)**2 # this", "intercept = session.run((m,b)) #calling our adjusted values print('slope: ', slope , 'Intercept: ',", "given values of (x,y) so that the line can be fit properly as", "Descent Optimizer which allows us to train over this data set and we", "\"error\".abs Remember Too Small a learning rate would make your training very slow", "cases. \"\"\" optimizer_op = tf.train.GradientDescentOptimizer(learning_rate=0.001).minimize(error) \"\"\" Tensorflow uses a \"session\" to run the", "session.run(init_op) _ITERATIONS = 1000 #number of passes on the dataset for iteration in", "want to make while minimizing the \"cost\" / \"error\".abs Remember Too Small a", "we use tensorflow Gradient Descent Optimizer which allows us to train over this", "the tensorflow model to adjust the values of m and b in order", "found by trying different values. Here we take 0.001 randomly as it usually", "tensorflow Gradient Descent Optimizer which allows us to train over this data set", "would provide very small dataset of randomly generated pointset xs and ys and", "times we would be able to minimize the error to a respecable fit", "above, we use tensorflow Gradient Descent Optimizer which allows us to train over", "trains the model to fit two values, slope(m) and x-intercept(b) in the equation", "can be adjusted in order to learn at each pass on the dataset.", "minimize the \"error\" between two given values of (x,y) so that the line", "to the minimize() function of this optimizer as a parameter.abs here while initialization", "as we minimize the value of distances between our m and b i.e.", "\"\"\" Author: <NAME> Github: github.com/yashbmewada Program for demonstrating simple line fitting using Tensorflow", "learned value of m and b. \"\"\" import os os.environ['TF_CPP_MIN_LOG_LEVEL']='2' # called in", "aka Dataset (only training. no validation or test) \"\"\" xs = [0.00,2.00,4.00,6.00,8.00,10.00,12.00,14.00] #features", "= tf.global_variables_initializer() \"\"\" All the calculations would now be done in a Session", "to minimize error slope, intercept = session.run((m,b)) #calling our adjusted values print('slope: ',", "while minimizing the \"cost\" / \"error\".abs Remember Too Small a learning rate would", "we try to minimize the \"error\" between two given values of (x,y) so", "error = 0.0 \"\"\" We write an operation for calculation of error and", "#labels (actual outputs) \"\"\" Initial values for m and b. These values would", "works in most cases. \"\"\" optimizer_op = tf.train.GradientDescentOptimizer(learning_rate=0.001).minimize(error) \"\"\" Tensorflow uses a \"session\"", "learn at each pass on the dataset. \"\"\" m = tf.Variable(m_initial) b =", "be found by trying different values. Here we take 0.001 randomly as it", "any unknown value Y for a given unknown X based on the learned", "square of difference of error added to the total error 'cost' which we", "y (from \"ys\"). \"\"\" error = 0.0 \"\"\" We write an operation for", "#calling our optimization operator to minimize error slope, intercept = session.run((m,b)) #calling our", "os.environ['TF_CPP_MIN_LOG_LEVEL']='2' # called in order to minimize the warnings about SSE4.1 instructions. import", "make while minimizing the \"cost\" / \"error\".abs Remember Too Small a learning rate", "\"\"\" error = 0.0 \"\"\" We write an operation for calculation of error", "always advisable to initialize variables randomly. \"\"\" init_op = tf.global_variables_initializer() \"\"\" All the", "an optimum solution. Best Learning Rate can be found by trying different values.", "of m and b. \"\"\" import os os.environ['TF_CPP_MIN_LOG_LEVEL']='2' # called in order to", "above dataset point \"\"\" m_initial = -0.50 b_initial = 1.00 \"\"\" tf.Variable :", "rate defines the magnitude OR \"how big\" of a jump we want to", "Learning Rate can be found by trying different values. Here we take 0.001", "tf.train.GradientDescentOptimizer(learning_rate=0.001).minimize(error) \"\"\" Tensorflow uses a \"session\" to run the above mentioned training steps.", "'cost' which we minimize. \"\"\" Now, in order to train over this operation", "in a Session \"\"\" with tf.Session() as session: session.run(init_op) _ITERATIONS = 1000 #number", "two values, slope(m) and x-intercept(b) in the equation of line y=mx+b. Here we", "to fit the above dataset point \"\"\" m_initial = -0.50 b_initial = 1.00", "and x-intercept(b) in the equation of line y=mx+b. Here we would provide very", "and b in order to fit a straight line. This straight line can", "i.e. predicted_y and actual y (from \"ys\"). \"\"\" error = 0.0 \"\"\" We", "the line, we try to minimize the \"error\" between two given values of", "model to adjust the values of m and b in order to fit", "slope, intercept = session.run((m,b)) #calling our adjusted values print('slope: ', slope , 'Intercept:", "the magnitude OR \"how big\" of a jump we want to make while", "in the equation of line y=mx+b. Here we would provide very small dataset", "ys and train the tensorflow model to adjust the values of m and", "value of m and b. \"\"\" import os os.environ['TF_CPP_MIN_LOG_LEVEL']='2' # called in order", "we minimize the value of distances between our m and b i.e. predicted_y", "us to create variables whose values can be adjusted in order to learn", "which allows us to train over this data set and we pass the", "= tf.Variable(b_initial) \"\"\" In order to adjust and fit the line, we try", "starting the session it is always advisable to initialize variables randomly. \"\"\" init_op", "done in a Session \"\"\" with tf.Session() as session: session.run(init_op) _ITERATIONS = 1000", "variables whose values can be adjusted in order to learn at each pass", "minimize the value of distances between our m and b i.e. predicted_y and", "of a jump we want to make while minimizing the \"cost\" / \"error\".abs", "= m*x + b error += (y-predicted_y)**2 # this is the square of", "Here we would provide very small dataset of randomly generated pointset xs and", "adjust the values of m and b in order to fit a straight", "[xs,ys]. Running this over around 1000 times we would be able to minimize", "around 1000 times we would be able to minimize the error to a", "of passes on the dataset for iteration in range(_ITERATIONS): session.run(optimizer_op) #calling our optimization", "equation of line y=mx+b. Here we would provide very small dataset of randomly", "usually works in most cases. \"\"\" optimizer_op = tf.train.GradientDescentOptimizer(learning_rate=0.001).minimize(error) \"\"\" Tensorflow uses a", "to minimize the warnings about SSE4.1 instructions. import tensorflow as tf \"\"\" Random", "it is always advisable to initialize variables randomly. \"\"\" init_op = tf.global_variables_initializer() \"\"\"", "unknown value Y for a given unknown X based on the learned value", "dataset. \"\"\" m = tf.Variable(m_initial) b = tf.Variable(b_initial) \"\"\" In order to adjust", "of error and also iteration over the value of X and Y from", "training never find an optimum solution. Best Learning Rate can be found by", "the \"error\" to the minimize() function of this optimizer as a parameter.abs here", "train over this data set and we pass the \"error\" to the minimize()", "This program trains the model to fit two values, slope(m) and x-intercept(b) in", "#features ys = [-0.82,-0.90,-0.12,0.26,0.31,0.64,1.02,1.00] #labels (actual outputs) \"\"\" Initial values for m and", "randomly generated pointset xs and ys and train the tensorflow model to adjust", "error added to the total error 'cost' which we minimize. \"\"\" Now, in", "xs = [0.00,2.00,4.00,6.00,8.00,10.00,12.00,14.00] #features ys = [-0.82,-0.90,-0.12,0.26,0.31,0.64,1.02,1.00] #labels (actual outputs) \"\"\" Initial values", "order to minimize the warnings about SSE4.1 instructions. import tensorflow as tf \"\"\"", "Running this over around 1000 times we would be able to minimize the", "tf.Variable(m_initial) b = tf.Variable(b_initial) \"\"\" In order to adjust and fit the line,", "\"\"\" We write an operation for calculation of error and also iteration over", "at each pass on the dataset. \"\"\" m = tf.Variable(m_initial) b = tf.Variable(b_initial)", "would make your training very slow and Too big learning rate would make", "value of X and Y from the Dataset [xs,ys]. Running this over around", "y=mx+b. Here we would provide very small dataset of randomly generated pointset xs", "= 1.00 \"\"\" tf.Variable : allows us to create variables whose values can", "big learning rate would make the training never find an optimum solution. Best", "x-intercept(b) in the equation of line y=mx+b. Here we would provide very small", "to predict any unknown value Y for a given unknown X based on", "Descent Algorithm This program trains the model to fit two values, slope(m) and", "and Y form the training data. aka Dataset (only training. no validation or", "provide very small dataset of randomly generated pointset xs and ys and train", "never find an optimum solution. Best Learning Rate can be found by trying", "of error added to the total error 'cost' which we minimize. \"\"\" Now,", "minimize the error to a respecable fit for the line. \"\"\" for x,y", "this data set and we pass the \"error\" to the minimize() function of", "allows us to create variables whose values can be adjusted in order to", "it usually works in most cases. \"\"\" optimizer_op = tf.train.GradientDescentOptimizer(learning_rate=0.001).minimize(error) \"\"\" Tensorflow uses", "values of m and b in order to fit a straight line. This", "github.com/yashbmewada Program for demonstrating simple line fitting using Tensorflow and Gradient Descent Algorithm", "is the square of difference of error added to the total error 'cost'", "the session it is always advisable to initialize variables randomly. \"\"\" init_op =", "jump we want to make while minimizing the \"cost\" / \"error\".abs Remember Too", "operation for calculation of error and also iteration over the value of X", "(x,y) so that the line can be fit properly as we minimize the", "a jump we want to make while minimizing the \"cost\" / \"error\".abs Remember", "line. \"\"\" for x,y in zip(xs,ys): predicted_y = m*x + b error +=", "m and b. These values would be adjusted to fit the above dataset", "\"\"\" Tensorflow uses a \"session\" to run the above mentioned training steps. So", "\"\"\" init_op = tf.global_variables_initializer() \"\"\" All the calculations would now be done in", "used to predict any unknown value Y for a given unknown X based", "different values. Here we take 0.001 randomly as it usually works in most", "the values of m and b in order to fit a straight line.", "set and we pass the \"error\" to the minimize() function of this optimizer", "that the line can be fit properly as we minimize the value of", "This learning rate defines the magnitude OR \"how big\" of a jump we", "adjust and fit the line, we try to minimize the \"error\" between two", "randomly as it usually works in most cases. \"\"\" optimizer_op = tf.train.GradientDescentOptimizer(learning_rate=0.001).minimize(error) \"\"\"", "learning_rate = 0.001. This learning rate defines the magnitude OR \"how big\" of", "be adjusted to fit the above dataset point \"\"\" m_initial = -0.50 b_initial", "pass on the dataset. \"\"\" m = tf.Variable(m_initial) b = tf.Variable(b_initial) \"\"\" In", "and actual y (from \"ys\"). \"\"\" error = 0.0 \"\"\" We write an", "ys = [-0.82,-0.90,-0.12,0.26,0.31,0.64,1.02,1.00] #labels (actual outputs) \"\"\" Initial values for m and b.", "our optimization operator to minimize error slope, intercept = session.run((m,b)) #calling our adjusted", "the Dataset [xs,ys]. Running this over around 1000 times we would be able", "we minimize. \"\"\" Now, in order to train over this operation set we", "\"ys\"). \"\"\" error = 0.0 \"\"\" We write an operation for calculation of", "dataset for iteration in range(_ITERATIONS): session.run(optimizer_op) #calling our optimization operator to minimize error", "line, we try to minimize the \"error\" between two given values of (x,y)", "try to minimize the \"error\" between two given values of (x,y) so that", "Too Small a learning rate would make your training very slow and Too", "1.00 \"\"\" tf.Variable : allows us to create variables whose values can be", "whose values can be adjusted in order to learn at each pass on", "import os os.environ['TF_CPP_MIN_LOG_LEVEL']='2' # called in order to minimize the warnings about SSE4.1", "operation set we defined above, we use tensorflow Gradient Descent Optimizer which allows", "So before starting the session it is always advisable to initialize variables randomly.", "we take 0.001 randomly as it usually works in most cases. \"\"\" optimizer_op", "difference of error added to the total error 'cost' which we minimize. \"\"\"", "here while initialization of the Gradient Descent optimizer, we define a learning_rate =", "predict any unknown value Y for a given unknown X based on the", "uses a \"session\" to run the above mentioned training steps. So before starting", "optimizer as a parameter.abs here while initialization of the Gradient Descent optimizer, we", "the Gradient Descent optimizer, we define a learning_rate = 0.001. This learning rate", "order to learn at each pass on the dataset. \"\"\" m = tf.Variable(m_initial)", "of X and Y form the training data. aka Dataset (only training. no", "the value of distances between our m and b i.e. predicted_y and actual", "+= (y-predicted_y)**2 # this is the square of difference of error added to", "Program for demonstrating simple line fitting using Tensorflow and Gradient Descent Algorithm This", "\"error\" to the minimize() function of this optimizer as a parameter.abs here while", "passes on the dataset for iteration in range(_ITERATIONS): session.run(optimizer_op) #calling our optimization operator", "for m and b. These values would be adjusted to fit the above", "to create variables whose values can be adjusted in order to learn at", "to minimize the \"error\" between two given values of (x,y) so that the", "minimizing the \"cost\" / \"error\".abs Remember Too Small a learning rate would make", "fit the line, we try to minimize the \"error\" between two given values", "dataset of randomly generated pointset xs and ys and train the tensorflow model", "would make the training never find an optimum solution. Best Learning Rate can", "be done in a Session \"\"\" with tf.Session() as session: session.run(init_op) _ITERATIONS =", "0.001. This learning rate defines the magnitude OR \"how big\" of a jump", "this is the square of difference of error added to the total error", "outputs) \"\"\" Initial values for m and b. These values would be adjusted", "while initialization of the Gradient Descent optimizer, we define a learning_rate = 0.001.", "Initial values for m and b. These values would be adjusted to fit", "dataset point \"\"\" m_initial = -0.50 b_initial = 1.00 \"\"\" tf.Variable : allows", "line can further be used to predict any unknown value Y for a", "b error += (y-predicted_y)**2 # this is the square of difference of error", "actual y (from \"ys\"). \"\"\" error = 0.0 \"\"\" We write an operation", "write an operation for calculation of error and also iteration over the value", "os os.environ['TF_CPP_MIN_LOG_LEVEL']='2' # called in order to minimize the warnings about SSE4.1 instructions.", "tf.global_variables_initializer() \"\"\" All the calculations would now be done in a Session \"\"\"", "b. \"\"\" import os os.environ['TF_CPP_MIN_LOG_LEVEL']='2' # called in order to minimize the warnings", "Y from the Dataset [xs,ys]. Running this over around 1000 times we would", "m and b in order to fit a straight line. This straight line", "learning rate would make your training very slow and Too big learning rate", "the warnings about SSE4.1 instructions. import tensorflow as tf \"\"\" Random points of", "m*x + b error += (y-predicted_y)**2 # this is the square of difference", "of difference of error added to the total error 'cost' which we minimize.", "\"\"\" Initial values for m and b. These values would be adjusted to", "of m and b in order to fit a straight line. This straight", "the above dataset point \"\"\" m_initial = -0.50 b_initial = 1.00 \"\"\" tf.Variable", "variables randomly. \"\"\" init_op = tf.global_variables_initializer() \"\"\" All the calculations would now be", "1000 times we would be able to minimize the error to a respecable", "the total error 'cost' which we minimize. \"\"\" Now, in order to train", "to minimize the error to a respecable fit for the line. \"\"\" for", "we defined above, we use tensorflow Gradient Descent Optimizer which allows us to", "our m and b i.e. predicted_y and actual y (from \"ys\"). \"\"\" error", "by trying different values. Here we take 0.001 randomly as it usually works", "operator to minimize error slope, intercept = session.run((m,b)) #calling our adjusted values print('slope:", "the training data. aka Dataset (only training. no validation or test) \"\"\" xs", "train the tensorflow model to adjust the values of m and b in", "take 0.001 randomly as it usually works in most cases. \"\"\" optimizer_op =", "over this data set and we pass the \"error\" to the minimize() function", "for a given unknown X based on the learned value of m and", "tf.Session() as session: session.run(init_op) _ITERATIONS = 1000 #number of passes on the dataset", "\"\"\" tf.Variable : allows us to create variables whose values can be adjusted", "would now be done in a Session \"\"\" with tf.Session() as session: session.run(init_op)", "Dataset [xs,ys]. Running this over around 1000 times we would be able to", "model to fit two values, slope(m) and x-intercept(b) in the equation of line", "magnitude OR \"how big\" of a jump we want to make while minimizing", "error to a respecable fit for the line. \"\"\" for x,y in zip(xs,ys):", "line. This straight line can further be used to predict any unknown value", "and we pass the \"error\" to the minimize() function of this optimizer as", "Session \"\"\" with tf.Session() as session: session.run(init_op) _ITERATIONS = 1000 #number of passes", "= 0.0 \"\"\" We write an operation for calculation of error and also", "point \"\"\" m_initial = -0.50 b_initial = 1.00 \"\"\" tf.Variable : allows us", "to run the above mentioned training steps. So before starting the session it", "range(_ITERATIONS): session.run(optimizer_op) #calling our optimization operator to minimize error slope, intercept = session.run((m,b))", "and b i.e. predicted_y and actual y (from \"ys\"). \"\"\" error = 0.0", "b = tf.Variable(b_initial) \"\"\" In order to adjust and fit the line, we", "to initialize variables randomly. \"\"\" init_op = tf.global_variables_initializer() \"\"\" All the calculations would", "values, slope(m) and x-intercept(b) in the equation of line y=mx+b. Here we would", "make the training never find an optimum solution. Best Learning Rate can be", "and Y from the Dataset [xs,ys]. Running this over around 1000 times we", "small dataset of randomly generated pointset xs and ys and train the tensorflow", "a respecable fit for the line. \"\"\" for x,y in zip(xs,ys): predicted_y =", "and fit the line, we try to minimize the \"error\" between two given", "Tensorflow uses a \"session\" to run the above mentioned training steps. So before", "straight line. This straight line can further be used to predict any unknown", "X and Y from the Dataset [xs,ys]. Running this over around 1000 times", "to adjust and fit the line, we try to minimize the \"error\" between", "zip(xs,ys): predicted_y = m*x + b error += (y-predicted_y)**2 # this is the", "the error to a respecable fit for the line. \"\"\" for x,y in", "learning rate would make the training never find an optimum solution. Best Learning", "training. no validation or test) \"\"\" xs = [0.00,2.00,4.00,6.00,8.00,10.00,12.00,14.00] #features ys = [-0.82,-0.90,-0.12,0.26,0.31,0.64,1.02,1.00]", "session it is always advisable to initialize variables randomly. \"\"\" init_op = tf.global_variables_initializer()", "tf.Variable : allows us to create variables whose values can be adjusted in", "can be fit properly as we minimize the value of distances between our", "to fit a straight line. This straight line can further be used to", ": allows us to create variables whose values can be adjusted in order", "on the learned value of m and b. \"\"\" import os os.environ['TF_CPP_MIN_LOG_LEVEL']='2' #", "validation or test) \"\"\" xs = [0.00,2.00,4.00,6.00,8.00,10.00,12.00,14.00] #features ys = [-0.82,-0.90,-0.12,0.26,0.31,0.64,1.02,1.00] #labels (actual", "given unknown X based on the learned value of m and b. \"\"\"", "from the Dataset [xs,ys]. Running this over around 1000 times we would be", "the line. \"\"\" for x,y in zip(xs,ys): predicted_y = m*x + b error", "for the line. \"\"\" for x,y in zip(xs,ys): predicted_y = m*x + b", "data. aka Dataset (only training. no validation or test) \"\"\" xs = [0.00,2.00,4.00,6.00,8.00,10.00,12.00,14.00]", "= 0.001. This learning rate defines the magnitude OR \"how big\" of a", "predicted_y and actual y (from \"ys\"). \"\"\" error = 0.0 \"\"\" We write", "Optimizer which allows us to train over this data set and we pass", "to a respecable fit for the line. \"\"\" for x,y in zip(xs,ys): predicted_y", "fitting using Tensorflow and Gradient Descent Algorithm This program trains the model to", "+ b error += (y-predicted_y)**2 # this is the square of difference of", "OR \"how big\" of a jump we want to make while minimizing the", "minimize the warnings about SSE4.1 instructions. import tensorflow as tf \"\"\" Random points", "allows us to train over this data set and we pass the \"error\"", "steps. So before starting the session it is always advisable to initialize variables", "between two given values of (x,y) so that the line can be fit", "fit properly as we minimize the value of distances between our m and", "SSE4.1 instructions. import tensorflow as tf \"\"\" Random points of X and Y", "respecable fit for the line. \"\"\" for x,y in zip(xs,ys): predicted_y = m*x", "so that the line can be fit properly as we minimize the value", "program trains the model to fit two values, slope(m) and x-intercept(b) in the", "tf.Variable(b_initial) \"\"\" In order to adjust and fit the line, we try to", "a straight line. This straight line can further be used to predict any", "further be used to predict any unknown value Y for a given unknown", "to the total error 'cost' which we minimize. \"\"\" Now, in order to", "= tf.Variable(m_initial) b = tf.Variable(b_initial) \"\"\" In order to adjust and fit the", "data set and we pass the \"error\" to the minimize() function of this", "be able to minimize the error to a respecable fit for the line.", "optimization operator to minimize error slope, intercept = session.run((m,b)) #calling our adjusted values", "as a parameter.abs here while initialization of the Gradient Descent optimizer, we define", "in range(_ITERATIONS): session.run(optimizer_op) #calling our optimization operator to minimize error slope, intercept =", "<NAME> Github: github.com/yashbmewada Program for demonstrating simple line fitting using Tensorflow and Gradient", "\"\"\" m_initial = -0.50 b_initial = 1.00 \"\"\" tf.Variable : allows us to", "the calculations would now be done in a Session \"\"\" with tf.Session() as", "between our m and b i.e. predicted_y and actual y (from \"ys\"). \"\"\"", "of the Gradient Descent optimizer, we define a learning_rate = 0.001. This learning", "(from \"ys\"). \"\"\" error = 0.0 \"\"\" We write an operation for calculation", "the equation of line y=mx+b. Here we would provide very small dataset of", "minimize() function of this optimizer as a parameter.abs here while initialization of the", "distances between our m and b i.e. predicted_y and actual y (from \"ys\").", "and also iteration over the value of X and Y from the Dataset", "Descent optimizer, we define a learning_rate = 0.001. This learning rate defines the", "advisable to initialize variables randomly. \"\"\" init_op = tf.global_variables_initializer() \"\"\" All the calculations", "value Y for a given unknown X based on the learned value of", "initialize variables randomly. \"\"\" init_op = tf.global_variables_initializer() \"\"\" All the calculations would now", "over this operation set we defined above, we use tensorflow Gradient Descent Optimizer", "training data. aka Dataset (only training. no validation or test) \"\"\" xs =", "the learned value of m and b. \"\"\" import os os.environ['TF_CPP_MIN_LOG_LEVEL']='2' # called", "a Session \"\"\" with tf.Session() as session: session.run(init_op) _ITERATIONS = 1000 #number of", "generated pointset xs and ys and train the tensorflow model to adjust the", "using Tensorflow and Gradient Descent Algorithm This program trains the model to fit", "calculations would now be done in a Session \"\"\" with tf.Session() as session:", "initialization of the Gradient Descent optimizer, we define a learning_rate = 0.001. This", "be fit properly as we minimize the value of distances between our m", "session.run(optimizer_op) #calling our optimization operator to minimize error slope, intercept = session.run((m,b)) #calling", "or test) \"\"\" xs = [0.00,2.00,4.00,6.00,8.00,10.00,12.00,14.00] #features ys = [-0.82,-0.90,-0.12,0.26,0.31,0.64,1.02,1.00] #labels (actual outputs)", "before starting the session it is always advisable to initialize variables randomly. \"\"\"", "most cases. \"\"\" optimizer_op = tf.train.GradientDescentOptimizer(learning_rate=0.001).minimize(error) \"\"\" Tensorflow uses a \"session\" to run", "above mentioned training steps. So before starting the session it is always advisable", "and b. These values would be adjusted to fit the above dataset point", "we define a learning_rate = 0.001. This learning rate defines the magnitude OR", "also iteration over the value of X and Y from the Dataset [xs,ys].", "based on the learned value of m and b. \"\"\" import os os.environ['TF_CPP_MIN_LOG_LEVEL']='2'", "training steps. So before starting the session it is always advisable to initialize", "simple line fitting using Tensorflow and Gradient Descent Algorithm This program trains the", "pass the \"error\" to the minimize() function of this optimizer as a parameter.abs", "of this optimizer as a parameter.abs here while initialization of the Gradient Descent", "which we minimize. \"\"\" Now, in order to train over this operation set", "to adjust the values of m and b in order to fit a", "order to train over this operation set we defined above, we use tensorflow", "optimizer, we define a learning_rate = 0.001. This learning rate defines the magnitude", "# this is the square of difference of error added to the total", "b_initial = 1.00 \"\"\" tf.Variable : allows us to create variables whose values", "defined above, we use tensorflow Gradient Descent Optimizer which allows us to train", "learning rate defines the magnitude OR \"how big\" of a jump we want", "Small a learning rate would make your training very slow and Too big", "order to adjust and fit the line, we try to minimize the \"error\"", "Gradient Descent Algorithm This program trains the model to fit two values, slope(m)", "predicted_y = m*x + b error += (y-predicted_y)**2 # this is the square", "the \"cost\" / \"error\".abs Remember Too Small a learning rate would make your", "[-0.82,-0.90,-0.12,0.26,0.31,0.64,1.02,1.00] #labels (actual outputs) \"\"\" Initial values for m and b. These values", "we would be able to minimize the error to a respecable fit for", "able to minimize the error to a respecable fit for the line. \"\"\"", "your training very slow and Too big learning rate would make the training", "can be found by trying different values. Here we take 0.001 randomly as", "this optimizer as a parameter.abs here while initialization of the Gradient Descent optimizer,", "optimum solution. Best Learning Rate can be found by trying different values. Here", "to fit two values, slope(m) and x-intercept(b) in the equation of line y=mx+b.", "and Gradient Descent Algorithm This program trains the model to fit two values,", "value of distances between our m and b i.e. predicted_y and actual y", "init_op = tf.global_variables_initializer() \"\"\" All the calculations would now be done in a", "= [-0.82,-0.90,-0.12,0.26,0.31,0.64,1.02,1.00] #labels (actual outputs) \"\"\" Initial values for m and b. These", "Dataset (only training. no validation or test) \"\"\" xs = [0.00,2.00,4.00,6.00,8.00,10.00,12.00,14.00] #features ys", "train over this operation set we defined above, we use tensorflow Gradient Descent", "defines the magnitude OR \"how big\" of a jump we want to make", "the value of X and Y from the Dataset [xs,ys]. Running this over", "for calculation of error and also iteration over the value of X and", "Remember Too Small a learning rate would make your training very slow and", "to learn at each pass on the dataset. \"\"\" m = tf.Variable(m_initial) b", "values. Here we take 0.001 randomly as it usually works in most cases.", "error slope, intercept = session.run((m,b)) #calling our adjusted values print('slope: ', slope ,", "\"session\" to run the above mentioned training steps. So before starting the session", "error += (y-predicted_y)**2 # this is the square of difference of error added", "big\" of a jump we want to make while minimizing the \"cost\" /", "define a learning_rate = 0.001. This learning rate defines the magnitude OR \"how", "minimize. \"\"\" Now, in order to train over this operation set we defined", "for x,y in zip(xs,ys): predicted_y = m*x + b error += (y-predicted_y)**2 #", "solution. Best Learning Rate can be found by trying different values. Here we", "\"\"\" xs = [0.00,2.00,4.00,6.00,8.00,10.00,12.00,14.00] #features ys = [-0.82,-0.90,-0.12,0.26,0.31,0.64,1.02,1.00] #labels (actual outputs) \"\"\" Initial", "and train the tensorflow model to adjust the values of m and b", "a \"session\" to run the above mentioned training steps. So before starting the", "\"how big\" of a jump we want to make while minimizing the \"cost\"", "order to fit a straight line. This straight line can further be used", "\"\"\" import os os.environ['TF_CPP_MIN_LOG_LEVEL']='2' # called in order to minimize the warnings about", "adjusted in order to learn at each pass on the dataset. \"\"\" m", "tensorflow as tf \"\"\" Random points of X and Y form the training", "(actual outputs) \"\"\" Initial values for m and b. These values would be", "in zip(xs,ys): predicted_y = m*x + b error += (y-predicted_y)**2 # this is", "fit for the line. \"\"\" for x,y in zip(xs,ys): predicted_y = m*x +", "rate would make the training never find an optimum solution. Best Learning Rate", "we want to make while minimizing the \"cost\" / \"error\".abs Remember Too Small", "m and b. \"\"\" import os os.environ['TF_CPP_MIN_LOG_LEVEL']='2' # called in order to minimize", "set we defined above, we use tensorflow Gradient Descent Optimizer which allows us", "Best Learning Rate can be found by trying different values. Here we take", "\"\"\" In order to adjust and fit the line, we try to minimize", "error and also iteration over the value of X and Y from the", "make your training very slow and Too big learning rate would make the", "properly as we minimize the value of distances between our m and b", "to make while minimizing the \"cost\" / \"error\".abs Remember Too Small a learning", "very slow and Too big learning rate would make the training never find", "we would provide very small dataset of randomly generated pointset xs and ys", "0.001 randomly as it usually works in most cases. \"\"\" optimizer_op = tf.train.GradientDescentOptimizer(learning_rate=0.001).minimize(error)", "in most cases. \"\"\" optimizer_op = tf.train.GradientDescentOptimizer(learning_rate=0.001).minimize(error) \"\"\" Tensorflow uses a \"session\" to", "b in order to fit a straight line. This straight line can further", "points of X and Y form the training data. aka Dataset (only training.", "(y-predicted_y)**2 # this is the square of difference of error added to the", "These values would be adjusted to fit the above dataset point \"\"\" m_initial", "demonstrating simple line fitting using Tensorflow and Gradient Descent Algorithm This program trains", "a learning_rate = 0.001. This learning rate defines the magnitude OR \"how big\"", "use tensorflow Gradient Descent Optimizer which allows us to train over this data", "All the calculations would now be done in a Session \"\"\" with tf.Session()", "iteration over the value of X and Y from the Dataset [xs,ys]. Running", "now be done in a Session \"\"\" with tf.Session() as session: session.run(init_op) _ITERATIONS", "fit two values, slope(m) and x-intercept(b) in the equation of line y=mx+b. Here", "values would be adjusted to fit the above dataset point \"\"\" m_initial =", "error 'cost' which we minimize. \"\"\" Now, in order to train over this", "and Too big learning rate would make the training never find an optimum", "of distances between our m and b i.e. predicted_y and actual y (from", "the model to fit two values, slope(m) and x-intercept(b) in the equation of", "tensorflow model to adjust the values of m and b in order to", "= 1000 #number of passes on the dataset for iteration in range(_ITERATIONS): session.run(optimizer_op)", "this operation set we defined above, we use tensorflow Gradient Descent Optimizer which", "fit a straight line. This straight line can further be used to predict", "a parameter.abs here while initialization of the Gradient Descent optimizer, we define a", "the line can be fit properly as we minimize the value of distances", "slope(m) and x-intercept(b) in the equation of line y=mx+b. Here we would provide", "the dataset for iteration in range(_ITERATIONS): session.run(optimizer_op) #calling our optimization operator to minimize" ]
[]
[]
[ "= args.file_name splitter = args.splitter #fields_num = args.fields_num max_lines = args.max_lines if not", "= 50000, help = 'max lines number in one excel') def download_from_txt(): #", "Created on Wed Jan 23 17:20:22 2019 convert txt to excel @author: zyb_as", "+ '.xls' # 创建表 workbook = xlwt.Workbook(encoding = 'utf-8') worksheet = workbook.add_sheet('temp', cell_overwrite_ok", "exists\") excel_file = '' if file_name[-4:] == '.txt': excel_file = file_name[:-4] + '.xls'", "splitter for each line in the txt file.') #parser.add_argument('--fields_num', type = int, default", "file need to be convert does't exists\") excel_file = '' if file_name[-4:] ==", "1 cur_excel_file = excel_file[:-4] + '_' + str(xls_index) + '.xls' workbook = xlwt.Workbook(encoding", "cnt = 0 item = line.split(splitter) print(cnt) for idx, it in enumerate(item): worksheet.write(cnt,", "the txt file.') #parser.add_argument('--fields_num', type = int, default = 1, # help =", "= 0 item = line.split(splitter) print(cnt) for idx, it in enumerate(item): worksheet.write(cnt, idx,", "'the path of the txt file') parser.add_argument('--splitter', type = str, default = '\\t',", "set options parser = argparse.ArgumentParser(description = 'convert txt to excel', usage = textwrap.dedent('''\\", "= excel_file[:-4] + '_' + str(xls_index) + '.xls' workbook = xlwt.Workbook(encoding = 'utf-8')", "'Row 0, Column 0 Value') for line in open(file_name, 'r').readlines(): if cnt ==", "item = line.split(splitter) print(cnt) for idx, it in enumerate(item): worksheet.write(cnt, idx, it.decode('utf-8', 'ignore'))", "enumerate(item): worksheet.write(cnt, idx, it.decode('utf-8', 'ignore')) cnt += 1 if cnt <= max_lines: workbook.save(cur_excel_file)", "0, label = 'Row 0, Column 0 Value') for line in open(file_name, 'r').readlines():", "0, Column 0 Value') for line in open(file_name, 'r').readlines(): if cnt == max_lines:", "= xlwt.Workbook(encoding = 'utf-8') worksheet = workbook.add_sheet('temp') cnt = 0 item = line.split(splitter)", "= 'the path of the txt file') parser.add_argument('--splitter', type = str, default =", "in one excel') def download_from_txt(): # get options args = parser.parse_args() file_name =", "= 'the splitter for each line in the txt file.') #parser.add_argument('--fields_num', type =", "path of the txt file') parser.add_argument('--splitter', type = str, default = '\\t', help", "excel_file = file_name + '.xls' if splitter == '\\\\t': splitter = '\\t' cnt", "'.txt': excel_file = file_name[:-4] + '.xls' else: excel_file = file_name + '.xls' if", "command example: python %(prog)s --file_name='test.txt' --splitter='\\\\t' '''), formatter_class = argparse.RawTextHelpFormatter) parser.add_argument('--file_name', type =", "max_lines = args.max_lines if not os.path.exists(file_name): print(\"ERROR! the file need to be convert", "'ignore')) cnt += 1 if cnt <= max_lines: workbook.save(cur_excel_file) if __name__ == \"__main__\":", "print(cnt) for idx, it in enumerate(item): worksheet.write(cnt, idx, it.decode('utf-8', 'ignore')) cnt += 1", "str, default = '\\t', help = 'the splitter for each line in the", "excel_file = file_name[:-4] + '.xls' else: excel_file = file_name + '.xls' if splitter", "argparse.RawTextHelpFormatter) parser.add_argument('--file_name', type = str, default = 'test.txt', help = 'the path of", "xlwt.Workbook(encoding = 'utf-8') worksheet = workbook.add_sheet('temp', cell_overwrite_ok = True) worksheet.write(0, 0, label =", "utf-8 -*- \"\"\" Created on Wed Jan 23 17:20:22 2019 convert txt to", "import argparse, textwrap import xlwt # set options parser = argparse.ArgumentParser(description = 'convert", "help = 'max lines number in one excel') def download_from_txt(): # get options", "worksheet.write(cnt, idx, it.decode('utf-8', 'ignore')) cnt += 1 if cnt <= max_lines: workbook.save(cur_excel_file) if", "'' if file_name[-4:] == '.txt': excel_file = file_name[:-4] + '.xls' else: excel_file =", "cnt == max_lines: workbook.save(cur_excel_file) xls_index += 1 cur_excel_file = excel_file[:-4] + '_' +", "+ '_' + str(xls_index) + '.xls' # 创建表 workbook = xlwt.Workbook(encoding = 'utf-8')", "+ '.xls' workbook = xlwt.Workbook(encoding = 'utf-8') worksheet = workbook.add_sheet('temp') cnt = 0", "= workbook.add_sheet('temp') cnt = 0 item = line.split(splitter) print(cnt) for idx, it in", "type = int, default = 1, # help = 'the fields number each", "idx, it.decode('utf-8', 'ignore')) cnt += 1 if cnt <= max_lines: workbook.save(cur_excel_file) if __name__", "type = str, default = 'test.txt', help = 'the path of the txt", "0 Value') for line in open(file_name, 'r').readlines(): if cnt == max_lines: workbook.save(cur_excel_file) xls_index", "txt to excel @author: zyb_as \"\"\" import os import argparse, textwrap import xlwt", "options parser = argparse.ArgumentParser(description = 'convert txt to excel', usage = textwrap.dedent('''\\ command", "file_name + '.xls' if splitter == '\\\\t': splitter = '\\t' cnt = 0", "1, # help = 'the fields number each line.') parser.add_argument('--max_lines', type = int,", "it.decode('utf-8', 'ignore')) cnt += 1 if cnt <= max_lines: workbook.save(cur_excel_file) if __name__ ==", "parser.add_argument('--splitter', type = str, default = '\\t', help = 'the splitter for each", "#parser.add_argument('--fields_num', type = int, default = 1, # help = 'the fields number", "does't exists\") excel_file = '' if file_name[-4:] == '.txt': excel_file = file_name[:-4] +", "cnt = 0 xls_index = 0 cur_excel_file = excel_file[:-4] + '_' + str(xls_index)", "= file_name + '.xls' if splitter == '\\\\t': splitter = '\\t' cnt =", "= 'convert txt to excel', usage = textwrap.dedent('''\\ command example: python %(prog)s --file_name='test.txt'", "worksheet = workbook.add_sheet('temp') cnt = 0 item = line.split(splitter) print(cnt) for idx, it", "+ '_' + str(xls_index) + '.xls' workbook = xlwt.Workbook(encoding = 'utf-8') worksheet =", "cur_excel_file = excel_file[:-4] + '_' + str(xls_index) + '.xls' workbook = xlwt.Workbook(encoding =", "+ str(xls_index) + '.xls' # 创建表 workbook = xlwt.Workbook(encoding = 'utf-8') worksheet =", "parser = argparse.ArgumentParser(description = 'convert txt to excel', usage = textwrap.dedent('''\\ command example:", "'_' + str(xls_index) + '.xls' workbook = xlwt.Workbook(encoding = 'utf-8') worksheet = workbook.add_sheet('temp')", "'utf-8') worksheet = workbook.add_sheet('temp', cell_overwrite_ok = True) worksheet.write(0, 0, label = 'Row 0,", "Jan 23 17:20:22 2019 convert txt to excel @author: zyb_as \"\"\" import os", "for each line in the txt file.') #parser.add_argument('--fields_num', type = int, default =", "be convert does't exists\") excel_file = '' if file_name[-4:] == '.txt': excel_file =", "= args.splitter #fields_num = args.fields_num max_lines = args.max_lines if not os.path.exists(file_name): print(\"ERROR! the", "excel', usage = textwrap.dedent('''\\ command example: python %(prog)s --file_name='test.txt' --splitter='\\\\t' '''), formatter_class =", "default = 1, # help = 'the fields number each line.') parser.add_argument('--max_lines', type", "on Wed Jan 23 17:20:22 2019 convert txt to excel @author: zyb_as \"\"\"", "= textwrap.dedent('''\\ command example: python %(prog)s --file_name='test.txt' --splitter='\\\\t' '''), formatter_class = argparse.RawTextHelpFormatter) parser.add_argument('--file_name',", "help = 'the path of the txt file') parser.add_argument('--splitter', type = str, default", "parser.add_argument('--max_lines', type = int, default = 50000, help = 'max lines number in", "worksheet.write(0, 0, label = 'Row 0, Column 0 Value') for line in open(file_name,", "--file_name='test.txt' --splitter='\\\\t' '''), formatter_class = argparse.RawTextHelpFormatter) parser.add_argument('--file_name', type = str, default = 'test.txt',", "file_name[:-4] + '.xls' else: excel_file = file_name + '.xls' if splitter == '\\\\t':", "else: excel_file = file_name + '.xls' if splitter == '\\\\t': splitter = '\\t'", "= 0 xls_index = 0 cur_excel_file = excel_file[:-4] + '_' + str(xls_index) +", "'.xls' workbook = xlwt.Workbook(encoding = 'utf-8') worksheet = workbook.add_sheet('temp') cnt = 0 item", "+= 1 cur_excel_file = excel_file[:-4] + '_' + str(xls_index) + '.xls' workbook =", "def download_from_txt(): # get options args = parser.parse_args() file_name = args.file_name splitter =", "Column 0 Value') for line in open(file_name, 'r').readlines(): if cnt == max_lines: workbook.save(cur_excel_file)", "to excel @author: zyb_as \"\"\" import os import argparse, textwrap import xlwt #", "the txt file') parser.add_argument('--splitter', type = str, default = '\\t', help = 'the", "one excel') def download_from_txt(): # get options args = parser.parse_args() file_name = args.file_name", "max_lines: workbook.save(cur_excel_file) xls_index += 1 cur_excel_file = excel_file[:-4] + '_' + str(xls_index) +", "= 'utf-8') worksheet = workbook.add_sheet('temp') cnt = 0 item = line.split(splitter) print(cnt) for", "parser.add_argument('--file_name', type = str, default = 'test.txt', help = 'the path of the", "file.') #parser.add_argument('--fields_num', type = int, default = 1, # help = 'the fields", "== '.txt': excel_file = file_name[:-4] + '.xls' else: excel_file = file_name + '.xls'", "# get options args = parser.parse_args() file_name = args.file_name splitter = args.splitter #fields_num", "file_name[-4:] == '.txt': excel_file = file_name[:-4] + '.xls' else: excel_file = file_name +", "xls_index = 0 cur_excel_file = excel_file[:-4] + '_' + str(xls_index) + '.xls' #", "= excel_file[:-4] + '_' + str(xls_index) + '.xls' # 创建表 workbook = xlwt.Workbook(encoding", "str(xls_index) + '.xls' # 创建表 workbook = xlwt.Workbook(encoding = 'utf-8') worksheet = workbook.add_sheet('temp',", "worksheet = workbook.add_sheet('temp', cell_overwrite_ok = True) worksheet.write(0, 0, label = 'Row 0, Column", "lines number in one excel') def download_from_txt(): # get options args = parser.parse_args()", "= args.fields_num max_lines = args.max_lines if not os.path.exists(file_name): print(\"ERROR! the file need to", "each line in the txt file.') #parser.add_argument('--fields_num', type = int, default = 1,", "= 'utf-8') worksheet = workbook.add_sheet('temp', cell_overwrite_ok = True) worksheet.write(0, 0, label = 'Row", "= 0 cur_excel_file = excel_file[:-4] + '_' + str(xls_index) + '.xls' # 创建表", "each line.') parser.add_argument('--max_lines', type = int, default = 50000, help = 'max lines", "args.max_lines if not os.path.exists(file_name): print(\"ERROR! the file need to be convert does't exists\")", "line in open(file_name, 'r').readlines(): if cnt == max_lines: workbook.save(cur_excel_file) xls_index += 1 cur_excel_file", "line in the txt file.') #parser.add_argument('--fields_num', type = int, default = 1, #", "= '' if file_name[-4:] == '.txt': excel_file = file_name[:-4] + '.xls' else: excel_file", "workbook.save(cur_excel_file) xls_index += 1 cur_excel_file = excel_file[:-4] + '_' + str(xls_index) + '.xls'", "args.file_name splitter = args.splitter #fields_num = args.fields_num max_lines = args.max_lines if not os.path.exists(file_name):", "coding: utf-8 -*- \"\"\" Created on Wed Jan 23 17:20:22 2019 convert txt", "+ str(xls_index) + '.xls' workbook = xlwt.Workbook(encoding = 'utf-8') worksheet = workbook.add_sheet('temp') cnt", "need to be convert does't exists\") excel_file = '' if file_name[-4:] == '.txt':", "'utf-8') worksheet = workbook.add_sheet('temp') cnt = 0 item = line.split(splitter) print(cnt) for idx,", "# set options parser = argparse.ArgumentParser(description = 'convert txt to excel', usage =", "= args.max_lines if not os.path.exists(file_name): print(\"ERROR! the file need to be convert does't", "excel_file[:-4] + '_' + str(xls_index) + '.xls' # 创建表 workbook = xlwt.Workbook(encoding =", "argparse, textwrap import xlwt # set options parser = argparse.ArgumentParser(description = 'convert txt", "0 cur_excel_file = excel_file[:-4] + '_' + str(xls_index) + '.xls' # 创建表 workbook", "'r').readlines(): if cnt == max_lines: workbook.save(cur_excel_file) xls_index += 1 cur_excel_file = excel_file[:-4] +", "if file_name[-4:] == '.txt': excel_file = file_name[:-4] + '.xls' else: excel_file = file_name", "--splitter='\\\\t' '''), formatter_class = argparse.RawTextHelpFormatter) parser.add_argument('--file_name', type = str, default = 'test.txt', help", "number in one excel') def download_from_txt(): # get options args = parser.parse_args() file_name", "= 1, # help = 'the fields number each line.') parser.add_argument('--max_lines', type =", "os.path.exists(file_name): print(\"ERROR! the file need to be convert does't exists\") excel_file = ''", "textwrap.dedent('''\\ command example: python %(prog)s --file_name='test.txt' --splitter='\\\\t' '''), formatter_class = argparse.RawTextHelpFormatter) parser.add_argument('--file_name', type", "import xlwt # set options parser = argparse.ArgumentParser(description = 'convert txt to excel',", "'_' + str(xls_index) + '.xls' # 创建表 workbook = xlwt.Workbook(encoding = 'utf-8') worksheet", "# 创建表 workbook = xlwt.Workbook(encoding = 'utf-8') worksheet = workbook.add_sheet('temp', cell_overwrite_ok = True)", "for idx, it in enumerate(item): worksheet.write(cnt, idx, it.decode('utf-8', 'ignore')) cnt += 1 if", "= line.split(splitter) print(cnt) for idx, it in enumerate(item): worksheet.write(cnt, idx, it.decode('utf-8', 'ignore')) cnt", "convert txt to excel @author: zyb_as \"\"\" import os import argparse, textwrap import", "= parser.parse_args() file_name = args.file_name splitter = args.splitter #fields_num = args.fields_num max_lines =", "'convert txt to excel', usage = textwrap.dedent('''\\ command example: python %(prog)s --file_name='test.txt' --splitter='\\\\t'", "line.split(splitter) print(cnt) for idx, it in enumerate(item): worksheet.write(cnt, idx, it.decode('utf-8', 'ignore')) cnt +=", "help = 'the splitter for each line in the txt file.') #parser.add_argument('--fields_num', type", "the file need to be convert does't exists\") excel_file = '' if file_name[-4:]", "txt file') parser.add_argument('--splitter', type = str, default = '\\t', help = 'the splitter", "'max lines number in one excel') def download_from_txt(): # get options args =", "args.splitter #fields_num = args.fields_num max_lines = args.max_lines if not os.path.exists(file_name): print(\"ERROR! the file", "'.xls' else: excel_file = file_name + '.xls' if splitter == '\\\\t': splitter =", "parser.parse_args() file_name = args.file_name splitter = args.splitter #fields_num = args.fields_num max_lines = args.max_lines", "default = '\\t', help = 'the splitter for each line in the txt", "cnt += 1 if cnt <= max_lines: workbook.save(cur_excel_file) if __name__ == \"__main__\": download_from_txt()", "-*- coding: utf-8 -*- \"\"\" Created on Wed Jan 23 17:20:22 2019 convert", "excel @author: zyb_as \"\"\" import os import argparse, textwrap import xlwt # set", "file') parser.add_argument('--splitter', type = str, default = '\\t', help = 'the splitter for", "convert does't exists\") excel_file = '' if file_name[-4:] == '.txt': excel_file = file_name[:-4]", "= str, default = 'test.txt', help = 'the path of the txt file')", "'\\t' cnt = 0 xls_index = 0 cur_excel_file = excel_file[:-4] + '_' +", "in open(file_name, 'r').readlines(): if cnt == max_lines: workbook.save(cur_excel_file) xls_index += 1 cur_excel_file =", "print(\"ERROR! the file need to be convert does't exists\") excel_file = '' if", "not os.path.exists(file_name): print(\"ERROR! the file need to be convert does't exists\") excel_file =", "to excel', usage = textwrap.dedent('''\\ command example: python %(prog)s --file_name='test.txt' --splitter='\\\\t' '''), formatter_class", "int, default = 50000, help = 'max lines number in one excel') def", "xls_index += 1 cur_excel_file = excel_file[:-4] + '_' + str(xls_index) + '.xls' workbook", "workbook = xlwt.Workbook(encoding = 'utf-8') worksheet = workbook.add_sheet('temp') cnt = 0 item =", "usage = textwrap.dedent('''\\ command example: python %(prog)s --file_name='test.txt' --splitter='\\\\t' '''), formatter_class = argparse.RawTextHelpFormatter)", "'\\\\t': splitter = '\\t' cnt = 0 xls_index = 0 cur_excel_file = excel_file[:-4]", "= 'max lines number in one excel') def download_from_txt(): # get options args", "args = parser.parse_args() file_name = args.file_name splitter = args.splitter #fields_num = args.fields_num max_lines", "= workbook.add_sheet('temp', cell_overwrite_ok = True) worksheet.write(0, 0, label = 'Row 0, Column 0", "python %(prog)s --file_name='test.txt' --splitter='\\\\t' '''), formatter_class = argparse.RawTextHelpFormatter) parser.add_argument('--file_name', type = str, default", "label = 'Row 0, Column 0 Value') for line in open(file_name, 'r').readlines(): if", "workbook.add_sheet('temp', cell_overwrite_ok = True) worksheet.write(0, 0, label = 'Row 0, Column 0 Value')", "type = str, default = '\\t', help = 'the splitter for each line", "= int, default = 50000, help = 'max lines number in one excel')", "+ '.xls' if splitter == '\\\\t': splitter = '\\t' cnt = 0 xls_index", "number each line.') parser.add_argument('--max_lines', type = int, default = 50000, help = 'max", "'''), formatter_class = argparse.RawTextHelpFormatter) parser.add_argument('--file_name', type = str, default = 'test.txt', help =", "# help = 'the fields number each line.') parser.add_argument('--max_lines', type = int, default", "txt file.') #parser.add_argument('--fields_num', type = int, default = 1, # help = 'the", "0 xls_index = 0 cur_excel_file = excel_file[:-4] + '_' + str(xls_index) + '.xls'", "cell_overwrite_ok = True) worksheet.write(0, 0, label = 'Row 0, Column 0 Value') for", "xlwt.Workbook(encoding = 'utf-8') worksheet = workbook.add_sheet('temp') cnt = 0 item = line.split(splitter) print(cnt)", "= file_name[:-4] + '.xls' else: excel_file = file_name + '.xls' if splitter ==", "@author: zyb_as \"\"\" import os import argparse, textwrap import xlwt # set options", "file_name = args.file_name splitter = args.splitter #fields_num = args.fields_num max_lines = args.max_lines if", "workbook.add_sheet('temp') cnt = 0 item = line.split(splitter) print(cnt) for idx, it in enumerate(item):", "-*- \"\"\" Created on Wed Jan 23 17:20:22 2019 convert txt to excel", "\"\"\" import os import argparse, textwrap import xlwt # set options parser =", "2019 convert txt to excel @author: zyb_as \"\"\" import os import argparse, textwrap", "os import argparse, textwrap import xlwt # set options parser = argparse.ArgumentParser(description =", "= '\\t' cnt = 0 xls_index = 0 cur_excel_file = excel_file[:-4] + '_'", "Value') for line in open(file_name, 'r').readlines(): if cnt == max_lines: workbook.save(cur_excel_file) xls_index +=", "= 'Row 0, Column 0 Value') for line in open(file_name, 'r').readlines(): if cnt", "str(xls_index) + '.xls' workbook = xlwt.Workbook(encoding = 'utf-8') worksheet = workbook.add_sheet('temp') cnt =", "if splitter == '\\\\t': splitter = '\\t' cnt = 0 xls_index = 0", "argparse.ArgumentParser(description = 'convert txt to excel', usage = textwrap.dedent('''\\ command example: python %(prog)s", "example: python %(prog)s --file_name='test.txt' --splitter='\\\\t' '''), formatter_class = argparse.RawTextHelpFormatter) parser.add_argument('--file_name', type = str,", "int, default = 1, # help = 'the fields number each line.') parser.add_argument('--max_lines',", "== '\\\\t': splitter = '\\t' cnt = 0 xls_index = 0 cur_excel_file =", "23 17:20:22 2019 convert txt to excel @author: zyb_as \"\"\" import os import", "download_from_txt(): # get options args = parser.parse_args() file_name = args.file_name splitter = args.splitter", "= True) worksheet.write(0, 0, label = 'Row 0, Column 0 Value') for line", "'test.txt', help = 'the path of the txt file') parser.add_argument('--splitter', type = str,", "of the txt file') parser.add_argument('--splitter', type = str, default = '\\t', help =", "splitter = args.splitter #fields_num = args.fields_num max_lines = args.max_lines if not os.path.exists(file_name): print(\"ERROR!", "str, default = 'test.txt', help = 'the path of the txt file') parser.add_argument('--splitter',", "'\\t', help = 'the splitter for each line in the txt file.') #parser.add_argument('--fields_num',", "type = int, default = 50000, help = 'max lines number in one", "excel_file[:-4] + '_' + str(xls_index) + '.xls' workbook = xlwt.Workbook(encoding = 'utf-8') worksheet", "创建表 workbook = xlwt.Workbook(encoding = 'utf-8') worksheet = workbook.add_sheet('temp', cell_overwrite_ok = True) worksheet.write(0,", "xlwt # set options parser = argparse.ArgumentParser(description = 'convert txt to excel', usage", "= 'test.txt', help = 'the path of the txt file') parser.add_argument('--splitter', type =", "= '\\t', help = 'the splitter for each line in the txt file.')", "Wed Jan 23 17:20:22 2019 convert txt to excel @author: zyb_as \"\"\" import", "'the fields number each line.') parser.add_argument('--max_lines', type = int, default = 50000, help", "= int, default = 1, # help = 'the fields number each line.')", "to be convert does't exists\") excel_file = '' if file_name[-4:] == '.txt': excel_file", "if not os.path.exists(file_name): print(\"ERROR! the file need to be convert does't exists\") excel_file", "50000, help = 'max lines number in one excel') def download_from_txt(): # get", "fields number each line.') parser.add_argument('--max_lines', type = int, default = 50000, help =", "import os import argparse, textwrap import xlwt # set options parser = argparse.ArgumentParser(description", "17:20:22 2019 convert txt to excel @author: zyb_as \"\"\" import os import argparse,", "= xlwt.Workbook(encoding = 'utf-8') worksheet = workbook.add_sheet('temp', cell_overwrite_ok = True) worksheet.write(0, 0, label", "txt to excel', usage = textwrap.dedent('''\\ command example: python %(prog)s --file_name='test.txt' --splitter='\\\\t' '''),", "= 'the fields number each line.') parser.add_argument('--max_lines', type = int, default = 50000,", "'.xls' # 创建表 workbook = xlwt.Workbook(encoding = 'utf-8') worksheet = workbook.add_sheet('temp', cell_overwrite_ok =", "+ '.xls' else: excel_file = file_name + '.xls' if splitter == '\\\\t': splitter", "options args = parser.parse_args() file_name = args.file_name splitter = args.splitter #fields_num = args.fields_num", "True) worksheet.write(0, 0, label = 'Row 0, Column 0 Value') for line in", "excel') def download_from_txt(): # get options args = parser.parse_args() file_name = args.file_name splitter", "default = 50000, help = 'max lines number in one excel') def download_from_txt():", "idx, it in enumerate(item): worksheet.write(cnt, idx, it.decode('utf-8', 'ignore')) cnt += 1 if cnt", "formatter_class = argparse.RawTextHelpFormatter) parser.add_argument('--file_name', type = str, default = 'test.txt', help = 'the", "'.xls' if splitter == '\\\\t': splitter = '\\t' cnt = 0 xls_index =", "splitter = '\\t' cnt = 0 xls_index = 0 cur_excel_file = excel_file[:-4] +", "if cnt == max_lines: workbook.save(cur_excel_file) xls_index += 1 cur_excel_file = excel_file[:-4] + '_'", "= str, default = '\\t', help = 'the splitter for each line in", "= argparse.RawTextHelpFormatter) parser.add_argument('--file_name', type = str, default = 'test.txt', help = 'the path", "== max_lines: workbook.save(cur_excel_file) xls_index += 1 cur_excel_file = excel_file[:-4] + '_' + str(xls_index)", "textwrap import xlwt # set options parser = argparse.ArgumentParser(description = 'convert txt to", "open(file_name, 'r').readlines(): if cnt == max_lines: workbook.save(cur_excel_file) xls_index += 1 cur_excel_file = excel_file[:-4]", "# -*- coding: utf-8 -*- \"\"\" Created on Wed Jan 23 17:20:22 2019", "default = 'test.txt', help = 'the path of the txt file') parser.add_argument('--splitter', type", "excel_file = '' if file_name[-4:] == '.txt': excel_file = file_name[:-4] + '.xls' else:", "splitter == '\\\\t': splitter = '\\t' cnt = 0 xls_index = 0 cur_excel_file", "in enumerate(item): worksheet.write(cnt, idx, it.decode('utf-8', 'ignore')) cnt += 1 if cnt <= max_lines:", "for line in open(file_name, 'r').readlines(): if cnt == max_lines: workbook.save(cur_excel_file) xls_index += 1", "%(prog)s --file_name='test.txt' --splitter='\\\\t' '''), formatter_class = argparse.RawTextHelpFormatter) parser.add_argument('--file_name', type = str, default =", "\"\"\" Created on Wed Jan 23 17:20:22 2019 convert txt to excel @author:", "args.fields_num max_lines = args.max_lines if not os.path.exists(file_name): print(\"ERROR! the file need to be", "get options args = parser.parse_args() file_name = args.file_name splitter = args.splitter #fields_num =", "line.') parser.add_argument('--max_lines', type = int, default = 50000, help = 'max lines number", "workbook = xlwt.Workbook(encoding = 'utf-8') worksheet = workbook.add_sheet('temp', cell_overwrite_ok = True) worksheet.write(0, 0,", "0 item = line.split(splitter) print(cnt) for idx, it in enumerate(item): worksheet.write(cnt, idx, it.decode('utf-8',", "it in enumerate(item): worksheet.write(cnt, idx, it.decode('utf-8', 'ignore')) cnt += 1 if cnt <=", "zyb_as \"\"\" import os import argparse, textwrap import xlwt # set options parser", "#fields_num = args.fields_num max_lines = args.max_lines if not os.path.exists(file_name): print(\"ERROR! the file need", "help = 'the fields number each line.') parser.add_argument('--max_lines', type = int, default =", "in the txt file.') #parser.add_argument('--fields_num', type = int, default = 1, # help", "'the splitter for each line in the txt file.') #parser.add_argument('--fields_num', type = int,", "= argparse.ArgumentParser(description = 'convert txt to excel', usage = textwrap.dedent('''\\ command example: python", "cur_excel_file = excel_file[:-4] + '_' + str(xls_index) + '.xls' # 创建表 workbook =" ]
[ "<gh_stars>0 from abc import ABC from django.db.backends.base.schema import BaseDatabaseSchemaEditor class DatabaseSchemaEditor(BaseDatabaseSchemaEditor, ABC): pass" ]
[ "how in_file = open(from_file) indata = in_file.read() print(f\"Input file is {len(indata)} bytes long\")", "in_file = open(from_file) indata = in_file.read() print(f\"Input file is {len(indata)} bytes long\") print(f\"Doesoutput", "long\") print(f\"Doesoutput file exist? {exists(to_file)}\") print(f\"Ready, hit RETURN to continute CTRL-C to abort.\")", "= argv print(f\"Copy from {from_file} to {to_file}\") #2 on i line how in_file", "= in_file.read() print(f\"Input file is {len(indata)} bytes long\") print(f\"Doesoutput file exist? {exists(to_file)}\") print(f\"Ready,", "{exists(to_file)}\") print(f\"Ready, hit RETURN to continute CTRL-C to abort.\") out_file = open(to_file, 'w')", "{from_file} to {to_file}\") #2 on i line how in_file = open(from_file) indata =", "from_file, to_file = argv print(f\"Copy from {from_file} to {to_file}\") #2 on i line", "{to_file}\") #2 on i line how in_file = open(from_file) indata = in_file.read() print(f\"Input", "sys import argv from os.path import exists script, from_file, to_file = argv print(f\"Copy", "exist? {exists(to_file)}\") print(f\"Ready, hit RETURN to continute CTRL-C to abort.\") out_file = open(to_file,", "open(from_file) indata = in_file.read() print(f\"Input file is {len(indata)} bytes long\") print(f\"Doesoutput file exist?", "<gh_stars>0 from sys import argv from os.path import exists script, from_file, to_file =", "print(f\"Copy from {from_file} to {to_file}\") #2 on i line how in_file = open(from_file)", "is {len(indata)} bytes long\") print(f\"Doesoutput file exist? {exists(to_file)}\") print(f\"Ready, hit RETURN to continute", "{len(indata)} bytes long\") print(f\"Doesoutput file exist? {exists(to_file)}\") print(f\"Ready, hit RETURN to continute CTRL-C", "to_file = argv print(f\"Copy from {from_file} to {to_file}\") #2 on i line how", "= open(from_file) indata = in_file.read() print(f\"Input file is {len(indata)} bytes long\") print(f\"Doesoutput file", "from {from_file} to {to_file}\") #2 on i line how in_file = open(from_file) indata", "hit RETURN to continute CTRL-C to abort.\") out_file = open(to_file, 'w') out_file.write(indata) print(\"Alright", "print(f\"Ready, hit RETURN to continute CTRL-C to abort.\") out_file = open(to_file, 'w') out_file.write(indata)", "indata = in_file.read() print(f\"Input file is {len(indata)} bytes long\") print(f\"Doesoutput file exist? {exists(to_file)}\")", "print(f\"Doesoutput file exist? {exists(to_file)}\") print(f\"Ready, hit RETURN to continute CTRL-C to abort.\") out_file", "to {to_file}\") #2 on i line how in_file = open(from_file) indata = in_file.read()", "import argv from os.path import exists script, from_file, to_file = argv print(f\"Copy from", "i line how in_file = open(from_file) indata = in_file.read() print(f\"Input file is {len(indata)}", "argv from os.path import exists script, from_file, to_file = argv print(f\"Copy from {from_file}", "#2 on i line how in_file = open(from_file) indata = in_file.read() print(f\"Input file", "os.path import exists script, from_file, to_file = argv print(f\"Copy from {from_file} to {to_file}\")", "CTRL-C to abort.\") out_file = open(to_file, 'w') out_file.write(indata) print(\"Alright all sone\") out_file.close() in_file.close()", "from sys import argv from os.path import exists script, from_file, to_file = argv", "exists script, from_file, to_file = argv print(f\"Copy from {from_file} to {to_file}\") #2 on", "script, from_file, to_file = argv print(f\"Copy from {from_file} to {to_file}\") #2 on i", "line how in_file = open(from_file) indata = in_file.read() print(f\"Input file is {len(indata)} bytes", "in_file.read() print(f\"Input file is {len(indata)} bytes long\") print(f\"Doesoutput file exist? {exists(to_file)}\") print(f\"Ready, hit", "bytes long\") print(f\"Doesoutput file exist? {exists(to_file)}\") print(f\"Ready, hit RETURN to continute CTRL-C to", "import exists script, from_file, to_file = argv print(f\"Copy from {from_file} to {to_file}\") #2", "argv print(f\"Copy from {from_file} to {to_file}\") #2 on i line how in_file =", "on i line how in_file = open(from_file) indata = in_file.read() print(f\"Input file is", "file is {len(indata)} bytes long\") print(f\"Doesoutput file exist? {exists(to_file)}\") print(f\"Ready, hit RETURN to", "file exist? {exists(to_file)}\") print(f\"Ready, hit RETURN to continute CTRL-C to abort.\") out_file =", "continute CTRL-C to abort.\") out_file = open(to_file, 'w') out_file.write(indata) print(\"Alright all sone\") out_file.close()", "from os.path import exists script, from_file, to_file = argv print(f\"Copy from {from_file} to", "RETURN to continute CTRL-C to abort.\") out_file = open(to_file, 'w') out_file.write(indata) print(\"Alright all", "to continute CTRL-C to abort.\") out_file = open(to_file, 'w') out_file.write(indata) print(\"Alright all sone\")", "print(f\"Input file is {len(indata)} bytes long\") print(f\"Doesoutput file exist? {exists(to_file)}\") print(f\"Ready, hit RETURN" ]
[ "as late as possible to # keep it snappy once we have more", "x2df.fileIOhandlers.__fileIOhandler__ import FileIOhandler # we want to do the imports as late as", "pd dfraw = pd.read_parquet(path) if postprocess: return self.processRawDF(dfraw) else: return [dfraw] def claim(self,", "pyarrow.parquet.read_schema(path) return [path] except: # noqa: E722 #this is fine. Reject any exception", "# noqa: F401 import pandas as pd dfraw = pd.read_parquet(path) if postprocess: return", "have more and more fileIOhandlers class Handler(FileIOhandler): def dump(self, df, dst, **kwargs): #", "noqa: F401 df.to_parquet(dst) def parse(self, path, postprocess=True, **kwargs): import pyarrow # noqa: F401", "self.processRawDF(dfraw) else: return [dfraw] def claim(self, path): import pyarrow # noqa: F401 try:", "def parse(self, path, postprocess=True, **kwargs): import pyarrow # noqa: F401 import pandas as", "possible to # keep it snappy once we have more and more fileIOhandlers", "def dump(self, df, dst, **kwargs): # we import pyarrow here to make sure", "need to install it. if not dst: return import pyarrow # noqa: F401", "dst: return import pyarrow # noqa: F401 df.to_parquet(dst) def parse(self, path, postprocess=True, **kwargs):", "postprocess: return self.processRawDF(dfraw) else: return [dfraw] def claim(self, path): import pyarrow # noqa:", "from x2df.fileIOhandlers.__fileIOhandler__ import FileIOhandler # we want to do the imports as late", "postprocess=True, **kwargs): import pyarrow # noqa: F401 import pandas as pd dfraw =", "import pyarrow # noqa: F401 df.to_parquet(dst) def parse(self, path, postprocess=True, **kwargs): import pyarrow", "it is not found, we get an error and need to install it.", "found by pyreqs. # if it is not found, we get an error", "else: return [dfraw] def claim(self, path): import pyarrow # noqa: F401 try: pyarrow.parquet.read_schema(path)", "late as possible to # keep it snappy once we have more and", "install it. if not dst: return import pyarrow # noqa: F401 df.to_parquet(dst) def", "import pandas as pd dfraw = pd.read_parquet(path) if postprocess: return self.processRawDF(dfraw) else: return", "want to do the imports as late as possible to # keep it", "is not found, we get an error and need to install it. if", "imports as late as possible to # keep it snappy once we have", "sure that is found by pyreqs. # if it is not found, we", "import pyarrow # noqa: F401 try: pyarrow.parquet.read_schema(path) return [path] except: # noqa: E722", "return import pyarrow # noqa: F401 df.to_parquet(dst) def parse(self, path, postprocess=True, **kwargs): import", "import pyarrow here to make sure that is found by pyreqs. # if", "pandas as pd dfraw = pd.read_parquet(path) if postprocess: return self.processRawDF(dfraw) else: return [dfraw]", "return [path] except: # noqa: E722 #this is fine. Reject any exception but", "pyarrow # noqa: F401 try: pyarrow.parquet.read_schema(path) return [path] except: # noqa: E722 #this", "<gh_stars>0 from x2df.fileIOhandlers.__fileIOhandler__ import FileIOhandler # we want to do the imports as", "# we import pyarrow here to make sure that is found by pyreqs.", "claim(self, path): import pyarrow # noqa: F401 try: pyarrow.parquet.read_schema(path) return [path] except: #", "the imports as late as possible to # keep it snappy once we", "dump(self, df, dst, **kwargs): # we import pyarrow here to make sure that", "path): import pyarrow # noqa: F401 try: pyarrow.parquet.read_schema(path) return [path] except: # noqa:", "it snappy once we have more and more fileIOhandlers class Handler(FileIOhandler): def dump(self,", "= pd.read_parquet(path) if postprocess: return self.processRawDF(dfraw) else: return [dfraw] def claim(self, path): import", "once we have more and more fileIOhandlers class Handler(FileIOhandler): def dump(self, df, dst,", "pyarrow # noqa: F401 df.to_parquet(dst) def parse(self, path, postprocess=True, **kwargs): import pyarrow #", "df, dst, **kwargs): # we import pyarrow here to make sure that is", "if not dst: return import pyarrow # noqa: F401 df.to_parquet(dst) def parse(self, path,", "error and need to install it. if not dst: return import pyarrow #", "here to make sure that is found by pyreqs. # if it is", "snappy once we have more and more fileIOhandlers class Handler(FileIOhandler): def dump(self, df,", "more fileIOhandlers class Handler(FileIOhandler): def dump(self, df, dst, **kwargs): # we import pyarrow", "we get an error and need to install it. if not dst: return", "noqa: F401 try: pyarrow.parquet.read_schema(path) return [path] except: # noqa: E722 #this is fine.", "dfraw = pd.read_parquet(path) if postprocess: return self.processRawDF(dfraw) else: return [dfraw] def claim(self, path):", "noqa: E722 #this is fine. Reject any exception but never crash. return []", "we want to do the imports as late as possible to # keep", "pyarrow # noqa: F401 import pandas as pd dfraw = pd.read_parquet(path) if postprocess:", "**kwargs): # we import pyarrow here to make sure that is found by", "F401 try: pyarrow.parquet.read_schema(path) return [path] except: # noqa: E722 #this is fine. Reject", "make sure that is found by pyreqs. # if it is not found,", "not found, we get an error and need to install it. if not", "that is found by pyreqs. # if it is not found, we get", "# noqa: F401 try: pyarrow.parquet.read_schema(path) return [path] except: # noqa: E722 #this is", "FileIOhandler # we want to do the imports as late as possible to", "import FileIOhandler # we want to do the imports as late as possible", "df.to_parquet(dst) def parse(self, path, postprocess=True, **kwargs): import pyarrow # noqa: F401 import pandas", "to # keep it snappy once we have more and more fileIOhandlers class", "to make sure that is found by pyreqs. # if it is not", "def claim(self, path): import pyarrow # noqa: F401 try: pyarrow.parquet.read_schema(path) return [path] except:", "class Handler(FileIOhandler): def dump(self, df, dst, **kwargs): # we import pyarrow here to", "as pd dfraw = pd.read_parquet(path) if postprocess: return self.processRawDF(dfraw) else: return [dfraw] def", "except: # noqa: E722 #this is fine. Reject any exception but never crash.", "if postprocess: return self.processRawDF(dfraw) else: return [dfraw] def claim(self, path): import pyarrow #", "more and more fileIOhandlers class Handler(FileIOhandler): def dump(self, df, dst, **kwargs): # we", "fileIOhandlers class Handler(FileIOhandler): def dump(self, df, dst, **kwargs): # we import pyarrow here", "# we want to do the imports as late as possible to #", "path, postprocess=True, **kwargs): import pyarrow # noqa: F401 import pandas as pd dfraw", "not dst: return import pyarrow # noqa: F401 df.to_parquet(dst) def parse(self, path, postprocess=True,", "# keep it snappy once we have more and more fileIOhandlers class Handler(FileIOhandler):", "pyarrow here to make sure that is found by pyreqs. # if it", "pd.read_parquet(path) if postprocess: return self.processRawDF(dfraw) else: return [dfraw] def claim(self, path): import pyarrow", "and need to install it. if not dst: return import pyarrow # noqa:", "keep it snappy once we have more and more fileIOhandlers class Handler(FileIOhandler): def", "parse(self, path, postprocess=True, **kwargs): import pyarrow # noqa: F401 import pandas as pd", "an error and need to install it. if not dst: return import pyarrow", "noqa: F401 import pandas as pd dfraw = pd.read_parquet(path) if postprocess: return self.processRawDF(dfraw)", "try: pyarrow.parquet.read_schema(path) return [path] except: # noqa: E722 #this is fine. Reject any", "to do the imports as late as possible to # keep it snappy", "get an error and need to install it. if not dst: return import", "is found by pyreqs. # if it is not found, we get an", "F401 df.to_parquet(dst) def parse(self, path, postprocess=True, **kwargs): import pyarrow # noqa: F401 import", "Handler(FileIOhandler): def dump(self, df, dst, **kwargs): # we import pyarrow here to make", "# noqa: F401 df.to_parquet(dst) def parse(self, path, postprocess=True, **kwargs): import pyarrow # noqa:", "dst, **kwargs): # we import pyarrow here to make sure that is found", "found, we get an error and need to install it. if not dst:", "pyreqs. # if it is not found, we get an error and need", "[dfraw] def claim(self, path): import pyarrow # noqa: F401 try: pyarrow.parquet.read_schema(path) return [path]", "[path] except: # noqa: E722 #this is fine. Reject any exception but never", "do the imports as late as possible to # keep it snappy once", "to install it. if not dst: return import pyarrow # noqa: F401 df.to_parquet(dst)", "**kwargs): import pyarrow # noqa: F401 import pandas as pd dfraw = pd.read_parquet(path)", "and more fileIOhandlers class Handler(FileIOhandler): def dump(self, df, dst, **kwargs): # we import", "it. if not dst: return import pyarrow # noqa: F401 df.to_parquet(dst) def parse(self,", "if it is not found, we get an error and need to install", "we have more and more fileIOhandlers class Handler(FileIOhandler): def dump(self, df, dst, **kwargs):", "# if it is not found, we get an error and need to", "we import pyarrow here to make sure that is found by pyreqs. #", "return self.processRawDF(dfraw) else: return [dfraw] def claim(self, path): import pyarrow # noqa: F401", "by pyreqs. # if it is not found, we get an error and", "as possible to # keep it snappy once we have more and more", "return [dfraw] def claim(self, path): import pyarrow # noqa: F401 try: pyarrow.parquet.read_schema(path) return", "import pyarrow # noqa: F401 import pandas as pd dfraw = pd.read_parquet(path) if", "# noqa: E722 #this is fine. Reject any exception but never crash. return", "F401 import pandas as pd dfraw = pd.read_parquet(path) if postprocess: return self.processRawDF(dfraw) else:" ]
[ "'License :: OSI Approved :: MIT License', 'Topic :: Communications :: File Sharing',", "command-line tool that automates renaming of so-called \"Scene Release\" files by fetching episode", "Status :: 5 - Production/Stable', 'Environment :: Console', 'Intended Audience :: End Users/Desktop',", "Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7',", "'test') project.set_property('flake8_break_build', True) project.set_property('flake8_include_test_sources', True) project.set_property('flake8_include_scripts', True) # relevant tests are in Scenery_tests.py", "3', 'Programming Language :: Python :: 3.7', 'Development Status :: 5 - Production/Stable',", "[\"install_dependencies\", \"analyze\", \"publish\"] @init def initialize(project): project.build_depends_on('mockito') project.set_property('dir_source_main_python', 'src') project.set_property('dir_source_unittest_python', 'test') project.set_property('flake8_break_build', True)", "episode number, episode title) to format the output. \"\"\" url = 'https://github.com/dachaz/scenery' version", "project.get_property('coverage_exceptions').append('scenery.__main__') project.get_property('coverage_exceptions').append('scenery') project.set_property('distutils_console_scripts', ['scenery = scenery:main']) project.set_property('distutils_classifiers', [ 'Programming Language :: Python', 'Programming", "blocks (show name, season number, episode number, episode title) to format the output.", "project.set_property('flake8_include_test_sources', True) project.set_property('flake8_include_scripts', True) # relevant tests are in Scenery_tests.py project.get_property('coverage_exceptions').append('scenery.__main__') project.get_property('coverage_exceptions').append('scenery') project.set_property('distutils_console_scripts',", "Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python", ":: Console', 'Intended Audience :: End Users/Desktop', 'License :: OSI Approved :: MIT", "= 'https://github.com/dachaz/scenery' version = '1.0.1' requires_python = \">=2.7\" default_task = [\"install_dependencies\", \"analyze\", \"publish\"]", "project.set_property('flake8_include_scripts', True) # relevant tests are in Scenery_tests.py project.get_property('coverage_exceptions').append('scenery.__main__') project.get_property('coverage_exceptions').append('scenery') project.set_property('distutils_console_scripts', ['scenery =", ":: 3', 'Programming Language :: Python :: 3.7', 'Development Status :: 5 -", "pattern-based generic building blocks (show name, season number, episode number, episode title) to", "'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.7', 'Development", "name, season number, episode number, episode title) to format the output. \"\"\" url", "\">=2.7\" default_task = [\"install_dependencies\", \"analyze\", \"publish\"] @init def initialize(project): project.build_depends_on('mockito') project.set_property('dir_source_main_python', 'src') project.set_property('dir_source_unittest_python',", "\"publish\"] @init def initialize(project): project.build_depends_on('mockito') project.set_property('dir_source_main_python', 'src') project.set_property('dir_source_unittest_python', 'test') project.set_property('flake8_break_build', True) project.set_property('flake8_include_test_sources', True)", "Users/Desktop', 'License :: OSI Approved :: MIT License', 'Topic :: Communications :: File", "name = 'scenery' summary = 'A pattern-based scene release renamer' description = \"\"\"A", "= 'MIT' name = 'scenery' summary = 'A pattern-based scene release renamer' description", "of so-called \"Scene Release\" files by fetching episode names (from TVMaze) and which", ":: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python ::", ":: Python :: 3.7', 'Development Status :: 5 - Production/Stable', 'Environment :: Console',", "use_plugin('python.unittest') use_plugin('python.coverage') use_plugin('python.distutils') use_plugin(\"python.install_dependencies\") authors = [Author('Dachaz', '<EMAIL>')] license = 'MIT' name =", "OSI Approved :: MIT License', 'Topic :: Communications :: File Sharing', 'Topic ::", "TVMaze) and which uses pattern-based generic building blocks (show name, season number, episode", "= 'scenery' summary = 'A pattern-based scene release renamer' description = \"\"\"A command-line", ":: MIT License', 'Topic :: Communications :: File Sharing', 'Topic :: Multimedia', 'Topic", "= [\"install_dependencies\", \"analyze\", \"publish\"] @init def initialize(project): project.build_depends_on('mockito') project.set_property('dir_source_main_python', 'src') project.set_property('dir_source_unittest_python', 'test') project.set_property('flake8_break_build',", "url = 'https://github.com/dachaz/scenery' version = '1.0.1' requires_python = \">=2.7\" default_task = [\"install_dependencies\", \"analyze\",", "2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3',", "2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.7',", "(from TVMaze) and which uses pattern-based generic building blocks (show name, season number,", "default_task = [\"install_dependencies\", \"analyze\", \"publish\"] @init def initialize(project): project.build_depends_on('mockito') project.set_property('dir_source_main_python', 'src') project.set_property('dir_source_unittest_python', 'test')", "and which uses pattern-based generic building blocks (show name, season number, episode number,", "tests are in Scenery_tests.py project.get_property('coverage_exceptions').append('scenery.__main__') project.get_property('coverage_exceptions').append('scenery') project.set_property('distutils_console_scripts', ['scenery = scenery:main']) project.set_property('distutils_classifiers', [ 'Programming", "fetching episode names (from TVMaze) and which uses pattern-based generic building blocks (show", "Python :: 3.7', 'Development Status :: 5 - Production/Stable', 'Environment :: Console', 'Intended", "use_plugin('python.flake8') use_plugin('python.unittest') use_plugin('python.coverage') use_plugin('python.distutils') use_plugin(\"python.install_dependencies\") authors = [Author('Dachaz', '<EMAIL>')] license = 'MIT' name", "use_plugin(\"python.install_dependencies\") authors = [Author('Dachaz', '<EMAIL>')] license = 'MIT' name = 'scenery' summary =", "Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language", "Console', 'Intended Audience :: End Users/Desktop', 'License :: OSI Approved :: MIT License',", "'src') project.set_property('dir_source_unittest_python', 'test') project.set_property('flake8_break_build', True) project.set_property('flake8_include_test_sources', True) project.set_property('flake8_include_scripts', True) # relevant tests are", "[Author('Dachaz', '<EMAIL>')] license = 'MIT' name = 'scenery' summary = 'A pattern-based scene", ":: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language ::", "tool that automates renaming of so-called \"Scene Release\" files by fetching episode names", "project.set_property('flake8_break_build', True) project.set_property('flake8_include_test_sources', True) project.set_property('flake8_include_scripts', True) # relevant tests are in Scenery_tests.py project.get_property('coverage_exceptions').append('scenery.__main__')", "= 'A pattern-based scene release renamer' description = \"\"\"A command-line tool that automates", "'<EMAIL>')] license = 'MIT' name = 'scenery' summary = 'A pattern-based scene release", "output. \"\"\" url = 'https://github.com/dachaz/scenery' version = '1.0.1' requires_python = \">=2.7\" default_task =", "number, episode title) to format the output. \"\"\" url = 'https://github.com/dachaz/scenery' version =", "= scenery:main']) project.set_property('distutils_classifiers', [ 'Programming Language :: Python', 'Programming Language :: Python ::", "import init, use_plugin, Author use_plugin('python.core') use_plugin('python.flake8') use_plugin('python.unittest') use_plugin('python.coverage') use_plugin('python.distutils') use_plugin(\"python.install_dependencies\") authors = [Author('Dachaz',", "use_plugin('python.coverage') use_plugin('python.distutils') use_plugin(\"python.install_dependencies\") authors = [Author('Dachaz', '<EMAIL>')] license = 'MIT' name = 'scenery'", "initialize(project): project.build_depends_on('mockito') project.set_property('dir_source_main_python', 'src') project.set_property('dir_source_unittest_python', 'test') project.set_property('flake8_break_build', True) project.set_property('flake8_include_test_sources', True) project.set_property('flake8_include_scripts', True) #", "Python :: 3', 'Programming Language :: Python :: 3.7', 'Development Status :: 5", ":: OSI Approved :: MIT License', 'Topic :: Communications :: File Sharing', 'Topic", "project.set_property('distutils_console_scripts', ['scenery = scenery:main']) project.set_property('distutils_classifiers', [ 'Programming Language :: Python', 'Programming Language ::", "use_plugin('python.core') use_plugin('python.flake8') use_plugin('python.unittest') use_plugin('python.coverage') use_plugin('python.distutils') use_plugin(\"python.install_dependencies\") authors = [Author('Dachaz', '<EMAIL>')] license = 'MIT'", "use_plugin, Author use_plugin('python.core') use_plugin('python.flake8') use_plugin('python.unittest') use_plugin('python.coverage') use_plugin('python.distutils') use_plugin(\"python.install_dependencies\") authors = [Author('Dachaz', '<EMAIL>')] license", "True) project.set_property('flake8_include_test_sources', True) project.set_property('flake8_include_scripts', True) # relevant tests are in Scenery_tests.py project.get_property('coverage_exceptions').append('scenery.__main__') project.get_property('coverage_exceptions').append('scenery')", "'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming", "# relevant tests are in Scenery_tests.py project.get_property('coverage_exceptions').append('scenery.__main__') project.get_property('coverage_exceptions').append('scenery') project.set_property('distutils_console_scripts', ['scenery = scenery:main']) project.set_property('distutils_classifiers',", "License', 'Topic :: Communications :: File Sharing', 'Topic :: Multimedia', 'Topic :: Multimedia", "scene release renamer' description = \"\"\"A command-line tool that automates renaming of so-called", "summary = 'A pattern-based scene release renamer' description = \"\"\"A command-line tool that", "scenery:main']) project.set_property('distutils_classifiers', [ 'Programming Language :: Python', 'Programming Language :: Python :: 2',", "description = \"\"\"A command-line tool that automates renaming of so-called \"Scene Release\" files", "project.set_property('distutils_classifiers', [ 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming", "= \">=2.7\" default_task = [\"install_dependencies\", \"analyze\", \"publish\"] @init def initialize(project): project.build_depends_on('mockito') project.set_property('dir_source_main_python', 'src')", "'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language ::", "'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming", "requires_python = \">=2.7\" default_task = [\"install_dependencies\", \"analyze\", \"publish\"] @init def initialize(project): project.build_depends_on('mockito') project.set_property('dir_source_main_python',", "Language :: Python :: 3.7', 'Development Status :: 5 - Production/Stable', 'Environment ::", "\"analyze\", \"publish\"] @init def initialize(project): project.build_depends_on('mockito') project.set_property('dir_source_main_python', 'src') project.set_property('dir_source_unittest_python', 'test') project.set_property('flake8_break_build', True) project.set_property('flake8_include_test_sources',", "relevant tests are in Scenery_tests.py project.get_property('coverage_exceptions').append('scenery.__main__') project.get_property('coverage_exceptions').append('scenery') project.set_property('distutils_console_scripts', ['scenery = scenery:main']) project.set_property('distutils_classifiers', [", "'Development Status :: 5 - Production/Stable', 'Environment :: Console', 'Intended Audience :: End", "True) # relevant tests are in Scenery_tests.py project.get_property('coverage_exceptions').append('scenery.__main__') project.get_property('coverage_exceptions').append('scenery') project.set_property('distutils_console_scripts', ['scenery = scenery:main'])", "the output. \"\"\" url = 'https://github.com/dachaz/scenery' version = '1.0.1' requires_python = \">=2.7\" default_task", "\"\"\" url = 'https://github.com/dachaz/scenery' version = '1.0.1' requires_python = \">=2.7\" default_task = [\"install_dependencies\",", "(show name, season number, episode number, episode title) to format the output. \"\"\"", "End Users/Desktop', 'License :: OSI Approved :: MIT License', 'Topic :: Communications ::", "Sharing', 'Topic :: Multimedia', 'Topic :: Multimedia :: Video', 'Topic :: Utilities' ])", "= [Author('Dachaz', '<EMAIL>')] license = 'MIT' name = 'scenery' summary = 'A pattern-based", "number, episode number, episode title) to format the output. \"\"\" url = 'https://github.com/dachaz/scenery'", "project.build_depends_on('mockito') project.set_property('dir_source_main_python', 'src') project.set_property('dir_source_unittest_python', 'test') project.set_property('flake8_break_build', True) project.set_property('flake8_include_test_sources', True) project.set_property('flake8_include_scripts', True) # relevant", "to format the output. \"\"\" url = 'https://github.com/dachaz/scenery' version = '1.0.1' requires_python =", "Communications :: File Sharing', 'Topic :: Multimedia', 'Topic :: Multimedia :: Video', 'Topic", "from pybuilder.core import init, use_plugin, Author use_plugin('python.core') use_plugin('python.flake8') use_plugin('python.unittest') use_plugin('python.coverage') use_plugin('python.distutils') use_plugin(\"python.install_dependencies\") authors", "'Intended Audience :: End Users/Desktop', 'License :: OSI Approved :: MIT License', 'Topic", "Scenery_tests.py project.get_property('coverage_exceptions').append('scenery.__main__') project.get_property('coverage_exceptions').append('scenery') project.set_property('distutils_console_scripts', ['scenery = scenery:main']) project.set_property('distutils_classifiers', [ 'Programming Language :: Python',", "episode names (from TVMaze) and which uses pattern-based generic building blocks (show name,", "Language :: Python :: 3', 'Programming Language :: Python :: 3.7', 'Development Status", "so-called \"Scene Release\" files by fetching episode names (from TVMaze) and which uses", "= '1.0.1' requires_python = \">=2.7\" default_task = [\"install_dependencies\", \"analyze\", \"publish\"] @init def initialize(project):", "project.set_property('dir_source_main_python', 'src') project.set_property('dir_source_unittest_python', 'test') project.set_property('flake8_break_build', True) project.set_property('flake8_include_test_sources', True) project.set_property('flake8_include_scripts', True) # relevant tests", "authors = [Author('Dachaz', '<EMAIL>')] license = 'MIT' name = 'scenery' summary = 'A", "Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python", "automates renaming of so-called \"Scene Release\" files by fetching episode names (from TVMaze)", "True) project.set_property('flake8_include_scripts', True) # relevant tests are in Scenery_tests.py project.get_property('coverage_exceptions').append('scenery.__main__') project.get_property('coverage_exceptions').append('scenery') project.set_property('distutils_console_scripts', ['scenery", "Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python", "'A pattern-based scene release renamer' description = \"\"\"A command-line tool that automates renaming", ":: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python ::", "Author use_plugin('python.core') use_plugin('python.flake8') use_plugin('python.unittest') use_plugin('python.coverage') use_plugin('python.distutils') use_plugin(\"python.install_dependencies\") authors = [Author('Dachaz', '<EMAIL>')] license =", "format the output. \"\"\" url = 'https://github.com/dachaz/scenery' version = '1.0.1' requires_python = \">=2.7\"", "pybuilder.core import init, use_plugin, Author use_plugin('python.core') use_plugin('python.flake8') use_plugin('python.unittest') use_plugin('python.coverage') use_plugin('python.distutils') use_plugin(\"python.install_dependencies\") authors =", "renaming of so-called \"Scene Release\" files by fetching episode names (from TVMaze) and", "season number, episode number, episode title) to format the output. \"\"\" url =", "project.set_property('dir_source_unittest_python', 'test') project.set_property('flake8_break_build', True) project.set_property('flake8_include_test_sources', True) project.set_property('flake8_include_scripts', True) # relevant tests are in", ":: Communications :: File Sharing', 'Topic :: Multimedia', 'Topic :: Multimedia :: Video',", "['scenery = scenery:main']) project.set_property('distutils_classifiers', [ 'Programming Language :: Python', 'Programming Language :: Python", "by fetching episode names (from TVMaze) and which uses pattern-based generic building blocks", "generic building blocks (show name, season number, episode number, episode title) to format", "version = '1.0.1' requires_python = \">=2.7\" default_task = [\"install_dependencies\", \"analyze\", \"publish\"] @init def", ":: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language ::", ":: File Sharing', 'Topic :: Multimedia', 'Topic :: Multimedia :: Video', 'Topic ::", "project.get_property('coverage_exceptions').append('scenery') project.set_property('distutils_console_scripts', ['scenery = scenery:main']) project.set_property('distutils_classifiers', [ 'Programming Language :: Python', 'Programming Language", "in Scenery_tests.py project.get_property('coverage_exceptions').append('scenery.__main__') project.get_property('coverage_exceptions').append('scenery') project.set_property('distutils_console_scripts', ['scenery = scenery:main']) project.set_property('distutils_classifiers', [ 'Programming Language ::", "'scenery' summary = 'A pattern-based scene release renamer' description = \"\"\"A command-line tool", ":: 3.7', 'Development Status :: 5 - Production/Stable', 'Environment :: Console', 'Intended Audience", "Audience :: End Users/Desktop', 'License :: OSI Approved :: MIT License', 'Topic ::", "that automates renaming of so-called \"Scene Release\" files by fetching episode names (from", "'https://github.com/dachaz/scenery' version = '1.0.1' requires_python = \">=2.7\" default_task = [\"install_dependencies\", \"analyze\", \"publish\"] @init", "names (from TVMaze) and which uses pattern-based generic building blocks (show name, season", "are in Scenery_tests.py project.get_property('coverage_exceptions').append('scenery.__main__') project.get_property('coverage_exceptions').append('scenery') project.set_property('distutils_console_scripts', ['scenery = scenery:main']) project.set_property('distutils_classifiers', [ 'Programming Language", "renamer' description = \"\"\"A command-line tool that automates renaming of so-called \"Scene Release\"", "\"\"\"A command-line tool that automates renaming of so-called \"Scene Release\" files by fetching", "Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language", "'Topic :: Communications :: File Sharing', 'Topic :: Multimedia', 'Topic :: Multimedia ::", "episode title) to format the output. \"\"\" url = 'https://github.com/dachaz/scenery' version = '1.0.1'", "title) to format the output. \"\"\" url = 'https://github.com/dachaz/scenery' version = '1.0.1' requires_python", "File Sharing', 'Topic :: Multimedia', 'Topic :: Multimedia :: Video', 'Topic :: Utilities'", "building blocks (show name, season number, episode number, episode title) to format the", "@init def initialize(project): project.build_depends_on('mockito') project.set_property('dir_source_main_python', 'src') project.set_property('dir_source_unittest_python', 'test') project.set_property('flake8_break_build', True) project.set_property('flake8_include_test_sources', True) project.set_property('flake8_include_scripts',", "MIT License', 'Topic :: Communications :: File Sharing', 'Topic :: Multimedia', 'Topic ::", "- Production/Stable', 'Environment :: Console', 'Intended Audience :: End Users/Desktop', 'License :: OSI", "Release\" files by fetching episode names (from TVMaze) and which uses pattern-based generic", "which uses pattern-based generic building blocks (show name, season number, episode number, episode", "files by fetching episode names (from TVMaze) and which uses pattern-based generic building", ":: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python ::", "[ 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language", ":: End Users/Desktop', 'License :: OSI Approved :: MIT License', 'Topic :: Communications", "init, use_plugin, Author use_plugin('python.core') use_plugin('python.flake8') use_plugin('python.unittest') use_plugin('python.coverage') use_plugin('python.distutils') use_plugin(\"python.install_dependencies\") authors = [Author('Dachaz', '<EMAIL>')]", ":: 5 - Production/Stable', 'Environment :: Console', 'Intended Audience :: End Users/Desktop', 'License", "\"Scene Release\" files by fetching episode names (from TVMaze) and which uses pattern-based", "license = 'MIT' name = 'scenery' summary = 'A pattern-based scene release renamer'", "def initialize(project): project.build_depends_on('mockito') project.set_property('dir_source_main_python', 'src') project.set_property('dir_source_unittest_python', 'test') project.set_property('flake8_break_build', True) project.set_property('flake8_include_test_sources', True) project.set_property('flake8_include_scripts', True)", "use_plugin('python.distutils') use_plugin(\"python.install_dependencies\") authors = [Author('Dachaz', '<EMAIL>')] license = 'MIT' name = 'scenery' summary", "uses pattern-based generic building blocks (show name, season number, episode number, episode title)", "3.7', 'Development Status :: 5 - Production/Stable', 'Environment :: Console', 'Intended Audience ::", "'1.0.1' requires_python = \">=2.7\" default_task = [\"install_dependencies\", \"analyze\", \"publish\"] @init def initialize(project): project.build_depends_on('mockito')", "'MIT' name = 'scenery' summary = 'A pattern-based scene release renamer' description =", "Approved :: MIT License', 'Topic :: Communications :: File Sharing', 'Topic :: Multimedia',", "'Environment :: Console', 'Intended Audience :: End Users/Desktop', 'License :: OSI Approved ::", "pattern-based scene release renamer' description = \"\"\"A command-line tool that automates renaming of", "= \"\"\"A command-line tool that automates renaming of so-called \"Scene Release\" files by", "5 - Production/Stable', 'Environment :: Console', 'Intended Audience :: End Users/Desktop', 'License ::", ":: Python :: 3', 'Programming Language :: Python :: 3.7', 'Development Status ::", "Production/Stable', 'Environment :: Console', 'Intended Audience :: End Users/Desktop', 'License :: OSI Approved", "'Programming Language :: Python :: 3.7', 'Development Status :: 5 - Production/Stable', 'Environment", "release renamer' description = \"\"\"A command-line tool that automates renaming of so-called \"Scene" ]
[ "model parameter. * if flat == True, a N x M array, where:", "#Don't return a length-1 list, as this doesn't index numpy arrays # like", "dim=(ks,M) profiler.add_time(\"MPI IPC\", tm) profiler.mem_check(\"bulk_fill_dprobs: post gather blocks\") #collect/gather results tm = _time.time()", "# dim=(cacheSize,nDerivCols1,nDerivCols2,dim,dim) return hProdCache # ------------------------------------------------------------------ if evalTree.is_split(): _warnings.warn(\"Ignoring tree splitting in hproduct", "\"statevec\": ps = _np.real(_np.abs(_np.dot(Es, _np.dot(G, rho)) * scale)**2) else: # evotype == \"densitymx\"", "specified if wrtFilter is None: blkSize = wrtBlockSize # could be None if", "# product cache mem += cache_size # scale cache (exps) mem += cache_size", "scaleCache[i] - (scaleCache[iLeft] + scaleCache[iRight]) if abs(scale) > 1e-8: # _np.isclose(scale,0) is SLOW!", "= self._process_wrtFilter(wrtSlice2, self.sos.get_prep(rholabel)) E_wrtFilter1, E_gpindices1 = self._process_wrtFilter(wrtSlice1, self.sos.get_effect(elabel)) E_wrtFilter2, E_gpindices2 = self._process_wrtFilter(wrtSlice2, self.sos.get_effect(elabel))", "nCircuits, nDerivCols, dim, dim ) self._fill_result_tuple( (mxToFill,), evalSubTree, blocks[iBlk], slice(None), calc_and_fill_blk) profiler.mem_check(\"bulk_fill_dprobs: post", "wrtLen1 * dim * dim # dproduct cache mem += cache_size * dim", "_fas(d2pr_drhos, [0, None, self.sos.get_prep(rholabel).gpindices], _np.dot(_np.dot(E, dprod_dOps), rhoVec.deriv_wrt_params())[0]) # (= [0,:,:]) d2pr_dEs = _np.zeros((1,", "clipTo=clipTo) profiler.add_time(\"bulk_fill_dprobs: total\", tStart) profiler.add_count(\"bulk_fill_dprobs count\") profiler.mem_check(\"bulk_fill_dprobs: end\") def bulk_fill_hprobs(self, mxToFill, evalTree, prMxToFill=None,", "model parameters) and deriv[i,j] holds the derivative of the i-th entry of the", "#all gate elements are at most linear in params, so # all hessians", "gate = self.sos.get_operation(opLabel) op_wrtFilter, gpindices = self._process_wrtFilter(wrtFilter, gate) # Allocate memory for the", "vec( d2prod/d(opLabel1)_kl*d(opLabel2)_ij ) = sum{...} [ G1 ... G(M-1) dG(M)/dkl G(M+1) ... G(L-1)", "None means compute all requested columns at once. The minimum of wrtBlockSize and", "computed elements (i.e. evalTree.num_final_elements()) and M is the number of model parameters. evalTree", "- 1)], xv), dop_dopLabel2[opLabel2]) # above: (nDerivCols1,dim**2,dim**2) * (dim**2,nDerivCols2) = (nDerivCols1,dim**2,nDerivCols2) flattened_d2prod[:, inds1,", "is None and wrtFilter2 is None: blkSize1 = wrtBlockSize1 # could be None", "Government retains certain rights # in this software. # Licensed under the Apache", "the product components (i.e. prod_kl) with # respect to a given gateLabel_ij. This", "M array, where M is the number of model parameters. hessian[0,j,k] is the", "[None, None, E_gpindices2], _np.dot(dp_dAnyE, devec)) # get d2pr_dEs where gate derivatives are wrt", "(and same for other diff order) # d2pr/d(E)_i d(opLabel)_mn = sum [dprod/d(opLabel)_mn]_il rho_l", "to True, additionally return the probabilities. bScale : bool, optional When True, return", ", where dpr/dx is the usual density-matrix-mode probability # (TODO in FUTURE) #", "EvalTree object appropriate for this calculator. Parameters ---------- simplified_circuits : list A list", "the elementary matrix where all entries are zero except the (i,j) entry ==", "of operation labels The sequence of operation labels. flat : bool, optional Affects", "the generator computes a 2-tuple: (hessian_col, d12_col), where d12_col is a column of", "infs occur here _np.seterr(**old_err) if bReturnProds: Gs = evalTree.final_view(prodCache, axis=0) #shape == (", "results from a single column of the Hessian at a time. For example,", "handle the remainder spam label. \"\"\" pslc1 = param_slice1 pslc2 = param_slice2 for", "for (i, gl) in enumerate(revOpLabelList): if gl != opLabel: continue # loop over", "optional Affects the shape of the returned derivative array (see below). bReturnProds :", "of exponent if H.max() < PSMALL and H.min() > -PSMALL: nG = max(_nla.norm(G),", "] # return PrepEffectFilter(rho_local_slices=loc_rho_slices, # rho_global_slices=global_rho_slices, # e_local_slices=loc_e_slices, # e_global_slices=global_e_slices, # num_rho_params=self.tot_rho_params, #", "> -HSMALL: _warnings.warn(\"hProd is small (oh well!).\") return hProdCache ## END CACHE FUNCTIONS", "to be applied to the resulting products (final_product[i] = scaleValues[i] * prods[i]). \"\"\"", "\"custom\" spamLabel consisting of a pair of SPAMVec (or array) # objects: (prepVec,", "== 0: # import objgraph # objgraph.show_growth(limit=50) #get distribution across subtrees (groups if", "derivative array (see below). bReturnDProdsAndProds : bool, optional when set to True, additionally", "rho has shape (N,1) rho = self.sos.get_prep(rholabel).todense()[:, None] Es = [self.sos.get_effect(elabel).todense()[:, None] for", "subtree iteration before computing caches scaleVals = Gs = prodCache = scaleCache =", "respect to in the first (row) and second (col) derivative operations, respectively. wrtBlockSize2,", "0, 1) hGs = _np.rollaxis(_np.rollaxis(hGs, 0, 3).reshape( (nDerivCols1, nDerivCols2, nCircuits * dim**2)), 2)", "deriv1MxToFill is not None: _mpit.gather_slices(blocks1, blk1Owners, deriv1MxToFill, [felInds], 1, mySubComm, gatherMemLimit) if deriv2MxToFill", "hGs = evalSubTree.final_view(hProdCache, axis=0) #Set filtering for calc_and_fill wrtSlice1 = blocks1[iBlk1] wrtSlice2 =", "zero, as these occur b/c an inf scaleVal is mult by a zero", "0, 1).reshape((num_deriv_cols, dim, dim)) def hoperation(self, opLabel, flat=False, wrtFilter1=None, wrtFilter2=None): \"\"\" Return the", "parameter filters, used to # select a subset of all the derivative columns,", "prodCache[iRight] dL, dR = dProdCache[iLeft], dProdCache[iRight] dProdCache[i] = _np.dot(dL, R) + \\ _np.swapaxes(_np.dot(L,", "may also give invalid value due to scaleVals being inf and dot-prod being", "# if vec(.) concatenates rows (which numpy.flatten does) # vec( A * E(0,1)", "by `subcalls`. num_subtrees : int The number of subtrees to split the full", "mem += 2 * cache_size * nspam * wrtLen1 * wrtLen2 # hprobs", "for distributing the computation across multiple processors. Distribution is performed as in bulk_product,", "2) if isinstance(spamTuple[0], _Label): rholabel, elabel = spamTuple # This calculator uses the", "_slct.list_to_slice(wrtFilter1) else: wrtSlice1 = None if wrtFilter2 is not None: assert(wrtBlockSize1 is None", "GL == oplabel} [ G1 ... G(L-1) dG(L)/dij G(L+1) ... GN ] ,", "comm, wrtSlice1, wrtSlice2) hGs = evalTree.final_view(hProdCache, axis=0) if bReturnDProbs12: dprobs1 = _np.zeros((nElements, _slct.length(wrtSlice1)),", "add=True) # (dim**2, nParams[opLabel]) if flat: return flattened_dprod else: # axes = (gate_ij,", "in product cache calc.\") cacheSize = len(evalTree) prodCache = _np.zeros((cacheSize, dim, dim)) scaleCache", "dp_drhos[i,J0+J] = sum_kl E[0,k] Gs[i,k,l] drhoP[l,J] # dp_drhos[i,J0+J] = dot(E, Gs, drhoP)[0,i,J] #", "FUTURE: we could add logic that accounts for the symmetry of the Hessian,", "sub-trees). Note also that there would be no memory savings from using a", "(i,j) entry == 1 # if vec(.) concatenates rows (which numpy.flatten does) #", "number of processor groups that will be assigned to subtrees of the created", "* prod ) = sum E_k prod_kl rho_l # d2pr/d(opLabel1)_mn d(opLabel2)_ij = sum", "* prod ) = sum E_k prod_kl rho_l # dpr/d(opLabel)_ij = sum E_k", "over the output of this function iterates over these computed blocks, in the", "= _np.transpose(d2pr_drhos2, (0, 2, 1)) # Get: d2pr_dEs[i, j, E_gpindices] = dot(transpose(dE/dEP),dGs[i,j],rho) #", "final elements (this can be obtained by `evalTree.num_final_elements()`. To interpret which elements correspond", "circuit_list], axis=0) if _nla.norm(hprMxToFill[fInds][0] - check_vhp[0]) > 1e-6: _warnings.warn(\"norm(vhp-check_vhp) = %g - %g", "with G0 # nG = norm(G); G /= nG; total_exp += log(nG) #", "if infs occur here _np.seterr(**old_err) if bReturnDProdsAndProds: Gs = evalTree.final_view(prodCache, axis=0) #shape ==", "* scaleVals, 0, 4) # convert nans to zero, as these occur b/c", "i] = float(_np.dot(E, _np.dot(dprod_dOps[i], rho))) if returnPr: p = _np.dot(E, _np.dot(prod, rho)) *", "col_i = A[col0] * B[0,1] ) = B^T tensor A * vec( E(0,1)", "prodCache, scaleCache = self._compute_product_cache(evalTree, comm) dProdCache = self._compute_dproduct_cache(evalTree, prodCache, scaleCache, comm, wrtSlice) #use", "(0, 2, 1)) + \\ d2pr_dEs + _np.transpose(d2pr_dEs, (0, 2, 1)) + \\", "# select a subset of all the derivative columns, essentially taking # a", "None for i, opLabel in zip(evalTree.get_init_indices(), evalTree.get_init_labels()): if opLabel == \"\": # special", "== nDerivCols2), \"hGs must be pre-filtered!\" #Compute d2(probability)/dGates2 and save in return list", "= self._compute_product_cache(evalSubTree, mySubComm) #use cached data to final values scaleVals = self._scaleExp(evalSubTree.final_view(scaleCache)) Gs", "def bulk_hprobs_by_block(self, evalTree, wrtSlicesList, bReturnDProbs12=False, comm=None): \"\"\" Constructs a generator that computes the", "product with respect to the k-th then j-th model parameters. * if flat", "from ..tools import slicetools as _slct from ..tools.matrixtools import _fas from .profiler import", "the k-th then k-th model parameters. \"\"\" # LEXICOGRAPHICAL VS MATRIX ORDER #", "nDerivCols2, nCircuits * dim**2)), 2) # cols = deriv cols, rows = all", "= self._compute_product_cache(evalTree, comm) dProdCache = self._compute_dproduct_cache(evalTree, prodCache, scaleCache, comm, wrtSlice) #use cached data", "i-th operation sequence dGs1 = evalTree.final_view(dProdCache1, axis=0) dGs2 = evalTree.final_view(dProdCache2, axis=0) #shape ==", "with smaller comm_blkSize blkSize2 = comm_blkSize if (blkSize2 is None) \\ else min(comm_blkSize,", "generator which, when iterated, yields the 3-tuple `(rowSlice, colSlice, hprobs)` or `(rowSlice, colSlice,", "= %g - %g = %g\" % (_nla.norm(prMxToFill[fInds]), _nla.norm(check_vp), _nla.norm(prMxToFill[fInds] - check_vp))) #", "fail. Used for testing, and runs much slower when True. comm : mpi4py.MPI.Comm,", "dim, dim ), # Gs[i] is product for i-th operation sequence dGs1 =", "vec(i,j)-col of [ sum_{L s.t. G(L) == oplabel} [ (G1 ... G(L-1)) tensor", "on. bScale : bool, optional When True, return a scaling factor (see below).", "wrtFilter=wrtIndices) doperation = self.doperation(opLabel, wrtFilter=wrtIndices) dProdCache[i] = doperation / _np.exp(scaleCache[i]) #profiler.print_mem(\"DEBUGMEM: POINT1\"); profiler.comm.barrier()", "keep prod managable.\") elif _np.count_nonzero(hProdCache[i]) and hProdCache[i].max() < HSMALL and hProdCache[i].min() > -HSMALL:", "caches scaleVals = Gs = dGs1 = dGs2 = hGs = None prodCache", "dR1), 1, 2) dLdR_sym = dLdRa + _np.swapaxes(dLdRb, 0, 1) hProdCache[i] = _np.dot(hL,", "most # linear in the parameters assert(opLabel1 == opLabel2) if opLabel1 in hop_dopLabels:", "GN , a matrix # noqa # dprod/d(opLabel)_ij = sum_{L s.t. GL ==", "subcalls to estimate memory usage for. cache_size : int The size of the", "array size. Could throw more informative error? #elif fnName == \"bulk_product\": # mem", "return the probability itself. clipTo : 2-tuple (min,max) to clip returned probability to", "evalTree (if given) is possible. wrtFilter1, wrtFilter2 : list of ints, optional If", "if flat == False, an array of shape S x M x M", "evalTree, flat=False, bReturnProds=False, bScale=False, comm=None, wrtFilter=None): \"\"\" Compute the derivative of a many", "within # the generator and yielded, *not* allocated by the user. mem +=", "_slct.shift(myDeriv2ColSlice, wrtSlice2.start) else: myHessianSlice2 = myDeriv2ColSlice if mySubSubComm is not None and mySubSubComm.Get_size()", "the first gate operation performed, which is on the far right of the", "out of (most likely because you want to computed their probabilites). These are", "a final \"filtered\" set. # \"\"\" # PrepEffectFilter = _collections.namedtuple( # 'PrepEffectFilter', 'rho_local_slices", "as numpy.flatten) - M == length of the vectorized model (number of model", "[], 1, comm) #, gatherMemLimit) #gather over row-distribution (Deriv1) #note: gathering axis 1", "tree being # split because there's no good way to reconstruct the #", "hproduct cache calc.\") hProdCache = _np.zeros((cacheSize,) + hessn_shape) #First element of cache are", "dim ), # Gs[i] is product for i-th operation sequence dGs1 = evalTree.final_view(dProdCache1,", "return G, scale else: G = _np.identity(self.dim) for lOp in circuit: G =", "mem) but isn't gathered until now (but using blk1Comm). # (just as prMxToFill", "_slct.length(wrtSlice1)), 'd') dprobs2 = _np.zeros((nElements, _slct.length(wrtSlice2)), 'd') else: dprobs1 = dprobs2 = None", "= spamTuple rhoVec = self.sos.get_prep(rholabel) # distinct from rho,E b/c rho,E are EVec", "gate = self.sos.get_operation(opLabel).todense() nG = max(_nla.norm(gate), 1.0) prodCache[i] = gate / nG scaleCache[i]", "... G(M-1) tensor (G(M+1) ... GN)^T vec( dG(M)/dkl ) ) )^T vec( dG(L)/dij", "because # (iRight,iLeft,iFinal) = tup implies circuit[i] = circuit[iLeft] + circuit[iRight], but we", "Get: dp_drhos[i, rho_gpindices] = dot(E,Gs[i],drho/drhoP) # dp_drhos[i,J0+J] = sum_kl E[0,k] Gs[i,k,l] drhoP[l,J] #", "dim, dim ) if not bScale: old_err = _np.seterr(over='ignore', invalid='ignore') # may overflow", "2, 0)).reshape( (num_deriv_cols1, num_deriv_cols2, dim, dim)) # axes = (gate_ij1, gateij2, prod_row, prod_col)", ") #assert( len( (_np.isinf(dGs)).nonzero()[0] ) == 0 ) #dGs = clip(dGs,-1e300,1e300) _np.seterr(**old_err) if", "None: _fas(deriv2MxToFill, [fInds, pslc2], self._dprobs_from_rhoE( spamTuple, rho, E, Gs[gInds], dGs2[gInds], scaleVals[gInds], wrtSlice2), add=sumInto)", "_warnings import numpy as _np import numpy.linalg as _nla import time as _time", "* (wrtLen1 + wrtLen2) * dim * dim # dproduct cache mem +=", "hessian of a specified sequence of operation labels. Parameters ---------- circuit : Circuit", "nDerivCols) # may also give invalid value due to scaleVals being inf and", "`bulk_fill_probs(...)`, but fills a 2D array with probability-derivatives for each \"final element\" of", "to efficiently compute the gate-only sequences. This routine fills in `mxToFill`, which must", "and then (and only when needed) a split tree to parallelize computation, since", "cols, rows = flattened all else dGs1 = _np.swapaxes(_np.swapaxes(dGs1, 0, 1).reshape((nDerivCols1, nCircuits *", "flat == True, an array of shape S*N x M where - N", "dGs, scaleVals, wrtSlice=None): if self.evotype == \"statevec\": raise NotImplementedError(\"Unitary evolution not fully supported", "= int(_np.ceil(self.Np / blkSize2)) # num blocks required to achieve desired average size", "# scale cache (exps) mem += cache_size # scale vals elif fnName ==", "all SPAM vectors should be dim x 1. gates, preps, effects : OrderedDict", "dG(L)/dij G(L+1) ... GN ] , a matrix for each given (i,j) #", "_np.seterr(**old_err) if returnPr: return dpr_drhos + dpr_dEs + dpr_dOps, p else: return dpr_drhos", "internally for distributing derivative calculations across multiple processors. Returns ------- derivs : numpy", "scaleVals, 0, 2) # may overflow, but ok # may overflow or get", "scaleCache, mySubComm, wrtSlice, profiler) dGs = evalSubTree.final_view(dProdCache, axis=0) #( nCircuits, nDerivCols, dim, dim", "dpr_dOps[0, i] = float(_np.dot(E, _np.dot(dprod_dOps[i], rho))) #Derivs wrt SPAM if returnDeriv: # same", "calc_and_fill_fn): \"\"\" This function takes a \"calc-and-fill\" function, which computes and *fills* (i.e.", "int, optional A memory limit in bytes to impose upon the \"gather\" operations", "\"densitymx\" ps = _np.real(_np.dot(Es, _np.dot(G, rho))) ps = ps.flatten() if _np.any(_np.isnan(ps)): if len(circuit)", "), # dGs[i] is dprod_dOps for ith string if not bScale: old_err =", "+ d2pr_dOps2 # wrt gates return ret def _check(self, evalTree, prMxToFill=None, dprMxToFill=None, hprMxToFill=None,", "arguments \"\"\" old_err = _np.seterr(over='ignore') rho, E = self._rhoE_from_spamTuple(spamTuple) if prMxToFill is not", "# if gl1 and gl2 are both in opsToVectorize1 and opsToVectorize2 we only", "# d2pr_dEs[i,j,J0+J] = sum_k dEP[k,J] dot(dGs, rho)[i,j,k,0] # d2pr_dEs[i,j,J0+J] = dot( squeeze(dot(dGs, rho),axis=(3,)),", "are zero except the (i,j) entry == 1 # if vec(.) concatenates rows", "being 0. In # this case set to zero since we can't tell", "OK if infs occur here _np.seterr(**old_err) if bReturnProds: Gs = evalTree.final_view(prodCache, axis=0) #shape", "derivative columns if prMxToFill is not None: self._fill_result_tuple((prMxToFill,), evalSubTree, slice(None), slice(None), calc_and_fill_p) profiler.mem_check(\"bulk_fill_dprobs:", "# scale cache # mem += cache_size # scale vals # #elif fnName", "when the *second* derivative is taken. If there are more processors than model", "# scale vals elif fnName == \"bulk_hprobs_by_block\": #Note: includes \"results\" memory since this", "__init__(self, dim, simplified_op_server, paramvec): \"\"\" Construct a new MatrixForwardSimulator object. Parameters ---------- dim", "vec( A * X * B ) = A tensor B^T * vec(", "for simultaneously. None means compute all requested columns at once. The minimum of", "wrtBlockSize=None, profiler=None, gatherMemLimit=None): \"\"\" Compute the outcome probability-derivatives for an entire tree of", "exponent if H.max() < PSMALL and H.min() > -PSMALL: nG = max(_nla.norm(G), _np.exp(-scale_exp))", "for i in range(self.Np): dpr_dOps[0, i] = float(_np.dot(E, _np.dot(dprod_dOps[i], rho))) #Derivs wrt SPAM", "elements(%d)!\" % (self.Np**2) + \" [blkSize = {%.1f,%.1f}, nBlks={%d,%d}]\" % (blkSize1, blkSize2, nBlks1,", "G(M+1) ... G(L-1) tensor (G(L+1) ... GN)^T vec( dG(L)/dij ) ] # noqa", "wrtFilter2 dictates block if blkSize1 is None and blkSize2 is None: #Fill hessian", "below) dGs1[_np.isnan(dGs1)] = 0 # convert nans to zero, as these occur b/c", "**) -- TODO: should also conjugate() here if complex? _fas(dpr_dEs, [0, EVec.gpindices], _np.dot(derivWrtAnyEvec,", "size that makes maximal use of available processors is used as the final", "# compare with older slower version that should do the same thing (for", "we can't do any further parallelization _mpit.gather_slices(deriv2Slices, deriv2Owners, hProdCache, [None, myDeriv1ColSlice], 2, mySubComm)", "ident = _np.identity(dim) for (i, opLabel1) in enumerate(revOpLabelList): # loop over \"starting\" gate", "-- note that we *cannot* make use of a tree being # split", "flat : bool, optional Affects the shape of the returned derivative array (see", "numSubtreeComms): \"\"\" Constructs an EvalTree object appropriate for this calculator. Parameters ---------- simplified_circuits", "% strToPrint) #DEBUG: print \"backtrace\" of product leading up to nan #G =", "track timing and memory usage. gatherMemLimit : int, optional A memory limit in", "len(circuit_list), nDerivColsX, dim, dim ), # dGs[i] is dprod_dOps for ith string hGs", "* _np.dot(prod, rhoVec.deriv_wrt_params()) # may generate overflow, but OK _fas(d2pr_dErhos, [0, EVec.gpindices, self.sos.get_prep(rholabel).gpindices],", "is SLOW! hProdCache[i] /= _np.exp(scale) if hProdCache[i].max() < HSMALL and hProdCache[i].min() > -HSMALL:", "derivWrtAnyRhovec = scale * _np.dot(E, prod) dpr_drhos = _np.zeros((1, self.Np)) _fas(dpr_drhos, [0, self.sos.get_prep(rholabel).gpindices],", "*not* mySubComm (this is ok, see \"if\" condition above) _mpit.gather_slices(deriv1Slices, deriv1Owners, hProdCache, [],", "parameters if wrtSlice1 == wrtSlice2: # Note: this doesn't involve gate derivatives d2pr_dErhos2", "None, E_gpindices2], _np.dot(dp_dAnyE, devec)) # get d2pr_dEs where gate derivatives are wrt the", "axis 1 of mxToFill[felInds], dim=(ks,M,M) _mpit.gather_slices(blocks1, blk1Owners, mxToFill, [felInds], 1, mySubComm, gatherMemLimit) if", "consolidate?) #NOTE: filtering is done via the yet-to-be-defined local variables # wrtSlice1 and", "of `evalTree`. Parameters ---------- mxToFill : numpy ndarray an already-allocated ExM numpy array", "dependence on their parameters. if self.sos.get_prep(rholabel).has_nonzero_hessian(): derivWrtAnyRhovec = scale * _np.dot(E, prod) #", "bulk_fill_dprobs(...), but where M is the number of model parameters selected for the", "import itertools as _itertools import collections as _collections from ..tools import mpitools as", "+= cache_size * nspam * (wrtLen1 + wrtLen2) # dprobs1 & dprobs2 mem", "# axes = (model_parameter1, model_parameter2, model_element_row, model_element_col) def prs(self, rholabel, elabels, circuit, clipTo,", "gates #Also Cache gate jacobians (still relatively little mem required) dop_dopLabel1 = {", "hessians : numpy array * if flat == False, an array of shape", "(opmx / ng, _np.log(ng)) gate, ex = scaledGatesAndExps[lOp] H = _np.dot(gate, G) #", "into blocks of at most blkSize assert(wrtFilter is None) # cannot specify both", "a part of MPI processor syncronization. Returns ------- None \"\"\" if wrtFilter1 is", "for opLabel in revOpLabelList: G = _np.dot(G, self.sos.get_operation(opLabel).todense()) leftProds.append(G) rightProdsT = [] G", "If True, perform extra checks within code to verify correctness, generating warnings when", "to denote the elementary matrix where all entries are zero except the (i,j)", "_np.zeros((nCircuits, nDerivCols1, nDerivCols2)) drho = rhoVec.deriv_wrt_params(rho_wrtFilter2) dp_dAnyE = _np.dot(Gs, drho) * scaleVals[:, None,", "if deriv1MxToFill is not None: _fas(deriv1MxToFill, [fInds, pslc1], self._dprobs_from_rhoE( spamTuple, rho, E, Gs[gInds],", "[] for iSubTree in mySubTreeIndices: evalSubTree = subtrees[iSubTree] felInds = evalSubTree.final_element_indices(evalTree) #Free memory", "of many gate sequence probabilities can often be computed column-by-column from the using", "None \"\"\" tStart = _time.time() if profiler is None: profiler = _dummy_profiler if", "additionally return the probabilities. bScale : bool, optional When True, return a scaling", "= wrtBlockSize1 # could be None blkSize2 = wrtBlockSize2 # could be None", "+ 1) elif len(relevant_gpindices) == 0: #Don't return a length-0 list, as this", "the i-th operation sequence product with respect to the k-th then j-th model", "= squeeze(dot(E, dGs, drhoP),axis=(0,))[:,:,J] drho = rhoVec.deriv_wrt_params(rho_wrtFilter2) d2pr_drhos1 = _np.zeros((nCircuits, nDerivCols1, nDerivCols2)) _fas(d2pr_drhos1,", "blkComm is not None: _warnings.warn(\"Note: more CPUs(%d)\" % mySubComm.Get_size() + \" than derivative", "hproduct(self, circuit, flat=False, wrtFilter1=None, wrtFilter2=None): \"\"\" Compute the hessian of a specified sequence", "%s)\" \\ # % (nDerivCols, str(allDerivColIndices), comm.Get_rank(), str(myDerivColIndices))) if mySubComm is not None", "== 1: #Don't return a length-1 list, as this doesn't index numpy arrays", "and outcomes, you'll need the mappings generated when the original list of `Circuits`", "_np.zeros((1, self.Np, self.Np)) _fas(d2pr_drhos, [0, None, self.sos.get_prep(rholabel).gpindices], _np.dot(_np.dot(E, dprod_dOps), rhoVec.deriv_wrt_params())[0]) # (= [0,:,:])", "= _np.zeros((nCircuits, nDerivCols2, nDerivCols1)) drho = rhoVec.deriv_wrt_params(rho_wrtFilter1) dp_dAnyE = _np.dot(Gs, drho) * scaleVals[:,", "_np.array(relevant_gpindices, _np.int64) if len(relevant_gpindices) == 1: #Don't return a length-1 list, as this", "[dprod/d(opLabel)_ij]_kl rho_l # dpr/d(rho)_i = sum E_k prod_ki # dpr/d(E)_i = sum prod_il", "deriv cells, give a # warning -- note that we *cannot* make use", "list # d2pr_dOps2[i,j,k] = sum_l,m E[0,l] hGs[i,j,k,l,m] rho[m,0] # d2pr_dOps2[i,j,k] = sum_l E[0,l]", "scaleCache[i] = scaleCache[iLeft] + scaleCache[iRight] if prodCache[i].max() < PSMALL and prodCache[i].min() > -PSMALL:", "0, 2) * scaleVals, 0, 2) # may overflow, but ok _np.seterr(**old_err) return", "; may overflow but OK def _dprobs_from_rhoE(self, spamTuple, rho, E, Gs, dGs, scaleVals,", "%.2fGB)\" % (mxToFill.nbytes / (1024.0**3))) ## memory profiling of python objects (never seemed", "default_distribute_method(self): \"\"\" Return the preferred MPI distribution mode for this calculator. \"\"\" return", "end\") def bulk_fill_hprobs(self, mxToFill, evalTree, prMxToFill=None, deriv1MxToFill=None, deriv2MxToFill=None, clipTo=None, check=False, comm=None, wrtFilter1=None, wrtFilter2=None,", "_np.dot(sL, sR); scaleCache[i] += _np.log(nL) + _np.log(nR) #print \"bulk_product DEBUG: %d rescalings out", "_MatrixEvalTree() evTree.initialize(simplified_circuits, numSubtreeComms) return evTree def estimate_mem_usage(self, subcalls, cache_size, num_subtrees, num_subtree_proc_groups, num_param1_groups, num_param2_groups,", "scaleVals, 0, 2) # may overflow, but ok _np.seterr(**old_err) return Gs def bulk_dproduct(self,", "set to True, additionally return the probabilities. bScale : bool, optional When True,", "ret ## BEGIN CACHE FUNCTIONS def _compute_product_cache(self, evalTree, comm=None): \"\"\" Computes a tree", "probabilities. bScale : bool, optional When True, return a scaling factor (see below).", "self.dproduct(circuit) dpr_dOps = _np.empty((1, self.Np)) for i in range(self.Np): dpr_dOps[0, i] = float(_np.dot(E,", "clipTo[1]) #Derivs wrt SPAM derivWrtAnyRhovec = scale * _np.dot(E, prod) dpr_drhos = _np.zeros((1,", "to distribute columns allDerivColSlice = slice(0, nDerivCols) if (wrtSlice is None) else wrtSlice", "drho = rhoVec.deriv_wrt_params(rho_wrtFilter2) dp_dAnyE = _np.dot(Gs, drho) * scaleVals[:, None, None] # overflow", "sequences found in an evaluation tree, `evalTree`. An initial list of (general) :class:`Circuit`", ": 2-tuple, optional (min,max) to clip return value if not None. check :", "= \\ _mpit.distribute_indices(list(range(nBlks2)), blk1Comm) if blk2Comm is not None: _warnings.warn(\"Note: more CPUs(%d)\" %", "dim mxs corresponding to a single kl xv = _np.swapaxes(xv, 1, 2) y", "rho,E b/c rho,E are EVec = self.sos.get_effect(elabel) # arrays, these are SPAMVecs nCircuits", "== the number of entries in a single flattened gate (ordering as numpy.flatten)", "myDeriv2ColSlice = slice(0,0) # #don't compute anything on \"extra\", i.e. rank != 0,", "% comm.Get_size()) # parallelize of deriv cols, then sub-trees (if available and necessary)", "and single-gate-strings) for i in evalTree.get_evaluation_order(): tm = _time.time() # combine iLeft +", "tuple(reversed(tuple(circuit))) # prod = G1 * G2 * .... * GN , a", "nDerivCols, dim, dim ), # dGs[i] is dprod_dOps for ith string if not", "of the now un-vectorized dim x dim mxs corresponding to a single kl", "of available processors is used as the final block size. These arguments must", "else: d2pr_dEs2 = _np.zeros((nCircuits, nDerivCols2, nDerivCols1)) dp_dAnyE = _np.squeeze(_np.dot(dGs2, rho), axis=(3,)) * scaleVals[:,", "*ordered* dictionaries to specify a well-defined column ordering when taking derivatives. paramvec :", "myDerivColSlice, _, mySubComm = \\ _mpit.distribute_slice(allDerivColSlice, comm) #print(\"MPI: _compute_dproduct_cache over %d cols (%s)", "_warnings.warn(\"Increased speed could be obtained\" \" by giving hproduct cache computation\" \" *fewer*", "wrtSlice2=None): if self.evotype == \"statevec\": raise NotImplementedError(\"Unitary evolution not fully supported yet!\") rholabel,", "rhoVec.deriv_wrt_params(rho_wrtFilter2) dp_dAnyE = _np.dot(Gs, drho) * scaleVals[:, None, None] # overflow OK devec", "mySubTreeIndices]))) #eval on each local subtree #my_results = [] for iSubTree in mySubTreeIndices:", "_mpit.gather_slices(blocks, blkOwners, mxToFill, [felInds], 1, mySubComm, gatherMemLimit) #note: gathering axis 1 of mxToFill[felInds],", "performed over subtrees of evalTree (if it is split), and then over blocks", "# and not d2(prod)/d(gl2)d(gl1) ... if m < l: x0 = _np.kron(_np.transpose(prods[(0, m", "== M} [ G1 ... G(M-1) tensor (G(M+1) ... GN)^T vec( d2G(M)/dkl*dji )", "reconstruct the parent tree's *non-final* elements from those of the sub-trees). Note also", "leftProds.append(G) for opLabel in revOpLabelList: G = _np.dot(G, self.sos.get_operation(opLabel).todense()) leftProds.append(G) rightProdsT = []", "squeeze(dot(E, Gs, drhoP),axis=(0,))[:,J] dp_drhos = _np.zeros((nCircuits, nDerivCols)) _fas(dp_drhos, [None, rho_gpindices], _np.squeeze(_np.dot(_np.dot(E, Gs), rhoVec.deriv_wrt_params(rho_wrtFilter)),", "\"\"\" tm = _time.time() old_err = _np.seterr(over='ignore') rho, E = self._rhoE_from_spamTuple(spamTuple) if prMxToFill", "comm) if clipTo is not None and prMxToFill is not None: _np.clip(prMxToFill, clipTo[0],", "(if given) is possible. wrtFilter1, wrtFilter2 : list of ints, optional If not", "M numpy array, where M is the number of model parameters. Parameters ----------", "(wrtFilter is None) else _slct.length(wrtFilter) dim = self.dim wrtSlice = _slct.list_to_slice(wrtFilter) if (wrtFilter", "same) Parameters ---------- rholabel : Label The state preparation label. elabels : list", "d2pr_dErhos[i,J0+J,K0+K] = swapaxes(dot(dEPT,prod,drhoP),0,1)[i,J,K] # d2pr_dErhos[:,J0+J,K0+K] = swapaxes(dot(dEPT,prod,drhoP),0,1)[:,J,K] d2pr_dErhos1 = _np.zeros((nCircuits, nDerivCols1, nDerivCols2)) drho", "# in-place clip if check: self._check(evalTree, prMxToFill, mxToFill, clipTo=clipTo) profiler.add_time(\"bulk_fill_dprobs: total\", tStart) profiler.add_count(\"bulk_fill_dprobs", "derivative of the entire operation sequence # with respect to only that gate's", "at most linear in their parameters, this # isn't currently needed. N =", "in `mxToFill`, which must have length equal to the number of final elements", "mem def _fill_result_tuple(self, result_tup, evalTree, param_slice1, param_slice2, calc_and_fill_fn): \"\"\" This function takes a", "wrtSlice1.start) else: myHessianSlice1 = myDeriv1ColSlice #print(\"MPI: _compute_hproduct_cache over %d cols (rank %d computing", "list of ints, optional If not None, a list of integers specifying which", "to compute the bulk operation on. clipTo : 2-tuple, optional (min,max) to clip", "wrtSlice1=None, wrtSlice2=None): if self.evotype == \"statevec\": raise NotImplementedError(\"Unitary evolution not fully supported yet!\")", "parameters) - G == the linear dimension of a operation matrix (G x", "(nDerivCols2, comm.Get_rank(), str(myDerivColSlice))) if mySubComm is not None and mySubComm.Get_size() > 1: deriv2Slices,", "x G x G; products[i] is the i-th operation sequence product. scaleVals :", "computation across blocks myBlk1Indices, blk1Owners, blk1Comm = \\ _mpit.distribute_indices(list(range(nBlks1)), mySubComm) myBlk2Indices, blk2Owners, blk2Comm", "columns of the operation sequences. Parameters ---------- spam_label_rows : dictionary a dictionary with", "0))) # _np.einsum('ij,jkl->ikl',derivWrtAnyEvec,self.sos.get_effect(elabel).hessian_wrt_params()) else: d2pr_d2Es = 0 ret = d2pr_dErhos + _np.transpose(d2pr_dErhos, (0,", "there are no memory savings from using a split tree. \"\"\" dim =", "has shape (len(elabels),N) return rho, Es def _probs_from_rhoE(self, rho, E, Gs, scaleVals): if", "return hProdCache # ------------------------------------------------------------------ if evalTree.is_split(): _warnings.warn(\"Ignoring tree splitting in hproduct cache calc.\")", "indices\" = indices into the (tree-) list of # all of the raw", "vec_ij_size = flattened_d2prod.shape[1:3] # == num_deriv_cols1, num_deriv_cols2 return _np.rollaxis(flattened_d2prod, 0, 3).reshape((vec_kl_size, vec_ij_size, dim,", "# if vec(.) stacks columns # vec( A * E(0,1) * B )", "= \"final indices\" = the \"element\" indices in the final # filled quantity", "once). But since we're # assuming that the gates are at most linear", "latter if `bReturnDProbs12 == True`). `rowSlice` and `colSlice` are slices directly from `wrtSlicesList`.", "and derivatives-of-product calculations. This is contained in a class separate from Model to", "array that is filled with probabilities, just like in bulk_fill_probs(...). clipTo : 2-tuple,", "Note when vectorizing op uses numpy.flatten rows are kept contiguous, so the first", "which must have length equal to the number of final elements (this can", "and `colSlice` are slices directly from `wrtSlicesList`. `hprobs` and `dprobs12` are arrays of", "# So for each opLabel the matrix [ sum_{L s.t. GL == oplabel}", "and fill appropriate columns of flattened_dprod. #gate = self.sos.get_operation[opLabel] UNNEEDED (I think) _fas(flattened_dprod,", "d2pr_drhos2 = _np.transpose(d2pr_drhos1, (0, 2, 1)) else: drho = rhoVec.deriv_wrt_params(rho_wrtFilter1) d2pr_drhos2 = _np.zeros((nCircuits,", "calc.\") hProdCache = _np.zeros((cacheSize,) + hessn_shape) #First element of cache are given by", "model parameter. * if flat == True, an array of shape S*N x", "dGs def bulk_hproduct(self, evalTree, flat=False, bReturnDProdsAndProds=False, bScale=False, comm=None, wrtFilter1=None, wrtFilter2=None): \"\"\" Return the", "when set to True, additionally return the probabilities. bScale : bool, optional When", "useful when memory constraints make constructing the entire Hessian at once impractical, and", "\"if\" condition above) _mpit.gather_slices(deriv1Slices, deriv1Owners, hProdCache, [], 1, comm) #, gatherMemLimit) #gather over", "empty label == no gate prodCache[i] = _np.identity(dim) # Note: scaleCache[i] = 0.0", "(wrtSlice is not None) else None for i, opLabel in zip(evalTree.get_init_indices(), evalTree.get_init_labels()): if", "(len(elabels),N) return rho, Es def _probs_from_rhoE(self, rho, E, Gs, scaleVals): if self.evotype ==", "each local subtree for iSubTree in mySubTreeIndices: evalSubTree = subtrees[iSubTree] #Free memory from", "original wrtFilter'd indices gpindices = obj.gpindices_as_array() for ii, i in enumerate(wrtFilter): if i", "- %g = %g\" % (_nla.norm(prMxToFill[fInds]), _nla.norm(check_vp), _nla.norm(prMxToFill[fInds] - check_vp))) # pragma: no", "= evalSubTree.final_view(dProdCache1, axis=0) for iBlk2 in myBlk2Indices: blk_wrtSlice2 = blocks2[iBlk2] if blk_wrtSlice1 ==", "for only a single spam label (specified to it by the first two", "---------- subcalls : list of strs A list of the names of the", "E, Gs[gInds], scaleVals[gInds]), add=sumInto) _np.seterr(**old_err) profiler.add_time(\"bulk_fill_dprobs: calc_and_fill_p\", tm) # Compute all probabilities all", "pragma: no cover def calc_and_fill_blk(spamTuple, fInds, gInds, pslc1, pslc2, sumInto): \"\"\" Compute and", ": list A list of `(rowSlice,colSlice)` 2-tuples, each of which specify a \"block\"", "for t in subtrees] _mpit.gather_indices(subtreeElementIndices, subTreeOwners, mxToFill, [], 0, comm) #note: pass mxToFill,", "a zero deriv value (see below) dGs1[_np.isnan(dGs1)] = 0 # convert nans to", "is fixed ## (and dominated) by the output array size. Could throw more", "(or array) # objects: (prepVec, effectVec) rho, Eraw = spamTuple E = _np.conjugate(_np.transpose(Eraw))", "in gpindices: relevant_gpindices.append(ii) obj_wrtFilter.append(list(gpindices).index(i)) relevant_gpindices = _np.array(relevant_gpindices, _np.int64) if len(relevant_gpindices) == 1: #Don't", "matrix dim = self.dim #Cache partial products (relatively little mem required) leftProds =", "compute this gate hessian once). But since we're # assuming that the gates", "elements (i.e. probabilities) to gate-only sequence and prep/effect pairs. The evaluation tree organizes", "a non-zero hessian x0 = _np.kron(_np.transpose(prods[(0, m - 1)]), prods[(m + 1, N", "model parameters. evalTree : EvalTree given by a prior call to bulk_evaltree. Specifies", "these occur b/c an inf scaleVal is mult by a zero hessian value", "for spamTuple, (fInds, gInds) in evalTree.spamtuple_indices.items(): circuit_list = master_circuit_list[gInds] if prMxToFill is not", "results tm = _time.time() subtreeElementIndices = [t.final_element_indices(evalTree) for t in subtrees] _mpit.gather_indices(subtreeElementIndices, subTreeOwners,", "products within decent bounds #assert( len( (_np.isnan(dGs)).nonzero()[0] ) == 0 ) #assert( len(", "* _np.dot(E, prod) _fas(dpr_drhos, [0, self.sos.get_prep(rholabel).gpindices], _np.dot(derivWrtAnyRhovec, rhoVec.deriv_wrt_params())) # may overflow, but OK", "(to save mem) but isn't gathered until now (but using blk1Comm). # (just", "of all the derivative columns, essentially taking # a derivative of only a", "(1, 2, 0, 3)) scale = scaleCache[i] - (scaleCache[iLeft] + scaleCache[iRight]) if abs(scale)", "itself. returnDeriv : bool when set to True, additionally return the derivative of", "MATRIX ORDER # we do matrix multiplication in this order (easier to think", "+ \\ d2pr_dEs + _np.transpose(d2pr_dEs, (0, 2, 1)) + \\ d2pr_d2rhos + d2pr_d2Es", "if wrtFilter is not None. Set this to non-None to reduce amount of", "# noqa # [ G1 ... G(M-1) dG(M)/dkl G(M+1) ... G(L-1) dG(L)/dij G(L+1)", "All operation matrices should be dim x dim, and all SPAM vectors should", "return values old_err = _np.seterr(over='ignore') scaleExps = evalTree.final_view(scaleCache) scaleVals = _np.exp(scaleExps) # may", "dProdCache = None #Fill cache info (not requiring column distribution) tm = _time.time()", "profiler) profiler.add_time(\"bulk_fill_dprobs: compute_dproduct_cache\", tm) profiler.mem_check( \"bulk_fill_dprobs: post compute dproduct blk (expect \" \"", "wrt SPAM derivWrtAnyRhovec = scale * _np.dot(E, prod) dpr_drhos = _np.zeros((1, self.Np)) _fas(dpr_drhos,", "model parameters. * if flat == True, an array of shape S*N x", "which model parameters to differentiate with respect to in the first (row) and", "to computation functions. Parameters ---------- subcalls : list of strs A list of", "derivatives. paramvec : ndarray The parameter vector of the Model. autogator : AutoGator", "> -PSMALL: nL, nR = max(_nla.norm(L), _np.exp(-scaleCache[iLeft]), 1e-300), max(_nla.norm(R), _np.exp(-scaleCache[iRight]), 1e-300) sL, sR", "over subtrees of evalTree (if it is split), and then over blocks (subsets)", "previous subtree iteration before computing caches scaleVals = Gs = prodCache = scaleCache", "blk2Owners, mxToFill, [felInds, blocks1[iBlk1]], 2, blk1Comm, gatherMemLimit) #gather row results; gather axis 1", "dim, dim ) def calc_and_fill(spamTuple, fInds, gInds, pslc1, pslc2, sumInto): \"\"\" Compute and", "= _np.squeeze(_np.dot(E, _np.dot(hGs, rho)), axis=(0, 4)) * scaleVals[:, None, None] _np.seterr(**old_err2) # may", "is not None: # loc_rho_slices = [ # _slct.shift(_slct.intersect( # wrtSlices['preps'], # slice(self.rho_offset[i],self.rho_offset[i+1])),", "when taking derivatives. paramvec : ndarray The parameter vector of the Model. autogator", "> nDerivCols1 * nDerivCols2: #If there are more processors than deriv cells, give", "This aids in the tree construction by giving the tree information it needs", "_nla.norm(check_vdp), _nla.norm(dprMxToFill[fInds] - check_vdp))) # pragma: no cover if hprMxToFill is not None:", "already-allocated ExM numpy array that is filled with probability derivatives, similar to bulk_fill_dprobs(...),", "used as the final block size. These arguments must be None if the", "respect to the j-th model parameter. * if flat == True, an array", "drho), axis=(0,)) * scaleVals[:, None, None]) # overflow OK d2pr_drhos2 = _np.transpose(d2pr_drhos2, (0,", "# evotype == \"densitymx\" # probability, with scaling applied (may generate overflow, but", "G = _np.dot(G,self[lOp]) # product of gates, starting with G0 # nG =", "= 0 ret = d2pr_dErhos + _np.transpose(d2pr_dErhos, (0, 2, 1)) + \\ d2pr_drhos", "_check(self, evalTree, prMxToFill=None, dprMxToFill=None, hprMxToFill=None, clipTo=None): # compare with older slower version that", "blk_wrtSlice2) hGs = evalSubTree.final_view(hProdCache, axis=0) #Set filtering for calc_and_fill wrtSlice1 = blocks1[iBlk1] wrtSlice2", "numpy array a 1 x M numpy array of derivatives of the probability", "for s in loc_e_slices] # tmp_offsets = [ sum(tmp_num_params[0:i]) for i in range(len(self.effects)+1)", "num_deriv_cols1, num_deriv_cols2), 'd') if _slct.length(gpindices1) > 0 and _slct.length(gpindices2) > 0: # works", "cache any nonzero gate hessians (memory?) hop_dopLabels = {} for opLabel, gate in", "= self.Np if wrtSlice1 is None else _slct.length(wrtSlice1) nDerivCols2 = self.Np if wrtSlice2", "dim, dim ) #Compute all requested derivative columns at once self._fill_result_tuple((prMxToFill, deriv1MxToFill, deriv2MxToFill,", "_np.clip(prMxToFill, clipTo[0], clipTo[1], out=prMxToFill) # in-place clip if check: self._check(evalTree, prMxToFill, deriv1MxToFill, mxToFill,", "1) elif len(relevant_gpindices) == 0: #Don't return a length-0 list, as this doesn't", "available processors is used as the final block size. This argument must be", "elif _np.count_nonzero(dProdCache[i]) and dProdCache[i].max() < DSMALL and dProdCache[i].min() > -DSMALL: _warnings.warn(\"Would have scaled", "= _np.zeros((nCircuits, nDerivCols1, nDerivCols2)) dp_dAnyE = _np.squeeze(_np.dot(dGs1, rho), axis=(3,)) * scaleVals[:, None, None]", "dProdCache2 = dGs2 = None # free mem dProdCache1 = dGs1 = None", "can be done efficiently by actually computing X^T ( note (A tensor B)^T", "the symmetry of the Hessian, so that # if gl1 and gl2 are", "local subtree for iSubTree in mySubTreeIndices: evalSubTree = subtrees[iSubTree] #Free memory from previous", "to the i-th model parameter. * if flat == True, a N x", "array a 1 x M numpy array of derivatives of the probability w.r.t.", "axis=(0,4)) old_err2 = _np.seterr(invalid='ignore', over='ignore') d2pr_dOps2 = _np.squeeze(_np.dot(E, _np.dot(hGs, rho)), axis=(0, 4)) *", "large all the storage arrays are. np1, np2 = num_param1_groups, num_param2_groups FLOATSIZE =", "= subtrees[iSubTree] #Free memory from previous subtree iteration before computing caches scaleVals =", "compute_product_cache\", tm) #use cached data to final values scaleVals = self._scaleExp(evalSubTree.final_view(scaleCache)) Gs =", "blocks, in the order given by `wrtSlicesList`. `rowSlice` and `colSlice` must by Python", "named by `subcalls`. num_subtrees : int The number of subtrees to split the", "None, rho_gpindices1], _np.squeeze(_np.dot(_np.dot(E, dGs2), drho), axis=(0,)) * scaleVals[:, None, None]) # overflow OK", "-- TODO: should also conjugate() here if complex? _fas(dpr_dEs, [0, EVec.gpindices], _np.dot(derivWrtAnyEvec, EVec.deriv_wrt_params()))", "= _np.dot(dL, R) + \\ _np.swapaxes(_np.dot(L, dR), 0, 1) # dot(dS, T) +", "return the derivative of the probability. clipTo : 2-tuple (min,max) to clip returned", "blkSize = comm_blkSize if (blkSize is None) \\ else min(comm_blkSize, blkSize) # override", "\"Deriv1\" row-derivatives distribution only; don't use column distribution hProdCache[:, myDeriv1ColSlice] = self._compute_hproduct_cache( evalTree,", "+ # 'e_local_slices e_global_slices num_rho_params num_e_params') # # if wrtSlices is not None:", "]] # noqa # # So for each opLabel the matrix [ sum_{L", "if it isn't specified if wrtFilter1 is None and wrtFilter2 is None: blkSize1", "= %g, norm %g, exp %g\\n%s\" % (i,p,norm(G),total_exp,str(G)) # if _np.isnan(p): raise ValueError(\"STOP\")", "opmx = self.sos.get_operation(lOp).todense() ng = max(_nla.norm(opmx), 1.0) scaledGatesAndExps[lOp] = (opmx / ng, _np.log(ng))", "= _np.squeeze(_np.dot(dGs2, rho), axis=(3,)) * scaleVals[:, None, None] # overflow OK devec =", "Gs[gInds], scaleVals[gInds]), add=sumInto) if deriv1MxToFill is not None: _fas(deriv1MxToFill, [fInds, pslc1], self._dprobs_from_rhoE( spamTuple,", "is just a matrix of parameters, then dG(L)/dij = E(i,j), an elementary matrix", "#distribute derivative computation across blocks myBlk1Indices, blk1Owners, blk1Comm = \\ _mpit.distribute_indices(list(range(nBlks1)), mySubComm) myBlk2Indices,", "of entries in a single flattened gate (ordering as numpy.flatten), - S,M ==", "are filled internally to `calc_and_fill_fn` must be the same as the elements of", "# _np.isclose(scale,0) is SLOW! hProdCache[i] /= _np.exp(scale) if hProdCache[i].max() < HSMALL and hProdCache[i].min()", "[ G1 ... G(L-1) tensor # noqa # ( unvec( G(L+1) ... G(M-1)", "# -self.rho_offset[i]) for i in range(len(self.preps))] # tmp_num_params = [_slct.length(s) for s in", "(>= starting gate) G = _np.dot(G, self.sos.get_operation(opLabel2).todense()) prods[(i, j)] = G prods[(len(revOpLabelList), len(revOpLabelList)", "are more processors than model parameters, distribution over a split evalTree (if given)", "will overflow and the subsequent trace operation will yield nan as the returned", "self.dim nspam = int(round(_np.sqrt(self.dim))) # an estimate - could compute? wrtLen1 = (self.Np", "+ 1, l - 1)]) # (dim**2, dim**2) x = _np.dot(_np.transpose(dop_dopLabel1[opLabel1]), x0); xv", "mem += cache_size * num_params * dim * dim # dproduct cache #", "T) + dot(S, dT) profiler.add_time(\"compute_dproduct_cache: dots\", tm) profiler.add_count(\"compute_dproduct_cache: dots\") scale = scaleCache[i] -", "0 # END SPAM DERIVS ----------------------- ret = d2pr_d2rhos + d2pr_dErhos2 + d2pr_drhos2", "= float(_np.dot(E, _np.dot(dprod_dOps[i], rho))) if returnPr: p = _np.dot(E, _np.dot(prod, rho)) * scale", "- (scaleCache[iLeft] + scaleCache[iRight]) if abs(scale) > 1e-8: # _np.isclose(scale,0) is SLOW! hProdCache[i]", "labels which specify the operation sequences to create an evaluation tree out of", "0))) # _np.einsum('ij,jkl->ikl', derivWrtAnyRhovec, self.sos.get_prep(rholabel).hessian_wrt_params()) else: d2pr_d2rhos = 0 if self.sos.get_effect(elabel).has_nonzero_hessian(): derivWrtAnyEvec =", "communicator for distributing the computation across multiple processors. Distribution is performed over subtrees", "* B ) = A tensor B^T * vec( X ) # if", "/ mySubComm.Get_size() blkSize = comm_blkSize if (blkSize is None) \\ else min(comm_blkSize, blkSize)", "bytes: TODO: a better way dim = self.dim nspam = int(round(_np.sqrt(self.dim))) # an", "== nDerivCols2), \"dGs1 must be pre-filtered!\" # Get: d2pr_drhos[i, j, rho_gpindices] = dot(E,dGs[i,j],drho/drhoP))", "needed) subtrees = evalTree.get_sub_trees() mySubTreeIndices, subTreeOwners, mySubComm = evalTree.distribute(comm) #eval on each local", "function, which computes and *fills* (i.e. doesn't return to save copying) some arrays.", "that results in a zero dimension else: obj_wrtFilter = None relevant_gpindices = obj.gpindices", "block of flattened_d2prod. #NOTE: if we needed to perform a hessian calculation (i.e.", "int The number of final strings (may be less than or greater than", "column distribution) tm = _time.time() prodCache, scaleCache = self._compute_product_cache(evalSubTree, mySubComm) profiler.add_time(\"bulk_fill_dprobs: compute_product_cache\", tm)", "the right single-gate-strings w/indices wrtIndices = _slct.indices(wrtSlice) if (wrtSlice is not None) else", "0, cpus hProdCache[:, myDeriv1ColSlice, myDeriv2ColSlice] = self._compute_hproduct_cache( evalTree, prodCache, dProdCache1[:, myDeriv1ColSlice], dProdCache2[:, myDeriv2ColSlice],", "None: check_vp = _np.array([self.prs(spamTuple[0], [spamTuple[1]], circuit, clipTo, False)[0] for circuit in circuit_list]) if", "argument is a boolean specifying whether the filling should overwrite or add to", "optional (min,max) to clip return value if not None. check : boolean, optional", "# noqa # # Note: ignoring L == M terms assumes that d^2", "%g\" % (_nla.norm(dprMxToFill[fInds]), _nla.norm(check_vdp), _nla.norm(dprMxToFill[fInds] - check_vdp))) # pragma: no cover if hprMxToFill", "# since all scaled gates start with norm <= 1, products should all", "if clipTo is not None: ret = _np.clip(ps, clipTo[0], clipTo[1]) else: ret =", "rho_l # d2pr/d(rho)_i d(opLabel)_mn = sum E_k [dprod/d(opLabel)_mn]_ki (and same for other diff", "t in subtrees] _mpit.gather_indices(subtreeElementIndices, subTreeOwners, mxToFill, [], 0, comm, gatherMemLimit) #note: pass mxToFill,", "if wrtFilter1 == wrtFilter2: dop_dopLabel2 = dop_dopLabel1 else: dop_dopLabel2 = { opLabel: gate.deriv_wrt_params(gate_wrtFilters2[opLabel])", "list of strs A list of the names of the subcalls to estimate", "self._rhoE_from_spamTuple(spamTuple) block_wrtSlice = pslc1 _fas(mxToFill, [fInds, pslc1], self._dprobs_from_rhoE( spamTuple, rho, E, Gs[gInds], dGs[gInds],", "requested derivative columns at once self._fill_result_tuple((prMxToFill, mxToFill), evalSubTree, slice(None), slice(None), calc_and_fill) profiler.mem_check(\"bulk_fill_dprobs: post", "== oplabel} [ (G1 ... G(L-1)) tensor (G(L+1) ... GN)^T vec( dG(L)/dij )", "d2pr_dEs[:,:,J0+J] = dot( squeeze(dot(dGs, rho),axis=(3,)), dEP)[:,:,J] d2pr_dEs1 = _np.zeros((nCircuits, nDerivCols1, nDerivCols2)) dp_dAnyE =", "pr*dpr/dx.C # = 2 Re(dpr/dx*pr.C) , where dpr/dx is the usual density-matrix-mode probability", "float(dot(E, dot(G, rho))) # vp[i] = sum_k,l E[0,k] Gs[i,k,l] rho[l,0] * scaleVals[i] #", "trumps since we've renormed to keep all the products within decent # bounds", "slice(None), slice(None), calc_and_fill) hProdCache = hGs = dProdCache2 = dGs2 = None #", "clipTo : 2-tuple, optional (min,max) to clip return value if not None. check", "None and blkSize2 is None: #Fill hessian cache info dProdCache1 = self._compute_dproduct_cache( evalSubTree,", "d2pr_dOps2[i,j,k] = dot( E, dot( dGs, rho ) )[0,i,j,k,0] # d2pr_dOps2 = squeeze(", "nCircuits = evalTree.num_final_strings() # len(circuit_list) wrtSlice1 = _slct.list_to_slice(wrtFilter1) if (wrtFilter1 is not None)", "differentiated with respect to. If there are more processors than model parameters, distribution", "row results; gather axis 1 of mxToFill[felInds], dim=(ks,M,M) _mpit.gather_slices(blocks1, blk1Owners, mxToFill, [felInds], 1,", "save in return list (now have G,dG => product, dprod_dOps) # prod, dprod_dOps", "opLabel the matrix [ sum_{L s.t. GL == oplabel} [ (G1 ... G(L-1))", "iteration before computing caches scaleVals = Gs = prodCache = scaleCache = None", "products for the i-th operation sequence. \"\"\" nCircuits = evalTree.num_final_strings() nDerivCols = self.Np", "# shape == (len(circuit_list),) ; may overflow but OK def _dprobs_from_rhoE(self, spamTuple, rho,", "giving the tree information it needs to distribute itself among the available processors.", "# loop over \"ending\" gate (>= starting gate) G = _np.dot(G, self.sos.get_operation(opLabel2).todense()) prods[(i,", "first done over the set of parameters being differentiated with respect to when", "`rowSlice` and `colSlice` must by Python `slice` objects. bReturnDProbs12 : boolean, optional If", "None) else len(wrtFilter) flattened_dprod = _np.zeros((dim**2, num_deriv_cols), 'd') # For each operation label,", "use a post-scaled product internally. If False, this routine will run slightly faster,", "_np.seterr(**old_err) #NOTE: don't distribute wrtSlicesList across comm procs, # as we assume the", "return the probabilities and their derivatives (see below). bScale : bool, optional When", "_np.seterr(over='ignore') scale = _np.exp(scale_exp) _np.seterr(**old_err) return G, scale else: G = _np.identity(self.dim) for", "wrtFilter -> wrtSlice? prodCache, scaleCache = self._compute_product_cache(evalTree, comm) dProdCache1 = self._compute_dproduct_cache(evalTree, prodCache, scaleCache,", "(hGs, dGs1, dGs2, Gs) else: hGs = evalTree.final_view(hProdCache, axis=0) #shape == ( len(circuit_list),", "matrix (G x G operation matrices). and deriv[i,j,k] holds the derivative of the", "assert(nDerivCols1 == nDerivCols2) d2pr_dEs2 = _np.transpose(d2pr_dEs1, (0, 2, 1)) else: d2pr_dEs2 = _np.zeros((nCircuits,", "the user. mem += 2 * cache_size * nspam * wrtLen1 * wrtLen2", "blkComm, block_wrtSlice, profiler) profiler.add_time(\"bulk_fill_dprobs: compute_dproduct_cache\", tm) profiler.mem_check( \"bulk_fill_dprobs: post compute dproduct blk (expect", "* wrtLen2 * dim * dim # hproduct cache mem += cache_size *", "GL == oplabel} [ (G1 ... G(L-1)) tensor (G(L+1) ... GN)^T ]] has", "cache_size # scale cache (exps) mem += cache_size # scale vals elif fnName", "an already-allocated length-E numpy array that is filled with probabilities, just like in", "dProdCache1 = self._compute_dproduct_cache( evalSubTree, prodCache, scaleCache, mySubComm, wrtSlice1) dProdCache2 = dProdCache1 if (wrtSlice1", "VS MATRIX ORDER Note: we reverse iLeft <=> iRight from evalTree because #", "self._dprobs_from_rhoE( spamTuple, rho, E, Gs[gInds], dGs[gInds], scaleVals[gInds], wrtSlice), add=sumInto) _np.seterr(**old_err) profiler.add_time(\"bulk_fill_dprobs: calc_and_fill\", tm)", "Identities. (Vectorization) # Note when vectorizing op uses numpy.flatten rows are kept contiguous,", "blk_wrtSlice1, blk_wrtSlice2) hGs = evalSubTree.final_view(hProdCache, axis=0) #Set filtering for calc_and_fill wrtSlice1 = blocks1[iBlk1]", "if complex? _fas(dpr_dEs, [0, EVec.gpindices], _np.dot(derivWrtAnyEvec, EVec.deriv_wrt_params())) _np.seterr(**old_err) if returnPr: return dpr_drhos +", "= A[i,0] * B[row1] ) = A tensor B^T * vec( E(0,1) )", "H.min() > -PSMALL: nG = max(_nla.norm(G), _np.exp(-scale_exp)) G = _np.dot(gate, G / nG);", "must be the same) Parameters ---------- rholabel : Label The state preparation label.", "a 1 x M numpy array of derivatives of the probability w.r.t. each", "that is filled with probabilities, just like in bulk_fill_probs(...). derivMxToFill1, derivMxToFill2 : numpy", "_np.identity(dim); rightProdsT.append(_np.transpose(G)) for opLabel in reversed(revOpLabelList): G = _np.dot(self.sos.get_operation(opLabel).todense(), G) rightProdsT.append(_np.transpose(G)) # Allocate", "scaleVals[gInds]), add=sumInto) _np.seterr(**old_err) self._fill_result_tuple((mxToFill,), evalSubTree, slice(None), slice(None), calc_and_fill) #collect/gather results subtreeElementIndices = [t.final_element_indices(evalTree)", "evTree.initialize(simplified_circuits, numSubtreeComms) return evTree def estimate_mem_usage(self, subcalls, cache_size, num_subtrees, num_subtree_proc_groups, num_param1_groups, num_param2_groups, num_final_strs):", "when the tree was split, but this is was # incorrect (and luckily", "mySubComm.Get_size() > 1: deriv2Slices, myDeriv2ColSlice, deriv2Owners, mySubSubComm = \\ _mpit.distribute_slice(allDeriv2ColSlice, mySubComm) # Get", "flat: return flattened_d2prod # axes = (vectorized_op_el_index, model_parameter1, model_parameter2) else: vec_kl_size, vec_ij_size =", "in a class separate from Model to allow for additional model classes (e.g.", "d2prod/d(opLabel1)_kl*d(opLabel2)_ij = sum_{M s.t. GM == gatelabel1} sum_{L s.t. GL == gatelabel2, M", "= 0 #SPAM ------------- # Get: dp_drhos[i, rho_gpindices] = dot(E,Gs[i],drho/drhoP) # dp_drhos[i,J0+J] =", "do something else LATER. def calc_and_fill(spamTuple, fInds, gInds, pslc1, pslc2, sumInto): \"\"\" Compute", "LEXICOGRAPHICAL VS MATRIX ORDER Note: we reverse iLeft <=> iRight from evalTree because", "deriv cols, give a # warning -- note that we *cannot* make use", "M} [ G1 ... G(L-1) tensor # noqa # ( unvec( G(L+1) ...", "not use this file except # in compliance with the License. You may", "- N == the number of entries in a single flattened gate (ordered", "derivative operations, respectively. Each element is an index into an array of gate", "product leading up to nan #G = _np.identity( self.dim ); total_exp = 0.0", "deriv_wrt_params # # Note: unvec( X ) can be done efficiently by actually", "!= 0, cpus my_results = self._compute_dproduct_cache( evalTree, prodCache, scaleCache, None, myDerivColSlice, profiler) #", "likely because you want to computed their probabilites). These are a \"simplified\" circuits", "Cannot be specified in conjuction with wrtBlockSize. wrtBlockSize : int or float, optional", "which, when iterated, yields the 3-tuple `(rowSlice, colSlice, hprobs)` or `(rowSlice, colSlice, dprobs12)`", "of entries in a single flattened gate (ordering same as numpy.flatten), - S,M", "the multiplicative scaling needed for the hessians, derivatives, and/or products for the i-th", "specifying which model parameters to differentiate with respect to in the first (row)", "= scaleCache = None #Fill product cache info (not requiring row or column", "blkSize1 is None and blkSize2 is None: #Fill hessian cache info dProdCache1 =", "operation sequence scaleExps = evalTree.final_view(scaleCache) old_err = _np.seterr(over='ignore') scaleVals = _np.exp(scaleExps) # may", "relevant_gpindices = obj.gpindices return obj_wrtFilter, relevant_gpindices #Vectorizing Identities. (Vectorization) # Note when vectorizing", "axis=0) #shape == ( len(circuit_list), nDerivCols1, nDerivCols2, dim, dim ), # hGs[i] is", "dGs, rho ) )[0,i,j,0] # dp_dOps = squeeze( dot( E, dot( dGs, rho", "last_wrtSlice1: dProdCache1 = dGs1 = None # free Mem dProdCache1 = self._compute_dproduct_cache( evalTree,", "= _np.clip(p, clipTo[0], clipTo[1]) dprod_dOps = self.dproduct(circuit) assert(dprod_dOps.shape[0] == self.Np) if returnDeriv: #", "gpindices1[opLabel1] nDerivCols1 = dop_dopLabel1[opLabel1].shape[1] if nDerivCols1 == 0: continue for l, opLabel2 in", "self.product(circuit, True) if self.evotype == \"statevec\": ps = _np.real(_np.abs(_np.dot(Es, _np.dot(G, rho)) * scale)**2)", "tree beforehand), as there\" \" are more cpus than derivative columns.\") # Use", "dim**2)), 2) # as above return (hGs, scaleVals) if bScale else hGs def", "add the result to the appropriate block of flattened_d2prod. #NOTE: if we needed", "- throws error if copy is needed) # transposes each of the now", "None: # loc_rho_slices = [ # _slct.shift(_slct.intersect( # wrtSlices['preps'], # slice(self.rho_offset[i],self.rho_offset[i+1])), # -self.rho_offset[i])", "spam_label_rows : dictionary a dictionary with keys == spam labels and values which", "will run slightly faster, but with a chance that the product will overflow", "[dprod/d(opLabel1)_mn d(opLabel2)_ij]_kl rho_l # d2pr/d(rho)_i d(opLabel)_mn = sum E_k [dprod/d(opLabel)_mn]_ki (and same for", "d2pr_d2rhos and d2pr_d2Es terms are always zero _np.seterr(**old_err) if returnDeriv: if returnPr: return", "EVec.gpindices, self.sos.get_prep(rholabel).gpindices], _np.dot(_np.transpose(EVec.deriv_wrt_params()), derivWrtAnyEvec)) #Note: these 2nd derivatives are non-zero when the spam", "dGs1 = evalTree.final_view(dProdCache1, axis=0) last_wrtSlice1 = wrtSlice1 if (wrtSlice1 == wrtSlice2): dProdCache2 =", "`deriv1MxToFill`), then: - `hprobs == mx[:,:,rowSlice,colSlice]` - `dprobs12 == dp1[:,:,rowSlice,None] * dp2[:,:,None,colSlice]` \"\"\"", "matrix # noqa # dprod/d(opLabel)_ij = sum_{L s.t. GL == oplabel} [ G1", "scaleVals = Gs = dGs1 = dGs2 = hGs = None prodCache =", "# distinct from rho,E b/c rho,E are EVec = self.sos.get_effect(elabel) # arrays, these", "rho), axis=(3,)) * scaleVals[:, None, None] # overflow OK devec = EVec.deriv_wrt_params(E_wrtFilter1) _fas(d2pr_dEs2,", "from `wrtSlicesList`. `hprobs` and `dprobs12` are arrays of shape K x S x", "dpr_dOps = _np.empty((1, self.Np)) for i in range(self.Np): dpr_dOps[0, i] = float(_np.dot(E, _np.dot(dprod_dOps[i],", "axis=(0,)) * scaleVals[:, None, None]) # overflow OK # get d2pr_drhos where gate", "return (dGs, scaleVals) if bScale else dGs def bulk_hproduct(self, evalTree, flat=False, bReturnDProdsAndProds=False, bScale=False,", "+ wrtLen2) * dim * dim # dproduct cache mem += cache_size *", "file except # in compliance with the License. You may obtain a copy", "# the generator and yielded, *not* allocated by the user. mem += 2", "and M1 & M2 are the number of selected gate-set parameters (by wrtFilter1", "the computation across multiple processors. Distribution is performed over subtrees of evalTree (if", "which match the current # gate (so we only need to compute this", "dGs2, Gs, scaleVals) if bScale else (hGs, dGs1, dGs2, Gs) else: hGs =", "wrtSlice2 is None else _slct.length(wrtSlice2) #flt1 = self._get_filter_info(wrtSlices1) #flt2 = self._get_filter_info(wrtSlices2) # GATE", "effects : OrderedDict Ordered dictionaries of LinearOperator, SPAMVec, and SPAMVec objects, respectively. Must", "GN)^T ]] has # columns which correspond to the vectorized derivatives of each", "_DummyProfiler from .label import Label as _Label from .matrixevaltree import MatrixEvalTree as _MatrixEvalTree", "= sum_k E[0,k] dot( dGs, rho )[i,j,k,0] # dp_dOps[i,j] = dot( E, dot(", "None: # print(\"MPI DEBUG: Rank%d subtee sizes = %s\" % # (comm.Get_rank(),\",\".join([str(len(subtrees[i])) #", "------- None \"\"\" if wrtFilter1 is not None: assert(wrtBlockSize1 is None and wrtBlockSize2", "from rho,E b/c rho,E are EVec = self.sos.get_effect(elabel) # arrays, these are SPAMVecs", "this # isn't currently needed. N = len(revOpLabelList) for m, opLabel1 in enumerate(revOpLabelList):", "the probabilities corresponding to the *simplified* operation sequences found in an evaluation tree,", "self.sos.get_operation(opLabel).todense()) leftProds.append(G) rightProdsT = [] G = _np.identity(dim); rightProdsT.append(_np.transpose(G)) for opLabel in reversed(revOpLabelList):", "l - 1)], xv), dop_dopLabel2[opLabel2]) # above: (nDerivCols1,dim**2,dim**2) * (dim**2,nDerivCols2) = (nDerivCols1,dim**2,nDerivCols2) flattened_d2prod[:,", "assert(len(nanOrInfCacheIndices) == 0) return prodCache, scaleCache def _compute_dproduct_cache(self, evalTree, prodCache, scaleCache, comm=None, wrtSlice=None,", "= dot( E, dot( dGs, rho ) )[0,i,j,0] # dp_dOps = squeeze( dot(", "should do something else LATER. def calc_and_fill(spamTuple, fInds, gInds, pslc1, pslc2, sumInto): \"\"\"", "_slct.length(wrtSlice) # GATE DERIVS (assume dGs is already sized/filtered) ------------------- assert(dGs.shape[1] == nDerivCols),", "dProdCache1 = dGs1 = None # free Mem dProdCache1 = self._compute_dproduct_cache( evalTree, prodCache,", "cache_size : int The size of the evaluation tree that will be passed", "* X * B ) = B^T tensor A * vec( X )", "to compute. Iterating over the output of this function iterates over these computed", "# Divide columns into blocks of at most blkSize assert(wrtFilter is None) #", "single flattened gate (ordering same as numpy.flatten), - S,M == as above, and", "of a wrtFilter argument relevant for a single object (gate or spam vec)", "scaleVals[:, None] # overflow OK d2pr_d2rhos = _np.zeros((nCircuits, nDerivCols1, nDerivCols2)) _fas(d2pr_d2rhos, [None, rho_gpindices1,", "be specified in conjuction with wrtBlockSize. wrtBlockSize : int or float, optional The", "mxToFill[felInds], dim=(ks,M) profiler.add_time(\"MPI IPC\", tm) profiler.mem_check(\"bulk_fill_dprobs: post gather blocks\") #collect/gather results tm =", "used_operations.items()} #Finally, cache any nonzero gate hessians (memory?) hop_dopLabels = {} for opLabel,", "None, myDerivColSlice, profiler) # pass None as comm, *not* mySubComm, since we can't", "comm, wrtSlice) #use cached data to construct return values old_err = _np.seterr(over='ignore') scaleExps", "d2pr_dErhos2 + d2pr_drhos2 # wrt rho ret += d2pr_dErhos1 + d2pr_d2Es + d2pr_dEs2", "drho) * scaleVals[:, None, None] # overflow OK devec = EVec.deriv_wrt_params(E_wrtFilter2) _fas(d2pr_dErhos2, [None,", "returned when bScale == True, in which case the actual product == product", "op_wrtFilter, gpindices = self._process_wrtFilter(wrtFilter, gate) dop_dopLabel = gate.deriv_wrt_params(op_wrtFilter) for (i, gl) in enumerate(revOpLabelList):", "G(L-1) tensor # noqa # ( unvec( G(L+1) ... G(M-1) tensor (G(M+1) ...", "wrtSlicesList: if wrtSlice1 != last_wrtSlice1: dProdCache1 = dGs1 = None # free Mem", "= num_param1_groups, num_param2_groups FLOATSIZE = 8 # in bytes: TODO: a better way", "_np.dot(G,self[lOp]) # product of gates, starting with G0 # nG = norm(G); G", "= _time.time() _mpit.gather_slices(blocks, blkOwners, mxToFill, [felInds], 1, mySubComm, gatherMemLimit) #note: gathering axis 1", "clipTo is not None: p = _np.clip(p, clipTo[0], clipTo[1]) dprod_dOps = self.dproduct(circuit) assert(dprod_dOps.shape[0]", "product with respect to the k-th then k-th model parameters. \"\"\" # LEXICOGRAPHICAL", "num_params * dim * dim # dproduct cache # mem += cache_size *", "hProdCache[i] /= _np.exp(scale) if hProdCache[i].max() < HSMALL and hProdCache[i].min() > -HSMALL: _warnings.warn(\"Scaled hProd", "the j-th then i-th model parameters. * if flat == True, a N", "the (l,m)-th entry of the i-th operation sequence product with respect to the", "# indicates a non-zero hessian x0 = _np.kron(_np.transpose(prods[(0, m - 1)]), prods[(m +", "compute anything on \"extra\", i.e. rank != 0, cpus hProdCache[:, myDeriv1ColSlice, myDeriv2ColSlice] =", "... G(L-1)) tensor (G(L+1) ... GN)^T vec( dG(L)/dij ) ] # noqa #", "_slct from ..tools.matrixtools import _fas from .profiler import DummyProfiler as _DummyProfiler from .label", "dp_dOps = _np.squeeze(_np.dot(E, _np.dot(dGs, rho)), axis=(0, 3)) * scaleVals[:, None] _np.seterr(**old_err2) # may", "to use a post-scaled product internally. If False, this routine will run slightly", "else: d2pr_d2Es = 0 # END SPAM DERIVS ----------------------- ret = d2pr_d2rhos +", "= _slct.list_to_slice(wrtFilter2) else: wrtSlice2 = None #get distribution across subtrees (groups if needed)", "0 _np.seterr(**old_err) if flat: # cols = deriv cols, rows = flattened all", "Returns ------- int \"\"\" return int(1.3 * nCircuits) def construct_evaltree(self, simplified_circuits, numSubtreeComms): \"\"\"", "OK _fas(d2pr_dErhos, [0, EVec.gpindices, self.sos.get_prep(rholabel).gpindices], _np.dot(_np.transpose(EVec.deriv_wrt_params()), derivWrtAnyEvec)) #Note: these 2nd derivatives are non-zero", "- B is the number of parameter rows (the length of rowSlice) -", "bUseScaling: old_err = _np.seterr(over='ignore') G, scale = self.product(circuit, True) if self.evotype == \"statevec\":", "------------------------------------------------------------------ #print(\"MPI: _compute_dproduct_cache begin: %d deriv cols\" % nDerivCols) if comm is not", "the k-th then j-th model parameters. * if flat == True, an array", "comm is not None and comm.Get_size() > 1: # parallelize of deriv cols,", "array Array of shape S x G x G, where: - S ==", "is is the probability generated by the sequence and spam label indexed by", "the gate-only sequences. This routine fills in `mxToFill`, which must have length equal", "number of selected gate-set parameters (by wrtFilter1 and wrtFilter2). evalTree : EvalTree given", "evalSubTree.final_view(prodCache, axis=0) #( nCircuits, dim, dim ) profiler.mem_check(\"bulk_fill_dprobs: post compute product\") def calc_and_fill(spamTuple,", "drhoP # d2pr_dErhos[i,J0+J,K0+K] = sum jk dEPT[J,j] prod[i,j,k] drhoP[k,K] # d2pr_dErhos[i,J0+J,K0+K] = sum", "None or _slct.length(wrtSlice2) == nDerivCols2) hessn_shape = (nDerivCols1, nDerivCols2, dim, dim) cacheSize =", "save copying) some arrays. The arrays that are filled internally to `calc_and_fill_fn` must", "\"\"\" Compute the derivative of a specified sequence of operation labels. Parameters ----------", "== M terms assumes that d^2 G/(dij)^2 == 0, which is true IF", "mySubSubComm is not None and mySubSubComm.Get_size() > 1: _warnings.warn(\"Too many processors to make", "rho))) if returnPr: p = _np.dot(E, _np.dot(prod, rho)) * scale # may generate", "j dEPT[J,j] dot(prod,drhoP)[i,j,K] # d2pr_dErhos[i,J0+J,K0+K] = dot(dEPT,prod,drhoP)[J,i,K] # d2pr_dErhos[i,J0+J,K0+K] = swapaxes(dot(dEPT,prod,drhoP),0,1)[i,J,K] # d2pr_dErhos[:,J0+J,K0+K]", "not None: _warnings.warn(\"Note: more CPUs(%d)\" % mySubComm.Get_size() + \" than hessian elements(%d)!\" %", "if _np.isnan(p): raise ValueError(\"STOP\") if clipTo is not None: ret = _np.clip(ps, clipTo[0],", "num_final_strs is irrelevant here b/c cachesize is always >= num_final_strs # and this", "# assume the zero hessian value trumps since we've renormed to keep all", "function returns a concatenated form of the above matrices, so that # each", "== as above, and hessians[i,j,k] holds the derivative of the (i % G^2)-th", "returned if returnDeriv == True. A 1 x M numpy array of derivatives", "clip(dGs,-1e300,1e300) _np.seterr(**old_err) if flat: dGs = _np.swapaxes(_np.swapaxes(dGs, 0, 1).reshape( (nDerivCols, nCircuits * dim**2)),", "(hessian_col, d12_col), where d12_col is a column of the matrix d12 defined by:", "flat: hGs = _np.rollaxis(_np.rollaxis(hGs, 0, 3).reshape( (nDerivCols1, nDerivCols2, nCircuits * dim**2)), 2) #", "w/better gather? # ------------------------------------------------------------------ tSerialStart = _time.time() if evalTree.is_split(): _warnings.warn(\"Ignoring tree splitting in", "here b/c cachesize is always >= num_final_strs # and this dictates how large", "SPAM derivWrtAnyRhovec = scale * _np.dot(E, prod) dpr_drhos = _np.zeros((1, self.Np)) _fas(dpr_drhos, [0,", "self.Np)) derivWrtAnyRhovec = scale * _np.dot(E, prod) _fas(dpr_drhos, [0, self.sos.get_prep(rholabel).gpindices], _np.dot(derivWrtAnyRhovec, rhoVec.deriv_wrt_params())) #", "`dp2` are the outputs of :func:`bulk_fill_hprobs` (i.e. args `mxToFill`, `deriv1MxToFill`, and `deriv1MxToFill`), then:", "prodCache, scaleCache, mySubComm, wrtSlice2) dGs1 = evalSubTree.final_view(dProdCache1, axis=0) dGs2 = evalSubTree.final_view(dProdCache2, axis=0) #(", "fully supported yet!\") # pr = Tr( |rho><E| * prod ) = sum", "vec_ij_size, dim, dim)) # axes = (model_parameter1, model_parameter2, model_element_row, model_element_col) def prs(self, rholabel,", "probability itself. returnDeriv : bool when set to True, additionally return the derivative", "we reverse iLeft <=> iRight from evalTree because # (iRight,iLeft,iFinal) = tup implies", "to construct virtual gates for use in computations. \"\"\" super(MatrixForwardSimulator, self).__init__( dim, simplified_op_server,", "= _time.time() all_results = comm.allgather(my_results) profiler.add_time(\"MPI IPC\", tm) return _np.concatenate(all_results, axis=1) # TODO:", "gatherMemLimit) #gather over row-distribution (Deriv1) #note: gathering axis 1 of hProdCache, # dim=(cacheSize,nDerivCols1,nDerivCols2,dim,dim)", "> nDerivCols: #If there are more processors than deriv cols, give a #", "#prMxToFill = None deriv1MxToFill = dprobs1 deriv2MxToFill = dprobs2 mxToFill = hprobs #Fill", "lOp not in scaledGatesAndExps: opmx = self.sos.get_operation(lOp).todense() ng = max(_nla.norm(opmx), 1.0) scaledGatesAndExps[lOp] =", "convert nans to zero, as these occur b/c an inf scaleVal is mult", "operation on. clipTo : 2-tuple, optional (min,max) to clip return value if not", "zero-operation labels for i, opLabel in zip(evalTree.get_init_indices(), evalTree.get_init_labels()): if opLabel == \"\": #", "bool, optional Affects the shape of the returned derivative array (see below). wrtFilter", "opsToVectorize1 and opsToVectorize2 we only compute d2(prod)/d(gl1)d(gl2) # and not d2(prod)/d(gl2)d(gl1) ... if", "devec)) d2pr_dEs2 = _np.transpose(d2pr_dEs2, (0, 2, 1)) # Get: d2pr_dErhos[i, e_offset[eIndex]:e_offset[eIndex+1], e_offset[rhoIndex]:e_offset[rhoIndex+1]] =", "done efficiently by actually computing X^T ( note (A tensor B)^T = A^T", "length of the vectorized model (number of model parameters) and hessian[i,j,k] holds the", "is not None: # _fas(prMxToFill, [fInds], # self._probs_from_rhoE(rho, E, Gs[gInds], scaleVals[gInds]), add=sumInto) if", "of operation labels which specify the operation sequences to create an evaluation tree", "each of the gate parameters. If this is not the case, need LinearOperator", "add=sumInto) _np.seterr(**old_err) profiler.add_time(\"bulk_fill_dprobs: calc_and_fill\", tm) #Set wrtBlockSize to use available processors if it", "dproduct, etc. to allow for *complex* derivatives, since matrices can be complex #", "dp_dOps[i,j] = dot( E, dot( dGs, rho ) )[0,i,j,0] # dp_dOps = squeeze(", "and blkSize2 is None: #Fill hessian cache info dProdCache1 = self._compute_dproduct_cache( evalSubTree, prodCache,", "computation across multiple processors. Distribution is performed as in bulk_product, bulk_dproduct, and bulk_hproduct.", "functions named by `subcalls`. num_subtrees : int The number of subtrees to split", "in dpr(...) dpr_dOps = _np.empty((1, self.Np)) for i in range(self.Np): dpr_dOps[0, i] =", "rho_gpindices2 = self._process_wrtFilter(wrtSlice2, self.sos.get_prep(rholabel)) E_wrtFilter1, E_gpindices1 = self._process_wrtFilter(wrtSlice1, self.sos.get_effect(elabel)) E_wrtFilter2, E_gpindices2 = self._process_wrtFilter(wrtSlice2,", "elabels): #Note: no support for \"custom\" spamlabels... # This calculator uses the convention", "computed elements (i.e. evalTree.num_final_elements()) evalTree : EvalTree given by a prior call to", "#eval on each local subtree for iSubTree in mySubTreeIndices: evalSubTree = subtrees[iSubTree] felInds", "array with probability-derivatives for each \"final element\" of `evalTree`. Parameters ---------- mxToFill :", "columns of flattened_dprod. _fas(flattened_hprod, [None, gpindices1, gpindices2], gate.hessian_wrt_params(op_wrtFilter1, op_wrtFilter2)) if flat: return flattened_hprod", "None, E_gpindices1], _np.dot(dp_dAnyE, devec)) d2pr_dEs2 = _np.transpose(d2pr_dEs2, (0, 2, 1)) # Get: d2pr_dErhos[i,", "scale = self.product(circuit, True) if self.evotype == \"statevec\": ps = _np.real(_np.abs(_np.dot(Es, _np.dot(G, rho))", "if blkSize1 is None and blkSize2 is None: #Fill hessian cache info dProdCache1", "_np.exp(scaleExps) # may overflow, but OK if infs occur here _np.seterr(**old_err) return scaleVals", "VS MATRIX ORDER # we do matrix multiplication in this order (easier to", "= _np.seterr(over='ignore') rho, E = self._rhoE_from_spamTuple(spamTuple) #if prMxToFill is not None: # _fas(prMxToFill,", "operation on. flat : bool, optional Affects the shape of the returned derivative", "non-zero hessian x0 = _np.kron(_np.transpose(prods[(0, m - 1)]), prods[(m + 1, N -", "2, 1)) # Get: d2pr_dErhos[i, e_offset[eIndex]:e_offset[eIndex+1], e_offset[rhoIndex]:e_offset[rhoIndex+1]] = # dEP^T * prod[i,:,:] *", "#DEBUG: print \"backtrace\" of product leading up to nan #G = _np.identity( self.dim", "flat == False, two arrays of shape S x M x G x", "parameter columns (the length of colSlice) If `mx`, `dp1`, and `dp2` are the", "_slct.indices(wrtFilter) if wrtFilter is not None: obj_wrtFilter = [] # values = object-local", "is not None: _np.clip(prMxToFill, clipTo[0], clipTo[1], out=prMxToFill) # in-place clip if check: self._check(evalTree,", "mySubComm.Get_size() + \" than derivative columns(%d)!\" % self.Np + \" [blkSize = %.1f,", "arrays # like length>1 lists do... ugh. relevant_gpindices = slice(0, 0) # slice", "hProdCache = hGs = dProdCache2 = dGs2 = None # free mem dProdCache1", "(gate_ij1, gateij2, prod_row, prod_col) def dproduct(self, circuit, flat=False, wrtFilter=None): \"\"\" Compute the derivative", "_fas(d2pr_d2rhos, [None, rho_gpindices1, rho_gpindices2], _np.tensordot(dp_dAnyRho, self.sos.get_prep(rholabel).hessian_wrt_params( rho_wrtFilter1, rho_wrtFilter2), (1, 0))) # _np.einsum('ij,jkl->ikl', dp_dAnyRho,", "1: _warnings.warn(\"Too many processors to make use of in \" \" _compute_hproduct_cache.\") #TODO:", "i, opLabel in zip(evalTree.get_init_indices(), evalTree.get_init_labels()): if opLabel == \"\": # special case of", "obtained\" \" by giving hproduct cache computation\" \" *fewer* processors and *smaller* (sub-)tree\"", "len(wrtFilter2) flattened_hprod = _np.zeros((dim**2, num_deriv_cols1, num_deriv_cols2), 'd') if _slct.length(gpindices1) > 0 and _slct.length(gpindices2)", "#print(\"MPI: _compute_hproduct_cache over %d cols (rank %d computing %s)\" \\ # % (nDerivCols2,", "1) hProdCache[i] = _np.dot(hL, R) + dLdR_sym + _np.transpose(_np.dot(L, hR), (1, 2, 0,", "_np.dot(G, rho)))**2) else: # evotype == \"densitymx\" ps = _np.real(_np.dot(Es, _np.dot(G, rho))) ps", "# mem += cache_size # scale vals # #elif fnName == \"bulk_dproduct\": #", "lists of gate-only sequences along with a mapping of final elements (i.e. probabilities)", "to the number of final elements (this can be obtained by `evalTree.num_final_elements()`. To", "E is the total number of computed elements (i.e. evalTree.num_final_elements()) and M1 &", "vectors have # a more than linear dependence on their parameters. if self.sos.get_prep(rholabel).has_nonzero_hessian():", "the subtrees. It can often be useful to have fewer processor groups then", "in the root pyGSTi directory. #*************************************************************************************************** import warnings as _warnings import numpy as", "the tuple. That is, the first element of circuit can be thought of", "-- faster but susceptible to overflow G = self.product(circuit, False) if self.evotype ==", "+ iRight => i # LEXICOGRAPHICAL VS MATRIX ORDER Note: we reverse iLeft", "nDerivCols, dim, dim ) profiler.add_time(\"bulk_fill_dprobs: compute_dproduct_cache\", tm) profiler.mem_check(\"bulk_fill_dprobs: post compute dproduct\") #Compute all", "evalSubTree, slice(None), slice(None), calc_and_fill) profiler.mem_check(\"bulk_fill_dprobs: post fill\") dProdCache = dGs = None #", "could compute? wrtLen1 = (self.Np + np1 - 1) // np1 # ceiling(num_params", "cache mem += cache_size # scale cache (exps) mem += cache_size # scale", "numpy array * if flat == False, a M x G x G", "an inf scaleVal is mult by a zero deriv value, and we dGs[_np.isnan(dGs)]", "final block size. This argument must be None if wrtFilter is not None.", "* scaleVals[:, None, None] # overflow OK devec = EVec.deriv_wrt_params(E_wrtFilter2) _fas(d2pr_dErhos2, [None, E_gpindices2,", "generate overflow, but OK if clipTo is not None: p = _np.clip(p, clipTo[0],", "of the probabilities. comm : mpi4py.MPI.Comm, optional When not None, an MPI communicator", "check_vhp = _np.concatenate( [self.hpr(spamTuple, circuit, False, False, clipTo) for circuit in circuit_list], axis=0)", "]] has # columns which correspond to the vectorized derivatives of each of", "use this file except # in compliance with the License. You may obtain", "m - 1)]), prods[(m + 1, N - 1)]) # (dim**2, dim**2) x", "self._get_filter_info(wrtSlices1) #flt2 = self._get_filter_info(wrtSlices2) # GATE DERIVS (assume hGs is already sized/filtered) -------------------", "Gs, scaleVals else: old_err = _np.seterr(over='ignore') Gs = _np.swapaxes(_np.swapaxes(Gs, 0, 2) * scaleVals,", "> 1: #print(\"MPI: _compute_dproduct_cache called w/comm size %d\" % comm.Get_size()) # parallelize of", "row indices into mxToFill, specifying the correspondence between rows of mxToFill and spam", "wrtFilter2 is None: blkSize1 = wrtBlockSize1 # could be None blkSize2 = wrtBlockSize2", "parameters. * if flat == True, a N x M x M numpy", "#shape == ( len(circuit_list), nDerivCols, dim, dim ), # dGs[i] is dprod_dOps for", "dp_dEs + dp_dOps return sub_vdp #def _get_filter_info(self, wrtSlices): # \"\"\" # Returns a", "dpr_dOps def hpr(self, spamTuple, circuit, returnPr, returnDeriv, clipTo): \"\"\" Compute the Hessian of", "[ sum_{L s.t. GL == oplabel} [ (G1 ... G(L-1)) tensor (G(L+1) ...", ", gatherMemLimit) #gather over col-distribution (Deriv2) #note: gathering axis 2 of hProdCache[:,myDeriv1ColSlice], #", "M x M numpy array, where: - N == the number of entries", "second (col) derivative operations, respectively. Each element is an index into an array", "sequence of operation labels. bScale : bool, optional When True, return a scaling", "d2pr_dErhos[:,J0+J,K0+K] = swapaxes(dot(dEPT,prod,drhoP),0,1)[:,J,K] d2pr_dErhos1 = _np.zeros((nCircuits, nDerivCols1, nDerivCols2)) drho = rhoVec.deriv_wrt_params(rho_wrtFilter2) dp_dAnyE =", "at which `circuit` is evaluated. Returns ------- numpy.ndarray An array of floating-point probabilities,", "dGs1 = _np.swapaxes(_np.swapaxes(dGs1, 0, 1).reshape((nDerivCols1, nCircuits * dim**2)), 0, 1) # cols =", "(invalid), but ok dGs2 = _np.swapaxes(_np.swapaxes(dGs2, 0, 3) * scaleVals, 0, 3) #", "the string, compute the hessian of the entire # operation sequence with respect", "to True, additionally return the probability itself. clipTo : 2-tuple (min,max) to clip", "myDeriv1ColSlice] = self._compute_hproduct_cache( evalTree, prodCache, dProdCache1[:, myDeriv1ColSlice], dProdCache2, scaleCache, None, myHessianSlice1, wrtSlice2) #", "fewer processor groups then subtrees (even == 1) in order to perform the", "comm) dProdCache = self._compute_dproduct_cache(evalTree, prodCache, scaleCache, comm, wrtSlice) #use cached data to construct", "S,M == as above, and deriv[i,j] holds the derivative of the (i %", "for \"custom\" spamlabels... # This calculator uses the convention that rho has shape", "This argument is used internally for distributing calculations across multiple processors and to", "# if dG(L)/dij = E(i,j) # noqa # = vec(i,j)-col of [ sum_{L", "1) # dot(dS, T) + dot(S, dT) profiler.add_time(\"compute_dproduct_cache: dots\", tm) profiler.add_count(\"compute_dproduct_cache: dots\") scale", "be automatically parallelized over these groups. num_param2_groups : int The number of groups", "shape (N,1) rho = self.sos.get_prep(rholabel).todense()[:, None] E = _np.conjugate(_np.transpose(self.sos.get_effect(elabel).todense() [:, None])) # convention:", "processor syncronization. Returns ------- None \"\"\" tStart = _time.time() if profiler is None:", "pslc2 = param_slice2 for spamTuple, (fInds, gInds) in evalTree.spamtuple_indices.items(): # fInds = \"final", "in circuit_list], axis=0) if _nla.norm(hprMxToFill[fInds][0] - check_vhp[0]) > 1e-6: _warnings.warn(\"norm(vhp-check_vhp) = %g -", "is split). Returns ------- None \"\"\" #get distribution across subtrees (groups if needed)", "convention: E has shape (1,N) else: # a \"custom\" spamLabel consisting of a", "b/c rho,E are EVec = self.sos.get_effect(elabel) # arrays, these are SPAMVecs #Derivs wrt", "shallow copy of this MatrixForwardSimulator \"\"\" return MatrixForwardSimulator(self.dim, self.sos, self.paramvec) def product(self, circuit,", "perform a hessian calculation (i.e. for l==m) then # it could make sense", "variables # wrtSlice1 and wrtSlice2, of the parent-function scope. This use of #", "time. For example, the Hessian of a function of many gate sequence probabilities", "single operation sequence. The spam tuples may only vary in their effect-label (their", "respect to the j-th model parameter. products : numpy array Only returned when", "# in-place clip if check: self._check(evalTree, mxToFill, clipTo=clipTo) def bulk_fill_dprobs(self, mxToFill, evalTree, prMxToFill=None,", "_fas(d2pr_d2Es, [None, E_gpindices1, E_gpindices2], _np.tensordot(dp_dAnyE, self.sos.get_effect(elabel).hessian_wrt_params( E_wrtFilter1, E_wrtFilter2), (1, 0))) # _np.einsum('ij,jkl->ikl', dp_dAnyE,", "method in addition of deriv_wrt_params # # Note: unvec( X ) can be", "float, optional The maximum number of derivative columns to compute *products* for simultaneously.", "parameters. * if flat == True, an array of shape S*N x M", "= evalSubTree.final_view(dProdCache2, axis=0) #( nCircuits, nDerivColsX, dim, dim ) hProdCache = self._compute_hproduct_cache(evalSubTree, prodCache,", "a dictionary with keys == spam labels and values which are integer row", "x0 = _np.kron(_np.transpose(prods[(0, m - 1)]), prods[(m + 1, l - 1)]) #", "by concatenating each gate's parameters (in the order specified by the model). This", "product for i-th operation sequence scaleExps = evalTree.final_view(scaleCache) old_err = _np.seterr(over='ignore') scaleVals =", "+= cache_size # scale vals # #elif fnName == \"bulk_hproduct\": # mem +=", "dG(L)/dij = E(i,j) # noqa # = vec(i,j)-col of [ sum_{L s.t. G(L)", "elabels] Es = _np.conjugate(_np.transpose(_np.concatenate(Es, axis=1))) # convention: Es has shape (len(elabels),N) return rho,", "The sequence of operation labels. bScale : bool, optional When True, return a", "derivative of the probability w.r.t. the k-th then the j-th model parameter. derivative", "for elabel in elabels ]) #assert(_np.linalg.norm(ps-check_ps) < 1e-8) return ret def dpr(self, spamTuple,", "elements (i.e. evalTree.num_final_elements()) and M1 & M2 are the number of selected gate-set", "# Note: L, R = GxG ; dL,dR = vgs x GxG ;", "these occur b/c an inf scaleVal is mult by a zero hessian value,", "inner loop completion # (to save mem) but isn't gathered until now (but", "return a length-0 list, as this doesn't index numpy arrays # like length>1", "E(i,j) # noqa # = vec(i,j)-col of [ sum_{L s.t. G(L) == oplabel}", "over locations of opLabel LRproduct = _np.kron(leftProds[i], rightProdsT[N - 1 - i]) #", "wrtBlockSize wrtSlice2 = _slct.list_to_slice(wrtFilter2) else: wrtSlice2 = None #get distribution across subtrees (groups", "probability and save in return array # want vp[iFinal] = float(dot(E, dot(G, rho)))", "cached data to final values scaleVals = self._scaleExp(evalSubTree.final_view(scaleCache)) Gs = evalSubTree.final_view(prodCache, axis=0) #", "args `mxToFill`, `deriv1MxToFill`, and `deriv1MxToFill`), then: - `hprobs == mx[:,:,rowSlice,colSlice]` - `dprobs12 ==", "used_operations[l] = self.sos.get_operation(l) gate_wrtFilters1[l], gpindices1[l] = self._process_wrtFilter(wrtFilter1, used_operations[l]) gate_wrtFilters2[l], gpindices2[l] = self._process_wrtFilter(wrtFilter2, used_operations[l])", "operations performed as a part of MPI processor syncronization. Returns ------- None \"\"\"", "of the returned derivative array (see below). bReturnDProdsAndProds : bool, optional when set", "G = _np.dot(gate, G / nG); scale_exp += _np.log(nG) # LEXICOGRAPHICAL VS MATRIX", "and hoperation below: pulls out pieces of a wrtFilter argument relevant for a", "labels. bScale : bool, optional When True, return a scaling factor (see below).", "E is the total number of computed elements (i.e. evalTree.num_final_elements()) and M is", "by giving the tree information it needs to distribute itself among the available", "label == no gate prodCache[i] = _np.identity(dim) # Note: scaleCache[i] = 0.0 from", "'Imyinst_0') returnPr : bool when set to True, additionally return the probability itself.", "_np.rollaxis(_np.rollaxis(hGs, 0, 3).reshape( (nDerivCols1, nDerivCols2, nCircuits * dim**2)), 2) # as above return", ") = sum{...} [ G1 ... G(M-1) dG(M)/dkl G(M+1) ... G(L-1) tensor (G(L+1)", "add=sumInto) _np.seterr(**old_err) #NOTE: don't distribute wrtSlicesList across comm procs, # as we assume", "Returns ------- product : numpy array The product or scaled product of the", "+ {similar with L < M} # noqa # + sum{M==L} [ G1", "tm = _time.time() # combine iLeft + iRight => i # LEXICOGRAPHICAL VS", "None: # ignoring comm since can't do anything with it! #_warnings.warn(\"More processors than", "overflow OK d2pr_d2Es = _np.zeros((nCircuits, nDerivCols1, nDerivCols2)) _fas(d2pr_d2Es, [None, E_gpindices1, E_gpindices2], _np.tensordot(dp_dAnyE, self.sos.get_effect(elabel).hessian_wrt_params(", "sized/filtered) ------------------- assert(hGs.shape[1] == nDerivCols1), \"hGs must be pre-filtered!\" assert(hGs.shape[2] == nDerivCols2), \"hGs", "array (see below). bReturnProds : bool, optional when set to True, additionally return", "e_global_slices=global_e_slices, # num_rho_params=_slct.length(wrtSlices['preps']), # num_e_params=_slct.length(wrtSlices['effects'])) # else: # loc_rho_slices = [slice(None,None)]*len(self.preps) # loc_e_slices", "# and this dictates how large all the storage arrays are. np1, np2", "prod ) = sum E_k prod_kl rho_l # dpr/d(opLabel)_ij = sum E_k [dprod/d(opLabel)_ij]_kl", "\"License\"); you may not use this file except # in compliance with the", "alter scaleCache.\") #profiler.print_mem(\"DEBUGMEM: POINT2\"); profiler.comm.barrier() profiler.add_time(\"compute_dproduct_cache: serial\", tSerialStart) profiler.add_count(\"compute_dproduct_cache: num columns\", nDerivCols) return", "pragma: no cover def bulk_fill_probs(self, mxToFill, evalTree, clipTo=None, check=False, comm=None): \"\"\" Compute the", "None and mySubComm.Get_size() > 1: deriv2Slices, myDeriv2ColSlice, deriv2Owners, mySubSubComm = \\ _mpit.distribute_slice(allDeriv2ColSlice, mySubComm)", "# # return PrepEffectFilter(rho_local_slices=loc_rho_slices, # rho_global_slices=global_rho_slices, # e_local_slices=loc_e_slices, # e_global_slices=global_e_slices, # num_rho_params=_slct.length(wrtSlices['preps']), #", "cells, give a # warning -- note that we *cannot* make use of", "that used by numpy.flatten), - S,M == as above, and deriv[i,j] holds the", "= sum_k E[0,k] dot(Gs, rho)[i,k,0] * scaleVals[i] # vp[i] = dot( E, dot(Gs,", "self.sos.get_operation(lOp).todense() ng = max(_nla.norm(opmx), 1.0) scaledGatesAndExps[lOp] = (opmx / ng, _np.log(ng)) gate, ex", "operation sequences using tree (skip over the zero and single-gate-strings) #cnt = 0", "parameter. * if flat == True, an array of shape S*N x M", "scaling. \"\"\" if bScale: scaledGatesAndExps = {} scale_exp = 0 G = _np.identity(self.dim)", "cols, rows = flattened everything else return (dGs, Gs, scaleVals) if bScale else", "_np.dot(Gs, rho)), axis=(0, 2)) * scaleVals # shape == (len(circuit_list),) ; may overflow", "= dot(E,Gs[i],drho/drhoP) # dp_drhos[i,J0+J] = sum_kl E[0,k] Gs[i,k,l] drhoP[l,J] # dp_drhos[i,J0+J] = dot(E,", "= evalSubTree.final_element_indices(evalTree) #Free memory from previous subtree iteration before computing caches scaleVals =", "1.0) prodCache[i] = gate / nG scaleCache[i] = _np.log(nG) #evaluate operation sequences using", "# operation sequence with respect to only those two gates' parameters and fill", "# get d2pr_dEs where gate derivatives are wrt the 2nd set of gate", "entry of the flattened product with respect to the k-th then k-th model", "False, clipTo) for circuit in circuit_list], axis=0) if _nla.norm(dprMxToFill[fInds] - check_vdp) > 1e-6:", "ones which use entirely different -- non-gate-local -- parameterizations of operation matrices and", "the k-th then j-th model parameters. derivs1, derivs2 : numpy array Only returned", "_fas(d2pr_drhos1, [None, None, rho_gpindices2], _np.squeeze(_np.dot(_np.dot(E, dGs1), drho), axis=(0,)) * scaleVals[:, None, None]) #", "numpy array, where: - M == length of the vectorized model (number of", "## END CACHE FUNCTIONS def default_distribute_method(self): \"\"\" Return the preferred MPI distribution mode", "seemed very useful ## since numpy does all the major allocation/deallocation). #if comm", "rho, E, Gs[gInds], dGs[gInds], scaleVals[gInds], wrtSlice), add=sumInto) _np.seterr(**old_err) profiler.add_time(\"bulk_fill_dprobs: calc_and_fill\", tm) #Set wrtBlockSize", "rho, E, Gs[gInds], dGs[gInds], scaleVals[gInds], block_wrtSlice), add=sumInto) _np.seterr(**old_err) profiler.add_time(\"bulk_fill_dprobs: calc_and_fill_blk\", tm) for iBlk", "performed as a part of MPI processor syncronization. Returns ------- None \"\"\" if", "column-by-column. This routine can be useful when memory constraints make constructing the entire", "the vectorized model (number of model parameters) - G == the linear dimension", "- B' is the number of parameter columns (the length of colSlice) If", "1)) + \\ d2pr_drhos + _np.transpose(d2pr_drhos, (0, 2, 1)) + \\ d2pr_dEs +", "\"\"\" def __init__(self, dim, simplified_op_server, paramvec): \"\"\" Construct a new MatrixForwardSimulator object. Parameters", "array of shape S x G x G; products[i] is the i-th operation", "_nla.norm(check_vp), _nla.norm(prMxToFill[fInds] - check_vp))) # pragma: no cover if dprMxToFill is not None:", "circuit[iLeft] + circuit[iRight], but we want: # since then matrixOf(circuit[i]) = matrixOf(circuit[iLeft]) *", "mySubTreeIndices: evalSubTree = subtrees[iSubTree] #Free memory from previous subtree iteration before computing caches", "self.sos.get_operation(opLabel2).todense()) prods[(i, j)] = G prods[(len(revOpLabelList), len(revOpLabelList) - 1)] = ident # product", "on. clipTo : 2-tuple, optional (min,max) to clip return value if not None.", "subcall name: %s\" % fnName) return mem * FLOATSIZE def bulk_product(self, evalTree, bScale=False,", "used_operations.items(): if gate.has_nonzero_hessian(): hop_dopLabels[opLabel] = gate.hessian_wrt_params( gate_wrtFilters1[opLabel], gate_wrtFilters2[opLabel]) # Allocate memory for the", "len( (_np.isinf(hGs)).nonzero()[0] ) == 0 ) #hGs = clip(hGs,-1e300,1e300) _np.seterr(**old_err) if flat: hGs", "* B ) = vec( mx w/ row_i = A[i,0] * B[row1] )", "numpy array, where: - N == the number of entries in a single", "_time.time() dProdCache = self._compute_dproduct_cache(evalSubTree, prodCache, scaleCache, mySubComm, wrtSlice, profiler) dGs = evalSubTree.final_view(dProdCache, axis=0)", "x M where - N == the number of entries in a single", "& dprobs12 results mem += cache_size * nspam * (wrtLen1 + wrtLen2) #", "wrtSlice1 != last_wrtSlice1: dProdCache1 = dGs1 = None # free Mem dProdCache1 =", "the derivative columns, essentially taking # a derivative of only a *subset* of", "evalTree (if it is split), and then over blocks (subsets) of the parameters", "of # prod.flatten()). # # Note: if gate G(L) is just a matrix", "EVec = self.sos.get_effect(elabel) # arrays, these are SPAMVecs nCircuits = Gs.shape[0] rho_wrtFilter, rho_gpindices", "used internally for distributing calculations across multiple processors and to control memory usage.", "d12[iSpamLabel,iOpStr,p1,p2] = dP/d(p1)*dP/d(p2) where P is is the probability generated by the sequence", "syncronization. Returns ------- None \"\"\" tStart = _time.time() if profiler is None: profiler", "IF each operation matrix element # is at most *linear* in each of", "slice(None), calc_and_fill_blk) profiler.mem_check(\"bulk_fill_dprobs: post fill blk\") dProdCache = dGs = None # free", "gate jacobians (still relatively little mem required) dop_dopLabel1 = { opLabel: gate.deriv_wrt_params(gate_wrtFilters1[opLabel]) for", "2019 National Technology & Engineering Solutions of Sandia, LLC (NTESS). # Under the", "is not None: obj_wrtFilter = [] # values = object-local param indices relevant_gpindices", "filled with probabilities, just like in bulk_fill_probs(...). clipTo : 2-tuple, optional (min,max) to", "dGs = _np.swapaxes(_np.swapaxes(dGs, 0, 3) * scaleVals, 0, 3) # convert nans to", "and their Hessians. PSMALL = 1e-100 DSMALL = 1e-100 HSMALL = 1e-100 class", "if bScale: scaledGatesAndExps = {} scale_exp = 0 G = _np.identity(self.dim) for lOp", "the first identity below is valid. # Below we use E(i,j) to denote", "= self._compute_hproduct_cache( evalTree, prodCache, dProdCache1[:, myDeriv1ColSlice], dProdCache2[:, myDeriv2ColSlice], scaleCache, None, myHessianSlice1, myHessianSlice2) #", "# ------------------------------------------------------------------ #print(\"MPI: _compute_dproduct_cache begin: %d deriv cols\" % nDerivCols) if comm is", "= [_slct.length(s) for s in loc_e_slices] # tmp_offsets = [ sum(tmp_num_params[0:i]) for i", "in this order (easier to think about) revOpLabelList = tuple(reversed(tuple(circuit))) # prod =", "enumerate(wrtFilter): if i in gpindices: relevant_gpindices.append(ii) obj_wrtFilter.append(list(gpindices).index(i)) relevant_gpindices = _np.array(relevant_gpindices, _np.int64) if len(relevant_gpindices)", "dGs1 = evalSubTree.final_view(dProdCache1, axis=0) for iBlk2 in myBlk2Indices: blk_wrtSlice2 = blocks2[iBlk2] if blk_wrtSlice1", "internally for conditional scaling required # to control bulk products, their gradients, and", "_mpit.gather_indices(subtreeElementIndices, subTreeOwners, mxToFill, [], 0, comm) #note: pass mxToFill, dim=(KS), so gather mxToFill[felslc]", "mem if bReturnDProbs12: dprobs12 = dprobs1[:, :, None] * dprobs2[:, None, :] #", "greater than `cacheSize`) the tree will hold. Returns ------- int The memory estimate", "rho)[i,j,0] dEP[j,J] # dp_dEs[i,J0+J] = dot(squeeze(dot(Gs, rho),2), dEP)[i,J] # dp_dEs[:,J0+J] = dot(squeeze(dot(Gs, rho),axis=(2,)),", "None wrtIndices2 = _slct.indices(wrtSlice2) if (wrtSlice2 is not None) else None for i,", "communicator for distributing the computation across multiple processors. Distribution is performed as in", "ValueError(\"STOP\") if clipTo is not None: ret = _np.clip(ps, clipTo[0], clipTo[1]) else: ret", "num_subtrees, num_subtree_proc_groups, num_param1_groups, num_param2_groups, num_final_strs): \"\"\" Estimate the memory required by a given", "operations. \"\"\" def __init__(self, dim, simplified_op_server, paramvec): \"\"\" Construct a new MatrixForwardSimulator object.", "/ (1024.0**3))) ## memory profiling of python objects (never seemed very useful ##", "the returned derivative array (see below). bReturnDProdsAndProds : bool, optional when set to", "* prod[i,:,:] * drhoP # d2pr_dErhos[i,J0+J,K0+K] = sum jk dEPT[J,j] prod[i,j,k] drhoP[k,K] #", "else _slct.length(wrtSlice) deriv_shape = (nDerivCols, dim, dim) cacheSize = len(evalTree) # ------------------------------------------------------------------ #print(\"MPI:", "derivative of the (j,k)-th entry of the product with respect to the i-th", "~ %.2fGB)\" % (mxToFill.nbytes / (1024.0**3))) ## memory profiling of python objects (never", "=> i # LEXICOGRAPHICAL VS MATRIX ORDER Note: we reverse iLeft <=> iRight", "zero deriv value trumps since we've renormed to keep all the products within", "numpy array that is filled with probabilities, just like in bulk_fill_probs(...). derivMxToFill1, derivMxToFill2", "first performed over subtrees of evalTree (if it is split), and then over", "vec( E(0,1) ) # In general: vec( A * X * B )", "self.product(circuit, True) if returnPr: p = _np.dot(E, _np.dot(prod, rho)) * scale # may", "the hessians, derivatives, and/or products for the i-th operation sequence. \"\"\" dim =", "calc_and_fill_p) profiler.mem_check(\"bulk_fill_dprobs: post fill probs\") #distribute derivative computation across blocks myBlkIndices, blkOwners, blkComm", "= d2pr_d2rhos + d2pr_dErhos2 + d2pr_drhos2 # wrt rho ret += d2pr_dErhos1 +", "retains certain rights # in this software. # Licensed under the Apache License,", "and second (col) derivative operations, respectively. wrtBlockSize2, wrtBlockSize2 : int or float, optional", "# assuming that the gates are at most linear in their parameters, this", "# d2pr_dErhos[:,J0+J,K0+K] = swapaxes(dot(dEPT,prod,drhoP),0,1)[:,J,K] d2pr_dErhos1 = _np.zeros((nCircuits, nDerivCols1, nDerivCols2)) drho = rhoVec.deriv_wrt_params(rho_wrtFilter2) dp_dAnyE", "* G2 * .... * GN , a matrix # noqa # dprod/d(opLabel)_ij", "ORDER else: G = H old_err = _np.seterr(over='ignore') scale = _np.exp(scale_exp) _np.seterr(**old_err) return", "_warnings.warn(\"Note: more CPUs(%d)\" % mySubComm.Get_size() + \" than derivative columns(%d)!\" % self.Np +", "min(comm_blkSize, blkSize) # override with smaller comm_blkSize else: blkSize = None # wrtFilter", "are slices directly from `wrtSlicesList`. `hprobs` and `dprobs12` are arrays of shape K", "G x G, where - S == len(circuit_list) - M == the length", "classes (e.g. ones which use entirely different -- non-gate-local -- parameterizations of operation", "right single-gate-strings w/indices wrtIndices = _slct.indices(wrtSlice) if (wrtSlice is not None) else None", "a split tree. In short, parallelization should be done at a higher level.", "True. comm : mpi4py.MPI.Comm, optional When not None, an MPI communicator for distributing", "specified in conjuction with wrtBlockSize. wrtBlockSize : int or float, optional The maximum", "cols, then sub-trees (if available and necessary) if comm.Get_size() > nDerivCols: #If there", "it needs to distribute itself among the available processors. Returns ------- MatrixEvalTree \"\"\"", "= dProdCache[iLeft], dProdCache[iRight] dProdCache[i] = _np.dot(dL, R) + \\ _np.swapaxes(_np.dot(L, dR), 0, 1)", "= None # free Mem dProdCache1 = self._compute_dproduct_cache( evalTree, prodCache, scaleCache, comm, wrtSlice1)", "if `bReturnDProbs12 == True`). `rowSlice` and `colSlice` are slices directly from `wrtSlicesList`. `hprobs`", "None # free mem #gather results tm = _time.time() _mpit.gather_slices(blocks, blkOwners, mxToFill, [felInds],", "# this case set to zero since we can't tell whether it's +", "#assert(_np.linalg.norm(ps-check_ps) < 1e-8) return ret def dpr(self, spamTuple, circuit, returnPr, clipTo): \"\"\" Compute", "returned when bScale == True. A length-S array specifying the scaling that needs", "existing array values, which is a functionality needed to correctly handle the remainder", "param indices relevant_gpindices = [] # indices into original wrtFilter'd indices gpindices =", "occur here _np.seterr(**old_err) if bScale: return Gs, scaleVals else: old_err = _np.seterr(over='ignore') Gs", "gave no contribution since we assume all gate elements are at most #", "indices\" = the \"element\" indices in the final # filled quantity combining both", "pieces of a wrtFilter argument relevant for a single object (gate or spam", "OK _fas(dpr_dEs, [0, EVec.gpindices], _np.dot(derivWrtAnyEvec, EVec.deriv_wrt_params())) dpr = dpr_drhos + dpr_dEs + dpr_dOps", "cache_size * wrtLen1 * wrtLen2 * dim * dim # hproduct cache mem", "2, 1)) + \\ d2pr_d2rhos + d2pr_d2Es + d2pr_dOps2 # Note: add transposes", "optional when set to True, additionally return the probabilities and their derivatives (see", "rho, E = self._rhoE_from_spamTuple(spamTuple) _fas(prMxToFill, [fInds], self._probs_from_rhoE(rho, E, Gs[gInds], scaleVals[gInds]), add=sumInto) _np.seterr(**old_err) profiler.add_time(\"bulk_fill_dprobs:", "sum_kl E[0,k] Gs[i,k,l] drhoP[l,J] # dp_drhos[i,J0+J] = dot(E, Gs, drhoP)[0,i,J] # dp_drhos[:,J0+J] =", "= self._compute_dproduct_cache(evalTree, prodCache, scaleCache, comm, wrtSlice1) dProdCache2 = dProdCache1 if (wrtSlice1 == wrtSlice2)", "noqa # + sum{ L < M} [ G1 ... G(L-1) tensor #", "type %s is incompatbile with \" \"matrix-based calculations\" % self.evotype)) def copy(self): \"\"\"", "supported yet!\") rholabel, elabel = spamTuple rhoVec = self.sos.get_prep(rholabel) # distinct from rho,E", "tmp_offsets = [ sum(tmp_num_params[0:i]) for i in range(len(self.preps)+1) ] # global_rho_slices = [", "profiler : Profiler, optional A profiler object used for to track timing and", "if nDerivCols1 == 0: continue for l, opLabel2 in enumerate(revOpLabelList): inds2 = gpindices1[opLabel2]", "output array size. Could throw more informative error? #elif fnName == \"bulk_product\": #", "(e.g. may include instrument elements like 'Imyinst_0') clipTo : 2-tuple (min,max) to clip", "in the first (row) and second (col) derivative operations, respectively. wrtBlockSize2, wrtBlockSize2 :", "decent bounds #assert( len( (_np.isnan(dGs)).nonzero()[0] ) == 0 ) #assert( len( (_np.isinf(dGs)).nonzero()[0] )", "\"\"\" Return an estimate of the ideal/desired cache size given a number of", "`mxToFill`, which must have length equal to the number of final elements (this", "= (nDerivCols, dim, dim) cacheSize = len(evalTree) # ------------------------------------------------------------------ #print(\"MPI: _compute_dproduct_cache begin: %d", "Technology & Engineering Solutions of Sandia, LLC (NTESS). # Under the terms of", "GN)^T vec( d2G(M)/dkl*dji ) # noqa # # Note: ignoring L == M", "= EVec.deriv_wrt_params(E_wrtFilter1) _fas(d2pr_dEs2, [None, None, E_gpindices1], _np.dot(dp_dAnyE, devec)) d2pr_dEs2 = _np.transpose(d2pr_dEs2, (0, 2,", "and dot-prod being 0. In # this case set to zero since we", "a (opLabel,i,j) tuple and each row corresponds to an element of the product", "sequence of operation labels. Parameters ---------- circuit : Circuit or tuple of operation", "= _np.log(nG) #evaluate operation sequences using tree (skip over the zero and single-gate-strings)", "if given a split tree (since there's no good way to reconstruct the", "int The number of subtrees to split the full evaluation tree into. num_subtree_proc_groups", "num blocks required to achieve desired average size == blkSize1 or blkSize2 blocks1", "evalSubTree, prodCache, scaleCache, blk2Comm, blk_wrtSlice2) dGs2 = evalSubTree.final_view(dProdCache2, axis=0) hProdCache = self._compute_hproduct_cache( evalSubTree,", ":class:`Label` objects giving the *simplified* effect labels. circuit : Circuit or tuple A", "3-tuple `(rowSlice, colSlice, hprobs)` or `(rowSlice, colSlice, dprobs12)` (the latter if `bReturnDProbs12 ==", "wrtSlice2: # Note: this doesn't involve gate derivatives d2pr_dErhos2 = _np.transpose(d2pr_dErhos1, (0, 2,", "None if (mySubComm is not None) and (mySubComm.Get_size() > 1): comm_blkSize = self.Np", "_np.zeros((nCircuits, nDerivCols1, nDerivCols2)) dp_dAnyE = _np.squeeze(_np.dot(dGs1, rho), axis=(3,)) * scaleVals[:, None, None] #", "(col) derivative operations, respectively. wrtBlockSize2, wrtBlockSize2 : int or float, optional The maximum", "gate / nG scaleCache[i] = _np.log(nG) #evaluate operation sequences using tree (skip over", "specifying which gate parameters to include in the derivative. Each element is an", "#flt2 = self._get_filter_info(wrtSlices2) # GATE DERIVS (assume hGs is already sized/filtered) ------------------- assert(hGs.shape[1]", "Note: we reverse iLeft <=> iRight from evalTree because # (iRight,iLeft,iFinal) = tup", "num_deriv_cols1, num_deriv_cols2), 'd') # For each pair of gates in the string, compute", "whether it's + or - inf anyway... dp_dOps[_np.isnan(dp_dOps)] = 0 #SPAM ------------- #", "evalTree, prodCache, scaleCache, None, myDerivColSlice, profiler) # pass None as comm, *not* mySubComm,", "G) # product of gates, starting with identity scale_exp += ex # scale", "mxToFill), evalSubTree, slice(None), slice(None), calc_and_fill) else: # Divide columns into blocks of at", "scaleCache, comm, wrtSlice2) dGs2 = evalTree.final_view(dProdCache2, axis=0) hProdCache = self._compute_hproduct_cache( evalTree, prodCache, dProdCache1,", "profiler = _dummy_profiler dim = self.dim nDerivCols = self.Np if (wrtSlice is None)", "rho), axis=(2,)) _fas(d2pr_dEs, [0, None, EVec.gpindices], _np.dot(derivWrtAnyEvec, EVec.deriv_wrt_params())) d2pr_dErhos = _np.zeros((1, self.Np, self.Np))", "processors to make use of in \" \" _compute_hproduct_cache.\") #TODO: remove: not needed", "_time.time() block_wrtSlice = blocks[iBlk] dProdCache = self._compute_dproduct_cache(evalSubTree, prodCache, scaleCache, blkComm, block_wrtSlice, profiler) profiler.add_time(\"bulk_fill_dprobs:", "1e-8: # _np.isclose(scale,0) is SLOW! hProdCache[i] /= _np.exp(scale) if hProdCache[i].max() < HSMALL and", ": int, optional A memory limit in bytes to impose upon the \"gather\"", "gate params to compute # derivatives wrt all spam parameters dGs = _np.empty((Gs.shape[0],", "gate.deriv_wrt_params(gate_wrtFilters2[opLabel]) for opLabel, gate in used_operations.items()} #Finally, cache any nonzero gate hessians (memory?)", "+ dot(S, dT) profiler.add_time(\"compute_dproduct_cache: dots\", tm) profiler.add_count(\"compute_dproduct_cache: dots\") scale = scaleCache[i] - (scaleCache[iLeft]", "the derivative of a specified sequence of operation labels. Parameters ---------- circuit :", "= Gs = dGs1 = dGs2 = hGs = None prodCache = scaleCache", "giving dproduct cache computation\" \" *fewer* processors and *smaller* (sub-)tree\" \" (e.g. by", "(expect ~ %.2fGB)\" % (mxToFill.nbytes / (1024.0**3))) ## memory profiling of python objects", ".label import Label as _Label from .matrixevaltree import MatrixEvalTree as _MatrixEvalTree from .forwardsim", "not bScale: old_err = _np.seterr(over='ignore', invalid='ignore') Gs = _np.swapaxes(_np.swapaxes(Gs, 0, 2) * scaleVals,", "over='ignore') dp_dOps = _np.squeeze(_np.dot(E, _np.dot(dGs, rho)), axis=(0, 3)) * scaleVals[:, None] _np.seterr(**old_err2) #", "by a zero deriv value (see below) dGs2[_np.isnan(dGs2)] = 0 # convert nans", "#Note: deriv2MxToFill gets computed on every inner loop completion # (to save mem)", "for this spam label (given by the subsequent arguments, except for the last).", "= _np.dot(E, Gs).squeeze(0) * scaleVals[:, None] # overflow OK d2pr_d2rhos = _np.zeros((nCircuits, nDerivCols1,", "overflow, but OK _fas(dpr_dEs, [0, EVec.gpindices], _np.dot(derivWrtAnyEvec, EVec.deriv_wrt_params())) dpr = dpr_drhos + dpr_dEs", ": numpy array Only returned when bScale == True. An array of shape", "nDerivCols2) deriv1Slices, myDeriv1ColSlice, deriv1Owners, mySubComm = \\ _mpit.distribute_slice(allDeriv1ColSlice, comm) # Get slice into", ": int The number of processor groups that will be assigned to subtrees", "model parameter (M is the length of the vectorized model). probability : float", "and wrtBlockSize wrtSlice = _slct.list_to_slice(wrtFilter) else: wrtSlice = None profiler.mem_check(\"bulk_fill_dprobs: begin (expect ~", "spamTuple, (fInds, gInds) in evalTree.spamtuple_indices.items(): # fInds = \"final indices\" = the \"element\"", "iterate through the self.operations.keys() as in # dproduct(...) and find the labels in", "clipTo[0], clipTo[1]) #Derivs wrt SPAM derivWrtAnyRhovec = scale * _np.dot(E, prod) dpr_drhos =", "invalid value due to scaleVals being inf and dot-prod being 0. In #", "ceiling(num_params / np2) mem = 0 for fnName in subcalls: if fnName ==", "dot(squeeze(dot(Gs, rho),axis=(2,)), dEP)[:,J] dp_dEs = _np.zeros((nCircuits, nDerivCols)) # may overflow, but OK (deriv", "an MPI communicator for distributing the computation across multiple processors. Distribution is performed", "np2 # ceiling(num_params / np2) mem = 0 for fnName in subcalls: if", "bool when set to True, additionally return the probability itself. clipTo : 2-tuple", "values, which is a functionality needed to correctly handle the remainder spam label.", "# cols = deriv cols, rows = flattened all else dGs2 = _np.swapaxes(_np.swapaxes(dGs2,", "(k,l)-th entry of the i-th operation sequence product with respect to the j-th", "mem += cache_size # scale vals ## It doesn't make sense to include", "computation, even if given a split tree (since there's no good way to", "a matrix # noqa # dprod/d(opLabel)_ij = sum_{L s.t. G(L) == oplabel} [", "assert(wrtSlice1 is None or _slct.length(wrtSlice1) == nDerivCols1) assert(wrtSlice2 is None or _slct.length(wrtSlice2) ==", "(easier to think about) revOpLabelList = tuple(reversed(tuple(circuit))) # prod = G1 * G2", "self._compute_dproduct_cache( evalTree, prodCache, scaleCache, None, myDerivColSlice, profiler) # pass None as comm, *not*", "spam labels. evalTree : EvalTree given by a prior call to bulk_evaltree. Specifies", "OK dpr_dEs = _np.zeros((1, self.Np)) derivWrtAnyEvec = scale * _np.transpose(_np.dot(prod, rho)) # may", "( len(circuit_list), nDerivCols, dim, dim ), # dGs[i] is dprod_dOps for ith string", "evolution not fully supported yet!\") # To support unitary evolution we need to:", "rho, E, Gs[gInds], dGs1[gInds], scaleVals[gInds], wrtSlice1), add=sumInto) if deriv2MxToFill is not None: _fas(deriv2MxToFill,", "if flat: return flattened_hprod else: return _np.transpose(flattened_hprod, (1, 2, 0)).reshape( (num_deriv_cols1, num_deriv_cols2, dim,", "and *smaller* (sub-)tree\" \" (e.g. by splitting tree beforehand), as there\" \" are", "(KM,N,1) * (KM,1,N') = (KM,N,N') yield wrtSlice1, wrtSlice2, hprobs, dprobs12 else: yield wrtSlice1,", "# dproduct(...) and find the labels in the string which match the current", "wrtSlice1, wrtSlice2), add=sumInto) _np.seterr(**old_err) #Set wrtBlockSize to use available processors if it isn't", "given) is possible. wrtFilter1, wrtFilter2 : list of ints, optional If not None,", "circuit: if lOp not in scaledGatesAndExps: opmx = self.sos.get_operation(lOp).todense() ng = max(_nla.norm(opmx), 1.0)", "have a 2nd-deriv method in addition of deriv_wrt_params # # Note: unvec( X", "the available processors. Returns ------- MatrixEvalTree \"\"\" evTree = _MatrixEvalTree() evTree.initialize(simplified_circuits, numSubtreeComms) return", "[ G1 ... G(M-1) d2G(M)/(dkl*dij) G(M+1) ... GN ] # noqa # a", "(no POVM or Instrument labels). numSubtreeComms : int The number of processor groups", "# (dim**2, nParams[opLabel]) if _slct.length(gpindices) > 0: # works for arrays too #", "opLabel, gate in used_operations.items(): if gate.has_nonzero_hessian(): hop_dopLabels[opLabel] = gate.hessian_wrt_params( gate_wrtFilters1[opLabel], gate_wrtFilters2[opLabel]) # Allocate", "\"\": # special case of empty label == no gate dProdCache[i] = _np.zeros(deriv_shape)", "start=0) # Create placeholder dGs for *no* gate params to compute # derivatives", "the (tree-) list of # all of the raw operation sequences which need", "num_deriv_cols1 = self.Np if (wrtFilter1 is None) else len(wrtFilter1) num_deriv_cols2 = self.Np if", "spam terms only compute one triangle of hessian # Note: d2pr_d2rhos and d2pr_d2Es", "rho,E b/c rho,E are EVec = self.sos.get_effect(elabel) # arrays, these are SPAMVecs d2prod_dGates", "in bulk_fill_probs(...). derivMxToFill1, derivMxToFill2 : numpy array, optional when not None, an already-allocated", "overwrite or add to the existing array values, which is a functionality needed", "\"\"\" if bScale: scaledGatesAndExps = {} scale_exp = 0 G = _np.identity(self.dim) for", "_warnings.warn(\"Scaled dProd small in order to keep prod managable.\") elif _np.count_nonzero(dProdCache[i]) and dProdCache[i].max()", "p = %g, norm %g, exp %g\\n%s\" % (i,p,norm(G),total_exp,str(G)) # if _np.isnan(p): raise", "opLabel in zip(evalTree.get_init_indices(), evalTree.get_init_labels()): if opLabel == \"\": # special case of empty", "= _np.conjugate(_np.transpose(Eraw)) return rho, E def _rhoEs_from_spamTuples(self, rholabel, elabels): #Note: no support for", "#Fill product cache info (not distributed) prodCache, scaleCache = self._compute_product_cache(evalTree, comm) scaleVals =", "_np.dot(E, prod) # may overflow, but OK d2pr_d2rhos = _np.zeros((1, self.Np, self.Np)) _fas(d2pr_d2rhos,", "None: _warnings.warn(\"Note: more CPUs(%d)\" % mySubComm.Get_size() + \" than hessian elements(%d)!\" % (self.Np**2)", "cache_size * wrtLen1 * dim * dim # dproduct cache mem += cache_size", "where M is the number of model parameters. hessian[0,j,k] is the derivative of", "a prior call to bulk_evaltree. Specifies the *simplified* gate strings to compute the", "0)).reshape( (num_deriv_cols1, num_deriv_cols2, dim, dim)) # axes = (gate_ij1, gateij2, prod_row, prod_col) def", "_np.tensordot(derivWrtAnyEvec, self.sos.get_effect(elabel).hessian_wrt_params(), (1, 0))) # _np.einsum('ij,jkl->ikl',derivWrtAnyEvec,self.sos.get_effect(elabel).hessian_wrt_params()) else: d2pr_d2Es = 0 ret = d2pr_dErhos", "of this is to allow a trace or other linear operation to be", "start with norm <= 1, products should all have norm <= 1 assert(len(nanOrInfCacheIndices)", "d2pr_d2Es = _np.zeros((1, self.Np, self.Np)) _fas(d2pr_d2Es, [0, self.sos.get_effect(elabel).gpindices, self.sos.get_effect(elabel).gpindices], _np.tensordot(derivWrtAnyEvec, self.sos.get_effect(elabel).hessian_wrt_params(), (1, 0)))", "-HSMALL: _warnings.warn(\"hProd is small (oh well!).\") return hProdCache ## END CACHE FUNCTIONS def", "add=sumInto) _fas(mxToFill, [fInds, pslc1], self._dprobs_from_rhoE( spamTuple, rho, E, Gs[gInds], dGs[gInds], scaleVals[gInds], wrtSlice), add=sumInto)", "info tm = _time.time() dProdCache = self._compute_dproduct_cache(evalSubTree, prodCache, scaleCache, mySubComm, wrtSlice, profiler) dGs", "# (nDerivCols1,dim**2) xv.shape = (nDerivCols1, dim, dim) # (reshape without copying - throws", "= _slct.list_to_slice(wrtFilter) else: wrtSlice = None profiler.mem_check(\"bulk_fill_dprobs: begin (expect ~ %.2fGB)\" % (mxToFill.nbytes", "= prodCache = scaleCache = None #Fill cache info prodCache, scaleCache = self._compute_product_cache(evalSubTree,", "preferred MPI distribution mode for this calculator. \"\"\" return \"deriv\" def estimate_cache_size(self, nCircuits):", "hProd small in order to keep prod managable.\") elif _np.count_nonzero(hProdCache[i]) and hProdCache[i].max() <", "1)) # get d2pr_dEs where E derivatives are wrt the 2nd set of", "operation sequences for spamTuple, (fInds, gInds) in evalTree.spamtuple_indices.items(): circuit_list = master_circuit_list[gInds] if prMxToFill", "self._process_wrtFilter(wrtFilter1, gate) op_wrtFilter2, gpindices2 = self._process_wrtFilter(wrtFilter2, gate) # Allocate memory for the final", "# _np.einsum('ij,jkl->ikl', derivWrtAnyRhovec, self.sos.get_prep(rholabel).hessian_wrt_params()) else: d2pr_d2rhos = 0 if self.sos.get_effect(elabel).has_nonzero_hessian(): derivWrtAnyEvec = scale", "wrtFilter2). evalTree : EvalTree given by a prior call to bulk_evaltree. Specifies the", "OK if infs occur here _np.seterr(**old_err) if bScale: return Gs, scaleVals else: old_err", "dp_dEs[i,J0+J] = sum_j dot(Gs, rho)[i,j,0] dEP[j,J] # dp_dEs[i,J0+J] = dot(squeeze(dot(Gs, rho),2), dEP)[i,J] #", "A generator which, when iterated, yields the 3-tuple `(rowSlice, colSlice, hprobs)` or `(rowSlice,", "# Compute all probabilities all at once so they're not repeatedly # computed", "evalTree.final_view(scaleCache) old_err = _np.seterr(over='ignore') scaleVals = _np.exp(scaleExps) # may overflow, but OK if", "self.evotype)) def copy(self): \"\"\" Return a shallow copy of this MatrixForwardSimulator \"\"\" return", "nDerivCols2: #If there are more processors than deriv cells, give a # warning", "2, mySubComm) # , gatherMemLimit) #gather over col-distribution (Deriv2) #note: gathering axis 2", "order to keep prod managable.\") elif _np.count_nonzero(hProdCache[i]) and hProdCache[i].max() < HSMALL and hProdCache[i].min()", "len(revOpLabelList) - 1)] = ident # product of no gates #Also Cache gate", "no contribution since we assume all gate elements are at most # linear", "bulk operation on. clipTo : 2-tuple, optional (min,max) to clip return value if", "#assert( len( (_np.isinf(hGs)).nonzero()[0] ) == 0 ) #hGs = clip(hGs,-1e300,1e300) _np.seterr(**old_err) if flat:", "now that we track owners #if mySubSubComm.Get_rank() > 0: myDeriv2ColSlice = slice(0,0) #", "at once so they're not repeatedly # computed for each block of derivative", "The number of final strings (may be less than or greater than `cacheSize`)", "flattened all else dGs1 = _np.swapaxes(_np.swapaxes(dGs1, 0, 1).reshape((nDerivCols1, nCircuits * dim**2)), 0, 1)", "=> (vec_prod_indx,kl,ij) else: # l==m, which we *used* to assume gave no contribution", "allow for parallelization of # _compute_product_cache when the tree was split, but this", "pslc2, sumInto): \"\"\" Compute and fill result quantities for given arguments \"\"\" tm", "CHECK #check_ps = _np.array( [ self.pr( (rholabel,elabel), circuit, clipTo, bScale) for elabel in", "the linear dimension of a operation matrix (G x G operation matrices). scaleValues", "dprobs12)` (the latter if `bReturnDProbs12 == True`). `rowSlice` and `colSlice` are slices directly", "error if copy is needed) y = _np.dot(_np.kron(xv, _np.transpose(prods[(l + 1, N -", "- 1)])), dop_dopLabel2[opLabel2]) # above: (nDerivCols1,dim**2,dim**2) * (dim**2,nDerivCols2) = (nDerivCols1,dim**2,nDerivCols2) flattened_d2prod[:, inds1, inds2]", "= _np.transpose(d2pr_dErhos1, (0, 2, 1)) else: d2pr_dErhos2 = _np.zeros((nCircuits, nDerivCols2, nDerivCols1)) drho =", "= len(evalTree) # ------------------------------------------------------------------ #print(\"MPI: _compute_dproduct_cache begin: %d deriv cols\" % nDerivCols) if", "rho ) )[0,i,j,0] # dp_dOps = squeeze( dot( E, dot( dGs, rho )", "operations, respectively. Each element is an index into an array of gate parameters", "dG(L)/dij ) ] # noqa # = sum{...} [ unvec( G1 ... G(M-1)", "EvalTree given by a prior call to bulk_evaltree. Specifies the operation sequences to", "that scaleVals[i] contains the multiplicative scaling needed for the hessians, derivatives, and/or products", "rho[l,0] * scaleVals[i] # vp[i] = sum_k E[0,k] dot(Gs, rho)[i,k,0] * scaleVals[i] #", "has shape (N,1) rho = self.sos.get_prep(rholabel).todense()[:, None] Es = [self.sos.get_effect(elabel).todense()[:, None] for elabel", "to track timing and memory usage. gatherMemLimit : int, optional A memory limit", "is None: profiler = _dummy_profiler if wrtFilter is not None: assert(wrtBlockSize is None)", "with \" \"matrix-based calculations\" % self.evotype)) def copy(self): \"\"\" Return a shallow copy", "When not None, an MPI communicator for distributing the computation across multiple processors.", "hGs = _np.rollaxis(_np.rollaxis(hGs, 0, 3).reshape( (nDerivCols1, nDerivCols2, nCircuits * dim**2)), 2) # as", "if clipTo is not None: _np.clip(mxToFill, clipTo[0], clipTo[1], out=mxToFill) # in-place clip if", "G(L+1) ... GN ] + {similar with L < M} # noqa #", "(if available and necessary) if comm.Get_size() > nDerivCols: #If there are more processors", "sorted(list(set(revOpLabelList))) for opLabel in uniqueOpLabels: gate = self.sos.get_operation(opLabel) op_wrtFilter, gpindices = self._process_wrtFilter(wrtFilter, gate)", "no cover if hprMxToFill is not None: check_vhp = _np.concatenate( [self.hpr(spamTuple, circuit, False,", "axis=0) #shape == ( len(circuit_list), nDerivColsX, dim, dim ), # dGs[i] is dprod_dOps", "[fInds], self._probs_from_rhoE(rho, E, Gs[gInds], scaleVals[gInds]), add=sumInto) _np.seterr(**old_err) profiler.add_time(\"bulk_fill_dprobs: calc_and_fill_p\", tm) # Compute all", "GN ] , a matrix for each given (i,j) # noqa # d2prod/d(opLabel1)_kl*d(opLabel2)_ij", "None # wrtFilter1 & wrtFilter2 dictates block if blkSize1 is None and blkSize2", "self.evotype not in (\"statevec\", \"densitymx\"): raise ValueError((\"Evolution type %s is incompatbile with \"", "order) # d2pr/d(E)_i d(rho)_j = prod_ij (and same for other diff order) #", "at a time. For example, the Hessian of a function of many gate", "may overflow or get nans (invalid), but ok hGs = _np.swapaxes(_np.swapaxes(hGs, 0, 4)", "_np.zeros((1, self.Np)) derivWrtAnyEvec = scale * _np.transpose(_np.dot(prod, rho)) # may overflow, but OK", "= Gs.shape[0] rho_wrtFilter1, rho_gpindices1 = self._process_wrtFilter(wrtSlice1, self.sos.get_prep(rholabel)) rho_wrtFilter2, rho_gpindices2 = self._process_wrtFilter(wrtSlice2, self.sos.get_prep(rholabel)) E_wrtFilter1,", "* B ) = B^T tensor A * vec( X ) def doperation(self,", "subcalls, cache_size, num_subtrees, num_subtree_proc_groups, num_param1_groups, num_param2_groups, num_final_strs): \"\"\" Estimate the memory required by", "_np.seterr(**old_err) if bReturnDProdsAndProds: Gs = evalTree.final_view(prodCache, axis=0) #shape == ( len(circuit_list), dim, dim", "is None or comm.Get_rank() == 0: # import objgraph # objgraph.show_growth(limit=50) #get distribution", "num_rho_params num_e_params') # # if wrtSlices is not None: # loc_rho_slices = [", "and hessians[i,j,k,l,m] holds the derivative of the (l,m)-th entry of the i-th operation", "self.Np)) _fas(d2pr_d2Es, [0, self.sos.get_effect(elabel).gpindices, self.sos.get_effect(elabel).gpindices], _np.tensordot(derivWrtAnyEvec, self.sos.get_effect(elabel).hessian_wrt_params(), (1, 0))) # _np.einsum('ij,jkl->ikl',derivWrtAnyEvec,self.sos.get_effect(elabel).hessian_wrt_params()) else: d2pr_d2Es", "tensor B^T * vec( E(0,1) ) # In general: vec( A * X", "circuit, clipTo, bUseScaling=False, time=None): \"\"\" Compute probabilities of a multiple \"outcomes\" (spam-tuples) for", "(see below). wrtFilter1, wrtFilter2 : list of ints, optional If not None, a", "when bReturnDProdsAndProds == True. An array of shape S x G x G;", "the number of model parameters selected for the 1st and 2nd differentiation, respectively", "compute all requested rows or columns at once. The minimum of wrtBlockSize and", "shape (len(elabels),N) return rho, Es def _probs_from_rhoE(self, rho, E, Gs, scaleVals): if self.evotype", "= evalSubTree.final_view(dProdCache2, axis=0) hProdCache = self._compute_hproduct_cache( evalSubTree, prodCache, dProdCache1, dProdCache2, scaleCache, blk2Comm, blk_wrtSlice1,", "SLOW! hProdCache[i] /= _np.exp(scale) if hProdCache[i].max() < HSMALL and hProdCache[i].min() > -HSMALL: _warnings.warn(\"Scaled", "<=> iRight from evalTree because # (iRight,iLeft,iFinal) = tup implies circuit[i] = circuit[iLeft]", "%d\" % comm.Get_size()) # parallelize of deriv cols, then sub-trees (if available and", "print(\"MPI DEBUG: Rank%d subtee sizes = %s\" % # (comm.Get_rank(),\",\".join([str(len(subtrees[i])) # for i", "arrays. The arrays that are filled internally to `calc_and_fill_fn` must be the same", "= (nDerivCols1,dim**2,nDerivCols2) flattened_d2prod[:, inds1, inds2] += _np.swapaxes(y, 0, 1) # above: dim =", "dEPT[J,k] dGs[i,j,k,l] rho[l,0] # d2pr_dEs[i,j,J0+J] = sum_k dEP[k,J] dot(dGs, rho)[i,j,k,0] # d2pr_dEs[i,j,J0+J] =", "prod ) = sum E_k prod_kl rho_l # d2pr/d(opLabel1)_mn d(opLabel2)_ij = sum E_k", "hproduct cache # mem += cache_size * num_params * dim * dim #", "), # hGs[i] is hprod_dGates for ith string if not bScale: old_err =", "the output of this function iterates over these computed blocks, in the order", "( len(circuit_list), dim, dim ), Gs[i] is product for i-th operation sequence scaleExps", "distributing the computation across multiple processors. Distribution is first performed over subtrees of", "wrtSlice1, wrtSlice2), add=sumInto) _np.seterr(**old_err) #NOTE: don't distribute wrtSlicesList across comm procs, # as", "Gs[gInds], dGs[gInds], scaleVals[gInds], block_wrtSlice), add=sumInto) _np.seterr(**old_err) profiler.add_time(\"bulk_fill_dprobs: calc_and_fill_blk\", tm) for iBlk in myBlkIndices:", "calc_and_fill_blk\", tm) for iBlk in myBlkIndices: tm = _time.time() block_wrtSlice = blocks[iBlk] dProdCache", "# transposes each of the now un-vectorized dim x dim mxs corresponding to", "rho_gpindices], _np.squeeze(_np.dot(_np.dot(E, Gs), rhoVec.deriv_wrt_params(rho_wrtFilter)), axis=(0,)) * scaleVals[:, None]) # may overflow, but OK", "is None) else _slct.length(wrtFilter) dim = self.dim wrtSlice = _slct.list_to_slice(wrtFilter) if (wrtFilter is", "mySubComm = evalTree.distribute(comm) #eval on each local subtree for iSubTree in mySubTreeIndices: evalSubTree", "nDerivCols2)) _fas(d2pr_d2rhos, [None, rho_gpindices1, rho_gpindices2], _np.tensordot(dp_dAnyRho, self.sos.get_prep(rholabel).hessian_wrt_params( rho_wrtFilter1, rho_wrtFilter2), (1, 0))) # _np.einsum('ij,jkl->ikl',", "L == M terms assumes that d^2 G/(dij)^2 == 0, which is true", "prodCache, scaleCache, blkComm, block_wrtSlice, profiler) profiler.add_time(\"bulk_fill_dprobs: compute_dproduct_cache\", tm) profiler.mem_check( \"bulk_fill_dprobs: post compute dproduct", "# [ G1 ... G(M-1) dG(M)/dkl G(M+1) ... G(L-1) dG(L)/dij G(L+1) ... GN", "[fInds, pslc1], self._dprobs_from_rhoE( spamTuple, rho, E, Gs[gInds], dGs[gInds], scaleVals[gInds], wrtSlice), add=sumInto) _np.seterr(**old_err) profiler.add_time(\"bulk_fill_dprobs:", "not None. Only relevant when prMxToFill is not None. bUseScaling : bool, optional", "dim)) scaleCache = _np.zeros(cacheSize, 'd') #First element of cache are given by evalTree's", "= self._rhoE_from_spamTuple(spamTuple) #if prMxToFill is not None: # _fas(prMxToFill, [fInds], # self._probs_from_rhoE(rho, E,", "number of subtrees to split the full evaluation tree into. num_subtree_proc_groups : int", "_np.transpose(xv, axes=(2, 0, 1)) # (dim2, nDerivCols1, nDerivCols2) flattened_d2prod[:, inds1, inds2] += xv", "and single-gate-strings) for i in evalTree.get_evaluation_order(): # combine iLeft + iRight => i", "makes maximal use of available processors is used as the final block size.", "# noqa # + sum{ L < M} [ G1 ... G(L-1) tensor", "M x G x G numpy array, where: - M == length of", "clipTo) for circuit in circuit_list], axis=0) if _nla.norm(dprMxToFill[fInds] - check_vdp) > 1e-6: _warnings.warn(\"norm(vdp-check_vdp)", "noqa # = [ sum_{L s.t. G(L) == oplabel} [ (G1 ... G(L-1))", "we use E(i,j) to denote the elementary matrix where all entries are zero", "internally for distributing calculations across multiple processors and to control memory usage. Cannot", "only compute d2(prod)/d(gl1)d(gl2) # and not d2(prod)/d(gl2)d(gl1) ... if m < l: x0", "zero except the (i,j) entry == 1 # if vec(.) concatenates rows (which", "dprod/d(opLabel)_ij = sum_{L s.t. GL == oplabel} [ G1 ... G(L-1) dG(L)/dij G(L+1)", "gathering axis 1 of hProdCache, # dim=(cacheSize,nDerivCols1,nDerivCols2,dim,dim) return hProdCache # ------------------------------------------------------------------ if evalTree.is_split():", "of all the gate's parameters if isinstance(wrtFilter, slice): wrtFilter = _slct.indices(wrtFilter) if wrtFilter", "at most *linear* in each of the gate parameters. If this is not", "iterate through the subtrees. It can often be useful to have fewer processor", "None: assert(wrtBlockSize is None) # Cannot specify both wrtFilter and wrtBlockSize wrtSlice =", "j in range(self.Np): d2pr_dOps2[0, i, j] = float(_np.dot(E, _np.dot(d2prod_dGates[i, j], rho))) old_err =", "= _np.dot(G, self.sos.get_operation(opLabel2).todense()) prods[(i, j)] = G prods[(len(revOpLabelList), len(revOpLabelList) - 1)] = ident", "not None: _fas(prMxToFill, [fInds], self._probs_from_rhoE( rho, E, Gs[gInds], scaleVals[gInds]), add=sumInto) _fas(mxToFill, [fInds, pslc1],", "if clipTo is not None: p = _np.clip(p, clipTo[0], clipTo[1]) #Derivs wrt SPAM", "a length-0 list, as this doesn't index numpy arrays # like length>1 lists", "post gather subtrees\") if clipTo is not None and prMxToFill is not None:", "# Note: d2pr_d2rhos and d2pr_d2Es terms are always zero _np.seterr(**old_err) if returnDeriv: if", "nDerivCols2, nDerivCols1)) drho = rhoVec.deriv_wrt_params(rho_wrtFilter1) dp_dAnyE = _np.dot(Gs, drho) * scaleVals[:, None, None]", "True. \"\"\" if self.evotype == \"statevec\": raise NotImplementedError(\"Unitary evolution not fully supported yet!\")", "(this can be obtained by `evalTree.num_final_elements()`. To interpret which elements correspond to which", "int The number of processor groups used to (in parallel) iterate through the", "= self._compute_hproduct_cache( evalTree, prodCache, dProdCache1[:, myDeriv1ColSlice], dProdCache2, scaleCache, None, myHessianSlice1, wrtSlice2) # pass", "= self.product(circuit, True) dprod_dOps = self.dproduct(circuit) dpr_dOps = _np.empty((1, self.Np)) for i in", "= [ sum(tmp_num_params[0:i]) for i in range(len(self.preps)+1) ] # global_rho_slices = [ slice(tmp_offsets[i],tmp_offsets[i+1])", "An array of shape S such that scaleVals[i] contains the multiplicative scaling needed", "\"bulk_product\": # mem += cache_size * dim * dim # product cache #", "then over blocks (subsets) of the parameters being differentiated with respect to (see", "evalTree, prodCache, scaleCache, comm, wrtSlice2) dGs2 = evalTree.final_view(dProdCache2, axis=0) hProdCache = self._compute_hproduct_cache( evalTree,", "\"\"\" nCircuits = evalTree.num_final_strings() nDerivCols = self.Np if (wrtFilter is None) else _slct.length(wrtFilter)", "deriv2MxToFill is not None: _mpit.gather_slices(blocks2, blk2Owners, deriv2MxToFill, [felInds], 1, blk1Comm, gatherMemLimit) #Note: deriv2MxToFill", "nBlks=%d]\" % (blkSize, nBlks)) # pragma: no cover def calc_and_fill_blk(spamTuple, fInds, gInds, pslc1,", "for arrays too # Compute the derivative of the entire operation sequence with", ": OrderedDict Ordered dictionaries of LinearOperator, SPAMVec, and SPAMVec objects, respectively. Must be", "* dim * dim # dproduct cache mem += cache_size * dim *", "to divide the first-derivative parameters into. Computation will be automatically parallelized over these", "False) if self.evotype == \"statevec\": ps = _np.real(_np.abs(_np.dot(Es, _np.dot(G, rho)))**2) else: # evotype", "self.sos.get_prep(rholabel).hessian_wrt_params()) else: d2pr_d2rhos = 0 if self.sos.get_effect(elabel).has_nonzero_hessian(): derivWrtAnyEvec = scale * _np.transpose(_np.dot(prod, rho))", "self._probs_from_rhoE(rho, E, Gs[gInds], scaleVals[gInds]), add=sumInto) _np.seterr(**old_err) self._fill_result_tuple((mxToFill,), evalSubTree, slice(None), slice(None), calc_and_fill) #collect/gather results", "gpindices2 = self._process_wrtFilter(wrtFilter2, gate) # Allocate memory for the final result num_deriv_cols1 =", "spamTuple, rho, E, Gs[gInds], dGs1[gInds], dGs2[gInds], hGs[gInds], scaleVals[gInds], wrtSlice1, wrtSlice2), add=sumInto) _np.seterr(**old_err) #Set", "not None and wrtSlice1.start is not None: myHessianSlice1 = _slct.shift(myDeriv1ColSlice, wrtSlice1.start) else: myHessianSlice1", "1, products should all have norm <= 1 assert(len(nanOrInfCacheIndices) == 0) return prodCache,", "1)] = ident # product of no gates #Also Cache gate jacobians (still", "evalTree, prodCache, scaleCache, comm=None, wrtSlice=None, profiler=None): \"\"\" Computes a tree of product derivatives", "before computing caches scaleVals = Gs = dGs1 = dGs2 = hGs =", ": int The size of the evaluation tree that will be passed to", "dGs[i] is dprod_dOps for ith string hGs = evalTree.final_view(hProdCache, axis=0) #shape == (", "num columns\", nDerivCols) return dProdCache def _compute_hproduct_cache(self, evalTree, prodCache, dProdCache1, dProdCache2, scaleCache, comm=None,", "inf anyway... dp_dOps[_np.isnan(dp_dOps)] = 0 #SPAM ------------- # Get: dp_drhos[i, rho_gpindices] = dot(E,Gs[i],drho/drhoP)", "= scaleCache = dProdCache = None #Fill cache info (not requiring column distribution)", "spam and gate-sequence indices # gInds = \"gate sequence indices\" = indices into", "dProdCache2.shape[1] assert(wrtSlice1 is None or _slct.length(wrtSlice1) == nDerivCols1) assert(wrtSlice2 is None or _slct.length(wrtSlice2)", "_np.zeros((nCircuits, nDerivCols)) _fas(dp_drhos, [None, rho_gpindices], _np.squeeze(_np.dot(_np.dot(E, Gs), rhoVec.deriv_wrt_params(rho_wrtFilter)), axis=(0,)) * scaleVals[:, None]) #", "... G(M-1) d2G(M)/(dkl*dij) G(M+1) ... GN ] # noqa # a matrix for", "cpus my_results = self._compute_dproduct_cache( evalTree, prodCache, scaleCache, None, myDerivColSlice, profiler) # pass None", "None and mySubSubComm.Get_size() > 1: _warnings.warn(\"Too many processors to make use of in", "# global_e_slices = [ slice(tmp_offsets[i],tmp_offsets[i+1]) # for i in range(len(self.effects)) ] # #", "Only relevant when prMxToFill is not None. bUseScaling : bool, optional Whether to", "`dprobs12` are arrays of shape K x S x B x B', where:", "prods = {} ident = _np.identity(dim) for (i, opLabel1) in enumerate(revOpLabelList): # loop", ") ) # noqa # tensor (G(L+1) ... GN)^T vec( dG(L)/dij ) ]", "else: dop_dopLabel2 = { opLabel: gate.deriv_wrt_params(gate_wrtFilters2[opLabel]) for opLabel, gate in used_operations.items()} #Finally, cache", "old_err = _np.seterr(over='ignore') G, scale = self.product(circuit, True) if self.evotype == \"statevec\": ps", "there are more processors than model parameters, distribution over a split evalTree (if", "Used for testing, and runs much slower when True. comm : mpi4py.MPI.Comm, optional", "== True, in which case the actual product == product * scale. The", "begin: %d deriv cols\" % nDerivCols) if comm is not None and comm.Get_size()", "needs to be applied to the resulting products (final_product[i] = scaleValues[i] * prods[i]).", "of model params or wrtFilter1 or 2, respectively - G == the linear", "if flat == False, an array of shape S x M x G", "indexed by iOpStr and iSpamLabel. d12 has the same dimensions as the Hessian,", "* if flat == False, a M x G x G array, where:", "Estimate the memory required by a given set of subcalls to computation functions.", "= dProdCache1.shape[1] nDerivCols2 = dProdCache2.shape[1] assert(wrtSlice1 is None or _slct.length(wrtSlice1) == nDerivCols1) assert(wrtSlice2", "] + {similar with L < M} # noqa # + sum{M==L} [", "copy is needed) y = _np.dot(_np.kron(xv, _np.transpose(prods[(l + 1, N - 1)])), dop_dopLabel2[opLabel2])", "d2pr_dErhos2 = _np.transpose(d2pr_dErhos1, (0, 2, 1)) else: d2pr_dErhos2 = _np.zeros((nCircuits, nDerivCols2, nDerivCols1)) drho", "nDerivCols, dim, dim ) if not bScale: old_err = _np.seterr(over='ignore', invalid='ignore') # may", "False, a M x G x G array, where: - M == length", "G = _np.identity(dim); rightProdsT.append(_np.transpose(G)) for opLabel in reversed(revOpLabelList): G = _np.dot(self.sos.get_operation(opLabel).todense(), G) rightProdsT.append(_np.transpose(G))", "when vectorizing op uses numpy.flatten rows are kept contiguous, so the first identity", "into entire range of model params (see above) if wrtSlice2 is not None", "squeeze(dot(dGs, rho),axis=(3,)), dEP)[:,:,J] d2pr_dEs1 = _np.zeros((nCircuits, nDerivCols1, nDerivCols2)) dp_dAnyE = _np.squeeze(_np.dot(dGs1, rho), axis=(3,))", "when prMxToFill is not None. bUseScaling : bool, optional Whether to use a", "( len(circuit_list), nDerivCols1, nDerivCols2, dim, dim ), # hGs[i] is hprod_dGates for ith", "_np.dot(Gs, drho) * scaleVals[:, None, None] # overflow OK devec = EVec.deriv_wrt_params(E_wrtFilter2) _fas(d2pr_dErhos2,", "blocks for given arguments \"\"\" tm = _time.time() old_err = _np.seterr(over='ignore') rho, E", "nan as the returned probability. time : float, optional The *start* time at", "but OK (deriv w.r.t any of self.effects - independent of which) dp_dAnyE =", "calcs of the given # wrtSlicesList last_wrtSlice1 = None # keep last dProdCache1", "\" \" _compute_dproduct_cache.\") if mySubComm.Get_rank() > 0: myDerivColSlice = slice(0, 0) #don't compute", "if infs occur here _np.seterr(**old_err) if bScale: return Gs, scaleVals else: old_err =", "the output array size. Could throw more informative error? #elif fnName == \"bulk_product\":", "1)) # Get: d2pr_dEs[i, j, E_gpindices] = dot(transpose(dE/dEP),dGs[i,j],rho) # d2pr_dEs[i,j,J0+J] = sum_kl dEPT[J,k]", "prMxToFill, mxToFill, clipTo=clipTo) profiler.add_time(\"bulk_fill_dprobs: total\", tStart) profiler.add_count(\"bulk_fill_dprobs count\") profiler.mem_check(\"bulk_fill_dprobs: end\") def bulk_fill_hprobs(self, mxToFill,", "not None: ret = _np.clip(ps, clipTo[0], clipTo[1]) else: ret = ps #DEBUG CHECK", "pre-filtered!\" assert(dGs2.shape[1] == nDerivCols2), \"dGs1 must be pre-filtered!\" # Get: d2pr_drhos[i, j, rho_gpindices]", "= _time.time() block_wrtSlice = blocks[iBlk] dProdCache = self._compute_dproduct_cache(evalSubTree, prodCache, scaleCache, blkComm, block_wrtSlice, profiler)", "= _np.seterr(over='ignore') scaleVals = _np.exp(scaleExps) # may overflow, but OK if infs occur", "any of self.effects - independent of which) dp_dAnyE = _np.squeeze(_np.dot(Gs, rho), axis=(2,)) *", "subtree #my_results = [] for iSubTree in mySubTreeIndices: evalSubTree = subtrees[iSubTree] felInds =", "# product of gates, starting with identity scale_exp += ex # scale and", "concatenated form of the above matrices, so that # each column corresponds to", "cache # mem += cache_size * dim * dim # product cache #", "= self.hproduct(circuit) assert(d2prod_dGates.shape[0] == d2prod_dGates.shape[1]) d2pr_dOps2 = _np.empty((1, self.Np, self.Np)) for i in", "autogator : AutoGator An auto-gator object that may be used to construct virtual", "overflow OK devec = EVec.deriv_wrt_params(E_wrtFilter1) _fas(d2pr_dErhos1, (None, E_gpindices1, rho_gpindices2), _np.swapaxes(_np.dot(_np.transpose(devec), dp_dAnyE), 0, 1))", "MatrixEvalTree \"\"\" evTree = _MatrixEvalTree() evTree.initialize(simplified_circuits, numSubtreeComms) return evTree def estimate_mem_usage(self, subcalls, cache_size,", "dim=(cacheSize,nDerivCols1,nDerivCols2,dim,dim) return hProdCache # ------------------------------------------------------------------ if evalTree.is_split(): _warnings.warn(\"Ignoring tree splitting in hproduct cache", "is used as the final block size. This argument must be None if", "True, an array of shape S*N x M where - N == the", "evaluation tree that will be passed to the functions named by `subcalls`. num_subtrees", "# noqa # = sum{...} [ unvec( G1 ... G(M-1) tensor (G(M+1) ...", "wrtSlices is not None: # loc_rho_slices = [ # _slct.shift(_slct.intersect( # wrtSlices['preps'], #", "This function returns a concatenated form of the above matrices, so that #", "memory usage. gatherMemLimit : int, optional A memory limit in bytes to impose", "Instrument labels). numSubtreeComms : int The number of processor groups that will be", "ps.flatten() if _np.any(_np.isnan(ps)): if len(circuit) < 10: strToPrint = str(circuit) else: strToPrint =", "clipTo[1]) dprod_dOps = self.dproduct(circuit) assert(dprod_dOps.shape[0] == self.Np) if returnDeriv: # same as in", "not the case, need LinearOperator objects to # have a 2nd-deriv method in", "mySubComm, wrtSlice2) dGs1 = evalSubTree.final_view(dProdCache1, axis=0) dGs2 = evalSubTree.final_view(dProdCache2, axis=0) #( nCircuits, nDerivColsX,", "values old_err = _np.seterr(over='ignore') scaleExps = evalTree.final_view(scaleCache) scaleVals = _np.exp(scaleExps) # may overflow,", "G(M+1) ... GN ] # noqa # a matrix for each given (i,j,k,l)", "strToPrint = str(circuit) else: strToPrint = str(circuit[0:10]) + \" ... (len %d)\" %", "Es has shape (len(elabels),N) return rho, Es def _probs_from_rhoE(self, rho, E, Gs, scaleVals):", "dop_dopLabel1 else: dop_dopLabel2 = { opLabel: gate.deriv_wrt_params(gate_wrtFilters2[opLabel]) for opLabel, gate in used_operations.items()} #Finally,", "to bulk_evaltree. Specifies the operation sequences to compute the bulk operation on. bScale", "# computed for each block of derivative columns if prMxToFill is not None:", "% (_nla.norm(hprMxToFill[fInds]), _nla.norm(check_vhp), _nla.norm(hprMxToFill[fInds] - check_vhp))) # pragma: no cover def bulk_fill_probs(self, mxToFill,", "self.Np, self.Np)) derivWrtAnyEvec = _np.squeeze(_np.dot(dprod_dOps, rho), axis=(2,)) _fas(d2pr_dEs, [0, None, EVec.gpindices], _np.dot(derivWrtAnyEvec, EVec.deriv_wrt_params()))", "> 1: deriv2Slices, myDeriv2ColSlice, deriv2Owners, mySubSubComm = \\ _mpit.distribute_slice(allDeriv2ColSlice, mySubComm) # Get slice", "self._fill_result_tuple((prMxToFill,), evalSubTree, slice(None), slice(None), calc_and_fill_p) profiler.mem_check(\"bulk_fill_dprobs: post fill probs\") #distribute derivative computation across", "returnDeriv : bool when set to True, additionally return the derivative of the", "gatherMemLimit) #note: gathering axis 1 of mxToFill[felInds], dim=(ks,M) profiler.add_time(\"MPI IPC\", tm) profiler.mem_check(\"bulk_fill_dprobs: post", "is None) # Cannot specify both wrtFilter and wrtBlockSize wrtSlice1 = _slct.list_to_slice(wrtFilter1) else:", "\"\"\" pslc1 = param_slice1 pslc2 = param_slice2 for spamTuple, (fInds, gInds) in evalTree.spamtuple_indices.items():", "fill function computes values for only a single spam label (specified to it", "= _np.seterr(over='ignore') scale = _np.exp(scale_exp) _np.seterr(**old_err) return G, scale else: G = _np.identity(self.dim)", "E(i,j) to denote the elementary matrix where all entries are zero except the", "*subset* of all the gate's parameters if isinstance(wrtFilter, slice): wrtFilter = _slct.indices(wrtFilter) if", "flattened product with respect to the j-th model parameter. \"\"\" # LEXICOGRAPHICAL VS", "Compute the derivative of a many operation sequences at once. Parameters ---------- evalTree", "if fnName == \"bulk_fill_probs\": mem += cache_size * dim * dim # product", "pragma: no cover if hprMxToFill is not None: check_vhp = _np.concatenate( [self.hpr(spamTuple, circuit,", "could make sense to iterate through the self.operations.keys() as in # dproduct(...) and", "of which specify a \"block\" of the Hessian to compute. Iterating over the", "= scale * _np.transpose(_np.dot(prod, rho)) # may overflow, but OK d2pr_d2Es = _np.zeros((1,", "= A^T tensor B^T ) # and using numpy's reshape dim = self.dim", "linear in params, so # all hessians for single- or zero-operation sequences are", "array of length equal to the total number of computed elements (i.e. evalTree.num_final_elements())", "probability-Hessians for an entire tree of gate strings. Similar to `bulk_fill_probs(...)`, but fills", "axis=1) # TODO: remove this concat w/better gather? # ------------------------------------------------------------------ tSerialStart = _time.time()", "# mem += cache_size * num_params * dim * dim # dproduct cache", "distribution over a split evalTree (if given) is possible. wrtFilter1, wrtFilter2 : list", "nBlks1) blocks2 = _mpit.slice_up_range(self.Np, nBlks2) #distribute derivative computation across blocks myBlk1Indices, blk1Owners, blk1Comm", "of the Hessian to compute. Iterating over the output of this function iterates", "1)], xv), dop_dopLabel2[opLabel2]) # above: (nDerivCols1,dim**2,dim**2) * (dim**2,nDerivCols2) = (nDerivCols1,dim**2,nDerivCols2) flattened_d2prod[:, inds1, inds2]", "array that is filled with probabilities, just like in bulk_fill_probs(...). derivMxToFill1, derivMxToFill2 :", "(reshape without copying - throws error if copy is needed) # transposes each", "_np.dot(hL, R) + dLdR_sym + _np.transpose(_np.dot(L, hR), (1, 2, 0, 3)) scale =", "inf scaleVal is mult by a zero deriv value (see below) dGs1[_np.isnan(dGs1)] =", "is not None: check_vdp = _np.concatenate( [self.dpr(spamTuple, circuit, False, clipTo) for circuit in", "_fas(deriv2MxToFill, [fInds, pslc2], self._dprobs_from_rhoE( spamTuple, rho, E, Gs[gInds], dGs2[gInds], scaleVals[gInds], wrtSlice2), add=sumInto) _fas(mxToFill,", "In # this case set to zero since we can't tell whether it's", "with probabilities, just like in bulk_fill_probs(...). clipTo : 2-tuple, optional (min,max) to clip", "in addition of deriv_wrt_params # # Note: unvec( X ) can be done", "== ( len(circuit_list), nDerivColsX, dim, dim ), # dGs[i] is dprod_dOps for ith", "+ d2pr_dErhos2 + d2pr_drhos2 # wrt rho ret += d2pr_dErhos1 + d2pr_d2Es +", "R = prodCache[iLeft], prodCache[iRight] dL, dR = dProdCache[iLeft], dProdCache[iRight] dProdCache[i] = _np.dot(dL, R)", "def bulk_fill_hprobs(self, mxToFill, evalTree, prMxToFill=None, deriv1MxToFill=None, deriv2MxToFill=None, clipTo=None, check=False, comm=None, wrtFilter1=None, wrtFilter2=None, wrtBlockSize1=None,", "additionally return the probability itself. clipTo : 2-tuple (min,max) to clip returned probability", "the zero and single-gate-strings) for i in evalTree.get_evaluation_order(): tm = _time.time() # combine", "tree information it needs to distribute itself among the available processors. Returns -------", "gatherMemLimit) #note: pass mxToFill, dim=(KS,M), so gather mxToFill[felInds] (axis=0) if prMxToFill is not", "_np.empty((Gs.shape[0], 0, self.dim, self.dim), 'd') def calc_and_fill_p(spamTuple, fInds, gInds, pslc1, pslc2, sumInto): \"\"\"", "# per-gate hessians can be computed properly if wrtSlice1 is not None and", "vals elif fnName == \"bulk_fill_hprobs\": mem += cache_size * wrtLen1 * wrtLen2 *", ") profiler.add_time(\"bulk_fill_dprobs: compute_dproduct_cache\", tm) profiler.mem_check(\"bulk_fill_dprobs: post compute dproduct\") #Compute all requested derivative columns", "(min,max) to clip returned probability to if not None. Only relevant when prMxToFill", "computed elements (i.e. evalTree.num_final_elements()) and M1 & M2 are the number of selected", "= evalTree.final_view(hProdCache, axis=0) if bReturnDProbs12: dprobs1 = _np.zeros((nElements, _slct.length(wrtSlice1)), 'd') dprobs2 = _np.zeros((nElements,", "in their effect-label (their prep labels must be the same) Parameters ---------- rholabel", "x M array, where M is the number of model parameters. hessian[0,j,k] is", "thought of as the first gate operation performed, which is on the far", "_np.seterr(**old_err) if flat: # cols = deriv cols, rows = flattened all else", "dim ), # dGs[i] is dprod_dOps for ith string hGs = evalTree.final_view(hProdCache, axis=0)", "uniqueOpLabels = sorted(list(set(revOpLabelList))) used_operations = _collections.OrderedDict() #Cache processed parameter filters for multiple uses", "overflow, but OK ; shape == (len(circuit_list), nDerivCols, nDerivCols) # may also give", "the parent-function scope. This use of # closures seems confusing and we should", "# noqa # = vec(i,j)-col of [ sum_{L s.t. G(L) == oplabel} [", "EVec.deriv_wrt_params(E_wrtFilter2) _fas(d2pr_dErhos2, [None, E_gpindices2, rho_gpindices1], _np.swapaxes(_np.dot(_np.transpose(devec), dp_dAnyE), 0, 1)) d2pr_dErhos2 = _np.transpose(d2pr_dErhos2, (0,", "maximal use of available processors is used as the final block size. This", "/ ng, _np.log(ng)) gate, ex = scaledGatesAndExps[lOp] H = _np.dot(gate, G) # product", "profiler.add_time(\"MPI IPC\", tm) profiler.mem_check(\"bulk_fill_dprobs: post gather subtrees\") if clipTo is not None and", "calc_and_fill_blk(spamTuple, fInds, gInds, pslc1, pslc2, sumInto): \"\"\" Compute and fill result quantities blocks", "the derivative of the entire operation sequence with respect to the # gate's", "simplified. Parameters ---------- mxToFill : numpy ndarray an already-allocated 1D numpy array of", "-- non-gate-local -- parameterizations of operation matrices and SPAM vectors) access to these", "model parameter. probability : float only returned if returnPr == True. \"\"\" if", "------- product : numpy array The product or scaled product of the operation", "\"\"\" prodCache, scaleCache = self._compute_product_cache(evalTree, comm) #use cached data to construct return values", "computing %s)\" \\ # % (nDerivCols2, comm.Get_rank(), str(myDerivColSlice))) if mySubComm is not None", "is irrelevant here b/c cachesize is always >= num_final_strs # and this dictates", "prodCache, scaleCache, comm, wrtSlice) #use cached data to construct return values old_err =", "nDerivCols1 = dop_dopLabel1[opLabel1].shape[1] if nDerivCols1 == 0: continue for l, opLabel2 in enumerate(revOpLabelList):", "dim = self.dim uniqueOpLabels = sorted(list(set(revOpLabelList))) used_operations = _collections.OrderedDict() #Cache processed parameter filters", "%g = %g\" % (_nla.norm(dprMxToFill[fInds]), _nla.norm(check_vdp), _nla.norm(dprMxToFill[fInds] - check_vdp))) # pragma: no cover", "over='ignore') d2pr_dOps2 = _np.squeeze(_np.dot(E, _np.dot(hGs, rho)), axis=(0, 4)) * scaleVals[:, None, None] _np.seterr(**old_err2)", "assert(dGs2.shape[1] == nDerivCols2), \"dGs1 must be pre-filtered!\" # Get: d2pr_drhos[i, j, rho_gpindices] =", "M x G x G array, where: - M == length of the", "memory hProdCache = _np.zeros((cacheSize,) + hessn_shape) # Use comm to distribute columns allDeriv1ColSlice", "fill result quantities blocks for given arguments \"\"\" tm = _time.time() old_err =", "get d2pr_dEs where E derivatives are wrt the 2nd set of gate parameters", "\"\"\" return int(1.3 * nCircuits) def construct_evaltree(self, simplified_circuits, numSubtreeComms): \"\"\" Constructs an EvalTree", "yielded, *not* allocated by the user. mem += 2 * cache_size * nspam", "check_vp = _np.array([self.prs(spamTuple[0], [spamTuple[1]], circuit, clipTo, False)[0] for circuit in circuit_list]) if _nla.norm(prMxToFill[fInds]", "zero hessian value (see below) hGs[_np.isnan(hGs)] = 0 _np.seterr(**old_err) if flat: # cols", "= param_slice1 pslc2 = param_slice2 for spamTuple, (fInds, gInds) in evalTree.spamtuple_indices.items(): # fInds", "comm.Get_size() > 1: # parallelize of deriv cols, then sub-trees (if available and", "that may be used to construct virtual gates for use in computations. \"\"\"", "dGs1[gInds], dGs2[gInds], hGs[gInds], scaleVals[gInds], wrtSlice1, wrtSlice2), add=sumInto) _np.seterr(**old_err) #NOTE: don't distribute wrtSlicesList across", "with # respect to a given gateLabel_ij. This function returns a concatenated form", "bulk_evaltree. Specifies the operation sequences to compute the bulk operation on. This tree", "= _np.dot(gate, G / nG); scale_exp += _np.log(nG) # LEXICOGRAPHICAL VS MATRIX ORDER", "with probability-Hessians for each \"final element\" of `evalTree`. Parameters ---------- mxToFill : numpy", "X^T ( note (A tensor B)^T = A^T tensor B^T ) # and", "the zero hessian value trumps since we've renormed to keep all the products", "# scale cache mem += cache_size # scale vals elif fnName == \"bulk_hprobs_by_block\":", "None: check_vhp = _np.concatenate( [self.hpr(spamTuple, circuit, False, False, clipTo) for circuit in circuit_list],", "of at most blkSize assert(wrtFilter is None) # cannot specify both wrtFilter and", "dproduct cache computation\" \" *fewer* processors and *smaller* (sub-)tree\" \" (e.g. by splitting", "wrtFilter=None): \"\"\" Compute the derivative of a many operation sequences at once. Parameters", "None) else len(wrtFilter1) num_deriv_cols2 = self.Np if (wrtFilter2 is None) else len(wrtFilter2) flattened_hprod", "outcome probability-derivatives for an entire tree of gate strings. Similar to `bulk_fill_probs(...)`, but", "required memory is fixed ## (and dominated) by the output array size. Could", "MPI communicator for distributing the computation across multiple processors. Distribution is first performed", "length of the vectorized model (number of model parameters) and deriv[i,j] holds the", "+ wrtLen2) # dprobs1 & dprobs2 mem += cache_size * wrtLen1 * wrtLen2", "Gs[i] is product for i-th operation sequence dGs1 = evalTree.final_view(dProdCache1, axis=0) dGs2 =", "wrt rho ret += d2pr_dErhos1 + d2pr_d2Es + d2pr_dEs2 # wrt E ret", "_np.squeeze(_np.dot(_np.dot(E, Gs), rhoVec.deriv_wrt_params(rho_wrtFilter)), axis=(0,)) * scaleVals[:, None]) # may overflow, but OK #", "The maximum number of derivative columns to compute *products* for simultaneously. None means", "each given (i,j,k,l) # noqa # vec( d2prod/d(opLabel1)_kl*d(opLabel2)_ij ) = sum{...} [ G1", "should be dim x 1. gates, preps, effects : OrderedDict Ordered dictionaries of", "def hoperation(self, opLabel, flat=False, wrtFilter1=None, wrtFilter2=None): \"\"\" Return the hessian of a length-1", "(single-gate) sequence \"\"\" dim = self.dim gate = self.sos.get_operation(opLabel) op_wrtFilter, gpindices = self._process_wrtFilter(wrtFilter,", "derivative calculations across multiple processors. Returns ------- derivs : numpy array * if", "linear in the parameters assert(opLabel1 == opLabel2) if opLabel1 in hop_dopLabels: # indicates", "sequences to compute the bulk operation on. flat : bool, optional Affects the", "None, None] # overflow OK devec = EVec.deriv_wrt_params(E_wrtFilter1) _fas(d2pr_dErhos1, (None, E_gpindices1, rho_gpindices2), _np.swapaxes(_np.dot(_np.transpose(devec),", "= _np.dot(gate, G) # product of gates, starting with identity scale_exp += ex", "OK d2pr_d2Es = _np.zeros((1, self.Np, self.Np)) _fas(d2pr_d2Es, [0, self.sos.get_effect(elabel).gpindices, self.sos.get_effect(elabel).gpindices], _np.tensordot(derivWrtAnyEvec, self.sos.get_effect(elabel).hessian_wrt_params(), (1,", "dGs2 = evalSubTree.final_view(dProdCache2, axis=0) #( nCircuits, nDerivColsX, dim, dim ) hProdCache = self._compute_hproduct_cache(evalSubTree,", "contiguous, so the first identity below is valid. # Below we use E(i,j)", "be passed to the functions named by `subcalls`. num_subtrees : int The number", "the number of entries in a single flattened gate (ordering as numpy.flatten) -", "for an entire tree of gate strings. Similar to `bulk_fill_probs(...)`, but fills a", "_fas(prMxToFill, [fInds], # self._probs_from_rhoE(rho, E, Gs[gInds], scaleVals[gInds]), add=sumInto) if deriv1MxToFill is not None:", "_np.rollaxis(_np.rollaxis(hGs, 0, 3).reshape( (nDerivCols1, nDerivCols2, nCircuits * dim**2)), 2) # cols = deriv", "# bounds #assert( len( (_np.isnan(hGs)).nonzero()[0] ) == 0 ) #assert( len( (_np.isinf(hGs)).nonzero()[0] )", "= squeeze( dot( E, dot(Gs, rho)), axis=(0,2) ) * scaleVals return _np.squeeze(_np.dot(E, _np.dot(Gs,", "correspond to the vectorized derivatives of each of the product components (i.e. prod_kl)", "gate_wrtFilters1 = {} gpindices2 = {}; gate_wrtFilters2 = {} for l in uniqueOpLabels:", "= _time.time() old_err = _np.seterr(over='ignore') rho, E = self._rhoE_from_spamTuple(spamTuple) block_wrtSlice = pslc1 _fas(mxToFill,", "wrtSlice2.start) else: myHessianSlice2 = myDeriv2ColSlice if mySubSubComm is not None and mySubSubComm.Get_size() >", "Hessian to compute. Iterating over the output of this function iterates over these", "savings from using a split tree. In short, parallelization should be done at", "for. cache_size : int The size of the evaluation tree that will be", "else len(wrtFilter) flattened_dprod = _np.zeros((dim**2, num_deriv_cols), 'd') _fas(flattened_dprod, [None, gpindices], gate.deriv_wrt_params(op_wrtFilter)) # (dim**2,", "scaleCache, comm, wrtSlice2) hProdCache = self._compute_hproduct_cache(evalTree, prodCache, dProdCache1, dProdCache2, scaleCache, comm, wrtSlice1, wrtSlice2)", "thing (for debugging) master_circuit_list = evalTree.generate_circuit_list(permute=False) # raw operation sequences for spamTuple, (fInds,", "not None, a list of integers specifying which parameters to include in the", "2, 1)) else: d2pr_dEs2 = _np.zeros((nCircuits, nDerivCols2, nDerivCols1)) dp_dAnyE = _np.squeeze(_np.dot(dGs2, rho), axis=(3,))", "= None #Fill cache info (not requiring column distribution) tm = _time.time() prodCache,", "_compute_dproduct_cache over %d cols (%s) (rank %d computing %s)\" \\ # % (nDerivCols,", "blk2Owners, deriv2MxToFill, [felInds], 1, blk1Comm, gatherMemLimit) #Note: deriv2MxToFill gets computed on every inner", "The purpose of this is to allow a trace or other linear operation", "the hessian of a specified sequence of operation labels. Parameters ---------- circuit :", "mpi4py.MPI.Comm, optional When not None, an MPI communicator for distributing the computation across", "of the (j,k)-th entry of the product with respect to the i-th model", "sum{...} [ G1 ... G(M-1) dG(M)/dkl G(M+1) ... G(L-1) tensor (G(L+1) ... GN)^T", ") * exp(total_exp) # probability # print \"%d: p = %g, norm %g,", "ret, dpr, p else: return ret, dpr else: if returnPr: return ret, p", "dpr else: if returnPr: return ret, p else: return ret ## BEGIN CACHE", "rho,E are EVec = self.sos.get_effect(elabel) # arrays, these are SPAMVecs #Derivs wrt Gates", "= G,dG # dp_dOps[i,j] = sum_k,l E[0,k] dGs[i,j,k,l] rho[l,0] # dp_dOps[i,j] = sum_k", "len(evalTree)) nanOrInfCacheIndices = (~_np.isfinite(prodCache)).nonzero()[0] # may be duplicates (a list, not a set)", "this dictates how large all the storage arrays are. np1, np2 = num_param1_groups,", "the derivative of the (k,l)-th entry of the product with respect to the", "HSMALL = 1e-100 class MatrixForwardSimulator(ForwardSimulator): \"\"\" Encapsulates a calculation tool used by model", "myBlk2Indices, blk2Owners, blk2Comm = \\ _mpit.distribute_indices(list(range(nBlks2)), blk1Comm) if blk2Comm is not None: _warnings.warn(\"Note:", "+ hessn_shape) #First element of cache are given by evalTree's initial single- or", "wrtSlice2) dGs2 = evalTree.final_view(dProdCache2, axis=0) hProdCache = self._compute_hproduct_cache( evalTree, prodCache, dProdCache1, dProdCache2, scaleCache,", "is None and blkSize2 is None: #Fill hessian cache info dProdCache1 = self._compute_dproduct_cache(", "# overflow OK devec = EVec.deriv_wrt_params(E_wrtFilter1) _fas(d2pr_dEs2, [None, None, E_gpindices1], _np.dot(dp_dAnyE, devec)) d2pr_dEs2", "and (mySubComm.Get_size() > 1): comm_blkSize = self.Np / mySubComm.Get_size() blkSize = comm_blkSize if", "dim * dim # hproduct cache mem += cache_size * (wrtLen1 + wrtLen2)", "\"\"\" assert(not evalTree.is_split()), \"`evalTree` cannot be split\" nElements = evalTree.num_final_elements() #Fill product cache", "a chance that the product will overflow and the subsequent trace operation will", "may overflow, but OK if infs occur here _np.seterr(**old_err) if bReturnDProdsAndProds: Gs =", "rho, E = self._rhoE_from_spamTuple(spamTuple) #if prMxToFill is not None: # _fas(prMxToFill, [fInds], #", "parameters into. Computation will be automatically parallelized over these groups. num_param2_groups : int", "an entire tree of gate strings. Similar to `bulk_fill_probs(...)`, but fills a 3D", "axis=0) if _nla.norm(hprMxToFill[fInds][0] - check_vhp[0]) > 1e-6: _warnings.warn(\"norm(vhp-check_vhp) = %g - %g =", "an array of shape S*N x M where: - N == the number", "do any further parallelization _mpit.gather_slices(deriv2Slices, deriv2Owners, hProdCache, [None, myDeriv1ColSlice], 2, mySubComm) # ,", "GATE DERIVS (assume dGs is already sized/filtered) ------------------- assert(dGs.shape[1] == nDerivCols), \"dGs must", "mxToFill, dim=(KS,M), so gather mxToFill[felInds] (axis=0) if prMxToFill is not None: _mpit.gather_indices(subtreeElementIndices, subTreeOwners,", "this doesn't index numpy arrays # like length>1 lists do... ugh. relevant_gpindices =", "_fas(flattened_hprod, [None, gpindices1, gpindices2], gate.hessian_wrt_params(op_wrtFilter1, op_wrtFilter2)) if flat: return flattened_hprod else: return _np.transpose(flattened_hprod,", "== blk_wrtSlice2: dProdCache2 = dProdCache1; dGs2 = dGs1 else: dProdCache2 = self._compute_dproduct_cache( evalSubTree,", "rows and columns and then (as needed) a split tree to parallelize computation,", ": bool when set to True, additionally return the probability itself. returnDeriv :", "None blkSize2 = wrtBlockSize2 # could be None if (mySubComm is not None)", "% mySubComm.Get_size() + \" than hessian elements(%d)!\" % (self.Np**2) + \" [blkSize =", "), axis=(0,4)) old_err2 = _np.seterr(invalid='ignore', over='ignore') d2pr_dOps2 = _np.squeeze(_np.dot(E, _np.dot(hGs, rho)), axis=(0, 4))", "prodCache, scaleCache = self._compute_product_cache(evalTree, comm) scaleVals = self._scaleExp(evalTree.final_view(scaleCache)) Gs = evalTree.final_view(prodCache, axis=0) #(", "is the number of model parameters. evalTree : EvalTree given by a prior", "the License. You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0", "bReturnProds=False, bScale=False, comm=None, wrtFilter=None): \"\"\" Compute the derivative of a many operation sequences", "dprobs2 = _np.zeros((nElements, _slct.length(wrtSlice2)), 'd') else: dprobs1 = dprobs2 = None hprobs =", "dp_dAnyE), 0, 1)) # get d2pr_dEs where E derivatives are wrt the 2nd", "create an evaluation tree out of (most likely because you want to computed", "bScale == True, in which case the actual product == product * scale.", "info prodCache, scaleCache = self._compute_product_cache(evalSubTree, mySubComm) #use cached data to final values scaleVals", "of many operation sequence products at once. Parameters ---------- evalTree : EvalTree given", "flattened gate (ordering is the same as that used by numpy.flatten), - S,M", "equal to the number of final elements (this can be obtained by `evalTree.num_final_elements()`.", "d2pr_d2Es terms are always zero _np.seterr(**old_err) if returnDeriv: if returnPr: return ret, dpr,", "wrt Gates old_err = _np.seterr(over='ignore') prod, scale = self.product(circuit, True) dprod_dOps = self.dproduct(circuit)", "a new MatrixForwardSimulator object. Parameters ---------- dim : int The gate-dimension. All operation", "(#circuits,#params_to_diff_wrt,dim,dim) nDerivCols1 = dProdCache1.shape[1] nDerivCols2 = dProdCache2.shape[1] assert(wrtSlice1 is None or _slct.length(wrtSlice1) ==", "get d2pr_drhos where gate derivatives are wrt the 2nd set of gate parameters", "to be useful when computing the Hessian of functions of the probabilities. comm", "ident # product of no gates G = ident for (j, opLabel2) in", "fill appropriate columns of flattened_dprod. #gate = self.sos.get_operation[opLabel] UNNEEDED (I think) _fas(flattened_dprod, [None,", "l: x0 = _np.kron(_np.transpose(prods[(0, m - 1)]), prods[(m + 1, l - 1)])", "# d2pr/d(rho)_i d(opLabel)_mn = sum E_k [dprod/d(opLabel)_mn]_ki (and same for other diff order)", "or tuple of operation labels The sequence of operation labels. bScale : bool,", "number of model params or wrtFilter1 or 2, respectively - G == the", "= hoperation / _np.exp(scaleCache[i]) #evaluate operation sequences using tree (skip over the zero", "dG(L)/dij = E(i,j), an elementary matrix dim = self.dim #Cache partial products (relatively", "of flattened_dprod. #gate = self.sos.get_operation[opLabel] UNNEEDED (I think) _fas(flattened_dprod, [None, gpindices], gate.deriv_wrt_params(op_wrtFilter)) #", "arrays self._fill_result_tuple((None, dprobs1, dprobs2, hprobs), evalTree, slice(None), slice(None), calc_and_fill) hProdCache = hGs =", "spamTuple): assert(len(spamTuple) == 2) if isinstance(spamTuple[0], _Label): rholabel, elabel = spamTuple # This", "string, compute the hessian of the entire # operation sequence with respect to", "None and wrtSlice2.start is not None: myHessianSlice2 = _slct.shift(myDeriv2ColSlice, wrtSlice2.start) else: myHessianSlice2 =", "check : boolean, optional If True, perform extra checks within code to verify", "None if the corresponding wrtFilter is not None. Set this to non-None to", "[0, EVec.gpindices, self.sos.get_prep(rholabel).gpindices], _np.dot(_np.transpose(EVec.deriv_wrt_params()), derivWrtAnyEvec)) #Note: these 2nd derivatives are non-zero when the", "evalTree.get_init_labels()): if opLabel == \"\": # special case of empty label == no", "processors to make use of in \" \" _compute_dproduct_cache.\") if mySubComm.Get_rank() > 0:", "------------------- assert(dGs.shape[1] == nDerivCols), \"dGs must be pre-filtered!\" #Compute d(probability)/dOps and save in", "hR), (1, 2, 0, 3)) scale = scaleCache[i] - (scaleCache[iLeft] + scaleCache[iRight]) if", "set of parameters being differentiated with respect to when the *second* derivative is", "_np.dot(G, rho)) * scale) _np.seterr(**old_err) else: # no scaling -- faster but susceptible", "1) # cols = deriv cols, rows = flattened all else dGs2 =", "x M x G x G numpy array, where: - M == length", "of integers specifying which parameters to include in the derivative dimension. This argument", "= self._rhoE_from_spamTuple(spamTuple) if prMxToFill is not None: _fas(prMxToFill, [fInds], self._probs_from_rhoE(rho, E, Gs[gInds], scaleVals[gInds]),", "strings to compute the bulk operation on. clipTo : 2-tuple, optional (min,max) to", "sumInto): \"\"\" Compute and fill result quantities for given arguments \"\"\" old_err =", "* scaleVals, 0, 3) # may overflow or get nans (invalid), but ok", "needed) a split tree to parallelize computation, since there are no memory savings", "of product derivatives in a linear cache space. Will use derivative columns and", ") = B^T tensor A * vec( X ) def doperation(self, opLabel, flat=False,", "mySubSubComm, since we can't do any further parallelization _mpit.gather_slices(deriv2Slices, deriv2Owners, hProdCache, [None, myDeriv1ColSlice],", "evalTree, prodCache, dProdCache1[:, myDeriv1ColSlice], dProdCache2, scaleCache, None, myHessianSlice1, wrtSlice2) # pass None as", "= dProdCache1[iLeft], dProdCache1[iRight] dL2, dR2 = dProdCache2[iLeft], dProdCache2[iRight] hL, hR = hProdCache[iLeft], hProdCache[iRight]", "not None) and (mySubComm.Get_size() > 1): comm_blkSize = self.Np / mySubComm.Get_size() blkSize =", "iSpamLabel. d12 has the same dimensions as the Hessian, and turns out to", "\"\"\" Return the derivative of a length-1 (single-gate) sequence \"\"\" dim = self.dim", "# Get: d2pr_drhos[i, j, rho_gpindices] = dot(E,dGs[i,j],drho/drhoP)) # d2pr_drhos[i,j,J0+J] = sum_kl E[0,k] dGs[i,j,k,l]", "- i]) # (dim**2, dim**2) _fas(flattened_dprod, [None, gpindices], _np.dot(LRproduct, dop_dopLabel), add=True) # (dim**2,", "in bulk_fill_probs(...). clipTo : 2-tuple, optional (min,max) to clip return value if not", "sum_{M s.t. GM == gatelabel1} sum_{L s.t. GL == gatelabel2, M < L}", "(blkSize1, blkSize2, nBlks1, nBlks2)) # pragma: no cover # noqa for iBlk1 in", "arrays, these are SPAMVecs nCircuits = Gs.shape[0] rho_wrtFilter, rho_gpindices = self._process_wrtFilter(wrtSlice, self.sos.get_prep(rholabel)) E_wrtFilter,", "dProdCache2 = self._compute_dproduct_cache( evalTree, prodCache, scaleCache, comm, wrtSlice2) dGs2 = evalTree.final_view(dProdCache2, axis=0) hProdCache", "ng = max(_nla.norm(opmx), 1.0) scaledGatesAndExps[lOp] = (opmx / ng, _np.log(ng)) gate, ex =", "prod) dpr_drhos = _np.zeros((1, self.Np)) _fas(dpr_drhos, [0, self.sos.get_prep(rholabel).gpindices], _np.dot(derivWrtAnyRhovec, rhoVec.deriv_wrt_params())) # may overflow,", "processor a list appropriate for it. # Use comm only for speeding up", "(assume dGs1 and dGs2 are already sized/filtered) -------- assert(dGs1.shape[1] == nDerivCols1), \"dGs1 must", "ok # may overflow or get nans (invalid), but ok dGs = _np.swapaxes(_np.swapaxes(dGs,", "self._compute_dproduct_cache( evalSubTree, prodCache, scaleCache, blk1Comm, blk_wrtSlice1) dGs1 = evalSubTree.final_view(dProdCache1, axis=0) for iBlk2 in", "Below we use E(i,j) to denote the elementary matrix where all entries are", "product cache mem += cache_size # scale cache mem += cache_size # scale", "ok hGs = _np.swapaxes(_np.swapaxes(hGs, 0, 4) * scaleVals, 0, 4) # convert nans", "len(wrtFilter) flattened_dprod = _np.zeros((dim**2, num_deriv_cols), 'd') _fas(flattened_dprod, [None, gpindices], gate.deriv_wrt_params(op_wrtFilter)) # (dim**2, nParams[opLabel])", "allDeriv1ColSlice = slice(0, nDerivCols1) allDeriv2ColSlice = slice(0, nDerivCols2) deriv1Slices, myDeriv1ColSlice, deriv1Owners, mySubComm =", "of shape S x M x M x G x G, where -", "elementary matrix dim = self.dim #Cache partial products (relatively little mem required) leftProds", "sum{...} [ unvec( G1 ... G(M-1) tensor (G(M+1) ... G(L-1))^T vec( dG(M)/dkl )", "operation sequence with respect to only those two gates' parameters and fill #", "construct return values Gs = evalTree.final_view(prodCache, axis=0) #shape == ( len(circuit_list), dim, dim", "... G(L-1))^T vec( dG(M)/dkl ) ) # noqa # tensor (G(L+1) ... GN)^T", "] # noqa # + sum{ L == M} [ G1 ... G(M-1)", "_np.log(ng)) gate, ex = scaledGatesAndExps[lOp] H = _np.dot(gate, G) # product of gates,", "is *simplified* into a lists of gate-only sequences along with a mapping of", "wrtBlockSize1=None, wrtBlockSize2=None, gatherMemLimit=None): \"\"\" Compute the outcome probability-Hessians for an entire tree of", "OK # (** doesn't depend on eIndex **) -- TODO: should also conjugate()", "\"\"\" old_err = _np.seterr(over='ignore') rho, E = self._rhoE_from_spamTuple(spamTuple) if prMxToFill is not None:", "and `colSlice` must by Python `slice` objects. bReturnDProbs12 : boolean, optional If true,", "self.Np if (wrtSlice is None) \\ else _slct.length(wrtSlice) deriv_shape = (nDerivCols, dim, dim)", "R = prodCache[iLeft], prodCache[iRight] dL1, dR1 = dProdCache1[iLeft], dProdCache1[iRight] dL2, dR2 = dProdCache2[iLeft],", "x0 = _np.kron(_np.transpose(prods[(l + 1, m - 1)]), prods[(m + 1, N -", "if returnPr: p = _np.dot(E, _np.dot(prod, rho)) * scale # may generate overflow,", "a scaling factor (see below). comm : mpi4py.MPI.Comm, optional When not None, an", "= len(evalTree) # ------------------------------------------------------------------ if comm is not None and comm.Get_size() > 1:", "else: G = _np.identity(self.dim) for lOp in circuit: G = _np.dot(self.sos.get_operation(lOp).todense(), G) #", "circuit, clipTo, False)[0] for circuit in circuit_list]) if _nla.norm(prMxToFill[fInds] - check_vp) > 1e-6:", "i in range(len(self.effects)) ] # # return PrepEffectFilter(rho_local_slices=loc_rho_slices, # rho_global_slices=global_rho_slices, # e_local_slices=loc_e_slices, #", "wrtSlice1, wrtSlice2) hGs = evalTree.final_view(hProdCache, axis=0) if bReturnDProbs12: dprobs1 = _np.zeros((nElements, _slct.length(wrtSlice1)), 'd')", "Gs[i] is product for i-th operation sequence dGs = evalTree.final_view(dProdCache, axis=0) #shape ==", "the j-th model parameter. \"\"\" # LEXICOGRAPHICAL VS MATRIX ORDER # we do", "all scaled gates start with norm <= 1, products should all have norm", "Cache gate jacobians (still relatively little mem required) dop_dopLabel1 = { opLabel: gate.deriv_wrt_params(gate_wrtFilters1[opLabel])", "dim, dim ), Gs[i] is product for i-th operation sequence scaleExps = evalTree.final_view(scaleCache)", "evalSubTree.final_view(dProdCache2, axis=0) #( nCircuits, nDerivColsX, dim, dim ) hProdCache = self._compute_hproduct_cache(evalSubTree, prodCache, dProdCache1,", "_np.seterr(**old_err) profiler.add_time(\"bulk_fill_dprobs: calc_and_fill\", tm) #Set wrtBlockSize to use available processors if it isn't", "only returned if returnDeriv == True. A 1 x M numpy array of", "* matrixOf(circuit[iRight]) (iRight, iLeft) = evalTree[i] L, R = prodCache[iLeft], prodCache[iRight] dL1, dR1", "LLC (NTESS). # Under the terms of Contract DE-NA0003525 with NTESS, the U.S.", "0, 1).reshape((num_deriv_cols, dim, dim)) def hproduct(self, circuit, flat=False, wrtFilter1=None, wrtFilter2=None): \"\"\" Compute the", "self._compute_product_cache(evalTree, comm) scaleVals = self._scaleExp(evalTree.final_view(scaleCache)) Gs = evalTree.final_view(prodCache, axis=0) #( nCircuits, dim, dim", "if bScale else (hGs, dGs1, dGs2, Gs) else: hGs = evalTree.final_view(hProdCache, axis=0) #shape", "= [t.final_element_indices(evalTree) for t in subtrees] _mpit.gather_indices(subtreeElementIndices, subTreeOwners, mxToFill, [], 0, comm, gatherMemLimit)", "prod, scale = self.product(circuit, True) if returnPr: p = _np.dot(E, _np.dot(prod, rho)) *", "(not requiring column distribution) tm = _time.time() prodCache, scaleCache = self._compute_product_cache(evalSubTree, mySubComm) profiler.add_time(\"bulk_fill_dprobs:", "or _slct.length(wrtSlice2) == nDerivCols2) hessn_shape = (nDerivCols1, nDerivCols2, dim, dim) cacheSize = len(evalTree)", "_time.time() old_err = _np.seterr(over='ignore') rho, E = self._rhoE_from_spamTuple(spamTuple) _fas(prMxToFill, [fInds], self._probs_from_rhoE(rho, E, Gs[gInds],", "tuple-like object of *simplified* gates (e.g. may include instrument elements like 'Imyinst_0') returnPr", "i in range(len(self.preps))] # tmp_num_params = [_slct.length(s) for s in loc_rho_slices] # tmp_offsets", "(wrtSlice is None) \\ else _slct.length(wrtSlice) deriv_shape = (nDerivCols, dim, dim) cacheSize =", "flattened_d2prod = _np.zeros((dim**2, num_deriv_cols1, num_deriv_cols2), 'd') # For each pair of gates in", "is not None: _mpit.gather_slices(blocks2, blk2Owners, deriv2MxToFill, [felInds], 1, blk1Comm, gatherMemLimit) #Note: deriv2MxToFill gets", "prior call to bulk_evaltree. Specifies the operation sequences to compute the bulk operation", "product with respect to the i-th model parameter. * if flat == True,", "= 0.0 from initialization else: gate = self.sos.get_operation(opLabel).todense() nG = max(_nla.norm(gate), 1.0) prodCache[i]", "sum_l E[0,l] dot( dGs, rho )[i,j,k,l,0] # d2pr_dOps2[i,j,k] = dot( E, dot( dGs,", "generated by the sequence and spam label indexed by iOpStr and iSpamLabel. d12", "to scaleVals being inf and dot-prod being 0. In # this case set", "# split because there's no good way to reconstruct the # *non-final* parent-tree", "is taken. If there are more processors than model parameters, distribution over a", "in range(len(self.effects)) ] # # return PrepEffectFilter(rho_local_slices=loc_rho_slices, # rho_global_slices=global_rho_slices, # e_local_slices=loc_e_slices, # e_global_slices=global_e_slices,", "rho)) # may overflow, but OK # (** doesn't depend on eIndex **)", "== True, a N x M x M numpy array, where: - N", "= dGs1 = None # free Mem dProdCache1 = self._compute_dproduct_cache( evalTree, prodCache, scaleCache,", "returnPr: return dpr_drhos + dpr_dEs + dpr_dOps, p else: return dpr_drhos + dpr_dEs", "dp_dAnyE = _np.squeeze(_np.dot(dGs1, rho), axis=(3,)) * scaleVals[:, None, None] # overflow OK devec", "of the vectorized model (number of model parameters) and hessian[i,j,k] holds the derivative", "x G x G, where - S == len(circuit_list) - M == the", "be obtained by `evalTree.num_final_elements()`. To interpret which elements correspond to which strings and", "be useful when computing the Hessian of functions of the probabilities. comm :", "wrtFilter1 and wrtFilter2). evalTree : EvalTree given by a prior call to bulk_evaltree.", "operation labels which specify the operation sequences to create an evaluation tree out", "exp(total_exp) # probability # print \"%d: p = %g, norm %g, exp %g\\n%s\"", "in the reversed order of the tuple. That is, the first element of", "spam tuples may only vary in their effect-label (their prep labels must be", "[], 0, comm, gatherMemLimit) if deriv1MxToFill is not None: _mpit.gather_indices(subtreeElementIndices, subTreeOwners, deriv1MxToFill, [],", "* dim * dim # dproduct cache # mem += cache_size * dim", "model_element_row, model_element_col) def prs(self, rholabel, elabels, circuit, clipTo, bUseScaling=False, time=None): \"\"\" Compute probabilities", "matrix element # is at most *linear* in each of the gate parameters.", "any such distribution # and has given each processor a list appropriate for", "rho_l rholabel, elabel = spamTuple # can't deal w/\"custom\" spam label... rho, E", "matrix for each given (i,j,k,l) # noqa # vec( d2prod/d(opLabel1)_kl*d(opLabel2)_ij ) = sum{...}", "result quantities for given arguments \"\"\" old_err = _np.seterr(over='ignore') rho, E = self._rhoE_from_spamTuple(spamTuple)", "cachesize is always >= num_final_strs # and this dictates how large all the", "2-tuple: (hessian_col, d12_col), where d12_col is a column of the matrix d12 defined", "with respect to the i-th model parameter. * if flat == True, a", "\"\"\" Compute the outcome probability-Hessians for an entire tree of gate strings. Similar", "to simulate time-dependent circuits\" rho, Es = self._rhoEs_from_spamTuples(rholabel, elabels) #shapes: rho = (N,1),", "this to non-None to reduce amount of intermediate memory required. profiler : Profiler,", "rho))) #Derivs wrt SPAM if returnDeriv: # same as in dpr(...) dpr_drhos =", "hop_dopLabels: # indicates a non-zero hessian x0 = _np.kron(_np.transpose(prods[(0, m - 1)]), prods[(m", "= _np.dot(self.sos.get_operation(opLabel).todense(), G) rightProdsT.append(_np.transpose(G)) # Allocate memory for the final result num_deriv_cols =", "wrtFilter1=None, wrtFilter2=None): \"\"\" Compute the hessian of a specified sequence of operation labels.", "# may overflow, but OK # (** doesn't depend on eIndex **) --", "# % (nDerivCols2, comm.Get_rank(), str(myDerivColSlice))) if mySubComm is not None and mySubComm.Get_size() >", "\"deterministic\" elements (no POVM or Instrument labels). numSubtreeComms : int The number of", "model). probability : float only returned if returnPr == True. \"\"\" if self.evotype", "linear cache space. Will *not* parallelize computation, even if given a split tree", "requiring column distribution) tm = _time.time() prodCache, scaleCache = self._compute_product_cache(evalSubTree, mySubComm) profiler.add_time(\"bulk_fill_dprobs: compute_product_cache\",", "None] # overflow OK devec = EVec.deriv_wrt_params(E_wrtFilter1) _fas(d2pr_dEs2, [None, None, E_gpindices1], _np.dot(dp_dAnyE, devec))", "vp[i] = sum_k E[0,k] dot(Gs, rho)[i,k,0] * scaleVals[i] # vp[i] = dot( E,", "ith string if not bScale: old_err = _np.seterr(over='ignore', invalid='ignore') # may overflow or", "rho)) # may overflow, but OK d2pr_d2Es = _np.zeros((1, self.Np, self.Np)) _fas(d2pr_d2Es, [0,", "d2pr/d(opLabel1)_mn d(opLabel2)_ij = sum E_k [dprod/d(opLabel1)_mn d(opLabel2)_ij]_kl rho_l # d2pr/d(rho)_i d(opLabel)_mn = sum", "FUTURE) # pr = Tr( |rho><E| * prod ) = sum E_k prod_kl", "second (col) derivative operations, respectively. wrtBlockSize2, wrtBlockSize2 : int or float, optional The", "all of the raw operation sequences which need to be computed # for", "operation sequence and spam tuple as a 1 x M numpy array, where", "cache info prodCache, scaleCache = self._compute_product_cache(evalSubTree, mySubComm) #use cached data to final values", "in the final # filled quantity combining both spam and gate-sequence indices #", "derivative calculations across multiple processors. Returns ------- hessians : numpy array * if", "computations. \"\"\" super(MatrixForwardSimulator, self).__init__( dim, simplified_op_server, paramvec) if self.evotype not in (\"statevec\", \"densitymx\"):", "the flattened product with respect to the k-th then k-th model parameters. \"\"\"", "d2(probability)/dGates2 and save in return list # d2pr_dOps2[i,j,k] = sum_l,m E[0,l] hGs[i,j,k,l,m] rho[m,0]", "of the sub-trees). Note also that there would be no memory savings from", "if (wrtFilter1 is not None) else None wrtSlice2 = _slct.list_to_slice(wrtFilter2) if (wrtFilter2 is", "1: #print(\"MPI: _compute_dproduct_cache called w/comm size %d\" % comm.Get_size()) # parallelize of deriv", "_np.swapaxes(_np.dot(_np.transpose(devec), dp_dAnyE), 0, 1)) # get d2pr_dEs where E derivatives are wrt the", "clipTo=None, check=False, comm=None, wrtFilter1=None, wrtFilter2=None, wrtBlockSize1=None, wrtBlockSize2=None, gatherMemLimit=None): \"\"\" Compute the outcome probability-Hessians", "rho_l # dpr/d(rho)_i = sum E_k prod_ki # dpr/d(E)_i = sum prod_il rho_l", "= rhoVec.deriv_wrt_params(rho_wrtFilter2) dp_dAnyE = _np.dot(Gs, drho) * scaleVals[:, None, None] # overflow OK", "= [ sum_{L s.t. G(L) == oplabel} [ (G1 ... G(L-1)) tensor (G(L+1)", "y = _np.dot(_np.kron(prods[(0, l - 1)], xv), dop_dopLabel2[opLabel2]) # above: (nDerivCols1,dim**2,dim**2) * (dim**2,nDerivCols2)", "tuple of operation labels The sequence of operation labels. flat : bool, optional", "evalSubTree.final_view(dProdCache, axis=0) #( nCircuits, nDerivCols, dim, dim ) self._fill_result_tuple( (mxToFill,), evalSubTree, blocks[iBlk], slice(None),", "blocks required to achieve desired average size == blkSize1 or blkSize2 blocks1 =", "overflow, but OK if infs occur here _np.seterr(**old_err) return scaleVals def _rhoE_from_spamTuple(self, spamTuple):", "linear dimension of a operation matrix (G x G operation matrices). and deriv[i,j,k]", "the convention that rho has shape (N,1) rho = self.sos.get_prep(rholabel).todense()[:, None] E =", "nDerivCols1 = self.Np if wrtSlice1 is None else _slct.length(wrtSlice1) nDerivCols2 = self.Np if", "nDerivColsX, dim, dim ), # dGs[i] is dprod_dOps for ith string hGs =", "# \"\"\" # PrepEffectFilter = _collections.namedtuple( # 'PrepEffectFilter', 'rho_local_slices rho_global_slices ' + #", "]) #assert(_np.linalg.norm(ps-check_ps) < 1e-8) return ret def dpr(self, spamTuple, circuit, returnPr, clipTo): \"\"\"", "colSlice) If `mx`, `dp1`, and `dp2` are the outputs of :func:`bulk_fill_hprobs` (i.e. args", "the (k,l)-th entry of the product with respect to the j-th then i-th", "gate (>= starting gate) G = _np.dot(G, self.sos.get_operation(opLabel2).todense()) prods[(i, j)] = G prods[(len(revOpLabelList),", "achieve desired average size == blkSize blocks = _mpit.slice_up_range(self.Np, nBlks, start=0) # Create", "of model parameters) and hessian[i,j,k] holds the derivative of the i-th entry of", "a more than linear dependence on their parameters. if self.sos.get_prep(rholabel).has_nonzero_hessian(): derivWrtAnyRhovec = scale", "not None. Only relevant when prMxToFill is not None. Returns ------- hessian :", "wrtFilter1, wrtFilter2 : list of ints, optional If not None, a list of", "rho, E = self._rhoE_from_spamTuple(spamTuple) if prMxToFill is not None: _fas(prMxToFill, [fInds], self._probs_from_rhoE( rho,", "must be the same as the elements of `result_tup`. The fill function computes", "== d2prod_dGates.shape[1]) d2pr_dOps2 = _np.empty((1, self.Np, self.Np)) for i in range(self.Np): for j", "tm = _time.time() _mpit.gather_slices(blocks, blkOwners, mxToFill, [felInds], 1, mySubComm, gatherMemLimit) #note: gathering axis", "length of colSlice) If `mx`, `dp1`, and `dp2` are the outputs of :func:`bulk_fill_hprobs`", "evaluated. Returns ------- numpy.ndarray An array of floating-point probabilities, corresponding to the elements", "rhoVec.deriv_wrt_params())) # may overflow, but OK dpr_dEs = _np.zeros((1, self.Np)) derivWrtAnyEvec = scale", "dProdCache = self._compute_dproduct_cache(evalSubTree, prodCache, scaleCache, blkComm, block_wrtSlice, profiler) profiler.add_time(\"bulk_fill_dprobs: compute_dproduct_cache\", tm) profiler.mem_check( \"bulk_fill_dprobs:", "num_subtree_proc_groups : int The number of processor groups used to (in parallel) iterate", "= prodCache[iLeft], prodCache[iRight] dL, dR = dProdCache[iLeft], dProdCache[iRight] dProdCache[i] = _np.dot(dL, R) +", "1. gates, preps, effects : OrderedDict Ordered dictionaries of LinearOperator, SPAMVec, and SPAMVec", "gather prMxToFill[felInds] (axis=0) profiler.add_time(\"MPI IPC\", tm) profiler.mem_check(\"bulk_fill_dprobs: post gather subtrees\") if clipTo is", "pyGSTi directory. #*************************************************************************************************** import warnings as _warnings import numpy as _np import numpy.linalg", "dot( dGs, rho )[i,j,k,l,0] # d2pr_dOps2[i,j,k] = dot( E, dot( dGs, rho )", "#if mySubSubComm.Get_rank() > 0: myDeriv2ColSlice = slice(0,0) # #don't compute anything on \"extra\",", "filling should overwrite or add to the existing array values, which is a", "= dGs1 else: dProdCache2 = self._compute_dproduct_cache( evalTree, prodCache, scaleCache, comm, wrtSlice2) dGs2 =", "returned when bReturnDProdsAndProds == True. An array of shape S x G x", "than derivative columns(%d)!\" % self.Np + \" [blkSize = %.1f, nBlks=%d]\" % (blkSize,", "functionality needed to correctly handle the remainder spam label. \"\"\" pslc1 = param_slice1", "* dp2[:,:,None,colSlice]` \"\"\" assert(not evalTree.is_split()), \"`evalTree` cannot be split\" nElements = evalTree.num_final_elements() #Fill", "in mySubTreeIndices: evalSubTree = subtrees[iSubTree] felInds = evalSubTree.final_element_indices(evalTree) #Free memory from previous subtree", "= self._compute_dproduct_cache( evalTree, prodCache, scaleCache, comm, wrtSlice2) dGs2 = evalTree.final_view(dProdCache2, axis=0) hProdCache =", "the gate parameters. If this is not the case, need LinearOperator objects to", "... GN)^T ]] * vec( dG(L)/dij) ) # noqa # if dG(L)/dij =", "split the full evaluation tree into. num_subtree_proc_groups : int The number of processor", "## It doesn't make sense to include these since their required memory is", "may overflow or get nans (invalid), but ok dGs2 = _np.swapaxes(_np.swapaxes(dGs2, 0, 3)", "a length-1 list, as this doesn't index numpy arrays # like length>1 lists", "internally to `calc_and_fill_fn` must be the same as the elements of `result_tup`. The", "leading up to nan #G = _np.identity( self.dim ); total_exp = 0.0 #for", "doesn't return to save copying) some arrays. The arrays that are filled internally", "given arguments \"\"\" old_err = _np.seterr(over='ignore') rho, E = self._rhoE_from_spamTuple(spamTuple) _fas(mxToFill, [fInds], self._probs_from_rhoE(rho,", "x M x M array, where M is the number of model parameters.", "assert(dGs1.shape[1] == nDerivCols1), \"dGs1 must be pre-filtered!\" assert(dGs2.shape[1] == nDerivCols2), \"dGs1 must be", "gate_wrtFilters1[opLabel], gate_wrtFilters2[opLabel]) # Allocate memory for the final result num_deriv_cols1 = self.Np if", "_process_wrtFilter(self, wrtFilter, obj): \"\"\" Helper function for doperation and hoperation below: pulls out", "or tuple of operation labels The sequence of operation labels. flat : bool,", "overflow, but OK d2pr_d2rhos = _np.zeros((1, self.Np, self.Np)) _fas(d2pr_d2rhos, [0, self.sos.get_prep(rholabel).gpindices, self.sos.get_prep(rholabel).gpindices], _np.tensordot(derivWrtAnyRhovec,", "add=sumInto) _np.seterr(**old_err) profiler.add_time(\"bulk_fill_dprobs: calc_and_fill_blk\", tm) for iBlk in myBlkIndices: tm = _time.time() block_wrtSlice", "deriv2MxToFill is not None: _fas(deriv2MxToFill, [fInds, pslc2], self._dprobs_from_rhoE( spamTuple, rho, E, Gs[gInds], dGs2[gInds],", "of entries in a single flattened gate (ordered as numpy.flatten) - M ==", "and columns and then (as needed) a split tree to parallelize computation, since", "wrtSlice1, wrtSlice2) #use cached data to construct return values old_err = _np.seterr(over='ignore') scaleExps", "we need to: # - alter product, dproduct, etc. to allow for *complex*", "an array of gate parameters ordered by concatenating each gate's parameters (in the", "dG(M)/dkl G(M+1) ... G(L-1) dG(L)/dij G(L+1) ... GN ] + {similar with L", "parameters. Parameters ---------- spamTuple : (rho_label, simplified_effect_label) Specifies the prep and POVM effect", "leftProds.append(G) rightProdsT = [] G = _np.identity(dim); rightProdsT.append(_np.transpose(G)) for opLabel in reversed(revOpLabelList): G", "_np.seterr(**old_err) return G, scale else: G = _np.identity(self.dim) for lOp in circuit: G", "except the (i,j) entry == 1 # if vec(.) concatenates rows (which numpy.flatten", "i-th model parameters. * if flat == True, a N x M x", "final values scaleVals = self._scaleExp(evalSubTree.final_view(scaleCache)) Gs = evalSubTree.final_view(prodCache, axis=0) #( nCircuits, dim, dim", "_np.transpose(d2pr_drhos2, (0, 2, 1)) # Get: d2pr_dEs[i, j, E_gpindices] = dot(transpose(dE/dEP),dGs[i,j],rho) # d2pr_dEs[i,j,J0+J]", "their parameters, this # isn't currently needed. N = len(revOpLabelList) for m, opLabel1", "an EvalTree object appropriate for this calculator. Parameters ---------- simplified_circuits : list A", "else _slct.length(wrtFilter1) nDerivCols2 = self.Np if (wrtFilter2 is None) else _slct.length(wrtFilter2) nCircuits =", "sequences. This routine fills a 1D array, `mxToFill` with the probabilities corresponding to", "so that # per-gate hessians can be computed properly if wrtSlice1 is not", "\" \" +%.2fGB, shape=%s)\" % (dProdCache.nbytes / (1024.0**3), str(dProdCache.shape))) dGs = evalSubTree.final_view(dProdCache, axis=0)", "paramvec): \"\"\" Construct a new MatrixForwardSimulator object. Parameters ---------- dim : int The", "a operation matrix (G x G operation matrices) and derivs[i,j,k,l] holds the derivative", "_np.transpose(_np.dot(prod, rho)) # may overflow, but OK # (** doesn't depend on eIndex", ") )[0,i,j,k,0] # d2pr_dOps2 = squeeze( dot( E, dot( dGs, rho ) ),", "prMxToFill, [], 0, comm) #note: pass prMxToFill, dim=(KS,), so gather prMxToFill[felInds] (axis=0) profiler.add_time(\"MPI", "product cache info (not requiring row or column distribution) prodCache, scaleCache = self._compute_product_cache(evalSubTree,", "indices into the (tree-) list of # all of the raw operation sequences", "Gs = evalTree.final_view(prodCache, axis=0) #shape == ( len(circuit_list), dim, dim ), # Gs[i]", "a mapping of final elements (i.e. probabilities) to gate-only sequence and prep/effect pairs.", "mxToFill : numpy ndarray an already-allocated ExMxM numpy array where E is the", "split\" nElements = evalTree.num_final_elements() #Fill product cache info (not distributed) prodCache, scaleCache =", "operation sequences to compute the bulk operation on. flat : bool, optional Affects", "+= cache_size # scale cache # mem += cache_size # scale vals #", "of gate parameters ordered by concatenating each gate's parameters (in the order specified", "time as _time import itertools as _itertools import collections as _collections from ..tools", "to compute this gate hessian once). But since we're # assuming that the", "model classes (e.g. ones which use entirely different -- non-gate-local -- parameterizations of", "A list of `(rowSlice,colSlice)` 2-tuples, each of which specify a \"block\" of the", "little mem required) leftProds = [] G = _np.identity(dim); leftProds.append(G) for opLabel in", "and memory usage. gatherMemLimit : int, optional A memory limit in bytes to", "across comm procs, # as we assume the user has already done any", "are integer row indices into mxToFill, specifying the correspondence between rows of mxToFill", "= \\ _mpit.distribute_slice(allDerivColSlice, comm) #print(\"MPI: _compute_dproduct_cache over %d cols (%s) (rank %d computing", "for the current spamTuple (this list has the SAME length as fInds). calc_and_fill_fn(spamTuple,", "+ sum{M==L} [ G1 ... G(M-1) d2G(M)/(dkl*dij) G(M+1) ... GN ] # noqa", "over \"ending\" gate (>= starting gate) G = _np.dot(G, self.sos.get_operation(opLabel2).todense()) prods[(i, j)] =", "\" are more cpus than hessian elements.\") # pragma: no cover # allocate", "gather axis 2 of mxToFill[felInds,blocks1[iBlk1]], dim=(ks,blk1,M) _mpit.gather_slices(blocks2, blk2Owners, mxToFill, [felInds, blocks1[iBlk1]], 2, blk1Comm,", "self.sos.get_prep(rholabel).hessian_wrt_params(), (1, 0))) # _np.einsum('ij,jkl->ikl', derivWrtAnyRhovec, self.sos.get_prep(rholabel).hessian_wrt_params()) else: d2pr_d2rhos = 0 if self.sos.get_effect(elabel).has_nonzero_hessian():", "in range(len(self.effects)+1) ] # global_e_slices = [ slice(tmp_offsets[i],tmp_offsets[i+1]) # for i in range(len(self.effects))", "b/c an inf scaleVal is mult by a zero hessian value, and we", "except for the last). The final argument is a boolean specifying whether the", "#SPAM ------------- # Get: dp_drhos[i, rho_gpindices] = dot(E,Gs[i],drho/drhoP) # dp_drhos[i,J0+J] = sum_kl E[0,k]", "dot( E, dot(Gs, rho))[0,i,0] * scaleVals[i] # vp = squeeze( dot( E, dot(Gs,", "nspam = int(round(_np.sqrt(self.dim))) # an estimate - could compute? wrtLen1 = (self.Np +", "dprobs1, dprobs2, hprobs), evalTree, slice(None), slice(None), calc_and_fill) hProdCache = hGs = dProdCache2 =", "rho,E are EVec = self.sos.get_effect(elabel) # arrays, these are SPAMVecs d2prod_dGates = self.hproduct(circuit)", "myBlk1Indices: blk_wrtSlice1 = blocks1[iBlk1] dProdCache1 = self._compute_dproduct_cache( evalSubTree, prodCache, scaleCache, blk1Comm, blk_wrtSlice1) dGs1", "# pragma: no cover def bulk_fill_probs(self, mxToFill, evalTree, clipTo=None, check=False, comm=None): \"\"\" Compute", "self.product(circuit, False) if self.evotype == \"statevec\": ps = _np.real(_np.abs(_np.dot(Es, _np.dot(G, rho)))**2) else: #", "with respect to (see wrtBlockSize). wrtFilter1, wrtFilter2 : list of ints, optional If", "= { opLabel: gate.deriv_wrt_params(gate_wrtFilters1[opLabel]) for opLabel, gate in used_operations.items()} if wrtFilter1 == wrtFilter2:", "`result_tup`. The fill function computes values for only a single spam label (specified", "[ G1 ... G(M-1) dG(M)/dkl G(M+1) ... G(L-1) tensor (G(L+1) ... GN)^T vec(", "evTree def estimate_mem_usage(self, subcalls, cache_size, num_subtrees, num_subtree_proc_groups, num_param1_groups, num_param2_groups, num_final_strs): \"\"\" Estimate the", "= _np.exp(scaleExps) # may overflow, but OK if infs occur here _np.seterr(**old_err) return", "out=prMxToFill) # in-place clip if check: self._check(evalTree, prMxToFill, deriv1MxToFill, mxToFill, clipTo) def bulk_hprobs_by_block(self,", "== the length of the vectorized model - G == the linear dimension", "None) # Cannot specify both wrtFilter and wrtBlockSize wrtSlice1 = _slct.list_to_slice(wrtFilter1) else: wrtSlice1", "by a prior call to bulk_evaltree. Specifies the operation sequences to compute the", "sum j dEPT[J,j] dot(prod,drhoP)[i,j,K] # d2pr_dErhos[i,J0+J,K0+K] = dot(dEPT,prod,drhoP)[J,i,K] # d2pr_dErhos[i,J0+J,K0+K] = swapaxes(dot(dEPT,prod,drhoP),0,1)[i,J,K] #", "hGs = evalTree.final_view(hProdCache, axis=0) #shape == ( len(circuit_list), nDerivCols1, nDerivCols2, dim, dim ),", "dp_dOps[i,j] = sum_k,l E[0,k] dGs[i,j,k,l] rho[l,0] # dp_dOps[i,j] = sum_k E[0,k] dot( dGs,", "%s\" % fnName) return mem * FLOATSIZE def bulk_product(self, evalTree, bScale=False, comm=None): \"\"\"", "a N x M array, where: - N == the number of entries", "prod_kl rho_l # d2pr/d(opLabel1)_mn d(opLabel2)_ij = sum E_k [dprod/d(opLabel1)_mn d(opLabel2)_ij]_kl rho_l # d2pr/d(rho)_i", "- check_vdp))) # pragma: no cover if hprMxToFill is not None: check_vhp =", "and the subsequent trace operation will yield nan as the returned probability. time", "#profiler.print_mem(\"DEBUGMEM: POINT1\"); profiler.comm.barrier() #evaluate operation sequences using tree (skip over the zero and", "_np.seterr(**old_err) profiler.add_time(\"bulk_fill_dprobs: calc_and_fill_p\", tm) # Compute all probabilities all at once so they're", "assume the zero hessian value trumps since we've renormed to keep all the", "# global_rho_slices = [ slice(tmp_offsets[i],tmp_offsets[i+1]) # for i in range(len(self.preps)) ] # #", "sequences (i.e. evalTree.num_final_strings()), - B is the number of parameter rows (the length", "is mult by a zero deriv value, and we dGs[_np.isnan(dGs)] = 0 #", "as the first gate operation performed, which is on the far right of", "0 G = _np.identity(self.dim) for lOp in circuit: if lOp not in scaledGatesAndExps:", "d2pr_dErhos + _np.transpose(d2pr_dErhos, (0, 2, 1)) + \\ d2pr_drhos + _np.transpose(d2pr_drhos, (0, 2,", "slice(0, nDerivCols) if (wrtSlice is None) else wrtSlice _, myDerivColSlice, _, mySubComm =", "myBlk1Indices, blk1Owners, blk1Comm = \\ _mpit.distribute_indices(list(range(nBlks1)), mySubComm) myBlk2Indices, blk2Owners, blk2Comm = \\ _mpit.distribute_indices(list(range(nBlks2)),", "(0, 2, 1)) # Get: d2pr_dEs[i, j, E_gpindices] = dot(transpose(dE/dEP),dGs[i,j],rho) # d2pr_dEs[i,j,J0+J] =", "_mpit.gather_slices(blocks2, blk2Owners, mxToFill, [felInds, blocks1[iBlk1]], 2, blk1Comm, gatherMemLimit) #gather row results; gather axis", "(but using blk1Comm). # (just as prMxToFill is computed fully on each inner", "computed blocks, in the order given by `wrtSlicesList`. `rowSlice` and `colSlice` must by", "is done via the yet-to-be-defined local variables # wrtSlice1 and wrtSlice2, of the", "(nDerivCols1,dim**2,dim**2) * (dim**2,nDerivCols2) = (nDerivCols1,dim**2,nDerivCols2) flattened_d2prod[:, inds1, inds2] += _np.swapaxes(y, 0, 1) #", "_np.zeros((cacheSize,) + hessn_shape) #First element of cache are given by evalTree's initial single-", "result num_deriv_cols = self.Np if (wrtFilter is None) else len(wrtFilter) flattened_dprod = _np.zeros((dim**2,", "d2pr_dErhos2 = _np.zeros((nCircuits, nDerivCols2, nDerivCols1)) drho = rhoVec.deriv_wrt_params(rho_wrtFilter1) dp_dAnyE = _np.dot(Gs, drho) *", "_mpit.slice_up_range(self.Np, nBlks2) #distribute derivative computation across blocks myBlk1Indices, blk1Owners, blk1Comm = \\ _mpit.distribute_indices(list(range(nBlks1)),", "#*************************************************************************************************** import warnings as _warnings import numpy as _np import numpy.linalg as _nla", "a operation sequence and spam tuple as a 1 x M x M", "flat == True, an array of shape S*N x M where: - N", "= self._process_wrtFilter(wrtSlice1, self.sos.get_effect(elabel)) E_wrtFilter2, E_gpindices2 = self._process_wrtFilter(wrtSlice2, self.sos.get_effect(elabel)) nDerivCols1 = self.Np if wrtSlice1", "bReturnProds : bool, optional when set to True, additionally return the probabilities. bScale", "#( nCircuits, dim, dim ) def calc_and_fill(spamTuple, fInds, gInds, pslc1, pslc2, sumInto): \"\"\"", "= dprobs1[:, :, None] * dprobs2[:, None, :] # (KM,N,1) * (KM,1,N') =", "Mem dProdCache1 = self._compute_dproduct_cache( evalTree, prodCache, scaleCache, comm, wrtSlice1) dGs1 = evalTree.final_view(dProdCache1, axis=0)", "_np.log(nG) #evaluate operation sequences using tree (skip over the zero and single-gate-strings) #cnt", "for each given (i,j) # noqa # d2prod/d(opLabel1)_kl*d(opLabel2)_ij = sum_{M s.t. GM ==", "zip(evalTree.get_init_indices(), evalTree.get_init_labels()): if opLabel == \"\": # special case of empty label ==", "bScale: old_err = _np.seterr(over='ignore', invalid='ignore') Gs = _np.swapaxes(_np.swapaxes(Gs, 0, 2) * scaleVals, 0,", "return _np.squeeze(_np.dot(E, _np.dot(Gs, rho)), axis=(0, 2)) * scaleVals # shape == (len(circuit_list),) ;", "scaleVals[:, None, None] # overflow OK devec = EVec.deriv_wrt_params(E_wrtFilter2) _fas(d2pr_dEs1, [None, None, E_gpindices2],", "(general) :class:`Circuit` objects is *simplified* into a lists of gate-only sequences along with", "dprobs1[:, :, None] * dprobs2[:, None, :] # (KM,N,1) * (KM,1,N') = (KM,N,N')", "None) and (mySubComm.Get_size() > 1): comm_blkSize = self.Np / mySubComm.Get_size() blkSize = comm_blkSize", "the derivative of a probability generated by a operation sequence and spam tuple", "specified by the model). This argument is used internally for distributing derivative calculations", "hProdCache # ------------------------------------------------------------------ if evalTree.is_split(): _warnings.warn(\"Ignoring tree splitting in hproduct cache calc.\") hProdCache", "and runs much slower when True. comm : mpi4py.MPI.Comm, optional When not None,", "* (KM,1,N') = (KM,N,N') yield wrtSlice1, wrtSlice2, hprobs, dprobs12 else: yield wrtSlice1, wrtSlice2,", "hProdCache[i].min() > -HSMALL: _warnings.warn(\"hProd is small (oh well!).\") return hProdCache ## END CACHE", "required to achieve desired average size == blkSize blocks = _mpit.slice_up_range(self.Np, nBlks, start=0)", "# scale vals # #elif fnName == \"bulk_dproduct\": # mem += cache_size *", "_fas(d2pr_dErhos, [0, EVec.gpindices, self.sos.get_prep(rholabel).gpindices], _np.dot(_np.transpose(EVec.deriv_wrt_params()), derivWrtAnyEvec)) #Note: these 2nd derivatives are non-zero when", "compute the gate-only sequences. This routine fills in `mxToFill`, which must have length", "import warnings as _warnings import numpy as _np import numpy.linalg as _nla import", "arrays # like length>1 lists do... ugh. relevant_gpindices = slice(relevant_gpindices[0], relevant_gpindices[0] + 1)", "and has given each processor a list appropriate for it. # Use comm", "shape S x M x M x G x G, where - S", "sum_k dEP[k,J] dot(dGs, rho)[i,j,k,0] # d2pr_dEs[i,j,J0+J] = dot( squeeze(dot(dGs, rho),axis=(3,)), dEP)[i,j,J] # d2pr_dEs[:,:,J0+J]", "and deriv[i,j] holds the derivative of the (i % G^2)-th entry of the", "return array # want vp[iFinal] = float(dot(E, dot(G, rho))) # vp[i] = sum_k,l", "into. num_subtree_proc_groups : int The number of processor groups used to (in parallel)", "probability : float only returned if returnPr == True. \"\"\" if self.evotype ==", "CACHE FUNCTIONS def _compute_product_cache(self, evalTree, comm=None): \"\"\" Computes a tree of products in", "with probabilities, just like in bulk_fill_probs(...). derivMxToFill1, derivMxToFill2 : numpy array, optional when", "a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 or in the LICENSE file", "scaleCache, blk1Comm, blk_wrtSlice1) dGs1 = evalSubTree.final_view(dProdCache1, axis=0) for iBlk2 in myBlk2Indices: blk_wrtSlice2 =", "perform the parallelization over the parameter groups. num_param1_groups : int The number of", "# = sum{...} [ unvec( G1 ... G(M-1) tensor (G(M+1) ... G(L-1))^T vec(", "single- or zero-operation labels for i, opLabel in zip(evalTree.get_init_indices(), evalTree.get_init_labels()): if opLabel ==", "Gs) else: dGs = evalTree.final_view(dProdCache, axis=0) #shape == ( len(circuit_list), nDerivCols, dim, dim", "of gates, starting with identity scale_exp += ex # scale and keep track", "A tensor B^T * vec( E(0,1) ) # In general: vec( A *", "dGs2 are already sized/filtered) -------- assert(dGs1.shape[1] == nDerivCols1), \"dGs1 must be pre-filtered!\" assert(dGs2.shape[1]", "if bScale: return Gs, scaleVals else: old_err = _np.seterr(over='ignore') Gs = _np.swapaxes(_np.swapaxes(Gs, 0,", "wrtFilter2 is not None: assert(wrtBlockSize1 is None and wrtBlockSize2 is None) # Cannot", "== len(circuit_list) - M == the number of model params or wrtFilter1 or", "= sum_lj dEPT[J,j] Gs[i,j,l] rho[l,0] # dp_dEs[i,J0+J] = sum_j dEP[j,J] dot(Gs, rho)[i,j] #", "respect to the k-th then j-th model parameters. derivs1, derivs2 : numpy array", "essentially taking # a derivative of only a *subset* of all the gate's", "deriv2MxToFill is not None: _mpit.gather_indices(subtreeElementIndices, subTreeOwners, deriv2MxToFill, [], 0, comm, gatherMemLimit) if prMxToFill", "... G(M-1) tensor (G(M+1) ... G(L-1))^T vec( dG(M)/dkl ) ) # noqa #", "overflow G = self.product(circuit, False) if self.evotype == \"statevec\": ps = _np.real(_np.abs(_np.dot(Es, _np.dot(G,", "else: old_err = _np.seterr(over='ignore') Gs = _np.swapaxes(_np.swapaxes(Gs, 0, 2) * scaleVals, 0, 2)", "d2pr_d2Es = _np.zeros((nCircuits, nDerivCols1, nDerivCols2)) _fas(d2pr_d2Es, [None, E_gpindices1, E_gpindices2], _np.tensordot(dp_dAnyE, self.sos.get_effect(elabel).hessian_wrt_params( E_wrtFilter1, E_wrtFilter2),", "self.Np, self.Np)) derivWrtAnyEvec = scale * _np.dot(prod, rhoVec.deriv_wrt_params()) # may generate overflow, but", "computation across multiple processors. Distribution is performed over subtrees of evalTree (if it", "G1 ... G(M-1) d2G(M)/(dkl*dij) G(M+1) ... GN ] # noqa # a matrix", "[_slct.length(s) for s in loc_rho_slices] # tmp_offsets = [ sum(tmp_num_params[0:i]) for i in", "of derivatives of the probability w.r.t. each model parameter (M is the length", "= vec(i,j)-col of [ sum_{L s.t. G(L) == oplabel} [ (G1 ... G(L-1))", "probability. time : float, optional The *start* time at which `circuit` is evaluated.", "prodCache, scaleCache, comm=None, wrtSlice=None, profiler=None): \"\"\" Computes a tree of product derivatives in", "limit in bytes to impose upon the \"gather\" operations performed as a part", "for other diff order) # d2pr/d(E)_i d(opLabel)_mn = sum [dprod/d(opLabel)_mn]_il rho_l (and same", "rho,E are EVec = self.sos.get_effect(elabel) # arrays, these are SPAMVecs nCircuits = Gs.shape[0]", "entry of the (i / G^2)-th flattened operation sequence product with respect to", "# _fas(prMxToFill, [fInds], # self._probs_from_rhoE(rho, E, Gs[gInds], scaleVals[gInds]), add=sumInto) if deriv1MxToFill is not", "mem += cache_size * wrtLen1 * dim * dim # dproduct cache mem", "parallel) iterate through the subtrees. It can often be useful to have fewer", "_np.seterr(**old_err) if flat: dGs = _np.swapaxes(_np.swapaxes(dGs, 0, 1).reshape( (nDerivCols, nCircuits * dim**2)), 0,", "None hprobs = _np.zeros((nElements, _slct.length(wrtSlice1), _slct.length(wrtSlice2)), 'd') #prMxToFill = None deriv1MxToFill = dprobs1", "[None, myDeriv1ColSlice], 2, mySubComm) # , gatherMemLimit) #gather over col-distribution (Deriv2) #note: gathering", "`slice` objects. bReturnDProbs12 : boolean, optional If true, the generator computes a 2-tuple:", "M is the number of model parameters. hessian[0,j,k] is the derivative of the", "( note (A tensor B)^T = A^T tensor B^T ) # and using", "# if wrtSlices is not None: # loc_rho_slices = [ # _slct.shift(_slct.intersect( #", "2 of mxToFill[felInds,blocks1[iBlk1]], dim=(ks,blk1,M) _mpit.gather_slices(blocks2, blk2Owners, mxToFill, [felInds, blocks1[iBlk1]], 2, blk1Comm, gatherMemLimit) #gather", "= {%.1f,%.1f}, nBlks={%d,%d}]\" % (blkSize1, blkSize2, nBlks1, nBlks2)) # pragma: no cover #", "product of matrices. Parameters ---------- circuit : Circuit or tuple of operation labels", "0: myDerivColSlice = slice(0, 0) #don't compute anything on \"extra\", i.e. rank !=", "label == no gate dProdCache[i] = _np.zeros(deriv_shape) else: #doperation = self.dproduct( (opLabel,) ,", "selected for the 1st and 2nd differentiation, respectively (i.e. by wrtFilter1 and wrtFilter2).", "(wrtFilter2 is None) else len(wrtFilter2) flattened_hprod = _np.zeros((dim**2, num_deriv_cols1, num_deriv_cols2), 'd') if _slct.length(gpindices1)", "at once impractical, and one is able to compute reduce results from a", "for i in mySubTreeIndices]))) #eval on each local subtree #my_results = [] for", "- K is the length of spam_label_rows, - S is the number of", "wrtSlice2=None): \"\"\" Computes a tree of product 2nd derivatives in a linear cache", "blkSize2) # override with smaller comm_blkSize else: blkSize1 = blkSize2 = None #", "occur here _np.seterr(**old_err) if bReturnProds: Gs = evalTree.final_view(prodCache, axis=0) #shape == ( len(circuit_list),", "1D array, `mxToFill` with the probabilities corresponding to the *simplified* operation sequences found", "(axis=0) if clipTo is not None: _np.clip(mxToFill, clipTo[0], clipTo[1], out=mxToFill) # in-place clip", "G, where: - S == len(circuit_list) - M == the length of the", "from using a split tree. In short, parallelization should be done at a", "(dGs, Gs) else: dGs = evalTree.final_view(dProdCache, axis=0) #shape == ( len(circuit_list), nDerivCols, dim,", "evalSubTree.final_view(dProdCache, axis=0) #( nCircuits, nDerivCols, dim, dim ) profiler.add_time(\"bulk_fill_dprobs: compute_dproduct_cache\", tm) profiler.mem_check(\"bulk_fill_dprobs: post", "prodCache[i] = _np.identity(dim) # Note: scaleCache[i] = 0.0 from initialization else: gate =", "columns into blocks of at most blkSize assert(wrtFilter1 is None and wrtFilter2 is", "a operation matrix (G x G operation matrices). and deriv[i,j,k] holds the derivative", "float, optional The maximum number of 1st (row) and 2nd (col) derivatives to", "is not the case, need LinearOperator objects to # have a 2nd-deriv method", "in # dproduct(...) and find the labels in the string which match the", "is done over operation sequences when a *split* evalTree is given, otherwise no", "and keep track of exponent if H.max() < PSMALL and H.min() > -PSMALL:", "= _slct.shift(myDeriv2ColSlice, wrtSlice2.start) else: myHessianSlice2 = myDeriv2ColSlice if mySubSubComm is not None and", "# _slct.shift(_slct.intersect( # wrtSlices['preps'], # slice(self.rho_offset[i],self.rho_offset[i+1])), # -self.rho_offset[i]) for i in range(len(self.preps))] #", "(ordered as numpy.flatten) - M == length of the vectorized model (number of", "compute *products* for simultaneously. None means compute all requested columns at once. The", "output of this function iterates over these computed blocks, in the order given", "def bulk_dproduct(self, evalTree, flat=False, bReturnProds=False, bScale=False, comm=None, wrtFilter=None): \"\"\" Compute the derivative of", "labels. Note: LinearOperator matrices are multiplied in the reversed order of the tuple.", "def estimate_mem_usage(self, subcalls, cache_size, num_subtrees, num_subtree_proc_groups, num_param1_groups, num_param2_groups, num_final_strs): \"\"\" Estimate the memory", "blkSize2 = None # wrtFilter1 & wrtFilter2 dictates block if blkSize1 is None", ">= num_final_strs # and this dictates how large all the storage arrays are.", "or 2, respectively - G == the linear dimension of a operation matrix", "the number of model parameters. Parameters ---------- spamTuple : (rho_label, simplified_effect_label) Specifies the", "add=sumInto) _np.seterr(**old_err) self._fill_result_tuple((mxToFill,), evalSubTree, slice(None), slice(None), calc_and_fill) #collect/gather results subtreeElementIndices = [t.final_element_indices(evalTree) for", "list of integers specifying which gate parameters to include in the derivative. Each", "whether the filling should overwrite or add to the existing array values, which", "given # wrtSlicesList last_wrtSlice1 = None # keep last dProdCache1 for wrtSlice1, wrtSlice2", "matrix # noqa # dprod/d(opLabel)_ij = sum_{L s.t. G(L) == oplabel} [ G1", "len(evalTree) prodCache = _np.zeros((cacheSize, dim, dim)) scaleCache = _np.zeros(cacheSize, 'd') #First element of", "derivative columns.\") # Use comm to distribute columns allDerivColSlice = slice(0, nDerivCols) if", "comm, gatherMemLimit) if deriv2MxToFill is not None: _mpit.gather_indices(subtreeElementIndices, subTreeOwners, deriv2MxToFill, [], 0, comm,", "_np.transpose(d2pr_dEs1, (0, 2, 1)) else: d2pr_dEs2 = _np.zeros((nCircuits, nDerivCols2, nDerivCols1)) dp_dAnyE = _np.squeeze(_np.dot(dGs2,", "this is a fairly common occurrence, and doesn't merit a warning # ------------------------------------------------------------------", "\"filtered\" set. # \"\"\" # PrepEffectFilter = _collections.namedtuple( # 'PrepEffectFilter', 'rho_local_slices rho_global_slices '", "\"\"\" #Create per-gate with-respect-to parameter filters, used to # select a subset of", "and blkSize nBlks1 = int(_np.ceil(self.Np / blkSize1)) nBlks2 = int(_np.ceil(self.Np / blkSize2)) #", "= obj.gpindices return obj_wrtFilter, relevant_gpindices #Vectorizing Identities. (Vectorization) # Note when vectorizing op", "= sum_{M s.t. GM == gatelabel1} sum_{L s.t. GL == gatelabel2, M <", "-DSMALL: _warnings.warn(\"Would have scaled dProd but now will not alter scaleCache.\") #profiler.print_mem(\"DEBUGMEM: POINT2\");", "_warnings.warn(\"hProd is small (oh well!).\") return hProdCache ## END CACHE FUNCTIONS def default_distribute_method(self):", "ret = ps #DEBUG CHECK #check_ps = _np.array( [ self.pr( (rholabel,elabel), circuit, clipTo,", "strings. Similar to `bulk_fill_probs(...)`, but fills a 3D array with probability-Hessians for each", "# pass None as comm, *not* mySubComm (this is ok, see \"if\" condition", "be pre-filtered!\" #Compute d(probability)/dOps and save in return list (now have G,dG =>", "where d12_col is a column of the matrix d12 defined by: d12[iSpamLabel,iOpStr,p1,p2] =", "scaleVal is mult by a zero hessian value (see below) hGs[_np.isnan(hGs)] = 0", "if needed) subtrees = evalTree.get_sub_trees() mySubTreeIndices, subTreeOwners, mySubComm = evalTree.distribute(comm) #eval on each", "a M x G x G array, where: - M == length of", "#Same as in bulk_fill_hprobs (TODO consolidate?) #NOTE: filtering is done via the yet-to-be-defined", "always zero _np.seterr(**old_err) if returnDeriv: if returnPr: return ret, dpr, p else: return", "(G x G operation matrices) and derivs[i,j,k,l] holds the derivative of the (k,l)-th", "arguments, except for the last). The final argument is a boolean specifying whether", "E ret += d2pr_drhos1 + d2pr_dEs1 + d2pr_dOps2 # wrt gates return ret", "# respect to a given gateLabel_ij. This function returns a concatenated form of", "comm_blkSize if (blkSize1 is None) \\ else min(comm_blkSize, blkSize1) # override with smaller", "the final # filled quantity combining both spam and gate-sequence indices # gInds", ": bool, optional Whether to use a post-scaled product internally. If False, this", "array # want vp[iFinal] = float(dot(E, dot(G, rho))) # vp[i] = sum_k,l E[0,k]", "yet!\") rholabel, elabel = spamTuple rhoVec = self.sos.get_prep(rholabel) # distinct from rho,E b/c", "for i in evalTree.get_evaluation_order(): tm = _time.time() # combine iLeft + iRight =>", "cache mem += cache_size # scale vals elif fnName == \"bulk_hprobs_by_block\": #Note: includes", "of final elements (i.e. probabilities) to gate-only sequence and prep/effect pairs. The evaluation", "1, 2) dLdR_sym = dLdRa + _np.swapaxes(dLdRb, 0, 1) hProdCache[i] = _np.dot(hL, R)", "prod_col) def dproduct(self, circuit, flat=False, wrtFilter=None): \"\"\" Compute the derivative of a specified", "evalTree.get_sub_trees() mySubTreeIndices, subTreeOwners, mySubComm = evalTree.distribute(comm) #eval on each local subtree for iSubTree", "dGs2 be None? assert(nDerivCols1 == nDerivCols2) d2pr_drhos2 = _np.transpose(d2pr_drhos1, (0, 2, 1)) else:", "vec( dG(M)/dkl ) ) # noqa # tensor (G(L+1) ... GN)^T vec( dG(L)/dij", "#G = _np.identity( self.dim ); total_exp = 0.0 #for i,lOp in enumerate(gateLabelList): #", "otherwise no parallelization is performed. Returns ------- prods : numpy array Array of", "tm) #use cached data to final values scaleVals = self._scaleExp(evalSubTree.final_view(scaleCache)) Gs = evalSubTree.final_view(prodCache,", "if comm is not None and comm.Get_size() > 1: # parallelize of deriv", "self._process_wrtFilter(wrtSlice2, self.sos.get_effect(elabel)) nDerivCols1 = self.Np if wrtSlice1 is None else _slct.length(wrtSlice1) nDerivCols2 =", "flattened_dprod. uniqueOpLabels = sorted(list(set(revOpLabelList))) for opLabel in uniqueOpLabels: gate = self.sos.get_operation(opLabel) op_wrtFilter, gpindices", "comm, gatherMemLimit) if deriv1MxToFill is not None: _mpit.gather_indices(subtreeElementIndices, subTreeOwners, deriv1MxToFill, [], 0, comm,", "= None # free mem else: # Divide columns into blocks of at", "dictionaries of LinearOperator, SPAMVec, and SPAMVec objects, respectively. Must be *ordered* dictionaries to", "Returns ------- prods : numpy array Array of shape S x G x", "[] G = _np.identity(dim); rightProdsT.append(_np.transpose(G)) for opLabel in reversed(revOpLabelList): G = _np.dot(self.sos.get_operation(opLabel).todense(), G)", "vals else: raise ValueError(\"Unknown subcall name: %s\" % fnName) return mem * FLOATSIZE", "comm) #use cached data to construct return values Gs = evalTree.final_view(prodCache, axis=0) #shape", "circuit : Circuit or tuple A tuple-like object of *simplified* gates (e.g. may", "---------- dim : int The gate-dimension. All operation matrices should be dim x", "Es def _probs_from_rhoE(self, rho, E, Gs, scaleVals): if self.evotype == \"statevec\": raise NotImplementedError(\"Unitary", "> 1e-6: _warnings.warn(\"norm(vdp-check_vdp) = %g - %g = %g\" % (_nla.norm(dprMxToFill[fInds]), _nla.norm(check_vdp), _nla.norm(dprMxToFill[fInds]", "but OK _fas(dpr_dEs, [0, EVec.gpindices], _np.dot(derivWrtAnyEvec, EVec.deriv_wrt_params())) dpr = dpr_drhos + dpr_dEs +", "of integers specifying which gate parameters to include in the derivative. Each element", "np2 - 1) // np2 # ceiling(num_params / np2) mem = 0 for", "estimate of the ideal/desired cache size given a number of operation sequences. Returns", "computation functions. Parameters ---------- subcalls : list of strs A list of the", "== nDerivCols), \"dGs must be pre-filtered!\" #Compute d(probability)/dOps and save in return list", "dim ) hProdCache = self._compute_hproduct_cache(evalSubTree, prodCache, dProdCache1, dProdCache2, scaleCache, mySubComm, wrtSlice1, wrtSlice2) hGs", "length of the vectorized model - G == the linear dimension of a", "s in loc_rho_slices] # tmp_offsets = [ sum(tmp_num_params[0:i]) for i in range(len(self.preps)+1) ]", "+ \\ d2pr_drhos + _np.transpose(d2pr_drhos, (0, 2, 1)) + \\ d2pr_dEs + _np.transpose(d2pr_dEs,", "# overflow OK # get d2pr_drhos where gate derivatives are wrt the 2nd", "for distributing the computation across multiple processors. Distribution is first done over the", "this calculator. Parameters ---------- simplified_circuits : list A list of Circuits or tuples", "self._rhoE_from_spamTuple(spamTuple) rhoVec = self.sos.get_prep(rholabel) # distinct from rho,E b/c rho,E are EVec =", "\"calc-and-fill\" function, which computes and *fills* (i.e. doesn't return to save copying) some", "wrtSlice2): dProdCache2 = dProdCache1; dGs2 = dGs1 else: dProdCache2 = self._compute_dproduct_cache( evalTree, prodCache,", "= dGs = None # free mem #gather results tm = _time.time() _mpit.gather_slices(blocks,", "# , gatherMemLimit) #gather over col-distribution (Deriv2) #note: gathering axis 2 of hProdCache[:,myDeriv1ColSlice],", "be useful when memory constraints make constructing the entire Hessian at once impractical,", "circuit: G = _np.dot(self.sos.get_operation(lOp).todense(), G) # LEXICOGRAPHICAL VS MATRIX ORDER return G def", "None. bUseScaling : bool, optional Whether to use a post-scaled product internally. If", "def _compute_hproduct_cache(self, evalTree, prodCache, dProdCache1, dProdCache2, scaleCache, comm=None, wrtSlice1=None, wrtSlice2=None): \"\"\" Computes a", "rho),2), dEP)[i,J] # dp_dEs[:,J0+J] = dot(squeeze(dot(Gs, rho),axis=(2,)), dEP)[:,J] dp_dEs = _np.zeros((nCircuits, nDerivCols)) #", "numpy arrays # like length>1 lists do... ugh. relevant_gpindices = slice(0, 0) #", "columns which correspond to the vectorized derivatives of each of the product components", "have scaled dProd but now will not alter scaleCache.\") #profiler.print_mem(\"DEBUGMEM: POINT2\"); profiler.comm.barrier() profiler.add_time(\"compute_dproduct_cache:", "alter product, dproduct, etc. to allow for *complex* derivatives, since matrices can be", "isn't specified if wrtFilter is None: blkSize = wrtBlockSize # could be None", "columns at once self._fill_result_tuple((prMxToFill, deriv1MxToFill, deriv2MxToFill, mxToFill), evalSubTree, slice(None), slice(None), calc_and_fill) else: #", "if blk2Comm is not None: _warnings.warn(\"Note: more CPUs(%d)\" % mySubComm.Get_size() + \" than", "scale. The purpose of this is to allow a trace or other linear", "nG = max(_nla.norm(gate), 1.0) prodCache[i] = gate / nG scaleCache[i] = _np.log(nG) #evaluate", "but isn't gathered until now (but using blk1Comm). # (just as prMxToFill is", "elabel = spamTuple rho, E = self._rhoE_from_spamTuple(spamTuple) rhoVec = self.sos.get_prep(rholabel) # distinct from", "gathering axis 2 of hProdCache[:,myDeriv1ColSlice], # dim=(cacheSize,nDerivCols1,nDerivCols2,dim,dim) else: #compute \"Deriv1\" row-derivatives distribution only;", "as that used by numpy.flatten), - S,M == as above, and deriv[i,j] holds", "elements of `result_tup`. The fill function computes values for only a single spam", "find the labels in the string which match the current # gate (so", "initial single- or zero-operation labels wrtIndices1 = _slct.indices(wrtSlice1) if (wrtSlice1 is not None)", "False, two arrays of shape S x M x G x G, where", "mySubComm.Get_size() + \" than hessian elements(%d)!\" % (self.Np**2) + \" [blkSize = {%.1f,%.1f},", "x G array, where: - M == length of the vectorized model (number", "= len(evalTree) prodCache = _np.zeros((cacheSize, dim, dim)) scaleCache = _np.zeros(cacheSize, 'd') #First element", "everything else return (dGs, scaleVals) if bScale else dGs def bulk_hproduct(self, evalTree, flat=False,", "l==m, which we *used* to assume gave no contribution since we assume all", "and POVM effect used to compute the probability. circuit : Circuit or tuple", "EVec = self.sos.get_effect(elabel) # arrays, these are SPAMVecs nCircuits = Gs.shape[0] rho_wrtFilter1, rho_gpindices1", "2 Re(dpr/dx*pr.C) , where dpr/dx is the usual density-matrix-mode probability # (TODO in", "_np.empty((1, self.Np)) for i in range(self.Np): dpr_dOps[0, i] = float(_np.dot(E, _np.dot(dprod_dOps[i], rho))) #Derivs", "`dprobs12 == dp1[:,:,rowSlice,None] * dp2[:,:,None,colSlice]` \"\"\" assert(not evalTree.is_split()), \"`evalTree` cannot be split\" nElements", "occur b/c an inf scaleVal is mult by a zero hessian value (see", "wrtBlockSize to use available processors if it isn't specified if wrtFilter1 is None", "order of the tuple. That is, the first element of circuit can be", "fInds, gInds, pslc1, pslc2, sumInto): \"\"\" Compute and fill result quantities blocks for", "self.evotype == \"statevec\": raise NotImplementedError(\"Unitary evolution not fully supported yet!\") # pr =", "distribute columns allDeriv1ColSlice = slice(0, nDerivCols1) allDeriv2ColSlice = slice(0, nDerivCols2) deriv1Slices, myDeriv1ColSlice, deriv1Owners,", "a functionality needed to correctly handle the remainder spam label. \"\"\" pslc1 =", "None) and (mySubComm.Get_size() > 1): comm_blkSize = self.Np / mySubComm.Get_size() blkSize1 = comm_blkSize", "None, None]) # overflow OK # get d2pr_drhos where gate derivatives are wrt", "and gl2 are both in opsToVectorize1 and opsToVectorize2 we only compute d2(prod)/d(gl1)d(gl2) #", "very useful ## since numpy does all the major allocation/deallocation). #if comm is", "* B ) = vec( mx w/ col_i = A[col0] * B[0,1] )", "old_err2 = _np.seterr(invalid='ignore', over='ignore') dp_dOps = _np.squeeze(_np.dot(E, _np.dot(dGs, rho)), axis=(0, 3)) * scaleVals[:,", "or Instrument labels). numSubtreeComms : int The number of processor groups that will", "self.product(circuit, True) dprod_dOps = self.dproduct(circuit) dpr_dOps = _np.empty((1, self.Np)) for i in range(self.Np):", "IPC\", tm) profiler.mem_check(\"bulk_fill_dprobs: post gather subtrees\") if clipTo is not None and prMxToFill", "Computation will be automatically parallelized over these groups. num_param2_groups : int The number", "Computation will be automatically parallelized over these groups. num_final_strs : int The number", "nCircuits * dim**2)), 2) # cols = deriv cols, rows = all else", "_nla.norm(dprMxToFill[fInds] - check_vdp) > 1e-6: _warnings.warn(\"norm(vdp-check_vdp) = %g - %g = %g\" %", "blk2Comm is not None: _warnings.warn(\"Note: more CPUs(%d)\" % mySubComm.Get_size() + \" than hessian", "deriv1Owners, hProdCache, [], 1, comm) #, gatherMemLimit) #gather over row-distribution (Deriv1) #note: gathering", "\" ... (len %d)\" % len(circuit) _warnings.warn(\"pr(%s) == nan\" % strToPrint) #DEBUG: print", "in mySubTreeIndices]))) #eval on each local subtree #my_results = [] for iSubTree in", "else _slct.length(wrtSlice) # GATE DERIVS (assume dGs is already sized/filtered) ------------------- assert(dGs.shape[1] ==", "i-th entry of the flattened product with respect to the k-th then k-th", "# hproduct cache # mem += cache_size * num_params * dim * dim", "= self.product(circuit, False) if self.evotype == \"statevec\": ps = _np.real(_np.abs(_np.dot(Es, _np.dot(G, rho)))**2) else:", "is able to compute reduce results from a single column of the Hessian", "= max(_nla.norm(opmx), 1.0) scaledGatesAndExps[lOp] = (opmx / ng, _np.log(ng)) gate, ex = scaledGatesAndExps[lOp]", "tree (skip over the zero and single-gate-strings) #cnt = 0 for i in", "dim = self.dim # Note: dProdCache?.shape = (#circuits,#params_to_diff_wrt,dim,dim) nDerivCols1 = dProdCache1.shape[1] nDerivCols2 =", "zero and single-gate-strings) for i in evalTree.get_evaluation_order(): # combine iLeft + iRight =>", "needed) # transposes each of the now un-vectorized dim x dim mxs corresponding", "d2pr_drhos1 = _np.zeros((nCircuits, nDerivCols1, nDerivCols2)) _fas(d2pr_drhos1, [None, None, rho_gpindices2], _np.squeeze(_np.dot(_np.dot(E, dGs1), drho), axis=(0,))", "scaleVal is mult by a zero deriv value, and we dGs[_np.isnan(dGs)] = 0", "fully supported yet!\") # To support unitary evolution we need to: # -", "the entire Hessian at once impractical, and one is able to compute reduce", "[felInds], 1, blk1Comm, gatherMemLimit) #Note: deriv2MxToFill gets computed on every inner loop completion", "0 and _slct.length(gpindices2) > 0: # works for arrays too # Compute the", "[ G1 ... G(M-1) dG(M)/dkl G(M+1) ... G(L-1) dG(L)/dij G(L+1) ... GN ]", "have fewer processor groups then subtrees (even == 1) in order to perform", "= _np.rollaxis(_np.rollaxis(hGs, 0, 3).reshape( (nDerivCols1, nDerivCols2, nCircuits * dim**2)), 2) # cols =", "== ( len(circuit_list), nDerivCols, dim, dim ), # dGs[i] is dprod_dOps for ith", "i-th operation sequence. \"\"\" dim = self.dim nDerivCols1 = self.Np if (wrtFilter1 is", "dop_dopLabel2 = { opLabel: gate.deriv_wrt_params(gate_wrtFilters2[opLabel]) for opLabel, gate in used_operations.items()} #Finally, cache any", "slice(None), calc_and_fill) profiler.mem_check(\"bulk_fill_dprobs: post fill\") dProdCache = dGs = None # free mem", "* nspam * wrtLen1 * wrtLen2 # hprobs & dprobs12 results mem +=", "= _np.transpose(d2pr_dErhos2, (0, 2, 1)) #Note: these 2nd derivatives are non-zero when the", "EvalTree given by a prior call to bulk_evaltree. Specifies the *simplified* gate strings", "= None # free mem dProdCache1 = dGs1 = None # free mem", "as _time import itertools as _itertools import collections as _collections from ..tools import", "nCircuits, dim, dim ) #Same as in bulk_fill_hprobs (TODO consolidate?) #NOTE: filtering is", "lists do... ugh. relevant_gpindices = slice(relevant_gpindices[0], relevant_gpindices[0] + 1) elif len(relevant_gpindices) == 0:", "LinearOperator matrices are multiplied in the reversed order of the tuple. That is,", "for i in range(len(self.effects)) ] # # return PrepEffectFilter(rho_local_slices=loc_rho_slices, # rho_global_slices=global_rho_slices, # e_local_slices=loc_e_slices,", "labels wrtIndices1 = _slct.indices(wrtSlice1) if (wrtSlice1 is not None) else None wrtIndices2 =", "is performed over subtrees of evalTree (if it is split). Returns ------- None", "the hessian of a length-1 (single-gate) sequence \"\"\" dim = self.dim gate =", "given arguments \"\"\" old_err = _np.seterr(over='ignore') rho, E = self._rhoE_from_spamTuple(spamTuple) #if prMxToFill is", "over these groups. num_param2_groups : int The number of groups to divide the", "x G operation matrices). and hessian[i,j,k,l] holds the derivative of the (k,l)-th entry", "an MPI communicator for distributing the computation across multiple processors. This is done", "evalTree.final_view(scaleCache) scaleVals = _np.exp(scaleExps) # may overflow, but OK if infs occur here", "None wrtSlice2 = _slct.list_to_slice(wrtFilter2) if (wrtFilter2 is not None) else None #TODO: just", "construct return values old_err = _np.seterr(over='ignore') scaleExps = evalTree.final_view(scaleCache) scaleVals = _np.exp(scaleExps) #", "computation\") pass # this is a fairly common occurrence, and doesn't merit a", "used to # select a subset of all the derivative columns, essentially taking", "entire range of model params so that # per-gate hessians can be computed", "dim)) # axes = (model_parameter1, model_parameter2, model_element_row, model_element_col) def prs(self, rholabel, elabels, circuit,", "_np.dot(gate, G / nG); scale_exp += _np.log(nG) # LEXICOGRAPHICAL VS MATRIX ORDER else:", "But since we're # assuming that the gates are at most linear in", "elements like 'Imyinst_0') returnPr : bool when set to True, additionally return the", "_np.transpose(d2pr_dErhos2, (0, 2, 1)) #Note: these 2nd derivatives are non-zero when the spam", "2nd derivatives are non-zero when the spam vectors have # a more than", "given by `wrtSlicesList`. `rowSlice` and `colSlice` must by Python `slice` objects. bReturnDProbs12 :", "such that scaleVals[i] contains the multiplicative scaling needed for the hessians, derivatives, and/or", "x = _np.dot(_np.transpose(hop_dopLabels[opLabel1], axes=(1, 2, 0)), x0); xv = x.view() xv = _np.transpose(xv,", "add=sumInto) if deriv1MxToFill is not None: _fas(deriv1MxToFill, [fInds, pslc1], self._dprobs_from_rhoE( spamTuple, rho, E,", "= evalTree.final_view(dProdCache1, axis=0) last_wrtSlice1 = wrtSlice1 if (wrtSlice1 == wrtSlice2): dProdCache2 = dProdCache1;", "max(_nla.norm(R), _np.exp(-scaleCache[iRight]), 1e-300) sL, sR = L / nL, R / nR prodCache[i]", "(i, opLabel1) in enumerate(revOpLabelList): # loop over \"starting\" gate prods[(i, i - 1)]", "_rhoE_from_spamTuple(self, spamTuple): assert(len(spamTuple) == 2) if isinstance(spamTuple[0], _Label): rholabel, elabel = spamTuple #", "to if not None. Only relevant when prMxToFill is not None. Returns -------", "_np.dot(dL, R) + \\ _np.swapaxes(_np.dot(L, dR), 0, 1) # dot(dS, T) + dot(S,", "of a operation matrix (G x G operation matrices). scaleValues : numpy array", "prods : numpy array Array of shape S x G x G, where:", "_, mySubComm = \\ _mpit.distribute_slice(allDerivColSlice, comm) #print(\"MPI: _compute_dproduct_cache over %d cols (%s) (rank", "of operation labels The sequence of operation labels. bScale : bool, optional When", "= evalTree.final_view(dProdCache2, axis=0) #shape == ( len(circuit_list), nDerivColsX, dim, dim ), # dGs[i]", "circuit can be thought of as the first gate operation performed, which is", "incorrect (and luckily never used) - so it's been removed. if comm is", "(see below). bReturnProds : bool, optional when set to True, additionally return the", "evalSubTree = subtrees[iSubTree] felInds = evalSubTree.final_element_indices(evalTree) #Free memory from previous subtree iteration before", ") # if vec(.) stacks columns # vec( A * E(0,1) * B", "int(_np.ceil(self.Np / blkSize1)) nBlks2 = int(_np.ceil(self.Np / blkSize2)) # num blocks required to", "== (len(circuit_list),) ; may overflow but OK def _dprobs_from_rhoE(self, spamTuple, rho, E, Gs,", "differentiation, respectively (i.e. by wrtFilter1 and wrtFilter2). clipTo : 2-tuple, optional (min,max) to", "= self.Np if (wrtFilter1 is None) else _slct.length(wrtFilter1) nDerivCols2 = self.Np if (wrtFilter2", "[:, None])) # convention: E has shape (1,N) else: # a \"custom\" spamLabel", "products[i] is the i-th operation sequence product. scaleVals : numpy array Only returned", "else: return ret ## BEGIN CACHE FUNCTIONS def _compute_product_cache(self, evalTree, comm=None): \"\"\" Computes", "#Set wrtBlockSize to use available processors if it isn't specified if wrtFilter is", "_np.kron(leftProds[i], rightProdsT[N - 1 - i]) # (dim**2, dim**2) _fas(flattened_dprod, [None, gpindices], _np.dot(LRproduct,", "A length-S array specifying the scaling that needs to be applied to the", "TODO: remove this concat w/better gather? # ------------------------------------------------------------------ tSerialStart = _time.time() if evalTree.is_split():", "G operation matrices). and deriv[i,j,k] holds the derivative of the (j,k)-th entry of", "slice into entire range of model params (see above) if wrtSlice2 is not", "gate.deriv_wrt_params(op_wrtFilter) for (i, gl) in enumerate(revOpLabelList): if gl != opLabel: continue # loop", "# vec( d2prod/d(opLabel1)_kl*d(opLabel2)_ij ) = sum{...} [ G1 ... G(M-1) dG(M)/dkl G(M+1) ...", "is not None and wrtSlice2.start is not None: myHessianSlice2 = _slct.shift(myDeriv2ColSlice, wrtSlice2.start) else:", "= spamTuple E = _np.conjugate(_np.transpose(Eraw)) return rho, E def _rhoEs_from_spamTuples(self, rholabel, elabels): #Note:", "ident # product of no gates #Also Cache gate jacobians (still relatively little", "the product of a specified sequence of operation labels. Note: LinearOperator matrices are", "sequence with respect to only those two gates' parameters and fill # add", "scaleCache[i] += _np.log(nL) + _np.log(nR) #print \"bulk_product DEBUG: %d rescalings out of %d", "rholabel, elabel = spamTuple # This calculator uses the convention that rho has", "# wrtSlices['preps'], # slice(self.rho_offset[i],self.rho_offset[i+1])), # -self.rho_offset[i]) for i in range(len(self.preps))] # tmp_num_params =", "is the total number of computed elements (i.e. evalTree.num_final_elements()) and M1 & M2", "= _np.transpose(d2pr_dEs2, (0, 2, 1)) # Get: d2pr_dErhos[i, e_offset[eIndex]:e_offset[eIndex+1], e_offset[rhoIndex]:e_offset[rhoIndex+1]] = # dEP^T", "self.sos.get_effect(elabel) # arrays, these are SPAMVecs nCircuits = Gs.shape[0] rho_wrtFilter1, rho_gpindices1 = self._process_wrtFilter(wrtSlice1,", "# (comm.Get_rank(),\",\".join([str(len(subtrees[i])) # for i in mySubTreeIndices]))) #eval on each local subtree #my_results", ": numpy ndarray an already-allocated ExMxM numpy array where E is the total", "sequences at once. Parameters ---------- evalTree : EvalTree given by a prior call", "0, 3) * scaleVals, 0, 3) # may overflow or get nans (invalid),", "& wrtFilter2 dictates block if blkSize1 is None and blkSize2 is None: #Fill", "l - 1)]) # (dim**2, dim**2) x = _np.dot(_np.transpose(dop_dopLabel1[opLabel1]), x0); xv = x.view()", "the sub-trees). Note also that there would be no memory savings from using", "the raw operation sequences which need to be computed # for the current", "labels. evalTree : EvalTree given by a prior call to bulk_evaltree. Specifies the", "numpy array Array of shape S x G x G, where: - S", "this concat w/better gather? # ------------------------------------------------------------------ tSerialStart = _time.time() if evalTree.is_split(): _warnings.warn(\"Ignoring tree", "compute # derivatives wrt all spam parameters dGs = _np.empty((Gs.shape[0], 0, self.dim, self.dim),", "pslc2], self._hprobs_from_rhoE( spamTuple, rho, E, Gs[gInds], dGs1[gInds], dGs2[gInds], hGs[gInds], scaleVals[gInds], wrtSlice1, wrtSlice2), add=sumInto)", "efficiently by actually computing X^T ( note (A tensor B)^T = A^T tensor", "wrtSlice1 is None else _slct.length(wrtSlice1) nDerivCols2 = self.Np if wrtSlice2 is None else", "* dim # hproduct cache mem += cache_size * (wrtLen1 + wrtLen2) *", "G^2)-th flattened operation sequence product with respect to the k-th then j-th model", "objects to # have a 2nd-deriv method in addition of deriv_wrt_params # #", "if copy is needed) y = _np.dot(_np.kron(xv, _np.transpose(prods[(l + 1, N - 1)])),", "(k,l)-th entry of the product with respect to the j-th then i-th model", "\"\"\" Compute and fill result quantities for given arguments \"\"\" old_err = _np.seterr(over='ignore')", "takes (kl,vec_prod_indx,ij) => (vec_prod_indx,kl,ij) else: # l==m, which we *used* to assume gave", "of the flattened product with respect to the k-th then k-th model parameters.", "ValueError((\"Evolution type %s is incompatbile with \" \"matrix-based calculations\" % self.evotype)) def copy(self):", "should be dim x dim, and all SPAM vectors should be dim x", "is not None) else None wrtSlice2 = _slct.list_to_slice(wrtFilter2) if (wrtFilter2 is not None)", "for iSubTree in mySubTreeIndices: evalSubTree = subtrees[iSubTree] #Free memory from previous subtree iteration", "multiple processors. Returns ------- deriv : numpy array * if flat == False,", "_mt.trace( _np.dot(self.SPAMs[spamLabel],G) ) * exp(total_exp) # probability # print \"%d: p = %g,", "divide the first-derivative parameters into. Computation will be automatically parallelized over these groups.", "hGs = evalTree.final_view(hProdCache, axis=0) if bReturnDProbs12: dprobs1 = _np.zeros((nElements, _slct.length(wrtSlice1)), 'd') dprobs2 =", "dProdCache[iRight] dProdCache[i] = _np.dot(dL, R) + \\ _np.swapaxes(_np.dot(L, dR), 0, 1) # dot(dS,", "is not None and wrtSlice1.start is not None: myHessianSlice1 = _slct.shift(myDeriv1ColSlice, wrtSlice1.start) else:", "d2prod/d(opLabel1)_kl*d(opLabel2)_ij ) = sum{...} [ G1 ... G(M-1) dG(M)/dkl G(M+1) ... G(L-1) tensor", "circuit, returnPr, clipTo): \"\"\" Compute the derivative of a probability generated by a", "= G prods[(len(revOpLabelList), len(revOpLabelList) - 1)] = ident # product of no gates", "dim ), Gs[i] is product for i-th operation sequence scaleExps = evalTree.final_view(scaleCache) old_err", "= sum_kl dEPT[J,k] dGs[i,j,k,l] rho[l,0] # d2pr_dEs[i,j,J0+J] = sum_k dEP[k,J] dot(dGs, rho)[i,j,k,0] #", "used to simulate time-dependent circuits\" rho, Es = self._rhoEs_from_spamTuples(rholabel, elabels) #shapes: rho =", "rho_gpindices2], _np.squeeze(_np.dot(_np.dot(E, dGs1), drho), axis=(0,)) * scaleVals[:, None, None]) # overflow OK #", "of intermediate memory required. profiler : Profiler, optional A profiler object used for", "gInds, pslc1, pslc2, sumInto): \"\"\" Compute and fill result quantities blocks for given", "is None) else len(wrtFilter2) flattened_hprod = _np.zeros((dim**2, num_deriv_cols1, num_deriv_cols2), 'd') if _slct.length(gpindices1) >", "+= 2 * cache_size * nspam * wrtLen1 * wrtLen2 # hprobs &", "None] for elabel in elabels] Es = _np.conjugate(_np.transpose(_np.concatenate(Es, axis=1))) # convention: Es has", "list of integers specifying which model parameters to differentiate with respect to in", "as numpy.flatten), - S,M == as above, and deriv[i,j] holds the derivative of", "= evalTree.final_view(scaleCache) old_err = _np.seterr(over='ignore') scaleVals = _np.exp(scaleExps) # may overflow, but OK", "of the tuple. That is, the first element of circuit can be thought", "= _time.time() old_err = _np.seterr(over='ignore') rho, E = self._rhoE_from_spamTuple(spamTuple) _fas(prMxToFill, [fInds], self._probs_from_rhoE(rho, E,", "out pieces of a wrtFilter argument relevant for a single object (gate or", "# d2pr_dErhos[i,J0+J,K0+K] = swapaxes(dot(dEPT,prod,drhoP),0,1)[i,J,K] # d2pr_dErhos[:,J0+J,K0+K] = swapaxes(dot(dEPT,prod,drhoP),0,1)[:,J,K] d2pr_dErhos1 = _np.zeros((nCircuits, nDerivCols1, nDerivCols2))", "effectVec) rho, Eraw = spamTuple E = _np.conjugate(_np.transpose(Eraw)) return rho, E def _rhoEs_from_spamTuples(self,", "loc_e_slices = [slice(None,None)]*len(self.effects) # global_rho_slices = [slice(self.rho_offset[i],self.rho_offset[i+1]) for i in range(len(self.preps)) ] #", "= 2 Re(dpr/dx*pr.C) , where dpr/dx is the usual density-matrix-mode probability # (TODO", "dim # dproduct cache # mem += cache_size * dim * dim #", "# TODO: better check for equivalence: maybe let dGs2 be None? assert(nDerivCols1 ==", "throw more informative error? #elif fnName == \"bulk_product\": # mem += cache_size *", "use derivative columns and then (and only when needed) a split tree to", "if _np.any(_np.isnan(ps)): if len(circuit) < 10: strToPrint = str(circuit) else: strToPrint = str(circuit[0:10])", "of flattened_d2prod. #NOTE: if we needed to perform a hessian calculation (i.e. for", "a \"filter\" object containing info about the mapping # of prep and effect", "of the matrix d12 defined by: d12[iSpamLabel,iOpStr,p1,p2] = dP/d(p1)*dP/d(p2) where P is is", "# noqa # dprod/d(opLabel)_ij = sum_{L s.t. G(L) == oplabel} [ G1 ...", "the functions named by `subcalls`. num_subtrees : int The number of subtrees to", "G def _process_wrtFilter(self, wrtFilter, obj): \"\"\" Helper function for doperation and hoperation below:", "subtrees[iSubTree] #Free memory from previous subtree iteration before computing caches scaleVals = Gs", "product with respect to the j-th model parameter. \"\"\" # LEXICOGRAPHICAL VS MATRIX", "a class separate from Model to allow for additional model classes (e.g. ones", "bReturnDProdsAndProds == True. * if flat == False, two arrays of shape S", "noqa # + sum{ L == M} [ G1 ... G(M-1) tensor (G(M+1)", "1e-8) return ret def dpr(self, spamTuple, circuit, returnPr, clipTo): \"\"\" Compute the derivative", "the spam vectors have # a more than linear dependence on their parameters.", "over these computed blocks, in the order given by `wrtSlicesList`. `rowSlice` and `colSlice`", "spam vec) \"\"\" #Create per-gate with-respect-to parameter filters, used to # select a", "is None) else len(wrtFilter) flattened_dprod = _np.zeros((dim**2, num_deriv_cols), 'd') # For each operation", "numpy array, optional when not None, an already-allocated length-E numpy array that is", "# objects: (prepVec, effectVec) rho, Eraw = spamTuple E = _np.conjugate(_np.transpose(Eraw)) return rho,", "#flt1 = self._get_filter_info(wrtSlices1) #flt2 = self._get_filter_info(wrtSlices2) # GATE DERIVS (assume hGs is already", "nDerivCols2 = self.Np if wrtSlice2 is None else _slct.length(wrtSlice2) #flt1 = self._get_filter_info(wrtSlices1) #flt2", "as _np import numpy.linalg as _nla import time as _time import itertools as", "check for equivalence: maybe let dGs2 be None? assert(nDerivCols1 == nDerivCols2) d2pr_dEs2 =", "parallelize of deriv cols, then sub-trees (if available and necessary) if comm.Get_size() >", "N == the number of entries in a single flattened gate (ordering same", "derivs[i,j,k,l] holds the derivative of the (k,l)-th entry of the i-th operation sequence", "in myBlk1Indices: blk_wrtSlice1 = blocks1[iBlk1] dProdCache1 = self._compute_dproduct_cache( evalSubTree, prodCache, scaleCache, blk1Comm, blk_wrtSlice1)", "if prMxToFill is not None: check_vp = _np.array([self.prs(spamTuple[0], [spamTuple[1]], circuit, clipTo, False)[0] for", "scale = self.product(circuit, True) dprod_dOps = self.dproduct(circuit) dpr_dOps = _np.empty((1, self.Np)) for i", "in enumerate(gateLabelList): # G = _np.dot(G,self[lOp]) # product of gates, starting with G0", "array (see below). bReturnDProdsAndProds : bool, optional when set to True, additionally return", "- check_vp) > 1e-6: _warnings.warn(\"norm(vp-check_vp) = %g - %g = %g\" % (_nla.norm(prMxToFill[fInds]),", "GN)^T vec( dG(L)/dij ) ] # noqa # + sum{ L < M}", "is not None: _mpit.gather_indices(subtreeElementIndices, subTreeOwners, prMxToFill, [], 0, comm) if clipTo is not", "_np.tensordot(dp_dAnyRho, self.sos.get_prep(rholabel).hessian_wrt_params( rho_wrtFilter1, rho_wrtFilter2), (1, 0))) # _np.einsum('ij,jkl->ikl', dp_dAnyRho, self.sos.get_prep(rholabel).hessian_wrt_params( # rho_wrtFilter1, rho_wrtFilter2))", "the mappings generated when the original list of `Circuits` was simplified. Parameters ----------", "is not None: assert(wrtBlockSize1 is None and wrtBlockSize2 is None) # Cannot specify", "to divide the second-derivative parameters into. Computation will be automatically parallelized over these", "computed on every inner loop completion # (to save mem) but isn't gathered", "G == the linear dimension of a operation matrix (G x G operation", "An array of shape S x G x G; products[i] is the i-th", "dEP[j,J] # dp_dEs[i,J0+J] = dot(squeeze(dot(Gs, rho),2), dEP)[i,J] # dp_dEs[:,J0+J] = dot(squeeze(dot(Gs, rho),axis=(2,)), dEP)[:,J]", "parameter (M is the length of the vectorized model). probability : float only", "scale * _np.transpose(_np.dot(prod, rho)) # may overflow, but OK d2pr_d2Es = _np.zeros((1, self.Np,", "= %s\" % # (comm.Get_rank(),\",\".join([str(len(subtrees[i])) # for i in mySubTreeIndices]))) #eval on each", "dProdCache2, scaleCache, comm, wrtSlice1, wrtSlice2) hGs = evalTree.final_view(hProdCache, axis=0) if bReturnDProbs12: dprobs1 =", "Parameters ---------- mxToFill : numpy ndarray an already-allocated ExMxM numpy array where E", "far right of the product of matrices. Parameters ---------- circuit : Circuit or", "small (oh well!).\") return hProdCache ## END CACHE FUNCTIONS def default_distribute_method(self): \"\"\" Return", "the i-th operation sequence. \"\"\" nCircuits = evalTree.num_final_strings() nDerivCols = self.Np if (wrtFilter", "derivative of the (i % G^2)-th entry of the (i / G^2)-th flattened", "groups. num_param2_groups : int The number of groups to divide the second-derivative parameters", "N = len(revOpLabelList) # length of operation sequence # prod = G1 *", "allow slices as argument: wrtFilter -> wrtSlice? prodCache, scaleCache = self._compute_product_cache(evalTree, comm) dProdCache1", "# Smallness tolerances, used internally for conditional scaling required # to control bulk", "[], 0, comm) #note: pass prMxToFill, dim=(KS,), so gather prMxToFill[felInds] (axis=0) profiler.add_time(\"MPI IPC\",", "the number of model parameters. hessian[0,j,k] is the derivative of the probability w.r.t.", "gate parameters to differentiate with respect to in the first (row) and second", "d2pr_d2Es + d2pr_dOps2 # Note: add transposes b/c spam terms only compute one", "axes=(2, 0, 1)) # (dim2, nDerivCols1, nDerivCols2) flattened_d2prod[:, inds1, inds2] += xv if", ") self._fill_result_tuple( (mxToFill,), evalSubTree, blocks[iBlk], slice(None), calc_and_fill_blk) profiler.mem_check(\"bulk_fill_dprobs: post fill blk\") dProdCache =", "B^T tensor A * vec( E(0,1) ) # In general: vec( A *", "= clip(dGs,-1e300,1e300) _np.seterr(**old_err) if flat: dGs = _np.swapaxes(_np.swapaxes(dGs, 0, 1).reshape( (nDerivCols, nCircuits *", "* dim * dim # hproduct cache mem += cache_size * (wrtLen1 +", "else min(comm_blkSize, blkSize) # override with smaller comm_blkSize else: blkSize = None #", "inds2] += _np.swapaxes(y, 0, 1) # above: dim = (dim2, nDerivCols1, nDerivCols2); #", "dim ) profiler.mem_check(\"bulk_fill_dprobs: post compute product\") def calc_and_fill(spamTuple, fInds, gInds, pslc1, pslc2, sumInto):", "nDerivCols1, nDerivCols2); # swapaxes takes (kl,vec_prod_indx,ij) => (vec_prod_indx,kl,ij) elif l < m: x0", "\" [blkSize = {%.1f,%.1f}, nBlks={%d,%d}]\" % (blkSize1, blkSize2, nBlks1, nBlks2)) # pragma: no", "A^T tensor B^T ) # and using numpy's reshape dim = self.dim uniqueOpLabels", "wrtLen2) # dprobs1 & dprobs2 mem += cache_size * wrtLen1 * wrtLen2 *", "squeeze(dot(dGs, rho),axis=(3,)), dEP)[i,j,J] # d2pr_dEs[:,:,J0+J] = dot( squeeze(dot(dGs, rho),axis=(3,)), dEP)[:,:,J] d2pr_dEs1 = _np.zeros((nCircuits,", "matrices) and derivs[i,j,k,l] holds the derivative of the (k,l)-th entry of the i-th", "# override with smaller comm_blkSize blkSize2 = comm_blkSize if (blkSize2 is None) \\", "nDerivCols1, nDerivCols2); # swapaxes takes (kl,vec_prod_indx,ij) => (vec_prod_indx,kl,ij) else: # l==m, which we", "_compute_dproduct_cache(self, evalTree, prodCache, scaleCache, comm=None, wrtSlice=None, profiler=None): \"\"\" Computes a tree of product", "# parallelize of deriv cols, then sub-trees (if available and necessary) if comm.Get_size()", "0: #Don't return a length-0 list, as this doesn't index numpy arrays #", "B ) = vec( mx w/ col_i = A[col0] * B[0,1] ) =", "self._compute_hproduct_cache(evalSubTree, prodCache, dProdCache1, dProdCache2, scaleCache, mySubComm, wrtSlice1, wrtSlice2) hGs = evalSubTree.final_view(hProdCache, axis=0) #(", "= (gate_ij, prod_row, prod_col) return _np.swapaxes(flattened_dprod, 0, 1).reshape((num_deriv_cols, dim, dim)) def hproduct(self, circuit,", "scale) _np.seterr(**old_err) else: # no scaling -- faster but susceptible to overflow G", "if (wrtFilter2 is not None) else None #TODO: just allow slices as argument:", "1) // np2 # ceiling(num_params / np2) mem = 0 for fnName in", "use of in \" \" _compute_dproduct_cache.\") if mySubComm.Get_rank() > 0: myDerivColSlice = slice(0,", "in \" \" _compute_hproduct_cache.\") #TODO: remove: not needed now that we track owners", "prMxToFill, [], 0, comm) if clipTo is not None and prMxToFill is not", "= ident # product of no gates #Also Cache gate jacobians (still relatively", "== 0 ) #hGs = clip(hGs,-1e300,1e300) _np.seterr(**old_err) if flat: hGs = _np.rollaxis(_np.rollaxis(hGs, 0,", "mySubComm) # Get slice into entire range of model params (see above) if", "parameters, distribution over a split evalTree (if given) is possible. wrtFilter1, wrtFilter2 :", "or blkSize2 blocks1 = _mpit.slice_up_range(self.Np, nBlks1) blocks2 = _mpit.slice_up_range(self.Np, nBlks2) #distribute derivative computation", "If not None, a list of integers specifying which gate parameters to include", "< 1e-8) return ret def dpr(self, spamTuple, circuit, returnPr, clipTo): \"\"\" Compute the", "each inner loop *iteration*!) #collect/gather results subtreeElementIndices = [t.final_element_indices(evalTree) for t in subtrees]", "= evalTree.final_view(prodCache, axis=0) #shape == ( len(circuit_list), dim, dim ), # Gs[i] is", "_np.tensordot(dp_dAnyE, self.sos.get_effect(elabel).hessian_wrt_params( E_wrtFilter1, E_wrtFilter2), (1, 0))) # _np.einsum('ij,jkl->ikl', dp_dAnyE, self.sos.get_effect(elabel).hessian_wrt_params( # E_wrtFilter1, E_wrtFilter2))", "dpr(self, spamTuple, circuit, returnPr, clipTo): \"\"\" Compute the derivative of a probability generated", "hessn_shape) # Use comm to distribute columns allDeriv1ColSlice = slice(0, nDerivCols1) allDeriv2ColSlice =", "0 # SPAM DERIVS (assume dGs1 and dGs2 are already sized/filtered) -------- assert(dGs1.shape[1]", "1, N - 1)])), dop_dopLabel2[opLabel2]) # above: (nDerivCols1,dim**2,dim**2) * (dim**2,nDerivCols2) = (nDerivCols1,dim**2,nDerivCols2) flattened_d2prod[:,", "print \"%d: p = %g, norm %g, exp %g\\n%s\" % (i,p,norm(G),total_exp,str(G)) # if", "dot(dS, T) + dot(S, dT) profiler.add_time(\"compute_dproduct_cache: dots\", tm) profiler.add_count(\"compute_dproduct_cache: dots\") scale = scaleCache[i]", ") ), axis=(0,3)) old_err2 = _np.seterr(invalid='ignore', over='ignore') dp_dOps = _np.squeeze(_np.dot(E, _np.dot(dGs, rho)), axis=(0,", "= scale * _np.transpose(_np.dot(prod, rho)) # may overflow, but OK _fas(dpr_dEs, [0, EVec.gpindices],", "elabels) #shapes: rho = (N,1), Es = (len(elabels),N) if bUseScaling: old_err = _np.seterr(over='ignore')", "to `calc_and_fill_fn` must be the same as the elements of `result_tup`. The fill", "prMxToFill is not None: _mpit.gather_indices(subtreeElementIndices, subTreeOwners, prMxToFill, [], 0, comm) #note: pass prMxToFill,", "`(rowSlice, colSlice, dprobs12)` (the latter if `bReturnDProbs12 == True`). `rowSlice` and `colSlice` are", "hoperation = self.hoperation(opLabel, wrtFilter1=wrtIndices1, wrtFilter2=wrtIndices2) hProdCache[i] = hoperation / _np.exp(scaleCache[i]) #evaluate operation sequences", "(vectorized_op_el_index, model_parameter1, model_parameter2) else: vec_kl_size, vec_ij_size = flattened_d2prod.shape[1:3] # == num_deriv_cols1, num_deriv_cols2 return", "the # gate's parameters and fill appropriate columns of flattened_dprod. #gate = self.sos.get_operation[opLabel]", "only vary in their effect-label (their prep labels must be the same) Parameters", "= scaleValues[i] * prods[i]). \"\"\" prodCache, scaleCache = self._compute_product_cache(evalTree, comm) #use cached data", "i in range(len(self.effects))] # tmp_num_params = [_slct.length(s) for s in loc_e_slices] # tmp_offsets", "caches scaleVals = Gs = prodCache = scaleCache = None #Fill cache info", "self.Np if (wrtFilter2 is None) else len(wrtFilter2) flattened_d2prod = _np.zeros((dim**2, num_deriv_cols1, num_deriv_cols2), 'd')", "the probability itself. clipTo : 2-tuple (min,max) to clip returned probability to if", "desired average size == blkSize blocks = _mpit.slice_up_range(self.Np, nBlks, start=0) # Create placeholder", "gatelabel1} sum_{L s.t. GL == gatelabel2, M < L} # noqa # [", "None else _slct.length(wrtSlice) # GATE DERIVS (assume dGs is already sized/filtered) ------------------- assert(dGs.shape[1]", "for opLabel in reversed(revOpLabelList): G = _np.dot(self.sos.get_operation(opLabel).todense(), G) rightProdsT.append(_np.transpose(G)) # Allocate memory for", "the elements of `elabels`. \"\"\" assert(time is None), \"MatrixForwardSimulator cannot be used to", "to it by the first two arguments), and in general only a specified", "overflow, but OK if infs occur here _np.seterr(**old_err) if bReturnProds: Gs = evalTree.final_view(prodCache,", "= self._process_wrtFilter(wrtFilter2, gate) # Allocate memory for the final result num_deriv_cols1 = self.Np", "_warnings.warn(\"Ignoring tree splitting in hproduct cache calc.\") hProdCache = _np.zeros((cacheSize,) + hessn_shape) #First", "prMxToFill, deriv1MxToFill, mxToFill, clipTo) def bulk_hprobs_by_block(self, evalTree, wrtSlicesList, bReturnDProbs12=False, comm=None): \"\"\" Constructs a", "compute the hessian of the entire # operation sequence with respect to only", "with-respect-to parameter filters, used to # select a subset of all the derivative", "may overflow, but OK dpr_dEs = _np.zeros((1, self.Np)) derivWrtAnyEvec = scale * _np.transpose(_np.dot(prod,", "len( (_np.isnan(hGs)).nonzero()[0] ) == 0 ) #assert( len( (_np.isinf(hGs)).nonzero()[0] ) == 0 )", "E, Gs[gInds], dGs2[gInds], scaleVals[gInds], wrtSlice2), add=sumInto) _fas(mxToFill, [fInds, pslc1, pslc2], self._hprobs_from_rhoE( spamTuple, rho,", "up to nan #G = _np.identity( self.dim ); total_exp = 0.0 #for i,lOp", "CACHE FUNCTIONS def default_distribute_method(self): \"\"\" Return the preferred MPI distribution mode for this", "dim * dim # product cache mem += cache_size # scale cache mem", "* .... * GN , a matrix # noqa # dprod/d(opLabel)_ij = sum_{L", "(i,j) # noqa # vec( dprod/d(opLabel)_ij ) = sum_{L s.t. G(L) == oplabel}", "% # (comm.Get_rank(),\",\".join([str(len(subtrees[i])) # for i in mySubTreeIndices]))) #eval on each local subtree", "shape S x G x G; products[i] is the i-th operation sequence product.", "EVec.deriv_wrt_params(E_wrtFilter2) _fas(d2pr_dEs1, [None, None, E_gpindices2], _np.dot(dp_dAnyE, devec)) # get d2pr_dEs where gate derivatives", "(NTESS). # Under the terms of Contract DE-NA0003525 with NTESS, the U.S. Government", "of the License at # http://www.apache.org/licenses/LICENSE-2.0 or in the LICENSE file in the", "mult by a zero hessian value, and we hGs[_np.isnan(hGs)] = 0 # assume", "Only returned when bReturnProds == True. An array of shape S x G", "# Create placeholder dGs for *no* gate params to compute # derivatives wrt", "may overflow or get nans (invalid), but ok dGs1 = _np.swapaxes(_np.swapaxes(dGs1, 0, 3)", "to compute # derivatives wrt all spam parameters dGs = _np.empty((Gs.shape[0], 0, self.dim,", "# override with smaller comm_blkSize else: blkSize1 = blkSize2 = None # wrtFilter1", "spam label (given by the subsequent arguments, except for the last). The final", "wrtFilter is None: blkSize = wrtBlockSize # could be None if (mySubComm is", "zero hessian value, and we hGs[_np.isnan(hGs)] = 0 # assume the zero hessian", "Compute the derivative of a probability generated by a operation sequence and spam", "gpindices = obj.gpindices_as_array() for ii, i in enumerate(wrtFilter): if i in gpindices: relevant_gpindices.append(ii)", "= \\ _mpit.distribute_slice(allDeriv1ColSlice, comm) # Get slice into entire range of model params", "nDerivCols2) d2pr_dEs2 = _np.transpose(d2pr_dEs1, (0, 2, 1)) else: d2pr_dEs2 = _np.zeros((nCircuits, nDerivCols2, nDerivCols1))", "If not None, a list of integers specifying which model parameters to differentiate", "# GATE DERIVS (assume dGs is already sized/filtered) ------------------- assert(dGs.shape[1] == nDerivCols), \"dGs", "_fas(d2pr_dEs2, [None, None, E_gpindices1], _np.dot(dp_dAnyE, devec)) d2pr_dEs2 = _np.transpose(d2pr_dEs2, (0, 2, 1)) #", "are the outputs of :func:`bulk_fill_hprobs` (i.e. args `mxToFill`, `deriv1MxToFill`, and `deriv1MxToFill`), then: -", "scaleValues[i] * prods[i]). \"\"\" prodCache, scaleCache = self._compute_product_cache(evalTree, comm) #use cached data to", "wrtSlice1.start is not None: myHessianSlice1 = _slct.shift(myDeriv1ColSlice, wrtSlice1.start) else: myHessianSlice1 = myDeriv1ColSlice #print(\"MPI:", "noqa # [ G1 ... G(M-1) dG(M)/dkl G(M+1) ... G(L-1) dG(L)/dij G(L+1) ...", "be done efficiently by actually computing X^T ( note (A tensor B)^T =", "vectors) access to these fundamental operations. \"\"\" def __init__(self, dim, simplified_op_server, paramvec): \"\"\"", "= _np.array( [ self.pr( (rholabel,elabel), circuit, clipTo, bScale) for elabel in elabels ])", "ndarray an already-allocated ExM numpy array where E is the total number of", "_np.swapaxes(flattened_dprod, 0, 1).reshape((num_deriv_cols, dim, dim)) def hoperation(self, opLabel, flat=False, wrtFilter1=None, wrtFilter2=None): \"\"\" Return", "= _np.concatenate( [self.hpr(spamTuple, circuit, False, False, clipTo) for circuit in circuit_list], axis=0) if", "GxG ; dL,dR = vgs x GxG ; hL,hR = vgs x vgs", "wrtLen2 * dim * dim # hproduct cache mem += cache_size * (wrtLen1", "wrtSlice2 = _slct.list_to_slice(wrtFilter2) else: wrtSlice2 = None #get distribution across subtrees (groups if", "G = H old_err = _np.seterr(over='ignore') scale = _np.exp(scale_exp) _np.seterr(**old_err) return G, scale", "no memory savings from using a split tree. In short, parallelization should be", ") == 0 ) #assert( len( (_np.isinf(hGs)).nonzero()[0] ) == 0 ) #hGs =", "# further parallelization tm = _time.time() all_results = comm.allgather(my_results) profiler.add_time(\"MPI IPC\", tm) return", "blocks myBlk1Indices, blk1Owners, blk1Comm = \\ _mpit.distribute_indices(list(range(nBlks1)), mySubComm) myBlk2Indices, blk2Owners, blk2Comm = \\", "1, m - 1)]), prods[(m + 1, N - 1)]) # (dim**2, dim**2)", "so gather mxToFill[felslc] (axis=0) if clipTo is not None: _np.clip(mxToFill, clipTo[0], clipTo[1], out=mxToFill)", "clipTo, bUseScaling=False, time=None): \"\"\" Compute probabilities of a multiple \"outcomes\" (spam-tuples) for a", "True, additionally return the probability itself. clipTo : 2-tuple (min,max) to clip returned", "self.sos.get_effect(elabel)) nDerivCols = self.Np if wrtSlice is None else _slct.length(wrtSlice) # GATE DERIVS", "dprobs12 else: yield wrtSlice1, wrtSlice2, hprobs dProdCache1 = dGs1 = None # free", "name: %s\" % fnName) return mem * FLOATSIZE def bulk_product(self, evalTree, bScale=False, comm=None):", "fills a 1D array, `mxToFill` with the probabilities corresponding to the *simplified* operation", "bScale: scaledGatesAndExps = {} scale_exp = 0 G = _np.identity(self.dim) for lOp in", "x0); xv = x.view() # (nDerivCols1,dim**2) xv.shape = (nDerivCols1, dim, dim) # (reshape", "list, as this doesn't index numpy arrays # like length>1 lists do... ugh.", "clipTo : 2-tuple (min,max) to clip returned probability to if not None. Only", "processors than model parameters, distribution over a split evalTree (if given) is possible.", "operation sequence product with respect to the k-th then j-th model parameters. derivs1,", "or wrtFilter1 or 2, respectively - G == the linear dimension of a", "a subset of all the derivative columns, essentially taking # a derivative of", "x G operation matrices) and derivs[i,j,k,l] holds the derivative of the (k,l)-th entry", "# dprod/d(opLabel)_ij = sum_{L s.t. G(L) == oplabel} [ G1 ... G(L-1) dG(L)/dij", "available processors if it isn't specified if wrtFilter1 is None and wrtFilter2 is", "num_deriv_cols2), 'd') if _slct.length(gpindices1) > 0 and _slct.length(gpindices2) > 0: # works for", "be the same as the elements of `result_tup`. The fill function computes values", "== 0 ) #assert( len( (_np.isinf(hGs)).nonzero()[0] ) == 0 ) #hGs = clip(hGs,-1e300,1e300)", "last). The final argument is a boolean specifying whether the filling should overwrite", "terms are always zero _np.seterr(**old_err) if returnDeriv: if returnPr: return ret, dpr, p", "sum_{L s.t. G(L) == oplabel} [ (G1 ... G(L-1)) tensor (G(L+1) ... GN)^T", "something else LATER. def calc_and_fill(spamTuple, fInds, gInds, pslc1, pslc2, sumInto): \"\"\" Compute and", "of computed elements (i.e. evalTree.num_final_elements()) and M1 & M2 are the number of", "scaleCache[iLeft] + scaleCache[iRight] if prodCache[i].max() < PSMALL and prodCache[i].min() > -PSMALL: nL, nR", "derivWrtAnyEvec = _np.squeeze(_np.dot(dprod_dOps, rho), axis=(2,)) _fas(d2pr_dEs, [0, None, EVec.gpindices], _np.dot(derivWrtAnyEvec, EVec.deriv_wrt_params())) d2pr_dErhos =", "products\" % (cnt, len(evalTree)) nanOrInfCacheIndices = (~_np.isfinite(prodCache)).nonzero()[0] # may be duplicates (a list,", "parallelize computation, since there are no memory savings from using a split tree.", "#If there are more processors than deriv cells, give a # warning --", "if (blkSize1 is None) \\ else min(comm_blkSize, blkSize1) # override with smaller comm_blkSize", "up the calcs of the given # wrtSlicesList last_wrtSlice1 = None # keep", "self._compute_dproduct_cache(evalTree, prodCache, scaleCache, comm, wrtSlice2) hProdCache = self._compute_hproduct_cache(evalTree, prodCache, dProdCache1, dProdCache2, scaleCache, comm,", "previous subtree iteration before computing caches scaleVals = Gs = dGs = None", "== nan\" % strToPrint) #DEBUG: print \"backtrace\" of product leading up to nan", "G x G, where - S == len(circuit_list) - M == the number", "for (i, opLabel1) in enumerate(revOpLabelList): # loop over \"starting\" gate prods[(i, i -", "into an array of gate parameters ordered by concatenating each gate's parameters (in", "self._compute_dproduct_cache(evalSubTree, prodCache, scaleCache, blkComm, block_wrtSlice, profiler) profiler.add_time(\"bulk_fill_dprobs: compute_dproduct_cache\", tm) profiler.mem_check( \"bulk_fill_dprobs: post compute", "fnName == \"bulk_hproduct\": # mem += cache_size * num_params**2 * dim * dim", "`wrtSlicesList`. `rowSlice` and `colSlice` must by Python `slice` objects. bReturnDProbs12 : boolean, optional", "= _DummyProfiler() # Smallness tolerances, used internally for conditional scaling required # to", "not None and mySubComm.Get_size() > 1: _warnings.warn(\"Too many processors to make use of", "tm = _time.time() block_wrtSlice = blocks[iBlk] dProdCache = self._compute_dproduct_cache(evalSubTree, prodCache, scaleCache, blkComm, block_wrtSlice,", "cols = deriv cols, rows = flattened all else dGs2 = _np.swapaxes(_np.swapaxes(dGs2, 0,", "is None: blkSize1 = wrtBlockSize1 # could be None blkSize2 = wrtBlockSize2 #", "the entire operation sequence # with respect to only that gate's parameters and", "check_vp) > 1e-6: _warnings.warn(\"norm(vp-check_vp) = %g - %g = %g\" % (_nla.norm(prMxToFill[fInds]), _nla.norm(check_vp),", "MATRIX ORDER return G def _process_wrtFilter(self, wrtFilter, obj): \"\"\" Helper function for doperation", "numpy.flatten) - M == length of the vectorized model (number of model parameters)", "evalTree.num_final_elements()) and M is the number of model parameters. evalTree : EvalTree given", "ndarray The parameter vector of the Model. autogator : AutoGator An auto-gator object", "[ G1 ... G(L-1) dG(L)/dij G(L+1) ... GN ] , a matrix for", "rholabel, elabel = spamTuple rho, E = self._rhoE_from_spamTuple(spamTuple) rhoVec = self.sos.get_prep(rholabel) # distinct", "like length>1 lists do... ugh. relevant_gpindices = slice(relevant_gpindices[0], relevant_gpindices[0] + 1) elif len(relevant_gpindices)", "from using a split tree. \"\"\" if profiler is None: profiler = _dummy_profiler", "- update probability-derivative computations: dpr/dx -> d|pr|^2/dx = d(pr*pr.C)/dx = dpr/dx*pr.C + pr*dpr/dx.C", "x G x G, where: - S == len(circuit_list) - M == the", "_np.swapaxes(_np.swapaxes(dGs1, 0, 3) * scaleVals, 0, 3) # may overflow or get nans", "call to bulk_evaltree. Specifies the operation sequences to compute the bulk operation on.", "is split), and then over blocks (subsets) of the parameters being differentiated with", "these fundamental operations. \"\"\" def __init__(self, dim, simplified_op_server, paramvec): \"\"\" Construct a new", "E_wrtFilter2, E_gpindices2 = self._process_wrtFilter(wrtSlice2, self.sos.get_effect(elabel)) nDerivCols1 = self.Np if wrtSlice1 is None else", "'d') def calc_and_fill_p(spamTuple, fInds, gInds, pslc1, pslc2, sumInto): \"\"\" Compute and fill result", "#evaluate operation sequences using tree (skip over the zero and single-gate-strings) for i", "probability derivatives, similar to bulk_fill_dprobs(...), but where M is the number of model", "to reduce amount of intermediate memory required. profiler : Profiler, optional A profiler", "# vec( A * E(0,1) * B ) = vec( mx w/ row_i", "comm, gatherMemLimit) if prMxToFill is not None: _mpit.gather_indices(subtreeElementIndices, subTreeOwners, prMxToFill, [], 0, comm)", "= None if wrtFilter2 is not None: assert(wrtBlockSize1 is None and wrtBlockSize2 is", "if gate.has_nonzero_hessian(): hop_dopLabels[opLabel] = gate.hessian_wrt_params( gate_wrtFilters1[opLabel], gate_wrtFilters2[opLabel]) # Allocate memory for the final", ") = sum E_k prod_kl rho_l # d2pr/d(opLabel1)_mn d(opLabel2)_ij = sum E_k [dprod/d(opLabel1)_mn", "(i,j,k,l) # noqa # vec( d2prod/d(opLabel1)_kl*d(opLabel2)_ij ) = sum{...} [ G1 ... G(M-1)", "post compute dproduct\") #Compute all requested derivative columns at once self._fill_result_tuple((prMxToFill, mxToFill), evalSubTree,", "OK d2pr_d2rhos = _np.zeros((1, self.Np, self.Np)) _fas(d2pr_d2rhos, [0, self.sos.get_prep(rholabel).gpindices, self.sos.get_prep(rholabel).gpindices], _np.tensordot(derivWrtAnyRhovec, self.sos.get_prep(rholabel).hessian_wrt_params(), (1,", "_np.dot(self.sos.get_operation(lOp).todense(), G) # LEXICOGRAPHICAL VS MATRIX ORDER return G def _process_wrtFilter(self, wrtFilter, obj):", "matrix of parameters, then dG(L)/dij = E(i,j), an elementary matrix dim = self.dim", "on. This tree *cannot* be split. wrtSlicesList : list A list of `(rowSlice,colSlice)`", "slice): wrtFilter = _slct.indices(wrtFilter) if wrtFilter is not None: obj_wrtFilter = [] #", "= None prodCache = scaleCache = dProdCache = None #Fill cache info (not", "return evTree def estimate_mem_usage(self, subcalls, cache_size, num_subtrees, num_subtree_proc_groups, num_param1_groups, num_param2_groups, num_final_strs): \"\"\" Estimate", "scaleVals = self._scaleExp(evalSubTree.final_view(scaleCache)) Gs = evalSubTree.final_view(prodCache, axis=0) #( nCircuits, dim, dim ) def", "in enumerate(revOpLabelList): if gl != opLabel: continue # loop over locations of opLabel", "circuit, False, False, clipTo) for circuit in circuit_list], axis=0) if _nla.norm(hprMxToFill[fInds][0] - check_vhp[0])", "spamTuple, rho, E, Gs[gInds], dGs[gInds], scaleVals[gInds], block_wrtSlice), add=sumInto) _np.seterr(**old_err) profiler.add_time(\"bulk_fill_dprobs: calc_and_fill_blk\", tm) for", "deriv2MxToFill gets computed on every inner loop completion # (to save mem) but", "cover # allocate final result memory hProdCache = _np.zeros((cacheSize,) + hessn_shape) # Use", "myDerivColSlice = slice(0, 0) #don't compute anything on \"extra\", i.e. rank != 0,", "rho)), axis=(0,2) ) * scaleVals return _np.squeeze(_np.dot(E, _np.dot(Gs, rho)), axis=(0, 2)) * scaleVals", "communicator for distributing the computation across multiple processors. Distribution is first performed over", "LATER. def calc_and_fill(spamTuple, fInds, gInds, pslc1, pslc2, sumInto): \"\"\" Compute and fill result", "a list of integers specifying which gate parameters to include in the derivative.", "= self._compute_hproduct_cache( evalTree, prodCache, dProdCache1, dProdCache2, scaleCache, comm, wrtSlice1, wrtSlice2) hGs = evalTree.final_view(hProdCache,", "of operation labels. bScale : bool, optional When True, return a scaling factor", "global_e_slices = [ slice(tmp_offsets[i],tmp_offsets[i+1]) # for i in range(len(self.effects)) ] # # return", "self._probs_from_rhoE(rho, E, Gs[gInds], scaleVals[gInds]), add=sumInto) _np.seterr(**old_err) profiler.add_time(\"bulk_fill_dprobs: calc_and_fill_p\", tm) # Compute all probabilities", "(see above) if wrtSlice2 is not None and wrtSlice2.start is not None: myHessianSlice2", "gate.hessian_wrt_params( gate_wrtFilters1[opLabel], gate_wrtFilters2[opLabel]) # Allocate memory for the final result num_deriv_cols1 = self.Np", "); total_exp = 0.0 #for i,lOp in enumerate(gateLabelList): # G = _np.dot(G,self[lOp]) #", "cols (rank %d computing %s)\" \\ # % (nDerivCols2, comm.Get_rank(), str(myDerivColSlice))) if mySubComm", "mem += cache_size # scale vals elif fnName == \"bulk_fill_hprobs\": mem += cache_size", "used_operations = _collections.OrderedDict() #Cache processed parameter filters for multiple uses below gpindices1 =", "#Fill cache info prodCache, scaleCache = self._compute_product_cache(evalSubTree, mySubComm) #use cached data to final", "of the entire operation sequence with respect to the # gate's parameters and", "is not None: _mpit.gather_indices(subtreeElementIndices, subTreeOwners, prMxToFill, [], 0, comm) #note: pass prMxToFill, dim=(KS,),", "clipTo, False)[0] for circuit in circuit_list]) if _nla.norm(prMxToFill[fInds] - check_vp) > 1e-6: _warnings.warn(\"norm(vp-check_vp)", "cache_size * (wrtLen1 + wrtLen2) * dim * dim # dproduct cache mem", "mem += cache_size * (wrtLen1 + wrtLen2) * dim * dim # dproduct", "derivative columns at once self._fill_result_tuple((prMxToFill, deriv1MxToFill, deriv2MxToFill, mxToFill), evalSubTree, slice(None), slice(None), calc_and_fill) else:", "= [slice(None,None)]*len(self.effects) # global_rho_slices = [slice(self.rho_offset[i],self.rho_offset[i+1]) for i in range(len(self.preps)) ] # global_e_slices", "sum_k,l E[0,k] Gs[i,k,l] rho[l,0] * scaleVals[i] # vp[i] = sum_k E[0,k] dot(Gs, rho)[i,k,0]", "rho_global_slices ' + # 'e_local_slices e_global_slices num_rho_params num_e_params') # # if wrtSlices is", "appropriate block of flattened_d2prod. #NOTE: if we needed to perform a hessian calculation", "ii, i in enumerate(wrtFilter): if i in gpindices: relevant_gpindices.append(ii) obj_wrtFilter.append(list(gpindices).index(i)) relevant_gpindices = _np.array(relevant_gpindices,", "cannot specify both wrtFilter and blkSize nBlks1 = int(_np.ceil(self.Np / blkSize1)) nBlks2 =", "list of (general) :class:`Circuit` objects is *simplified* into a lists of gate-only sequences", "gradients, and their Hessians. PSMALL = 1e-100 DSMALL = 1e-100 HSMALL = 1e-100", "dim ) def calc_and_fill(spamTuple, fInds, gInds, pslc1, pslc2, sumInto): \"\"\" Compute and fill", "self._compute_hproduct_cache( evalSubTree, prodCache, dProdCache1, dProdCache2, scaleCache, blk2Comm, blk_wrtSlice1, blk_wrtSlice2) hGs = evalSubTree.final_view(hProdCache, axis=0)", "before computing caches scaleVals = Gs = prodCache = scaleCache = None #Fill", "= scaleCache[i] - (scaleCache[iLeft] + scaleCache[iRight]) if abs(scale) > 1e-8: # _np.isclose(scale,0) is", "d2pr_d2Es = 0 # END SPAM DERIVS ----------------------- ret = d2pr_d2rhos + d2pr_dErhos2", "1e-8: # _np.isclose(scale,0) is SLOW! dProdCache[i] /= _np.exp(scale) if dProdCache[i].max() < DSMALL and", "nspam * (wrtLen1 + wrtLen2) # dprobs1 & dprobs2 mem += cache_size *", "_np.swapaxes(flattened_dprod, 0, 1).reshape((num_deriv_cols, dim, dim)) def hproduct(self, circuit, flat=False, wrtFilter1=None, wrtFilter2=None): \"\"\" Compute", "# cols = deriv cols, rows = all else return (hGs, dGs1, dGs2,", "prodCache, scaleCache, comm, wrtSlice2) dGs2 = evalTree.final_view(dProdCache2, axis=0) hProdCache = self._compute_hproduct_cache( evalTree, prodCache,", "= _np.identity( self.dim ); total_exp = 0.0 #for i,lOp in enumerate(gateLabelList): # G", "invalid='ignore') Gs = _np.swapaxes(_np.swapaxes(Gs, 0, 2) * scaleVals, 0, 2) # may overflow,", "E(i,j), an elementary matrix dim = self.dim #Cache partial products (relatively little mem", "true IF each operation matrix element # is at most *linear* in each", "The number of groups to divide the first-derivative parameters into. Computation will be", "prMxToFill is not None: _mpit.gather_indices(subtreeElementIndices, subTreeOwners, prMxToFill, [], 0, comm) if clipTo is", "but ok hGs = _np.swapaxes(_np.swapaxes(hGs, 0, 4) * scaleVals, 0, 4) # convert", "operation matrix (G x G operation matrices). and deriv[i,j,k] holds the derivative of", "Compute the products of many operation sequences at once. Parameters ---------- evalTree :", ") if not bScale: old_err = _np.seterr(over='ignore', invalid='ignore') # may overflow or get", "product internally. If False, this routine will run slightly faster, but with a", "only those two gates' parameters and fill # add the result to the", "_np.swapaxes(_np.swapaxes(dGs, 0, 3) * scaleVals, 0, 3) # convert nans to zero, as", "bulk_dproduct, and bulk_hproduct. Returns ------- block_generator A generator which, when iterated, yields the", "None #TODO: just allow slices as argument: wrtFilter -> wrtSlice? prodCache, scaleCache =", "construction by giving the tree information it needs to distribute itself among the", "sequences. This routine fills in `mxToFill`, which must have length equal to the", "dot( E, dot( dGs, rho ) )[0,i,j,k,0] # d2pr_dOps2 = squeeze( dot( E,", "prod_il rho_l rholabel, elabel = spamTuple # can't deal w/\"custom\" spam label... rho,", "profiler.mem_check(\"bulk_fill_dprobs: begin (expect ~ %.2fGB)\" % (mxToFill.nbytes / (1024.0**3))) ## memory profiling of", "vec( dG(L)/dij ) ] # noqa # = sum{...} [ unvec( G1 ...", "= sum_{L s.t. G(L) == oplabel} [ (G1 ... G(L-1)) tensor (G(L+1) ...", "do... ugh. relevant_gpindices = slice(relevant_gpindices[0], relevant_gpindices[0] + 1) elif len(relevant_gpindices) == 0: #Don't", "if (wrtFilter is None) else _slct.length(wrtFilter) dim = self.dim wrtSlice = _slct.list_to_slice(wrtFilter) if", "UNNEEDED (I think) _fas(flattened_dprod, [None, gpindices], gate.deriv_wrt_params(op_wrtFilter)) # (dim**2, nParams in wrtFilter for", "... G(M-1) dG(M)/dkl G(M+1) ... G(L-1) dG(L)/dij G(L+1) ... GN ] + {similar", "than linear dependence on their parameters. if self.sos.get_prep(rholabel).has_nonzero_hessian(): derivWrtAnyRhovec = scale * _np.dot(E,", "there\" \" are more cpus than derivative columns.\") # Use comm to distribute", "(nDerivCols1, nDerivCols2, nCircuits * dim**2)), 2) # as above return (hGs, scaleVals) if", "prodCache, dProdCache1, dProdCache2, scaleCache, blk2Comm, blk_wrtSlice1, blk_wrtSlice2) hGs = evalSubTree.final_view(hProdCache, axis=0) #Set filtering", "True. A length-S array specifying the scaling that needs to be applied to", "# # if wrtSlices is not None: # loc_rho_slices = [ # _slct.shift(_slct.intersect(", "*cannot* be split. wrtSlicesList : list A list of `(rowSlice,colSlice)` 2-tuples, each of", "nDerivCols) return dProdCache def _compute_hproduct_cache(self, evalTree, prodCache, dProdCache1, dProdCache2, scaleCache, comm=None, wrtSlice1=None, wrtSlice2=None):", "file in the root pyGSTi directory. #*************************************************************************************************** import warnings as _warnings import numpy", "# scale cache mem += cache_size # scale vals elif fnName == \"bulk_fill_hprobs\":", ") * scaleVals return _np.squeeze(_np.dot(E, _np.dot(Gs, rho)), axis=(0, 2)) * scaleVals # shape", "= 0 G = _np.identity(self.dim) for lOp in circuit: if lOp not in", "when needed) a split tree to parallelize computation, since there are no memory", "we tried to allow for parallelization of # _compute_product_cache when the tree was", "(ordering as numpy.flatten) - M == length of the vectorized model (number of", "self._compute_dproduct_cache(evalTree, prodCache, scaleCache, comm, wrtSlice1) dProdCache2 = dProdCache1 if (wrtSlice1 == wrtSlice2) else", "= evalSubTree.final_view(dProdCache, axis=0) #( nCircuits, nDerivCols, dim, dim ) self._fill_result_tuple( (mxToFill,), evalSubTree, blocks[iBlk],", "= blocks2[iBlk2] if blk_wrtSlice1 == blk_wrtSlice2: dProdCache2 = dProdCache1; dGs2 = dGs1 else:", "needed) subtrees = evalTree.get_sub_trees() mySubTreeIndices, subTreeOwners, mySubComm = evalTree.distribute(comm) #if comm is not", "# scale vals # #elif fnName == \"bulk_hproduct\": # mem += cache_size *", "_slct.length(wrtSlice2)), 'd') else: dprobs1 = dprobs2 = None hprobs = _np.zeros((nElements, _slct.length(wrtSlice1), _slct.length(wrtSlice2)),", "DummyProfiler as _DummyProfiler from .label import Label as _Label from .matrixevaltree import MatrixEvalTree", "... G(M-1) dG(M)/dkl G(M+1) ... G(L-1) tensor (G(L+1) ... GN)^T vec( dG(L)/dij )", "dGs, rho ) ), axis=(0,4)) old_err2 = _np.seterr(invalid='ignore', over='ignore') d2pr_dOps2 = _np.squeeze(_np.dot(E, _np.dot(hGs,", "the *second* derivative is taken. If there are more processors than model parameters,", "and wrtBlockSize wrtSlice2 = _slct.list_to_slice(wrtFilter2) else: wrtSlice2 = None #get distribution across subtrees", "if self.evotype == \"statevec\": ps = _np.real(_np.abs(_np.dot(Es, _np.dot(G, rho)) * scale)**2) else: #", "= sum E_k [dprod/d(opLabel)_mn]_ki (and same for other diff order) # d2pr/d(E)_i d(opLabel)_mn", "_np.dot(E, prod) _fas(dpr_drhos, [0, self.sos.get_prep(rholabel).gpindices], _np.dot(derivWrtAnyRhovec, rhoVec.deriv_wrt_params())) # may overflow, but OK dpr_dEs", "p = _mt.trace( _np.dot(self.SPAMs[spamLabel],G) ) * exp(total_exp) # probability # print \"%d: p", "# dGs[i] is dprod_dOps for ith string hGs = evalTree.final_view(hProdCache, axis=0) #shape ==", "(1, 0))) # _np.einsum('ij,jkl->ikl', dp_dAnyRho, self.sos.get_prep(rholabel).hessian_wrt_params( # rho_wrtFilter1, rho_wrtFilter2)) else: d2pr_d2rhos = 0", "root pyGSTi directory. #*************************************************************************************************** import warnings as _warnings import numpy as _np import", "in dproduct cache calc.\") dProdCache = _np.zeros((cacheSize,) + deriv_shape) # This iteration **must**", "% (cnt, len(evalTree)) nanOrInfCacheIndices = (~_np.isfinite(prodCache)).nonzero()[0] # may be duplicates (a list, not", "in FUTURE) # pr = Tr( |rho><E| * prod ) = sum E_k", "length equal to the number of final elements (this can be obtained by", "probability. circuit : Circuit or tuple A tuple-like object of *simplified* gates (e.g.", "= _mpit.slice_up_range(self.Np, nBlks, start=0) # Create placeholder dGs for *no* gate params to", "that in bulk_evaltree # in order to associate the right single-gate-strings w/indices wrtIndices", "is to allow a trace or other linear operation to be done prior", "processors. Distribution is first performed over subtrees of evalTree (if it is split),", "= sum{...} [ G1 ... G(M-1) dG(M)/dkl G(M+1) ... G(L-1) tensor (G(L+1) ...", "specify both wrtFilter and wrtBlockSize wrtSlice1 = _slct.list_to_slice(wrtFilter1) else: wrtSlice1 = None if", "vals elif fnName == \"bulk_hprobs_by_block\": #Note: includes \"results\" memory since this is allocated", "% (blkSize, nBlks)) # pragma: no cover def calc_and_fill_blk(spamTuple, fInds, gInds, pslc1, pslc2,", "0 ) #hGs = clip(hGs,-1e300,1e300) _np.seterr(**old_err) if flat: hGs = _np.rollaxis(_np.rollaxis(hGs, 0, 3).reshape(", "_dprobs_from_rhoE(self, spamTuple, rho, E, Gs, dGs, scaleVals, wrtSlice=None): if self.evotype == \"statevec\": raise", "for given arguments \"\"\" old_err = _np.seterr(over='ignore') rho, E = self._rhoE_from_spamTuple(spamTuple) _fas(mxToFill, [fInds],", "required) prods = {} ident = _np.identity(dim) for (i, opLabel1) in enumerate(revOpLabelList): #", "(invalid), but ok dGs1 = _np.swapaxes(_np.swapaxes(dGs1, 0, 3) * scaleVals, 0, 3) #", "just allow slices as argument: wrtFilter -> wrtSlice? prodCache, scaleCache = self._compute_product_cache(evalTree, comm)", "M x M where - N == the number of entries in a", "else dGs def bulk_hproduct(self, evalTree, flat=False, bReturnDProdsAndProds=False, bScale=False, comm=None, wrtFilter1=None, wrtFilter2=None): \"\"\" Return", "(N,1) rho = self.sos.get_prep(rholabel).todense()[:, None] Es = [self.sos.get_effect(elabel).todense()[:, None] for elabel in elabels]", "bulk_fill_probs(...). clipTo : 2-tuple, optional (min,max) to clip return value if not None.", "the parameters assert(opLabel1 == opLabel2) if opLabel1 in hop_dopLabels: # indicates a non-zero", "-PSMALL: nL, nR = max(_nla.norm(L), _np.exp(-scaleCache[iLeft]), 1e-300), max(_nla.norm(R), _np.exp(-scaleCache[iRight]), 1e-300) sL, sR =", "(iRight, iLeft) = evalTree[i] L, R = prodCache[iLeft], prodCache[iRight] dL, dR = dProdCache[iLeft],", "of gate parameters if dGs1 is dGs2 and wrtSlice1 == wrtSlice2: # TODO:", "else: #doperation = self.dproduct( (opLabel,) , wrtFilter=wrtIndices) doperation = self.doperation(opLabel, wrtFilter=wrtIndices) dProdCache[i] =", "nDerivCols: #If there are more processors than deriv cols, give a # warning", "E_k prod_kl rho_l # d2pr/d(opLabel1)_mn d(opLabel2)_ij = sum E_k [dprod/d(opLabel1)_mn d(opLabel2)_ij]_kl rho_l #", "= self._compute_product_cache(evalTree, comm) dProdCache1 = self._compute_dproduct_cache(evalTree, prodCache, scaleCache, comm, wrtSlice1) dProdCache2 = dProdCache1", "d2pr_dEs where gate derivatives are wrt the 2nd set of gate parameters if", "[self.dpr(spamTuple, circuit, False, clipTo) for circuit in circuit_list], axis=0) if _nla.norm(dprMxToFill[fInds] - check_vdp)", "rho_l (and same for other diff order) # d2pr/d(E)_i d(rho)_j = prod_ij (and", "d2pr_dEs = _np.zeros((1, self.Np, self.Np)) derivWrtAnyEvec = _np.squeeze(_np.dot(dprod_dOps, rho), axis=(2,)) _fas(d2pr_dEs, [0, None,", "gpindices1, gpindices2], gate.hessian_wrt_params(op_wrtFilter1, op_wrtFilter2)) if flat: return flattened_hprod else: return _np.transpose(flattened_hprod, (1, 2,", "probability generated by the sequence and spam label indexed by iOpStr and iSpamLabel.", "are no memory savings from using a split tree. \"\"\" if profiler is", "to include in the derivative dimension. This argument is used internally for distributing", "= evalTree[i] L, R = prodCache[iLeft], prodCache[iRight] dL1, dR1 = dProdCache1[iLeft], dProdCache1[iRight] dL2,", "evalTree, wrtSlicesList, bReturnDProbs12=False, comm=None): \"\"\" Constructs a generator that computes the 2nd derivatives", "_warnings.warn(\"Scaled hProd small in order to keep prod managable.\") elif _np.count_nonzero(hProdCache[i]) and hProdCache[i].max()", "here _np.seterr(**old_err) if bReturnDProdsAndProds: Gs = evalTree.final_view(prodCache, axis=0) #shape == ( len(circuit_list), dim,", "reduce results from a single column of the Hessian at a time. For", "str(myDerivColIndices))) if mySubComm is not None and mySubComm.Get_size() > 1: _warnings.warn(\"Too many processors", "> 1: # parallelize of deriv cols, then sub-trees (if available and necessary)", "] # noqa # + sum{ L < M} [ G1 ... G(L-1)", "-> wrtSlice? prodCache, scaleCache = self._compute_product_cache(evalTree, comm) dProdCache1 = self._compute_dproduct_cache(evalTree, prodCache, scaleCache, comm,", "to subtrees of the created tree. This aids in the tree construction by", "0, 3) # may overflow or get nans (invalid), but ok hGs =", "= max(_nla.norm(L), _np.exp(-scaleCache[iLeft]), 1e-300), max(_nla.norm(R), _np.exp(-scaleCache[iRight]), 1e-300) sL, sR = L / nL,", "(i.e. evalTree.num_final_elements()) and M is the number of model parameters. evalTree : EvalTree", "self._fill_result_tuple((prMxToFill, mxToFill), evalSubTree, slice(None), slice(None), calc_and_fill) profiler.mem_check(\"bulk_fill_dprobs: post fill\") dProdCache = dGs =", "returnPr: return ret, dpr, p else: return ret, dpr else: if returnPr: return", "there are more processors than deriv cells, give a # warning -- note", "not alter scaleCache.\") #profiler.print_mem(\"DEBUGMEM: POINT2\"); profiler.comm.barrier() profiler.add_time(\"compute_dproduct_cache: serial\", tSerialStart) profiler.add_count(\"compute_dproduct_cache: num columns\", nDerivCols)", "not None) else None wrtIndices2 = _slct.indices(wrtSlice2) if (wrtSlice2 is not None) else", "all the gate's parameters if isinstance(wrtFilter, slice): wrtFilter = _slct.indices(wrtFilter) if wrtFilter is", "to differentiate with respect to in the first (row) and second (col) derivative", "= self._process_wrtFilter(wrtFilter2, used_operations[l]) #Cache partial products (relatively little mem required) prods = {}", "= _np.kron(_np.transpose(prods[(l + 1, m - 1)]), prods[(m + 1, N - 1)])", "np1) wrtLen2 = (self.Np + np2 - 1) // np2 # ceiling(num_params /", "compute the bulk operation on. bScale : bool, optional When True, return a", "to the functions named by `subcalls`. num_subtrees : int The number of subtrees", "used as the final block size. This argument must be None if wrtFilter", "_np.zeros((nCircuits, nDerivCols1, nDerivCols2)) _fas(d2pr_d2Es, [None, E_gpindices1, E_gpindices2], _np.tensordot(dp_dAnyE, self.sos.get_effect(elabel).hessian_wrt_params( E_wrtFilter1, E_wrtFilter2), (1, 0)))", "specifying whether the filling should overwrite or add to the existing array values,", "self.sos.get_effect(elabel) # arrays, these are SPAMVecs #Derivs wrt Gates old_err = _np.seterr(over='ignore') prod,", "not self.sos.get_operation(opLabel).has_nonzero_hessian(): #all gate elements are at most linear in params, so #", "nDerivCols2 = self.Np if (wrtFilter2 is None) else _slct.length(wrtFilter2) nCircuits = evalTree.num_final_strings() #", "wrtSlice1) dProdCache2 = dProdCache1 if (wrtSlice1 == wrtSlice2) else \\ self._compute_dproduct_cache(evalTree, prodCache, scaleCache,", "prods[(i, i - 1)] = ident # product of no gates G =", "= _np.swapaxes(_np.swapaxes(Gs, 0, 2) * scaleVals, 0, 2) # may overflow, but ok", "differentiate with respect to in the first (row) and second (col) derivative operations,", "# dp_dEs[i,J0+J] = sum_lj dEPT[J,j] Gs[i,j,l] rho[l,0] # dp_dEs[i,J0+J] = sum_j dEP[j,J] dot(Gs,", "A * vec( X ) def doperation(self, opLabel, flat=False, wrtFilter=None): \"\"\" Return the", "circuit, flat=False, wrtFilter1=None, wrtFilter2=None): \"\"\" Compute the hessian of a specified sequence of", "in loc_rho_slices] # tmp_offsets = [ sum(tmp_num_params[0:i]) for i in range(len(self.preps)+1) ] #", "rho),axis=(3,)), dEP)[:,:,J] d2pr_dEs1 = _np.zeros((nCircuits, nDerivCols1, nDerivCols2)) dp_dAnyE = _np.squeeze(_np.dot(dGs1, rho), axis=(3,)) *", "derivative operations, respectively. wrtBlockSize2, wrtBlockSize2 : int or float, optional The maximum number", "\"\"\" Encapsulates a calculation tool used by model objects to perform product and", "track of exponent if H.max() < PSMALL and H.min() > -PSMALL: nG =", "= spamTuple rho, E = self._rhoE_from_spamTuple(spamTuple) rhoVec = self.sos.get_prep(rholabel) # distinct from rho,E", "parallelization should be done at a higher level. \"\"\" dim = self.dim #Note:", "None] _np.seterr(**old_err2) # may overflow, but OK ; shape == (len(circuit_list), nDerivCols) #", "(0, 2, 1)) # Get: d2pr_dErhos[i, e_offset[eIndex]:e_offset[eIndex+1], e_offset[rhoIndex]:e_offset[rhoIndex+1]] = # dEP^T * prod[i,:,:]", "same as that used by numpy.flatten), - S,M == as above, and deriv[i,j]", "prMxToFill is not None. Returns ------- hessian : numpy array a 1 x", "M array, where M is the number of model parameters. Parameters ---------- spamTuple", "rho = self.sos.get_prep(rholabel).todense()[:, None] E = _np.conjugate(_np.transpose(self.sos.get_effect(elabel).todense() [:, None])) # convention: E has", "(and same for other diff order) # d2pr/d(E)_i d(rho)_j = prod_ij (and same", "+= cache_size # scale vals elif fnName == \"bulk_hprobs_by_block\": #Note: includes \"results\" memory", "= None # free mem #gather results tm = _time.time() _mpit.gather_slices(blocks, blkOwners, mxToFill,", "= spamTuple # This calculator uses the convention that rho has shape (N,1)", ") = vec( mx w/ col_i = A[col0] * B[0,1] ) = B^T", "is None: #Fill hessian cache info dProdCache1 = self._compute_dproduct_cache( evalSubTree, prodCache, scaleCache, mySubComm,", ") == 0 ) #dGs = clip(dGs,-1e300,1e300) _np.seterr(**old_err) if flat: dGs = _np.swapaxes(_np.swapaxes(dGs,", "split tree to parallelize computation, since there are no memory savings from using", "of the i-th operation sequence product with respect to the j-th model parameter.", "(comm.Get_rank(),\",\".join([str(len(subtrees[i])) # for i in mySubTreeIndices]))) #eval on each local subtree #my_results =", "and 2nd differentiation, respectively (i.e. by wrtFilter1 and wrtFilter2). clipTo : 2-tuple, optional", "# may overflow, but OK d2pr_d2rhos = _np.zeros((1, self.Np, self.Np)) _fas(d2pr_d2rhos, [0, self.sos.get_prep(rholabel).gpindices,", "obj_wrtFilter.append(list(gpindices).index(i)) relevant_gpindices = _np.array(relevant_gpindices, _np.int64) if len(relevant_gpindices) == 1: #Don't return a length-1", "[], 0, comm, gatherMemLimit) if deriv2MxToFill is not None: _mpit.gather_indices(subtreeElementIndices, subTreeOwners, deriv2MxToFill, [],", "or - inf anyway... dp_dOps[_np.isnan(dp_dOps)] = 0 #SPAM ------------- # Get: dp_drhos[i, rho_gpindices]", "j-th then i-th model parameters. * if flat == True, a N x", "supported yet!\") # To support unitary evolution we need to: # - alter", "not d2(prod)/d(gl2)d(gl1) ... if m < l: x0 = _np.kron(_np.transpose(prods[(0, m - 1)]),", "Gs[gInds], dGs2[gInds], scaleVals[gInds], wrtSlice2), add=sumInto) _fas(mxToFill, [fInds, pslc1, pslc2], self._hprobs_from_rhoE( spamTuple, rho, E,", "with the probabilities corresponding to the *simplified* operation sequences found in an evaluation", "derivatives-of-product calculations. This is contained in a class separate from Model to allow", "_np.squeeze(_np.dot(dGs2, rho), axis=(3,)) * scaleVals[:, None, None] # overflow OK devec = EVec.deriv_wrt_params(E_wrtFilter1)", "to include in the derivative. Each element is an index into an array", "/ G^2)-th flattened operation sequence product with respect to the k-th then j-th", "and yielded, *not* allocated by the user. mem += 2 * cache_size *", "sequence \"\"\" dim = self.dim gate = self.sos.get_operation(opLabel) op_wrtFilter, gpindices = self._process_wrtFilter(wrtFilter, gate)", "_np.real(_np.abs(_np.dot(Es, _np.dot(G, rho)))**2) else: # evotype == \"densitymx\" ps = _np.real(_np.dot(Es, _np.dot(G, rho)))", "= _np.real(_np.abs(_np.dot(Es, _np.dot(G, rho)) * scale)**2) else: # evotype == \"densitymx\" # probability,", "comm_blkSize if (blkSize2 is None) \\ else min(comm_blkSize, blkSize2) # override with smaller", "_time import itertools as _itertools import collections as _collections from ..tools import mpitools", "may overflow, but OK d2pr_d2Es = _np.zeros((1, self.Np, self.Np)) _fas(d2pr_d2Es, [0, self.sos.get_effect(elabel).gpindices, self.sos.get_effect(elabel).gpindices],", "over operation sequences when a *split* evalTree is given, otherwise no parallelization is", "wrtFilter2). clipTo : 2-tuple, optional (min,max) to clip return value if not None.", "to reconstruct the parent tree's *non-final* elements from those of the sub-trees). Note", "is the length of the vectorized model). probability : float only returned if", "to (in parallel) iterate through the subtrees. It can often be useful to", "= tuple(reversed(tuple(circuit))) # prod = G1 * G2 * .... * GN ,", "self.sos.get_effect(elabel).has_nonzero_hessian(): dp_dAnyE = _np.dot(Gs, rho).squeeze(2) * scaleVals[:, None] # overflow OK d2pr_d2Es =", "no gates G = ident for (j, opLabel2) in enumerate(revOpLabelList[i:], start=i): # loop", "dim=(ks,blk1,M) _mpit.gather_slices(blocks2, blk2Owners, mxToFill, [felInds, blocks1[iBlk1]], 2, blk1Comm, gatherMemLimit) #gather row results; gather", "self.Np, self.Np)) _fas(d2pr_drhos, [0, None, self.sos.get_prep(rholabel).gpindices], _np.dot(_np.dot(E, dprod_dOps), rhoVec.deriv_wrt_params())[0]) # (= [0,:,:]) d2pr_dEs", "noqa # vec( d2prod/d(opLabel1)_kl*d(opLabel2)_ij ) = sum{...} [ G1 ... G(M-1) dG(M)/dkl G(M+1)", "to a (opLabel,i,j) tuple and each row corresponds to an element of the", "(rank %d computing %s)\" \\ # % (nDerivCols, str(allDerivColIndices), comm.Get_rank(), str(myDerivColIndices))) if mySubComm", "i in range(self.Np): dpr_dOps[0, i] = float(_np.dot(E, _np.dot(dprod_dOps[i], rho))) if returnPr: p =", "- 1 - i]) # (dim**2, dim**2) _fas(flattened_dprod, [None, gpindices], _np.dot(LRproduct, dop_dopLabel), add=True)", "above return (hGs, scaleVals) if bScale else hGs def _scaleExp(self, scaleExps): old_err =", "split, but this is was # incorrect (and luckily never used) - so", "in wrtSlicesList: if wrtSlice1 != last_wrtSlice1: dProdCache1 = dGs1 = None # free", "scaling that needs to be applied to the resulting products (final_product[i] = scaleValues[i]", "_fas(d2pr_drhos2, [None, None, rho_gpindices1], _np.squeeze(_np.dot(_np.dot(E, dGs2), drho), axis=(0,)) * scaleVals[:, None, None]) #", "= _np.seterr(over='ignore') rho, E = self._rhoE_from_spamTuple(spamTuple) _fas(mxToFill, [fInds], self._probs_from_rhoE(rho, E, Gs[gInds], scaleVals[gInds]), add=sumInto)", "prMxToFill=None, deriv1MxToFill=None, deriv2MxToFill=None, clipTo=None, check=False, comm=None, wrtFilter1=None, wrtFilter2=None, wrtBlockSize1=None, wrtBlockSize2=None, gatherMemLimit=None): \"\"\" Compute", "# _compute_product_cache when the tree was split, but this is was # incorrect", "1 x M numpy array, where M is the number of model parameters.", "yield wrtSlice1, wrtSlice2, hprobs dProdCache1 = dGs1 = None # free mem def", "these are SPAMVecs nCircuits = Gs.shape[0] rho_wrtFilter1, rho_gpindices1 = self._process_wrtFilter(wrtSlice1, self.sos.get_prep(rholabel)) rho_wrtFilter2, rho_gpindices2", "dprobs12 results mem += cache_size * nspam * (wrtLen1 + wrtLen2) # dprobs1", "if wrtFilter1 is None and wrtFilter2 is None: blkSize1 = wrtBlockSize1 # could", "parameters if isinstance(wrtFilter, slice): wrtFilter = _slct.indices(wrtFilter) if wrtFilter is not None: obj_wrtFilter", "the bulk operation on. flat : bool, optional Affects the shape of the", "operation on. prMxToFill : numpy array, optional when not None, an already-allocated length-E", "scale = scaleCache[i] - (scaleCache[iLeft] + scaleCache[iRight]) if abs(scale) > 1e-8: # _np.isclose(scale,0)", "returnPr : bool when set to True, additionally return the probability itself. returnDeriv", "in bulk_product, bulk_dproduct, and bulk_hproduct. Returns ------- block_generator A generator which, when iterated,", "#TODO: just allow slices as argument: wrtFilter -> wrtSlice? prodCache, scaleCache = self._compute_product_cache(evalTree,", "range(self.Np): dpr_dOps[0, i] = float(_np.dot(E, _np.dot(dprod_dOps[i], rho))) #Derivs wrt SPAM if returnDeriv: #", "first (row) and second (col) derivative operations, respectively. Each element is an index", "mySubComm is not None and mySubComm.Get_size() > 1: _warnings.warn(\"Too many processors to make", "R) scaleCache[i] = scaleCache[iLeft] + scaleCache[iRight] if prodCache[i].max() < PSMALL and prodCache[i].min() >", "pass mxToFill, dim=(KS), so gather mxToFill[felslc] (axis=0) if clipTo is not None: _np.clip(mxToFill,", "+ dLdR_sym + _np.transpose(_np.dot(L, hR), (1, 2, 0, 3)) scale = scaleCache[i] -", "E_gpindices2], _np.dot(dp_dAnyE, devec)) # get d2pr_dEs where gate derivatives are wrt the 2nd", "(i.e. doesn't return to save copying) some arrays. The arrays that are filled", "op_wrtFilter2)) if flat: return flattened_hprod else: return _np.transpose(flattened_hprod, (1, 2, 0)).reshape( (num_deriv_cols1, num_deriv_cols2,", "evaluation tree into. num_subtree_proc_groups : int The number of processor groups used to", "_np.dot(self.SPAMs[spamLabel],G) ) * exp(total_exp) # probability # print \"%d: p = %g, norm", "_np.swapaxes(_np.dot(L, dR), 0, 1) # dot(dS, T) + dot(S, dT) profiler.add_time(\"compute_dproduct_cache: dots\", tm)", "fnName == \"bulk_fill_hprobs\": mem += cache_size * wrtLen1 * wrtLen2 * dim *", "clipTo[1], out=prMxToFill) # in-place clip if check: self._check(evalTree, prMxToFill, deriv1MxToFill, mxToFill, clipTo) def", "of in \" \" _compute_hproduct_cache.\") #TODO: remove: not needed now that we track", "(dim**2, dim**2) _fas(flattened_dprod, [None, gpindices], _np.dot(LRproduct, dop_dopLabel), add=True) # (dim**2, nParams[opLabel]) if flat:", "#print(\"MPI: _compute_dproduct_cache called w/comm size %d\" % comm.Get_size()) # parallelize of deriv cols,", "by `evalTree.num_final_elements()`. To interpret which elements correspond to which strings and outcomes, you'll", "inds2] += xv if flat: return flattened_d2prod # axes = (vectorized_op_el_index, model_parameter1, model_parameter2)", "as in bulk_fill_hprobs (TODO consolidate?) #NOTE: filtering is done via the yet-to-be-defined local", "with respect to the j-th then i-th model parameters. * if flat ==", "_slct.shift(_slct.intersect( # wrtSlices['effects'], # slice(self.e_offset[i],self.e_offset[i+1])), # -self.e_offset[i]) for i in range(len(self.effects))] # tmp_num_params", "---------- rholabel : Label The state preparation label. elabels : list A list", "numpy array Only returned if bReturnDProdsAndProds == True. * if flat == False,", "doperation and hoperation below: pulls out pieces of a wrtFilter argument relevant for", "bScale: return Gs, scaleVals else: old_err = _np.seterr(over='ignore') Gs = _np.swapaxes(_np.swapaxes(Gs, 0, 2)", "dProdCache = dGs = None # free mem else: # Divide columns into", "(row) and second (col) derivative operations, respectively. wrtBlockSize2, wrtBlockSize2 : int or float,", "... GN ] # noqa # a matrix for each given (i,j,k,l) #", "bulk_fill_probs(self, mxToFill, evalTree, clipTo=None, check=False, comm=None): \"\"\" Compute the outcome probabilities for an", "gates, starting with identity scale_exp += ex # scale and keep track of", "---------- mxToFill : numpy ndarray an already-allocated ExMxM numpy array where E is", "model_parameter2) else: vec_kl_size, vec_ij_size = flattened_d2prod.shape[1:3] # == num_deriv_cols1, num_deriv_cols2 return _np.rollaxis(flattened_d2prod, 0,", "derivative. Each element is an index into an array of gate parameters ordered", "[] # values = object-local param indices relevant_gpindices = [] # indices into", "string if not bScale: old_err = _np.seterr(over='ignore', invalid='ignore') Gs = _np.swapaxes(_np.swapaxes(Gs, 0, 2)", "Use comm to distribute columns allDerivColSlice = slice(0, nDerivCols) if (wrtSlice is None)", "a post-scaled product internally. If False, this routine will run slightly faster, but", "the memory required by a given set of subcalls to computation functions. Parameters", "of mxToFill and spam labels. evalTree : EvalTree given by a prior call", "add=sumInto) _np.seterr(**old_err) #Set wrtBlockSize to use available processors if it isn't specified if", "_np.seterr(over='ignore') Gs = _np.swapaxes(_np.swapaxes(Gs, 0, 2) * scaleVals, 0, 2) # may overflow,", "_np.zeros((nCircuits, nDerivCols1, nDerivCols2)) _fas(d2pr_drhos1, [None, None, rho_gpindices2], _np.squeeze(_np.dot(_np.dot(E, dGs1), drho), axis=(0,)) * scaleVals[:,", "evalTree.distribute(comm) #eval on each local subtree for iSubTree in mySubTreeIndices: evalSubTree = subtrees[iSubTree]", "_slct.indices(wrtSlice1) if (wrtSlice1 is not None) else None wrtIndices2 = _slct.indices(wrtSlice2) if (wrtSlice2", "routine can be useful when memory constraints make constructing the entire Hessian at", "# may overflow, but OK if infs occur here _np.seterr(**old_err) return scaleVals def", "for the derivatives and/or products for the i-th operation sequence. \"\"\" nCircuits =", "_np.zeros((nCircuits, nDerivCols2, nDerivCols1)) _fas(d2pr_drhos2, [None, None, rho_gpindices1], _np.squeeze(_np.dot(_np.dot(E, dGs2), drho), axis=(0,)) * scaleVals[:,", "and hessians[i,j,k] holds the derivative of the (i % G^2)-th entry of the", "columns if prMxToFill is not None: self._fill_result_tuple((prMxToFill,), evalSubTree, slice(None), slice(None), calc_and_fill_p) profiler.mem_check(\"bulk_fill_dprobs: post", "dGs = None # free mem else: # Divide columns into blocks of", "when bReturnProds == True. An array of shape S x G x G;", "G1 ... G(L-1) tensor # noqa # ( unvec( G(L+1) ... G(M-1) tensor", "array * if flat == False, a M x M x G x", "are SPAMVecs nCircuits = Gs.shape[0] rho_wrtFilter1, rho_gpindices1 = self._process_wrtFilter(wrtSlice1, self.sos.get_prep(rholabel)) rho_wrtFilter2, rho_gpindices2 =", "= 0 if self.sos.get_effect(elabel).has_nonzero_hessian(): dp_dAnyE = _np.dot(Gs, rho).squeeze(2) * scaleVals[:, None] # overflow", "labels. circuit : Circuit or tuple A tuple-like object of *simplified* gates (e.g.", "x GxG ; hL,hR = vgs x vgs x GxG dLdRa = _np.swapaxes(_np.dot(dL1,", "else len(wrtFilter) flattened_dprod = _np.zeros((dim**2, num_deriv_cols), 'd') # For each operation label, compute", "the scaling. \"\"\" if bScale: scaledGatesAndExps = {} scale_exp = 0 G =", "and turns out to be useful when computing the Hessian of functions of", "range of model params (see above) if wrtSlice2 is not None and wrtSlice2.start", "+ _np.transpose(_np.dot(L, hR), (1, 2, 0, 3)) scale = scaleCache[i] - (scaleCache[iLeft] +", "subtrees] _mpit.gather_indices(subtreeElementIndices, subTreeOwners, mxToFill, [], 0, comm, gatherMemLimit) #note: pass mxToFill, dim=(KS,M), so", "is incompatbile with \" \"matrix-based calculations\" % self.evotype)) def copy(self): \"\"\" Return a", "# Get slice into entire range of model params (see above) if wrtSlice2", "len(relevant_gpindices) == 1: #Don't return a length-1 list, as this doesn't index numpy", "prodCache, scaleCache, blk1Comm, blk_wrtSlice1) dGs1 = evalSubTree.final_view(dProdCache1, axis=0) for iBlk2 in myBlk2Indices: blk_wrtSlice2", "|rho><E| * prod ) = sum E_k prod_kl rho_l # dpr/d(opLabel)_ij = sum", "bScale=False): \"\"\" Compute the product of a specified sequence of operation labels. Note:", "clip if check: self._check(evalTree, mxToFill, clipTo=clipTo) def bulk_fill_dprobs(self, mxToFill, evalTree, prMxToFill=None, clipTo=None, check=False,", "Smallness tolerances, used internally for conditional scaling required # to control bulk products,", "(num_deriv_cols1, num_deriv_cols2, dim, dim)) # axes = (gate_ij1, gateij2, prod_row, prod_col) def dproduct(self,", "scale cache # mem += cache_size # scale vals # #elif fnName ==", "d2pr_dOps2[i,j,k] = sum_l E[0,l] dot( dGs, rho )[i,j,k,l,0] # d2pr_dOps2[i,j,k] = dot( E,", "nDerivCols2)) dp_dAnyE = _np.squeeze(_np.dot(dGs1, rho), axis=(3,)) * scaleVals[:, None, None] # overflow OK", "array, optional when not None, an already-allocated ExM numpy array that is filled", "is first done over the set of parameters being differentiated with respect to.", "split. wrtSlicesList : list A list of `(rowSlice,colSlice)` 2-tuples, each of which specify", "Parameters ---------- subcalls : list of strs A list of the names of", "in wrtFilter for opLabel) if flat: return flattened_dprod else: # axes = (gate_ij,", "to split the full evaluation tree into. num_subtree_proc_groups : int The number of", "convention that rho has shape (N,1) rho = self.sos.get_prep(rholabel).todense()[:, None] Es = [self.sos.get_effect(elabel).todense()[:,", "= dGs2 = None # free mem if bReturnDProbs12: dprobs12 = dprobs1[:, :,", "if wrtSlice1 is not None and wrtSlice1.start is not None: myHessianSlice1 = _slct.shift(myDeriv1ColSlice,", "Hessian at once impractical, and one is able to compute reduce results from", "certain rights # in this software. # Licensed under the Apache License, Version", "E[0,l] dot( dGs, rho )[i,j,k,l,0] # d2pr_dOps2[i,j,k] = dot( E, dot( dGs, rho", "respect to a given gateLabel_ij. This function returns a concatenated form of the", "this is to allow a trace or other linear operation to be done", "= dGs1 = None # free mem #gather column results: gather axis 2", "select a subset of all the derivative columns, essentially taking # a derivative", "over blocks (subsets) of the parameters being differentiated with respect to (see wrtBlockSize).", "of integers specifying which model parameters to differentiate with respect to in the", "to allow for *complex* derivatives, since matrices can be complex # - update", "= evalSubTree.final_view(hProdCache, axis=0) #( nCircuits, len(wrtFilter1), len(wrtFilter2), dim, dim ) #Compute all requested", "the set of parameters being differentiated with respect to. If there are more", "which correspond to the vectorized derivatives of each of the product components (i.e.", "= 0 if self.sos.get_effect(elabel).has_nonzero_hessian(): derivWrtAnyEvec = scale * _np.transpose(_np.dot(prod, rho)) # may overflow,", "vec( mx w/ col_i = A[col0] * B[0,1] ) = B^T tensor A", "but with a chance that the product will overflow and the subsequent trace", "= int(_np.ceil(self.Np / blkSize1)) nBlks2 = int(_np.ceil(self.Np / blkSize2)) # num blocks required", "#Fill cache info (not requiring column distribution) tm = _time.time() prodCache, scaleCache =", "scale * _np.dot(E, prod) dpr_drhos = _np.zeros((1, self.Np)) _fas(dpr_drhos, [0, self.sos.get_prep(rholabel).gpindices], _np.dot(derivWrtAnyRhovec, rhoVec.deriv_wrt_params()))", "takes (kl,vec_prod_indx,ij) => (vec_prod_indx,kl,ij) elif l < m: x0 = _np.kron(_np.transpose(prods[(l + 1,", "dGs2 be None? assert(nDerivCols1 == nDerivCols2) d2pr_dEs2 = _np.transpose(d2pr_dEs1, (0, 2, 1)) else:", "scaleVals, wrtSlice1=None, wrtSlice2=None): if self.evotype == \"statevec\": raise NotImplementedError(\"Unitary evolution not fully supported", "Note: if gate G(L) is just a matrix of parameters, then dG(L)/dij =", "may overflow, but OK if infs occur here _np.seterr(**old_err) if bScale: return Gs,", "here if complex? _fas(dpr_dEs, [0, EVec.gpindices], _np.dot(derivWrtAnyEvec, EVec.deriv_wrt_params())) _np.seterr(**old_err) if returnPr: return dpr_drhos", "is dprod_dOps for ith string hGs = evalTree.final_view(hProdCache, axis=0) #shape == ( len(circuit_list),", "fully supported yet!\") #Compute probability and save in return array # want vp[iFinal]", "opLabel LRproduct = _np.kron(leftProds[i], rightProdsT[N - 1 - i]) # (dim**2, dim**2) _fas(flattened_dprod,", "3)) * scaleVals[:, None] _np.seterr(**old_err2) # may overflow, but OK ; shape ==", "hGs[_np.isnan(hGs)] = 0 _np.seterr(**old_err) if flat: # cols = deriv cols, rows =", "profiler.mem_check(\"bulk_fill_dprobs: post fill blk\") dProdCache = dGs = None # free mem #gather", "is None: blkSize = wrtBlockSize # could be None if (mySubComm is not", "comm_blkSize = self.Np / mySubComm.Get_size() blkSize1 = comm_blkSize if (blkSize1 is None) \\", "hProdCache, [], 1, comm) #, gatherMemLimit) #gather over row-distribution (Deriv1) #note: gathering axis", "_np.exp(scaleExps) # may overflow, but OK if infs occur here _np.seterr(**old_err) if bScale:", "== True. An array of shape S x G x G; products[i] is", "self.operations.keys() as in # dproduct(...) and find the labels in the string which", "= _np.seterr(invalid='ignore', over='ignore') dp_dOps = _np.squeeze(_np.dot(E, _np.dot(dGs, rho)), axis=(0, 3)) * scaleVals[:, None]", "The sequence of operation labels. flat : bool, optional Affects the shape of", "= myDeriv2ColSlice if mySubSubComm is not None and mySubSubComm.Get_size() > 1: _warnings.warn(\"Too many", "rholabel : Label The state preparation label. elabels : list A list of", "_compute_product_cache when the tree was split, but this is was # incorrect (and", "may overflow, but ok _np.seterr(**old_err) return Gs def bulk_dproduct(self, evalTree, flat=False, bReturnProds=False, bScale=False,", "matrixOf(circuit[iRight]) (iRight, iLeft) = evalTree[i] L, R = prodCache[iLeft], prodCache[iRight] dL1, dR1 =", "in elabels ]) #assert(_np.linalg.norm(ps-check_ps) < 1e-8) return ret def dpr(self, spamTuple, circuit, returnPr,", "a operation sequence and spam tuple as a 1 x M numpy array,", "*not* mySubSubComm, since we can't do any further parallelization _mpit.gather_slices(deriv2Slices, deriv2Owners, hProdCache, [None,", "object appropriate for this calculator. Parameters ---------- simplified_circuits : list A list of", "# dim=(cacheSize,nDerivCols1,nDerivCols2,dim,dim) else: #compute \"Deriv1\" row-derivatives distribution only; don't use column distribution hProdCache[:,", "Affects the shape of the returned derivative array (see below). wrtFilter : list", ".profiler import DummyProfiler as _DummyProfiler from .label import Label as _Label from .matrixevaltree", "nL, R / nR prodCache[i] = _np.dot(sL, sR); scaleCache[i] += _np.log(nL) + _np.log(nR)", "track of exponent # # p = _mt.trace( _np.dot(self.SPAMs[spamLabel],G) ) * exp(total_exp) #", "_np.clip(prMxToFill, clipTo[0], clipTo[1], out=prMxToFill) # in-place clip if check: self._check(evalTree, prMxToFill, mxToFill, clipTo=clipTo)", "= sum_k,l E[0,k] dGs[i,j,k,l] rho[l,0] # dp_dOps[i,j] = sum_k E[0,k] dot( dGs, rho", "cache size given a number of operation sequences. Returns ------- int \"\"\" return", "model parameters. hessian[0,j,k] is the derivative of the probability w.r.t. the k-th then", "+ dpr_dOps d2pr_drhos = _np.zeros((1, self.Np, self.Np)) _fas(d2pr_drhos, [0, None, self.sos.get_prep(rholabel).gpindices], _np.dot(_np.dot(E, dprod_dOps),", "= _slct.indices(wrtSlice1) if (wrtSlice1 is not None) else None wrtIndices2 = _slct.indices(wrtSlice2) if", "is a functionality needed to correctly handle the remainder spam label. \"\"\" pslc1", "blkSize1) # override with smaller comm_blkSize blkSize2 = comm_blkSize if (blkSize2 is None)", "parameters ordered by concatenating each gate's parameters (in the order specified by the", "subtrees of evalTree (if it is split). Returns ------- None \"\"\" #get distribution", "== \"bulk_fill_probs\": mem += cache_size * dim * dim # product cache mem", "scaleCache, blkComm, block_wrtSlice, profiler) profiler.add_time(\"bulk_fill_dprobs: compute_dproduct_cache\", tm) profiler.mem_check( \"bulk_fill_dprobs: post compute dproduct blk", "profiler.mem_check(\"bulk_fill_dprobs: post gather subtrees\") if clipTo is not None and prMxToFill is not", "and wrtBlockSize2 is None) # Cannot specify both wrtFilter and wrtBlockSize wrtSlice1 =", "rho ) )[0,i,j,k,0] # d2pr_dOps2 = squeeze( dot( E, dot( dGs, rho )", "_compute_hproduct_cache(self, evalTree, prodCache, dProdCache1, dProdCache2, scaleCache, comm=None, wrtSlice1=None, wrtSlice2=None): \"\"\" Computes a tree", "or get nans (invalid), but ok dGs1 = _np.swapaxes(_np.swapaxes(dGs1, 0, 3) * scaleVals,", "+ pr*dpr/dx.C # = 2 Re(dpr/dx*pr.C) , where dpr/dx is the usual density-matrix-mode", "1).reshape((num_deriv_cols, dim, dim)) def hproduct(self, circuit, flat=False, wrtFilter1=None, wrtFilter2=None): \"\"\" Compute the hessian", "dGs = _np.empty((Gs.shape[0], 0, self.dim, self.dim), 'd') def calc_and_fill_p(spamTuple, fInds, gInds, pslc1, pslc2,", "model_element_col) def prs(self, rholabel, elabels, circuit, clipTo, bUseScaling=False, time=None): \"\"\" Compute probabilities of", "#Compute d2(probability)/dGates2 and save in return list # d2pr_dOps2[i,j,k] = sum_l,m E[0,l] hGs[i,j,k,l,m]", "vec( dG(L)/dij) ) # noqa # if dG(L)/dij = E(i,j) # noqa #", "{}; gate_wrtFilters2 = {} for l in uniqueOpLabels: used_operations[l] = self.sos.get_operation(l) gate_wrtFilters1[l], gpindices1[l]", "parallelize computation, even if given a split tree (since there's no good way", "------------------------------------------------------------------ if evalTree.is_split(): _warnings.warn(\"Ignoring tree splitting in hproduct cache calc.\") hProdCache = _np.zeros((cacheSize,)", "evotype == \"densitymx\" # probability, with scaling applied (may generate overflow, but OK)", "gate dProdCache[i] = _np.zeros(deriv_shape) else: #doperation = self.dproduct( (opLabel,) , wrtFilter=wrtIndices) doperation =", "d2pr_dEs2 = _np.transpose(d2pr_dEs1, (0, 2, 1)) else: d2pr_dEs2 = _np.zeros((nCircuits, nDerivCols2, nDerivCols1)) dp_dAnyE", "if returnDeriv == True. A 1 x M numpy array of derivatives of", "_warnings.warn(\"Would have scaled dProd but now will not alter scaleCache.\") #profiler.print_mem(\"DEBUGMEM: POINT2\"); profiler.comm.barrier()", "from previous subtree iteration before computing caches scaleVals = Gs = prodCache =", "else: vec_kl_size, vec_ij_size = flattened_d2prod.shape[1:3] # == num_deriv_cols1, num_deriv_cols2 return _np.rollaxis(flattened_d2prod, 0, 3).reshape((vec_kl_size,", "# free mem #gather column results: gather axis 2 of mxToFill[felInds,blocks1[iBlk1]], dim=(ks,blk1,M) _mpit.gather_slices(blocks2,", ": numpy array The product or scaled product of the operation matrices. scale", "`deriv1MxToFill`, and `deriv1MxToFill`), then: - `hprobs == mx[:,:,rowSlice,colSlice]` - `dprobs12 == dp1[:,:,rowSlice,None] *", "= [slice(self.rho_offset[i],self.rho_offset[i+1]) for i in range(len(self.preps)) ] # global_e_slices = [slice(self.e_offset[i],self.e_offset[i+1]) for i", "are wrt the 2nd set of gate parameters if wrtSlice1 == wrtSlice2: #", "None and wrtFilter2 is None: blkSize1 = wrtBlockSize1 # could be None blkSize2", "MatrixForwardSimulator(ForwardSimulator): \"\"\" Encapsulates a calculation tool used by model objects to perform product", "entry == 1 # if vec(.) concatenates rows (which numpy.flatten does) # vec(", "rho)) * scale) _np.seterr(**old_err) else: # no scaling -- faster but susceptible to", "def _rhoE_from_spamTuple(self, spamTuple): assert(len(spamTuple) == 2) if isinstance(spamTuple[0], _Label): rholabel, elabel = spamTuple", "The number of groups to divide the second-derivative parameters into. Computation will be", "but OK if infs occur here _np.seterr(**old_err) return scaleVals def _rhoE_from_spamTuple(self, spamTuple): assert(len(spamTuple)", "= _time.time() prodCache, scaleCache = self._compute_product_cache(evalSubTree, mySubComm) profiler.add_time(\"bulk_fill_dprobs: compute_product_cache\", tm) #use cached data", "nDerivCols2 = dProdCache2.shape[1] assert(wrtSlice1 is None or _slct.length(wrtSlice1) == nDerivCols1) assert(wrtSlice2 is None", "# vp = squeeze( dot( E, dot(Gs, rho)), axis=(0,2) ) * scaleVals return", "hessn_shape) #First element of cache are given by evalTree's initial single- or zero-operation", "with probability derivatives, similar to bulk_fill_dprobs(...), but where M is the number of", "labels for i, opLabel in zip(evalTree.get_init_indices(), evalTree.get_init_labels()): if opLabel == \"\": # special", "works for arrays too # Compute the derivative of the entire operation sequence", "blocks[iBlk], slice(None), calc_and_fill_blk) profiler.mem_check(\"bulk_fill_dprobs: post fill blk\") dProdCache = dGs = None #", "FUNCTIONS def default_distribute_method(self): \"\"\" Return the preferred MPI distribution mode for this calculator.", "dp_dAnyE = _np.squeeze(_np.dot(dGs2, rho), axis=(3,)) * scaleVals[:, None, None] # overflow OK devec", "a single flattened gate (ordered as numpy.flatten) - M == length of the", "# d2pr/d(E)_i d(opLabel)_mn = sum [dprod/d(opLabel)_mn]_il rho_l (and same for other diff order)", "[self.sos.get_effect(elabel).todense()[:, None] for elabel in elabels] Es = _np.conjugate(_np.transpose(_np.concatenate(Es, axis=1))) # convention: Es", "#*************************************************************************************************** # Copyright 2015, 2019 National Technology & Engineering Solutions of Sandia, LLC", "[ (G1 ... G(L-1)) tensor (G(L+1) ... GN)^T ]] * vec( dG(L)/dij) )", "\"outcomes\" (spam-tuples) for a single operation sequence. The spam tuples may only vary", "for distributing the computation across multiple processors. Distribution is performed over subtrees of", "do any # further parallelization tm = _time.time() all_results = comm.allgather(my_results) profiler.add_time(\"MPI IPC\",", "None) else None for i, opLabel in zip(evalTree.get_init_indices(), evalTree.get_init_labels()): if opLabel == \"\":", "M x M x G x G numpy array, where: - M ==", "# cols = deriv cols, rows = flattened all else dGs1 = _np.swapaxes(_np.swapaxes(dGs1,", "sequences are zero. hProdCache[i] = _np.zeros(hessn_shape) else: hoperation = self.hoperation(opLabel, wrtFilter1=wrtIndices1, wrtFilter2=wrtIndices2) hProdCache[i]", "= _np.zeros((nCircuits, nDerivCols1, nDerivCols2)) _fas(d2pr_drhos1, [None, None, rho_gpindices2], _np.squeeze(_np.dot(_np.dot(E, dGs1), drho), axis=(0,)) *", "below: pulls out pieces of a wrtFilter argument relevant for a single object", "_nla import time as _time import itertools as _itertools import collections as _collections", "to True, additionally return the derivative of the probability. clipTo : 2-tuple (min,max)", "spamTuple rhoVec = self.sos.get_prep(rholabel) # distinct from rho,E b/c rho,E are EVec =", "of the operation sequences. Parameters ---------- spam_label_rows : dictionary a dictionary with keys", "the Apache License, Version 2.0 (the \"License\"); you may not use this file", "of the evaluation tree that will be passed to the functions named by", "dim = self.dim gate = self.sos.get_operation(opLabel) op_wrtFilter, gpindices = self._process_wrtFilter(wrtFilter, gate) # Allocate", "# noqa # dprod/d(opLabel)_ij = sum_{L s.t. GL == oplabel} [ G1 ...", "done over the set of parameters being differentiated with respect to. If there", "ignoring L == M terms assumes that d^2 G/(dij)^2 == 0, which is", "(so we only need to compute this gate hessian once). But since we're", "bool, optional when set to True, additionally return the probabilities. bScale : bool,", "MPI processor syncronization. Returns ------- None \"\"\" if wrtFilter1 is not None: assert(wrtBlockSize1", "the operation sequences to compute the bulk operation on. flat : bool, optional", "None) # Cannot specify both wrtFilter and wrtBlockSize wrtSlice2 = _slct.list_to_slice(wrtFilter2) else: wrtSlice2", "to control memory usage. Cannot be specified in conjuction with wrtBlockSize. wrtBlockSize :", "bulk_fill_hprobs (TODO consolidate?) #NOTE: filtering is done via the yet-to-be-defined local variables #", "time : float, optional The *start* time at which `circuit` is evaluated. Returns", "!= last_wrtSlice1: dProdCache1 = dGs1 = None # free Mem dProdCache1 = self._compute_dproduct_cache(", "array Only returned when bReturnDProdsAndProds == True. An array of shape S x", "import _fas from .profiler import DummyProfiler as _DummyProfiler from .label import Label as", "than derivative columns.\") # Use comm to distribute columns allDerivColSlice = slice(0, nDerivCols)", "profiler.add_time(\"MPI IPC\", tm) return _np.concatenate(all_results, axis=1) # TODO: remove this concat w/better gather?", "= all else return (hGs, dGs1, dGs2, Gs, scaleVals) if bScale else (hGs,", "dGs = _np.swapaxes(_np.swapaxes(dGs, 0, 1).reshape( (nDerivCols, nCircuits * dim**2)), 0, 1) # cols", "blk1Comm, gatherMemLimit) #Note: deriv2MxToFill gets computed on every inner loop completion # (to", "model parameter. derivative : numpy array only returned if returnDeriv == True. A", "matrix (G x G operation matrices) and derivs[i,j,k,l] holds the derivative of the", "a concatenated form of the above matrices, so that # each column corresponds", "= _np.exp(scale_exp) _np.seterr(**old_err) return G, scale else: G = _np.identity(self.dim) for lOp in", "# gate's parameters and fill appropriate columns of flattened_dprod. #gate = self.sos.get_operation[opLabel] UNNEEDED", "as in dpr(...) dpr_drhos = _np.zeros((1, self.Np)) derivWrtAnyRhovec = scale * _np.dot(E, prod)", "# else: # loc_rho_slices = [slice(None,None)]*len(self.preps) # loc_e_slices = [slice(None,None)]*len(self.effects) # global_rho_slices =", "nDerivCols), \"dGs must be pre-filtered!\" #Compute d(probability)/dOps and save in return list (now", "elements (this can be obtained by `evalTree.num_final_elements()`. To interpret which elements correspond to", "all requested derivative columns at once self._fill_result_tuple((prMxToFill, mxToFill), evalSubTree, slice(None), slice(None), calc_and_fill) profiler.mem_check(\"bulk_fill_dprobs:", "dGs2 = dGs1 else: dProdCache2 = self._compute_dproduct_cache( evalSubTree, prodCache, scaleCache, blk2Comm, blk_wrtSlice2) dGs2", "sequence # with respect to only that gate's parameters and fill the appropriate", "prod) # may overflow, but OK d2pr_d2rhos = _np.zeros((1, self.Np, self.Np)) _fas(d2pr_d2rhos, [0,", "to achieve desired average size == blkSize1 or blkSize2 blocks1 = _mpit.slice_up_range(self.Np, nBlks1)", "E_gpindices1 = self._process_wrtFilter(wrtSlice1, self.sos.get_effect(elabel)) E_wrtFilter2, E_gpindices2 = self._process_wrtFilter(wrtSlice2, self.sos.get_effect(elabel)) nDerivCols1 = self.Np if", "communicator for distributing the computation across multiple processors. This is done over operation", "dim x 1. gates, preps, effects : OrderedDict Ordered dictionaries of LinearOperator, SPAMVec,", "`hprobs` and `dprobs12` are arrays of shape K x S x B x", "num_deriv_cols2, dim, dim)) # axes = (gate_ij1, gateij2, prod_row, prod_col) def dproduct(self, circuit,", "not None: assert(wrtBlockSize is None) # Cannot specify both wrtFilter and wrtBlockSize wrtSlice", "prod_row, prod_col) def dproduct(self, circuit, flat=False, wrtFilter=None): \"\"\" Compute the derivative of a", "_warnings.warn(\"Ignoring tree splitting in product cache calc.\") cacheSize = len(evalTree) prodCache = _np.zeros((cacheSize,", "return (hGs, scaleVals) if bScale else hGs def _scaleExp(self, scaleExps): old_err = _np.seterr(over='ignore')", "= prodCache[iLeft], prodCache[iRight] prodCache[i] = _np.dot(L, R) scaleCache[i] = scaleCache[iLeft] + scaleCache[iRight] if", "# Get: d2pr_dErhos[i, e_offset[eIndex]:e_offset[eIndex+1], e_offset[rhoIndex]:e_offset[rhoIndex+1]] = # dEP^T * prod[i,:,:] * drhoP #", "so that # if gl1 and gl2 are both in opsToVectorize1 and opsToVectorize2", "required) leftProds = [] G = _np.identity(dim); leftProds.append(G) for opLabel in revOpLabelList: G", "axis=0) #( nCircuits, nDerivColsX, dim, dim ) hProdCache = self._compute_hproduct_cache(evalSubTree, prodCache, dProdCache1, dProdCache2,", "and spam label indexed by iOpStr and iSpamLabel. d12 has the same dimensions", "= _collections.OrderedDict() #Cache processed parameter filters for multiple uses below gpindices1 = {};", "[ slice(tmp_offsets[i],tmp_offsets[i+1]) # for i in range(len(self.effects)) ] # # return PrepEffectFilter(rho_local_slices=loc_rho_slices, #", "This tree *cannot* be split. wrtSlicesList : list A list of `(rowSlice,colSlice)` 2-tuples,", "= {} for l in uniqueOpLabels: used_operations[l] = self.sos.get_operation(l) gate_wrtFilters1[l], gpindices1[l] = self._process_wrtFilter(wrtFilter1,", "cache info (not distributed) prodCache, scaleCache = self._compute_product_cache(evalTree, comm) scaleVals = self._scaleExp(evalTree.final_view(scaleCache)) Gs", "= dp_drhos + dp_dEs + dp_dOps return sub_vdp #def _get_filter_info(self, wrtSlices): # \"\"\"", "scaleExps = evalTree.final_view(scaleCache) scaleVals = _np.exp(scaleExps) # may overflow, but OK if infs", "bytes to impose upon the \"gather\" operations performed as a part of MPI", "not None: # loc_rho_slices = [ # _slct.shift(_slct.intersect( # wrtSlices['preps'], # slice(self.rho_offset[i],self.rho_offset[i+1])), #", "rows = flattened everything else return (dGs, scaleVals) if bScale else dGs def", "of # all of the raw operation sequences which need to be computed", "to when the *second* derivative is taken. If there are more processors than", "optional The *start* time at which `circuit` is evaluated. Returns ------- numpy.ndarray An", "returned derivative array (see below). bReturnDProdsAndProds : bool, optional when set to True,", "\\ _mpit.distribute_indices(list(range(nBlks1)), mySubComm) myBlk2Indices, blk2Owners, blk2Comm = \\ _mpit.distribute_indices(list(range(nBlks2)), blk1Comm) if blk2Comm is", "else: myHessianSlice2 = myDeriv2ColSlice if mySubSubComm is not None and mySubSubComm.Get_size() > 1:", "of shape S*N x M where - N == the number of entries", "self.sos.get_prep(rholabel).hessian_wrt_params( rho_wrtFilter1, rho_wrtFilter2), (1, 0))) # _np.einsum('ij,jkl->ikl', dp_dAnyRho, self.sos.get_prep(rholabel).hessian_wrt_params( # rho_wrtFilter1, rho_wrtFilter2)) else:", "where E is the total number of computed elements (i.e. evalTree.num_final_elements()) and M", "\"dGs1 must be pre-filtered!\" # Get: d2pr_drhos[i, j, rho_gpindices] = dot(E,dGs[i,j],drho/drhoP)) # d2pr_drhos[i,j,J0+J]", "vectorizing op uses numpy.flatten rows are kept contiguous, so the first identity below", "must be None if the corresponding wrtFilter is not None. Set this to", "dot( dGs, rho ) ), axis=(0,3)) old_err2 = _np.seterr(invalid='ignore', over='ignore') dp_dOps = _np.squeeze(_np.dot(E,", "of circuit can be thought of as the first gate operation performed, which", "= indices into the (tree-) list of # all of the raw operation", "mxToFill, [felInds], 1, mySubComm, gatherMemLimit) if deriv1MxToFill is not None: _mpit.gather_slices(blocks1, blk1Owners, deriv1MxToFill,", "If False, this routine will run slightly faster, but with a chance that", "[dprod/d(opLabel)_mn]_ki (and same for other diff order) # d2pr/d(E)_i d(opLabel)_mn = sum [dprod/d(opLabel)_mn]_il", "prMxToFill is not None: _np.clip(prMxToFill, clipTo[0], clipTo[1], out=prMxToFill) # in-place clip if check:", "nans (invalid), but ok dGs = _np.swapaxes(_np.swapaxes(dGs, 0, 3) * scaleVals, 0, 3)", "nDerivCols) if comm is not None and comm.Get_size() > 1: #print(\"MPI: _compute_dproduct_cache called", "\"block\" of the Hessian to compute. Iterating over the output of this function", "( len(circuit_list), nDerivColsX, dim, dim ), # dGs[i] is dprod_dOps for ith string", "... GN ] + {similar with L < M} # noqa # +", "hGs = _np.rollaxis(_np.rollaxis(hGs, 0, 3).reshape( (nDerivCols1, nDerivCols2, nCircuits * dim**2)), 2) # cols", "prods[(m + 1, N - 1)]) # (dim**2, dim**2) # (nDerivCols1,nDerivCols2,dim**2) x =", "*used* to assume gave no contribution since we assume all gate elements are", "i, j] = float(_np.dot(E, _np.dot(d2prod_dGates[i, j], rho))) old_err = _np.seterr(over='ignore') prod, scale =", "hGs[i,j,k,l,m] rho[m,0] # d2pr_dOps2[i,j,k] = sum_l E[0,l] dot( dGs, rho )[i,j,k,l,0] # d2pr_dOps2[i,j,k]", "dim) # (reshape without copying - throws error if copy is needed) #", "processors. Returns ------- hessian : numpy array * if flat == False, a", "_np.kron(_np.transpose(prods[(0, m - 1)]), prods[(m + 1, l - 1)]) # (dim**2, dim**2)", "xv = _np.transpose(xv, axes=(2, 0, 1)) # (dim2, nDerivCols1, nDerivCols2) flattened_d2prod[:, inds1, inds2]", "pulls out pieces of a wrtFilter argument relevant for a single object (gate", "X ) can be done efficiently by actually computing X^T ( note (A", "self._compute_product_cache(evalTree, comm) dProdCache1 = self._compute_dproduct_cache(evalTree, prodCache, scaleCache, comm, wrtSlice1) dProdCache2 = dProdCache1 if", "# may overflow, but OK ; shape == (len(circuit_list), nDerivCols, nDerivCols) # may", "and fill the appropriate # columns of flattened_dprod. uniqueOpLabels = sorted(list(set(revOpLabelList))) for opLabel", "final argument is a boolean specifying whether the filling should overwrite or add", "tree. \"\"\" dim = self.dim # Note: dProdCache?.shape = (#circuits,#params_to_diff_wrt,dim,dim) nDerivCols1 = dProdCache1.shape[1]", "simplified_op_server, paramvec) if self.evotype not in (\"statevec\", \"densitymx\"): raise ValueError((\"Evolution type %s is", "fully on each inner loop *iteration*!) #collect/gather results subtreeElementIndices = [t.final_element_indices(evalTree) for t", "[0,:,:]) d2pr_dEs = _np.zeros((1, self.Np, self.Np)) derivWrtAnyEvec = _np.squeeze(_np.dot(dprod_dOps, rho), axis=(2,)) _fas(d2pr_dEs, [0,", "mxToFill, [], 0, comm, gatherMemLimit) #note: pass mxToFill, dim=(KS,M), so gather mxToFill[felInds] (axis=0)", "operation matrices). and hessian[i,j,k,l] holds the derivative of the (k,l)-th entry of the", "tmp_offsets = [ sum(tmp_num_params[0:i]) for i in range(len(self.effects)+1) ] # global_e_slices = [", "G(M+1) ... G(L-1) dG(L)/dij G(L+1) ... GN ] + {similar with L <", "prodCache[i].max() < PSMALL and prodCache[i].min() > -PSMALL: nL, nR = max(_nla.norm(L), _np.exp(-scaleCache[iLeft]), 1e-300),", "pair of SPAMVec (or array) # objects: (prepVec, effectVec) rho, Eraw = spamTuple", "- G == the linear dimension of a operation matrix (G x G", "on every inner loop completion # (to save mem) but isn't gathered until", "on their parameters. if self.sos.get_prep(rholabel).has_nonzero_hessian(): derivWrtAnyRhovec = scale * _np.dot(E, prod) # may", "float(_np.dot(E, _np.dot(d2prod_dGates[i, j], rho))) old_err = _np.seterr(over='ignore') prod, scale = self.product(circuit, True) if", "## since numpy does all the major allocation/deallocation). #if comm is None or", "can't do any further parallelization _mpit.gather_slices(deriv2Slices, deriv2Owners, hProdCache, [None, myDeriv1ColSlice], 2, mySubComm) #", "(0, 2, 1)) else: d2pr_dErhos2 = _np.zeros((nCircuits, nDerivCols2, nDerivCols1)) drho = rhoVec.deriv_wrt_params(rho_wrtFilter1) dp_dAnyE", "SPAMVecs nCircuits = Gs.shape[0] rho_wrtFilter, rho_gpindices = self._process_wrtFilter(wrtSlice, self.sos.get_prep(rholabel)) E_wrtFilter, E_gpindices = self._process_wrtFilter(wrtSlice,", "over the set of parameters being differentiated with respect to when the *second*", "hessian elements(%d)!\" % (self.Np**2) + \" [blkSize = {%.1f,%.1f}, nBlks={%d,%d}]\" % (blkSize1, blkSize2,", "rightProdsT.append(_np.transpose(G)) # Allocate memory for the final result num_deriv_cols = self.Np if (wrtFilter", "wrtBlockSize). wrtFilter : list of ints, optional If not None, a list of", "LEXICOGRAPHICAL VS MATRIX ORDER # we do matrix multiplication in this order (easier", "and mySubSubComm.Get_size() > 1: _warnings.warn(\"Too many processors to make use of in \"", "< M} [ G1 ... G(L-1) tensor # noqa # ( unvec( G(L+1)", "= _np.seterr(over='ignore', invalid='ignore') Gs = _np.swapaxes(_np.swapaxes(Gs, 0, 2) * scaleVals, 0, 2) #", "the computation across multiple processors. Distribution is first performed over subtrees of evalTree", "def bulk_product(self, evalTree, bScale=False, comm=None): \"\"\" Compute the products of many operation sequences", "= _np.dot(hL, R) + dLdR_sym + _np.transpose(_np.dot(L, hR), (1, 2, 0, 3)) scale", "each gate sequence given by evalTree column-by-column. This routine can be useful when", "e_local_slices=loc_e_slices, # e_global_slices=global_e_slices, # num_rho_params=_slct.length(wrtSlices['preps']), # num_e_params=_slct.length(wrtSlices['effects'])) # else: # loc_rho_slices = [slice(None,None)]*len(self.preps)", "of the (l,m)-th entry of the i-th operation sequence product with respect to", "in enumerate(revOpLabelList[i:], start=i): # loop over \"ending\" gate (>= starting gate) G =", "sized/filtered) ------------------- assert(dGs.shape[1] == nDerivCols), \"dGs must be pre-filtered!\" #Compute d(probability)/dOps and save", "nanOrInfCacheIndices = (~_np.isfinite(prodCache)).nonzero()[0] # may be duplicates (a list, not a set) #", "here _np.seterr(**old_err) if bReturnProds: Gs = evalTree.final_view(prodCache, axis=0) #shape == ( len(circuit_list), dim,", ") # noqa # if dG(L)/dij = E(i,j) # noqa # = vec(i,j)-col", "# print \"%d: p = %g, norm %g, exp %g\\n%s\" % (i,p,norm(G),total_exp,str(G)) #", "True, additionally return the probabilities. bScale : bool, optional When True, return a", "def bulk_hproduct(self, evalTree, flat=False, bReturnDProdsAndProds=False, bScale=False, comm=None, wrtFilter1=None, wrtFilter2=None): \"\"\" Return the Hessian", ": bool, optional Affects the shape of the returned derivative array (see below).", "if hProdCache[i].max() < HSMALL and hProdCache[i].min() > -HSMALL: _warnings.warn(\"Scaled hProd small in order", "if copy is needed) # transposes each of the now un-vectorized dim x", "labels The sequence of operation labels. bScale : bool, optional When True, return", "The product or scaled product of the operation matrices. scale : float Only", "gate elements are at most linear in params, so # all hessians for", "circuits\" rho, Es = self._rhoEs_from_spamTuples(rholabel, elabels) #shapes: rho = (N,1), Es = (len(elabels),N)", "- S == the number of operation sequences - G == the linear", "label, compute the derivative of the entire operation sequence # with respect to", "for iSubTree in mySubTreeIndices: evalSubTree = subtrees[iSubTree] felInds = evalSubTree.final_element_indices(evalTree) #Free memory from", "opLabel1 in enumerate(revOpLabelList): inds1 = gpindices1[opLabel1] nDerivCols1 = dop_dopLabel1[opLabel1].shape[1] if nDerivCols1 == 0:", "This iteration **must** match that in bulk_evaltree # in order to associate the", "and wrtSlice1 == wrtSlice2: # TODO: better check for equivalence: maybe let dGs2", "the Model. autogator : AutoGator An auto-gator object that may be used to", "when not None, an already-allocated length-E numpy array that is filled with probabilities,", "mem required) dop_dopLabel1 = { opLabel: gate.deriv_wrt_params(gate_wrtFilters1[opLabel]) for opLabel, gate in used_operations.items()} if", "\" by giving dproduct cache computation\" \" *fewer* processors and *smaller* (sub-)tree\" \"", "(see below). bReturnDProdsAndProds : bool, optional when set to True, additionally return the", "shape S x M x G x G, where - S == len(circuit_list)", "is filled with probabilities, just like in bulk_fill_probs(...). derivMxToFill1, derivMxToFill2 : numpy array,", "product with respect to the j-th model parameter. * if flat == True,", "each given (i,j) # noqa # vec( dprod/d(opLabel)_ij ) = sum_{L s.t. G(L)", "_np.count_nonzero(hProdCache[i]) and hProdCache[i].max() < HSMALL and hProdCache[i].min() > -HSMALL: _warnings.warn(\"hProd is small (oh", "scaleVals[:, None, None]) # overflow OK d2pr_drhos2 = _np.transpose(d2pr_drhos2, (0, 2, 1)) #", "tree (skip over the zero and single-gate-strings) for i in evalTree.get_evaluation_order(): # combine", "strToPrint) #DEBUG: print \"backtrace\" of product leading up to nan #G = _np.identity(", "identity scale_exp += ex # scale and keep track of exponent if H.max()", "hR = hProdCache[iLeft], hProdCache[iRight] # Note: L, R = GxG ; dL,dR =", "parameters (in the order specified by the model). This argument is used internally", "2, 1)) + \\ d2pr_dEs + _np.transpose(d2pr_dEs, (0, 2, 1)) + \\ d2pr_d2rhos", "E, Gs[gInds], dGs1[gInds], dGs2[gInds], hGs[gInds], scaleVals[gInds], wrtSlice1, wrtSlice2), add=sumInto) _np.seterr(**old_err) #NOTE: don't distribute", "hprobs = _np.zeros((nElements, _slct.length(wrtSlice1), _slct.length(wrtSlice2)), 'd') #prMxToFill = None deriv1MxToFill = dprobs1 deriv2MxToFill", "is, the first element of circuit can be thought of as the first", "---------- evalTree : EvalTree given by a prior call to bulk_evaltree. Specifies the", "(nDerivCols1, dim, dim) # (reshape without copying - throws error if copy is", "pr = Tr( |rho><E| * prod ) = sum E_k prod_kl rho_l #", "dR2), 1, 2) dLdRb = _np.swapaxes(_np.dot(dL2, dR1), 1, 2) dLdR_sym = dLdRa +", "distributing derivative calculations across multiple processors. Returns ------- derivs : numpy array *", "of entries in a single flattened gate (ordering as numpy.flatten) - M ==", "is None else _slct.length(wrtSlice2) #flt1 = self._get_filter_info(wrtSlices1) #flt2 = self._get_filter_info(wrtSlices2) # GATE DERIVS", "prodCache[iLeft], prodCache[iRight] dL, dR = dProdCache[iLeft], dProdCache[iRight] dProdCache[i] = _np.dot(dL, R) + \\", "it! #_warnings.warn(\"More processors than can be used for product computation\") pass # this", "last dProdCache1 for wrtSlice1, wrtSlice2 in wrtSlicesList: if wrtSlice1 != last_wrtSlice1: dProdCache1 =", "self._compute_product_cache(evalSubTree, mySubComm) profiler.add_time(\"bulk_fill_dprobs: compute_product_cache\", tm) #use cached data to final values scaleVals =", "to the appropriate block of flattened_d2prod. #NOTE: if we needed to perform a", "optional Whether to use a post-scaled product internally. If False, this routine will", "over \"starting\" gate prods[(i, i - 1)] = ident # product of no", "`(rowSlice, colSlice, hprobs)` or `(rowSlice, colSlice, dprobs12)` (the latter if `bReturnDProbs12 == True`).", "deriv2Owners, mySubSubComm = \\ _mpit.distribute_slice(allDeriv2ColSlice, mySubComm) # Get slice into entire range of", "list of integers specifying which gate parameters to differentiate with respect to in", "that # each column corresponds to a (opLabel,i,j) tuple and each row corresponds", "each local subtree #my_results = [] for iSubTree in mySubTreeIndices: evalSubTree = subtrees[iSubTree]", "G1 ... G(L-1) dG(L)/dij G(L+1) ... GN ] , a matrix for each", "length equal to the total number of computed elements (i.e. evalTree.num_final_elements()) evalTree :", "dGs, drhoP),axis=(0,))[:,:,J] drho = rhoVec.deriv_wrt_params(rho_wrtFilter2) d2pr_drhos1 = _np.zeros((nCircuits, nDerivCols1, nDerivCols2)) _fas(d2pr_drhos1, [None, None,", "columns(%d)!\" % self.Np + \" [blkSize = %.1f, nBlks=%d]\" % (blkSize, nBlks)) #", "and fill result quantities for given arguments \"\"\" old_err = _np.seterr(over='ignore') rho, E", ": Circuit or tuple of operation labels The sequence of operation labels. flat", "below) dGs2[_np.isnan(dGs2)] = 0 # convert nans to zero, as these occur b/c", "set. # \"\"\" # PrepEffectFilter = _collections.namedtuple( # 'PrepEffectFilter', 'rho_local_slices rho_global_slices ' +", "dGs2 = hGs = None prodCache = scaleCache = None #Fill product cache", "def product(self, circuit, bScale=False): \"\"\" Compute the product of a specified sequence of", "s.t. GL == oplabel} [ (G1 ... G(L-1)) tensor (G(L+1) ... GN)^T ]]", "10: strToPrint = str(circuit) else: strToPrint = str(circuit[0:10]) + \" ... (len %d)\"", "x G, where: - S == len(circuit_list) - M == the length of", "d2pr_dOps2 = squeeze( dot( E, dot( dGs, rho ) ), axis=(0,4)) old_err2 =", "# this is a fairly common occurrence, and doesn't merit a warning #", "dot(S, dT) profiler.add_time(\"compute_dproduct_cache: dots\", tm) profiler.add_count(\"compute_dproduct_cache: dots\") scale = scaleCache[i] - (scaleCache[iLeft] +", "= evalTree.distribute(comm) #if comm is not None: # print(\"MPI DEBUG: Rank%d subtee sizes", "_mpit.gather_slices(deriv1Slices, deriv1Owners, hProdCache, [], 1, comm) #, gatherMemLimit) #gather over row-distribution (Deriv1) #note:", "+= cache_size * wrtLen1 * dim * dim # dproduct cache mem +=", "None, a list of integers specifying which model parameters to differentiate with respect", "kept contiguous, so the first identity below is valid. # Below we use", "the number of model parameters. evalTree : EvalTree given by a prior call", "\"bulk_hproduct\": # mem += cache_size * num_params**2 * dim * dim # hproduct", "= pslc1 _fas(mxToFill, [fInds, pslc1], self._dprobs_from_rhoE( spamTuple, rho, E, Gs[gInds], dGs[gInds], scaleVals[gInds], block_wrtSlice),", "Under the terms of Contract DE-NA0003525 with NTESS, the U.S. Government retains certain", "tensor (G(M+1) ... G(L-1))^T vec( dG(M)/dkl ) ) # noqa # tensor (G(L+1)", "this calculator. \"\"\" return \"deriv\" def estimate_cache_size(self, nCircuits): \"\"\" Return an estimate of", "gate sequence probabilities can often be computed column-by-column from the using the columns", "dimension of a operation matrix (G x G operation matrices). and hessian[i,j,k,l] holds", "object. Parameters ---------- dim : int The gate-dimension. All operation matrices should be", "& M2 are the number of selected gate-set parameters (by wrtFilter1 and wrtFilter2).", "the derivative of the probability w.r.t. the k-th then the j-th model parameter.", "b/c an inf scaleVal is mult by a zero deriv value, and we", "; shape == (len(circuit_list), nDerivCols, nDerivCols) # may also give invalid value due", "Note: L, R = GxG ; dL,dR = vgs x GxG ; hL,hR", "profiler is None: profiler = _dummy_profiler if wrtFilter is not None: assert(wrtBlockSize is", "(G1 ... G(L-1)) tensor (G(L+1) ... GN)^T vec( dG(L)/dij ) ] # noqa", "cols, rows = flattened everything else return (dGs, scaleVals) if bScale else dGs", "for a single operation sequence. The spam tuples may only vary in their", "Returns ------- MatrixEvalTree \"\"\" evTree = _MatrixEvalTree() evTree.initialize(simplified_circuits, numSubtreeComms) return evTree def estimate_mem_usage(self,", "= (vectorized_op_el_index, model_parameter1, model_parameter2) else: vec_kl_size, vec_ij_size = flattened_d2prod.shape[1:3] # == num_deriv_cols1, num_deriv_cols2", "E[0,k] Gs[i,k,l] rho[l,0] * scaleVals[i] # vp[i] = sum_k E[0,k] dot(Gs, rho)[i,k,0] *", "= 0 _np.seterr(**old_err) if flat: dGs = _np.swapaxes(_np.swapaxes(dGs, 0, 1).reshape( (nDerivCols, nCircuits *", "dim ) profiler.add_time(\"bulk_fill_dprobs: compute_dproduct_cache\", tm) profiler.mem_check(\"bulk_fill_dprobs: post compute dproduct\") #Compute all requested derivative", "= _np.squeeze(_np.dot(Gs, rho), axis=(2,)) * scaleVals[:, None] _fas(dp_dEs, [None, E_gpindices], _np.dot(dp_dAnyE, EVec.deriv_wrt_params(E_wrtFilter))) sub_vdp", "rows (which numpy.flatten does) # vec( A * E(0,1) * B ) =", "no gate prodCache[i] = _np.identity(dim) # Note: scaleCache[i] = 0.0 from initialization else:", "* B[row1] ) = A tensor B^T * vec( E(0,1) ) # In", "as the returned probability. time : float, optional The *start* time at which", "= _np.dot(_np.transpose(hop_dopLabels[opLabel1], axes=(1, 2, 0)), x0); xv = x.view() xv = _np.transpose(xv, axes=(2,", "bScale) for elabel in elabels ]) #assert(_np.linalg.norm(ps-check_ps) < 1e-8) return ret def dpr(self,", "no cover def calc_and_fill_blk(spamTuple, fInds, gInds, pslc1, pslc2, sumInto): \"\"\" Compute and fill", "is not None and prMxToFill is not None: _np.clip(prMxToFill, clipTo[0], clipTo[1], out=prMxToFill) #", "of `evalTree`. Parameters ---------- mxToFill : numpy ndarray an already-allocated ExMxM numpy array", "have length equal to the number of final elements (this can be obtained", "the number of parameter columns (the length of colSlice) If `mx`, `dp1`, and", ": numpy array Only returned if bReturnDProdsAndProds == True. * if flat ==", "done via the yet-to-be-defined local variables # wrtSlice1 and wrtSlice2, of the parent-function", "wrtBlockSize1 # could be None blkSize2 = wrtBlockSize2 # could be None if", "value, and we hGs[_np.isnan(hGs)] = 0 # assume the zero hessian value trumps", "rho)), axis=(0, 3)) * scaleVals[:, None] _np.seterr(**old_err2) # may overflow, but OK ;", "[ # _slct.shift(_slct.intersect( # wrtSlices['effects'], # slice(self.e_offset[i],self.e_offset[i+1])), # -self.e_offset[i]) for i in range(len(self.effects))]", "(j, opLabel2) in enumerate(revOpLabelList[i:], start=i): # loop over \"ending\" gate (>= starting gate)", "%g - %g = %g\" % (_nla.norm(prMxToFill[fInds]), _nla.norm(check_vp), _nla.norm(prMxToFill[fInds] - check_vp))) # pragma:", "use E(i,j) to denote the elementary matrix where all entries are zero except", "the linear dimension of a operation matrix (G x G operation matrices). and", "the entire # operation sequence with respect to only those two gates' parameters", "\"bulk_hprobs_by_block\": #Note: includes \"results\" memory since this is allocated within # the generator", "if blkSize is None: #Fill derivative cache info tm = _time.time() dProdCache =", "rho[l,0] # dp_dOps[i,j] = sum_k E[0,k] dot( dGs, rho )[i,j,k,0] # dp_dOps[i,j] =", "E_k [dprod/d(opLabel1)_mn d(opLabel2)_ij]_kl rho_l # d2pr/d(rho)_i d(opLabel)_mn = sum E_k [dprod/d(opLabel)_mn]_ki (and same", "overflow, but OK dpr_dEs = _np.zeros((1, self.Np)) derivWrtAnyEvec = scale * _np.transpose(_np.dot(prod, rho))", "int The size of the evaluation tree that will be passed to the", "param_slice1 pslc2 = param_slice2 for spamTuple, (fInds, gInds) in evalTree.spamtuple_indices.items(): # fInds =", "two gates' parameters and fill # add the result to the appropriate block", "(1, 0))) # _np.einsum('ij,jkl->ikl', dp_dAnyE, self.sos.get_effect(elabel).hessian_wrt_params( # E_wrtFilter1, E_wrtFilter2)) else: d2pr_d2Es = 0", "slice(0, nDerivCols2) deriv1Slices, myDeriv1ColSlice, deriv1Owners, mySubComm = \\ _mpit.distribute_slice(allDeriv1ColSlice, comm) # Get slice", "are EVec = self.sos.get_effect(elabel) # arrays, these are SPAMVecs #Derivs wrt Gates old_err", "G = _np.identity(dim); leftProds.append(G) for opLabel in revOpLabelList: G = _np.dot(G, self.sos.get_operation(opLabel).todense()) leftProds.append(G)", "True, perform extra checks within code to verify correctness, generating warnings when checks", "/= nG; total_exp += log(nG) # scale and keep track of exponent #", "array, optional when not None, an already-allocated length-E numpy array that is filled", "use column distribution hProdCache[:, myDeriv1ColSlice] = self._compute_hproduct_cache( evalTree, prodCache, dProdCache1[:, myDeriv1ColSlice], dProdCache2, scaleCache,", "\\ else _slct.length(wrtSlice) deriv_shape = (nDerivCols, dim, dim) cacheSize = len(evalTree) # ------------------------------------------------------------------", "array specifying the scaling that needs to be applied to the resulting products", "comm, wrtSlice1) dProdCache2 = dProdCache1 if (wrtSlice1 == wrtSlice2) else \\ self._compute_dproduct_cache(evalTree, prodCache,", "(kl,vec_prod_indx,ij) => (vec_prod_indx,kl,ij) elif l < m: x0 = _np.kron(_np.transpose(prods[(l + 1, m", "Compute the product of a specified sequence of operation labels. Note: LinearOperator matrices", "#evaluate operation sequences using tree (skip over the zero and single-gate-strings) #cnt =", "%d computing %s)\" \\ # % (nDerivCols, str(allDerivColIndices), comm.Get_rank(), str(myDerivColIndices))) if mySubComm is", "!= 0, cpus hProdCache[:, myDeriv1ColSlice, myDeriv2ColSlice] = self._compute_hproduct_cache( evalTree, prodCache, dProdCache1[:, myDeriv1ColSlice], dProdCache2[:,", "# cannot specify both wrtFilter and blkSize nBlks = int(_np.ceil(self.Np / blkSize)) #", "# END SPAM DERIVS ----------------------- ret = d2pr_d2rhos + d2pr_dErhos2 + d2pr_drhos2 #", "to the k-th then j-th model parameters. * if flat == True, an", "and values which are integer row indices into mxToFill, specifying the correspondence between", "the same) Parameters ---------- rholabel : Label The state preparation label. elabels :", "being inf and dot-prod being 0. In # this case set to zero", "------------------------------------------------------------------ if comm is not None and comm.Get_size() > 1: # parallelize of", "blkSize1)) nBlks2 = int(_np.ceil(self.Np / blkSize2)) # num blocks required to achieve desired", "and deriv[i,j,k] holds the derivative of the (j,k)-th entry of the product with", "S == the number of operation sequences - G == the linear dimension", "self._process_wrtFilter(wrtSlice1, self.sos.get_prep(rholabel)) rho_wrtFilter2, rho_gpindices2 = self._process_wrtFilter(wrtSlice2, self.sos.get_prep(rholabel)) E_wrtFilter1, E_gpindices1 = self._process_wrtFilter(wrtSlice1, self.sos.get_effect(elabel)) E_wrtFilter2,", "= \\ _mpit.distribute_indices(list(range(nBlks1)), mySubComm) myBlk2Indices, blk2Owners, blk2Comm = \\ _mpit.distribute_indices(list(range(nBlks2)), blk1Comm) if blk2Comm", "blocks2 = _mpit.slice_up_range(self.Np, nBlks2) #distribute derivative computation across blocks myBlk1Indices, blk1Owners, blk1Comm =", "col-distribution (Deriv2) #note: gathering axis 2 of hProdCache[:,myDeriv1ColSlice], # dim=(cacheSize,nDerivCols1,nDerivCols2,dim,dim) else: #compute \"Deriv1\"", "NTESS, the U.S. Government retains certain rights # in this software. # Licensed", "that is filled with probabilities, just like in bulk_fill_probs(...). clipTo : 2-tuple, optional", "generate overflow, but OK _fas(d2pr_dErhos, [0, EVec.gpindices, self.sos.get_prep(rholabel).gpindices], _np.dot(_np.transpose(EVec.deriv_wrt_params()), derivWrtAnyEvec)) #Note: these 2nd", "of derivative columns to compute *products* for simultaneously. None means compute all requested", "for iBlk in myBlkIndices: tm = _time.time() block_wrtSlice = blocks[iBlk] dProdCache = self._compute_dproduct_cache(evalSubTree,", "= _np.swapaxes(_np.dot(dL2, dR1), 1, 2) dLdR_sym = dLdRa + _np.swapaxes(dLdRb, 0, 1) hProdCache[i]", "flat == False, a M x G x G array, where: - M", "#don't compute anything on \"extra\", i.e. rank != 0, cpus my_results = self._compute_dproduct_cache(", "wrtSlice2 = None #get distribution across subtrees (groups if needed) subtrees = evalTree.get_sub_trees()", "tree out of (most likely because you want to computed their probabilites). These", "#note: gathering axis 1 of mxToFill[felInds], dim=(ks,M) profiler.add_time(\"MPI IPC\", tm) profiler.mem_check(\"bulk_fill_dprobs: post gather", "scaleVals[i] # vp = squeeze( dot( E, dot(Gs, rho)), axis=(0,2) ) * scaleVals", "_fas(d2pr_dEs, [0, None, EVec.gpindices], _np.dot(derivWrtAnyEvec, EVec.deriv_wrt_params())) d2pr_dErhos = _np.zeros((1, self.Np, self.Np)) derivWrtAnyEvec =", "testing, and runs much slower when True. comm : mpi4py.MPI.Comm, optional When not", "in order to perform the parallelization over the parameter groups. num_param1_groups : int", "make sense to include these since their required memory is fixed ## (and", "for ith string if not bScale: old_err = _np.seterr(over='ignore', invalid='ignore') Gs = _np.swapaxes(_np.swapaxes(Gs,", "for equivalence: maybe let dGs2 be None? assert(nDerivCols1 == nDerivCols2) d2pr_drhos2 = _np.transpose(d2pr_drhos1,", "scaleVals[:, None] _fas(dp_dEs, [None, E_gpindices], _np.dot(dp_dAnyE, EVec.deriv_wrt_params(E_wrtFilter))) sub_vdp = dp_drhos + dp_dEs +", "self._compute_dproduct_cache(evalTree, prodCache, scaleCache, comm, wrtSlice) #use cached data to construct return values old_err", "= E(i,j), an elementary matrix dim = self.dim #Cache partial products (relatively little", "of this function iterates over these computed blocks, in the order given by", "flat == False, an array of shape S x M x M x", "= _time.time() if evalTree.is_split(): _warnings.warn(\"Ignoring tree splitting in dproduct cache calc.\") dProdCache =", "_np.dot(prod, rho)) * scale # may generate overflow, but OK if clipTo is", "1, N - 1)]) # (dim**2, dim**2) # (nDerivCols1,nDerivCols2,dim**2) x = _np.dot(_np.transpose(hop_dopLabels[opLabel1], axes=(1,", "differentiated with respect to (see wrtBlockSize). wrtFilter : list of ints, optional If", "spamTuple, rho, E, Gs, dGs1, dGs2, hGs, scaleVals, wrtSlice1=None, wrtSlice2=None): if self.evotype ==", "more CPUs(%d)\" % mySubComm.Get_size() + \" than derivative columns(%d)!\" % self.Np + \"", "we should do something else LATER. def calc_and_fill(spamTuple, fInds, gInds, pslc1, pslc2, sumInto):", "L} # noqa # [ G1 ... G(M-1) dG(M)/dkl G(M+1) ... G(L-1) dG(L)/dij", "hessian : numpy array a 1 x M x M array, where M", "None: profiler = _dummy_profiler dim = self.dim nDerivCols = self.Np if (wrtSlice is", "d2pr_dErhos[i,J0+J,K0+K] = sum j dEPT[J,j] dot(prod,drhoP)[i,j,K] # d2pr_dErhos[i,J0+J,K0+K] = dot(dEPT,prod,drhoP)[J,i,K] # d2pr_dErhos[i,J0+J,K0+K] =", "------- derivative : numpy array a 1 x M numpy array of derivatives", "dop_dopLabel1[opLabel1].shape[1] if nDerivCols1 == 0: continue for l, opLabel2 in enumerate(revOpLabelList): inds2 =", "= self._compute_dproduct_cache( evalSubTree, prodCache, scaleCache, mySubComm, wrtSlice1) dProdCache2 = dProdCache1 if (wrtSlice1 ==", "numpy array that is filled with probability derivatives, similar to bulk_fill_dprobs(...), but where", "mem += cache_size # scale vals else: raise ValueError(\"Unknown subcall name: %s\" %", "# as we assume the user has already done any such distribution #", "nspam * wrtLen1 * wrtLen2 # hprobs & dprobs12 results mem += cache_size", "iterates over these computed blocks, in the order given by `wrtSlicesList`. `rowSlice` and", "(mySubComm.Get_size() > 1): comm_blkSize = self.Np / mySubComm.Get_size() blkSize = comm_blkSize if (blkSize", "cache # mem += cache_size * num_params * dim * dim # dproduct", "== \"densitymx\" ps = _np.real(_np.dot(Es, _np.dot(G, rho))) ps = ps.flatten() if _np.any(_np.isnan(ps)): if", "# if _np.isnan(p): raise ValueError(\"STOP\") if clipTo is not None: ret = _np.clip(ps,", "objects is *simplified* into a lists of gate-only sequences along with a mapping", "mySubComm.Get_size() blkSize = comm_blkSize if (blkSize is None) \\ else min(comm_blkSize, blkSize) #", "a part of MPI processor syncronization. Returns ------- None \"\"\" tStart = _time.time()", "= GxG ; dL,dR = vgs x GxG ; hL,hR = vgs x", "= _np.seterr(over='ignore', invalid='ignore') # may overflow or get nans (invalid), but ok hGs", "than linear dependence on their parameters. if self.sos.get_prep(rholabel).has_nonzero_hessian(): dp_dAnyRho = _np.dot(E, Gs).squeeze(0) *", "= [slice(self.e_offset[i],self.e_offset[i+1]) for i in range(len(self.effects)) ] # return PrepEffectFilter(rho_local_slices=loc_rho_slices, # rho_global_slices=global_rho_slices, #", "operation on. This tree *cannot* be split. wrtSlicesList : list A list of", "(G x G operation matrices). and hessian[i,j,k,l] holds the derivative of the (k,l)-th", "x0); xv = x.view() xv = _np.transpose(xv, axes=(2, 0, 1)) # (dim2, nDerivCols1,", "nDerivCols2), \"hGs must be pre-filtered!\" #Compute d2(probability)/dGates2 and save in return list #", "and prodCache[i].min() > -PSMALL: nL, nR = max(_nla.norm(L), _np.exp(-scaleCache[iLeft]), 1e-300), max(_nla.norm(R), _np.exp(-scaleCache[iRight]), 1e-300)", "found in an evaluation tree, `evalTree`. An initial list of (general) :class:`Circuit` objects", "given by a prior call to bulk_evaltree. Specifies the *simplified* gate strings to", "_np.seterr(over='ignore', invalid='ignore') Gs = _np.swapaxes(_np.swapaxes(Gs, 0, 2) * scaleVals, 0, 2) # may", "list has the SAME length as fInds). calc_and_fill_fn(spamTuple, fInds, gInds, pslc1, pslc2, False)", "tree of gate strings. Similar to `bulk_fill_probs(...)`, but fills a 2D array with", "respect to only those two gates' parameters and fill # add the result", "copy is needed) # transposes each of the now un-vectorized dim x dim", "prMxToFill : numpy array, optional when not None, an already-allocated length-E numpy array", "m: x0 = _np.kron(_np.transpose(prods[(l + 1, m - 1)]), prods[(m + 1, N", "This argument must be None if wrtFilter is not None. Set this to", "i,lOp in enumerate(gateLabelList): # G = _np.dot(G,self[lOp]) # product of gates, starting with", "self.Np)) _fas(d2pr_drhos, [0, None, self.sos.get_prep(rholabel).gpindices], _np.dot(_np.dot(E, dprod_dOps), rhoVec.deriv_wrt_params())[0]) # (= [0,:,:]) d2pr_dEs =", "currently needed. N = len(revOpLabelList) for m, opLabel1 in enumerate(revOpLabelList): inds1 = gpindices1[opLabel1]", "= [ # _slct.shift(_slct.intersect( # wrtSlices['effects'], # slice(self.e_offset[i],self.e_offset[i+1])), # -self.e_offset[i]) for i in", "all the products within decent bounds #assert( len( (_np.isnan(dGs)).nonzero()[0] ) == 0 )", "than `cacheSize`) the tree will hold. Returns ------- int The memory estimate in", "xv), dop_dopLabel2[opLabel2]) # above: (nDerivCols1,dim**2,dim**2) * (dim**2,nDerivCols2) = (nDerivCols1,dim**2,nDerivCols2) flattened_d2prod[:, inds1, inds2] +=", "# rho_global_slices=global_rho_slices, # e_local_slices=loc_e_slices, # e_global_slices=global_e_slices, # num_rho_params=self.tot_rho_params, # num_e_params=self.tot_e_params) def _hprobs_from_rhoE(self, spamTuple,", "G) # LEXICOGRAPHICAL VS MATRIX ORDER return G def _process_wrtFilter(self, wrtFilter, obj): \"\"\"", "deriv value trumps since we've renormed to keep all the products within decent", "non-None to reduce amount of intermediate memory required. profiler : Profiler, optional A", "= subtrees[iSubTree] felInds = evalSubTree.final_element_indices(evalTree) #Free memory from previous subtree iteration before computing", "True, a N x M array, where: - N == the number of", "respect to the k-th then k-th model parameters. \"\"\" # LEXICOGRAPHICAL VS MATRIX", "= comm_blkSize if (blkSize2 is None) \\ else min(comm_blkSize, blkSize2) # override with", "mxToFill, evalTree, prMxToFill=None, deriv1MxToFill=None, deriv2MxToFill=None, clipTo=None, check=False, comm=None, wrtFilter1=None, wrtFilter2=None, wrtBlockSize1=None, wrtBlockSize2=None, gatherMemLimit=None):", "= dpr_drhos + dpr_dEs + dpr_dOps d2pr_drhos = _np.zeros((1, self.Np, self.Np)) _fas(d2pr_drhos, [0,", "a length-1 (single-gate) sequence \"\"\" dim = self.dim gate = self.sos.get_operation(opLabel) op_wrtFilter, gpindices", "Gs = prodCache = scaleCache = None #Fill cache info prodCache, scaleCache =", "simplified_effect_label) Specifies the prep and POVM effect used to compute the probability. circuit", "wrtFilter2=None): \"\"\" Return the Hessian of many operation sequence products at once. Parameters", "i-th operation sequence scaleExps = evalTree.final_view(scaleCache) old_err = _np.seterr(over='ignore') scaleVals = _np.exp(scaleExps) #", "nCircuits, dim, dim ) profiler.mem_check(\"bulk_fill_dprobs: post compute product\") def calc_and_fill(spamTuple, fInds, gInds, pslc1,", "for ii, i in enumerate(wrtFilter): if i in gpindices: relevant_gpindices.append(ii) obj_wrtFilter.append(list(gpindices).index(i)) relevant_gpindices =", "import Label as _Label from .matrixevaltree import MatrixEvalTree as _MatrixEvalTree from .forwardsim import", "dG(L)/dij) ) # noqa # if dG(L)/dij = E(i,j) # noqa # =", "noqa # d2prod/d(opLabel1)_kl*d(opLabel2)_ij = sum_{M s.t. GM == gatelabel1} sum_{L s.t. GL ==", "rho)))**2) else: # evotype == \"densitymx\" ps = _np.real(_np.dot(Es, _np.dot(G, rho))) ps =", "is not None: assert(wrtBlockSize is None) # Cannot specify both wrtFilter and wrtBlockSize", "= blocks1[iBlk1] wrtSlice2 = blocks2[iBlk2] self._fill_result_tuple((prMxToFill, deriv1MxToFill, deriv2MxToFill, mxToFill), evalSubTree, blocks1[iBlk1], blocks2[iBlk2], calc_and_fill)", "dProdCache1 for wrtSlice1, wrtSlice2 in wrtSlicesList: if wrtSlice1 != last_wrtSlice1: dProdCache1 = dGs1", "( len(circuit_list), dim, dim ), # Gs[i] is product for i-th operation sequence", "dproduct cache calc.\") dProdCache = _np.zeros((cacheSize,) + deriv_shape) # This iteration **must** match", "parameters and fill appropriate columns of flattened_dprod. #gate = self.sos.get_operation[opLabel] UNNEEDED (I think)", "are kept contiguous, so the first identity below is valid. # Below we", "fill\") dProdCache = dGs = None # free mem else: # Divide columns", "None and wrtBlockSize2 is None) # Cannot specify both wrtFilter and wrtBlockSize wrtSlice2", "evalTree.spamtuple_indices.items(): circuit_list = master_circuit_list[gInds] if prMxToFill is not None: check_vp = _np.array([self.prs(spamTuple[0], [spamTuple[1]],", "== \"bulk_dproduct\": # mem += cache_size * num_params * dim * dim #", "is allocated within # the generator and yielded, *not* allocated by the user.", "if m < l: x0 = _np.kron(_np.transpose(prods[(0, m - 1)]), prods[(m + 1,", "= self._compute_dproduct_cache( evalSubTree, prodCache, scaleCache, blk2Comm, blk_wrtSlice2) dGs2 = evalSubTree.final_view(dProdCache2, axis=0) hProdCache =", "list of # all of the raw operation sequences which need to be", "to reconstruct the # *non-final* parent-tree elements from those of the sub-trees. _warnings.warn(\"Increased", "M is the number of model parameters selected for the 1st and 2nd", "then subtrees (even == 1) in order to perform the parallelization over the", "estimate_mem_usage(self, subcalls, cache_size, num_subtrees, num_subtree_proc_groups, num_param1_groups, num_param2_groups, num_final_strs): \"\"\" Estimate the memory required", "tree of operation sequences. This routine fills a 1D array, `mxToFill` with the", "rho))) ps = ps.flatten() if _np.any(_np.isnan(ps)): if len(circuit) < 10: strToPrint = str(circuit)", "parameter rows (the length of rowSlice) - B' is the number of parameter", "GN)^T vec( dG(M)/dkl ) ) )^T vec( dG(L)/dij ) ] # noqa #", "drhoP[l,J] # d2pr_drhos[i,j,J0+J] = dot(E, dGs, drhoP)[0,i,j,J] # d2pr_drhos[:,:,J0+J] = squeeze(dot(E, dGs, drhoP),axis=(0,))[:,:,J]", "TODO: a better way dim = self.dim nspam = int(round(_np.sqrt(self.dim))) # an estimate", "self.dim gate = self.sos.get_operation(opLabel) op_wrtFilter1, gpindices1 = self._process_wrtFilter(wrtFilter1, gate) op_wrtFilter2, gpindices2 = self._process_wrtFilter(wrtFilter2,", "2-tuple (min,max) to clip returned probability to if not None. Only relevant when", "+= cache_size # scale cache mem += cache_size # scale vals ## It", "else len(wrtFilter1) num_deriv_cols2 = self.Np if (wrtFilter2 is None) else len(wrtFilter2) flattened_d2prod =", "as there\" \" are more cpus than hessian elements.\") # pragma: no cover", "cache are given by evalTree's initial single- or zero-operation labels wrtIndices1 = _slct.indices(wrtSlice1)", "\"simplified\" circuits in that they should only contain \"deterministic\" elements (no POVM or", "prodCache, scaleCache, mySubComm, wrtSlice, profiler) dGs = evalSubTree.final_view(dProdCache, axis=0) #( nCircuits, nDerivCols, dim,", "dProdCache1[:, myDeriv1ColSlice], dProdCache2[:, myDeriv2ColSlice], scaleCache, None, myHessianSlice1, myHessianSlice2) # pass None as comm,", "prodCache = scaleCache = dProdCache = None #Fill cache info (not requiring column", "dProdCache1, dProdCache2, scaleCache, comm, wrtSlice1, wrtSlice2) hGs = evalTree.final_view(hProdCache, axis=0) if bReturnDProbs12: dprobs1", "derivatives of each of the product components (i.e. prod_kl) with # respect to", "0 # d2pr/d(rho)_i d(rho)_j = 0 rholabel, elabel = spamTuple rho, E =", "x = _np.dot(_np.transpose(dop_dopLabel1[opLabel1]), x0); xv = x.view() # (nDerivCols1,dim**2) xv.shape = (nDerivCols1, dim,", "deriv value (see below) dGs[_np.isnan(dGs)] = 0 _np.seterr(**old_err) if flat: dGs = _np.swapaxes(_np.swapaxes(dGs,", "Affects the shape of the returned derivative array (see below). wrtFilter1, wrtFilter2 :", "(G(L+1) ... GN)^T vec( dG(L)/dij ) ] # noqa # = sum{...} [", "), # Gs[i] is product for i-th operation sequence dGs1 = evalTree.final_view(dProdCache1, axis=0)", "= wrtSlice1 if (wrtSlice1 == wrtSlice2): dProdCache2 = dProdCache1; dGs2 = dGs1 else:", "2) # cols = deriv cols, rows = all else return (hGs, dGs1,", "entries in a single flattened gate (ordering same as numpy.flatten), - S,M ==", "# product of no gates #Also Cache gate jacobians (still relatively little mem", "gate (so we only need to compute this gate hessian once). But since", "e_global_slices num_rho_params num_e_params') # # if wrtSlices is not None: # loc_rho_slices =", "+ d2pr_d2Es + d2pr_dEs2 # wrt E ret += d2pr_drhos1 + d2pr_dEs1 +", "dGs = evalSubTree.final_view(dProdCache, axis=0) #( nCircuits, nDerivCols, dim, dim ) self._fill_result_tuple( (mxToFill,), evalSubTree,", "deriv2MxToFill, mxToFill), evalSubTree, blocks1[iBlk1], blocks2[iBlk2], calc_and_fill) hProdCache = hGs = dProdCache2 = dGs2", "mxToFill, [], 0, comm, gatherMemLimit) if deriv1MxToFill is not None: _mpit.gather_indices(subtreeElementIndices, subTreeOwners, deriv1MxToFill,", "'PrepEffectFilter', 'rho_local_slices rho_global_slices ' + # 'e_local_slices e_global_slices num_rho_params num_e_params') # # if", "_time.time() # combine iLeft + iRight => i # LEXICOGRAPHICAL VS MATRIX ORDER", "= evalTree.final_view(hProdCache, axis=0) #shape == ( len(circuit_list), nDerivCols1, nDerivCols2, dim, dim ), #", "usage. Cannot be specified in conjuction with wrtBlockSize. wrtBlockSize : int or float,", "# in bytes: TODO: a better way dim = self.dim nspam = int(round(_np.sqrt(self.dim)))", "bool, optional When True, return a scaling factor (see below). comm : mpi4py.MPI.Comm,", "nBlks, start=0) # Create placeholder dGs for *no* gate params to compute #", "2, blk1Comm, gatherMemLimit) #gather row results; gather axis 1 of mxToFill[felInds], dim=(ks,M,M) _mpit.gather_slices(blocks1,", "# Compute the derivative of the entire operation sequence with respect to the", "# dproduct cache # mem += cache_size * dim * dim # product", "columns of flattened_dprod. #gate = self.sos.get_operation[opLabel] UNNEEDED (I think) _fas(flattened_dprod, [None, gpindices], gate.deriv_wrt_params(op_wrtFilter))", "assert(wrtSlice2 is None or _slct.length(wrtSlice2) == nDerivCols2) hessn_shape = (nDerivCols1, nDerivCols2, dim, dim)", "parameters being differentiated with respect to. If there are more processors than model", "self._compute_product_cache(evalSubTree, mySubComm) #use cached data to final values scaleVals = self._scaleExp(evalSubTree.final_view(scaleCache)) Gs =", "rho, Es def _probs_from_rhoE(self, rho, E, Gs, scaleVals): if self.evotype == \"statevec\": raise", "since we can't do any # further parallelization tm = _time.time() all_results =", "is not None. Set this to non-None to reduce amount of intermediate memory", "subTreeOwners, mxToFill, [], 0, comm) #note: pass mxToFill, dim=(KS), so gather mxToFill[felslc] (axis=0)", "each processor a list appropriate for it. # Use comm only for speeding", "derivative of the entire operation sequence with respect to the # gate's parameters", "E_gpindices1, E_gpindices2], _np.tensordot(dp_dAnyE, self.sos.get_effect(elabel).hessian_wrt_params( E_wrtFilter1, E_wrtFilter2), (1, 0))) # _np.einsum('ij,jkl->ikl', dp_dAnyE, self.sos.get_effect(elabel).hessian_wrt_params( #", "which gate parameters to differentiate with respect to in the first (row) and", "tm = _time.time() old_err = _np.seterr(over='ignore') rho, E = self._rhoE_from_spamTuple(spamTuple) block_wrtSlice = pslc1", "dEP)[:,J] dp_dEs = _np.zeros((nCircuits, nDerivCols)) # may overflow, but OK (deriv w.r.t any", "m - 1)]), prods[(m + 1, N - 1)]) # (dim**2, dim**2) #", "most blkSize assert(wrtFilter1 is None and wrtFilter2 is None) # cannot specify both", "but OK) ps = _np.real(_np.dot(Es, _np.dot(G, rho)) * scale) _np.seterr(**old_err) else: # no", "dProdCache = _np.zeros((cacheSize,) + deriv_shape) # This iteration **must** match that in bulk_evaltree", "may generate overflow, but OK _fas(d2pr_dErhos, [0, EVec.gpindices, self.sos.get_prep(rholabel).gpindices], _np.dot(_np.transpose(EVec.deriv_wrt_params()), derivWrtAnyEvec)) #Note: these", "dProdCache[iLeft], dProdCache[iRight] dProdCache[i] = _np.dot(dL, R) + \\ _np.swapaxes(_np.dot(L, dR), 0, 1) #", "evalTree.distribute(comm) #if comm is not None: # print(\"MPI DEBUG: Rank%d subtee sizes =", "# Under the terms of Contract DE-NA0003525 with NTESS, the U.S. Government retains", "dprod/d(opLabel)_ij ) = sum_{L s.t. G(L) == oplabel} [ (G1 ... G(L-1)) tensor", "much slower when True. comm : mpi4py.MPI.Comm, optional When not None, an MPI", "subTreeOwners, prMxToFill, [], 0, comm) #note: pass prMxToFill, dim=(KS,), so gather prMxToFill[felInds] (axis=0)", "\"gate sequence indices\" = indices into the (tree-) list of # all of", ") ) )^T vec( dG(L)/dij ) ] # noqa # + sum{ L", "Gs.shape[0] rho_wrtFilter, rho_gpindices = self._process_wrtFilter(wrtSlice, self.sos.get_prep(rholabel)) E_wrtFilter, E_gpindices = self._process_wrtFilter(wrtSlice, self.sos.get_effect(elabel)) nDerivCols =", "#note: pass mxToFill, dim=(KS,M), so gather mxToFill[felInds] (axis=0) if prMxToFill is not None:", "OK d2pr_d2Es = _np.zeros((nCircuits, nDerivCols1, nDerivCols2)) _fas(d2pr_d2Es, [None, E_gpindices1, E_gpindices2], _np.tensordot(dp_dAnyE, self.sos.get_effect(elabel).hessian_wrt_params( E_wrtFilter1,", "\\ # % (nDerivCols, str(allDerivColIndices), comm.Get_rank(), str(myDerivColIndices))) if mySubComm is not None and", "from previous subtree iteration before computing caches scaleVals = Gs = dGs =", "for additional model classes (e.g. ones which use entirely different -- non-gate-local --", "evalTree, prodCache, scaleCache, comm, wrtSlice1) dGs1 = evalTree.final_view(dProdCache1, axis=0) last_wrtSlice1 = wrtSlice1 if", "d2pr_dErhos = _np.zeros((1, self.Np, self.Np)) derivWrtAnyEvec = scale * _np.dot(prod, rhoVec.deriv_wrt_params()) # may", "a specified sequence of operation labels. Note: LinearOperator matrices are multiplied in the", "(i.e. for l==m) then # it could make sense to iterate through the", "arguments), and in general only a specified slice of the values for this", "respect to the # gate's parameters and fill appropriate columns of flattened_dprod. _fas(flattened_hprod,", "iRight => i # LEXICOGRAPHICAL VS MATRIX ORDER Note: we reverse iLeft <=>", "below). Returns ------- product : numpy array The product or scaled product of", "SPAMVecs #Derivs wrt Gates old_err = _np.seterr(over='ignore') prod, scale = self.product(circuit, True) dprod_dOps", "S such that scaleVals[i] contains the multiplicative scaling needed for the derivatives and/or", "S x M x G x G, where - S == len(circuit_list) -", "spamTuple, (fInds, gInds) in evalTree.spamtuple_indices.items(): circuit_list = master_circuit_list[gInds] if prMxToFill is not None:", "mxToFill, specifying the correspondence between rows of mxToFill and spam labels. evalTree :", "assumes that d^2 G/(dij)^2 == 0, which is true IF each operation matrix", "= int(round(_np.sqrt(self.dim))) # an estimate - could compute? wrtLen1 = (self.Np + np1", "#elif fnName == \"bulk_hproduct\": # mem += cache_size * num_params**2 * dim *", "out of %d products\" % (cnt, len(evalTree)) nanOrInfCacheIndices = (~_np.isfinite(prodCache)).nonzero()[0] # may be", "this doesn't involve gate derivatives d2pr_dErhos2 = _np.transpose(d2pr_dErhos1, (0, 2, 1)) else: d2pr_dErhos2", "then matrixOf(circuit[i]) = matrixOf(circuit[iLeft]) * matrixOf(circuit[iRight]) (iRight, iLeft) = evalTree[i] L, R =", "Gs = evalSubTree.final_view(prodCache, axis=0) #( nCircuits, dim, dim ) profiler.mem_check(\"bulk_fill_dprobs: post compute product\")", "x M numpy array, where: - N == the number of entries in", "if gl1 and gl2 are both in opsToVectorize1 and opsToVectorize2 we only compute", "product for i-th operation sequence dGs = evalTree.final_view(dProdCache, axis=0) #shape == ( len(circuit_list),", ") ] # noqa # + sum{ L < M} [ G1 ...", "else len(wrtFilter2) flattened_hprod = _np.zeros((dim**2, num_deriv_cols1, num_deriv_cols2), 'd') if _slct.length(gpindices1) > 0 and", "subset of all the derivative columns, essentially taking # a derivative of only", "xv = x.view() xv = _np.transpose(xv, axes=(2, 0, 1)) # (dim2, nDerivCols1, nDerivCols2)", "of a length-1 (single-gate) sequence \"\"\" dim = self.dim gate = self.sos.get_operation(opLabel) op_wrtFilter1,", "[] # indices into original wrtFilter'd indices gpindices = obj.gpindices_as_array() for ii, i", "For example, the Hessian of a function of many gate sequence probabilities can", "# d2pr_dEs[:,:,J0+J] = dot( squeeze(dot(dGs, rho),axis=(3,)), dEP)[:,:,J] d2pr_dEs1 = _np.zeros((nCircuits, nDerivCols1, nDerivCols2)) dp_dAnyE", "tStart = _time.time() if profiler is None: profiler = _dummy_profiler if wrtFilter is", "array The product or scaled product of the operation matrices. scale : float", "National Technology & Engineering Solutions of Sandia, LLC (NTESS). # Under the terms", "tree to parallelize computation, since there are no memory savings from using a", "corresponds to a (opLabel,i,j) tuple and each row corresponds to an element of", "gates G = ident for (j, opLabel2) in enumerate(revOpLabelList[i:], start=i): # loop over", "== oplabel} [ (G1 ... G(L-1)) tensor (G(L+1) ... GN)^T ]] has #", "def hproduct(self, circuit, flat=False, wrtFilter1=None, wrtFilter2=None): \"\"\" Compute the hessian of a specified", "element of cache are given by evalTree's initial single- or zero-operation labels wrtIndices1", "to if not None. Only relevant when prMxToFill is not None. bUseScaling :", "dim, dim)) scaleCache = _np.zeros(cacheSize, 'd') #First element of cache are given by", "GN)^T vec( dG(L)/dij ) ] # noqa # = sum{...} [ unvec( G1", "no gates #Also Cache gate jacobians (still relatively little mem required) dop_dopLabel1 =", "of operation sequences (i.e. evalTree.num_final_strings()), - B is the number of parameter rows", "derivative calculations across multiple processors. Returns ------- deriv : numpy array * if", "!= opLabel: continue # loop over locations of opLabel LRproduct = _np.kron(leftProds[i], rightProdsT[N", "to the elements of `elabels`. \"\"\" assert(time is None), \"MatrixForwardSimulator cannot be used", "\"\"\" tStart = _time.time() if profiler is None: profiler = _dummy_profiler if wrtFilter", "1)) d2pr_dErhos2 = _np.transpose(d2pr_dErhos2, (0, 2, 1)) #Note: these 2nd derivatives are non-zero", "each gate's parameters (in the order specified by the model). This argument is", "== 1) in order to perform the parallelization over the parameter groups. num_param1_groups", "arrays are. np1, np2 = num_param1_groups, num_param2_groups FLOATSIZE = 8 # in bytes:", "a linear cache space. Will use derivative columns and then (and only when", "\"results\" memory since this is allocated within # the generator and yielded, *not*", "rho, E, Gs[gInds], dGs1[gInds], dGs2[gInds], hGs[gInds], scaleVals[gInds], wrtSlice1, wrtSlice2), add=sumInto) _np.seterr(**old_err) #Set wrtBlockSize", "as we assume the user has already done any such distribution # and", "Gs[gInds], dGs[gInds], scaleVals[gInds], wrtSlice), add=sumInto) _np.seterr(**old_err) profiler.add_time(\"bulk_fill_dprobs: calc_and_fill\", tm) #Set wrtBlockSize to use", "label (given by the subsequent arguments, except for the last). The final argument", "_np.zeros((nElements, _slct.length(wrtSlice2)), 'd') else: dprobs1 = dprobs2 = None hprobs = _np.zeros((nElements, _slct.length(wrtSlice1),", "is None or _slct.length(wrtSlice1) == nDerivCols1) assert(wrtSlice2 is None or _slct.length(wrtSlice2) == nDerivCols2)", "cache_size # scale vals elif fnName == \"bulk_fill_hprobs\": mem += cache_size * wrtLen1", "processors. Returns ------- hessians : numpy array * if flat == False, an", "E[0,l] hGs[i,j,k,l,m] rho[m,0] # d2pr_dOps2[i,j,k] = sum_l E[0,l] dot( dGs, rho )[i,j,k,l,0] #", "(G(L+1) ... GN)^T ]] * vec( dG(L)/dij) ) # noqa # if dG(L)/dij", ": 2-tuple (min,max) to clip returned probability to if not None. Only relevant", "if deriv1MxToFill is not None: _mpit.gather_slices(blocks1, blk1Owners, deriv1MxToFill, [felInds], 1, mySubComm, gatherMemLimit) if", "wrt SPAM if returnDeriv: # same as in dpr(...) dpr_drhos = _np.zeros((1, self.Np))", "sequence product with respect to the k-th then j-th model parameters. * if", "that makes maximal use of available processors is used as the final block", "wrtSlicesList across comm procs, # as we assume the user has already done", "speed could be obtained\" \" by giving hproduct cache computation\" \" *fewer* processors", "luckily never used) - so it's been removed. if comm is not None:", "by the sequence and spam label indexed by iOpStr and iSpamLabel. d12 has", "with respect to the j-th model parameter. \"\"\" # LEXICOGRAPHICAL VS MATRIX ORDER", "[fInds, pslc2], self._dprobs_from_rhoE( spamTuple, rho, E, Gs[gInds], dGs2[gInds], scaleVals[gInds], wrtSlice2), add=sumInto) _fas(mxToFill, [fInds,", "below). bReturnProds : bool, optional when set to True, additionally return the probabilities.", "= _dummy_profiler if wrtFilter is not None: assert(wrtBlockSize is None) # Cannot specify", "rho),axis=(3,)), dEP)[i,j,J] # d2pr_dEs[:,:,J0+J] = dot( squeeze(dot(dGs, rho),axis=(3,)), dEP)[:,:,J] d2pr_dEs1 = _np.zeros((nCircuits, nDerivCols1,", "1e-100 class MatrixForwardSimulator(ForwardSimulator): \"\"\" Encapsulates a calculation tool used by model objects to", "_np.log(nG) # LEXICOGRAPHICAL VS MATRIX ORDER else: G = H old_err = _np.seterr(over='ignore')", "boolean specifying whether the filling should overwrite or add to the existing array", "return flattened_dprod else: # axes = (gate_ij, prod_row, prod_col) return _np.swapaxes(flattened_dprod, 0, 1).reshape((num_deriv_cols,", "memory required. profiler : Profiler, optional A profiler object used for to track", "Return the derivative of a length-1 (single-gate) sequence \"\"\" dim = self.dim gate", "= sum E_k prod_kl rho_l # dpr/d(opLabel)_ij = sum E_k [dprod/d(opLabel)_ij]_kl rho_l #", "prep and effect parameters onto a final \"filtered\" set. # \"\"\" # PrepEffectFilter", "optional when set to True, additionally return the probabilities. bScale : bool, optional", "sum(tmp_num_params[0:i]) for i in range(len(self.effects)+1) ] # global_e_slices = [ slice(tmp_offsets[i],tmp_offsets[i+1]) # for", "a split evalTree (if given) is possible. wrtFilter : list of ints, optional", "scaleCache, None, myHessianSlice1, wrtSlice2) # pass None as comm, *not* mySubComm (this is", "from .forwardsim import ForwardSimulator _dummy_profiler = _DummyProfiler() # Smallness tolerances, used internally for", "average size == blkSize blocks = _mpit.slice_up_range(self.Np, nBlks, start=0) # Create placeholder dGs", "# dp_dOps[i,j] = sum_k,l E[0,k] dGs[i,j,k,l] rho[l,0] # dp_dOps[i,j] = sum_k E[0,k] dot(", "num_param1_groups, num_param2_groups, num_final_strs): \"\"\" Estimate the memory required by a given set of", "are always zero _np.seterr(**old_err) if returnDeriv: if returnPr: return ret, dpr, p else:", "ret = _np.clip(ps, clipTo[0], clipTo[1]) else: ret = ps #DEBUG CHECK #check_ps =", "single-gate-strings) for i in evalTree.get_evaluation_order(): # combine iLeft + iRight => i #", "num_e_params') # # if wrtSlices is not None: # loc_rho_slices = [ #", "wrtFilter is not None. Set this to non-None to reduce amount of intermediate", "Only relevant when prMxToFill is not None. Returns ------- hessian : numpy array", "for j in range(self.Np): d2pr_dOps2[0, i, j] = float(_np.dot(E, _np.dot(d2prod_dGates[i, j], rho))) old_err", "2, 0)), x0); xv = x.view() xv = _np.transpose(xv, axes=(2, 0, 1)) #", "computing caches scaleVals = Gs = dGs1 = dGs2 = hGs = None", "= [] G = _np.identity(dim); leftProds.append(G) for opLabel in revOpLabelList: G = _np.dot(G,", "= _np.zeros((cacheSize, dim, dim)) scaleCache = _np.zeros(cacheSize, 'd') #First element of cache are", "given arguments \"\"\" tm = _time.time() old_err = _np.seterr(over='ignore') rho, E = self._rhoE_from_spamTuple(spamTuple)", "and hProdCache[i].max() < HSMALL and hProdCache[i].min() > -HSMALL: _warnings.warn(\"hProd is small (oh well!).\")", "rho, E, Gs[gInds], scaleVals[gInds]), add=sumInto) _fas(mxToFill, [fInds, pslc1], self._dprobs_from_rhoE( spamTuple, rho, E, Gs[gInds],", "dot(dEPT,prod,drhoP)[J,i,K] # d2pr_dErhos[i,J0+J,K0+K] = swapaxes(dot(dEPT,prod,drhoP),0,1)[i,J,K] # d2pr_dErhos[:,J0+J,K0+K] = swapaxes(dot(dEPT,prod,drhoP),0,1)[:,J,K] d2pr_dErhos1 = _np.zeros((nCircuits, nDerivCols1,", "not None. check : boolean, optional If True, perform extra checks within code", "iSubTree in mySubTreeIndices: evalSubTree = subtrees[iSubTree] felInds = evalSubTree.final_element_indices(evalTree) #Free memory from previous", "a function of many gate sequence probabilities can often be computed column-by-column from", "`mx`, `dp1`, and `dp2` are the outputs of :func:`bulk_fill_hprobs` (i.e. args `mxToFill`, `deriv1MxToFill`,", "model parameter. products : numpy array Only returned when bReturnProds == True. An", "(G(L+1) ... GN)^T vec( dG(L)/dij ) ] # noqa # + sum{ L", "\"\"\" Computes a tree of product 2nd derivatives in a linear cache space.", "num blocks required to achieve desired average size == blkSize blocks = _mpit.slice_up_range(self.Np,", "d2pr_d2rhos + d2pr_d2Es + d2pr_dOps2 # Note: add transposes b/c spam terms only", "# pass None as comm, *not* mySubComm, since we can't do any #", "_warnings.warn(\"Too many processors to make use of in \" \" _compute_dproduct_cache.\") if mySubComm.Get_rank()", "parameters onto a final \"filtered\" set. # \"\"\" # PrepEffectFilter = _collections.namedtuple( #", "axis=0) dGs2 = evalSubTree.final_view(dProdCache2, axis=0) #( nCircuits, nDerivColsX, dim, dim ) hProdCache =", "the first element of circuit can be thought of as the first gate", "ret def dpr(self, spamTuple, circuit, returnPr, clipTo): \"\"\" Compute the derivative of a", "like 'Imyinst_0') returnPr : bool when set to True, additionally return the probability", "shape K x S x B x B', where: - K is the", "# d2pr_drhos[:,:,J0+J] = squeeze(dot(E, dGs, drhoP),axis=(0,))[:,:,J] drho = rhoVec.deriv_wrt_params(rho_wrtFilter2) d2pr_drhos1 = _np.zeros((nCircuits, nDerivCols1,", "and dProdCache[i].min() > -DSMALL: _warnings.warn(\"Scaled dProd small in order to keep prod managable.\")", "obtained\" \" by giving dproduct cache computation\" \" *fewer* processors and *smaller* (sub-)tree\"", "nCircuits * dim**2)), 0, 1) # cols = deriv cols, rows = flattened", "True, return a scaling factor (see below). comm : mpi4py.MPI.Comm, optional When not", "rows = all else return (hGs, dGs1, dGs2, Gs, scaleVals) if bScale else", "blkSize assert(wrtFilter1 is None and wrtFilter2 is None) # cannot specify both wrtFilter", "free Mem dProdCache1 = self._compute_dproduct_cache( evalTree, prodCache, scaleCache, comm, wrtSlice1) dGs1 = evalTree.final_view(dProdCache1,", "conditional scaling required # to control bulk products, their gradients, and their Hessians.", "= _np.dot(_np.transpose(dop_dopLabel1[opLabel1]), x0); xv = x.view() # (nDerivCols1,dim**2) xv.shape = (nDerivCols1, dim, dim)", "if vec(.) concatenates rows (which numpy.flatten does) # vec( A * E(0,1) *", "corresponding to the elements of `elabels`. \"\"\" assert(time is None), \"MatrixForwardSimulator cannot be", "of products in a linear cache space. Will *not* parallelize computation, even if", ") = sum E_k prod_kl rho_l # dpr/d(opLabel)_ij = sum E_k [dprod/d(opLabel)_ij]_kl rho_l", "which) dp_dAnyE = _np.squeeze(_np.dot(Gs, rho), axis=(2,)) * scaleVals[:, None] _fas(dp_dEs, [None, E_gpindices], _np.dot(dp_dAnyE,", "as in dpr(...) dpr_dOps = _np.empty((1, self.Np)) for i in range(self.Np): dpr_dOps[0, i]", "gate-set parameters (by wrtFilter1 and wrtFilter2). evalTree : EvalTree given by a prior", "if blkComm is not None: _warnings.warn(\"Note: more CPUs(%d)\" % mySubComm.Get_size() + \" than", "but ok # may overflow or get nans (invalid), but ok dGs1 =", "rho, E = self._rhoE_from_spamTuple(spamTuple) if prMxToFill is not None: _fas(prMxToFill, [fInds], self._probs_from_rhoE(rho, E,", "axis=0) hProdCache = self._compute_hproduct_cache( evalSubTree, prodCache, dProdCache1, dProdCache2, scaleCache, blk2Comm, blk_wrtSlice1, blk_wrtSlice2) hGs", "fInds, gInds, pslc1, pslc2, sumInto): \"\"\" Compute and fill result quantities for given", "evolution not fully supported yet!\") # pr = Tr( |rho><E| * prod )", "\\ # % (nDerivCols2, comm.Get_rank(), str(myDerivColSlice))) if mySubComm is not None and mySubComm.Get_size()", "of mxToFill[felInds], dim=(ks,M) profiler.add_time(\"MPI IPC\", tm) profiler.mem_check(\"bulk_fill_dprobs: post gather blocks\") #collect/gather results tm", "_np.einsum('ij,jkl->ikl',derivWrtAnyEvec,self.sos.get_effect(elabel).hessian_wrt_params()) else: d2pr_d2Es = 0 ret = d2pr_dErhos + _np.transpose(d2pr_dErhos, (0, 2, 1))", "set of gate parameters if wrtSlice1 == wrtSlice2: # Note: this doesn't involve", "to compute reduce results from a single column of the Hessian at a", "anything on \"extra\", i.e. rank != 0, cpus hProdCache[:, myDeriv1ColSlice, myDeriv2ColSlice] = self._compute_hproduct_cache(", "as these occur b/c an inf scaleVal is mult by a zero hessian", "mxToFill = hprobs #Fill arrays self._fill_result_tuple((None, dprobs1, dprobs2, hprobs), evalTree, slice(None), slice(None), calc_and_fill)", "above) if wrtSlice2 is not None and wrtSlice2.start is not None: myHessianSlice2 =", "(nDerivCols1, nDerivCols2, nCircuits * dim**2)), 2) # cols = deriv cols, rows =", "*simplified* gate strings to compute the bulk operation on. clipTo : 2-tuple, optional", "the ideal/desired cache size given a number of operation sequences. Returns ------- int", "if wrtFilter1 is not None: assert(wrtBlockSize1 is None and wrtBlockSize2 is None) #", "None: _fas(prMxToFill, [fInds], self._probs_from_rhoE(rho, E, Gs[gInds], scaleVals[gInds]), add=sumInto) if deriv1MxToFill is not None:", "profiler.add_count(\"compute_dproduct_cache: dots\") scale = scaleCache[i] - (scaleCache[iLeft] + scaleCache[iRight]) if abs(scale) > 1e-8:", "# warning -- note that we *cannot* make use of a tree being", "to compute *products* for simultaneously. None means compute all requested rows or columns", "an MPI communicator for distributing the computation across multiple processors. Distribution is first", "sequence and spam tuple as a 1 x M numpy array, where M", "evTree = _MatrixEvalTree() evTree.initialize(simplified_circuits, numSubtreeComms) return evTree def estimate_mem_usage(self, subcalls, cache_size, num_subtrees, num_subtree_proc_groups,", "0, 1).reshape((nDerivCols2, nCircuits * dim**2)), 0, 1) hGs = _np.rollaxis(_np.rollaxis(hGs, 0, 3).reshape( (nDerivCols1,", "calc_and_fill(spamTuple, fInds, gInds, pslc1, pslc2, sumInto): \"\"\" Compute and fill result quantities for", "a matrix for each given (i,j) # noqa # vec( dprod/d(opLabel)_ij ) =", "only a specified slice of the values for this spam label (given by", "dim, dim) cacheSize = len(evalTree) # ------------------------------------------------------------------ if comm is not None and", "1e-6: _warnings.warn(\"norm(vdp-check_vdp) = %g - %g = %g\" % (_nla.norm(dprMxToFill[fInds]), _nla.norm(check_vdp), _nla.norm(dprMxToFill[fInds] -", "nan\" % strToPrint) #DEBUG: print \"backtrace\" of product leading up to nan #G", "scaleCache = self._compute_product_cache(evalTree, comm) dProdCache = self._compute_dproduct_cache(evalTree, prodCache, scaleCache, comm, wrtSlice) #use cached", "d2pr_drhos2 # wrt rho ret += d2pr_dErhos1 + d2pr_d2Es + d2pr_dEs2 # wrt", "fills a 2D array with probability-derivatives for each \"final element\" of `evalTree`. Parameters", "that scaleVals[i] contains the multiplicative scaling needed for the derivatives and/or products for", "only for speeding up the calcs of the given # wrtSlicesList last_wrtSlice1 =", "Return the hessian of a length-1 (single-gate) sequence \"\"\" dim = self.dim gate", "dProdCache[i] /= _np.exp(scale) if dProdCache[i].max() < DSMALL and dProdCache[i].min() > -DSMALL: _warnings.warn(\"Scaled dProd", "nDerivCols1 = self.Np if (wrtFilter1 is None) else _slct.length(wrtFilter1) nDerivCols2 = self.Np if", "cache space. Will use derivative columns and then (and only when needed) a", "dProdCache1 = self._compute_dproduct_cache(evalTree, prodCache, scaleCache, comm, wrtSlice1) dProdCache2 = dProdCache1 if (wrtSlice1 ==", "value trumps since we've renormed to keep all the products within decent bounds", "hProdCache = _np.zeros((cacheSize,) + hessn_shape) #First element of cache are given by evalTree's", "'d') #First element of cache are given by evalTree's initial single- or zero-operation", "< HSMALL and hProdCache[i].min() > -HSMALL: _warnings.warn(\"Scaled hProd small in order to keep", "of the vectorized model - G == the linear dimension of a operation", "sequences using tree (skip over the zero and single-gate-strings) for i in evalTree.get_evaluation_order():", "dpr_dEs = _np.zeros((1, self.Np)) derivWrtAnyEvec = scale * _np.transpose(_np.dot(prod, rho)) # may overflow,", "_np.dot(_np.transpose(dop_dopLabel1[opLabel1]), x0); xv = x.view() # (nDerivCols1,dim**2) xv.shape = (nDerivCols1, dim, dim) #", "of a length-1 (single-gate) sequence \"\"\" dim = self.dim gate = self.sos.get_operation(opLabel) op_wrtFilter,", "is not None) else None #TODO: just allow slices as argument: wrtFilter ->", "through the self.operations.keys() as in # dproduct(...) and find the labels in the", "subtrees (groups if needed) subtrees = evalTree.get_sub_trees() mySubTreeIndices, subTreeOwners, mySubComm = evalTree.distribute(comm) #eval", "value, and we dGs[_np.isnan(dGs)] = 0 # assume the zero deriv value trumps", "dEP^T * prod[i,:,:] * drhoP # d2pr_dErhos[i,J0+J,K0+K] = sum jk dEPT[J,j] prod[i,j,k] drhoP[k,K]", "% (dProdCache.nbytes / (1024.0**3), str(dProdCache.shape))) dGs = evalSubTree.final_view(dProdCache, axis=0) #( nCircuits, nDerivCols, dim,", "respectively. Each element is an index into an array of gate parameters ordered", "of available processors is used as the final block size. This argument must", "should all have norm <= 1 assert(len(nanOrInfCacheIndices) == 0) return prodCache, scaleCache def", "_slct.shift(myDeriv1ColSlice, wrtSlice1.start) else: myHessianSlice1 = myDeriv1ColSlice #print(\"MPI: _compute_hproduct_cache over %d cols (rank %d", "if isinstance(spamTuple[0], _Label): rholabel, elabel = spamTuple # This calculator uses the convention", "This routine fills in `mxToFill`, which must have length equal to the number", "columns allDerivColSlice = slice(0, nDerivCols) if (wrtSlice is None) else wrtSlice _, myDerivColSlice,", "of a tree being # split because there's no good way to reconstruct", "products in a linear cache space. Will *not* parallelize computation, even if given", "wrtSlice1), add=sumInto) if deriv2MxToFill is not None: _fas(deriv2MxToFill, [fInds, pslc2], self._dprobs_from_rhoE( spamTuple, rho,", "product * scale. The purpose of this is to allow a trace or", "and (mySubComm.Get_size() > 1): comm_blkSize = self.Np / mySubComm.Get_size() blkSize1 = comm_blkSize if", "wrtSlices['effects'], # slice(self.e_offset[i],self.e_offset[i+1])), # -self.e_offset[i]) for i in range(len(self.effects))] # tmp_num_params = [_slct.length(s)", "#Fill derivative cache info tm = _time.time() dProdCache = self._compute_dproduct_cache(evalSubTree, prodCache, scaleCache, mySubComm,", "; shape == (len(circuit_list), nDerivCols) # may also give invalid value due to", "operation sequences using tree (skip over the zero and single-gate-strings) for i in", "scale * _np.dot(E, prod) # may overflow, but OK d2pr_d2rhos = _np.zeros((1, self.Np,", "profiler.comm.barrier() profiler.add_time(\"compute_dproduct_cache: serial\", tSerialStart) profiler.add_count(\"compute_dproduct_cache: num columns\", nDerivCols) return dProdCache def _compute_hproduct_cache(self, evalTree,", "dim**2)), 0, 1) hGs = _np.rollaxis(_np.rollaxis(hGs, 0, 3).reshape( (nDerivCols1, nDerivCols2, nCircuits * dim**2)),", "number of final strings (may be less than or greater than `cacheSize`) the", "= max(_nla.norm(gate), 1.0) prodCache[i] = gate / nG scaleCache[i] = _np.log(nG) #evaluate operation", "myDeriv1ColSlice, deriv1Owners, mySubComm = \\ _mpit.distribute_slice(allDeriv1ColSlice, comm) # Get slice into entire range", "be applied to the resulting products (final_product[i] = scaleValues[i] * prods[i]). \"\"\" prodCache,", "Model to allow for additional model classes (e.g. ones which use entirely different", "size. Could throw more informative error? #elif fnName == \"bulk_product\": # mem +=", "gate parameters ordered by concatenating each gate's parameters (in the order specified by", "product, dproduct, etc. to allow for *complex* derivatives, since matrices can be complex", "%d rescalings out of %d products\" % (cnt, len(evalTree)) nanOrInfCacheIndices = (~_np.isfinite(prodCache)).nonzero()[0] #", "warnings when checks fail. Used for testing, and runs much slower when True.", "matrixOf(circuit[iLeft]) * matrixOf(circuit[iRight]) (iRight, iLeft) = evalTree[i] L, R = prodCache[iLeft], prodCache[iRight] dL,", "#( nCircuits, nDerivCols, dim, dim ) self._fill_result_tuple( (mxToFill,), evalSubTree, blocks[iBlk], slice(None), calc_and_fill_blk) profiler.mem_check(\"bulk_fill_dprobs:", "overflow OK d2pr_d2rhos = _np.zeros((nCircuits, nDerivCols1, nDerivCols2)) _fas(d2pr_d2rhos, [None, rho_gpindices1, rho_gpindices2], _np.tensordot(dp_dAnyRho, self.sos.get_prep(rholabel).hessian_wrt_params(", "# Use comm only for speeding up the calcs of the given #", "the j-th model parameter. derivative : numpy array only returned if returnDeriv ==", "to make use of in \" \" _compute_hproduct_cache.\") #TODO: remove: not needed now", "x G, where: - S == the number of operation sequences - G", "colSlice, dprobs12)` (the latter if `bReturnDProbs12 == True`). `rowSlice` and `colSlice` are slices", "the bulk operation on. This tree *cannot* be split. wrtSlicesList : list A", "self.sos.get_prep(rholabel).gpindices], _np.dot(derivWrtAnyRhovec, rhoVec.deriv_wrt_params())) # may overflow, but OK dpr_dEs = _np.zeros((1, self.Np)) derivWrtAnyEvec", "E = self._rhoE_from_spamTuple(spamTuple) _fas(mxToFill, [fInds], self._probs_from_rhoE(rho, E, Gs[gInds], scaleVals[gInds]), add=sumInto) _np.seterr(**old_err) self._fill_result_tuple((mxToFill,), evalSubTree,", "probability, with scaling applied (may generate overflow, but OK) ps = _np.real(_np.dot(Es, _np.dot(G,", "pslc1], self._dprobs_from_rhoE( spamTuple, rho, E, Gs[gInds], dGs[gInds], scaleVals[gInds], block_wrtSlice), add=sumInto) _np.seterr(**old_err) profiler.add_time(\"bulk_fill_dprobs: calc_and_fill_blk\",", "for iBlk1 in myBlk1Indices: blk_wrtSlice1 = blocks1[iBlk1] dProdCache1 = self._compute_dproduct_cache( evalSubTree, prodCache, scaleCache,", "list A list of :class:`Label` objects giving the *simplified* effect labels. circuit :", "= self._rhoEs_from_spamTuples(rholabel, elabels) #shapes: rho = (N,1), Es = (len(elabels),N) if bUseScaling: old_err", "should overwrite or add to the existing array values, which is a functionality", "taking derivatives. paramvec : ndarray The parameter vector of the Model. autogator :", "by a zero deriv value (see below) dGs1[_np.isnan(dGs1)] = 0 # convert nans", "G x G, where: - S == len(circuit_list) - M == the length", "construct virtual gates for use in computations. \"\"\" super(MatrixForwardSimulator, self).__init__( dim, simplified_op_server, paramvec)", "# LEXICOGRAPHICAL VS MATRIX ORDER Note: we reverse iLeft <=> iRight from evalTree", "from a single column of the Hessian at a time. For example, the", "zero. hProdCache[i] = _np.zeros(hessn_shape) else: hoperation = self.hoperation(opLabel, wrtFilter1=wrtIndices1, wrtFilter2=wrtIndices2) hProdCache[i] = hoperation", "complex? _fas(dpr_dEs, [0, EVec.gpindices], _np.dot(derivWrtAnyEvec, EVec.deriv_wrt_params())) _np.seterr(**old_err) if returnPr: return dpr_drhos + dpr_dEs", "None] Es = [self.sos.get_effect(elabel).todense()[:, None] for elabel in elabels] Es = _np.conjugate(_np.transpose(_np.concatenate(Es, axis=1)))", "and hProdCache[i].min() > -HSMALL: _warnings.warn(\"hProd is small (oh well!).\") return hProdCache ## END", "itertools as _itertools import collections as _collections from ..tools import mpitools as _mpit", "def __init__(self, dim, simplified_op_server, paramvec): \"\"\" Construct a new MatrixForwardSimulator object. Parameters ----------", "_np.zeros(hessn_shape) elif not self.sos.get_operation(opLabel).has_nonzero_hessian(): #all gate elements are at most linear in params,", "cols, give a # warning -- note that we *cannot* make use of", "(oh well!).\") return hProdCache ## END CACHE FUNCTIONS def default_distribute_method(self): \"\"\" Return the", "and fill result quantities blocks for given arguments \"\"\" tm = _time.time() old_err", "= scale * _np.dot(E, prod) _fas(dpr_drhos, [0, self.sos.get_prep(rholabel).gpindices], _np.dot(derivWrtAnyRhovec, rhoVec.deriv_wrt_params())) # may overflow,", "is not None: _fas(prMxToFill, [fInds], self._probs_from_rhoE(rho, E, Gs[gInds], scaleVals[gInds]), add=sumInto) if deriv1MxToFill is", "scale vals elif fnName == \"bulk_fill_dprobs\": mem += cache_size * wrtLen1 * dim", "rho_global_slices=global_rho_slices, # e_local_slices=loc_e_slices, # e_global_slices=global_e_slices, # num_rho_params=_slct.length(wrtSlices['preps']), # num_e_params=_slct.length(wrtSlices['effects'])) # else: # loc_rho_slices", "# noqa # = [ sum_{L s.t. G(L) == oplabel} [ (G1 ...", "self.evotype == \"statevec\": ps = _np.real(_np.abs(_np.dot(Es, _np.dot(G, rho)) * scale)**2) else: # evotype", "not None) else None wrtSlice2 = _slct.list_to_slice(wrtFilter2) if (wrtFilter2 is not None) else", "# vp[i] = sum_k E[0,k] dot(Gs, rho)[i,k,0] * scaleVals[i] # vp[i] = dot(", "return list (now have G,dG => product, dprod_dOps) # prod, dprod_dOps = G,dG", "[fInds], self._probs_from_rhoE( rho, E, Gs[gInds], scaleVals[gInds]), add=sumInto) _fas(mxToFill, [fInds, pslc1], self._dprobs_from_rhoE( spamTuple, rho,", "(since there's no good way to reconstruct the parent tree's *non-final* elements from", "- M == length of the vectorized model (number of model parameters) -", "these 2nd derivatives are non-zero when the spam vectors have # a more", "S == len(circuit_list) - M == the length of the vectorized model -", "fundamental operations. \"\"\" def __init__(self, dim, simplified_op_server, paramvec): \"\"\" Construct a new MatrixForwardSimulator", "(l,m)-th entry of the i-th operation sequence product with respect to the k-th", "chance that the product will overflow and the subsequent trace operation will yield", "axis=(0,3)) old_err2 = _np.seterr(invalid='ignore', over='ignore') dp_dOps = _np.squeeze(_np.dot(E, _np.dot(dGs, rho)), axis=(0, 3)) *", "spam labels and values which are integer row indices into mxToFill, specifying the", "sum E_k [dprod/d(opLabel)_mn]_ki (and same for other diff order) # d2pr/d(E)_i d(opLabel)_mn =", "older slower version that should do the same thing (for debugging) master_circuit_list =", "across subtrees (groups if needed) subtrees = evalTree.get_sub_trees() mySubTreeIndices, subTreeOwners, mySubComm = evalTree.distribute(comm)", "be None? assert(nDerivCols1 == nDerivCols2) d2pr_dEs2 = _np.transpose(d2pr_dEs1, (0, 2, 1)) else: d2pr_dEs2", "len(evalTree) # ------------------------------------------------------------------ if comm is not None and comm.Get_size() > 1: #", "final elements (i.e. probabilities) to gate-only sequence and prep/effect pairs. The evaluation tree", "calc_and_fill\", tm) #Set wrtBlockSize to use available processors if it isn't specified if", "#Derivs wrt SPAM derivWrtAnyRhovec = scale * _np.dot(E, prod) dpr_drhos = _np.zeros((1, self.Np))", "of spam_label_rows, - S is the number of operation sequences (i.e. evalTree.num_final_strings()), -", "wrtBlockSize. wrtBlockSize : int or float, optional The maximum number of derivative columns", "self.sos.get_prep(rholabel).gpindices], _np.tensordot(derivWrtAnyRhovec, self.sos.get_prep(rholabel).hessian_wrt_params(), (1, 0))) # _np.einsum('ij,jkl->ikl', derivWrtAnyRhovec, self.sos.get_prep(rholabel).hessian_wrt_params()) else: d2pr_d2rhos = 0", "return Gs, scaleVals else: old_err = _np.seterr(over='ignore') Gs = _np.swapaxes(_np.swapaxes(Gs, 0, 2) *", "# derivatives wrt all spam parameters dGs = _np.empty((Gs.shape[0], 0, self.dim, self.dim), 'd')", "#Compute all requested derivative columns at once self._fill_result_tuple((prMxToFill, deriv1MxToFill, deriv2MxToFill, mxToFill), evalSubTree, slice(None),", "be None if the corresponding wrtFilter is not None. Set this to non-None", "Label as _Label from .matrixevaltree import MatrixEvalTree as _MatrixEvalTree from .forwardsim import ForwardSimulator", "OK devec = EVec.deriv_wrt_params(E_wrtFilter1) _fas(d2pr_dErhos1, (None, E_gpindices1, rho_gpindices2), _np.swapaxes(_np.dot(_np.transpose(devec), dp_dAnyE), 0, 1)) #", "self._scaleExp(evalTree.final_view(scaleCache)) Gs = evalTree.final_view(prodCache, axis=0) #( nCircuits, dim, dim ) #Same as in", "derivative calculations across multiple processors. Returns ------- hessian : numpy array * if", "by splitting tree beforehand), as there\" \" are more cpus than derivative columns.\")", "list of `Circuits` was simplified. Parameters ---------- mxToFill : numpy ndarray an already-allocated", "# swapaxes takes (kl,vec_prod_indx,ij) => (vec_prod_indx,kl,ij) elif l < m: x0 = _np.kron(_np.transpose(prods[(l", "if (wrtSlice1 == wrtSlice2) else \\ self._compute_dproduct_cache(evalTree, prodCache, scaleCache, comm, wrtSlice2) hProdCache =", "tmp_num_params = [_slct.length(s) for s in loc_e_slices] # tmp_offsets = [ sum(tmp_num_params[0:i]) for", "of parameter rows (the length of rowSlice) - B' is the number of", "to distribute columns allDeriv1ColSlice = slice(0, nDerivCols1) allDeriv2ColSlice = slice(0, nDerivCols2) deriv1Slices, myDeriv1ColSlice,", "None), \"MatrixForwardSimulator cannot be used to simulate time-dependent circuits\" rho, Es = self._rhoEs_from_spamTuples(rholabel,", "labels The sequence of operation labels. flat : bool, optional Affects the shape", "dGs[_np.isnan(dGs)] = 0 # assume the zero deriv value trumps since we've renormed", "= dLdRa + _np.swapaxes(dLdRb, 0, 1) hProdCache[i] = _np.dot(hL, R) + dLdR_sym +", "(0, 2, 1)) else: drho = rhoVec.deriv_wrt_params(rho_wrtFilter1) d2pr_drhos2 = _np.zeros((nCircuits, nDerivCols2, nDerivCols1)) _fas(d2pr_drhos2,", "nR prodCache[i] = _np.dot(sL, sR); scaleCache[i] += _np.log(nL) + _np.log(nR) #print \"bulk_product DEBUG:", "reconstruct the # *non-final* parent-tree elements from those of the sub-trees. _warnings.warn(\"Increased speed", "such that scaleVals[i] contains the multiplicative scaling needed for the derivatives and/or products", "rho_wrtFilter2, rho_gpindices2 = self._process_wrtFilter(wrtSlice2, self.sos.get_prep(rholabel)) E_wrtFilter1, E_gpindices1 = self._process_wrtFilter(wrtSlice1, self.sos.get_effect(elabel)) E_wrtFilter2, E_gpindices2 =", "x G; products[i] is the i-th operation sequence product. scaleVals : numpy array", "is product for i-th operation sequence dGs1 = evalTree.final_view(dProdCache1, axis=0) dGs2 = evalTree.final_view(dProdCache2,", "vec( A * E(0,1) * B ) = vec( mx w/ col_i =", "distribution only; don't use column distribution hProdCache[:, myDeriv1ColSlice] = self._compute_hproduct_cache( evalTree, prodCache, dProdCache1[:,", "and H.min() > -PSMALL: nG = max(_nla.norm(G), _np.exp(-scale_exp)) G = _np.dot(gate, G /", "for doperation and hoperation below: pulls out pieces of a wrtFilter argument relevant", "= slice(0, 0) #don't compute anything on \"extra\", i.e. rank != 0, cpus", "it is split), and then over blocks (subsets) of the parameters being differentiated", "circuit_list = master_circuit_list[gInds] if prMxToFill is not None: check_vp = _np.array([self.prs(spamTuple[0], [spamTuple[1]], circuit,", "self.sos.get_prep(rholabel)) E_wrtFilter1, E_gpindices1 = self._process_wrtFilter(wrtSlice1, self.sos.get_effect(elabel)) E_wrtFilter2, E_gpindices2 = self._process_wrtFilter(wrtSlice2, self.sos.get_effect(elabel)) nDerivCols1 =", "not None: _mpit.gather_slices(blocks2, blk2Owners, deriv2MxToFill, [felInds], 1, blk1Comm, gatherMemLimit) #Note: deriv2MxToFill gets computed", "memory from previous subtree iteration before computing caches scaleVals = Gs = dGs1", "as _warnings import numpy as _np import numpy.linalg as _nla import time as", "length of the vectorized model). probability : float only returned if returnPr ==", "== True. \"\"\" if self.evotype == \"statevec\": raise NotImplementedError(\"Unitary evolution not fully supported", "* dim * dim # hproduct cache # mem += cache_size * num_params", "ndarray an already-allocated 1D numpy array of length equal to the total number", "self._compute_dproduct_cache( evalTree, prodCache, scaleCache, comm, wrtSlice2) dGs2 = evalTree.final_view(dProdCache2, axis=0) hProdCache = self._compute_hproduct_cache(", "entries in a single flattened gate (ordering as numpy.flatten), - S,M == as", "0: # works for arrays too # Compute the derivative of the entire", "both wrtFilter and wrtBlockSize wrtSlice1 = _slct.list_to_slice(wrtFilter1) else: wrtSlice1 = None if wrtFilter2", "This routine fills a 1D array, `mxToFill` with the probabilities corresponding to the", "seems confusing and we should do something else LATER. def calc_and_fill(spamTuple, fInds, gInds,", "dots\", tm) profiler.add_count(\"compute_dproduct_cache: dots\") scale = scaleCache[i] - (scaleCache[iLeft] + scaleCache[iRight]) if abs(scale)", "update probability-derivative computations: dpr/dx -> d|pr|^2/dx = d(pr*pr.C)/dx = dpr/dx*pr.C + pr*dpr/dx.C #", "then j-th model parameters. * if flat == True, an array of shape", "operation label, compute the derivative of the entire operation sequence # with respect", "get nans (invalid), but ok dGs1 = _np.swapaxes(_np.swapaxes(dGs1, 0, 3) * scaleVals, 0,", "flattened all else dGs2 = _np.swapaxes(_np.swapaxes(dGs2, 0, 1).reshape((nDerivCols2, nCircuits * dim**2)), 0, 1)", "_np.seterr(**old_err) if flat: hGs = _np.rollaxis(_np.rollaxis(hGs, 0, 3).reshape( (nDerivCols1, nDerivCols2, nCircuits * dim**2)),", "dp_dEs[i,J0+J] = sum_j dEP[j,J] dot(Gs, rho)[i,j] # dp_dEs[i,J0+J] = sum_j dot(Gs, rho)[i,j,0] dEP[j,J]", "flat=False, wrtFilter1=None, wrtFilter2=None): \"\"\" Compute the hessian of a specified sequence of operation", "B)^T = A^T tensor B^T ) # and using numpy's reshape dim =", "corresponding to a single kl xv = _np.swapaxes(xv, 1, 2) y = _np.dot(_np.kron(prods[(0,", "float only returned if returnPr == True. \"\"\" if self.evotype == \"statevec\": raise", "product of a specified sequence of operation labels. Note: LinearOperator matrices are multiplied", "= flattened all else dGs2 = _np.swapaxes(_np.swapaxes(dGs2, 0, 1).reshape((nDerivCols2, nCircuits * dim**2)), 0,", "#use cached data to construct return values old_err = _np.seterr(over='ignore') scaleExps = evalTree.final_view(scaleCache)", "how to efficiently compute the gate-only sequences. This routine fills in `mxToFill`, which", "i] = float(_np.dot(E, _np.dot(dprod_dOps[i], rho))) #Derivs wrt SPAM if returnDeriv: # same as", "[None, rho_gpindices1, rho_gpindices2], _np.tensordot(dp_dAnyRho, self.sos.get_prep(rholabel).hessian_wrt_params( rho_wrtFilter1, rho_wrtFilter2), (1, 0))) # _np.einsum('ij,jkl->ikl', dp_dAnyRho, self.sos.get_prep(rholabel).hessian_wrt_params(", "nDerivColsX, dim, dim ) hProdCache = self._compute_hproduct_cache(evalSubTree, prodCache, dProdCache1, dProdCache2, scaleCache, mySubComm, wrtSlice1,", "self._rhoE_from_spamTuple(spamTuple) _fas(prMxToFill, [fInds], self._probs_from_rhoE(rho, E, Gs[gInds], scaleVals[gInds]), add=sumInto) _np.seterr(**old_err) profiler.add_time(\"bulk_fill_dprobs: calc_and_fill_p\", tm) #", "parameter. derivative : numpy array only returned if returnDeriv == True. A 1", "once. The minimum of wrtBlockSize and the size that makes maximal use of", "hProdCache, # dim=(cacheSize,nDerivCols1,nDerivCols2,dim,dim) return hProdCache # ------------------------------------------------------------------ if evalTree.is_split(): _warnings.warn(\"Ignoring tree splitting in", "= None # free mem #gather column results: gather axis 2 of mxToFill[felInds,blocks1[iBlk1]],", "can often be useful to have fewer processor groups then subtrees (even ==", "w/ row_i = A[i,0] * B[row1] ) = A tensor B^T * vec(", "list A list of Circuits or tuples of operation labels which specify the", "d^2 G/(dij)^2 == 0, which is true IF each operation matrix element #", "old_err = _np.seterr(over='ignore') rho, E = self._rhoE_from_spamTuple(spamTuple) _fas(prMxToFill, [fInds], self._probs_from_rhoE(rho, E, Gs[gInds], scaleVals[gInds]),", "calculator. Parameters ---------- simplified_circuits : list A list of Circuits or tuples of", "num_subtree_proc_groups, num_param1_groups, num_param2_groups, num_final_strs): \"\"\" Estimate the memory required by a given set", "to the # gate's parameters and fill appropriate columns of flattened_dprod. #gate =", "+ _np.log(nR) #print \"bulk_product DEBUG: %d rescalings out of %d products\" % (cnt,", "cols\" % nDerivCols) if comm is not None and comm.Get_size() > 1: #print(\"MPI:", "the usual density-matrix-mode probability # (TODO in FUTURE) # pr = Tr( |rho><E|", "G1 ... G(M-1) dG(M)/dkl G(M+1) ... G(L-1) dG(L)/dij G(L+1) ... GN ] +", "# works for arrays too # Compute the derivative of the entire operation", "= dP/d(p1)*dP/d(p2) where P is is the probability generated by the sequence and", "= dGs = None prodCache = scaleCache = dProdCache = None #Fill cache", "vals # #elif fnName == \"bulk_dproduct\": # mem += cache_size * num_params *", "= _np.swapaxes(xv, 1, 2) y = _np.dot(_np.kron(prods[(0, l - 1)], xv), dop_dopLabel2[opLabel2]) #", "d2pr_dOps2 # Note: add transposes b/c spam terms only compute one triangle of", "same as in dpr(...) dpr_drhos = _np.zeros((1, self.Np)) derivWrtAnyRhovec = scale * _np.dot(E,", "scaleCache[iRight]) if abs(scale) > 1e-8: # _np.isclose(scale,0) is SLOW! dProdCache[i] /= _np.exp(scale) if", "must be pre-filtered!\" # Get: d2pr_drhos[i, j, rho_gpindices] = dot(E,dGs[i,j],drho/drhoP)) # d2pr_drhos[i,j,J0+J] =", "str(myDerivColSlice))) if mySubComm is not None and mySubComm.Get_size() > 1: deriv2Slices, myDeriv2ColSlice, deriv2Owners,", "whether it's + or - inf anyway... d2pr_dOps2[_np.isnan(d2pr_dOps2)] = 0 # SPAM DERIVS", "be None if (mySubComm is not None) and (mySubComm.Get_size() > 1): comm_blkSize =", "dim = self.dim #Note: previously, we tried to allow for parallelization of #", "range(len(self.preps)) ] # global_e_slices = [slice(self.e_offset[i],self.e_offset[i+1]) for i in range(len(self.effects)) ] # return", "processors. Returns ------- derivs : numpy array * if flat == False, an", "= dprobs2 mxToFill = hprobs #Fill arrays self._fill_result_tuple((None, dprobs1, dprobs2, hprobs), evalTree, slice(None),", "self._process_wrtFilter(wrtFilter2, used_operations[l]) #Cache partial products (relatively little mem required) prods = {} ident", "scale # may generate overflow, but OK if clipTo is not None: p", "entries are zero except the (i,j) entry == 1 # if vec(.) concatenates", "j-th model parameter. products : numpy array Only returned when bReturnProds == True.", "(G1 ... G(L-1)) tensor (G(L+1) ... GN)^T ]] * vec( dG(L)/dij) ) #", "# prod, dprod_dOps = G,dG # dp_dOps[i,j] = sum_k,l E[0,k] dGs[i,j,k,l] rho[l,0] #", "(dim**2,nDerivCols2) = (nDerivCols1,dim**2,nDerivCols2) flattened_d2prod[:, inds1, inds2] += _np.swapaxes(y, 0, 1) # above: dim", "compute the bulk operation on. clipTo : 2-tuple, optional (min,max) to clip return", "dpr_dEs + dpr_dOps d2pr_drhos = _np.zeros((1, self.Np, self.Np)) _fas(d2pr_drhos, [0, None, self.sos.get_prep(rholabel).gpindices], _np.dot(_np.dot(E,", "dGs2 = dGs1 else: dProdCache2 = self._compute_dproduct_cache( evalTree, prodCache, scaleCache, comm, wrtSlice2) dGs2", "of model params (see above) if wrtSlice2 is not None and wrtSlice2.start is", "evalTree.num_final_strings()), - B is the number of parameter rows (the length of rowSlice)", "Returns ------- hessian : numpy array * if flat == False, a M", "spam label. \"\"\" pslc1 = param_slice1 pslc2 = param_slice2 for spamTuple, (fInds, gInds)", "_np.dot(d2prod_dGates[i, j], rho))) old_err = _np.seterr(over='ignore') prod, scale = self.product(circuit, True) if returnPr:", "True. * if flat == False, two arrays of shape S x M", "inds1, inds2] += _np.swapaxes(y, 0, 1) # above: dim = (dim2, nDerivCols1, nDerivCols2);", "spamTuple, rho, E, Gs[gInds], dGs1[gInds], dGs2[gInds], hGs[gInds], scaleVals[gInds], wrtSlice1, wrtSlice2), add=sumInto) _np.seterr(**old_err) #NOTE:", "# scale and keep track of exponent if H.max() < PSMALL and H.min()", "differentiated with respect to (see wrtBlockSize). wrtFilter1, wrtFilter2 : list of ints, optional", "bulk operation on. flat : bool, optional Affects the shape of the returned", "G = _np.identity(self.dim) for lOp in circuit: if lOp not in scaledGatesAndExps: opmx", "= ident # product of no gates G = ident for (j, opLabel2)", "without copying - throws error if copy is needed) # transposes each of", "the Hessian of many operation sequence products at once. Parameters ---------- evalTree :", "max(_nla.norm(opmx), 1.0) scaledGatesAndExps[lOp] = (opmx / ng, _np.log(ng)) gate, ex = scaledGatesAndExps[lOp] H", "on each local subtree for iSubTree in mySubTreeIndices: evalSubTree = subtrees[iSubTree] felInds =", "parent tree's *non-final* elements from those of the sub-trees). Note also that there", "the labels in the string which match the current # gate (so we", "x G x G, where: - S == the number of operation sequences", "(dim**2, nParams[opLabel]) if _slct.length(gpindices) > 0: # works for arrays too # Compute", "clipTo) def bulk_hprobs_by_block(self, evalTree, wrtSlicesList, bReturnDProbs12=False, comm=None): \"\"\" Constructs a generator that computes", "if opLabel1 in hop_dopLabels: # indicates a non-zero hessian x0 = _np.kron(_np.transpose(prods[(0, m", "to control bulk products, their gradients, and their Hessians. PSMALL = 1e-100 DSMALL", "_np.exp(-scaleCache[iLeft]), 1e-300), max(_nla.norm(R), _np.exp(-scaleCache[iRight]), 1e-300) sL, sR = L / nL, R /", "function computes values for only a single spam label (specified to it by", "# wrt rho ret += d2pr_dErhos1 + d2pr_d2Es + d2pr_dEs2 # wrt E", "serial\", tSerialStart) profiler.add_count(\"compute_dproduct_cache: num columns\", nDerivCols) return dProdCache def _compute_hproduct_cache(self, evalTree, prodCache, dProdCache1,", "yet!\") # To support unitary evolution we need to: # - alter product,", "old_err = _np.seterr(over='ignore') Gs = _np.swapaxes(_np.swapaxes(Gs, 0, 2) * scaleVals, 0, 2) #", "Version 2.0 (the \"License\"); you may not use this file except # in", "are at most # linear in the parameters assert(opLabel1 == opLabel2) if opLabel1", "# (reshape without copying - throws error if copy is needed) # transposes", "bScale else dGs def bulk_hproduct(self, evalTree, flat=False, bReturnDProdsAndProds=False, bScale=False, comm=None, wrtFilter1=None, wrtFilter2=None): \"\"\"", "if deriv2MxToFill is not None: _mpit.gather_slices(blocks2, blk2Owners, deriv2MxToFill, [felInds], 1, blk1Comm, gatherMemLimit) #Note:", "_np.seterr(over='ignore') rho, E = self._rhoE_from_spamTuple(spamTuple) #if prMxToFill is not None: # _fas(prMxToFill, [fInds],", "prod_ki # dpr/d(E)_i = sum prod_il rho_l rholabel, elabel = spamTuple # can't", "shape=%s)\" % (dProdCache.nbytes / (1024.0**3), str(dProdCache.shape))) dGs = evalSubTree.final_view(dProdCache, axis=0) #( nCircuits, nDerivCols,", "% self.Np + \" [blkSize = %.1f, nBlks=%d]\" % (blkSize, nBlks)) # pragma:", "used_operations[l]) gate_wrtFilters2[l], gpindices2[l] = self._process_wrtFilter(wrtFilter2, used_operations[l]) #Cache partial products (relatively little mem required)", "= dot( squeeze(dot(dGs, rho),axis=(3,)), dEP)[:,:,J] d2pr_dEs1 = _np.zeros((nCircuits, nDerivCols1, nDerivCols2)) dp_dAnyE = _np.squeeze(_np.dot(dGs1,", "using a split tree. \"\"\" if profiler is None: profiler = _dummy_profiler dim", "assume gave no contribution since we assume all gate elements are at most", "the probability w.r.t. the k-th then the j-th model parameter. derivative : numpy", "dProdCache2, scaleCache, blk2Comm, blk_wrtSlice1, blk_wrtSlice2) hGs = evalSubTree.final_view(hProdCache, axis=0) #Set filtering for calc_and_fill", "blocks2[iBlk2] self._fill_result_tuple((prMxToFill, deriv1MxToFill, deriv2MxToFill, mxToFill), evalSubTree, blocks1[iBlk1], blocks2[iBlk2], calc_and_fill) hProdCache = hGs =", "correspond to which strings and outcomes, you'll need the mappings generated when the", "x.view() # (nDerivCols1,dim**2) xv.shape = (nDerivCols1, dim, dim) # (reshape without copying -", "subTreeOwners, deriv1MxToFill, [], 0, comm, gatherMemLimit) if deriv2MxToFill is not None: _mpit.gather_indices(subtreeElementIndices, subTreeOwners,", "0, which is true IF each operation matrix element # is at most", "\"\"\" Return the Hessian of many operation sequence products at once. Parameters ----------", "mySubComm) scaleVals = self._scaleExp(evalSubTree.final_view(scaleCache)) Gs = evalSubTree.final_view(prodCache, axis=0) #( nCircuits, dim, dim )", "= scale * _np.dot(E, prod) # may overflow, but OK d2pr_d2rhos = _np.zeros((1,", "dp_dOps return sub_vdp #def _get_filter_info(self, wrtSlices): # \"\"\" # Returns a \"filter\" object", "dGs1 = None # free Mem dProdCache1 = self._compute_dproduct_cache( evalTree, prodCache, scaleCache, comm,", "Model. autogator : AutoGator An auto-gator object that may be used to construct", "a list of integers specifying which model parameters to differentiate with respect to", "* dim # dproduct cache # mem += cache_size * dim * dim", "old_err = _np.seterr(over='ignore', invalid='ignore') # may overflow or get nans (invalid), but ok", "prods[(m + 1, l - 1)]) # (dim**2, dim**2) x = _np.dot(_np.transpose(dop_dopLabel1[opLabel1]), x0);", "\"\"\" Compute the hessian of a specified sequence of operation labels. Parameters ----------", "processor syncronization. Returns ------- None \"\"\" if wrtFilter1 is not None: assert(wrtBlockSize1 is", "_np.exp(scaleExps) # may overflow, but OK if infs occur here _np.seterr(**old_err) if bReturnProds:", "Label The state preparation label. elabels : list A list of :class:`Label` objects", "is None) # Cannot specify both wrtFilter and wrtBlockSize wrtSlice = _slct.list_to_slice(wrtFilter) else:", "not None and comm.Get_size() > 1: #print(\"MPI: _compute_dproduct_cache called w/comm size %d\" %", "specify both wrtFilter and wrtBlockSize wrtSlice = _slct.list_to_slice(wrtFilter) else: wrtSlice = None profiler.mem_check(\"bulk_fill_dprobs:", "at most linear in params, so # all hessians for single- or zero-operation", "derivatives d2pr_dErhos2 = _np.transpose(d2pr_dErhos1, (0, 2, 1)) else: d2pr_dErhos2 = _np.zeros((nCircuits, nDerivCols2, nDerivCols1))", "= dProdCache = None #Fill cache info (not requiring column distribution) tm =", "# - update probability-derivative computations: dpr/dx -> d|pr|^2/dx = d(pr*pr.C)/dx = dpr/dx*pr.C +", "derivWrtAnyRhovec, self.sos.get_prep(rholabel).hessian_wrt_params()) else: d2pr_d2rhos = 0 if self.sos.get_effect(elabel).has_nonzero_hessian(): derivWrtAnyEvec = scale * _np.transpose(_np.dot(prod,", "wrtSlicesList : list A list of `(rowSlice,colSlice)` 2-tuples, each of which specify a", "multiple processors. Returns ------- derivs : numpy array * if flat == False,", "loc_e_slices = [ # _slct.shift(_slct.intersect( # wrtSlices['effects'], # slice(self.e_offset[i],self.e_offset[i+1])), # -self.e_offset[i]) for i", "savings from using a split tree. \"\"\" dim = self.dim # Note: dProdCache?.shape", "nDerivCols2) d2pr_drhos2 = _np.transpose(d2pr_drhos1, (0, 2, 1)) else: drho = rhoVec.deriv_wrt_params(rho_wrtFilter1) d2pr_drhos2 =", "Constructs a generator that computes the 2nd derivatives of the probabilities generated by", "to allow a trace or other linear operation to be done prior to", "dProdCache = dGs = None # free mem #gather results tm = _time.time()", "compute the bulk operation on. This tree *cannot* be split. wrtSlicesList : list", "+ 1, m - 1)]), prods[(m + 1, N - 1)]) # (dim**2,", "(may be less than or greater than `cacheSize`) the tree will hold. Returns", "a matrix of parameters, then dG(L)/dij = E(i,j), an elementary matrix dim =", "== mx[:,:,rowSlice,colSlice]` - `dprobs12 == dp1[:,:,rowSlice,None] * dp2[:,:,None,colSlice]` \"\"\" assert(not evalTree.is_split()), \"`evalTree` cannot", "= evalTree.get_sub_trees() mySubTreeIndices, subTreeOwners, mySubComm = evalTree.distribute(comm) #eval on each local subtree for", "be None if wrtFilter is not None. Set this to non-None to reduce", "= _np.dot(G, self.sos.get_operation(opLabel).todense()) leftProds.append(G) rightProdsT = [] G = _np.identity(dim); rightProdsT.append(_np.transpose(G)) for opLabel", "opLabel: gate.deriv_wrt_params(gate_wrtFilters1[opLabel]) for opLabel, gate in used_operations.items()} if wrtFilter1 == wrtFilter2: dop_dopLabel2 =", "d2pr_dEs[i, j, E_gpindices] = dot(transpose(dE/dEP),dGs[i,j],rho) # d2pr_dEs[i,j,J0+J] = sum_kl dEPT[J,k] dGs[i,j,k,l] rho[l,0] #", "evalTree.is_split(): _warnings.warn(\"Ignoring tree splitting in dproduct cache calc.\") dProdCache = _np.zeros((cacheSize,) + deriv_shape)", "_np.identity(dim) for (i, opLabel1) in enumerate(revOpLabelList): # loop over \"starting\" gate prods[(i, i", "wrtFilter1 is None and wrtFilter2 is None: blkSize1 = wrtBlockSize1 # could be", "_np.dot(gate, G) # product of gates, starting with identity scale_exp += ex #", "= _np.identity(dim); leftProds.append(G) for opLabel in revOpLabelList: G = _np.dot(G, self.sos.get_operation(opLabel).todense()) leftProds.append(G) rightProdsT", "sum_{L s.t. GL == oplabel} [ G1 ... G(L-1) dG(L)/dij G(L+1) ... GN", "dProdCache2[:, myDeriv2ColSlice], scaleCache, None, myHessianSlice1, myHessianSlice2) # pass None as comm, *not* mySubSubComm,", "spamTuple # This calculator uses the convention that rho has shape (N,1) rho", "dimensions as the Hessian, and turns out to be useful when computing the", "%d cols (rank %d computing %s)\" \\ # % (nDerivCols2, comm.Get_rank(), str(myDerivColSlice))) if", "information it needs to distribute itself among the available processors. Returns ------- MatrixEvalTree", "the LICENSE file in the root pyGSTi directory. #*************************************************************************************************** import warnings as _warnings", "x M x G x G, where - S == len(circuit_list) - M", "_warnings.warn(\"norm(vp-check_vp) = %g - %g = %g\" % (_nla.norm(prMxToFill[fInds]), _nla.norm(check_vp), _nla.norm(prMxToFill[fInds] - check_vp)))", "prodCache, dProdCache1, dProdCache2, scaleCache, comm=None, wrtSlice1=None, wrtSlice2=None): \"\"\" Computes a tree of product", "Return the preferred MPI distribution mode for this calculator. \"\"\" return \"deriv\" def", "not None, an already-allocated length-E numpy array that is filled with probabilities, just", "norm <= 1, products should all have norm <= 1 assert(len(nanOrInfCacheIndices) == 0)", "# ignoring comm since can't do anything with it! #_warnings.warn(\"More processors than can", "scale * _np.dot(prod, rhoVec.deriv_wrt_params()) # may generate overflow, but OK _fas(d2pr_dErhos, [0, EVec.gpindices,", "It doesn't make sense to include these since their required memory is fixed", "2) * scaleVals, 0, 2) # may overflow, but ok _np.seterr(**old_err) return Gs", "_np.seterr(over='ignore') rho, E = self._rhoE_from_spamTuple(spamTuple) _fas(prMxToFill, [fInds], self._probs_from_rhoE(rho, E, Gs[gInds], scaleVals[gInds]), add=sumInto) _np.seterr(**old_err)", "and 2nd (col) derivatives to compute *products* for simultaneously. None means compute all", "self._process_wrtFilter(wrtSlice, self.sos.get_prep(rholabel)) E_wrtFilter, E_gpindices = self._process_wrtFilter(wrtSlice, self.sos.get_effect(elabel)) nDerivCols = self.Np if wrtSlice is", "else: wrtSlice2 = None #get distribution across subtrees (groups if needed) subtrees =", "created tree. This aids in the tree construction by giving the tree information", "hessian elements.\") # pragma: no cover # allocate final result memory hProdCache =", "# l==m, which we *used* to assume gave no contribution since we assume", "3) # convert nans to zero, as these occur b/c an inf scaleVal", "MatrixForwardSimulator calculator class\"\"\" #*************************************************************************************************** # Copyright 2015, 2019 National Technology & Engineering Solutions", "dprobs1 = _np.zeros((nElements, _slct.length(wrtSlice1)), 'd') dprobs2 = _np.zeros((nElements, _slct.length(wrtSlice2)), 'd') else: dprobs1 =", "general only a specified slice of the values for this spam label (given", "since can't do anything with it! #_warnings.warn(\"More processors than can be used for", "tensor (G(L+1) ... GN)^T vec( dG(L)/dij ) ] # noqa # = [", "elements (i.e. evalTree.num_final_elements()) evalTree : EvalTree given by a prior call to bulk_evaltree.", "in subtrees] _mpit.gather_indices(subtreeElementIndices, subTreeOwners, mxToFill, [], 0, comm) #note: pass mxToFill, dim=(KS), so", "= self.dproduct(circuit) dpr_dOps = _np.empty((1, self.Np)) for i in range(self.Np): dpr_dOps[0, i] =", "a lists of gate-only sequences along with a mapping of final elements (i.e.", "tolerances, used internally for conditional scaling required # to control bulk products, their", "(G(L+1) ... GN)^T ]] # noqa # # So for each opLabel the", "wrtSlice? prodCache, scaleCache = self._compute_product_cache(evalTree, comm) dProdCache = self._compute_dproduct_cache(evalTree, prodCache, scaleCache, comm, wrtSlice)", "# (dim2, nDerivCols1, nDerivCols2) flattened_d2prod[:, inds1, inds2] += xv if flat: return flattened_d2prod", "are. np1, np2 = num_param1_groups, num_param2_groups FLOATSIZE = 8 # in bytes: TODO:", "returned probability to if not None. Only relevant when prMxToFill is not None.", "the appropriate # columns of flattened_dprod. uniqueOpLabels = sorted(list(set(revOpLabelList))) for opLabel in uniqueOpLabels:", "this gate hessian once). But since we're # assuming that the gates are", "VS MATRIX ORDER else: G = H old_err = _np.seterr(over='ignore') scale = _np.exp(scale_exp)", "= _np.zeros((nElements, _slct.length(wrtSlice2)), 'd') else: dprobs1 = dprobs2 = None hprobs = _np.zeros((nElements,", "numpy array The product or scaled product of the operation matrices. scale :", "just like in bulk_fill_probs(...). clipTo : 2-tuple, optional (min,max) to clip return value", "holds the derivative of the (l,m)-th entry of the i-th operation sequence product", "better way dim = self.dim nspam = int(round(_np.sqrt(self.dim))) # an estimate - could", "is not None: # ignoring comm since can't do anything with it! #_warnings.warn(\"More", "sequence with respect to the # gate's parameters and fill appropriate columns of", "if dProdCache[i].max() < DSMALL and dProdCache[i].min() > -DSMALL: _warnings.warn(\"Scaled dProd small in order", "little mem required) prods = {} ident = _np.identity(dim) for (i, opLabel1) in", "splitting in hproduct cache calc.\") hProdCache = _np.zeros((cacheSize,) + hessn_shape) #First element of", "relevant_gpindices = slice(0, 0) # slice that results in a zero dimension else:", "wrtSlice2) hProdCache = self._compute_hproduct_cache(evalTree, prodCache, dProdCache1, dProdCache2, scaleCache, comm, wrtSlice1, wrtSlice2) #use cached", "= swapaxes(dot(dEPT,prod,drhoP),0,1)[:,J,K] d2pr_dErhos1 = _np.zeros((nCircuits, nDerivCols1, nDerivCols2)) drho = rhoVec.deriv_wrt_params(rho_wrtFilter2) dp_dAnyE = _np.dot(Gs,", "hold. Returns ------- int The memory estimate in bytes. \"\"\" #Note: num_final_strs is", "transposes b/c spam terms only compute one triangle of hessian # Note: d2pr_d2rhos", "w/comm size %d\" % comm.Get_size()) # parallelize of deriv cols, then sub-trees (if", "then the j-th model parameter. derivative : numpy array only returned if returnDeriv", "0) return prodCache, scaleCache def _compute_dproduct_cache(self, evalTree, prodCache, scaleCache, comm=None, wrtSlice=None, profiler=None): \"\"\"", "when bScale == True. An array of shape S such that scaleVals[i] contains", "filters for multiple uses below gpindices1 = {}; gate_wrtFilters1 = {} gpindices2 =", "(len %d)\" % len(circuit) _warnings.warn(\"pr(%s) == nan\" % strToPrint) #DEBUG: print \"backtrace\" of", "a zero hessian value, and we hGs[_np.isnan(hGs)] = 0 # assume the zero", "also give invalid value due to scaleVals being inf and dot-prod being 0.", "gate elements are at most # linear in the parameters assert(opLabel1 == opLabel2)", "parameter. products : numpy array Only returned when bReturnDProdsAndProds == True. An array", "gates are at most linear in their parameters, this # isn't currently needed.", "None) # Cannot specify both wrtFilter and wrtBlockSize wrtSlice = _slct.list_to_slice(wrtFilter) else: wrtSlice", "`mxToFill`, `deriv1MxToFill`, and `deriv1MxToFill`), then: - `hprobs == mx[:,:,rowSlice,colSlice]` - `dprobs12 == dp1[:,:,rowSlice,None]", "#if prMxToFill is not None: # _fas(prMxToFill, [fInds], # self._probs_from_rhoE(rho, E, Gs[gInds], scaleVals[gInds]),", "calc_and_fill_fn(spamTuple, fInds, gInds, pslc1, pslc2, False) # TODO: remove SumInto == True cases", "or get nans (invalid), but ok dGs2 = _np.swapaxes(_np.swapaxes(dGs2, 0, 3) * scaleVals,", "quantities for given arguments \"\"\" tm = _time.time() old_err = _np.seterr(over='ignore') rho, E", ": int The gate-dimension. All operation matrices should be dim x dim, and", "self.sos.get_prep(rholabel).gpindices], _np.dot(_np.transpose(EVec.deriv_wrt_params()), derivWrtAnyEvec)) #Note: these 2nd derivatives are non-zero when the spam vectors", "A list of Circuits or tuples of operation labels which specify the operation", "arrays of shape S x M x G x G, where - S", "Ordered dictionaries of LinearOperator, SPAMVec, and SPAMVec objects, respectively. Must be *ordered* dictionaries", "be done at a higher level. \"\"\" dim = self.dim #Note: previously, we", "(wrtSlice1 is not None) else None wrtIndices2 = _slct.indices(wrtSlice2) if (wrtSlice2 is not", "over %d cols (%s) (rank %d computing %s)\" \\ # % (nDerivCols, str(allDerivColIndices),", "= dGs1 = dGs2 = hGs = None prodCache = scaleCache = None", "self.sos, self.paramvec) def product(self, circuit, bScale=False): \"\"\" Compute the product of a specified", "holds the derivative of the (i % G^2)-th entry of the (i /", "prodCache = _np.zeros((cacheSize, dim, dim)) scaleCache = _np.zeros(cacheSize, 'd') #First element of cache", "evalTree (if given) is possible. wrtFilter : list of ints, optional If not", "iOpStr and iSpamLabel. d12 has the same dimensions as the Hessian, and turns", "norm(G); G /= nG; total_exp += log(nG) # scale and keep track of", "to include these since their required memory is fixed ## (and dominated) by", "] , a matrix for each given (i,j) # noqa # d2prod/d(opLabel1)_kl*d(opLabel2)_ij =", "= _np.dot(Gs, drho) * scaleVals[:, None, None] # overflow OK devec = EVec.deriv_wrt_params(E_wrtFilter1)", "iBlk1 in myBlk1Indices: blk_wrtSlice1 = blocks1[iBlk1] dProdCache1 = self._compute_dproduct_cache( evalSubTree, prodCache, scaleCache, blk1Comm,", "is already sized/filtered) ------------------- assert(dGs.shape[1] == nDerivCols), \"dGs must be pre-filtered!\" #Compute d(probability)/dOps", "2, 1)) else: drho = rhoVec.deriv_wrt_params(rho_wrtFilter1) d2pr_drhos2 = _np.zeros((nCircuits, nDerivCols2, nDerivCols1)) _fas(d2pr_drhos2, [None,", "which `circuit` is evaluated. Returns ------- numpy.ndarray An array of floating-point probabilities, corresponding", "parameters. hessian[0,j,k] is the derivative of the probability w.r.t. the k-th then the", "derivs2 : numpy array Only returned if bReturnDProdsAndProds == True. * if flat", "# This iteration **must** match that in bulk_evaltree # in order to associate", "of (general) :class:`Circuit` objects is *simplified* into a lists of gate-only sequences along", "if self.sos.get_prep(rholabel).has_nonzero_hessian(): dp_dAnyRho = _np.dot(E, Gs).squeeze(0) * scaleVals[:, None] # overflow OK d2pr_d2rhos", "- 1)]) # (dim**2, dim**2) # (nDerivCols1,nDerivCols2,dim**2) x = _np.dot(_np.transpose(hop_dopLabels[opLabel1], axes=(1, 2, 0)),", "using tree (skip over the zero and single-gate-strings) for i in evalTree.get_evaluation_order(): #", "For each operation label, compute the derivative of the entire operation sequence #", "is not None and mySubSubComm.Get_size() > 1: _warnings.warn(\"Too many processors to make use", "None, None] _np.seterr(**old_err2) # may overflow, but OK ; shape == (len(circuit_list), nDerivCols,", "0, comm, gatherMemLimit) if prMxToFill is not None: _mpit.gather_indices(subtreeElementIndices, subTreeOwners, prMxToFill, [], 0,", "doperation / _np.exp(scaleCache[i]) #profiler.print_mem(\"DEBUGMEM: POINT1\"); profiler.comm.barrier() #evaluate operation sequences using tree (skip over", "use available processors if it isn't specified if wrtFilter is None: blkSize =", "an array of shape S x M x M x G x G,", "among the available processors. Returns ------- MatrixEvalTree \"\"\" evTree = _MatrixEvalTree() evTree.initialize(simplified_circuits, numSubtreeComms)", "nDerivCols2) hessn_shape = (nDerivCols1, nDerivCols2, dim, dim) cacheSize = len(evalTree) # ------------------------------------------------------------------ if", "in each of the gate parameters. If this is not the case, need", "`colSlice` are slices directly from `wrtSlicesList`. `hprobs` and `dprobs12` are arrays of shape", "comm.Get_size() > 1: #print(\"MPI: _compute_dproduct_cache called w/comm size %d\" % comm.Get_size()) # parallelize", "+ d2pr_dOps2 # Note: add transposes b/c spam terms only compute one triangle", "(i / G^2)-th flattened operation sequence product with respect to the k-th then", "tuples may only vary in their effect-label (their prep labels must be the", "d2pr_drhos[i,j,J0+J] = dot(E, dGs, drhoP)[0,i,j,J] # d2pr_drhos[:,:,J0+J] = squeeze(dot(E, dGs, drhoP),axis=(0,))[:,:,J] drho =", "is used internally for distributing derivative calculations across multiple processors. Returns ------- derivs", "and SPAM vectors) access to these fundamental operations. \"\"\" def __init__(self, dim, simplified_op_server,", "pre-filtered!\" #Compute d(probability)/dOps and save in return list (now have G,dG => product,", "wrtFilter, obj): \"\"\" Helper function for doperation and hoperation below: pulls out pieces", "# dprod/d(opLabel)_ij = sum_{L s.t. GL == oplabel} [ G1 ... G(L-1) dG(L)/dij", "OK d2pr_d2rhos = _np.zeros((nCircuits, nDerivCols1, nDerivCols2)) _fas(d2pr_d2rhos, [None, rho_gpindices1, rho_gpindices2], _np.tensordot(dp_dAnyRho, self.sos.get_prep(rholabel).hessian_wrt_params( rho_wrtFilter1,", ":] # (KM,N,1) * (KM,1,N') = (KM,N,N') yield wrtSlice1, wrtSlice2, hprobs, dprobs12 else:", "None: myHessianSlice2 = _slct.shift(myDeriv2ColSlice, wrtSlice2.start) else: myHessianSlice2 = myDeriv2ColSlice if mySubSubComm is not", "includes \"results\" memory since this is allocated within # the generator and yielded,", "dprobs1 deriv2MxToFill = dprobs2 mxToFill = hprobs #Fill arrays self._fill_result_tuple((None, dprobs1, dprobs2, hprobs),", "when checks fail. Used for testing, and runs much slower when True. comm", "post fill blk\") dProdCache = dGs = None # free mem #gather results", "hGs[gInds], scaleVals[gInds], wrtSlice1, wrtSlice2), add=sumInto) _np.seterr(**old_err) #NOTE: don't distribute wrtSlicesList across comm procs,", "False, clipTo) for circuit in circuit_list], axis=0) if _nla.norm(hprMxToFill[fInds][0] - check_vhp[0]) > 1e-6:", "correctly handle the remainder spam label. \"\"\" pslc1 = param_slice1 pslc2 = param_slice2", "opLabel, gate in used_operations.items()} #Finally, cache any nonzero gate hessians (memory?) hop_dopLabels =", "_slct.length(wrtSlice1) == nDerivCols1) assert(wrtSlice2 is None or _slct.length(wrtSlice2) == nDerivCols2) hessn_shape = (nDerivCols1,", "= dProdCache1 if (wrtSlice1 == wrtSlice2) else \\ self._compute_dproduct_cache(evalSubTree, prodCache, scaleCache, mySubComm, wrtSlice2)", "self.sos.get_prep(rholabel).gpindices], _np.dot(_np.dot(E, dprod_dOps), rhoVec.deriv_wrt_params())[0]) # (= [0,:,:]) d2pr_dEs = _np.zeros((1, self.Np, self.Np)) derivWrtAnyEvec", "self.Np / mySubComm.Get_size() blkSize1 = comm_blkSize if (blkSize1 is None) \\ else min(comm_blkSize,", "tm = _time.time() dProdCache = self._compute_dproduct_cache(evalSubTree, prodCache, scaleCache, mySubComm, wrtSlice, profiler) dGs =", "required # to control bulk products, their gradients, and their Hessians. PSMALL =", "None) else len(wrtFilter2) flattened_hprod = _np.zeros((dim**2, num_deriv_cols1, num_deriv_cols2), 'd') if _slct.length(gpindices1) > 0", "parameter. \"\"\" # LEXICOGRAPHICAL VS MATRIX ORDER # we do matrix multiplication in", "= gate.hessian_wrt_params( gate_wrtFilters1[opLabel], gate_wrtFilters2[opLabel]) # Allocate memory for the final result num_deriv_cols1 =", "The memory estimate in bytes. \"\"\" #Note: num_final_strs is irrelevant here b/c cachesize", "their parameters. if self.sos.get_prep(rholabel).has_nonzero_hessian(): dp_dAnyRho = _np.dot(E, Gs).squeeze(0) * scaleVals[:, None] # overflow", "= _time.time() dProdCache = self._compute_dproduct_cache(evalSubTree, prodCache, scaleCache, mySubComm, wrtSlice, profiler) dGs = evalSubTree.final_view(dProdCache,", "axis=(0, 2)) * scaleVals # shape == (len(circuit_list),) ; may overflow but OK", "values Gs = evalTree.final_view(prodCache, axis=0) #shape == ( len(circuit_list), dim, dim ), Gs[i]", "num_final_strs # and this dictates how large all the storage arrays are. np1,", "slice(tmp_offsets[i],tmp_offsets[i+1]) # for i in range(len(self.preps)) ] # # loc_e_slices = [ #", "operation matrix (G x G operation matrices). and hessian[i,j,k,l] holds the derivative of", "dim # hproduct cache # mem += cache_size * num_params * dim *", "= evalTree.distribute(comm) #eval on each local subtree for iSubTree in mySubTreeIndices: evalSubTree =", "d2pr_drhos2 = _np.transpose(d2pr_drhos2, (0, 2, 1)) # Get: d2pr_dEs[i, j, E_gpindices] = dot(transpose(dE/dEP),dGs[i,j],rho)", "order) # d2pr/d(E)_i d(opLabel)_mn = sum [dprod/d(opLabel)_mn]_il rho_l (and same for other diff", "nCircuits) def construct_evaltree(self, simplified_circuits, numSubtreeComms): \"\"\" Constructs an EvalTree object appropriate for this", "_np.zeros(deriv_shape) else: #doperation = self.dproduct( (opLabel,) , wrtFilter=wrtIndices) doperation = self.doperation(opLabel, wrtFilter=wrtIndices) dProdCache[i]", "into blocks of at most blkSize assert(wrtFilter1 is None and wrtFilter2 is None)", "\"\"\" dim = self.dim gate = self.sos.get_operation(opLabel) op_wrtFilter, gpindices = self._process_wrtFilter(wrtFilter, gate) #", "_time.time() all_results = comm.allgather(my_results) profiler.add_time(\"MPI IPC\", tm) return _np.concatenate(all_results, axis=1) # TODO: remove", "to the total number of computed elements (i.e. evalTree.num_final_elements()) evalTree : EvalTree given", "one triangle of hessian # Note: d2pr_d2rhos and d2pr_d2Es terms are always zero", "`hprobs == mx[:,:,rowSlice,colSlice]` - `dprobs12 == dp1[:,:,rowSlice,None] * dp2[:,:,None,colSlice]` \"\"\" assert(not evalTree.is_split()), \"`evalTree`", "better check for equivalence: maybe let dGs2 be None? assert(nDerivCols1 == nDerivCols2) d2pr_dEs2", "OrderedDict Ordered dictionaries of LinearOperator, SPAMVec, and SPAMVec objects, respectively. Must be *ordered*", "bScale else (hGs, dGs1, dGs2, Gs) else: hGs = evalTree.final_view(hProdCache, axis=0) #shape ==", "a *split* evalTree is given, otherwise no parallelization is performed. Returns ------- prods", "of the product with respect to the j-th then i-th model parameters. *", "#doperation = self.dproduct( (opLabel,) , wrtFilter=wrtIndices) doperation = self.doperation(opLabel, wrtFilter=wrtIndices) dProdCache[i] = doperation", "self.dproduct( (opLabel,) , wrtFilter=wrtIndices) doperation = self.doperation(opLabel, wrtFilter=wrtIndices) dProdCache[i] = doperation / _np.exp(scaleCache[i])", "sum_kl E[0,k] dGs[i,j,k,l] drhoP[l,J] # d2pr_drhos[i,j,J0+J] = dot(E, dGs, drhoP)[0,i,j,J] # d2pr_drhos[:,:,J0+J] =", "in bulk_evaltree # in order to associate the right single-gate-strings w/indices wrtIndices =", "(mySubComm is not None) and (mySubComm.Get_size() > 1): comm_blkSize = self.Np / mySubComm.Get_size()", "wrtFilter1 or 2, respectively - G == the linear dimension of a operation", "profiler.add_time(\"MPI IPC\", tm) profiler.mem_check(\"bulk_fill_dprobs: post gather blocks\") #collect/gather results tm = _time.time() subtreeElementIndices", "= _np.seterr(over='ignore', invalid='ignore') # may overflow or get nans (invalid), but ok dGs", "ok # may overflow or get nans (invalid), but ok dGs1 = _np.swapaxes(_np.swapaxes(dGs1,", "values which are integer row indices into mxToFill, specifying the correspondence between rows", "== the number of model params or wrtFilter1 or 2, respectively - G", "*linear* in each of the gate parameters. If this is not the case,", "deriv value (see below) dGs2[_np.isnan(dGs2)] = 0 # convert nans to zero, as", "dim=(ks,M,M) _mpit.gather_slices(blocks1, blk1Owners, mxToFill, [felInds], 1, mySubComm, gatherMemLimit) if deriv1MxToFill is not None:", "prods[i]). \"\"\" prodCache, scaleCache = self._compute_product_cache(evalTree, comm) #use cached data to construct return", "are EVec = self.sos.get_effect(elabel) # arrays, these are SPAMVecs nCircuits = Gs.shape[0] rho_wrtFilter,", "License at # http://www.apache.org/licenses/LICENSE-2.0 or in the LICENSE file in the root pyGSTi", "dprod_dOps = self.dproduct(circuit) assert(dprod_dOps.shape[0] == self.Np) if returnDeriv: # same as in dpr(...)", "array of derivatives of the probability w.r.t. each model parameter (M is the", "mySubSubComm.Get_rank() > 0: myDeriv2ColSlice = slice(0,0) # #don't compute anything on \"extra\", i.e.", "_compute_dproduct_cache.\") if mySubComm.Get_rank() > 0: myDerivColSlice = slice(0, 0) #don't compute anything on", "spamTuple, rho, E, Gs[gInds], dGs1[gInds], scaleVals[gInds], wrtSlice1), add=sumInto) if deriv2MxToFill is not None:", "B[0,1] ) = B^T tensor A * vec( E(0,1) ) # In general:", "Each element is an index into an array of gate parameters ordered by", ") #assert( len( (_np.isinf(hGs)).nonzero()[0] ) == 0 ) #hGs = clip(hGs,-1e300,1e300) _np.seterr(**old_err) if", "def prs(self, rholabel, elabels, circuit, clipTo, bUseScaling=False, time=None): \"\"\" Compute probabilities of a", "# pragma: no cover # noqa for iBlk1 in myBlk1Indices: blk_wrtSlice1 = blocks1[iBlk1]", "evalTree, prodCache, dProdCache1[:, myDeriv1ColSlice], dProdCache2[:, myDeriv2ColSlice], scaleCache, None, myHessianSlice1, myHessianSlice2) # pass None", "LICENSE file in the root pyGSTi directory. #*************************************************************************************************** import warnings as _warnings import", "R) + dLdR_sym + _np.transpose(_np.dot(L, hR), (1, 2, 0, 3)) scale = scaleCache[i]", "# arrays, these are SPAMVecs nCircuits = Gs.shape[0] rho_wrtFilter, rho_gpindices = self._process_wrtFilter(wrtSlice, self.sos.get_prep(rholabel))", "of final elements (this can be obtained by `evalTree.num_final_elements()`. To interpret which elements", "= _np.real(_np.abs(_np.dot(Es, _np.dot(G, rho)))**2) else: # evotype == \"densitymx\" ps = _np.real(_np.dot(Es, _np.dot(G,", "the (i / G^2)-th flattened operation sequence product with respect to the j-th", "keep last dProdCache1 for wrtSlice1, wrtSlice2 in wrtSlicesList: if wrtSlice1 != last_wrtSlice1: dProdCache1", "= ps.flatten() if _np.any(_np.isnan(ps)): if len(circuit) < 10: strToPrint = str(circuit) else: strToPrint", "IPC\", tm) return _np.concatenate(all_results, axis=1) # TODO: remove this concat w/better gather? #", "dproduct(...) and find the labels in the string which match the current #", "Parameters ---------- spam_label_rows : dictionary a dictionary with keys == spam labels and", "the hessian of the entire # operation sequence with respect to only those", "Only returned when bReturnDProdsAndProds == True. An array of shape S x G", "with respect to the # gate's parameters and fill appropriate columns of flattened_dprod.", "nDerivCols2); # swapaxes takes (kl,vec_prod_indx,ij) => (vec_prod_indx,kl,ij) elif l < m: x0 =", "of *simplified* gates (e.g. may include instrument elements like 'Imyinst_0') returnPr : bool", "= # dEP^T * prod[i,:,:] * drhoP # d2pr_dErhos[i,J0+J,K0+K] = sum jk dEPT[J,j]", "mySubComm.Get_size() > 1: _warnings.warn(\"Too many processors to make use of in \" \"", "return prodCache, scaleCache def _compute_dproduct_cache(self, evalTree, prodCache, scaleCache, comm=None, wrtSlice=None, profiler=None): \"\"\" Computes", "2, respectively - G == the linear dimension of a operation matrix (G", "clip if check: self._check(evalTree, prMxToFill, deriv1MxToFill, mxToFill, clipTo) def bulk_hprobs_by_block(self, evalTree, wrtSlicesList, bReturnDProbs12=False,", "(hGs, dGs1, dGs2, Gs, scaleVals) if bScale else (hGs, dGs1, dGs2, Gs) else:", "tree was split, but this is was # incorrect (and luckily never used)", "(len(circuit_list), nDerivCols) # may also give invalid value due to scaleVals being inf", "not None: _mpit.gather_indices(subtreeElementIndices, subTreeOwners, prMxToFill, [], 0, comm) if clipTo is not None", "_np.seterr(**old_err) else: # no scaling -- faster but susceptible to overflow G =", "= (nDerivCols1, dim, dim) # (reshape without copying - throws error if copy", "as _mpit from ..tools import slicetools as _slct from ..tools.matrixtools import _fas from", "= (dim2, nDerivCols1, nDerivCols2); # swapaxes takes (kl,vec_prod_indx,ij) => (vec_prod_indx,kl,ij) else: # l==m,", "operation sequences which need to be computed # for the current spamTuple (this", "columns to compute *products* for simultaneously. None means compute all requested columns at", "dEP)[i,j,J] # d2pr_dEs[:,:,J0+J] = dot( squeeze(dot(dGs, rho),axis=(3,)), dEP)[:,:,J] d2pr_dEs1 = _np.zeros((nCircuits, nDerivCols1, nDerivCols2))", "3) # may overflow or get nans (invalid), but ok hGs = _np.swapaxes(_np.swapaxes(hGs,", "# may overflow, but ok _np.seterr(**old_err) return Gs def bulk_dproduct(self, evalTree, flat=False, bReturnProds=False,", "must by Python `slice` objects. bReturnDProbs12 : boolean, optional If true, the generator", "flat: return flattened_hprod else: return _np.transpose(flattened_hprod, (1, 2, 0)).reshape( (num_deriv_cols1, num_deriv_cols2, dim, dim))", "overflow, but OK ; shape == (len(circuit_list), nDerivCols) # may also give invalid", "1.0) scaledGatesAndExps[lOp] = (opmx / ng, _np.log(ng)) gate, ex = scaledGatesAndExps[lOp] H =", "cache_size # scale vals # #elif fnName == \"bulk_hproduct\": # mem += cache_size", "model (number of model parameters) and deriv[i,j] holds the derivative of the i-th", "model parameters, distribution over a split evalTree (if given) is possible. wrtFilter :", "not in scaledGatesAndExps: opmx = self.sos.get_operation(lOp).todense() ng = max(_nla.norm(opmx), 1.0) scaledGatesAndExps[lOp] = (opmx", "DERIVS (assume dGs1 and dGs2 are already sized/filtered) -------- assert(dGs1.shape[1] == nDerivCols1), \"dGs1", "blkSize1 or blkSize2 blocks1 = _mpit.slice_up_range(self.Np, nBlks1) blocks2 = _mpit.slice_up_range(self.Np, nBlks2) #distribute derivative", "... G(L-1) dG(L)/dij G(L+1) ... GN ] + {similar with L < M}", "|rho><E| * prod ) = sum E_k prod_kl rho_l # d2pr/d(opLabel1)_mn d(opLabel2)_ij =", "Gs[i,k,l] rho[l,0] * scaleVals[i] # vp[i] = sum_k E[0,k] dot(Gs, rho)[i,k,0] * scaleVals[i]", "which parameters to include in the derivative dimension. This argument is used internally", "axis 2 of mxToFill[felInds,blocks1[iBlk1]], dim=(ks,blk1,M) _mpit.gather_slices(blocks2, blk2Owners, mxToFill, [felInds, blocks1[iBlk1]], 2, blk1Comm, gatherMemLimit)", "== dp1[:,:,rowSlice,None] * dp2[:,:,None,colSlice]` \"\"\" assert(not evalTree.is_split()), \"`evalTree` cannot be split\" nElements =", "contain \"deterministic\" elements (no POVM or Instrument labels). numSubtreeComms : int The number", "#dGs = clip(dGs,-1e300,1e300) _np.seterr(**old_err) if flat: dGs = _np.swapaxes(_np.swapaxes(dGs, 0, 1).reshape( (nDerivCols, nCircuits", "# gInds = \"gate sequence indices\" = indices into the (tree-) list of", "\"backtrace\" of product leading up to nan #G = _np.identity( self.dim ); total_exp", "range(len(self.preps)+1) ] # global_rho_slices = [ slice(tmp_offsets[i],tmp_offsets[i+1]) # for i in range(len(self.preps)) ]", "upon the \"gather\" operations performed as a part of MPI processor syncronization. Returns", "[felInds], 1, mySubComm, gatherMemLimit) #note: gathering axis 1 of mxToFill[felInds], dim=(ks,M) profiler.add_time(\"MPI IPC\",", "derivative array (see below). bReturnProds : bool, optional when set to True, additionally", "dGs1, dGs2, Gs) else: hGs = evalTree.final_view(hProdCache, axis=0) #shape == ( len(circuit_list), nDerivCols,", "_np.seterr(over='ignore') scaleExps = evalTree.final_view(scaleCache) scaleVals = _np.exp(scaleExps) # may overflow, but OK if", "ident for (j, opLabel2) in enumerate(revOpLabelList[i:], start=i): # loop over \"ending\" gate (>=", "mapping of final elements (i.e. probabilities) to gate-only sequence and prep/effect pairs. The", "of integers specifying which gate parameters to differentiate with respect to in the", "multiplied in the reversed order of the tuple. That is, the first element", "noqa # # Note: ignoring L == M terms assumes that d^2 G/(dij)^2", "So for each opLabel the matrix [ sum_{L s.t. GL == oplabel} [", "# == num_deriv_cols1, num_deriv_cols2 return _np.rollaxis(flattened_d2prod, 0, 3).reshape((vec_kl_size, vec_ij_size, dim, dim)) # axes", "so they're not repeatedly # computed for each block of derivative columns if", "scaleVals = Gs = dGs = None prodCache = scaleCache = dProdCache =", "\"\"\" assert(time is None), \"MatrixForwardSimulator cannot be used to simulate time-dependent circuits\" rho,", "# Cannot specify both wrtFilter and wrtBlockSize wrtSlice1 = _slct.list_to_slice(wrtFilter1) else: wrtSlice1 =", "in uniqueOpLabels: gate = self.sos.get_operation(opLabel) op_wrtFilter, gpindices = self._process_wrtFilter(wrtFilter, gate) dop_dopLabel = gate.deriv_wrt_params(op_wrtFilter)", "dot( E, dot( dGs, rho ) )[0,i,j,0] # dp_dOps = squeeze( dot( E,", "each of which specify a \"block\" of the Hessian to compute. Iterating over", "dot(prod,drhoP)[i,j,K] # d2pr_dErhos[i,J0+J,K0+K] = dot(dEPT,prod,drhoP)[J,i,K] # d2pr_dErhos[i,J0+J,K0+K] = swapaxes(dot(dEPT,prod,drhoP),0,1)[i,J,K] # d2pr_dErhos[:,J0+J,K0+K] = swapaxes(dot(dEPT,prod,drhoP),0,1)[:,J,K]", "compute the bulk operation on. flat : bool, optional Affects the shape of", ": bool, optional when set to True, additionally return the probabilities. bScale :", "/ blkSize)) # num blocks required to achieve desired average size == blkSize", "above: dim = (dim2, nDerivCols1, nDerivCols2); # swapaxes takes (kl,vec_prod_indx,ij) => (vec_prod_indx,kl,ij) elif", "argument: wrtFilter -> wrtSlice? prodCache, scaleCache = self._compute_product_cache(evalTree, comm) dProdCache = self._compute_dproduct_cache(evalTree, prodCache,", "get d2pr_dEs where gate derivatives are wrt the 2nd set of gate parameters", "# ------------------------------------------------------------------ if evalTree.is_split(): _warnings.warn(\"Ignoring tree splitting in hproduct cache calc.\") hProdCache =", "info (not distributed) prodCache, scaleCache = self._compute_product_cache(evalTree, comm) scaleVals = self._scaleExp(evalTree.final_view(scaleCache)) Gs =", "+ sum{ L == M} [ G1 ... G(M-1) tensor (G(M+1) ... GN)^T", "None: #Fill derivative cache info tm = _time.time() dProdCache = self._compute_dproduct_cache(evalSubTree, prodCache, scaleCache,", "row corresponds to an element of the product (els of # prod.flatten()). #", "and necessary) if comm.Get_size() > nDerivCols1 * nDerivCols2: #If there are more processors", "parameters and fill # add the result to the appropriate block of flattened_d2prod.", ": numpy array * if flat == False, a M x G x", "with respect to the k-th then k-th model parameters. \"\"\" # LEXICOGRAPHICAL VS", "+= cache_size * (wrtLen1 + wrtLen2) * dim * dim # dproduct cache", "calculations across multiple processors. Returns ------- hessian : numpy array * if flat", "by giving dproduct cache computation\" \" *fewer* processors and *smaller* (sub-)tree\" \" (e.g.", "object that may be used to construct virtual gates for use in computations.", "dim ), # hGs[i] is hprod_dGates for ith string if not bScale: old_err", "all_results = comm.allgather(my_results) profiler.add_time(\"MPI IPC\", tm) return _np.concatenate(all_results, axis=1) # TODO: remove this", "== opLabel2) if opLabel1 in hop_dopLabels: # indicates a non-zero hessian x0 =", "None: p = _np.clip(p, clipTo[0], clipTo[1]) #Derivs wrt SPAM derivWrtAnyRhovec = scale *", "0, 3)) scale = scaleCache[i] - (scaleCache[iLeft] + scaleCache[iRight]) if abs(scale) > 1e-8:", "*iteration*!) #collect/gather results subtreeElementIndices = [t.final_element_indices(evalTree) for t in subtrees] _mpit.gather_indices(subtreeElementIndices, subTreeOwners, mxToFill,", "+ deriv_shape) # This iteration **must** match that in bulk_evaltree # in order", "*simplified* operation sequences found in an evaluation tree, `evalTree`. An initial list of", "gate G(L) is just a matrix of parameters, then dG(L)/dij = E(i,j), an", "# For each operation label, compute the derivative of the entire operation sequence", "already-allocated 1D numpy array of length equal to the total number of computed", "with NTESS, the U.S. Government retains certain rights # in this software. #", "# noqa # tensor (G(L+1) ... GN)^T vec( dG(L)/dij ) ] # noqa", "to nan #G = _np.identity( self.dim ); total_exp = 0.0 #for i,lOp in", "using a split tree. \"\"\" dim = self.dim # Note: dProdCache?.shape = (#circuits,#params_to_diff_wrt,dim,dim)", "dot( dGs, rho ) )[0,i,j,0] # dp_dOps = squeeze( dot( E, dot( dGs,", "the derivative of a length-1 (single-gate) sequence \"\"\" dim = self.dim gate =", "(given by the subsequent arguments, except for the last). The final argument is", "when bScale == True, in which case the actual product == product *", "matrix for each given (i,j) # noqa # vec( dprod/d(opLabel)_ij ) = sum_{L", "not None) else None for i, opLabel in zip(evalTree.get_init_indices(), evalTree.get_init_labels()): if opLabel ==", "_np.transpose(d2pr_dErhos, (0, 2, 1)) + \\ d2pr_drhos + _np.transpose(d2pr_drhos, (0, 2, 1)) +", "gather mxToFill[felInds] (axis=0) if prMxToFill is not None: _mpit.gather_indices(subtreeElementIndices, subTreeOwners, prMxToFill, [], 0,", "_itertools import collections as _collections from ..tools import mpitools as _mpit from ..tools", "are multiplied in the reversed order of the tuple. That is, the first", "params to compute # derivatives wrt all spam parameters dGs = _np.empty((Gs.shape[0], 0,", "#NOTE: if we needed to perform a hessian calculation (i.e. for l==m) then", "different -- non-gate-local -- parameterizations of operation matrices and SPAM vectors) access to", "rights # in this software. # Licensed under the Apache License, Version 2.0", "and mySubComm.Get_size() > 1: _warnings.warn(\"Too many processors to make use of in \"", "cols = deriv cols, rows = all else return (hGs, dGs1, dGs2, Gs,", "if flat == False, two arrays of shape S x M x G", "is None: profiler = _dummy_profiler dim = self.dim nDerivCols = self.Np if (wrtSlice", "# mem += cache_size * dim * dim # product cache # mem", "product(self, circuit, bScale=False): \"\"\" Compute the product of a specified sequence of operation", "using the columns of the operation sequences. Parameters ---------- spam_label_rows : dictionary a", "we *used* to assume gave no contribution since we assume all gate elements", "filled with probabilities, just like in bulk_fill_probs(...). derivMxToFill1, derivMxToFill2 : numpy array, optional", "None: _mpit.gather_indices(subtreeElementIndices, subTreeOwners, prMxToFill, [], 0, comm) if clipTo is not None and", "= 0.0 #for i,lOp in enumerate(gateLabelList): # G = _np.dot(G,self[lOp]) # product of", ": numpy array a 1 x M numpy array of derivatives of the", "virtual gates for use in computations. \"\"\" super(MatrixForwardSimulator, self).__init__( dim, simplified_op_server, paramvec) if", "if (wrtFilter2 is None) else len(wrtFilter2) flattened_hprod = _np.zeros((dim**2, num_deriv_cols1, num_deriv_cols2), 'd') if", "# Copyright 2015, 2019 National Technology & Engineering Solutions of Sandia, LLC (NTESS).", "G(L-1)) tensor (G(L+1) ... GN)^T ]] * vec( dG(L)/dij) ) # noqa #", "Note: this doesn't involve gate derivatives d2pr_dErhos2 = _np.transpose(d2pr_dErhos1, (0, 2, 1)) else:", "self.sos.get_prep(rholabel).hessian_wrt_params( # rho_wrtFilter1, rho_wrtFilter2)) else: d2pr_d2rhos = 0 if self.sos.get_effect(elabel).has_nonzero_hessian(): dp_dAnyE = _np.dot(Gs,", "no cover # noqa for iBlk1 in myBlk1Indices: blk_wrtSlice1 = blocks1[iBlk1] dProdCache1 =", "linear in their parameters, this # isn't currently needed. N = len(revOpLabelList) for", "2nd derivatives of the probabilities generated by a each gate sequence given by", "the matrix [ sum_{L s.t. GL == oplabel} [ (G1 ... G(L-1)) tensor", "concat w/better gather? # ------------------------------------------------------------------ tSerialStart = _time.time() if evalTree.is_split(): _warnings.warn(\"Ignoring tree splitting", "data to final values scaleVals = self._scaleExp(evalSubTree.final_view(scaleCache)) Gs = evalSubTree.final_view(prodCache, axis=0) #( nCircuits,", "dProdCache[i].min() > -DSMALL: _warnings.warn(\"Would have scaled dProd but now will not alter scaleCache.\")", "dProdCache = self._compute_dproduct_cache(evalTree, prodCache, scaleCache, comm, wrtSlice) #use cached data to construct return", "numpy's reshape dim = self.dim uniqueOpLabels = sorted(list(set(revOpLabelList))) used_operations = _collections.OrderedDict() #Cache processed", "dprobs1 & dprobs2 mem += cache_size * wrtLen1 * wrtLen2 * dim *", "scaleCache[iRight] if prodCache[i].max() < PSMALL and prodCache[i].min() > -PSMALL: nL, nR = max(_nla.norm(L),", "0 #SPAM ------------- # Get: dp_drhos[i, rho_gpindices] = dot(E,Gs[i],drho/drhoP) # dp_drhos[i,J0+J] = sum_kl", "dProdCache[i].max() < DSMALL and dProdCache[i].min() > -DSMALL: _warnings.warn(\"Scaled dProd small in order to", "= [ # _slct.shift(_slct.intersect( # wrtSlices['preps'], # slice(self.rho_offset[i],self.rho_offset[i+1])), # -self.rho_offset[i]) for i in", "_fas(mxToFill, [fInds, pslc1], self._dprobs_from_rhoE( spamTuple, rho, E, Gs[gInds], dGs[gInds], scaleVals[gInds], block_wrtSlice), add=sumInto) _np.seterr(**old_err)", "additionally return the derivative of the probability. clipTo : 2-tuple (min,max) to clip", "\"statevec\": raise NotImplementedError(\"Unitary evolution not fully supported yet!\") # pr = Tr( |rho><E|", "dot(E,Gs[i],drho/drhoP) # dp_drhos[i,J0+J] = sum_kl E[0,k] Gs[i,k,l] drhoP[l,J] # dp_drhos[i,J0+J] = dot(E, Gs,", "dim = self.dim #Cache partial products (relatively little mem required) leftProds = []", "length-S array specifying the scaling that needs to be applied to the resulting", "a 1 x M numpy array, where M is the number of model", "bulk_product, bulk_dproduct, and bulk_hproduct. Returns ------- block_generator A generator which, when iterated, yields", "self.Np)) _fas(d2pr_d2rhos, [0, self.sos.get_prep(rholabel).gpindices, self.sos.get_prep(rholabel).gpindices], _np.tensordot(derivWrtAnyRhovec, self.sos.get_prep(rholabel).hessian_wrt_params(), (1, 0))) # _np.einsum('ij,jkl->ikl', derivWrtAnyRhovec, self.sos.get_prep(rholabel).hessian_wrt_params())", "OK devec = EVec.deriv_wrt_params(E_wrtFilter2) _fas(d2pr_dEs1, [None, None, E_gpindices2], _np.dot(dp_dAnyE, devec)) # get d2pr_dEs", "scaleVals, 0, 3) # may overflow or get nans (invalid), but ok dGs2", "gatherMemLimit) if deriv1MxToFill is not None: _mpit.gather_indices(subtreeElementIndices, subTreeOwners, deriv1MxToFill, [], 0, comm, gatherMemLimit)", "clipTo): \"\"\" Compute the Hessian of a probability generated by a operation sequence", "all have norm <= 1 assert(len(nanOrInfCacheIndices) == 0) return prodCache, scaleCache def _compute_dproduct_cache(self,", "return PrepEffectFilter(rho_local_slices=loc_rho_slices, # rho_global_slices=global_rho_slices, # e_local_slices=loc_e_slices, # e_global_slices=global_e_slices, # num_rho_params=_slct.length(wrtSlices['preps']), # num_e_params=_slct.length(wrtSlices['effects'])) #", "# _np.einsum('ij,jkl->ikl', dp_dAnyRho, self.sos.get_prep(rholabel).hessian_wrt_params( # rho_wrtFilter1, rho_wrtFilter2)) else: d2pr_d2rhos = 0 if self.sos.get_effect(elabel).has_nonzero_hessian():", "= obj.gpindices_as_array() for ii, i in enumerate(wrtFilter): if i in gpindices: relevant_gpindices.append(ii) obj_wrtFilter.append(list(gpindices).index(i))", "#note: pass prMxToFill, dim=(KS,), so gather prMxToFill[felInds] (axis=0) profiler.add_time(\"MPI IPC\", tm) profiler.mem_check(\"bulk_fill_dprobs: post", "gate derivatives d2pr_dErhos2 = _np.transpose(d2pr_dErhos1, (0, 2, 1)) else: d2pr_dErhos2 = _np.zeros((nCircuits, nDerivCols2,", "(iRight, iLeft) = evalTree[i] L, R = prodCache[iLeft], prodCache[iRight] prodCache[i] = _np.dot(L, R)", "mySubTreeIndices, subTreeOwners, mySubComm = evalTree.distribute(comm) #eval on each local subtree for iSubTree in", "L == M} [ G1 ... G(M-1) tensor (G(M+1) ... GN)^T vec( d2G(M)/dkl*dji", "are arrays of shape K x S x B x B', where: -", "nBlks2) #distribute derivative computation across blocks myBlk1Indices, blk1Owners, blk1Comm = \\ _mpit.distribute_indices(list(range(nBlks1)), mySubComm)", "# rho_wrtFilter1, rho_wrtFilter2)) else: d2pr_d2rhos = 0 if self.sos.get_effect(elabel).has_nonzero_hessian(): dp_dAnyE = _np.dot(Gs, rho).squeeze(2)", "G = ident for (j, opLabel2) in enumerate(revOpLabelList[i:], start=i): # loop over \"ending\"", "tSerialStart) profiler.add_count(\"compute_dproduct_cache: num columns\", nDerivCols) return dProdCache def _compute_hproduct_cache(self, evalTree, prodCache, dProdCache1, dProdCache2,", "prod.flatten()). # # Note: if gate G(L) is just a matrix of parameters,", "self.Np, self.Np)) _fas(d2pr_d2rhos, [0, self.sos.get_prep(rholabel).gpindices, self.sos.get_prep(rholabel).gpindices], _np.tensordot(derivWrtAnyRhovec, self.sos.get_prep(rholabel).hessian_wrt_params(), (1, 0))) # _np.einsum('ij,jkl->ikl', derivWrtAnyRhovec,", "final result num_deriv_cols = self.Np if (wrtFilter is None) else len(wrtFilter) flattened_dprod =", "self._fill_result_tuple( (mxToFill,), evalSubTree, blocks[iBlk], slice(None), calc_and_fill_blk) profiler.mem_check(\"bulk_fill_dprobs: post fill blk\") dProdCache = dGs", "This is done over operation sequences when a *split* evalTree is given, otherwise", "numpy array Only returned when bReturnDProdsAndProds == True. An array of shape S", "first two arguments), and in general only a specified slice of the values", "raise NotImplementedError(\"Unitary evolution not fully supported yet!\") #Compute probability and save in return", "]] * vec( dG(L)/dij) ) # noqa # if dG(L)/dij = E(i,j) #", "evalTree.is_split(): _warnings.warn(\"Ignoring tree splitting in product cache calc.\") cacheSize = len(evalTree) prodCache =", "i in range(len(self.preps)) ] # global_e_slices = [slice(self.e_offset[i],self.e_offset[i+1]) for i in range(len(self.effects)) ]", "dProdCache1[iRight] dL2, dR2 = dProdCache2[iLeft], dProdCache2[iRight] hL, hR = hProdCache[iLeft], hProdCache[iRight] # Note:", "# wrtSlices['effects'], # slice(self.e_offset[i],self.e_offset[i+1])), # -self.e_offset[i]) for i in range(len(self.effects))] # tmp_num_params =", "\"\"\" tm = _time.time() old_err = _np.seterr(over='ignore') rho, E = self._rhoE_from_spamTuple(spamTuple) block_wrtSlice =", "\"\"\" #Note: num_final_strs is irrelevant here b/c cachesize is always >= num_final_strs #", "#Fill hessian cache info dProdCache1 = self._compute_dproduct_cache( evalSubTree, prodCache, scaleCache, mySubComm, wrtSlice1) dProdCache2", "= E(i,j) # noqa # = vec(i,j)-col of [ sum_{L s.t. G(L) ==", "+ dpr_dOps def hpr(self, spamTuple, circuit, returnPr, returnDeriv, clipTo): \"\"\" Compute the Hessian", "a tree being # split because there's no good way to reconstruct the", "most linear in params, so # all hessians for single- or zero-operation sequences", "and wrtFilter2 is None: blkSize1 = wrtBlockSize1 # could be None blkSize2 =", "below). wrtFilter : list of ints, optional If not None, a list of", "comm=None): \"\"\" Compute the products of many operation sequences at once. Parameters ----------", "== False, two arrays of shape S x M x G x G,", "E_gpindices2, rho_gpindices1], _np.swapaxes(_np.dot(_np.transpose(devec), dp_dAnyE), 0, 1)) d2pr_dErhos2 = _np.transpose(d2pr_dErhos2, (0, 2, 1)) #Note:", "# could be None blkSize2 = wrtBlockSize2 # could be None if (mySubComm", "== length of the vectorized model (number of model parameters) - G ==", "(len(circuit_list), nDerivCols, nDerivCols) # may also give invalid value due to scaleVals being", "(see wrtBlockSize). wrtFilter1, wrtFilter2 : list of ints, optional If not None, a", "efficiently compute the gate-only sequences. This routine fills in `mxToFill`, which must have", "[felInds, blocks1[iBlk1]], 2, blk1Comm, gatherMemLimit) #gather row results; gather axis 1 of mxToFill[felInds],", "B ) = B^T tensor A * vec( X ) def doperation(self, opLabel,", "to construct return values Gs = evalTree.final_view(prodCache, axis=0) #shape == ( len(circuit_list), dim,", "mySubComm) # , gatherMemLimit) #gather over col-distribution (Deriv2) #note: gathering axis 2 of", "hProdCache = self._compute_hproduct_cache(evalTree, prodCache, dProdCache1, dProdCache2, scaleCache, comm, wrtSlice1, wrtSlice2) #use cached data", "LinearOperator objects to # have a 2nd-deriv method in addition of deriv_wrt_params #", "and `deriv1MxToFill`), then: - `hprobs == mx[:,:,rowSlice,colSlice]` - `dprobs12 == dp1[:,:,rowSlice,None] * dp2[:,:,None,colSlice]`", "of gates in the string, compute the hessian of the entire # operation", "irrelevant here b/c cachesize is always >= num_final_strs # and this dictates how", "# product of no gates G = ident for (j, opLabel2) in enumerate(revOpLabelList[i:],", "cache # mem += cache_size # scale vals # #elif fnName == \"bulk_hproduct\":", "allow a trace or other linear operation to be done prior to the", "1) # cols = deriv cols, rows = flattened everything else return (dGs,", "will be assigned to subtrees of the created tree. This aids in the", "# hprobs & dprobs12 results mem += cache_size * nspam * (wrtLen1 +", "# ------------------------------------------------------------------ tSerialStart = _time.time() if evalTree.is_split(): _warnings.warn(\"Ignoring tree splitting in dproduct cache", "wrtBlockSize2 is None) # Cannot specify both wrtFilter and wrtBlockSize wrtSlice1 = _slct.list_to_slice(wrtFilter1)", "the 1st and 2nd differentiation, respectively (i.e. by wrtFilter1 and wrtFilter2). clipTo :", "Specifies the *simplified* gate strings to compute the bulk operation on. clipTo :", "array Only returned when bScale == True. An array of shape S such", "[slice(self.e_offset[i],self.e_offset[i+1]) for i in range(len(self.effects)) ] # return PrepEffectFilter(rho_local_slices=loc_rho_slices, # rho_global_slices=global_rho_slices, # e_local_slices=loc_e_slices,", "= x.view() xv = _np.transpose(xv, axes=(2, 0, 1)) # (dim2, nDerivCols1, nDerivCols2) flattened_d2prod[:,", "respectively (i.e. by wrtFilter1 and wrtFilter2). clipTo : 2-tuple, optional (min,max) to clip", "the user has already done any such distribution # and has given each", "evalTree (if it is split). Returns ------- None \"\"\" #get distribution across subtrees", "flat == True, a N x M array, where: - N == the", "the tree information it needs to distribute itself among the available processors. Returns", "sum_k E[0,k] dot(Gs, rho)[i,k,0] * scaleVals[i] # vp[i] = dot( E, dot(Gs, rho))[0,i,0]", "same thing (for debugging) master_circuit_list = evalTree.generate_circuit_list(permute=False) # raw operation sequences for spamTuple,", "wrtSlice2) dGs1 = evalSubTree.final_view(dProdCache1, axis=0) dGs2 = evalSubTree.final_view(dProdCache2, axis=0) #( nCircuits, nDerivColsX, dim,", "done at a higher level. \"\"\" dim = self.dim #Note: previously, we tried", "spamTuple E = _np.conjugate(_np.transpose(Eraw)) return rho, E def _rhoEs_from_spamTuples(self, rholabel, elabels): #Note: no", "rhoVec.deriv_wrt_params(rho_wrtFilter1) dp_dAnyE = _np.dot(Gs, drho) * scaleVals[:, None, None] # overflow OK devec", "is performed as in bulk_product, bulk_dproduct, and bulk_hproduct. Returns ------- block_generator A generator", "dProdCache1 = dGs1 = None # free mem def _fill_result_tuple(self, result_tup, evalTree, param_slice1,", "if wrtFilter is not None: assert(wrtBlockSize is None) # Cannot specify both wrtFilter", "L, R = GxG ; dL,dR = vgs x GxG ; hL,hR =", "by evalTree's initial single- or zero-operation labels wrtIndices1 = _slct.indices(wrtSlice1) if (wrtSlice1 is", "there would be no memory savings from using a split tree. In short,", "processor groups used to (in parallel) iterate through the subtrees. It can often", "dictates block if blkSize is None: #Fill derivative cache info tm = _time.time()", "you'll need the mappings generated when the original list of `Circuits` was simplified.", "the matrix d12 defined by: d12[iSpamLabel,iOpStr,p1,p2] = dP/d(p1)*dP/d(p2) where P is is the", "loc_rho_slices = [slice(None,None)]*len(self.preps) # loc_e_slices = [slice(None,None)]*len(self.effects) # global_rho_slices = [slice(self.rho_offset[i],self.rho_offset[i+1]) for i", "subtrees = evalTree.get_sub_trees() mySubTreeIndices, subTreeOwners, mySubComm = evalTree.distribute(comm) #eval on each local subtree", "# free mem def _fill_result_tuple(self, result_tup, evalTree, param_slice1, param_slice2, calc_and_fill_fn): \"\"\" This function", "from .matrixevaltree import MatrixEvalTree as _MatrixEvalTree from .forwardsim import ForwardSimulator _dummy_profiler = _DummyProfiler()", "such distribution # and has given each processor a list appropriate for it.", "which computes and *fills* (i.e. doesn't return to save copying) some arrays. The", "iSubTree in mySubTreeIndices: evalSubTree = subtrees[iSubTree] #Free memory from previous subtree iteration before", "flattened product with respect to the k-th then k-th model parameters. \"\"\" #", "blkSize = None # wrtFilter dictates block if blkSize is None: #Fill derivative", "scaleVals[gInds], wrtSlice1), add=sumInto) if deriv2MxToFill is not None: _fas(deriv2MxToFill, [fInds, pslc2], self._dprobs_from_rhoE( spamTuple,", "the derivative of the entire operation sequence # with respect to only that", "of python objects (never seemed very useful ## since numpy does all the", "dGs2 = evalTree.final_view(dProdCache2, axis=0) hProdCache = self._compute_hproduct_cache( evalTree, prodCache, dProdCache1, dProdCache2, scaleCache, comm,", "END CACHE FUNCTIONS def default_distribute_method(self): \"\"\" Return the preferred MPI distribution mode for", "major allocation/deallocation). #if comm is None or comm.Get_rank() == 0: # import objgraph", "# get d2pr_drhos where gate derivatives are wrt the 2nd set of gate", "hop_dopLabels[opLabel] = gate.hessian_wrt_params( gate_wrtFilters1[opLabel], gate_wrtFilters2[opLabel]) # Allocate memory for the final result num_deriv_cols1", "mem dProdCache1 = dGs1 = None # free mem #gather column results: gather", "[ G1 ... G(M-1) tensor (G(M+1) ... GN)^T vec( d2G(M)/dkl*dji ) # noqa", "# a matrix for each given (i,j,k,l) # noqa # vec( d2prod/d(opLabel1)_kl*d(opLabel2)_ij )", "before computing caches scaleVals = Gs = dGs = None prodCache = scaleCache", "MPI processor syncronization. Returns ------- None \"\"\" tStart = _time.time() if profiler is", "self._check(evalTree, mxToFill, clipTo=clipTo) def bulk_fill_dprobs(self, mxToFill, evalTree, prMxToFill=None, clipTo=None, check=False, comm=None, wrtFilter=None, wrtBlockSize=None,", "(opLabel,) , wrtFilter=wrtIndices) doperation = self.doperation(opLabel, wrtFilter=wrtIndices) dProdCache[i] = doperation / _np.exp(scaleCache[i]) #profiler.print_mem(\"DEBUGMEM:", "parameters to include in the derivative dimension. This argument is used internally for", "hessians[i,j,k,l,m] holds the derivative of the (l,m)-th entry of the i-th operation sequence", "of a operation matrix (G x G operation matrices). and hessian[i,j,k,l] holds the", "will not alter scaleCache.\") #profiler.print_mem(\"DEBUGMEM: POINT2\"); profiler.comm.barrier() profiler.add_time(\"compute_dproduct_cache: serial\", tSerialStart) profiler.add_count(\"compute_dproduct_cache: num columns\",", "and not d2(prod)/d(gl2)d(gl1) ... if m < l: x0 = _np.kron(_np.transpose(prods[(0, m -", "return flattened_d2prod # axes = (vectorized_op_el_index, model_parameter1, model_parameter2) else: vec_kl_size, vec_ij_size = flattened_d2prod.shape[1:3]", "elements correspond to which strings and outcomes, you'll need the mappings generated when", ") hProdCache = self._compute_hproduct_cache(evalSubTree, prodCache, dProdCache1, dProdCache2, scaleCache, mySubComm, wrtSlice1, wrtSlice2) hGs =", "_np.zeros((1, self.Np, self.Np)) derivWrtAnyEvec = _np.squeeze(_np.dot(dprod_dOps, rho), axis=(2,)) _fas(d2pr_dEs, [0, None, EVec.gpindices], _np.dot(derivWrtAnyEvec,", "of the i-th entry of the flattened product with respect to the k-th", "flattened everything else return (dGs, scaleVals) if bScale else dGs def bulk_hproduct(self, evalTree,", "(_nla.norm(prMxToFill[fInds]), _nla.norm(check_vp), _nla.norm(prMxToFill[fInds] - check_vp))) # pragma: no cover if dprMxToFill is not", ": int The number of groups to divide the first-derivative parameters into. Computation", "0 for fnName in subcalls: if fnName == \"bulk_fill_probs\": mem += cache_size *", "array (see below). wrtFilter : list of ints, optional If not None, a", "ordered by concatenating each gate's parameters (in the order specified by the model).", "generate overflow, but OK) ps = _np.real(_np.dot(Es, _np.dot(G, rho)) * scale) _np.seterr(**old_err) else:", "the operation sequences to compute the bulk operation on. bScale : bool, optional", "# dp_dOps = squeeze( dot( E, dot( dGs, rho ) ), axis=(0,3)) old_err2", "dp1[:,:,rowSlice,None] * dp2[:,:,None,colSlice]` \"\"\" assert(not evalTree.is_split()), \"`evalTree` cannot be split\" nElements = evalTree.num_final_elements()", "self.sos.get_prep(rholabel) # distinct from rho,E b/c rho,E are EVec = self.sos.get_effect(elabel) # arrays,", "matrices). and deriv[i,j,k] holds the derivative of the (j,k)-th entry of the product", "EVec.deriv_wrt_params())) d2pr_dErhos = _np.zeros((1, self.Np, self.Np)) derivWrtAnyEvec = scale * _np.dot(prod, rhoVec.deriv_wrt_params()) #", "None) \\ else min(comm_blkSize, blkSize) # override with smaller comm_blkSize else: blkSize =", "zero _np.seterr(**old_err) if returnDeriv: if returnPr: return ret, dpr, p else: return ret,", "self.sos.get_operation(opLabel).todense() nG = max(_nla.norm(gate), 1.0) prodCache[i] = gate / nG scaleCache[i] = _np.log(nG)", "i.e. rank != 0, cpus hProdCache[:, myDeriv1ColSlice, myDeriv2ColSlice] = self._compute_hproduct_cache( evalTree, prodCache, dProdCache1[:,", "boolean, optional If True, perform extra checks within code to verify correctness, generating", "self.sos.get_prep(rholabel).todense()[:, None] E = _np.conjugate(_np.transpose(self.sos.get_effect(elabel).todense() [:, None])) # convention: E has shape (1,N)", "for *complex* derivatives, since matrices can be complex # - update probability-derivative computations:", "dprobs12 = dprobs1[:, :, None] * dprobs2[:, None, :] # (KM,N,1) * (KM,1,N')", "gate strings to compute the bulk operation on. clipTo : 2-tuple, optional (min,max)", "nDerivCols2); # swapaxes takes (kl,vec_prod_indx,ij) => (vec_prod_indx,kl,ij) else: # l==m, which we *used*", "calculation tool used by model objects to perform product and derivatives-of-product calculations. This", "iRight from evalTree because # (iRight,iLeft,iFinal) = tup implies circuit[i] = circuit[iLeft] +", "simultaneously. None means compute all requested columns at once. The minimum of wrtBlockSize", "range(len(self.preps)) ] # # loc_e_slices = [ # _slct.shift(_slct.intersect( # wrtSlices['effects'], # slice(self.e_offset[i],self.e_offset[i+1])),", "scaling factor (see below). Returns ------- product : numpy array The product or", "since matrices can be complex # - update probability-derivative computations: dpr/dx -> d|pr|^2/dx", "the (i / G^2)-th flattened operation sequence product with respect to the k-th", "derivWrtAnyEvec)) #Note: these 2nd derivatives are non-zero when the spam vectors have #", "used by numpy.flatten), - S,M == as above, and deriv[i,j] holds the derivative", "= ps #DEBUG CHECK #check_ps = _np.array( [ self.pr( (rholabel,elabel), circuit, clipTo, bScale)", "{%.1f,%.1f}, nBlks={%d,%d}]\" % (blkSize1, blkSize2, nBlks1, nBlks2)) # pragma: no cover # noqa", "ps #DEBUG CHECK #check_ps = _np.array( [ self.pr( (rholabel,elabel), circuit, clipTo, bScale) for", "self.Np)) derivWrtAnyEvec = scale * _np.transpose(_np.dot(prod, rho)) # may overflow, but OK _fas(dpr_dEs,", "max(_nla.norm(gate), 1.0) prodCache[i] = gate / nG scaleCache[i] = _np.log(nG) #evaluate operation sequences", "_np.seterr(invalid='ignore', over='ignore') dp_dOps = _np.squeeze(_np.dot(E, _np.dot(dGs, rho)), axis=(0, 3)) * scaleVals[:, None] _np.seterr(**old_err2)", "always >= num_final_strs # and this dictates how large all the storage arrays", "slices directly from `wrtSlicesList`. `hprobs` and `dprobs12` are arrays of shape K x", "## BEGIN CACHE FUNCTIONS def _compute_product_cache(self, evalTree, comm=None): \"\"\" Computes a tree of", "#NOTE: don't distribute wrtSlicesList across comm procs, # as we assume the user", "Specifies the operation sequences to compute the bulk operation on. This tree *cannot*", "(wrtFilter is not None) else None #TODO: just allow slices as argument: wrtFilter", "on each local subtree for iSubTree in mySubTreeIndices: evalSubTree = subtrees[iSubTree] #Free memory", "complex # - update probability-derivative computations: dpr/dx -> d|pr|^2/dx = d(pr*pr.C)/dx = dpr/dx*pr.C", "(G1 ... G(L-1)) tensor (G(L+1) ... GN)^T ]] has # columns which correspond", "Circuit or tuple of operation labels The sequence of operation labels. flat :", "# since then matrixOf(circuit[i]) = matrixOf(circuit[iLeft]) * matrixOf(circuit[iRight]) (iRight, iLeft) = evalTree[i] L,", "gate (ordering as numpy.flatten), - S,M == as above, and hessians[i,j,k] holds the", "zero deriv value (see below) dGs[_np.isnan(dGs)] = 0 _np.seterr(**old_err) if flat: dGs =", "num_param2_groups : int The number of groups to divide the second-derivative parameters into.", "the corresponding wrtFilter is not None. Set this to non-None to reduce amount", "required. profiler : Profiler, optional A profiler object used for to track timing", "general: vec( A * X * B ) = B^T tensor A *", "G prods[(len(revOpLabelList), len(revOpLabelList) - 1)] = ident # product of no gates #Also", "can be computed properly if wrtSlice1 is not None and wrtSlice1.start is not", "dot( E, dot( dGs, rho ) ), axis=(0,3)) old_err2 = _np.seterr(invalid='ignore', over='ignore') dp_dOps", "_fas(d2pr_dErhos1, (None, E_gpindices1, rho_gpindices2), _np.swapaxes(_np.dot(_np.transpose(devec), dp_dAnyE), 0, 1)) # get d2pr_dEs where E", "# Note when vectorizing op uses numpy.flatten rows are kept contiguous, so the", "range(len(self.effects)) ] # return PrepEffectFilter(rho_local_slices=loc_rho_slices, # rho_global_slices=global_rho_slices, # e_local_slices=loc_e_slices, # e_global_slices=global_e_slices, # num_rho_params=self.tot_rho_params,", "multiple processors. Distribution is first performed over subtrees of evalTree (if it is", "mem += cache_size * nspam * (wrtLen1 + wrtLen2) # dprobs1 & dprobs2", "be complex # - update probability-derivative computations: dpr/dx -> d|pr|^2/dx = d(pr*pr.C)/dx =", "dprod_dOps = self.dproduct(circuit) dpr_dOps = _np.empty((1, self.Np)) for i in range(self.Np): dpr_dOps[0, i]", "starting with identity scale_exp += ex # scale and keep track of exponent", "dProdCache1[iLeft], dProdCache1[iRight] dL2, dR2 = dProdCache2[iLeft], dProdCache2[iRight] hL, hR = hProdCache[iLeft], hProdCache[iRight] #", "for distributing derivative calculations across multiple processors. Returns ------- hessian : numpy array", "of the above matrices, so that # each column corresponds to a (opLabel,i,j)", "None, an MPI communicator for distributing the computation across multiple processors. This is", "M} [ G1 ... G(M-1) tensor (G(M+1) ... GN)^T vec( d2G(M)/dkl*dji ) #", "in enumerate(wrtFilter): if i in gpindices: relevant_gpindices.append(ii) obj_wrtFilter.append(list(gpindices).index(i)) relevant_gpindices = _np.array(relevant_gpindices, _np.int64) if", ") ] # noqa # = sum{...} [ unvec( G1 ... G(M-1) tensor", "subcalls to computation functions. Parameters ---------- subcalls : list of strs A list", "a time. For example, the Hessian of a function of many gate sequence", "x M where: - N == the number of entries in a single", "i-th entry of the flattened product with respect to the j-th model parameter.", "* if flat == True, an array of shape S*N x M x", "blocks1[iBlk1]], 2, blk1Comm, gatherMemLimit) #gather row results; gather axis 1 of mxToFill[felInds], dim=(ks,M,M)", "range(self.Np): dpr_dOps[0, i] = float(_np.dot(E, _np.dot(dprod_dOps[i], rho))) if returnPr: p = _np.dot(E, _np.dot(prod,", "(sub-)tree\" \" (e.g. by splitting tree beforehand), as there\" \" are more cpus", "_slct.list_to_slice(wrtFilter2) if (wrtFilter2 is not None) else None #TODO: just allow slices as", "= _np.dot(self.sos.get_operation(lOp).todense(), G) # LEXICOGRAPHICAL VS MATRIX ORDER return G def _process_wrtFilter(self, wrtFilter,", "of %d products\" % (cnt, len(evalTree)) nanOrInfCacheIndices = (~_np.isfinite(prodCache)).nonzero()[0] # may be duplicates", "E[0,k] dGs[i,j,k,l] drhoP[l,J] # d2pr_drhos[i,j,J0+J] = dot(E, dGs, drhoP)[0,i,j,J] # d2pr_drhos[:,:,J0+J] = squeeze(dot(E,", "drho) * scaleVals[:, None, None] # overflow OK devec = EVec.deriv_wrt_params(E_wrtFilter1) _fas(d2pr_dErhos1, (None,", "= sum E_k [dprod/d(opLabel1)_mn d(opLabel2)_ij]_kl rho_l # d2pr/d(rho)_i d(opLabel)_mn = sum E_k [dprod/d(opLabel)_mn]_ki", "ith string hGs = evalTree.final_view(hProdCache, axis=0) #shape == ( len(circuit_list), nDerivCols1, nDerivCols2, dim,", "== True, a N x M array, where: - N == the number", "swapaxes takes (kl,vec_prod_indx,ij) => (vec_prod_indx,kl,ij) else: # l==m, which we *used* to assume", "= 1e-100 DSMALL = 1e-100 HSMALL = 1e-100 class MatrixForwardSimulator(ForwardSimulator): \"\"\" Encapsulates a", "#if comm is not None: # print(\"MPI DEBUG: Rank%d subtee sizes = %s\"", "but ok _np.seterr(**old_err) return Gs def bulk_dproduct(self, evalTree, flat=False, bReturnProds=False, bScale=False, comm=None, wrtFilter=None):", "sized/filtered) -------- assert(dGs1.shape[1] == nDerivCols1), \"dGs1 must be pre-filtered!\" assert(dGs2.shape[1] == nDerivCols2), \"dGs1", "a many operation sequences at once. Parameters ---------- evalTree : EvalTree given by", "comm is not None and comm.Get_size() > 1: #print(\"MPI: _compute_dproduct_cache called w/comm size", "self.dim #Cache partial products (relatively little mem required) leftProds = [] G =", "hL,hR = vgs x vgs x GxG dLdRa = _np.swapaxes(_np.dot(dL1, dR2), 1, 2)", "i in range(len(self.preps)+1) ] # global_rho_slices = [ slice(tmp_offsets[i],tmp_offsets[i+1]) # for i in", "add=sumInto) _np.seterr(**old_err) profiler.add_time(\"bulk_fill_dprobs: calc_and_fill_p\", tm) # Compute all probabilities all at once so", "tree of products in a linear cache space. Will *not* parallelize computation, even", "mxToFill, evalTree, prMxToFill=None, clipTo=None, check=False, comm=None, wrtFilter=None, wrtBlockSize=None, profiler=None, gatherMemLimit=None): \"\"\" Compute the", "0.0 from initialization else: gate = self.sos.get_operation(opLabel).todense() nG = max(_nla.norm(gate), 1.0) prodCache[i] =", "bounds #assert( len( (_np.isnan(hGs)).nonzero()[0] ) == 0 ) #assert( len( (_np.isinf(hGs)).nonzero()[0] ) ==", "be useful to have fewer processor groups then subtrees (even == 1) in", "Gs = dGs1 = dGs2 = hGs = None prodCache = scaleCache =", ": int or float, optional The maximum number of derivative columns to compute", "the storage arrays are. np1, np2 = num_param1_groups, num_param2_groups FLOATSIZE = 8 #", "dimension of a operation matrix (G x G operation matrices) and hessians[i,j,k,l,m] holds", "can be obtained by `evalTree.num_final_elements()`. To interpret which elements correspond to which strings", "wrtBlockSize2 is None) # Cannot specify both wrtFilter and wrtBlockSize wrtSlice2 = _slct.list_to_slice(wrtFilter2)", "G(L) == oplabel} [ (G1 ... G(L-1)) tensor (G(L+1) ... GN)^T ]] *", "string hGs = evalTree.final_view(hProdCache, axis=0) #shape == ( len(circuit_list), nDerivCols1, nDerivCols2, dim, dim", "array only returned if returnDeriv == True. A 1 x M numpy array", "in the derivative. Each element is an index into an array of gate", "\"\"\" Return the preferred MPI distribution mode for this calculator. \"\"\" return \"deriv\"", "dGs2 = _np.swapaxes(_np.swapaxes(dGs2, 0, 1).reshape((nDerivCols2, nCircuits * dim**2)), 0, 1) hGs = _np.rollaxis(_np.rollaxis(hGs,", "dp_dEs = _np.zeros((nCircuits, nDerivCols)) # may overflow, but OK (deriv w.r.t any of", "(blkSize, nBlks)) # pragma: no cover def calc_and_fill_blk(spamTuple, fInds, gInds, pslc1, pslc2, sumInto):", "numpy.flatten does) # vec( A * E(0,1) * B ) = vec( mx", "You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 or in", "= _slct.list_to_slice(wrtFilter2) if (wrtFilter2 is not None) else None #TODO: just allow slices", "set) # since all scaled gates start with norm <= 1, products should", "subtrees] _mpit.gather_indices(subtreeElementIndices, subTreeOwners, mxToFill, [], 0, comm, gatherMemLimit) if deriv1MxToFill is not None:", "= _np.kron(leftProds[i], rightProdsT[N - 1 - i]) # (dim**2, dim**2) _fas(flattened_dprod, [None, gpindices],", "/ np2) mem = 0 for fnName in subcalls: if fnName == \"bulk_fill_probs\":", "mx[:,:,rowSlice,colSlice]` - `dprobs12 == dp1[:,:,rowSlice,None] * dp2[:,:,None,colSlice]` \"\"\" assert(not evalTree.is_split()), \"`evalTree` cannot be", "circuit in circuit_list]) if _nla.norm(prMxToFill[fInds] - check_vp) > 1e-6: _warnings.warn(\"norm(vp-check_vp) = %g -", "Parameters ---------- rholabel : Label The state preparation label. elabels : list A", "= float(dot(E, dot(G, rho))) # vp[i] = sum_k,l E[0,k] Gs[i,k,l] rho[l,0] * scaleVals[i]", "== \"statevec\": ps = _np.real(_np.abs(_np.dot(Es, _np.dot(G, rho)))**2) else: # evotype == \"densitymx\" ps", "# overflow OK d2pr_d2Es = _np.zeros((nCircuits, nDerivCols1, nDerivCols2)) _fas(d2pr_d2Es, [None, E_gpindices1, E_gpindices2], _np.tensordot(dp_dAnyE,", "overflow, but OK # (** doesn't depend on eIndex **) -- TODO: should", "enumerate(revOpLabelList[i:], start=i): # loop over \"ending\" gate (>= starting gate) G = _np.dot(G,", "(nDerivCols, nCircuits * dim**2)), 0, 1) # cols = deriv cols, rows =", "_warnings.warn(\"Note: more CPUs(%d)\" % mySubComm.Get_size() + \" than hessian elements(%d)!\" % (self.Np**2) +", "for m, opLabel1 in enumerate(revOpLabelList): inds1 = gpindices1[opLabel1] nDerivCols1 = dop_dopLabel1[opLabel1].shape[1] if nDerivCols1", "needed to correctly handle the remainder spam label. \"\"\" pslc1 = param_slice1 pslc2", "bReturnProds: Gs = evalTree.final_view(prodCache, axis=0) #shape == ( len(circuit_list), dim, dim ), #", "_compute_hproduct_cache over %d cols (rank %d computing %s)\" \\ # % (nDerivCols2, comm.Get_rank(),", "allDerivColSlice = slice(0, nDerivCols) if (wrtSlice is None) else wrtSlice _, myDerivColSlice, _,", "# product cache mem += cache_size # scale cache mem += cache_size #", "= (self.Np + np1 - 1) // np1 # ceiling(num_params / np1) wrtLen2", "each block of derivative columns if prMxToFill is not None: self._fill_result_tuple((prMxToFill,), evalSubTree, slice(None),", "None: _mpit.gather_slices(blocks1, blk1Owners, deriv1MxToFill, [felInds], 1, mySubComm, gatherMemLimit) if deriv2MxToFill is not None:", "memory savings from using a split tree. \"\"\" if profiler is None: profiler", "MPI communicator for distributing the computation across multiple processors. This is done over", "float Only returned when bScale == True, in which case the actual product", "hessian # Note: d2pr_d2rhos and d2pr_d2Es terms are always zero _np.seterr(**old_err) if returnDeriv:", ": list of ints, optional If not None, a list of integers specifying", "wrtSlice1, wrtSlice2, hprobs dProdCache1 = dGs1 = None # free mem def _fill_result_tuple(self,", "Parameters ---------- dim : int The gate-dimension. All operation matrices should be dim", "wrtIndices2 = _slct.indices(wrtSlice2) if (wrtSlice2 is not None) else None for i, opLabel", "noqa # dprod/d(opLabel)_ij = sum_{L s.t. G(L) == oplabel} [ G1 ... G(L-1)", "bulk operation on. This tree *cannot* be split. wrtSlicesList : list A list", "model_parameter1, model_parameter2) else: vec_kl_size, vec_ij_size = flattened_d2prod.shape[1:3] # == num_deriv_cols1, num_deriv_cols2 return _np.rollaxis(flattened_d2prod,", "dpr_dOps, p else: return dpr_drhos + dpr_dEs + dpr_dOps def hpr(self, spamTuple, circuit,", "be thought of as the first gate operation performed, which is on the", "flat: dGs = _np.swapaxes(_np.swapaxes(dGs, 0, 1).reshape( (nDerivCols, nCircuits * dim**2)), 0, 1) #", "* scaleVals[i] # vp[i] = sum_k E[0,k] dot(Gs, rho)[i,k,0] * scaleVals[i] # vp[i]", "evalTree.final_view(hProdCache, axis=0) if bReturnDProbs12: dprobs1 = _np.zeros((nElements, _slct.length(wrtSlice1)), 'd') dprobs2 = _np.zeros((nElements, _slct.length(wrtSlice2)),", "*fewer* processors and *smaller* (sub-)tree\" \" (e.g. by splitting tree beforehand), as there\"", "flattened_d2prod # axes = (vectorized_op_el_index, model_parameter1, model_parameter2) else: vec_kl_size, vec_ij_size = flattened_d2prod.shape[1:3] #", "evalTree.final_view(prodCache, axis=0) #shape == ( len(circuit_list), dim, dim ), # Gs[i] is product", "\"MatrixForwardSimulator cannot be used to simulate time-dependent circuits\" rho, Es = self._rhoEs_from_spamTuples(rholabel, elabels)", "if mySubSubComm is not None and mySubSubComm.Get_size() > 1: _warnings.warn(\"Too many processors to", "# scale vals ## It doesn't make sense to include these since their", "elabel in elabels ]) #assert(_np.linalg.norm(ps-check_ps) < 1e-8) return ret def dpr(self, spamTuple, circuit,", "distributing the computation across multiple processors. Distribution is first done over the set", "blocks1[iBlk1] dProdCache1 = self._compute_dproduct_cache( evalSubTree, prodCache, scaleCache, blk1Comm, blk_wrtSlice1) dGs1 = evalSubTree.final_view(dProdCache1, axis=0)", "E, dot( dGs, rho ) ), axis=(0,3)) old_err2 = _np.seterr(invalid='ignore', over='ignore') dp_dOps =", "_np.zeros((1, self.Np, self.Np)) _fas(d2pr_d2Es, [0, self.sos.get_effect(elabel).gpindices, self.sos.get_effect(elabel).gpindices], _np.tensordot(derivWrtAnyEvec, self.sos.get_effect(elabel).hessian_wrt_params(), (1, 0))) # _np.einsum('ij,jkl->ikl',derivWrtAnyEvec,self.sos.get_effect(elabel).hessian_wrt_params())", "< DSMALL and dProdCache[i].min() > -DSMALL: _warnings.warn(\"Would have scaled dProd but now will", "d12 defined by: d12[iSpamLabel,iOpStr,p1,p2] = dP/d(p1)*dP/d(p2) where P is is the probability generated", "operation sequence and spam tuple as a 1 x M x M array,", "columns and then (as needed) a split tree to parallelize computation, since there", "it's been removed. if comm is not None: # ignoring comm since can't", "E_gpindices], _np.dot(dp_dAnyE, EVec.deriv_wrt_params(E_wrtFilter))) sub_vdp = dp_drhos + dp_dEs + dp_dOps return sub_vdp #def", "slice(0,0) # #don't compute anything on \"extra\", i.e. rank != 0, cpus hProdCache[:,", "save in return list # d2pr_dOps2[i,j,k] = sum_l,m E[0,l] hGs[i,j,k,l,m] rho[m,0] # d2pr_dOps2[i,j,k]", "if (wrtFilter1 is None) else len(wrtFilter1) num_deriv_cols2 = self.Np if (wrtFilter2 is None)", "matrixOf(circuit[iLeft]) * matrixOf(circuit[iRight]) (iRight, iLeft) = evalTree[i] L, R = prodCache[iLeft], prodCache[iRight] prodCache[i]", "memory limit in bytes to impose upon the \"gather\" operations performed as a", "a derivative of only a *subset* of all the gate's parameters if isinstance(wrtFilter,", "elements from those of the sub-trees). Note also that there would be no", "_time.time() _mpit.gather_slices(blocks, blkOwners, mxToFill, [felInds], 1, mySubComm, gatherMemLimit) #note: gathering axis 1 of", "elements from those of the sub-trees. _warnings.warn(\"Increased speed could be obtained\" \" by", "Gs, scaleVals) if bScale else (hGs, dGs1, dGs2, Gs) else: hGs = evalTree.final_view(hProdCache,", "rho),axis=(2,)), dEP)[:,J] dp_dEs = _np.zeros((nCircuits, nDerivCols)) # may overflow, but OK (deriv w.r.t", "copying - throws error if copy is needed) # transposes each of the", "scaling needed for the derivatives and/or products for the i-th operation sequence. \"\"\"", "d(rho)_j = 0 rholabel, elabel = spamTuple rho, E = self._rhoE_from_spamTuple(spamTuple) rhoVec =", "bReturnProds == True. An array of shape S x G x G; products[i]", "_np.identity(self.dim) for lOp in circuit: G = _np.dot(self.sos.get_operation(lOp).todense(), G) # LEXICOGRAPHICAL VS MATRIX", "_np.isnan(p): raise ValueError(\"STOP\") if clipTo is not None: ret = _np.clip(ps, clipTo[0], clipTo[1])", "= _np.zeros((dim**2, num_deriv_cols1, num_deriv_cols2), 'd') if _slct.length(gpindices1) > 0 and _slct.length(gpindices2) > 0:", "), Gs[i] is product for i-th operation sequence scaleExps = evalTree.final_view(scaleCache) old_err =", "dim**2)), 2) # cols = deriv cols, rows = all else return (hGs,", "= {} gpindices2 = {}; gate_wrtFilters2 = {} for l in uniqueOpLabels: used_operations[l]", "that the product will overflow and the subsequent trace operation will yield nan", "evalTree.final_view(prodCache, axis=0) #shape == ( len(circuit_list), dim, dim ), Gs[i] is product for", "= 0 _np.seterr(**old_err) if flat: # cols = deriv cols, rows = flattened", "1)] = ident # product of no gates G = ident for (j,", "will be passed to the functions named by `subcalls`. num_subtrees : int The", "rank != 0, cpus hProdCache[:, myDeriv1ColSlice, myDeriv2ColSlice] = self._compute_hproduct_cache( evalTree, prodCache, dProdCache1[:, myDeriv1ColSlice],", "is the number of parameter columns (the length of colSlice) If `mx`, `dp1`,", "None, None] # overflow OK devec = EVec.deriv_wrt_params(E_wrtFilter2) _fas(d2pr_dEs1, [None, None, E_gpindices2], _np.dot(dp_dAnyE,", "\"\"\" Compute probabilities of a multiple \"outcomes\" (spam-tuples) for a single operation sequence.", "transposes each of the now un-vectorized dim x dim mxs corresponding to a", "cacheSize = len(evalTree) # ------------------------------------------------------------------ #print(\"MPI: _compute_dproduct_cache begin: %d deriv cols\" % nDerivCols)", "> 0: myDerivColSlice = slice(0, 0) #don't compute anything on \"extra\", i.e. rank", "E[0,k] Gs[i,k,l] drhoP[l,J] # dp_drhos[i,J0+J] = dot(E, Gs, drhoP)[0,i,J] # dp_drhos[:,J0+J] = squeeze(dot(E,", "evalSubTree.final_view(prodCache, axis=0) #( nCircuits, dim, dim ) def calc_and_fill(spamTuple, fInds, gInds, pslc1, pslc2,", "operation matrices). and deriv[i,j,k] holds the derivative of the (j,k)-th entry of the", "import slicetools as _slct from ..tools.matrixtools import _fas from .profiler import DummyProfiler as", "order specified by the model). This argument is used internally for distributing derivative", "_np.dot(dp_dAnyE, devec)) # get d2pr_dEs where gate derivatives are wrt the 2nd set", "self._compute_dproduct_cache(evalSubTree, prodCache, scaleCache, mySubComm, wrtSlice, profiler) dGs = evalSubTree.final_view(dProdCache, axis=0) #( nCircuits, nDerivCols,", "deriv1MxToFill, [felInds], 1, mySubComm, gatherMemLimit) if deriv2MxToFill is not None: _mpit.gather_slices(blocks2, blk2Owners, deriv2MxToFill,", "over the set of parameters being differentiated with respect to. If there are", "the number of entries in a single flattened gate (ordering as numpy.flatten), -", "in revOpLabelList: G = _np.dot(G, self.sos.get_operation(opLabel).todense()) leftProds.append(G) rightProdsT = [] G = _np.identity(dim);", "scaleVal is mult by a zero deriv value (see below) dGs1[_np.isnan(dGs1)] = 0", "the subsequent arguments, except for the last). The final argument is a boolean", "G operation matrices). and hessian[i,j,k,l] holds the derivative of the (k,l)-th entry of", "self.sos.get_effect(elabel).gpindices], _np.tensordot(derivWrtAnyEvec, self.sos.get_effect(elabel).hessian_wrt_params(), (1, 0))) # _np.einsum('ij,jkl->ikl',derivWrtAnyEvec,self.sos.get_effect(elabel).hessian_wrt_params()) else: d2pr_d2Es = 0 ret =", "bReturnDProdsAndProds == True. An array of shape S x G x G; products[i]", "the zero deriv value trumps since we've renormed to keep all the products", "to # select a subset of all the derivative columns, essentially taking #", "+ scaleCache[iRight]) if abs(scale) > 1e-8: # _np.isclose(scale,0) is SLOW! hProdCache[i] /= _np.exp(scale)", "parameters, then dG(L)/dij = E(i,j), an elementary matrix dim = self.dim #Cache partial", "None, myHessianSlice1, myHessianSlice2) # pass None as comm, *not* mySubSubComm, since we can't", "None \"\"\" #get distribution across subtrees (groups if needed) subtrees = evalTree.get_sub_trees() mySubTreeIndices,", "on the far right of the product of matrices. Parameters ---------- circuit :", "a wrtFilter argument relevant for a single object (gate or spam vec) \"\"\"", "by the subsequent arguments, except for the last). The final argument is a", "_mpit.gather_indices(subtreeElementIndices, subTreeOwners, prMxToFill, [], 0, comm) #note: pass prMxToFill, dim=(KS,), so gather prMxToFill[felInds]", "the length of spam_label_rows, - S is the number of operation sequences (i.e.", "i in evalTree.get_evaluation_order(): tm = _time.time() # combine iLeft + iRight => i", "(nDerivCols1,dim**2,nDerivCols2) flattened_d2prod[:, inds1, inds2] += _np.swapaxes(y, 0, 1) # above: dim = (dim2,", "they're not repeatedly # computed for each block of derivative columns if prMxToFill", "myDeriv1ColSlice #print(\"MPI: _compute_hproduct_cache over %d cols (rank %d computing %s)\" \\ # %", "if evalTree.is_split(): _warnings.warn(\"Ignoring tree splitting in hproduct cache calc.\") hProdCache = _np.zeros((cacheSize,) +", "[None, gpindices], _np.dot(LRproduct, dop_dopLabel), add=True) # (dim**2, nParams[opLabel]) if flat: return flattened_dprod else:", "= tup implies circuit[i] = circuit[iLeft] + circuit[iRight], but we want: # since", "the zero and single-gate-strings) for i in evalTree.get_evaluation_order(): # combine iLeft + iRight", "= self.dim # Note: dProdCache?.shape = (#circuits,#params_to_diff_wrt,dim,dim) nDerivCols1 = dProdCache1.shape[1] nDerivCols2 = dProdCache2.shape[1]", "vectorized model). probability : float only returned if returnPr == True. \"\"\" if", "= self._scaleExp(evalSubTree.final_view(scaleCache)) Gs = evalSubTree.final_view(prodCache, axis=0) #( nCircuits, dim, dim ) profiler.mem_check(\"bulk_fill_dprobs: post", "doperation(self, opLabel, flat=False, wrtFilter=None): \"\"\" Return the derivative of a length-1 (single-gate) sequence", ")[0,i,j,0] # dp_dOps = squeeze( dot( E, dot( dGs, rho ) ), axis=(0,3))", "first-derivative parameters into. Computation will be automatically parallelized over these groups. num_param2_groups :", "# *non-final* parent-tree elements from those of the sub-trees. _warnings.warn(\"Increased speed could be", "memory since this is allocated within # the generator and yielded, *not* allocated", "None: blkSize = wrtBlockSize # could be None if (mySubComm is not None)", "derivative dimension. This argument is used internally for distributing calculations across multiple processors", "= _np.identity(dim) for (i, opLabel1) in enumerate(revOpLabelList): # loop over \"starting\" gate prods[(i,", "into entire range of model params so that # per-gate hessians can be", "`dp1`, and `dp2` are the outputs of :func:`bulk_fill_hprobs` (i.e. args `mxToFill`, `deriv1MxToFill`, and", "single spam label (specified to it by the first two arguments), and in", "global_e_slices = [slice(self.e_offset[i],self.e_offset[i+1]) for i in range(len(self.effects)) ] # return PrepEffectFilter(rho_local_slices=loc_rho_slices, # rho_global_slices=global_rho_slices,", "prodCache, scaleCache = self._compute_product_cache(evalTree, comm) dProdCache1 = self._compute_dproduct_cache(evalTree, prodCache, scaleCache, comm, wrtSlice1) dProdCache2", "] # global_rho_slices = [ slice(tmp_offsets[i],tmp_offsets[i+1]) # for i in range(len(self.preps)) ] #", "given) is possible. wrtFilter : list of ints, optional If not None, a", "gate-only sequences. This routine fills in `mxToFill`, which must have length equal to", "#First element of cache are given by evalTree's initial single- or zero-operation labels", "self.Np)) derivWrtAnyEvec = scale * _np.transpose(_np.dot(prod, rho)) # may overflow, but OK #", "of the entire operation sequence # with respect to only that gate's parameters", "An initial list of (general) :class:`Circuit` objects is *simplified* into a lists of", "since their required memory is fixed ## (and dominated) by the output array", "\\ else min(comm_blkSize, blkSize) # override with smaller comm_blkSize else: blkSize = None", "[t.final_element_indices(evalTree) for t in subtrees] _mpit.gather_indices(subtreeElementIndices, subTreeOwners, mxToFill, [], 0, comm, gatherMemLimit) if", "% (_nla.norm(prMxToFill[fInds]), _nla.norm(check_vp), _nla.norm(prMxToFill[fInds] - check_vp))) # pragma: no cover if dprMxToFill is", "gate (ordered as numpy.flatten) - M == length of the vectorized model (number", "comm only for speeding up the calcs of the given # wrtSlicesList last_wrtSlice1", "deriv value (see below) dGs1[_np.isnan(dGs1)] = 0 # convert nans to zero, as", "2-tuples, each of which specify a \"block\" of the Hessian to compute. Iterating", "override with smaller comm_blkSize else: blkSize = None # wrtFilter dictates block if", "# FUTURE: we could add logic that accounts for the symmetry of the", "fills in `mxToFill`, which must have length equal to the number of final", "(see below). Returns ------- product : numpy array The product or scaled product", "(number of model parameters) and hessian[i,j,k] holds the derivative of the i-th entry", "1 of mxToFill[felInds], dim=(ks,M) profiler.add_time(\"MPI IPC\", tm) profiler.mem_check(\"bulk_fill_dprobs: post gather blocks\") #collect/gather results", "call to bulk_evaltree. Specifies the *simplified* gate strings to compute the bulk operation", "when set to True, additionally return the derivative of the probability. clipTo :", "_np.clip(p, clipTo[0], clipTo[1]) #Derivs wrt SPAM derivWrtAnyRhovec = scale * _np.dot(E, prod) dpr_drhos", "\"deriv\" def estimate_cache_size(self, nCircuits): \"\"\" Return an estimate of the ideal/desired cache size", ": mpi4py.MPI.Comm, optional When not None, an MPI communicator for distributing the computation", "to keep all the products within decent bounds #assert( len( (_np.isnan(dGs)).nonzero()[0] ) ==", "an entire tree of gate strings. Similar to `bulk_fill_probs(...)`, but fills a 2D", "results in a zero dimension else: obj_wrtFilter = None relevant_gpindices = obj.gpindices return", "== wrtSlice2) else \\ self._compute_dproduct_cache(evalSubTree, prodCache, scaleCache, mySubComm, wrtSlice2) dGs1 = evalSubTree.final_view(dProdCache1, axis=0)", "== wrtSlice2): dProdCache2 = dProdCache1; dGs2 = dGs1 else: dProdCache2 = self._compute_dproduct_cache( evalTree,", "a M x M x G x G numpy array, where: - M", "means compute all requested rows or columns at once. The minimum of wrtBlockSize", "a 2-tuple: (hessian_col, d12_col), where d12_col is a column of the matrix d12", "* scaleVals # shape == (len(circuit_list),) ; may overflow but OK def _dprobs_from_rhoE(self,", "subtrees[iSubTree] felInds = evalSubTree.final_element_indices(evalTree) #Free memory from previous subtree iteration before computing caches", "the Hessian to compute. Iterating over the output of this function iterates over", "# ( unvec( G(L+1) ... G(M-1) tensor (G(M+1) ... GN)^T vec( dG(M)/dkl )", "the j-th model parameter. * if flat == True, an array of shape", "then sub-trees (if available and necessary) if comm.Get_size() > nDerivCols1 * nDerivCols2: #If", "derivatives of the probability w.r.t. each model parameter (M is the length of", "result quantities for given arguments \"\"\" tm = _time.time() old_err = _np.seterr(over='ignore') rho,", "M == the number of model params or wrtFilter1 or 2, respectively -", "needed. N = len(revOpLabelList) for m, opLabel1 in enumerate(revOpLabelList): inds1 = gpindices1[opLabel1] nDerivCols1", "Eraw = spamTuple E = _np.conjugate(_np.transpose(Eraw)) return rho, E def _rhoEs_from_spamTuples(self, rholabel, elabels):", "# like length>1 lists do... ugh. relevant_gpindices = slice(0, 0) # slice that", "to only those two gates' parameters and fill # add the result to", "keep track of exponent if H.max() < PSMALL and H.min() > -PSMALL: nG", "num_deriv_cols), 'd') _fas(flattened_dprod, [None, gpindices], gate.deriv_wrt_params(op_wrtFilter)) # (dim**2, nParams[opLabel]) if _slct.length(gpindices) > 0:", "a tree of product derivatives in a linear cache space. Will use derivative", "2nd derivatives in a linear cache space. Will use derivative rows and columns", "iLeft) = evalTree[i] L, R = prodCache[iLeft], prodCache[iRight] dL, dR = dProdCache[iLeft], dProdCache[iRight]", "[ (G1 ... G(L-1)) tensor (G(L+1) ... GN)^T vec( dG(L)/dij ) ] #", "w/ col_i = A[col0] * B[0,1] ) = B^T tensor A * vec(", "# = [ sum_{L s.t. G(L) == oplabel} [ (G1 ... G(L-1)) tensor", "# values = object-local param indices relevant_gpindices = [] # indices into original", "[self.hpr(spamTuple, circuit, False, False, clipTo) for circuit in circuit_list], axis=0) if _nla.norm(hprMxToFill[fInds][0] -", "return ret, dpr, p else: return ret, dpr else: if returnPr: return ret,", "False)[0] for circuit in circuit_list]) if _nla.norm(prMxToFill[fInds] - check_vp) > 1e-6: _warnings.warn(\"norm(vp-check_vp) =", "# Cannot specify both wrtFilter and wrtBlockSize wrtSlice = _slct.list_to_slice(wrtFilter) else: wrtSlice =", "scaleVals[gInds], wrtSlice2), add=sumInto) _fas(mxToFill, [fInds, pslc1, pslc2], self._hprobs_from_rhoE( spamTuple, rho, E, Gs[gInds], dGs1[gInds],", "K is the length of spam_label_rows, - S is the number of operation", "flattened gate (ordering as numpy.flatten) - M == length of the vectorized model", "ints, optional If not None, a list of integers specifying which model parameters", "for lOp in circuit: G = _np.dot(self.sos.get_operation(lOp).todense(), G) # LEXICOGRAPHICAL VS MATRIX ORDER", "numpy does all the major allocation/deallocation). #if comm is None or comm.Get_rank() ==", "L < M} # noqa # + sum{M==L} [ G1 ... G(M-1) d2G(M)/(dkl*dij)", "dot(Gs, rho)), axis=(0,2) ) * scaleVals return _np.squeeze(_np.dot(E, _np.dot(Gs, rho)), axis=(0, 2)) *", "= self.sos.get_prep(rholabel).todense()[:, None] E = _np.conjugate(_np.transpose(self.sos.get_effect(elabel).todense() [:, None])) # convention: E has shape", "class MatrixForwardSimulator(ForwardSimulator): \"\"\" Encapsulates a calculation tool used by model objects to perform", "iLeft <=> iRight from evalTree because # (iRight,iLeft,iFinal) = tup implies circuit[i] =", "axis=(3,)) * scaleVals[:, None, None] # overflow OK devec = EVec.deriv_wrt_params(E_wrtFilter2) _fas(d2pr_dEs1, [None,", "may overflow or get nans (invalid), but ok dGs = _np.swapaxes(_np.swapaxes(dGs, 0, 3)", "block if blkSize is None: #Fill derivative cache info tm = _time.time() dProdCache", "multiplicative scaling needed for the hessians, derivatives, and/or products for the i-th operation", "dimension else: obj_wrtFilter = None relevant_gpindices = obj.gpindices return obj_wrtFilter, relevant_gpindices #Vectorizing Identities.", "for single- or zero-operation sequences are zero. hProdCache[i] = _np.zeros(hessn_shape) else: hoperation =", "below) hGs[_np.isnan(hGs)] = 0 _np.seterr(**old_err) if flat: # cols = deriv cols, rows", "product of gates, starting with G0 # nG = norm(G); G /= nG;", "elif len(relevant_gpindices) == 0: #Don't return a length-0 list, as this doesn't index", "original list of `Circuits` was simplified. Parameters ---------- mxToFill : numpy ndarray an", "None: ret = _np.clip(ps, clipTo[0], clipTo[1]) else: ret = ps #DEBUG CHECK #check_ps", "mem += cache_size * dim * dim # product cache mem += cache_size", "hessian once). But since we're # assuming that the gates are at most", "circuit in circuit_list], axis=0) if _nla.norm(dprMxToFill[fInds] - check_vdp) > 1e-6: _warnings.warn(\"norm(vdp-check_vdp) = %g", "we needed to perform a hessian calculation (i.e. for l==m) then # it", "%s\" % # (comm.Get_rank(),\",\".join([str(len(subtrees[i])) # for i in mySubTreeIndices]))) #eval on each local", "wrtFilter : list of ints, optional If not None, a list of integers", "directory. #*************************************************************************************************** import warnings as _warnings import numpy as _np import numpy.linalg as", "dproduct(self, circuit, flat=False, wrtFilter=None): \"\"\" Compute the derivative of a specified sequence of", "self._probs_from_rhoE( rho, E, Gs[gInds], scaleVals[gInds]), add=sumInto) _fas(mxToFill, [fInds, pslc1], self._dprobs_from_rhoE( spamTuple, rho, E,", "`bReturnDProbs12 == True`). `rowSlice` and `colSlice` are slices directly from `wrtSlicesList`. `hprobs` and", "myHessianSlice1 = myDeriv1ColSlice #print(\"MPI: _compute_hproduct_cache over %d cols (rank %d computing %s)\" \\", "scaleVals = self._scaleExp(evalSubTree.final_view(scaleCache)) Gs = evalSubTree.final_view(prodCache, axis=0) #( nCircuits, dim, dim ) profiler.mem_check(\"bulk_fill_dprobs:", "params (see above) if wrtSlice2 is not None and wrtSlice2.start is not None:", "use of in \" \" _compute_hproduct_cache.\") #TODO: remove: not needed now that we", "a split evalTree (if given) is possible. wrtFilter1, wrtFilter2 : list of ints,", "E, Gs, scaleVals): if self.evotype == \"statevec\": raise NotImplementedError(\"Unitary evolution not fully supported", "is not None: _warnings.warn(\"Note: more CPUs(%d)\" % mySubComm.Get_size() + \" than hessian elements(%d)!\"", "(still relatively little mem required) dop_dopLabel1 = { opLabel: gate.deriv_wrt_params(gate_wrtFilters1[opLabel]) for opLabel, gate", "/ _np.exp(scaleCache[i]) #evaluate operation sequences using tree (skip over the zero and single-gate-strings)", "Computes a tree of products in a linear cache space. Will *not* parallelize", "computed properly if wrtSlice1 is not None and wrtSlice1.start is not None: myHessianSlice1", "... G(L-1)) tensor (G(L+1) ... GN)^T ]] # noqa # # So for", "= A[col0] * B[0,1] ) = B^T tensor A * vec( E(0,1) )", "# 'PrepEffectFilter', 'rho_local_slices rho_global_slices ' + # 'e_local_slices e_global_slices num_rho_params num_e_params') # #", "in subtrees] _mpit.gather_indices(subtreeElementIndices, subTreeOwners, mxToFill, [], 0, comm, gatherMemLimit) if deriv1MxToFill is not", "dp_dEs[i,J0+J] = dot(squeeze(dot(Gs, rho),2), dEP)[i,J] # dp_dEs[:,J0+J] = dot(squeeze(dot(Gs, rho),axis=(2,)), dEP)[:,J] dp_dEs =", "B^T ) # and using numpy's reshape dim = self.dim uniqueOpLabels = sorted(list(set(revOpLabelList)))", "products should all have norm <= 1 assert(len(nanOrInfCacheIndices) == 0) return prodCache, scaleCache", "bulk_evaltree. Specifies the *simplified* gate strings to compute the bulk operation on. prMxToFill", "vectorized model - G == the linear dimension of a operation matrix (G", "and wrtFilter2). evalTree : EvalTree given by a prior call to bulk_evaltree. Specifies", "= None # wrtFilter1 & wrtFilter2 dictates block if blkSize1 is None and", "and hessian[i,j,k,l] holds the derivative of the (k,l)-th entry of the product with", "np2 = num_param1_groups, num_param2_groups FLOATSIZE = 8 # in bytes: TODO: a better", "integers specifying which gate parameters to include in the derivative. Each element is", "circuit, False, clipTo) for circuit in circuit_list], axis=0) if _nla.norm(dprMxToFill[fInds] - check_vdp) >", "dot(E, dGs, drhoP)[0,i,j,J] # d2pr_drhos[:,:,J0+J] = squeeze(dot(E, dGs, drhoP),axis=(0,))[:,:,J] drho = rhoVec.deriv_wrt_params(rho_wrtFilter2) d2pr_drhos1", "is the same as that used by numpy.flatten), - S,M == as above,", "dG(M)/dkl G(M+1) ... G(L-1) tensor (G(L+1) ... GN)^T vec( dG(L)/dij ) ] #", "groups to divide the second-derivative parameters into. Computation will be automatically parallelized over", "`mxToFill` with the probabilities corresponding to the *simplified* operation sequences found in an", "# cols = deriv cols, rows = flattened everything else return (dGs, scaleVals)", "M x G x G, where - S == len(circuit_list) - M ==", "deriv cols, then sub-trees (if available and necessary) if comm.Get_size() > nDerivCols1 *", "shape of the returned derivative array (see below). bReturnDProdsAndProds : bool, optional when", "hProdCache[:,myDeriv1ColSlice], # dim=(cacheSize,nDerivCols1,nDerivCols2,dim,dim) else: #compute \"Deriv1\" row-derivatives distribution only; don't use column distribution", "rho), axis=(2,)) * scaleVals[:, None] _fas(dp_dEs, [None, E_gpindices], _np.dot(dp_dAnyE, EVec.deriv_wrt_params(E_wrtFilter))) sub_vdp = dp_drhos", "flattened_dprod = _np.zeros((dim**2, num_deriv_cols), 'd') _fas(flattened_dprod, [None, gpindices], gate.deriv_wrt_params(op_wrtFilter)) # (dim**2, nParams[opLabel]) if", "to specify a well-defined column ordering when taking derivatives. paramvec : ndarray The", "vec( dG(L)/dij ) ] # noqa # = [ sum_{L s.t. G(L) ==", "# free mem dProdCache1 = dGs1 = None # free mem #gather column", "None means compute all requested rows or columns at once. The minimum of", "* if flat == False, two arrays of shape S x M x", "across multiple processors. Distribution is first done over the set of parameters being", "evalSubTree.final_view(hProdCache, axis=0) #Set filtering for calc_and_fill wrtSlice1 = blocks1[iBlk1] wrtSlice2 = blocks2[iBlk2] self._fill_result_tuple((prMxToFill,", "is not None) and (mySubComm.Get_size() > 1): comm_blkSize = self.Np / mySubComm.Get_size() blkSize1", "mem += cache_size # scale cache mem += cache_size # scale vals ##", "if self.evotype == \"statevec\": raise NotImplementedError(\"Unitary evolution not fully supported yet!\") # pr", "pre-filtered!\" #Compute d2(probability)/dGates2 and save in return list # d2pr_dOps2[i,j,k] = sum_l,m E[0,l]", "License, Version 2.0 (the \"License\"); you may not use this file except #", "mySubSubComm = \\ _mpit.distribute_slice(allDeriv2ColSlice, mySubComm) # Get slice into entire range of model", "if bUseScaling: old_err = _np.seterr(over='ignore') G, scale = self.product(circuit, True) if self.evotype ==", "think about) revOpLabelList = tuple(reversed(tuple(circuit))) # prod = G1 * G2 * ....", "uniqueOpLabels: used_operations[l] = self.sos.get_operation(l) gate_wrtFilters1[l], gpindices1[l] = self._process_wrtFilter(wrtFilter1, used_operations[l]) gate_wrtFilters2[l], gpindices2[l] = self._process_wrtFilter(wrtFilter2,", "Cannot specify both wrtFilter and wrtBlockSize wrtSlice2 = _slct.list_to_slice(wrtFilter2) else: wrtSlice2 = None", "number of processor groups used to (in parallel) iterate through the subtrees. It", "G, scale else: G = _np.identity(self.dim) for lOp in circuit: G = _np.dot(self.sos.get_operation(lOp).todense(),", "# In general: vec( A * X * B ) = B^T tensor", "multiple processors. Distribution is performed over subtrees of evalTree (if it is split).", "* dim # dproduct cache mem += cache_size * dim * dim #", "isinstance(wrtFilter, slice): wrtFilter = _slct.indices(wrtFilter) if wrtFilter is not None: obj_wrtFilter = []", "clipTo): \"\"\" Compute the derivative of a probability generated by a operation sequence", "be used for product computation\") pass # this is a fairly common occurrence,", "elabel = spamTuple # can't deal w/\"custom\" spam label... rho, E = self._rhoE_from_spamTuple(spamTuple)", "= evalTree.final_view(hProdCache, axis=0) #shape == ( len(circuit_list), nDerivCols, nDerivCols, dim, dim ) if", "= dot( E, dot(Gs, rho))[0,i,0] * scaleVals[i] # vp = squeeze( dot( E,", "None: #Fill hessian cache info dProdCache1 = self._compute_dproduct_cache( evalSubTree, prodCache, scaleCache, mySubComm, wrtSlice1)", "return \"deriv\" def estimate_cache_size(self, nCircuits): \"\"\" Return an estimate of the ideal/desired cache", "0))) # _np.einsum('ij,jkl->ikl', dp_dAnyRho, self.sos.get_prep(rholabel).hessian_wrt_params( # rho_wrtFilter1, rho_wrtFilter2)) else: d2pr_d2rhos = 0 if", "OK if infs occur here _np.seterr(**old_err) if bReturnDProdsAndProds: Gs = evalTree.final_view(prodCache, axis=0) #shape", "if bReturnDProdsAndProds == True. * if flat == False, two arrays of shape", "for circuit in circuit_list]) if _nla.norm(prMxToFill[fInds] - check_vp) > 1e-6: _warnings.warn(\"norm(vp-check_vp) = %g", "slice(None), calc_and_fill_p) profiler.mem_check(\"bulk_fill_dprobs: post fill probs\") #distribute derivative computation across blocks myBlkIndices, blkOwners,", "= %.1f, nBlks=%d]\" % (blkSize, nBlks)) # pragma: no cover def calc_and_fill_blk(spamTuple, fInds,", "dominated) by the output array size. Could throw more informative error? #elif fnName", "elif fnName == \"bulk_hprobs_by_block\": #Note: includes \"results\" memory since this is allocated within", "calc_and_fill) hProdCache = hGs = dProdCache2 = dGs2 = None # free mem", "gatherMemLimit=None): \"\"\" Compute the outcome probability-derivatives for an entire tree of gate strings.", "to. If there are more processors than model parameters, distribution over a split", "operation sequence. The spam tuples may only vary in their effect-label (their prep", "= None #Fill cache info prodCache, scaleCache = self._compute_product_cache(evalSubTree, mySubComm) #use cached data", "# + sum{ L < M} [ G1 ... G(L-1) tensor # noqa", "splitting tree beforehand), as there\" \" are more cpus than derivative columns.\") #", "self._compute_product_cache(evalSubTree, mySubComm) scaleVals = self._scaleExp(evalSubTree.final_view(scaleCache)) Gs = evalSubTree.final_view(prodCache, axis=0) #( nCircuits, dim, dim", "dProdCache1 = self._compute_dproduct_cache( evalTree, prodCache, scaleCache, comm, wrtSlice1) dGs1 = evalTree.final_view(dProdCache1, axis=0) last_wrtSlice1", "_slct.length(wrtFilter2) nCircuits = evalTree.num_final_strings() # len(circuit_list) wrtSlice1 = _slct.list_to_slice(wrtFilter1) if (wrtFilter1 is not", "fnName) return mem * FLOATSIZE def bulk_product(self, evalTree, bScale=False, comm=None): \"\"\" Compute the", "not None: _fas(deriv1MxToFill, [fInds, pslc1], self._dprobs_from_rhoE( spamTuple, rho, E, Gs[gInds], dGs1[gInds], scaleVals[gInds], wrtSlice1),", "range(len(self.preps))] # tmp_num_params = [_slct.length(s) for s in loc_rho_slices] # tmp_offsets = [", "at once. Parameters ---------- evalTree : EvalTree given by a prior call to", "_np.squeeze(_np.dot(dGs1, rho), axis=(3,)) * scaleVals[:, None, None] # overflow OK devec = EVec.deriv_wrt_params(E_wrtFilter2)", "dEPT[J,j] dot(prod,drhoP)[i,j,K] # d2pr_dErhos[i,J0+J,K0+K] = dot(dEPT,prod,drhoP)[J,i,K] # d2pr_dErhos[i,J0+J,K0+K] = swapaxes(dot(dEPT,prod,drhoP),0,1)[i,J,K] # d2pr_dErhos[:,J0+J,K0+K] =", "_np.zeros((nCircuits, nDerivCols1, nDerivCols2)) _fas(d2pr_d2rhos, [None, rho_gpindices1, rho_gpindices2], _np.tensordot(dp_dAnyRho, self.sos.get_prep(rholabel).hessian_wrt_params( rho_wrtFilter1, rho_wrtFilter2), (1, 0)))", "be done prior to the scaling. \"\"\" if bScale: scaledGatesAndExps = {} scale_exp", "X * B ) = B^T tensor A * vec( X ) def", "of `elabels`. \"\"\" assert(time is None), \"MatrixForwardSimulator cannot be used to simulate time-dependent", "contains the multiplicative scaling needed for the derivatives and/or products for the i-th", "for opLabel, gate in used_operations.items(): if gate.has_nonzero_hessian(): hop_dopLabels[opLabel] = gate.hessian_wrt_params( gate_wrtFilters1[opLabel], gate_wrtFilters2[opLabel]) #", "for i in evalTree.get_evaluation_order(): # combine iLeft + iRight => i # LEXICOGRAPHICAL", "axis 2 of hProdCache[:,myDeriv1ColSlice], # dim=(cacheSize,nDerivCols1,nDerivCols2,dim,dim) else: #compute \"Deriv1\" row-derivatives distribution only; don't", "== ( len(circuit_list), nDerivCols, nDerivCols, dim, dim ) if not bScale: old_err =", "None: _warnings.warn(\"Note: more CPUs(%d)\" % mySubComm.Get_size() + \" than derivative columns(%d)!\" % self.Np", "#DEBUG CHECK #check_ps = _np.array( [ self.pr( (rholabel,elabel), circuit, clipTo, bScale) for elabel", "mult by a zero deriv value (see below) dGs[_np.isnan(dGs)] = 0 _np.seterr(**old_err) if", "MatrixEvalTree as _MatrixEvalTree from .forwardsim import ForwardSimulator _dummy_profiler = _DummyProfiler() # Smallness tolerances,", "prMxToFill is not None: # _fas(prMxToFill, [fInds], # self._probs_from_rhoE(rho, E, Gs[gInds], scaleVals[gInds]), add=sumInto)", "VS MATRIX ORDER return G def _process_wrtFilter(self, wrtFilter, obj): \"\"\" Helper function for", "deriv[i,j] holds the derivative of the (i % G^2)-th entry of the (i", "... G(L-1) tensor (G(L+1) ... GN)^T vec( dG(L)/dij ) ] # noqa #", "calc_and_fill_p\", tm) # Compute all probabilities all at once so they're not repeatedly", "mem += cache_size * wrtLen1 * wrtLen2 * dim * dim # hproduct", "+= cache_size * num_params**2 * dim * dim # hproduct cache # mem", "0, 1)) # get d2pr_dEs where E derivatives are wrt the 2nd set", "\"\"\" Compute and fill result quantities for given arguments \"\"\" tm = _time.time()", "not None: p = _np.clip(p, clipTo[0], clipTo[1]) dprod_dOps = self.dproduct(circuit) assert(dprod_dOps.shape[0] == self.Np)", "hessians for single- or zero-operation sequences are zero. hProdCache[i] = _np.zeros(hessn_shape) else: hoperation", "as _itertools import collections as _collections from ..tools import mpitools as _mpit from", "but OK ; shape == (len(circuit_list), nDerivCols) # may also give invalid value", "d2pr_dEs1 + d2pr_dOps2 # wrt gates return ret def _check(self, evalTree, prMxToFill=None, dprMxToFill=None,", "wrtSlice1 is not None and wrtSlice1.start is not None: myHessianSlice1 = _slct.shift(myDeriv1ColSlice, wrtSlice1.start)", "decent # bounds #assert( len( (_np.isnan(hGs)).nonzero()[0] ) == 0 ) #assert( len( (_np.isinf(hGs)).nonzero()[0]", "2) # may overflow, but ok # may overflow or get nans (invalid),", "depend on eIndex **) -- TODO: should also conjugate() here if complex? _fas(dpr_dEs,", "maximal use of available processors is used as the final block size. These", "on \"extra\", i.e. rank != 0, cpus my_results = self._compute_dproduct_cache( evalTree, prodCache, scaleCache,", "self._process_wrtFilter(wrtFilter, gate) dop_dopLabel = gate.deriv_wrt_params(op_wrtFilter) for (i, gl) in enumerate(revOpLabelList): if gl !=", "[0, EVec.gpindices], _np.dot(derivWrtAnyEvec, EVec.deriv_wrt_params())) dpr = dpr_drhos + dpr_dEs + dpr_dOps d2pr_drhos =", ") = A tensor B^T * vec( E(0,1) ) # In general: vec(", "_np.seterr(over='ignore', invalid='ignore') # may overflow or get nans (invalid), but ok dGs =", "G1 ... G(M-1) tensor (G(M+1) ... G(L-1))^T vec( dG(M)/dkl ) ) # noqa", "a zero deriv value, and we dGs[_np.isnan(dGs)] = 0 # assume the zero", "dProdCache2 = dGs2 = None # free mem if bReturnDProbs12: dprobs12 = dprobs1[:,", "gpindices2 = {}; gate_wrtFilters2 = {} for l in uniqueOpLabels: used_operations[l] = self.sos.get_operation(l)", "uses the convention that rho has shape (N,1) rho = self.sos.get_prep(rholabel).todense()[:, None] Es", "A * X * B ) = A tensor B^T * vec( X", "# Cannot specify both wrtFilter and wrtBlockSize wrtSlice2 = _slct.list_to_slice(wrtFilter2) else: wrtSlice2 =", "/ mySubComm.Get_size() blkSize1 = comm_blkSize if (blkSize1 is None) \\ else min(comm_blkSize, blkSize1)", "zero and single-gate-strings) for i in evalTree.get_evaluation_order(): tm = _time.time() # combine iLeft", "= _np.zeros((cacheSize,) + deriv_shape) # This iteration **must** match that in bulk_evaltree #", "vp = squeeze( dot( E, dot(Gs, rho)), axis=(0,2) ) * scaleVals return _np.squeeze(_np.dot(E,", "has the SAME length as fInds). calc_and_fill_fn(spamTuple, fInds, gInds, pslc1, pslc2, False) #", "(0, 2, 1)) + \\ d2pr_drhos + _np.transpose(d2pr_drhos, (0, 2, 1)) + \\", "for distributing derivative calculations across multiple processors. Returns ------- hessians : numpy array", "processors is used as the final block size. This argument must be None", "then dG(L)/dij = E(i,j), an elementary matrix dim = self.dim #Cache partial products", "may only vary in their effect-label (their prep labels must be the same)", "NotImplementedError(\"Unitary evolution not fully supported yet!\") # pr = Tr( |rho><E| * prod", "if _nla.norm(dprMxToFill[fInds] - check_vdp) > 1e-6: _warnings.warn(\"norm(vdp-check_vdp) = %g - %g = %g\"", "the final result num_deriv_cols1 = self.Np if (wrtFilter1 is None) else len(wrtFilter1) num_deriv_cols2", "return _np.swapaxes(flattened_dprod, 0, 1).reshape((num_deriv_cols, dim, dim)) def hproduct(self, circuit, flat=False, wrtFilter1=None, wrtFilter2=None): \"\"\"", "match that in bulk_evaltree # in order to associate the right single-gate-strings w/indices", "+ \" [blkSize = %.1f, nBlks=%d]\" % (blkSize, nBlks)) # pragma: no cover", "model (number of model parameters) - G == the linear dimension of a", "M1 & M2 are the number of selected gate-set parameters (by wrtFilter1 and", "L, R = prodCache[iLeft], prodCache[iRight] dL1, dR1 = dProdCache1[iLeft], dProdCache1[iRight] dL2, dR2 =", "special case of empty label == no gate dProdCache[i] = _np.zeros(deriv_shape) else: #doperation", "should only contain \"deterministic\" elements (no POVM or Instrument labels). numSubtreeComms : int", "the (k,l)-th entry of the i-th operation sequence product with respect to the", "# wrtFilter1 & wrtFilter2 dictates block if blkSize1 is None and blkSize2 is", "+ \" [blkSize = {%.1f,%.1f}, nBlks={%d,%d}]\" % (blkSize1, blkSize2, nBlks1, nBlks2)) # pragma:", ")^T vec( dG(L)/dij ) ] # noqa # + sum{ L == M}", "len(circuit_list) - M == the number of model params or wrtFilter1 or 2,", "# pragma: no cover if dprMxToFill is not None: check_vdp = _np.concatenate( [self.dpr(spamTuple,", "Similar to `bulk_fill_probs(...)`, but fills a 3D array with probability-Hessians for each \"final", "info (not requiring row or column distribution) prodCache, scaleCache = self._compute_product_cache(evalSubTree, mySubComm) scaleVals", "rho_gpindices1], _np.squeeze(_np.dot(_np.dot(E, dGs2), drho), axis=(0,)) * scaleVals[:, None, None]) # overflow OK d2pr_drhos2", "EVec.deriv_wrt_params(E_wrtFilter1) _fas(d2pr_dEs2, [None, None, E_gpindices1], _np.dot(dp_dAnyE, devec)) d2pr_dEs2 = _np.transpose(d2pr_dEs2, (0, 2, 1))", "+= cache_size # scale vals elif fnName == \"bulk_fill_dprobs\": mem += cache_size *", "if self.evotype not in (\"statevec\", \"densitymx\"): raise ValueError((\"Evolution type %s is incompatbile with", "partial products (relatively little mem required) leftProds = [] G = _np.identity(dim); leftProds.append(G)", "mxToFill[felslc] (axis=0) if clipTo is not None: _np.clip(mxToFill, clipTo[0], clipTo[1], out=mxToFill) # in-place", "for opLabel, gate in used_operations.items()} if wrtFilter1 == wrtFilter2: dop_dopLabel2 = dop_dopLabel1 else:", "overflow OK devec = EVec.deriv_wrt_params(E_wrtFilter2) _fas(d2pr_dErhos2, [None, E_gpindices2, rho_gpindices1], _np.swapaxes(_np.dot(_np.transpose(devec), dp_dAnyE), 0, 1))", "== 1 # if vec(.) concatenates rows (which numpy.flatten does) # vec( A", "is used internally for distributing derivative calculations across multiple processors. Returns ------- hessian", "with L < M} # noqa # + sum{M==L} [ G1 ... G(M-1)", "nCircuits * dim**2)), 0, 1) hGs = _np.rollaxis(_np.rollaxis(hGs, 0, 3).reshape( (nDerivCols1, nDerivCols2, nCircuits", "from initialization else: gate = self.sos.get_operation(opLabel).todense() nG = max(_nla.norm(gate), 1.0) prodCache[i] = gate", "don't distribute wrtSlicesList across comm procs, # as we assume the user has", "- check_vhp))) # pragma: no cover def bulk_fill_probs(self, mxToFill, evalTree, clipTo=None, check=False, comm=None):", "{} scale_exp = 0 G = _np.identity(self.dim) for lOp in circuit: if lOp", "which is true IF each operation matrix element # is at most *linear*", "for opLabel, gate in used_operations.items()} #Finally, cache any nonzero gate hessians (memory?) hop_dopLabels", "anyway... dp_dOps[_np.isnan(dp_dOps)] = 0 #SPAM ------------- # Get: dp_drhos[i, rho_gpindices] = dot(E,Gs[i],drho/drhoP) #", "tuple. That is, the first element of circuit can be thought of as", "compare with older slower version that should do the same thing (for debugging)", "for the 1st and 2nd differentiation, respectively (i.e. by wrtFilter1 and wrtFilter2). clipTo", "boolean, optional If true, the generator computes a 2-tuple: (hessian_col, d12_col), where d12_col", "the gate's parameters if isinstance(wrtFilter, slice): wrtFilter = _slct.indices(wrtFilter) if wrtFilter is not", "quantities for given arguments \"\"\" old_err = _np.seterr(over='ignore') rho, E = self._rhoE_from_spamTuple(spamTuple) #if", "DSMALL and dProdCache[i].min() > -DSMALL: _warnings.warn(\"Would have scaled dProd but now will not", "1)) # Get: d2pr_dErhos[i, e_offset[eIndex]:e_offset[eIndex+1], e_offset[rhoIndex]:e_offset[rhoIndex+1]] = # dEP^T * prod[i,:,:] * drhoP", "-PSMALL: nG = max(_nla.norm(G), _np.exp(-scale_exp)) G = _np.dot(gate, G / nG); scale_exp +=", "#Cache partial products (relatively little mem required) prods = {} ident = _np.identity(dim)", "and using numpy's reshape dim = self.dim uniqueOpLabels = sorted(list(set(revOpLabelList))) used_operations = _collections.OrderedDict()", "# rho_global_slices=global_rho_slices, # e_local_slices=loc_e_slices, # e_global_slices=global_e_slices, # num_rho_params=_slct.length(wrtSlices['preps']), # num_e_params=_slct.length(wrtSlices['effects'])) # else: #", "prods[(m + 1, N - 1)]) # (dim**2, dim**2) x = _np.dot(_np.transpose(dop_dopLabel1[opLabel1]), x0);", "hProdCache[i] = _np.dot(hL, R) + dLdR_sym + _np.transpose(_np.dot(L, hR), (1, 2, 0, 3))", "OK if clipTo is not None: p = _np.clip(p, clipTo[0], clipTo[1]) dprod_dOps =", "will yield nan as the returned probability. time : float, optional The *start*", "None: _mpit.gather_indices(subtreeElementIndices, subTreeOwners, deriv2MxToFill, [], 0, comm, gatherMemLimit) if prMxToFill is not None:", "int(round(_np.sqrt(self.dim))) # an estimate - could compute? wrtLen1 = (self.Np + np1 -", "small in order to keep prod managable.\") elif _np.count_nonzero(hProdCache[i]) and hProdCache[i].max() < HSMALL", "= [] # values = object-local param indices relevant_gpindices = [] # indices", "nDerivCols2, nCircuits * dim**2)), 2) # as above return (hGs, scaleVals) if bScale", "_np.dot(derivWrtAnyEvec, EVec.deriv_wrt_params())) _np.seterr(**old_err) if returnPr: return dpr_drhos + dpr_dEs + dpr_dOps, p else:", "\" than hessian elements(%d)!\" % (self.Np**2) + \" [blkSize = {%.1f,%.1f}, nBlks={%d,%d}]\" %", "the *simplified* effect labels. circuit : Circuit or tuple A tuple-like object of", "must be pre-filtered!\" assert(dGs2.shape[1] == nDerivCols2), \"dGs1 must be pre-filtered!\" # Get: d2pr_drhos[i,", "is None) # Cannot specify both wrtFilter and wrtBlockSize wrtSlice2 = _slct.list_to_slice(wrtFilter2) else:", ": EvalTree given by a prior call to bulk_evaltree. Specifies the *simplified* gate", "where: - S == len(circuit_list) - M == the length of the vectorized", "slice into entire range of model params so that # per-gate hessians can", "wrtSlices): # \"\"\" # Returns a \"filter\" object containing info about the mapping", "_np.seterr(over='ignore') rho, E = self._rhoE_from_spamTuple(spamTuple) block_wrtSlice = pslc1 _fas(mxToFill, [fInds, pslc1], self._dprobs_from_rhoE( spamTuple,", "list appropriate for it. # Use comm only for speeding up the calcs", "also that there would be no memory savings from using a split tree.", "sum_{L s.t. GL == gatelabel2, M < L} # noqa # [ G1", "None, an already-allocated ExM numpy array that is filled with probability derivatives, similar", "for i in range(self.Np): for j in range(self.Np): d2pr_dOps2[0, i, j] = float(_np.dot(E,", "if prMxToFill is not None: _mpit.gather_indices(subtreeElementIndices, subTreeOwners, prMxToFill, [], 0, comm) #note: pass", "combine iLeft + iRight => i # LEXICOGRAPHICAL VS MATRIX ORDER Note: we", "(see below). comm : mpi4py.MPI.Comm, optional When not None, an MPI communicator for", "loc_rho_slices = [ # _slct.shift(_slct.intersect( # wrtSlices['preps'], # slice(self.rho_offset[i],self.rho_offset[i+1])), # -self.rho_offset[i]) for i", "sub-trees. _warnings.warn(\"Increased speed could be obtained\" \" by giving dproduct cache computation\" \"", "to compute the probability. circuit : Circuit or tuple A tuple-like object of", "1, mySubComm, gatherMemLimit) #note: gathering axis 1 of mxToFill[felInds], dim=(ks,M) profiler.add_time(\"MPI IPC\", tm)", "prod_kl) with # respect to a given gateLabel_ij. This function returns a concatenated", "Divide columns into blocks of at most blkSize assert(wrtFilter1 is None and wrtFilter2", "= squeeze( dot( E, dot( dGs, rho ) ), axis=(0,3)) old_err2 = _np.seterr(invalid='ignore',", "+ _np.transpose(d2pr_dEs, (0, 2, 1)) + \\ d2pr_d2rhos + d2pr_d2Es + d2pr_dOps2 #", "self._scaleExp(evalSubTree.final_view(scaleCache)) Gs = evalSubTree.final_view(prodCache, axis=0) #( nCircuits, dim, dim ) def calc_and_fill(spamTuple, fInds,", "where: - N == the number of entries in a single flattened gate", "function for doperation and hoperation below: pulls out pieces of a wrtFilter argument", "sR = L / nL, R / nR prodCache[i] = _np.dot(sL, sR); scaleCache[i]", "In general: vec( A * X * B ) = B^T tensor A", "# may overflow or get nans (invalid), but ok dGs = _np.swapaxes(_np.swapaxes(dGs, 0,", "arrays of shape K x S x B x B', where: - K", "dp_dAnyE = _np.dot(Gs, rho).squeeze(2) * scaleVals[:, None] # overflow OK d2pr_d2Es = _np.zeros((nCircuits,", "requested columns at once. The minimum of wrtBlockSize and the size that makes", "the number of entries in a single flattened gate (ordering is the same", "dLdR_sym + _np.transpose(_np.dot(L, hR), (1, 2, 0, 3)) scale = scaleCache[i] - (scaleCache[iLeft]", "rho)[i,k,0] * scaleVals[i] # vp[i] = dot( E, dot(Gs, rho))[0,i,0] * scaleVals[i] #", "specify both wrtFilter and wrtBlockSize wrtSlice2 = _slct.list_to_slice(wrtFilter2) else: wrtSlice2 = None #get", "are SPAMVecs #Derivs wrt Gates old_err = _np.seterr(over='ignore') prod, scale = self.product(circuit, True)", "calc_and_fill wrtSlice1 = blocks1[iBlk1] wrtSlice2 = blocks2[iBlk2] self._fill_result_tuple((prMxToFill, deriv1MxToFill, deriv2MxToFill, mxToFill), evalSubTree, blocks1[iBlk1],", "G(L-1) tensor (G(L+1) ... GN)^T vec( dG(L)/dij ) ] # noqa # =", "flattened gate (ordered as numpy.flatten) - M == length of the vectorized model", "filled with probability derivatives, similar to bulk_fill_dprobs(...), but where M is the number", "computing caches scaleVals = Gs = dGs = None prodCache = scaleCache =", "(expect \" \" +%.2fGB, shape=%s)\" % (dProdCache.nbytes / (1024.0**3), str(dProdCache.shape))) dGs = evalSubTree.final_view(dProdCache,", "scaled dProd but now will not alter scaleCache.\") #profiler.print_mem(\"DEBUGMEM: POINT2\"); profiler.comm.barrier() profiler.add_time(\"compute_dproduct_cache: serial\",", "deal w/\"custom\" spam label... rho, E = self._rhoE_from_spamTuple(spamTuple) rhoVec = self.sos.get_prep(rholabel) # distinct", "space. Will *not* parallelize computation, even if given a split tree (since there's", "not None: _warnings.warn(\"Note: more CPUs(%d)\" % mySubComm.Get_size() + \" than derivative columns(%d)!\" %", "= deriv cols, rows = all else return (hGs, dGs1, dGs2, Gs, scaleVals)", "on. prMxToFill : numpy array, optional when not None, an already-allocated length-E numpy", ": int The number of subtrees to split the full evaluation tree into.", "X ) def doperation(self, opLabel, flat=False, wrtFilter=None): \"\"\" Return the derivative of a", "== wrtFilter2: dop_dopLabel2 = dop_dopLabel1 else: dop_dopLabel2 = { opLabel: gate.deriv_wrt_params(gate_wrtFilters2[opLabel]) for opLabel,", "{} for l in uniqueOpLabels: used_operations[l] = self.sos.get_operation(l) gate_wrtFilters1[l], gpindices1[l] = self._process_wrtFilter(wrtFilter1, used_operations[l])", "the derivative of the (k,l)-th entry of the i-th operation sequence product with", "revOpLabelList = tuple(reversed(tuple(circuit))) N = len(revOpLabelList) # length of operation sequence # prod", "derivative computation across blocks myBlkIndices, blkOwners, blkComm = \\ _mpit.distribute_indices(list(range(nBlks)), mySubComm) if blkComm", "and the size that makes maximal use of available processors is used as", "= evalTree.get_sub_trees() mySubTreeIndices, subTreeOwners, mySubComm = evalTree.distribute(comm) #if comm is not None: #", "mem += cache_size # scale vals # #elif fnName == \"bulk_dproduct\": # mem", "blk1Comm = \\ _mpit.distribute_indices(list(range(nBlks1)), mySubComm) myBlk2Indices, blk2Owners, blk2Comm = \\ _mpit.distribute_indices(list(range(nBlks2)), blk1Comm) if", "these occur b/c an inf scaleVal is mult by a zero deriv value,", "* dim**2)), 2) # as above return (hGs, scaleVals) if bScale else hGs", "dot(dGs, rho)[i,j,k,0] # d2pr_dEs[i,j,J0+J] = dot( squeeze(dot(dGs, rho),axis=(3,)), dEP)[i,j,J] # d2pr_dEs[:,:,J0+J] = dot(", "Solutions of Sandia, LLC (NTESS). # Under the terms of Contract DE-NA0003525 with", "arguments \"\"\" old_err = _np.seterr(over='ignore') rho, E = self._rhoE_from_spamTuple(spamTuple) #if prMxToFill is not", "keys == spam labels and values which are integer row indices into mxToFill,", "\"\"\" Return a shallow copy of this MatrixForwardSimulator \"\"\" return MatrixForwardSimulator(self.dim, self.sos, self.paramvec)", "mySubComm = \\ _mpit.distribute_slice(allDeriv1ColSlice, comm) # Get slice into entire range of model", "arrays, these are SPAMVecs #Derivs wrt Gates old_err = _np.seterr(over='ignore') prod, scale =", "is None) \\ else _slct.length(wrtSlice) deriv_shape = (nDerivCols, dim, dim) cacheSize = len(evalTree)", "blkSize is None: #Fill derivative cache info tm = _time.time() dProdCache = self._compute_dproduct_cache(evalSubTree,", "of # _compute_product_cache when the tree was split, but this is was #", "blocks of at most blkSize assert(wrtFilter is None) # cannot specify both wrtFilter", "a zero deriv value (see below) dGs2[_np.isnan(dGs2)] = 0 # convert nans to", "opLabel in reversed(revOpLabelList): G = _np.dot(self.sos.get_operation(opLabel).todense(), G) rightProdsT.append(_np.transpose(G)) # Allocate memory for the", "gate_wrtFilters2[opLabel]) # Allocate memory for the final result num_deriv_cols1 = self.Np if (wrtFilter1", "= dot(dEPT,prod,drhoP)[J,i,K] # d2pr_dErhos[i,J0+J,K0+K] = swapaxes(dot(dEPT,prod,drhoP),0,1)[i,J,K] # d2pr_dErhos[:,J0+J,K0+K] = swapaxes(dot(dEPT,prod,drhoP),0,1)[:,J,K] d2pr_dErhos1 = _np.zeros((nCircuits,", "dot( squeeze(dot(dGs, rho),axis=(3,)), dEP)[i,j,J] # d2pr_dEs[:,:,J0+J] = dot( squeeze(dot(dGs, rho),axis=(3,)), dEP)[:,:,J] d2pr_dEs1 =", "divide the second-derivative parameters into. Computation will be automatically parallelized over these groups.", ": numpy array Array of shape S x G x G, where: -", "(ordering as numpy.flatten), - S,M == as above, and hessians[i,j,k] holds the derivative", "across multiple processors. Returns ------- hessians : numpy array * if flat ==", "None and wrtBlockSize2 is None) # Cannot specify both wrtFilter and wrtBlockSize wrtSlice1", "# cannot specify both wrtFilter and blkSize nBlks1 = int(_np.ceil(self.Np / blkSize1)) nBlks2", "list of integers specifying which parameters to include in the derivative dimension. This", "but OK d2pr_d2rhos = _np.zeros((1, self.Np, self.Np)) _fas(d2pr_d2rhos, [0, self.sos.get_prep(rholabel).gpindices, self.sos.get_prep(rholabel).gpindices], _np.tensordot(derivWrtAnyRhovec, self.sos.get_prep(rholabel).hessian_wrt_params(),", "== len(circuit_list) - M == the length of the vectorized model - G", "float, optional The *start* time at which `circuit` is evaluated. Returns ------- numpy.ndarray", "objgraph.show_growth(limit=50) #get distribution across subtrees (groups if needed) subtrees = evalTree.get_sub_trees() mySubTreeIndices, subTreeOwners,", "# special case of empty label == no gate dProdCache[i] = _np.zeros(deriv_shape) else:", "match the current # gate (so we only need to compute this gate", "0, 2) * scaleVals, 0, 2) # may overflow, but ok # may", "extra checks within code to verify correctness, generating warnings when checks fail. Used", ": list A list of :class:`Label` objects giving the *simplified* effect labels. circuit", "sequence given by evalTree column-by-column. This routine can be useful when memory constraints", "self.Np if wrtSlice2 is None else _slct.length(wrtSlice2) #flt1 = self._get_filter_info(wrtSlices1) #flt2 = self._get_filter_info(wrtSlices2)", "evalTree[i] L, R = prodCache[iLeft], prodCache[iRight] prodCache[i] = _np.dot(L, R) scaleCache[i] = scaleCache[iLeft]", "i-th operation sequence product with respect to the k-th then j-th model parameters.", "are a \"simplified\" circuits in that they should only contain \"deterministic\" elements (no", "e_global_slices=global_e_slices, # num_rho_params=self.tot_rho_params, # num_e_params=self.tot_e_params) def _hprobs_from_rhoE(self, spamTuple, rho, E, Gs, dGs1, dGs2,", "slices as argument: wrtFilter -> wrtSlice? prodCache, scaleCache = self._compute_product_cache(evalTree, comm) dProdCache1 =", ": Circuit or tuple of operation labels The sequence of operation labels. bScale", "prodCache, scaleCache = self._compute_product_cache(evalSubTree, mySubComm) #use cached data to final values scaleVals =", "spamTuple, rho, E, Gs[gInds], dGs[gInds], scaleVals[gInds], wrtSlice), add=sumInto) _np.seterr(**old_err) profiler.add_time(\"bulk_fill_dprobs: calc_and_fill\", tm) #Set", "probabilities, just like in bulk_fill_probs(...). clipTo : 2-tuple, optional (min,max) to clip return", "error? #elif fnName == \"bulk_product\": # mem += cache_size * dim * dim", "i in mySubTreeIndices]))) #eval on each local subtree #my_results = [] for iSubTree", "the operation matrices. scale : float Only returned when bScale == True, in", "estimate_cache_size(self, nCircuits): \"\"\" Return an estimate of the ideal/desired cache size given a", "numpy array only returned if returnDeriv == True. A 1 x M numpy", "in a linear cache space. Will *not* parallelize computation, even if given a", "scaleVals[gInds]), add=sumInto) _fas(mxToFill, [fInds, pslc1], self._dprobs_from_rhoE( spamTuple, rho, E, Gs[gInds], dGs[gInds], scaleVals[gInds], wrtSlice),", "memory for the final result num_deriv_cols = self.Np if (wrtFilter is None) else", "deriv cols, then sub-trees (if available and necessary) if comm.Get_size() > nDerivCols: #If", "# e_local_slices=loc_e_slices, # e_global_slices=global_e_slices, # num_rho_params=self.tot_rho_params, # num_e_params=self.tot_e_params) def _hprobs_from_rhoE(self, spamTuple, rho, E,", "optional If true, the generator computes a 2-tuple: (hessian_col, d12_col), where d12_col is", "then: - `hprobs == mx[:,:,rowSlice,colSlice]` - `dprobs12 == dp1[:,:,rowSlice,None] * dp2[:,:,None,colSlice]` \"\"\" assert(not", "scaleCache, blk2Comm, blk_wrtSlice1, blk_wrtSlice2) hGs = evalSubTree.final_view(hProdCache, axis=0) #Set filtering for calc_and_fill wrtSlice1", "_np.zeros((cacheSize, dim, dim)) scaleCache = _np.zeros(cacheSize, 'd') #First element of cache are given", "in which case the actual product == product * scale. The purpose of", "tree. \"\"\" if profiler is None: profiler = _dummy_profiler dim = self.dim nDerivCols", "may overflow, but OK # (** doesn't depend on eIndex **) -- TODO:", "# TODO: remove this concat w/better gather? # ------------------------------------------------------------------ tSerialStart = _time.time() if", "single flattened gate (ordering as numpy.flatten), - S,M == as above, and hessians[i,j,k]", "requested rows or columns at once. The minimum of wrtBlockSize and the size", "dim=(cacheSize,nDerivCols1,nDerivCols2,dim,dim) else: #compute \"Deriv1\" row-derivatives distribution only; don't use column distribution hProdCache[:, myDeriv1ColSlice]", "== blkSize1 or blkSize2 blocks1 = _mpit.slice_up_range(self.Np, nBlks1) blocks2 = _mpit.slice_up_range(self.Np, nBlks2) #distribute", "= dProdCache1; dGs2 = dGs1 else: dProdCache2 = self._compute_dproduct_cache( evalTree, prodCache, scaleCache, comm,", "is mult by a zero hessian value (see below) hGs[_np.isnan(hGs)] = 0 _np.seterr(**old_err)", "profiler.add_count(\"compute_dproduct_cache: num columns\", nDerivCols) return dProdCache def _compute_hproduct_cache(self, evalTree, prodCache, dProdCache1, dProdCache2, scaleCache,", "# dpr/d(E)_i = sum prod_il rho_l rholabel, elabel = spamTuple # can't deal", "we do matrix multiplication in this order (easier to think about) revOpLabelList =", "None: p = _np.clip(p, clipTo[0], clipTo[1]) dprod_dOps = self.dproduct(circuit) assert(dprod_dOps.shape[0] == self.Np) if", "dProdCache[i].max() < DSMALL and dProdCache[i].min() > -DSMALL: _warnings.warn(\"Would have scaled dProd but now", "to create an evaluation tree out of (most likely because you want to", "keep all the products within decent bounds #assert( len( (_np.isnan(dGs)).nonzero()[0] ) == 0", "use of available processors is used as the final block size. These arguments", "d2pr_dOps2 = _np.squeeze(_np.dot(E, _np.dot(hGs, rho)), axis=(0, 4)) * scaleVals[:, None, None] _np.seterr(**old_err2) #", "= { opLabel: gate.deriv_wrt_params(gate_wrtFilters2[opLabel]) for opLabel, gate in used_operations.items()} #Finally, cache any nonzero", "hGs is already sized/filtered) ------------------- assert(hGs.shape[1] == nDerivCols1), \"hGs must be pre-filtered!\" assert(hGs.shape[2]", "comm is not None: # ignoring comm since can't do anything with it!", "SPAMVec (or array) # objects: (prepVec, effectVec) rho, Eraw = spamTuple E =", "dprod_dOps = G,dG # dp_dOps[i,j] = sum_k,l E[0,k] dGs[i,j,k,l] rho[l,0] # dp_dOps[i,j] =", "arrays too # Compute the derivative of the entire operation sequence with respect", "of the gate parameters. If this is not the case, need LinearOperator objects", "-------- assert(dGs1.shape[1] == nDerivCols1), \"dGs1 must be pre-filtered!\" assert(dGs2.shape[1] == nDerivCols2), \"dGs1 must", "= _np.zeros((1, self.Np, self.Np)) derivWrtAnyEvec = scale * _np.dot(prod, rhoVec.deriv_wrt_params()) # may generate", "with it! #_warnings.warn(\"More processors than can be used for product computation\") pass #", "gpindices1 = self._process_wrtFilter(wrtFilter1, gate) op_wrtFilter2, gpindices2 = self._process_wrtFilter(wrtFilter2, gate) # Allocate memory for", "be less than or greater than `cacheSize`) the tree will hold. Returns -------", "multiplication in this order (easier to think about) revOpLabelList = tuple(reversed(tuple(circuit))) # prod", "w.r.t. each model parameter. probability : float only returned if returnPr == True.", "# G = _np.dot(G,self[lOp]) # product of gates, starting with G0 # nG", "= len(revOpLabelList) for m, opLabel1 in enumerate(revOpLabelList): inds1 = gpindices1[opLabel1] nDerivCols1 = dop_dopLabel1[opLabel1].shape[1]", "those of the sub-trees. _warnings.warn(\"Increased speed could be obtained\" \" by giving dproduct", "enumerate(gateLabelList): # G = _np.dot(G,self[lOp]) # product of gates, starting with G0 #", "if we needed to perform a hessian calculation (i.e. for l==m) then #", "for lOp in circuit: if lOp not in scaledGatesAndExps: opmx = self.sos.get_operation(lOp).todense() ng", "_slct.indices(wrtSlice2) if (wrtSlice2 is not None) else None for i, opLabel in zip(evalTree.get_init_indices(),", "Specifies the *simplified* gate strings to compute the bulk operation on. prMxToFill :", "shape (1,N) else: # a \"custom\" spamLabel consisting of a pair of SPAMVec", "_np.empty((1, self.Np, self.Np)) for i in range(self.Np): for j in range(self.Np): d2pr_dOps2[0, i,", "dim, and all SPAM vectors should be dim x 1. gates, preps, effects", "gate = self.sos.get_operation(opLabel) op_wrtFilter, gpindices = self._process_wrtFilter(wrtFilter, gate) dop_dopLabel = gate.deriv_wrt_params(op_wrtFilter) for (i,", "cacheSize = len(evalTree) prodCache = _np.zeros((cacheSize, dim, dim)) scaleCache = _np.zeros(cacheSize, 'd') #First", "_np.transpose(prods[(l + 1, N - 1)])), dop_dopLabel2[opLabel2]) # above: (nDerivCols1,dim**2,dim**2) * (dim**2,nDerivCols2) =", "E, Gs[gInds], dGs[gInds], scaleVals[gInds], block_wrtSlice), add=sumInto) _np.seterr(**old_err) profiler.add_time(\"bulk_fill_dprobs: calc_and_fill_blk\", tm) for iBlk in", "self.Np)) for i in range(self.Np): dpr_dOps[0, i] = float(_np.dot(E, _np.dot(dprod_dOps[i], rho))) if returnPr:", "no parallelization is performed. Returns ------- prods : numpy array Array of shape", "info about the mapping # of prep and effect parameters onto a final", "nDerivCols1 == 0: continue for l, opLabel2 in enumerate(revOpLabelList): inds2 = gpindices1[opLabel2] #nDerivCols2", "(self.Np + np1 - 1) // np1 # ceiling(num_params / np1) wrtLen2 =", "zero deriv value (see below) dGs2[_np.isnan(dGs2)] = 0 # convert nans to zero,", "None \"\"\" if wrtFilter1 is not None: assert(wrtBlockSize1 is None and wrtBlockSize2 is", "shape of the returned derivative array (see below). wrtFilter : list of ints,", "pragma: no cover if dprMxToFill is not None: check_vdp = _np.concatenate( [self.dpr(spamTuple, circuit,", "_mpit.gather_indices(subtreeElementIndices, subTreeOwners, mxToFill, [], 0, comm, gatherMemLimit) if deriv1MxToFill is not None: _mpit.gather_indices(subtreeElementIndices,", "_np.squeeze(_np.dot(E, _np.dot(Gs, rho)), axis=(0, 2)) * scaleVals # shape == (len(circuit_list),) ; may", "#gather row results; gather axis 1 of mxToFill[felInds], dim=(ks,M,M) _mpit.gather_slices(blocks1, blk1Owners, mxToFill, [felInds],", "string which match the current # gate (so we only need to compute", "like 'Imyinst_0') clipTo : 2-tuple (min,max) to clip returned probability to if not", "dimension of a operation matrix (G x G operation matrices) and derivs[i,j,k,l] holds", "the derivative of the (l,m)-th entry of the i-th operation sequence product with", "False, an array of shape S x M x G x G, where:", "and fill appropriate columns of flattened_dprod. _fas(flattened_hprod, [None, gpindices1, gpindices2], gate.hessian_wrt_params(op_wrtFilter1, op_wrtFilter2)) if", "gather? # ------------------------------------------------------------------ tSerialStart = _time.time() if evalTree.is_split(): _warnings.warn(\"Ignoring tree splitting in dproduct", "dT) profiler.add_time(\"compute_dproduct_cache: dots\", tm) profiler.add_count(\"compute_dproduct_cache: dots\") scale = scaleCache[i] - (scaleCache[iLeft] + scaleCache[iRight])", "to compute the bulk operation on. bScale : bool, optional When True, return", "nDerivCols2, nDerivCols1)) dp_dAnyE = _np.squeeze(_np.dot(dGs2, rho), axis=(3,)) * scaleVals[:, None, None] # overflow", "tensor (G(L+1) ... GN)^T ]] has # columns which correspond to the vectorized", "smaller comm_blkSize else: blkSize1 = blkSize2 = None # wrtFilter1 & wrtFilter2 dictates", "myDeriv2ColSlice], scaleCache, None, myHessianSlice1, myHessianSlice2) # pass None as comm, *not* mySubSubComm, since", "a specified sequence of operation labels. Parameters ---------- circuit : Circuit or tuple", "num_rho_params=_slct.length(wrtSlices['preps']), # num_e_params=_slct.length(wrtSlices['effects'])) # else: # loc_rho_slices = [slice(None,None)]*len(self.preps) # loc_e_slices = [slice(None,None)]*len(self.effects)", "parameters selected for the 1st and 2nd differentiation, respectively (i.e. by wrtFilter1 and", "informative error? #elif fnName == \"bulk_product\": # mem += cache_size * dim *", "pslc2], self._dprobs_from_rhoE( spamTuple, rho, E, Gs[gInds], dGs2[gInds], scaleVals[gInds], wrtSlice2), add=sumInto) _fas(mxToFill, [fInds, pslc1,", "the second-derivative parameters into. Computation will be automatically parallelized over these groups. num_final_strs", "memory required by a given set of subcalls to computation functions. Parameters ----------", "used) - so it's been removed. if comm is not None: # ignoring", "else: #compute \"Deriv1\" row-derivatives distribution only; don't use column distribution hProdCache[:, myDeriv1ColSlice] =", "multiple processors. Distribution is first done over the set of parameters being differentiated", "of at most blkSize assert(wrtFilter1 is None and wrtFilter2 is None) # cannot", "_np.exp(-scale_exp)) G = _np.dot(gate, G / nG); scale_exp += _np.log(nG) # LEXICOGRAPHICAL VS", "A * E(0,1) * B ) = vec( mx w/ row_i = A[i,0]", "== True. A 1 x M numpy array of derivatives of the probability", "diff order) # d2pr/d(E)_i d(E)_j = 0 # d2pr/d(rho)_i d(rho)_j = 0 rholabel,", "profiler=None): \"\"\" Computes a tree of product derivatives in a linear cache space.", "result_tup, evalTree, param_slice1, param_slice2, calc_and_fill_fn): \"\"\" This function takes a \"calc-and-fill\" function, which", "specify both wrtFilter and blkSize nBlks = int(_np.ceil(self.Np / blkSize)) # num blocks", "bReturnDProdsAndProds : bool, optional when set to True, additionally return the probabilities and", "clipTo=None): # compare with older slower version that should do the same thing", "parameters. If this is not the case, need LinearOperator objects to # have", "with smaller comm_blkSize else: blkSize1 = blkSize2 = None # wrtFilter1 & wrtFilter2", "True, in which case the actual product == product * scale. The purpose", "p else: return ret, dpr else: if returnPr: return ret, p else: return", "self.doperation(opLabel, wrtFilter=wrtIndices) dProdCache[i] = doperation / _np.exp(scaleCache[i]) #profiler.print_mem(\"DEBUGMEM: POINT1\"); profiler.comm.barrier() #evaluate operation sequences", "filtering for calc_and_fill wrtSlice1 = blocks1[iBlk1] wrtSlice2 = blocks2[iBlk2] self._fill_result_tuple((prMxToFill, deriv1MxToFill, deriv2MxToFill, mxToFill),", "True, a N x M x M numpy array, where: - N ==", "nR = max(_nla.norm(L), _np.exp(-scaleCache[iLeft]), 1e-300), max(_nla.norm(R), _np.exp(-scaleCache[iRight]), 1e-300) sL, sR = L /", "comm, *not* mySubSubComm, since we can't do any further parallelization _mpit.gather_slices(deriv2Slices, deriv2Owners, hProdCache,", "of model parameters) - G == the linear dimension of a operation matrix", "[ sum(tmp_num_params[0:i]) for i in range(len(self.effects)+1) ] # global_e_slices = [ slice(tmp_offsets[i],tmp_offsets[i+1]) #", "verify correctness, generating warnings when checks fail. Used for testing, and runs much", "> 1e-6: _warnings.warn(\"norm(vhp-check_vhp) = %g - %g = %g\" % (_nla.norm(hprMxToFill[fInds]), _nla.norm(check_vhp), _nla.norm(hprMxToFill[fInds]", "entry of the product with respect to the i-th model parameter. * if", "= self.dim nDerivCols = self.Np if (wrtSlice is None) \\ else _slct.length(wrtSlice) deriv_shape", "# pass None as comm, *not* mySubSubComm, since we can't do any further", "since there are no memory savings from using a split tree. \"\"\" if", "the result to the appropriate block of flattened_d2prod. #NOTE: if we needed to", "= (len(elabels),N) if bUseScaling: old_err = _np.seterr(over='ignore') G, scale = self.product(circuit, True) if", "= _np.conjugate(_np.transpose(self.sos.get_effect(elabel).todense() [:, None])) # convention: E has shape (1,N) else: # a", "mode for this calculator. \"\"\" return \"deriv\" def estimate_cache_size(self, nCircuits): \"\"\" Return an", "2, 1)) + \\ d2pr_drhos + _np.transpose(d2pr_drhos, (0, 2, 1)) + \\ d2pr_dEs", "rho, E = self._rhoE_from_spamTuple(spamTuple) block_wrtSlice = pslc1 _fas(mxToFill, [fInds, pslc1], self._dprobs_from_rhoE( spamTuple, rho,", "# all of the raw operation sequences which need to be computed #", "vec(.) stacks columns # vec( A * E(0,1) * B ) = vec(", "post fill probs\") #distribute derivative computation across blocks myBlkIndices, blkOwners, blkComm = \\", "iteration **must** match that in bulk_evaltree # in order to associate the right", "product computation\") pass # this is a fairly common occurrence, and doesn't merit", "respect to (see wrtBlockSize). wrtFilter : list of ints, optional If not None,", "# global_e_slices = [slice(self.e_offset[i],self.e_offset[i+1]) for i in range(len(self.effects)) ] # return PrepEffectFilter(rho_local_slices=loc_rho_slices, #", "flat == False, a M x M x G x G numpy array,", "# # Note: unvec( X ) can be done efficiently by actually computing", "the 2nd set of gate parameters if wrtSlice1 == wrtSlice2: # Note: this", "not None. Only relevant when prMxToFill is not None. Returns ------- derivative :", "ret += d2pr_dErhos1 + d2pr_d2Es + d2pr_dEs2 # wrt E ret += d2pr_drhos1", "of the ideal/desired cache size given a number of operation sequences. Returns -------", "E, dot( dGs, rho ) ), axis=(0,4)) old_err2 = _np.seterr(invalid='ignore', over='ignore') d2pr_dOps2 =", "% fnName) return mem * FLOATSIZE def bulk_product(self, evalTree, bScale=False, comm=None): \"\"\" Compute", "0, 1) # cols = deriv cols, rows = flattened all else dGs2", "flat: return flattened_dprod else: # axes = (gate_ij, prod_row, prod_col) return _np.swapaxes(flattened_dprod, 0,", "G1 ... G(M-1) dG(M)/dkl G(M+1) ... G(L-1) tensor (G(L+1) ... GN)^T vec( dG(L)/dij", "evalTree's initial single- or zero-operation labels for i, opLabel in zip(evalTree.get_init_indices(), evalTree.get_init_labels()): if", "_slct.length(wrtSlice2) #flt1 = self._get_filter_info(wrtSlices1) #flt2 = self._get_filter_info(wrtSlices2) # GATE DERIVS (assume hGs is", "memory from previous subtree iteration before computing caches scaleVals = Gs = prodCache", "derivatives of the probability w.r.t. each model parameter. probability : float only returned", "is the number of operation sequences (i.e. evalTree.num_final_strings()), - B is the number", "len(evalTree) # ------------------------------------------------------------------ #print(\"MPI: _compute_dproduct_cache begin: %d deriv cols\" % nDerivCols) if comm", "Gs[gInds], scaleVals[gInds]), add=sumInto) _fas(mxToFill, [fInds, pslc1], self._dprobs_from_rhoE( spamTuple, rho, E, Gs[gInds], dGs[gInds], scaleVals[gInds],", "is dprod_dOps for ith string if not bScale: old_err = _np.seterr(over='ignore', invalid='ignore') Gs", "clip return value if not None. check : boolean, optional If True, perform", "gInds = \"gate sequence indices\" = indices into the (tree-) list of #", "nDerivCols1) assert(wrtSlice2 is None or _slct.length(wrtSlice2) == nDerivCols2) hessn_shape = (nDerivCols1, nDerivCols2, dim,", "useful to have fewer processor groups then subtrees (even == 1) in order", "rows or columns at once. The minimum of wrtBlockSize and the size that", "operation sequence # with respect to only that gate's parameters and fill the", "the number of selected gate-set parameters (by wrtFilter1 and wrtFilter2). evalTree : EvalTree", "be used to construct virtual gates for use in computations. \"\"\" super(MatrixForwardSimulator, self).__init__(", "None: _np.clip(mxToFill, clipTo[0], clipTo[1], out=mxToFill) # in-place clip if check: self._check(evalTree, mxToFill, clipTo=clipTo)", "# d2pr_dErhos[i,J0+J,K0+K] = sum j dEPT[J,j] dot(prod,drhoP)[i,j,K] # d2pr_dErhos[i,J0+J,K0+K] = dot(dEPT,prod,drhoP)[J,i,K] # d2pr_dErhos[i,J0+J,K0+K]", "corresponding wrtFilter is not None. Set this to non-None to reduce amount of", "GL == gatelabel2, M < L} # noqa # [ G1 ... G(M-1)", "# #elif fnName == \"bulk_dproduct\": # mem += cache_size * num_params * dim", "\\ _mpit.distribute_indices(list(range(nBlks)), mySubComm) if blkComm is not None: _warnings.warn(\"Note: more CPUs(%d)\" % mySubComm.Get_size()", "hProdCache = _np.zeros((cacheSize,) + hessn_shape) # Use comm to distribute columns allDeriv1ColSlice =", "dEP)[i,J] # dp_dEs[:,J0+J] = dot(squeeze(dot(Gs, rho),axis=(2,)), dEP)[:,J] dp_dEs = _np.zeros((nCircuits, nDerivCols)) # may", "opLabel == \"\": # special case of empty label == no gate hProdCache[i]", "[None, None, rho_gpindices2], _np.squeeze(_np.dot(_np.dot(E, dGs1), drho), axis=(0,)) * scaleVals[:, None, None]) # overflow", "= _np.zeros((nCircuits, nDerivCols)) # may overflow, but OK (deriv w.r.t any of self.effects", "a single flattened gate (ordering as numpy.flatten), - S,M == as above, and", "_np.zeros((nCircuits, nDerivCols)) # may overflow, but OK (deriv w.r.t any of self.effects -", "computation across blocks myBlkIndices, blkOwners, blkComm = \\ _mpit.distribute_indices(list(range(nBlks)), mySubComm) if blkComm is", "dGs1 is dGs2 and wrtSlice1 == wrtSlice2: # TODO: better check for equivalence:", "dim = (dim2, nDerivCols1, nDerivCols2); # swapaxes takes (kl,vec_prod_indx,ij) => (vec_prod_indx,kl,ij) elif l", "relevant for a single object (gate or spam vec) \"\"\" #Create per-gate with-respect-to", "(A tensor B)^T = A^T tensor B^T ) # and using numpy's reshape", "the length of the vectorized model). probability : float only returned if returnPr", "j] = float(_np.dot(E, _np.dot(d2prod_dGates[i, j], rho))) old_err = _np.seterr(over='ignore') prod, scale = self.product(circuit,", "_np.identity( self.dim ); total_exp = 0.0 #for i,lOp in enumerate(gateLabelList): # G =", "could be None blkSize2 = wrtBlockSize2 # could be None if (mySubComm is", "mxToFill, [felInds], 1, mySubComm, gatherMemLimit) #note: gathering axis 1 of mxToFill[felInds], dim=(ks,M) profiler.add_time(\"MPI", "is a boolean specifying whether the filling should overwrite or add to the", "(blkSize2 is None) \\ else min(comm_blkSize, blkSize2) # override with smaller comm_blkSize else:", "scaleVals, 0, 3) # convert nans to zero, as these occur b/c an", "# Use comm to distribute columns allDerivColSlice = slice(0, nDerivCols) if (wrtSlice is", "operation sequence. \"\"\" dim = self.dim nDerivCols1 = self.Np if (wrtFilter1 is None)", "If `mx`, `dp1`, and `dp2` are the outputs of :func:`bulk_fill_hprobs` (i.e. args `mxToFill`,", "fill # add the result to the appropriate block of flattened_d2prod. #NOTE: if", "= squeeze( dot( E, dot( dGs, rho ) ), axis=(0,4)) old_err2 = _np.seterr(invalid='ignore',", "wrt all spam parameters dGs = _np.empty((Gs.shape[0], 0, self.dim, self.dim), 'd') def calc_and_fill_p(spamTuple,", "not None: _mpit.gather_indices(subtreeElementIndices, subTreeOwners, deriv2MxToFill, [], 0, comm, gatherMemLimit) if prMxToFill is not", "_time.time() if evalTree.is_split(): _warnings.warn(\"Ignoring tree splitting in dproduct cache calc.\") dProdCache = _np.zeros((cacheSize,)", "an array of shape S*N x M x M where - N ==", "bReturnDProdsAndProds: Gs = evalTree.final_view(prodCache, axis=0) #shape == ( len(circuit_list), dim, dim ), #", "(may generate overflow, but OK) ps = _np.real(_np.dot(Es, _np.dot(G, rho)) * scale) _np.seterr(**old_err)", "#_warnings.warn(\"More processors than can be used for product computation\") pass # this is", "rho_gpindices1 = self._process_wrtFilter(wrtSlice1, self.sos.get_prep(rholabel)) rho_wrtFilter2, rho_gpindices2 = self._process_wrtFilter(wrtSlice2, self.sos.get_prep(rholabel)) E_wrtFilter1, E_gpindices1 = self._process_wrtFilter(wrtSlice1,", "= self.sos.get_operation(opLabel).todense() nG = max(_nla.norm(gate), 1.0) prodCache[i] = gate / nG scaleCache[i] =", "over the parameter groups. num_param1_groups : int The number of groups to divide", "`wrtSlicesList`. `hprobs` and `dprobs12` are arrays of shape K x S x B", "of cache are given by evalTree's initial single- or zero-operation labels for i,", "1: #Don't return a length-1 list, as this doesn't index numpy arrays #", "and derivs[i,j,k,l] holds the derivative of the (k,l)-th entry of the i-th operation", "== False, an array of shape S x M x M x G", "if returnPr: return ret, dpr, p else: return ret, dpr else: if returnPr:", "is not None) else None wrtIndices2 = _slct.indices(wrtSlice2) if (wrtSlice2 is not None)", "which specify a \"block\" of the Hessian to compute. Iterating over the output", "PSMALL and H.min() > -PSMALL: nG = max(_nla.norm(G), _np.exp(-scale_exp)) G = _np.dot(gate, G", "may overflow, but OK _fas(dpr_dEs, [0, EVec.gpindices], _np.dot(derivWrtAnyEvec, EVec.deriv_wrt_params())) dpr = dpr_drhos +", "gpindices2[l] = self._process_wrtFilter(wrtFilter2, used_operations[l]) #Cache partial products (relatively little mem required) prods =", "noqa for iBlk1 in myBlk1Indices: blk_wrtSlice1 = blocks1[iBlk1] dProdCache1 = self._compute_dproduct_cache( evalSubTree, prodCache,", "prMxToFill[felInds] (axis=0) profiler.add_time(\"MPI IPC\", tm) profiler.mem_check(\"bulk_fill_dprobs: post gather subtrees\") if clipTo is not", "dp_dOps[_np.isnan(dp_dOps)] = 0 #SPAM ------------- # Get: dp_drhos[i, rho_gpindices] = dot(E,Gs[i],drho/drhoP) # dp_drhos[i,J0+J]", "since there are no memory savings from using a split tree. \"\"\" dim", "overflow, but OK (deriv w.r.t any of self.effects - independent of which) dp_dAnyE", "dProdCache2, scaleCache, comm=None, wrtSlice1=None, wrtSlice2=None): \"\"\" Computes a tree of product 2nd derivatives", "optional When not None, an MPI communicator for distributing the computation across multiple", "of computed elements (i.e. evalTree.num_final_elements()) evalTree : EvalTree given by a prior call", "array a 1 x M x M array, where M is the number", "gate (ordering same as numpy.flatten), - S,M == as above, and deriv[i,j] holds", "the i-th operation sequence product with respect to the j-th model parameter. *", "if flat: # cols = deriv cols, rows = flattened all else dGs1", "(kl,vec_prod_indx,ij) => (vec_prod_indx,kl,ij) else: # l==m, which we *used* to assume gave no", "Apache License, Version 2.0 (the \"License\"); you may not use this file except", "\"\"\" Estimate the memory required by a given set of subcalls to computation", "case of empty label == no gate prodCache[i] = _np.identity(dim) # Note: scaleCache[i]", "ok dGs2 = _np.swapaxes(_np.swapaxes(dGs2, 0, 3) * scaleVals, 0, 3) # may overflow", "you want to computed their probabilites). These are a \"simplified\" circuits in that", "that we *cannot* make use of a tree being # split because there's", "that gate's parameters and fill the appropriate # columns of flattened_dprod. uniqueOpLabels =", "is not None: myHessianSlice1 = _slct.shift(myDeriv1ColSlice, wrtSlice1.start) else: myHessianSlice1 = myDeriv1ColSlice #print(\"MPI: _compute_hproduct_cache", "G(L) == oplabel} [ (G1 ... G(L-1)) tensor (G(L+1) ... GN)^T vec( dG(L)/dij", "sequence # prod = G1 * G2 * .... * GN , a", "but we want: # since then matrixOf(circuit[i]) = matrixOf(circuit[iLeft]) * matrixOf(circuit[iRight]) (iRight, iLeft)", "subcalls : list of strs A list of the names of the subcalls", "be no memory savings from using a split tree. In short, parallelization should", "across multiple processors. This is done over operation sequences when a *split* evalTree", "_slct.indices(wrtSlice) if (wrtSlice is not None) else None for i, opLabel in zip(evalTree.get_init_indices(),", "= (dim2, nDerivCols1, nDerivCols2); # swapaxes takes (kl,vec_prod_indx,ij) => (vec_prod_indx,kl,ij) elif l <", "self.sos.get_prep(rholabel).todense()[:, None] Es = [self.sos.get_effect(elabel).todense()[:, None] for elabel in elabels] Es = _np.conjugate(_np.transpose(_np.concatenate(Es,", "mem += cache_size # scale vals elif fnName == \"bulk_hprobs_by_block\": #Note: includes \"results\"", "numpy.flatten rows are kept contiguous, so the first identity below is valid. #", "the convention that rho has shape (N,1) rho = self.sos.get_prep(rholabel).todense()[:, None] Es =", "scaleVals return _np.squeeze(_np.dot(E, _np.dot(Gs, rho)), axis=(0, 2)) * scaleVals # shape == (len(circuit_list),)", "int(_np.ceil(self.Np / blkSize)) # num blocks required to achieve desired average size ==", "# filled quantity combining both spam and gate-sequence indices # gInds = \"gate", "gate parameters if dGs1 is dGs2 and wrtSlice1 == wrtSlice2: # TODO: better", "flat=False, wrtFilter=None): \"\"\" Return the derivative of a length-1 (single-gate) sequence \"\"\" dim", "# dp_dOps[i,j] = sum_k E[0,k] dot( dGs, rho )[i,j,k,0] # dp_dOps[i,j] = dot(", "revOpLabelList: G = _np.dot(G, self.sos.get_operation(opLabel).todense()) leftProds.append(G) rightProdsT = [] G = _np.identity(dim); rightProdsT.append(_np.transpose(G))", "self.Np, self.Np)) _fas(d2pr_d2Es, [0, self.sos.get_effect(elabel).gpindices, self.sos.get_effect(elabel).gpindices], _np.tensordot(derivWrtAnyEvec, self.sos.get_effect(elabel).hessian_wrt_params(), (1, 0))) # _np.einsum('ij,jkl->ikl',derivWrtAnyEvec,self.sos.get_effect(elabel).hessian_wrt_params()) else:", "Array of shape S x G x G, where: - S == the", "------- numpy.ndarray An array of floating-point probabilities, corresponding to the elements of `elabels`.", "G, where - S == len(circuit_list) - M == the length of the", "in return array # want vp[iFinal] = float(dot(E, dot(G, rho))) # vp[i] =", "if (blkSize2 is None) \\ else min(comm_blkSize, blkSize2) # override with smaller comm_blkSize", "d2pr_drhos1 + d2pr_dEs1 + d2pr_dOps2 # wrt gates return ret def _check(self, evalTree,", "# axes = (vectorized_op_el_index, model_parameter1, model_parameter2) else: vec_kl_size, vec_ij_size = flattened_d2prod.shape[1:3] # ==", "can't do any # further parallelization tm = _time.time() all_results = comm.allgather(my_results) profiler.add_time(\"MPI", "x S x B x B', where: - K is the length of", "_np.zeros((nCircuits, nDerivCols2, nDerivCols1)) dp_dAnyE = _np.squeeze(_np.dot(dGs2, rho), axis=(3,)) * scaleVals[:, None, None] #", "ret = d2pr_dErhos + _np.transpose(d2pr_dErhos, (0, 2, 1)) + \\ d2pr_drhos + _np.transpose(d2pr_drhos,", "dprod_dOps) # prod, dprod_dOps = G,dG # dp_dOps[i,j] = sum_k,l E[0,k] dGs[i,j,k,l] rho[l,0]", "sequence and prep/effect pairs. The evaluation tree organizes how to efficiently compute the", "* dim # hproduct cache # mem += cache_size * num_params * dim", "* FLOATSIZE def bulk_product(self, evalTree, bScale=False, comm=None): \"\"\" Compute the products of many", "str(dProdCache.shape))) dGs = evalSubTree.final_view(dProdCache, axis=0) #( nCircuits, nDerivCols, dim, dim ) self._fill_result_tuple( (mxToFill,),", "this order (easier to think about) revOpLabelList = tuple(reversed(tuple(circuit))) N = len(revOpLabelList) #", "def hpr(self, spamTuple, circuit, returnPr, returnDeriv, clipTo): \"\"\" Compute the Hessian of a", "product with respect to the j-th model parameter. products : numpy array Only", "starting gate) G = _np.dot(G, self.sos.get_operation(opLabel2).todense()) prods[(i, j)] = G prods[(len(revOpLabelList), len(revOpLabelList) -", "for distributing derivative calculations across multiple processors. Returns ------- deriv : numpy array", "which are integer row indices into mxToFill, specifying the correspondence between rows of", "# free mem if bReturnDProbs12: dprobs12 = dprobs1[:, :, None] * dprobs2[:, None,", "we can't tell whether it's + or - inf anyway... dp_dOps[_np.isnan(dp_dOps)] = 0", "not None: _np.clip(mxToFill, clipTo[0], clipTo[1], out=mxToFill) # in-place clip if check: self._check(evalTree, mxToFill,", "contains the multiplicative scaling needed for the hessians, derivatives, and/or products for the", "be duplicates (a list, not a set) # since all scaled gates start", "index into an array of gate parameters ordered by concatenating each gate's parameters", "d12 has the same dimensions as the Hessian, and turns out to be", "for the last). The final argument is a boolean specifying whether the filling", "contribution since we assume all gate elements are at most # linear in", "tSerialStart = _time.time() if evalTree.is_split(): _warnings.warn(\"Ignoring tree splitting in dproduct cache calc.\") dProdCache", "- so it's been removed. if comm is not None: # ignoring comm", "prods[(i, j)] = G prods[(len(revOpLabelList), len(revOpLabelList) - 1)] = ident # product of", "else _slct.length(wrtSlice1) nDerivCols2 = self.Np if wrtSlice2 is None else _slct.length(wrtSlice2) #flt1 =", "== the linear dimension of a operation matrix (G x G operation matrices).", "bool when set to True, additionally return the probability itself. returnDeriv : bool", "is was # incorrect (and luckily never used) - so it's been removed.", "= Gs = dGs = None prodCache = scaleCache = dProdCache = None", "to `bulk_fill_probs(...)`, but fills a 3D array with probability-Hessians for each \"final element\"", "mem += cache_size # scale cache # mem += cache_size # scale vals", "'d') #prMxToFill = None deriv1MxToFill = dprobs1 deriv2MxToFill = dprobs2 mxToFill = hprobs", "of the returned derivative array (see below). wrtFilter1, wrtFilter2 : list of ints,", "non-gate-local -- parameterizations of operation matrices and SPAM vectors) access to these fundamental", "if returnPr: return ret, p else: return ret ## BEGIN CACHE FUNCTIONS def", "= None relevant_gpindices = obj.gpindices return obj_wrtFilter, relevant_gpindices #Vectorizing Identities. (Vectorization) # Note", "[None, E_gpindices2, rho_gpindices1], _np.swapaxes(_np.dot(_np.transpose(devec), dp_dAnyE), 0, 1)) d2pr_dErhos2 = _np.transpose(d2pr_dErhos2, (0, 2, 1))", "evalSubTree.final_view(hProdCache, axis=0) #( nCircuits, len(wrtFilter1), len(wrtFilter2), dim, dim ) #Compute all requested derivative", "#( nCircuits, nDerivCols, dim, dim ) profiler.add_time(\"bulk_fill_dprobs: compute_dproduct_cache\", tm) profiler.mem_check(\"bulk_fill_dprobs: post compute dproduct\")", "to be done prior to the scaling. \"\"\" if bScale: scaledGatesAndExps = {}", "> 1e-8: # _np.isclose(scale,0) is SLOW! hProdCache[i] /= _np.exp(scale) if hProdCache[i].max() < HSMALL", "value (see below) hGs[_np.isnan(hGs)] = 0 _np.seterr(**old_err) if flat: # cols = deriv", "wrtFilter=None): \"\"\" Return the derivative of a length-1 (single-gate) sequence \"\"\" dim =", "through the subtrees. It can often be useful to have fewer processor groups", "a \"custom\" spamLabel consisting of a pair of SPAMVec (or array) # objects:", "= wrtBlockSize2 # could be None if (mySubComm is not None) and (mySubComm.Get_size()", "gate.deriv_wrt_params(op_wrtFilter)) # (dim**2, nParams in wrtFilter for opLabel) if flat: return flattened_dprod else:", "time=None): \"\"\" Compute probabilities of a multiple \"outcomes\" (spam-tuples) for a single operation", "# noqa # d2prod/d(opLabel1)_kl*d(opLabel2)_ij = sum_{M s.t. GM == gatelabel1} sum_{L s.t. GL", "old_err = _np.seterr(over='ignore') prod, scale = self.product(circuit, True) if returnPr: p = _np.dot(E,", "j, rho_gpindices] = dot(E,dGs[i,j],drho/drhoP)) # d2pr_drhos[i,j,J0+J] = sum_kl E[0,k] dGs[i,j,k,l] drhoP[l,J] # d2pr_drhos[i,j,J0+J]", "_np.dot(derivWrtAnyEvec, EVec.deriv_wrt_params())) d2pr_dErhos = _np.zeros((1, self.Np, self.Np)) derivWrtAnyEvec = scale * _np.dot(prod, rhoVec.deriv_wrt_params())", "wrtSlice1 = blocks1[iBlk1] wrtSlice2 = blocks2[iBlk2] self._fill_result_tuple((prMxToFill, deriv1MxToFill, deriv2MxToFill, mxToFill), evalSubTree, blocks1[iBlk1], blocks2[iBlk2],", "all else return (hGs, dGs1, dGs2, Gs, scaleVals) if bScale else (hGs, dGs1,", "= _np.zeros((nCircuits, nDerivCols1, nDerivCols2)) _fas(d2pr_d2rhos, [None, rho_gpindices1, rho_gpindices2], _np.tensordot(dp_dAnyRho, self.sos.get_prep(rholabel).hessian_wrt_params( rho_wrtFilter1, rho_wrtFilter2), (1,", "completion # (to save mem) but isn't gathered until now (but using blk1Comm).", "d2pr_dEs2 = _np.zeros((nCircuits, nDerivCols2, nDerivCols1)) dp_dAnyE = _np.squeeze(_np.dot(dGs2, rho), axis=(3,)) * scaleVals[:, None,", "wrt E ret += d2pr_drhos1 + d2pr_dEs1 + d2pr_dOps2 # wrt gates return", "blkSize2, nBlks1, nBlks2)) # pragma: no cover # noqa for iBlk1 in myBlk1Indices:", "data to construct return values Gs = evalTree.final_view(prodCache, axis=0) #shape == ( len(circuit_list),", "oplabel} [ (G1 ... G(L-1)) tensor (G(L+1) ... GN)^T vec( dG(L)/dij ) ]", "2 of hProdCache[:,myDeriv1ColSlice], # dim=(cacheSize,nDerivCols1,nDerivCols2,dim,dim) else: #compute \"Deriv1\" row-derivatives distribution only; don't use", "dop_dopLabel1 = { opLabel: gate.deriv_wrt_params(gate_wrtFilters1[opLabel]) for opLabel, gate in used_operations.items()} if wrtFilter1 ==", "> 1: _warnings.warn(\"Too many processors to make use of in \" \" _compute_dproduct_cache.\")", "in mySubTreeIndices: evalSubTree = subtrees[iSubTree] #Free memory from previous subtree iteration before computing", "A[i,0] * B[row1] ) = A tensor B^T * vec( E(0,1) ) #", "axis=0) #Set filtering for calc_and_fill wrtSlice1 = blocks1[iBlk1] wrtSlice2 = blocks2[iBlk2] self._fill_result_tuple((prMxToFill, deriv1MxToFill,", "self._probs_from_rhoE(rho, E, Gs[gInds], scaleVals[gInds]), add=sumInto) if deriv1MxToFill is not None: _fas(deriv1MxToFill, [fInds, pslc1],", "# In general: vec( A * X * B ) = A tensor", "number of operation sequences. Returns ------- int \"\"\" return int(1.3 * nCircuits) def", "= dot(E,dGs[i,j],drho/drhoP)) # d2pr_drhos[i,j,J0+J] = sum_kl E[0,k] dGs[i,j,k,l] drhoP[l,J] # d2pr_drhos[i,j,J0+J] = dot(E,", "free mem #gather results tm = _time.time() _mpit.gather_slices(blocks, blkOwners, mxToFill, [felInds], 1, mySubComm,", "able to compute reduce results from a single column of the Hessian at", "bScale : bool, optional When True, return a scaling factor (see below). comm", "else: # loc_rho_slices = [slice(None,None)]*len(self.preps) # loc_e_slices = [slice(None,None)]*len(self.effects) # global_rho_slices = [slice(self.rho_offset[i],self.rho_offset[i+1])", "to iterate through the self.operations.keys() as in # dproduct(...) and find the labels", "# length of operation sequence # prod = G1 * G2 * ....", "`cacheSize`) the tree will hold. Returns ------- int The memory estimate in bytes.", "= param_slice2 for spamTuple, (fInds, gInds) in evalTree.spamtuple_indices.items(): # fInds = \"final indices\"", "E, dot(Gs, rho)), axis=(0,2) ) * scaleVals return _np.squeeze(_np.dot(E, _np.dot(Gs, rho)), axis=(0, 2))", "`circuit` is evaluated. Returns ------- numpy.ndarray An array of floating-point probabilities, corresponding to", "sizes = %s\" % # (comm.Get_rank(),\",\".join([str(len(subtrees[i])) # for i in mySubTreeIndices]))) #eval on", "Compute the outcome probability-Hessians for an entire tree of gate strings. Similar to", "optional If not None, a list of integers specifying which model parameters to", "\"dGs must be pre-filtered!\" #Compute d(probability)/dOps and save in return list (now have", "= None # free mem if bReturnDProbs12: dprobs12 = dprobs1[:, :, None] *", "'d') # For each operation label, compute the derivative of the entire operation", "..tools.matrixtools import _fas from .profiler import DummyProfiler as _DummyProfiler from .label import Label", "parameter vector of the Model. autogator : AutoGator An auto-gator object that may", "hGs[gInds], scaleVals[gInds], wrtSlice1, wrtSlice2), add=sumInto) _np.seterr(**old_err) #Set wrtBlockSize to use available processors if", "but OK # Get: dp_dEs[i, E_gpindices] = dot(transpose(dE/dEP),Gs[i],rho)) # dp_dEs[i,J0+J] = sum_lj dEPT[J,j]", "nDerivCols) if (wrtSlice is None) else wrtSlice _, myDerivColSlice, _, mySubComm = \\", "= 0 # assume the zero hessian value trumps since we've renormed to", "return list # d2pr_dOps2[i,j,k] = sum_l,m E[0,l] hGs[i,j,k,l,m] rho[m,0] # d2pr_dOps2[i,j,k] = sum_l", "\"\"\" old_err = _np.seterr(over='ignore') rho, E = self._rhoE_from_spamTuple(spamTuple) _fas(mxToFill, [fInds], self._probs_from_rhoE(rho, E, Gs[gInds],", "count\") profiler.mem_check(\"bulk_fill_dprobs: end\") def bulk_fill_hprobs(self, mxToFill, evalTree, prMxToFill=None, deriv1MxToFill=None, deriv2MxToFill=None, clipTo=None, check=False, comm=None,", "software. # Licensed under the Apache License, Version 2.0 (the \"License\"); you may", "# it could make sense to iterate through the self.operations.keys() as in #", "good way to reconstruct the # *non-final* parent-tree elements from those of the", "rho, E, Gs[gInds], dGs2[gInds], scaleVals[gInds], wrtSlice2), add=sumInto) _fas(mxToFill, [fInds, pslc1, pslc2], self._hprobs_from_rhoE( spamTuple,", "density-matrix-mode probability # (TODO in FUTURE) # pr = Tr( |rho><E| * prod", "cache mem += cache_size * (wrtLen1 + wrtLen2) * dim * dim #", "evalTree, param_slice1, param_slice2, calc_and_fill_fn): \"\"\" This function takes a \"calc-and-fill\" function, which computes", "rows are kept contiguous, so the first identity below is valid. # Below", "if vec(.) stacks columns # vec( A * E(0,1) * B ) =", "== gatelabel2, M < L} # noqa # [ G1 ... G(M-1) dG(M)/dkl", "memory is fixed ## (and dominated) by the output array size. Could throw", "G operation matrices). scaleValues : numpy array Only returned when bScale == True.", "properly if wrtSlice1 is not None and wrtSlice1.start is not None: myHessianSlice1 =", "array, where: - N == the number of entries in a single flattened", "G,dG => product, dprod_dOps) # prod, dprod_dOps = G,dG # dp_dOps[i,j] = sum_k,l", "\"\": # special case of empty label == no gate hProdCache[i] = _np.zeros(hessn_shape)", "anyway... d2pr_dOps2[_np.isnan(d2pr_dOps2)] = 0 # SPAM DERIVS (assume dGs1 and dGs2 are already", "num_deriv_cols2), 'd') # For each pair of gates in the string, compute the", "mappings generated when the original list of `Circuits` was simplified. Parameters ---------- mxToFill", "applied to the resulting products (final_product[i] = scaleValues[i] * prods[i]). \"\"\" prodCache, scaleCache", ":func:`bulk_fill_hprobs` (i.e. args `mxToFill`, `deriv1MxToFill`, and `deriv1MxToFill`), then: - `hprobs == mx[:,:,rowSlice,colSlice]` -", "\"extra\", i.e. rank != 0, cpus my_results = self._compute_dproduct_cache( evalTree, prodCache, scaleCache, None,", "arguments \"\"\" old_err = _np.seterr(over='ignore') rho, E = self._rhoE_from_spamTuple(spamTuple) _fas(mxToFill, [fInds], self._probs_from_rhoE(rho, E,", "# overflow OK d2pr_d2rhos = _np.zeros((nCircuits, nDerivCols1, nDerivCols2)) _fas(d2pr_d2rhos, [None, rho_gpindices1, rho_gpindices2], _np.tensordot(dp_dAnyRho,", "check_vhp[0]) > 1e-6: _warnings.warn(\"norm(vhp-check_vhp) = %g - %g = %g\" % (_nla.norm(hprMxToFill[fInds]), _nla.norm(check_vhp),", "[ (G1 ... G(L-1)) tensor (G(L+1) ... GN)^T ]] # noqa # #", "model parameters) and hessian[i,j,k] holds the derivative of the i-th entry of the", "self.sos.get_effect(elabel) # arrays, these are SPAMVecs nCircuits = Gs.shape[0] rho_wrtFilter, rho_gpindices = self._process_wrtFilter(wrtSlice,", "the operation sequences to compute the bulk operation on. This tree *cannot* be", "objects (never seemed very useful ## since numpy does all the major allocation/deallocation).", "scaleCache[i] = 0.0 from initialization else: gate = self.sos.get_operation(opLabel).todense() nG = max(_nla.norm(gate), 1.0)", "self._compute_dproduct_cache( evalSubTree, prodCache, scaleCache, blk2Comm, blk_wrtSlice2) dGs2 = evalSubTree.final_view(dProdCache2, axis=0) hProdCache = self._compute_hproduct_cache(", "num_deriv_cols), 'd') # For each operation label, compute the derivative of the entire", "# with respect to only that gate's parameters and fill the appropriate #", "myDeriv2ColSlice] = self._compute_hproduct_cache( evalTree, prodCache, dProdCache1[:, myDeriv1ColSlice], dProdCache2[:, myDeriv2ColSlice], scaleCache, None, myHessianSlice1, myHessianSlice2)", "... GN)^T ]] has # columns which correspond to the vectorized derivatives of", "given by evalTree's initial single- or zero-operation labels wrtIndices1 = _slct.indices(wrtSlice1) if (wrtSlice1", "the bulk operation on. bScale : bool, optional When True, return a scaling", "== 0: #Don't return a length-0 list, as this doesn't index numpy arrays", "tree *cannot* be split. wrtSlicesList : list A list of `(rowSlice,colSlice)` 2-tuples, each", "d2pr/d(E)_i d(opLabel)_mn = sum [dprod/d(opLabel)_mn]_il rho_l (and same for other diff order) #", "M numpy array of derivatives of the probability w.r.t. each model parameter. probability", "of in \" \" _compute_dproduct_cache.\") if mySubComm.Get_rank() > 0: myDerivColSlice = slice(0, 0)", "of the probability w.r.t. the k-th then the j-th model parameter. derivative :", "to perform a hessian calculation (i.e. for l==m) then # it could make", "\"\": # special case of empty label == no gate prodCache[i] = _np.identity(dim)", "comm) #, gatherMemLimit) #gather over row-distribution (Deriv1) #note: gathering axis 1 of hProdCache,", "only a *subset* of all the gate's parameters if isinstance(wrtFilter, slice): wrtFilter =", "x M array, where M is the number of model parameters. Parameters ----------", "distributing derivative calculations across multiple processors. Returns ------- hessian : numpy array *", "max(_nla.norm(L), _np.exp(-scaleCache[iLeft]), 1e-300), max(_nla.norm(R), _np.exp(-scaleCache[iRight]), 1e-300) sL, sR = L / nL, R", "by a zero deriv value (see below) dGs[_np.isnan(dGs)] = 0 _np.seterr(**old_err) if flat:", "vectorized model (number of model parameters) and hessian[i,j,k] holds the derivative of the", "R = GxG ; dL,dR = vgs x GxG ; hL,hR = vgs", "spam parameters dGs = _np.empty((Gs.shape[0], 0, self.dim, self.dim), 'd') def calc_and_fill_p(spamTuple, fInds, gInds,", "== \"statevec\": ps = _np.real(_np.abs(_np.dot(Es, _np.dot(G, rho)) * scale)**2) else: # evotype ==", "access to these fundamental operations. \"\"\" def __init__(self, dim, simplified_op_server, paramvec): \"\"\" Construct", "of a pair of SPAMVec (or array) # objects: (prepVec, effectVec) rho, Eraw", "or columns at once. The minimum of wrtBlockSize and the size that makes", "= self.Np / mySubComm.Get_size() blkSize1 = comm_blkSize if (blkSize1 is None) \\ else", ") profiler.mem_check(\"bulk_fill_dprobs: post compute product\") def calc_and_fill(spamTuple, fInds, gInds, pslc1, pslc2, sumInto): \"\"\"", "clipTo[0], clipTo[1]) else: ret = ps #DEBUG CHECK #check_ps = _np.array( [ self.pr(", "# may overflow, but OK (deriv w.r.t any of self.effects - independent of", "slice(None), calc_and_fill) else: # Divide columns into blocks of at most blkSize assert(wrtFilter1", "_fas(dp_drhos, [None, rho_gpindices], _np.squeeze(_np.dot(_np.dot(E, Gs), rhoVec.deriv_wrt_params(rho_wrtFilter)), axis=(0,)) * scaleVals[:, None]) # may overflow,", "assert(dprod_dOps.shape[0] == self.Np) if returnDeriv: # same as in dpr(...) dpr_dOps = _np.empty((1,", "for fnName in subcalls: if fnName == \"bulk_fill_probs\": mem += cache_size * dim", "= Tr( |rho><E| * prod ) = sum E_k prod_kl rho_l # dpr/d(opLabel)_ij", "= _np.array(relevant_gpindices, _np.int64) if len(relevant_gpindices) == 1: #Don't return a length-1 list, as", "array of shape S*N x M x M where - N == the", "is None or _slct.length(wrtSlice2) == nDerivCols2) hessn_shape = (nDerivCols1, nDerivCols2, dim, dim) cacheSize", "all probabilities all at once so they're not repeatedly # computed for each", "often be computed column-by-column from the using the columns of the operation sequences.", "d2pr_dErhos1 + d2pr_d2Es + d2pr_dEs2 # wrt E ret += d2pr_drhos1 + d2pr_dEs1", "a generator that computes the 2nd derivatives of the probabilities generated by a", "# in order to associate the right single-gate-strings w/indices wrtIndices = _slct.indices(wrtSlice) if", "# dpr/d(rho)_i = sum E_k prod_ki # dpr/d(E)_i = sum prod_il rho_l rholabel,", "compute dproduct blk (expect \" \" +%.2fGB, shape=%s)\" % (dProdCache.nbytes / (1024.0**3), str(dProdCache.shape)))", "None] _np.seterr(**old_err2) # may overflow, but OK ; shape == (len(circuit_list), nDerivCols, nDerivCols)", "cache_size * dim * dim # product cache # mem += cache_size #", "to the scaling. \"\"\" if bScale: scaledGatesAndExps = {} scale_exp = 0 G", "evaluation tree out of (most likely because you want to computed their probabilites).", "---------- mxToFill : numpy ndarray an already-allocated 1D numpy array of length equal", "axis=0) #( nCircuits, nDerivCols, dim, dim ) self._fill_result_tuple( (mxToFill,), evalSubTree, blocks[iBlk], slice(None), calc_and_fill_blk)", "prodCache[iLeft], prodCache[iRight] dL1, dR1 = dProdCache1[iLeft], dProdCache1[iRight] dL2, dR2 = dProdCache2[iLeft], dProdCache2[iRight] hL,", "cache_size # scale cache # mem += cache_size # scale vals # #elif", "sequence product with respect to the j-th model parameter. * if flat ==", ": int The number of processor groups used to (in parallel) iterate through", "sequence indices\" = indices into the (tree-) list of # all of the", "model_parameter2, model_element_row, model_element_col) def prs(self, rholabel, elabels, circuit, clipTo, bUseScaling=False, time=None): \"\"\" Compute", "tensor B^T ) # and using numpy's reshape dim = self.dim uniqueOpLabels =", "with wrtBlockSize. wrtBlockSize : int or float, optional The maximum number of derivative", "= _np.transpose(xv, axes=(2, 0, 1)) # (dim2, nDerivCols1, nDerivCols2) flattened_d2prod[:, inds1, inds2] +=", "yet!\") #Compute probability and save in return array # want vp[iFinal] = float(dot(E,", "that they should only contain \"deterministic\" elements (no POVM or Instrument labels). numSubtreeComms", ": float, optional The *start* time at which `circuit` is evaluated. Returns -------", "shape == (len(circuit_list),) ; may overflow but OK def _dprobs_from_rhoE(self, spamTuple, rho, E,", "products within decent # bounds #assert( len( (_np.isnan(hGs)).nonzero()[0] ) == 0 ) #assert(", "Distribution is first performed over subtrees of evalTree (if it is split), and", "# may overflow, but OK if infs occur here _np.seterr(**old_err) if bReturnProds: Gs", "indicates a non-zero hessian x0 = _np.kron(_np.transpose(prods[(0, m - 1)]), prods[(m + 1,", "numpy array Only returned when bReturnProds == True. An array of shape S", "# dp_dOps[i,j] = dot( E, dot( dGs, rho ) )[0,i,j,0] # dp_dOps =", "supported yet!\") #Compute probability and save in return array # want vp[iFinal] =", "sum_{L s.t. GL == oplabel} [ (G1 ... G(L-1)) tensor (G(L+1) ... GN)^T", "mySubComm, gatherMemLimit) #note: gathering axis 1 of mxToFill[felInds], dim=(ks,M) profiler.add_time(\"MPI IPC\", tm) profiler.mem_check(\"bulk_fill_dprobs:", "add transposes b/c spam terms only compute one triangle of hessian # Note:", "] # noqa # = [ sum_{L s.t. G(L) == oplabel} [ (G1", "OK # Get: dp_dEs[i, E_gpindices] = dot(transpose(dE/dEP),Gs[i],rho)) # dp_dEs[i,J0+J] = sum_lj dEPT[J,j] Gs[i,j,l]", "R = prodCache[iLeft], prodCache[iRight] prodCache[i] = _np.dot(L, R) scaleCache[i] = scaleCache[iLeft] + scaleCache[iRight]", "then (and only when needed) a split tree to parallelize computation, since there", "# dEP^T * prod[i,:,:] * drhoP # d2pr_dErhos[i,J0+J,K0+K] = sum jk dEPT[J,j] prod[i,j,k]", "dim, dim ) profiler.mem_check(\"bulk_fill_dprobs: post compute product\") def calc_and_fill(spamTuple, fInds, gInds, pslc1, pslc2,", "if gate G(L) is just a matrix of parameters, then dG(L)/dij = E(i,j),", "else (dGs, Gs) else: dGs = evalTree.final_view(dProdCache, axis=0) #shape == ( len(circuit_list), nDerivCols,", "(_nla.norm(dprMxToFill[fInds]), _nla.norm(check_vdp), _nla.norm(dprMxToFill[fInds] - check_vdp))) # pragma: no cover if hprMxToFill is not", "assume all gate elements are at most # linear in the parameters assert(opLabel1", "myBlk2Indices: blk_wrtSlice2 = blocks2[iBlk2] if blk_wrtSlice1 == blk_wrtSlice2: dProdCache2 = dProdCache1; dGs2 =", "total number of computed elements (i.e. evalTree.num_final_elements()) evalTree : EvalTree given by a", "# dp_dEs[i,J0+J] = dot(squeeze(dot(Gs, rho),2), dEP)[i,J] # dp_dEs[:,J0+J] = dot(squeeze(dot(Gs, rho),axis=(2,)), dEP)[:,J] dp_dEs", "hProdCache[:, myDeriv1ColSlice] = self._compute_hproduct_cache( evalTree, prodCache, dProdCache1[:, myDeriv1ColSlice], dProdCache2, scaleCache, None, myHessianSlice1, wrtSlice2)", "(KM,1,N') = (KM,N,N') yield wrtSlice1, wrtSlice2, hprobs, dprobs12 else: yield wrtSlice1, wrtSlice2, hprobs", "evalTree because # (iRight,iLeft,iFinal) = tup implies circuit[i] = circuit[iLeft] + circuit[iRight], but", "PrepEffectFilter(rho_local_slices=loc_rho_slices, # rho_global_slices=global_rho_slices, # e_local_slices=loc_e_slices, # e_global_slices=global_e_slices, # num_rho_params=_slct.length(wrtSlices['preps']), # num_e_params=_slct.length(wrtSlices['effects'])) # else:", "gpindices], gate.deriv_wrt_params(op_wrtFilter)) # (dim**2, nParams[opLabel]) if _slct.length(gpindices) > 0: # works for arrays", "1)]), prods[(m + 1, N - 1)]) # (dim**2, dim**2) x = _np.dot(_np.transpose(dop_dopLabel1[opLabel1]),", "many processors to make use of in \" \" _compute_dproduct_cache.\") if mySubComm.Get_rank() >", "to True, additionally return the probabilities and their derivatives (see below). bScale :", "wrtSlice? prodCache, scaleCache = self._compute_product_cache(evalTree, comm) dProdCache1 = self._compute_dproduct_cache(evalTree, prodCache, scaleCache, comm, wrtSlice1)", "profiler.add_time(\"bulk_fill_dprobs: calc_and_fill\", tm) #Set wrtBlockSize to use available processors if it isn't specified", "_np.dot(Gs, rho).squeeze(2) * scaleVals[:, None] # overflow OK d2pr_d2Es = _np.zeros((nCircuits, nDerivCols1, nDerivCols2))", "argument is used internally for distributing calculations across multiple processors and to control", "cols, rows = all else return (hGs, dGs1, dGs2, Gs, scaleVals) if bScale", "distributing derivative calculations across multiple processors. Returns ------- deriv : numpy array *", "bScale == True. An array of shape S such that scaleVals[i] contains the", "bounds #assert( len( (_np.isnan(dGs)).nonzero()[0] ) == 0 ) #assert( len( (_np.isinf(dGs)).nonzero()[0] ) ==", "sum prod_il rho_l rholabel, elabel = spamTuple # can't deal w/\"custom\" spam label...", "dGs1 else: dProdCache2 = self._compute_dproduct_cache( evalTree, prodCache, scaleCache, comm, wrtSlice2) dGs2 = evalTree.final_view(dProdCache2,", "to construct return values old_err = _np.seterr(over='ignore') scaleExps = evalTree.final_view(scaleCache) scaleVals = _np.exp(scaleExps)", "scaleVals[gInds]), add=sumInto) if deriv1MxToFill is not None: _fas(deriv1MxToFill, [fInds, pslc1], self._dprobs_from_rhoE( spamTuple, rho,", "respect to. If there are more processors than model parameters, distribution over a", "Compute the derivative of the entire operation sequence with respect to the #", "\\ _mpit.distribute_slice(allDeriv1ColSlice, comm) # Get slice into entire range of model params so", "if len(relevant_gpindices) == 1: #Don't return a length-1 list, as this doesn't index", "# may also give invalid value due to scaleVals being inf and dot-prod", "the shape of the returned derivative array (see below). bReturnProds : bool, optional", "M is the number of model parameters. evalTree : EvalTree given by a", "are more processors than deriv cols, give a # warning -- note that", "objects. bReturnDProbs12 : boolean, optional If true, the generator computes a 2-tuple: (hessian_col,", "gather blocks\") #collect/gather results tm = _time.time() subtreeElementIndices = [t.final_element_indices(evalTree) for t in", "E, Gs[gInds], scaleVals[gInds]), add=sumInto) _np.seterr(**old_err) self._fill_result_tuple((mxToFill,), evalSubTree, slice(None), slice(None), calc_and_fill) #collect/gather results subtreeElementIndices", "is not None. bUseScaling : bool, optional Whether to use a post-scaled product", "OK def _dprobs_from_rhoE(self, spamTuple, rho, E, Gs, dGs, scaleVals, wrtSlice=None): if self.evotype ==", "Create placeholder dGs for *no* gate params to compute # derivatives wrt all", "# (just as prMxToFill is computed fully on each inner loop *iteration*!) #collect/gather", "{ opLabel: gate.deriv_wrt_params(gate_wrtFilters2[opLabel]) for opLabel, gate in used_operations.items()} #Finally, cache any nonzero gate", "# num_rho_params=_slct.length(wrtSlices['preps']), # num_e_params=_slct.length(wrtSlices['effects'])) # else: # loc_rho_slices = [slice(None,None)]*len(self.preps) # loc_e_slices =", "dim, simplified_op_server, paramvec) if self.evotype not in (\"statevec\", \"densitymx\"): raise ValueError((\"Evolution type %s", "(wrtFilter is None) else len(wrtFilter) flattened_dprod = _np.zeros((dim**2, num_deriv_cols), 'd') _fas(flattened_dprod, [None, gpindices],", "no good way to reconstruct the # *non-final* parent-tree elements from those of", "memory savings from using a split tree. \"\"\" dim = self.dim # Note:", "------- hessian : numpy array a 1 x M x M array, where", "Gs) else: hGs = evalTree.final_view(hProdCache, axis=0) #shape == ( len(circuit_list), nDerivCols, nDerivCols, dim,", "self._rhoE_from_spamTuple(spamTuple) _fas(mxToFill, [fInds], self._probs_from_rhoE(rho, E, Gs[gInds], scaleVals[gInds]), add=sumInto) _np.seterr(**old_err) self._fill_result_tuple((mxToFill,), evalSubTree, slice(None), slice(None),", "shape S x G x G, where: - S == the number of", "dGs for *no* gate params to compute # derivatives wrt all spam parameters", "hessian : numpy array * if flat == False, a M x M", "parent-tree elements from those of the sub-trees. _warnings.warn(\"Increased speed could be obtained\" \"", "= self._compute_dproduct_cache(evalTree, prodCache, scaleCache, comm, wrtSlice) #use cached data to construct return values", "dim, dim) cacheSize = len(evalTree) # ------------------------------------------------------------------ #print(\"MPI: _compute_dproduct_cache begin: %d deriv cols\"", "to in the first (row) and second (col) derivative operations, respectively. Each element", "self.sos.get_effect(elabel)) nDerivCols1 = self.Np if wrtSlice1 is None else _slct.length(wrtSlice1) nDerivCols2 = self.Np", "= 0 for fnName in subcalls: if fnName == \"bulk_fill_probs\": mem += cache_size", "blkSize1 = wrtBlockSize1 # could be None blkSize2 = wrtBlockSize2 # could be", "(gate_ij, prod_row, prod_col) return _np.swapaxes(flattened_dprod, 0, 1).reshape((num_deriv_cols, dim, dim)) def hoperation(self, opLabel, flat=False,", "operation labels The sequence of operation labels. bScale : bool, optional When True,", "return _np.transpose(flattened_hprod, (1, 2, 0)).reshape( (num_deriv_cols1, num_deriv_cols2, dim, dim)) # axes = (gate_ij1,", "split evalTree (if given) is possible. wrtFilter1, wrtFilter2 : list of ints, optional", "the resulting products (final_product[i] = scaleValues[i] * prods[i]). \"\"\" prodCache, scaleCache = self._compute_product_cache(evalTree,", "it isn't specified if wrtFilter1 is None and wrtFilter2 is None: blkSize1 =", "the returned probability. time : float, optional The *start* time at which `circuit`", "flat == True, a N x M x M numpy array, where: -", "operation matrices) and derivs[i,j,k,l] holds the derivative of the (k,l)-th entry of the", "= dGs = None # free mem else: # Divide columns into blocks", "cache_size # scale vals ## It doesn't make sense to include these since", "in a single flattened gate (ordering as numpy.flatten), - S,M == as above,", "wrtFilter and wrtBlockSize wrtSlice = _slct.list_to_slice(wrtFilter) else: wrtSlice = None profiler.mem_check(\"bulk_fill_dprobs: begin (expect", "% (nDerivCols, str(allDerivColIndices), comm.Get_rank(), str(myDerivColIndices))) if mySubComm is not None and mySubComm.Get_size() >", "= prod_ij (and same for other diff order) # d2pr/d(E)_i d(E)_j = 0", "prodCache, scaleCache, comm, wrtSlice1) dProdCache2 = dProdCache1 if (wrtSlice1 == wrtSlice2) else \\", "Get: d2pr_dErhos[i, e_offset[eIndex]:e_offset[eIndex+1], e_offset[rhoIndex]:e_offset[rhoIndex+1]] = # dEP^T * prod[i,:,:] * drhoP # d2pr_dErhos[i,J0+J,K0+K]", "self._compute_dproduct_cache(evalSubTree, prodCache, scaleCache, mySubComm, wrtSlice2) dGs1 = evalSubTree.final_view(dProdCache1, axis=0) dGs2 = evalSubTree.final_view(dProdCache2, axis=0)", "self._compute_hproduct_cache( evalTree, prodCache, dProdCache1[:, myDeriv1ColSlice], dProdCache2, scaleCache, None, myHessianSlice1, wrtSlice2) # pass None", "prodCache[i] = _np.dot(sL, sR); scaleCache[i] += _np.log(nL) + _np.log(nR) #print \"bulk_product DEBUG: %d", "= scale * _np.transpose(_np.dot(prod, rho)) # may overflow, but OK # (** doesn't", "inf anyway... d2pr_dOps2[_np.isnan(d2pr_dOps2)] = 0 # SPAM DERIVS (assume dGs1 and dGs2 are", "than can be used for product computation\") pass # this is a fairly", "swapaxes takes (kl,vec_prod_indx,ij) => (vec_prod_indx,kl,ij) elif l < m: x0 = _np.kron(_np.transpose(prods[(l +", "occur here _np.seterr(**old_err) if bReturnDProdsAndProds: Gs = evalTree.final_view(prodCache, axis=0) #shape == ( len(circuit_list),", "scaleCache, comm, wrtSlice1, wrtSlice2) hGs = evalTree.final_view(hProdCache, axis=0) if bReturnDProbs12: dprobs1 = _np.zeros((nElements,", "splitting in dproduct cache calc.\") dProdCache = _np.zeros((cacheSize,) + deriv_shape) # This iteration", "(e.g. by splitting tree beforehand), as there\" \" are more cpus than hessian", "in order to associate the right single-gate-strings w/indices wrtIndices = _slct.indices(wrtSlice) if (wrtSlice", "& Engineering Solutions of Sandia, LLC (NTESS). # Under the terms of Contract", "opLabel, gate in used_operations.items()} if wrtFilter1 == wrtFilter2: dop_dopLabel2 = dop_dopLabel1 else: dop_dopLabel2", "elements are at most # linear in the parameters assert(opLabel1 == opLabel2) if", "= evalSubTree.final_view(prodCache, axis=0) #( nCircuits, dim, dim ) profiler.mem_check(\"bulk_fill_dprobs: post compute product\") def", "of parameters, then dG(L)/dij = E(i,j), an elementary matrix dim = self.dim #Cache", "specified sequence of operation labels. Parameters ---------- circuit : Circuit or tuple of", "flattened_dprod = _np.zeros((dim**2, num_deriv_cols), 'd') # For each operation label, compute the derivative", "Note: unvec( X ) can be done efficiently by actually computing X^T (", ".matrixevaltree import MatrixEvalTree as _MatrixEvalTree from .forwardsim import ForwardSimulator _dummy_profiler = _DummyProfiler() #", "cache info (not requiring column distribution) tm = _time.time() prodCache, scaleCache = self._compute_product_cache(evalSubTree,", "is not None: _warnings.warn(\"Note: more CPUs(%d)\" % mySubComm.Get_size() + \" than derivative columns(%d)!\"", "derivative of the (l,m)-th entry of the i-th operation sequence product with respect", "= _np.zeros((nCircuits, nDerivCols2, nDerivCols1)) dp_dAnyE = _np.squeeze(_np.dot(dGs2, rho), axis=(3,)) * scaleVals[:, None, None]", "indices relevant_gpindices = [] # indices into original wrtFilter'd indices gpindices = obj.gpindices_as_array()", "mem else: # Divide columns into blocks of at most blkSize assert(wrtFilter is", "dGs, rho )[i,j,k,l,0] # d2pr_dOps2[i,j,k] = dot( E, dot( dGs, rho ) )[0,i,j,k,0]", "None, an MPI communicator for distributing the computation across multiple processors. Distribution is", "noqa # if dG(L)/dij = E(i,j) # noqa # = vec(i,j)-col of [", "_np.dot(G, self.sos.get_operation(opLabel).todense()) leftProds.append(G) rightProdsT = [] G = _np.identity(dim); rightProdsT.append(_np.transpose(G)) for opLabel in", "dGs1 = None # free mem #gather column results: gather axis 2 of", "spamTuple, rho, E, Gs, dGs, scaleVals, wrtSlice=None): if self.evotype == \"statevec\": raise NotImplementedError(\"Unitary", "_slct.list_to_slice(wrtFilter) else: wrtSlice = None profiler.mem_check(\"bulk_fill_dprobs: begin (expect ~ %.2fGB)\" % (mxToFill.nbytes /", "axis=(0,)) * scaleVals[:, None]) # may overflow, but OK # Get: dp_dEs[i, E_gpindices]", "E = self._rhoE_from_spamTuple(spamTuple) rhoVec = self.sos.get_prep(rholabel) # distinct from rho,E b/c rho,E are", "assert(time is None), \"MatrixForwardSimulator cannot be used to simulate time-dependent circuits\" rho, Es", "(see below) dGs1[_np.isnan(dGs1)] = 0 # convert nans to zero, as these occur", "Es = [self.sos.get_effect(elabel).todense()[:, None] for elabel in elabels] Es = _np.conjugate(_np.transpose(_np.concatenate(Es, axis=1))) #", "N == the number of entries in a single flattened gate (ordering is", ") ] # noqa # = [ sum_{L s.t. G(L) == oplabel} [", "# Note: ignoring L == M terms assumes that d^2 G/(dij)^2 == 0,", "rho_gpindices2], _np.tensordot(dp_dAnyRho, self.sos.get_prep(rholabel).hessian_wrt_params( rho_wrtFilter1, rho_wrtFilter2), (1, 0))) # _np.einsum('ij,jkl->ikl', dp_dAnyRho, self.sos.get_prep(rholabel).hessian_wrt_params( # rho_wrtFilter1,", "#get distribution across subtrees (groups if needed) subtrees = evalTree.get_sub_trees() mySubTreeIndices, subTreeOwners, mySubComm", "may not use this file except # in compliance with the License. You", "- %g = %g\" % (_nla.norm(dprMxToFill[fInds]), _nla.norm(check_vdp), _nla.norm(dprMxToFill[fInds] - check_vdp))) # pragma: no", "x M x M where - N == the number of entries in", "of operation sequence # prod = G1 * G2 * .... * GN", "sum(tmp_num_params[0:i]) for i in range(len(self.preps)+1) ] # global_rho_slices = [ slice(tmp_offsets[i],tmp_offsets[i+1]) # for", "the sequence and spam label indexed by iOpStr and iSpamLabel. d12 has the", "overflow but OK def _dprobs_from_rhoE(self, spamTuple, rho, E, Gs, dGs, scaleVals, wrtSlice=None): if", "(deriv w.r.t any of self.effects - independent of which) dp_dAnyE = _np.squeeze(_np.dot(Gs, rho),", "gate parameters. If this is not the case, need LinearOperator objects to #", ": AutoGator An auto-gator object that may be used to construct virtual gates", "= _slct.indices(wrtFilter) if wrtFilter is not None: obj_wrtFilter = [] # values =", "derivatives are wrt the 2nd set of gate parameters if wrtSlice1 == wrtSlice2:", "%g = %g\" % (_nla.norm(prMxToFill[fInds]), _nla.norm(check_vp), _nla.norm(prMxToFill[fInds] - check_vp))) # pragma: no cover", "\"ending\" gate (>= starting gate) G = _np.dot(G, self.sos.get_operation(opLabel2).todense()) prods[(i, j)] = G", "blk2Owners, blk2Comm = \\ _mpit.distribute_indices(list(range(nBlks2)), blk1Comm) if blk2Comm is not None: _warnings.warn(\"Note: more", "as _MatrixEvalTree from .forwardsim import ForwardSimulator _dummy_profiler = _DummyProfiler() # Smallness tolerances, used", "mySubComm) #use cached data to final values scaleVals = self._scaleExp(evalSubTree.final_view(scaleCache)) Gs = evalSubTree.final_view(prodCache,", "if prMxToFill is not None: _mpit.gather_indices(subtreeElementIndices, subTreeOwners, prMxToFill, [], 0, comm) if clipTo", "comm=None): \"\"\" Constructs a generator that computes the 2nd derivatives of the probabilities", "with respect to in the first (row) and second (col) derivative operations, respectively.", "kl xv = _np.swapaxes(xv, 1, 2) y = _np.dot(_np.kron(prods[(0, l - 1)], xv),", "0, comm) if clipTo is not None and prMxToFill is not None: _np.clip(prMxToFill,", "over %d cols (rank %d computing %s)\" \\ # % (nDerivCols2, comm.Get_rank(), str(myDerivColSlice)))", "sumInto): \"\"\" Compute and fill result quantities for given arguments \"\"\" tm =", "evalTree.spamtuple_indices.items(): # fInds = \"final indices\" = the \"element\" indices in the final", "w.r.t. each model parameter (M is the length of the vectorized model). probability", "above) _mpit.gather_slices(deriv1Slices, deriv1Owners, hProdCache, [], 1, comm) #, gatherMemLimit) #gather over row-distribution (Deriv1)", "E_gpindices] = dot(transpose(dE/dEP),Gs[i],rho)) # dp_dEs[i,J0+J] = sum_lj dEPT[J,j] Gs[i,j,l] rho[l,0] # dp_dEs[i,J0+J] =", "1e-300), max(_nla.norm(R), _np.exp(-scaleCache[iRight]), 1e-300) sL, sR = L / nL, R / nR", "M == length of the vectorized model (number of model parameters) and deriv[i,j]", "merit a warning # ------------------------------------------------------------------ if evalTree.is_split(): _warnings.warn(\"Ignoring tree splitting in product cache", "wrtSlice = None profiler.mem_check(\"bulk_fill_dprobs: begin (expect ~ %.2fGB)\" % (mxToFill.nbytes / (1024.0**3))) ##", "= self._process_wrtFilter(wrtFilter, gate) # Allocate memory for the final result num_deriv_cols = self.Np", "\"\"\" if wrtFilter1 is not None: assert(wrtBlockSize1 is None and wrtBlockSize2 is None)", "E_wrtFilter, E_gpindices = self._process_wrtFilter(wrtSlice, self.sos.get_effect(elabel)) nDerivCols = self.Np if wrtSlice is None else", "terms assumes that d^2 G/(dij)^2 == 0, which is true IF each operation", "d(opLabel2)_ij]_kl rho_l # d2pr/d(rho)_i d(opLabel)_mn = sum E_k [dprod/d(opLabel)_mn]_ki (and same for other", "else _slct.length(wrtFilter) dim = self.dim wrtSlice = _slct.list_to_slice(wrtFilter) if (wrtFilter is not None)", "vectorized model (number of model parameters) and deriv[i,j] holds the derivative of the", "contained in a class separate from Model to allow for additional model classes", "2nd set of gate parameters if wrtSlice1 == wrtSlice2: # Note: this doesn't", "the product (els of # prod.flatten()). # # Note: if gate G(L) is", "in the tree construction by giving the tree information it needs to distribute", "small in order to keep prod managable.\") elif _np.count_nonzero(dProdCache[i]) and dProdCache[i].max() < DSMALL", "is the length of spam_label_rows, - S is the number of operation sequences", "self.sos.get_effect(elabel).hessian_wrt_params( # E_wrtFilter1, E_wrtFilter2)) else: d2pr_d2Es = 0 # END SPAM DERIVS -----------------------", "hpr(self, spamTuple, circuit, returnPr, returnDeriv, clipTo): \"\"\" Compute the Hessian of a probability", "check_vdp) > 1e-6: _warnings.warn(\"norm(vdp-check_vdp) = %g - %g = %g\" % (_nla.norm(dprMxToFill[fInds]), _nla.norm(check_vdp),", "unitary evolution we need to: # - alter product, dproduct, etc. to allow", "of Circuits or tuples of operation labels which specify the operation sequences to", "None) else None #TODO: just allow slices as argument: wrtFilter -> wrtSlice? prodCache,", "\"bulk_fill_probs\": mem += cache_size * dim * dim # product cache mem +=", "= flattened everything else return (dGs, Gs, scaleVals) if bScale else (dGs, Gs)", "the parallelization over the parameter groups. num_param1_groups : int The number of groups", "comm_blkSize else: blkSize1 = blkSize2 = None # wrtFilter1 & wrtFilter2 dictates block", "scaling applied (may generate overflow, but OK) ps = _np.real(_np.dot(Es, _np.dot(G, rho)) *", "+ \" than derivative columns(%d)!\" % self.Np + \" [blkSize = %.1f, nBlks=%d]\"", "cache computation\" \" *fewer* processors and *smaller* (sub-)tree\" \" (e.g. by splitting tree", "= _np.zeros((1, self.Np, self.Np)) derivWrtAnyEvec = _np.squeeze(_np.dot(dprod_dOps, rho), axis=(2,)) _fas(d2pr_dEs, [0, None, EVec.gpindices],", "evalTree[i] L, R = prodCache[iLeft], prodCache[iRight] dL1, dR1 = dProdCache1[iLeft], dProdCache1[iRight] dL2, dR2", "old_err2 = _np.seterr(invalid='ignore', over='ignore') d2pr_dOps2 = _np.squeeze(_np.dot(E, _np.dot(hGs, rho)), axis=(0, 4)) * scaleVals[:,", "= _np.seterr(invalid='ignore', over='ignore') d2pr_dOps2 = _np.squeeze(_np.dot(E, _np.dot(hGs, rho)), axis=(0, 4)) * scaleVals[:, None,", "prMxToFill is not None. bUseScaling : bool, optional Whether to use a post-scaled", "computation across multiple processors. Distribution is first performed over subtrees of evalTree (if", "1)]) # (dim**2, dim**2) x = _np.dot(_np.transpose(dop_dopLabel1[opLabel1]), x0); xv = x.view() # (nDerivCols1,dim**2)", "# keep last dProdCache1 for wrtSlice1, wrtSlice2 in wrtSlicesList: if wrtSlice1 != last_wrtSlice1:", "same as the elements of `result_tup`. The fill function computes values for only", "== \"statevec\": raise NotImplementedError(\"Unitary evolution not fully supported yet!\") # To support unitary", "add to the existing array values, which is a functionality needed to correctly", "dp_drhos[i,J0+J] = dot(E, Gs, drhoP)[0,i,J] # dp_drhos[:,J0+J] = squeeze(dot(E, Gs, drhoP),axis=(0,))[:,J] dp_drhos =", "_np.swapaxes(_np.dot(_np.transpose(devec), dp_dAnyE), 0, 1)) d2pr_dErhos2 = _np.transpose(d2pr_dErhos2, (0, 2, 1)) #Note: these 2nd", ", wrtFilter=wrtIndices) doperation = self.doperation(opLabel, wrtFilter=wrtIndices) dProdCache[i] = doperation / _np.exp(scaleCache[i]) #profiler.print_mem(\"DEBUGMEM: POINT1\");", "over the zero and single-gate-strings) for i in evalTree.get_evaluation_order(): # combine iLeft +", "numpy array Only returned when bScale == True. An array of shape S", "fInds, gInds, pslc1, pslc2, False) # TODO: remove SumInto == True cases return", "are EVec = self.sos.get_effect(elabel) # arrays, these are SPAMVecs nCircuits = Gs.shape[0] rho_wrtFilter1,", "prod_col) return _np.swapaxes(flattened_dprod, 0, 1).reshape((num_deriv_cols, dim, dim)) def hproduct(self, circuit, flat=False, wrtFilter1=None, wrtFilter2=None):", "MatrixForwardSimulator \"\"\" return MatrixForwardSimulator(self.dim, self.sos, self.paramvec) def product(self, circuit, bScale=False): \"\"\" Compute the", "to correctly handle the remainder spam label. \"\"\" pslc1 = param_slice1 pslc2 =", "*simplified* into a lists of gate-only sequences along with a mapping of final", "axis=(0,2) ) * scaleVals return _np.squeeze(_np.dot(E, _np.dot(Gs, rho)), axis=(0, 2)) * scaleVals #", "dProdCache?.shape = (#circuits,#params_to_diff_wrt,dim,dim) nDerivCols1 = dProdCache1.shape[1] nDerivCols2 = dProdCache2.shape[1] assert(wrtSlice1 is None or", "* if flat == False, an array of shape S x M x", "and blkSize nBlks = int(_np.ceil(self.Np / blkSize)) # num blocks required to achieve", "gates for use in computations. \"\"\" super(MatrixForwardSimulator, self).__init__( dim, simplified_op_server, paramvec) if self.evotype", "the yet-to-be-defined local variables # wrtSlice1 and wrtSlice2, of the parent-function scope. This", "then k-th model parameters. \"\"\" # LEXICOGRAPHICAL VS MATRIX ORDER # we do", "'e_local_slices e_global_slices num_rho_params num_e_params') # # if wrtSlices is not None: # loc_rho_slices", "can be complex # - update probability-derivative computations: dpr/dx -> d|pr|^2/dx = d(pr*pr.C)/dx", "myBlkIndices: tm = _time.time() block_wrtSlice = blocks[iBlk] dProdCache = self._compute_dproduct_cache(evalSubTree, prodCache, scaleCache, blkComm,", "return scaleVals def _rhoE_from_spamTuple(self, spamTuple): assert(len(spamTuple) == 2) if isinstance(spamTuple[0], _Label): rholabel, elabel", "operation sequences. This routine fills a 1D array, `mxToFill` with the probabilities corresponding", "applied (may generate overflow, but OK) ps = _np.real(_np.dot(Es, _np.dot(G, rho)) * scale)", "Gs[gInds], dGs1[gInds], scaleVals[gInds], wrtSlice1), add=sumInto) if deriv2MxToFill is not None: _fas(deriv2MxToFill, [fInds, pslc2],", "subtrees] _mpit.gather_indices(subtreeElementIndices, subTreeOwners, mxToFill, [], 0, comm) #note: pass mxToFill, dim=(KS), so gather", "(in parallel) iterate through the subtrees. It can often be useful to have", "may overflow but OK def _dprobs_from_rhoE(self, spamTuple, rho, E, Gs, dGs, scaleVals, wrtSlice=None):", "(wrtSlice1 == wrtSlice2): dProdCache2 = dProdCache1; dGs2 = dGs1 else: dProdCache2 = self._compute_dproduct_cache(", "# d2pr/d(opLabel1)_mn d(opLabel2)_ij = sum E_k [dprod/d(opLabel1)_mn d(opLabel2)_ij]_kl rho_l # d2pr/d(rho)_i d(opLabel)_mn =", "of :class:`Label` objects giving the *simplified* effect labels. circuit : Circuit or tuple", "evaluation tree, `evalTree`. An initial list of (general) :class:`Circuit` objects is *simplified* into", "zero-operation sequences are zero. hProdCache[i] = _np.zeros(hessn_shape) else: hoperation = self.hoperation(opLabel, wrtFilter1=wrtIndices1, wrtFilter2=wrtIndices2)", "product and derivatives-of-product calculations. This is contained in a class separate from Model", "but OK if infs occur here _np.seterr(**old_err) if bScale: return Gs, scaleVals else:", "if bReturnProds: Gs = evalTree.final_view(prodCache, axis=0) #shape == ( len(circuit_list), dim, dim ),", "G1 ... G(M-1) tensor (G(M+1) ... GN)^T vec( d2G(M)/dkl*dji ) # noqa #", "self.dim # Note: dProdCache?.shape = (#circuits,#params_to_diff_wrt,dim,dim) nDerivCols1 = dProdCache1.shape[1] nDerivCols2 = dProdCache2.shape[1] assert(wrtSlice1", "j-th model parameter. derivative : numpy array only returned if returnDeriv == True.", "d2pr_dOps2 = _np.empty((1, self.Np, self.Np)) for i in range(self.Np): for j in range(self.Np):", "returned derivative array (see below). wrtFilter1, wrtFilter2 : list of ints, optional If", "those of the sub-trees. _warnings.warn(\"Increased speed could be obtained\" \" by giving hproduct", "dGs2[gInds], scaleVals[gInds], wrtSlice2), add=sumInto) _fas(mxToFill, [fInds, pslc1, pslc2], self._hprobs_from_rhoE( spamTuple, rho, E, Gs[gInds],", "valid. # Below we use E(i,j) to denote the elementary matrix where all", "in range(self.Np): dpr_dOps[0, i] = float(_np.dot(E, _np.dot(dprod_dOps[i], rho))) #Derivs wrt SPAM if returnDeriv:", "drhoP),axis=(0,))[:,J] dp_drhos = _np.zeros((nCircuits, nDerivCols)) _fas(dp_drhos, [None, rho_gpindices], _np.squeeze(_np.dot(_np.dot(E, Gs), rhoVec.deriv_wrt_params(rho_wrtFilter)), axis=(0,)) *", "= evalTree.final_view(dProdCache2, axis=0) hProdCache = self._compute_hproduct_cache( evalTree, prodCache, dProdCache1, dProdCache2, scaleCache, comm, wrtSlice1,", "ExM numpy array that is filled with probability derivatives, similar to bulk_fill_dprobs(...), but", "Parameters ---------- evalTree : EvalTree given by a prior call to bulk_evaltree. Specifies", "-- parameterizations of operation matrices and SPAM vectors) access to these fundamental operations.", "local subtree for iSubTree in mySubTreeIndices: evalSubTree = subtrees[iSubTree] felInds = evalSubTree.final_element_indices(evalTree) #Free", "class\"\"\" #*************************************************************************************************** # Copyright 2015, 2019 National Technology & Engineering Solutions of Sandia,", "where M is the number of model parameters. Parameters ---------- spamTuple : (rho_label,", "some arrays. The arrays that are filled internally to `calc_and_fill_fn` must be the", "# for i in range(len(self.effects)) ] # # return PrepEffectFilter(rho_local_slices=loc_rho_slices, # rho_global_slices=global_rho_slices, #", "(if it is split). Returns ------- None \"\"\" #get distribution across subtrees (groups", "operation labels. Parameters ---------- circuit : Circuit or tuple of operation labels The", "given by evalTree column-by-column. This routine can be useful when memory constraints make", "E, dot( dGs, rho ) )[0,i,j,0] # dp_dOps = squeeze( dot( E, dot(", "in a single flattened gate (ordering as numpy.flatten) - M == length of", "= A tensor B^T * vec( X ) # if vec(.) stacks columns", "gatherMemLimit) if prMxToFill is not None: _mpit.gather_indices(subtreeElementIndices, subTreeOwners, prMxToFill, [], 0, comm) if", "s.t. GM == gatelabel1} sum_{L s.t. GL == gatelabel2, M < L} #", "split tree. \"\"\" dim = self.dim # Note: dProdCache?.shape = (#circuits,#params_to_diff_wrt,dim,dim) nDerivCols1 =", "tool used by model objects to perform product and derivatives-of-product calculations. This is", "but OK def _dprobs_from_rhoE(self, spamTuple, rho, E, Gs, dGs, scaleVals, wrtSlice=None): if self.evotype", "_np.seterr(**old_err2) # may overflow, but OK ; shape == (len(circuit_list), nDerivCols, nDerivCols) #", "the current # gate (so we only need to compute this gate hessian", "1 x M x M array, where M is the number of model", "fully supported yet!\") rholabel, elabel = spamTuple rhoVec = self.sos.get_prep(rholabel) # distinct from", "* X * B ) = A tensor B^T * vec( X )", "their Hessians. PSMALL = 1e-100 DSMALL = 1e-100 HSMALL = 1e-100 class MatrixForwardSimulator(ForwardSimulator):", "_np.clip(mxToFill, clipTo[0], clipTo[1], out=mxToFill) # in-place clip if check: self._check(evalTree, mxToFill, clipTo=clipTo) def", "+= d2pr_dErhos1 + d2pr_d2Es + d2pr_dEs2 # wrt E ret += d2pr_drhos1 +", "wrtSlice2, hprobs dProdCache1 = dGs1 = None # free mem def _fill_result_tuple(self, result_tup,", "add=sumInto) _fas(mxToFill, [fInds, pslc1, pslc2], self._hprobs_from_rhoE( spamTuple, rho, E, Gs[gInds], dGs1[gInds], dGs2[gInds], hGs[gInds],", "-DSMALL: _warnings.warn(\"Scaled dProd small in order to keep prod managable.\") elif _np.count_nonzero(dProdCache[i]) and", "because you want to computed their probabilites). These are a \"simplified\" circuits in", "* scale # may generate overflow, but OK if clipTo is not None:", "bool, optional When True, return a scaling factor (see below). Returns ------- product", "if (wrtSlice is None) \\ else _slct.length(wrtSlice) deriv_shape = (nDerivCols, dim, dim) cacheSize", "wrtSlice = _slct.list_to_slice(wrtFilter) else: wrtSlice = None profiler.mem_check(\"bulk_fill_dprobs: begin (expect ~ %.2fGB)\" %", "Copyright 2015, 2019 National Technology & Engineering Solutions of Sandia, LLC (NTESS). #", "(nDerivCols1,dim**2) xv.shape = (nDerivCols1, dim, dim) # (reshape without copying - throws error", "if not bScale: old_err = _np.seterr(over='ignore', invalid='ignore') Gs = _np.swapaxes(_np.swapaxes(Gs, 0, 2) *", "== nDerivCols1) assert(wrtSlice2 is None or _slct.length(wrtSlice2) == nDerivCols2) hessn_shape = (nDerivCols1, nDerivCols2,", "+= cache_size # scale cache mem += cache_size # scale vals elif fnName", "(e.g. by splitting tree beforehand), as there\" \" are more cpus than derivative", "if self.evotype == \"statevec\": raise NotImplementedError(\"Unitary evolution not fully supported yet!\") #Compute probability", "we track owners #if mySubSubComm.Get_rank() > 0: myDeriv2ColSlice = slice(0,0) # #don't compute", "speeding up the calcs of the given # wrtSlicesList last_wrtSlice1 = None #", "(e.g. may include instrument elements like 'Imyinst_0') returnPr : bool when set to", "gl) in enumerate(revOpLabelList): if gl != opLabel: continue # loop over locations of", "None] E = _np.conjugate(_np.transpose(self.sos.get_effect(elabel).todense() [:, None])) # convention: E has shape (1,N) else:", "evalTree column-by-column. This routine can be useful when memory constraints make constructing the", "entries in a single flattened gate (ordering as numpy.flatten) - M == length", "tuple as a 1 x M numpy array, where M is the number", "copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 or in the LICENSE file in", "else None #TODO: just allow slices as argument: wrtFilter -> wrtSlice? prodCache, scaleCache", "bReturnDProdsAndProds=False, bScale=False, comm=None, wrtFilter1=None, wrtFilter2=None): \"\"\" Return the Hessian of many operation sequence", "A * vec( E(0,1) ) # In general: vec( A * X *", "= _np.swapaxes(_np.swapaxes(dGs2, 0, 1).reshape((nDerivCols2, nCircuits * dim**2)), 0, 1) hGs = _np.rollaxis(_np.rollaxis(hGs, 0,", "the full evaluation tree into. num_subtree_proc_groups : int The number of processor groups", "is not None. Returns ------- derivative : numpy array a 1 x M", "_np.swapaxes(_np.swapaxes(hGs, 0, 4) * scaleVals, 0, 4) # convert nans to zero, as", "the number of entries in a single flattened gate (ordering same as numpy.flatten),", "(** doesn't depend on eIndex **) -- TODO: should also conjugate() here if", "wrt gates return ret def _check(self, evalTree, prMxToFill=None, dprMxToFill=None, hprMxToFill=None, clipTo=None): # compare", "super(MatrixForwardSimulator, self).__init__( dim, simplified_op_server, paramvec) if self.evotype not in (\"statevec\", \"densitymx\"): raise ValueError((\"Evolution", "product of the operation matrices. scale : float Only returned when bScale ==", "of floating-point probabilities, corresponding to the elements of `elabels`. \"\"\" assert(time is None),", "bulk_evaltree. Specifies the *simplified* gate strings to compute the bulk operation on. clipTo", ": dictionary a dictionary with keys == spam labels and values which are", "+ or - inf anyway... dp_dOps[_np.isnan(dp_dOps)] = 0 #SPAM ------------- # Get: dp_drhos[i,", "Compute all probabilities all at once so they're not repeatedly # computed for", "None profiler.mem_check(\"bulk_fill_dprobs: begin (expect ~ %.2fGB)\" % (mxToFill.nbytes / (1024.0**3))) ## memory profiling", "be obtained\" \" by giving dproduct cache computation\" \" *fewer* processors and *smaller*", "* scaleVals[:, None, None]) # overflow OK d2pr_drhos2 = _np.transpose(d2pr_drhos2, (0, 2, 1))", "_nla.norm(hprMxToFill[fInds] - check_vhp))) # pragma: no cover def bulk_fill_probs(self, mxToFill, evalTree, clipTo=None, check=False,", "_np.transpose(d2pr_drhos1, (0, 2, 1)) else: drho = rhoVec.deriv_wrt_params(rho_wrtFilter1) d2pr_drhos2 = _np.zeros((nCircuits, nDerivCols2, nDerivCols1))", "import objgraph # objgraph.show_growth(limit=50) #get distribution across subtrees (groups if needed) subtrees =", "N == the number of entries in a single flattened gate (ordering as", "fairly common occurrence, and doesn't merit a warning # ------------------------------------------------------------------ if evalTree.is_split(): _warnings.warn(\"Ignoring", "operation labels. Note: LinearOperator matrices are multiplied in the reversed order of the", "Specifies the operation sequences to compute the bulk operation on. flat : bool,", "x GxG dLdRa = _np.swapaxes(_np.dot(dL1, dR2), 1, 2) dLdRb = _np.swapaxes(_np.dot(dL2, dR1), 1,", "prep/effect pairs. The evaluation tree organizes how to efficiently compute the gate-only sequences.", "pairs. The evaluation tree organizes how to efficiently compute the gate-only sequences. This", "gate.has_nonzero_hessian(): hop_dopLabels[opLabel] = gate.hessian_wrt_params( gate_wrtFilters1[opLabel], gate_wrtFilters2[opLabel]) # Allocate memory for the final result", "= sum E_k prod_ki # dpr/d(E)_i = sum prod_il rho_l rholabel, elabel =", "non-zero when the spam vectors have # a more than linear dependence on", "scaleVals : numpy array Only returned when bScale == True. An array of", "vals elif fnName == \"bulk_fill_dprobs\": mem += cache_size * wrtLen1 * dim *", "shape S*N x M x M where - N == the number of", "parameters if dGs1 is dGs2 and wrtSlice1 == wrtSlice2: # TODO: better check", "== no gate prodCache[i] = _np.identity(dim) # Note: scaleCache[i] = 0.0 from initialization", "is hprod_dGates for ith string if not bScale: old_err = _np.seterr(over='ignore', invalid='ignore') Gs", "of selected gate-set parameters (by wrtFilter1 and wrtFilter2). evalTree : EvalTree given by", "* B[0,1] ) = B^T tensor A * vec( E(0,1) ) # In", "(relatively little mem required) prods = {} ident = _np.identity(dim) for (i, opLabel1)", "# d2pr_drhos[i,j,J0+J] = dot(E, dGs, drhoP)[0,i,j,J] # d2pr_drhos[:,:,J0+J] = squeeze(dot(E, dGs, drhoP),axis=(0,))[:,:,J] drho", "cpus than derivative columns.\") # Use comm to distribute columns allDerivColSlice = slice(0,", "matrixOf(circuit[i]) = matrixOf(circuit[iLeft]) * matrixOf(circuit[iRight]) (iRight, iLeft) = evalTree[i] L, R = prodCache[iLeft],", "DSMALL = 1e-100 HSMALL = 1e-100 class MatrixForwardSimulator(ForwardSimulator): \"\"\" Encapsulates a calculation tool", "length-E numpy array that is filled with probabilities, just like in bulk_fill_probs(...). derivMxToFill1,", "allocate final result memory hProdCache = _np.zeros((cacheSize,) + hessn_shape) # Use comm to", "prep and POVM effect used to compute the probability. circuit : Circuit or", "are already sized/filtered) -------- assert(dGs1.shape[1] == nDerivCols1), \"dGs1 must be pre-filtered!\" assert(dGs2.shape[1] ==", "filled quantity combining both spam and gate-sequence indices # gInds = \"gate sequence", "to only that gate's parameters and fill the appropriate # columns of flattened_dprod.", "if check: self._check(evalTree, prMxToFill, deriv1MxToFill, mxToFill, clipTo) def bulk_hprobs_by_block(self, evalTree, wrtSlicesList, bReturnDProbs12=False, comm=None):", "2, 0, 3)) scale = scaleCache[i] - (scaleCache[iLeft] + scaleCache[iRight]) if abs(scale) >", "is None) else _slct.length(wrtFilter2) nCircuits = evalTree.num_final_strings() # len(circuit_list) wrtSlice1 = _slct.list_to_slice(wrtFilter1) if", "e_offset[eIndex]:e_offset[eIndex+1], e_offset[rhoIndex]:e_offset[rhoIndex+1]] = # dEP^T * prod[i,:,:] * drhoP # d2pr_dErhos[i,J0+J,K0+K] = sum", "used_operations[l]) #Cache partial products (relatively little mem required) prods = {} ident =", "flat=False, bReturnDProdsAndProds=False, bScale=False, comm=None, wrtFilter1=None, wrtFilter2=None): \"\"\" Return the Hessian of many operation", "= scale * _np.dot(E, prod) dpr_drhos = _np.zeros((1, self.Np)) _fas(dpr_drhos, [0, self.sos.get_prep(rholabel).gpindices], _np.dot(derivWrtAnyRhovec,", "blkSize2 = comm_blkSize if (blkSize2 is None) \\ else min(comm_blkSize, blkSize2) # override", "spamTuple, circuit, returnPr, clipTo): \"\"\" Compute the derivative of a probability generated by", "intermediate memory required. profiler : Profiler, optional A profiler object used for to", "specified if wrtFilter1 is None and wrtFilter2 is None: blkSize1 = wrtBlockSize1 #", "returned probability. time : float, optional The *start* time at which `circuit` is", "= _slct.list_to_slice(wrtFilter) if (wrtFilter is not None) else None #TODO: just allow slices", "rho[m,0] # d2pr_dOps2[i,j,k] = sum_l E[0,l] dot( dGs, rho )[i,j,k,l,0] # d2pr_dOps2[i,j,k] =", "for opLabel in uniqueOpLabels: gate = self.sos.get_operation(opLabel) op_wrtFilter, gpindices = self._process_wrtFilter(wrtFilter, gate) dop_dopLabel", "* scale)**2) else: # evotype == \"densitymx\" # probability, with scaling applied (may", "= _np.transpose(d2pr_dEs1, (0, 2, 1)) else: d2pr_dEs2 = _np.zeros((nCircuits, nDerivCols2, nDerivCols1)) dp_dAnyE =", "or _slct.length(wrtSlice1) == nDerivCols1) assert(wrtSlice2 is None or _slct.length(wrtSlice2) == nDerivCols2) hessn_shape =", "nBlks1 = int(_np.ceil(self.Np / blkSize1)) nBlks2 = int(_np.ceil(self.Np / blkSize2)) # num blocks", "bUseScaling=False, time=None): \"\"\" Compute probabilities of a multiple \"outcomes\" (spam-tuples) for a single", "tree splitting in product cache calc.\") cacheSize = len(evalTree) prodCache = _np.zeros((cacheSize, dim,", "if returnDeriv: # same as in dpr(...) dpr_dOps = _np.empty((1, self.Np)) for i", "nParams[opLabel]) if _slct.length(gpindices) > 0: # works for arrays too # Compute the", "= self._compute_dproduct_cache( evalTree, prodCache, scaleCache, comm, wrtSlice1) dGs1 = evalTree.final_view(dProdCache1, axis=0) last_wrtSlice1 =", "= vgs x vgs x GxG dLdRa = _np.swapaxes(_np.dot(dL1, dR2), 1, 2) dLdRb", "trumps since we've renormed to keep all the products within decent bounds #assert(", "e_offset[rhoIndex]:e_offset[rhoIndex+1]] = # dEP^T * prod[i,:,:] * drhoP # d2pr_dErhos[i,J0+J,K0+K] = sum jk", "specified sequence of operation labels. Note: LinearOperator matrices are multiplied in the reversed", "distributed) prodCache, scaleCache = self._compute_product_cache(evalTree, comm) scaleVals = self._scaleExp(evalTree.final_view(scaleCache)) Gs = evalTree.final_view(prodCache, axis=0)", "sequence of operation labels. flat : bool, optional Affects the shape of the", "= _np.swapaxes(_np.swapaxes(hGs, 0, 4) * scaleVals, 0, 4) # convert nans to zero,", "_time.time() old_err = _np.seterr(over='ignore') rho, E = self._rhoE_from_spamTuple(spamTuple) if prMxToFill is not None:", "PSMALL and prodCache[i].min() > -PSMALL: nL, nR = max(_nla.norm(L), _np.exp(-scaleCache[iLeft]), 1e-300), max(_nla.norm(R), _np.exp(-scaleCache[iRight]),", "myHessianSlice2) # pass None as comm, *not* mySubSubComm, since we can't do any", "the number of operation sequences - G == the linear dimension of a", "this function iterates over these computed blocks, in the order given by `wrtSlicesList`.", "int \"\"\" return int(1.3 * nCircuits) def construct_evaltree(self, simplified_circuits, numSubtreeComms): \"\"\" Constructs an", "profiler=None, gatherMemLimit=None): \"\"\" Compute the outcome probability-derivatives for an entire tree of gate", "= self.dproduct(circuit) assert(dprod_dOps.shape[0] == self.Np) if returnDeriv: # same as in dpr(...) dpr_dOps", "if self.sos.get_prep(rholabel).has_nonzero_hessian(): derivWrtAnyRhovec = scale * _np.dot(E, prod) # may overflow, but OK", "(wrtLen1 + wrtLen2) # dprobs1 & dprobs2 mem += cache_size * wrtLen1 *", "Gs[gInds], dGs1[gInds], dGs2[gInds], hGs[gInds], scaleVals[gInds], wrtSlice1, wrtSlice2), add=sumInto) _np.seterr(**old_err) #Set wrtBlockSize to use", "operation on. bScale : bool, optional When True, return a scaling factor (see", "None and mySubComm.Get_size() > 1: _warnings.warn(\"Too many processors to make use of in", "_np.seterr(**old_err) return scaleVals def _rhoE_from_spamTuple(self, spamTuple): assert(len(spamTuple) == 2) if isinstance(spamTuple[0], _Label): rholabel,", "relevant_gpindices[0] + 1) elif len(relevant_gpindices) == 0: #Don't return a length-0 list, as", "operation sequence dGs = evalTree.final_view(dProdCache, axis=0) #shape == ( len(circuit_list), nDerivCols, dim, dim", "in the string which match the current # gate (so we only need", "+ np2 - 1) // np2 # ceiling(num_params / np2) mem = 0", "drhoP[k,K] # d2pr_dErhos[i,J0+J,K0+K] = sum j dEPT[J,j] dot(prod,drhoP)[i,j,K] # d2pr_dErhos[i,J0+J,K0+K] = dot(dEPT,prod,drhoP)[J,i,K] #", "loc_e_slices] # tmp_offsets = [ sum(tmp_num_params[0:i]) for i in range(len(self.effects)+1) ] # global_e_slices", "a matrix for each given (i,j,k,l) # noqa # vec( d2prod/d(opLabel1)_kl*d(opLabel2)_ij ) =", "#collect/gather results subtreeElementIndices = [t.final_element_indices(evalTree) for t in subtrees] _mpit.gather_indices(subtreeElementIndices, subTreeOwners, mxToFill, [],", "to overflow G = self.product(circuit, False) if self.evotype == \"statevec\": ps = _np.real(_np.abs(_np.dot(Es,", "compute the derivative of the entire operation sequence # with respect to only", "for i-th operation sequence dGs1 = evalTree.final_view(dProdCache1, axis=0) dGs2 = evalTree.final_view(dProdCache2, axis=0) #shape", "E, Gs[gInds], scaleVals[gInds]), add=sumInto) if deriv1MxToFill is not None: _fas(deriv1MxToFill, [fInds, pslc1], self._dprobs_from_rhoE(", "== the number of entries in a single flattened gate (ordered as numpy.flatten)", "subtrees to split the full evaluation tree into. num_subtree_proc_groups : int The number", "== \"bulk_hprobs_by_block\": #Note: includes \"results\" memory since this is allocated within # the", "(i.e. evalTree.num_final_elements()) and M1 & M2 are the number of selected gate-set parameters", "to final values scaleVals = self._scaleExp(evalSubTree.final_view(scaleCache)) Gs = evalSubTree.final_view(prodCache, axis=0) #( nCircuits, dim,", "with respect to only that gate's parameters and fill the appropriate # columns", "which we *used* to assume gave no contribution since we assume all gate", "== the linear dimension of a operation matrix (G x G operation matrices)", "inds1, inds2] += xv if flat: return flattened_d2prod # axes = (vectorized_op_el_index, model_parameter1,", "circuit[i] = circuit[iLeft] + circuit[iRight], but we want: # since then matrixOf(circuit[i]) =", "may be duplicates (a list, not a set) # since all scaled gates", "parameters into. Computation will be automatically parallelized over these groups. num_final_strs : int", "return to save copying) some arrays. The arrays that are filled internally to", "= _np.zeros((cacheSize,) + hessn_shape) # Use comm to distribute columns allDeriv1ColSlice = slice(0,", "of gate strings. Similar to `bulk_fill_probs(...)`, but fills a 3D array with probability-Hessians", "shape (N,1) rho = self.sos.get_prep(rholabel).todense()[:, None] Es = [self.sos.get_effect(elabel).todense()[:, None] for elabel in", "label == no gate hProdCache[i] = _np.zeros(hessn_shape) elif not self.sos.get_operation(opLabel).has_nonzero_hessian(): #all gate elements", "dpr_dOps d2pr_drhos = _np.zeros((1, self.Np, self.Np)) _fas(d2pr_drhos, [0, None, self.sos.get_prep(rholabel).gpindices], _np.dot(_np.dot(E, dprod_dOps), rhoVec.deriv_wrt_params())[0])", "= Gs = prodCache = scaleCache = None #Fill cache info prodCache, scaleCache", "doesn't involve gate derivatives d2pr_dErhos2 = _np.transpose(d2pr_dErhos1, (0, 2, 1)) else: d2pr_dErhos2 =", ": list A list of Circuits or tuples of operation labels which specify", "array, `mxToFill` with the probabilities corresponding to the *simplified* operation sequences found in", "bReturnDProbs12=False, comm=None): \"\"\" Constructs a generator that computes the 2nd derivatives of the", "True. An array of shape S such that scaleVals[i] contains the multiplicative scaling", "to (see wrtBlockSize). wrtFilter1, wrtFilter2 : list of ints, optional If not None,", "+= cache_size # scale vals else: raise ValueError(\"Unknown subcall name: %s\" % fnName)", "would be no memory savings from using a split tree. In short, parallelization", "# http://www.apache.org/licenses/LICENSE-2.0 or in the LICENSE file in the root pyGSTi directory. #***************************************************************************************************", "squeeze( dot( E, dot(Gs, rho)), axis=(0,2) ) * scaleVals return _np.squeeze(_np.dot(E, _np.dot(Gs, rho)),", "sub_vdp #def _get_filter_info(self, wrtSlices): # \"\"\" # Returns a \"filter\" object containing info", "OK ; shape == (len(circuit_list), nDerivCols, nDerivCols) # may also give invalid value", "product\") def calc_and_fill(spamTuple, fInds, gInds, pslc1, pslc2, sumInto): \"\"\" Compute and fill result", "= _np.zeros((nCircuits, nDerivCols1, nDerivCols2)) _fas(d2pr_d2Es, [None, E_gpindices1, E_gpindices2], _np.tensordot(dp_dAnyE, self.sos.get_effect(elabel).hessian_wrt_params( E_wrtFilter1, E_wrtFilter2), (1,", "sequence \"\"\" dim = self.dim gate = self.sos.get_operation(opLabel) op_wrtFilter1, gpindices1 = self._process_wrtFilter(wrtFilter1, gate)", "Only returned if bReturnDProdsAndProds == True. * if flat == False, two arrays", "defined by: d12[iSpamLabel,iOpStr,p1,p2] = dP/d(p1)*dP/d(p2) where P is is the probability generated by", "opLabel in uniqueOpLabels: gate = self.sos.get_operation(opLabel) op_wrtFilter, gpindices = self._process_wrtFilter(wrtFilter, gate) dop_dopLabel =", "opLabel == \"\": # special case of empty label == no gate prodCache[i]", "but ok dGs1 = _np.swapaxes(_np.swapaxes(dGs1, 0, 3) * scaleVals, 0, 3) # may", "set to zero since we can't tell whether it's + or - inf", "columns # vec( A * E(0,1) * B ) = vec( mx w/", "_np.swapaxes(_np.dot(dL1, dR2), 1, 2) dLdRb = _np.swapaxes(_np.dot(dL2, dR1), 1, 2) dLdR_sym = dLdRa", "dim ) #Compute all requested derivative columns at once self._fill_result_tuple((prMxToFill, deriv1MxToFill, deriv2MxToFill, mxToFill),", "= dot(squeeze(dot(Gs, rho),2), dEP)[i,J] # dp_dEs[:,J0+J] = dot(squeeze(dot(Gs, rho),axis=(2,)), dEP)[:,J] dp_dEs = _np.zeros((nCircuits,", "evalTree.final_view(dProdCache, axis=0) #shape == ( len(circuit_list), nDerivCols, dim, dim ), # dGs[i] is", "G(M-1) tensor (G(M+1) ... GN)^T vec( dG(M)/dkl ) ) )^T vec( dG(L)/dij )", "Re(dpr/dx*pr.C) , where dpr/dx is the usual density-matrix-mode probability # (TODO in FUTURE)", "wrtFilter argument relevant for a single object (gate or spam vec) \"\"\" #Create", "%g, exp %g\\n%s\" % (i,p,norm(G),total_exp,str(G)) # if _np.isnan(p): raise ValueError(\"STOP\") if clipTo is", "are SPAMVecs d2prod_dGates = self.hproduct(circuit) assert(d2prod_dGates.shape[0] == d2prod_dGates.shape[1]) d2pr_dOps2 = _np.empty((1, self.Np, self.Np))", "gate's parameters and fill the appropriate # columns of flattened_dprod. uniqueOpLabels = sorted(list(set(revOpLabelList)))", "\"\"\" Computes a tree of product derivatives in a linear cache space. Will", "# product cache # mem += cache_size # scale cache # mem +=", "of gates, starting with G0 # nG = norm(G); G /= nG; total_exp", "E_gpindices2], _np.tensordot(dp_dAnyE, self.sos.get_effect(elabel).hessian_wrt_params( E_wrtFilter1, E_wrtFilter2), (1, 0))) # _np.einsum('ij,jkl->ikl', dp_dAnyE, self.sos.get_effect(elabel).hessian_wrt_params( # E_wrtFilter1,", "_collections.namedtuple( # 'PrepEffectFilter', 'rho_local_slices rho_global_slices ' + # 'e_local_slices e_global_slices num_rho_params num_e_params') #", "is dGs2 and wrtSlice1 == wrtSlice2: # TODO: better check for equivalence: maybe", "Tr( |rho><E| * prod ) = sum E_k prod_kl rho_l # d2pr/d(opLabel1)_mn d(opLabel2)_ij", "LRproduct = _np.kron(leftProds[i], rightProdsT[N - 1 - i]) # (dim**2, dim**2) _fas(flattened_dprod, [None,", "pslc1, pslc2, sumInto): \"\"\" Compute and fill result quantities blocks for given arguments", "# d2pr_dOps2 = squeeze( dot( E, dot( dGs, rho ) ), axis=(0,4)) old_err2", "# free mem #gather results tm = _time.time() _mpit.gather_slices(blocks, blkOwners, mxToFill, [felInds], 1,", "is None and wrtFilter2 is None) # cannot specify both wrtFilter and blkSize", "operation sequence product. scaleVals : numpy array Only returned when bScale == True.", "of the values for this spam label (given by the subsequent arguments, except", "to compute the bulk operation on. flat : bool, optional Affects the shape", "= EVec.deriv_wrt_params(E_wrtFilter2) _fas(d2pr_dErhos2, [None, E_gpindices2, rho_gpindices1], _np.swapaxes(_np.dot(_np.transpose(devec), dp_dAnyE), 0, 1)) d2pr_dErhos2 = _np.transpose(d2pr_dErhos2,", "probabilities. comm : mpi4py.MPI.Comm, optional When not None, an MPI communicator for distributing", "N = len(revOpLabelList) for m, opLabel1 in enumerate(revOpLabelList): inds1 = gpindices1[opLabel1] nDerivCols1 =", "dprod_dOps for ith string if not bScale: old_err = _np.seterr(over='ignore', invalid='ignore') Gs =", "pre-filtered!\" # Get: d2pr_drhos[i, j, rho_gpindices] = dot(E,dGs[i,j],drho/drhoP)) # d2pr_drhos[i,j,J0+J] = sum_kl E[0,k]", "entire tree of operation sequences. This routine fills a 1D array, `mxToFill` with", "warning # ------------------------------------------------------------------ if evalTree.is_split(): _warnings.warn(\"Ignoring tree splitting in product cache calc.\") cacheSize", "functions of the probabilities. comm : mpi4py.MPI.Comm, optional When not None, an MPI", "lOp in circuit: G = _np.dot(self.sos.get_operation(lOp).todense(), G) # LEXICOGRAPHICAL VS MATRIX ORDER return", "is a fairly common occurrence, and doesn't merit a warning # ------------------------------------------------------------------ if", "appropriate for it. # Use comm only for speeding up the calcs of", "= dProdCache2[iLeft], dProdCache2[iRight] hL, hR = hProdCache[iLeft], hProdCache[iRight] # Note: L, R =", "the i-th entry of the flattened product with respect to the k-th then", "scaleVals = _np.exp(scaleExps) # may overflow, but OK if infs occur here _np.seterr(**old_err)", "in a linear cache space. Will use derivative rows and columns and then", "and d2pr_d2Es terms are always zero _np.seterr(**old_err) if returnDeriv: if returnPr: return ret,", "all the derivative columns, essentially taking # a derivative of only a *subset*", "_np.dot(E, prod) dpr_drhos = _np.zeros((1, self.Np)) _fas(dpr_drhos, [0, self.sos.get_prep(rholabel).gpindices], _np.dot(derivWrtAnyRhovec, rhoVec.deriv_wrt_params())) # may", "special case of empty label == no gate hProdCache[i] = _np.zeros(hessn_shape) elif not", "hProdCache[iRight] # Note: L, R = GxG ; dL,dR = vgs x GxG", "wrtFilter'd indices gpindices = obj.gpindices_as_array() for ii, i in enumerate(wrtFilter): if i in", "prodCache, scaleCache, comm, wrtSlice1) dGs1 = evalTree.final_view(dProdCache1, axis=0) last_wrtSlice1 = wrtSlice1 if (wrtSlice1", "and to control memory usage. Cannot be specified in conjuction with wrtBlockSize. wrtBlockSize", "probability # print \"%d: p = %g, norm %g, exp %g\\n%s\" % (i,p,norm(G),total_exp,str(G))", "self.evotype == \"statevec\": raise NotImplementedError(\"Unitary evolution not fully supported yet!\") #Compute probability and", "the (j,k)-th entry of the product with respect to the i-th model parameter.", "use of a tree being # split because there's no good way to", "comm) # Get slice into entire range of model params so that #", "available processors. Returns ------- MatrixEvalTree \"\"\" evTree = _MatrixEvalTree() evTree.initialize(simplified_circuits, numSubtreeComms) return evTree", "(e.g. ones which use entirely different -- non-gate-local -- parameterizations of operation matrices", "#eval on each local subtree for iSubTree in mySubTreeIndices: evalSubTree = subtrees[iSubTree] #Free", "processed parameter filters for multiple uses below gpindices1 = {}; gate_wrtFilters1 = {}", "dprod_dOps for ith string if not bScale: old_err = _np.seterr(over='ignore', invalid='ignore') # may", "else: d2pr_d2rhos = 0 if self.sos.get_effect(elabel).has_nonzero_hessian(): dp_dAnyE = _np.dot(Gs, rho).squeeze(2) * scaleVals[:, None]", "scale vals # #elif fnName == \"bulk_hproduct\": # mem += cache_size * num_params**2", "# import objgraph # objgraph.show_growth(limit=50) #get distribution across subtrees (groups if needed) subtrees", "or zero-operation sequences are zero. hProdCache[i] = _np.zeros(hessn_shape) else: hoperation = self.hoperation(opLabel, wrtFilter1=wrtIndices1,", "or `(rowSlice, colSlice, dprobs12)` (the latter if `bReturnDProbs12 == True`). `rowSlice` and `colSlice`", "dGs[i,j,k,l] rho[l,0] # d2pr_dEs[i,j,J0+J] = sum_k dEP[k,J] dot(dGs, rho)[i,j,k,0] # d2pr_dEs[i,j,J0+J] = dot(", "# (dim**2, nParams in wrtFilter for opLabel) if flat: return flattened_dprod else: #", "the i-th operation sequence product. scaleVals : numpy array Only returned when bScale", "a trace or other linear operation to be done prior to the scaling.", "these since their required memory is fixed ## (and dominated) by the output", "empty label == no gate dProdCache[i] = _np.zeros(deriv_shape) else: #doperation = self.dproduct( (opLabel,)", "dGs2 and wrtSlice1 == wrtSlice2: # TODO: better check for equivalence: maybe let", "wrtSlicesList last_wrtSlice1 = None # keep last dProdCache1 for wrtSlice1, wrtSlice2 in wrtSlicesList:", "number of derivative columns to compute *products* for simultaneously. None means compute all", "derivatives, since matrices can be complex # - update probability-derivative computations: dpr/dx ->", "/= _np.exp(scale) if hProdCache[i].max() < HSMALL and hProdCache[i].min() > -HSMALL: _warnings.warn(\"Scaled hProd small", "Allocate memory for the final result num_deriv_cols1 = self.Np if (wrtFilter1 is None)", "rho_l # dpr/d(opLabel)_ij = sum E_k [dprod/d(opLabel)_ij]_kl rho_l # dpr/d(rho)_i = sum E_k", "vectorized derivatives of each of the product components (i.e. prod_kl) with # respect", "fixed ## (and dominated) by the output array size. Could throw more informative", "cols, rows = flattened all else dGs2 = _np.swapaxes(_np.swapaxes(dGs2, 0, 1).reshape((nDerivCols2, nCircuits *", "keep all the products within decent # bounds #assert( len( (_np.isnan(hGs)).nonzero()[0] ) ==", "computation across multiple processors. Distribution is first done over the set of parameters", "from ..tools.matrixtools import _fas from .profiler import DummyProfiler as _DummyProfiler from .label import", "= evalTree.generate_circuit_list(permute=False) # raw operation sequences for spamTuple, (fInds, gInds) in evalTree.spamtuple_indices.items(): circuit_list", "# can't deal w/\"custom\" spam label... rho, E = self._rhoE_from_spamTuple(spamTuple) rhoVec = self.sos.get_prep(rholabel)", "optional If not None, a list of integers specifying which parameters to include", "hessian calculation (i.e. for l==m) then # it could make sense to iterate", "compute_dproduct_cache\", tm) profiler.mem_check(\"bulk_fill_dprobs: post compute dproduct\") #Compute all requested derivative columns at once", "iBlk2 in myBlk2Indices: blk_wrtSlice2 = blocks2[iBlk2] if blk_wrtSlice1 == blk_wrtSlice2: dProdCache2 = dProdCache1;", "calculations across multiple processors and to control memory usage. Cannot be specified in", "an array of shape S x M x G x G, where: -", "probabilities and their derivatives (see below). bScale : bool, optional When True, return", "%g - %g = %g\" % (_nla.norm(dprMxToFill[fInds]), _nla.norm(check_vdp), _nla.norm(dprMxToFill[fInds] - check_vdp))) # pragma:", "len(circuit_list) wrtSlice1 = _slct.list_to_slice(wrtFilter1) if (wrtFilter1 is not None) else None wrtSlice2 =", "a well-defined column ordering when taking derivatives. paramvec : ndarray The parameter vector", "= 1e-100 HSMALL = 1e-100 class MatrixForwardSimulator(ForwardSimulator): \"\"\" Encapsulates a calculation tool used", "noqa # + sum{M==L} [ G1 ... G(M-1) d2G(M)/(dkl*dij) G(M+1) ... GN ]", "#note: gathering axis 2 of hProdCache[:,myDeriv1ColSlice], # dim=(cacheSize,nDerivCols1,nDerivCols2,dim,dim) else: #compute \"Deriv1\" row-derivatives distribution", "Tr( |rho><E| * prod ) = sum E_k prod_kl rho_l # dpr/d(opLabel)_ij =", "this spam label (given by the subsequent arguments, except for the last). The", "dim * dim # dproduct cache # mem += cache_size * dim *", "< HSMALL and hProdCache[i].min() > -HSMALL: _warnings.warn(\"hProd is small (oh well!).\") return hProdCache", "a \"block\" of the Hessian to compute. Iterating over the output of this", "[None, gpindices], gate.deriv_wrt_params(op_wrtFilter)) # (dim**2, nParams in wrtFilter for opLabel) if flat: return", "if not None. Only relevant when prMxToFill is not None. Returns ------- derivative", "wrtSlice2 is not None and wrtSlice2.start is not None: myHessianSlice2 = _slct.shift(myDeriv2ColSlice, wrtSlice2.start)", "implies circuit[i] = circuit[iLeft] + circuit[iRight], but we want: # since then matrixOf(circuit[i])", "returnDeriv: if returnPr: return ret, dpr, p else: return ret, dpr else: if", "distribution mode for this calculator. \"\"\" return \"deriv\" def estimate_cache_size(self, nCircuits): \"\"\" Return", "dim, dim) # (reshape without copying - throws error if copy is needed)", "circuit, returnPr, returnDeriv, clipTo): \"\"\" Compute the Hessian of a probability generated by", "= str(circuit) else: strToPrint = str(circuit[0:10]) + \" ... (len %d)\" % len(circuit)", "(the \"License\"); you may not use this file except # in compliance with", ")[0,i,j,k,0] # d2pr_dOps2 = squeeze( dot( E, dot( dGs, rho ) ), axis=(0,4))", "fnName == \"bulk_hprobs_by_block\": #Note: includes \"results\" memory since this is allocated within #", "nDerivCols1)) drho = rhoVec.deriv_wrt_params(rho_wrtFilter1) dp_dAnyE = _np.dot(Gs, drho) * scaleVals[:, None, None] #", "the model). This argument is used internally for distributing derivative calculations across multiple", "but OK if infs occur here _np.seterr(**old_err) if bReturnDProdsAndProds: Gs = evalTree.final_view(prodCache, axis=0)", "dim, dim)) # axes = (model_parameter1, model_parameter2, model_element_row, model_element_col) def prs(self, rholabel, elabels,", "# may overflow or get nans (invalid), but ok dGs1 = _np.swapaxes(_np.swapaxes(dGs1, 0,", "> -DSMALL: _warnings.warn(\"Would have scaled dProd but now will not alter scaleCache.\") #profiler.print_mem(\"DEBUGMEM:", "scaleCache = _np.zeros(cacheSize, 'd') #First element of cache are given by evalTree's initial", "# no scaling -- faster but susceptible to overflow G = self.product(circuit, False)", "evolution not fully supported yet!\") #Compute probability and save in return array #", "mem += cache_size # scale cache (exps) mem += cache_size # scale vals", "= dprobs2 = None hprobs = _np.zeros((nElements, _slct.length(wrtSlice1), _slct.length(wrtSlice2)), 'd') #prMxToFill = None", "myDeriv1ColSlice], dProdCache2, scaleCache, None, myHessianSlice1, wrtSlice2) # pass None as comm, *not* mySubComm", "_np.dot(_np.transpose(hop_dopLabels[opLabel1], axes=(1, 2, 0)), x0); xv = x.view() xv = _np.transpose(xv, axes=(2, 0,", "0, 3) # may overflow or get nans (invalid), but ok dGs2 =", "processors if it isn't specified if wrtFilter is None: blkSize = wrtBlockSize #", "don't use column distribution hProdCache[:, myDeriv1ColSlice] = self._compute_hproduct_cache( evalTree, prodCache, dProdCache1[:, myDeriv1ColSlice], dProdCache2,", "numpy array Only returned when bScale == True. A length-S array specifying the", "_np.dot(G, self.sos.get_operation(opLabel2).todense()) prods[(i, j)] = G prods[(len(revOpLabelList), len(revOpLabelList) - 1)] = ident #", "[None, gpindices1, gpindices2], gate.hessian_wrt_params(op_wrtFilter1, op_wrtFilter2)) if flat: return flattened_hprod else: return _np.transpose(flattened_hprod, (1,", "parameters, this # isn't currently needed. N = len(revOpLabelList) for m, opLabel1 in", "a single object (gate or spam vec) \"\"\" #Create per-gate with-respect-to parameter filters,", "a scaling factor (see below). Returns ------- product : numpy array The product", "scale = _np.exp(scale_exp) _np.seterr(**old_err) return G, scale else: G = _np.identity(self.dim) for lOp", "blkSize)) # num blocks required to achieve desired average size == blkSize blocks", "gathering axis 1 of mxToFill[felInds], dim=(ks,M) profiler.add_time(\"MPI IPC\", tm) profiler.mem_check(\"bulk_fill_dprobs: post gather blocks\")", "(i % G^2)-th entry of the (i / G^2)-th flattened operation sequence product", "# - alter product, dproduct, etc. to allow for *complex* derivatives, since matrices", "= (model_parameter1, model_parameter2, model_element_row, model_element_col) def prs(self, rholabel, elabels, circuit, clipTo, bUseScaling=False, time=None):", "can't do anything with it! #_warnings.warn(\"More processors than can be used for product", "gate-only sequence and prep/effect pairs. The evaluation tree organizes how to efficiently compute", "obj): \"\"\" Helper function for doperation and hoperation below: pulls out pieces of", "== (len(circuit_list), nDerivCols, nDerivCols) # may also give invalid value due to scaleVals", "number of computed elements (i.e. evalTree.num_final_elements()) and M is the number of model", "#use cached data to construct return values Gs = evalTree.final_view(prodCache, axis=0) #shape ==", "value (see below) dGs[_np.isnan(dGs)] = 0 _np.seterr(**old_err) if flat: dGs = _np.swapaxes(_np.swapaxes(dGs, 0,", "# may be duplicates (a list, not a set) # since all scaled", ") # and using numpy's reshape dim = self.dim uniqueOpLabels = sorted(list(set(revOpLabelList))) used_operations", "for ith string hGs = evalTree.final_view(hProdCache, axis=0) #shape == ( len(circuit_list), nDerivCols1, nDerivCols2,", "if flat == True, a N x M x M numpy array, where:", "`(rowSlice,colSlice)` 2-tuples, each of which specify a \"block\" of the Hessian to compute.", "scaledGatesAndExps[lOp] H = _np.dot(gate, G) # product of gates, starting with identity scale_exp", "in hproduct cache calc.\") hProdCache = _np.zeros((cacheSize,) + hessn_shape) #First element of cache", "1, N - 1)]) # (dim**2, dim**2) x = _np.dot(_np.transpose(dop_dopLabel1[opLabel1]), x0); xv =", "the scaling that needs to be applied to the resulting products (final_product[i] =", "dGs[gInds], scaleVals[gInds], block_wrtSlice), add=sumInto) _np.seterr(**old_err) profiler.add_time(\"bulk_fill_dprobs: calc_and_fill_blk\", tm) for iBlk in myBlkIndices: tm", "space. Will use derivative columns and then (and only when needed) a split", "groups that will be assigned to subtrees of the created tree. This aids", "\\ _mpit.distribute_slice(allDerivColSlice, comm) #print(\"MPI: _compute_dproduct_cache over %d cols (%s) (rank %d computing %s)\"", "comm=None): \"\"\" Computes a tree of products in a linear cache space. Will", ") == 0 ) #assert( len( (_np.isinf(dGs)).nonzero()[0] ) == 0 ) #dGs =", "calc_and_fill) else: # Divide columns into blocks of at most blkSize assert(wrtFilter1 is", "num_params**2 * dim * dim # hproduct cache # mem += cache_size *", "AutoGator An auto-gator object that may be used to construct virtual gates for", "mapping # of prep and effect parameters onto a final \"filtered\" set. #", "tm = _time.time() old_err = _np.seterr(over='ignore') rho, E = self._rhoE_from_spamTuple(spamTuple) if prMxToFill is", "comm=None, wrtFilter1=None, wrtFilter2=None, wrtBlockSize1=None, wrtBlockSize2=None, gatherMemLimit=None): \"\"\" Compute the outcome probability-Hessians for an", "product cache info (not distributed) prodCache, scaleCache = self._compute_product_cache(evalTree, comm) scaleVals = self._scaleExp(evalTree.final_view(scaleCache))", "None) # cannot specify both wrtFilter and blkSize nBlks1 = int(_np.ceil(self.Np / blkSize1))", "blk1Comm, blk_wrtSlice1) dGs1 = evalSubTree.final_view(dProdCache1, axis=0) for iBlk2 in myBlk2Indices: blk_wrtSlice2 = blocks2[iBlk2]", "(skip over the zero and single-gate-strings) for i in evalTree.get_evaluation_order(): tm = _time.time()", "# noqa # vec( d2prod/d(opLabel1)_kl*d(opLabel2)_ij ) = sum{...} [ G1 ... G(M-1) dG(M)/dkl", "additionally return the probability itself. returnDeriv : bool when set to True, additionally", "pass None as comm, *not* mySubComm, since we can't do any # further", "give invalid value due to scaleVals being inf and dot-prod being 0. In", "dim, dim ) self._fill_result_tuple( (mxToFill,), evalSubTree, blocks[iBlk], slice(None), calc_and_fill_blk) profiler.mem_check(\"bulk_fill_dprobs: post fill blk\")", "x G, where - S == len(circuit_list) - M == the number of", "= _np.swapaxes(_np.swapaxes(dGs, 0, 3) * scaleVals, 0, 3) # convert nans to zero,", "mySubComm) myBlk2Indices, blk2Owners, blk2Comm = \\ _mpit.distribute_indices(list(range(nBlks2)), blk1Comm) if blk2Comm is not None:", "product components (i.e. prod_kl) with # respect to a given gateLabel_ij. This function", "= self._process_wrtFilter(wrtSlice, self.sos.get_prep(rholabel)) E_wrtFilter, E_gpindices = self._process_wrtFilter(wrtSlice, self.sos.get_effect(elabel)) nDerivCols = self.Np if wrtSlice", "flattened_d2prod[:, inds1, inds2] += _np.swapaxes(y, 0, 1) # above: dim = (dim2, nDerivCols1,", "evalTree.generate_circuit_list(permute=False) # raw operation sequences for spamTuple, (fInds, gInds) in evalTree.spamtuple_indices.items(): circuit_list =", "have # a more than linear dependence on their parameters. if self.sos.get_prep(rholabel).has_nonzero_hessian(): derivWrtAnyRhovec", "= self.sos.get_effect(elabel) # arrays, these are SPAMVecs nCircuits = Gs.shape[0] rho_wrtFilter, rho_gpindices =", "0, 4) * scaleVals, 0, 4) # convert nans to zero, as these", "is the number of model parameters. hessian[0,j,k] is the derivative of the probability", "quantities for given arguments \"\"\" old_err = _np.seterr(over='ignore') rho, E = self._rhoE_from_spamTuple(spamTuple) _fas(mxToFill,", "diff order) # d2pr/d(E)_i d(opLabel)_mn = sum [dprod/d(opLabel)_mn]_il rho_l (and same for other", "the returned derivative array (see below). bReturnProds : bool, optional when set to", "sequence product with respect to the j-th model parameter. products : numpy array", "= _np.seterr(over='ignore') scaleExps = evalTree.final_view(scaleCache) scaleVals = _np.exp(scaleExps) # may overflow, but OK", "= object-local param indices relevant_gpindices = [] # indices into original wrtFilter'd indices", "None: self._fill_result_tuple((prMxToFill,), evalSubTree, slice(None), slice(None), calc_and_fill_p) profiler.mem_check(\"bulk_fill_dprobs: post fill probs\") #distribute derivative computation", "self.Np)) derivWrtAnyEvec = scale * _np.dot(prod, rhoVec.deriv_wrt_params()) # may generate overflow, but OK", "None) \\ else min(comm_blkSize, blkSize2) # override with smaller comm_blkSize else: blkSize1 =", "the parent tree's *non-final* elements from those of the sub-trees). Note also that", "= self.Np if (wrtFilter1 is None) else len(wrtFilter1) num_deriv_cols2 = self.Np if (wrtFilter2", "all at once so they're not repeatedly # computed for each block of", "opLabel, flat=False, wrtFilter1=None, wrtFilter2=None): \"\"\" Return the hessian of a length-1 (single-gate) sequence", "the prep and POVM effect used to compute the probability. circuit : Circuit", "# E_wrtFilter1, E_wrtFilter2)) else: d2pr_d2Es = 0 # END SPAM DERIVS ----------------------- ret", "sub_vdp = dp_drhos + dp_dEs + dp_dOps return sub_vdp #def _get_filter_info(self, wrtSlices): #", "param_slice2, calc_and_fill_fn): \"\"\" This function takes a \"calc-and-fill\" function, which computes and *fills*", "\"bulk_fill_dprobs\": mem += cache_size * wrtLen1 * dim * dim # dproduct cache", "= self.sos.get_operation(opLabel) op_wrtFilter1, gpindices1 = self._process_wrtFilter(wrtFilter1, gate) op_wrtFilter2, gpindices2 = self._process_wrtFilter(wrtFilter2, gate) #", "keep prod managable.\") elif _np.count_nonzero(dProdCache[i]) and dProdCache[i].max() < DSMALL and dProdCache[i].min() > -DSMALL:", "checks within code to verify correctness, generating warnings when checks fail. Used for", "# wrt E ret += d2pr_drhos1 + d2pr_dEs1 + d2pr_dOps2 # wrt gates", "(most likely because you want to computed their probabilites). These are a \"simplified\"", "- alter product, dproduct, etc. to allow for *complex* derivatives, since matrices can", "is None) # cannot specify both wrtFilter and blkSize nBlks = int(_np.ceil(self.Np /", "not None: _fas(deriv2MxToFill, [fInds, pslc2], self._dprobs_from_rhoE( spamTuple, rho, E, Gs[gInds], dGs2[gInds], scaleVals[gInds], wrtSlice2),", "circuit_list], axis=0) if _nla.norm(dprMxToFill[fInds] - check_vdp) > 1e-6: _warnings.warn(\"norm(vdp-check_vdp) = %g - %g", "= max(_nla.norm(G), _np.exp(-scale_exp)) G = _np.dot(gate, G / nG); scale_exp += _np.log(nG) #", "i]) # (dim**2, dim**2) _fas(flattened_dprod, [None, gpindices], _np.dot(LRproduct, dop_dopLabel), add=True) # (dim**2, nParams[opLabel])", "1, 2) y = _np.dot(_np.kron(prods[(0, l - 1)], xv), dop_dopLabel2[opLabel2]) # above: (nDerivCols1,dim**2,dim**2)", "blk2Comm, blk_wrtSlice1, blk_wrtSlice2) hGs = evalSubTree.final_view(hProdCache, axis=0) #Set filtering for calc_and_fill wrtSlice1 =", "dot( E, dot( dGs, rho ) ), axis=(0,4)) old_err2 = _np.seterr(invalid='ignore', over='ignore') d2pr_dOps2", "2nd differentiation, respectively (i.e. by wrtFilter1 and wrtFilter2). clipTo : 2-tuple, optional (min,max)", "sum_j dot(Gs, rho)[i,j,0] dEP[j,J] # dp_dEs[i,J0+J] = dot(squeeze(dot(Gs, rho),2), dEP)[i,J] # dp_dEs[:,J0+J] =", "elements (i.e. evalTree.num_final_elements()) and M is the number of model parameters. evalTree :", "memory savings from using a split tree. In short, parallelization should be done", "gate hProdCache[i] = _np.zeros(hessn_shape) elif not self.sos.get_operation(opLabel).has_nonzero_hessian(): #all gate elements are at most", "= wrtBlockSize # could be None if (mySubComm is not None) and (mySubComm.Get_size()", "obj.gpindices return obj_wrtFilter, relevant_gpindices #Vectorizing Identities. (Vectorization) # Note when vectorizing op uses", "dpr_dEs + dpr_dOps, p else: return dpr_drhos + dpr_dEs + dpr_dOps def hpr(self,", "already done any such distribution # and has given each processor a list", "rows = flattened all else dGs2 = _np.swapaxes(_np.swapaxes(dGs2, 0, 1).reshape((nDerivCols2, nCircuits * dim**2)),", "clipTo, bScale) for elabel in elabels ]) #assert(_np.linalg.norm(ps-check_ps) < 1e-8) return ret def", "axes=(1, 2, 0)), x0); xv = x.view() xv = _np.transpose(xv, axes=(2, 0, 1))", "squeeze(dot(E, dGs, drhoP),axis=(0,))[:,:,J] drho = rhoVec.deriv_wrt_params(rho_wrtFilter2) d2pr_drhos1 = _np.zeros((nCircuits, nDerivCols1, nDerivCols2)) _fas(d2pr_drhos1, [None,", "a linear cache space. Will use derivative rows and columns and then (as", "derivative of a many operation sequences at once. Parameters ---------- evalTree : EvalTree", "subTreeOwners, prMxToFill, [], 0, comm) if clipTo is not None and prMxToFill is", "for distributing the computation across multiple processors. Distribution is first performed over subtrees", "= (N,1), Es = (len(elabels),N) if bUseScaling: old_err = _np.seterr(over='ignore') G, scale =", "None # free mem def _fill_result_tuple(self, result_tup, evalTree, param_slice1, param_slice2, calc_and_fill_fn): \"\"\" This", "when set to True, additionally return the probability itself. clipTo : 2-tuple (min,max)", "we *cannot* make use of a tree being # split because there's no", "# for the current spamTuple (this list has the SAME length as fInds).", "if deriv2MxToFill is not None: _mpit.gather_indices(subtreeElementIndices, subTreeOwners, deriv2MxToFill, [], 0, comm, gatherMemLimit) if", "_np.count_nonzero(dProdCache[i]) and dProdCache[i].max() < DSMALL and dProdCache[i].min() > -DSMALL: _warnings.warn(\"Would have scaled dProd", "product (els of # prod.flatten()). # # Note: if gate G(L) is just", "None: # _fas(prMxToFill, [fInds], # self._probs_from_rhoE(rho, E, Gs[gInds], scaleVals[gInds]), add=sumInto) if deriv1MxToFill is", "(dim**2, dim**2) # (nDerivCols1,nDerivCols2,dim**2) x = _np.dot(_np.transpose(hop_dopLabels[opLabel1], axes=(1, 2, 0)), x0); xv =", "so it's been removed. if comm is not None: # ignoring comm since", "set to True, additionally return the derivative of the probability. clipTo : 2-tuple", "# above: (nDerivCols1,dim**2,dim**2) * (dim**2,nDerivCols2) = (nDerivCols1,dim**2,nDerivCols2) flattened_d2prod[:, inds1, inds2] += _np.swapaxes(y, 0,", "* vec( X ) def doperation(self, opLabel, flat=False, wrtFilter=None): \"\"\" Return the derivative", "parameters being differentiated with respect to (see wrtBlockSize). wrtFilter : list of ints,", "evalSubTree, prodCache, dProdCache1, dProdCache2, scaleCache, blk2Comm, blk_wrtSlice1, blk_wrtSlice2) hGs = evalSubTree.final_view(hProdCache, axis=0) #Set", "(col) derivative operations, respectively. Each element is an index into an array of", "Gs = evalTree.final_view(prodCache, axis=0) #shape == ( len(circuit_list), dim, dim ), Gs[i] is", "dGs, rho ) ), axis=(0,3)) old_err2 = _np.seterr(invalid='ignore', over='ignore') dp_dOps = _np.squeeze(_np.dot(E, _np.dot(dGs,", "may overflow, but OK # Get: dp_dEs[i, E_gpindices] = dot(transpose(dE/dEP),Gs[i],rho)) # dp_dEs[i,J0+J] =", "wrtLen1 * wrtLen2 * dim * dim # hproduct cache mem += cache_size", "the Hessian, so that # if gl1 and gl2 are both in opsToVectorize1", "flat == True, an array of shape S*N x M x M where", "E_wrtFilter1, E_wrtFilter2)) else: d2pr_d2Es = 0 # END SPAM DERIVS ----------------------- ret =", "dp_dOps[i,j] = sum_k E[0,k] dot( dGs, rho )[i,j,k,0] # dp_dOps[i,j] = dot( E,", "array values, which is a functionality needed to correctly handle the remainder spam", "== the number of entries in a single flattened gate (ordering as numpy.flatten),", "x G operation matrices) and hessians[i,j,k,l,m] holds the derivative of the (l,m)-th entry", "# (KM,N,1) * (KM,1,N') = (KM,N,N') yield wrtSlice1, wrtSlice2, hprobs, dprobs12 else: yield", "for wrtSlice1, wrtSlice2 in wrtSlicesList: if wrtSlice1 != last_wrtSlice1: dProdCache1 = dGs1 =", "# Note: dProdCache?.shape = (#circuits,#params_to_diff_wrt,dim,dim) nDerivCols1 = dProdCache1.shape[1] nDerivCols2 = dProdCache2.shape[1] assert(wrtSlice1 is", "# (dim**2, dim**2) # (nDerivCols1,nDerivCols2,dim**2) x = _np.dot(_np.transpose(hop_dopLabels[opLabel1], axes=(1, 2, 0)), x0); xv", "self.Np if (wrtFilter1 is None) else len(wrtFilter1) num_deriv_cols2 = self.Np if (wrtFilter2 is", "_np.seterr(**old_err) self._fill_result_tuple((mxToFill,), evalSubTree, slice(None), slice(None), calc_and_fill) #collect/gather results subtreeElementIndices = [t.final_element_indices(evalTree) for t", "remove: not needed now that we track owners #if mySubSubComm.Get_rank() > 0: myDeriv2ColSlice", "nG scaleCache[i] = _np.log(nG) #evaluate operation sequences using tree (skip over the zero", "so # all hessians for single- or zero-operation sequences are zero. hProdCache[i] =", "It can often be useful to have fewer processor groups then subtrees (even", "_slct.length(wrtSlice1), _slct.length(wrtSlice2)), 'd') #prMxToFill = None deriv1MxToFill = dprobs1 deriv2MxToFill = dprobs2 mxToFill", "self.paramvec) def product(self, circuit, bScale=False): \"\"\" Compute the product of a specified sequence", "from those of the sub-trees. _warnings.warn(\"Increased speed could be obtained\" \" by giving", "= _np.zeros((1, self.Np, self.Np)) _fas(d2pr_d2Es, [0, self.sos.get_effect(elabel).gpindices, self.sos.get_effect(elabel).gpindices], _np.tensordot(derivWrtAnyEvec, self.sos.get_effect(elabel).hessian_wrt_params(), (1, 0))) #", "dim, dim ), # dGs[i] is dprod_dOps for ith string hGs = evalTree.final_view(hProdCache,", "dGs1, dGs2, Gs, scaleVals) if bScale else (hGs, dGs1, dGs2, Gs) else: hGs", "numpy arrays # like length>1 lists do... ugh. relevant_gpindices = slice(relevant_gpindices[0], relevant_gpindices[0] +", "The arrays that are filled internally to `calc_and_fill_fn` must be the same as", "a 2D array with probability-derivatives for each \"final element\" of `evalTree`. Parameters ----------", "_np.exp(scaleExps) # may overflow, but OK if infs occur here _np.seterr(**old_err) if bReturnDProdsAndProds:", "returnPr, clipTo): \"\"\" Compute the derivative of a probability generated by a operation", "matrix d12 defined by: d12[iSpamLabel,iOpStr,p1,p2] = dP/d(p1)*dP/d(p2) where P is is the probability", "dp_dOps = squeeze( dot( E, dot( dGs, rho ) ), axis=(0,3)) old_err2 =", "in this order (easier to think about) revOpLabelList = tuple(reversed(tuple(circuit))) N = len(revOpLabelList)", "exponent # # p = _mt.trace( _np.dot(self.SPAMs[spamLabel],G) ) * exp(total_exp) # probability #", "and hessian[i,j,k] holds the derivative of the i-th entry of the flattened product", "scaleCache = self._compute_product_cache(evalTree, comm) dProdCache1 = self._compute_dproduct_cache(evalTree, prodCache, scaleCache, comm, wrtSlice1) dProdCache2 =", ": list of strs A list of the names of the subcalls to", "many processors to make use of in \" \" _compute_hproduct_cache.\") #TODO: remove: not", "dR1 = dProdCache1[iLeft], dProdCache1[iRight] dL2, dR2 = dProdCache2[iLeft], dProdCache2[iRight] hL, hR = hProdCache[iLeft],", "+ d2pr_dEs2 # wrt E ret += d2pr_drhos1 + d2pr_dEs1 + d2pr_dOps2 #", "#assert( len( (_np.isinf(dGs)).nonzero()[0] ) == 0 ) #dGs = clip(dGs,-1e300,1e300) _np.seterr(**old_err) if flat:", "if deriv1MxToFill is not None: _mpit.gather_indices(subtreeElementIndices, subTreeOwners, deriv1MxToFill, [], 0, comm, gatherMemLimit) if", "def _check(self, evalTree, prMxToFill=None, dprMxToFill=None, hprMxToFill=None, clipTo=None): # compare with older slower version", "loop *iteration*!) #collect/gather results subtreeElementIndices = [t.final_element_indices(evalTree) for t in subtrees] _mpit.gather_indices(subtreeElementIndices, subTreeOwners,", "noqa # tensor (G(L+1) ... GN)^T vec( dG(L)/dij ) ] # noqa #", "warning -- note that we *cannot* make use of a tree being #", "matrices). and hessian[i,j,k,l] holds the derivative of the (k,l)-th entry of the product", "the \"gather\" operations performed as a part of MPI processor syncronization. Returns -------", "wrtFilter and wrtBlockSize wrtSlice2 = _slct.list_to_slice(wrtFilter2) else: wrtSlice2 = None #get distribution across", "Returns ------- None \"\"\" if wrtFilter1 is not None: assert(wrtBlockSize1 is None and", "no scaling -- faster but susceptible to overflow G = self.product(circuit, False) if", "vec( dprod/d(opLabel)_ij ) = sum_{L s.t. G(L) == oplabel} [ (G1 ... G(L-1))", "due to scaleVals being inf and dot-prod being 0. In # this case", "overflow, but OK) ps = _np.real(_np.dot(Es, _np.dot(G, rho)) * scale) _np.seterr(**old_err) else: #", "overflow or get nans (invalid), but ok dGs = _np.swapaxes(_np.swapaxes(dGs, 0, 3) *", "and iSpamLabel. d12 has the same dimensions as the Hessian, and turns out", "a hessian calculation (i.e. for l==m) then # it could make sense to", "#Finally, cache any nonzero gate hessians (memory?) hop_dopLabels = {} for opLabel, gate", "nDerivCols1, nDerivCols2)) _fas(d2pr_d2Es, [None, E_gpindices1, E_gpindices2], _np.tensordot(dp_dAnyE, self.sos.get_effect(elabel).hessian_wrt_params( E_wrtFilter1, E_wrtFilter2), (1, 0))) #", "is ok, see \"if\" condition above) _mpit.gather_slices(deriv1Slices, deriv1Owners, hProdCache, [], 1, comm) #,", "a single kl xv = _np.swapaxes(xv, 1, 2) y = _np.dot(_np.kron(prods[(0, l -", "E(0,1) * B ) = vec( mx w/ row_i = A[i,0] * B[row1]", "TODO: better check for equivalence: maybe let dGs2 be None? assert(nDerivCols1 == nDerivCols2)", "rowSlice) - B' is the number of parameter columns (the length of colSlice)", "blk_wrtSlice1 = blocks1[iBlk1] dProdCache1 = self._compute_dproduct_cache( evalSubTree, prodCache, scaleCache, blk1Comm, blk_wrtSlice1) dGs1 =", "of no gates G = ident for (j, opLabel2) in enumerate(revOpLabelList[i:], start=i): #", "None. Only relevant when prMxToFill is not None. Returns ------- hessian : numpy", "< L} # noqa # [ G1 ... G(M-1) dG(M)/dkl G(M+1) ... G(L-1)", "# (to save mem) but isn't gathered until now (but using blk1Comm). #", "enumerate(revOpLabelList): inds2 = gpindices1[opLabel2] #nDerivCols2 = dop_dopLabel2[opLabel2].shape[1] # FUTURE: we could add logic", "holds the derivative of the (j,k)-th entry of the product with respect to", "the size that makes maximal use of available processors is used as the", "a probability generated by a operation sequence and spam tuple as a 1", "#Derivs wrt SPAM if returnDeriv: # same as in dpr(...) dpr_drhos = _np.zeros((1,", "the probabilities. bScale : bool, optional When True, return a scaling factor (see", "the MatrixForwardSimulator calculator class\"\"\" #*************************************************************************************************** # Copyright 2015, 2019 National Technology & Engineering", "------- deriv : numpy array * if flat == False, a M x", "at once. The minimum of wrtBlockSize and the size that makes maximal use", "a column of the matrix d12 defined by: d12[iSpamLabel,iOpStr,p1,p2] = dP/d(p1)*dP/d(p2) where P", "1)) else: d2pr_dEs2 = _np.zeros((nCircuits, nDerivCols2, nDerivCols1)) dp_dAnyE = _np.squeeze(_np.dot(dGs2, rho), axis=(3,)) *", "evalTree.num_final_elements() #Fill product cache info (not distributed) prodCache, scaleCache = self._compute_product_cache(evalTree, comm) scaleVals", "of empty label == no gate prodCache[i] = _np.identity(dim) # Note: scaleCache[i] =", "of a function of many gate sequence probabilities can often be computed column-by-column", "rho)) * scale # may generate overflow, but OK if clipTo is not", "+= ex # scale and keep track of exponent if H.max() < PSMALL", "evalTree.num_final_elements()) evalTree : EvalTree given by a prior call to bulk_evaltree. Specifies the", "of the parent-function scope. This use of # closures seems confusing and we", "np1 - 1) // np1 # ceiling(num_params / np1) wrtLen2 = (self.Np +", "processors. Distribution is first done over the set of parameters being differentiated with", "------------- # Get: dp_drhos[i, rho_gpindices] = dot(E,Gs[i],drho/drhoP) # dp_drhos[i,J0+J] = sum_kl E[0,k] Gs[i,k,l]", "0, 2) # may overflow, but ok _np.seterr(**old_err) return Gs def bulk_dproduct(self, evalTree,", "compute the probability. circuit : Circuit or tuple A tuple-like object of *simplified*", "dGs2 = None # free mem dProdCache1 = dGs1 = None # free", "i in gpindices: relevant_gpindices.append(ii) obj_wrtFilter.append(list(gpindices).index(i)) relevant_gpindices = _np.array(relevant_gpindices, _np.int64) if len(relevant_gpindices) == 1:", "actually computing X^T ( note (A tensor B)^T = A^T tensor B^T )", "gpindices1[l] = self._process_wrtFilter(wrtFilter1, used_operations[l]) gate_wrtFilters2[l], gpindices2[l] = self._process_wrtFilter(wrtFilter2, used_operations[l]) #Cache partial products (relatively", "/ nG scaleCache[i] = _np.log(nG) #evaluate operation sequences using tree (skip over the", "dGs1 = _np.swapaxes(_np.swapaxes(dGs1, 0, 3) * scaleVals, 0, 3) # may overflow or", "distribution # and has given each processor a list appropriate for it. #", "== ( len(circuit_list), nDerivCols1, nDerivCols2, dim, dim ), # hGs[i] is hprod_dGates for", "fInds = \"final indices\" = the \"element\" indices in the final # filled", "Gs, dGs1, dGs2, hGs, scaleVals, wrtSlice1=None, wrtSlice2=None): if self.evotype == \"statevec\": raise NotImplementedError(\"Unitary", "be *ordered* dictionaries to specify a well-defined column ordering when taking derivatives. paramvec", "self.hproduct(circuit) assert(d2prod_dGates.shape[0] == d2prod_dGates.shape[1]) d2pr_dOps2 = _np.empty((1, self.Np, self.Np)) for i in range(self.Np):", "if profiler is None: profiler = _dummy_profiler dim = self.dim nDerivCols = self.Np", "= self.product(circuit, True) if returnPr: p = _np.dot(E, _np.dot(prod, rho)) * scale #", "comm) dProdCache1 = self._compute_dproduct_cache(evalTree, prodCache, scaleCache, comm, wrtSlice1) dProdCache2 = dProdCache1 if (wrtSlice1", "\"dGs1 must be pre-filtered!\" assert(dGs2.shape[1] == nDerivCols2), \"dGs1 must be pre-filtered!\" # Get:", "minimum of wrtBlockSize and the size that makes maximal use of available processors", "#Cache processed parameter filters for multiple uses below gpindices1 = {}; gate_wrtFilters1 =", "conjugate() here if complex? _fas(dpr_dEs, [0, EVec.gpindices], _np.dot(derivWrtAnyEvec, EVec.deriv_wrt_params())) _np.seterr(**old_err) if returnPr: return", "derivative of only a *subset* of all the gate's parameters if isinstance(wrtFilter, slice):", "size given a number of operation sequences. Returns ------- int \"\"\" return int(1.3", "but OK # (** doesn't depend on eIndex **) -- TODO: should also", "sum_l,m E[0,l] hGs[i,j,k,l,m] rho[m,0] # d2pr_dOps2[i,j,k] = sum_l E[0,l] dot( dGs, rho )[i,j,k,l,0]", "= len(revOpLabelList) # length of operation sequence # prod = G1 * G2", "if wrtSlice1 != last_wrtSlice1: dProdCache1 = dGs1 = None # free Mem dProdCache1", "of a specified sequence of operation labels. Parameters ---------- circuit : Circuit or", "cache_size # scale vals elif fnName == \"bulk_fill_dprobs\": mem += cache_size * wrtLen1", "operation matrix element # is at most *linear* in each of the gate", "relevant_gpindices #Vectorizing Identities. (Vectorization) # Note when vectorizing op uses numpy.flatten rows are", "full evaluation tree into. num_subtree_proc_groups : int The number of processor groups used", "rho))) # vp[i] = sum_k,l E[0,k] Gs[i,k,l] rho[l,0] * scaleVals[i] # vp[i] =", "distributing the computation across multiple processors. Distribution is performed over subtrees of evalTree", "= hProdCache[iLeft], hProdCache[iRight] # Note: L, R = GxG ; dL,dR = vgs", "scaleCache = self._compute_product_cache(evalTree, comm) #use cached data to construct return values Gs =", "a zero dimension else: obj_wrtFilter = None relevant_gpindices = obj.gpindices return obj_wrtFilter, relevant_gpindices", "mySubComm, gatherMemLimit) if deriv1MxToFill is not None: _mpit.gather_slices(blocks1, blk1Owners, deriv1MxToFill, [felInds], 1, mySubComm,", "drho = rhoVec.deriv_wrt_params(rho_wrtFilter1) d2pr_drhos2 = _np.zeros((nCircuits, nDerivCols2, nDerivCols1)) _fas(d2pr_drhos2, [None, None, rho_gpindices1], _np.squeeze(_np.dot(_np.dot(E,", "this MatrixForwardSimulator \"\"\" return MatrixForwardSimulator(self.dim, self.sos, self.paramvec) def product(self, circuit, bScale=False): \"\"\" Compute", "(N,1) rho = self.sos.get_prep(rholabel).todense()[:, None] E = _np.conjugate(_np.transpose(self.sos.get_effect(elabel).todense() [:, None])) # convention: E", "dLdRa = _np.swapaxes(_np.dot(dL1, dR2), 1, 2) dLdRb = _np.swapaxes(_np.dot(dL2, dR1), 1, 2) dLdR_sym", "rho), axis=(3,)) * scaleVals[:, None, None] # overflow OK devec = EVec.deriv_wrt_params(E_wrtFilter2) _fas(d2pr_dEs1,", "subtree for iSubTree in mySubTreeIndices: evalSubTree = subtrees[iSubTree] #Free memory from previous subtree", "G0 # nG = norm(G); G /= nG; total_exp += log(nG) # scale", "w.r.t. the k-th then the j-th model parameter. derivative : numpy array only", "should be done at a higher level. \"\"\" dim = self.dim #Note: previously,", "= self.Np if (wrtSlice is None) \\ else _slct.length(wrtSlice) deriv_shape = (nDerivCols, dim,", "slice(None), slice(None), calc_and_fill) profiler.mem_check(\"bulk_fill_dprobs: post fill\") dProdCache = dGs = None # free", "spam label indexed by iOpStr and iSpamLabel. d12 has the same dimensions as", "# ceiling(num_params / np2) mem = 0 for fnName in subcalls: if fnName", "matrix multiplication in this order (easier to think about) revOpLabelList = tuple(reversed(tuple(circuit))) N", "self.dim nDerivCols1 = self.Np if (wrtFilter1 is None) else _slct.length(wrtFilter1) nDerivCols2 = self.Np", "* _np.dot(E, prod) dpr_drhos = _np.zeros((1, self.Np)) _fas(dpr_drhos, [0, self.sos.get_prep(rholabel).gpindices], _np.dot(derivWrtAnyRhovec, rhoVec.deriv_wrt_params())) #", "is on the far right of the product of matrices. Parameters ---------- circuit", ": bool, optional When True, return a scaling factor (see below). comm :", "prod[i,j,k] drhoP[k,K] # d2pr_dErhos[i,J0+J,K0+K] = sum j dEPT[J,j] dot(prod,drhoP)[i,j,K] # d2pr_dErhos[i,J0+J,K0+K] = dot(dEPT,prod,drhoP)[J,i,K]", "not fully supported yet!\") #Compute probability and save in return array # want", "else: # a \"custom\" spamLabel consisting of a pair of SPAMVec (or array)", "necessary) if comm.Get_size() > nDerivCols: #If there are more processors than deriv cols,", "zero deriv value (see below) dGs1[_np.isnan(dGs1)] = 0 # convert nans to zero,", "slice(0, nDerivCols1) allDeriv2ColSlice = slice(0, nDerivCols2) deriv1Slices, myDeriv1ColSlice, deriv1Owners, mySubComm = \\ _mpit.distribute_slice(allDeriv1ColSlice,", "scaleCache[iRight]) if abs(scale) > 1e-8: # _np.isclose(scale,0) is SLOW! hProdCache[i] /= _np.exp(scale) if", "is true IF each operation matrix element # is at most *linear* in", "_np.dot(E, _np.dot(prod, rho)) * scale # may generate overflow, but OK if clipTo", "d2G(M)/(dkl*dij) G(M+1) ... GN ] # noqa # a matrix for each given", "dGs = evalSubTree.final_view(dProdCache, axis=0) #( nCircuits, nDerivCols, dim, dim ) profiler.add_time(\"bulk_fill_dprobs: compute_dproduct_cache\", tm)", "array of shape S x M x M x G x G, where", "caches scaleVals = Gs = dGs = None prodCache = scaleCache = dProdCache", "operation sequences found in an evaluation tree, `evalTree`. An initial list of (general)", "it could make sense to iterate through the self.operations.keys() as in # dproduct(...)", "To support unitary evolution we need to: # - alter product, dproduct, etc.", "if not None. Only relevant when prMxToFill is not None. Returns ------- hessian", "identity below is valid. # Below we use E(i,j) to denote the elementary", "ints, optional If not None, a list of integers specifying which gate parameters", "(0, 2, 1)) + \\ d2pr_d2rhos + d2pr_d2Es + d2pr_dOps2 # Note: add", "(i.e. prod_kl) with # respect to a given gateLabel_ij. This function returns a", "dEP)[:,:,J] d2pr_dEs1 = _np.zeros((nCircuits, nDerivCols1, nDerivCols2)) dp_dAnyE = _np.squeeze(_np.dot(dGs1, rho), axis=(3,)) * scaleVals[:,", "d2pr_dErhos1 = _np.zeros((nCircuits, nDerivCols1, nDerivCols2)) drho = rhoVec.deriv_wrt_params(rho_wrtFilter2) dp_dAnyE = _np.dot(Gs, drho) *", "but OK if clipTo is not None: p = _np.clip(p, clipTo[0], clipTo[1]) dprod_dOps", "info dProdCache1 = self._compute_dproduct_cache( evalSubTree, prodCache, scaleCache, mySubComm, wrtSlice1) dProdCache2 = dProdCache1 if", "let dGs2 be None? assert(nDerivCols1 == nDerivCols2) d2pr_drhos2 = _np.transpose(d2pr_drhos1, (0, 2, 1))", "cache calc.\") cacheSize = len(evalTree) prodCache = _np.zeros((cacheSize, dim, dim)) scaleCache = _np.zeros(cacheSize,", "2015, 2019 National Technology & Engineering Solutions of Sandia, LLC (NTESS). # Under", "is contained in a class separate from Model to allow for additional model", "dim ), # dGs[i] is dprod_dOps for ith string if not bScale: old_err", "tm) profiler.add_count(\"compute_dproduct_cache: dots\") scale = scaleCache[i] - (scaleCache[iLeft] + scaleCache[iRight]) if abs(scale) >", "num_param1_groups, num_param2_groups FLOATSIZE = 8 # in bytes: TODO: a better way dim", "yield nan as the returned probability. time : float, optional The *start* time", "= _np.zeros((dim**2, num_deriv_cols), 'd') _fas(flattened_dprod, [None, gpindices], gate.deriv_wrt_params(op_wrtFilter)) # (dim**2, nParams[opLabel]) if _slct.length(gpindices)", "# loc_rho_slices = [slice(None,None)]*len(self.preps) # loc_e_slices = [slice(None,None)]*len(self.effects) # global_rho_slices = [slice(self.rho_offset[i],self.rho_offset[i+1]) for", "in \" \" _compute_dproduct_cache.\") if mySubComm.Get_rank() > 0: myDerivColSlice = slice(0, 0) #don't", "is dprod_dOps for ith string if not bScale: old_err = _np.seterr(over='ignore', invalid='ignore') #", "used to (in parallel) iterate through the subtrees. It can often be useful", ") = B^T tensor A * vec( E(0,1) ) # In general: vec(", "= \"gate sequence indices\" = indices into the (tree-) list of # all", "# hproduct cache mem += cache_size * (wrtLen1 + wrtLen2) * dim *", "nCircuits = evalTree.num_final_strings() nDerivCols = self.Np if (wrtFilter is None) else _slct.length(wrtFilter) dim", "self.effects - independent of which) dp_dAnyE = _np.squeeze(_np.dot(Gs, rho), axis=(2,)) * scaleVals[:, None]", ": numpy array * if flat == False, a M x M x", "elif not self.sos.get_operation(opLabel).has_nonzero_hessian(): #all gate elements are at most linear in params, so", "None]) # overflow OK d2pr_drhos2 = _np.transpose(d2pr_drhos2, (0, 2, 1)) # Get: d2pr_dEs[i,", "= spamTuple # can't deal w/\"custom\" spam label... rho, E = self._rhoE_from_spamTuple(spamTuple) rhoVec", "assigned to subtrees of the created tree. This aids in the tree construction", "bulk_hprobs_by_block(self, evalTree, wrtSlicesList, bReturnDProbs12=False, comm=None): \"\"\" Constructs a generator that computes the 2nd", "or spam vec) \"\"\" #Create per-gate with-respect-to parameter filters, used to # select", "= G1 * G2 * .... * GN , a matrix # noqa", "correspondence between rows of mxToFill and spam labels. evalTree : EvalTree given by", "\"\"\" return \"deriv\" def estimate_cache_size(self, nCircuits): \"\"\" Return an estimate of the ideal/desired", "(groups if needed) subtrees = evalTree.get_sub_trees() mySubTreeIndices, subTreeOwners, mySubComm = evalTree.distribute(comm) #if comm", "E, Gs[gInds], dGs1[gInds], scaleVals[gInds], wrtSlice1), add=sumInto) if deriv2MxToFill is not None: _fas(deriv2MxToFill, [fInds,", "in used_operations.items()} if wrtFilter1 == wrtFilter2: dop_dopLabel2 = dop_dopLabel1 else: dop_dopLabel2 = {", "j-th model parameter. products : numpy array Only returned when bReturnDProdsAndProds == True.", "\"\"\" Compute the outcome probability-derivatives for an entire tree of gate strings. Similar", "(i,j) # noqa # d2prod/d(opLabel1)_kl*d(opLabel2)_ij = sum_{M s.t. GM == gatelabel1} sum_{L s.t.", "_fas(d2pr_dErhos2, [None, E_gpindices2, rho_gpindices1], _np.swapaxes(_np.dot(_np.transpose(devec), dp_dAnyE), 0, 1)) d2pr_dErhos2 = _np.transpose(d2pr_dErhos2, (0, 2,", "is the number of model parameters selected for the 1st and 2nd differentiation,", "a single spam label (specified to it by the first two arguments), and", "(vec_prod_indx,kl,ij) else: # l==m, which we *used* to assume gave no contribution since", "else wrtSlice _, myDerivColSlice, _, mySubComm = \\ _mpit.distribute_slice(allDerivColSlice, comm) #print(\"MPI: _compute_dproduct_cache over", "# axes = (gate_ij, prod_row, prod_col) return _np.swapaxes(flattened_dprod, 0, 1).reshape((num_deriv_cols, dim, dim)) def", "array (see below). wrtFilter1, wrtFilter2 : list of ints, optional If not None,", "dGs[_np.isnan(dGs)] = 0 _np.seterr(**old_err) if flat: dGs = _np.swapaxes(_np.swapaxes(dGs, 0, 1).reshape( (nDerivCols, nCircuits", "drhoP[l,J] # dp_drhos[i,J0+J] = dot(E, Gs, drhoP)[0,i,J] # dp_drhos[:,J0+J] = squeeze(dot(E, Gs, drhoP),axis=(0,))[:,J]", "MPI communicator for distributing the computation across multiple processors. Distribution is performed as", "_np.zeros((nElements, _slct.length(wrtSlice1)), 'd') dprobs2 = _np.zeros((nElements, _slct.length(wrtSlice2)), 'd') else: dprobs1 = dprobs2 =", "most linear in their parameters, this # isn't currently needed. N = len(revOpLabelList)", "= dot(squeeze(dot(Gs, rho),axis=(2,)), dEP)[:,J] dp_dEs = _np.zeros((nCircuits, nDerivCols)) # may overflow, but OK", "Computes a tree of product derivatives in a linear cache space. Will use", "of processor groups used to (in parallel) iterate through the subtrees. It can", "d2pr_d2Es = 0 ret = d2pr_dErhos + _np.transpose(d2pr_dErhos, (0, 2, 1)) + \\", "elabels ]) #assert(_np.linalg.norm(ps-check_ps) < 1e-8) return ret def dpr(self, spamTuple, circuit, returnPr, clipTo):", "scaleCache.\") #profiler.print_mem(\"DEBUGMEM: POINT2\"); profiler.comm.barrier() profiler.add_time(\"compute_dproduct_cache: serial\", tSerialStart) profiler.add_count(\"compute_dproduct_cache: num columns\", nDerivCols) return dProdCache", "+ np1 - 1) // np1 # ceiling(num_params / np1) wrtLen2 = (self.Np", "the probability w.r.t. each model parameter (M is the length of the vectorized", "more cpus than derivative columns.\") # Use comm to distribute columns allDerivColSlice =", "hessian value trumps since we've renormed to keep all the products within decent", "scaleVals[:, None, None] # overflow OK devec = EVec.deriv_wrt_params(E_wrtFilter2) _fas(d2pr_dErhos2, [None, E_gpindices2, rho_gpindices1],", "hessian x0 = _np.kron(_np.transpose(prods[(0, m - 1)]), prods[(m + 1, N - 1)])", "array of shape S*N x M where: - N == the number of", "entry of the i-th operation sequence product with respect to the j-th model", "dGs2 = evalSubTree.final_view(dProdCache2, axis=0) hProdCache = self._compute_hproduct_cache( evalSubTree, prodCache, dProdCache1, dProdCache2, scaleCache, blk2Comm,", "self.sos.get_operation(opLabel) op_wrtFilter, gpindices = self._process_wrtFilter(wrtFilter, gate) dop_dopLabel = gate.deriv_wrt_params(op_wrtFilter) for (i, gl) in", "a zero deriv value (see below) dGs[_np.isnan(dGs)] = 0 _np.seterr(**old_err) if flat: dGs", "'d') dprobs2 = _np.zeros((nElements, _slct.length(wrtSlice2)), 'd') else: dprobs1 = dprobs2 = None hprobs", "clip(hGs,-1e300,1e300) _np.seterr(**old_err) if flat: hGs = _np.rollaxis(_np.rollaxis(hGs, 0, 3).reshape( (nDerivCols1, nDerivCols2, nCircuits *", "model parameter. products : numpy array Only returned when bReturnDProdsAndProds == True. An", "Gs, drhoP),axis=(0,))[:,J] dp_drhos = _np.zeros((nCircuits, nDerivCols)) _fas(dp_drhos, [None, rho_gpindices], _np.squeeze(_np.dot(_np.dot(E, Gs), rhoVec.deriv_wrt_params(rho_wrtFilter)), axis=(0,))", "deriv cols, rows = all else return (hGs, dGs1, dGs2, Gs, scaleVals) if", "# _np.einsum('ij,jkl->ikl', dp_dAnyE, self.sos.get_effect(elabel).hessian_wrt_params( # E_wrtFilter1, E_wrtFilter2)) else: d2pr_d2Es = 0 # END", "the probabilities generated by a each gate sequence given by evalTree column-by-column. This", "(1, 0))) # _np.einsum('ij,jkl->ikl',derivWrtAnyEvec,self.sos.get_effect(elabel).hessian_wrt_params()) else: d2pr_d2Es = 0 ret = d2pr_dErhos + _np.transpose(d2pr_dErhos,", "uses below gpindices1 = {}; gate_wrtFilters1 = {} gpindices2 = {}; gate_wrtFilters2 =", "fill appropriate columns of flattened_dprod. _fas(flattened_hprod, [None, gpindices1, gpindices2], gate.hessian_wrt_params(op_wrtFilter1, op_wrtFilter2)) if flat:", "clipTo[1], out=prMxToFill) # in-place clip if check: self._check(evalTree, prMxToFill, mxToFill, clipTo=clipTo) profiler.add_time(\"bulk_fill_dprobs: total\",", "# cols = deriv cols, rows = flattened everything else return (dGs, Gs,", "P is is the probability generated by the sequence and spam label indexed", "axis=0) #shape == ( len(circuit_list), dim, dim ), # Gs[i] is product for", "dp_dAnyE = _np.dot(Gs, drho) * scaleVals[:, None, None] # overflow OK devec =", "_np.zeros((dim**2, num_deriv_cols), 'd') _fas(flattened_dprod, [None, gpindices], gate.deriv_wrt_params(op_wrtFilter)) # (dim**2, nParams[opLabel]) if _slct.length(gpindices) >", "hessian value, and we hGs[_np.isnan(hGs)] = 0 # assume the zero hessian value", "since we can't tell whether it's + or - inf anyway... d2pr_dOps2[_np.isnan(d2pr_dOps2)] =", "in the parameters assert(opLabel1 == opLabel2) if opLabel1 in hop_dopLabels: # indicates a", "License. You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 or", "dG(L)/dij ) ] # noqa # + sum{ L == M} [ G1", "rho_wrtFilter, rho_gpindices = self._process_wrtFilter(wrtSlice, self.sos.get_prep(rholabel)) E_wrtFilter, E_gpindices = self._process_wrtFilter(wrtSlice, self.sos.get_effect(elabel)) nDerivCols = self.Np", "the 2nd set of gate parameters if dGs1 is dGs2 and wrtSlice1 ==", "Returns a \"filter\" object containing info about the mapping # of prep and", "old_err = _np.seterr(over='ignore', invalid='ignore') Gs = _np.swapaxes(_np.swapaxes(Gs, 0, 2) * scaleVals, 0, 2)", "Could throw more informative error? #elif fnName == \"bulk_product\": # mem += cache_size", "scaleCache, comm, wrtSlice) #use cached data to construct return values old_err = _np.seterr(over='ignore')", "as these occur b/c an inf scaleVal is mult by a zero deriv", "0 # assume the zero hessian value trumps since we've renormed to keep", "by the model). This argument is used internally for distributing derivative calculations across", "for the symmetry of the Hessian, so that # if gl1 and gl2", "DERIVS (assume dGs is already sized/filtered) ------------------- assert(dGs.shape[1] == nDerivCols), \"dGs must be", "of hProdCache[:,myDeriv1ColSlice], # dim=(cacheSize,nDerivCols1,nDerivCols2,dim,dim) else: #compute \"Deriv1\" row-derivatives distribution only; don't use column", "equivalence: maybe let dGs2 be None? assert(nDerivCols1 == nDerivCols2) d2pr_drhos2 = _np.transpose(d2pr_drhos1, (0,", "as _DummyProfiler from .label import Label as _Label from .matrixevaltree import MatrixEvalTree as", "nBlks = int(_np.ceil(self.Np / blkSize)) # num blocks required to achieve desired average", "constraints make constructing the entire Hessian at once impractical, and one is able", "generating warnings when checks fail. Used for testing, and runs much slower when", "turns out to be useful when computing the Hessian of functions of the", "an index into an array of gate parameters ordered by concatenating each gate's", "_warnings.warn(\"Too many processors to make use of in \" \" _compute_hproduct_cache.\") #TODO: remove:", "return obj_wrtFilter, relevant_gpindices #Vectorizing Identities. (Vectorization) # Note when vectorizing op uses numpy.flatten", "num_param2_groups, num_final_strs): \"\"\" Estimate the memory required by a given set of subcalls", "if deriv2MxToFill is not None: _fas(deriv2MxToFill, [fInds, pslc2], self._dprobs_from_rhoE( spamTuple, rho, E, Gs[gInds],", "= _np.zeros((1, self.Np, self.Np)) _fas(d2pr_drhos, [0, None, self.sos.get_prep(rholabel).gpindices], _np.dot(_np.dot(E, dprod_dOps), rhoVec.deriv_wrt_params())[0]) # (=", "tm) profiler.mem_check(\"bulk_fill_dprobs: post compute dproduct\") #Compute all requested derivative columns at once self._fill_result_tuple((prMxToFill,", "tree that will be passed to the functions named by `subcalls`. num_subtrees :", "G(L-1)) tensor (G(L+1) ... GN)^T ]] # noqa # # So for each", "a 3D array with probability-Hessians for each \"final element\" of `evalTree`. Parameters ----------", "d12_col), where d12_col is a column of the matrix d12 defined by: d12[iSpamLabel,iOpStr,p1,p2]", "*not* allocated by the user. mem += 2 * cache_size * nspam *", "= _np.zeros(cacheSize, 'd') #First element of cache are given by evalTree's initial single-", "in an evaluation tree, `evalTree`. An initial list of (general) :class:`Circuit` objects is", "myDeriv2ColSlice, deriv2Owners, mySubSubComm = \\ _mpit.distribute_slice(allDeriv2ColSlice, mySubComm) # Get slice into entire range", "prodCache, scaleCache = self._compute_product_cache(evalSubTree, mySubComm) scaleVals = self._scaleExp(evalSubTree.final_view(scaleCache)) Gs = evalSubTree.final_view(prodCache, axis=0) #(", "Compute the hessian of a specified sequence of operation labels. Parameters ---------- circuit", "dim * dim # hproduct cache # mem += cache_size * num_params *", "rows = flattened all else dGs1 = _np.swapaxes(_np.swapaxes(dGs1, 0, 1).reshape((nDerivCols1, nCircuits * dim**2)),", "d2prod_dGates.shape[1]) d2pr_dOps2 = _np.empty((1, self.Np, self.Np)) for i in range(self.Np): for j in", "scaleCache = dProdCache = None #Fill cache info (not requiring column distribution) tm", "wrtSlice1) dGs1 = evalTree.final_view(dProdCache1, axis=0) last_wrtSlice1 = wrtSlice1 if (wrtSlice1 == wrtSlice2): dProdCache2", "takes a \"calc-and-fill\" function, which computes and *fills* (i.e. doesn't return to save", "(G(M+1) ... G(L-1))^T vec( dG(M)/dkl ) ) # noqa # tensor (G(L+1) ...", "parameters) and hessian[i,j,k] holds the derivative of the i-th entry of the flattened", "of operation labels. Parameters ---------- circuit : Circuit or tuple of operation labels", "by splitting tree beforehand), as there\" \" are more cpus than hessian elements.\")", "# each column corresponds to a (opLabel,i,j) tuple and each row corresponds to", "condition above) _mpit.gather_slices(deriv1Slices, deriv1Owners, hProdCache, [], 1, comm) #, gatherMemLimit) #gather over row-distribution", "loc_rho_slices] # tmp_offsets = [ sum(tmp_num_params[0:i]) for i in range(len(self.preps)+1) ] # global_rho_slices", "prior to the scaling. \"\"\" if bScale: scaledGatesAndExps = {} scale_exp = 0", "\"\"\" if profiler is None: profiler = _dummy_profiler dim = self.dim nDerivCols =", "rho ret += d2pr_dErhos1 + d2pr_d2Es + d2pr_dEs2 # wrt E ret +=", "estimate - could compute? wrtLen1 = (self.Np + np1 - 1) // np1", "if prMxToFill is not None: self._fill_result_tuple((prMxToFill,), evalSubTree, slice(None), slice(None), calc_and_fill_p) profiler.mem_check(\"bulk_fill_dprobs: post fill", "uniqueOpLabels: gate = self.sos.get_operation(opLabel) op_wrtFilter, gpindices = self._process_wrtFilter(wrtFilter, gate) dop_dopLabel = gate.deriv_wrt_params(op_wrtFilter) for", "(the length of rowSlice) - B' is the number of parameter columns (the", "dGs[gInds], scaleVals[gInds], wrtSlice), add=sumInto) _np.seterr(**old_err) profiler.add_time(\"bulk_fill_dprobs: calc_and_fill\", tm) #Set wrtBlockSize to use available", "multiple processors. Distribution is performed as in bulk_product, bulk_dproduct, and bulk_hproduct. Returns -------", "tm = _time.time() all_results = comm.allgather(my_results) profiler.add_time(\"MPI IPC\", tm) return _np.concatenate(all_results, axis=1) #", "NotImplementedError(\"Unitary evolution not fully supported yet!\") rholabel, elabel = spamTuple rhoVec = self.sos.get_prep(rholabel)", "effect used to compute the probability. circuit : Circuit or tuple A tuple-like", "_np.dot(_np.transpose(EVec.deriv_wrt_params()), derivWrtAnyEvec)) #Note: these 2nd derivatives are non-zero when the spam vectors have", "comm.Get_rank(), str(myDerivColSlice))) if mySubComm is not None and mySubComm.Get_size() > 1: deriv2Slices, myDeriv2ColSlice,", "0: myDeriv2ColSlice = slice(0,0) # #don't compute anything on \"extra\", i.e. rank !=", "the j-th model parameter. products : numpy array Only returned when bReturnProds ==", "_np.einsum('ij,jkl->ikl', dp_dAnyE, self.sos.get_effect(elabel).hessian_wrt_params( # E_wrtFilter1, E_wrtFilter2)) else: d2pr_d2Es = 0 # END SPAM", "(i,p,norm(G),total_exp,str(G)) # if _np.isnan(p): raise ValueError(\"STOP\") if clipTo is not None: ret =", "`elabels`. \"\"\" assert(time is None), \"MatrixForwardSimulator cannot be used to simulate time-dependent circuits\"", "scaleVals[:, None] _np.seterr(**old_err2) # may overflow, but OK ; shape == (len(circuit_list), nDerivCols)", "need to: # - alter product, dproduct, etc. to allow for *complex* derivatives,", "\"\"\" Return the hessian of a length-1 (single-gate) sequence \"\"\" dim = self.dim", "subtrees\") if clipTo is not None and prMxToFill is not None: _np.clip(prMxToFill, clipTo[0],", "OK devec = EVec.deriv_wrt_params(E_wrtFilter1) _fas(d2pr_dEs2, [None, None, E_gpindices1], _np.dot(dp_dAnyE, devec)) d2pr_dEs2 = _np.transpose(d2pr_dEs2,", "(i.e. evalTree.num_final_elements()) evalTree : EvalTree given by a prior call to bulk_evaltree. Specifies", "uses the convention that rho has shape (N,1) rho = self.sos.get_prep(rholabel).todense()[:, None] E", "beforehand), as there\" \" are more cpus than hessian elements.\") # pragma: no", "block of derivative columns if prMxToFill is not None: self._fill_result_tuple((prMxToFill,), evalSubTree, slice(None), slice(None),", "\"statevec\": raise NotImplementedError(\"Unitary evolution not fully supported yet!\") rholabel, elabel = spamTuple rhoVec", "\" are more cpus than derivative columns.\") # Use comm to distribute columns", "d(opLabel)_mn = sum E_k [dprod/d(opLabel)_mn]_ki (and same for other diff order) # d2pr/d(E)_i", "G operation matrices) and hessians[i,j,k,l,m] holds the derivative of the (l,m)-th entry of", "overflow or get nans (invalid), but ok hGs = _np.swapaxes(_np.swapaxes(hGs, 0, 4) *", "E = self._rhoE_from_spamTuple(spamTuple) if prMxToFill is not None: _fas(prMxToFill, [fInds], self._probs_from_rhoE(rho, E, Gs[gInds],", "from previous subtree iteration before computing caches scaleVals = Gs = dGs1 =", "if _slct.length(gpindices1) > 0 and _slct.length(gpindices2) > 0: # works for arrays too", "is used internally for distributing calculations across multiple processors and to control memory", "d2pr_dOps2[_np.isnan(d2pr_dOps2)] = 0 # SPAM DERIVS (assume dGs1 and dGs2 are already sized/filtered)", "_np.seterr(over='ignore') rho, E = self._rhoE_from_spamTuple(spamTuple) if prMxToFill is not None: _fas(prMxToFill, [fInds], self._probs_from_rhoE(rho,", "d2pr_d2rhos = 0 if self.sos.get_effect(elabel).has_nonzero_hessian(): derivWrtAnyEvec = scale * _np.transpose(_np.dot(prod, rho)) # may", "\"\"\" Compute and fill result quantities blocks for given arguments \"\"\" tm =", "None # free mem dProdCache1 = dGs1 = None # free mem #gather", "myBlkIndices, blkOwners, blkComm = \\ _mpit.distribute_indices(list(range(nBlks)), mySubComm) if blkComm is not None: _warnings.warn(\"Note:", "objects giving the *simplified* effect labels. circuit : Circuit or tuple A tuple-like", "#Vectorizing Identities. (Vectorization) # Note when vectorizing op uses numpy.flatten rows are kept", "of SPAMVec (or array) # objects: (prepVec, effectVec) rho, Eraw = spamTuple E", "if returnPr: return dpr_drhos + dpr_dEs + dpr_dOps, p else: return dpr_drhos +", "a 1 x M x M array, where M is the number of", "index numpy arrays # like length>1 lists do... ugh. relevant_gpindices = slice(relevant_gpindices[0], relevant_gpindices[0]", "enumerate(revOpLabelList): # loop over \"starting\" gate prods[(i, i - 1)] = ident #", "DEBUG: %d rescalings out of %d products\" % (cnt, len(evalTree)) nanOrInfCacheIndices = (~_np.isfinite(prodCache)).nonzero()[0]", "np2) mem = 0 for fnName in subcalls: if fnName == \"bulk_fill_probs\": mem", "number of parameter columns (the length of colSlice) If `mx`, `dp1`, and `dp2`", "Computes a tree of product 2nd derivatives in a linear cache space. Will", "array of gate parameters ordered by concatenating each gate's parameters (in the order", "d2pr_dEs + _np.transpose(d2pr_dEs, (0, 2, 1)) + \\ d2pr_d2rhos + d2pr_d2Es + d2pr_dOps2", "list A list of `(rowSlice,colSlice)` 2-tuples, each of which specify a \"block\" of", "= evalTree.final_view(prodCache, axis=0) #shape == ( len(circuit_list), dim, dim ), Gs[i] is product", "# Gs[i] is product for i-th operation sequence dGs = evalTree.final_view(dProdCache, axis=0) #shape", "_np.einsum('ij,jkl->ikl', dp_dAnyRho, self.sos.get_prep(rholabel).hessian_wrt_params( # rho_wrtFilter1, rho_wrtFilter2)) else: d2pr_d2rhos = 0 if self.sos.get_effect(elabel).has_nonzero_hessian(): dp_dAnyE", "nG; total_exp += log(nG) # scale and keep track of exponent # #", "multiple processors. Returns ------- hessian : numpy array * if flat == False,", "scale vals elif fnName == \"bulk_hprobs_by_block\": #Note: includes \"results\" memory since this is", "comm.Get_size() > nDerivCols1 * nDerivCols2: #If there are more processors than deriv cells,", "_nla.norm(dprMxToFill[fInds] - check_vdp))) # pragma: no cover if hprMxToFill is not None: check_vhp", "_fill_result_tuple(self, result_tup, evalTree, param_slice1, param_slice2, calc_and_fill_fn): \"\"\" This function takes a \"calc-and-fill\" function,", "When True, return a scaling factor (see below). Returns ------- product : numpy", "mySubComm, wrtSlice1) dProdCache2 = dProdCache1 if (wrtSlice1 == wrtSlice2) else \\ self._compute_dproduct_cache(evalSubTree, prodCache,", "control bulk products, their gradients, and their Hessians. PSMALL = 1e-100 DSMALL =", "processors. Returns ------- deriv : numpy array * if flat == False, a", "is given, otherwise no parallelization is performed. Returns ------- prods : numpy array", "new MatrixForwardSimulator object. Parameters ---------- dim : int The gate-dimension. All operation matrices", "memory from previous subtree iteration before computing caches scaleVals = Gs = dGs", "mult by a zero deriv value, and we dGs[_np.isnan(dGs)] = 0 # assume", "save mem) but isn't gathered until now (but using blk1Comm). # (just as", "OK d2pr_drhos2 = _np.transpose(d2pr_drhos2, (0, 2, 1)) # Get: d2pr_dEs[i, j, E_gpindices] =", "copy of this MatrixForwardSimulator \"\"\" return MatrixForwardSimulator(self.dim, self.sos, self.paramvec) def product(self, circuit, bScale=False):", "more than linear dependence on their parameters. if self.sos.get_prep(rholabel).has_nonzero_hessian(): derivWrtAnyRhovec = scale *", "parameter. * if flat == True, a N x M array, where: -", "= self._process_wrtFilter(wrtSlice1, self.sos.get_prep(rholabel)) rho_wrtFilter2, rho_gpindices2 = self._process_wrtFilter(wrtSlice2, self.sos.get_prep(rholabel)) E_wrtFilter1, E_gpindices1 = self._process_wrtFilter(wrtSlice1, self.sos.get_effect(elabel))", "_np.seterr(invalid='ignore', over='ignore') d2pr_dOps2 = _np.squeeze(_np.dot(E, _np.dot(hGs, rho)), axis=(0, 4)) * scaleVals[:, None, None]", "The final argument is a boolean specifying whether the filling should overwrite or", "= _np.identity(dim); rightProdsT.append(_np.transpose(G)) for opLabel in reversed(revOpLabelList): G = _np.dot(self.sos.get_operation(opLabel).todense(), G) rightProdsT.append(_np.transpose(G)) #", "each pair of gates in the string, compute the hessian of the entire", "to bulk_evaltree. Specifies the operation sequences to compute the bulk operation on. This", "sum_{L s.t. G(L) == oplabel} [ G1 ... G(L-1) dG(L)/dij G(L+1) ... GN", "Gs.shape[0] rho_wrtFilter1, rho_gpindices1 = self._process_wrtFilter(wrtSlice1, self.sos.get_prep(rholabel)) rho_wrtFilter2, rho_gpindices2 = self._process_wrtFilter(wrtSlice2, self.sos.get_prep(rholabel)) E_wrtFilter1, E_gpindices1", "for the i-th operation sequence. \"\"\" nCircuits = evalTree.num_final_strings() nDerivCols = self.Np if", "dimension. This argument is used internally for distributing calculations across multiple processors and", "self).__init__( dim, simplified_op_server, paramvec) if self.evotype not in (\"statevec\", \"densitymx\"): raise ValueError((\"Evolution type", "achieve desired average size == blkSize1 or blkSize2 blocks1 = _mpit.slice_up_range(self.Np, nBlks1) blocks2", ": boolean, optional If True, perform extra checks within code to verify correctness,", "is not None: _mpit.gather_indices(subtreeElementIndices, subTreeOwners, deriv1MxToFill, [], 0, comm, gatherMemLimit) if deriv2MxToFill is", "None. Set this to non-None to reduce amount of intermediate memory required. profiler", "H old_err = _np.seterr(over='ignore') scale = _np.exp(scale_exp) _np.seterr(**old_err) return G, scale else: G", "Gs = _np.swapaxes(_np.swapaxes(Gs, 0, 2) * scaleVals, 0, 2) # may overflow, but", "None, a list of integers specifying which gate parameters to include in the", "we're # assuming that the gates are at most linear in their parameters,", "the root pyGSTi directory. #*************************************************************************************************** import warnings as _warnings import numpy as _np", "inf scaleVal is mult by a zero deriv value (see below) dGs2[_np.isnan(dGs2)] =", "# Note: scaleCache[i] = 0.0 from initialization else: gate = self.sos.get_operation(opLabel).todense() nG =", "yield wrtSlice1, wrtSlice2, hprobs, dprobs12 else: yield wrtSlice1, wrtSlice2, hprobs dProdCache1 = dGs1", "length of spam_label_rows, - S is the number of operation sequences (i.e. evalTree.num_final_strings()),", "xv = x.view() # (nDerivCols1,dim**2) xv.shape = (nDerivCols1, dim, dim) # (reshape without", "SPAMVec, and SPAMVec objects, respectively. Must be *ordered* dictionaries to specify a well-defined", "y = _np.dot(_np.kron(xv, _np.transpose(prods[(l + 1, N - 1)])), dop_dopLabel2[opLabel2]) # above: (nDerivCols1,dim**2,dim**2)", "each opLabel the matrix [ sum_{L s.t. GL == oplabel} [ (G1 ...", "block size. These arguments must be None if the corresponding wrtFilter is not", "= blocks2[iBlk2] self._fill_result_tuple((prMxToFill, deriv1MxToFill, deriv2MxToFill, mxToFill), evalSubTree, blocks1[iBlk1], blocks2[iBlk2], calc_and_fill) hProdCache = hGs", "# and has given each processor a list appropriate for it. # Use", "the # gate's parameters and fill appropriate columns of flattened_dprod. _fas(flattened_hprod, [None, gpindices1,", "else return (hGs, dGs1, dGs2, Gs, scaleVals) if bScale else (hGs, dGs1, dGs2,", "prod_kl rho_l # dpr/d(opLabel)_ij = sum E_k [dprod/d(opLabel)_ij]_kl rho_l # dpr/d(rho)_i = sum", "scaleVals else: old_err = _np.seterr(over='ignore') Gs = _np.swapaxes(_np.swapaxes(Gs, 0, 2) * scaleVals, 0,", "an inf scaleVal is mult by a zero deriv value (see below) dGs1[_np.isnan(dGs1)]", "distribution over a split evalTree (if given) is possible. wrtFilter : list of", "swapaxes(dot(dEPT,prod,drhoP),0,1)[:,J,K] d2pr_dErhos1 = _np.zeros((nCircuits, nDerivCols1, nDerivCols2)) drho = rhoVec.deriv_wrt_params(rho_wrtFilter2) dp_dAnyE = _np.dot(Gs, drho)", "of the raw operation sequences which need to be computed # for the", "... GN ] , a matrix for each given (i,j) # noqa #", "instrument elements like 'Imyinst_0') clipTo : 2-tuple (min,max) to clip returned probability to", "is not None: _mpit.gather_slices(blocks1, blk1Owners, deriv1MxToFill, [felInds], 1, mySubComm, gatherMemLimit) if deriv2MxToFill is", "gatherMemLimit=None): \"\"\" Compute the outcome probability-Hessians for an entire tree of gate strings.", "this routine will run slightly faster, but with a chance that the product", "usage. gatherMemLimit : int, optional A memory limit in bytes to impose upon", "the given # wrtSlicesList last_wrtSlice1 = None # keep last dProdCache1 for wrtSlice1,", "the case, need LinearOperator objects to # have a 2nd-deriv method in addition", "\" (e.g. by splitting tree beforehand), as there\" \" are more cpus than", "must be pre-filtered!\" assert(hGs.shape[2] == nDerivCols2), \"hGs must be pre-filtered!\" #Compute d2(probability)/dGates2 and", "ret += d2pr_drhos1 + d2pr_dEs1 + d2pr_dOps2 # wrt gates return ret def", "X * B ) = A tensor B^T * vec( X ) #", "vgs x GxG ; hL,hR = vgs x vgs x GxG dLdRa =", "+ dpr_dOps, p else: return dpr_drhos + dpr_dEs + dpr_dOps def hpr(self, spamTuple,", "partial products (relatively little mem required) prods = {} ident = _np.identity(dim) for", "== the number of entries in a single flattened gate (ordering is the", "obtained by `evalTree.num_final_elements()`. To interpret which elements correspond to which strings and outcomes,", "E_wrtFilter1, E_gpindices1 = self._process_wrtFilter(wrtSlice1, self.sos.get_effect(elabel)) E_wrtFilter2, E_gpindices2 = self._process_wrtFilter(wrtSlice2, self.sos.get_effect(elabel)) nDerivCols1 = self.Np", "by a given set of subcalls to computation functions. Parameters ---------- subcalls :", "return the probabilities. bScale : bool, optional When True, return a scaling factor", "ret, p else: return ret ## BEGIN CACHE FUNCTIONS def _compute_product_cache(self, evalTree, comm=None):", "being differentiated with respect to when the *second* derivative is taken. If there", "gate_wrtFilters2[l], gpindices2[l] = self._process_wrtFilter(wrtFilter2, used_operations[l]) #Cache partial products (relatively little mem required) prods", "slice(None), calc_and_fill) hProdCache = hGs = dProdCache2 = dGs2 = None # free", "in enumerate(revOpLabelList): inds1 = gpindices1[opLabel1] nDerivCols1 = dop_dopLabel1[opLabel1].shape[1] if nDerivCols1 == 0: continue", "array of derivatives of the probability w.r.t. each model parameter. probability : float", "= self.sos.get_effect(elabel) # arrays, these are SPAMVecs d2prod_dGates = self.hproduct(circuit) assert(d2prod_dGates.shape[0] == d2prod_dGates.shape[1])", "wrtBlockSize wrtSlice1 = _slct.list_to_slice(wrtFilter1) else: wrtSlice1 = None if wrtFilter2 is not None:", ": bool, optional When True, return a scaling factor (see below). Returns -------", "import numpy as _np import numpy.linalg as _nla import time as _time import", "# return PrepEffectFilter(rho_local_slices=loc_rho_slices, # rho_global_slices=global_rho_slices, # e_local_slices=loc_e_slices, # e_global_slices=global_e_slices, # num_rho_params=self.tot_rho_params, # num_e_params=self.tot_e_params)", "within decent # bounds #assert( len( (_np.isnan(hGs)).nonzero()[0] ) == 0 ) #assert( len(", "(G(M+1) ... GN)^T vec( d2G(M)/dkl*dji ) # noqa # # Note: ignoring L", "bUseScaling : bool, optional Whether to use a post-scaled product internally. If False,", "[slice(None,None)]*len(self.preps) # loc_e_slices = [slice(None,None)]*len(self.effects) # global_rho_slices = [slice(self.rho_offset[i],self.rho_offset[i+1]) for i in range(len(self.preps))", "# num blocks required to achieve desired average size == blkSize1 or blkSize2", "blk1Owners, deriv1MxToFill, [felInds], 1, mySubComm, gatherMemLimit) if deriv2MxToFill is not None: _mpit.gather_slices(blocks2, blk2Owners,", "product or scaled product of the operation matrices. scale : float Only returned", "True, additionally return the probabilities and their derivatives (see below). bScale : bool,", "conjuction with wrtBlockSize. wrtBlockSize : int or float, optional The maximum number of", "m < l: x0 = _np.kron(_np.transpose(prods[(0, m - 1)]), prods[(m + 1, l", "and wrtBlockSize wrtSlice1 = _slct.list_to_slice(wrtFilter1) else: wrtSlice1 = None if wrtFilter2 is not", "blk1Comm, gatherMemLimit) #gather row results; gather axis 1 of mxToFill[felInds], dim=(ks,M,M) _mpit.gather_slices(blocks1, blk1Owners,", "zero dimension else: obj_wrtFilter = None relevant_gpindices = obj.gpindices return obj_wrtFilter, relevant_gpindices #Vectorizing", "distribute itself among the available processors. Returns ------- MatrixEvalTree \"\"\" evTree = _MatrixEvalTree()", "other diff order) # d2pr/d(E)_i d(E)_j = 0 # d2pr/d(rho)_i d(rho)_j = 0", "of the flattened product with respect to the j-th model parameter. \"\"\" #", "if comm.Get_size() > nDerivCols1 * nDerivCols2: #If there are more processors than deriv", "and dProdCache[i].max() < DSMALL and dProdCache[i].min() > -DSMALL: _warnings.warn(\"Would have scaled dProd but", "rows = flattened everything else return (dGs, Gs, scaleVals) if bScale else (dGs,", "= doperation / _np.exp(scaleCache[i]) #profiler.print_mem(\"DEBUGMEM: POINT1\"); profiler.comm.barrier() #evaluate operation sequences using tree (skip", "sum E_k prod_kl rho_l # d2pr/d(opLabel1)_mn d(opLabel2)_ij = sum E_k [dprod/d(opLabel1)_mn d(opLabel2)_ij]_kl rho_l", "of entries in a single flattened gate (ordering is the same as that", "matrixOf(circuit[iLeft]) * matrixOf(circuit[iRight]) (iRight, iLeft) = evalTree[i] L, R = prodCache[iLeft], prodCache[iRight] dL1,", "= _collections.namedtuple( # 'PrepEffectFilter', 'rho_local_slices rho_global_slices ' + # 'e_local_slices e_global_slices num_rho_params num_e_params')", "by a operation sequence and spam tuple as a 1 x M numpy", "bool, optional Whether to use a post-scaled product internally. If False, this routine", "have G,dG => product, dprod_dOps) # prod, dprod_dOps = G,dG # dp_dOps[i,j] =", "has given each processor a list appropriate for it. # Use comm only", "derivs : numpy array * if flat == False, an array of shape", "wrtFilter=wrtIndices) dProdCache[i] = doperation / _np.exp(scaleCache[i]) #profiler.print_mem(\"DEBUGMEM: POINT1\"); profiler.comm.barrier() #evaluate operation sequences using", "or tuple A tuple-like object of *simplified* gates (e.g. may include instrument elements", "d2pr_dOps2 # wrt gates return ret def _check(self, evalTree, prMxToFill=None, dprMxToFill=None, hprMxToFill=None, clipTo=None):", "into a lists of gate-only sequences along with a mapping of final elements", "both wrtFilter and wrtBlockSize wrtSlice = _slct.list_to_slice(wrtFilter) else: wrtSlice = None profiler.mem_check(\"bulk_fill_dprobs: begin", "mySubComm = \\ _mpit.distribute_slice(allDerivColSlice, comm) #print(\"MPI: _compute_dproduct_cache over %d cols (%s) (rank %d", "post-scaled product internally. If False, this routine will run slightly faster, but with", "% len(circuit) _warnings.warn(\"pr(%s) == nan\" % strToPrint) #DEBUG: print \"backtrace\" of product leading", "numpy array a 1 x M x M array, where M is the", "in range(len(self.preps))] # tmp_num_params = [_slct.length(s) for s in loc_rho_slices] # tmp_offsets =", "the parameters being differentiated with respect to (see wrtBlockSize). wrtFilter1, wrtFilter2 : list", "... GN)^T vec( dG(M)/dkl ) ) )^T vec( dG(L)/dij ) ] # noqa", "need LinearOperator objects to # have a 2nd-deriv method in addition of deriv_wrt_params", "# have a 2nd-deriv method in addition of deriv_wrt_params # # Note: unvec(", "len(revOpLabelList) for m, opLabel1 in enumerate(revOpLabelList): inds1 = gpindices1[opLabel1] nDerivCols1 = dop_dopLabel1[opLabel1].shape[1] if", "any further parallelization _mpit.gather_slices(deriv2Slices, deriv2Owners, hProdCache, [None, myDeriv1ColSlice], 2, mySubComm) # , gatherMemLimit)", "the elements of `result_tup`. The fill function computes values for only a single", "wrtSlice _, myDerivColSlice, _, mySubComm = \\ _mpit.distribute_slice(allDerivColSlice, comm) #print(\"MPI: _compute_dproduct_cache over %d", "to keep prod managable.\") elif _np.count_nonzero(hProdCache[i]) and hProdCache[i].max() < HSMALL and hProdCache[i].min() >", "#assert( len( (_np.isnan(hGs)).nonzero()[0] ) == 0 ) #assert( len( (_np.isinf(hGs)).nonzero()[0] ) == 0", "is needed) # transposes each of the now un-vectorized dim x dim mxs", "3D array with probability-Hessians for each \"final element\" of `evalTree`. Parameters ---------- mxToFill", "If not None, a list of integers specifying which gate parameters to differentiate", "bulk_fill_hprobs(self, mxToFill, evalTree, prMxToFill=None, deriv1MxToFill=None, deriv2MxToFill=None, clipTo=None, check=False, comm=None, wrtFilter1=None, wrtFilter2=None, wrtBlockSize1=None, wrtBlockSize2=None,", "groups. num_final_strs : int The number of final strings (may be less than", "- check_vhp[0]) > 1e-6: _warnings.warn(\"norm(vhp-check_vhp) = %g - %g = %g\" % (_nla.norm(hprMxToFill[fInds]),", "mx w/ row_i = A[i,0] * B[row1] ) = A tensor B^T *", "= L / nL, R / nR prodCache[i] = _np.dot(sL, sR); scaleCache[i] +=", "# (nDerivCols1,nDerivCols2,dim**2) x = _np.dot(_np.transpose(hop_dopLabels[opLabel1], axes=(1, 2, 0)), x0); xv = x.view() xv", "_np.clip(p, clipTo[0], clipTo[1]) dprod_dOps = self.dproduct(circuit) assert(dprod_dOps.shape[0] == self.Np) if returnDeriv: # same", "= self._scaleExp(evalSubTree.final_view(scaleCache)) Gs = evalSubTree.final_view(prodCache, axis=0) #( nCircuits, dim, dim ) def calc_and_fill(spamTuple,", "as in # dproduct(...) and find the labels in the string which match", "which specify the operation sequences to create an evaluation tree out of (most", "dproduct blk (expect \" \" +%.2fGB, shape=%s)\" % (dProdCache.nbytes / (1024.0**3), str(dProdCache.shape))) dGs", "wrtLen2) * dim * dim # dproduct cache mem += cache_size * dim", "B ) = A tensor B^T * vec( X ) # if vec(.)", "time-dependent circuits\" rho, Es = self._rhoEs_from_spamTuples(rholabel, elabels) #shapes: rho = (N,1), Es =", "done any such distribution # and has given each processor a list appropriate", "self.dim #Note: previously, we tried to allow for parallelization of # _compute_product_cache when", "there are no memory savings from using a split tree. \"\"\" if profiler", "the computation across multiple processors. Distribution is performed as in bulk_product, bulk_dproduct, and", "of ints, optional If not None, a list of integers specifying which model", "flattened_d2prod. #NOTE: if we needed to perform a hessian calculation (i.e. for l==m)", "> -PSMALL: nG = max(_nla.norm(G), _np.exp(-scale_exp)) G = _np.dot(gate, G / nG); scale_exp", "clipTo=clipTo) def bulk_fill_dprobs(self, mxToFill, evalTree, prMxToFill=None, clipTo=None, check=False, comm=None, wrtFilter=None, wrtBlockSize=None, profiler=None, gatherMemLimit=None):", "scaleCache = self._compute_product_cache(evalSubTree, mySubComm) #use cached data to final values scaleVals = self._scaleExp(evalSubTree.final_view(scaleCache))", "scaleCache, mySubComm, wrtSlice2) dGs1 = evalSubTree.final_view(dProdCache1, axis=0) dGs2 = evalSubTree.final_view(dProdCache2, axis=0) #( nCircuits,", "old_err = _np.seterr(over='ignore') rho, E = self._rhoE_from_spamTuple(spamTuple) #if prMxToFill is not None: #", "Hessian at a time. For example, the Hessian of a function of many", "convention: Es has shape (len(elabels),N) return rho, Es def _probs_from_rhoE(self, rho, E, Gs,", "M array, where: - N == the number of entries in a single", "* scaleVals[:, None, None] # overflow OK devec = EVec.deriv_wrt_params(E_wrtFilter1) _fas(d2pr_dErhos1, (None, E_gpindices1,", "length-1 (single-gate) sequence \"\"\" dim = self.dim gate = self.sos.get_operation(opLabel) op_wrtFilter1, gpindices1 =", "Note: scaleCache[i] = 0.0 from initialization else: gate = self.sos.get_operation(opLabel).todense() nG = max(_nla.norm(gate),", "doesn't merit a warning # ------------------------------------------------------------------ if evalTree.is_split(): _warnings.warn(\"Ignoring tree splitting in product", "nDerivCols1, nDerivCols2) flattened_d2prod[:, inds1, inds2] += xv if flat: return flattened_d2prod # axes", "of functions of the probabilities. comm : mpi4py.MPI.Comm, optional When not None, an", "means compute all requested columns at once. The minimum of wrtBlockSize and the", "x G x G array, where: - M == length of the vectorized", "copying - throws error if copy is needed) y = _np.dot(_np.kron(xv, _np.transpose(prods[(l +", "dProd but now will not alter scaleCache.\") #profiler.print_mem(\"DEBUGMEM: POINT2\"); profiler.comm.barrier() profiler.add_time(\"compute_dproduct_cache: serial\", tSerialStart)", "def bulk_fill_probs(self, mxToFill, evalTree, clipTo=None, check=False, comm=None): \"\"\" Compute the outcome probabilities for", "tuple(reversed(tuple(circuit))) N = len(revOpLabelList) # length of operation sequence # prod = G1", "first (row) and second (col) derivative operations, respectively. wrtBlockSize2, wrtBlockSize2 : int or", "for (j, opLabel2) in enumerate(revOpLabelList[i:], start=i): # loop over \"ending\" gate (>= starting", "tree, `evalTree`. An initial list of (general) :class:`Circuit` objects is *simplified* into a", "(see wrtBlockSize). wrtFilter : list of ints, optional If not None, a list", "devec = EVec.deriv_wrt_params(E_wrtFilter2) _fas(d2pr_dEs1, [None, None, E_gpindices2], _np.dot(dp_dAnyE, devec)) # get d2pr_dEs where", "ugh. relevant_gpindices = slice(0, 0) # slice that results in a zero dimension", "gates (e.g. may include instrument elements like 'Imyinst_0') returnPr : bool when set", "scale vals ## It doesn't make sense to include these since their required", "optional When True, return a scaling factor (see below). comm : mpi4py.MPI.Comm, optional", "parallelization tm = _time.time() all_results = comm.allgather(my_results) profiler.add_time(\"MPI IPC\", tm) return _np.concatenate(all_results, axis=1)", "(exps) mem += cache_size # scale vals elif fnName == \"bulk_fill_dprobs\": mem +=", "fnName == \"bulk_dproduct\": # mem += cache_size * num_params * dim * dim", "Gs, scaleVals): if self.evotype == \"statevec\": raise NotImplementedError(\"Unitary evolution not fully supported yet!\")", "Compute and fill result quantities blocks for given arguments \"\"\" tm = _time.time()", "overflow and the subsequent trace operation will yield nan as the returned probability.", "[spamTuple[1]], circuit, clipTo, False)[0] for circuit in circuit_list]) if _nla.norm(prMxToFill[fInds] - check_vp) >", "# convention: Es has shape (len(elabels),N) return rho, Es def _probs_from_rhoE(self, rho, E,", "gate (ordering as numpy.flatten) - M == length of the vectorized model (number", "... GN)^T vec( dG(L)/dij ) ] # noqa # = [ sum_{L s.t.", "= myDeriv1ColSlice #print(\"MPI: _compute_hproduct_cache over %d cols (rank %d computing %s)\" \\ #", "the outcome probability-Hessians for an entire tree of gate strings. Similar to `bulk_fill_probs(...)`,", "else: return dpr_drhos + dpr_dEs + dpr_dOps def hpr(self, spamTuple, circuit, returnPr, returnDeriv,", "for l==m) then # it could make sense to iterate through the self.operations.keys()", "include in the derivative. Each element is an index into an array of", "probability-derivative computations: dpr/dx -> d|pr|^2/dx = d(pr*pr.C)/dx = dpr/dx*pr.C + pr*dpr/dx.C # =", "is computed fully on each inner loop *iteration*!) #collect/gather results subtreeElementIndices = [t.final_element_indices(evalTree)", "symmetry of the Hessian, so that # if gl1 and gl2 are both", "wrtFilter and wrtBlockSize wrtSlice1 = _slct.list_to_slice(wrtFilter1) else: wrtSlice1 = None if wrtFilter2 is", "multiple processors. This is done over operation sequences when a *split* evalTree is", "columns at once. The minimum of wrtBlockSize and the size that makes maximal", "dprobs2, hprobs), evalTree, slice(None), slice(None), calc_and_fill) hProdCache = hGs = dProdCache2 = dGs2", "vec( dG(L)/dij ) ] # noqa # + sum{ L < M} [", "B ) = vec( mx w/ row_i = A[i,0] * B[row1] ) =", "can often be computed column-by-column from the using the columns of the operation", "`evalTree`. An initial list of (general) :class:`Circuit` objects is *simplified* into a lists", "evalTree.final_view(dProdCache1, axis=0) last_wrtSlice1 = wrtSlice1 if (wrtSlice1 == wrtSlice2): dProdCache2 = dProdCache1; dGs2", "comm.Get_size() > nDerivCols: #If there are more processors than deriv cols, give a", "= 1e-100 class MatrixForwardSimulator(ForwardSimulator): \"\"\" Encapsulates a calculation tool used by model objects", "if prMxToFill is not None: _fas(prMxToFill, [fInds], self._probs_from_rhoE( rho, E, Gs[gInds], scaleVals[gInds]), add=sumInto)", "hGs = dProdCache2 = dGs2 = None # free mem if bReturnDProbs12: dprobs12", "per-gate hessians can be computed properly if wrtSlice1 is not None and wrtSlice1.start", "0, 3) * scaleVals, 0, 3) # convert nans to zero, as these", "= _np.zeros((dim**2, num_deriv_cols), 'd') # For each operation label, compute the derivative of", "# arrays, these are SPAMVecs d2prod_dGates = self.hproduct(circuit) assert(d2prod_dGates.shape[0] == d2prod_dGates.shape[1]) d2pr_dOps2 =", "dG(M)/dkl ) ) )^T vec( dG(L)/dij ) ] # noqa # + sum{", "dProdCache[i].min() > -DSMALL: _warnings.warn(\"Scaled dProd small in order to keep prod managable.\") elif", "= the \"element\" indices in the final # filled quantity combining both spam", "computes the 2nd derivatives of the probabilities generated by a each gate sequence", "G operation matrices) and derivs[i,j,k,l] holds the derivative of the (k,l)-th entry of", "else: return _np.transpose(flattened_hprod, (1, 2, 0)).reshape( (num_deriv_cols1, num_deriv_cols2, dim, dim)) # axes =", "%.1f, nBlks=%d]\" % (blkSize, nBlks)) # pragma: no cover def calc_and_fill_blk(spamTuple, fInds, gInds,", "= rhoVec.deriv_wrt_params(rho_wrtFilter2) d2pr_drhos1 = _np.zeros((nCircuits, nDerivCols1, nDerivCols2)) _fas(d2pr_drhos1, [None, None, rho_gpindices2], _np.squeeze(_np.dot(_np.dot(E, dGs1),", "= evalTree.num_final_elements() #Fill product cache info (not distributed) prodCache, scaleCache = self._compute_product_cache(evalTree, comm)", "To interpret which elements correspond to which strings and outcomes, you'll need the", "cover if dprMxToFill is not None: check_vdp = _np.concatenate( [self.dpr(spamTuple, circuit, False, clipTo)", "+ dpr_dEs + dpr_dOps, p else: return dpr_drhos + dpr_dEs + dpr_dOps def", "if (wrtSlice is not None) else None for i, opLabel in zip(evalTree.get_init_indices(), evalTree.get_init_labels()):", "dprod_dOps), rhoVec.deriv_wrt_params())[0]) # (= [0,:,:]) d2pr_dEs = _np.zeros((1, self.Np, self.Np)) derivWrtAnyEvec = _np.squeeze(_np.dot(dprod_dOps,", "nDerivCols1 * nDerivCols2: #If there are more processors than deriv cells, give a", "np1 # ceiling(num_params / np1) wrtLen2 = (self.Np + np2 - 1) //", "when prMxToFill is not None. Returns ------- hessian : numpy array a 1", "None # free mem #gather column results: gather axis 2 of mxToFill[felInds,blocks1[iBlk1]], dim=(ks,blk1,M)", "product for i-th operation sequence dGs1 = evalTree.final_view(dProdCache1, axis=0) dGs2 = evalTree.final_view(dProdCache2, axis=0)", "# + sum{M==L} [ G1 ... G(M-1) d2G(M)/(dkl*dij) G(M+1) ... GN ] #", "check_vdp = _np.concatenate( [self.dpr(spamTuple, circuit, False, clipTo) for circuit in circuit_list], axis=0) if", "does) # vec( A * E(0,1) * B ) = vec( mx w/", "are non-zero when the spam vectors have # a more than linear dependence", "not None, an already-allocated ExM numpy array that is filled with probability derivatives,", "dpr_drhos = _np.zeros((1, self.Np)) derivWrtAnyRhovec = scale * _np.dot(E, prod) _fas(dpr_drhos, [0, self.sos.get_prep(rholabel).gpindices],", "else: # axes = (gate_ij, prod_row, prod_col) return _np.swapaxes(flattened_dprod, 0, 1).reshape((num_deriv_cols, dim, dim))", "numpy array of derivatives of the probability w.r.t. each model parameter (M is", "little mem required) dop_dopLabel1 = { opLabel: gate.deriv_wrt_params(gate_wrtFilters1[opLabel]) for opLabel, gate in used_operations.items()}", "#Compute probability and save in return array # want vp[iFinal] = float(dot(E, dot(G,", "bulk operation on. prMxToFill : numpy array, optional when not None, an already-allocated", "for each opLabel the matrix [ sum_{L s.t. GL == oplabel} [ (G1", "start=i): # loop over \"ending\" gate (>= starting gate) G = _np.dot(G, self.sos.get_operation(opLabel2).todense())", "str(circuit) else: strToPrint = str(circuit[0:10]) + \" ... (len %d)\" % len(circuit) _warnings.warn(\"pr(%s)", ") )^T vec( dG(L)/dij ) ] # noqa # + sum{ L ==", ") def calc_and_fill(spamTuple, fInds, gInds, pslc1, pslc2, sumInto): \"\"\" Compute and fill result", "spamTuple (this list has the SAME length as fInds). calc_and_fill_fn(spamTuple, fInds, gInds, pslc1,", "axis=0) #( nCircuits, dim, dim ) profiler.mem_check(\"bulk_fill_dprobs: post compute product\") def calc_and_fill(spamTuple, fInds,", "prs(self, rholabel, elabels, circuit, clipTo, bUseScaling=False, time=None): \"\"\" Compute probabilities of a multiple", "== \"bulk_fill_hprobs\": mem += cache_size * wrtLen1 * wrtLen2 * dim * dim", "wrtSlice) #use cached data to construct return values old_err = _np.seterr(over='ignore') scaleExps =", "(KM,N,N') yield wrtSlice1, wrtSlice2, hprobs, dprobs12 else: yield wrtSlice1, wrtSlice2, hprobs dProdCache1 =", "M numpy array of derivatives of the probability w.r.t. each model parameter (M", "now (but using blk1Comm). # (just as prMxToFill is computed fully on each", "'d') _fas(flattened_dprod, [None, gpindices], gate.deriv_wrt_params(op_wrtFilter)) # (dim**2, nParams[opLabel]) if _slct.length(gpindices) > 0: #", "= _np.zeros((1, self.Np)) _fas(dpr_drhos, [0, self.sos.get_prep(rholabel).gpindices], _np.dot(derivWrtAnyRhovec, rhoVec.deriv_wrt_params())) # may overflow, but OK", "d(opLabel)_mn = sum [dprod/d(opLabel)_mn]_il rho_l (and same for other diff order) # d2pr/d(E)_i", "are SPAMVecs nCircuits = Gs.shape[0] rho_wrtFilter, rho_gpindices = self._process_wrtFilter(wrtSlice, self.sos.get_prep(rholabel)) E_wrtFilter, E_gpindices =", "nCircuits = Gs.shape[0] rho_wrtFilter1, rho_gpindices1 = self._process_wrtFilter(wrtSlice1, self.sos.get_prep(rholabel)) rho_wrtFilter2, rho_gpindices2 = self._process_wrtFilter(wrtSlice2, self.sos.get_prep(rholabel))", "- 1)] = ident # product of no gates G = ident for", "num_deriv_cols2 return _np.rollaxis(flattened_d2prod, 0, 3).reshape((vec_kl_size, vec_ij_size, dim, dim)) # axes = (model_parameter1, model_parameter2,", ": numpy array Only returned when bScale == True. A length-S array specifying", "strings to compute the bulk operation on. prMxToFill : numpy array, optional when", "most blkSize assert(wrtFilter is None) # cannot specify both wrtFilter and blkSize nBlks", "of empty label == no gate dProdCache[i] = _np.zeros(deriv_shape) else: #doperation = self.dproduct(", "= {} scale_exp = 0 G = _np.identity(self.dim) for lOp in circuit: if", "evalTree.get_sub_trees() mySubTreeIndices, subTreeOwners, mySubComm = evalTree.distribute(comm) #if comm is not None: # print(\"MPI", "True) dprod_dOps = self.dproduct(circuit) dpr_dOps = _np.empty((1, self.Np)) for i in range(self.Np): dpr_dOps[0,", "d2pr_d2rhos = _np.zeros((nCircuits, nDerivCols1, nDerivCols2)) _fas(d2pr_d2rhos, [None, rho_gpindices1, rho_gpindices2], _np.tensordot(dp_dAnyRho, self.sos.get_prep(rholabel).hessian_wrt_params( rho_wrtFilter1, rho_wrtFilter2),", "(G x G operation matrices). and deriv[i,j,k] holds the derivative of the (j,k)-th", "j)] = G prods[(len(revOpLabelList), len(revOpLabelList) - 1)] = ident # product of no", "as a 1 x M numpy array, where M is the number of", "sense to include these since their required memory is fixed ## (and dominated)", "G, where: - S == the number of operation sequences - G ==", "number of entries in a single flattened gate (ordered as numpy.flatten) - M", "nDerivCols = self.Np if (wrtFilter is None) else _slct.length(wrtFilter) dim = self.dim wrtSlice", "if prMxToFill is not None: _fas(prMxToFill, [fInds], self._probs_from_rhoE(rho, E, Gs[gInds], scaleVals[gInds]), add=sumInto) if", "*no* gate params to compute # derivatives wrt all spam parameters dGs =", "Gs[i,j,l] rho[l,0] # dp_dEs[i,J0+J] = sum_j dEP[j,J] dot(Gs, rho)[i,j] # dp_dEs[i,J0+J] = sum_j", "wrtFilter1 & wrtFilter2 dictates block if blkSize1 is None and blkSize2 is None:", "axis=1))) # convention: Es has shape (len(elabels),N) return rho, Es def _probs_from_rhoE(self, rho,", "an inf scaleVal is mult by a zero hessian value, and we hGs[_np.isnan(hGs)]", "SPAM vectors should be dim x 1. gates, preps, effects : OrderedDict Ordered", "like in bulk_fill_probs(...). clipTo : 2-tuple, optional (min,max) to clip return value if", "block_generator A generator which, when iterated, yields the 3-tuple `(rowSlice, colSlice, hprobs)` or", "of groups to divide the second-derivative parameters into. Computation will be automatically parallelized", "rightProdsT = [] G = _np.identity(dim); rightProdsT.append(_np.transpose(G)) for opLabel in reversed(revOpLabelList): G =", "blkSize nBlks = int(_np.ceil(self.Np / blkSize)) # num blocks required to achieve desired", "paramvec : ndarray The parameter vector of the Model. autogator : AutoGator An", "#gate = self.sos.get_operation[opLabel] UNNEEDED (I think) _fas(flattened_dprod, [None, gpindices], gate.deriv_wrt_params(op_wrtFilter)) # (dim**2, nParams", "= _np.dot(_np.kron(prods[(0, l - 1)], xv), dop_dopLabel2[opLabel2]) # above: (nDerivCols1,dim**2,dim**2) * (dim**2,nDerivCols2) =", "comm procs, # as we assume the user has already done any such", "m - 1)]), prods[(m + 1, l - 1)]) # (dim**2, dim**2) x", "d2pr_drhos + _np.transpose(d2pr_drhos, (0, 2, 1)) + \\ d2pr_dEs + _np.transpose(d2pr_dEs, (0, 2,", "blkSize2 = wrtBlockSize2 # could be None if (mySubComm is not None) and", "_compute_hproduct_cache.\") #TODO: remove: not needed now that we track owners #if mySubSubComm.Get_rank() >", "every inner loop completion # (to save mem) but isn't gathered until now", "return values Gs = evalTree.final_view(prodCache, axis=0) #shape == ( len(circuit_list), dim, dim ),", "d2prod_dGates = self.hproduct(circuit) assert(d2prod_dGates.shape[0] == d2prod_dGates.shape[1]) d2pr_dOps2 = _np.empty((1, self.Np, self.Np)) for i", "way to reconstruct the # *non-final* parent-tree elements from those of the sub-trees.", "array with probability-Hessians for each \"final element\" of `evalTree`. Parameters ---------- mxToFill :", "d2pr/d(E)_i d(rho)_j = prod_ij (and same for other diff order) # d2pr/d(E)_i d(E)_j", "cpus hProdCache[:, myDeriv1ColSlice, myDeriv2ColSlice] = self._compute_hproduct_cache( evalTree, prodCache, dProdCache1[:, myDeriv1ColSlice], dProdCache2[:, myDeriv2ColSlice], scaleCache,", "calc_and_fill_p(spamTuple, fInds, gInds, pslc1, pslc2, sumInto): \"\"\" Compute and fill result quantities for", "dGs1[gInds], dGs2[gInds], hGs[gInds], scaleVals[gInds], wrtSlice1, wrtSlice2), add=sumInto) _np.seterr(**old_err) #Set wrtBlockSize to use available", "given arguments \"\"\" old_err = _np.seterr(over='ignore') rho, E = self._rhoE_from_spamTuple(spamTuple) if prMxToFill is", "sequences using tree (skip over the zero and single-gate-strings) #cnt = 0 for", "# dprobs1 & dprobs2 mem += cache_size * wrtLen1 * wrtLen2 * dim", "x dim mxs corresponding to a single kl xv = _np.swapaxes(xv, 1, 2)", "* scaleVals, 0, 2) # may overflow, but ok # may overflow or", "# dproduct cache mem += cache_size * dim * dim # product cache", "wrtSlice1 == wrtSlice2: # Note: this doesn't involve gate derivatives d2pr_dErhos2 = _np.transpose(d2pr_dErhos1,", "list of :class:`Label` objects giving the *simplified* effect labels. circuit : Circuit or", "not None and prMxToFill is not None: _np.clip(prMxToFill, clipTo[0], clipTo[1], out=prMxToFill) # in-place", "_np.real(_np.dot(Es, _np.dot(G, rho)) * scale) _np.seterr(**old_err) else: # no scaling -- faster but", "NotImplementedError(\"Unitary evolution not fully supported yet!\") # To support unitary evolution we need", "wrtFilter and blkSize nBlks1 = int(_np.ceil(self.Np / blkSize1)) nBlks2 = int(_np.ceil(self.Np / blkSize2))", "optional When True, return a scaling factor (see below). Returns ------- product :", "ret def _check(self, evalTree, prMxToFill=None, dprMxToFill=None, hprMxToFill=None, clipTo=None): # compare with older slower", "* if flat == True, an array of shape S*N x M where:", "not None and mySubComm.Get_size() > 1: deriv2Slices, myDeriv2ColSlice, deriv2Owners, mySubSubComm = \\ _mpit.distribute_slice(allDeriv2ColSlice,", "= comm_blkSize if (blkSize is None) \\ else min(comm_blkSize, blkSize) # override with", "for calc_and_fill wrtSlice1 = blocks1[iBlk1] wrtSlice2 = blocks2[iBlk2] self._fill_result_tuple((prMxToFill, deriv1MxToFill, deriv2MxToFill, mxToFill), evalSubTree,", "d(E)_j = 0 # d2pr/d(rho)_i d(rho)_j = 0 rholabel, elabel = spamTuple rho,", "1): comm_blkSize = self.Np / mySubComm.Get_size() blkSize = comm_blkSize if (blkSize is None)", "using numpy's reshape dim = self.dim uniqueOpLabels = sorted(list(set(revOpLabelList))) used_operations = _collections.OrderedDict() #Cache", "dGs = evalTree.final_view(dProdCache, axis=0) #shape == ( len(circuit_list), nDerivCols, dim, dim ), #", "(assume hGs is already sized/filtered) ------------------- assert(hGs.shape[1] == nDerivCols1), \"hGs must be pre-filtered!\"", "_np.seterr(**old_err) return Gs def bulk_dproduct(self, evalTree, flat=False, bReturnProds=False, bScale=False, comm=None, wrtFilter=None): \"\"\" Compute", "rho, Es = self._rhoEs_from_spamTuples(rholabel, elabels) #shapes: rho = (N,1), Es = (len(elabels),N) if", "M x G x G, where: - S == len(circuit_list) - M ==", "d2pr_dEs[i,j,J0+J] = sum_k dEP[k,J] dot(dGs, rho)[i,j,k,0] # d2pr_dEs[i,j,J0+J] = dot( squeeze(dot(dGs, rho),axis=(3,)), dEP)[i,j,J]", "max(_nla.norm(G), _np.exp(-scale_exp)) G = _np.dot(gate, G / nG); scale_exp += _np.log(nG) # LEXICOGRAPHICAL", "E = self._rhoE_from_spamTuple(spamTuple) _fas(prMxToFill, [fInds], self._probs_from_rhoE(rho, E, Gs[gInds], scaleVals[gInds]), add=sumInto) _np.seterr(**old_err) profiler.add_time(\"bulk_fill_dprobs: calc_and_fill_p\",", "bScale else hGs def _scaleExp(self, scaleExps): old_err = _np.seterr(over='ignore') scaleVals = _np.exp(scaleExps) #", "int or float, optional The maximum number of 1st (row) and 2nd (col)", "self.sos.get_prep(rholabel).has_nonzero_hessian(): derivWrtAnyRhovec = scale * _np.dot(E, prod) # may overflow, but OK d2pr_d2rhos", "blocks\") #collect/gather results tm = _time.time() subtreeElementIndices = [t.final_element_indices(evalTree) for t in subtrees]", "None # free mem if bReturnDProbs12: dprobs12 = dprobs1[:, :, None] * dprobs2[:,", "vec( dG(M)/dkl ) ) )^T vec( dG(L)/dij ) ] # noqa # +", "spam tuple as a 1 x M x M array, where M is", "ExMxM numpy array where E is the total number of computed elements (i.e.", "sequence of operation labels. Note: LinearOperator matrices are multiplied in the reversed order", "parameters, distribution over a split evalTree (if given) is possible. wrtFilter : list", "\"%d: p = %g, norm %g, exp %g\\n%s\" % (i,p,norm(G),total_exp,str(G)) # if _np.isnan(p):", "= sum_l E[0,l] dot( dGs, rho )[i,j,k,l,0] # d2pr_dOps2[i,j,k] = dot( E, dot(", "* dim**2)), 2) # cols = deriv cols, rows = all else return", "if mySubComm.Get_rank() > 0: myDerivColSlice = slice(0, 0) #don't compute anything on \"extra\",", "if bScale else hGs def _scaleExp(self, scaleExps): old_err = _np.seterr(over='ignore') scaleVals = _np.exp(scaleExps)", "to associate the right single-gate-strings w/indices wrtIndices = _slct.indices(wrtSlice) if (wrtSlice is not", "# Allocate memory for the final result num_deriv_cols = self.Np if (wrtFilter is", "rhoVec.deriv_wrt_params()) # may generate overflow, but OK _fas(d2pr_dErhos, [0, EVec.gpindices, self.sos.get_prep(rholabel).gpindices], _np.dot(_np.transpose(EVec.deriv_wrt_params()), derivWrtAnyEvec))", "that should do the same thing (for debugging) master_circuit_list = evalTree.generate_circuit_list(permute=False) # raw", "need to compute this gate hessian once). But since we're # assuming that", "_np.isclose(scale,0) is SLOW! hProdCache[i] /= _np.exp(scale) if hProdCache[i].max() < HSMALL and hProdCache[i].min() >", "prodCache = scaleCache = None #Fill product cache info (not requiring row or", "squeeze( dot( E, dot( dGs, rho ) ), axis=(0,4)) old_err2 = _np.seterr(invalid='ignore', over='ignore')", "initial single- or zero-operation labels for i, opLabel in zip(evalTree.get_init_indices(), evalTree.get_init_labels()): if opLabel", "M} # noqa # + sum{M==L} [ G1 ... G(M-1) d2G(M)/(dkl*dij) G(M+1) ...", "auto-gator object that may be used to construct virtual gates for use in", "the self.operations.keys() as in # dproduct(...) and find the labels in the string", "(1,N) else: # a \"custom\" spamLabel consisting of a pair of SPAMVec (or", "return a length-1 list, as this doesn't index numpy arrays # like length>1", "only need to compute this gate hessian once). But since we're # assuming", "available and necessary) if comm.Get_size() > nDerivCols1 * nDerivCols2: #If there are more", "= 0 # convert nans to zero, as these occur b/c an inf", "allDeriv2ColSlice = slice(0, nDerivCols2) deriv1Slices, myDeriv1ColSlice, deriv1Owners, mySubComm = \\ _mpit.distribute_slice(allDeriv1ColSlice, comm) #", "for the final result num_deriv_cols = self.Np if (wrtFilter is None) else len(wrtFilter)", "_np.exp(scale) if hProdCache[i].max() < HSMALL and hProdCache[i].min() > -HSMALL: _warnings.warn(\"Scaled hProd small in", "possible. wrtFilter : list of ints, optional If not None, a list of", "= flattened_d2prod.shape[1:3] # == num_deriv_cols1, num_deriv_cols2 return _np.rollaxis(flattened_d2prod, 0, 3).reshape((vec_kl_size, vec_ij_size, dim, dim))", "below). bReturnDProdsAndProds : bool, optional when set to True, additionally return the probabilities", "to have fewer processor groups then subtrees (even == 1) in order to", "no cover def bulk_fill_probs(self, mxToFill, evalTree, clipTo=None, check=False, comm=None): \"\"\" Compute the outcome", "gather mxToFill[felslc] (axis=0) if clipTo is not None: _np.clip(mxToFill, clipTo[0], clipTo[1], out=mxToFill) #", "_np.transpose(flattened_hprod, (1, 2, 0)).reshape( (num_deriv_cols1, num_deriv_cols2, dim, dim)) # axes = (gate_ij1, gateij2,", "on \"extra\", i.e. rank != 0, cpus hProdCache[:, myDeriv1ColSlice, myDeriv2ColSlice] = self._compute_hproduct_cache( evalTree,", "_np.real(_np.abs(_np.dot(Es, _np.dot(G, rho)) * scale)**2) else: # evotype == \"densitymx\" # probability, with", "(axis=0) profiler.add_time(\"MPI IPC\", tm) profiler.mem_check(\"bulk_fill_dprobs: post gather subtrees\") if clipTo is not None", "once. Parameters ---------- evalTree : EvalTree given by a prior call to bulk_evaltree.", "An array of floating-point probabilities, corresponding to the elements of `elabels`. \"\"\" assert(time", "Will use derivative rows and columns and then (as needed) a split tree", "# get d2pr_dEs where E derivatives are wrt the 2nd set of gate", "{} ident = _np.identity(dim) for (i, opLabel1) in enumerate(revOpLabelList): # loop over \"starting\"", "returnDeriv == True. A 1 x M numpy array of derivatives of the", "i in range(self.Np): for j in range(self.Np): d2pr_dOps2[0, i, j] = float(_np.dot(E, _np.dot(d2prod_dGates[i,", "(nDerivCols1, nDerivCols2, dim, dim) cacheSize = len(evalTree) # ------------------------------------------------------------------ if comm is not", "2) dLdRb = _np.swapaxes(_np.dot(dL2, dR1), 1, 2) dLdR_sym = dLdRa + _np.swapaxes(dLdRb, 0,", "the outcome probability-derivatives for an entire tree of gate strings. Similar to `bulk_fill_probs(...)`,", "scaleVals) if bScale else hGs def _scaleExp(self, scaleExps): old_err = _np.seterr(over='ignore') scaleVals =", "ForwardSimulator _dummy_profiler = _DummyProfiler() # Smallness tolerances, used internally for conditional scaling required", "pslc2, sumInto): \"\"\" Compute and fill result quantities for given arguments \"\"\" old_err", "model parameters selected for the 1st and 2nd differentiation, respectively (i.e. by wrtFilter1", "using blk1Comm). # (just as prMxToFill is computed fully on each inner loop", "(groups if needed) subtrees = evalTree.get_sub_trees() mySubTreeIndices, subTreeOwners, mySubComm = evalTree.distribute(comm) #eval on", "the filling should overwrite or add to the existing array values, which is", "dim=(KS), so gather mxToFill[felslc] (axis=0) if clipTo is not None: _np.clip(mxToFill, clipTo[0], clipTo[1],", "# noqa # + sum{ L == M} [ G1 ... G(M-1) tensor", "(i.e. evalTree.num_final_strings()), - B is the number of parameter rows (the length of", "not None: _mpit.gather_indices(subtreeElementIndices, subTreeOwners, deriv1MxToFill, [], 0, comm, gatherMemLimit) if deriv2MxToFill is not", "is needed) y = _np.dot(_np.kron(xv, _np.transpose(prods[(l + 1, N - 1)])), dop_dopLabel2[opLabel2]) #", "tensor # noqa # ( unvec( G(L+1) ... G(M-1) tensor (G(M+1) ... GN)^T", "useful when computing the Hessian of functions of the probabilities. comm : mpi4py.MPI.Comm,", "# scale vals elif fnName == \"bulk_fill_hprobs\": mem += cache_size * wrtLen1 *", "clipTo[1]) else: ret = ps #DEBUG CHECK #check_ps = _np.array( [ self.pr( (rholabel,elabel),", "pass None as comm, *not* mySubComm (this is ok, see \"if\" condition above)", "in enumerate(revOpLabelList): inds2 = gpindices1[opLabel2] #nDerivCols2 = dop_dopLabel2[opLabel2].shape[1] # FUTURE: we could add", "probability w.r.t. each model parameter. probability : float only returned if returnPr ==", "for this calculator. \"\"\" return \"deriv\" def estimate_cache_size(self, nCircuits): \"\"\" Return an estimate", "a list of integers specifying which parameters to include in the derivative dimension.", "\" +%.2fGB, shape=%s)\" % (dProdCache.nbytes / (1024.0**3), str(dProdCache.shape))) dGs = evalSubTree.final_view(dProdCache, axis=0) #(", "hproduct cache mem += cache_size * (wrtLen1 + wrtLen2) * dim * dim", "object used for to track timing and memory usage. gatherMemLimit : int, optional", "array) # objects: (prepVec, effectVec) rho, Eraw = spamTuple E = _np.conjugate(_np.transpose(Eraw)) return", "return rho, E def _rhoEs_from_spamTuples(self, rholabel, elabels): #Note: no support for \"custom\" spamlabels...", "scale else: G = _np.identity(self.dim) for lOp in circuit: G = _np.dot(self.sos.get_operation(lOp).todense(), G)", "groups used to (in parallel) iterate through the subtrees. It can often be", "------------------- assert(hGs.shape[1] == nDerivCols1), \"hGs must be pre-filtered!\" assert(hGs.shape[2] == nDerivCols2), \"hGs must", "0)), x0); xv = x.view() xv = _np.transpose(xv, axes=(2, 0, 1)) # (dim2,", "= %g\" % (_nla.norm(dprMxToFill[fInds]), _nla.norm(check_vdp), _nla.norm(dprMxToFill[fInds] - check_vdp))) # pragma: no cover if", "\"\"\" #get distribution across subtrees (groups if needed) subtrees = evalTree.get_sub_trees() mySubTreeIndices, subTreeOwners,", "= _np.identity(self.dim) for lOp in circuit: if lOp not in scaledGatesAndExps: opmx =", "_np.swapaxes(_np.swapaxes(Gs, 0, 2) * scaleVals, 0, 2) # may overflow, but ok _np.seterr(**old_err)", "the bulk operation on. clipTo : 2-tuple, optional (min,max) to clip return value", "dim**2)), 0, 1) # cols = deriv cols, rows = flattened all else", "can't tell whether it's + or - inf anyway... dp_dOps[_np.isnan(dp_dOps)] = 0 #SPAM", "rho, E def _rhoEs_from_spamTuples(self, rholabel, elabels): #Note: no support for \"custom\" spamlabels... #", "to clip returned probability to if not None. Only relevant when prMxToFill is", "MatrixForwardSimulator object. Parameters ---------- dim : int The gate-dimension. All operation matrices should", "bulk_product(self, evalTree, bScale=False, comm=None): \"\"\" Compute the products of many operation sequences at", "None. Returns ------- hessian : numpy array a 1 x M x M", "nDerivCols, dim, dim ) self._fill_result_tuple( (mxToFill,), evalSubTree, blocks[iBlk], slice(None), calc_and_fill_blk) profiler.mem_check(\"bulk_fill_dprobs: post fill", "i-th operation sequence product. scaleVals : numpy array Only returned when bScale ==", "== product * scale. The purpose of this is to allow a trace", "first done over the set of parameters being differentiated with respect to. If", "= dGs2 = None # free mem dProdCache1 = dGs1 = None #", "operation sequences to compute the bulk operation on. This tree *cannot* be split.", "* cache_size * nspam * wrtLen1 * wrtLen2 # hprobs & dprobs12 results", "the j-th model parameter. products : numpy array Only returned when bReturnDProdsAndProds ==", "= d(pr*pr.C)/dx = dpr/dx*pr.C + pr*dpr/dx.C # = 2 Re(dpr/dx*pr.C) , where dpr/dx", "subtreeElementIndices = [t.final_element_indices(evalTree) for t in subtrees] _mpit.gather_indices(subtreeElementIndices, subTreeOwners, mxToFill, [], 0, comm)", "prodCache[iLeft], prodCache[iRight] prodCache[i] = _np.dot(L, R) scaleCache[i] = scaleCache[iLeft] + scaleCache[iRight] if prodCache[i].max()", "This argument is used internally for distributing derivative calculations across multiple processors. Returns", "perform product and derivatives-of-product calculations. This is contained in a class separate from", "global_rho_slices = [ slice(tmp_offsets[i],tmp_offsets[i+1]) # for i in range(len(self.preps)) ] # # loc_e_slices", "x vgs x GxG dLdRa = _np.swapaxes(_np.dot(dL1, dR2), 1, 2) dLdRb = _np.swapaxes(_np.dot(dL2,", "+= cache_size # scale vals elif fnName == \"bulk_fill_hprobs\": mem += cache_size *", "_np.zeros((dim**2, num_deriv_cols), 'd') # For each operation label, compute the derivative of the", "all spam parameters dGs = _np.empty((Gs.shape[0], 0, self.dim, self.dim), 'd') def calc_and_fill_p(spamTuple, fInds,", "array, where M is the number of model parameters. hessian[0,j,k] is the derivative", "*simplified* gate strings to compute the bulk operation on. prMxToFill : numpy array,", "rows (the length of rowSlice) - B' is the number of parameter columns", "(nDerivCols, str(allDerivColIndices), comm.Get_rank(), str(myDerivColIndices))) if mySubComm is not None and mySubComm.Get_size() > 1:", "of the Model. autogator : AutoGator An auto-gator object that may be used", "scale vals elif fnName == \"bulk_fill_hprobs\": mem += cache_size * wrtLen1 * wrtLen2", "B', where: - K is the length of spam_label_rows, - S is the", "slice of the values for this spam label (given by the subsequent arguments,", "(G(L+1) ... GN)^T vec( dG(L)/dij ) ] # noqa # = [ sum_{L", "rho, E, Gs, dGs1, dGs2, hGs, scaleVals, wrtSlice1=None, wrtSlice2=None): if self.evotype == \"statevec\":", "row-derivatives distribution only; don't use column distribution hProdCache[:, myDeriv1ColSlice] = self._compute_hproduct_cache( evalTree, prodCache,", "can't tell whether it's + or - inf anyway... d2pr_dOps2[_np.isnan(d2pr_dOps2)] = 0 #", "evolution not fully supported yet!\") rholabel, elabel = spamTuple rhoVec = self.sos.get_prep(rholabel) #", "1)) + \\ d2pr_d2rhos + d2pr_d2Es + d2pr_dOps2 # Note: add transposes b/c", "dGs[i] is dprod_dOps for ith string if not bScale: old_err = _np.seterr(over='ignore', invalid='ignore')", ") )[0,i,j,0] # dp_dOps = squeeze( dot( E, dot( dGs, rho ) ),", "nDerivCols2)) _fas(d2pr_drhos1, [None, None, rho_gpindices2], _np.squeeze(_np.dot(_np.dot(E, dGs1), drho), axis=(0,)) * scaleVals[:, None, None])", "linear dependence on their parameters. if self.sos.get_prep(rholabel).has_nonzero_hessian(): dp_dAnyRho = _np.dot(E, Gs).squeeze(0) * scaleVals[:,", "at a higher level. \"\"\" dim = self.dim #Note: previously, we tried to", "product 2nd derivatives in a linear cache space. Will use derivative rows and", "rho_global_slices=global_rho_slices, # e_local_slices=loc_e_slices, # e_global_slices=global_e_slices, # num_rho_params=self.tot_rho_params, # num_e_params=self.tot_e_params) def _hprobs_from_rhoE(self, spamTuple, rho,", "with probability-derivatives for each \"final element\" of `evalTree`. Parameters ---------- mxToFill : numpy", "in-place clip if check: self._check(evalTree, prMxToFill, deriv1MxToFill, mxToFill, clipTo) def bulk_hprobs_by_block(self, evalTree, wrtSlicesList,", "filled internally to `calc_and_fill_fn` must be the same as the elements of `result_tup`.", "dpr_drhos + dpr_dEs + dpr_dOps def hpr(self, spamTuple, circuit, returnPr, returnDeriv, clipTo): \"\"\"", "of operation matrices and SPAM vectors) access to these fundamental operations. \"\"\" def", "hProdCache[i] = _np.zeros(hessn_shape) elif not self.sos.get_operation(opLabel).has_nonzero_hessian(): #all gate elements are at most linear", "of operation sequences - G == the linear dimension of a operation matrix", "`rowSlice` and `colSlice` are slices directly from `wrtSlicesList`. `hprobs` and `dprobs12` are arrays", "_np import numpy.linalg as _nla import time as _time import itertools as _itertools", "master_circuit_list[gInds] if prMxToFill is not None: check_vp = _np.array([self.prs(spamTuple[0], [spamTuple[1]], circuit, clipTo, False)[0]", "(i / G^2)-th flattened operation sequence product with respect to the j-th model", "x 1. gates, preps, effects : OrderedDict Ordered dictionaries of LinearOperator, SPAMVec, and", "_np.seterr(over='ignore') prod, scale = self.product(circuit, True) if returnPr: p = _np.dot(E, _np.dot(prod, rho))", "size. These arguments must be None if the corresponding wrtFilter is not None.", "E = self._rhoE_from_spamTuple(spamTuple) #if prMxToFill is not None: # _fas(prMxToFill, [fInds], # self._probs_from_rhoE(rho,", "array, where M is the number of model parameters. Parameters ---------- spamTuple :", "value trumps since we've renormed to keep all the products within decent #", "dEPT[J,j] Gs[i,j,l] rho[l,0] # dp_dEs[i,J0+J] = sum_j dEP[j,J] dot(Gs, rho)[i,j] # dp_dEs[i,J0+J] =", "if not bScale: old_err = _np.seterr(over='ignore', invalid='ignore') # may overflow or get nans", "scale : float Only returned when bScale == True, in which case the", "SPAM DERIVS (assume dGs1 and dGs2 are already sized/filtered) -------- assert(dGs1.shape[1] == nDerivCols1),", "... G(L-1) tensor # noqa # ( unvec( G(L+1) ... G(M-1) tensor (G(M+1)", "profiler object used for to track timing and memory usage. gatherMemLimit : int,", "that is filled with probability derivatives, similar to bulk_fill_dprobs(...), but where M is", "split), and then over blocks (subsets) of the parameters being differentiated with respect", "M x M x G x G, where - S == len(circuit_list) -", "order (easier to think about) revOpLabelList = tuple(reversed(tuple(circuit))) N = len(revOpLabelList) # length", "= float(_np.dot(E, _np.dot(d2prod_dGates[i, j], rho))) old_err = _np.seterr(over='ignore') prod, scale = self.product(circuit, True)", "numpy.flatten), - S,M == as above, and hessians[i,j,k] holds the derivative of the", "(None, E_gpindices1, rho_gpindices2), _np.swapaxes(_np.dot(_np.transpose(devec), dp_dAnyE), 0, 1)) # get d2pr_dEs where E derivatives", "_np.swapaxes(xv, 1, 2) y = _np.dot(_np.kron(prods[(0, l - 1)], xv), dop_dopLabel2[opLabel2]) # above:", "numpy array that is filled with probabilities, just like in bulk_fill_probs(...). clipTo :", "assert(opLabel1 == opLabel2) if opLabel1 in hop_dopLabels: # indicates a non-zero hessian x0", "of processor groups that will be assigned to subtrees of the created tree.", "dGs1 = evalSubTree.final_view(dProdCache1, axis=0) dGs2 = evalSubTree.final_view(dProdCache2, axis=0) #( nCircuits, nDerivColsX, dim, dim", "drhoP)[0,i,J] # dp_drhos[:,J0+J] = squeeze(dot(E, Gs, drhoP),axis=(0,))[:,J] dp_drhos = _np.zeros((nCircuits, nDerivCols)) _fas(dp_drhos, [None,", "#print(\"MPI: _compute_dproduct_cache over %d cols (%s) (rank %d computing %s)\" \\ # %", "construct_evaltree(self, simplified_circuits, numSubtreeComms): \"\"\" Constructs an EvalTree object appropriate for this calculator. Parameters", "to use available processors if it isn't specified if wrtFilter1 is None and", "scaleCache, comm, wrtSlice1, wrtSlice2) #use cached data to construct return values old_err =", "Distribution is performed as in bulk_product, bulk_dproduct, and bulk_hproduct. Returns ------- block_generator A", "flattened_dprod. #gate = self.sos.get_operation[opLabel] UNNEEDED (I think) _fas(flattened_dprod, [None, gpindices], gate.deriv_wrt_params(op_wrtFilter)) # (dim**2,", "j], rho))) old_err = _np.seterr(over='ignore') prod, scale = self.product(circuit, True) if returnPr: p", "dGs2, hGs, scaleVals, wrtSlice1=None, wrtSlice2=None): if self.evotype == \"statevec\": raise NotImplementedError(\"Unitary evolution not", "ORDER # we do matrix multiplication in this order (easier to think about)", "else None wrtSlice2 = _slct.list_to_slice(wrtFilter2) if (wrtFilter2 is not None) else None #TODO:", "to non-None to reduce amount of intermediate memory required. profiler : Profiler, optional", "2)) * scaleVals # shape == (len(circuit_list),) ; may overflow but OK def", "tuple and each row corresponds to an element of the product (els of", "as the elements of `result_tup`. The fill function computes values for only a", "comm=None, wrtFilter=None): \"\"\" Compute the derivative of a many operation sequences at once.", "# mem += cache_size # scale vals # #elif fnName == \"bulk_hproduct\": #", "#gather results tm = _time.time() _mpit.gather_slices(blocks, blkOwners, mxToFill, [felInds], 1, mySubComm, gatherMemLimit) #note:", "as this doesn't index numpy arrays # like length>1 lists do... ugh. relevant_gpindices", "== True, an array of shape S*N x M where: - N ==", "is not None: _mpit.gather_indices(subtreeElementIndices, subTreeOwners, deriv2MxToFill, [], 0, comm, gatherMemLimit) if prMxToFill is", "# scale cache # mem += cache_size # scale vals else: raise ValueError(\"Unknown", "else _slct.length(wrtFilter2) nCircuits = evalTree.num_final_strings() # len(circuit_list) wrtSlice1 = _slct.list_to_slice(wrtFilter1) if (wrtFilter1 is", "cached data to final values scaleVals = self._scaleExp(evalSubTree.final_view(scaleCache)) Gs = evalSubTree.final_view(prodCache, axis=0) #(", "dim, dim ), # Gs[i] is product for i-th operation sequence dGs =", "entire tree of gate strings. Similar to `bulk_fill_probs(...)`, but fills a 3D array", "derivatives in a linear cache space. Will use derivative columns and then (and", "\"final indices\" = the \"element\" indices in the final # filled quantity combining", "deriv2MxToFill, mxToFill), evalSubTree, slice(None), slice(None), calc_and_fill) else: # Divide columns into blocks of", "Returns ------- derivs : numpy array * if flat == False, an array", "# Get: dp_dEs[i, E_gpindices] = dot(transpose(dE/dEP),Gs[i],rho)) # dp_dEs[i,J0+J] = sum_lj dEPT[J,j] Gs[i,j,l] rho[l,0]", "\"bulk_product DEBUG: %d rescalings out of %d products\" % (cnt, len(evalTree)) nanOrInfCacheIndices =", "self.sos.get_effect(elabel).hessian_wrt_params( E_wrtFilter1, E_wrtFilter2), (1, 0))) # _np.einsum('ij,jkl->ikl', dp_dAnyE, self.sos.get_effect(elabel).hessian_wrt_params( # E_wrtFilter1, E_wrtFilter2)) else:", "Will *not* parallelize computation, even if given a split tree (since there's no", "if (wrtSlice1 == wrtSlice2): dProdCache2 = dProdCache1; dGs2 = dGs1 else: dProdCache2 =", "return sub_vdp #def _get_filter_info(self, wrtSlices): # \"\"\" # Returns a \"filter\" object containing", "sequence product. scaleVals : numpy array Only returned when bScale == True. An", "deriv2MxToFill = dprobs2 mxToFill = hprobs #Fill arrays self._fill_result_tuple((None, dprobs1, dprobs2, hprobs), evalTree,", "in scaledGatesAndExps: opmx = self.sos.get_operation(lOp).todense() ng = max(_nla.norm(opmx), 1.0) scaledGatesAndExps[lOp] = (opmx /", "probabilities all at once so they're not repeatedly # computed for each block", "in circuit_list], axis=0) if _nla.norm(dprMxToFill[fInds] - check_vdp) > 1e-6: _warnings.warn(\"norm(vdp-check_vdp) = %g -", ": numpy array, optional when not None, an already-allocated length-E numpy array that", "len(circuit_list), nDerivCols, dim, dim ), # dGs[i] is dprod_dOps for ith string if", "placeholder dGs for *no* gate params to compute # derivatives wrt all spam", "assert(nDerivCols1 == nDerivCols2) d2pr_drhos2 = _np.transpose(d2pr_drhos1, (0, 2, 1)) else: drho = rhoVec.deriv_wrt_params(rho_wrtFilter1)", "tensor A * vec( E(0,1) ) # In general: vec( A * X", "probability w.r.t. each model parameter (M is the length of the vectorized model).", "values scaleVals = self._scaleExp(evalSubTree.final_view(scaleCache)) Gs = evalSubTree.final_view(prodCache, axis=0) # ( nCircuits, dim, dim", "... G(M-1) tensor (G(M+1) ... GN)^T vec( d2G(M)/dkl*dji ) # noqa # #", "[0, None, self.sos.get_prep(rholabel).gpindices], _np.dot(_np.dot(E, dprod_dOps), rhoVec.deriv_wrt_params())[0]) # (= [0,:,:]) d2pr_dEs = _np.zeros((1, self.Np,", "uniqueOpLabels = sorted(list(set(revOpLabelList))) for opLabel in uniqueOpLabels: gate = self.sos.get_operation(opLabel) op_wrtFilter, gpindices =", "self.dim nDerivCols = self.Np if (wrtSlice is None) \\ else _slct.length(wrtSlice) deriv_shape =", "bulk_hproduct(self, evalTree, flat=False, bReturnDProdsAndProds=False, bScale=False, comm=None, wrtFilter1=None, wrtFilter2=None): \"\"\" Return the Hessian of", "dGs, rho ) )[0,i,j,k,0] # d2pr_dOps2 = squeeze( dot( E, dot( dGs, rho", "matrices, so that # each column corresponds to a (opLabel,i,j) tuple and each", "= self.sos.get_operation(opLabel) op_wrtFilter, gpindices = self._process_wrtFilter(wrtFilter, gate) dop_dopLabel = gate.deriv_wrt_params(op_wrtFilter) for (i, gl)", "FLOATSIZE def bulk_product(self, evalTree, bScale=False, comm=None): \"\"\" Compute the products of many operation", "This calculator uses the convention that rho has shape (N,1) rho = self.sos.get_prep(rholabel).todense()[:,", "gate derivatives are wrt the 2nd set of gate parameters if dGs1 is", "and M is the number of model parameters. evalTree : EvalTree given by", "old_err = _np.seterr(over='ignore') rho, E = self._rhoE_from_spamTuple(spamTuple) block_wrtSlice = pslc1 _fas(mxToFill, [fInds, pslc1],", "self.evotype == \"statevec\": raise NotImplementedError(\"Unitary evolution not fully supported yet!\") rholabel, elabel =", "iBlk in myBlkIndices: tm = _time.time() block_wrtSlice = blocks[iBlk] dProdCache = self._compute_dproduct_cache(evalSubTree, prodCache,", "matrixOf(circuit[iRight]) (iRight, iLeft) = evalTree[i] L, R = prodCache[iLeft], prodCache[iRight] prodCache[i] = _np.dot(L,", "vec) \"\"\" #Create per-gate with-respect-to parameter filters, used to # select a subset", "scaling required # to control bulk products, their gradients, and their Hessians. PSMALL", "could add logic that accounts for the symmetry of the Hessian, so that", "interpret which elements correspond to which strings and outcomes, you'll need the mappings", "nDerivCols = self.Np if (wrtSlice is None) \\ else _slct.length(wrtSlice) deriv_shape = (nDerivCols,", "indices into original wrtFilter'd indices gpindices = obj.gpindices_as_array() for ii, i in enumerate(wrtFilter):", "given, otherwise no parallelization is performed. Returns ------- prods : numpy array Array", "Defines the MatrixForwardSimulator calculator class\"\"\" #*************************************************************************************************** # Copyright 2015, 2019 National Technology &", "flattened_d2prod[:, inds1, inds2] += xv if flat: return flattened_d2prod # axes = (vectorized_op_el_index,", "isinstance(spamTuple[0], _Label): rholabel, elabel = spamTuple # This calculator uses the convention that", "all the major allocation/deallocation). #if comm is None or comm.Get_rank() == 0: #", "(_np.isnan(hGs)).nonzero()[0] ) == 0 ) #assert( len( (_np.isinf(hGs)).nonzero()[0] ) == 0 ) #hGs", "0, comm) #note: pass mxToFill, dim=(KS), so gather mxToFill[felslc] (axis=0) if clipTo is", "G = _np.dot(G, self.sos.get_operation(opLabel2).todense()) prods[(i, j)] = G prods[(len(revOpLabelList), len(revOpLabelList) - 1)] =", "sequence probabilities can often be computed column-by-column from the using the columns of", "self.Np if (wrtFilter2 is None) else len(wrtFilter2) flattened_hprod = _np.zeros((dim**2, num_deriv_cols1, num_deriv_cols2), 'd')", "------- prods : numpy array Array of shape S x G x G,", "optional If not None, a list of integers specifying which gate parameters to", "# (reshape without copying - throws error if copy is needed) y =", "function iterates over these computed blocks, in the order given by `wrtSlicesList`. `rowSlice`", "of MPI processor syncronization. Returns ------- None \"\"\" tStart = _time.time() if profiler", "and this dictates how large all the storage arrays are. np1, np2 =", "# #don't compute anything on \"extra\", i.e. rank != 0, cpus hProdCache[:, myDeriv1ColSlice,", "clipTo=None, check=False, comm=None): \"\"\" Compute the outcome probabilities for an entire tree of", "prep labels must be the same) Parameters ---------- rholabel : Label The state", "0, 1) # above: dim = (dim2, nDerivCols1, nDerivCols2); # swapaxes takes (kl,vec_prod_indx,ij)", "same for other diff order) # d2pr/d(E)_i d(E)_j = 0 # d2pr/d(rho)_i d(rho)_j", "no gate dProdCache[i] = _np.zeros(deriv_shape) else: #doperation = self.dproduct( (opLabel,) , wrtFilter=wrtIndices) doperation", "G(L) == oplabel} [ G1 ... G(L-1) dG(L)/dij G(L+1) ... GN ] ,", "# tmp_num_params = [_slct.length(s) for s in loc_rho_slices] # tmp_offsets = [ sum(tmp_num_params[0:i])", "wrtSlices['preps'], # slice(self.rho_offset[i],self.rho_offset[i+1])), # -self.rho_offset[i]) for i in range(len(self.preps))] # tmp_num_params = [_slct.length(s)", "numSubtreeComms : int The number of processor groups that will be assigned to", "probability-derivatives for each \"final element\" of `evalTree`. Parameters ---------- mxToFill : numpy ndarray", "this is not the case, need LinearOperator objects to # have a 2nd-deriv", "None: _np.clip(prMxToFill, clipTo[0], clipTo[1], out=prMxToFill) # in-place clip if check: self._check(evalTree, prMxToFill, mxToFill,", "to computed their probabilites). These are a \"simplified\" circuits in that they should", "*cannot* make use of a tree being # split because there's no good", "(gate or spam vec) \"\"\" #Create per-gate with-respect-to parameter filters, used to #", "column distribution hProdCache[:, myDeriv1ColSlice] = self._compute_hproduct_cache( evalTree, prodCache, dProdCache1[:, myDeriv1ColSlice], dProdCache2, scaleCache, None,", "prodCache, dProdCache1[:, myDeriv1ColSlice], dProdCache2, scaleCache, None, myHessianSlice1, wrtSlice2) # pass None as comm,", "_Label): rholabel, elabel = spamTuple # This calculator uses the convention that rho", "0 ret = d2pr_dErhos + _np.transpose(d2pr_dErhos, (0, 2, 1)) + \\ d2pr_drhos +", "(%s) (rank %d computing %s)\" \\ # % (nDerivCols, str(allDerivColIndices), comm.Get_rank(), str(myDerivColIndices))) if", "d2G(M)/dkl*dji ) # noqa # # Note: ignoring L == M terms assumes", "% mySubComm.Get_size() + \" than derivative columns(%d)!\" % self.Np + \" [blkSize =", "- `dprobs12 == dp1[:,:,rowSlice,None] * dp2[:,:,None,colSlice]` \"\"\" assert(not evalTree.is_split()), \"`evalTree` cannot be split\"", "dim = self.dim nDerivCols1 = self.Np if (wrtFilter1 is None) else _slct.length(wrtFilter1) nDerivCols2", "gpindices], gate.deriv_wrt_params(op_wrtFilter)) # (dim**2, nParams in wrtFilter for opLabel) if flat: return flattened_dprod", "these groups. num_final_strs : int The number of final strings (may be less", "internally. If False, this routine will run slightly faster, but with a chance", "l==m) then # it could make sense to iterate through the self.operations.keys() as", "None, an already-allocated length-E numpy array that is filled with probabilities, just like", "axis 1 of hProdCache, # dim=(cacheSize,nDerivCols1,nDerivCols2,dim,dim) return hProdCache # ------------------------------------------------------------------ if evalTree.is_split(): _warnings.warn(\"Ignoring", "myHessianSlice1, myHessianSlice2) # pass None as comm, *not* mySubSubComm, since we can't do", "= self._scaleExp(evalSubTree.final_view(scaleCache)) Gs = evalSubTree.final_view(prodCache, axis=0) # ( nCircuits, dim, dim ) def", "x B x B', where: - K is the length of spam_label_rows, -", "wrtSlice1 if (wrtSlice1 == wrtSlice2): dProdCache2 = dProdCache1; dGs2 = dGs1 else: dProdCache2", "each of the now un-vectorized dim x dim mxs corresponding to a single", "a set) # since all scaled gates start with norm <= 1, products", "within code to verify correctness, generating warnings when checks fail. Used for testing,", "the number of operation sequences (i.e. evalTree.num_final_strings()), - B is the number of", "_warnings.warn(\"pr(%s) == nan\" % strToPrint) #DEBUG: print \"backtrace\" of product leading up to", "profiler.add_time(\"bulk_fill_dprobs: calc_and_fill_p\", tm) # Compute all probabilities all at once so they're not", "j-th model parameter. \"\"\" # LEXICOGRAPHICAL VS MATRIX ORDER # we do matrix", "Hessian, and turns out to be useful when computing the Hessian of functions", "= dpr/dx*pr.C + pr*dpr/dx.C # = 2 Re(dpr/dx*pr.C) , where dpr/dx is the", "the i-th entry of the flattened product with respect to the j-th model", "additional model classes (e.g. ones which use entirely different -- non-gate-local -- parameterizations", "if wrtFilter is not None: obj_wrtFilter = [] # values = object-local param", "along with a mapping of final elements (i.e. probabilities) to gate-only sequence and", "When True, return a scaling factor (see below). comm : mpi4py.MPI.Comm, optional When", "None: _fas(prMxToFill, [fInds], self._probs_from_rhoE( rho, E, Gs[gInds], scaleVals[gInds]), add=sumInto) _fas(mxToFill, [fInds, pslc1], self._dprobs_from_rhoE(", "can be thought of as the first gate operation performed, which is on", "array * if flat == False, an array of shape S x M", "parent-function scope. This use of # closures seems confusing and we should do", "def _compute_product_cache(self, evalTree, comm=None): \"\"\" Computes a tree of products in a linear", "= _np.dot(Gs, rho).squeeze(2) * scaleVals[:, None] # overflow OK d2pr_d2Es = _np.zeros((nCircuits, nDerivCols1,", "any nonzero gate hessians (memory?) hop_dopLabels = {} for opLabel, gate in used_operations.items():", "computation across multiple processors. This is done over operation sequences when a *split*", "outcome probabilities for an entire tree of operation sequences. This routine fills a", "fnName == \"bulk_fill_dprobs\": mem += cache_size * wrtLen1 * dim * dim #", "error if copy is needed) # transposes each of the now un-vectorized dim", "\\ _mpit.distribute_indices(list(range(nBlks2)), blk1Comm) if blk2Comm is not None: _warnings.warn(\"Note: more CPUs(%d)\" % mySubComm.Get_size()", "hProdCache[i].min() > -HSMALL: _warnings.warn(\"Scaled hProd small in order to keep prod managable.\") elif", "+= cache_size * dim * dim # product cache mem += cache_size #", "purpose of this is to allow a trace or other linear operation to", "of the vectorized model (number of model parameters) and deriv[i,j] holds the derivative", "(this is ok, see \"if\" condition above) _mpit.gather_slices(deriv1Slices, deriv1Owners, hProdCache, [], 1, comm)", "of strs A list of the names of the subcalls to estimate memory", "Hessian of functions of the probabilities. comm : mpi4py.MPI.Comm, optional When not None,", "(fInds, gInds) in evalTree.spamtuple_indices.items(): # fInds = \"final indices\" = the \"element\" indices", "out=prMxToFill) # in-place clip if check: self._check(evalTree, prMxToFill, mxToFill, clipTo=clipTo) profiler.add_time(\"bulk_fill_dprobs: total\", tStart)", "since we've renormed to keep all the products within decent bounds #assert( len(", "= _np.transpose(d2pr_drhos1, (0, 2, 1)) else: drho = rhoVec.deriv_wrt_params(rho_wrtFilter1) d2pr_drhos2 = _np.zeros((nCircuits, nDerivCols2,", "dim = self.dim nDerivCols = self.Np if (wrtSlice is None) \\ else _slct.length(wrtSlice)", "== no gate dProdCache[i] = _np.zeros(deriv_shape) else: #doperation = self.dproduct( (opLabel,) , wrtFilter=wrtIndices)", "like in bulk_fill_probs(...). derivMxToFill1, derivMxToFill2 : numpy array, optional when not None, an", "mxToFill, clipTo) def bulk_hprobs_by_block(self, evalTree, wrtSlicesList, bReturnDProbs12=False, comm=None): \"\"\" Constructs a generator that", "subtree iteration before computing caches scaleVals = Gs = dGs1 = dGs2 =", "* scaleVals[:, None, None] # overflow OK devec = EVec.deriv_wrt_params(E_wrtFilter2) _fas(d2pr_dEs1, [None, None,", "gateij2, prod_row, prod_col) def dproduct(self, circuit, flat=False, wrtFilter=None): \"\"\" Compute the derivative of", "E_wrtFilter1, E_wrtFilter2), (1, 0))) # _np.einsum('ij,jkl->ikl', dp_dAnyE, self.sos.get_effect(elabel).hessian_wrt_params( # E_wrtFilter1, E_wrtFilter2)) else: d2pr_d2Es", "(self.Np + np2 - 1) // np2 # ceiling(num_params / np2) mem =", "this order (easier to think about) revOpLabelList = tuple(reversed(tuple(circuit))) # prod = G1", "to bulk_fill_dprobs(...), but where M is the number of model parameters selected for", "the preferred MPI distribution mode for this calculator. \"\"\" return \"deriv\" def estimate_cache_size(self,", "* dim * dim # product cache mem += cache_size # scale cache", "bReturnDProbs12: dprobs1 = _np.zeros((nElements, _slct.length(wrtSlice1)), 'd') dprobs2 = _np.zeros((nElements, _slct.length(wrtSlice2)), 'd') else: dprobs1", "Parameters ---------- circuit : Circuit or tuple of operation labels The sequence of", "wrtSlice=None, profiler=None): \"\"\" Computes a tree of product derivatives in a linear cache", "old_err = _np.seterr(over='ignore') rho, E = self._rhoE_from_spamTuple(spamTuple) _fas(mxToFill, [fInds], self._probs_from_rhoE(rho, E, Gs[gInds], scaleVals[gInds]),", "cache mem += cache_size # scale vals ## It doesn't make sense to", "processors than can be used for product computation\") pass # this is a", "addition of deriv_wrt_params # # Note: unvec( X ) can be done efficiently", "self._get_filter_info(wrtSlices2) # GATE DERIVS (assume hGs is already sized/filtered) ------------------- assert(hGs.shape[1] == nDerivCols1),", "raise ValueError((\"Evolution type %s is incompatbile with \" \"matrix-based calculations\" % self.evotype)) def", "# This calculator uses the convention that rho has shape (N,1) rho =", "len(circuit) _warnings.warn(\"pr(%s) == nan\" % strToPrint) #DEBUG: print \"backtrace\" of product leading up", "blocks required to achieve desired average size == blkSize blocks = _mpit.slice_up_range(self.Np, nBlks,", "of the subcalls to estimate memory usage for. cache_size : int The size", "> 1): comm_blkSize = self.Np / mySubComm.Get_size() blkSize1 = comm_blkSize if (blkSize1 is", "mySubSubComm.Get_size() > 1: _warnings.warn(\"Too many processors to make use of in \" \"", "computed their probabilites). These are a \"simplified\" circuits in that they should only", "+ 1, N - 1)]) # (dim**2, dim**2) # (nDerivCols1,nDerivCols2,dim**2) x = _np.dot(_np.transpose(hop_dopLabels[opLabel1],", "occur b/c an inf scaleVal is mult by a zero hessian value, and", "... (len %d)\" % len(circuit) _warnings.warn(\"pr(%s) == nan\" % strToPrint) #DEBUG: print \"backtrace\"", "_np.zeros((1, self.Np)) derivWrtAnyRhovec = scale * _np.dot(E, prod) _fas(dpr_drhos, [0, self.sos.get_prep(rholabel).gpindices], _np.dot(derivWrtAnyRhovec, rhoVec.deriv_wrt_params()))", "nCircuits, len(wrtFilter1), len(wrtFilter2), dim, dim ) #Compute all requested derivative columns at once", "gate_wrtFilters2 = {} for l in uniqueOpLabels: used_operations[l] = self.sos.get_operation(l) gate_wrtFilters1[l], gpindices1[l] =", "Returns ------- None \"\"\" #get distribution across subtrees (groups if needed) subtrees =", "size of the evaluation tree that will be passed to the functions named", "dProdCache1, dProdCache2, scaleCache, mySubComm, wrtSlice1, wrtSlice2) hGs = evalSubTree.final_view(hProdCache, axis=0) #( nCircuits, len(wrtFilter1),", "inf scaleVal is mult by a zero deriv value, and we dGs[_np.isnan(dGs)] =", "of model params so that # per-gate hessians can be computed properly if", "vectorized model (number of model parameters) - G == the linear dimension of", "self.hoperation(opLabel, wrtFilter1=wrtIndices1, wrtFilter2=wrtIndices2) hProdCache[i] = hoperation / _np.exp(scaleCache[i]) #evaluate operation sequences using tree", "already sized/filtered) -------- assert(dGs1.shape[1] == nDerivCols1), \"dGs1 must be pre-filtered!\" assert(dGs2.shape[1] == nDerivCols2),", "the operation sequences to create an evaluation tree out of (most likely because", "_fas(d2pr_d2rhos, [0, self.sos.get_prep(rholabel).gpindices, self.sos.get_prep(rholabel).gpindices], _np.tensordot(derivWrtAnyRhovec, self.sos.get_prep(rholabel).hessian_wrt_params(), (1, 0))) # _np.einsum('ij,jkl->ikl', derivWrtAnyRhovec, self.sos.get_prep(rholabel).hessian_wrt_params()) else:", "for multiple uses below gpindices1 = {}; gate_wrtFilters1 = {} gpindices2 = {};", "the appropriate block of flattened_d2prod. #NOTE: if we needed to perform a hessian", "= [_slct.length(s) for s in loc_rho_slices] # tmp_offsets = [ sum(tmp_num_params[0:i]) for i", "if H.max() < PSMALL and H.min() > -PSMALL: nG = max(_nla.norm(G), _np.exp(-scale_exp)) G", "0, comm, gatherMemLimit) #note: pass mxToFill, dim=(KS,M), so gather mxToFill[felInds] (axis=0) if prMxToFill", "%g\\n%s\" % (i,p,norm(G),total_exp,str(G)) # if _np.isnan(p): raise ValueError(\"STOP\") if clipTo is not None:", "optional when not None, an already-allocated length-E numpy array that is filled with", ", a matrix # noqa # dprod/d(opLabel)_ij = sum_{L s.t. G(L) == oplabel}", "_slct.length(wrtFilter) dim = self.dim wrtSlice = _slct.list_to_slice(wrtFilter) if (wrtFilter is not None) else", "slice(relevant_gpindices[0], relevant_gpindices[0] + 1) elif len(relevant_gpindices) == 0: #Don't return a length-0 list,", "over a split evalTree (if given) is possible. wrtFilter1, wrtFilter2 : list of", "[None, rho_gpindices], _np.squeeze(_np.dot(_np.dot(E, Gs), rhoVec.deriv_wrt_params(rho_wrtFilter)), axis=(0,)) * scaleVals[:, None]) # may overflow, but", "self.sos.get_operation(opLabel) op_wrtFilter, gpindices = self._process_wrtFilter(wrtFilter, gate) # Allocate memory for the final result", "# Get slice into entire range of model params so that # per-gate", "N x M array, where: - N == the number of entries in", "len(relevant_gpindices) == 0: #Don't return a length-0 list, as this doesn't index numpy", "of derivatives of the probability w.r.t. each model parameter. probability : float only", "not None and mySubSubComm.Get_size() > 1: _warnings.warn(\"Too many processors to make use of", "[None, E_gpindices1, E_gpindices2], _np.tensordot(dp_dAnyE, self.sos.get_effect(elabel).hessian_wrt_params( E_wrtFilter1, E_wrtFilter2), (1, 0))) # _np.einsum('ij,jkl->ikl', dp_dAnyE, self.sos.get_effect(elabel).hessian_wrt_params(", "raise ValueError(\"Unknown subcall name: %s\" % fnName) return mem * FLOATSIZE def bulk_product(self,", "order given by `wrtSlicesList`. `rowSlice` and `colSlice` must by Python `slice` objects. bReturnDProbs12", "# may overflow, but OK ; shape == (len(circuit_list), nDerivCols) # may also", "Must be *ordered* dictionaries to specify a well-defined column ordering when taking derivatives.", "self.sos.get_effect(elabel) # arrays, these are SPAMVecs d2prod_dGates = self.hproduct(circuit) assert(d2prod_dGates.shape[0] == d2prod_dGates.shape[1]) d2pr_dOps2", "opLabel, flat=False, wrtFilter=None): \"\"\" Return the derivative of a length-1 (single-gate) sequence \"\"\"", "checks fail. Used for testing, and runs much slower when True. comm :", "result to the appropriate block of flattened_d2prod. #NOTE: if we needed to perform", "free mem else: # Divide columns into blocks of at most blkSize assert(wrtFilter", "None) else None wrtIndices2 = _slct.indices(wrtSlice2) if (wrtSlice2 is not None) else None", "The parameter vector of the Model. autogator : AutoGator An auto-gator object that", "/ nR prodCache[i] = _np.dot(sL, sR); scaleCache[i] += _np.log(nL) + _np.log(nR) #print \"bulk_product", "useful ## since numpy does all the major allocation/deallocation). #if comm is None", "1)]) # (dim**2, dim**2) # (nDerivCols1,nDerivCols2,dim**2) x = _np.dot(_np.transpose(hop_dopLabels[opLabel1], axes=(1, 2, 0)), x0);", "model params so that # per-gate hessians can be computed properly if wrtSlice1", "is not None: self._fill_result_tuple((prMxToFill,), evalSubTree, slice(None), slice(None), calc_and_fill_p) profiler.mem_check(\"bulk_fill_dprobs: post fill probs\") #distribute", "N == the number of entries in a single flattened gate (ordered as", "cache # mem += cache_size # scale cache # mem += cache_size #", "x M x M x G x G, where - S == len(circuit_list)", "(see below). bScale : bool, optional When True, return a scaling factor (see", "return (hGs, dGs1, dGs2, Gs, scaleVals) if bScale else (hGs, dGs1, dGs2, Gs)", ": Profiler, optional A profiler object used for to track timing and memory", "scaleVals[gInds], wrtSlice), add=sumInto) _np.seterr(**old_err) profiler.add_time(\"bulk_fill_dprobs: calc_and_fill\", tm) #Set wrtBlockSize to use available processors", "+%.2fGB, shape=%s)\" % (dProdCache.nbytes / (1024.0**3), str(dProdCache.shape))) dGs = evalSubTree.final_view(dProdCache, axis=0) #( nCircuits,", "G(L) is just a matrix of parameters, then dG(L)/dij = E(i,j), an elementary", ") # noqa # tensor (G(L+1) ... GN)^T vec( dG(L)/dij ) ] #", "= _time.time() subtreeElementIndices = [t.final_element_indices(evalTree) for t in subtrees] _mpit.gather_indices(subtreeElementIndices, subTreeOwners, mxToFill, [],", "but fills a 3D array with probability-Hessians for each \"final element\" of `evalTree`.", "* GN , a matrix # noqa # dprod/d(opLabel)_ij = sum_{L s.t. GL", "GN)^T ]] * vec( dG(L)/dij) ) # noqa # if dG(L)/dij = E(i,j)", "convention that rho has shape (N,1) rho = self.sos.get_prep(rholabel).todense()[:, None] E = _np.conjugate(_np.transpose(self.sos.get_effect(elabel).todense()", "_np.squeeze(_np.dot(Gs, rho), axis=(2,)) * scaleVals[:, None] _fas(dp_dEs, [None, E_gpindices], _np.dot(dp_dAnyE, EVec.deriv_wrt_params(E_wrtFilter))) sub_vdp =", "with respect to the k-th then j-th model parameters. * if flat ==", "mySubComm, gatherMemLimit) if deriv2MxToFill is not None: _mpit.gather_slices(blocks2, blk2Owners, deriv2MxToFill, [felInds], 1, blk1Comm,", "single flattened gate (ordered as numpy.flatten) - M == length of the vectorized", "is None else _slct.length(wrtSlice) # GATE DERIVS (assume dGs is already sized/filtered) -------------------", "if flat: return flattened_d2prod # axes = (vectorized_op_el_index, model_parameter1, model_parameter2) else: vec_kl_size, vec_ij_size", "operation sequences - G == the linear dimension of a operation matrix (G", "inner loop *iteration*!) #collect/gather results subtreeElementIndices = [t.final_element_indices(evalTree) for t in subtrees] _mpit.gather_indices(subtreeElementIndices,", "derivatives, and/or products for the i-th operation sequence. \"\"\" dim = self.dim nDerivCols1", "xv.shape = (nDerivCols1, dim, dim) # (reshape without copying - throws error if", "- M == length of the vectorized model (number of model parameters) and", "respectively. wrtBlockSize2, wrtBlockSize2 : int or float, optional The maximum number of 1st", "dot(E, Gs, drhoP)[0,i,J] # dp_drhos[:,J0+J] = squeeze(dot(E, Gs, drhoP),axis=(0,))[:,J] dp_drhos = _np.zeros((nCircuits, nDerivCols))", ": bool when set to True, additionally return the derivative of the probability.", "_fas(flattened_dprod, [None, gpindices], gate.deriv_wrt_params(op_wrtFilter)) # (dim**2, nParams[opLabel]) if _slct.length(gpindices) > 0: # works", "GN ] # noqa # a matrix for each given (i,j,k,l) # noqa", "= %g - %g = %g\" % (_nla.norm(dprMxToFill[fInds]), _nla.norm(check_vdp), _nla.norm(dprMxToFill[fInds] - check_vdp))) #", "scale * _np.transpose(_np.dot(prod, rho)) # may overflow, but OK _fas(dpr_dEs, [0, EVec.gpindices], _np.dot(derivWrtAnyEvec,", "their parameters. if self.sos.get_prep(rholabel).has_nonzero_hessian(): derivWrtAnyRhovec = scale * _np.dot(E, prod) # may overflow,", "drho = rhoVec.deriv_wrt_params(rho_wrtFilter1) dp_dAnyE = _np.dot(Gs, drho) * scaleVals[:, None, None] # overflow", "dp_dAnyRho, self.sos.get_prep(rholabel).hessian_wrt_params( # rho_wrtFilter1, rho_wrtFilter2)) else: d2pr_d2rhos = 0 if self.sos.get_effect(elabel).has_nonzero_hessian(): dp_dAnyE =", "gateLabel_ij. This function returns a concatenated form of the above matrices, so that", "is mult by a zero deriv value (see below) dGs[_np.isnan(dGs)] = 0 _np.seterr(**old_err)", "Gs = evalSubTree.final_view(prodCache, axis=0) # ( nCircuits, dim, dim ) def calc_and_fill(spamTuple, fInds,", "axis 1 of mxToFill[felInds], dim=(ks,M) profiler.add_time(\"MPI IPC\", tm) profiler.mem_check(\"bulk_fill_dprobs: post gather blocks\") #collect/gather", "values for only a single spam label (specified to it by the first", "Returns ------- derivative : numpy array a 1 x M numpy array of", "def estimate_cache_size(self, nCircuits): \"\"\" Return an estimate of the ideal/desired cache size given", "sequence and spam label indexed by iOpStr and iSpamLabel. d12 has the same", "for spamTuple, (fInds, gInds) in evalTree.spamtuple_indices.items(): # fInds = \"final indices\" = the", ") ] # noqa # + sum{ L == M} [ G1 ...", "parameters. if self.sos.get_prep(rholabel).has_nonzero_hessian(): derivWrtAnyRhovec = scale * _np.dot(E, prod) # may overflow, but", "calculations. This is contained in a class separate from Model to allow for", "if not None. Only relevant when prMxToFill is not None. bUseScaling : bool,", "cache space. Will use derivative rows and columns and then (as needed) a", "self.Np if (wrtFilter is None) else len(wrtFilter) flattened_dprod = _np.zeros((dim**2, num_deriv_cols), 'd') #", "more processors than deriv cells, give a # warning -- note that we", "scale = self.product(circuit, True) if returnPr: p = _np.dot(E, _np.dot(prod, rho)) * scale", "4) * scaleVals, 0, 4) # convert nans to zero, as these occur", "= 0 # d2pr/d(rho)_i d(rho)_j = 0 rholabel, elabel = spamTuple rho, E", "\"matrix-based calculations\" % self.evotype)) def copy(self): \"\"\" Return a shallow copy of this", "numpy array where E is the total number of computed elements (i.e. evalTree.num_final_elements())", "wrtFilter2 is None) # cannot specify both wrtFilter and blkSize nBlks1 = int(_np.ceil(self.Np", "dim = self.dim nspam = int(round(_np.sqrt(self.dim))) # an estimate - could compute? wrtLen1", "[fInds, pslc1], self._dprobs_from_rhoE( spamTuple, rho, E, Gs[gInds], dGs1[gInds], scaleVals[gInds], wrtSlice1), add=sumInto) if deriv2MxToFill", "operation labels. flat : bool, optional Affects the shape of the returned derivative", "self.Np)) for i in range(self.Np): dpr_dOps[0, i] = float(_np.dot(E, _np.dot(dprod_dOps[i], rho))) #Derivs wrt", "int The number of groups to divide the first-derivative parameters into. Computation will", "wrtSlice1, wrtSlice2, hprobs, dprobs12 else: yield wrtSlice1, wrtSlice2, hprobs dProdCache1 = dGs1 =", "mx w/ col_i = A[col0] * B[0,1] ) = B^T tensor A *", "entirely different -- non-gate-local -- parameterizations of operation matrices and SPAM vectors) access", "passed to the functions named by `subcalls`. num_subtrees : int The number of", "- 1)]), prods[(m + 1, l - 1)]) # (dim**2, dim**2) x =", "prodCache, dProdCache1[:, myDeriv1ColSlice], dProdCache2[:, myDeriv2ColSlice], scaleCache, None, myHessianSlice1, myHessianSlice2) # pass None as", "S is the number of operation sequences (i.e. evalTree.num_final_strings()), - B is the", "blkSize2 blocks1 = _mpit.slice_up_range(self.Np, nBlks1) blocks2 = _mpit.slice_up_range(self.Np, nBlks2) #distribute derivative computation across", "if self.evotype == \"statevec\": ps = _np.real(_np.abs(_np.dot(Es, _np.dot(G, rho)))**2) else: # evotype ==", "# noqa for iBlk1 in myBlk1Indices: blk_wrtSlice1 = blocks1[iBlk1] dProdCache1 = self._compute_dproduct_cache( evalSubTree,", "products : numpy array Only returned when bReturnProds == True. An array of", "probability-derivatives for an entire tree of gate strings. Similar to `bulk_fill_probs(...)`, but fills", "Contract DE-NA0003525 with NTESS, the U.S. Government retains certain rights # in this", "an element of the product (els of # prod.flatten()). # # Note: if", "comm) #print(\"MPI: _compute_dproduct_cache over %d cols (%s) (rank %d computing %s)\" \\ #", "not None: # print(\"MPI DEBUG: Rank%d subtee sizes = %s\" % # (comm.Get_rank(),\",\".join([str(len(subtrees[i]))", "= _np.dot(L, R) scaleCache[i] = scaleCache[iLeft] + scaleCache[iRight] if prodCache[i].max() < PSMALL and", "probabilities, corresponding to the elements of `elabels`. \"\"\" assert(time is None), \"MatrixForwardSimulator cannot", "ints, optional If not None, a list of integers specifying which parameters to", "parameters being differentiated with respect to (see wrtBlockSize). wrtFilter1, wrtFilter2 : list of", ") # In general: vec( A * X * B ) = B^T", "for distributing the computation across multiple processors. This is done over operation sequences", "[felInds], 1, mySubComm, gatherMemLimit) if deriv2MxToFill is not None: _mpit.gather_slices(blocks2, blk2Owners, deriv2MxToFill, [felInds],", "d(pr*pr.C)/dx = dpr/dx*pr.C + pr*dpr/dx.C # = 2 Re(dpr/dx*pr.C) , where dpr/dx is", "(nDerivCols, dim, dim) cacheSize = len(evalTree) # ------------------------------------------------------------------ #print(\"MPI: _compute_dproduct_cache begin: %d deriv", "_np.zeros((cacheSize,) + hessn_shape) # Use comm to distribute columns allDeriv1ColSlice = slice(0, nDerivCols1)", "= sum [dprod/d(opLabel)_mn]_il rho_l (and same for other diff order) # d2pr/d(E)_i d(rho)_j", "copy(self): \"\"\" Return a shallow copy of this MatrixForwardSimulator \"\"\" return MatrixForwardSimulator(self.dim, self.sos,", "return flattened_hprod else: return _np.transpose(flattened_hprod, (1, 2, 0)).reshape( (num_deriv_cols1, num_deriv_cols2, dim, dim)) #", "parameter. products : numpy array Only returned when bReturnProds == True. An array", "_np.conjugate(_np.transpose(Eraw)) return rho, E def _rhoEs_from_spamTuples(self, rholabel, elabels): #Note: no support for \"custom\"", "felInds = evalSubTree.final_element_indices(evalTree) #Free memory from previous subtree iteration before computing caches scaleVals", "relevant when prMxToFill is not None. bUseScaling : bool, optional Whether to use", "A * E(0,1) * B ) = vec( mx w/ col_i = A[col0]", "self.Np)) _fas(dpr_drhos, [0, self.sos.get_prep(rholabel).gpindices], _np.dot(derivWrtAnyRhovec, rhoVec.deriv_wrt_params())) # may overflow, but OK dpr_dEs =", "renormed to keep all the products within decent bounds #assert( len( (_np.isnan(dGs)).nonzero()[0] )", "# a derivative of only a *subset* of all the gate's parameters if", "all the products within decent # bounds #assert( len( (_np.isnan(hGs)).nonzero()[0] ) == 0", "== \"statevec\": raise NotImplementedError(\"Unitary evolution not fully supported yet!\") #Compute probability and save", "as the final block size. These arguments must be None if the corresponding", "wrtFilter is not None: obj_wrtFilter = [] # values = object-local param indices", "a given gateLabel_ij. This function returns a concatenated form of the above matrices,", "first element of circuit can be thought of as the first gate operation", "dG(M)/dkl ) ) # noqa # tensor (G(L+1) ... GN)^T vec( dG(L)/dij )", "Will use derivative columns and then (and only when needed) a split tree", "nDerivCols = self.Np if wrtSlice is None else _slct.length(wrtSlice) # GATE DERIVS (assume", "_slct.list_to_slice(wrtFilter2) else: wrtSlice2 = None #get distribution across subtrees (groups if needed) subtrees", "unvec( G1 ... G(M-1) tensor (G(M+1) ... G(L-1))^T vec( dG(M)/dkl ) ) #", "deriv cols, rows = flattened everything else return (dGs, Gs, scaleVals) if bScale", "then # it could make sense to iterate through the self.operations.keys() as in", "axis=0) if bReturnDProbs12: dprobs1 = _np.zeros((nElements, _slct.length(wrtSlice1)), 'd') dprobs2 = _np.zeros((nElements, _slct.length(wrtSlice2)), 'd')", "and opsToVectorize2 we only compute d2(prod)/d(gl1)d(gl2) # and not d2(prod)/d(gl2)d(gl1) ... if m", "dProdCache1 = dGs1 = None # free mem #gather column results: gather axis", "d2pr_drhos[i,j,J0+J] = sum_kl E[0,k] dGs[i,j,k,l] drhoP[l,J] # d2pr_drhos[i,j,J0+J] = dot(E, dGs, drhoP)[0,i,j,J] #", "## (and dominated) by the output array size. Could throw more informative error?", "shape S*N x M where: - N == the number of entries in", "# d2pr_dOps2[i,j,k] = sum_l E[0,l] dot( dGs, rho )[i,j,k,l,0] # d2pr_dOps2[i,j,k] = dot(", "in-place clip if check: self._check(evalTree, prMxToFill, mxToFill, clipTo=clipTo) profiler.add_time(\"bulk_fill_dprobs: total\", tStart) profiler.add_count(\"bulk_fill_dprobs count\")", "x G operation matrices). and deriv[i,j,k] holds the derivative of the (j,k)-th entry", "d2pr_dEs[i,j,J0+J] = dot( squeeze(dot(dGs, rho),axis=(3,)), dEP)[i,j,J] # d2pr_dEs[:,:,J0+J] = dot( squeeze(dot(dGs, rho),axis=(3,)), dEP)[:,:,J]", "by Python `slice` objects. bReturnDProbs12 : boolean, optional If true, the generator computes", "wrtBlockSize : int or float, optional The maximum number of derivative columns to", "if flat == True, an array of shape S*N x M x M", "incompatbile with \" \"matrix-based calculations\" % self.evotype)) def copy(self): \"\"\" Return a shallow", "== ( len(circuit_list), dim, dim ), # Gs[i] is product for i-th operation", "scaleVals[:, None]) # may overflow, but OK # Get: dp_dEs[i, E_gpindices] = dot(transpose(dE/dEP),Gs[i],rho))", "wrtLen2 # hprobs & dprobs12 results mem += cache_size * nspam * (wrtLen1", "gate (ordering is the same as that used by numpy.flatten), - S,M ==", "deriv2MxToFill, [], 0, comm, gatherMemLimit) if prMxToFill is not None: _mpit.gather_indices(subtreeElementIndices, subTreeOwners, prMxToFill,", "w.r.t any of self.effects - independent of which) dp_dAnyE = _np.squeeze(_np.dot(Gs, rho), axis=(2,))", "mxToFill, clipTo=clipTo) def bulk_fill_dprobs(self, mxToFill, evalTree, prMxToFill=None, clipTo=None, check=False, comm=None, wrtFilter=None, wrtBlockSize=None, profiler=None,", "1)) + \\ d2pr_dEs + _np.transpose(d2pr_dEs, (0, 2, 1)) + \\ d2pr_d2rhos +", "may overflow, but OK if infs occur here _np.seterr(**old_err) return scaleVals def _rhoE_from_spamTuple(self,", "a tree of product 2nd derivatives in a linear cache space. Will use", "simultaneously. None means compute all requested rows or columns at once. The minimum", "that d^2 G/(dij)^2 == 0, which is true IF each operation matrix element", "= _np.seterr(over='ignore') Gs = _np.swapaxes(_np.swapaxes(Gs, 0, 2) * scaleVals, 0, 2) # may", "# # loc_e_slices = [ # _slct.shift(_slct.intersect( # wrtSlices['effects'], # slice(self.e_offset[i],self.e_offset[i+1])), # -self.e_offset[i])", "their probabilites). These are a \"simplified\" circuits in that they should only contain", "since we've renormed to keep all the products within decent # bounds #assert(", "wrtSlice1) dProdCache2 = dProdCache1 if (wrtSlice1 == wrtSlice2) else \\ self._compute_dproduct_cache(evalSubTree, prodCache, scaleCache,", "E_wrtFilter2)) else: d2pr_d2Es = 0 # END SPAM DERIVS ----------------------- ret = d2pr_d2rhos", "below gpindices1 = {}; gate_wrtFilters1 = {} gpindices2 = {}; gate_wrtFilters2 = {}", "[_slct.length(s) for s in loc_e_slices] # tmp_offsets = [ sum(tmp_num_params[0:i]) for i in", "i-th operation sequence dGs = evalTree.final_view(dProdCache, axis=0) #shape == ( len(circuit_list), nDerivCols, dim,", "0 # convert nans to zero, as these occur b/c an inf scaleVal", "free mem dProdCache1 = dGs1 = None # free mem #gather column results:", "wrtFilter -> wrtSlice? prodCache, scaleCache = self._compute_product_cache(evalTree, comm) dProdCache = self._compute_dproduct_cache(evalTree, prodCache, scaleCache,", "exp %g\\n%s\" % (i,p,norm(G),total_exp,str(G)) # if _np.isnan(p): raise ValueError(\"STOP\") if clipTo is not", "\"final element\" of `evalTree`. Parameters ---------- mxToFill : numpy ndarray an already-allocated ExM", "info (not requiring column distribution) tm = _time.time() prodCache, scaleCache = self._compute_product_cache(evalSubTree, mySubComm)", "we've renormed to keep all the products within decent # bounds #assert( len(", "x0 = _np.kron(_np.transpose(prods[(0, m - 1)]), prods[(m + 1, N - 1)]) #", "to bulk_evaltree. Specifies the *simplified* gate strings to compute the bulk operation on.", "... G(L-1)) tensor (G(L+1) ... GN)^T ]] has # columns which correspond to", "_nla.norm(check_vhp), _nla.norm(hprMxToFill[fInds] - check_vhp))) # pragma: no cover def bulk_fill_probs(self, mxToFill, evalTree, clipTo=None,", "of self.effects - independent of which) dp_dAnyE = _np.squeeze(_np.dot(Gs, rho), axis=(2,)) * scaleVals[:,", "in range(self.Np): dpr_dOps[0, i] = float(_np.dot(E, _np.dot(dprod_dOps[i], rho))) if returnPr: p = _np.dot(E,", "Get: d2pr_dEs[i, j, E_gpindices] = dot(transpose(dE/dEP),dGs[i,j],rho) # d2pr_dEs[i,j,J0+J] = sum_kl dEPT[J,k] dGs[i,j,k,l] rho[l,0]", "# vec( dprod/d(opLabel)_ij ) = sum_{L s.t. G(L) == oplabel} [ (G1 ...", "so that # each column corresponds to a (opLabel,i,j) tuple and each row", "dot(transpose(dE/dEP),Gs[i],rho)) # dp_dEs[i,J0+J] = sum_lj dEPT[J,j] Gs[i,j,l] rho[l,0] # dp_dEs[i,J0+J] = sum_j dEP[j,J]", "to compute the bulk operation on. This tree *cannot* be split. wrtSlicesList :", "column of the Hessian at a time. For example, the Hessian of a", "computed fully on each inner loop *iteration*!) #collect/gather results subtreeElementIndices = [t.final_element_indices(evalTree) for", "0, 3).reshape( (nDerivCols1, nDerivCols2, nCircuits * dim**2)), 2) # cols = deriv cols,", "(j,k)-th entry of the product with respect to the i-th model parameter. *", "rows of mxToFill and spam labels. evalTree : EvalTree given by a prior", "dL,dR = vgs x GxG ; hL,hR = vgs x vgs x GxG", "nDerivCols, nDerivCols, dim, dim ) if not bScale: old_err = _np.seterr(over='ignore', invalid='ignore') #", "= _np.zeros((cacheSize,) + hessn_shape) #First element of cache are given by evalTree's initial", "no cover if dprMxToFill is not None: check_vdp = _np.concatenate( [self.dpr(spamTuple, circuit, False,", "scope. This use of # closures seems confusing and we should do something", "if i in gpindices: relevant_gpindices.append(ii) obj_wrtFilter.append(list(gpindices).index(i)) relevant_gpindices = _np.array(relevant_gpindices, _np.int64) if len(relevant_gpindices) ==", "rho,E b/c rho,E are EVec = self.sos.get_effect(elabel) # arrays, these are SPAMVecs #Derivs", "hProdCache[i] = _np.zeros(hessn_shape) else: hoperation = self.hoperation(opLabel, wrtFilter1=wrtIndices1, wrtFilter2=wrtIndices2) hProdCache[i] = hoperation /", "is not None: p = _np.clip(p, clipTo[0], clipTo[1]) dprod_dOps = self.dproduct(circuit) assert(dprod_dOps.shape[0] ==", "return MatrixForwardSimulator(self.dim, self.sos, self.paramvec) def product(self, circuit, bScale=False): \"\"\" Compute the product of", ")[i,j,k,l,0] # d2pr_dOps2[i,j,k] = dot( E, dot( dGs, rho ) )[0,i,j,k,0] # d2pr_dOps2", "prodCache = scaleCache = None #Fill cache info prodCache, scaleCache = self._compute_product_cache(evalSubTree, mySubComm)", "below) dGs[_np.isnan(dGs)] = 0 _np.seterr(**old_err) if flat: dGs = _np.swapaxes(_np.swapaxes(dGs, 0, 1).reshape( (nDerivCols,", "wrtFilter1=None, wrtFilter2=None): \"\"\" Return the hessian of a length-1 (single-gate) sequence \"\"\" dim", "1, mySubComm, gatherMemLimit) if deriv1MxToFill is not None: _mpit.gather_slices(blocks1, blk1Owners, deriv1MxToFill, [felInds], 1,", "def doperation(self, opLabel, flat=False, wrtFilter=None): \"\"\" Return the derivative of a length-1 (single-gate)", "in subcalls: if fnName == \"bulk_fill_probs\": mem += cache_size * dim * dim", "derivative of a specified sequence of operation labels. Parameters ---------- circuit : Circuit", "rho[l,0] # d2pr_dEs[i,j,J0+J] = sum_k dEP[k,J] dot(dGs, rho)[i,j,k,0] # d2pr_dEs[i,j,J0+J] = dot( squeeze(dot(dGs,", "l, opLabel2 in enumerate(revOpLabelList): inds2 = gpindices1[opLabel2] #nDerivCols2 = dop_dopLabel2[opLabel2].shape[1] # FUTURE: we", "A list of :class:`Label` objects giving the *simplified* effect labels. circuit : Circuit", "multiplicative scaling needed for the derivatives and/or products for the i-th operation sequence.", "deriv2Owners, hProdCache, [None, myDeriv1ColSlice], 2, mySubComm) # , gatherMemLimit) #gather over col-distribution (Deriv2)", "#NOTE: filtering is done via the yet-to-be-defined local variables # wrtSlice1 and wrtSlice2,", "NotImplementedError(\"Unitary evolution not fully supported yet!\") #Compute probability and save in return array", "tmp_num_params = [_slct.length(s) for s in loc_rho_slices] # tmp_offsets = [ sum(tmp_num_params[0:i]) for", "nDerivCols2, nDerivCols1)) _fas(d2pr_drhos2, [None, None, rho_gpindices1], _np.squeeze(_np.dot(_np.dot(E, dGs2), drho), axis=(0,)) * scaleVals[:, None,", "a single operation sequence. The spam tuples may only vary in their effect-label", "else: wrtSlice = None profiler.mem_check(\"bulk_fill_dprobs: begin (expect ~ %.2fGB)\" % (mxToFill.nbytes / (1024.0**3)))", "nDerivCols2)) drho = rhoVec.deriv_wrt_params(rho_wrtFilter2) dp_dAnyE = _np.dot(Gs, drho) * scaleVals[:, None, None] #", "== 0 ) #assert( len( (_np.isinf(dGs)).nonzero()[0] ) == 0 ) #dGs = clip(dGs,-1e300,1e300)", "= %g\" % (_nla.norm(prMxToFill[fInds]), _nla.norm(check_vp), _nla.norm(prMxToFill[fInds] - check_vp))) # pragma: no cover if", "None and prMxToFill is not None: _np.clip(prMxToFill, clipTo[0], clipTo[1], out=prMxToFill) # in-place clip", "overflow or get nans (invalid), but ok dGs2 = _np.swapaxes(_np.swapaxes(dGs2, 0, 3) *", "d(probability)/dOps and save in return list (now have G,dG => product, dprod_dOps) #", "- S == len(circuit_list) - M == the length of the vectorized model", "= self._compute_hproduct_cache(evalSubTree, prodCache, dProdCache1, dProdCache2, scaleCache, mySubComm, wrtSlice1, wrtSlice2) hGs = evalSubTree.final_view(hProdCache, axis=0)", "True, additionally return the derivative of the probability. clipTo : 2-tuple (min,max) to", "Allocate memory for the final result num_deriv_cols = self.Np if (wrtFilter is None)", "ret, dpr else: if returnPr: return ret, p else: return ret ## BEGIN", "scale cache # mem += cache_size # scale vals else: raise ValueError(\"Unknown subcall", "quantity combining both spam and gate-sequence indices # gInds = \"gate sequence indices\"", "wrtBlockSize and the size that makes maximal use of available processors is used", "with norm <= 1, products should all have norm <= 1 assert(len(nanOrInfCacheIndices) ==", "syncronization. Returns ------- None \"\"\" if wrtFilter1 is not None: assert(wrtBlockSize1 is None", "j-th model parameter. * if flat == True, an array of shape S*N", "above: (nDerivCols1,dim**2,dim**2) * (dim**2,nDerivCols2) = (nDerivCols1,dim**2,nDerivCols2) flattened_d2prod[:, inds1, inds2] += _np.swapaxes(y, 0, 1)", "dim ) #Same as in bulk_fill_hprobs (TODO consolidate?) #NOTE: filtering is done via", "x M numpy array, where M is the number of model parameters. Parameters", "of operation labels. Note: LinearOperator matrices are multiplied in the reversed order of", "None: assert(wrtBlockSize1 is None and wrtBlockSize2 is None) # Cannot specify both wrtFilter", "in the order given by `wrtSlicesList`. `rowSlice` and `colSlice` must by Python `slice`", "# same as in dpr(...) dpr_dOps = _np.empty((1, self.Np)) for i in range(self.Np):", "in zip(evalTree.get_init_indices(), evalTree.get_init_labels()): if opLabel == \"\": # special case of empty label", "names of the subcalls to estimate memory usage for. cache_size : int The", "do matrix multiplication in this order (easier to think about) revOpLabelList = tuple(reversed(tuple(circuit)))", "for s in loc_rho_slices] # tmp_offsets = [ sum(tmp_num_params[0:i]) for i in range(len(self.preps)+1)", "dot( dGs, rho ) ), axis=(0,4)) old_err2 = _np.seterr(invalid='ignore', over='ignore') d2pr_dOps2 = _np.squeeze(_np.dot(E,", "_warnings.warn(\"Ignoring tree splitting in dproduct cache calc.\") dProdCache = _np.zeros((cacheSize,) + deriv_shape) #", "if abs(scale) > 1e-8: # _np.isclose(scale,0) is SLOW! dProdCache[i] /= _np.exp(scale) if dProdCache[i].max()", "hGs = evalSubTree.final_view(hProdCache, axis=0) #( nCircuits, len(wrtFilter1), len(wrtFilter2), dim, dim ) #Compute all", "dprod_dOps for ith string hGs = evalTree.final_view(hProdCache, axis=0) #shape == ( len(circuit_list), nDerivCols1,", "= self._compute_dproduct_cache( evalSubTree, prodCache, scaleCache, blk1Comm, blk_wrtSlice1) dGs1 = evalSubTree.final_view(dProdCache1, axis=0) for iBlk2", "can be used for product computation\") pass # this is a fairly common", "parameters (by wrtFilter1 and wrtFilter2). evalTree : EvalTree given by a prior call", "0, self.dim, self.dim), 'd') def calc_and_fill_p(spamTuple, fInds, gInds, pslc1, pslc2, sumInto): \"\"\" Compute", "probabilities generated by a each gate sequence given by evalTree column-by-column. This routine", "calc_and_fill) profiler.mem_check(\"bulk_fill_dprobs: post fill\") dProdCache = dGs = None # free mem else:", "OK if clipTo is not None: p = _np.clip(p, clipTo[0], clipTo[1]) #Derivs wrt", "and necessary) if comm.Get_size() > nDerivCols: #If there are more processors than deriv", "G(L+1) ... GN ] , a matrix for each given (i,j) # noqa", "= sum j dEPT[J,j] dot(prod,drhoP)[i,j,K] # d2pr_dErhos[i,J0+J,K0+K] = dot(dEPT,prod,drhoP)[J,i,K] # d2pr_dErhos[i,J0+J,K0+K] = swapaxes(dot(dEPT,prod,drhoP),0,1)[i,J,K]", "# -self.e_offset[i]) for i in range(len(self.effects))] # tmp_num_params = [_slct.length(s) for s in", "dim x dim, and all SPAM vectors should be dim x 1. gates,", "1e-300) sL, sR = L / nL, R / nR prodCache[i] = _np.dot(sL,", "= dProdCache1 if (wrtSlice1 == wrtSlice2) else \\ self._compute_dproduct_cache(evalTree, prodCache, scaleCache, comm, wrtSlice2)", "profiling of python objects (never seemed very useful ## since numpy does all", "%d computing %s)\" \\ # % (nDerivCols2, comm.Get_rank(), str(myDerivColSlice))) if mySubComm is not", "_warnings.warn(\"norm(vhp-check_vhp) = %g - %g = %g\" % (_nla.norm(hprMxToFill[fInds]), _nla.norm(check_vhp), _nla.norm(hprMxToFill[fInds] - check_vhp)))", "objects: (prepVec, effectVec) rho, Eraw = spamTuple E = _np.conjugate(_np.transpose(Eraw)) return rho, E", "self.Np if (wrtFilter is None) else len(wrtFilter) flattened_dprod = _np.zeros((dim**2, num_deriv_cols), 'd') _fas(flattened_dprod,", "= _np.exp(scaleExps) # may overflow, but OK if infs occur here _np.seterr(**old_err) if", "Gs, dGs, scaleVals, wrtSlice=None): if self.evotype == \"statevec\": raise NotImplementedError(\"Unitary evolution not fully", "+= d2pr_drhos1 + d2pr_dEs1 + d2pr_dOps2 # wrt gates return ret def _check(self,", "dEPT[J,j] prod[i,j,k] drhoP[k,K] # d2pr_dErhos[i,J0+J,K0+K] = sum j dEPT[J,j] dot(prod,drhoP)[i,j,K] # d2pr_dErhos[i,J0+J,K0+K] =", "also conjugate() here if complex? _fas(dpr_dEs, [0, EVec.gpindices], _np.dot(derivWrtAnyEvec, EVec.deriv_wrt_params())) _np.seterr(**old_err) if returnPr:", "memory usage for. cache_size : int The size of the evaluation tree that", "(TODO in FUTURE) # pr = Tr( |rho><E| * prod ) = sum", "= [self.sos.get_effect(elabel).todense()[:, None] for elabel in elabels] Es = _np.conjugate(_np.transpose(_np.concatenate(Es, axis=1))) # convention:", "like length>1 lists do... ugh. relevant_gpindices = slice(0, 0) # slice that results", "to bulk_evaltree. Specifies the operation sequences to compute the bulk operation on. flat", "scale_exp = 0 G = _np.identity(self.dim) for lOp in circuit: if lOp not", "None]) # may overflow, but OK # Get: dp_dEs[i, E_gpindices] = dot(transpose(dE/dEP),Gs[i],rho)) #", "operation sequence with respect to the # gate's parameters and fill appropriate columns", "scaleVals[:, None] # overflow OK d2pr_d2Es = _np.zeros((nCircuits, nDerivCols1, nDerivCols2)) _fas(d2pr_d2Es, [None, E_gpindices1,", "in-place clip if check: self._check(evalTree, mxToFill, clipTo=clipTo) def bulk_fill_dprobs(self, mxToFill, evalTree, prMxToFill=None, clipTo=None,", "if prodCache[i].max() < PSMALL and prodCache[i].min() > -PSMALL: nL, nR = max(_nla.norm(L), _np.exp(-scaleCache[iLeft]),", "# noqa # if dG(L)/dij = E(i,j) # noqa # = vec(i,j)-col of", "E(0,1) * B ) = vec( mx w/ col_i = A[col0] * B[0,1]", "MATRIX ORDER Note: we reverse iLeft <=> iRight from evalTree because # (iRight,iLeft,iFinal)", "or get nans (invalid), but ok dGs = _np.swapaxes(_np.swapaxes(dGs, 0, 3) * scaleVals,", "vgs x vgs x GxG dLdRa = _np.swapaxes(_np.dot(dL1, dR2), 1, 2) dLdRb =", "in evalTree.spamtuple_indices.items(): # fInds = \"final indices\" = the \"element\" indices in the", "str(allDerivColIndices), comm.Get_rank(), str(myDerivColIndices))) if mySubComm is not None and mySubComm.Get_size() > 1: _warnings.warn(\"Too", "we could add logic that accounts for the symmetry of the Hessian, so", "Engineering Solutions of Sandia, LLC (NTESS). # Under the terms of Contract DE-NA0003525", "G(M-1) dG(M)/dkl G(M+1) ... G(L-1) tensor (G(L+1) ... GN)^T vec( dG(L)/dij ) ]", "# ( nCircuits, dim, dim ) def calc_and_fill(spamTuple, fInds, gInds, pslc1, pslc2, sumInto):", "b/c an inf scaleVal is mult by a zero deriv value (see below)", "labels and values which are integer row indices into mxToFill, specifying the correspondence", "L, R = prodCache[iLeft], prodCache[iRight] prodCache[i] = _np.dot(L, R) scaleCache[i] = scaleCache[iLeft] +", "of the parameters being differentiated with respect to (see wrtBlockSize). wrtFilter : list", "state preparation label. elabels : list A list of :class:`Label` objects giving the", "prod) _fas(dpr_drhos, [0, self.sos.get_prep(rholabel).gpindices], _np.dot(derivWrtAnyRhovec, rhoVec.deriv_wrt_params())) # may overflow, but OK dpr_dEs =", "min(comm_blkSize, blkSize1) # override with smaller comm_blkSize blkSize2 = comm_blkSize if (blkSize2 is", "# p = _mt.trace( _np.dot(self.SPAMs[spamLabel],G) ) * exp(total_exp) # probability # print \"%d:", "same for other diff order) # d2pr/d(E)_i d(opLabel)_mn = sum [dprod/d(opLabel)_mn]_il rho_l (and", "all requested columns at once. The minimum of wrtBlockSize and the size that", "# overflow OK devec = EVec.deriv_wrt_params(E_wrtFilter1) _fas(d2pr_dErhos1, (None, E_gpindices1, rho_gpindices2), _np.swapaxes(_np.dot(_np.transpose(devec), dp_dAnyE), 0,", "dP/d(p1)*dP/d(p2) where P is is the probability generated by the sequence and spam", "in evalTree.spamtuple_indices.items(): circuit_list = master_circuit_list[gInds] if prMxToFill is not None: check_vp = _np.array([self.prs(spamTuple[0],", "# GATE DERIVS (assume hGs is already sized/filtered) ------------------- assert(hGs.shape[1] == nDerivCols1), \"hGs", "deriv : numpy array * if flat == False, a M x G", "are EVec = self.sos.get_effect(elabel) # arrays, these are SPAMVecs d2prod_dGates = self.hproduct(circuit) assert(d2prod_dGates.shape[0]", "optional Affects the shape of the returned derivative array (see below). bReturnDProdsAndProds :", "if bReturnDProdsAndProds: Gs = evalTree.final_view(prodCache, axis=0) #shape == ( len(circuit_list), dim, dim ),", "A list of the names of the subcalls to estimate memory usage for.", "= _np.seterr(over='ignore') rho, E = self._rhoE_from_spamTuple(spamTuple) block_wrtSlice = pslc1 _fas(mxToFill, [fInds, pslc1], self._dprobs_from_rhoE(", "(which numpy.flatten does) # vec( A * E(0,1) * B ) = vec(", "= self.dim uniqueOpLabels = sorted(list(set(revOpLabelList))) used_operations = _collections.OrderedDict() #Cache processed parameter filters for", "... GN)^T vec( dG(L)/dij ) ] # noqa # + sum{ L <", "= squeeze(dot(E, Gs, drhoP),axis=(0,))[:,J] dp_drhos = _np.zeros((nCircuits, nDerivCols)) _fas(dp_drhos, [None, rho_gpindices], _np.squeeze(_np.dot(_np.dot(E, Gs),", "way dim = self.dim nspam = int(round(_np.sqrt(self.dim))) # an estimate - could compute?", "given each processor a list appropriate for it. # Use comm only for", "= self.dproduct( (opLabel,) , wrtFilter=wrtIndices) doperation = self.doperation(opLabel, wrtFilter=wrtIndices) dProdCache[i] = doperation /", "dp2[:,:,None,colSlice]` \"\"\" assert(not evalTree.is_split()), \"`evalTree` cannot be split\" nElements = evalTree.num_final_elements() #Fill product", "the tree construction by giving the tree information it needs to distribute itself", "wrtSlice = _slct.list_to_slice(wrtFilter) if (wrtFilter is not None) else None #TODO: just allow", "= self._compute_product_cache(evalSubTree, mySubComm) scaleVals = self._scaleExp(evalSubTree.final_view(scaleCache)) Gs = evalSubTree.final_view(prodCache, axis=0) #( nCircuits, dim,", "not None: check_vdp = _np.concatenate( [self.dpr(spamTuple, circuit, False, clipTo) for circuit in circuit_list],", "is a column of the matrix d12 defined by: d12[iSpamLabel,iOpStr,p1,p2] = dP/d(p1)*dP/d(p2) where", "= _np.zeros((1, self.Np, self.Np)) _fas(d2pr_d2rhos, [0, self.sos.get_prep(rholabel).gpindices, self.sos.get_prep(rholabel).gpindices], _np.tensordot(derivWrtAnyRhovec, self.sos.get_prep(rholabel).hessian_wrt_params(), (1, 0))) #", "pslc1 = param_slice1 pslc2 = param_slice2 for spamTuple, (fInds, gInds) in evalTree.spamtuple_indices.items(): #", "the now un-vectorized dim x dim mxs corresponding to a single kl xv", "prior call to bulk_evaltree. Specifies the *simplified* gate strings to compute the bulk", "calculations across multiple processors. Returns ------- hessians : numpy array * if flat", "+ d2pr_dEs1 + d2pr_dOps2 # wrt gates return ret def _check(self, evalTree, prMxToFill=None,", "model). This argument is used internally for distributing derivative calculations across multiple processors.", "Get slice into entire range of model params (see above) if wrtSlice2 is", "dop_dopLabel), add=True) # (dim**2, nParams[opLabel]) if flat: return flattened_dprod else: # axes =", "or tuples of operation labels which specify the operation sequences to create an", "is product for i-th operation sequence scaleExps = evalTree.final_view(scaleCache) old_err = _np.seterr(over='ignore') scaleVals", "(invalid), but ok dGs = _np.swapaxes(_np.swapaxes(dGs, 0, 3) * scaleVals, 0, 3) #", "too # Compute the derivative of the entire operation sequence with respect to", "params or wrtFilter1 or 2, respectively - G == the linear dimension of", "Gs).squeeze(0) * scaleVals[:, None] # overflow OK d2pr_d2rhos = _np.zeros((nCircuits, nDerivCols1, nDerivCols2)) _fas(d2pr_d2rhos,", "Returns ------- int The memory estimate in bytes. \"\"\" #Note: num_final_strs is irrelevant", "(opLabel,i,j) tuple and each row corresponds to an element of the product (els", "flattened_dprod else: # axes = (gate_ij, prod_row, prod_col) return _np.swapaxes(flattened_dprod, 0, 1).reshape((num_deriv_cols, dim,", "(scaleCache[iLeft] + scaleCache[iRight]) if abs(scale) > 1e-8: # _np.isclose(scale,0) is SLOW! hProdCache[i] /=", "This routine can be useful when memory constraints make constructing the entire Hessian", "\"\"\" dim = self.dim nDerivCols1 = self.Np if (wrtFilter1 is None) else _slct.length(wrtFilter1)", "under the Apache License, Version 2.0 (the \"License\"); you may not use this", "being # split because there's no good way to reconstruct the # *non-final*", "= self._compute_hproduct_cache(evalTree, prodCache, dProdCache1, dProdCache2, scaleCache, comm, wrtSlice1, wrtSlice2) #use cached data to", "#for i,lOp in enumerate(gateLabelList): # G = _np.dot(G,self[lOp]) # product of gates, starting", "processors and to control memory usage. Cannot be specified in conjuction with wrtBlockSize.", "3).reshape((vec_kl_size, vec_ij_size, dim, dim)) # axes = (model_parameter1, model_parameter2, model_element_row, model_element_col) def prs(self,", "(dGs, scaleVals) if bScale else dGs def bulk_hproduct(self, evalTree, flat=False, bReturnDProdsAndProds=False, bScale=False, comm=None,", "t in subtrees] _mpit.gather_indices(subtreeElementIndices, subTreeOwners, mxToFill, [], 0, comm, gatherMemLimit) if deriv1MxToFill is", "use in computations. \"\"\" super(MatrixForwardSimulator, self).__init__( dim, simplified_op_server, paramvec) if self.evotype not in", "scaling -- faster but susceptible to overflow G = self.product(circuit, False) if self.evotype", "constructing the entire Hessian at once impractical, and one is able to compute", "# nG = norm(G); G /= nG; total_exp += log(nG) # scale and", "returned if bReturnDProdsAndProds == True. * if flat == False, two arrays of", "not None: p = _np.clip(p, clipTo[0], clipTo[1]) #Derivs wrt SPAM derivWrtAnyRhovec = scale", "compute_dproduct_cache\", tm) profiler.mem_check( \"bulk_fill_dprobs: post compute dproduct blk (expect \" \" +%.2fGB, shape=%s)\"", "# LEXICOGRAPHICAL VS MATRIX ORDER else: G = H old_err = _np.seterr(over='ignore') scale", "* nCircuits) def construct_evaltree(self, simplified_circuits, numSubtreeComms): \"\"\" Constructs an EvalTree object appropriate for", "object of *simplified* gates (e.g. may include instrument elements like 'Imyinst_0') returnPr :", "# num_e_params=_slct.length(wrtSlices['effects'])) # else: # loc_rho_slices = [slice(None,None)]*len(self.preps) # loc_e_slices = [slice(None,None)]*len(self.effects) #", "== length of the vectorized model (number of model parameters) and deriv[i,j] holds", "be None? assert(nDerivCols1 == nDerivCols2) d2pr_drhos2 = _np.transpose(d2pr_drhos1, (0, 2, 1)) else: drho", "dproduct cache # mem += cache_size * dim * dim # product cache", "in params, so # all hessians for single- or zero-operation sequences are zero.", "dp_drhos = _np.zeros((nCircuits, nDerivCols)) _fas(dp_drhos, [None, rho_gpindices], _np.squeeze(_np.dot(_np.dot(E, Gs), rhoVec.deriv_wrt_params(rho_wrtFilter)), axis=(0,)) * scaleVals[:,", "num_subtrees : int The number of subtrees to split the full evaluation tree", "self.pr( (rholabel,elabel), circuit, clipTo, bScale) for elabel in elabels ]) #assert(_np.linalg.norm(ps-check_ps) < 1e-8)", "*non-final* parent-tree elements from those of the sub-trees. _warnings.warn(\"Increased speed could be obtained\"", "of shape S such that scaleVals[i] contains the multiplicative scaling needed for the", "* _np.transpose(_np.dot(prod, rho)) # may overflow, but OK # (** doesn't depend on", "Parameters ---------- mxToFill : numpy ndarray an already-allocated 1D numpy array of length", "other diff order) # d2pr/d(E)_i d(opLabel)_mn = sum [dprod/d(opLabel)_mn]_il rho_l (and same for", "bScale : bool, optional When True, return a scaling factor (see below). Returns", "l in uniqueOpLabels: used_operations[l] = self.sos.get_operation(l) gate_wrtFilters1[l], gpindices1[l] = self._process_wrtFilter(wrtFilter1, used_operations[l]) gate_wrtFilters2[l], gpindices2[l]", "deriv_shape) # This iteration **must** match that in bulk_evaltree # in order to", "dGs2), drho), axis=(0,)) * scaleVals[:, None, None]) # overflow OK d2pr_drhos2 = _np.transpose(d2pr_drhos2,", "int The memory estimate in bytes. \"\"\" #Note: num_final_strs is irrelevant here b/c", "bReturnDProbs12: dprobs12 = dprobs1[:, :, None] * dprobs2[:, None, :] # (KM,N,1) *", "prod_ij (and same for other diff order) # d2pr/d(E)_i d(E)_j = 0 #", "0, 1) hProdCache[i] = _np.dot(hL, R) + dLdR_sym + _np.transpose(_np.dot(L, hR), (1, 2,", "- %g = %g\" % (_nla.norm(hprMxToFill[fInds]), _nla.norm(check_vhp), _nla.norm(hprMxToFill[fInds] - check_vhp))) # pragma: no", "return PrepEffectFilter(rho_local_slices=loc_rho_slices, # rho_global_slices=global_rho_slices, # e_local_slices=loc_e_slices, # e_global_slices=global_e_slices, # num_rho_params=self.tot_rho_params, # num_e_params=self.tot_e_params) def", "used to construct virtual gates for use in computations. \"\"\" super(MatrixForwardSimulator, self).__init__( dim,", "only a single spam label (specified to it by the first two arguments),", "< DSMALL and dProdCache[i].min() > -DSMALL: _warnings.warn(\"Scaled dProd small in order to keep", "_time.time() prodCache, scaleCache = self._compute_product_cache(evalSubTree, mySubComm) profiler.add_time(\"bulk_fill_dprobs: compute_product_cache\", tm) #use cached data to", "which elements correspond to which strings and outcomes, you'll need the mappings generated", "Gs[gInds], dGs1[gInds], dGs2[gInds], hGs[gInds], scaleVals[gInds], wrtSlice1, wrtSlice2), add=sumInto) _np.seterr(**old_err) #NOTE: don't distribute wrtSlicesList", "is None) else wrtSlice _, myDerivColSlice, _, mySubComm = \\ _mpit.distribute_slice(allDerivColSlice, comm) #print(\"MPI:", "wrtSlicesList, bReturnDProbs12=False, comm=None): \"\"\" Constructs a generator that computes the 2nd derivatives of", "blocks2[iBlk2], calc_and_fill) hProdCache = hGs = dProdCache2 = dGs2 = None # free", "1)) # (dim2, nDerivCols1, nDerivCols2) flattened_d2prod[:, inds1, inds2] += xv if flat: return", "= _np.swapaxes(_np.dot(dL1, dR2), 1, 2) dLdRb = _np.swapaxes(_np.dot(dL2, dR1), 1, 2) dLdR_sym =", "parameterizations of operation matrices and SPAM vectors) access to these fundamental operations. \"\"\"", "=> product, dprod_dOps) # prod, dprod_dOps = G,dG # dp_dOps[i,j] = sum_k,l E[0,k]", "None else _slct.length(wrtSlice1) nDerivCols2 = self.Np if wrtSlice2 is None else _slct.length(wrtSlice2) #flt1", "hProdCache = self._compute_hproduct_cache( evalTree, prodCache, dProdCache1, dProdCache2, scaleCache, comm, wrtSlice1, wrtSlice2) hGs =", "{} gpindices2 = {}; gate_wrtFilters2 = {} for l in uniqueOpLabels: used_operations[l] =", "gates start with norm <= 1, products should all have norm <= 1", "for each block of derivative columns if prMxToFill is not None: self._fill_result_tuple((prMxToFill,), evalSubTree,", "a split tree. \"\"\" if profiler is None: profiler = _dummy_profiler dim =", "d2pr_drhos[i, j, rho_gpindices] = dot(E,dGs[i,j],drho/drhoP)) # d2pr_drhos[i,j,J0+J] = sum_kl E[0,k] dGs[i,j,k,l] drhoP[l,J] #", "which case the actual product == product * scale. The purpose of this", "to save copying) some arrays. The arrays that are filled internally to `calc_and_fill_fn`", "(see below) dGs2[_np.isnan(dGs2)] = 0 # convert nans to zero, as these occur", "shape of the returned derivative array (see below). bReturnProds : bool, optional when", "parallelized over these groups. num_final_strs : int The number of final strings (may", "prMxToFill is not None: check_vp = _np.array([self.prs(spamTuple[0], [spamTuple[1]], circuit, clipTo, False)[0] for circuit", "_mpit.gather_indices(subtreeElementIndices, subTreeOwners, mxToFill, [], 0, comm, gatherMemLimit) #note: pass mxToFill, dim=(KS,M), so gather", "G^2)-th entry of the (i / G^2)-th flattened operation sequence product with respect", "cols = deriv cols, rows = flattened everything else return (dGs, Gs, scaleVals)", "tm) return _np.concatenate(all_results, axis=1) # TODO: remove this concat w/better gather? # ------------------------------------------------------------------", "estimate in bytes. \"\"\" #Note: num_final_strs is irrelevant here b/c cachesize is always", "to the j-th model parameter. * if flat == True, an array of", "# noqa # + sum{M==L} [ G1 ... G(M-1) d2G(M)/(dkl*dij) G(M+1) ... GN", "dProdCache2[iLeft], dProdCache2[iRight] hL, hR = hProdCache[iLeft], hProdCache[iRight] # Note: L, R = GxG", "ps = _np.real(_np.dot(Es, _np.dot(G, rho)) * scale) _np.seterr(**old_err) else: # no scaling --", "derivWrtAnyEvec = scale * _np.transpose(_np.dot(prod, rho)) # may overflow, but OK d2pr_d2Es =", "= _np.swapaxes(_np.swapaxes(dGs1, 0, 1).reshape((nDerivCols1, nCircuits * dim**2)), 0, 1) # cols = deriv", "columns allDeriv1ColSlice = slice(0, nDerivCols1) allDeriv2ColSlice = slice(0, nDerivCols2) deriv1Slices, myDeriv1ColSlice, deriv1Owners, mySubComm", "from .profiler import DummyProfiler as _DummyProfiler from .label import Label as _Label from", "(and same for other diff order) # d2pr/d(E)_i d(E)_j = 0 # d2pr/d(rho)_i", "performed, which is on the far right of the product of matrices. Parameters", "_nla.norm(prMxToFill[fInds] - check_vp) > 1e-6: _warnings.warn(\"norm(vp-check_vp) = %g - %g = %g\" %", "blk_wrtSlice1 == blk_wrtSlice2: dProdCache2 = dProdCache1; dGs2 = dGs1 else: dProdCache2 = self._compute_dproduct_cache(", "- check_vdp) > 1e-6: _warnings.warn(\"norm(vdp-check_vdp) = %g - %g = %g\" % (_nla.norm(dprMxToFill[fInds]),", "rho).squeeze(2) * scaleVals[:, None] # overflow OK d2pr_d2Es = _np.zeros((nCircuits, nDerivCols1, nDerivCols2)) _fas(d2pr_d2Es,", "returned when bScale == True. An array of shape S such that scaleVals[i]", "concatenates rows (which numpy.flatten does) # vec( A * E(0,1) * B )", "numpy array, optional when not None, an already-allocated ExM numpy array that is", "profiler = _dummy_profiler if wrtFilter is not None: assert(wrtBlockSize is None) # Cannot", "self._process_wrtFilter(wrtSlice, self.sos.get_effect(elabel)) nDerivCols = self.Np if wrtSlice is None else _slct.length(wrtSlice) # GATE", "slice(None), slice(None), calc_and_fill) else: # Divide columns into blocks of at most blkSize", "want to computed their probabilites). These are a \"simplified\" circuits in that they", "L / nL, R / nR prodCache[i] = _np.dot(sL, sR); scaleCache[i] += _np.log(nL)", "number of entries in a single flattened gate (ordering as numpy.flatten), - S,M", "rho )[i,j,k,l,0] # d2pr_dOps2[i,j,k] = dot( E, dot( dGs, rho ) )[0,i,j,k,0] #", "= self._rhoE_from_spamTuple(spamTuple) _fas(prMxToFill, [fInds], self._probs_from_rhoE(rho, E, Gs[gInds], scaleVals[gInds]), add=sumInto) _np.seterr(**old_err) profiler.add_time(\"bulk_fill_dprobs: calc_and_fill_p\", tm)", "scaleVals = self._scaleExp(evalTree.final_view(scaleCache)) Gs = evalTree.final_view(prodCache, axis=0) #( nCircuits, dim, dim ) #Same", "not in (\"statevec\", \"densitymx\"): raise ValueError((\"Evolution type %s is incompatbile with \" \"matrix-based", "+= cache_size * dim * dim # product cache # mem += cache_size", "sequences which need to be computed # for the current spamTuple (this list", "include instrument elements like 'Imyinst_0') clipTo : 2-tuple (min,max) to clip returned probability", "#cnt = 0 for i in evalTree.get_evaluation_order(): # combine iLeft + iRight =>", "derivative rows and columns and then (as needed) a split tree to parallelize", "block size. This argument must be None if wrtFilter is not None. Set", "appropriate for this calculator. Parameters ---------- simplified_circuits : list A list of Circuits", "be dim x dim, and all SPAM vectors should be dim x 1.", "in enumerate(revOpLabelList): # loop over \"starting\" gate prods[(i, i - 1)] = ident", "int The number of processor groups that will be assigned to subtrees of", "rho_gpindices1, rho_gpindices2], _np.tensordot(dp_dAnyRho, self.sos.get_prep(rholabel).hessian_wrt_params( rho_wrtFilter1, rho_wrtFilter2), (1, 0))) # _np.einsum('ij,jkl->ikl', dp_dAnyRho, self.sos.get_prep(rholabel).hessian_wrt_params( #", "Note also that there would be no memory savings from using a split", "not needed now that we track owners #if mySubSubComm.Get_rank() > 0: myDeriv2ColSlice =", "p = _np.clip(p, clipTo[0], clipTo[1]) dprod_dOps = self.dproduct(circuit) assert(dprod_dOps.shape[0] == self.Np) if returnDeriv:", "evalTree[i] L, R = prodCache[iLeft], prodCache[iRight] dL, dR = dProdCache[iLeft], dProdCache[iRight] dProdCache[i] =", "return dpr_drhos + dpr_dEs + dpr_dOps, p else: return dpr_drhos + dpr_dEs +", "%d)\" % len(circuit) _warnings.warn(\"pr(%s) == nan\" % strToPrint) #DEBUG: print \"backtrace\" of product", "is evaluated. Returns ------- numpy.ndarray An array of floating-point probabilities, corresponding to the", "be obtained\" \" by giving hproduct cache computation\" \" *fewer* processors and *smaller*", "shape == (len(circuit_list), nDerivCols, nDerivCols) # may also give invalid value due to", "# gate's parameters and fill appropriate columns of flattened_dprod. _fas(flattened_hprod, [None, gpindices1, gpindices2],", "#Create per-gate with-respect-to parameter filters, used to # select a subset of all", "> -DSMALL: _warnings.warn(\"Scaled dProd small in order to keep prod managable.\") elif _np.count_nonzero(dProdCache[i])", "d2pr_dErhos[i, e_offset[eIndex]:e_offset[eIndex+1], e_offset[rhoIndex]:e_offset[rhoIndex+1]] = # dEP^T * prod[i,:,:] * drhoP # d2pr_dErhos[i,J0+J,K0+K] =", "need the mappings generated when the original list of `Circuits` was simplified. Parameters", "Whether to use a post-scaled product internally. If False, this routine will run", "of prep and effect parameters onto a final \"filtered\" set. # \"\"\" #", "scaleVals[gInds], wrtSlice1, wrtSlice2), add=sumInto) _np.seterr(**old_err) #NOTE: don't distribute wrtSlicesList across comm procs, #", "def _probs_from_rhoE(self, rho, E, Gs, scaleVals): if self.evotype == \"statevec\": raise NotImplementedError(\"Unitary evolution", "mxToFill, dim=(KS), so gather mxToFill[felslc] (axis=0) if clipTo is not None: _np.clip(mxToFill, clipTo[0],", "on eIndex **) -- TODO: should also conjugate() here if complex? _fas(dpr_dEs, [0,", "(not distributed) prodCache, scaleCache = self._compute_product_cache(evalTree, comm) scaleVals = self._scaleExp(evalTree.final_view(scaleCache)) Gs = evalTree.final_view(prodCache,", "for i in range(len(self.effects))] # tmp_num_params = [_slct.length(s) for s in loc_e_slices] #", "(Deriv1) #note: gathering axis 1 of hProdCache, # dim=(cacheSize,nDerivCols1,nDerivCols2,dim,dim) return hProdCache # ------------------------------------------------------------------", "the evaluation tree that will be passed to the functions named by `subcalls`.", "shape == (len(circuit_list), nDerivCols) # may also give invalid value due to scaleVals", "= dProdCache2.shape[1] assert(wrtSlice1 is None or _slct.length(wrtSlice1) == nDerivCols1) assert(wrtSlice2 is None or", "# hGs[i] is hprod_dGates for ith string if not bScale: old_err = _np.seterr(over='ignore',", "clipTo) for circuit in circuit_list], axis=0) if _nla.norm(hprMxToFill[fInds][0] - check_vhp[0]) > 1e-6: _warnings.warn(\"norm(vhp-check_vhp)", "an evaluation tree, `evalTree`. An initial list of (general) :class:`Circuit` objects is *simplified*", "is the probability generated by the sequence and spam label indexed by iOpStr", "http://www.apache.org/licenses/LICENSE-2.0 or in the LICENSE file in the root pyGSTi directory. #*************************************************************************************************** import", "final # filled quantity combining both spam and gate-sequence indices # gInds =", "self.sos.get_effect(elabel).gpindices, self.sos.get_effect(elabel).gpindices], _np.tensordot(derivWrtAnyEvec, self.sos.get_effect(elabel).hessian_wrt_params(), (1, 0))) # _np.einsum('ij,jkl->ikl',derivWrtAnyEvec,self.sos.get_effect(elabel).hessian_wrt_params()) else: d2pr_d2Es = 0 ret", "def _process_wrtFilter(self, wrtFilter, obj): \"\"\" Helper function for doperation and hoperation below: pulls", "rightProdsT.append(_np.transpose(G)) for opLabel in reversed(revOpLabelList): G = _np.dot(self.sos.get_operation(opLabel).todense(), G) rightProdsT.append(_np.transpose(G)) # Allocate memory", "comm to distribute columns allDeriv1ColSlice = slice(0, nDerivCols1) allDeriv2ColSlice = slice(0, nDerivCols2) deriv1Slices,", "blocks2[iBlk2] if blk_wrtSlice1 == blk_wrtSlice2: dProdCache2 = dProdCache1; dGs2 = dGs1 else: dProdCache2", "each of the product components (i.e. prod_kl) with # respect to a given", "1 of mxToFill[felInds], dim=(ks,M,M) _mpit.gather_slices(blocks1, blk1Owners, mxToFill, [felInds], 1, mySubComm, gatherMemLimit) if deriv1MxToFill", "= swapaxes(dot(dEPT,prod,drhoP),0,1)[i,J,K] # d2pr_dErhos[:,J0+J,K0+K] = swapaxes(dot(dEPT,prod,drhoP),0,1)[:,J,K] d2pr_dErhos1 = _np.zeros((nCircuits, nDerivCols1, nDerivCols2)) drho =", "m, opLabel1 in enumerate(revOpLabelList): inds1 = gpindices1[opLabel1] nDerivCols1 = dop_dopLabel1[opLabel1].shape[1] if nDerivCols1 ==", "pslc1 _fas(mxToFill, [fInds, pslc1], self._dprobs_from_rhoE( spamTuple, rho, E, Gs[gInds], dGs[gInds], scaleVals[gInds], block_wrtSlice), add=sumInto)", "dProdCache1 = self._compute_dproduct_cache( evalSubTree, prodCache, scaleCache, blk1Comm, blk_wrtSlice1) dGs1 = evalSubTree.final_view(dProdCache1, axis=0) for", "a higher level. \"\"\" dim = self.dim #Note: previously, we tried to allow", "trace operation will yield nan as the returned probability. time : float, optional", "gate = self.sos.get_operation(opLabel) op_wrtFilter1, gpindices1 = self._process_wrtFilter(wrtFilter1, gate) op_wrtFilter2, gpindices2 = self._process_wrtFilter(wrtFilter2, gate)", "clipTo is not None and prMxToFill is not None: _np.clip(prMxToFill, clipTo[0], clipTo[1], out=prMxToFill)", "a prior call to bulk_evaltree. Specifies the operation sequences to compute the bulk", "\"\"\" Compute the product of a specified sequence of operation labels. Note: LinearOperator", "returnPr, returnDeriv, clipTo): \"\"\" Compute the Hessian of a probability generated by a", "old_err = _np.seterr(over='ignore') prod, scale = self.product(circuit, True) dprod_dOps = self.dproduct(circuit) dpr_dOps =", "in general only a specified slice of the values for this spam label", "specifying the scaling that needs to be applied to the resulting products (final_product[i]", "= _slct.list_to_slice(wrtFilter1) else: wrtSlice1 = None if wrtFilter2 is not None: assert(wrtBlockSize1 is", "wrtFilter2=None): \"\"\" Compute the hessian of a specified sequence of operation labels. Parameters", "each model parameter. probability : float only returned if returnPr == True. \"\"\"", "_np.transpose(_np.dot(prod, rho)) # may overflow, but OK d2pr_d2Es = _np.zeros((1, self.Np, self.Np)) _fas(d2pr_d2Es,", "if bReturnDProbs12: dprobs1 = _np.zeros((nElements, _slct.length(wrtSlice1)), 'd') dprobs2 = _np.zeros((nElements, _slct.length(wrtSlice2)), 'd') else:", "only when needed) a split tree to parallelize computation, since there are no", "oplabel} [ (G1 ... G(L-1)) tensor (G(L+1) ... GN)^T ]] has # columns", "a better way dim = self.dim nspam = int(round(_np.sqrt(self.dim))) # an estimate -", "blkSize1 = blkSize2 = None # wrtFilter1 & wrtFilter2 dictates block if blkSize1", "from using a split tree. \"\"\" dim = self.dim # Note: dProdCache?.shape =", "1 of hProdCache, # dim=(cacheSize,nDerivCols1,nDerivCols2,dim,dim) return hProdCache # ------------------------------------------------------------------ if evalTree.is_split(): _warnings.warn(\"Ignoring tree", "the original list of `Circuits` was simplified. Parameters ---------- mxToFill : numpy ndarray", "not None: obj_wrtFilter = [] # values = object-local param indices relevant_gpindices =", "at once self._fill_result_tuple((prMxToFill, mxToFill), evalSubTree, slice(None), slice(None), calc_and_fill) profiler.mem_check(\"bulk_fill_dprobs: post fill\") dProdCache =", "self._compute_hproduct_cache( evalTree, prodCache, dProdCache1, dProdCache2, scaleCache, comm, wrtSlice1, wrtSlice2) hGs = evalTree.final_view(hProdCache, axis=0)", "sequence. \"\"\" dim = self.dim nDerivCols1 = self.Np if (wrtFilter1 is None) else", "None as comm, *not* mySubSubComm, since we can't do any further parallelization _mpit.gather_slices(deriv2Slices,", "products of many operation sequences at once. Parameters ---------- evalTree : EvalTree given", "2) dLdR_sym = dLdRa + _np.swapaxes(dLdRb, 0, 1) hProdCache[i] = _np.dot(hL, R) +", "a linear cache space. Will *not* parallelize computation, even if given a split", "= 0 # SPAM DERIVS (assume dGs1 and dGs2 are already sized/filtered) --------", "devec = EVec.deriv_wrt_params(E_wrtFilter1) _fas(d2pr_dErhos1, (None, E_gpindices1, rho_gpindices2), _np.swapaxes(_np.dot(_np.transpose(devec), dp_dAnyE), 0, 1)) # get", "slice that results in a zero dimension else: obj_wrtFilter = None relevant_gpindices =", "* wrtLen2 # hprobs & dprobs12 results mem += cache_size * nspam *", "are at most linear in params, so # all hessians for single- or", "[None, None, E_gpindices1], _np.dot(dp_dAnyE, devec)) d2pr_dEs2 = _np.transpose(d2pr_dEs2, (0, 2, 1)) # Get:", "organizes how to efficiently compute the gate-only sequences. This routine fills in `mxToFill`,", "parallelization of # _compute_product_cache when the tree was split, but this is was", "across multiple processors. Returns ------- hessian : numpy array * if flat ==", "below is valid. # Below we use E(i,j) to denote the elementary matrix", "[fInds], self._probs_from_rhoE(rho, E, Gs[gInds], scaleVals[gInds]), add=sumInto) _np.seterr(**old_err) self._fill_result_tuple((mxToFill,), evalSubTree, slice(None), slice(None), calc_and_fill) #collect/gather", "tm = _time.time() old_err = _np.seterr(over='ignore') rho, E = self._rhoE_from_spamTuple(spamTuple) _fas(prMxToFill, [fInds], self._probs_from_rhoE(rho,", "numpy ndarray an already-allocated ExMxM numpy array where E is the total number", "in used_operations.items()} #Finally, cache any nonzero gate hessians (memory?) hop_dopLabels = {} for", "combining both spam and gate-sequence indices # gInds = \"gate sequence indices\" =", "columns (the length of colSlice) If `mx`, `dp1`, and `dp2` are the outputs", "to make use of in \" \" _compute_dproduct_cache.\") if mySubComm.Get_rank() > 0: myDerivColSlice", "num_deriv_cols = self.Np if (wrtFilter is None) else len(wrtFilter) flattened_dprod = _np.zeros((dim**2, num_deriv_cols),", "nDerivCols, nDerivCols) # may also give invalid value due to scaleVals being inf", "filters, used to # select a subset of all the derivative columns, essentially", "* E(0,1) * B ) = vec( mx w/ row_i = A[i,0] *", "swapaxes(dot(dEPT,prod,drhoP),0,1)[i,J,K] # d2pr_dErhos[:,J0+J,K0+K] = swapaxes(dot(dEPT,prod,drhoP),0,1)[:,J,K] d2pr_dErhos1 = _np.zeros((nCircuits, nDerivCols1, nDerivCols2)) drho = rhoVec.deriv_wrt_params(rho_wrtFilter2)", "of the (k,l)-th entry of the i-th operation sequence product with respect to", "(easier to think about) revOpLabelList = tuple(reversed(tuple(circuit))) N = len(revOpLabelList) # length of", "with older slower version that should do the same thing (for debugging) master_circuit_list", "of the product (els of # prod.flatten()). # # Note: if gate G(L)", "if comm is not None and comm.Get_size() > 1: #print(\"MPI: _compute_dproduct_cache called w/comm", "dProdCache2, scaleCache, None, myHessianSlice1, wrtSlice2) # pass None as comm, *not* mySubComm (this", "product with respect to the k-th then j-th model parameters. derivs1, derivs2 :", "(dim2, nDerivCols1, nDerivCols2) flattened_d2prod[:, inds1, inds2] += xv if flat: return flattened_d2prod #", "evalTree, clipTo=None, check=False, comm=None): \"\"\" Compute the outcome probabilities for an entire tree", "#Free memory from previous subtree iteration before computing caches scaleVals = Gs =", "# scale vals elif fnName == \"bulk_fill_dprobs\": mem += cache_size * wrtLen1 *", "if profiler is None: profiler = _dummy_profiler if wrtFilter is not None: assert(wrtBlockSize", "flattened gate (ordering as numpy.flatten), - S,M == as above, and hessians[i,j,k] holds", "wrtSlice2) else \\ self._compute_dproduct_cache(evalTree, prodCache, scaleCache, comm, wrtSlice2) hProdCache = self._compute_hproduct_cache(evalTree, prodCache, dProdCache1,", "distribution hProdCache[:, myDeriv1ColSlice] = self._compute_hproduct_cache( evalTree, prodCache, dProdCache1[:, myDeriv1ColSlice], dProdCache2, scaleCache, None, myHessianSlice1,", "dp_dAnyE = _np.squeeze(_np.dot(Gs, rho), axis=(2,)) * scaleVals[:, None] _fas(dp_dEs, [None, E_gpindices], _np.dot(dp_dAnyE, EVec.deriv_wrt_params(E_wrtFilter)))", "_np.dot(G, rho))) ps = ps.flatten() if _np.any(_np.isnan(ps)): if len(circuit) < 10: strToPrint =", "sum{M==L} [ G1 ... G(M-1) d2G(M)/(dkl*dij) G(M+1) ... GN ] # noqa #", "when computing the Hessian of functions of the probabilities. comm : mpi4py.MPI.Comm, optional", "Helper function for doperation and hoperation below: pulls out pieces of a wrtFilter", "True) if self.evotype == \"statevec\": ps = _np.real(_np.abs(_np.dot(Es, _np.dot(G, rho)) * scale)**2) else:", "obj_wrtFilter = None relevant_gpindices = obj.gpindices return obj_wrtFilter, relevant_gpindices #Vectorizing Identities. (Vectorization) #", "raise NotImplementedError(\"Unitary evolution not fully supported yet!\") # To support unitary evolution we", "(rho_label, simplified_effect_label) Specifies the prep and POVM effect used to compute the probability.", "myDeriv2ColSlice if mySubSubComm is not None and mySubSubComm.Get_size() > 1: _warnings.warn(\"Too many processors", "- (scaleCache[iLeft] + scaleCache[iRight]) if abs(scale) > 1e-8: # _np.isclose(scale,0) is SLOW! dProdCache[i]", ") = sum_{L s.t. G(L) == oplabel} [ (G1 ... G(L-1)) tensor (G(L+1)", "entry of the i-th operation sequence product with respect to the k-th then", "else: d2pr_d2rhos = 0 if self.sos.get_effect(elabel).has_nonzero_hessian(): derivWrtAnyEvec = scale * _np.transpose(_np.dot(prod, rho)) #", "subTreeOwners, mxToFill, [], 0, comm, gatherMemLimit) #note: pass mxToFill, dim=(KS,M), so gather mxToFill[felInds]", "derivatives and/or products for the i-th operation sequence. \"\"\" nCircuits = evalTree.num_final_strings() nDerivCols", "multiplication in this order (easier to think about) revOpLabelList = tuple(reversed(tuple(circuit))) N =", "is None) else len(wrtFilter) flattened_dprod = _np.zeros((dim**2, num_deriv_cols), 'd') _fas(flattened_dprod, [None, gpindices], gate.deriv_wrt_params(op_wrtFilter))", "Gs = dGs = None prodCache = scaleCache = dProdCache = None #Fill", "noqa # = vec(i,j)-col of [ sum_{L s.t. G(L) == oplabel} [ (G1", "None as comm, *not* mySubComm (this is ok, see \"if\" condition above) _mpit.gather_slices(deriv1Slices,", "each operation matrix element # is at most *linear* in each of the", "return ret def _check(self, evalTree, prMxToFill=None, dprMxToFill=None, hprMxToFill=None, clipTo=None): # compare with older", "Compute probabilities of a multiple \"outcomes\" (spam-tuples) for a single operation sequence. The", "this is was # incorrect (and luckily never used) - so it's been", "-> wrtSlice? prodCache, scaleCache = self._compute_product_cache(evalTree, comm) dProdCache = self._compute_dproduct_cache(evalTree, prodCache, scaleCache, comm,", "self.Np / mySubComm.Get_size() blkSize = comm_blkSize if (blkSize is None) \\ else min(comm_blkSize,", "is not None) and (mySubComm.Get_size() > 1): comm_blkSize = self.Np / mySubComm.Get_size() blkSize", "), # dGs[i] is dprod_dOps for ith string hGs = evalTree.final_view(hProdCache, axis=0) #shape", "to keep all the products within decent # bounds #assert( len( (_np.isnan(hGs)).nonzero()[0] )", "d|pr|^2/dx = d(pr*pr.C)/dx = dpr/dx*pr.C + pr*dpr/dx.C # = 2 Re(dpr/dx*pr.C) , where", "scaleVals[i] # vp[i] = sum_k E[0,k] dot(Gs, rho)[i,k,0] * scaleVals[i] # vp[i] =", "integers specifying which parameters to include in the derivative dimension. This argument is", "than deriv cols, give a # warning -- note that we *cannot* make", "than hessian elements.\") # pragma: no cover # allocate final result memory hProdCache", "== self.Np) if returnDeriv: # same as in dpr(...) dpr_dOps = _np.empty((1, self.Np))", "the zero and single-gate-strings) #cnt = 0 for i in evalTree.get_evaluation_order(): # combine", "associate the right single-gate-strings w/indices wrtIndices = _slct.indices(wrtSlice) if (wrtSlice is not None)", "(ordering is the same as that used by numpy.flatten), - S,M == as", "[ self.pr( (rholabel,elabel), circuit, clipTo, bScale) for elabel in elabels ]) #assert(_np.linalg.norm(ps-check_ps) <", "of the probability w.r.t. each model parameter. probability : float only returned if", "+ _np.swapaxes(dLdRb, 0, 1) hProdCache[i] = _np.dot(hL, R) + dLdR_sym + _np.transpose(_np.dot(L, hR),", ": int The number of final strings (may be less than or greater", "= float(_np.dot(E, _np.dot(dprod_dOps[i], rho))) #Derivs wrt SPAM if returnDeriv: # same as in", "M < L} # noqa # [ G1 ... G(M-1) dG(M)/dkl G(M+1) ...", "# e_local_slices=loc_e_slices, # e_global_slices=global_e_slices, # num_rho_params=_slct.length(wrtSlices['preps']), # num_e_params=_slct.length(wrtSlices['effects'])) # else: # loc_rho_slices =", "0: # import objgraph # objgraph.show_growth(limit=50) #get distribution across subtrees (groups if needed)", "= master_circuit_list[gInds] if prMxToFill is not None: check_vp = _np.array([self.prs(spamTuple[0], [spamTuple[1]], circuit, clipTo,", "dpr_dOps[0, i] = float(_np.dot(E, _np.dot(dprod_dOps[i], rho))) if returnPr: p = _np.dot(E, _np.dot(prod, rho))", "+ dp_dOps return sub_vdp #def _get_filter_info(self, wrtSlices): # \"\"\" # Returns a \"filter\"", "gate in used_operations.items()} #Finally, cache any nonzero gate hessians (memory?) hop_dopLabels = {}", "element\" of `evalTree`. Parameters ---------- mxToFill : numpy ndarray an already-allocated ExM numpy", "self._compute_dproduct_cache( evalSubTree, prodCache, scaleCache, mySubComm, wrtSlice1) dProdCache2 = dProdCache1 if (wrtSlice1 == wrtSlice2)", "to compute the bulk operation on. prMxToFill : numpy array, optional when not", "int The gate-dimension. All operation matrices should be dim x dim, and all", "dGs2 = None # free mem if bReturnDProbs12: dprobs12 = dprobs1[:, :, None]", "# (** doesn't depend on eIndex **) -- TODO: should also conjugate() here", "blocks myBlkIndices, blkOwners, blkComm = \\ _mpit.distribute_indices(list(range(nBlks)), mySubComm) if blkComm is not None:", "[ # _slct.shift(_slct.intersect( # wrtSlices['preps'], # slice(self.rho_offset[i],self.rho_offset[i+1])), # -self.rho_offset[i]) for i in range(len(self.preps))]", "derivative array (see below). wrtFilter1, wrtFilter2 : list of ints, optional If not", "= _np.zeros(hessn_shape) elif not self.sos.get_operation(opLabel).has_nonzero_hessian(): #all gate elements are at most linear in", "evaluation tree organizes how to efficiently compute the gate-only sequences. This routine fills", "= vgs x GxG ; hL,hR = vgs x vgs x GxG dLdRa", "(specified to it by the first two arguments), and in general only a", "d2pr_d2rhos = _np.zeros((1, self.Np, self.Np)) _fas(d2pr_d2rhos, [0, self.sos.get_prep(rholabel).gpindices, self.sos.get_prep(rholabel).gpindices], _np.tensordot(derivWrtAnyRhovec, self.sos.get_prep(rholabel).hessian_wrt_params(), (1, 0)))", "possible. wrtFilter1, wrtFilter2 : list of ints, optional If not None, a list", "dim, dim ), # dGs[i] is dprod_dOps for ith string if not bScale:", "dim ), # Gs[i] is product for i-th operation sequence dGs = evalTree.final_view(dProdCache,", "of computed elements (i.e. evalTree.num_final_elements()) and M is the number of model parameters.", "bScale else (dGs, Gs) else: dGs = evalTree.final_view(dProdCache, axis=0) #shape == ( len(circuit_list),", "no cover # allocate final result memory hProdCache = _np.zeros((cacheSize,) + hessn_shape) #", "to keep prod managable.\") elif _np.count_nonzero(dProdCache[i]) and dProdCache[i].max() < DSMALL and dProdCache[i].min() >", "last_wrtSlice1 = None # keep last dProdCache1 for wrtSlice1, wrtSlice2 in wrtSlicesList: if", "duplicates (a list, not a set) # since all scaled gates start with", "integer row indices into mxToFill, specifying the correspondence between rows of mxToFill and", "simplified_circuits, numSubtreeComms): \"\"\" Constructs an EvalTree object appropriate for this calculator. Parameters ----------", "scaleVals): if self.evotype == \"statevec\": raise NotImplementedError(\"Unitary evolution not fully supported yet!\") #Compute", "E has shape (1,N) else: # a \"custom\" spamLabel consisting of a pair", "in used_operations.items(): if gate.has_nonzero_hessian(): hop_dopLabels[opLabel] = gate.hessian_wrt_params( gate_wrtFilters1[opLabel], gate_wrtFilters2[opLabel]) # Allocate memory for", "subcalls: if fnName == \"bulk_fill_probs\": mem += cache_size * dim * dim #", "of gate-only sequences along with a mapping of final elements (i.e. probabilities) to", "strings and outcomes, you'll need the mappings generated when the original list of", "= sum_{L s.t. G(L) == oplabel} [ G1 ... G(L-1) dG(L)/dij G(L+1) ...", "object-local param indices relevant_gpindices = [] # indices into original wrtFilter'd indices gpindices", "optional when not None, an already-allocated ExM numpy array that is filled with", "Encapsulates a calculation tool used by model objects to perform product and derivatives-of-product", "mxToFill), evalSubTree, slice(None), slice(None), calc_and_fill) profiler.mem_check(\"bulk_fill_dprobs: post fill\") dProdCache = dGs = None", "giving the *simplified* effect labels. circuit : Circuit or tuple A tuple-like object", "= self._compute_product_cache(evalTree, comm) scaleVals = self._scaleExp(evalTree.final_view(scaleCache)) Gs = evalTree.final_view(prodCache, axis=0) #( nCircuits, dim,", "spamLabel consisting of a pair of SPAMVec (or array) # objects: (prepVec, effectVec)", "overflow, but ok # may overflow or get nans (invalid), but ok dGs", "= flattened everything else return (dGs, scaleVals) if bScale else dGs def bulk_hproduct(self,", "gInds) in evalTree.spamtuple_indices.items(): # fInds = \"final indices\" = the \"element\" indices in", "l < m: x0 = _np.kron(_np.transpose(prods[(l + 1, m - 1)]), prods[(m +", "clipTo is not None: _np.clip(mxToFill, clipTo[0], clipTo[1], out=mxToFill) # in-place clip if check:", "cache_size # scale cache mem += cache_size # scale vals elif fnName ==", "wrtSlice, profiler) dGs = evalSubTree.final_view(dProdCache, axis=0) #( nCircuits, nDerivCols, dim, dim ) profiler.add_time(\"bulk_fill_dprobs:", "rho )[i,j,k,0] # dp_dOps[i,j] = dot( E, dot( dGs, rho ) )[0,i,j,0] #", "of mxToFill[felInds], dim=(ks,M,M) _mpit.gather_slices(blocks1, blk1Owners, mxToFill, [felInds], 1, mySubComm, gatherMemLimit) if deriv1MxToFill is", "if wrtSlice is None else _slct.length(wrtSlice) # GATE DERIVS (assume dGs is already", "if flat == False, a M x G x G array, where: -", "value if not None. check : boolean, optional If True, perform extra checks", "is the i-th operation sequence product. scaleVals : numpy array Only returned when", "# in-place clip if check: self._check(evalTree, prMxToFill, deriv1MxToFill, mxToFill, clipTo) def bulk_hprobs_by_block(self, evalTree,", "since numpy does all the major allocation/deallocation). #if comm is None or comm.Get_rank()", "= _np.real(_np.dot(Es, _np.dot(G, rho)) * scale) _np.seterr(**old_err) else: # no scaling -- faster", "is not None: check_vp = _np.array([self.prs(spamTuple[0], [spamTuple[1]], circuit, clipTo, False)[0] for circuit in", "dpr = dpr_drhos + dpr_dEs + dpr_dOps d2pr_drhos = _np.zeros((1, self.Np, self.Np)) _fas(d2pr_drhos,", "or add to the existing array values, which is a functionality needed to", "sum{ L == M} [ G1 ... G(M-1) tensor (G(M+1) ... GN)^T vec(", "deriv_shape = (nDerivCols, dim, dim) cacheSize = len(evalTree) # ------------------------------------------------------------------ #print(\"MPI: _compute_dproduct_cache begin:", "+= cache_size # scale cache (exps) mem += cache_size # scale vals elif", "Only returned when bScale == True. An array of shape S such that", "#compute \"Deriv1\" row-derivatives distribution only; don't use column distribution hProdCache[:, myDeriv1ColSlice] = self._compute_hproduct_cache(", "self.sos.get_prep(rholabel).has_nonzero_hessian(): dp_dAnyRho = _np.dot(E, Gs).squeeze(0) * scaleVals[:, None] # overflow OK d2pr_d2rhos =", "an array of shape S*N x M where - N == the number", "dp_drhos[:,J0+J] = squeeze(dot(E, Gs, drhoP),axis=(0,))[:,J] dp_drhos = _np.zeros((nCircuits, nDerivCols)) _fas(dp_drhos, [None, rho_gpindices], _np.squeeze(_np.dot(_np.dot(E,", "a warning # ------------------------------------------------------------------ if evalTree.is_split(): _warnings.warn(\"Ignoring tree splitting in product cache calc.\")", "remainder spam label. \"\"\" pslc1 = param_slice1 pslc2 = param_slice2 for spamTuple, (fInds,", "uses numpy.flatten rows are kept contiguous, so the first identity below is valid.", "when set to True, additionally return the probabilities and their derivatives (see below).", "can be useful when memory constraints make constructing the entire Hessian at once", "prod managable.\") elif _np.count_nonzero(hProdCache[i]) and hProdCache[i].max() < HSMALL and hProdCache[i].min() > -HSMALL: _warnings.warn(\"hProd", "_mpit.gather_slices(deriv2Slices, deriv2Owners, hProdCache, [None, myDeriv1ColSlice], 2, mySubComm) # , gatherMemLimit) #gather over col-distribution", "wrtSlice1=None, wrtSlice2=None): \"\"\" Computes a tree of product 2nd derivatives in a linear", "The minimum of wrtBlockSize and the size that makes maximal use of available", "hessians (memory?) hop_dopLabels = {} for opLabel, gate in used_operations.items(): if gate.has_nonzero_hessian(): hop_dopLabels[opLabel]", "vec_kl_size, vec_ij_size = flattened_d2prod.shape[1:3] # == num_deriv_cols1, num_deriv_cols2 return _np.rollaxis(flattened_d2prod, 0, 3).reshape((vec_kl_size, vec_ij_size,", "None relevant_gpindices = obj.gpindices return obj_wrtFilter, relevant_gpindices #Vectorizing Identities. (Vectorization) # Note when", "_MatrixEvalTree from .forwardsim import ForwardSimulator _dummy_profiler = _DummyProfiler() # Smallness tolerances, used internally", "= _np.squeeze(_np.dot(dprod_dOps, rho), axis=(2,)) _fas(d2pr_dEs, [0, None, EVec.gpindices], _np.dot(derivWrtAnyEvec, EVec.deriv_wrt_params())) d2pr_dErhos = _np.zeros((1,", "\" _compute_hproduct_cache.\") #TODO: remove: not needed now that we track owners #if mySubSubComm.Get_rank()", "to estimate memory usage for. cache_size : int The size of the evaluation", "within decent bounds #assert( len( (_np.isnan(dGs)).nonzero()[0] ) == 0 ) #assert( len( (_np.isinf(dGs)).nonzero()[0]", "---------- spamTuple : (rho_label, simplified_effect_label) Specifies the prep and POVM effect used to", "sequence products at once. Parameters ---------- evalTree : EvalTree given by a prior", "the i-th operation sequence. \"\"\" dim = self.dim nDerivCols1 = self.Np if (wrtFilter1", "(number of model parameters) and deriv[i,j] holds the derivative of the i-th entry", "(just as prMxToFill is computed fully on each inner loop *iteration*!) #collect/gather results", "evalSubTree.final_view(dProdCache2, axis=0) hProdCache = self._compute_hproduct_cache( evalSubTree, prodCache, dProdCache1, dProdCache2, scaleCache, blk2Comm, blk_wrtSlice1, blk_wrtSlice2)", "return int(1.3 * nCircuits) def construct_evaltree(self, simplified_circuits, numSubtreeComms): \"\"\" Constructs an EvalTree object", "evalTree.num_final_strings() nDerivCols = self.Np if (wrtFilter is None) else _slct.length(wrtFilter) dim = self.dim", "dproduct\") #Compute all requested derivative columns at once self._fill_result_tuple((prMxToFill, mxToFill), evalSubTree, slice(None), slice(None),", "_np.seterr(over='ignore') G, scale = self.product(circuit, True) if self.evotype == \"statevec\": ps = _np.real(_np.abs(_np.dot(Es,", "gatherMemLimit) if deriv2MxToFill is not None: _mpit.gather_indices(subtreeElementIndices, subTreeOwners, deriv2MxToFill, [], 0, comm, gatherMemLimit)", "devec = EVec.deriv_wrt_params(E_wrtFilter2) _fas(d2pr_dErhos2, [None, E_gpindices2, rho_gpindices1], _np.swapaxes(_np.dot(_np.transpose(devec), dp_dAnyE), 0, 1)) d2pr_dErhos2 =", "- 1)]) # (dim**2, dim**2) x = _np.dot(_np.transpose(dop_dopLabel1[opLabel1]), x0); xv = x.view() #", "assert(len(spamTuple) == 2) if isinstance(spamTuple[0], _Label): rholabel, elabel = spamTuple # This calculator", "nCircuits = Gs.shape[0] rho_wrtFilter, rho_gpindices = self._process_wrtFilter(wrtSlice, self.sos.get_prep(rholabel)) E_wrtFilter, E_gpindices = self._process_wrtFilter(wrtSlice, self.sos.get_effect(elabel))", "= H old_err = _np.seterr(over='ignore') scale = _np.exp(scale_exp) _np.seterr(**old_err) return G, scale else:", "None if wrtFilter2 is not None: assert(wrtBlockSize1 is None and wrtBlockSize2 is None)", "dim, dim ) profiler.add_time(\"bulk_fill_dprobs: compute_dproduct_cache\", tm) profiler.mem_check(\"bulk_fill_dprobs: post compute dproduct\") #Compute all requested", "return the probability itself. returnDeriv : bool when set to True, additionally return", "computing %s)\" \\ # % (nDerivCols, str(allDerivColIndices), comm.Get_rank(), str(myDerivColIndices))) if mySubComm is not", "splitting in product cache calc.\") cacheSize = len(evalTree) prodCache = _np.zeros((cacheSize, dim, dim))", "need to be computed # for the current spamTuple (this list has the", "True. An array of shape S x G x G; products[i] is the", "4)) * scaleVals[:, None, None] _np.seterr(**old_err2) # may overflow, but OK ; shape", "dprobs2 = None hprobs = _np.zeros((nElements, _slct.length(wrtSlice1), _slct.length(wrtSlice2)), 'd') #prMxToFill = None deriv1MxToFill", "of shape S*N x M where: - N == the number of entries", "the order given by `wrtSlicesList`. `rowSlice` and `colSlice` must by Python `slice` objects.", "The *start* time at which `circuit` is evaluated. Returns ------- numpy.ndarray An array", "respect to the k-th then j-th model parameters. * if flat == True,", "# allocate final result memory hProdCache = _np.zeros((cacheSize,) + hessn_shape) # Use comm", "being differentiated with respect to. If there are more processors than model parameters,", "1: deriv2Slices, myDeriv2ColSlice, deriv2Owners, mySubSubComm = \\ _mpit.distribute_slice(allDeriv2ColSlice, mySubComm) # Get slice into", "+= cache_size # scale cache # mem += cache_size # scale vals else:", "num_rho_params=self.tot_rho_params, # num_e_params=self.tot_e_params) def _hprobs_from_rhoE(self, spamTuple, rho, E, Gs, dGs1, dGs2, hGs, scaleVals,", "is None) else len(wrtFilter2) flattened_d2prod = _np.zeros((dim**2, num_deriv_cols1, num_deriv_cols2), 'd') # For each", "with respect to only those two gates' parameters and fill # add the", "a fairly common occurrence, and doesn't merit a warning # ------------------------------------------------------------------ if evalTree.is_split():", "post gather blocks\") #collect/gather results tm = _time.time() subtreeElementIndices = [t.final_element_indices(evalTree) for t", "self._check(evalTree, prMxToFill, deriv1MxToFill, mxToFill, clipTo) def bulk_hprobs_by_block(self, evalTree, wrtSlicesList, bReturnDProbs12=False, comm=None): \"\"\" Constructs", "Parameters ---------- simplified_circuits : list A list of Circuits or tuples of operation", "# # So for each opLabel the matrix [ sum_{L s.t. GL ==", "columns.\") # Use comm to distribute columns allDerivColSlice = slice(0, nDerivCols) if (wrtSlice", "Returns ------- None \"\"\" tStart = _time.time() if profiler is None: profiler =", "time at which `circuit` is evaluated. Returns ------- numpy.ndarray An array of floating-point", "sequence dGs1 = evalTree.final_view(dProdCache1, axis=0) dGs2 = evalTree.final_view(dProdCache2, axis=0) #shape == ( len(circuit_list),", "nElements = evalTree.num_final_elements() #Fill product cache info (not distributed) prodCache, scaleCache = self._compute_product_cache(evalTree,", "in compliance with the License. You may obtain a copy of the License", "# tmp_num_params = [_slct.length(s) for s in loc_e_slices] # tmp_offsets = [ sum(tmp_num_params[0:i])", "list, not a set) # since all scaled gates start with norm <=", "already-allocated ExM numpy array where E is the total number of computed elements", ", a matrix for each given (i,j) # noqa # d2prod/d(opLabel1)_kl*d(opLabel2)_ij = sum_{M", "could be obtained\" \" by giving dproduct cache computation\" \" *fewer* processors and", "of Contract DE-NA0003525 with NTESS, the U.S. Government retains certain rights # in", "# of prep and effect parameters onto a final \"filtered\" set. # \"\"\"", "result memory hProdCache = _np.zeros((cacheSize,) + hessn_shape) # Use comm to distribute columns", "dim) cacheSize = len(evalTree) # ------------------------------------------------------------------ #print(\"MPI: _compute_dproduct_cache begin: %d deriv cols\" %", "2D array with probability-derivatives for each \"final element\" of `evalTree`. Parameters ---------- mxToFill", "relevant_gpindices = _np.array(relevant_gpindices, _np.int64) if len(relevant_gpindices) == 1: #Don't return a length-1 list,", ", a matrix # noqa # dprod/d(opLabel)_ij = sum_{L s.t. GL == oplabel}", "SPAM vectors) access to these fundamental operations. \"\"\" def __init__(self, dim, simplified_op_server, paramvec):", "or float, optional The maximum number of 1st (row) and 2nd (col) derivatives", "= blkSize2 = None # wrtFilter1 & wrtFilter2 dictates block if blkSize1 is", "deriv1MxToFill is not None: _fas(deriv1MxToFill, [fInds, pslc1], self._dprobs_from_rhoE( spamTuple, rho, E, Gs[gInds], dGs1[gInds],", "[dprod/d(opLabel)_mn]_il rho_l (and same for other diff order) # d2pr/d(E)_i d(rho)_j = prod_ij", "rho)[i,j,k,0] # d2pr_dEs[i,j,J0+J] = dot( squeeze(dot(dGs, rho),axis=(3,)), dEP)[i,j,J] # d2pr_dEs[:,:,J0+J] = dot( squeeze(dot(dGs,", "# (iRight,iLeft,iFinal) = tup implies circuit[i] = circuit[iLeft] + circuit[iRight], but we want:", "wrtFilter2=None, wrtBlockSize1=None, wrtBlockSize2=None, gatherMemLimit=None): \"\"\" Compute the outcome probability-Hessians for an entire tree", "\"\"\" Computes a tree of products in a linear cache space. Will *not*", "\"`evalTree` cannot be split\" nElements = evalTree.num_final_elements() #Fill product cache info (not distributed)", "in circuit_list]) if _nla.norm(prMxToFill[fInds] - check_vp) > 1e-6: _warnings.warn(\"norm(vp-check_vp) = %g - %g", "return value if not None. check : boolean, optional If True, perform extra", "wrtFilter2: dop_dopLabel2 = dop_dopLabel1 else: dop_dopLabel2 = { opLabel: gate.deriv_wrt_params(gate_wrtFilters2[opLabel]) for opLabel, gate", "indices into mxToFill, specifying the correspondence between rows of mxToFill and spam labels.", "the computation across multiple processors. This is done over operation sequences when a", "_np.zeros((1, self.Np, self.Np)) _fas(d2pr_d2rhos, [0, self.sos.get_prep(rholabel).gpindices, self.sos.get_prep(rholabel).gpindices], _np.tensordot(derivWrtAnyRhovec, self.sos.get_prep(rholabel).hessian_wrt_params(), (1, 0))) # _np.einsum('ij,jkl->ikl',", "= self.Np / mySubComm.Get_size() blkSize = comm_blkSize if (blkSize is None) \\ else", "(and luckily never used) - so it's been removed. if comm is not", "G numpy array, where: - M == length of the vectorized model (number", "is None) \\ else min(comm_blkSize, blkSize) # override with smaller comm_blkSize else: blkSize", "tensor (G(L+1) ... GN)^T ]] # noqa # # So for each opLabel", "(skip over the zero and single-gate-strings) #cnt = 0 for i in evalTree.get_evaluation_order():", "# Get: dp_drhos[i, rho_gpindices] = dot(E,Gs[i],drho/drhoP) # dp_drhos[i,J0+J] = sum_kl E[0,k] Gs[i,k,l] drhoP[l,J]", "distribution) prodCache, scaleCache = self._compute_product_cache(evalSubTree, mySubComm) scaleVals = self._scaleExp(evalSubTree.final_view(scaleCache)) Gs = evalSubTree.final_view(prodCache, axis=0)", "(see below) hGs[_np.isnan(hGs)] = 0 _np.seterr(**old_err) if flat: # cols = deriv cols,", "<= 1 assert(len(nanOrInfCacheIndices) == 0) return prodCache, scaleCache def _compute_dproduct_cache(self, evalTree, prodCache, scaleCache,", "1, comm) #, gatherMemLimit) #gather over row-distribution (Deriv1) #note: gathering axis 1 of", "self.sos.get_operation(opLabel) op_wrtFilter1, gpindices1 = self._process_wrtFilter(wrtFilter1, gate) op_wrtFilter2, gpindices2 = self._process_wrtFilter(wrtFilter2, gate) # Allocate", "s.t. GL == gatelabel2, M < L} # noqa # [ G1 ...", "e_local_slices=loc_e_slices, # e_global_slices=global_e_slices, # num_rho_params=self.tot_rho_params, # num_e_params=self.tot_e_params) def _hprobs_from_rhoE(self, spamTuple, rho, E, Gs,", "of ints, optional If not None, a list of integers specifying which parameters", "* nspam * (wrtLen1 + wrtLen2) # dprobs1 & dprobs2 mem += cache_size", "self.Np if (wrtFilter1 is None) else _slct.length(wrtFilter1) nDerivCols2 = self.Np if (wrtFilter2 is", "= self.dim nDerivCols1 = self.Np if (wrtFilter1 is None) else _slct.length(wrtFilter1) nDerivCols2 =", "evalSubTree, prodCache, scaleCache, mySubComm, wrtSlice1) dProdCache2 = dProdCache1 if (wrtSlice1 == wrtSlice2) else", "= vec( mx w/ row_i = A[i,0] * B[row1] ) = A tensor", "num_param2_groups FLOATSIZE = 8 # in bytes: TODO: a better way dim =", "0 ) #assert( len( (_np.isinf(dGs)).nonzero()[0] ) == 0 ) #dGs = clip(dGs,-1e300,1e300) _np.seterr(**old_err)", "scaleCache, comm=None, wrtSlice1=None, wrtSlice2=None): \"\"\" Computes a tree of product 2nd derivatives in", "we only need to compute this gate hessian once). But since we're #", "(row) and 2nd (col) derivatives to compute *products* for simultaneously. None means compute", "op_wrtFilter2, gpindices2 = self._process_wrtFilter(wrtFilter2, gate) # Allocate memory for the final result num_deriv_cols1", "+= _np.log(nG) # LEXICOGRAPHICAL VS MATRIX ORDER else: G = H old_err =", "self._fill_result_tuple((mxToFill,), evalSubTree, slice(None), slice(None), calc_and_fill) #collect/gather results subtreeElementIndices = [t.final_element_indices(evalTree) for t in", "else hGs def _scaleExp(self, scaleExps): old_err = _np.seterr(over='ignore') scaleVals = _np.exp(scaleExps) # may", "8 # in bytes: TODO: a better way dim = self.dim nspam =", "be pre-filtered!\" assert(dGs2.shape[1] == nDerivCols2), \"dGs1 must be pre-filtered!\" # Get: d2pr_drhos[i, j,", "memory constraints make constructing the entire Hessian at once impractical, and one is", "clipTo[0], clipTo[1], out=prMxToFill) # in-place clip if check: self._check(evalTree, prMxToFill, mxToFill, clipTo=clipTo) profiler.add_time(\"bulk_fill_dprobs:", "operation matrices) and hessians[i,j,k,l,m] holds the derivative of the (l,m)-th entry of the", "prod[i,:,:] * drhoP # d2pr_dErhos[i,J0+J,K0+K] = sum jk dEPT[J,j] prod[i,j,k] drhoP[k,K] # d2pr_dErhos[i,J0+J,K0+K]", "not None, a list of integers specifying which gate parameters to include in", "list of `(rowSlice,colSlice)` 2-tuples, each of which specify a \"block\" of the Hessian", "scaled gates start with norm <= 1, products should all have norm <=", "mxToFill : numpy ndarray an already-allocated 1D numpy array of length equal to", "user has already done any such distribution # and has given each processor", "else: # Divide columns into blocks of at most blkSize assert(wrtFilter is None)", "G array, where: - M == length of the vectorized model (number of", "if _slct.length(gpindices) > 0: # works for arrays too # Compute the derivative", "dProd small in order to keep prod managable.\") elif _np.count_nonzero(dProdCache[i]) and dProdCache[i].max() <", "sum [dprod/d(opLabel)_mn]_il rho_l (and same for other diff order) # d2pr/d(E)_i d(rho)_j =", "of parameters being differentiated with respect to when the *second* derivative is taken.", "OK devec = EVec.deriv_wrt_params(E_wrtFilter2) _fas(d2pr_dErhos2, [None, E_gpindices2, rho_gpindices1], _np.swapaxes(_np.dot(_np.transpose(devec), dp_dAnyE), 0, 1)) d2pr_dErhos2", "in myBlk2Indices: blk_wrtSlice2 = blocks2[iBlk2] if blk_wrtSlice1 == blk_wrtSlice2: dProdCache2 = dProdCache1; dGs2", "deriv1MxToFill=None, deriv2MxToFill=None, clipTo=None, check=False, comm=None, wrtFilter1=None, wrtFilter2=None, wrtBlockSize1=None, wrtBlockSize2=None, gatherMemLimit=None): \"\"\" Compute the", "may generate overflow, but OK if clipTo is not None: p = _np.clip(p,", "[0, None, EVec.gpindices], _np.dot(derivWrtAnyEvec, EVec.deriv_wrt_params())) d2pr_dErhos = _np.zeros((1, self.Np, self.Np)) derivWrtAnyEvec = scale", "flattened everything else return (dGs, Gs, scaleVals) if bScale else (dGs, Gs) else:", "self._dprobs_from_rhoE( spamTuple, rho, E, Gs[gInds], dGs1[gInds], scaleVals[gInds], wrtSlice1), add=sumInto) if deriv2MxToFill is not", "gatherMemLimit) if deriv2MxToFill is not None: _mpit.gather_slices(blocks2, blk2Owners, deriv2MxToFill, [felInds], 1, blk1Comm, gatherMemLimit)", "SAME length as fInds). calc_and_fill_fn(spamTuple, fInds, gInds, pslc1, pslc2, False) # TODO: remove", "= _np.zeros((nCircuits, nDerivCols2, nDerivCols1)) _fas(d2pr_drhos2, [None, None, rho_gpindices1], _np.squeeze(_np.dot(_np.dot(E, dGs2), drho), axis=(0,)) *", "objgraph # objgraph.show_growth(limit=50) #get distribution across subtrees (groups if needed) subtrees = evalTree.get_sub_trees()", "b/c rho,E are EVec = self.sos.get_effect(elabel) # arrays, these are SPAMVecs nCircuits =", "and *fills* (i.e. doesn't return to save copying) some arrays. The arrays that", "len(circuit_list), dim, dim ), # Gs[i] is product for i-th operation sequence dGs1", "function takes a \"calc-and-fill\" function, which computes and *fills* (i.e. doesn't return to", "dGs2[gInds], hGs[gInds], scaleVals[gInds], wrtSlice1, wrtSlice2), add=sumInto) _np.seterr(**old_err) #NOTE: don't distribute wrtSlicesList across comm", "effect labels. circuit : Circuit or tuple A tuple-like object of *simplified* gates", "0, comm) #note: pass prMxToFill, dim=(KS,), so gather prMxToFill[felInds] (axis=0) profiler.add_time(\"MPI IPC\", tm)", "single column of the Hessian at a time. For example, the Hessian of", ") #Compute all requested derivative columns at once self._fill_result_tuple((prMxToFill, deriv1MxToFill, deriv2MxToFill, mxToFill), evalSubTree,", "[0, EVec.gpindices], _np.dot(derivWrtAnyEvec, EVec.deriv_wrt_params())) _np.seterr(**old_err) if returnPr: return dpr_drhos + dpr_dEs + dpr_dOps,", "(see below) dGs[_np.isnan(dGs)] = 0 _np.seterr(**old_err) if flat: dGs = _np.swapaxes(_np.swapaxes(dGs, 0, 1).reshape(", "If this is not the case, need LinearOperator objects to # have a", "= _np.clip(p, clipTo[0], clipTo[1]) #Derivs wrt SPAM derivWrtAnyRhovec = scale * _np.dot(E, prod)", "gl != opLabel: continue # loop over locations of opLabel LRproduct = _np.kron(leftProds[i],", "the *simplified* operation sequences found in an evaluation tree, `evalTree`. An initial list", "\" than derivative columns(%d)!\" % self.Np + \" [blkSize = %.1f, nBlks=%d]\" %", "tree will hold. Returns ------- int The memory estimate in bytes. \"\"\" #Note:", "gates return ret def _check(self, evalTree, prMxToFill=None, dprMxToFill=None, hprMxToFill=None, clipTo=None): # compare with", "have # a more than linear dependence on their parameters. if self.sos.get_prep(rholabel).has_nonzero_hessian(): dp_dAnyRho", "comm.Get_rank() == 0: # import objgraph # objgraph.show_growth(limit=50) #get distribution across subtrees (groups", "allow for *complex* derivatives, since matrices can be complex # - update probability-derivative", "maybe let dGs2 be None? assert(nDerivCols1 == nDerivCols2) d2pr_dEs2 = _np.transpose(d2pr_dEs1, (0, 2,", "infs occur here _np.seterr(**old_err) return scaleVals def _rhoE_from_spamTuple(self, spamTuple): assert(len(spamTuple) == 2) if", "_fas(flattened_dprod, [None, gpindices], _np.dot(LRproduct, dop_dopLabel), add=True) # (dim**2, nParams[opLabel]) if flat: return flattened_dprod", "and wrtFilter2). clipTo : 2-tuple, optional (min,max) to clip return value if not", "= evalSubTree.final_view(dProdCache1, axis=0) dGs2 = evalSubTree.final_view(dProdCache2, axis=0) #( nCircuits, nDerivColsX, dim, dim )", "second-derivative parameters into. Computation will be automatically parallelized over these groups. num_final_strs :", "= gpindices1[opLabel2] #nDerivCols2 = dop_dopLabel2[opLabel2].shape[1] # FUTURE: we could add logic that accounts", "sum_lj dEPT[J,j] Gs[i,j,l] rho[l,0] # dp_dEs[i,J0+J] = sum_j dEP[j,J] dot(Gs, rho)[i,j] # dp_dEs[i,J0+J]", "for i in range(len(self.preps)) ] # global_e_slices = [slice(self.e_offset[i],self.e_offset[i+1]) for i in range(len(self.effects))", "cache calc.\") dProdCache = _np.zeros((cacheSize,) + deriv_shape) # This iteration **must** match that", "of final strings (may be less than or greater than `cacheSize`) the tree", "case, need LinearOperator objects to # have a 2nd-deriv method in addition of", "floating-point probabilities, corresponding to the elements of `elabels`. \"\"\" assert(time is None), \"MatrixForwardSimulator", "tuple of operation labels The sequence of operation labels. bScale : bool, optional", "tried to allow for parallelization of # _compute_product_cache when the tree was split,", "# slice that results in a zero dimension else: obj_wrtFilter = None relevant_gpindices", "self._process_wrtFilter(wrtSlice1, self.sos.get_effect(elabel)) E_wrtFilter2, E_gpindices2 = self._process_wrtFilter(wrtSlice2, self.sos.get_effect(elabel)) nDerivCols1 = self.Np if wrtSlice1 is", "= self._get_filter_info(wrtSlices1) #flt2 = self._get_filter_info(wrtSlices2) # GATE DERIVS (assume hGs is already sized/filtered)", "elements like 'Imyinst_0') clipTo : 2-tuple (min,max) to clip returned probability to if", "an elementary matrix dim = self.dim #Cache partial products (relatively little mem required)", "for simultaneously. None means compute all requested rows or columns at once. The", "axis=0) #shape == ( len(circuit_list), dim, dim ), Gs[i] is product for i-th", "operation matrices). scaleValues : numpy array Only returned when bScale == True. A", "#Note: no support for \"custom\" spamlabels... # This calculator uses the convention that", "%s)\" \\ # % (nDerivCols2, comm.Get_rank(), str(myDerivColSlice))) if mySubComm is not None and", "bulk products, their gradients, and their Hessians. PSMALL = 1e-100 DSMALL = 1e-100", "wrtSlice2, of the parent-function scope. This use of # closures seems confusing and", "x M x M numpy array, where: - N == the number of", "(spam-tuples) for a single operation sequence. The spam tuples may only vary in", "squeeze( dot( E, dot( dGs, rho ) ), axis=(0,3)) old_err2 = _np.seterr(invalid='ignore', over='ignore')", "# linear in the parameters assert(opLabel1 == opLabel2) if opLabel1 in hop_dopLabels: #", "# may overflow, but OK if infs occur here _np.seterr(**old_err) if bScale: return", "d2pr_dEs2 # wrt E ret += d2pr_drhos1 + d2pr_dEs1 + d2pr_dOps2 # wrt", "wrtSlice2) hGs = evalTree.final_view(hProdCache, axis=0) if bReturnDProbs12: dprobs1 = _np.zeros((nElements, _slct.length(wrtSlice1)), 'd') dprobs2", "self.dproduct(circuit) assert(dprod_dOps.shape[0] == self.Np) if returnDeriv: # same as in dpr(...) dpr_dOps =", "G) rightProdsT.append(_np.transpose(G)) # Allocate memory for the final result num_deriv_cols = self.Np if", "=> (vec_prod_indx,kl,ij) elif l < m: x0 = _np.kron(_np.transpose(prods[(l + 1, m -", "= (nDerivCols1, nDerivCols2, dim, dim) cacheSize = len(evalTree) # ------------------------------------------------------------------ if comm is", "== the number of entries in a single flattened gate (ordering same as", "param_slice1, param_slice2, calc_and_fill_fn): \"\"\" This function takes a \"calc-and-fill\" function, which computes and", "operation matrices. scale : float Only returned when bScale == True, in which", "= None # wrtFilter dictates block if blkSize is None: #Fill derivative cache", "= flattened all else dGs1 = _np.swapaxes(_np.swapaxes(dGs1, 0, 1).reshape((nDerivCols1, nCircuits * dim**2)), 0,", "scaleVal is mult by a zero deriv value (see below) dGs[_np.isnan(dGs)] = 0", "columns\", nDerivCols) return dProdCache def _compute_hproduct_cache(self, evalTree, prodCache, dProdCache1, dProdCache2, scaleCache, comm=None, wrtSlice1=None,", "number of final elements (this can be obtained by `evalTree.num_final_elements()`. To interpret which", "derivative columns and then (and only when needed) a split tree to parallelize", "# is at most *linear* in each of the gate parameters. If this", "d2pr_dErhos[i,J0+J,K0+K] = dot(dEPT,prod,drhoP)[J,i,K] # d2pr_dErhos[i,J0+J,K0+K] = swapaxes(dot(dEPT,prod,drhoP),0,1)[i,J,K] # d2pr_dErhos[:,J0+J,K0+K] = swapaxes(dot(dEPT,prod,drhoP),0,1)[:,J,K] d2pr_dErhos1 =", "a single flattened gate (ordering as numpy.flatten) - M == length of the", "A tuple-like object of *simplified* gates (e.g. may include instrument elements like 'Imyinst_0')", "but OK dpr_dEs = _np.zeros((1, self.Np)) derivWrtAnyEvec = scale * _np.transpose(_np.dot(prod, rho)) #", "number of groups to divide the first-derivative parameters into. Computation will be automatically", "a single column of the Hessian at a time. For example, the Hessian", "logic that accounts for the symmetry of the Hessian, so that # if", "evalTree.is_split(): _warnings.warn(\"Ignoring tree splitting in hproduct cache calc.\") hProdCache = _np.zeros((cacheSize,) + hessn_shape)", "/= _np.exp(scale) if dProdCache[i].max() < DSMALL and dProdCache[i].min() > -DSMALL: _warnings.warn(\"Scaled dProd small", "given gateLabel_ij. This function returns a concatenated form of the above matrices, so", "be assigned to subtrees of the created tree. This aids in the tree", "ORDER return G def _process_wrtFilter(self, wrtFilter, obj): \"\"\" Helper function for doperation and", "of `result_tup`. The fill function computes values for only a single spam label", "version that should do the same thing (for debugging) master_circuit_list = evalTree.generate_circuit_list(permute=False) #", "(as needed) a split tree to parallelize computation, since there are no memory", "1e-100 DSMALL = 1e-100 HSMALL = 1e-100 class MatrixForwardSimulator(ForwardSimulator): \"\"\" Encapsulates a calculation", "# as above return (hGs, scaleVals) if bScale else hGs def _scaleExp(self, scaleExps):", "number of entries in a single flattened gate (ordering same as numpy.flatten), -", "elif fnName == \"bulk_fill_dprobs\": mem += cache_size * wrtLen1 * dim * dim", "below). bScale : bool, optional When True, return a scaling factor (see below).", "= dop_dopLabel1 else: dop_dopLabel2 = { opLabel: gate.deriv_wrt_params(gate_wrtFilters2[opLabel]) for opLabel, gate in used_operations.items()}", "% (self.Np**2) + \" [blkSize = {%.1f,%.1f}, nBlks={%d,%d}]\" % (blkSize1, blkSize2, nBlks1, nBlks2))", "= (~_np.isfinite(prodCache)).nonzero()[0] # may be duplicates (a list, not a set) # since", "Gs = evalSubTree.final_view(prodCache, axis=0) #( nCircuits, dim, dim ) def calc_and_fill(spamTuple, fInds, gInds,", "gates, starting with G0 # nG = norm(G); G /= nG; total_exp +=", "else (hGs, dGs1, dGs2, Gs) else: hGs = evalTree.final_view(hProdCache, axis=0) #shape == (", "= sum{...} [ unvec( G1 ... G(M-1) tensor (G(M+1) ... G(L-1))^T vec( dG(M)/dkl", "for opLabel) if flat: return flattened_dprod else: # axes = (gate_ij, prod_row, prod_col)", "number of model parameters. Parameters ---------- spamTuple : (rho_label, simplified_effect_label) Specifies the prep", "axis=0) hProdCache = self._compute_hproduct_cache( evalTree, prodCache, dProdCache1, dProdCache2, scaleCache, comm, wrtSlice1, wrtSlice2) hGs", "the product of matrices. Parameters ---------- circuit : Circuit or tuple of operation", "pslc1], self._dprobs_from_rhoE( spamTuple, rho, E, Gs[gInds], dGs[gInds], scaleVals[gInds], wrtSlice), add=sumInto) _np.seterr(**old_err) profiler.add_time(\"bulk_fill_dprobs: calc_and_fill\",", "check for equivalence: maybe let dGs2 be None? assert(nDerivCols1 == nDerivCols2) d2pr_drhos2 =", "= dGs1 = None # free mem def _fill_result_tuple(self, result_tup, evalTree, param_slice1, param_slice2,", "note that we *cannot* make use of a tree being # split because", "* scaleVals[:, None] _fas(dp_dEs, [None, E_gpindices], _np.dot(dp_dAnyE, EVec.deriv_wrt_params(E_wrtFilter))) sub_vdp = dp_drhos + dp_dEs", "scaleVals[i] contains the multiplicative scaling needed for the derivatives and/or products for the", "i.e. rank != 0, cpus my_results = self._compute_dproduct_cache( evalTree, prodCache, scaleCache, None, myDerivColSlice,", "check_vdp))) # pragma: no cover if hprMxToFill is not None: check_vhp = _np.concatenate(", "in myBlkIndices: tm = _time.time() block_wrtSlice = blocks[iBlk] dProdCache = self._compute_dproduct_cache(evalSubTree, prodCache, scaleCache,", "= self._compute_product_cache(evalTree, comm) #use cached data to construct return values Gs = evalTree.final_view(prodCache,", "so the first identity below is valid. # Below we use E(i,j) to", "must be None if wrtFilter is not None. Set this to non-None to", "# To support unitary evolution we need to: # - alter product, dproduct,", "comm, gatherMemLimit) #note: pass mxToFill, dim=(KS,M), so gather mxToFill[felInds] (axis=0) if prMxToFill is", "dpr(...) dpr_dOps = _np.empty((1, self.Np)) for i in range(self.Np): dpr_dOps[0, i] = float(_np.dot(E,", "(~_np.isfinite(prodCache)).nonzero()[0] # may be duplicates (a list, not a set) # since all", "the calcs of the given # wrtSlicesList last_wrtSlice1 = None # keep last", "a zero hessian value (see below) hGs[_np.isnan(hGs)] = 0 _np.seterr(**old_err) if flat: #", "the vectorized model (number of model parameters) and hessian[i,j,k] holds the derivative of", "bScale: old_err = _np.seterr(over='ignore', invalid='ignore') # may overflow or get nans (invalid), but", "rho_wrtFilter2), (1, 0))) # _np.einsum('ij,jkl->ikl', dp_dAnyRho, self.sos.get_prep(rholabel).hessian_wrt_params( # rho_wrtFilter1, rho_wrtFilter2)) else: d2pr_d2rhos =", "\"\"\" dim = self.dim # Note: dProdCache?.shape = (#circuits,#params_to_diff_wrt,dim,dim) nDerivCols1 = dProdCache1.shape[1] nDerivCols2", "to # have a 2nd-deriv method in addition of deriv_wrt_params # # Note:", "GxG ; hL,hR = vgs x vgs x GxG dLdRa = _np.swapaxes(_np.dot(dL1, dR2),", "Gs[gInds], scaleVals[gInds]), add=sumInto) _np.seterr(**old_err) self._fill_result_tuple((mxToFill,), evalSubTree, slice(None), slice(None), calc_and_fill) #collect/gather results subtreeElementIndices =", "num_param1_groups : int The number of groups to divide the first-derivative parameters into.", "above, and hessians[i,j,k] holds the derivative of the (i % G^2)-th entry of", "self.dim gate = self.sos.get_operation(opLabel) op_wrtFilter, gpindices = self._process_wrtFilter(wrtFilter, gate) # Allocate memory for", "comm, wrtSlice2) hProdCache = self._compute_hproduct_cache(evalTree, prodCache, dProdCache1, dProdCache2, scaleCache, comm, wrtSlice1, wrtSlice2) #use", "is the number of parameter rows (the length of rowSlice) - B' is", "The evaluation tree organizes how to efficiently compute the gate-only sequences. This routine", "processors and *smaller* (sub-)tree\" \" (e.g. by splitting tree beforehand), as there\" \"", "rhoVec.deriv_wrt_params())[0]) # (= [0,:,:]) d2pr_dEs = _np.zeros((1, self.Np, self.Np)) derivWrtAnyEvec = _np.squeeze(_np.dot(dprod_dOps, rho),", "(wrtFilter is None) else len(wrtFilter) flattened_dprod = _np.zeros((dim**2, num_deriv_cols), 'd') # For each", "Returns ------- deriv : numpy array * if flat == False, a M", "Hessian of a probability generated by a operation sequence and spam tuple as", "_np.exp(scale_exp) _np.seterr(**old_err) return G, scale else: G = _np.identity(self.dim) for lOp in circuit:", "now un-vectorized dim x dim mxs corresponding to a single kl xv =", "if wrtSlice1 == wrtSlice2: # Note: this doesn't involve gate derivatives d2pr_dErhos2 =", "wrtSlice2), add=sumInto) _fas(mxToFill, [fInds, pslc1, pslc2], self._hprobs_from_rhoE( spamTuple, rho, E, Gs[gInds], dGs1[gInds], dGs2[gInds],", "wrtLen2 = (self.Np + np2 - 1) // np2 # ceiling(num_params / np2)", "by evalTree column-by-column. This routine can be useful when memory constraints make constructing", "------- block_generator A generator which, when iterated, yields the 3-tuple `(rowSlice, colSlice, hprobs)`", "will be automatically parallelized over these groups. num_param2_groups : int The number of", "data to construct return values old_err = _np.seterr(over='ignore') scaleExps = evalTree.final_view(scaleCache) scaleVals =", "free mem #gather column results: gather axis 2 of mxToFill[felInds,blocks1[iBlk1]], dim=(ks,blk1,M) _mpit.gather_slices(blocks2, blk2Owners,", "else: return ret, dpr else: if returnPr: return ret, p else: return ret", "managable.\") elif _np.count_nonzero(hProdCache[i]) and hProdCache[i].max() < HSMALL and hProdCache[i].min() > -HSMALL: _warnings.warn(\"hProd is", "are given by evalTree's initial single- or zero-operation labels wrtIndices1 = _slct.indices(wrtSlice1) if", "1)) else: d2pr_dErhos2 = _np.zeros((nCircuits, nDerivCols2, nDerivCols1)) drho = rhoVec.deriv_wrt_params(rho_wrtFilter1) dp_dAnyE = _np.dot(Gs,", "'rho_local_slices rho_global_slices ' + # 'e_local_slices e_global_slices num_rho_params num_e_params') # # if wrtSlices", "_slct.length(gpindices) > 0: # works for arrays too # Compute the derivative of", "_fas(dpr_drhos, [0, self.sos.get_prep(rholabel).gpindices], _np.dot(derivWrtAnyRhovec, rhoVec.deriv_wrt_params())) # may overflow, but OK dpr_dEs = _np.zeros((1,", "== spam labels and values which are integer row indices into mxToFill, specifying", "model parameters. derivs1, derivs2 : numpy array Only returned if bReturnDProdsAndProds == True.", "products at once. Parameters ---------- evalTree : EvalTree given by a prior call", "entire tree of gate strings. Similar to `bulk_fill_probs(...)`, but fills a 2D array", "nDerivCols1), \"hGs must be pre-filtered!\" assert(hGs.shape[2] == nDerivCols2), \"hGs must be pre-filtered!\" #Compute", "in this software. # Licensed under the Apache License, Version 2.0 (the \"License\");", "* exp(total_exp) # probability # print \"%d: p = %g, norm %g, exp", ") #hGs = clip(hGs,-1e300,1e300) _np.seterr(**old_err) if flat: hGs = _np.rollaxis(_np.rollaxis(hGs, 0, 3).reshape( (nDerivCols1,", "processors. Distribution is performed over subtrees of evalTree (if it is split). Returns", "_np.exp(scaleCache[i]) #evaluate operation sequences using tree (skip over the zero and single-gate-strings) for", "if wrtSlices is not None: # loc_rho_slices = [ # _slct.shift(_slct.intersect( # wrtSlices['preps'],", "devec = EVec.deriv_wrt_params(E_wrtFilter1) _fas(d2pr_dEs2, [None, None, E_gpindices1], _np.dot(dp_dAnyE, devec)) d2pr_dEs2 = _np.transpose(d2pr_dEs2, (0,", "gate strings to compute the bulk operation on. prMxToFill : numpy array, optional", "* scaleVals, 0, 3) # convert nans to zero, as these occur b/c", "_rhoEs_from_spamTuples(self, rholabel, elabels): #Note: no support for \"custom\" spamlabels... # This calculator uses", "calculations across multiple processors. Returns ------- deriv : numpy array * if flat", "pragma: no cover # allocate final result memory hProdCache = _np.zeros((cacheSize,) + hessn_shape)", "G(M-1) dG(M)/dkl G(M+1) ... G(L-1) dG(L)/dij G(L+1) ... GN ] + {similar with", "elif _np.count_nonzero(hProdCache[i]) and hProdCache[i].max() < HSMALL and hProdCache[i].min() > -HSMALL: _warnings.warn(\"hProd is small", "mySubComm, wrtSlice1, wrtSlice2) hGs = evalSubTree.final_view(hProdCache, axis=0) #( nCircuits, len(wrtFilter1), len(wrtFilter2), dim, dim", "scale * _np.dot(E, prod) _fas(dpr_drhos, [0, self.sos.get_prep(rholabel).gpindices], _np.dot(derivWrtAnyRhovec, rhoVec.deriv_wrt_params())) # may overflow, but", "that rho has shape (N,1) rho = self.sos.get_prep(rholabel).todense()[:, None] E = _np.conjugate(_np.transpose(self.sos.get_effect(elabel).todense() [:,", "[fInds], self._probs_from_rhoE(rho, E, Gs[gInds], scaleVals[gInds]), add=sumInto) if deriv1MxToFill is not None: _fas(deriv1MxToFill, [fInds,", "outputs of :func:`bulk_fill_hprobs` (i.e. args `mxToFill`, `deriv1MxToFill`, and `deriv1MxToFill`), then: - `hprobs ==", "_slct.length(wrtSlice2)), 'd') #prMxToFill = None deriv1MxToFill = dprobs1 deriv2MxToFill = dprobs2 mxToFill =", "hProdCache = self._compute_hproduct_cache(evalSubTree, prodCache, dProdCache1, dProdCache2, scaleCache, mySubComm, wrtSlice1, wrtSlice2) hGs = evalSubTree.final_view(hProdCache,", "= [ sum(tmp_num_params[0:i]) for i in range(len(self.effects)+1) ] # global_e_slices = [ slice(tmp_offsets[i],tmp_offsets[i+1])", "where - S == len(circuit_list) - M == the length of the vectorized", "with respect to. If there are more processors than model parameters, distribution over", "E_gpindices1, rho_gpindices2), _np.swapaxes(_np.dot(_np.transpose(devec), dp_dAnyE), 0, 1)) # get d2pr_dEs where E derivatives are", "derivatives in a linear cache space. Will use derivative rows and columns and", "nDerivCols1, nDerivCols2, dim, dim ), # hGs[i] is hprod_dGates for ith string if", "for ith string if not bScale: old_err = _np.seterr(over='ignore', invalid='ignore') # may overflow", "None, a list of integers specifying which parameters to include in the derivative", "True, return a scaling factor (see below). Returns ------- product : numpy array", "not None: self._fill_result_tuple((prMxToFill,), evalSubTree, slice(None), slice(None), calc_and_fill_p) profiler.mem_check(\"bulk_fill_dprobs: post fill probs\") #distribute derivative", "self.Np + \" [blkSize = %.1f, nBlks=%d]\" % (blkSize, nBlks)) # pragma: no", "hProdCache[i].max() < HSMALL and hProdCache[i].min() > -HSMALL: _warnings.warn(\"hProd is small (oh well!).\") return", "evalSubTree, slice(None), slice(None), calc_and_fill) else: # Divide columns into blocks of at most", "linear dimension of a operation matrix (G x G operation matrices) and derivs[i,j,k,l]", "matrices and SPAM vectors) access to these fundamental operations. \"\"\" def __init__(self, dim,", "nG); scale_exp += _np.log(nG) # LEXICOGRAPHICAL VS MATRIX ORDER else: G = H", "from ..tools import mpitools as _mpit from ..tools import slicetools as _slct from", "d(rho)_j = prod_ij (and same for other diff order) # d2pr/d(E)_i d(E)_j =", "post fill\") dProdCache = dGs = None # free mem else: # Divide", "= _mpit.slice_up_range(self.Np, nBlks1) blocks2 = _mpit.slice_up_range(self.Np, nBlks2) #distribute derivative computation across blocks myBlk1Indices,", "terms only compute one triangle of hessian # Note: d2pr_d2rhos and d2pr_d2Es terms", "(wrtSlice1 == wrtSlice2) else \\ self._compute_dproduct_cache(evalSubTree, prodCache, scaleCache, mySubComm, wrtSlice2) dGs1 = evalSubTree.final_view(dProdCache1,", "special case of empty label == no gate prodCache[i] = _np.identity(dim) # Note:", "gl2 are both in opsToVectorize1 and opsToVectorize2 we only compute d2(prod)/d(gl1)d(gl2) # and", "derivWrtAnyEvec = scale * _np.transpose(_np.dot(prod, rho)) # may overflow, but OK _fas(dpr_dEs, [0,", "(reshape without copying - throws error if copy is needed) y = _np.dot(_np.kron(xv,", "for other diff order) # d2pr/d(E)_i d(E)_j = 0 # d2pr/d(rho)_i d(rho)_j =", "self.evotype == \"statevec\": ps = _np.real(_np.abs(_np.dot(Es, _np.dot(G, rho)))**2) else: # evotype == \"densitymx\"", "in range(self.Np): for j in range(self.Np): d2pr_dOps2[0, i, j] = float(_np.dot(E, _np.dot(d2prod_dGates[i, j],", ": bool, optional when set to True, additionally return the probabilities and their", "compute *products* for simultaneously. None means compute all requested rows or columns at", "the final block size. These arguments must be None if the corresponding wrtFilter", "DE-NA0003525 with NTESS, the U.S. Government retains certain rights # in this software.", "using tree (skip over the zero and single-gate-strings) #cnt = 0 for i", "probability # (TODO in FUTURE) # pr = Tr( |rho><E| * prod )", "of the parameters being differentiated with respect to (see wrtBlockSize). wrtFilter1, wrtFilter2 :", "memory estimate in bytes. \"\"\" #Note: num_final_strs is irrelevant here b/c cachesize is", "if comm.Get_size() > nDerivCols: #If there are more processors than deriv cols, give", "computes values for only a single spam label (specified to it by the", "wrtSlice2) #use cached data to construct return values old_err = _np.seterr(over='ignore') scaleExps =", "SPAMVecs d2prod_dGates = self.hproduct(circuit) assert(d2prod_dGates.shape[0] == d2prod_dGates.shape[1]) d2pr_dOps2 = _np.empty((1, self.Np, self.Np)) for", "= evalTree.final_view(dProdCache1, axis=0) dGs2 = evalTree.final_view(dProdCache2, axis=0) #shape == ( len(circuit_list), nDerivColsX, dim,", "flattened_hprod else: return _np.transpose(flattened_hprod, (1, 2, 0)).reshape( (num_deriv_cols1, num_deriv_cols2, dim, dim)) # axes", "as a part of MPI processor syncronization. Returns ------- None \"\"\" tStart =", "1e-100 HSMALL = 1e-100 class MatrixForwardSimulator(ForwardSimulator): \"\"\" Encapsulates a calculation tool used by", "E_gpindices2 = self._process_wrtFilter(wrtSlice2, self.sos.get_effect(elabel)) nDerivCols1 = self.Np if wrtSlice1 is None else _slct.length(wrtSlice1)", "blocks1[iBlk1], blocks2[iBlk2], calc_and_fill) hProdCache = hGs = dProdCache2 = dGs2 = None #", "of (most likely because you want to computed their probabilites). These are a", "ideal/desired cache size given a number of operation sequences. Returns ------- int \"\"\"", "else: # evotype == \"densitymx\" # probability, with scaling applied (may generate overflow,", "hProdCache = hGs = dProdCache2 = dGs2 = None # free mem if", "and fill result quantities for given arguments \"\"\" tm = _time.time() old_err =", "if flat == False, a M x M x G x G numpy", "usual density-matrix-mode probability # (TODO in FUTURE) # pr = Tr( |rho><E| *", "product will overflow and the subsequent trace operation will yield nan as the", "# global_rho_slices = [slice(self.rho_offset[i],self.rho_offset[i+1]) for i in range(len(self.preps)) ] # global_e_slices = [slice(self.e_offset[i],self.e_offset[i+1])", "# special case of empty label == no gate prodCache[i] = _np.identity(dim) #", "operation sequences. Parameters ---------- spam_label_rows : dictionary a dictionary with keys == spam", "be split\" nElements = evalTree.num_final_elements() #Fill product cache info (not distributed) prodCache, scaleCache", "%d cols (%s) (rank %d computing %s)\" \\ # % (nDerivCols, str(allDerivColIndices), comm.Get_rank(),", "profiler.mem_check(\"bulk_fill_dprobs: post compute product\") def calc_and_fill(spamTuple, fInds, gInds, pslc1, pslc2, sumInto): \"\"\" Compute", "generated by a operation sequence and spam tuple as a 1 x M", "= sum_k,l E[0,k] Gs[i,k,l] rho[l,0] * scaleVals[i] # vp[i] = sum_k E[0,k] dot(Gs,", "evalSubTree.final_view(dProdCache1, axis=0) dGs2 = evalSubTree.final_view(dProdCache2, axis=0) #( nCircuits, nDerivColsX, dim, dim ) hProdCache", "k-th then j-th model parameters. derivs1, derivs2 : numpy array Only returned if", "* scaleVals[:, None, None] _np.seterr(**old_err2) # may overflow, but OK ; shape ==", "as in bulk_product, bulk_dproduct, and bulk_hproduct. Returns ------- block_generator A generator which, when", "# closures seems confusing and we should do something else LATER. def calc_and_fill(spamTuple,", "dot(Gs, rho)[i,j,0] dEP[j,J] # dp_dEs[i,J0+J] = dot(squeeze(dot(Gs, rho),2), dEP)[i,J] # dp_dEs[:,J0+J] = dot(squeeze(dot(Gs,", "order (easier to think about) revOpLabelList = tuple(reversed(tuple(circuit))) # prod = G1 *", "scale and keep track of exponent # # p = _mt.trace( _np.dot(self.SPAMs[spamLabel],G) )", "gate strings. Similar to `bulk_fill_probs(...)`, but fills a 2D array with probability-derivatives for", "model parameter. \"\"\" # LEXICOGRAPHICAL VS MATRIX ORDER # we do matrix multiplication", "1).reshape( (nDerivCols, nCircuits * dim**2)), 0, 1) # cols = deriv cols, rows", "E, Gs[gInds], dGs1[gInds], dGs2[gInds], hGs[gInds], scaleVals[gInds], wrtSlice1, wrtSlice2), add=sumInto) _np.seterr(**old_err) #Set wrtBlockSize to", "rho))) old_err = _np.seterr(over='ignore') prod, scale = self.product(circuit, True) if returnPr: p =", "\"densitymx\"): raise ValueError((\"Evolution type %s is incompatbile with \" \"matrix-based calculations\" % self.evotype))", "[], 0, comm, gatherMemLimit) #note: pass mxToFill, dim=(KS,M), so gather mxToFill[felInds] (axis=0) if", "else: ret = ps #DEBUG CHECK #check_ps = _np.array( [ self.pr( (rholabel,elabel), circuit,", "def default_distribute_method(self): \"\"\" Return the preferred MPI distribution mode for this calculator. \"\"\"", "gate prodCache[i] = _np.identity(dim) # Note: scaleCache[i] = 0.0 from initialization else: gate", "anything on \"extra\", i.e. rank != 0, cpus my_results = self._compute_dproduct_cache( evalTree, prodCache,", "1) # above: dim = (dim2, nDerivCols1, nDerivCols2); # swapaxes takes (kl,vec_prod_indx,ij) =>", "tree splitting in hproduct cache calc.\") hProdCache = _np.zeros((cacheSize,) + hessn_shape) #First element", "comm is None or comm.Get_rank() == 0: # import objgraph # objgraph.show_growth(limit=50) #get", "_mpit.distribute_indices(list(range(nBlks)), mySubComm) if blkComm is not None: _warnings.warn(\"Note: more CPUs(%d)\" % mySubComm.Get_size() +", "and prep/effect pairs. The evaluation tree organizes how to efficiently compute the gate-only", "if wrtFilter is None: blkSize = wrtBlockSize # could be None if (mySubComm", "== \"statevec\": raise NotImplementedError(\"Unitary evolution not fully supported yet!\") # pr = Tr(", "cache are given by evalTree's initial single- or zero-operation labels for i, opLabel", "giving hproduct cache computation\" \" *fewer* processors and *smaller* (sub-)tree\" \" (e.g. by", "nDerivCols1, nDerivCols2)) drho = rhoVec.deriv_wrt_params(rho_wrtFilter2) dp_dAnyE = _np.dot(Gs, drho) * scaleVals[:, None, None]", "abs(scale) > 1e-8: # _np.isclose(scale,0) is SLOW! dProdCache[i] /= _np.exp(scale) if dProdCache[i].max() <", "prod = G1 * G2 * .... * GN , a matrix #", "# noqa # # So for each opLabel the matrix [ sum_{L s.t.", "1st and 2nd differentiation, respectively (i.e. by wrtFilter1 and wrtFilter2). clipTo : 2-tuple,", "the products within decent bounds #assert( len( (_np.isnan(dGs)).nonzero()[0] ) == 0 ) #assert(", "None, myHessianSlice1, wrtSlice2) # pass None as comm, *not* mySubComm (this is ok,", "# a more than linear dependence on their parameters. if self.sos.get_prep(rholabel).has_nonzero_hessian(): dp_dAnyRho =", "the same dimensions as the Hessian, and turns out to be useful when", "`colSlice` must by Python `slice` objects. bReturnDProbs12 : boolean, optional If true, the", "dot(G, rho))) # vp[i] = sum_k,l E[0,k] Gs[i,k,l] rho[l,0] * scaleVals[i] # vp[i]", "EVec = self.sos.get_effect(elabel) # arrays, these are SPAMVecs #Derivs wrt Gates old_err =", "_np.swapaxes(_np.swapaxes(dGs2, 0, 1).reshape((nDerivCols2, nCircuits * dim**2)), 0, 1) hGs = _np.rollaxis(_np.rollaxis(hGs, 0, 3).reshape(", "the probability generated by the sequence and spam label indexed by iOpStr and", "the first (row) and second (col) derivative operations, respectively. wrtBlockSize2, wrtBlockSize2 : int", "processors than deriv cols, give a # warning -- note that we *cannot*", "----------------------- ret = d2pr_d2rhos + d2pr_dErhos2 + d2pr_drhos2 # wrt rho ret +=", "we dGs[_np.isnan(dGs)] = 0 # assume the zero deriv value trumps since we've", "None #get distribution across subtrees (groups if needed) subtrees = evalTree.get_sub_trees() mySubTreeIndices, subTreeOwners,", "product of no gates G = ident for (j, opLabel2) in enumerate(revOpLabelList[i:], start=i):", "dprobs2[:, None, :] # (KM,N,1) * (KM,1,N') = (KM,N,N') yield wrtSlice1, wrtSlice2, hprobs,", "to perform product and derivatives-of-product calculations. This is contained in a class separate", "where dpr/dx is the usual density-matrix-mode probability # (TODO in FUTURE) # pr", "column ordering when taking derivatives. paramvec : ndarray The parameter vector of the", "- N == the number of entries in a single flattened gate (ordering", "A profiler object used for to track timing and memory usage. gatherMemLimit :", "circuit in circuit_list], axis=0) if _nla.norm(hprMxToFill[fInds][0] - check_vhp[0]) > 1e-6: _warnings.warn(\"norm(vhp-check_vhp) = %g", "0) #don't compute anything on \"extra\", i.e. rank != 0, cpus my_results =", "entries in a single flattened gate (ordered as numpy.flatten) - M == length", "given set of subcalls to computation functions. Parameters ---------- subcalls : list of", "= _np.zeros((1, self.Np)) derivWrtAnyEvec = scale * _np.transpose(_np.dot(prod, rho)) # may overflow, but", "of the given # wrtSlicesList last_wrtSlice1 = None # keep last dProdCache1 for", "*products* for simultaneously. None means compute all requested columns at once. The minimum", "gates (e.g. may include instrument elements like 'Imyinst_0') clipTo : 2-tuple (min,max) to", "# % (nDerivCols, str(allDerivColIndices), comm.Get_rank(), str(myDerivColIndices))) if mySubComm is not None and mySubComm.Get_size()", "if bScale else dGs def bulk_hproduct(self, evalTree, flat=False, bReturnDProdsAndProds=False, bScale=False, comm=None, wrtFilter1=None, wrtFilter2=None):", "we've renormed to keep all the products within decent bounds #assert( len( (_np.isnan(dGs)).nonzero()[0]", "import MatrixEvalTree as _MatrixEvalTree from .forwardsim import ForwardSimulator _dummy_profiler = _DummyProfiler() # Smallness", "{ opLabel: gate.deriv_wrt_params(gate_wrtFilters1[opLabel]) for opLabel, gate in used_operations.items()} if wrtFilter1 == wrtFilter2: dop_dopLabel2", "d2pr_dEs[i,j,J0+J] = sum_kl dEPT[J,k] dGs[i,j,k,l] rho[l,0] # d2pr_dEs[i,j,J0+J] = sum_k dEP[k,J] dot(dGs, rho)[i,j,k,0]", "1): comm_blkSize = self.Np / mySubComm.Get_size() blkSize1 = comm_blkSize if (blkSize1 is None)", "\"\"\" Compute the derivative of a many operation sequences at once. Parameters ----------", "single flattened gate (ordering is the same as that used by numpy.flatten), -", "d2pr_d2rhos = 0 if self.sos.get_effect(elabel).has_nonzero_hessian(): dp_dAnyE = _np.dot(Gs, rho).squeeze(2) * scaleVals[:, None] #", "in range(len(self.effects)) ] # return PrepEffectFilter(rho_local_slices=loc_rho_slices, # rho_global_slices=global_rho_slices, # e_local_slices=loc_e_slices, # e_global_slices=global_e_slices, #", "the subsequent trace operation will yield nan as the returned probability. time :", "(mySubComm.Get_size() > 1): comm_blkSize = self.Np / mySubComm.Get_size() blkSize1 = comm_blkSize if (blkSize1", "matrix (G x G operation matrices). and hessian[i,j,k,l] holds the derivative of the", "not repeatedly # computed for each block of derivative columns if prMxToFill is", "END SPAM DERIVS ----------------------- ret = d2pr_d2rhos + d2pr_dErhos2 + d2pr_drhos2 # wrt", "+ scaleCache[iRight] if prodCache[i].max() < PSMALL and prodCache[i].min() > -PSMALL: nL, nR =", "products : numpy array Only returned when bReturnDProdsAndProds == True. An array of", "this is allocated within # the generator and yielded, *not* allocated by the", "(not requiring row or column distribution) prodCache, scaleCache = self._compute_product_cache(evalSubTree, mySubComm) scaleVals =", "sum_k,l E[0,k] dGs[i,j,k,l] rho[l,0] # dp_dOps[i,j] = sum_k E[0,k] dot( dGs, rho )[i,j,k,0]", "distribute columns allDerivColSlice = slice(0, nDerivCols) if (wrtSlice is None) else wrtSlice _,", "for equivalence: maybe let dGs2 be None? assert(nDerivCols1 == nDerivCols2) d2pr_dEs2 = _np.transpose(d2pr_dEs1,", "to the j-th model parameter. products : numpy array Only returned when bReturnProds", "give a # warning -- note that we *cannot* make use of a", "of subtrees to split the full evaluation tree into. num_subtree_proc_groups : int The", "overflow OK d2pr_drhos2 = _np.transpose(d2pr_drhos2, (0, 2, 1)) # Get: d2pr_dEs[i, j, E_gpindices]", "The spam tuples may only vary in their effect-label (their prep labels must", "* wrtLen1 * wrtLen2 # hprobs & dprobs12 results mem += cache_size *", "global_rho_slices = [slice(self.rho_offset[i],self.rho_offset[i+1]) for i in range(len(self.preps)) ] # global_e_slices = [slice(self.e_offset[i],self.e_offset[i+1]) for", "(min,max) to clip return value if not None. check : boolean, optional If", "is not None) else None for i, opLabel in zip(evalTree.get_init_indices(), evalTree.get_init_labels()): if opLabel", "hoperation below: pulls out pieces of a wrtFilter argument relevant for a single", "labels). numSubtreeComms : int The number of processor groups that will be assigned", "wrtSlice2 = _slct.list_to_slice(wrtFilter2) if (wrtFilter2 is not None) else None #TODO: just allow", "\"\"\" Defines the MatrixForwardSimulator calculator class\"\"\" #*************************************************************************************************** # Copyright 2015, 2019 National Technology", "run slightly faster, but with a chance that the product will overflow and", "G, where - S == len(circuit_list) - M == the number of model", "wrtFilter and blkSize nBlks = int(_np.ceil(self.Np / blkSize)) # num blocks required to", "to True, additionally return the probability itself. returnDeriv : bool when set to", "mxs corresponding to a single kl xv = _np.swapaxes(xv, 1, 2) y =", "to the j-th model parameter. products : numpy array Only returned when bReturnDProdsAndProds", "G(M-1) tensor (G(M+1) ... G(L-1))^T vec( dG(M)/dkl ) ) # noqa # tensor", "\" \" _compute_hproduct_cache.\") #TODO: remove: not needed now that we track owners #if", "but fills a 2D array with probability-derivatives for each \"final element\" of `evalTree`.", "mult by a zero deriv value (see below) dGs2[_np.isnan(dGs2)] = 0 # convert", "rho_gpindices = self._process_wrtFilter(wrtSlice, self.sos.get_prep(rholabel)) E_wrtFilter, E_gpindices = self._process_wrtFilter(wrtSlice, self.sos.get_effect(elabel)) nDerivCols = self.Np if", "num_deriv_cols1, num_deriv_cols2 return _np.rollaxis(flattened_d2prod, 0, 3).reshape((vec_kl_size, vec_ij_size, dim, dim)) # axes = (model_parameter1,", "only compute one triangle of hessian # Note: d2pr_d2rhos and d2pr_d2Es terms are", "_collections.OrderedDict() #Cache processed parameter filters for multiple uses below gpindices1 = {}; gate_wrtFilters1", "returned when bReturnProds == True. An array of shape S x G x", "G, scale = self.product(circuit, True) if self.evotype == \"statevec\": ps = _np.real(_np.abs(_np.dot(Es, _np.dot(G,", "the vectorized model). probability : float only returned if returnPr == True. \"\"\"", "gatherMemLimit : int, optional A memory limit in bytes to impose upon the", "\"bulk_dproduct\": # mem += cache_size * num_params * dim * dim # dproduct", "the Hessian of a probability generated by a operation sequence and spam tuple", "# objgraph.show_growth(limit=50) #get distribution across subtrees (groups if needed) subtrees = evalTree.get_sub_trees() mySubTreeIndices,", "== nDerivCols2) hessn_shape = (nDerivCols1, nDerivCols2, dim, dim) cacheSize = len(evalTree) # ------------------------------------------------------------------", "block if blkSize1 is None and blkSize2 is None: #Fill hessian cache info", "= evalSubTree.final_view(hProdCache, axis=0) #Set filtering for calc_and_fill wrtSlice1 = blocks1[iBlk1] wrtSlice2 = blocks2[iBlk2]", "is not None: myHessianSlice2 = _slct.shift(myDeriv2ColSlice, wrtSlice2.start) else: myHessianSlice2 = myDeriv2ColSlice if mySubSubComm", "nDerivCols2, dim, dim) cacheSize = len(evalTree) # ------------------------------------------------------------------ if comm is not None", "of the i-th operation sequence product with respect to the k-th then j-th", "if wrtSlice1 is None else _slct.length(wrtSlice1) nDerivCols2 = self.Np if wrtSlice2 is None", "gate) # Allocate memory for the final result num_deriv_cols1 = self.Np if (wrtFilter1", "else len(wrtFilter1) num_deriv_cols2 = self.Np if (wrtFilter2 is None) else len(wrtFilter2) flattened_hprod =", "= int(_np.ceil(self.Np / blkSize)) # num blocks required to achieve desired average size", "(their prep labels must be the same) Parameters ---------- rholabel : Label The", "of deriv cols, then sub-trees (if available and necessary) if comm.Get_size() > nDerivCols1", "all else dGs2 = _np.swapaxes(_np.swapaxes(dGs2, 0, 1).reshape((nDerivCols2, nCircuits * dim**2)), 0, 1) hGs", "nDerivCols2), \"dGs1 must be pre-filtered!\" # Get: d2pr_drhos[i, j, rho_gpindices] = dot(E,dGs[i,j],drho/drhoP)) #", "is not None and comm.Get_size() > 1: #print(\"MPI: _compute_dproduct_cache called w/comm size %d\"", "a split tree to parallelize computation, since there are no memory savings from", "#note: gathering axis 1 of hProdCache, # dim=(cacheSize,nDerivCols1,nDerivCols2,dim,dim) return hProdCache # ------------------------------------------------------------------ if", "dpr/d(rho)_i = sum E_k prod_ki # dpr/d(E)_i = sum prod_il rho_l rholabel, elabel", "d2pr_drhos[:,:,J0+J] = squeeze(dot(E, dGs, drhoP),axis=(0,))[:,:,J] drho = rhoVec.deriv_wrt_params(rho_wrtFilter2) d2pr_drhos1 = _np.zeros((nCircuits, nDerivCols1, nDerivCols2))", "# Note: add transposes b/c spam terms only compute one triangle of hessian", "repeatedly # computed for each block of derivative columns if prMxToFill is not", "dot(Gs, rho)[i,j] # dp_dEs[i,J0+J] = sum_j dot(Gs, rho)[i,j,0] dEP[j,J] # dp_dEs[i,J0+J] = dot(squeeze(dot(Gs,", "- M == the length of the vectorized model - G == the", "deriv[i,j] holds the derivative of the i-th entry of the flattened product with", "Only returned when bScale == True, in which case the actual product ==", "initialization else: gate = self.sos.get_operation(opLabel).todense() nG = max(_nla.norm(gate), 1.0) prodCache[i] = gate /", "Returns ------- hessians : numpy array * if flat == False, an array", "bulk_fill_dprobs(self, mxToFill, evalTree, prMxToFill=None, clipTo=None, check=False, comm=None, wrtFilter=None, wrtBlockSize=None, profiler=None, gatherMemLimit=None): \"\"\" Compute", "final \"filtered\" set. # \"\"\" # PrepEffectFilter = _collections.namedtuple( # 'PrepEffectFilter', 'rho_local_slices rho_global_slices", "length of rowSlice) - B' is the number of parameter columns (the length", "clip if check: self._check(evalTree, prMxToFill, mxToFill, clipTo=clipTo) profiler.add_time(\"bulk_fill_dprobs: total\", tStart) profiler.add_count(\"bulk_fill_dprobs count\") profiler.mem_check(\"bulk_fill_dprobs:", "0, 3).reshape((vec_kl_size, vec_ij_size, dim, dim)) # axes = (model_parameter1, model_parameter2, model_element_row, model_element_col) def", "nBlks)) # pragma: no cover def calc_and_fill_blk(spamTuple, fInds, gInds, pslc1, pslc2, sumInto): \"\"\"", "evalTree, prMxToFill=None, dprMxToFill=None, hprMxToFill=None, clipTo=None): # compare with older slower version that should", "---------- simplified_circuits : list A list of Circuits or tuples of operation labels", "d2pr_dOps2[i,j,k] = sum_l,m E[0,l] hGs[i,j,k,l,m] rho[m,0] # d2pr_dOps2[i,j,k] = sum_l E[0,l] dot( dGs,", "vp[i] = dot( E, dot(Gs, rho))[0,i,0] * scaleVals[i] # vp = squeeze( dot(", "#( nCircuits, dim, dim ) #Same as in bulk_fill_hprobs (TODO consolidate?) #NOTE: filtering", "(final_product[i] = scaleValues[i] * prods[i]). \"\"\" prodCache, scaleCache = self._compute_product_cache(evalTree, comm) #use cached", "* dim # product cache mem += cache_size # scale cache mem +=", "wrtSlice2) else \\ self._compute_dproduct_cache(evalSubTree, prodCache, scaleCache, mySubComm, wrtSlice2) dGs1 = evalSubTree.final_view(dProdCache1, axis=0) dGs2", "savings from using a split tree. \"\"\" if profiler is None: profiler =", "def construct_evaltree(self, simplified_circuits, numSubtreeComms): \"\"\" Constructs an EvalTree object appropriate for this calculator.", "corresponds to an element of the product (els of # prod.flatten()). # #", "if dGs1 is dGs2 and wrtSlice1 == wrtSlice2: # TODO: better check for", "prodCache, dProdCache1, dProdCache2, scaleCache, comm, wrtSlice1, wrtSlice2) hGs = evalTree.final_view(hProdCache, axis=0) if bReturnDProbs12:", "dimension of a operation matrix (G x G operation matrices). and deriv[i,j,k] holds", "products (relatively little mem required) leftProds = [] G = _np.identity(dim); leftProds.append(G) for", "correctness, generating warnings when checks fail. Used for testing, and runs much slower", "the number of parameter rows (the length of rowSlice) - B' is the", "the shape of the returned derivative array (see below). wrtFilter1, wrtFilter2 : list", "hproduct cache computation\" \" *fewer* processors and *smaller* (sub-)tree\" \" (e.g. by splitting", "return a scaling factor (see below). comm : mpi4py.MPI.Comm, optional When not None,", "for to track timing and memory usage. gatherMemLimit : int, optional A memory", "bool, optional Affects the shape of the returned derivative array (see below). wrtFilter1,", "old_err = _np.seterr(over='ignore') scaleVals = _np.exp(scaleExps) # may overflow, but OK if infs", "wrtLen1 * wrtLen2 # hprobs & dprobs12 results mem += cache_size * nspam", "a matrix for each given (i,j) # noqa # d2prod/d(opLabel1)_kl*d(opLabel2)_ij = sum_{M s.t.", "comm : mpi4py.MPI.Comm, optional When not None, an MPI communicator for distributing the", "in reversed(revOpLabelList): G = _np.dot(self.sos.get_operation(opLabel).todense(), G) rightProdsT.append(_np.transpose(G)) # Allocate memory for the final", "= self.sos.get_operation(lOp).todense() ng = max(_nla.norm(opmx), 1.0) scaledGatesAndExps[lOp] = (opmx / ng, _np.log(ng)) gate,", "dGs1, dGs2, hGs, scaleVals, wrtSlice1=None, wrtSlice2=None): if self.evotype == \"statevec\": raise NotImplementedError(\"Unitary evolution", "def calc_and_fill_p(spamTuple, fInds, gInds, pslc1, pslc2, sumInto): \"\"\" Compute and fill result quantities", "In short, parallelization should be done at a higher level. \"\"\" dim =", "if flat == True, an array of shape S*N x M where -", "number of model parameters selected for the 1st and 2nd differentiation, respectively (i.e.", "mem += cache_size # scale vals elif fnName == \"bulk_fill_dprobs\": mem += cache_size", "= hprobs #Fill arrays self._fill_result_tuple((None, dprobs1, dprobs2, hprobs), evalTree, slice(None), slice(None), calc_and_fill) hProdCache", "post compute product\") def calc_and_fill(spamTuple, fInds, gInds, pslc1, pslc2, sumInto): \"\"\" Compute and", "(i.e. args `mxToFill`, `deriv1MxToFill`, and `deriv1MxToFill`), then: - `hprobs == mx[:,:,rowSlice,colSlice]` - `dprobs12", "but susceptible to overflow G = self.product(circuit, False) if self.evotype == \"statevec\": ps", "with respect to the k-th then j-th model parameters. derivs1, derivs2 : numpy", "# dp_drhos[:,J0+J] = squeeze(dot(E, Gs, drhoP),axis=(0,))[:,J] dp_drhos = _np.zeros((nCircuits, nDerivCols)) _fas(dp_drhos, [None, rho_gpindices],", "_np.zeros((dim**2, num_deriv_cols1, num_deriv_cols2), 'd') if _slct.length(gpindices1) > 0 and _slct.length(gpindices2) > 0: #", "dp_dAnyRho = _np.dot(E, Gs).squeeze(0) * scaleVals[:, None] # overflow OK d2pr_d2rhos = _np.zeros((nCircuits,", "dR = dProdCache[iLeft], dProdCache[iRight] dProdCache[i] = _np.dot(dL, R) + \\ _np.swapaxes(_np.dot(L, dR), 0,", "and deriv[i,j] holds the derivative of the i-th entry of the flattened product", "these groups. num_param2_groups : int The number of groups to divide the second-derivative", "= self.dim gate = self.sos.get_operation(opLabel) op_wrtFilter, gpindices = self._process_wrtFilter(wrtFilter, gate) # Allocate memory", "G(M-1) d2G(M)/(dkl*dij) G(M+1) ... GN ] # noqa # a matrix for each", "both in opsToVectorize1 and opsToVectorize2 we only compute d2(prod)/d(gl1)d(gl2) # and not d2(prod)/d(gl2)d(gl1)", "_np.zeros((cacheSize,) + deriv_shape) # This iteration **must** match that in bulk_evaltree # in", "to `bulk_fill_probs(...)`, but fills a 2D array with probability-derivatives for each \"final element\"", "\"\"\" old_err = _np.seterr(over='ignore') rho, E = self._rhoE_from_spamTuple(spamTuple) #if prMxToFill is not None:", "derivative columns at once self._fill_result_tuple((prMxToFill, mxToFill), evalSubTree, slice(None), slice(None), calc_and_fill) profiler.mem_check(\"bulk_fill_dprobs: post fill\")", "\" *fewer* processors and *smaller* (sub-)tree\" \" (e.g. by splitting tree beforehand), as", "%g\" % (_nla.norm(hprMxToFill[fInds]), _nla.norm(check_vhp), _nla.norm(hprMxToFill[fInds] - check_vhp))) # pragma: no cover def bulk_fill_probs(self,", "in range(len(self.effects))] # tmp_num_params = [_slct.length(s) for s in loc_e_slices] # tmp_offsets =", "gpindices = self._process_wrtFilter(wrtFilter, gate) # Allocate memory for the final result num_deriv_cols =", "# may overflow, but OK dpr_dEs = _np.zeros((1, self.Np)) derivWrtAnyEvec = scale *", "= A tensor B^T * vec( E(0,1) ) # In general: vec( A", "by iOpStr and iSpamLabel. d12 has the same dimensions as the Hessian, and", "of the vectorized model). probability : float only returned if returnPr == True.", "mem += cache_size * dim * dim # product cache # mem +=", "blk2Comm, blk_wrtSlice2) dGs2 = evalSubTree.final_view(dProdCache2, axis=0) hProdCache = self._compute_hproduct_cache( evalSubTree, prodCache, dProdCache1, dProdCache2,", "E_k [dprod/d(opLabel)_mn]_ki (and same for other diff order) # d2pr/d(E)_i d(opLabel)_mn = sum", "0, 3).reshape( (nDerivCols1, nDerivCols2, nCircuits * dim**2)), 2) # as above return (hGs,", "= {} for opLabel, gate in used_operations.items(): if gate.has_nonzero_hessian(): hop_dopLabels[opLabel] = gate.hessian_wrt_params( gate_wrtFilters1[opLabel],", "current spamTuple (this list has the SAME length as fInds). calc_and_fill_fn(spamTuple, fInds, gInds,", "hGs def _scaleExp(self, scaleExps): old_err = _np.seterr(over='ignore') scaleVals = _np.exp(scaleExps) # may overflow,", "..tools import mpitools as _mpit from ..tools import slicetools as _slct from ..tools.matrixtools", "differentiated with respect to when the *second* derivative is taken. If there are", "k-th model parameters. \"\"\" # LEXICOGRAPHICAL VS MATRIX ORDER # we do matrix", "relevant when prMxToFill is not None. Returns ------- hessian : numpy array a", "== True. * if flat == False, two arrays of shape S x", "evalTree.final_view(hProdCache, axis=0) #shape == ( len(circuit_list), nDerivCols1, nDerivCols2, dim, dim ), # hGs[i]", "of model parameters. evalTree : EvalTree given by a prior call to bulk_evaltree.", "is not None: _fas(prMxToFill, [fInds], self._probs_from_rhoE( rho, E, Gs[gInds], scaleVals[gInds]), add=sumInto) _fas(mxToFill, [fInds,", "= _np.seterr(over='ignore') prod, scale = self.product(circuit, True) dprod_dOps = self.dproduct(circuit) dpr_dOps = _np.empty((1,", "[] G = _np.identity(dim); leftProds.append(G) for opLabel in revOpLabelList: G = _np.dot(G, self.sos.get_operation(opLabel).todense())", "matrices) and hessians[i,j,k,l,m] holds the derivative of the (l,m)-th entry of the i-th", "\\ _np.swapaxes(_np.dot(L, dR), 0, 1) # dot(dS, T) + dot(S, dT) profiler.add_time(\"compute_dproduct_cache: dots\",", "elabel = spamTuple rhoVec = self.sos.get_prep(rholabel) # distinct from rho,E b/c rho,E are", "dp_dEs[i, E_gpindices] = dot(transpose(dE/dEP),Gs[i],rho)) # dp_dEs[i,J0+J] = sum_lj dEPT[J,j] Gs[i,j,l] rho[l,0] # dp_dEs[i,J0+J]", "scaleVals[i] # vp[i] = dot( E, dot(Gs, rho))[0,i,0] * scaleVals[i] # vp =", "nDerivCols2) flattened_d2prod[:, inds1, inds2] += xv if flat: return flattened_d2prod # axes =", "as the Hessian, and turns out to be useful when computing the Hessian", "), axis=(0,3)) old_err2 = _np.seterr(invalid='ignore', over='ignore') dp_dOps = _np.squeeze(_np.dot(E, _np.dot(dGs, rho)), axis=(0, 3))", "* if flat == True, a N x M array, where: - N", "# # Note: ignoring L == M terms assumes that d^2 G/(dij)^2 ==", "of gate parameters if wrtSlice1 == wrtSlice2: # Note: this doesn't involve gate", "dProdCache[i] = _np.zeros(deriv_shape) else: #doperation = self.dproduct( (opLabel,) , wrtFilter=wrtIndices) doperation = self.doperation(opLabel,", "dG(L)/dij ) ] # noqa # + sum{ L < M} [ G1", "row-distribution (Deriv1) #note: gathering axis 1 of hProdCache, # dim=(cacheSize,nDerivCols1,nDerivCols2,dim,dim) return hProdCache #", "dim, simplified_op_server, paramvec): \"\"\" Construct a new MatrixForwardSimulator object. Parameters ---------- dim :", "== as above, and deriv[i,j] holds the derivative of the (i % G^2)-th", "\"statevec\": raise NotImplementedError(\"Unitary evolution not fully supported yet!\") #Compute probability and save in", "== the number of operation sequences - G == the linear dimension of", "== \"bulk_hproduct\": # mem += cache_size * num_params**2 * dim * dim #", "derivs1, derivs2 : numpy array Only returned if bReturnDProdsAndProds == True. * if", "must be pre-filtered!\" #Compute d(probability)/dOps and save in return list (now have G,dG", "is at most *linear* in each of the gate parameters. If this is", "by wrtFilter1 and wrtFilter2). clipTo : 2-tuple, optional (min,max) to clip return value", "= dProdCache1; dGs2 = dGs1 else: dProdCache2 = self._compute_dproduct_cache( evalSubTree, prodCache, scaleCache, blk2Comm,", "= dop_dopLabel1[opLabel1].shape[1] if nDerivCols1 == 0: continue for l, opLabel2 in enumerate(revOpLabelList): inds2", "as numpy.flatten), - S,M == as above, and hessians[i,j,k] holds the derivative of", "or float, optional The maximum number of derivative columns to compute *products* for", "None prodCache = scaleCache = None #Fill product cache info (not requiring row", "MPI communicator for distributing the computation across multiple processors. Distribution is first done", "the computation across multiple processors. Distribution is first done over the set of", "else None for i, opLabel in zip(evalTree.get_init_indices(), evalTree.get_init_labels()): if opLabel == \"\": #", "except # in compliance with the License. You may obtain a copy of", "return a scaling factor (see below). Returns ------- product : numpy array The", "num_deriv_cols2 = self.Np if (wrtFilter2 is None) else len(wrtFilter2) flattened_hprod = _np.zeros((dim**2, num_deriv_cols1,", "(now have G,dG => product, dprod_dOps) # prod, dprod_dOps = G,dG # dp_dOps[i,j]", "slice(tmp_offsets[i],tmp_offsets[i+1]) # for i in range(len(self.effects)) ] # # return PrepEffectFilter(rho_local_slices=loc_rho_slices, # rho_global_slices=global_rho_slices,", "MATRIX ORDER else: G = H old_err = _np.seterr(over='ignore') scale = _np.exp(scale_exp) _np.seterr(**old_err)", "deriv[i,j,k] holds the derivative of the (j,k)-th entry of the product with respect", "product cache # mem += cache_size # scale cache # mem += cache_size", "else: # no scaling -- faster but susceptible to overflow G = self.product(circuit,", "of the entire # operation sequence with respect to only those two gates'", "(_np.isinf(dGs)).nonzero()[0] ) == 0 ) #dGs = clip(dGs,-1e300,1e300) _np.seterr(**old_err) if flat: dGs =", "= sum_j dEP[j,J] dot(Gs, rho)[i,j] # dp_dEs[i,J0+J] = sum_j dot(Gs, rho)[i,j,0] dEP[j,J] #", "if opLabel == \"\": # special case of empty label == no gate", "= dot( squeeze(dot(dGs, rho),axis=(3,)), dEP)[i,j,J] # d2pr_dEs[:,:,J0+J] = dot( squeeze(dot(dGs, rho),axis=(3,)), dEP)[:,:,J] d2pr_dEs1", "check: self._check(evalTree, prMxToFill, deriv1MxToFill, mxToFill, clipTo) def bulk_hprobs_by_block(self, evalTree, wrtSlicesList, bReturnDProbs12=False, comm=None): \"\"\"", "[slice(self.rho_offset[i],self.rho_offset[i+1]) for i in range(len(self.preps)) ] # global_e_slices = [slice(self.e_offset[i],self.e_offset[i+1]) for i in", "+ sum{ L < M} [ G1 ... G(L-1) tensor # noqa #", "operation sequences (i.e. evalTree.num_final_strings()), - B is the number of parameter rows (the", "spamTuple : (rho_label, simplified_effect_label) Specifies the prep and POVM effect used to compute", "comm_blkSize else: blkSize = None # wrtFilter dictates block if blkSize is None:", "single object (gate or spam vec) \"\"\" #Create per-gate with-respect-to parameter filters, used", "[0, self.sos.get_effect(elabel).gpindices, self.sos.get_effect(elabel).gpindices], _np.tensordot(derivWrtAnyEvec, self.sos.get_effect(elabel).hessian_wrt_params(), (1, 0))) # _np.einsum('ij,jkl->ikl',derivWrtAnyEvec,self.sos.get_effect(elabel).hessian_wrt_params()) else: d2pr_d2Es = 0", "the final result num_deriv_cols = self.Np if (wrtFilter is None) else len(wrtFilter) flattened_dprod", "operation sequence product with respect to the j-th model parameter. products : numpy", "-self.rho_offset[i]) for i in range(len(self.preps))] # tmp_num_params = [_slct.length(s) for s in loc_rho_slices]", "[slice(None,None)]*len(self.effects) # global_rho_slices = [slice(self.rho_offset[i],self.rho_offset[i+1]) for i in range(len(self.preps)) ] # global_e_slices =", "_np.zeros((1, self.Np)) _fas(dpr_drhos, [0, self.sos.get_prep(rholabel).gpindices], _np.dot(derivWrtAnyRhovec, rhoVec.deriv_wrt_params())) # may overflow, but OK dpr_dEs", "G(L+1) ... G(M-1) tensor (G(M+1) ... GN)^T vec( dG(M)/dkl ) ) )^T vec(", "* scale) _np.seterr(**old_err) else: # no scaling -- faster but susceptible to overflow", "not None: myHessianSlice1 = _slct.shift(myDeriv1ColSlice, wrtSlice1.start) else: myHessianSlice1 = myDeriv1ColSlice #print(\"MPI: _compute_hproduct_cache over", "None] # overflow OK devec = EVec.deriv_wrt_params(E_wrtFilter2) _fas(d2pr_dErhos2, [None, E_gpindices2, rho_gpindices1], _np.swapaxes(_np.dot(_np.transpose(devec), dp_dAnyE),", "# an estimate - could compute? wrtLen1 = (self.Np + np1 - 1)", "for given arguments \"\"\" old_err = _np.seterr(over='ignore') rho, E = self._rhoE_from_spamTuple(spamTuple) if prMxToFill", "the outcome probabilities for an entire tree of operation sequences. This routine fills", "The size of the evaluation tree that will be passed to the functions", "derivative cache info tm = _time.time() dProdCache = self._compute_dproduct_cache(evalSubTree, prodCache, scaleCache, mySubComm, wrtSlice,", "%d products\" % (cnt, len(evalTree)) nanOrInfCacheIndices = (~_np.isfinite(prodCache)).nonzero()[0] # may be duplicates (a", "myHessianSlice1, wrtSlice2) # pass None as comm, *not* mySubComm (this is ok, see", "derivatives are non-zero when the spam vectors have # a more than linear", "parameters and fill the appropriate # columns of flattened_dprod. uniqueOpLabels = sorted(list(set(revOpLabelList))) for", "import DummyProfiler as _DummyProfiler from .label import Label as _Label from .matrixevaltree import", "None else _slct.length(wrtSlice2) #flt1 = self._get_filter_info(wrtSlices1) #flt2 = self._get_filter_info(wrtSlices2) # GATE DERIVS (assume", "preparation label. elabels : list A list of :class:`Label` objects giving the *simplified*", "rho_gpindices] = dot(E,Gs[i],drho/drhoP) # dp_drhos[i,J0+J] = sum_kl E[0,k] Gs[i,k,l] drhoP[l,J] # dp_drhos[i,J0+J] =", "if it isn't specified if wrtFilter is None: blkSize = wrtBlockSize # could", "we hGs[_np.isnan(hGs)] = 0 # assume the zero hessian value trumps since we've", "gate) # Allocate memory for the final result num_deriv_cols = self.Np if (wrtFilter", "it. # Use comm only for speeding up the calcs of the given", "not None: # _fas(prMxToFill, [fInds], # self._probs_from_rhoE(rho, E, Gs[gInds], scaleVals[gInds]), add=sumInto) if deriv1MxToFill", "single- or zero-operation sequences are zero. hProdCache[i] = _np.zeros(hessn_shape) else: hoperation = self.hoperation(opLabel,", "relevant_gpindices.append(ii) obj_wrtFilter.append(list(gpindices).index(i)) relevant_gpindices = _np.array(relevant_gpindices, _np.int64) if len(relevant_gpindices) == 1: #Don't return a", "subtrees of the created tree. This aids in the tree construction by giving", "respect to when the *second* derivative is taken. If there are more processors", "= sum_l,m E[0,l] hGs[i,j,k,l,m] rho[m,0] # d2pr_dOps2[i,j,k] = sum_l E[0,l] dot( dGs, rho", "via the yet-to-be-defined local variables # wrtSlice1 and wrtSlice2, of the parent-function scope.", "GATE DERIVS (assume hGs is already sized/filtered) ------------------- assert(hGs.shape[1] == nDerivCols1), \"hGs must", "#print(\"MPI: _compute_dproduct_cache begin: %d deriv cols\" % nDerivCols) if comm is not None", "computing the Hessian of functions of the probabilities. comm : mpi4py.MPI.Comm, optional When", "axis=0) #( nCircuits, dim, dim ) #Same as in bulk_fill_hprobs (TODO consolidate?) #NOTE:", "hessian[i,j,k] holds the derivative of the i-th entry of the flattened product with", "returnPr == True. \"\"\" if self.evotype == \"statevec\": raise NotImplementedError(\"Unitary evolution not fully", "None: _np.clip(prMxToFill, clipTo[0], clipTo[1], out=prMxToFill) # in-place clip if check: self._check(evalTree, prMxToFill, deriv1MxToFill,", "inds1 = gpindices1[opLabel1] nDerivCols1 = dop_dopLabel1[opLabel1].shape[1] if nDerivCols1 == 0: continue for l,", "be pre-filtered!\" #Compute d2(probability)/dGates2 and save in return list # d2pr_dOps2[i,j,k] = sum_l,m", "= _time.time() if profiler is None: profiler = _dummy_profiler if wrtFilter is not", "#, gatherMemLimit) #gather over row-distribution (Deriv1) #note: gathering axis 1 of hProdCache, #", "old_err = _np.seterr(over='ignore') rho, E = self._rhoE_from_spamTuple(spamTuple) if prMxToFill is not None: _fas(prMxToFill,", "True) if returnPr: p = _np.dot(E, _np.dot(prod, rho)) * scale # may generate", "overflow OK # get d2pr_drhos where gate derivatives are wrt the 2nd set", "is the derivative of the probability w.r.t. the k-th then the j-th model", "(wrtFilter1 is None) else len(wrtFilter1) num_deriv_cols2 = self.Np if (wrtFilter2 is None) else", "# evotype == \"densitymx\" ps = _np.real(_np.dot(Es, _np.dot(G, rho))) ps = ps.flatten() if", "blocks (subsets) of the parameters being differentiated with respect to (see wrtBlockSize). wrtFilter", "(G x G operation matrices). scaleValues : numpy array Only returned when bScale", "(skip over the zero and single-gate-strings) for i in evalTree.get_evaluation_order(): # combine iLeft", "# dp_dEs[:,J0+J] = dot(squeeze(dot(Gs, rho),axis=(2,)), dEP)[:,J] dp_dEs = _np.zeros((nCircuits, nDerivCols)) # may overflow,", "check=False, comm=None, wrtFilter=None, wrtBlockSize=None, profiler=None, gatherMemLimit=None): \"\"\" Compute the outcome probability-derivatives for an", "split tree (since there's no good way to reconstruct the parent tree's *non-final*", "procs, # as we assume the user has already done any such distribution", "#print \"bulk_product DEBUG: %d rescalings out of %d products\" % (cnt, len(evalTree)) nanOrInfCacheIndices", "derivative of a length-1 (single-gate) sequence \"\"\" dim = self.dim gate = self.sos.get_operation(opLabel)", "flattened operation sequence product with respect to the j-th model parameter. products :", "comm=None, wrtSlice1=None, wrtSlice2=None): \"\"\" Computes a tree of product 2nd derivatives in a", ") # In general: vec( A * X * B ) = A", "2, 1)) #Note: these 2nd derivatives are non-zero when the spam vectors have", "the License at # http://www.apache.org/licenses/LICENSE-2.0 or in the LICENSE file in the root", "scaleCache = self._compute_product_cache(evalTree, comm) scaleVals = self._scaleExp(evalTree.final_view(scaleCache)) Gs = evalTree.final_view(prodCache, axis=0) #( nCircuits,", "EVec.gpindices], _np.dot(derivWrtAnyEvec, EVec.deriv_wrt_params())) d2pr_dErhos = _np.zeros((1, self.Np, self.Np)) derivWrtAnyEvec = scale * _np.dot(prod,", "these are SPAMVecs nCircuits = Gs.shape[0] rho_wrtFilter, rho_gpindices = self._process_wrtFilter(wrtSlice, self.sos.get_prep(rholabel)) E_wrtFilter, E_gpindices", "len(circuit_list), dim, dim ), # Gs[i] is product for i-th operation sequence dGs", "# dGs[i] is dprod_dOps for ith string if not bScale: old_err = _np.seterr(over='ignore',", "element of the product (els of # prod.flatten()). # # Note: if gate", "spamTuple rho, E = self._rhoE_from_spamTuple(spamTuple) rhoVec = self.sos.get_prep(rholabel) # distinct from rho,E b/c", "op uses numpy.flatten rows are kept contiguous, so the first identity below is", "_np.zeros((1, self.Np, self.Np)) derivWrtAnyEvec = scale * _np.dot(prod, rhoVec.deriv_wrt_params()) # may generate overflow,", "Set this to non-None to reduce amount of intermediate memory required. profiler :", "model objects to perform product and derivatives-of-product calculations. This is contained in a", "and wrtSlice2.start is not None: myHessianSlice2 = _slct.shift(myDeriv2ColSlice, wrtSlice2.start) else: myHessianSlice2 = myDeriv2ColSlice", "compute the bulk operation on. prMxToFill : numpy array, optional when not None,", "not None. bUseScaling : bool, optional Whether to use a post-scaled product internally.", "= 0 rholabel, elabel = spamTuple rho, E = self._rhoE_from_spamTuple(spamTuple) rhoVec = self.sos.get_prep(rholabel)", "mem = 0 for fnName in subcalls: if fnName == \"bulk_fill_probs\": mem +=", "obj_wrtFilter, relevant_gpindices #Vectorizing Identities. (Vectorization) # Note when vectorizing op uses numpy.flatten rows", "fill blk\") dProdCache = dGs = None # free mem #gather results tm", "to these fundamental operations. \"\"\" def __init__(self, dim, simplified_op_server, paramvec): \"\"\" Construct a", "OK) ps = _np.real(_np.dot(Es, _np.dot(G, rho)) * scale) _np.seterr(**old_err) else: # no scaling", "matrix (G x G operation matrices). scaleValues : numpy array Only returned when", "= [slice(None,None)]*len(self.preps) # loc_e_slices = [slice(None,None)]*len(self.effects) # global_rho_slices = [slice(self.rho_offset[i],self.rho_offset[i+1]) for i in", "Hessian, so that # if gl1 and gl2 are both in opsToVectorize1 and", "when iterated, yields the 3-tuple `(rowSlice, colSlice, hprobs)` or `(rowSlice, colSlice, dprobs12)` (the", "dependence on their parameters. if self.sos.get_prep(rholabel).has_nonzero_hessian(): dp_dAnyRho = _np.dot(E, Gs).squeeze(0) * scaleVals[:, None]", "in bulk_fill_hprobs (TODO consolidate?) #NOTE: filtering is done via the yet-to-be-defined local variables", "else: dProdCache2 = self._compute_dproduct_cache( evalTree, prodCache, scaleCache, comm, wrtSlice2) dGs2 = evalTree.final_view(dProdCache2, axis=0)", "block_wrtSlice = pslc1 _fas(mxToFill, [fInds, pslc1], self._dprobs_from_rhoE( spamTuple, rho, E, Gs[gInds], dGs[gInds], scaleVals[gInds],", "(a list, not a set) # since all scaled gates start with norm", "3) * scaleVals, 0, 3) # convert nans to zero, as these occur", "# wrtSlice1 and wrtSlice2, of the parent-function scope. This use of # closures", "returnDeriv: # same as in dpr(...) dpr_drhos = _np.zeros((1, self.Np)) derivWrtAnyRhovec = scale", "mySubComm (this is ok, see \"if\" condition above) _mpit.gather_slices(deriv1Slices, deriv1Owners, hProdCache, [], 1,", "support for \"custom\" spamlabels... # This calculator uses the convention that rho has", "allocated within # the generator and yielded, *not* allocated by the user. mem", "dp_dAnyE, self.sos.get_effect(elabel).hessian_wrt_params( # E_wrtFilter1, E_wrtFilter2)) else: d2pr_d2Es = 0 # END SPAM DERIVS", "label indexed by iOpStr and iSpamLabel. d12 has the same dimensions as the", "GN , a matrix # noqa # dprod/d(opLabel)_ij = sum_{L s.t. G(L) ==", "Circuit or tuple of operation labels The sequence of operation labels. bScale :", "occurrence, and doesn't merit a warning # ------------------------------------------------------------------ if evalTree.is_split(): _warnings.warn(\"Ignoring tree splitting", "prMxToFill is computed fully on each inner loop *iteration*!) #collect/gather results subtreeElementIndices =", "self._compute_dproduct_cache( evalTree, prodCache, scaleCache, comm, wrtSlice1) dGs1 = evalTree.final_view(dProdCache1, axis=0) last_wrtSlice1 = wrtSlice1", "\"starting\" gate prods[(i, i - 1)] = ident # product of no gates", "if infs occur here _np.seterr(**old_err) if bReturnProds: Gs = evalTree.final_view(prodCache, axis=0) #shape ==", "dpr/dx -> d|pr|^2/dx = d(pr*pr.C)/dx = dpr/dx*pr.C + pr*dpr/dx.C # = 2 Re(dpr/dx*pr.C)", "it by the first two arguments), and in general only a specified slice", "_np.dot(Gs, drho) * scaleVals[:, None, None] # overflow OK devec = EVec.deriv_wrt_params(E_wrtFilter1) _fas(d2pr_dErhos1,", "and dProdCache[i].min() > -DSMALL: _warnings.warn(\"Would have scaled dProd but now will not alter", "faster but susceptible to overflow G = self.product(circuit, False) if self.evotype == \"statevec\":", "blkOwners, mxToFill, [felInds], 1, mySubComm, gatherMemLimit) #note: gathering axis 1 of mxToFill[felInds], dim=(ks,M)", "# pragma: no cover # allocate final result memory hProdCache = _np.zeros((cacheSize,) +", "\"gather\" operations performed as a part of MPI processor syncronization. Returns ------- None", "E_wrtFilter2), (1, 0))) # _np.einsum('ij,jkl->ikl', dp_dAnyE, self.sos.get_effect(elabel).hessian_wrt_params( # E_wrtFilter1, E_wrtFilter2)) else: d2pr_d2Es =", "when the original list of `Circuits` was simplified. Parameters ---------- mxToFill : numpy", "gate-only sequences along with a mapping of final elements (i.e. probabilities) to gate-only", "elabels : list A list of :class:`Label` objects giving the *simplified* effect labels.", "nDerivCols2)) _fas(d2pr_d2Es, [None, E_gpindices1, E_gpindices2], _np.tensordot(dp_dAnyE, self.sos.get_effect(elabel).hessian_wrt_params( E_wrtFilter1, E_wrtFilter2), (1, 0))) # _np.einsum('ij,jkl->ikl',", "linear cache space. Will use derivative rows and columns and then (as needed)", "\"hGs must be pre-filtered!\" #Compute d2(probability)/dGates2 and save in return list # d2pr_dOps2[i,j,k]", "= _np.dot(sL, sR); scaleCache[i] += _np.log(nL) + _np.log(nR) #print \"bulk_product DEBUG: %d rescalings", "\"\"\" Helper function for doperation and hoperation below: pulls out pieces of a", "bytes. \"\"\" #Note: num_final_strs is irrelevant here b/c cachesize is always >= num_final_strs", "evalSubTree.final_view(dProdCache1, axis=0) for iBlk2 in myBlk2Indices: blk_wrtSlice2 = blocks2[iBlk2] if blk_wrtSlice1 == blk_wrtSlice2:", "None: _mpit.gather_indices(subtreeElementIndices, subTreeOwners, prMxToFill, [], 0, comm) #note: pass prMxToFill, dim=(KS,), so gather", "= evalTree.final_view(dProdCache, axis=0) #shape == ( len(circuit_list), nDerivCols, dim, dim ), # dGs[i]", "by a zero hessian value (see below) hGs[_np.isnan(hGs)] = 0 _np.seterr(**old_err) if flat:", "by numpy.flatten), - S,M == as above, and deriv[i,j] holds the derivative of", "HSMALL and hProdCache[i].min() > -HSMALL: _warnings.warn(\"hProd is small (oh well!).\") return hProdCache ##", "as _nla import time as _time import itertools as _itertools import collections as", "blocks1[iBlk1] wrtSlice2 = blocks2[iBlk2] self._fill_result_tuple((prMxToFill, deriv1MxToFill, deriv2MxToFill, mxToFill), evalSubTree, blocks1[iBlk1], blocks2[iBlk2], calc_and_fill) hProdCache", "sR); scaleCache[i] += _np.log(nL) + _np.log(nR) #print \"bulk_product DEBUG: %d rescalings out of", "\\ _mpit.distribute_slice(allDeriv2ColSlice, mySubComm) # Get slice into entire range of model params (see", "= slice(0, 0) # slice that results in a zero dimension else: obj_wrtFilter", "num_e_params=_slct.length(wrtSlices['effects'])) # else: # loc_rho_slices = [slice(None,None)]*len(self.preps) # loc_e_slices = [slice(None,None)]*len(self.effects) # global_rho_slices", "scaling factor (see below). comm : mpi4py.MPI.Comm, optional When not None, an MPI", "if needed) subtrees = evalTree.get_sub_trees() mySubTreeIndices, subTreeOwners, mySubComm = evalTree.distribute(comm) #if comm is", "= dProdCache2 = dGs2 = None # free mem dProdCache1 = dGs1 =", "value due to scaleVals being inf and dot-prod being 0. In # this", "None: check_vdp = _np.concatenate( [self.dpr(spamTuple, circuit, False, clipTo) for circuit in circuit_list], axis=0)", "the tree was split, but this is was # incorrect (and luckily never", "LinearOperator, SPAMVec, and SPAMVec objects, respectively. Must be *ordered* dictionaries to specify a", "gate) op_wrtFilter2, gpindices2 = self._process_wrtFilter(wrtFilter2, gate) # Allocate memory for the final result", "4) # convert nans to zero, as these occur b/c an inf scaleVal", "= _np.dot(G,self[lOp]) # product of gates, starting with G0 # nG = norm(G);", "# e_global_slices=global_e_slices, # num_rho_params=_slct.length(wrtSlices['preps']), # num_e_params=_slct.length(wrtSlices['effects'])) # else: # loc_rho_slices = [slice(None,None)]*len(self.preps) #", "derivatives (see below). bScale : bool, optional When True, return a scaling factor", "routine fills in `mxToFill`, which must have length equal to the number of", "which gate parameters to include in the derivative. Each element is an index", "prod_col) return _np.swapaxes(flattened_dprod, 0, 1).reshape((num_deriv_cols, dim, dim)) def hoperation(self, opLabel, flat=False, wrtFilter1=None, wrtFilter2=None):", "None) else len(wrtFilter1) num_deriv_cols2 = self.Np if (wrtFilter2 is None) else len(wrtFilter2) flattened_d2prod", "elabels, circuit, clipTo, bUseScaling=False, time=None): \"\"\" Compute probabilities of a multiple \"outcomes\" (spam-tuples)", "use of available processors is used as the final block size. This argument", "scaled product of the operation matrices. scale : float Only returned when bScale", "dim # product cache # mem += cache_size # scale cache # mem", "product == product * scale. The purpose of this is to allow a", "_mpit.gather_indices(subtreeElementIndices, subTreeOwners, deriv2MxToFill, [], 0, comm, gatherMemLimit) if prMxToFill is not None: _mpit.gather_indices(subtreeElementIndices,", "_np.dot(derivWrtAnyEvec, EVec.deriv_wrt_params())) dpr = dpr_drhos + dpr_dEs + dpr_dOps d2pr_drhos = _np.zeros((1, self.Np,", "comm) scaleVals = self._scaleExp(evalTree.final_view(scaleCache)) Gs = evalTree.final_view(prodCache, axis=0) #( nCircuits, dim, dim )", "sum{ L < M} [ G1 ... G(L-1) tensor # noqa # (", "general: vec( A * X * B ) = A tensor B^T *", "the operation sequences. Parameters ---------- spam_label_rows : dictionary a dictionary with keys ==", "numpy array of derivatives of the probability w.r.t. each model parameter. probability :", "sequences when a *split* evalTree is given, otherwise no parallelization is performed. Returns", "make sense to iterate through the self.operations.keys() as in # dproduct(...) and find", "since all scaled gates start with norm <= 1, products should all have", "vector of the Model. autogator : AutoGator An auto-gator object that may be", "3) # may overflow or get nans (invalid), but ok dGs2 = _np.swapaxes(_np.swapaxes(dGs2,", "else: myHessianSlice1 = myDeriv1ColSlice #print(\"MPI: _compute_hproduct_cache over %d cols (rank %d computing %s)\"", "(assume dGs is already sized/filtered) ------------------- assert(dGs.shape[1] == nDerivCols), \"dGs must be pre-filtered!\"", "% (mxToFill.nbytes / (1024.0**3))) ## memory profiling of python objects (never seemed very", "parallelization over the parameter groups. num_param1_groups : int The number of groups to", "(wrtSlice1 == wrtSlice2) else \\ self._compute_dproduct_cache(evalTree, prodCache, scaleCache, comm, wrtSlice2) hProdCache = self._compute_hproduct_cache(evalTree,", "do anything with it! #_warnings.warn(\"More processors than can be used for product computation\")", "a list appropriate for it. # Use comm only for speeding up the", "or get nans (invalid), but ok hGs = _np.swapaxes(_np.swapaxes(hGs, 0, 4) * scaleVals,", "------- None \"\"\" tStart = _time.time() if profiler is None: profiler = _dummy_profiler", "not None) and (mySubComm.Get_size() > 1): comm_blkSize = self.Np / mySubComm.Get_size() blkSize1 =", "# d2pr_dOps2[i,j,k] = sum_l,m E[0,l] hGs[i,j,k,l,m] rho[m,0] # d2pr_dOps2[i,j,k] = sum_l E[0,l] dot(", "result quantities blocks for given arguments \"\"\" tm = _time.time() old_err = _np.seterr(over='ignore')", "not None: assert(wrtBlockSize1 is None and wrtBlockSize2 is None) # Cannot specify both", "dot-prod being 0. In # this case set to zero since we can't", "have norm <= 1 assert(len(nanOrInfCacheIndices) == 0) return prodCache, scaleCache def _compute_dproduct_cache(self, evalTree,", "_mpit.distribute_indices(list(range(nBlks2)), blk1Comm) if blk2Comm is not None: _warnings.warn(\"Note: more CPUs(%d)\" % mySubComm.Get_size() +", "to which strings and outcomes, you'll need the mappings generated when the original", "prMxToFill is not None: _fas(prMxToFill, [fInds], self._probs_from_rhoE( rho, E, Gs[gInds], scaleVals[gInds]), add=sumInto) _fas(mxToFill,", "integers specifying which gate parameters to differentiate with respect to in the first", "= self.dim gate = self.sos.get_operation(opLabel) op_wrtFilter1, gpindices1 = self._process_wrtFilter(wrtFilter1, gate) op_wrtFilter2, gpindices2 =", "int(_np.ceil(self.Np / blkSize2)) # num blocks required to achieve desired average size ==", "opLabel: gate.deriv_wrt_params(gate_wrtFilters2[opLabel]) for opLabel, gate in used_operations.items()} #Finally, cache any nonzero gate hessians", "model params (see above) if wrtSlice2 is not None and wrtSlice2.start is not", "gate.deriv_wrt_params(op_wrtFilter)) # (dim**2, nParams[opLabel]) if _slct.length(gpindices) > 0: # works for arrays too", "M x M array, where M is the number of model parameters. Parameters", "local variables # wrtSlice1 and wrtSlice2, of the parent-function scope. This use of", "appropriate columns of flattened_dprod. #gate = self.sos.get_operation[opLabel] UNNEEDED (I think) _fas(flattened_dprod, [None, gpindices],", "dpr_drhos = _np.zeros((1, self.Np)) _fas(dpr_drhos, [0, self.sos.get_prep(rholabel).gpindices], _np.dot(derivWrtAnyRhovec, rhoVec.deriv_wrt_params())) # may overflow, but", "optional A profiler object used for to track timing and memory usage. gatherMemLimit", "is None) \\ else min(comm_blkSize, blkSize2) # override with smaller comm_blkSize else: blkSize1", "profiler.add_time(\"compute_dproduct_cache: dots\", tm) profiler.add_count(\"compute_dproduct_cache: dots\") scale = scaleCache[i] - (scaleCache[iLeft] + scaleCache[iRight]) if", "= _np.array([self.prs(spamTuple[0], [spamTuple[1]], circuit, clipTo, False)[0] for circuit in circuit_list]) if _nla.norm(prMxToFill[fInds] -", "derivatives of the probabilities generated by a each gate sequence given by evalTree", "[fInds], # self._probs_from_rhoE(rho, E, Gs[gInds], scaleVals[gInds]), add=sumInto) if deriv1MxToFill is not None: _fas(deriv1MxToFill,", "------------------------------------------------------------------ if evalTree.is_split(): _warnings.warn(\"Ignoring tree splitting in product cache calc.\") cacheSize = len(evalTree)", "i-th model parameter. * if flat == True, a N x M array,", "overflow, but OK # Get: dp_dEs[i, E_gpindices] = dot(transpose(dE/dEP),Gs[i],rho)) # dp_dEs[i,J0+J] = sum_lj", "(if given) is possible. wrtFilter : list of ints, optional If not None,", "_np.transpose(_np.dot(L, hR), (1, 2, 0, 3)) scale = scaleCache[i] - (scaleCache[iLeft] + scaleCache[iRight])", "G(L-1))^T vec( dG(M)/dkl ) ) # noqa # tensor (G(L+1) ... GN)^T vec(", "of colSlice) If `mx`, `dp1`, and `dp2` are the outputs of :func:`bulk_fill_hprobs` (i.e.", "to gate-only sequence and prep/effect pairs. The evaluation tree organizes how to efficiently", "comm.Get_rank(), str(myDerivColIndices))) if mySubComm is not None and mySubComm.Get_size() > 1: _warnings.warn(\"Too many", ": Circuit or tuple A tuple-like object of *simplified* gates (e.g. may include", "wrtBlockSize2, wrtBlockSize2 : int or float, optional The maximum number of 1st (row)", "optional If True, perform extra checks within code to verify correctness, generating warnings", "#shape == ( len(circuit_list), dim, dim ), # Gs[i] is product for i-th", "the probability w.r.t. each model parameter. probability : float only returned if returnPr", "== wrtSlice2: # TODO: better check for equivalence: maybe let dGs2 be None?", "dprMxToFill=None, hprMxToFill=None, clipTo=None): # compare with older slower version that should do the", "None: _mpit.gather_slices(blocks2, blk2Owners, deriv2MxToFill, [felInds], 1, blk1Comm, gatherMemLimit) #Note: deriv2MxToFill gets computed on", "(wrtSlice is None) else wrtSlice _, myDerivColSlice, _, mySubComm = \\ _mpit.distribute_slice(allDerivColSlice, comm)", "# isn't currently needed. N = len(revOpLabelList) for m, opLabel1 in enumerate(revOpLabelList): inds1", "profiler.mem_check(\"bulk_fill_dprobs: post fill\") dProdCache = dGs = None # free mem else: #", "as comm, *not* mySubSubComm, since we can't do any further parallelization _mpit.gather_slices(deriv2Slices, deriv2Owners,", "Gs), rhoVec.deriv_wrt_params(rho_wrtFilter)), axis=(0,)) * scaleVals[:, None]) # may overflow, but OK # Get:", "2, 1)) # Get: d2pr_dEs[i, j, E_gpindices] = dot(transpose(dE/dEP),dGs[i,j],rho) # d2pr_dEs[i,j,J0+J] = sum_kl", "wrtFilter=None, wrtBlockSize=None, profiler=None, gatherMemLimit=None): \"\"\" Compute the outcome probability-derivatives for an entire tree", "use of # closures seems confusing and we should do something else LATER.", "scaleVals[:, None, None] # overflow OK devec = EVec.deriv_wrt_params(E_wrtFilter1) _fas(d2pr_dEs2, [None, None, E_gpindices1],", "dProdCache2 = dProdCache1; dGs2 = dGs1 else: dProdCache2 = self._compute_dproduct_cache( evalTree, prodCache, scaleCache,", "comm=None): \"\"\" Compute the outcome probabilities for an entire tree of operation sequences.", "(row) and second (col) derivative operations, respectively. Each element is an index into", "= vec( mx w/ col_i = A[col0] * B[0,1] ) = B^T tensor", "pass prMxToFill, dim=(KS,), so gather prMxToFill[felInds] (axis=0) profiler.add_time(\"MPI IPC\", tm) profiler.mem_check(\"bulk_fill_dprobs: post gather", "else: obj_wrtFilter = None relevant_gpindices = obj.gpindices return obj_wrtFilter, relevant_gpindices #Vectorizing Identities. (Vectorization)", "column corresponds to a (opLabel,i,j) tuple and each row corresponds to an element", "make use of in \" \" _compute_hproduct_cache.\") #TODO: remove: not needed now that", "dim, dim ) #Same as in bulk_fill_hprobs (TODO consolidate?) #NOTE: filtering is done", "wrtIndices1 = _slct.indices(wrtSlice1) if (wrtSlice1 is not None) else None wrtIndices2 = _slct.indices(wrtSlice2)", "+ dp_dEs + dp_dOps return sub_vdp #def _get_filter_info(self, wrtSlices): # \"\"\" # Returns", "return Gs def bulk_dproduct(self, evalTree, flat=False, bReturnProds=False, bScale=False, comm=None, wrtFilter=None): \"\"\" Compute the", "split tree. In short, parallelization should be done at a higher level. \"\"\"", "M where: - N == the number of entries in a single flattened", "the product will overflow and the subsequent trace operation will yield nan as", "else min(comm_blkSize, blkSize1) # override with smaller comm_blkSize blkSize2 = comm_blkSize if (blkSize2", "= dGs1 else: dProdCache2 = self._compute_dproduct_cache( evalSubTree, prodCache, scaleCache, blk2Comm, blk_wrtSlice2) dGs2 =", "_np.identity(dim); leftProds.append(G) for opLabel in revOpLabelList: G = _np.dot(G, self.sos.get_operation(opLabel).todense()) leftProds.append(G) rightProdsT =", "_slct.length(wrtFilter1) nDerivCols2 = self.Np if (wrtFilter2 is None) else _slct.length(wrtFilter2) nCircuits = evalTree.num_final_strings()", "overflow or get nans (invalid), but ok dGs1 = _np.swapaxes(_np.swapaxes(dGs1, 0, 3) *", "you may not use this file except # in compliance with the License.", "do the same thing (for debugging) master_circuit_list = evalTree.generate_circuit_list(permute=False) # raw operation sequences", "returnDeriv: # same as in dpr(...) dpr_dOps = _np.empty((1, self.Np)) for i in", "LEXICOGRAPHICAL VS MATRIX ORDER else: G = H old_err = _np.seterr(over='ignore') scale =", "dictates block if blkSize1 is None and blkSize2 is None: #Fill hessian cache", "= self.sos.get_effect(elabel) # arrays, these are SPAMVecs #Derivs wrt Gates old_err = _np.seterr(over='ignore')", "else return (dGs, Gs, scaleVals) if bScale else (dGs, Gs) else: dGs =", "fill result quantities for given arguments \"\"\" tm = _time.time() old_err = _np.seterr(over='ignore')", "_np.any(_np.isnan(ps)): if len(circuit) < 10: strToPrint = str(circuit) else: strToPrint = str(circuit[0:10]) +", "w/indices wrtIndices = _slct.indices(wrtSlice) if (wrtSlice is not None) else None for i,", "in a single flattened gate (ordering is the same as that used by", "= scaledGatesAndExps[lOp] H = _np.dot(gate, G) # product of gates, starting with identity", "\" by giving hproduct cache computation\" \" *fewer* processors and *smaller* (sub-)tree\" \"", ")[i,j,k,0] # dp_dOps[i,j] = dot( E, dot( dGs, rho ) )[0,i,j,0] # dp_dOps", "+= cache_size * num_params * dim * dim # dproduct cache # mem", "ok, see \"if\" condition above) _mpit.gather_slices(deriv1Slices, deriv1Owners, hProdCache, [], 1, comm) #, gatherMemLimit)", "( len(circuit_list), nDerivCols, nDerivCols, dim, dim ) if not bScale: old_err = _np.seterr(over='ignore',", "i in range(len(self.effects)) ] # return PrepEffectFilter(rho_local_slices=loc_rho_slices, # rho_global_slices=global_rho_slices, # e_local_slices=loc_e_slices, # e_global_slices=global_e_slices,", "= _np.zeros((nElements, _slct.length(wrtSlice1), _slct.length(wrtSlice2)), 'd') #prMxToFill = None deriv1MxToFill = dprobs1 deriv2MxToFill =", "sequence scaleExps = evalTree.final_view(scaleCache) old_err = _np.seterr(over='ignore') scaleVals = _np.exp(scaleExps) # may overflow,", "not bScale: old_err = _np.seterr(over='ignore', invalid='ignore') # may overflow or get nans (invalid),", "reverse iLeft <=> iRight from evalTree because # (iRight,iLeft,iFinal) = tup implies circuit[i]", "cache mem += cache_size # scale cache mem += cache_size # scale vals", "_np.log(nR) #print \"bulk_product DEBUG: %d rescalings out of %d products\" % (cnt, len(evalTree))", "evalTree, prMxToFill=None, clipTo=None, check=False, comm=None, wrtFilter=None, wrtBlockSize=None, profiler=None, gatherMemLimit=None): \"\"\" Compute the outcome", "given (i,j,k,l) # noqa # vec( d2prod/d(opLabel1)_kl*d(opLabel2)_ij ) = sum{...} [ G1 ...", "hProdCache[i] = hoperation / _np.exp(scaleCache[i]) #evaluate operation sequences using tree (skip over the", "# _slct.shift(_slct.intersect( # wrtSlices['effects'], # slice(self.e_offset[i],self.e_offset[i+1])), # -self.e_offset[i]) for i in range(len(self.effects))] #", "ex = scaledGatesAndExps[lOp] H = _np.dot(gate, G) # product of gates, starting with", "of gate strings. Similar to `bulk_fill_probs(...)`, but fills a 2D array with probability-derivatives", "operation matrix (G x G operation matrices). scaleValues : numpy array Only returned", "_np.identity(dim) # Note: scaleCache[i] = 0.0 from initialization else: gate = self.sos.get_operation(opLabel).todense() nG", "else return (dGs, scaleVals) if bScale else dGs def bulk_hproduct(self, evalTree, flat=False, bReturnDProdsAndProds=False,", "are the number of selected gate-set parameters (by wrtFilter1 and wrtFilter2). evalTree :", "of the sub-trees. _warnings.warn(\"Increased speed could be obtained\" \" by giving hproduct cache", "used internally for distributing derivative calculations across multiple processors. Returns ------- derivs :", "is None: #Fill derivative cache info tm = _time.time() dProdCache = self._compute_dproduct_cache(evalSubTree, prodCache,", "DSMALL and dProdCache[i].min() > -DSMALL: _warnings.warn(\"Scaled dProd small in order to keep prod", "prodCache, dProdCache1, dProdCache2, scaleCache, mySubComm, wrtSlice1, wrtSlice2) hGs = evalSubTree.final_view(hProdCache, axis=0) #( nCircuits,", "clipTo[0], clipTo[1]) dprod_dOps = self.dproduct(circuit) assert(dprod_dOps.shape[0] == self.Np) if returnDeriv: # same as", "comm.allgather(my_results) profiler.add_time(\"MPI IPC\", tm) return _np.concatenate(all_results, axis=1) # TODO: remove this concat w/better", "the existing array values, which is a functionality needed to correctly handle the", "bScale=False, comm=None, wrtFilter1=None, wrtFilter2=None): \"\"\" Return the Hessian of many operation sequence products", "bulk_fill_probs(...). derivMxToFill1, derivMxToFill2 : numpy array, optional when not None, an already-allocated ExM", "self.Np if (wrtFilter is None) else _slct.length(wrtFilter) dim = self.dim wrtSlice = _slct.list_to_slice(wrtFilter)", "(axis=0) if prMxToFill is not None: _mpit.gather_indices(subtreeElementIndices, subTreeOwners, prMxToFill, [], 0, comm) #note:", "if blk_wrtSlice1 == blk_wrtSlice2: dProdCache2 = dProdCache1; dGs2 = dGs1 else: dProdCache2 =", "already-allocated length-E numpy array that is filled with probabilities, just like in bulk_fill_probs(...).", "axis=0) for iBlk2 in myBlk2Indices: blk_wrtSlice2 = blocks2[iBlk2] if blk_wrtSlice1 == blk_wrtSlice2: dProdCache2", "scale_exp += _np.log(nG) # LEXICOGRAPHICAL VS MATRIX ORDER else: G = H old_err", "add logic that accounts for the symmetry of the Hessian, so that #", "independent of which) dp_dAnyE = _np.squeeze(_np.dot(Gs, rho), axis=(2,)) * scaleVals[:, None] _fas(dp_dEs, [None,", "gate hessian once). But since we're # assuming that the gates are at", "% (i,p,norm(G),total_exp,str(G)) # if _np.isnan(p): raise ValueError(\"STOP\") if clipTo is not None: ret", "Note: d2pr_d2rhos and d2pr_d2Es terms are always zero _np.seterr(**old_err) if returnDeriv: if returnPr:", "= evalTree[i] L, R = prodCache[iLeft], prodCache[iRight] prodCache[i] = _np.dot(L, R) scaleCache[i] =", "hprMxToFill is not None: check_vhp = _np.concatenate( [self.hpr(spamTuple, circuit, False, False, clipTo) for", "in elabels] Es = _np.conjugate(_np.transpose(_np.concatenate(Es, axis=1))) # convention: Es has shape (len(elabels),N) return", ": bool when set to True, additionally return the probability itself. clipTo :", "colSlice, hprobs)` or `(rowSlice, colSlice, dprobs12)` (the latter if `bReturnDProbs12 == True`). `rowSlice`", "length-0 list, as this doesn't index numpy arrays # like length>1 lists do...", "_np.exp(scale) if dProdCache[i].max() < DSMALL and dProdCache[i].min() > -DSMALL: _warnings.warn(\"Scaled dProd small in", "_np.squeeze(_np.dot(E, _np.dot(dGs, rho)), axis=(0, 3)) * scaleVals[:, None] _np.seterr(**old_err2) # may overflow, but", "compute reduce results from a single column of the Hessian at a time.", "matrixOf(circuit[iRight]) (iRight, iLeft) = evalTree[i] L, R = prodCache[iLeft], prodCache[iRight] dL, dR =", "#Derivs wrt Gates old_err = _np.seterr(over='ignore') prod, scale = self.product(circuit, True) dprod_dOps =", "None] # overflow OK devec = EVec.deriv_wrt_params(E_wrtFilter1) _fas(d2pr_dErhos1, (None, E_gpindices1, rho_gpindices2), _np.swapaxes(_np.dot(_np.transpose(devec), dp_dAnyE),", "None and comm.Get_size() > 1: #print(\"MPI: _compute_dproduct_cache called w/comm size %d\" % comm.Get_size())", "len(circuit_list) - M == the length of the vectorized model - G ==", "may overflow, but OK ; shape == (len(circuit_list), nDerivCols) # may also give", "element of circuit can be thought of as the first gate operation performed,", "is not None: ret = _np.clip(ps, clipTo[0], clipTo[1]) else: ret = ps #DEBUG", "across blocks myBlkIndices, blkOwners, blkComm = \\ _mpit.distribute_indices(list(range(nBlks)), mySubComm) if blkComm is not", "= dProdCache2 = dGs2 = None # free mem if bReturnDProbs12: dprobs12 =", "blocks of at most blkSize assert(wrtFilter1 is None and wrtFilter2 is None) #", "blk1Comm). # (just as prMxToFill is computed fully on each inner loop *iteration*!)", "= _np.seterr(over='ignore') prod, scale = self.product(circuit, True) if returnPr: p = _np.dot(E, _np.dot(prod,", "subtrees (even == 1) in order to perform the parallelization over the parameter", "OK if infs occur here _np.seterr(**old_err) return scaleVals def _rhoE_from_spamTuple(self, spamTuple): assert(len(spamTuple) ==", "if hprMxToFill is not None: check_vhp = _np.concatenate( [self.hpr(spamTuple, circuit, False, False, clipTo)", "an evaluation tree out of (most likely because you want to computed their", "myHessianSlice2 = myDeriv2ColSlice if mySubSubComm is not None and mySubSubComm.Get_size() > 1: _warnings.warn(\"Too", "more than linear dependence on their parameters. if self.sos.get_prep(rholabel).has_nonzero_hessian(): dp_dAnyRho = _np.dot(E, Gs).squeeze(0)", "if dprMxToFill is not None: check_vdp = _np.concatenate( [self.dpr(spamTuple, circuit, False, clipTo) for", "a operation matrix (G x G operation matrices). scaleValues : numpy array Only", "Return an estimate of the ideal/desired cache size given a number of operation", "where: - S == the number of operation sequences - G == the", "= None profiler.mem_check(\"bulk_fill_dprobs: begin (expect ~ %.2fGB)\" % (mxToFill.nbytes / (1024.0**3))) ## memory", "] # global_e_slices = [slice(self.e_offset[i],self.e_offset[i+1]) for i in range(len(self.effects)) ] # return PrepEffectFilter(rho_local_slices=loc_rho_slices,", "* matrixOf(circuit[iRight]) (iRight, iLeft) = evalTree[i] L, R = prodCache[iLeft], prodCache[iRight] prodCache[i] =", "should also conjugate() here if complex? _fas(dpr_dEs, [0, EVec.gpindices], _np.dot(derivWrtAnyEvec, EVec.deriv_wrt_params())) _np.seterr(**old_err) if", "ceiling(num_params / np1) wrtLen2 = (self.Np + np2 - 1) // np2 #", "dp_drhos[i, rho_gpindices] = dot(E,Gs[i],drho/drhoP) # dp_drhos[i,J0+J] = sum_kl E[0,k] Gs[i,k,l] drhoP[l,J] # dp_drhos[i,J0+J]", "dimension of a operation matrix (G x G operation matrices). scaleValues : numpy", "(_nla.norm(hprMxToFill[fInds]), _nla.norm(check_vhp), _nla.norm(hprMxToFill[fInds] - check_vhp))) # pragma: no cover def bulk_fill_probs(self, mxToFill, evalTree,", "when the spam vectors have # a more than linear dependence on their", "is filled with probability derivatives, similar to bulk_fill_dprobs(...), but where M is the", "holds the derivative of the (k,l)-th entry of the i-th operation sequence product", "many gate sequence probabilities can often be computed column-by-column from the using the", "on. flat : bool, optional Affects the shape of the returned derivative array", "shape S x M x G x G, where: - S == len(circuit_list)", "_np.dot(derivWrtAnyRhovec, rhoVec.deriv_wrt_params())) # may overflow, but OK dpr_dEs = _np.zeros((1, self.Np)) derivWrtAnyEvec =", "# probability # print \"%d: p = %g, norm %g, exp %g\\n%s\" %", "FUNCTIONS def _compute_product_cache(self, evalTree, comm=None): \"\"\" Computes a tree of products in a", "are zero. hProdCache[i] = _np.zeros(hessn_shape) else: hoperation = self.hoperation(opLabel, wrtFilter1=wrtIndices1, wrtFilter2=wrtIndices2) hProdCache[i] =", "will be automatically parallelized over these groups. num_final_strs : int The number of", "nG = max(_nla.norm(G), _np.exp(-scale_exp)) G = _np.dot(gate, G / nG); scale_exp += _np.log(nG)", "of the probability. clipTo : 2-tuple (min,max) to clip returned probability to if", "Sandia, LLC (NTESS). # Under the terms of Contract DE-NA0003525 with NTESS, the", "cache info (not requiring row or column distribution) prodCache, scaleCache = self._compute_product_cache(evalSubTree, mySubComm)", "wrtSlice2), add=sumInto) _np.seterr(**old_err) #Set wrtBlockSize to use available processors if it isn't specified", "derivatives wrt all spam parameters dGs = _np.empty((Gs.shape[0], 0, self.dim, self.dim), 'd') def", "operation sequence product with respect to the j-th model parameter. * if flat", "necessary) if comm.Get_size() > nDerivCols1 * nDerivCols2: #If there are more processors than", "used internally for distributing derivative calculations across multiple processors. Returns ------- hessians :", "import mpitools as _mpit from ..tools import slicetools as _slct from ..tools.matrixtools import", "of no gates #Also Cache gate jacobians (still relatively little mem required) dop_dopLabel1", "sum E_k prod_kl rho_l # dpr/d(opLabel)_ij = sum E_k [dprod/d(opLabel)_ij]_kl rho_l # dpr/d(rho)_i", "axis=0) #( nCircuits, dim, dim ) def calc_and_fill(spamTuple, fInds, gInds, pslc1, pslc2, sumInto):", "by a each gate sequence given by evalTree column-by-column. This routine can be", "circuits in that they should only contain \"deterministic\" elements (no POVM or Instrument", "Gs, scaleVals) if bScale else (dGs, Gs) else: dGs = evalTree.final_view(dProdCache, axis=0) #shape", "here _np.seterr(**old_err) return scaleVals def _rhoE_from_spamTuple(self, spamTuple): assert(len(spamTuple) == 2) if isinstance(spamTuple[0], _Label):", "previously, we tried to allow for parallelization of # _compute_product_cache when the tree", "scaleVals being inf and dot-prod being 0. In # this case set to", "no good way to reconstruct the parent tree's *non-final* elements from those of", "fill result quantities for given arguments \"\"\" old_err = _np.seterr(over='ignore') rho, E =", "operations, respectively. wrtBlockSize2, wrtBlockSize2 : int or float, optional The maximum number of", "# # Note: if gate G(L) is just a matrix of parameters, then", "= deriv cols, rows = flattened all else dGs1 = _np.swapaxes(_np.swapaxes(dGs1, 0, 1).reshape((nDerivCols1,", "< PSMALL and H.min() > -PSMALL: nG = max(_nla.norm(G), _np.exp(-scale_exp)) G = _np.dot(gate,", "numpy.flatten), - S,M == as above, and deriv[i,j] holds the derivative of the", "lists do... ugh. relevant_gpindices = slice(0, 0) # slice that results in a", "\"extra\", i.e. rank != 0, cpus hProdCache[:, myDeriv1ColSlice, myDeriv2ColSlice] = self._compute_hproduct_cache( evalTree, prodCache,", "desired average size == blkSize1 or blkSize2 blocks1 = _mpit.slice_up_range(self.Np, nBlks1) blocks2 =", "= self.Np if (wrtFilter2 is None) else _slct.length(wrtFilter2) nCircuits = evalTree.num_final_strings() # len(circuit_list)", "EVec = self.sos.get_effect(elabel) # arrays, these are SPAMVecs d2prod_dGates = self.hproduct(circuit) assert(d2prod_dGates.shape[0] ==", "x M array, where: - N == the number of entries in a", "string if not bScale: old_err = _np.seterr(over='ignore', invalid='ignore') # may overflow or get", "gets computed on every inner loop completion # (to save mem) but isn't", "None # free Mem dProdCache1 = self._compute_dproduct_cache( evalTree, prodCache, scaleCache, comm, wrtSlice1) dGs1", "E = _np.conjugate(_np.transpose(self.sos.get_effect(elabel).todense() [:, None])) # convention: E has shape (1,N) else: #", "= sum_kl E[0,k] dGs[i,j,k,l] drhoP[l,J] # d2pr_drhos[i,j,J0+J] = dot(E, dGs, drhoP)[0,i,j,J] # d2pr_drhos[:,:,J0+J]", "\"\"\" if self.evotype == \"statevec\": raise NotImplementedError(\"Unitary evolution not fully supported yet!\") #", "number of model parameters. hessian[0,j,k] is the derivative of the probability w.r.t. the", "\"hGs must be pre-filtered!\" assert(hGs.shape[2] == nDerivCols2), \"hGs must be pre-filtered!\" #Compute d2(probability)/dGates2", "sequence and spam tuple as a 1 x M x M array, where", "for each \"final element\" of `evalTree`. Parameters ---------- mxToFill : numpy ndarray an", "being differentiated with respect to (see wrtBlockSize). wrtFilter : list of ints, optional", "impose upon the \"gather\" operations performed as a part of MPI processor syncronization.", "hessian value (see below) hGs[_np.isnan(hGs)] = 0 _np.seterr(**old_err) if flat: # cols =", "a multiple \"outcomes\" (spam-tuples) for a single operation sequence. The spam tuples may", "ex # scale and keep track of exponent if H.max() < PSMALL and", "evalTree.final_view(dProdCache2, axis=0) #shape == ( len(circuit_list), nDerivColsX, dim, dim ), # dGs[i] is", "#TODO: remove: not needed now that we track owners #if mySubSubComm.Get_rank() > 0:", "noqa # dprod/d(opLabel)_ij = sum_{L s.t. GL == oplabel} [ G1 ... G(L-1)", "), # Gs[i] is product for i-th operation sequence dGs = evalTree.final_view(dProdCache, axis=0)", "_np.zeros((dim**2, num_deriv_cols1, num_deriv_cols2), 'd') # For each pair of gates in the string,", "deriv1MxToFill, [], 0, comm, gatherMemLimit) if deriv2MxToFill is not None: _mpit.gather_indices(subtreeElementIndices, subTreeOwners, deriv2MxToFill,", "\"\"\" Compute the outcome probabilities for an entire tree of operation sequences. This", "scale_exp += ex # scale and keep track of exponent if H.max() <", "for *no* gate params to compute # derivatives wrt all spam parameters dGs", "for the final result num_deriv_cols1 = self.Np if (wrtFilter1 is None) else len(wrtFilter1)", "== False, a M x G x G array, where: - M ==", "= self.dim wrtSlice = _slct.list_to_slice(wrtFilter) if (wrtFilter is not None) else None #TODO:", "gate hessians (memory?) hop_dopLabels = {} for opLabel, gate in used_operations.items(): if gate.has_nonzero_hessian():", "if mySubComm is not None and mySubComm.Get_size() > 1: _warnings.warn(\"Too many processors to", "gather subtrees\") if clipTo is not None and prMxToFill is not None: _np.clip(prMxToFill,", "blk1Comm) if blk2Comm is not None: _warnings.warn(\"Note: more CPUs(%d)\" % mySubComm.Get_size() + \"", "wrtSlice1 and wrtSlice2, of the parent-function scope. This use of # closures seems", "at most blkSize assert(wrtFilter1 is None and wrtFilter2 is None) # cannot specify", "split tree. \"\"\" if profiler is None: profiler = _dummy_profiler dim = self.dim", "return ret def dpr(self, spamTuple, circuit, returnPr, clipTo): \"\"\" Compute the derivative of", "mxToFill, [], 0, comm) #note: pass mxToFill, dim=(KS), so gather mxToFill[felslc] (axis=0) if", "vec( dG(L)/dij ) ] # noqa # + sum{ L == M} [", "cached data to construct return values old_err = _np.seterr(over='ignore') scaleExps = evalTree.final_view(scaleCache) scaleVals", "the bulk operation on. prMxToFill : numpy array, optional when not None, an", "in the LICENSE file in the root pyGSTi directory. #*************************************************************************************************** import warnings as", "obj_wrtFilter = [] # values = object-local param indices relevant_gpindices = [] #", "available and necessary) if comm.Get_size() > nDerivCols: #If there are more processors than", "_np.swapaxes(y, 0, 1) # above: dim = (dim2, nDerivCols1, nDerivCols2); # swapaxes takes", "None #Fill cache info (not requiring column distribution) tm = _time.time() prodCache, scaleCache", "etc. to allow for *complex* derivatives, since matrices can be complex # -", "label... rho, E = self._rhoE_from_spamTuple(spamTuple) rhoVec = self.sos.get_prep(rholabel) # distinct from rho,E b/c", "must have length equal to the number of final elements (this can be", "None, rho_gpindices2], _np.squeeze(_np.dot(_np.dot(E, dGs1), drho), axis=(0,)) * scaleVals[:, None, None]) # overflow OK", "slower when True. comm : mpi4py.MPI.Comm, optional When not None, an MPI communicator", "an estimate - could compute? wrtLen1 = (self.Np + np1 - 1) //", "== 0) return prodCache, scaleCache def _compute_dproduct_cache(self, evalTree, prodCache, scaleCache, comm=None, wrtSlice=None, profiler=None):", "into. Computation will be automatically parallelized over these groups. num_param2_groups : int The", "* dim**2)), 0, 1) # cols = deriv cols, rows = flattened all", "flattened_hprod = _np.zeros((dim**2, num_deriv_cols1, num_deriv_cols2), 'd') if _slct.length(gpindices1) > 0 and _slct.length(gpindices2) >", "split evalTree (if given) is possible. wrtFilter : list of ints, optional If", "self._compute_product_cache(evalTree, comm) dProdCache = self._compute_dproduct_cache(evalTree, prodCache, scaleCache, comm, wrtSlice) #use cached data to", "= gpindices1[opLabel1] nDerivCols1 = dop_dopLabel1[opLabel1].shape[1] if nDerivCols1 == 0: continue for l, opLabel2", "= evalTree[i] L, R = prodCache[iLeft], prodCache[iRight] dL, dR = dProdCache[iLeft], dProdCache[iRight] dProdCache[i]", "d2(prod)/d(gl1)d(gl2) # and not d2(prod)/d(gl2)d(gl1) ... if m < l: x0 = _np.kron(_np.transpose(prods[(0,", "below). wrtFilter1, wrtFilter2 : list of ints, optional If not None, a list", "# prod.flatten()). # # Note: if gate G(L) is just a matrix of", "- S,M == as above, and deriv[i,j] holds the derivative of the (i", "G,dG # dp_dOps[i,j] = sum_k,l E[0,k] dGs[i,j,k,l] rho[l,0] # dp_dOps[i,j] = sum_k E[0,k]", "involve gate derivatives d2pr_dErhos2 = _np.transpose(d2pr_dErhos1, (0, 2, 1)) else: d2pr_dErhos2 = _np.zeros((nCircuits,", "gate.deriv_wrt_params(gate_wrtFilters1[opLabel]) for opLabel, gate in used_operations.items()} if wrtFilter1 == wrtFilter2: dop_dopLabel2 = dop_dopLabel1", "already-allocated ExMxM numpy array where E is the total number of computed elements", "_np.seterr(**old_err) if bReturnProds: Gs = evalTree.final_view(prodCache, axis=0) #shape == ( len(circuit_list), dim, dim", "(wrtFilter2 is not None) else None #TODO: just allow slices as argument: wrtFilter", "**must** match that in bulk_evaltree # in order to associate the right single-gate-strings", "len(wrtFilter) flattened_dprod = _np.zeros((dim**2, num_deriv_cols), 'd') # For each operation label, compute the", "let dGs2 be None? assert(nDerivCols1 == nDerivCols2) d2pr_dEs2 = _np.transpose(d2pr_dEs1, (0, 2, 1))", "the derivative of the (j,k)-th entry of the product with respect to the", "min(comm_blkSize, blkSize2) # override with smaller comm_blkSize else: blkSize1 = blkSize2 = None", "The gate-dimension. All operation matrices should be dim x dim, and all SPAM", "rho_wrtFilter1, rho_wrtFilter2), (1, 0))) # _np.einsum('ij,jkl->ikl', dp_dAnyRho, self.sos.get_prep(rholabel).hessian_wrt_params( # rho_wrtFilter1, rho_wrtFilter2)) else: d2pr_d2rhos", "wrtSlice1, wrtSlice2) hGs = evalSubTree.final_view(hProdCache, axis=0) #( nCircuits, len(wrtFilter1), len(wrtFilter2), dim, dim )", "the Hessian, and turns out to be useful when computing the Hessian of", "index numpy arrays # like length>1 lists do... ugh. relevant_gpindices = slice(0, 0)", "subTreeOwners, mySubComm = evalTree.distribute(comm) #eval on each local subtree for iSubTree in mySubTreeIndices:", "and we should do something else LATER. def calc_and_fill(spamTuple, fInds, gInds, pslc1, pslc2,", "then (as needed) a split tree to parallelize computation, since there are no", "to be computed # for the current spamTuple (this list has the SAME", "the derivative. Each element is an index into an array of gate parameters", "] # noqa # a matrix for each given (i,j,k,l) # noqa #", "(this list has the SAME length as fInds). calc_and_fill_fn(spamTuple, fInds, gInds, pslc1, pslc2,", "else: gate = self.sos.get_operation(opLabel).todense() nG = max(_nla.norm(gate), 1.0) prodCache[i] = gate / nG", "no memory savings from using a split tree. \"\"\" if profiler is None:", "is possible. wrtFilter : list of ints, optional If not None, a list", "circuit, bScale=False): \"\"\" Compute the product of a specified sequence of operation labels.", "loop over \"starting\" gate prods[(i, i - 1)] = ident # product of", "d2pr_dEs2 = _np.transpose(d2pr_dEs2, (0, 2, 1)) # Get: d2pr_dErhos[i, e_offset[eIndex]:e_offset[eIndex+1], e_offset[rhoIndex]:e_offset[rhoIndex+1]] = #", "(subsets) of the parameters being differentiated with respect to (see wrtBlockSize). wrtFilter :", "nDerivCols1)) dp_dAnyE = _np.squeeze(_np.dot(dGs2, rho), axis=(3,)) * scaleVals[:, None, None] # overflow OK", "element # is at most *linear* in each of the gate parameters. If", "evalSubTree, blocks1[iBlk1], blocks2[iBlk2], calc_and_fill) hProdCache = hGs = dProdCache2 = dGs2 = None", "dp_drhos + dp_dEs + dp_dOps return sub_vdp #def _get_filter_info(self, wrtSlices): # \"\"\" #", "#gather over row-distribution (Deriv1) #note: gathering axis 1 of hProdCache, # dim=(cacheSize,nDerivCols1,nDerivCols2,dim,dim) return", "len(circuit_list), dim, dim ), Gs[i] is product for i-th operation sequence scaleExps =", "the entire operation sequence with respect to the # gate's parameters and fill", "directly from `wrtSlicesList`. `hprobs` and `dprobs12` are arrays of shape K x S", "# (dim**2, dim**2) _fas(flattened_dprod, [None, gpindices], _np.dot(LRproduct, dop_dopLabel), add=True) # (dim**2, nParams[opLabel]) if", "is used internally for distributing derivative calculations across multiple processors. Returns ------- deriv", "model (number of model parameters) and hessian[i,j,k] holds the derivative of the i-th", "want: # since then matrixOf(circuit[i]) = matrixOf(circuit[iLeft]) * matrixOf(circuit[iRight]) (iRight, iLeft) = evalTree[i]", "else: blkSize = None # wrtFilter dictates block if blkSize is None: #Fill", "perform extra checks within code to verify correctness, generating warnings when checks fail.", "to distribute itself among the available processors. Returns ------- MatrixEvalTree \"\"\" evTree =", "product of no gates #Also Cache gate jacobians (still relatively little mem required)", "starting with G0 # nG = norm(G); G /= nG; total_exp += log(nG)", "but ok # may overflow or get nans (invalid), but ok dGs =", "If not None, a list of integers specifying which parameters to include in", "params so that # per-gate hessians can be computed properly if wrtSlice1 is", "blk1Owners, blk1Comm = \\ _mpit.distribute_indices(list(range(nBlks1)), mySubComm) myBlk2Indices, blk2Owners, blk2Comm = \\ _mpit.distribute_indices(list(range(nBlks2)), blk1Comm)", "save in return array # want vp[iFinal] = float(dot(E, dot(G, rho))) # vp[i]", "old_err = _np.seterr(over='ignore') scale = _np.exp(scale_exp) _np.seterr(**old_err) return G, scale else: G =", "#Note: includes \"results\" memory since this is allocated within # the generator and", "axis=(0,)) * scaleVals[:, None, None]) # overflow OK d2pr_drhos2 = _np.transpose(d2pr_drhos2, (0, 2,", "computes and *fills* (i.e. doesn't return to save copying) some arrays. The arrays", "wrtFilter for opLabel) if flat: return flattened_dprod else: # axes = (gate_ij, prod_row,", "POINT2\"); profiler.comm.barrier() profiler.add_time(\"compute_dproduct_cache: serial\", tSerialStart) profiler.add_count(\"compute_dproduct_cache: num columns\", nDerivCols) return dProdCache def _compute_hproduct_cache(self,", "# slice(self.e_offset[i],self.e_offset[i+1])), # -self.e_offset[i]) for i in range(len(self.effects))] # tmp_num_params = [_slct.length(s) for", "Specifies the operation sequences to compute the bulk operation on. bScale : bool,", "wrtSlice), add=sumInto) _np.seterr(**old_err) profiler.add_time(\"bulk_fill_dprobs: calc_and_fill\", tm) #Set wrtBlockSize to use available processors if", "which use entirely different -- non-gate-local -- parameterizations of operation matrices and SPAM", "[fInds, pslc1], self._dprobs_from_rhoE( spamTuple, rho, E, Gs[gInds], dGs[gInds], scaleVals[gInds], block_wrtSlice), add=sumInto) _np.seterr(**old_err) profiler.add_time(\"bulk_fill_dprobs:", "= self.Np if (wrtFilter2 is None) else len(wrtFilter2) flattened_hprod = _np.zeros((dim**2, num_deriv_cols1, num_deriv_cols2),", "rho, Eraw = spamTuple E = _np.conjugate(_np.transpose(Eraw)) return rho, E def _rhoEs_from_spamTuples(self, rholabel,", "for use in computations. \"\"\" super(MatrixForwardSimulator, self).__init__( dim, simplified_op_server, paramvec) if self.evotype not", "------------------------------------------------------------------ tSerialStart = _time.time() if evalTree.is_split(): _warnings.warn(\"Ignoring tree splitting in dproduct cache calc.\")", "flat=False, wrtFilter1=None, wrtFilter2=None): \"\"\" Return the hessian of a length-1 (single-gate) sequence \"\"\"", "overflow, but OK if clipTo is not None: p = _np.clip(p, clipTo[0], clipTo[1])", "%s is incompatbile with \" \"matrix-based calculations\" % self.evotype)) def copy(self): \"\"\" Return", "column of the matrix d12 defined by: d12[iSpamLabel,iOpStr,p1,p2] = dP/d(p1)*dP/d(p2) where P is", "calculation (i.e. for l==m) then # it could make sense to iterate through", "zero hessian value trumps since we've renormed to keep all the products within", "and mySubComm.Get_size() > 1: deriv2Slices, myDeriv2ColSlice, deriv2Owners, mySubSubComm = \\ _mpit.distribute_slice(allDeriv2ColSlice, mySubComm) #", "operation sequences to compute the bulk operation on. bScale : bool, optional When", "_mpit.gather_slices(blocks1, blk1Owners, mxToFill, [felInds], 1, mySubComm, gatherMemLimit) if deriv1MxToFill is not None: _mpit.gather_slices(blocks1,", "spamTuple, circuit, returnPr, returnDeriv, clipTo): \"\"\" Compute the Hessian of a probability generated", "bulk operation on. bScale : bool, optional When True, return a scaling factor", "for the i-th operation sequence. \"\"\" dim = self.dim nDerivCols1 = self.Np if", "_slct.shift(_slct.intersect( # wrtSlices['preps'], # slice(self.rho_offset[i],self.rho_offset[i+1])), # -self.rho_offset[i]) for i in range(len(self.preps))] # tmp_num_params", "the shape of the returned derivative array (see below). wrtFilter : list of", "dGs2, Gs) else: hGs = evalTree.final_view(hProdCache, axis=0) #shape == ( len(circuit_list), nDerivCols, nDerivCols,", "gate's parameters and fill appropriate columns of flattened_dprod. _fas(flattened_hprod, [None, gpindices1, gpindices2], gate.hessian_wrt_params(op_wrtFilter1,", "scaleVals[gInds]), add=sumInto) _np.seterr(**old_err) profiler.add_time(\"bulk_fill_dprobs: calc_and_fill_p\", tm) # Compute all probabilities all at once", "(vec_prod_indx,kl,ij) elif l < m: x0 = _np.kron(_np.transpose(prods[(l + 1, m - 1)]),", "= 0 for i in evalTree.get_evaluation_order(): # combine iLeft + iRight => i", "_np.seterr(**old_err) #Set wrtBlockSize to use available processors if it isn't specified if wrtFilter1", "* scaleVals, 0, 2) # may overflow, but ok _np.seterr(**old_err) return Gs def", "0))) # _np.einsum('ij,jkl->ikl', dp_dAnyE, self.sos.get_effect(elabel).hessian_wrt_params( # E_wrtFilter1, E_wrtFilter2)) else: d2pr_d2Es = 0 #", "zero-operation labels wrtIndices1 = _slct.indices(wrtSlice1) if (wrtSlice1 is not None) else None wrtIndices2", "... if m < l: x0 = _np.kron(_np.transpose(prods[(0, m - 1)]), prods[(m +", "None] # overflow OK d2pr_d2rhos = _np.zeros((nCircuits, nDerivCols1, nDerivCols2)) _fas(d2pr_d2rhos, [None, rho_gpindices1, rho_gpindices2],", "True, an array of shape S*N x M where: - N == the", "%g = %g\" % (_nla.norm(hprMxToFill[fInds]), _nla.norm(check_vhp), _nla.norm(hprMxToFill[fInds] - check_vhp))) # pragma: no cover", "an entire tree of operation sequences. This routine fills a 1D array, `mxToFill`", "compute all requested columns at once. The minimum of wrtBlockSize and the size", "zero deriv value, and we dGs[_np.isnan(dGs)] = 0 # assume the zero deriv", "Get: dp_dEs[i, E_gpindices] = dot(transpose(dE/dEP),Gs[i],rho)) # dp_dEs[i,J0+J] = sum_lj dEPT[J,j] Gs[i,j,l] rho[l,0] #", "scale and keep track of exponent if H.max() < PSMALL and H.min() >", "s in loc_e_slices] # tmp_offsets = [ sum(tmp_num_params[0:i]) for i in range(len(self.effects)+1) ]", "ps = _np.real(_np.abs(_np.dot(Es, _np.dot(G, rho)))**2) else: # evotype == \"densitymx\" ps = _np.real(_np.dot(Es,", "subtee sizes = %s\" % # (comm.Get_rank(),\",\".join([str(len(subtrees[i])) # for i in mySubTreeIndices]))) #eval", "gate) G = _np.dot(G, self.sos.get_operation(opLabel2).todense()) prods[(i, j)] = G prods[(len(revOpLabelList), len(revOpLabelList) - 1)]", "same as numpy.flatten), - S,M == as above, and deriv[i,j] holds the derivative", "= self._compute_dproduct_cache(evalSubTree, prodCache, scaleCache, blkComm, block_wrtSlice, profiler) profiler.add_time(\"bulk_fill_dprobs: compute_dproduct_cache\", tm) profiler.mem_check( \"bulk_fill_dprobs: post", "profiler.add_time(\"bulk_fill_dprobs: compute_product_cache\", tm) #use cached data to final values scaleVals = self._scaleExp(evalSubTree.final_view(scaleCache)) Gs", "check: self._check(evalTree, prMxToFill, mxToFill, clipTo=clipTo) profiler.add_time(\"bulk_fill_dprobs: total\", tStart) profiler.add_count(\"bulk_fill_dprobs count\") profiler.mem_check(\"bulk_fill_dprobs: end\") def", "1)) else: drho = rhoVec.deriv_wrt_params(rho_wrtFilter1) d2pr_drhos2 = _np.zeros((nCircuits, nDerivCols2, nDerivCols1)) _fas(d2pr_drhos2, [None, None,", "comm is not None: # print(\"MPI DEBUG: Rank%d subtee sizes = %s\" %", "M2 are the number of selected gate-set parameters (by wrtFilter1 and wrtFilter2). evalTree", "spam tuple as a 1 x M numpy array, where M is the", "elements.\") # pragma: no cover # allocate final result memory hProdCache = _np.zeros((cacheSize,)", "derivative array (see below). wrtFilter : list of ints, optional If not None,", "In general: vec( A * X * B ) = A tensor B^T", "wrtSlice2.start is not None: myHessianSlice2 = _slct.shift(myDeriv2ColSlice, wrtSlice2.start) else: myHessianSlice2 = myDeriv2ColSlice if", "# convention: E has shape (1,N) else: # a \"custom\" spamLabel consisting of", "number of model parameters. evalTree : EvalTree given by a prior call to", "of only a *subset* of all the gate's parameters if isinstance(wrtFilter, slice): wrtFilter", "+= xv if flat: return flattened_d2prod # axes = (vectorized_op_el_index, model_parameter1, model_parameter2) else:", "#Don't return a length-0 list, as this doesn't index numpy arrays # like", "hessn_shape = (nDerivCols1, nDerivCols2, dim, dim) cacheSize = len(evalTree) # ------------------------------------------------------------------ if comm", "these occur b/c an inf scaleVal is mult by a zero deriv value", "# dp_drhos[i,J0+J] = sum_kl E[0,k] Gs[i,k,l] drhoP[l,J] # dp_drhos[i,J0+J] = dot(E, Gs, drhoP)[0,i,J]", "\"\"\" return MatrixForwardSimulator(self.dim, self.sos, self.paramvec) def product(self, circuit, bScale=False): \"\"\" Compute the product", "== nDerivCols2) d2pr_drhos2 = _np.transpose(d2pr_drhos1, (0, 2, 1)) else: drho = rhoVec.deriv_wrt_params(rho_wrtFilter1) d2pr_drhos2", "doperation = self.doperation(opLabel, wrtFilter=wrtIndices) dProdCache[i] = doperation / _np.exp(scaleCache[i]) #profiler.print_mem(\"DEBUGMEM: POINT1\"); profiler.comm.barrier() #evaluate", "was # incorrect (and luckily never used) - so it's been removed. if", "slice(0, 0) # slice that results in a zero dimension else: obj_wrtFilter =", "using a split tree. In short, parallelization should be done at a higher", "scaleCache, None, myHessianSlice1, myHessianSlice2) # pass None as comm, *not* mySubSubComm, since we", "= self._compute_product_cache(evalSubTree, mySubComm) profiler.add_time(\"bulk_fill_dprobs: compute_product_cache\", tm) #use cached data to final values scaleVals", "d2pr_dEs where E derivatives are wrt the 2nd set of gate parameters if", "%g - %g = %g\" % (_nla.norm(hprMxToFill[fInds]), _nla.norm(check_vhp), _nla.norm(hprMxToFill[fInds] - check_vhp))) # pragma:", "product with respect to the j-th then i-th model parameters. * if flat", "elif fnName == \"bulk_fill_hprobs\": mem += cache_size * wrtLen1 * wrtLen2 * dim", "not None. Returns ------- derivative : numpy array a 1 x M numpy", "dG(L)/dij G(L+1) ... GN ] + {similar with L < M} # noqa", "0) # slice that results in a zero dimension else: obj_wrtFilter = None", "mem required) leftProds = [] G = _np.identity(dim); leftProds.append(G) for opLabel in revOpLabelList:", "relatively little mem required) dop_dopLabel1 = { opLabel: gate.deriv_wrt_params(gate_wrtFilters1[opLabel]) for opLabel, gate in", "slice(self.rho_offset[i],self.rho_offset[i+1])), # -self.rho_offset[i]) for i in range(len(self.preps))] # tmp_num_params = [_slct.length(s) for s", "mySubComm.Get_size() blkSize1 = comm_blkSize if (blkSize1 is None) \\ else min(comm_blkSize, blkSize1) #", "zero since we can't tell whether it's + or - inf anyway... dp_dOps[_np.isnan(dp_dOps)]", "scaling needed for the hessians, derivatives, and/or products for the i-th operation sequence.", "The number of subtrees to split the full evaluation tree into. num_subtree_proc_groups :", "= _np.swapaxes(_np.swapaxes(dGs1, 0, 3) * scaleVals, 0, 3) # may overflow or get", ": numpy array, optional when not None, an already-allocated ExM numpy array that", "- throws error if copy is needed) y = _np.dot(_np.kron(xv, _np.transpose(prods[(l + 1,", "model parameters, distribution over a split evalTree (if given) is possible. wrtFilter1, wrtFilter2", "self.Np, self.Np)) for i in range(self.Np): for j in range(self.Np): d2pr_dOps2[0, i, j]", "SPAMVec objects, respectively. Must be *ordered* dictionaries to specify a well-defined column ordering", "the final block size. This argument must be None if wrtFilter is not", "_np.dot(dprod_dOps[i], rho))) if returnPr: p = _np.dot(E, _np.dot(prod, rho)) * scale # may", "E_k prod_ki # dpr/d(E)_i = sum prod_il rho_l rholabel, elabel = spamTuple #", "\"bulk_fill_hprobs\": mem += cache_size * wrtLen1 * wrtLen2 * dim * dim #", "= str(circuit[0:10]) + \" ... (len %d)\" % len(circuit) _warnings.warn(\"pr(%s) == nan\" %", "stacks columns # vec( A * E(0,1) * B ) = vec( mx", ": Label The state preparation label. elabels : list A list of :class:`Label`", "the correspondence between rows of mxToFill and spam labels. evalTree : EvalTree given", "(wrtSlice2 is not None) else None for i, opLabel in zip(evalTree.get_init_indices(), evalTree.get_init_labels()): if", "# pragma: no cover if hprMxToFill is not None: check_vhp = _np.concatenate( [self.hpr(spamTuple,", "= sum_k dEP[k,J] dot(dGs, rho)[i,j,k,0] # d2pr_dEs[i,j,J0+J] = dot( squeeze(dot(dGs, rho),axis=(3,)), dEP)[i,j,J] #", "multiple \"outcomes\" (spam-tuples) for a single operation sequence. The spam tuples may only", "assert(d2prod_dGates.shape[0] == d2prod_dGates.shape[1]) d2pr_dOps2 = _np.empty((1, self.Np, self.Np)) for i in range(self.Np): for", "cache_size # scale vals # #elif fnName == \"bulk_dproduct\": # mem += cache_size", "s.t. G(L) == oplabel} [ G1 ... G(L-1) dG(L)/dij G(L+1) ... GN ]", "scaledGatesAndExps = {} scale_exp = 0 G = _np.identity(self.dim) for lOp in circuit:", "scaleVals[:, None, None] _np.seterr(**old_err2) # may overflow, but OK ; shape == (len(circuit_list),", "cache space. Will *not* parallelize computation, even if given a split tree (since", "\"\"\" dim = self.dim #Note: previously, we tried to allow for parallelization of", "array Only returned when bReturnProds == True. An array of shape S x", "// np2 # ceiling(num_params / np2) mem = 0 for fnName in subcalls:", "num_final_strs : int The number of final strings (may be less than or", ") = vec( mx w/ row_i = A[i,0] * B[row1] ) = A", "= self.dim nspam = int(round(_np.sqrt(self.dim))) # an estimate - could compute? wrtLen1 =", "... GN)^T ]] # noqa # # So for each opLabel the matrix", "a calculation tool used by model objects to perform product and derivatives-of-product calculations.", "prMxToFill is not None. Returns ------- derivative : numpy array a 1 x", "#shape == ( len(circuit_list), dim, dim ), Gs[i] is product for i-th operation", "# wrtSlicesList last_wrtSlice1 = None # keep last dProdCache1 for wrtSlice1, wrtSlice2 in", "are no memory savings from using a split tree. \"\"\" dim = self.dim", "ValueError(\"Unknown subcall name: %s\" % fnName) return mem * FLOATSIZE def bulk_product(self, evalTree,", "= self.hoperation(opLabel, wrtFilter1=wrtIndices1, wrtFilter2=wrtIndices2) hProdCache[i] = hoperation / _np.exp(scaleCache[i]) #evaluate operation sequences using", "not None: _fas(prMxToFill, [fInds], self._probs_from_rhoE(rho, E, Gs[gInds], scaleVals[gInds]), add=sumInto) if deriv1MxToFill is not", "\"\"\" Construct a new MatrixForwardSimulator object. Parameters ---------- dim : int The gate-dimension.", "scaleExps = evalTree.final_view(scaleCache) old_err = _np.seterr(over='ignore') scaleVals = _np.exp(scaleExps) # may overflow, but", "sequence. The spam tuples may only vary in their effect-label (their prep labels", "the total number of computed elements (i.e. evalTree.num_final_elements()) and M is the number", "confusing and we should do something else LATER. def calc_and_fill(spamTuple, fInds, gInds, pslc1,", "dim * dim # dproduct cache mem += cache_size * dim * dim", "\"\"\" # LEXICOGRAPHICAL VS MATRIX ORDER # we do matrix multiplication in this", "get nans (invalid), but ok hGs = _np.swapaxes(_np.swapaxes(hGs, 0, 4) * scaleVals, 0,", "# SPAM DERIVS (assume dGs1 and dGs2 are already sized/filtered) -------- assert(dGs1.shape[1] ==", "= comm_blkSize if (blkSize1 is None) \\ else min(comm_blkSize, blkSize1) # override with", "= self.Np if (wrtFilter is None) else len(wrtFilter) flattened_dprod = _np.zeros((dim**2, num_deriv_cols), 'd')", "be used to simulate time-dependent circuits\" rho, Es = self._rhoEs_from_spamTuples(rholabel, elabels) #shapes: rho", "out to be useful when computing the Hessian of functions of the probabilities.", "- independent of which) dp_dAnyE = _np.squeeze(_np.dot(Gs, rho), axis=(2,)) * scaleVals[:, None] _fas(dp_dEs,", "# noqa # ( unvec( G(L+1) ... G(M-1) tensor (G(M+1) ... GN)^T vec(", "value (see below) dGs2[_np.isnan(dGs2)] = 0 # convert nans to zero, as these", "of ints, optional If not None, a list of integers specifying which gate", "and one is able to compute reduce results from a single column of", "flat == False, an array of shape S x M x G x", "evotype == \"densitymx\" ps = _np.real(_np.dot(Es, _np.dot(G, rho))) ps = ps.flatten() if _np.any(_np.isnan(ps)):", "mxToFill), evalSubTree, blocks1[iBlk1], blocks2[iBlk2], calc_and_fill) hProdCache = hGs = dProdCache2 = dGs2 =", "dGs1), drho), axis=(0,)) * scaleVals[:, None, None]) # overflow OK # get d2pr_drhos", "optional The maximum number of derivative columns to compute *products* for simultaneously. None", "element is an index into an array of gate parameters ordered by concatenating", "probability-Hessians for each \"final element\" of `evalTree`. Parameters ---------- mxToFill : numpy ndarray", "else: wrtSlice1 = None if wrtFilter2 is not None: assert(wrtBlockSize1 is None and", "results mem += cache_size * nspam * (wrtLen1 + wrtLen2) # dprobs1 &", "_np.array([self.prs(spamTuple[0], [spamTuple[1]], circuit, clipTo, False)[0] for circuit in circuit_list]) if _nla.norm(prMxToFill[fInds] - check_vp)", "cache_size * num_params**2 * dim * dim # hproduct cache # mem +=", "and _slct.length(gpindices2) > 0: # works for arrays too # Compute the derivative", "itself among the available processors. Returns ------- MatrixEvalTree \"\"\" evTree = _MatrixEvalTree() evTree.initialize(simplified_circuits,", "#Note: previously, we tried to allow for parallelization of # _compute_product_cache when the", "a operation matrix (G x G operation matrices) and hessians[i,j,k,l,m] holds the derivative", "= slice(0,0) # #don't compute anything on \"extra\", i.e. rank != 0, cpus", "self.sos.get_prep(rholabel)) E_wrtFilter, E_gpindices = self._process_wrtFilter(wrtSlice, self.sos.get_effect(elabel)) nDerivCols = self.Np if wrtSlice is None", "in evalTree.get_evaluation_order(): # combine iLeft + iRight => i # LEXICOGRAPHICAL VS MATRIX", "mySubComm = evalTree.distribute(comm) #if comm is not None: # print(\"MPI DEBUG: Rank%d subtee", "(N,1), Es = (len(elabels),N) if bUseScaling: old_err = _np.seterr(over='ignore') G, scale = self.product(circuit,", "cache # mem += cache_size # scale vals # #elif fnName == \"bulk_dproduct\":", "array Only returned when bScale == True. A length-S array specifying the scaling", "over a split evalTree (if given) is possible. wrtFilter : list of ints,", "slower version that should do the same thing (for debugging) master_circuit_list = evalTree.generate_circuit_list(permute=False)", "_np.isclose(scale,0) is SLOW! dProdCache[i] /= _np.exp(scale) if dProdCache[i].max() < DSMALL and dProdCache[i].min() >", "# may generate overflow, but OK if clipTo is not None: p =", "= self._rhoE_from_spamTuple(spamTuple) block_wrtSlice = pslc1 _fas(mxToFill, [fInds, pslc1], self._dprobs_from_rhoE( spamTuple, rho, E, Gs[gInds],", "and save in return list # d2pr_dOps2[i,j,k] = sum_l,m E[0,l] hGs[i,j,k,l,m] rho[m,0] #", "but this is was # incorrect (and luckily never used) - so it's", "------- hessians : numpy array * if flat == False, an array of", "`calc_and_fill_fn` must be the same as the elements of `result_tup`. The fill function", "bulk_evaltree. Specifies the operation sequences to compute the bulk operation on. flat :", "cols, then sub-trees (if available and necessary) if comm.Get_size() > nDerivCols1 * nDerivCols2:", "iLeft + iRight => i # LEXICOGRAPHICAL VS MATRIX ORDER Note: we reverse", "compliance with the License. You may obtain a copy of the License at", "hProdCache ## END CACHE FUNCTIONS def default_distribute_method(self): \"\"\" Return the preferred MPI distribution", "hprobs #Fill arrays self._fill_result_tuple((None, dprobs1, dprobs2, hprobs), evalTree, slice(None), slice(None), calc_and_fill) hProdCache =", "that rho has shape (N,1) rho = self.sos.get_prep(rholabel).todense()[:, None] Es = [self.sos.get_effect(elabel).todense()[:, None]", "nDerivCols1, nDerivCols2)) dp_dAnyE = _np.squeeze(_np.dot(dGs1, rho), axis=(3,)) * scaleVals[:, None, None] # overflow", "specify both wrtFilter and blkSize nBlks1 = int(_np.ceil(self.Np / blkSize1)) nBlks2 = int(_np.ceil(self.Np", "_Label from .matrixevaltree import MatrixEvalTree as _MatrixEvalTree from .forwardsim import ForwardSimulator _dummy_profiler =", "prodCache[iRight] prodCache[i] = _np.dot(L, R) scaleCache[i] = scaleCache[iLeft] + scaleCache[iRight] if prodCache[i].max() <", "rho_wrtFilter1, rho_wrtFilter2)) else: d2pr_d2rhos = 0 if self.sos.get_effect(elabel).has_nonzero_hessian(): dp_dAnyE = _np.dot(Gs, rho).squeeze(2) *", "the remainder spam label. \"\"\" pslc1 = param_slice1 pslc2 = param_slice2 for spamTuple,", "d(opLabel2)_ij = sum E_k [dprod/d(opLabel1)_mn d(opLabel2)_ij]_kl rho_l # d2pr/d(rho)_i d(opLabel)_mn = sum E_k", "def dproduct(self, circuit, flat=False, wrtFilter=None): \"\"\" Compute the derivative of a specified sequence", "once self._fill_result_tuple((prMxToFill, deriv1MxToFill, deriv2MxToFill, mxToFill), evalSubTree, slice(None), slice(None), calc_and_fill) else: # Divide columns", "the flattened product with respect to the j-th model parameter. \"\"\" # LEXICOGRAPHICAL", "%g\" % (_nla.norm(prMxToFill[fInds]), _nla.norm(check_vp), _nla.norm(prMxToFill[fInds] - check_vp))) # pragma: no cover if dprMxToFill", "str(circuit[0:10]) + \" ... (len %d)\" % len(circuit) _warnings.warn(\"pr(%s) == nan\" % strToPrint)", "on each inner loop *iteration*!) #collect/gather results subtreeElementIndices = [t.final_element_indices(evalTree) for t in", "_np.exp(scaleCache[i]) #profiler.print_mem(\"DEBUGMEM: POINT1\"); profiler.comm.barrier() #evaluate operation sequences using tree (skip over the zero", "else: # evotype == \"densitymx\" ps = _np.real(_np.dot(Es, _np.dot(G, rho))) ps = ps.flatten()", "= \\ _mpit.distribute_slice(allDeriv2ColSlice, mySubComm) # Get slice into entire range of model params", "taking # a derivative of only a *subset* of all the gate's parameters", "The number of processor groups that will be assigned to subtrees of the", "length-1 list, as this doesn't index numpy arrays # like length>1 lists do...", "tensor (G(L+1) ... GN)^T ]] * vec( dG(L)/dij) ) # noqa # if", "but now will not alter scaleCache.\") #profiler.print_mem(\"DEBUGMEM: POINT2\"); profiler.comm.barrier() profiler.add_time(\"compute_dproduct_cache: serial\", tSerialStart) profiler.add_count(\"compute_dproduct_cache:", "sequences to create an evaluation tree out of (most likely because you want", "prMxToFill, dim=(KS,), so gather prMxToFill[felInds] (axis=0) profiler.add_time(\"MPI IPC\", tm) profiler.mem_check(\"bulk_fill_dprobs: post gather subtrees\")", "L < M} [ G1 ... G(L-1) tensor # noqa # ( unvec(", "hprMxToFill=None, clipTo=None): # compare with older slower version that should do the same", "i in evalTree.get_evaluation_order(): # combine iLeft + iRight => i # LEXICOGRAPHICAL VS", "parameters dGs = _np.empty((Gs.shape[0], 0, self.dim, self.dim), 'd') def calc_and_fill_p(spamTuple, fInds, gInds, pslc1,", "3) * scaleVals, 0, 3) # may overflow or get nans (invalid), but", "_np.int64) if len(relevant_gpindices) == 1: #Don't return a length-1 list, as this doesn't", "dim**2) # (nDerivCols1,nDerivCols2,dim**2) x = _np.dot(_np.transpose(hop_dopLabels[opLabel1], axes=(1, 2, 0)), x0); xv = x.view()", "POVM or Instrument labels). numSubtreeComms : int The number of processor groups that", "the derivative of the probability. clipTo : 2-tuple (min,max) to clip returned probability", "rholabel, elabels, circuit, clipTo, bUseScaling=False, time=None): \"\"\" Compute probabilities of a multiple \"outcomes\"", "not None. Set this to non-None to reduce amount of intermediate memory required.", "blk_wrtSlice2: dProdCache2 = dProdCache1; dGs2 = dGs1 else: dProdCache2 = self._compute_dproduct_cache( evalSubTree, prodCache,", "final values scaleVals = self._scaleExp(evalSubTree.final_view(scaleCache)) Gs = evalSubTree.final_view(prodCache, axis=0) # ( nCircuits, dim,", "_np.empty((1, self.Np)) for i in range(self.Np): dpr_dOps[0, i] = float(_np.dot(E, _np.dot(dprod_dOps[i], rho))) if", "_slct.list_to_slice(wrtFilter1) if (wrtFilter1 is not None) else None wrtSlice2 = _slct.list_to_slice(wrtFilter2) if (wrtFilter2", "to in the first (row) and second (col) derivative operations, respectively. wrtBlockSize2, wrtBlockSize2", "None. Only relevant when prMxToFill is not None. bUseScaling : bool, optional Whether", "dGs2 = _np.swapaxes(_np.swapaxes(dGs2, 0, 3) * scaleVals, 0, 3) # may overflow or", "dProdCache1; dGs2 = dGs1 else: dProdCache2 = self._compute_dproduct_cache( evalSubTree, prodCache, scaleCache, blk2Comm, blk_wrtSlice2)", "gpindices: relevant_gpindices.append(ii) obj_wrtFilter.append(list(gpindices).index(i)) relevant_gpindices = _np.array(relevant_gpindices, _np.int64) if len(relevant_gpindices) == 1: #Don't return", "# free Mem dProdCache1 = self._compute_dproduct_cache( evalTree, prodCache, scaleCache, comm, wrtSlice1) dGs1 =", "== oplabel} [ G1 ... G(L-1) dG(L)/dij G(L+1) ... GN ] , a", "# overflow OK d2pr_drhos2 = _np.transpose(d2pr_drhos2, (0, 2, 1)) # Get: d2pr_dEs[i, j,", "---------- mxToFill : numpy ndarray an already-allocated ExM numpy array where E is", "owners #if mySubSubComm.Get_rank() > 0: myDeriv2ColSlice = slice(0,0) # #don't compute anything on", "# return PrepEffectFilter(rho_local_slices=loc_rho_slices, # rho_global_slices=global_rho_slices, # e_local_slices=loc_e_slices, # e_global_slices=global_e_slices, # num_rho_params=_slct.length(wrtSlices['preps']), # num_e_params=_slct.length(wrtSlices['effects']))", "= 0 # END SPAM DERIVS ----------------------- ret = d2pr_d2rhos + d2pr_dErhos2 +", "profiler.add_time(\"bulk_fill_dprobs: calc_and_fill_blk\", tm) for iBlk in myBlkIndices: tm = _time.time() block_wrtSlice = blocks[iBlk]", "Returns ------- block_generator A generator which, when iterated, yields the 3-tuple `(rowSlice, colSlice,", "dproduct cache mem += cache_size * dim * dim # product cache mem", "import time as _time import itertools as _itertools import collections as _collections from", "we want: # since then matrixOf(circuit[i]) = matrixOf(circuit[iLeft]) * matrixOf(circuit[iRight]) (iRight, iLeft) =", "1D numpy array of length equal to the total number of computed elements", "Return a shallow copy of this MatrixForwardSimulator \"\"\" return MatrixForwardSimulator(self.dim, self.sos, self.paramvec) def", "(dim**2, dim**2) x = _np.dot(_np.transpose(dop_dopLabel1[opLabel1]), x0); xv = x.view() # (nDerivCols1,dim**2) xv.shape =", "d12_col is a column of the matrix d12 defined by: d12[iSpamLabel,iOpStr,p1,p2] = dP/d(p1)*dP/d(p2)", "dProdCache2 = dProdCache1; dGs2 = dGs1 else: dProdCache2 = self._compute_dproduct_cache( evalSubTree, prodCache, scaleCache,", "flattened operation sequence product with respect to the k-th then j-th model parameters.", "None) else len(wrtFilter2) flattened_d2prod = _np.zeros((dim**2, num_deriv_cols1, num_deriv_cols2), 'd') # For each pair", "scaleCache = self._compute_product_cache(evalSubTree, mySubComm) profiler.add_time(\"bulk_fill_dprobs: compute_product_cache\", tm) #use cached data to final values", "my_results = self._compute_dproduct_cache( evalTree, prodCache, scaleCache, None, myDerivColSlice, profiler) # pass None as", "occur here _np.seterr(**old_err) return scaleVals def _rhoE_from_spamTuple(self, spamTuple): assert(len(spamTuple) == 2) if isinstance(spamTuple[0],", "= B^T tensor A * vec( X ) def doperation(self, opLabel, flat=False, wrtFilter=None):", "and hProdCache[i].min() > -HSMALL: _warnings.warn(\"Scaled hProd small in order to keep prod managable.\")", "when not None, an already-allocated ExM numpy array that is filled with probability", "pslc1, pslc2], self._hprobs_from_rhoE( spamTuple, rho, E, Gs[gInds], dGs1[gInds], dGs2[gInds], hGs[gInds], scaleVals[gInds], wrtSlice1, wrtSlice2),", "= self.Np if wrtSlice2 is None else _slct.length(wrtSlice2) #flt1 = self._get_filter_info(wrtSlices1) #flt2 =", "[blkSize = {%.1f,%.1f}, nBlks={%d,%d}]\" % (blkSize1, blkSize2, nBlks1, nBlks2)) # pragma: no cover", "== \"bulk_product\": # mem += cache_size * dim * dim # product cache", "gInds) in evalTree.spamtuple_indices.items(): circuit_list = master_circuit_list[gInds] if prMxToFill is not None: check_vp =", "gate parameters if wrtSlice1 == wrtSlice2: # Note: this doesn't involve gate derivatives", "holds the derivative of the (k,l)-th entry of the product with respect to", "None prodCache = scaleCache = dProdCache = None #Fill cache info (not requiring", "the parameters being differentiated with respect to (see wrtBlockSize). wrtFilter : list of", "tree into. num_subtree_proc_groups : int The number of processor groups used to (in", "None, None] # overflow OK devec = EVec.deriv_wrt_params(E_wrtFilter1) _fas(d2pr_dEs2, [None, None, E_gpindices1], _np.dot(dp_dAnyE,", "dop_dopLabel = gate.deriv_wrt_params(op_wrtFilter) for (i, gl) in enumerate(revOpLabelList): if gl != opLabel: continue", "needed now that we track owners #if mySubSubComm.Get_rank() > 0: myDeriv2ColSlice = slice(0,0)", "norm %g, exp %g\\n%s\" % (i,p,norm(G),total_exp,str(G)) # if _np.isnan(p): raise ValueError(\"STOP\") if clipTo", "Compute the derivative of a specified sequence of operation labels. Parameters ---------- circuit", "params, so # all hessians for single- or zero-operation sequences are zero. hProdCache[i]", "trace or other linear operation to be done prior to the scaling. \"\"\"", "Only returned when bScale == True. A length-S array specifying the scaling that", "of a operation matrix (G x G operation matrices). and deriv[i,j,k] holds the", "vp[i] = sum_k,l E[0,k] Gs[i,k,l] rho[l,0] * scaleVals[i] # vp[i] = sum_k E[0,k]", "to verify correctness, generating warnings when checks fail. Used for testing, and runs", "removed. if comm is not None: # ignoring comm since can't do anything", "old_err = _np.seterr(over='ignore') scaleExps = evalTree.final_view(scaleCache) scaleVals = _np.exp(scaleExps) # may overflow, but", "each given (i,j) # noqa # d2prod/d(opLabel1)_kl*d(opLabel2)_ij = sum_{M s.t. GM == gatelabel1}", "------- int \"\"\" return int(1.3 * nCircuits) def construct_evaltree(self, simplified_circuits, numSubtreeComms): \"\"\" Constructs", "return _np.swapaxes(flattened_dprod, 0, 1).reshape((num_deriv_cols, dim, dim)) def hoperation(self, opLabel, flat=False, wrtFilter1=None, wrtFilter2=None): \"\"\"", "# dp_dEs[i,J0+J] = sum_j dEP[j,J] dot(Gs, rho)[i,j] # dp_dEs[i,J0+J] = sum_j dot(Gs, rho)[i,j,0]", "* prods[i]). \"\"\" prodCache, scaleCache = self._compute_product_cache(evalTree, comm) #use cached data to construct", "Es = self._rhoEs_from_spamTuples(rholabel, elabels) #shapes: rho = (N,1), Es = (len(elabels),N) if bUseScaling:", "rho = self.sos.get_prep(rholabel).todense()[:, None] Es = [self.sos.get_effect(elabel).todense()[:, None] for elabel in elabels] Es", "numpy ndarray an already-allocated ExM numpy array where E is the total number", "the generator and yielded, *not* allocated by the user. mem += 2 *", "collections as _collections from ..tools import mpitools as _mpit from ..tools import slicetools", "if bScale else (dGs, Gs) else: dGs = evalTree.final_view(dProdCache, axis=0) #shape == (", "_np.squeeze(_np.dot(E, _np.dot(hGs, rho)), axis=(0, 4)) * scaleVals[:, None, None] _np.seterr(**old_err2) # may overflow,", "parameters. derivs1, derivs2 : numpy array Only returned if bReturnDProdsAndProds == True. *", "overflow, but OK if infs occur here _np.seterr(**old_err) if bReturnDProdsAndProds: Gs = evalTree.final_view(prodCache,", "Compute the outcome probability-derivatives for an entire tree of gate strings. Similar to", "0, comm, gatherMemLimit) if deriv1MxToFill is not None: _mpit.gather_indices(subtreeElementIndices, subTreeOwners, deriv1MxToFill, [], 0,", "= _np.swapaxes(_np.swapaxes(dGs, 0, 1).reshape( (nDerivCols, nCircuits * dim**2)), 0, 1) # cols =", "set to True, additionally return the probabilities and their derivatives (see below). bScale", "which is a functionality needed to correctly handle the remainder spam label. \"\"\"", "model parameters. Parameters ---------- spamTuple : (rho_label, simplified_effect_label) Specifies the prep and POVM", "of shape S x G x G, where: - S == the number", "Distribution is performed over subtrees of evalTree (if it is split). Returns -------", "values for this spam label (given by the subsequent arguments, except for the", "an inf scaleVal is mult by a zero deriv value (see below) dGs2[_np.isnan(dGs2)]", "- S is the number of operation sequences (i.e. evalTree.num_final_strings()), - B is", "G^2)-th flattened operation sequence product with respect to the j-th model parameter. products", "as comm, *not* mySubComm (this is ok, see \"if\" condition above) _mpit.gather_slices(deriv1Slices, deriv1Owners,", "of evalTree (if it is split), and then over blocks (subsets) of the", "mxToFill[felInds], dim=(ks,M,M) _mpit.gather_slices(blocks1, blk1Owners, mxToFill, [felInds], 1, mySubComm, gatherMemLimit) if deriv1MxToFill is not", "# for i in range(len(self.preps)) ] # # loc_e_slices = [ # _slct.shift(_slct.intersect(", "dim, dim ) hProdCache = self._compute_hproduct_cache(evalSubTree, prodCache, dProdCache1, dProdCache2, scaleCache, mySubComm, wrtSlice1, wrtSlice2)", "in opsToVectorize1 and opsToVectorize2 we only compute d2(prod)/d(gl1)d(gl2) # and not d2(prod)/d(gl2)d(gl1) ...", "dProdCache2 = self._compute_dproduct_cache( evalSubTree, prodCache, scaleCache, blk2Comm, blk_wrtSlice2) dGs2 = evalSubTree.final_view(dProdCache2, axis=0) hProdCache", "and wrtSlice1.start is not None: myHessianSlice1 = _slct.shift(myDeriv1ColSlice, wrtSlice1.start) else: myHessianSlice1 = myDeriv1ColSlice", "dLdR_sym = dLdRa + _np.swapaxes(dLdRb, 0, 1) hProdCache[i] = _np.dot(hL, R) + dLdR_sym", "compute one triangle of hessian # Note: d2pr_d2rhos and d2pr_d2Es terms are always", "cache info tm = _time.time() dProdCache = self._compute_dproduct_cache(evalSubTree, prodCache, scaleCache, mySubComm, wrtSlice, profiler)", "s.t. G(L) == oplabel} [ (G1 ... G(L-1)) tensor (G(L+1) ... GN)^T vec(", "hGs[_np.isnan(hGs)] = 0 # assume the zero hessian value trumps since we've renormed", "the same as the elements of `result_tup`. The fill function computes values for", "= scaleCache = None #Fill cache info prodCache, scaleCache = self._compute_product_cache(evalSubTree, mySubComm) #use", "*non-final* elements from those of the sub-trees). Note also that there would be", "compute? wrtLen1 = (self.Np + np1 - 1) // np1 # ceiling(num_params /", "loop over locations of opLabel LRproduct = _np.kron(leftProds[i], rightProdsT[N - 1 - i])", "of parameter columns (the length of colSlice) If `mx`, `dp1`, and `dp2` are", "int or float, optional The maximum number of derivative columns to compute *products*", "None and comm.Get_size() > 1: # parallelize of deriv cols, then sub-trees (if", "and gate-sequence indices # gInds = \"gate sequence indices\" = indices into the", "E_gpindices = self._process_wrtFilter(wrtSlice, self.sos.get_effect(elabel)) nDerivCols = self.Np if wrtSlice is None else _slct.length(wrtSlice)", "evalTree.num_final_elements()) and M1 & M2 are the number of selected gate-set parameters (by", "for each given (i,j,k,l) # noqa # vec( d2prod/d(opLabel1)_kl*d(opLabel2)_ij ) = sum{...} [", "isn't currently needed. N = len(revOpLabelList) for m, opLabel1 in enumerate(revOpLabelList): inds1 =", "(dim**2, nParams[opLabel]) if flat: return flattened_dprod else: # axes = (gate_ij, prod_row, prod_col)", "inf scaleVal is mult by a zero hessian value, and we hGs[_np.isnan(hGs)] =", "import collections as _collections from ..tools import mpitools as _mpit from ..tools import", "(dim**2, nParams in wrtFilter for opLabel) if flat: return flattened_dprod else: # axes", "linear dependence on their parameters. if self.sos.get_prep(rholabel).has_nonzero_hessian(): derivWrtAnyRhovec = scale * _np.dot(E, prod)", "comm_blkSize blkSize2 = comm_blkSize if (blkSize2 is None) \\ else min(comm_blkSize, blkSize2) #", "OK # get d2pr_drhos where gate derivatives are wrt the 2nd set of", "EVec.deriv_wrt_params(E_wrtFilter1) _fas(d2pr_dErhos1, (None, E_gpindices1, rho_gpindices2), _np.swapaxes(_np.dot(_np.transpose(devec), dp_dAnyE), 0, 1)) # get d2pr_dEs where", "a single flattened gate (ordering same as numpy.flatten), - S,M == as above,", "comm.Get_size()) # parallelize of deriv cols, then sub-trees (if available and necessary) if", "being differentiated with respect to (see wrtBlockSize). wrtFilter1, wrtFilter2 : list of ints,", "self._fill_result_tuple((prMxToFill, deriv1MxToFill, deriv2MxToFill, mxToFill), evalSubTree, slice(None), slice(None), calc_and_fill) else: # Divide columns into", "comm to distribute columns allDerivColSlice = slice(0, nDerivCols) if (wrtSlice is None) else", "argument must be None if wrtFilter is not None. Set this to non-None", "mxToFill, clipTo=clipTo) profiler.add_time(\"bulk_fill_dprobs: total\", tStart) profiler.add_count(\"bulk_fill_dprobs count\") profiler.mem_check(\"bulk_fill_dprobs: end\") def bulk_fill_hprobs(self, mxToFill, evalTree,", "norm <= 1 assert(len(nanOrInfCacheIndices) == 0) return prodCache, scaleCache def _compute_dproduct_cache(self, evalTree, prodCache,", "gathered until now (but using blk1Comm). # (just as prMxToFill is computed fully", "[None, E_gpindices], _np.dot(dp_dAnyE, EVec.deriv_wrt_params(E_wrtFilter))) sub_vdp = dp_drhos + dp_dEs + dp_dOps return sub_vdp", "order to keep prod managable.\") elif _np.count_nonzero(dProdCache[i]) and dProdCache[i].max() < DSMALL and dProdCache[i].min()", "all else dGs1 = _np.swapaxes(_np.swapaxes(dGs1, 0, 1).reshape((nDerivCols1, nCircuits * dim**2)), 0, 1) #", "of cache are given by evalTree's initial single- or zero-operation labels wrtIndices1 =", "x B', where: - K is the length of spam_label_rows, - S is", "\\ d2pr_dEs + _np.transpose(d2pr_dEs, (0, 2, 1)) + \\ d2pr_d2rhos + d2pr_d2Es +", "def bulk_fill_dprobs(self, mxToFill, evalTree, prMxToFill=None, clipTo=None, check=False, comm=None, wrtFilter=None, wrtBlockSize=None, profiler=None, gatherMemLimit=None): \"\"\"", "elif l < m: x0 = _np.kron(_np.transpose(prods[(l + 1, m - 1)]), prods[(m", "= _np.dot(E, _np.dot(prod, rho)) * scale # may generate overflow, but OK if", "entire operation sequence # with respect to only that gate's parameters and fill", "for parallelization of # _compute_product_cache when the tree was split, but this is", "is None) # cannot specify both wrtFilter and blkSize nBlks1 = int(_np.ceil(self.Np /", "> 0: myDeriv2ColSlice = slice(0,0) # #don't compute anything on \"extra\", i.e. rank", "self.Np)) derivWrtAnyEvec = _np.squeeze(_np.dot(dprod_dOps, rho), axis=(2,)) _fas(d2pr_dEs, [0, None, EVec.gpindices], _np.dot(derivWrtAnyEvec, EVec.deriv_wrt_params())) d2pr_dErhos", "#Note: these 2nd derivatives are non-zero when the spam vectors have # a", "blk2Comm = \\ _mpit.distribute_indices(list(range(nBlks2)), blk1Comm) if blk2Comm is not None: _warnings.warn(\"Note: more CPUs(%d)\"", "\\ d2pr_drhos + _np.transpose(d2pr_drhos, (0, 2, 1)) + \\ d2pr_dEs + _np.transpose(d2pr_dEs, (0,", "else min(comm_blkSize, blkSize2) # override with smaller comm_blkSize else: blkSize1 = blkSize2 =", "= hGs = dProdCache2 = dGs2 = None # free mem if bReturnDProbs12:", "do... ugh. relevant_gpindices = slice(0, 0) # slice that results in a zero", "'d') if _slct.length(gpindices1) > 0 and _slct.length(gpindices2) > 0: # works for arrays", "i in enumerate(wrtFilter): if i in gpindices: relevant_gpindices.append(ii) obj_wrtFilter.append(list(gpindices).index(i)) relevant_gpindices = _np.array(relevant_gpindices, _np.int64)", "of each of the product components (i.e. prod_kl) with # respect to a", "effect parameters onto a final \"filtered\" set. # \"\"\" # PrepEffectFilter = _collections.namedtuple(", "myHessianSlice1 = _slct.shift(myDeriv1ColSlice, wrtSlice1.start) else: myHessianSlice1 = myDeriv1ColSlice #print(\"MPI: _compute_hproduct_cache over %d cols", "# d2pr_drhos[i,j,J0+J] = sum_kl E[0,k] dGs[i,j,k,l] drhoP[l,J] # d2pr_drhos[i,j,J0+J] = dot(E, dGs, drhoP)[0,i,j,J]", "_mpit.slice_up_range(self.Np, nBlks1) blocks2 = _mpit.slice_up_range(self.Np, nBlks2) #distribute derivative computation across blocks myBlk1Indices, blk1Owners,", "# LEXICOGRAPHICAL VS MATRIX ORDER # we do matrix multiplication in this order", "if dG(L)/dij = E(i,j) # noqa # = vec(i,j)-col of [ sum_{L s.t.", "additionally return the probabilities and their derivatives (see below). bScale : bool, optional", "dim = self.dim gate = self.sos.get_operation(opLabel) op_wrtFilter1, gpindices1 = self._process_wrtFilter(wrtFilter1, gate) op_wrtFilter2, gpindices2", "(I think) _fas(flattened_dprod, [None, gpindices], gate.deriv_wrt_params(op_wrtFilter)) # (dim**2, nParams in wrtFilter for opLabel)", "= (KM,N,N') yield wrtSlice1, wrtSlice2, hprobs, dprobs12 else: yield wrtSlice1, wrtSlice2, hprobs dProdCache1", "_slct.length(wrtSlice1) nDerivCols2 = self.Np if wrtSlice2 is None else _slct.length(wrtSlice2) #flt1 = self._get_filter_info(wrtSlices1)", "\" _compute_dproduct_cache.\") if mySubComm.Get_rank() > 0: myDerivColSlice = slice(0, 0) #don't compute anything", "cache_size * num_params * dim * dim # dproduct cache # mem +=", "python objects (never seemed very useful ## since numpy does all the major", "# (dim**2, dim**2) x = _np.dot(_np.transpose(dop_dopLabel1[opLabel1]), x0); xv = x.view() # (nDerivCols1,dim**2) xv.shape", "is None else _slct.length(wrtSlice1) nDerivCols2 = self.Np if wrtSlice2 is None else _slct.length(wrtSlice2)", "previous subtree iteration before computing caches scaleVals = Gs = dGs1 = dGs2", "\\ else min(comm_blkSize, blkSize1) # override with smaller comm_blkSize blkSize2 = comm_blkSize if", "* nDerivCols2: #If there are more processors than deriv cells, give a #", "scale * _np.transpose(_np.dot(prod, rho)) # may overflow, but OK # (** doesn't depend", "+= cache_size * wrtLen1 * wrtLen2 * dim * dim # hproduct cache", "elements (no POVM or Instrument labels). numSubtreeComms : int The number of processor", "= self.Np if (wrtFilter is None) else _slct.length(wrtFilter) dim = self.dim wrtSlice =", "Compute and fill result quantities for given arguments \"\"\" old_err = _np.seterr(over='ignore') rho,", "distribution across subtrees (groups if needed) subtrees = evalTree.get_sub_trees() mySubTreeIndices, subTreeOwners, mySubComm =", "= None # keep last dProdCache1 for wrtSlice1, wrtSlice2 in wrtSlicesList: if wrtSlice1", "short, parallelization should be done at a higher level. \"\"\" dim = self.dim", "myHessianSlice2 = _slct.shift(myDeriv2ColSlice, wrtSlice2.start) else: myHessianSlice2 = myDeriv2ColSlice if mySubSubComm is not None", "noqa # # So for each opLabel the matrix [ sum_{L s.t. GL", "been removed. if comm is not None: # ignoring comm since can't do", "rho, E = self._rhoE_from_spamTuple(spamTuple) _fas(mxToFill, [fInds], self._probs_from_rhoE(rho, E, Gs[gInds], scaleVals[gInds]), add=sumInto) _np.seterr(**old_err) self._fill_result_tuple((mxToFill,),", "* (dim**2,nDerivCols2) = (nDerivCols1,dim**2,nDerivCols2) flattened_d2prod[:, inds1, inds2] += _np.swapaxes(y, 0, 1) # above:", "rho_wrtFilter1, rho_gpindices1 = self._process_wrtFilter(wrtSlice1, self.sos.get_prep(rholabel)) rho_wrtFilter2, rho_gpindices2 = self._process_wrtFilter(wrtSlice2, self.sos.get_prep(rholabel)) E_wrtFilter1, E_gpindices1 =", "a length-1 (single-gate) sequence \"\"\" dim = self.dim gate = self.sos.get_operation(opLabel) op_wrtFilter1, gpindices1", "an estimate of the ideal/desired cache size given a number of operation sequences.", "by the user. mem += 2 * cache_size * nspam * wrtLen1 *", "prodCache, scaleCache, comm, wrtSlice2) hProdCache = self._compute_hproduct_cache(evalTree, prodCache, dProdCache1, dProdCache2, scaleCache, comm, wrtSlice1,", "data to final values scaleVals = self._scaleExp(evalSubTree.final_view(scaleCache)) Gs = evalSubTree.final_view(prodCache, axis=0) # (", "array of shape S such that scaleVals[i] contains the multiplicative scaling needed for", "2) # as above return (hGs, scaleVals) if bScale else hGs def _scaleExp(self,", "a boolean specifying whether the filling should overwrite or add to the existing", "sub-trees (if available and necessary) if comm.Get_size() > nDerivCols: #If there are more", "dGs1 and dGs2 are already sized/filtered) -------- assert(dGs1.shape[1] == nDerivCols1), \"dGs1 must be", "operation sequences to create an evaluation tree out of (most likely because you", "for an entire tree of operation sequences. This routine fills a 1D array,", "deriv1MxToFill = dprobs1 deriv2MxToFill = dprobs2 mxToFill = hprobs #Fill arrays self._fill_result_tuple((None, dprobs1,", "B x B', where: - K is the length of spam_label_rows, - S", "_np.zeros((nElements, _slct.length(wrtSlice1), _slct.length(wrtSlice2)), 'd') #prMxToFill = None deriv1MxToFill = dprobs1 deriv2MxToFill = dprobs2", "and save in return list (now have G,dG => product, dprod_dOps) # prod,", "None. Returns ------- derivative : numpy array a 1 x M numpy array", "sorted(list(set(revOpLabelList))) used_operations = _collections.OrderedDict() #Cache processed parameter filters for multiple uses below gpindices1", "numpy array * if flat == False, a M x M x G", "probability to if not None. Only relevant when prMxToFill is not None. bUseScaling", "= self._process_wrtFilter(wrtFilter, gate) dop_dopLabel = gate.deriv_wrt_params(op_wrtFilter) for (i, gl) in enumerate(revOpLabelList): if gl", "range of model params so that # per-gate hessians can be computed properly", "of 1st (row) and 2nd (col) derivatives to compute *products* for simultaneously. None", "instrument elements like 'Imyinst_0') returnPr : bool when set to True, additionally return", "1) hGs = _np.rollaxis(_np.rollaxis(hGs, 0, 3).reshape( (nDerivCols1, nDerivCols2, nCircuits * dim**2)), 2) #", "#Fill arrays self._fill_result_tuple((None, dprobs1, dprobs2, hprobs), evalTree, slice(None), slice(None), calc_and_fill) hProdCache = hGs", "(mxToFill,), evalSubTree, blocks[iBlk], slice(None), calc_and_fill_blk) profiler.mem_check(\"bulk_fill_dprobs: post fill blk\") dProdCache = dGs =", "raw operation sequences for spamTuple, (fInds, gInds) in evalTree.spamtuple_indices.items(): circuit_list = master_circuit_list[gInds] if", "resulting products (final_product[i] = scaleValues[i] * prods[i]). \"\"\" prodCache, scaleCache = self._compute_product_cache(evalTree, comm)", "if bReturnDProbs12: dprobs12 = dprobs1[:, :, None] * dprobs2[:, None, :] # (KM,N,1)", "_fas(prMxToFill, [fInds], self._probs_from_rhoE(rho, E, Gs[gInds], scaleVals[gInds]), add=sumInto) _np.seterr(**old_err) profiler.add_time(\"bulk_fill_dprobs: calc_and_fill_p\", tm) # Compute", "of operation sequences. Returns ------- int \"\"\" return int(1.3 * nCircuits) def construct_evaltree(self,", "done over operation sequences when a *split* evalTree is given, otherwise no parallelization", "else: if returnPr: return ret, p else: return ret ## BEGIN CACHE FUNCTIONS", "vec(.) concatenates rows (which numpy.flatten does) # vec( A * E(0,1) * B", "parameters and fill appropriate columns of flattened_dprod. _fas(flattened_hprod, [None, gpindices1, gpindices2], gate.hessian_wrt_params(op_wrtFilter1, op_wrtFilter2))", "bScale == True. A length-S array specifying the scaling that needs to be", "blocks (subsets) of the parameters being differentiated with respect to (see wrtBlockSize). wrtFilter1,", "# same as in dpr(...) dpr_drhos = _np.zeros((1, self.Np)) derivWrtAnyRhovec = scale *", "available processors is used as the final block size. These arguments must be", "None: myHessianSlice1 = _slct.shift(myDeriv1ColSlice, wrtSlice1.start) else: myHessianSlice1 = myDeriv1ColSlice #print(\"MPI: _compute_hproduct_cache over %d", "= sorted(list(set(revOpLabelList))) used_operations = _collections.OrderedDict() #Cache processed parameter filters for multiple uses below", "= _slct.indices(wrtSlice2) if (wrtSlice2 is not None) else None for i, opLabel in", "shape S*N x M where - N == the number of entries in", "return G def _process_wrtFilter(self, wrtFilter, obj): \"\"\" Helper function for doperation and hoperation", "True. A 1 x M numpy array of derivatives of the probability w.r.t.", "hProdCache[:, myDeriv1ColSlice, myDeriv2ColSlice] = self._compute_hproduct_cache( evalTree, prodCache, dProdCache1[:, myDeriv1ColSlice], dProdCache2[:, myDeriv2ColSlice], scaleCache, None,", "Returns ------- numpy.ndarray An array of floating-point probabilities, corresponding to the elements of", "ith string if not bScale: old_err = _np.seterr(over='ignore', invalid='ignore') Gs = _np.swapaxes(_np.swapaxes(Gs, 0,", "since we can't tell whether it's + or - inf anyway... dp_dOps[_np.isnan(dp_dOps)] =", "overflow, but ok _np.seterr(**old_err) return Gs def bulk_dproduct(self, evalTree, flat=False, bReturnProds=False, bScale=False, comm=None,", "scaleCache = self._compute_product_cache(evalSubTree, mySubComm) scaleVals = self._scaleExp(evalSubTree.final_view(scaleCache)) Gs = evalSubTree.final_view(prodCache, axis=0) #( nCircuits,", "1 assert(len(nanOrInfCacheIndices) == 0) return prodCache, scaleCache def _compute_dproduct_cache(self, evalTree, prodCache, scaleCache, comm=None,", "IPC\", tm) profiler.mem_check(\"bulk_fill_dprobs: post gather blocks\") #collect/gather results tm = _time.time() subtreeElementIndices =", "when a *split* evalTree is given, otherwise no parallelization is performed. Returns -------", "arguments \"\"\" tm = _time.time() old_err = _np.seterr(over='ignore') rho, E = self._rhoE_from_spamTuple(spamTuple) if", "nDerivCols)) _fas(dp_drhos, [None, rho_gpindices], _np.squeeze(_np.dot(_np.dot(E, Gs), rhoVec.deriv_wrt_params(rho_wrtFilter)), axis=(0,)) * scaleVals[:, None]) # may", "storage arrays are. np1, np2 = num_param1_groups, num_param2_groups FLOATSIZE = 8 # in", "_np.seterr(over='ignore') scaleVals = _np.exp(scaleExps) # may overflow, but OK if infs occur here", "Hessian of many operation sequence products at once. Parameters ---------- evalTree : EvalTree", "wrtSlice1 == wrtSlice2: # TODO: better check for equivalence: maybe let dGs2 be", "just like in bulk_fill_probs(...). derivMxToFill1, derivMxToFill2 : numpy array, optional when not None,", "# ceiling(num_params / np1) wrtLen2 = (self.Np + np2 - 1) // np2", "profiler.add_time(\"bulk_fill_dprobs: total\", tStart) profiler.add_count(\"bulk_fill_dprobs count\") profiler.mem_check(\"bulk_fill_dprobs: end\") def bulk_fill_hprobs(self, mxToFill, evalTree, prMxToFill=None, deriv1MxToFill=None,", "scaledGatesAndExps[lOp] = (opmx / ng, _np.log(ng)) gate, ex = scaledGatesAndExps[lOp] H = _np.dot(gate,", ") #dGs = clip(dGs,-1e300,1e300) _np.seterr(**old_err) if flat: dGs = _np.swapaxes(_np.swapaxes(dGs, 0, 1).reshape( (nDerivCols,", "(model_parameter1, model_parameter2, model_element_row, model_element_col) def prs(self, rholabel, elabels, circuit, clipTo, bUseScaling=False, time=None): \"\"\"", "j, E_gpindices] = dot(transpose(dE/dEP),dGs[i,j],rho) # d2pr_dEs[i,j,J0+J] = sum_kl dEPT[J,k] dGs[i,j,k,l] rho[l,0] # d2pr_dEs[i,j,J0+J]", "mult by a zero hessian value (see below) hGs[_np.isnan(hGs)] = 0 _np.seterr(**old_err) if", "of matrices. Parameters ---------- circuit : Circuit or tuple of operation labels The", "tree construction by giving the tree information it needs to distribute itself among", "E[0,k] dGs[i,j,k,l] rho[l,0] # dp_dOps[i,j] = sum_k E[0,k] dot( dGs, rho )[i,j,k,0] #", "for the hessians, derivatives, and/or products for the i-th operation sequence. \"\"\" dim", "distribute wrtSlicesList across comm procs, # as we assume the user has already", "_, myDerivColSlice, _, mySubComm = \\ _mpit.distribute_slice(allDerivColSlice, comm) #print(\"MPI: _compute_dproduct_cache over %d cols", "if (wrtSlice is None) else wrtSlice _, myDerivColSlice, _, mySubComm = \\ _mpit.distribute_slice(allDerivColSlice,", "elements are at most linear in params, so # all hessians for single-", "infs occur here _np.seterr(**old_err) if bScale: return Gs, scaleVals else: old_err = _np.seterr(over='ignore')", "maximum number of 1st (row) and 2nd (col) derivatives to compute *products* for", "B is the number of parameter rows (the length of rowSlice) - B'", "..tools import slicetools as _slct from ..tools.matrixtools import _fas from .profiler import DummyProfiler", "operation sequence products at once. Parameters ---------- evalTree : EvalTree given by a", "else: G = H old_err = _np.seterr(over='ignore') scale = _np.exp(scale_exp) _np.seterr(**old_err) return G,", "the product with respect to the i-th model parameter. * if flat ==", "gate, ex = scaledGatesAndExps[lOp] H = _np.dot(gate, G) # product of gates, starting", "wrtFilter1=None, wrtFilter2=None, wrtBlockSize1=None, wrtBlockSize2=None, gatherMemLimit=None): \"\"\" Compute the outcome probability-Hessians for an entire", "#Cache partial products (relatively little mem required) leftProds = [] G = _np.identity(dim);", "wrtFilter2=wrtIndices2) hProdCache[i] = hoperation / _np.exp(scaleCache[i]) #evaluate operation sequences using tree (skip over", "\"\"\" super(MatrixForwardSimulator, self).__init__( dim, simplified_op_server, paramvec) if self.evotype not in (\"statevec\", \"densitymx\"): raise", "routine fills a 1D array, `mxToFill` with the probabilities corresponding to the *simplified*", "flattened_dprod. _fas(flattened_hprod, [None, gpindices1, gpindices2], gate.hessian_wrt_params(op_wrtFilter1, op_wrtFilter2)) if flat: return flattened_hprod else: return", "for testing, and runs much slower when True. comm : mpi4py.MPI.Comm, optional When", "* vec( dG(L)/dij) ) # noqa # if dG(L)/dij = E(i,j) # noqa", "check=False, comm=None, wrtFilter1=None, wrtFilter2=None, wrtBlockSize1=None, wrtBlockSize2=None, gatherMemLimit=None): \"\"\" Compute the outcome probability-Hessians for", "hprobs dProdCache1 = dGs1 = None # free mem def _fill_result_tuple(self, result_tup, evalTree,", "the first two arguments), and in general only a specified slice of the", "\"bulk_fill_dprobs: post compute dproduct blk (expect \" \" +%.2fGB, shape=%s)\" % (dProdCache.nbytes /", "if infs occur here _np.seterr(**old_err) return scaleVals def _rhoE_from_spamTuple(self, spamTuple): assert(len(spamTuple) == 2)", "oplabel} [ (G1 ... G(L-1)) tensor (G(L+1) ... GN)^T ]] * vec( dG(L)/dij)", "of exponent # # p = _mt.trace( _np.dot(self.SPAMs[spamLabel],G) ) * exp(total_exp) # probability", "evalTree, bScale=False, comm=None): \"\"\" Compute the products of many operation sequences at once.", "array of shape S*N x M where - N == the number of", "if check: self._check(evalTree, mxToFill, clipTo=clipTo) def bulk_fill_dprobs(self, mxToFill, evalTree, prMxToFill=None, clipTo=None, check=False, comm=None,", "a tree of products in a linear cache space. Will *not* parallelize computation,", "if (mySubComm is not None) and (mySubComm.Get_size() > 1): comm_blkSize = self.Np /", "of `(rowSlice,colSlice)` 2-tuples, each of which specify a \"block\" of the Hessian to", "drhoP)[0,i,j,J] # d2pr_drhos[:,:,J0+J] = squeeze(dot(E, dGs, drhoP),axis=(0,))[:,:,J] drho = rhoVec.deriv_wrt_params(rho_wrtFilter2) d2pr_drhos1 = _np.zeros((nCircuits,", "* GN , a matrix # noqa # dprod/d(opLabel)_ij = sum_{L s.t. G(L)", "rho)) * scale)**2) else: # evotype == \"densitymx\" # probability, with scaling applied", "None, None] # overflow OK devec = EVec.deriv_wrt_params(E_wrtFilter2) _fas(d2pr_dErhos2, [None, E_gpindices2, rho_gpindices1], _np.swapaxes(_np.dot(_np.transpose(devec),", "_mpit.slice_up_range(self.Np, nBlks, start=0) # Create placeholder dGs for *no* gate params to compute", "= _np.empty((Gs.shape[0], 0, self.dim, self.dim), 'd') def calc_and_fill_p(spamTuple, fInds, gInds, pslc1, pslc2, sumInto):", "multiple processors and to control memory usage. Cannot be specified in conjuction with", "derivatives to compute *products* for simultaneously. None means compute all requested rows or", "cache_size # scale cache mem += cache_size # scale vals ## It doesn't", "# dp_drhos[i,J0+J] = dot(E, Gs, drhoP)[0,i,J] # dp_drhos[:,J0+J] = squeeze(dot(E, Gs, drhoP),axis=(0,))[:,J] dp_drhos", "yet-to-be-defined local variables # wrtSlice1 and wrtSlice2, of the parent-function scope. This use", "self.sos.get_prep(rholabel).gpindices, self.sos.get_prep(rholabel).gpindices], _np.tensordot(derivWrtAnyRhovec, self.sos.get_prep(rholabel).hessian_wrt_params(), (1, 0))) # _np.einsum('ij,jkl->ikl', derivWrtAnyRhovec, self.sos.get_prep(rholabel).hessian_wrt_params()) else: d2pr_d2rhos =", "warnings as _warnings import numpy as _np import numpy.linalg as _nla import time", "ordering when taking derivatives. paramvec : ndarray The parameter vector of the Model.", "matrix (G x G operation matrices) and hessians[i,j,k,l,m] holds the derivative of the", "0, 4) # convert nans to zero, as these occur b/c an inf", "of hProdCache, # dim=(cacheSize,nDerivCols1,nDerivCols2,dim,dim) return hProdCache # ------------------------------------------------------------------ if evalTree.is_split(): _warnings.warn(\"Ignoring tree splitting", "(G1 ... G(L-1)) tensor (G(L+1) ... GN)^T ]] # noqa # # So", "dp_dEs[i,J0+J] = sum_lj dEPT[J,j] Gs[i,j,l] rho[l,0] # dp_dEs[i,J0+J] = sum_j dEP[j,J] dot(Gs, rho)[i,j]", "pragma: no cover # noqa for iBlk1 in myBlk1Indices: blk_wrtSlice1 = blocks1[iBlk1] dProdCache1", "if _nla.norm(prMxToFill[fInds] - check_vp) > 1e-6: _warnings.warn(\"norm(vp-check_vp) = %g - %g = %g\"", "set of parameters being differentiated with respect to. If there are more processors", "ignoring comm since can't do anything with it! #_warnings.warn(\"More processors than can be", "#collect/gather results tm = _time.time() subtreeElementIndices = [t.final_element_indices(evalTree) for t in subtrees] _mpit.gather_indices(subtreeElementIndices,", "where: - K is the length of spam_label_rows, - S is the number", "# pragma: no cover def calc_and_fill_blk(spamTuple, fInds, gInds, pslc1, pslc2, sumInto): \"\"\" Compute", "bulk_evaltree. Specifies the operation sequences to compute the bulk operation on. bScale :", "= None prodCache = scaleCache = None #Fill product cache info (not requiring", "derivative : numpy array a 1 x M numpy array of derivatives of", "---------- spam_label_rows : dictionary a dictionary with keys == spam labels and values", "is small (oh well!).\") return hProdCache ## END CACHE FUNCTIONS def default_distribute_method(self): \"\"\"", "None] # overflow OK d2pr_d2Es = _np.zeros((nCircuits, nDerivCols1, nDerivCols2)) _fas(d2pr_d2Es, [None, E_gpindices1, E_gpindices2],", "cover if hprMxToFill is not None: check_vhp = _np.concatenate( [self.hpr(spamTuple, circuit, False, False,", "OK (deriv w.r.t any of self.effects - independent of which) dp_dAnyE = _np.squeeze(_np.dot(Gs,", "dProdCache = self._compute_dproduct_cache(evalSubTree, prodCache, scaleCache, mySubComm, wrtSlice, profiler) dGs = evalSubTree.final_view(dProdCache, axis=0) #(", "= _np.clip(ps, clipTo[0], clipTo[1]) else: ret = ps #DEBUG CHECK #check_ps = _np.array(", "when set to True, additionally return the probability itself. returnDeriv : bool when", "list (now have G,dG => product, dprod_dOps) # prod, dprod_dOps = G,dG #", "never used) - so it's been removed. if comm is not None: #", "ndarray an already-allocated ExMxM numpy array where E is the total number of", ") # noqa # # Note: ignoring L == M terms assumes that", "of subcalls to computation functions. Parameters ---------- subcalls : list of strs A", "space. Will use derivative rows and columns and then (as needed) a split", "assume the user has already done any such distribution # and has given", "_mpit.distribute_slice(allDeriv2ColSlice, mySubComm) # Get slice into entire range of model params (see above)", "_np.seterr(**old_err) profiler.add_time(\"bulk_fill_dprobs: calc_and_fill_blk\", tm) for iBlk in myBlkIndices: tm = _time.time() block_wrtSlice =", "hop_dopLabels = {} for opLabel, gate in used_operations.items(): if gate.has_nonzero_hessian(): hop_dopLabels[opLabel] = gate.hessian_wrt_params(", "Compute the outcome probabilities for an entire tree of operation sequences. This routine", "* dprobs2[:, None, :] # (KM,N,1) * (KM,1,N') = (KM,N,N') yield wrtSlice1, wrtSlice2,", "& dprobs2 mem += cache_size * wrtLen1 * wrtLen2 * dim * dim", "evalSubTree, prodCache, scaleCache, blk1Comm, blk_wrtSlice1) dGs1 = evalSubTree.final_view(dProdCache1, axis=0) for iBlk2 in myBlk2Indices:", "_dummy_profiler dim = self.dim nDerivCols = self.Np if (wrtSlice is None) \\ else", "operation sequence product with respect to the k-th then j-th model parameters. *", "of the created tree. This aids in the tree construction by giving the", "\"\"\" Constructs a generator that computes the 2nd derivatives of the probabilities generated", "x.view() xv = _np.transpose(xv, axes=(2, 0, 1)) # (dim2, nDerivCols1, nDerivCols2) flattened_d2prod[:, inds1,", "_np.dot(dp_dAnyE, devec)) d2pr_dEs2 = _np.transpose(d2pr_dEs2, (0, 2, 1)) # Get: d2pr_dErhos[i, e_offset[eIndex]:e_offset[eIndex+1], e_offset[rhoIndex]:e_offset[rhoIndex+1]]", "_warnings.warn(\"norm(vdp-check_vdp) = %g - %g = %g\" % (_nla.norm(dprMxToFill[fInds]), _nla.norm(check_vdp), _nla.norm(dprMxToFill[fInds] - check_vdp)))", "_slct.length(wrtSlice2) == nDerivCols2) hessn_shape = (nDerivCols1, nDerivCols2, dim, dim) cacheSize = len(evalTree) #", "matrices should be dim x dim, and all SPAM vectors should be dim", "clipTo=None, check=False, comm=None, wrtFilter=None, wrtBlockSize=None, profiler=None, gatherMemLimit=None): \"\"\" Compute the outcome probability-derivatives for", "aids in the tree construction by giving the tree information it needs to", "# scale cache mem += cache_size # scale vals ## It doesn't make", "arguments \"\"\" tm = _time.time() old_err = _np.seterr(over='ignore') rho, E = self._rhoE_from_spamTuple(spamTuple) block_wrtSlice", "= \\ _mpit.distribute_indices(list(range(nBlks)), mySubComm) if blkComm is not None: _warnings.warn(\"Note: more CPUs(%d)\" %", "labels in the string which match the current # gate (so we only", "matrix multiplication in this order (easier to think about) revOpLabelList = tuple(reversed(tuple(circuit))) #", "d2pr_drhos = _np.zeros((1, self.Np, self.Np)) _fas(d2pr_drhos, [0, None, self.sos.get_prep(rholabel).gpindices], _np.dot(_np.dot(E, dprod_dOps), rhoVec.deriv_wrt_params())[0]) #", "allocated by the user. mem += 2 * cache_size * nspam * wrtLen1", "#If there are more processors than deriv cols, give a # warning --", "more CPUs(%d)\" % mySubComm.Get_size() + \" than hessian elements(%d)!\" % (self.Np**2) + \"", "scale vals else: raise ValueError(\"Unknown subcall name: %s\" % fnName) return mem *", "respectively - G == the linear dimension of a operation matrix (G x", "override with smaller comm_blkSize else: blkSize1 = blkSize2 = None # wrtFilter1 &", "part of MPI processor syncronization. Returns ------- None \"\"\" if wrtFilter1 is not", "automatically parallelized over these groups. num_param2_groups : int The number of groups to", "[ slice(tmp_offsets[i],tmp_offsets[i+1]) # for i in range(len(self.preps)) ] # # loc_e_slices = [", "def calc_and_fill_blk(spamTuple, fInds, gInds, pslc1, pslc2, sumInto): \"\"\" Compute and fill result quantities", "inf scaleVal is mult by a zero hessian value (see below) hGs[_np.isnan(hGs)] =", "0, 2) # may overflow, but ok # may overflow or get nans", "0, 3) # convert nans to zero, as these occur b/c an inf", "= x.view() # (nDerivCols1,dim**2) xv.shape = (nDerivCols1, dim, dim) # (reshape without copying", "nDerivCols1) allDeriv2ColSlice = slice(0, nDerivCols2) deriv1Slices, myDeriv1ColSlice, deriv1Owners, mySubComm = \\ _mpit.distribute_slice(allDeriv1ColSlice, comm)", "of the operation matrices. scale : float Only returned when bScale == True,", "DEBUG: Rank%d subtee sizes = %s\" % # (comm.Get_rank(),\",\".join([str(len(subtrees[i])) # for i in", "_fas(d2pr_dEs1, [None, None, E_gpindices2], _np.dot(dp_dAnyE, devec)) # get d2pr_dEs where gate derivatives are", "num_deriv_cols2 = self.Np if (wrtFilter2 is None) else len(wrtFilter2) flattened_d2prod = _np.zeros((dim**2, num_deriv_cols1,", "results; gather axis 1 of mxToFill[felInds], dim=(ks,M,M) _mpit.gather_slices(blocks1, blk1Owners, mxToFill, [felInds], 1, mySubComm,", "of which) dp_dAnyE = _np.squeeze(_np.dot(Gs, rho), axis=(2,)) * scaleVals[:, None] _fas(dp_dEs, [None, E_gpindices],", "the # *non-final* parent-tree elements from those of the sub-trees. _warnings.warn(\"Increased speed could", "by evalTree's initial single- or zero-operation labels for i, opLabel in zip(evalTree.get_init_indices(), evalTree.get_init_labels()):", "= (self.Np + np2 - 1) // np2 # ceiling(num_params / np2) mem", "set of gate parameters if dGs1 is dGs2 and wrtSlice1 == wrtSlice2: #", "dProdCache1 if (wrtSlice1 == wrtSlice2) else \\ self._compute_dproduct_cache(evalSubTree, prodCache, scaleCache, mySubComm, wrtSlice2) dGs1", "check_vp))) # pragma: no cover if dprMxToFill is not None: check_vdp = _np.concatenate(", "we only compute d2(prod)/d(gl1)d(gl2) # and not d2(prod)/d(gl2)d(gl1) ... if m < l:", "overflow, but OK _fas(d2pr_dErhos, [0, EVec.gpindices, self.sos.get_prep(rholabel).gpindices], _np.dot(_np.transpose(EVec.deriv_wrt_params()), derivWrtAnyEvec)) #Note: these 2nd derivatives", "x G operation matrices). scaleValues : numpy array Only returned when bScale ==", "Affects the shape of the returned derivative array (see below). bReturnProds : bool,", "_np.dot(L, R) scaleCache[i] = scaleCache[iLeft] + scaleCache[iRight] if prodCache[i].max() < PSMALL and prodCache[i].min()", "dLdRa + _np.swapaxes(dLdRb, 0, 1) hProdCache[i] = _np.dot(hL, R) + dLdR_sym + _np.transpose(_np.dot(L,", "taken. If there are more processors than model parameters, distribution over a split", "flat=False, bReturnProds=False, bScale=False, comm=None, wrtFilter=None): \"\"\" Compute the derivative of a many operation", "= _np.squeeze(_np.dot(dGs1, rho), axis=(3,)) * scaleVals[:, None, None] # overflow OK devec =", "across multiple processors. Distribution is first performed over subtrees of evalTree (if it", "dim x dim mxs corresponding to a single kl xv = _np.swapaxes(xv, 1,", "as prMxToFill is computed fully on each inner loop *iteration*!) #collect/gather results subtreeElementIndices", "evalTree.final_view(dProdCache1, axis=0) dGs2 = evalTree.final_view(dProdCache2, axis=0) #shape == ( len(circuit_list), nDerivColsX, dim, dim", "rhoVec.deriv_wrt_params(rho_wrtFilter1) d2pr_drhos2 = _np.zeros((nCircuits, nDerivCols2, nDerivCols1)) _fas(d2pr_drhos2, [None, None, rho_gpindices1], _np.squeeze(_np.dot(_np.dot(E, dGs2), drho),", "mem #gather column results: gather axis 2 of mxToFill[felInds,blocks1[iBlk1]], dim=(ks,blk1,M) _mpit.gather_slices(blocks2, blk2Owners, mxToFill,", "if not None. check : boolean, optional If True, perform extra checks within", "= _np.identity(self.dim) for lOp in circuit: G = _np.dot(self.sos.get_operation(lOp).todense(), G) # LEXICOGRAPHICAL VS", "each column corresponds to a (opLabel,i,j) tuple and each row corresponds to an", "spamTuple, rho, E, Gs[gInds], dGs2[gInds], scaleVals[gInds], wrtSlice2), add=sumInto) _fas(mxToFill, [fInds, pslc1, pslc2], self._hprobs_from_rhoE(", "compute anything on \"extra\", i.e. rank != 0, cpus my_results = self._compute_dproduct_cache( evalTree,", "`Circuits` was simplified. Parameters ---------- mxToFill : numpy ndarray an already-allocated 1D numpy", "subtree iteration before computing caches scaleVals = Gs = dGs = None prodCache", "used for to track timing and memory usage. gatherMemLimit : int, optional A", "EVec.gpindices], _np.dot(derivWrtAnyEvec, EVec.deriv_wrt_params())) _np.seterr(**old_err) if returnPr: return dpr_drhos + dpr_dEs + dpr_dOps, p", "None #Fill cache info prodCache, scaleCache = self._compute_product_cache(evalSubTree, mySubComm) #use cached data to", "per-gate with-respect-to parameter filters, used to # select a subset of all the", "probability to if not None. Only relevant when prMxToFill is not None. Returns", "subsequent arguments, except for the last). The final argument is a boolean specifying", "cannot specify both wrtFilter and blkSize nBlks = int(_np.ceil(self.Np / blkSize)) # num", "LEXICOGRAPHICAL VS MATRIX ORDER return G def _process_wrtFilter(self, wrtFilter, obj): \"\"\" Helper function", "# may overflow, but OK if infs occur here _np.seterr(**old_err) if bReturnDProdsAndProds: Gs", "prMxToFill is not None: self._fill_result_tuple((prMxToFill,), evalSubTree, slice(None), slice(None), calc_and_fill_p) profiler.mem_check(\"bulk_fill_dprobs: post fill probs\")", "blkSize2)) # num blocks required to achieve desired average size == blkSize1 or", "is not None and comm.Get_size() > 1: # parallelize of deriv cols, then", "_np.identity(self.dim) for lOp in circuit: if lOp not in scaledGatesAndExps: opmx = self.sos.get_operation(lOp).todense()", "there are more processors than deriv cols, give a # warning -- note", "wrtBlockSize wrtSlice = _slct.list_to_slice(wrtFilter) else: wrtSlice = None profiler.mem_check(\"bulk_fill_dprobs: begin (expect ~ %.2fGB)\"", ": numpy ndarray an already-allocated 1D numpy array of length equal to the", "#use cached data to final values scaleVals = self._scaleExp(evalSubTree.final_view(scaleCache)) Gs = evalSubTree.final_view(prodCache, axis=0)", "= sum_{L s.t. GL == oplabel} [ G1 ... G(L-1) dG(L)/dij G(L+1) ...", "[fInds, pslc1, pslc2], self._hprobs_from_rhoE( spamTuple, rho, E, Gs[gInds], dGs1[gInds], dGs2[gInds], hGs[gInds], scaleVals[gInds], wrtSlice1,", "dp_dAnyE), 0, 1)) d2pr_dErhos2 = _np.transpose(d2pr_dErhos2, (0, 2, 1)) #Note: these 2nd derivatives", "evalTree is given, otherwise no parallelization is performed. Returns ------- prods : numpy", "wrtSlice2 in wrtSlicesList: if wrtSlice1 != last_wrtSlice1: dProdCache1 = dGs1 = None #", "number of operation sequences (i.e. evalTree.num_final_strings()), - B is the number of parameter", "Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use", "= self.product(circuit, True) if self.evotype == \"statevec\": ps = _np.real(_np.abs(_np.dot(Es, _np.dot(G, rho)) *", "diff order) # d2pr/d(E)_i d(rho)_j = prod_ij (and same for other diff order)", "cols = deriv cols, rows = flattened everything else return (dGs, scaleVals) if", "(0, 2, 1)) else: d2pr_dEs2 = _np.zeros((nCircuits, nDerivCols2, nDerivCols1)) dp_dAnyE = _np.squeeze(_np.dot(dGs2, rho),", ": ndarray The parameter vector of the Model. autogator : AutoGator An auto-gator", "evalTree, slice(None), slice(None), calc_and_fill) hProdCache = hGs = dProdCache2 = dGs2 = None", "may include instrument elements like 'Imyinst_0') clipTo : 2-tuple (min,max) to clip returned", "of shape S*N x M x M where - N == the number", "in hop_dopLabels: # indicates a non-zero hessian x0 = _np.kron(_np.transpose(prods[(0, m - 1)]),", "= comm.allgather(my_results) profiler.add_time(\"MPI IPC\", tm) return _np.concatenate(all_results, axis=1) # TODO: remove this concat", "matrix where all entries are zero except the (i,j) entry == 1 #", "blk1Owners, mxToFill, [felInds], 1, mySubComm, gatherMemLimit) if deriv1MxToFill is not None: _mpit.gather_slices(blocks1, blk1Owners,", "derivative : numpy array only returned if returnDeriv == True. A 1 x", "(TODO consolidate?) #NOTE: filtering is done via the yet-to-be-defined local variables # wrtSlice1", "p = _np.dot(E, _np.dot(prod, rho)) * scale # may generate overflow, but OK", "if returnDeriv: # same as in dpr(...) dpr_drhos = _np.zeros((1, self.Np)) derivWrtAnyRhovec =", "scaleCache[i] = _np.log(nG) #evaluate operation sequences using tree (skip over the zero and", "+ d2pr_drhos2 # wrt rho ret += d2pr_dErhos1 + d2pr_d2Es + d2pr_dEs2 #", "in the string, compute the hessian of the entire # operation sequence with", "# columns which correspond to the vectorized derivatives of each of the product", "dim)) # axes = (gate_ij1, gateij2, prod_row, prod_col) def dproduct(self, circuit, flat=False, wrtFilter=None):", "each model parameter (M is the length of the vectorized model). probability :", "else \\ self._compute_dproduct_cache(evalTree, prodCache, scaleCache, comm, wrtSlice2) hProdCache = self._compute_hproduct_cache(evalTree, prodCache, dProdCache1, dProdCache2,", "+ circuit[iRight], but we want: # since then matrixOf(circuit[i]) = matrixOf(circuit[iLeft]) * matrixOf(circuit[iRight])", "= self._process_wrtFilter(wrtFilter1, gate) op_wrtFilter2, gpindices2 = self._process_wrtFilter(wrtFilter2, gate) # Allocate memory for the", "* vec( E(0,1) ) # In general: vec( A * X * B", "the names of the subcalls to estimate memory usage for. cache_size : int", "single kl xv = _np.swapaxes(xv, 1, 2) y = _np.dot(_np.kron(prods[(0, l - 1)],", "self._process_wrtFilter(wrtSlice2, self.sos.get_prep(rholabel)) E_wrtFilter1, E_gpindices1 = self._process_wrtFilter(wrtSlice1, self.sos.get_effect(elabel)) E_wrtFilter2, E_gpindices2 = self._process_wrtFilter(wrtSlice2, self.sos.get_effect(elabel)) nDerivCols1", "assert(wrtBlockSize is None) # Cannot specify both wrtFilter and wrtBlockSize wrtSlice = _slct.list_to_slice(wrtFilter)", "else: blkSize1 = blkSize2 = None # wrtFilter1 & wrtFilter2 dictates block if", "# may overflow, but ok # may overflow or get nans (invalid), but", "same dimensions as the Hessian, and turns out to be useful when computing", "The fill function computes values for only a single spam label (specified to", "pair of gates in the string, compute the hessian of the entire #", "label. \"\"\" pslc1 = param_slice1 pslc2 = param_slice2 for spamTuple, (fInds, gInds) in", "False, this routine will run slightly faster, but with a chance that the", "else: dProdCache2 = self._compute_dproduct_cache( evalSubTree, prodCache, scaleCache, blk2Comm, blk_wrtSlice2) dGs2 = evalSubTree.final_view(dProdCache2, axis=0)", "if (wrtFilter is None) else len(wrtFilter) flattened_dprod = _np.zeros((dim**2, num_deriv_cols), 'd') _fas(flattened_dprod, [None,", "array * if flat == False, a M x G x G array,", "cover # noqa for iBlk1 in myBlk1Indices: blk_wrtSlice1 = blocks1[iBlk1] dProdCache1 = self._compute_dproduct_cache(", "def _scaleExp(self, scaleExps): old_err = _np.seterr(over='ignore') scaleVals = _np.exp(scaleExps) # may overflow, but", "blkSize = wrtBlockSize # could be None if (mySubComm is not None) and", "= _slct.indices(wrtSlice) if (wrtSlice is not None) else None for i, opLabel in", "note (A tensor B)^T = A^T tensor B^T ) # and using numpy's", "number of groups to divide the second-derivative parameters into. Computation will be automatically", "they should only contain \"deterministic\" elements (no POVM or Instrument labels). numSubtreeComms :", "prodCache, scaleCache, blk2Comm, blk_wrtSlice2) dGs2 = evalSubTree.final_view(dProdCache2, axis=0) hProdCache = self._compute_hproduct_cache( evalSubTree, prodCache,", "return dProdCache def _compute_hproduct_cache(self, evalTree, prodCache, dProdCache1, dProdCache2, scaleCache, comm=None, wrtSlice1=None, wrtSlice2=None): \"\"\"", "of this MatrixForwardSimulator \"\"\" return MatrixForwardSimulator(self.dim, self.sos, self.paramvec) def product(self, circuit, bScale=False): \"\"\"", "only contain \"deterministic\" elements (no POVM or Instrument labels). numSubtreeComms : int The", "else len(wrtFilter2) flattened_d2prod = _np.zeros((dim**2, num_deriv_cols1, num_deriv_cols2), 'd') # For each pair of", "dim = (dim2, nDerivCols1, nDerivCols2); # swapaxes takes (kl,vec_prod_indx,ij) => (vec_prod_indx,kl,ij) else: #", "== \"densitymx\" # probability, with scaling applied (may generate overflow, but OK) ps", "there\" \" are more cpus than hessian elements.\") # pragma: no cover #", "GN ] , a matrix for each given (i,j) # noqa # vec(", "# a more than linear dependence on their parameters. if self.sos.get_prep(rholabel).has_nonzero_hessian(): derivWrtAnyRhovec =", "that needs to be applied to the resulting products (final_product[i] = scaleValues[i] *", "deriv2MxToFill=None, clipTo=None, check=False, comm=None, wrtFilter1=None, wrtFilter2=None, wrtBlockSize1=None, wrtBlockSize2=None, gatherMemLimit=None): \"\"\" Compute the outcome", "average size == blkSize1 or blkSize2 blocks1 = _mpit.slice_up_range(self.Np, nBlks1) blocks2 = _mpit.slice_up_range(self.Np,", "scaleExps): old_err = _np.seterr(over='ignore') scaleVals = _np.exp(scaleExps) # may overflow, but OK if", "= _np.seterr(over='ignore') rho, E = self._rhoE_from_spamTuple(spamTuple) if prMxToFill is not None: _fas(prMxToFill, [fInds],", "computation\" \" *fewer* processors and *smaller* (sub-)tree\" \" (e.g. by splitting tree beforehand),", "single- or zero-operation labels wrtIndices1 = _slct.indices(wrtSlice1) if (wrtSlice1 is not None) else", "------- MatrixEvalTree \"\"\" evTree = _MatrixEvalTree() evTree.initialize(simplified_circuits, numSubtreeComms) return evTree def estimate_mem_usage(self, subcalls,", "usage for. cache_size : int The size of the evaluation tree that will", "over the zero and single-gate-strings) #cnt = 0 for i in evalTree.get_evaluation_order(): #", "operation matrix (G x G operation matrices) and derivs[i,j,k,l] holds the derivative of", "to the j-th then i-th model parameters. * if flat == True, a", "tuple as a 1 x M x M array, where M is the", "* scaleVals[:, None] # overflow OK d2pr_d2rhos = _np.zeros((nCircuits, nDerivCols1, nDerivCols2)) _fas(d2pr_d2rhos, [None,", "tensor B)^T = A^T tensor B^T ) # and using numpy's reshape dim", "# override with smaller comm_blkSize else: blkSize = None # wrtFilter dictates block", "as there\" \" are more cpus than derivative columns.\") # Use comm to", "to the k-th then k-th model parameters. \"\"\" # LEXICOGRAPHICAL VS MATRIX ORDER", "nDerivCols1 = dProdCache1.shape[1] nDerivCols2 = dProdCache2.shape[1] assert(wrtSlice1 is None or _slct.length(wrtSlice1) == nDerivCols1)", "leftProds = [] G = _np.identity(dim); leftProds.append(G) for opLabel in revOpLabelList: G =", "wrtBlockSize). wrtFilter1, wrtFilter2 : list of ints, optional If not None, a list", "where P is is the probability generated by the sequence and spam label", "just a matrix of parameters, then dG(L)/dij = E(i,j), an elementary matrix dim", "opLabel1 in hop_dopLabels: # indicates a non-zero hessian x0 = _np.kron(_np.transpose(prods[(0, m -", "#profiler.print_mem(\"DEBUGMEM: POINT2\"); profiler.comm.barrier() profiler.add_time(\"compute_dproduct_cache: serial\", tSerialStart) profiler.add_count(\"compute_dproduct_cache: num columns\", nDerivCols) return dProdCache def", "a pair of SPAMVec (or array) # objects: (prepVec, effectVec) rho, Eraw =", "+= cache_size # scale vals ## It doesn't make sense to include these", "= [] # indices into original wrtFilter'd indices gpindices = obj.gpindices_as_array() for ii,", "scaleVals def _rhoE_from_spamTuple(self, spamTuple): assert(len(spamTuple) == 2) if isinstance(spamTuple[0], _Label): rholabel, elabel =", "axis=(2,)) * scaleVals[:, None] _fas(dp_dEs, [None, E_gpindices], _np.dot(dp_dAnyE, EVec.deriv_wrt_params(E_wrtFilter))) sub_vdp = dp_drhos +", "= _np.empty((1, self.Np)) for i in range(self.Np): dpr_dOps[0, i] = float(_np.dot(E, _np.dot(dprod_dOps[i], rho)))", "dGs1[gInds], scaleVals[gInds], wrtSlice1), add=sumInto) if deriv2MxToFill is not None: _fas(deriv2MxToFill, [fInds, pslc2], self._dprobs_from_rhoE(", "= _MatrixEvalTree() evTree.initialize(simplified_circuits, numSubtreeComms) return evTree def estimate_mem_usage(self, subcalls, cache_size, num_subtrees, num_subtree_proc_groups, num_param1_groups,", "of Sandia, LLC (NTESS). # Under the terms of Contract DE-NA0003525 with NTESS,", "probability itself. clipTo : 2-tuple (min,max) to clip returned probability to if not", "of a many operation sequences at once. Parameters ---------- evalTree : EvalTree given", "or greater than `cacheSize`) the tree will hold. Returns ------- int The memory", "mySubTreeIndices: evalSubTree = subtrees[iSubTree] felInds = evalSubTree.final_element_indices(evalTree) #Free memory from previous subtree iteration", "# noqa # vec( dprod/d(opLabel)_ij ) = sum_{L s.t. G(L) == oplabel} [", "these computed blocks, in the order given by `wrtSlicesList`. `rowSlice` and `colSlice` must", "of :func:`bulk_fill_hprobs` (i.e. args `mxToFill`, `deriv1MxToFill`, and `deriv1MxToFill`), then: - `hprobs == mx[:,:,rowSlice,colSlice]`", "sub-trees. _warnings.warn(\"Increased speed could be obtained\" \" by giving hproduct cache computation\" \"", "B^T tensor A * vec( X ) def doperation(self, opLabel, flat=False, wrtFilter=None): \"\"\"", "That is, the first element of circuit can be thought of as the", "*simplified* gates (e.g. may include instrument elements like 'Imyinst_0') returnPr : bool when", "wrtSlice2 = blocks2[iBlk2] self._fill_result_tuple((prMxToFill, deriv1MxToFill, deriv2MxToFill, mxToFill), evalSubTree, blocks1[iBlk1], blocks2[iBlk2], calc_and_fill) hProdCache =", "rho_gpindices] = dot(E,dGs[i,j],drho/drhoP)) # d2pr_drhos[i,j,J0+J] = sum_kl E[0,k] dGs[i,j,k,l] drhoP[l,J] # d2pr_drhos[i,j,J0+J] =", "for t in subtrees] _mpit.gather_indices(subtreeElementIndices, subTreeOwners, mxToFill, [], 0, comm, gatherMemLimit) #note: pass", "d2pr/d(rho)_i d(opLabel)_mn = sum E_k [dprod/d(opLabel)_mn]_ki (and same for other diff order) #", "rho)) # may overflow, but OK _fas(dpr_dEs, [0, EVec.gpindices], _np.dot(derivWrtAnyEvec, EVec.deriv_wrt_params())) dpr =", "sequences for spamTuple, (fInds, gInds) in evalTree.spamtuple_indices.items(): circuit_list = master_circuit_list[gInds] if prMxToFill is", "result num_deriv_cols1 = self.Np if (wrtFilter1 is None) else len(wrtFilter1) num_deriv_cols2 = self.Np", "# vp[i] = dot( E, dot(Gs, rho))[0,i,0] * scaleVals[i] # vp = squeeze(", "calculator. \"\"\" return \"deriv\" def estimate_cache_size(self, nCircuits): \"\"\" Return an estimate of the", "* scaleVals return _np.squeeze(_np.dot(E, _np.dot(Gs, rho)), axis=(0, 2)) * scaleVals # shape ==", "that # per-gate hessians can be computed properly if wrtSlice1 is not None", "1)]), prods[(m + 1, N - 1)]) # (dim**2, dim**2) # (nDerivCols1,nDerivCols2,dim**2) x", "DERIVS (assume hGs is already sized/filtered) ------------------- assert(hGs.shape[1] == nDerivCols1), \"hGs must be", "needed for the hessians, derivatives, and/or products for the i-th operation sequence. \"\"\"", "not None: # ignoring comm since can't do anything with it! #_warnings.warn(\"More processors", "factor (see below). Returns ------- product : numpy array The product or scaled", "0. In # this case set to zero since we can't tell whether", "object of *simplified* gates (e.g. may include instrument elements like 'Imyinst_0') clipTo :", "_np.exp(-scaleCache[iRight]), 1e-300) sL, sR = L / nL, R / nR prodCache[i] =", "* scaleVals[:, None] # overflow OK d2pr_d2Es = _np.zeros((nCircuits, nDerivCols1, nDerivCols2)) _fas(d2pr_d2Es, [None,", "wrtFilter=None): \"\"\" Compute the derivative of a specified sequence of operation labels. Parameters", "into. Computation will be automatically parallelized over these groups. num_final_strs : int The", "] # # return PrepEffectFilter(rho_local_slices=loc_rho_slices, # rho_global_slices=global_rho_slices, # e_local_slices=loc_e_slices, # e_global_slices=global_e_slices, # num_rho_params=_slct.length(wrtSlices['preps']),", "be computed column-by-column from the using the columns of the operation sequences. Parameters", "internally for distributing derivative calculations across multiple processors. Returns ------- hessians : numpy", "comm_blkSize = self.Np / mySubComm.Get_size() blkSize = comm_blkSize if (blkSize is None) \\", "an inf scaleVal is mult by a zero deriv value (see below) dGs[_np.isnan(dGs)]", "doesn't make sense to include these since their required memory is fixed ##", "] # noqa # = sum{...} [ unvec( G1 ... G(M-1) tensor (G(M+1)", "probability w.r.t. the k-th then the j-th model parameter. derivative : numpy array", "cache_size * dim * dim # product cache mem += cache_size # scale", "len(revOpLabelList) # length of operation sequence # prod = G1 * G2 *", "0: continue for l, opLabel2 in enumerate(revOpLabelList): inds2 = gpindices1[opLabel2] #nDerivCols2 = dop_dopLabel2[opLabel2].shape[1]", "(dGs, Gs, scaleVals) if bScale else (dGs, Gs) else: dGs = evalTree.final_view(dProdCache, axis=0)", "elementary matrix where all entries are zero except the (i,j) entry == 1", "and save in return array # want vp[iFinal] = float(dot(E, dot(G, rho))) #", "block_wrtSlice, profiler) profiler.add_time(\"bulk_fill_dprobs: compute_dproduct_cache\", tm) profiler.mem_check( \"bulk_fill_dprobs: post compute dproduct blk (expect \"", "subtrees = evalTree.get_sub_trees() mySubTreeIndices, subTreeOwners, mySubComm = evalTree.distribute(comm) #if comm is not None:", "gate's parameters and fill appropriate columns of flattened_dprod. #gate = self.sos.get_operation[opLabel] UNNEEDED (I", "the tree will hold. Returns ------- int The memory estimate in bytes. \"\"\"", "b/c an inf scaleVal is mult by a zero hessian value (see below)", "where - S == len(circuit_list) - M == the number of model params", "compute dproduct\") #Compute all requested derivative columns at once self._fill_result_tuple((prMxToFill, mxToFill), evalSubTree, slice(None),", "# d2pr_dEs[i,j,J0+J] = dot( squeeze(dot(dGs, rho),axis=(3,)), dEP)[i,j,J] # d2pr_dEs[:,:,J0+J] = dot( squeeze(dot(dGs, rho),axis=(3,)),", "the outputs of :func:`bulk_fill_hprobs` (i.e. args `mxToFill`, `deriv1MxToFill`, and `deriv1MxToFill`), then: - `hprobs", "is not None and mySubComm.Get_size() > 1: _warnings.warn(\"Too many processors to make use", "the *simplified* gate strings to compute the bulk operation on. clipTo : 2-tuple,", "1).reshape((num_deriv_cols, dim, dim)) def hoperation(self, opLabel, flat=False, wrtFilter1=None, wrtFilter2=None): \"\"\" Return the hessian", "derivatives, similar to bulk_fill_dprobs(...), but where M is the number of model parameters", "= deriv cols, rows = flattened everything else return (dGs, scaleVals) if bScale", "are both in opsToVectorize1 and opsToVectorize2 we only compute d2(prod)/d(gl1)d(gl2) # and not", "return ret, p else: return ret ## BEGIN CACHE FUNCTIONS def _compute_product_cache(self, evalTree,", "None: blkSize1 = wrtBlockSize1 # could be None blkSize2 = wrtBlockSize2 # could", "N x M x M numpy array, where: - N == the number", "[t.final_element_indices(evalTree) for t in subtrees] _mpit.gather_indices(subtreeElementIndices, subTreeOwners, mxToFill, [], 0, comm) #note: pass", "mem * FLOATSIZE def bulk_product(self, evalTree, bScale=False, comm=None): \"\"\" Compute the products of", "- inf anyway... dp_dOps[_np.isnan(dp_dOps)] = 0 #SPAM ------------- # Get: dp_drhos[i, rho_gpindices] =", "== length of the vectorized model (number of model parameters) and hessian[i,j,k] holds", "case of empty label == no gate hProdCache[i] = _np.zeros(hessn_shape) elif not self.sos.get_operation(opLabel).has_nonzero_hessian():", "else: drho = rhoVec.deriv_wrt_params(rho_wrtFilter1) d2pr_drhos2 = _np.zeros((nCircuits, nDerivCols2, nDerivCols1)) _fas(d2pr_drhos2, [None, None, rho_gpindices1],", "returnPr : bool when set to True, additionally return the probability itself. clipTo", "locations of opLabel LRproduct = _np.kron(leftProds[i], rightProdsT[N - 1 - i]) # (dim**2,", "rho_gpindices1], _np.swapaxes(_np.dot(_np.transpose(devec), dp_dAnyE), 0, 1)) d2pr_dErhos2 = _np.transpose(d2pr_dErhos2, (0, 2, 1)) #Note: these", "the products of many operation sequences at once. Parameters ---------- evalTree : EvalTree", "of length equal to the total number of computed elements (i.e. evalTree.num_final_elements()) evalTree", "or in the LICENSE file in the root pyGSTi directory. #*************************************************************************************************** import warnings", "derivative computation across blocks myBlk1Indices, blk1Owners, blk1Comm = \\ _mpit.distribute_indices(list(range(nBlks1)), mySubComm) myBlk2Indices, blk2Owners,", "* num_params * dim * dim # dproduct cache # mem += cache_size", "multiple uses below gpindices1 = {}; gate_wrtFilters1 = {} gpindices2 = {}; gate_wrtFilters2", ") ), axis=(0,4)) old_err2 = _np.seterr(invalid='ignore', over='ignore') d2pr_dOps2 = _np.squeeze(_np.dot(E, _np.dot(hGs, rho)), axis=(0,", "dim = self.dim wrtSlice = _slct.list_to_slice(wrtFilter) if (wrtFilter is not None) else None", "M terms assumes that d^2 G/(dij)^2 == 0, which is true IF each", "= _np.zeros(deriv_shape) else: #doperation = self.dproduct( (opLabel,) , wrtFilter=wrtIndices) doperation = self.doperation(opLabel, wrtFilter=wrtIndices)", "for elabel in elabels] Es = _np.conjugate(_np.transpose(_np.concatenate(Es, axis=1))) # convention: Es has shape", "scaleVals # shape == (len(circuit_list),) ; may overflow but OK def _dprobs_from_rhoE(self, spamTuple,", "(1, 2, 0)).reshape( (num_deriv_cols1, num_deriv_cols2, dim, dim)) # axes = (gate_ij1, gateij2, prod_row,", "= dot( E, dot( dGs, rho ) )[0,i,j,k,0] # d2pr_dOps2 = squeeze( dot(", "dim) cacheSize = len(evalTree) # ------------------------------------------------------------------ if comm is not None and comm.Get_size()", "the mapping # of prep and effect parameters onto a final \"filtered\" set.", "None) \\ else min(comm_blkSize, blkSize1) # override with smaller comm_blkSize blkSize2 = comm_blkSize", "scale cache (exps) mem += cache_size # scale vals elif fnName == \"bulk_fill_dprobs\":", "the length of the vectorized model - G == the linear dimension of", "scale)**2) else: # evotype == \"densitymx\" # probability, with scaling applied (may generate", "= self._compute_dproduct_cache( evalTree, prodCache, scaleCache, None, myDerivColSlice, profiler) # pass None as comm,", "of LinearOperator, SPAMVec, and SPAMVec objects, respectively. Must be *ordered* dictionaries to specify", "than model parameters, distribution over a split evalTree (if given) is possible. wrtFilter", "_time.time() if profiler is None: profiler = _dummy_profiler if wrtFilter is not None:", "rho, E = self._rhoE_from_spamTuple(spamTuple) rhoVec = self.sos.get_prep(rholabel) # distinct from rho,E b/c rho,E", "to impose upon the \"gather\" operations performed as a part of MPI processor", "nDerivCols1, nDerivCols2)) _fas(d2pr_d2rhos, [None, rho_gpindices1, rho_gpindices2], _np.tensordot(dp_dAnyRho, self.sos.get_prep(rholabel).hessian_wrt_params( rho_wrtFilter1, rho_wrtFilter2), (1, 0))) #", "since we can't do any further parallelization _mpit.gather_slices(deriv2Slices, deriv2Owners, hProdCache, [None, myDeriv1ColSlice], 2,", "with respect to the j-th model parameter. products : numpy array Only returned", "dpr(...) dpr_drhos = _np.zeros((1, self.Np)) derivWrtAnyRhovec = scale * _np.dot(E, prod) _fas(dpr_drhos, [0,", "ng, _np.log(ng)) gate, ex = scaledGatesAndExps[lOp] H = _np.dot(gate, G) # product of", "M == length of the vectorized model (number of model parameters) and hessian[i,j,k]", "dot(Gs, rho)[i,k,0] * scaleVals[i] # vp[i] = dot( E, dot(Gs, rho))[0,i,0] * scaleVals[i]", "GM == gatelabel1} sum_{L s.t. GL == gatelabel2, M < L} # noqa", "axis=0) #( nCircuits, nDerivCols, dim, dim ) profiler.add_time(\"bulk_fill_dprobs: compute_dproduct_cache\", tm) profiler.mem_check(\"bulk_fill_dprobs: post compute", "Note: add transposes b/c spam terms only compute one triangle of hessian #", "= _np.conjugate(_np.transpose(_np.concatenate(Es, axis=1))) # convention: Es has shape (len(elabels),N) return rho, Es def", "(fInds, gInds) in evalTree.spamtuple_indices.items(): circuit_list = master_circuit_list[gInds] if prMxToFill is not None: check_vp", "are more processors than deriv cells, give a # warning -- note that", "mySubComm, since we can't do any # further parallelization tm = _time.time() all_results", "ExM numpy array where E is the total number of computed elements (i.e.", "dprod/d(opLabel)_ij = sum_{L s.t. G(L) == oplabel} [ G1 ... G(L-1) dG(L)/dij G(L+1)", "for it. # Use comm only for speeding up the calcs of the", "[], 0, comm) #note: pass mxToFill, dim=(KS), so gather mxToFill[felslc] (axis=0) if clipTo", "as above return (hGs, scaleVals) if bScale else hGs def _scaleExp(self, scaleExps): old_err", "first identity below is valid. # Below we use E(i,j) to denote the", "Parameters ---------- spamTuple : (rho_label, simplified_effect_label) Specifies the prep and POVM effect used", "derivative of the (k,l)-th entry of the i-th operation sequence product with respect", "= d2pr_dErhos + _np.transpose(d2pr_dErhos, (0, 2, 1)) + \\ d2pr_drhos + _np.transpose(d2pr_drhos, (0,", "Constructs an EvalTree object appropriate for this calculator. Parameters ---------- simplified_circuits : list", "== True. An array of shape S such that scaleVals[i] contains the multiplicative", "# Gs[i] is product for i-th operation sequence dGs1 = evalTree.final_view(dProdCache1, axis=0) dGs2", "in range(len(self.preps)) ] # global_e_slices = [slice(self.e_offset[i],self.e_offset[i+1]) for i in range(len(self.effects)) ] #", "is not None: # print(\"MPI DEBUG: Rank%d subtee sizes = %s\" % #", "compute. Iterating over the output of this function iterates over these computed blocks,", "(_np.isnan(dGs)).nonzero()[0] ) == 0 ) #assert( len( (_np.isinf(dGs)).nonzero()[0] ) == 0 ) #dGs", "None deriv1MxToFill = dprobs1 deriv2MxToFill = dprobs2 mxToFill = hprobs #Fill arrays self._fill_result_tuple((None,", "be None blkSize2 = wrtBlockSize2 # could be None if (mySubComm is not", "/ (1024.0**3), str(dProdCache.shape))) dGs = evalSubTree.final_view(dProdCache, axis=0) #( nCircuits, nDerivCols, dim, dim )", "Hessians. PSMALL = 1e-100 DSMALL = 1e-100 HSMALL = 1e-100 class MatrixForwardSimulator(ForwardSimulator): \"\"\"", "order to associate the right single-gate-strings w/indices wrtIndices = _slct.indices(wrtSlice) if (wrtSlice is", "dEP[j,J] dot(Gs, rho)[i,j] # dp_dEs[i,J0+J] = sum_j dot(Gs, rho)[i,j,0] dEP[j,J] # dp_dEs[i,J0+J] =", "tm) profiler.mem_check( \"bulk_fill_dprobs: post compute dproduct blk (expect \" \" +%.2fGB, shape=%s)\" %", "tm = _time.time() prodCache, scaleCache = self._compute_product_cache(evalSubTree, mySubComm) profiler.add_time(\"bulk_fill_dprobs: compute_product_cache\", tm) #use cached", "# a \"custom\" spamLabel consisting of a pair of SPAMVec (or array) #", "operation matrix (G x G operation matrices) and hessians[i,j,k,l,m] holds the derivative of", "blkSize2 is None: #Fill hessian cache info dProdCache1 = self._compute_dproduct_cache( evalSubTree, prodCache, scaleCache,", "A memory limit in bytes to impose upon the \"gather\" operations performed as", "(nDerivCols1,nDerivCols2,dim**2) x = _np.dot(_np.transpose(hop_dopLabels[opLabel1], axes=(1, 2, 0)), x0); xv = x.view() xv =", "_np.transpose(d2pr_dEs, (0, 2, 1)) + \\ d2pr_d2rhos + d2pr_d2Es + d2pr_dOps2 # Note:", "x G x G numpy array, where: - M == length of the", "# axes = (gate_ij1, gateij2, prod_row, prod_col) def dproduct(self, circuit, flat=False, wrtFilter=None): \"\"\"", "oplabel} [ G1 ... G(L-1) dG(L)/dij G(L+1) ... GN ] , a matrix", "spamlabels... # This calculator uses the convention that rho has shape (N,1) rho", "_mpit.gather_slices(blocks2, blk2Owners, deriv2MxToFill, [felInds], 1, blk1Comm, gatherMemLimit) #Note: deriv2MxToFill gets computed on every", "in the first (row) and second (col) derivative operations, respectively. Each element is", "self.Np if (wrtFilter2 is None) else _slct.length(wrtFilter2) nCircuits = evalTree.num_final_strings() # len(circuit_list) wrtSlice1", "of rowSlice) - B' is the number of parameter columns (the length of", "< 10: strToPrint = str(circuit) else: strToPrint = str(circuit[0:10]) + \" ... (len", "be computed # for the current spamTuple (this list has the SAME length", "= norm(G); G /= nG; total_exp += log(nG) # scale and keep track", "vec( A * X * B ) = B^T tensor A * vec(", "( unvec( G(L+1) ... G(M-1) tensor (G(M+1) ... GN)^T vec( dG(M)/dkl ) )", "def dpr(self, spamTuple, circuit, returnPr, clipTo): \"\"\" Compute the derivative of a probability", "S x M x G x G, where: - S == len(circuit_list) -", "dim**2) x = _np.dot(_np.transpose(dop_dopLabel1[opLabel1]), x0); xv = x.view() # (nDerivCols1,dim**2) xv.shape = (nDerivCols1,", "into mxToFill, specifying the correspondence between rows of mxToFill and spam labels. evalTree", "= _slct.list_to_slice(wrtFilter1) if (wrtFilter1 is not None) else None wrtSlice2 = _slct.list_to_slice(wrtFilter2) if", "gpindices1 = {}; gate_wrtFilters1 = {} gpindices2 = {}; gate_wrtFilters2 = {} for", "rho)[i,j] # dp_dEs[i,J0+J] = sum_j dot(Gs, rho)[i,j,0] dEP[j,J] # dp_dEs[i,J0+J] = dot(squeeze(dot(Gs, rho),2),", "subTreeOwners, mySubComm = evalTree.distribute(comm) #if comm is not None: # print(\"MPI DEBUG: Rank%d", "# Allocate memory for the final result num_deriv_cols1 = self.Np if (wrtFilter1 is", "GN)^T vec( dG(L)/dij ) ] # noqa # = [ sum_{L s.t. G(L)", "M numpy array, where: - N == the number of entries in a", "probabilities can often be computed column-by-column from the using the columns of the", "gInds, pslc1, pslc2, sumInto): \"\"\" Compute and fill result quantities for given arguments", "derivative of the (k,l)-th entry of the product with respect to the j-th", "done over the set of parameters being differentiated with respect to when the", "[ (G1 ... G(L-1)) tensor (G(L+1) ... GN)^T ]] has # columns which", "assert(hGs.shape[2] == nDerivCols2), \"hGs must be pre-filtered!\" #Compute d2(probability)/dGates2 and save in return", "+ 1, N - 1)]) # (dim**2, dim**2) x = _np.dot(_np.transpose(dop_dopLabel1[opLabel1]), x0); xv", "ugh. relevant_gpindices = slice(relevant_gpindices[0], relevant_gpindices[0] + 1) elif len(relevant_gpindices) == 0: #Don't return", "rho_l # d2pr/d(opLabel1)_mn d(opLabel2)_ij = sum E_k [dprod/d(opLabel1)_mn d(opLabel2)_ij]_kl rho_l # d2pr/d(rho)_i d(opLabel)_mn", "as above, and deriv[i,j] holds the derivative of the (i % G^2)-th entry", "hProdCache = self._compute_hproduct_cache( evalSubTree, prodCache, dProdCache1, dProdCache2, scaleCache, blk2Comm, blk_wrtSlice1, blk_wrtSlice2) hGs =", "as _Label from .matrixevaltree import MatrixEvalTree as _MatrixEvalTree from .forwardsim import ForwardSimulator _dummy_profiler", "Es = _np.conjugate(_np.transpose(_np.concatenate(Es, axis=1))) # convention: Es has shape (len(elabels),N) return rho, Es", "'d') else: dprobs1 = dprobs2 = None hprobs = _np.zeros((nElements, _slct.length(wrtSlice1), _slct.length(wrtSlice2)), 'd')", "concatenating each gate's parameters (in the order specified by the model). This argument", "None. Only relevant when prMxToFill is not None. Returns ------- derivative : numpy", "to achieve desired average size == blkSize blocks = _mpit.slice_up_range(self.Np, nBlks, start=0) #", "parameter filters for multiple uses below gpindices1 = {}; gate_wrtFilters1 = {} gpindices2", "0 # assume the zero deriv value trumps since we've renormed to keep", "# LEXICOGRAPHICAL VS MATRIX ORDER return G def _process_wrtFilter(self, wrtFilter, obj): \"\"\" Helper", "None) else _slct.length(wrtFilter2) nCircuits = evalTree.num_final_strings() # len(circuit_list) wrtSlice1 = _slct.list_to_slice(wrtFilter1) if (wrtFilter1", "generated when the original list of `Circuits` was simplified. Parameters ---------- mxToFill :", "\"\"\" Compute the derivative of a probability generated by a operation sequence and", "gate-sequence indices # gInds = \"gate sequence indices\" = indices into the (tree-)", "(Vectorization) # Note when vectorizing op uses numpy.flatten rows are kept contiguous, so", "linear dimension of a operation matrix (G x G operation matrices) and hessians[i,j,k,l,m]", "_np.dot(LRproduct, dop_dopLabel), add=True) # (dim**2, nParams[opLabel]) if flat: return flattened_dprod else: # axes", "optional Affects the shape of the returned derivative array (see below). wrtFilter1, wrtFilter2", "outcome probability-Hessians for an entire tree of gate strings. Similar to `bulk_fill_probs(...)`, but", "requiring row or column distribution) prodCache, scaleCache = self._compute_product_cache(evalSubTree, mySubComm) scaleVals = self._scaleExp(evalSubTree.final_view(scaleCache))", "evalSubTree, slice(None), slice(None), calc_and_fill) #collect/gather results subtreeElementIndices = [t.final_element_indices(evalTree) for t in subtrees]", "derivative of the probability. clipTo : 2-tuple (min,max) to clip returned probability to", "0, 1)) d2pr_dErhos2 = _np.transpose(d2pr_dErhos2, (0, 2, 1)) #Note: these 2nd derivatives are", "not None, a list of integers specifying which gate parameters to differentiate with", "p else: return dpr_drhos + dpr_dEs + dpr_dOps def hpr(self, spamTuple, circuit, returnPr,", ".... * GN , a matrix # noqa # dprod/d(opLabel)_ij = sum_{L s.t.", "[ unvec( G1 ... G(M-1) tensor (G(M+1) ... G(L-1))^T vec( dG(M)/dkl ) )", "the gates are at most linear in their parameters, this # isn't currently", "= _np.kron(_np.transpose(prods[(0, m - 1)]), prods[(m + 1, l - 1)]) # (dim**2,", "_fas from .profiler import DummyProfiler as _DummyProfiler from .label import Label as _Label", "if len(circuit) < 10: strToPrint = str(circuit) else: strToPrint = str(circuit[0:10]) + \"", "_time.time() subtreeElementIndices = [t.final_element_indices(evalTree) for t in subtrees] _mpit.gather_indices(subtreeElementIndices, subTreeOwners, mxToFill, [], 0,", "- `hprobs == mx[:,:,rowSlice,colSlice]` - `dprobs12 == dp1[:,:,rowSlice,None] * dp2[:,:,None,colSlice]` \"\"\" assert(not evalTree.is_split()),", "wrtFilter1 and wrtFilter2). clipTo : 2-tuple, optional (min,max) to clip return value if", "using tree (skip over the zero and single-gate-strings) for i in evalTree.get_evaluation_order(): tm", "both wrtFilter and blkSize nBlks = int(_np.ceil(self.Np / blkSize)) # num blocks required", "= evalSubTree.final_view(dProdCache, axis=0) #( nCircuits, nDerivCols, dim, dim ) profiler.add_time(\"bulk_fill_dprobs: compute_dproduct_cache\", tm) profiler.mem_check(\"bulk_fill_dprobs:", "object (gate or spam vec) \"\"\" #Create per-gate with-respect-to parameter filters, used to", "axes = (gate_ij, prod_row, prod_col) return _np.swapaxes(flattened_dprod, 0, 1).reshape((num_deriv_cols, dim, dim)) def hoperation(self,", "self._compute_hproduct_cache( evalTree, prodCache, dProdCache1[:, myDeriv1ColSlice], dProdCache2[:, myDeriv2ColSlice], scaleCache, None, myHessianSlice1, myHessianSlice2) # pass", "arrays, these are SPAMVecs d2prod_dGates = self.hproduct(circuit) assert(d2prod_dGates.shape[0] == d2prod_dGates.shape[1]) d2pr_dOps2 = _np.empty((1,", "DERIVS ----------------------- ret = d2pr_d2rhos + d2pr_dErhos2 + d2pr_drhos2 # wrt rho ret", "EVec.deriv_wrt_params())) _np.seterr(**old_err) if returnPr: return dpr_drhos + dpr_dEs + dpr_dOps, p else: return", "probabilities of a multiple \"outcomes\" (spam-tuples) for a single operation sequence. The spam", "begin (expect ~ %.2fGB)\" % (mxToFill.nbytes / (1024.0**3))) ## memory profiling of python", "isn't specified if wrtFilter1 is None and wrtFilter2 is None: blkSize1 = wrtBlockSize1", "scaleCache, mySubComm, wrtSlice1) dProdCache2 = dProdCache1 if (wrtSlice1 == wrtSlice2) else \\ self._compute_dproduct_cache(evalSubTree,", "= _dummy_profiler dim = self.dim nDerivCols = self.Np if (wrtSlice is None) \\", "over these groups. num_final_strs : int The number of final strings (may be", "an already-allocated ExM numpy array where E is the total number of computed", "# may overflow, but OK _fas(dpr_dEs, [0, EVec.gpindices], _np.dot(derivWrtAnyEvec, EVec.deriv_wrt_params())) dpr = dpr_drhos", "accounts for the symmetry of the Hessian, so that # if gl1 and", "axis=(2,)) _fas(d2pr_dEs, [0, None, EVec.gpindices], _np.dot(derivWrtAnyEvec, EVec.deriv_wrt_params())) d2pr_dErhos = _np.zeros((1, self.Np, self.Np)) derivWrtAnyEvec", "A[col0] * B[0,1] ) = B^T tensor A * vec( E(0,1) ) #", "* if flat == False, a M x M x G x G", "(G(M+1) ... GN)^T vec( dG(M)/dkl ) ) )^T vec( dG(L)/dij ) ] #", "None) else _slct.length(wrtFilter) dim = self.dim wrtSlice = _slct.list_to_slice(wrtFilter) if (wrtFilter is not", "arrays, these are SPAMVecs nCircuits = Gs.shape[0] rho_wrtFilter1, rho_gpindices1 = self._process_wrtFilter(wrtSlice1, self.sos.get_prep(rholabel)) rho_wrtFilter2,", "------- None \"\"\" #get distribution across subtrees (groups if needed) subtrees = evalTree.get_sub_trees()", "but where M is the number of model parameters selected for the 1st", "in a linear cache space. Will use derivative columns and then (and only", "= self._process_wrtFilter(wrtSlice2, self.sos.get_effect(elabel)) nDerivCols1 = self.Np if wrtSlice1 is None else _slct.length(wrtSlice1) nDerivCols2", "E(0,1) ) # In general: vec( A * X * B ) =", "vec( A * E(0,1) * B ) = vec( mx w/ row_i =", "dots\") scale = scaleCache[i] - (scaleCache[iLeft] + scaleCache[iRight]) if abs(scale) > 1e-8: #", "gate-dimension. All operation matrices should be dim x dim, and all SPAM vectors", "iLeft) = evalTree[i] L, R = prodCache[iLeft], prodCache[iRight] dL1, dR1 = dProdCache1[iLeft], dProdCache1[iRight]", "_mpit.gather_indices(subtreeElementIndices, subTreeOwners, prMxToFill, [], 0, comm) if clipTo is not None and prMxToFill", "results tm = _time.time() _mpit.gather_slices(blocks, blkOwners, mxToFill, [felInds], 1, mySubComm, gatherMemLimit) #note: gathering", "for given arguments \"\"\" old_err = _np.seterr(over='ignore') rho, E = self._rhoE_from_spamTuple(spamTuple) #if prMxToFill", "each \"final element\" of `evalTree`. Parameters ---------- mxToFill : numpy ndarray an already-allocated", "nBlks1, nBlks2)) # pragma: no cover # noqa for iBlk1 in myBlk1Indices: blk_wrtSlice1", "# wrtFilter dictates block if blkSize is None: #Fill derivative cache info tm", "profiler.add_time(\"bulk_fill_dprobs: compute_dproduct_cache\", tm) profiler.mem_check( \"bulk_fill_dprobs: post compute dproduct blk (expect \" \" +%.2fGB,", "inf and dot-prod being 0. In # this case set to zero since", "by the first two arguments), and in general only a specified slice of", "bScale=False, comm=None): \"\"\" Compute the products of many operation sequences at once. Parameters", "= _np.seterr(over='ignore') rho, E = self._rhoE_from_spamTuple(spamTuple) _fas(prMxToFill, [fInds], self._probs_from_rhoE(rho, E, Gs[gInds], scaleVals[gInds]), add=sumInto)", "slicetools as _slct from ..tools.matrixtools import _fas from .profiler import DummyProfiler as _DummyProfiler", "dot(Gs, rho))[0,i,0] * scaleVals[i] # vp = squeeze( dot( E, dot(Gs, rho)), axis=(0,2)", "dGs1 = None # free mem def _fill_result_tuple(self, result_tup, evalTree, param_slice1, param_slice2, calc_and_fill_fn):", "2-tuple, optional (min,max) to clip return value if not None. check : boolean,", "may include instrument elements like 'Imyinst_0') returnPr : bool when set to True,", "the shape of the returned derivative array (see below). bReturnDProdsAndProds : bool, optional", "the (i % G^2)-th entry of the (i / G^2)-th flattened operation sequence", "_np.zeros(cacheSize, 'd') #First element of cache are given by evalTree's initial single- or", "else: d2pr_dErhos2 = _np.zeros((nCircuits, nDerivCols2, nDerivCols1)) drho = rhoVec.deriv_wrt_params(rho_wrtFilter1) dp_dAnyE = _np.dot(Gs, drho)", "matrices. Parameters ---------- circuit : Circuit or tuple of operation labels The sequence", "gate in used_operations.items(): if gate.has_nonzero_hessian(): hop_dopLabels[opLabel] = gate.hessian_wrt_params( gate_wrtFilters1[opLabel], gate_wrtFilters2[opLabel]) # Allocate memory", "of *simplified* gates (e.g. may include instrument elements like 'Imyinst_0') clipTo : 2-tuple", "spam vectors have # a more than linear dependence on their parameters. if", "to a single kl xv = _np.swapaxes(xv, 1, 2) y = _np.dot(_np.kron(prods[(0, l", "# d2pr_dErhos[i,J0+J,K0+K] = sum jk dEPT[J,j] prod[i,j,k] drhoP[k,K] # d2pr_dErhos[i,J0+J,K0+K] = sum j", "is None and wrtBlockSize2 is None) # Cannot specify both wrtFilter and wrtBlockSize", "cacheSize = len(evalTree) # ------------------------------------------------------------------ if comm is not None and comm.Get_size() >", "(0, 2, 1)) #Note: these 2nd derivatives are non-zero when the spam vectors", "to use available processors if it isn't specified if wrtFilter is None: blkSize", "dpr_drhos + dpr_dEs + dpr_dOps, p else: return dpr_drhos + dpr_dEs + dpr_dOps", "hProdCache[i].max() < HSMALL and hProdCache[i].min() > -HSMALL: _warnings.warn(\"Scaled hProd small in order to", "once so they're not repeatedly # computed for each block of derivative columns", "prodCache, scaleCache, mySubComm, wrtSlice1) dProdCache2 = dProdCache1 if (wrtSlice1 == wrtSlice2) else \\", "parallelized over these groups. num_param2_groups : int The number of groups to divide", "= dot(E, Gs, drhoP)[0,i,J] # dp_drhos[:,J0+J] = squeeze(dot(E, Gs, drhoP),axis=(0,))[:,J] dp_drhos = _np.zeros((nCircuits,", "sL, sR = L / nL, R / nR prodCache[i] = _np.dot(sL, sR);", "0 ) #assert( len( (_np.isinf(hGs)).nonzero()[0] ) == 0 ) #hGs = clip(hGs,-1e300,1e300) _np.seterr(**old_err)", "order to perform the parallelization over the parameter groups. num_param1_groups : int The", "_compute_dproduct_cache begin: %d deriv cols\" % nDerivCols) if comm is not None and", "# #elif fnName == \"bulk_hproduct\": # mem += cache_size * num_params**2 * dim", "part of MPI processor syncronization. Returns ------- None \"\"\" tStart = _time.time() if", "hprobs, dprobs12 else: yield wrtSlice1, wrtSlice2, hprobs dProdCache1 = dGs1 = None #", "dim # product cache mem += cache_size # scale cache (exps) mem +=", "final block size. These arguments must be None if the corresponding wrtFilter is", "clipTo[0], clipTo[1], out=prMxToFill) # in-place clip if check: self._check(evalTree, prMxToFill, deriv1MxToFill, mxToFill, clipTo)", "wrtLen1 = (self.Np + np1 - 1) // np1 # ceiling(num_params / np1)", "an already-allocated ExMxM numpy array where E is the total number of computed", "= hGs = None prodCache = scaleCache = None #Fill product cache info", "derivWrtAnyEvec = scale * _np.dot(prod, rhoVec.deriv_wrt_params()) # may generate overflow, but OK _fas(d2pr_dErhos,", "i # LEXICOGRAPHICAL VS MATRIX ORDER Note: we reverse iLeft <=> iRight from", "and comm.Get_size() > 1: # parallelize of deriv cols, then sub-trees (if available", "for product computation\") pass # this is a fairly common occurrence, and doesn't", "S such that scaleVals[i] contains the multiplicative scaling needed for the hessians, derivatives,", "1)]), prods[(m + 1, l - 1)]) # (dim**2, dim**2) x = _np.dot(_np.transpose(dop_dopLabel1[opLabel1]),", "d2pr/d(rho)_i d(rho)_j = 0 rholabel, elabel = spamTuple rho, E = self._rhoE_from_spamTuple(spamTuple) rhoVec", "= _np.zeros((nCircuits, nDerivCols1, nDerivCols2)) drho = rhoVec.deriv_wrt_params(rho_wrtFilter2) dp_dAnyE = _np.dot(Gs, drho) * scaleVals[:,", "prod_row, prod_col) return _np.swapaxes(flattened_dprod, 0, 1).reshape((num_deriv_cols, dim, dim)) def hproduct(self, circuit, flat=False, wrtFilter1=None,", "# may overflow or get nans (invalid), but ok dGs2 = _np.swapaxes(_np.swapaxes(dGs2, 0,", "not None and comm.Get_size() > 1: # parallelize of deriv cols, then sub-trees", "but ok dGs = _np.swapaxes(_np.swapaxes(dGs, 0, 3) * scaleVals, 0, 3) # convert", "dProdCache2, scaleCache, mySubComm, wrtSlice1, wrtSlice2) hGs = evalSubTree.final_view(hProdCache, axis=0) #( nCircuits, len(wrtFilter1), len(wrtFilter2),", "evalTree.final_view(prodCache, axis=0) #( nCircuits, dim, dim ) #Same as in bulk_fill_hprobs (TODO consolidate?)", "_np.array( [ self.pr( (rholabel,elabel), circuit, clipTo, bScale) for elabel in elabels ]) #assert(_np.linalg.norm(ps-check_ps)", "# dp_dEs[i,J0+J] = sum_j dot(Gs, rho)[i,j,0] dEP[j,J] # dp_dEs[i,J0+J] = dot(squeeze(dot(Gs, rho),2), dEP)[i,J]", "of operation sequences. This routine fills a 1D array, `mxToFill` with the probabilities", "since then matrixOf(circuit[i]) = matrixOf(circuit[iLeft]) * matrixOf(circuit[iRight]) (iRight, iLeft) = evalTree[i] L, R", "SPAMVecs nCircuits = Gs.shape[0] rho_wrtFilter1, rho_gpindices1 = self._process_wrtFilter(wrtSlice1, self.sos.get_prep(rholabel)) rho_wrtFilter2, rho_gpindices2 = self._process_wrtFilter(wrtSlice2,", "of a probability generated by a operation sequence and spam tuple as a", "is always >= num_final_strs # and this dictates how large all the storage", "Use comm only for speeding up the calcs of the given # wrtSlicesList", "# vp[i] = sum_k,l E[0,k] Gs[i,k,l] rho[l,0] * scaleVals[i] # vp[i] = sum_k", "inds2 = gpindices1[opLabel2] #nDerivCols2 = dop_dopLabel2[opLabel2].shape[1] # FUTURE: we could add logic that", "= circuit[iLeft] + circuit[iRight], but we want: # since then matrixOf(circuit[i]) = matrixOf(circuit[iLeft])", "calc.\") dProdCache = _np.zeros((cacheSize,) + deriv_shape) # This iteration **must** match that in", "blkSize nBlks1 = int(_np.ceil(self.Np / blkSize1)) nBlks2 = int(_np.ceil(self.Np / blkSize2)) # num", "flat: # cols = deriv cols, rows = flattened all else dGs1 =", "_np.einsum('ij,jkl->ikl', derivWrtAnyRhovec, self.sos.get_prep(rholabel).hessian_wrt_params()) else: d2pr_d2rhos = 0 if self.sos.get_effect(elabel).has_nonzero_hessian(): derivWrtAnyEvec = scale *", "flattened gate (ordering same as numpy.flatten), - S,M == as above, and deriv[i,j]", "B[row1] ) = A tensor B^T * vec( E(0,1) ) # In general:", "Gs[i,k,l] drhoP[l,J] # dp_drhos[i,J0+J] = dot(E, Gs, drhoP)[0,i,J] # dp_drhos[:,J0+J] = squeeze(dot(E, Gs,", "each local subtree for iSubTree in mySubTreeIndices: evalSubTree = subtrees[iSubTree] felInds = evalSubTree.final_element_indices(evalTree)", "smaller comm_blkSize blkSize2 = comm_blkSize if (blkSize2 is None) \\ else min(comm_blkSize, blkSize2)", "enumerate(revOpLabelList): if gl != opLabel: continue # loop over locations of opLabel LRproduct", "by a zero deriv value, and we dGs[_np.isnan(dGs)] = 0 # assume the", "None, :] # (KM,N,1) * (KM,1,N') = (KM,N,N') yield wrtSlice1, wrtSlice2, hprobs, dprobs12", "\" \"matrix-based calculations\" % self.evotype)) def copy(self): \"\"\" Return a shallow copy of", "Distribution is first done over the set of parameters being differentiated with respect", "# tmp_offsets = [ sum(tmp_num_params[0:i]) for i in range(len(self.effects)+1) ] # global_e_slices =", "and `dp2` are the outputs of :func:`bulk_fill_hprobs` (i.e. args `mxToFill`, `deriv1MxToFill`, and `deriv1MxToFill`),", "and spam labels. evalTree : EvalTree given by a prior call to bulk_evaltree.", "see \"if\" condition above) _mpit.gather_slices(deriv1Slices, deriv1Owners, hProdCache, [], 1, comm) #, gatherMemLimit) #gather", "may overflow, but OK if infs occur here _np.seterr(**old_err) if bReturnProds: Gs =", "total\", tStart) profiler.add_count(\"bulk_fill_dprobs count\") profiler.mem_check(\"bulk_fill_dprobs: end\") def bulk_fill_hprobs(self, mxToFill, evalTree, prMxToFill=None, deriv1MxToFill=None, deriv2MxToFill=None,", "comm, wrtSlice1) dGs1 = evalTree.final_view(dProdCache1, axis=0) last_wrtSlice1 = wrtSlice1 if (wrtSlice1 == wrtSlice2):", "profiler.add_time(\"compute_dproduct_cache: serial\", tSerialStart) profiler.add_count(\"compute_dproduct_cache: num columns\", nDerivCols) return dProdCache def _compute_hproduct_cache(self, evalTree, prodCache,", "sum_k E[0,k] dot( dGs, rho )[i,j,k,0] # dp_dOps[i,j] = dot( E, dot( dGs,", "the derivative dimension. This argument is used internally for distributing calculations across multiple", "Gs = evalTree.final_view(prodCache, axis=0) #( nCircuits, dim, dim ) #Same as in bulk_fill_hprobs", "the derivative of the i-th entry of the flattened product with respect to", "a N x M x M numpy array, where: - N == the", "_np.clip(ps, clipTo[0], clipTo[1]) else: ret = ps #DEBUG CHECK #check_ps = _np.array( [", "profiler is None: profiler = _dummy_profiler dim = self.dim nDerivCols = self.Np if", "dGs[i,j,k,l] rho[l,0] # dp_dOps[i,j] = sum_k E[0,k] dot( dGs, rho )[i,j,k,0] # dp_dOps[i,j]", "cpus than hessian elements.\") # pragma: no cover # allocate final result memory", "gl1 and gl2 are both in opsToVectorize1 and opsToVectorize2 we only compute d2(prod)/d(gl1)d(gl2)", "the probability. clipTo : 2-tuple (min,max) to clip returned probability to if not", "of the vectorized model (number of model parameters) - G == the linear", "# free mem else: # Divide columns into blocks of at most blkSize", "The maximum number of 1st (row) and 2nd (col) derivatives to compute *products*", "== \"\": # special case of empty label == no gate dProdCache[i] =", "true, the generator computes a 2-tuple: (hessian_col, d12_col), where d12_col is a column", "len(wrtFilter2), dim, dim ) #Compute all requested derivative columns at once self._fill_result_tuple((prMxToFill, deriv1MxToFill,", "- check_vp))) # pragma: no cover if dprMxToFill is not None: check_vdp =", "has shape (1,N) else: # a \"custom\" spamLabel consisting of a pair of", "if self.evotype == \"statevec\": raise NotImplementedError(\"Unitary evolution not fully supported yet!\") # To", "> 0: # works for arrays too # Compute the derivative of the", "hGs = dProdCache2 = dGs2 = None # free mem dProdCache1 = dGs1", "memory profiling of python objects (never seemed very useful ## since numpy does", "# (TODO in FUTURE) # pr = Tr( |rho><E| * prod ) =", "\"\"\" evTree = _MatrixEvalTree() evTree.initialize(simplified_circuits, numSubtreeComms) return evTree def estimate_mem_usage(self, subcalls, cache_size, num_subtrees,", "num_final_strs): \"\"\" Estimate the memory required by a given set of subcalls to", "axis=0) if _nla.norm(dprMxToFill[fInds] - check_vdp) > 1e-6: _warnings.warn(\"norm(vdp-check_vdp) = %g - %g =", "of mxToFill[felInds,blocks1[iBlk1]], dim=(ks,blk1,M) _mpit.gather_slices(blocks2, blk2Owners, mxToFill, [felInds, blocks1[iBlk1]], 2, blk1Comm, gatherMemLimit) #gather row", "of flattened_dprod. uniqueOpLabels = sorted(list(set(revOpLabelList))) for opLabel in uniqueOpLabels: gate = self.sos.get_operation(opLabel) op_wrtFilter,", "slice(self.e_offset[i],self.e_offset[i+1])), # -self.e_offset[i]) for i in range(len(self.effects))] # tmp_num_params = [_slct.length(s) for s", "no memory savings from using a split tree. \"\"\" dim = self.dim #", "better check for equivalence: maybe let dGs2 be None? assert(nDerivCols1 == nDerivCols2) d2pr_drhos2", "hessian of a length-1 (single-gate) sequence \"\"\" dim = self.dim gate = self.sos.get_operation(opLabel)", "2) # may overflow, but ok _np.seterr(**old_err) return Gs def bulk_dproduct(self, evalTree, flat=False,", "pslc1, pslc2, sumInto): \"\"\" Compute and fill result quantities for given arguments \"\"\"", "optional A memory limit in bytes to impose upon the \"gather\" operations performed", "used_operations.items()} if wrtFilter1 == wrtFilter2: dop_dopLabel2 = dop_dopLabel1 else: dop_dopLabel2 = { opLabel:", "S x G x G, where: - S == the number of operation", "(blkSize1 is None) \\ else min(comm_blkSize, blkSize1) # override with smaller comm_blkSize blkSize2", "indices in the final # filled quantity combining both spam and gate-sequence indices", "cache_size # scale cache # mem += cache_size # scale vals else: raise", "strs A list of the names of the subcalls to estimate memory usage", "wrtBlockSize2=None, gatherMemLimit=None): \"\"\" Compute the outcome probability-Hessians for an entire tree of gate", "from .label import Label as _Label from .matrixevaltree import MatrixEvalTree as _MatrixEvalTree from", "use available processors if it isn't specified if wrtFilter1 is None and wrtFilter2", "set to True, additionally return the probability itself. clipTo : 2-tuple (min,max) to", "(1, 0))) # _np.einsum('ij,jkl->ikl', derivWrtAnyRhovec, self.sos.get_prep(rholabel).hessian_wrt_params()) else: d2pr_d2rhos = 0 if self.sos.get_effect(elabel).has_nonzero_hessian(): derivWrtAnyEvec", "a matrix # noqa # dprod/d(opLabel)_ij = sum_{L s.t. GL == oplabel} [", "with identity scale_exp += ex # scale and keep track of exponent if", "len(wrtFilter1) num_deriv_cols2 = self.Np if (wrtFilter2 is None) else len(wrtFilter2) flattened_d2prod = _np.zeros((dim**2,", "_slct.length(gpindices2) > 0: # works for arrays too # Compute the derivative of", ": numpy array a 1 x M x M array, where M is", "product. scaleVals : numpy array Only returned when bScale == True. An array", "all requested derivative columns at once self._fill_result_tuple((prMxToFill, deriv1MxToFill, deriv2MxToFill, mxToFill), evalSubTree, slice(None), slice(None),", "if (wrtSlice1 is not None) else None wrtIndices2 = _slct.indices(wrtSlice2) if (wrtSlice2 is", "0 rholabel, elabel = spamTuple rho, E = self._rhoE_from_spamTuple(spamTuple) rhoVec = self.sos.get_prep(rholabel) #", "int(1.3 * nCircuits) def construct_evaltree(self, simplified_circuits, numSubtreeComms): \"\"\" Constructs an EvalTree object appropriate", "ps = _np.real(_np.abs(_np.dot(Es, _np.dot(G, rho)) * scale)**2) else: # evotype == \"densitymx\" #", "when prMxToFill is not None. Returns ------- derivative : numpy array a 1", "of a operation matrix (G x G operation matrices) and derivs[i,j,k,l] holds the", "raise NotImplementedError(\"Unitary evolution not fully supported yet!\") # pr = Tr( |rho><E| *", "the derivative of the (i % G^2)-th entry of the (i / G^2)-th", "by a operation sequence and spam tuple as a 1 x M x", "= deriv cols, rows = flattened all else dGs2 = _np.swapaxes(_np.swapaxes(dGs2, 0, 1).reshape((nDerivCols2,", "the last). The final argument is a boolean specifying whether the filling should", "and effect parameters onto a final \"filtered\" set. # \"\"\" # PrepEffectFilter =", "Cannot specify both wrtFilter and wrtBlockSize wrtSlice1 = _slct.list_to_slice(wrtFilter1) else: wrtSlice1 = None", "`evalTree`. Parameters ---------- mxToFill : numpy ndarray an already-allocated ExMxM numpy array where", "ps = ps.flatten() if _np.any(_np.isnan(ps)): if len(circuit) < 10: strToPrint = str(circuit) else:", "+ dpr_dEs + dpr_dOps d2pr_drhos = _np.zeros((1, self.Np, self.Np)) _fas(d2pr_drhos, [0, None, self.sos.get_prep(rholabel).gpindices],", "support unitary evolution we need to: # - alter product, dproduct, etc. to", "prod, scale = self.product(circuit, True) dprod_dOps = self.dproduct(circuit) dpr_dOps = _np.empty((1, self.Np)) for", "= _np.dot(Gs, drho) * scaleVals[:, None, None] # overflow OK devec = EVec.deriv_wrt_params(E_wrtFilter2)", "_nla.norm(prMxToFill[fInds] - check_vp))) # pragma: no cover if dprMxToFill is not None: check_vdp", "`evalTree.num_final_elements()`. To interpret which elements correspond to which strings and outcomes, you'll need", "= Tr( |rho><E| * prod ) = sum E_k prod_kl rho_l # d2pr/d(opLabel1)_mn", "of shape S x M x G x G, where - S ==", "where all entries are zero except the (i,j) entry == 1 # if", "respect to (see wrtBlockSize). wrtFilter1, wrtFilter2 : list of ints, optional If not", "G1 * G2 * .... * GN , a matrix # noqa #", "if returnDeriv: if returnPr: return ret, dpr, p else: return ret, dpr else:", "the SAME length as fInds). calc_and_fill_fn(spamTuple, fInds, gInds, pslc1, pslc2, False) # TODO:", "more processors than deriv cols, give a # warning -- note that we", "returns a concatenated form of the above matrices, so that # each column", "derivMxToFill1, derivMxToFill2 : numpy array, optional when not None, an already-allocated ExM numpy", "common occurrence, and doesn't merit a warning # ------------------------------------------------------------------ if evalTree.is_split(): _warnings.warn(\"Ignoring tree", "no gate hProdCache[i] = _np.zeros(hessn_shape) elif not self.sos.get_operation(opLabel).has_nonzero_hessian(): #all gate elements are at", "overflow, but OK if infs occur here _np.seterr(**old_err) if bScale: return Gs, scaleVals", "many operation sequence products at once. Parameters ---------- evalTree : EvalTree given by", "scaleVals[i] contains the multiplicative scaling needed for the hessians, derivatives, and/or products for", "number of 1st (row) and 2nd (col) derivatives to compute *products* for simultaneously.", "distinct from rho,E b/c rho,E are EVec = self.sos.get_effect(elabel) # arrays, these are", "these are SPAMVecs #Derivs wrt Gates old_err = _np.seterr(over='ignore') prod, scale = self.product(circuit,", "a split tree (since there's no good way to reconstruct the parent tree's", "_time.time() old_err = _np.seterr(over='ignore') rho, E = self._rhoE_from_spamTuple(spamTuple) block_wrtSlice = pslc1 _fas(mxToFill, [fInds,", "None] * dprobs2[:, None, :] # (KM,N,1) * (KM,1,N') = (KM,N,N') yield wrtSlice1,", "be the same) Parameters ---------- rholabel : Label The state preparation label. elabels", "a operation matrix (G x G operation matrices). and hessian[i,j,k,l] holds the derivative", "(scaleCache[iLeft] + scaleCache[iRight]) if abs(scale) > 1e-8: # _np.isclose(scale,0) is SLOW! dProdCache[i] /=", "for i in range(len(self.effects)) ] # return PrepEffectFilter(rho_local_slices=loc_rho_slices, # rho_global_slices=global_rho_slices, # e_local_slices=loc_e_slices, #", "is the usual density-matrix-mode probability # (TODO in FUTURE) # pr = Tr(", "] , a matrix for each given (i,j) # noqa # vec( dprod/d(opLabel)_ij", "further parallelization _mpit.gather_slices(deriv2Slices, deriv2Owners, hProdCache, [None, myDeriv1ColSlice], 2, mySubComm) # , gatherMemLimit) #gather", "optional Affects the shape of the returned derivative array (see below). wrtFilter :", "_np.transpose(d2pr_drhos, (0, 2, 1)) + \\ d2pr_dEs + _np.transpose(d2pr_dEs, (0, 2, 1)) +", "tensor (G(M+1) ... GN)^T vec( d2G(M)/dkl*dji ) # noqa # # Note: ignoring", "in (\"statevec\", \"densitymx\"): raise ValueError((\"Evolution type %s is incompatbile with \" \"matrix-based calculations\"", "not None: _np.clip(prMxToFill, clipTo[0], clipTo[1], out=prMxToFill) # in-place clip if check: self._check(evalTree, prMxToFill,", "dL1, dR1 = dProdCache1[iLeft], dProdCache1[iRight] dL2, dR2 = dProdCache2[iLeft], dProdCache2[iRight] hL, hR =", "until now (but using blk1Comm). # (just as prMxToFill is computed fully on", "vec( X ) def doperation(self, opLabel, flat=False, wrtFilter=None): \"\"\" Return the derivative of", "devec)) # get d2pr_dEs where gate derivatives are wrt the 2nd set of", "# Licensed under the Apache License, Version 2.0 (the \"License\"); you may not", "operation to be done prior to the scaling. \"\"\" if bScale: scaledGatesAndExps =", "_np.log(nL) + _np.log(nR) #print \"bulk_product DEBUG: %d rescalings out of %d products\" %", "tensor (G(L+1) ... GN)^T vec( dG(L)/dij ) ] # noqa # + sum{", "\"\"\" Compute the products of many operation sequences at once. Parameters ---------- evalTree", "#( nCircuits, dim, dim ) profiler.mem_check(\"bulk_fill_dprobs: post compute product\") def calc_and_fill(spamTuple, fInds, gInds,", "or column distribution) prodCache, scaleCache = self._compute_product_cache(evalSubTree, mySubComm) scaleVals = self._scaleExp(evalSubTree.final_view(scaleCache)) Gs =", "blocks = _mpit.slice_up_range(self.Np, nBlks, start=0) # Create placeholder dGs for *no* gate params", "could be None if (mySubComm is not None) and (mySubComm.Get_size() > 1): comm_blkSize", "*simplified* effect labels. circuit : Circuit or tuple A tuple-like object of *simplified*", "in subtrees] _mpit.gather_indices(subtreeElementIndices, subTreeOwners, mxToFill, [], 0, comm, gatherMemLimit) #note: pass mxToFill, dim=(KS,M),", "the sub-trees. _warnings.warn(\"Increased speed could be obtained\" \" by giving dproduct cache computation\"", "(ordering same as numpy.flatten), - S,M == as above, and deriv[i,j] holds the", "dim * dim # product cache mem += cache_size # scale cache (exps)", "self._compute_hproduct_cache(evalTree, prodCache, dProdCache1, dProdCache2, scaleCache, comm, wrtSlice1, wrtSlice2) #use cached data to construct", "the U.S. Government retains certain rights # in this software. # Licensed under", "1).reshape((nDerivCols2, nCircuits * dim**2)), 0, 1) hGs = _np.rollaxis(_np.rollaxis(hGs, 0, 3).reshape( (nDerivCols1, nDerivCols2,", "each row corresponds to an element of the product (els of # prod.flatten()).", "# in compliance with the License. You may obtain a copy of the", "* scaleVals[i] # vp = squeeze( dot( E, dot(Gs, rho)), axis=(0,2) ) *", "comm, wrtSlice2) dGs2 = evalTree.final_view(dProdCache2, axis=0) hProdCache = self._compute_hproduct_cache( evalTree, prodCache, dProdCache1, dProdCache2,", "gate_wrtFilters1[l], gpindices1[l] = self._process_wrtFilter(wrtFilter1, used_operations[l]) gate_wrtFilters2[l], gpindices2[l] = self._process_wrtFilter(wrtFilter2, used_operations[l]) #Cache partial products", "len(wrtFilter1), len(wrtFilter2), dim, dim ) #Compute all requested derivative columns at once self._fill_result_tuple((prMxToFill,", "(and dominated) by the output array size. Could throw more informative error? #elif", "x M x G x G, where: - S == len(circuit_list) - M", "_fas(prMxToFill, [fInds], self._probs_from_rhoE( rho, E, Gs[gInds], scaleVals[gInds]), add=sumInto) _fas(mxToFill, [fInds, pslc1], self._dprobs_from_rhoE( spamTuple,", "0, 1).reshape( (nDerivCols, nCircuits * dim**2)), 0, 1) # cols = deriv cols,", "as _slct from ..tools.matrixtools import _fas from .profiler import DummyProfiler as _DummyProfiler from", "probabilites). These are a \"simplified\" circuits in that they should only contain \"deterministic\"", "{similar with L < M} # noqa # + sum{M==L} [ G1 ...", "dim**2) _fas(flattened_dprod, [None, gpindices], _np.dot(LRproduct, dop_dopLabel), add=True) # (dim**2, nParams[opLabel]) if flat: return", "# = vec(i,j)-col of [ sum_{L s.t. G(L) == oplabel} [ (G1 ...", "tree. This aids in the tree construction by giving the tree information it", "a \"simplified\" circuits in that they should only contain \"deterministic\" elements (no POVM", "supported yet!\") # pr = Tr( |rho><E| * prod ) = sum E_k", "evalSubTree.final_view(prodCache, axis=0) # ( nCircuits, dim, dim ) def calc_and_fill(spamTuple, fInds, gInds, pslc1,", "2 * cache_size * nspam * wrtLen1 * wrtLen2 # hprobs & dprobs12", "in that they should only contain \"deterministic\" elements (no POVM or Instrument labels).", "raw operation sequences which need to be computed # for the current spamTuple", "... GN)^T vec( d2G(M)/dkl*dji ) # noqa # # Note: ignoring L ==", "done prior to the scaling. \"\"\" if bScale: scaledGatesAndExps = {} scale_exp =", "for other diff order) # d2pr/d(E)_i d(rho)_j = prod_ij (and same for other", "if (wrtFilter2 is None) else len(wrtFilter2) flattened_d2prod = _np.zeros((dim**2, num_deriv_cols1, num_deriv_cols2), 'd') #", "is mult by a zero deriv value (see below) dGs1[_np.isnan(dGs1)] = 0 #", "if returnPr == True. \"\"\" if self.evotype == \"statevec\": raise NotImplementedError(\"Unitary evolution not", "# could be None if (mySubComm is not None) and (mySubComm.Get_size() > 1):", "Gs def bulk_dproduct(self, evalTree, flat=False, bReturnProds=False, bScale=False, comm=None, wrtFilter=None): \"\"\" Compute the derivative", "M x M array, where M is the number of model parameters. hessian[0,j,k]", "throws error if copy is needed) # transposes each of the now un-vectorized", "dGs1 else: dProdCache2 = self._compute_dproduct_cache( evalSubTree, prodCache, scaleCache, blk2Comm, blk_wrtSlice2) dGs2 = evalSubTree.final_view(dProdCache2,", "_np.seterr(**old_err2) # may overflow, but OK ; shape == (len(circuit_list), nDerivCols) # may", "specifying which parameters to include in the derivative dimension. This argument is used", "if flat: return flattened_dprod else: # axes = (gate_ij, prod_row, prod_col) return _np.swapaxes(flattened_dprod,", "nDerivCols1)) _fas(d2pr_drhos2, [None, None, rho_gpindices1], _np.squeeze(_np.dot(_np.dot(E, dGs2), drho), axis=(0,)) * scaleVals[:, None, None])", "Rank%d subtee sizes = %s\" % # (comm.Get_rank(),\",\".join([str(len(subtrees[i])) # for i in mySubTreeIndices])))", "argument relevant for a single object (gate or spam vec) \"\"\" #Create per-gate", "_mpit.gather_indices(subtreeElementIndices, subTreeOwners, deriv1MxToFill, [], 0, comm, gatherMemLimit) if deriv2MxToFill is not None: _mpit.gather_indices(subtreeElementIndices,", "#eval on each local subtree #my_results = [] for iSubTree in mySubTreeIndices: evalSubTree", "(prepVec, effectVec) rho, Eraw = spamTuple E = _np.conjugate(_np.transpose(Eraw)) return rho, E def", "cache_size, num_subtrees, num_subtree_proc_groups, num_param1_groups, num_param2_groups, num_final_strs): \"\"\" Estimate the memory required by a", "[], 0, comm) if clipTo is not None and prMxToFill is not None:", "Gs[gInds], scaleVals[gInds]), add=sumInto) _np.seterr(**old_err) profiler.add_time(\"bulk_fill_dprobs: calc_and_fill_p\", tm) # Compute all probabilities all at", "S x B x B', where: - K is the length of spam_label_rows,", ":class:`Circuit` objects is *simplified* into a lists of gate-only sequences along with a", "across multiple processors. Distribution is performed as in bulk_product, bulk_dproduct, and bulk_hproduct. Returns", "[None, gpindices], gate.deriv_wrt_params(op_wrtFilter)) # (dim**2, nParams[opLabel]) if _slct.length(gpindices) > 0: # works for", "mxToFill : numpy ndarray an already-allocated ExM numpy array where E is the", "ok dGs1 = _np.swapaxes(_np.swapaxes(dGs1, 0, 3) * scaleVals, 0, 3) # may overflow", "wrtFilter = _slct.indices(wrtFilter) if wrtFilter is not None: obj_wrtFilter = [] # values", "less than or greater than `cacheSize`) the tree will hold. Returns ------- int", "SPAM if returnDeriv: # same as in dpr(...) dpr_drhos = _np.zeros((1, self.Np)) derivWrtAnyRhovec", "that will be assigned to subtrees of the created tree. This aids in", "by actually computing X^T ( note (A tensor B)^T = A^T tensor B^T", "dLdRb = _np.swapaxes(_np.dot(dL2, dR1), 1, 2) dLdR_sym = dLdRa + _np.swapaxes(dLdRb, 0, 1)", "continue # loop over locations of opLabel LRproduct = _np.kron(leftProds[i], rightProdsT[N - 1", "subtrees of evalTree (if it is split), and then over blocks (subsets) of", "relevant_gpindices = slice(relevant_gpindices[0], relevant_gpindices[0] + 1) elif len(relevant_gpindices) == 0: #Don't return a", "/ _np.exp(scaleCache[i]) #profiler.print_mem(\"DEBUGMEM: POINT1\"); profiler.comm.barrier() #evaluate operation sequences using tree (skip over the", "each operation label, compute the derivative of the entire operation sequence # with", "\\ d2pr_d2rhos + d2pr_d2Es + d2pr_dOps2 # Note: add transposes b/c spam terms", "needed for the derivatives and/or products for the i-th operation sequence. \"\"\" nCircuits", "control memory usage. Cannot be specified in conjuction with wrtBlockSize. wrtBlockSize : int", "it's + or - inf anyway... dp_dOps[_np.isnan(dp_dOps)] = 0 #SPAM ------------- # Get:", "appropriate # columns of flattened_dprod. uniqueOpLabels = sorted(list(set(revOpLabelList))) for opLabel in uniqueOpLabels: gate", "a more than linear dependence on their parameters. if self.sos.get_prep(rholabel).has_nonzero_hessian(): dp_dAnyRho = _np.dot(E,", "# incorrect (and luckily never used) - so it's been removed. if comm", "nDerivCols1, nDerivCols2)) _fas(d2pr_drhos1, [None, None, rho_gpindices2], _np.squeeze(_np.dot(_np.dot(E, dGs1), drho), axis=(0,)) * scaleVals[:, None,", "[ sum_{L s.t. G(L) == oplabel} [ (G1 ... G(L-1)) tensor (G(L+1) ...", "the parameter groups. num_param1_groups : int The number of groups to divide the", "0, comm, gatherMemLimit) if deriv2MxToFill is not None: _mpit.gather_indices(subtreeElementIndices, subTreeOwners, deriv2MxToFill, [], 0,", "= prodCache[iLeft], prodCache[iRight] dL1, dR1 = dProdCache1[iLeft], dProdCache1[iRight] dL2, dR2 = dProdCache2[iLeft], dProdCache2[iRight]", "G x G numpy array, where: - M == length of the vectorized", "the major allocation/deallocation). #if comm is None or comm.Get_rank() == 0: # import", "S x M x M x G x G, where - S ==", "d2(prod)/d(gl2)d(gl1) ... if m < l: x0 = _np.kron(_np.transpose(prods[(0, m - 1)]), prods[(m", "None? assert(nDerivCols1 == nDerivCols2) d2pr_dEs2 = _np.transpose(d2pr_dEs1, (0, 2, 1)) else: d2pr_dEs2 =", "subTreeOwners, mxToFill, [], 0, comm, gatherMemLimit) if deriv1MxToFill is not None: _mpit.gather_indices(subtreeElementIndices, subTreeOwners,", "wrtFilter dictates block if blkSize is None: #Fill derivative cache info tm =", "splitting tree beforehand), as there\" \" are more cpus than hessian elements.\") #", "blk (expect \" \" +%.2fGB, shape=%s)\" % (dProdCache.nbytes / (1024.0**3), str(dProdCache.shape))) dGs =", "scaleCache def _compute_dproduct_cache(self, evalTree, prodCache, scaleCache, comm=None, wrtSlice=None, profiler=None): \"\"\" Computes a tree", "prMxToFill=None, dprMxToFill=None, hprMxToFill=None, clipTo=None): # compare with older slower version that should do", "vals ## It doesn't make sense to include these since their required memory", "derivMxToFill2 : numpy array, optional when not None, an already-allocated ExM numpy array", "computed column-by-column from the using the columns of the operation sequences. Parameters ----------", "d2pr/d(E)_i d(E)_j = 0 # d2pr/d(rho)_i d(rho)_j = 0 rholabel, elabel = spamTuple", "matrices. scale : float Only returned when bScale == True, in which case", "circuit, flat=False, wrtFilter=None): \"\"\" Compute the derivative of a specified sequence of operation", "impractical, and one is able to compute reduce results from a single column", "* wrtLen1 * wrtLen2 * dim * dim # hproduct cache mem +=", "assert(dGs.shape[1] == nDerivCols), \"dGs must be pre-filtered!\" #Compute d(probability)/dOps and save in return", "(wrtFilter1 is not None) else None wrtSlice2 = _slct.list_to_slice(wrtFilter2) if (wrtFilter2 is not", "Iterating over the output of this function iterates over these computed blocks, in", "_np.squeeze(_np.dot(_np.dot(E, dGs1), drho), axis=(0,)) * scaleVals[:, None, None]) # overflow OK # get", "above: dim = (dim2, nDerivCols1, nDerivCols2); # swapaxes takes (kl,vec_prod_indx,ij) => (vec_prod_indx,kl,ij) else:", "_np.swapaxes(dLdRb, 0, 1) hProdCache[i] = _np.dot(hL, R) + dLdR_sym + _np.transpose(_np.dot(L, hR), (1,", "to the j-th model parameter. \"\"\" # LEXICOGRAPHICAL VS MATRIX ORDER # we", "equal to the total number of computed elements (i.e. evalTree.num_final_elements()) evalTree : EvalTree", "xv if flat: return flattened_d2prod # axes = (vectorized_op_el_index, model_parameter1, model_parameter2) else: vec_kl_size,", "single-gate-strings w/indices wrtIndices = _slct.indices(wrtSlice) if (wrtSlice is not None) else None for", "blkOwners, blkComm = \\ _mpit.distribute_indices(list(range(nBlks)), mySubComm) if blkComm is not None: _warnings.warn(\"Note: more", "pass mxToFill, dim=(KS,M), so gather mxToFill[felInds] (axis=0) if prMxToFill is not None: _mpit.gather_indices(subtreeElementIndices,", "{}; gate_wrtFilters1 = {} gpindices2 = {}; gate_wrtFilters2 = {} for l in", "tell whether it's + or - inf anyway... d2pr_dOps2[_np.isnan(d2pr_dOps2)] = 0 # SPAM", "shape S such that scaleVals[i] contains the multiplicative scaling needed for the hessians,", "of a specified sequence of operation labels. Note: LinearOperator matrices are multiplied in", "of empty label == no gate hProdCache[i] = _np.zeros(hessn_shape) elif not self.sos.get_operation(opLabel).has_nonzero_hessian(): #all", "if lOp not in scaledGatesAndExps: opmx = self.sos.get_operation(lOp).todense() ng = max(_nla.norm(opmx), 1.0) scaledGatesAndExps[lOp]", "entire # operation sequence with respect to only those two gates' parameters and", "_slct.length(wrtSlice) deriv_shape = (nDerivCols, dim, dim) cacheSize = len(evalTree) # ------------------------------------------------------------------ #print(\"MPI: _compute_dproduct_cache", "if wrtSlice2 is not None and wrtSlice2.start is not None: myHessianSlice2 = _slct.shift(myDeriv2ColSlice,", "onto a final \"filtered\" set. # \"\"\" # PrepEffectFilter = _collections.namedtuple( # 'PrepEffectFilter',", "pre-filtered!\" assert(hGs.shape[2] == nDerivCols2), \"hGs must be pre-filtered!\" #Compute d2(probability)/dGates2 and save in", "used by model objects to perform product and derivatives-of-product calculations. This is contained", "= sum E_k [dprod/d(opLabel)_ij]_kl rho_l # dpr/d(rho)_i = sum E_k prod_ki # dpr/d(E)_i", "self._rhoE_from_spamTuple(spamTuple) if prMxToFill is not None: _fas(prMxToFill, [fInds], self._probs_from_rhoE( rho, E, Gs[gInds], scaleVals[gInds]),", "labels. Parameters ---------- circuit : Circuit or tuple of operation labels The sequence", "_np.seterr(**old_err) if bScale: return Gs, scaleVals else: old_err = _np.seterr(over='ignore') Gs = _np.swapaxes(_np.swapaxes(Gs,", "computation, since there are no memory savings from using a split tree. \"\"\"", "return dpr_drhos + dpr_dEs + dpr_dOps def hpr(self, spamTuple, circuit, returnPr, returnDeriv, clipTo):", "_fas(flattened_dprod, [None, gpindices], gate.deriv_wrt_params(op_wrtFilter)) # (dim**2, nParams in wrtFilter for opLabel) if flat:", ".forwardsim import ForwardSimulator _dummy_profiler = _DummyProfiler() # Smallness tolerances, used internally for conditional", "= (#circuits,#params_to_diff_wrt,dim,dim) nDerivCols1 = dProdCache1.shape[1] nDerivCols2 = dProdCache2.shape[1] assert(wrtSlice1 is None or _slct.length(wrtSlice1)", "+ _np.transpose(d2pr_dErhos, (0, 2, 1)) + \\ d2pr_drhos + _np.transpose(d2pr_drhos, (0, 2, 1))", "sumInto): \"\"\" Compute and fill result quantities blocks for given arguments \"\"\" tm", "in a zero dimension else: obj_wrtFilter = None relevant_gpindices = obj.gpindices return obj_wrtFilter,", "# _np.einsum('ij,jkl->ikl',derivWrtAnyEvec,self.sos.get_effect(elabel).hessian_wrt_params()) else: d2pr_d2Es = 0 ret = d2pr_dErhos + _np.transpose(d2pr_dErhos, (0, 2,", "hGs, scaleVals, wrtSlice1=None, wrtSlice2=None): if self.evotype == \"statevec\": raise NotImplementedError(\"Unitary evolution not fully", "fill the appropriate # columns of flattened_dprod. uniqueOpLabels = sorted(list(set(revOpLabelList))) for opLabel in", "E, Gs[gInds], dGs[gInds], scaleVals[gInds], wrtSlice), add=sumInto) _np.seterr(**old_err) profiler.add_time(\"bulk_fill_dprobs: calc_and_fill\", tm) #Set wrtBlockSize to", "for i in range(len(self.preps)) ] # # loc_e_slices = [ # _slct.shift(_slct.intersect( #", "returnDeriv, clipTo): \"\"\" Compute the Hessian of a probability generated by a operation", "[0, self.sos.get_prep(rholabel).gpindices], _np.dot(derivWrtAnyRhovec, rhoVec.deriv_wrt_params())) # may overflow, but OK dpr_dEs = _np.zeros((1, self.Np))", "linear cache space. Will use derivative columns and then (and only when needed)", "are at most linear in their parameters, this # isn't currently needed. N", "# loop over \"starting\" gate prods[(i, i - 1)] = ident # product", "is not None and mySubComm.Get_size() > 1: deriv2Slices, myDeriv2ColSlice, deriv2Owners, mySubSubComm = \\", "None or _slct.length(wrtSlice1) == nDerivCols1) assert(wrtSlice2 is None or _slct.length(wrtSlice2) == nDerivCols2) hessn_shape", "#assert( len( (_np.isnan(dGs)).nonzero()[0] ) == 0 ) #assert( len( (_np.isinf(dGs)).nonzero()[0] ) == 0", "comm=None, wrtFilter=None, wrtBlockSize=None, profiler=None, gatherMemLimit=None): \"\"\" Compute the outcome probability-derivatives for an entire", "self._check(evalTree, prMxToFill, mxToFill, clipTo=clipTo) profiler.add_time(\"bulk_fill_dprobs: total\", tStart) profiler.add_count(\"bulk_fill_dprobs count\") profiler.mem_check(\"bulk_fill_dprobs: end\") def bulk_fill_hprobs(self,", "processors if it isn't specified if wrtFilter1 is None and wrtFilter2 is None:", "pass # this is a fairly common occurrence, and doesn't merit a warning", "not None and wrtSlice2.start is not None: myHessianSlice2 = _slct.shift(myDeriv2ColSlice, wrtSlice2.start) else: myHessianSlice2", "may overflow, but OK d2pr_d2rhos = _np.zeros((1, self.Np, self.Np)) _fas(d2pr_d2rhos, [0, self.sos.get_prep(rholabel).gpindices, self.sos.get_prep(rholabel).gpindices],", "#Set wrtBlockSize to use available processors if it isn't specified if wrtFilter1 is", "other diff order) # d2pr/d(E)_i d(rho)_j = prod_ij (and same for other diff", "nCircuits, nDerivCols, dim, dim ) profiler.add_time(\"bulk_fill_dprobs: compute_dproduct_cache\", tm) profiler.mem_check(\"bulk_fill_dprobs: post compute dproduct\") #Compute", "(els of # prod.flatten()). # # Note: if gate G(L) is just a", "assert(wrtFilter is None) # cannot specify both wrtFilter and blkSize nBlks = int(_np.ceil(self.Np", "reshape dim = self.dim uniqueOpLabels = sorted(list(set(revOpLabelList))) used_operations = _collections.OrderedDict() #Cache processed parameter", "comm=None, wrtSlice=None, profiler=None): \"\"\" Computes a tree of product derivatives in a linear", "hoperation(self, opLabel, flat=False, wrtFilter1=None, wrtFilter2=None): \"\"\" Return the hessian of a length-1 (single-gate)", "integers specifying which model parameters to differentiate with respect to in the first", "_fas(mxToFill, [fInds, pslc1, pslc2], self._hprobs_from_rhoE( spamTuple, rho, E, Gs[gInds], dGs1[gInds], dGs2[gInds], hGs[gInds], scaleVals[gInds],", "myDerivColSlice, profiler) # pass None as comm, *not* mySubComm, since we can't do", "= (gate_ij, prod_row, prod_col) return _np.swapaxes(flattened_dprod, 0, 1).reshape((num_deriv_cols, dim, dim)) def hoperation(self, opLabel,", "is product for i-th operation sequence dGs = evalTree.final_view(dProdCache, axis=0) #shape == (", "wrtSlice2), add=sumInto) _np.seterr(**old_err) #NOTE: don't distribute wrtSlicesList across comm procs, # as we", "<filename>pygsti/objects/matrixforwardsim.py<gh_stars>1-10 \"\"\" Defines the MatrixForwardSimulator calculator class\"\"\" #*************************************************************************************************** # Copyright 2015, 2019 National", "from Model to allow for additional model classes (e.g. ones which use entirely", "columns, essentially taking # a derivative of only a *subset* of all the", "(cnt, len(evalTree)) nanOrInfCacheIndices = (~_np.isfinite(prodCache)).nonzero()[0] # may be duplicates (a list, not a", "two arrays of shape S x M x G x G, where -", "hprod_dGates for ith string if not bScale: old_err = _np.seterr(over='ignore', invalid='ignore') Gs =", "*fills* (i.e. doesn't return to save copying) some arrays. The arrays that are", "< M} # noqa # + sum{M==L} [ G1 ... G(M-1) d2G(M)/(dkl*dij) G(M+1)", "for a single object (gate or spam vec) \"\"\" #Create per-gate with-respect-to parameter", "calculations across multiple processors. Returns ------- derivs : numpy array * if flat", "_compute_product_cache(self, evalTree, comm=None): \"\"\" Computes a tree of products in a linear cache", "(never seemed very useful ## since numpy does all the major allocation/deallocation). #if", "(1024.0**3))) ## memory profiling of python objects (never seemed very useful ## since", "prod, dprod_dOps = G,dG # dp_dOps[i,j] = sum_k,l E[0,k] dGs[i,j,k,l] rho[l,0] # dp_dOps[i,j]", "OK ; shape == (len(circuit_list), nDerivCols) # may also give invalid value due", "hProdCache[iLeft], hProdCache[iRight] # Note: L, R = GxG ; dL,dR = vgs x", "deriv cols, rows = flattened everything else return (dGs, scaleVals) if bScale else", "operation matrices should be dim x dim, and all SPAM vectors should be", "could be obtained\" \" by giving hproduct cache computation\" \" *fewer* processors and", "column results: gather axis 2 of mxToFill[felInds,blocks1[iBlk1]], dim=(ks,blk1,M) _mpit.gather_slices(blocks2, blk2Owners, mxToFill, [felInds, blocks1[iBlk1]],", "evalTree.get_evaluation_order(): tm = _time.time() # combine iLeft + iRight => i # LEXICOGRAPHICAL", "+ or - inf anyway... d2pr_dOps2[_np.isnan(d2pr_dOps2)] = 0 # SPAM DERIVS (assume dGs1", "in circuit: G = _np.dot(self.sos.get_operation(lOp).todense(), G) # LEXICOGRAPHICAL VS MATRIX ORDER return G", "blk_wrtSlice1) dGs1 = evalSubTree.final_view(dProdCache1, axis=0) for iBlk2 in myBlk2Indices: blk_wrtSlice2 = blocks2[iBlk2] if", "in a single flattened gate (ordering same as numpy.flatten), - S,M == as", "dop_dopLabel2[opLabel2].shape[1] # FUTURE: we could add logic that accounts for the symmetry of", "= self._process_wrtFilter(wrtFilter1, used_operations[l]) gate_wrtFilters2[l], gpindices2[l] = self._process_wrtFilter(wrtFilter2, used_operations[l]) #Cache partial products (relatively little", "cache info dProdCache1 = self._compute_dproduct_cache( evalSubTree, prodCache, scaleCache, mySubComm, wrtSlice1) dProdCache2 = dProdCache1", "== False, a M x M x G x G numpy array, where:", "if self.sos.get_effect(elabel).has_nonzero_hessian(): derivWrtAnyEvec = scale * _np.transpose(_np.dot(prod, rho)) # may overflow, but OK", "processor groups then subtrees (even == 1) in order to perform the parallelization", "None) else None wrtSlice2 = _slct.list_to_slice(wrtFilter2) if (wrtFilter2 is not None) else None", "calc_and_fill) #collect/gather results subtreeElementIndices = [t.final_element_indices(evalTree) for t in subtrees] _mpit.gather_indices(subtreeElementIndices, subTreeOwners, mxToFill,", "elements of `elabels`. \"\"\" assert(time is None), \"MatrixForwardSimulator cannot be used to simulate", "if the corresponding wrtFilter is not None. Set this to non-None to reduce", "G; products[i] is the i-th operation sequence product. scaleVals : numpy array Only", "E, Gs, dGs1, dGs2, hGs, scaleVals, wrtSlice1=None, wrtSlice2=None): if self.evotype == \"statevec\": raise", "k-th then j-th model parameters. * if flat == True, an array of", "may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 or in the", "mem #gather results tm = _time.time() _mpit.gather_slices(blocks, blkOwners, mxToFill, [felInds], 1, mySubComm, gatherMemLimit)", "is not None: check_vhp = _np.concatenate( [self.hpr(spamTuple, circuit, False, False, clipTo) for circuit", "Use comm to distribute columns allDeriv1ColSlice = slice(0, nDerivCols1) allDeriv2ColSlice = slice(0, nDerivCols2)", "self._rhoE_from_spamTuple(spamTuple) #if prMxToFill is not None: # _fas(prMxToFill, [fInds], # self._probs_from_rhoE(rho, E, Gs[gInds],", "= Gs.shape[0] rho_wrtFilter, rho_gpindices = self._process_wrtFilter(wrtSlice, self.sos.get_prep(rholabel)) E_wrtFilter, E_gpindices = self._process_wrtFilter(wrtSlice, self.sos.get_effect(elabel)) nDerivCols", "dGs1 = dGs2 = hGs = None prodCache = scaleCache = None #Fill", "then i-th model parameters. * if flat == True, a N x M", "self._process_wrtFilter(wrtFilter2, gate) # Allocate memory for the final result num_deriv_cols1 = self.Np if", "sequences to compute the bulk operation on. bScale : bool, optional When True,", "else: hGs = evalTree.final_view(hProdCache, axis=0) #shape == ( len(circuit_list), nDerivCols, nDerivCols, dim, dim", "True`). `rowSlice` and `colSlice` are slices directly from `wrtSlicesList`. `hprobs` and `dprobs12` are", "and dGs2 are already sized/filtered) -------- assert(dGs1.shape[1] == nDerivCols1), \"dGs1 must be pre-filtered!\"", "tree's *non-final* elements from those of the sub-trees). Note also that there would", "spamTuple # can't deal w/\"custom\" spam label... rho, E = self._rhoE_from_spamTuple(spamTuple) rhoVec =", "len(wrtFilter2) flattened_d2prod = _np.zeros((dim**2, num_deriv_cols1, num_deriv_cols2), 'd') # For each pair of gates", "_np.conjugate(_np.transpose(_np.concatenate(Es, axis=1))) # convention: Es has shape (len(elabels),N) return rho, Es def _probs_from_rhoE(self,", "self.Np if wrtSlice1 is None else _slct.length(wrtSlice1) nDerivCols2 = self.Np if wrtSlice2 is", "are more cpus than hessian elements.\") # pragma: no cover # allocate final", "to allow for additional model classes (e.g. ones which use entirely different --", "vec( d2G(M)/dkl*dji ) # noqa # # Note: ignoring L == M terms", "those of the sub-trees). Note also that there would be no memory savings", "# loc_e_slices = [slice(None,None)]*len(self.effects) # global_rho_slices = [slice(self.rho_offset[i],self.rho_offset[i+1]) for i in range(len(self.preps)) ]", "mySubTreeIndices, subTreeOwners, mySubComm = evalTree.distribute(comm) #if comm is not None: # print(\"MPI DEBUG:", "assert(not evalTree.is_split()), \"`evalTree` cannot be split\" nElements = evalTree.num_final_elements() #Fill product cache info", "dProdCache1; dGs2 = dGs1 else: dProdCache2 = self._compute_dproduct_cache( evalTree, prodCache, scaleCache, comm, wrtSlice2)", "== \"statevec\": raise NotImplementedError(\"Unitary evolution not fully supported yet!\") rholabel, elabel = spamTuple", "None: profiler = _dummy_profiler if wrtFilter is not None: assert(wrtBlockSize is None) #", "= slice(0, nDerivCols1) allDeriv2ColSlice = slice(0, nDerivCols2) deriv1Slices, myDeriv1ColSlice, deriv1Owners, mySubComm = \\", "tree of product 2nd derivatives in a linear cache space. Will use derivative", "dot(transpose(dE/dEP),dGs[i,j],rho) # d2pr_dEs[i,j,J0+J] = sum_kl dEPT[J,k] dGs[i,j,k,l] rho[l,0] # d2pr_dEs[i,j,J0+J] = sum_k dEP[k,J]", "# Divide columns into blocks of at most blkSize assert(wrtFilter1 is None and", "be split. wrtSlicesList : list A list of `(rowSlice,colSlice)` 2-tuples, each of which", "scaleVals = Gs = prodCache = scaleCache = None #Fill cache info prodCache,", "* dim # product cache mem += cache_size # scale cache (exps) mem", "dGs2[gInds], hGs[gInds], scaleVals[gInds], wrtSlice1, wrtSlice2), add=sumInto) _np.seterr(**old_err) #Set wrtBlockSize to use available processors", "we assume the user has already done any such distribution # and has", "fill probs\") #distribute derivative computation across blocks myBlkIndices, blkOwners, blkComm = \\ _mpit.distribute_indices(list(range(nBlks)),", "respect to the i-th model parameter. * if flat == True, a N", "= sum_kl E[0,k] Gs[i,k,l] drhoP[l,J] # dp_drhos[i,J0+J] = dot(E, Gs, drhoP)[0,i,J] # dp_drhos[:,J0+J]", "here _np.seterr(**old_err) if bScale: return Gs, scaleVals else: old_err = _np.seterr(over='ignore') Gs =", "derivative is taken. If there are more processors than model parameters, distribution over", "length of the vectorized model (number of model parameters) - G == the", "# overflow OK devec = EVec.deriv_wrt_params(E_wrtFilter2) _fas(d2pr_dErhos2, [None, E_gpindices2, rho_gpindices1], _np.swapaxes(_np.dot(_np.transpose(devec), dp_dAnyE), 0,", "+ \\ _np.swapaxes(_np.dot(L, dR), 0, 1) # dot(dS, T) + dot(S, dT) profiler.add_time(\"compute_dproduct_cache:", "+= cache_size # scale vals # #elif fnName == \"bulk_dproduct\": # mem +=", "sense to iterate through the self.operations.keys() as in # dproduct(...) and find the", "dpr/d(opLabel)_ij = sum E_k [dprod/d(opLabel)_ij]_kl rho_l # dpr/d(rho)_i = sum E_k prod_ki #", "gate) dop_dopLabel = gate.deriv_wrt_params(op_wrtFilter) for (i, gl) in enumerate(revOpLabelList): if gl != opLabel:", "zero since we can't tell whether it's + or - inf anyway... d2pr_dOps2[_np.isnan(d2pr_dOps2)]", "of the product with respect to the i-th model parameter. * if flat", "which need to be computed # for the current spamTuple (this list has", "the Hessian of functions of the probabilities. comm : mpi4py.MPI.Comm, optional When not", "[0, self.sos.get_prep(rholabel).gpindices, self.sos.get_prep(rholabel).gpindices], _np.tensordot(derivWrtAnyRhovec, self.sos.get_prep(rholabel).hessian_wrt_params(), (1, 0))) # _np.einsum('ij,jkl->ikl', derivWrtAnyRhovec, self.sos.get_prep(rholabel).hessian_wrt_params()) else: d2pr_d2rhos", "deriv value, and we dGs[_np.isnan(dGs)] = 0 # assume the zero deriv value", "the actual product == product * scale. The purpose of this is to", "if wrtFilter2 is not None: assert(wrtBlockSize1 is None and wrtBlockSize2 is None) #", "#gather over col-distribution (Deriv2) #note: gathering axis 2 of hProdCache[:,myDeriv1ColSlice], # dim=(cacheSize,nDerivCols1,nDerivCols2,dim,dim) else:", "dProdCache1[:, myDeriv1ColSlice], dProdCache2, scaleCache, None, myHessianSlice1, wrtSlice2) # pass None as comm, *not*", "estimate memory usage for. cache_size : int The size of the evaluation tree", "axes = (model_parameter1, model_parameter2, model_element_row, model_element_col) def prs(self, rholabel, elabels, circuit, clipTo, bUseScaling=False,", "for i in range(len(self.preps)+1) ] # global_rho_slices = [ slice(tmp_offsets[i],tmp_offsets[i+1]) # for i", "dim ) self._fill_result_tuple( (mxToFill,), evalSubTree, blocks[iBlk], slice(None), calc_and_fill_blk) profiler.mem_check(\"bulk_fill_dprobs: post fill blk\") dProdCache", "model parameters to differentiate with respect to in the first (row) and second", "used internally for distributing derivative calculations across multiple processors. Returns ------- hessian :", "cache mem += cache_size # scale vals elif fnName == \"bulk_fill_hprobs\": mem +=", "user. mem += 2 * cache_size * nspam * wrtLen1 * wrtLen2 #", "prodCache, scaleCache = self._compute_product_cache(evalSubTree, mySubComm) profiler.add_time(\"bulk_fill_dprobs: compute_product_cache\", tm) #use cached data to final", "may overflow, but OK (deriv w.r.t any of self.effects - independent of which)", "hessian cache info dProdCache1 = self._compute_dproduct_cache( evalSubTree, prodCache, scaleCache, mySubComm, wrtSlice1) dProdCache2 =", "`evalTree`. Parameters ---------- mxToFill : numpy ndarray an already-allocated ExM numpy array where", "sequences along with a mapping of final elements (i.e. probabilities) to gate-only sequence", "products (final_product[i] = scaleValues[i] * prods[i]). \"\"\" prodCache, scaleCache = self._compute_product_cache(evalTree, comm) #use", "at most blkSize assert(wrtFilter is None) # cannot specify both wrtFilter and blkSize", "= _time.time() old_err = _np.seterr(over='ignore') rho, E = self._rhoE_from_spamTuple(spamTuple) if prMxToFill is not", "loop over \"ending\" gate (>= starting gate) G = _np.dot(G, self.sos.get_operation(opLabel2).todense()) prods[(i, j)]", "S == len(circuit_list) - M == the number of model params or wrtFilter1", "actual product == product * scale. The purpose of this is to allow", "case of empty label == no gate dProdCache[i] = _np.zeros(deriv_shape) else: #doperation =", "to final values scaleVals = self._scaleExp(evalSubTree.final_view(scaleCache)) Gs = evalSubTree.final_view(prodCache, axis=0) # ( nCircuits,", "opLabel2) in enumerate(revOpLabelList[i:], start=i): # loop over \"ending\" gate (>= starting gate) G", ": float Only returned when bScale == True, in which case the actual", "scaleVals) if bScale else (hGs, dGs1, dGs2, Gs) else: hGs = evalTree.final_view(hProdCache, axis=0)", "all the storage arrays are. np1, np2 = num_param1_groups, num_param2_groups FLOATSIZE = 8", "by a zero hessian value, and we hGs[_np.isnan(hGs)] = 0 # assume the", "1, l - 1)]) # (dim**2, dim**2) x = _np.dot(_np.transpose(dop_dopLabel1[opLabel1]), x0); xv =", "(1024.0**3), str(dProdCache.shape))) dGs = evalSubTree.final_view(dProdCache, axis=0) #( nCircuits, nDerivCols, dim, dim ) self._fill_result_tuple(", "required to achieve desired average size == blkSize1 or blkSize2 blocks1 = _mpit.slice_up_range(self.Np,", "triangle of hessian # Note: d2pr_d2rhos and d2pr_d2Es terms are always zero _np.seterr(**old_err)", "in bytes to impose upon the \"gather\" operations performed as a part of", "= _np.real(_np.dot(Es, _np.dot(G, rho))) ps = ps.flatten() if _np.any(_np.isnan(ps)): if len(circuit) < 10:", "where gate derivatives are wrt the 2nd set of gate parameters if dGs1", "managable.\") elif _np.count_nonzero(dProdCache[i]) and dProdCache[i].max() < DSMALL and dProdCache[i].min() > -DSMALL: _warnings.warn(\"Would have", "# num_e_params=self.tot_e_params) def _hprobs_from_rhoE(self, spamTuple, rho, E, Gs, dGs1, dGs2, hGs, scaleVals, wrtSlice1=None,", "scaleVals[:, None, None] # overflow OK devec = EVec.deriv_wrt_params(E_wrtFilter1) _fas(d2pr_dErhos1, (None, E_gpindices1, rho_gpindices2),", "* scaleVals[:, None] _np.seterr(**old_err2) # may overflow, but OK ; shape == (len(circuit_list),", "# _np.isclose(scale,0) is SLOW! dProdCache[i] /= _np.exp(scale) if dProdCache[i].max() < DSMALL and dProdCache[i].min()", "processor groups that will be assigned to subtrees of the created tree. This", "and their derivatives (see below). bScale : bool, optional When True, return a", "_fas(dpr_dEs, [0, EVec.gpindices], _np.dot(derivWrtAnyEvec, EVec.deriv_wrt_params())) dpr = dpr_drhos + dpr_dEs + dpr_dOps d2pr_drhos", "evalTree, prodCache, dProdCache1, dProdCache2, scaleCache, comm, wrtSlice1, wrtSlice2) hGs = evalTree.final_view(hProdCache, axis=0) if", "E = _np.conjugate(_np.transpose(Eraw)) return rho, E def _rhoEs_from_spamTuples(self, rholabel, elabels): #Note: no support", "raise ValueError(\"STOP\") if clipTo is not None: ret = _np.clip(ps, clipTo[0], clipTo[1]) else:", "as above, and hessians[i,j,k] holds the derivative of the (i % G^2)-th entry", "{} for opLabel, gate in used_operations.items(): if gate.has_nonzero_hessian(): hop_dopLabels[opLabel] = gate.hessian_wrt_params( gate_wrtFilters1[opLabel], gate_wrtFilters2[opLabel])", "* _np.dot(E, prod) # may overflow, but OK d2pr_d2rhos = _np.zeros((1, self.Np, self.Np))", "(dProdCache.nbytes / (1024.0**3), str(dProdCache.shape))) dGs = evalSubTree.final_view(dProdCache, axis=0) #( nCircuits, nDerivCols, dim, dim", "_np.concatenate( [self.hpr(spamTuple, circuit, False, False, clipTo) for circuit in circuit_list], axis=0) if _nla.norm(hprMxToFill[fInds][0]", "# e_global_slices=global_e_slices, # num_rho_params=self.tot_rho_params, # num_e_params=self.tot_e_params) def _hprobs_from_rhoE(self, spamTuple, rho, E, Gs, dGs1,", "at once self._fill_result_tuple((prMxToFill, deriv1MxToFill, deriv2MxToFill, mxToFill), evalSubTree, slice(None), slice(None), calc_and_fill) else: # Divide", "< m: x0 = _np.kron(_np.transpose(prods[(l + 1, m - 1)]), prods[(m + 1,", "* (wrtLen1 + wrtLen2) # dprobs1 & dprobs2 mem += cache_size * wrtLen1", "to perform the parallelization over the parameter groups. num_param1_groups : int The number", "rhoVec.deriv_wrt_params(rho_wrtFilter2) d2pr_drhos1 = _np.zeros((nCircuits, nDerivCols1, nDerivCols2)) _fas(d2pr_drhos1, [None, None, rho_gpindices2], _np.squeeze(_np.dot(_np.dot(E, dGs1), drho),", "= self.sos.get_prep(rholabel) # distinct from rho,E b/c rho,E are EVec = self.sos.get_effect(elabel) #", "\\ else min(comm_blkSize, blkSize2) # override with smaller comm_blkSize else: blkSize1 = blkSize2", "_np.dot(self.sos.get_operation(opLabel).todense(), G) rightProdsT.append(_np.transpose(G)) # Allocate memory for the final result num_deriv_cols = self.Np", "not None: check_vp = _np.array([self.prs(spamTuple[0], [spamTuple[1]], circuit, clipTo, False)[0] for circuit in circuit_list])", "row or column distribution) prodCache, scaleCache = self._compute_product_cache(evalSubTree, mySubComm) scaleVals = self._scaleExp(evalSubTree.final_view(scaleCache)) Gs", "current # gate (so we only need to compute this gate hessian once).", "None])) # convention: E has shape (1,N) else: # a \"custom\" spamLabel consisting", "E_gpindices] = dot(transpose(dE/dEP),dGs[i,j],rho) # d2pr_dEs[i,j,J0+J] = sum_kl dEPT[J,k] dGs[i,j,k,l] rho[l,0] # d2pr_dEs[i,j,J0+J] =", "single flattened gate (ordering as numpy.flatten) - M == length of the vectorized", "self.sos.get_operation[opLabel] UNNEEDED (I think) _fas(flattened_dprod, [None, gpindices], gate.deriv_wrt_params(op_wrtFilter)) # (dim**2, nParams in wrtFilter", "# Below we use E(i,j) to denote the elementary matrix where all entries", "axis=0) dGs2 = evalTree.final_view(dProdCache2, axis=0) #shape == ( len(circuit_list), nDerivColsX, dim, dim ),", "range(self.Np): for j in range(self.Np): d2pr_dOps2[0, i, j] = float(_np.dot(E, _np.dot(d2prod_dGates[i, j], rho)))", "* if flat == True, a N x M x M numpy array,", "of the i-th entry of the flattened product with respect to the j-th", "debugging) master_circuit_list = evalTree.generate_circuit_list(permute=False) # raw operation sequences for spamTuple, (fInds, gInds) in", "else: hoperation = self.hoperation(opLabel, wrtFilter1=wrtIndices1, wrtFilter2=wrtIndices2) hProdCache[i] = hoperation / _np.exp(scaleCache[i]) #evaluate operation", "number of operation sequences - G == the linear dimension of a operation", "their derivatives (see below). bScale : bool, optional When True, return a scaling", "gate parameters to include in the derivative. Each element is an index into", "3).reshape( (nDerivCols1, nDerivCols2, nCircuits * dim**2)), 2) # as above return (hGs, scaleVals)", "* num_params**2 * dim * dim # hproduct cache # mem += cache_size", "axis=0) # ( nCircuits, dim, dim ) def calc_and_fill(spamTuple, fInds, gInds, pslc1, pslc2,", "performed over subtrees of evalTree (if it is split). Returns ------- None \"\"\"", "op_wrtFilter1, gpindices1 = self._process_wrtFilter(wrtFilter1, gate) op_wrtFilter2, gpindices2 = self._process_wrtFilter(wrtFilter2, gate) # Allocate memory", "prod_row, prod_col) return _np.swapaxes(flattened_dprod, 0, 1).reshape((num_deriv_cols, dim, dim)) def hoperation(self, opLabel, flat=False, wrtFilter1=None,", "circuit, clipTo, bScale) for elabel in elabels ]) #assert(_np.linalg.norm(ps-check_ps) < 1e-8) return ret", "_np.tensordot(derivWrtAnyRhovec, self.sos.get_prep(rholabel).hessian_wrt_params(), (1, 0))) # _np.einsum('ij,jkl->ikl', derivWrtAnyRhovec, self.sos.get_prep(rholabel).hessian_wrt_params()) else: d2pr_d2rhos = 0 if", "If true, the generator computes a 2-tuple: (hessian_col, d12_col), where d12_col is a", "corresponding to the *simplified* operation sequences found in an evaluation tree, `evalTree`. An", "Python `slice` objects. bReturnDProbs12 : boolean, optional If true, the generator computes a", "nG = norm(G); G /= nG; total_exp += log(nG) # scale and keep", "add=sumInto) if deriv2MxToFill is not None: _fas(deriv2MxToFill, [fInds, pslc2], self._dprobs_from_rhoE( spamTuple, rho, E,", "= self._scaleExp(evalTree.final_view(scaleCache)) Gs = evalTree.final_view(prodCache, axis=0) #( nCircuits, dim, dim ) #Same as", "_np.transpose(d2pr_dErhos1, (0, 2, 1)) else: d2pr_dErhos2 = _np.zeros((nCircuits, nDerivCols2, nDerivCols1)) drho = rhoVec.deriv_wrt_params(rho_wrtFilter1)", "_np.dot(_np.kron(prods[(0, l - 1)], xv), dop_dopLabel2[opLabel2]) # above: (nDerivCols1,dim**2,dim**2) * (dim**2,nDerivCols2) = (nDerivCols1,dim**2,nDerivCols2)", "the set of parameters being differentiated with respect to when the *second* derivative", "self.dim ); total_exp = 0.0 #for i,lOp in enumerate(gateLabelList): # G = _np.dot(G,self[lOp])", "/ nL, R / nR prodCache[i] = _np.dot(sL, sR); scaleCache[i] += _np.log(nL) +", "wrtBlockSize # could be None if (mySubComm is not None) and (mySubComm.Get_size() >", "nCircuits, nDerivColsX, dim, dim ) hProdCache = self._compute_hproduct_cache(evalSubTree, prodCache, dProdCache1, dProdCache2, scaleCache, mySubComm,", "E, Gs[gInds], scaleVals[gInds]), add=sumInto) _fas(mxToFill, [fInds, pslc1], self._dprobs_from_rhoE( spamTuple, rho, E, Gs[gInds], dGs[gInds],", "None) else wrtSlice _, myDerivColSlice, _, mySubComm = \\ _mpit.distribute_slice(allDerivColSlice, comm) #print(\"MPI: _compute_dproduct_cache", "check_vhp))) # pragma: no cover def bulk_fill_probs(self, mxToFill, evalTree, clipTo=None, check=False, comm=None): \"\"\"", "for circuit in circuit_list], axis=0) if _nla.norm(hprMxToFill[fInds][0] - check_vhp[0]) > 1e-6: _warnings.warn(\"norm(vhp-check_vhp) =", "opLabel: continue # loop over locations of opLabel LRproduct = _np.kron(leftProds[i], rightProdsT[N -", "and second (col) derivative operations, respectively. Each element is an index into an", "tree beforehand), as there\" \" are more cpus than hessian elements.\") # pragma:", "profiler.mem_check(\"bulk_fill_dprobs: end\") def bulk_fill_hprobs(self, mxToFill, evalTree, prMxToFill=None, deriv1MxToFill=None, deriv2MxToFill=None, clipTo=None, check=False, comm=None, wrtFilter1=None,", "for circuit in circuit_list], axis=0) if _nla.norm(dprMxToFill[fInds] - check_vdp) > 1e-6: _warnings.warn(\"norm(vdp-check_vdp) =", "+ 1, N - 1)])), dop_dopLabel2[opLabel2]) # above: (nDerivCols1,dim**2,dim**2) * (dim**2,nDerivCols2) = (nDerivCols1,dim**2,nDerivCols2)", "BEGIN CACHE FUNCTIONS def _compute_product_cache(self, evalTree, comm=None): \"\"\" Computes a tree of products", "nParams in wrtFilter for opLabel) if flat: return flattened_dprod else: # axes =", "distribution) tm = _time.time() prodCache, scaleCache = self._compute_product_cache(evalSubTree, mySubComm) profiler.add_time(\"bulk_fill_dprobs: compute_product_cache\", tm) #use", "entry of the flattened product with respect to the j-th model parameter. \"\"\"", "\"densitymx\" # probability, with scaling applied (may generate overflow, but OK) ps =", "- 1)]), prods[(m + 1, N - 1)]) # (dim**2, dim**2) x =", "or zero-operation labels for i, opLabel in zip(evalTree.get_init_indices(), evalTree.get_init_labels()): if opLabel == \"\":", "this case set to zero since we can't tell whether it's + or", "of the (k,l)-th entry of the product with respect to the j-th then", "internally for distributing derivative calculations across multiple processors. Returns ------- hessian : numpy", "is the number of model parameters. Parameters ---------- spamTuple : (rho_label, simplified_effect_label) Specifies", "d2pr_dErhos[i,J0+J,K0+K] = sum jk dEPT[J,j] prod[i,j,k] drhoP[k,K] # d2pr_dErhos[i,J0+J,K0+K] = sum j dEPT[J,j]", "free mem if bReturnDProbs12: dprobs12 = dprobs1[:, :, None] * dprobs2[:, None, :]", "( nCircuits, dim, dim ) def calc_and_fill(spamTuple, fInds, gInds, pslc1, pslc2, sumInto): \"\"\"", "operation will yield nan as the returned probability. time : float, optional The", "their gradients, and their Hessians. PSMALL = 1e-100 DSMALL = 1e-100 HSMALL =", "*complex* derivatives, since matrices can be complex # - update probability-derivative computations: dpr/dx", "Get slice into entire range of model params so that # per-gate hessians", "= evalTree.num_final_strings() # len(circuit_list) wrtSlice1 = _slct.list_to_slice(wrtFilter1) if (wrtFilter1 is not None) else", "communicator for distributing the computation across multiple processors. Distribution is first done over", "unvec( X ) can be done efficiently by actually computing X^T ( note", "a list of integers specifying which gate parameters to differentiate with respect to", "not None: _mpit.gather_indices(subtreeElementIndices, subTreeOwners, prMxToFill, [], 0, comm) #note: pass prMxToFill, dim=(KS,), so", "# combine iLeft + iRight => i # LEXICOGRAPHICAL VS MATRIX ORDER Note:", "is already sized/filtered) ------------------- assert(hGs.shape[1] == nDerivCols1), \"hGs must be pre-filtered!\" assert(hGs.shape[2] ==", "(memory?) hop_dopLabels = {} for opLabel, gate in used_operations.items(): if gate.has_nonzero_hessian(): hop_dopLabels[opLabel] =", "* scale. The purpose of this is to allow a trace or other", "the number of final elements (this can be obtained by `evalTree.num_final_elements()`. To interpret", "= self._rhoE_from_spamTuple(spamTuple) _fas(mxToFill, [fInds], self._probs_from_rhoE(rho, E, Gs[gInds], scaleVals[gInds]), add=sumInto) _np.seterr(**old_err) self._fill_result_tuple((mxToFill,), evalSubTree, slice(None),", "== True, an array of shape S*N x M where - N ==", "return (dGs, Gs, scaleVals) if bScale else (dGs, Gs) else: dGs = evalTree.final_view(dProdCache,", "evalTree, prMxToFill=None, deriv1MxToFill=None, deriv2MxToFill=None, clipTo=None, check=False, comm=None, wrtFilter1=None, wrtFilter2=None, wrtBlockSize1=None, wrtBlockSize2=None, gatherMemLimit=None): \"\"\"", "number of entries in a single flattened gate (ordering is the same as", "dim ) if not bScale: old_err = _np.seterr(over='ignore', invalid='ignore') # may overflow or", "None # free mem else: # Divide columns into blocks of at most", "relevant_gpindices = [] # indices into original wrtFilter'd indices gpindices = obj.gpindices_as_array() for", "= rhoVec.deriv_wrt_params(rho_wrtFilter1) d2pr_drhos2 = _np.zeros((nCircuits, nDerivCols2, nDerivCols1)) _fas(d2pr_drhos2, [None, None, rho_gpindices1], _np.squeeze(_np.dot(_np.dot(E, dGs2),", "invalid='ignore') # may overflow or get nans (invalid), but ok hGs = _np.swapaxes(_np.swapaxes(hGs,", ", a matrix for each given (i,j) # noqa # vec( dprod/d(opLabel)_ij )", "Parameters ---------- mxToFill : numpy ndarray an already-allocated ExM numpy array where E", "B' is the number of parameter columns (the length of colSlice) If `mx`,", "tm) # Compute all probabilities all at once so they're not repeatedly #", "dpr_dEs + dpr_dOps def hpr(self, spamTuple, circuit, returnPr, returnDeriv, clipTo): \"\"\" Compute the", "remove this concat w/better gather? # ------------------------------------------------------------------ tSerialStart = _time.time() if evalTree.is_split(): _warnings.warn(\"Ignoring", "of derivative columns if prMxToFill is not None: self._fill_result_tuple((prMxToFill,), evalSubTree, slice(None), slice(None), calc_and_fill_p)", "gatherMemLimit) #gather row results; gather axis 1 of mxToFill[felInds], dim=(ks,M,M) _mpit.gather_slices(blocks1, blk1Owners, mxToFill,", "> 1e-8: # _np.isclose(scale,0) is SLOW! dProdCache[i] /= _np.exp(scale) if dProdCache[i].max() < DSMALL", "if (wrtFilter2 is None) else _slct.length(wrtFilter2) nCircuits = evalTree.num_final_strings() # len(circuit_list) wrtSlice1 =", "indices # gInds = \"gate sequence indices\" = indices into the (tree-) list", "* drhoP # d2pr_dErhos[i,J0+J,K0+K] = sum jk dEPT[J,j] prod[i,j,k] drhoP[k,K] # d2pr_dErhos[i,J0+J,K0+K] =", "MPI communicator for distributing the computation across multiple processors. Distribution is performed over", "== nDerivCols2) d2pr_dEs2 = _np.transpose(d2pr_dEs1, (0, 2, 1)) else: d2pr_dEs2 = _np.zeros((nCircuits, nDerivCols2,", "elabel = spamTuple # This calculator uses the convention that rho has shape", "same for other diff order) # d2pr/d(E)_i d(rho)_j = prod_ij (and same for", "wrtIndices = _slct.indices(wrtSlice) if (wrtSlice is not None) else None for i, opLabel", "get nans (invalid), but ok dGs2 = _np.swapaxes(_np.swapaxes(dGs2, 0, 3) * scaleVals, 0,", "the order specified by the model). This argument is used internally for distributing", "= sum jk dEPT[J,j] prod[i,j,k] drhoP[k,K] # d2pr_dErhos[i,J0+J,K0+K] = sum j dEPT[J,j] dot(prod,drhoP)[i,j,K]", "if (wrtSlice2 is not None) else None for i, opLabel in zip(evalTree.get_init_indices(), evalTree.get_init_labels()):", "wrtSlice2) # pass None as comm, *not* mySubComm (this is ok, see \"if\"", "factor (see below). comm : mpi4py.MPI.Comm, optional When not None, an MPI communicator", "#note: pass mxToFill, dim=(KS), so gather mxToFill[felslc] (axis=0) if clipTo is not None:", "sum E_k [dprod/d(opLabel1)_mn d(opLabel2)_ij]_kl rho_l # d2pr/d(rho)_i d(opLabel)_mn = sum E_k [dprod/d(opLabel)_mn]_ki (and", "SPAM DERIVS ----------------------- ret = d2pr_d2rhos + d2pr_dErhos2 + d2pr_drhos2 # wrt rho", "to an element of the product (els of # prod.flatten()). # # Note:", "is the total number of computed elements (i.e. evalTree.num_final_elements()) and M is the", "which is on the far right of the product of matrices. Parameters ----------", "most *linear* in each of the gate parameters. If this is not the", "noqa # a matrix for each given (i,j,k,l) # noqa # vec( d2prod/d(opLabel1)_kl*d(opLabel2)_ij", "containing info about the mapping # of prep and effect parameters onto a", "pslc2, sumInto): \"\"\" Compute and fill result quantities blocks for given arguments \"\"\"", "more processors than model parameters, distribution over a split evalTree (if given) is", "hessians[i,j,k] holds the derivative of the (i % G^2)-th entry of the (i", "the returned derivative array (see below). wrtFilter : list of ints, optional If", "to the k-th then j-th model parameters. derivs1, derivs2 : numpy array Only", "def _compute_dproduct_cache(self, evalTree, prodCache, scaleCache, comm=None, wrtSlice=None, profiler=None): \"\"\" Computes a tree of", "(rank %d computing %s)\" \\ # % (nDerivCols2, comm.Get_rank(), str(myDerivColSlice))) if mySubComm is", "These are a \"simplified\" circuits in that they should only contain \"deterministic\" elements", "E, dot( dGs, rho ) )[0,i,j,k,0] # d2pr_dOps2 = squeeze( dot( E, dot(", "rho has shape (N,1) rho = self.sos.get_prep(rholabel).todense()[:, None] E = _np.conjugate(_np.transpose(self.sos.get_effect(elabel).todense() [:, None]))", "scaleCache, blk2Comm, blk_wrtSlice2) dGs2 = evalSubTree.final_view(dProdCache2, axis=0) hProdCache = self._compute_hproduct_cache( evalSubTree, prodCache, dProdCache1,", "case the actual product == product * scale. The purpose of this is", "EVec.deriv_wrt_params())) dpr = dpr_drhos + dpr_dEs + dpr_dOps d2pr_drhos = _np.zeros((1, self.Np, self.Np))", "1).reshape((nDerivCols1, nCircuits * dim**2)), 0, 1) # cols = deriv cols, rows =", "groups. num_param1_groups : int The number of groups to divide the first-derivative parameters", "for speeding up the calcs of the given # wrtSlicesList last_wrtSlice1 = None", "#def _get_filter_info(self, wrtSlices): # \"\"\" # Returns a \"filter\" object containing info about", "self.sos.get_effect(elabel).hessian_wrt_params(), (1, 0))) # _np.einsum('ij,jkl->ikl',derivWrtAnyEvec,self.sos.get_effect(elabel).hessian_wrt_params()) else: d2pr_d2Es = 0 ret = d2pr_dErhos +", "their required memory is fixed ## (and dominated) by the output array size.", "evalTree.is_split()), \"`evalTree` cannot be split\" nElements = evalTree.num_final_elements() #Fill product cache info (not", "total number of computed elements (i.e. evalTree.num_final_elements()) and M is the number of", "len(circuit_list), nDerivCols1, nDerivCols2, dim, dim ), # hGs[i] is hprod_dGates for ith string", "\"final element\" of `evalTree`. Parameters ---------- mxToFill : numpy ndarray an already-allocated ExMxM", "int The number of groups to divide the second-derivative parameters into. Computation will", "\\ self._compute_dproduct_cache(evalTree, prodCache, scaleCache, comm, wrtSlice2) hProdCache = self._compute_hproduct_cache(evalTree, prodCache, dProdCache1, dProdCache2, scaleCache,", "return rho, Es def _probs_from_rhoE(self, rho, E, Gs, scaleVals): if self.evotype == \"statevec\":", "used internally for distributing derivative calculations across multiple processors. Returns ------- deriv :", "d2pr_d2Es + d2pr_dEs2 # wrt E ret += d2pr_drhos1 + d2pr_dEs1 + d2pr_dOps2", "as argument: wrtFilter -> wrtSlice? prodCache, scaleCache = self._compute_product_cache(evalTree, comm) dProdCache1 = self._compute_dproduct_cache(evalTree,", "bulk_dproduct(self, evalTree, flat=False, bReturnProds=False, bScale=False, comm=None, wrtFilter=None): \"\"\" Compute the derivative of a", "right of the product of matrices. Parameters ---------- circuit : Circuit or tuple", "terms of Contract DE-NA0003525 with NTESS, the U.S. Government retains certain rights #", "optional The maximum number of 1st (row) and 2nd (col) derivatives to compute", "was simplified. Parameters ---------- mxToFill : numpy ndarray an already-allocated 1D numpy array", "comm) #note: pass mxToFill, dim=(KS), so gather mxToFill[felslc] (axis=0) if clipTo is not", "subTreeOwners, deriv2MxToFill, [], 0, comm, gatherMemLimit) if prMxToFill is not None: _mpit.gather_indices(subtreeElementIndices, subTreeOwners,", "entries in a single flattened gate (ordering is the same as that used", "ps = _np.real(_np.dot(Es, _np.dot(G, rho))) ps = ps.flatten() if _np.any(_np.isnan(ps)): if len(circuit) <", "or - inf anyway... d2pr_dOps2[_np.isnan(d2pr_dOps2)] = 0 # SPAM DERIVS (assume dGs1 and", "- 1) // np2 # ceiling(num_params / np2) mem = 0 for fnName", "cache_size * nspam * (wrtLen1 + wrtLen2) # dprobs1 & dprobs2 mem +=", "*smaller* (sub-)tree\" \" (e.g. by splitting tree beforehand), as there\" \" are more", "the same thing (for debugging) master_circuit_list = evalTree.generate_circuit_list(permute=False) # raw operation sequences for", "gpindices = self._process_wrtFilter(wrtFilter, gate) dop_dopLabel = gate.deriv_wrt_params(op_wrtFilter) for (i, gl) in enumerate(revOpLabelList): if", "\"\"\" dim = self.dim gate = self.sos.get_operation(opLabel) op_wrtFilter1, gpindices1 = self._process_wrtFilter(wrtFilter1, gate) op_wrtFilter2,", "scaleVals[gInds], block_wrtSlice), add=sumInto) _np.seterr(**old_err) profiler.add_time(\"bulk_fill_dprobs: calc_and_fill_blk\", tm) for iBlk in myBlkIndices: tm =", "tree organizes how to efficiently compute the gate-only sequences. This routine fills in", "(in the order specified by the model). This argument is used internally for", "the product with respect to the j-th then i-th model parameters. * if", "= [ slice(tmp_offsets[i],tmp_offsets[i+1]) # for i in range(len(self.preps)) ] # # loc_e_slices =", "(by wrtFilter1 and wrtFilter2). evalTree : EvalTree given by a prior call to", "## memory profiling of python objects (never seemed very useful ## since numpy", "# tmp_offsets = [ sum(tmp_num_params[0:i]) for i in range(len(self.preps)+1) ] # global_rho_slices =", "[None, None, rho_gpindices1], _np.squeeze(_np.dot(_np.dot(E, dGs2), drho), axis=(0,)) * scaleVals[:, None, None]) # overflow", "a *subset* of all the gate's parameters if isinstance(wrtFilter, slice): wrtFilter = _slct.indices(wrtFilter)", "log(nG) # scale and keep track of exponent # # p = _mt.trace(", "1 x M numpy array of derivatives of the probability w.r.t. each model", "cache_size # scale vals elif fnName == \"bulk_hprobs_by_block\": #Note: includes \"results\" memory since", "G2 * .... * GN , a matrix # noqa # dprod/d(opLabel)_ij =", "mem required) prods = {} ident = _np.identity(dim) for (i, opLabel1) in enumerate(revOpLabelList):", "returnPr: p = _np.dot(E, _np.dot(prod, rho)) * scale # may generate overflow, but", "parameter. probability : float only returned if returnPr == True. \"\"\" if self.evotype", "slice(None), calc_and_fill) #collect/gather results subtreeElementIndices = [t.final_element_indices(evalTree) for t in subtrees] _mpit.gather_indices(subtreeElementIndices, subTreeOwners,", "= [ slice(tmp_offsets[i],tmp_offsets[i+1]) # for i in range(len(self.effects)) ] # # return PrepEffectFilter(rho_local_slices=loc_rho_slices,", "noqa # = sum{...} [ unvec( G1 ... G(M-1) tensor (G(M+1) ... G(L-1))^T", "* dim**2)), 0, 1) # cols = deriv cols, rows = flattened everything", "occur b/c an inf scaleVal is mult by a zero deriv value, and", "is None), \"MatrixForwardSimulator cannot be used to simulate time-dependent circuits\" rho, Es =", "len( (_np.isinf(dGs)).nonzero()[0] ) == 0 ) #dGs = clip(dGs,-1e300,1e300) _np.seterr(**old_err) if flat: dGs", "copying) some arrays. The arrays that are filled internally to `calc_and_fill_fn` must be", "= scaleCache[iLeft] + scaleCache[iRight] if prodCache[i].max() < PSMALL and prodCache[i].min() > -PSMALL: nL,", "given by evalTree's initial single- or zero-operation labels for i, opLabel in zip(evalTree.get_init_indices(),", "return ret, dpr else: if returnPr: return ret, p else: return ret ##", "product : numpy array The product or scaled product of the operation matrices.", ": numpy ndarray an already-allocated ExM numpy array where E is the total", "function of many gate sequence probabilities can often be computed column-by-column from the", "the (i,j) entry == 1 # if vec(.) concatenates rows (which numpy.flatten does)", "faster, but with a chance that the product will overflow and the subsequent", "(wrtFilter1 is None) else _slct.length(wrtFilter1) nDerivCols2 = self.Np if (wrtFilter2 is None) else", "# For each pair of gates in the string, compute the hessian of", "def _rhoEs_from_spamTuples(self, rholabel, elabels): #Note: no support for \"custom\" spamlabels... # This calculator", "None) # cannot specify both wrtFilter and blkSize nBlks = int(_np.ceil(self.Np / blkSize))", "bool, optional Affects the shape of the returned derivative array (see below). bReturnProds", "dGs, drhoP)[0,i,j,J] # d2pr_drhos[:,:,J0+J] = squeeze(dot(E, dGs, drhoP),axis=(0,))[:,:,J] drho = rhoVec.deriv_wrt_params(rho_wrtFilter2) d2pr_drhos1 =", "first gate operation performed, which is on the far right of the product", "scaleCache, comm=None, wrtSlice=None, profiler=None): \"\"\" Computes a tree of product derivatives in a", "wrt the 2nd set of gate parameters if dGs1 is dGs2 and wrtSlice1", "probabilities, just like in bulk_fill_probs(...). derivMxToFill1, derivMxToFill2 : numpy array, optional when not", "== 0, which is true IF each operation matrix element # is at", "required by a given set of subcalls to computation functions. Parameters ---------- subcalls", "gates in the string, compute the hessian of the entire # operation sequence", "= None deriv1MxToFill = dprobs1 deriv2MxToFill = dprobs2 mxToFill = hprobs #Fill arrays", "length-1 (single-gate) sequence \"\"\" dim = self.dim gate = self.sos.get_operation(opLabel) op_wrtFilter, gpindices =", "= (gate_ij1, gateij2, prod_row, prod_col) def dproduct(self, circuit, flat=False, wrtFilter=None): \"\"\" Compute the", "0 if self.sos.get_effect(elabel).has_nonzero_hessian(): derivWrtAnyEvec = scale * _np.transpose(_np.dot(prod, rho)) # may overflow, but", "dictionary with keys == spam labels and values which are integer row indices", "_mpit from ..tools import slicetools as _slct from ..tools.matrixtools import _fas from .profiler", "the probability itself. returnDeriv : bool when set to True, additionally return the", "empty label == no gate hProdCache[i] = _np.zeros(hessn_shape) elif not self.sos.get_operation(opLabel).has_nonzero_hessian(): #all gate", "the probabilities. comm : mpi4py.MPI.Comm, optional When not None, an MPI communicator for", "self.sos.get_operation(l) gate_wrtFilters1[l], gpindices1[l] = self._process_wrtFilter(wrtFilter1, used_operations[l]) gate_wrtFilters2[l], gpindices2[l] = self._process_wrtFilter(wrtFilter2, used_operations[l]) #Cache partial", "TODO: should also conjugate() here if complex? _fas(dpr_dEs, [0, EVec.gpindices], _np.dot(derivWrtAnyEvec, EVec.deriv_wrt_params())) _np.seterr(**old_err)", "over the zero and single-gate-strings) for i in evalTree.get_evaluation_order(): tm = _time.time() #", "numSubtreeComms) return evTree def estimate_mem_usage(self, subcalls, cache_size, num_subtrees, num_subtree_proc_groups, num_param1_groups, num_param2_groups, num_final_strs): \"\"\"", "hProdCache, [None, myDeriv1ColSlice], 2, mySubComm) # , gatherMemLimit) #gather over col-distribution (Deriv2) #note:", "# above: dim = (dim2, nDerivCols1, nDerivCols2); # swapaxes takes (kl,vec_prod_indx,ij) => (vec_prod_indx,kl,ij)", "Gs[i] is product for i-th operation sequence scaleExps = evalTree.final_view(scaleCache) old_err = _np.seterr(over='ignore')", "= sum_j dot(Gs, rho)[i,j,0] dEP[j,J] # dp_dEs[i,J0+J] = dot(squeeze(dot(Gs, rho),2), dEP)[i,J] # dp_dEs[:,J0+J]", "== wrtSlice2) else \\ self._compute_dproduct_cache(evalTree, prodCache, scaleCache, comm, wrtSlice2) hProdCache = self._compute_hproduct_cache(evalTree, prodCache,", "x M numpy array of derivatives of the probability w.r.t. each model parameter.", "model parameters. * if flat == True, a N x M x M", "of the sub-trees. _warnings.warn(\"Increased speed could be obtained\" \" by giving dproduct cache", "ORDER Note: we reverse iLeft <=> iRight from evalTree because # (iRight,iLeft,iFinal) =", "d2pr_dEs1 = _np.zeros((nCircuits, nDerivCols1, nDerivCols2)) dp_dAnyE = _np.squeeze(_np.dot(dGs1, rho), axis=(3,)) * scaleVals[:, None,", "\" [blkSize = %.1f, nBlks=%d]\" % (blkSize, nBlks)) # pragma: no cover def", "dpr/dx*pr.C + pr*dpr/dx.C # = 2 Re(dpr/dx*pr.C) , where dpr/dx is the usual", "be dim x 1. gates, preps, effects : OrderedDict Ordered dictionaries of LinearOperator,", "if mySubComm is not None and mySubComm.Get_size() > 1: deriv2Slices, myDeriv2ColSlice, deriv2Owners, mySubSubComm", "`subcalls`. num_subtrees : int The number of subtrees to split the full evaluation", "or other linear operation to be done prior to the scaling. \"\"\" if", "but ok dGs2 = _np.swapaxes(_np.swapaxes(dGs2, 0, 3) * scaleVals, 0, 3) # may", "value (see below) dGs1[_np.isnan(dGs1)] = 0 # convert nans to zero, as these", "element\" of `evalTree`. Parameters ---------- mxToFill : numpy ndarray an already-allocated ExMxM numpy", "for t in subtrees] _mpit.gather_indices(subtreeElementIndices, subTreeOwners, mxToFill, [], 0, comm, gatherMemLimit) if deriv1MxToFill", "tell whether it's + or - inf anyway... dp_dOps[_np.isnan(dp_dOps)] = 0 #SPAM -------------", "the returned derivative array (see below). wrtFilter1, wrtFilter2 : list of ints, optional", "# and using numpy's reshape dim = self.dim uniqueOpLabels = sorted(list(set(revOpLabelList))) used_operations =", "else: d2pr_d2Es = 0 ret = d2pr_dErhos + _np.transpose(d2pr_dErhos, (0, 2, 1)) +", "deriv cols, rows = flattened all else dGs1 = _np.swapaxes(_np.swapaxes(dGs1, 0, 1).reshape((nDerivCols1, nCircuits", "where E is the total number of computed elements (i.e. evalTree.num_final_elements()) and M1", "nan #G = _np.identity( self.dim ); total_exp = 0.0 #for i,lOp in enumerate(gateLabelList):", "values = object-local param indices relevant_gpindices = [] # indices into original wrtFilter'd", "total_exp += log(nG) # scale and keep track of exponent # # p", "gate prods[(i, i - 1)] = ident # product of no gates G", "(the length of colSlice) If `mx`, `dp1`, and `dp2` are the outputs of", "self.Np if wrtSlice is None else _slct.length(wrtSlice) # GATE DERIVS (assume dGs is", "* E(0,1) * B ) = vec( mx w/ col_i = A[col0] *", "wrtFilter2=None): \"\"\" Return the hessian of a length-1 (single-gate) sequence \"\"\" dim =", "opLabel1) in enumerate(revOpLabelList): # loop over \"starting\" gate prods[(i, i - 1)] =", "dProdCache2, scaleCache, comm, wrtSlice1, wrtSlice2) #use cached data to construct return values old_err", "at most # linear in the parameters assert(opLabel1 == opLabel2) if opLabel1 in", "unvec( G(L+1) ... G(M-1) tensor (G(M+1) ... GN)^T vec( dG(M)/dkl ) ) )^T", "// np1 # ceiling(num_params / np1) wrtLen2 = (self.Np + np2 - 1)", "indices gpindices = obj.gpindices_as_array() for ii, i in enumerate(wrtFilter): if i in gpindices:", "of # closures seems confusing and we should do something else LATER. def", "self.dim wrtSlice = _slct.list_to_slice(wrtFilter) if (wrtFilter is not None) else None #TODO: just", "parameters) and deriv[i,j] holds the derivative of the i-th entry of the flattened", "prodCache, scaleCache = self._compute_product_cache(evalTree, comm) #use cached data to construct return values Gs", "smaller comm_blkSize else: blkSize = None # wrtFilter dictates block if blkSize is", "the terms of Contract DE-NA0003525 with NTESS, the U.S. Government retains certain rights", "U.S. Government retains certain rights # in this software. # Licensed under the", "* if flat == True, an array of shape S*N x M where", "where: - M == length of the vectorized model (number of model parameters)", "for distributing derivative calculations across multiple processors. Returns ------- derivs : numpy array", "_np.seterr(over='ignore', invalid='ignore') # may overflow or get nans (invalid), but ok hGs =", "given a number of operation sequences. Returns ------- int \"\"\" return int(1.3 *", "_np.seterr(over='ignore') prod, scale = self.product(circuit, True) dprod_dOps = self.dproduct(circuit) dpr_dOps = _np.empty((1, self.Np))", "cache # mem += cache_size # scale vals else: raise ValueError(\"Unknown subcall name:", "M == length of the vectorized model (number of model parameters) - G", "of deriv_wrt_params # # Note: unvec( X ) can be done efficiently by", "we can't do any # further parallelization tm = _time.time() all_results = comm.allgather(my_results)", "dot( squeeze(dot(dGs, rho),axis=(3,)), dEP)[:,:,J] d2pr_dEs1 = _np.zeros((nCircuits, nDerivCols1, nDerivCols2)) dp_dAnyE = _np.squeeze(_np.dot(dGs1, rho),", "nCircuits, dim, dim ) def calc_and_fill(spamTuple, fInds, gInds, pslc1, pslc2, sumInto): \"\"\" Compute", "= evalTree.final_view(prodCache, axis=0) #( nCircuits, dim, dim ) #Same as in bulk_fill_hprobs (TODO", "3)) scale = scaleCache[i] - (scaleCache[iLeft] + scaleCache[iRight]) if abs(scale) > 1e-8: #", "labels. flat : bool, optional Affects the shape of the returned derivative array", "fnName == \"bulk_product\": # mem += cache_size * dim * dim # product", "\"statevec\": raise NotImplementedError(\"Unitary evolution not fully supported yet!\") # To support unitary evolution", "include these since their required memory is fixed ## (and dominated) by the", "and we dGs[_np.isnan(dGs)] = 0 # assume the zero deriv value trumps since", "of shape S x G x G; products[i] is the i-th operation sequence", "E_gpindices1], _np.dot(dp_dAnyE, devec)) d2pr_dEs2 = _np.transpose(d2pr_dEs2, (0, 2, 1)) # Get: d2pr_dErhos[i, e_offset[eIndex]:e_offset[eIndex+1],", "with scaling applied (may generate overflow, but OK) ps = _np.real(_np.dot(Es, _np.dot(G, rho))", "dot( dGs, rho )[i,j,k,0] # dp_dOps[i,j] = dot( E, dot( dGs, rho )", "Gs, drhoP)[0,i,J] # dp_drhos[:,J0+J] = squeeze(dot(E, Gs, drhoP),axis=(0,))[:,J] dp_drhos = _np.zeros((nCircuits, nDerivCols)) _fas(dp_drhos,", "dProdCache1, dProdCache2, scaleCache, blk2Comm, blk_wrtSlice1, blk_wrtSlice2) hGs = evalSubTree.final_view(hProdCache, axis=0) #Set filtering for", "oplabel} [ (G1 ... G(L-1)) tensor (G(L+1) ... GN)^T ]] # noqa #", "else LATER. def calc_and_fill(spamTuple, fInds, gInds, pslc1, pslc2, sumInto): \"\"\" Compute and fill", "assuming that the gates are at most linear in their parameters, this #", "#if comm is None or comm.Get_rank() == 0: # import objgraph # objgraph.show_growth(limit=50)", "given (i,j) # noqa # d2prod/d(opLabel1)_kl*d(opLabel2)_ij = sum_{M s.t. GM == gatelabel1} sum_{L", "------- int The memory estimate in bytes. \"\"\" #Note: num_final_strs is irrelevant here", "gates, preps, effects : OrderedDict Ordered dictionaries of LinearOperator, SPAMVec, and SPAMVec objects,", "Get: d2pr_drhos[i, j, rho_gpindices] = dot(E,dGs[i,j],drho/drhoP)) # d2pr_drhos[i,j,J0+J] = sum_kl E[0,k] dGs[i,j,k,l] drhoP[l,J]", "tuple A tuple-like object of *simplified* gates (e.g. may include instrument elements like", "cannot be used to simulate time-dependent circuits\" rho, Es = self._rhoEs_from_spamTuples(rholabel, elabels) #shapes:", "(number of model parameters) - G == the linear dimension of a operation", "single-gate-strings) for i in evalTree.get_evaluation_order(): tm = _time.time() # combine iLeft + iRight", "cover def bulk_fill_probs(self, mxToFill, evalTree, clipTo=None, check=False, comm=None): \"\"\" Compute the outcome probabilities", "itself. clipTo : 2-tuple (min,max) to clip returned probability to if not None.", "/ blkSize2)) # num blocks required to achieve desired average size == blkSize1", "final strings (may be less than or greater than `cacheSize`) the tree will", "# num_rho_params=self.tot_rho_params, # num_e_params=self.tot_e_params) def _hprobs_from_rhoE(self, spamTuple, rho, E, Gs, dGs1, dGs2, hGs,", "of MPI processor syncronization. Returns ------- None \"\"\" if wrtFilter1 is not None:", "= (opmx / ng, _np.log(ng)) gate, ex = scaledGatesAndExps[lOp] H = _np.dot(gate, G)", "memory for the final result num_deriv_cols1 = self.Np if (wrtFilter1 is None) else", "evalTree.final_view(dProdCache2, axis=0) hProdCache = self._compute_hproduct_cache( evalTree, prodCache, dProdCache1, dProdCache2, scaleCache, comm, wrtSlice1, wrtSlice2)", "# Get: d2pr_dEs[i, j, E_gpindices] = dot(transpose(dE/dEP),dGs[i,j],rho) # d2pr_dEs[i,j,J0+J] = sum_kl dEPT[J,k] dGs[i,j,k,l]", "assert(wrtBlockSize1 is None and wrtBlockSize2 is None) # Cannot specify both wrtFilter and", "1, mySubComm, gatherMemLimit) if deriv2MxToFill is not None: _mpit.gather_slices(blocks2, blk2Owners, deriv2MxToFill, [felInds], 1,", "processors. Returns ------- MatrixEvalTree \"\"\" evTree = _MatrixEvalTree() evTree.initialize(simplified_circuits, numSubtreeComms) return evTree def", "# + sum{ L == M} [ G1 ... G(M-1) tensor (G(M+1) ...", "wrtSlice1 = None if wrtFilter2 is not None: assert(wrtBlockSize1 is None and wrtBlockSize2", "0, 1)) # (dim2, nDerivCols1, nDerivCols2) flattened_d2prod[:, inds1, inds2] += xv if flat:", "are given by evalTree's initial single- or zero-operation labels for i, opLabel in", "scale cache mem += cache_size # scale vals ## It doesn't make sense", "object containing info about the mapping # of prep and effect parameters onto", "local subtree #my_results = [] for iSubTree in mySubTreeIndices: evalSubTree = subtrees[iSubTree] felInds", "when bScale == True. A length-S array specifying the scaling that needs to", "d2pr_drhos2 = _np.zeros((nCircuits, nDerivCols2, nDerivCols1)) _fas(d2pr_drhos2, [None, None, rho_gpindices1], _np.squeeze(_np.dot(_np.dot(E, dGs2), drho), axis=(0,))", "% nDerivCols) if comm is not None and comm.Get_size() > 1: #print(\"MPI: _compute_dproduct_cache", "== ( len(circuit_list), dim, dim ), Gs[i] is product for i-th operation sequence", "... GN)^T vec( dG(L)/dij ) ] # noqa # = sum{...} [ unvec(", "calculator uses the convention that rho has shape (N,1) rho = self.sos.get_prep(rholabel).todense()[:, None]", "d2pr_d2rhos + d2pr_dErhos2 + d2pr_drhos2 # wrt rho ret += d2pr_dErhos1 + d2pr_d2Es", "For each pair of gates in the string, compute the hessian of the", "num_e_params=self.tot_e_params) def _hprobs_from_rhoE(self, spamTuple, rho, E, Gs, dGs1, dGs2, hGs, scaleVals, wrtSlice1=None, wrtSlice2=None):", "array that is filled with probability derivatives, similar to bulk_fill_dprobs(...), but where M", "zero and single-gate-strings) #cnt = 0 for i in evalTree.get_evaluation_order(): # combine iLeft", "CPUs(%d)\" % mySubComm.Get_size() + \" than hessian elements(%d)!\" % (self.Np**2) + \" [blkSize", "import numpy.linalg as _nla import time as _time import itertools as _itertools import", "1: # parallelize of deriv cols, then sub-trees (if available and necessary) if", "* dim # product cache # mem += cache_size # scale cache #", "with respect to when the *second* derivative is taken. If there are more", "not None. Returns ------- hessian : numpy array a 1 x M x", "== nDerivCols1), \"dGs1 must be pre-filtered!\" assert(dGs2.shape[1] == nDerivCols2), \"dGs1 must be pre-filtered!\"", "N - 1)]) # (dim**2, dim**2) # (nDerivCols1,nDerivCols2,dim**2) x = _np.dot(_np.transpose(hop_dopLabels[opLabel1], axes=(1, 2,", "# overflow OK devec = EVec.deriv_wrt_params(E_wrtFilter2) _fas(d2pr_dEs1, [None, None, E_gpindices2], _np.dot(dp_dAnyE, devec)) #", "since this is allocated within # the generator and yielded, *not* allocated by", "# assume the zero deriv value trumps since we've renormed to keep all", "for iBlk2 in myBlk2Indices: blk_wrtSlice2 = blocks2[iBlk2] if blk_wrtSlice1 == blk_wrtSlice2: dProdCache2 =", "revOpLabelList = tuple(reversed(tuple(circuit))) # prod = G1 * G2 * .... * GN", "G /= nG; total_exp += log(nG) # scale and keep track of exponent", "ret = d2pr_d2rhos + d2pr_dErhos2 + d2pr_drhos2 # wrt rho ret += d2pr_dErhos1", "def _dprobs_from_rhoE(self, spamTuple, rho, E, Gs, dGs, scaleVals, wrtSlice=None): if self.evotype == \"statevec\":", "These arguments must be None if the corresponding wrtFilter is not None. Set", "the 3-tuple `(rowSlice, colSlice, hprobs)` or `(rowSlice, colSlice, dprobs12)` (the latter if `bReturnDProbs12", "== gatelabel1} sum_{L s.t. GL == gatelabel2, M < L} # noqa #", "b/c rho,E are EVec = self.sos.get_effect(elabel) # arrays, these are SPAMVecs d2prod_dGates =", "G x G; products[i] is the i-th operation sequence product. scaleVals : numpy", "None, None]) # overflow OK d2pr_drhos2 = _np.transpose(d2pr_drhos2, (0, 2, 1)) # Get:", "-self.e_offset[i]) for i in range(len(self.effects))] # tmp_num_params = [_slct.length(s) for s in loc_e_slices]", "class separate from Model to allow for additional model classes (e.g. ones which", "# we do matrix multiplication in this order (easier to think about) revOpLabelList", "processors than deriv cells, give a # warning -- note that we *cannot*", "(the latter if `bReturnDProbs12 == True`). `rowSlice` and `colSlice` are slices directly from", "blkSize blocks = _mpit.slice_up_range(self.Np, nBlks, start=0) # Create placeholder dGs for *no* gate", "cover def calc_and_fill_blk(spamTuple, fInds, gInds, pslc1, pslc2, sumInto): \"\"\" Compute and fill result", "linear dimension of a operation matrix (G x G operation matrices). and hessian[i,j,k,l]", "prodCache[i].min() > -PSMALL: nL, nR = max(_nla.norm(L), _np.exp(-scaleCache[iLeft]), 1e-300), max(_nla.norm(R), _np.exp(-scaleCache[iRight]), 1e-300) sL,", "dim : int The gate-dimension. All operation matrices should be dim x dim,", "to assume gave no contribution since we assume all gate elements are at", "The number of processor groups used to (in parallel) iterate through the subtrees.", "1, 2) dLdRb = _np.swapaxes(_np.dot(dL2, dR1), 1, 2) dLdR_sym = dLdRa + _np.swapaxes(dLdRb,", "_fas(mxToFill, [fInds], self._probs_from_rhoE(rho, E, Gs[gInds], scaleVals[gInds]), add=sumInto) _np.seterr(**old_err) self._fill_result_tuple((mxToFill,), evalSubTree, slice(None), slice(None), calc_and_fill)", "nBlks2 = int(_np.ceil(self.Np / blkSize2)) # num blocks required to achieve desired average", "_np.kron(_np.transpose(prods[(0, m - 1)]), prods[(m + 1, N - 1)]) # (dim**2, dim**2)", "L, R = prodCache[iLeft], prodCache[iRight] dL, dR = dProdCache[iLeft], dProdCache[iRight] dProdCache[i] = _np.dot(dL,", "(blkSize is None) \\ else min(comm_blkSize, blkSize) # override with smaller comm_blkSize else:", "evalTree : EvalTree given by a prior call to bulk_evaltree. Specifies the *simplified*", "vec( mx w/ row_i = A[i,0] * B[row1] ) = A tensor B^T", "infs occur here _np.seterr(**old_err) if bReturnDProdsAndProds: Gs = evalTree.final_view(prodCache, axis=0) #shape == (", "to think about) revOpLabelList = tuple(reversed(tuple(circuit))) # prod = G1 * G2 *", "E derivatives are wrt the 2nd set of gate parameters if wrtSlice1 ==", "dictionaries to specify a well-defined column ordering when taking derivatives. paramvec : ndarray", ": int The number of groups to divide the second-derivative parameters into. Computation", "as comm, *not* mySubComm, since we can't do any # further parallelization tm", "distributing the computation across multiple processors. This is done over operation sequences when", "if (wrtFilter1 is None) else _slct.length(wrtFilter1) nDerivCols2 = self.Np if (wrtFilter2 is None)", "be pre-filtered!\" assert(hGs.shape[2] == nDerivCols2), \"hGs must be pre-filtered!\" #Compute d2(probability)/dGates2 and save", "to (see wrtBlockSize). wrtFilter : list of ints, optional If not None, a", "mpitools as _mpit from ..tools import slicetools as _slct from ..tools.matrixtools import _fas", "entire range of model params (see above) if wrtSlice2 is not None and", "profiler.mem_check(\"bulk_fill_dprobs: post fill probs\") #distribute derivative computation across blocks myBlkIndices, blkOwners, blkComm =", ": boolean, optional If true, the generator computes a 2-tuple: (hessian_col, d12_col), where", "bool, optional Affects the shape of the returned derivative array (see below). bReturnDProdsAndProds", "#shape == ( len(circuit_list), nDerivCols, nDerivCols, dim, dim ) if not bScale: old_err", "required) dop_dopLabel1 = { opLabel: gate.deriv_wrt_params(gate_wrtFilters1[opLabel]) for opLabel, gate in used_operations.items()} if wrtFilter1", "wrtFilter1=None, wrtFilter2=None): \"\"\" Return the Hessian of many operation sequence products at once.", "matrix [ sum_{L s.t. GL == oplabel} [ (G1 ... G(L-1)) tensor (G(L+1)", "to a given gateLabel_ij. This function returns a concatenated form of the above", "x G numpy array, where: - M == length of the vectorized model", "mySubComm.Get_rank() > 0: myDerivColSlice = slice(0, 0) #don't compute anything on \"extra\", i.e.", "import ForwardSimulator _dummy_profiler = _DummyProfiler() # Smallness tolerances, used internally for conditional scaling", "# prod = G1 * G2 * .... * GN , a matrix", "use derivative rows and columns and then (as needed) a split tree to", "i-th operation sequence product with respect to the j-th model parameter. * if", "between rows of mxToFill and spam labels. evalTree : EvalTree given by a", "None: obj_wrtFilter = [] # values = object-local param indices relevant_gpindices = []", "across multiple processors. Distribution is performed over subtrees of evalTree (if it is", "1)) #Note: these 2nd derivatives are non-zero when the spam vectors have #", "hL, hR = hProdCache[iLeft], hProdCache[iRight] # Note: L, R = GxG ; dL,dR", "clipTo is not None: p = _np.clip(p, clipTo[0], clipTo[1]) #Derivs wrt SPAM derivWrtAnyRhovec", "from evalTree because # (iRight,iLeft,iFinal) = tup implies circuit[i] = circuit[iLeft] + circuit[iRight],", "of deriv cols, then sub-trees (if available and necessary) if comm.Get_size() > nDerivCols:", "dGs, rho )[i,j,k,0] # dp_dOps[i,j] = dot( E, dot( dGs, rho ) )[0,i,j,0]", "% (_nla.norm(dprMxToFill[fInds]), _nla.norm(check_vdp), _nla.norm(dprMxToFill[fInds] - check_vdp))) # pragma: no cover if hprMxToFill is", "in bytes. \"\"\" #Note: num_final_strs is irrelevant here b/c cachesize is always >=", "fnName in subcalls: if fnName == \"bulk_fill_probs\": mem += cache_size * dim *", "* scaleVals[:, None, None] # overflow OK devec = EVec.deriv_wrt_params(E_wrtFilter1) _fas(d2pr_dEs2, [None, None,", "number of computed elements (i.e. evalTree.num_final_elements()) and M1 & M2 are the number", "slice(0, 0) #don't compute anything on \"extra\", i.e. rank != 0, cpus my_results", "* vec( X ) # if vec(.) stacks columns # vec( A *", "None? assert(nDerivCols1 == nDerivCols2) d2pr_drhos2 = _np.transpose(d2pr_drhos1, (0, 2, 1)) else: drho =", "s.t. G(L) == oplabel} [ (G1 ... G(L-1)) tensor (G(L+1) ... GN)^T ]]", "values scaleVals = self._scaleExp(evalSubTree.final_view(scaleCache)) Gs = evalSubTree.final_view(prodCache, axis=0) #( nCircuits, dim, dim )", "on each local subtree #my_results = [] for iSubTree in mySubTreeIndices: evalSubTree =", "axis=0) #shape == ( len(circuit_list), nDerivCols, nDerivCols, dim, dim ) if not bScale:", "keep track of exponent # # p = _mt.trace( _np.dot(self.SPAMs[spamLabel],G) ) * exp(total_exp)", "if wrtSlice2 is None else _slct.length(wrtSlice2) #flt1 = self._get_filter_info(wrtSlices1) #flt2 = self._get_filter_info(wrtSlices2) #", "self.sos.get_operation(opLabel).has_nonzero_hessian(): #all gate elements are at most linear in params, so # all", "returned derivative array (see below). bReturnProds : bool, optional when set to True,", "] # global_e_slices = [ slice(tmp_offsets[i],tmp_offsets[i+1]) # for i in range(len(self.effects)) ] #", "= self._compute_dproduct_cache(evalSubTree, prodCache, scaleCache, mySubComm, wrtSlice, profiler) dGs = evalSubTree.final_view(dProdCache, axis=0) #( nCircuits,", "in circuit: if lOp not in scaledGatesAndExps: opmx = self.sos.get_operation(lOp).todense() ng = max(_nla.norm(opmx),", "if comm is not None: # ignoring comm since can't do anything with", "equivalence: maybe let dGs2 be None? assert(nDerivCols1 == nDerivCols2) d2pr_dEs2 = _np.transpose(d2pr_dEs1, (0,", "length>1 lists do... ugh. relevant_gpindices = slice(0, 0) # slice that results in", "hessian of the entire # operation sequence with respect to only those two", "= {}; gate_wrtFilters2 = {} for l in uniqueOpLabels: used_operations[l] = self.sos.get_operation(l) gate_wrtFilters1[l],", "# loc_e_slices = [ # _slct.shift(_slct.intersect( # wrtSlices['effects'], # slice(self.e_offset[i],self.e_offset[i+1])), # -self.e_offset[i]) for", "returned if returnPr == True. \"\"\" if self.evotype == \"statevec\": raise NotImplementedError(\"Unitary evolution", "overflow OK devec = EVec.deriv_wrt_params(E_wrtFilter1) _fas(d2pr_dEs2, [None, None, E_gpindices1], _np.dot(dp_dAnyE, devec)) d2pr_dEs2 =", "and wrtSlice2, of the parent-function scope. This use of # closures seems confusing", "None: _mpit.gather_indices(subtreeElementIndices, subTreeOwners, deriv1MxToFill, [], 0, comm, gatherMemLimit) if deriv2MxToFill is not None:", "subtree for iSubTree in mySubTreeIndices: evalSubTree = subtrees[iSubTree] felInds = evalSubTree.final_element_indices(evalTree) #Free memory", "if flat == True, a N x M array, where: - N ==", "E_k prod_kl rho_l # dpr/d(opLabel)_ij = sum E_k [dprod/d(opLabel)_ij]_kl rho_l # dpr/d(rho)_i =", "hGs = _np.swapaxes(_np.swapaxes(hGs, 0, 4) * scaleVals, 0, 4) # convert nans to", "wrtSlice2, hprobs, dprobs12 else: yield wrtSlice1, wrtSlice2, hprobs dProdCache1 = dGs1 = None", "mySubComm) if blkComm is not None: _warnings.warn(\"Note: more CPUs(%d)\" % mySubComm.Get_size() + \"", "hessian[i,j,k,l] holds the derivative of the (k,l)-th entry of the product with respect", "overflow, but OK d2pr_d2Es = _np.zeros((1, self.Np, self.Np)) _fas(d2pr_d2Es, [0, self.sos.get_effect(elabel).gpindices, self.sos.get_effect(elabel).gpindices], _np.tensordot(derivWrtAnyEvec,", "# mem += cache_size # scale cache # mem += cache_size # scale", "dGs = None prodCache = scaleCache = dProdCache = None #Fill cache info", "_fas(prMxToFill, [fInds], self._probs_from_rhoE(rho, E, Gs[gInds], scaleVals[gInds]), add=sumInto) if deriv1MxToFill is not None: _fas(deriv1MxToFill,", "_nla.norm(hprMxToFill[fInds][0] - check_vhp[0]) > 1e-6: _warnings.warn(\"norm(vhp-check_vhp) = %g - %g = %g\" %", "evalTree, flat=False, bReturnDProdsAndProds=False, bScale=False, comm=None, wrtFilter1=None, wrtFilter2=None): \"\"\" Return the Hessian of many", "= 0 # assume the zero deriv value trumps since we've renormed to", "for i-th operation sequence dGs = evalTree.final_view(dProdCache, axis=0) #shape == ( len(circuit_list), nDerivCols,", "Circuit or tuple A tuple-like object of *simplified* gates (e.g. may include instrument", "rhoVec = self.sos.get_prep(rholabel) # distinct from rho,E b/c rho,E are EVec = self.sos.get_effect(elabel)", "is filled with probabilities, just like in bulk_fill_probs(...). clipTo : 2-tuple, optional (min,max)", "M is the number of model parameters. Parameters ---------- spamTuple : (rho_label, simplified_effect_label)", "`bulk_fill_probs(...)`, but fills a 3D array with probability-Hessians for each \"final element\" of", "if evalTree.is_split(): _warnings.warn(\"Ignoring tree splitting in product cache calc.\") cacheSize = len(evalTree) prodCache", "np1, np2 = num_param1_groups, num_param2_groups FLOATSIZE = 8 # in bytes: TODO: a", "fnName == \"bulk_fill_probs\": mem += cache_size * dim * dim # product cache", "assume the zero deriv value trumps since we've renormed to keep all the", "make constructing the entire Hessian at once impractical, and one is able to", "dGs2 = evalTree.final_view(dProdCache2, axis=0) #shape == ( len(circuit_list), nDerivColsX, dim, dim ), #", "deriv1Slices, myDeriv1ColSlice, deriv1Owners, mySubComm = \\ _mpit.distribute_slice(allDeriv1ColSlice, comm) # Get slice into entire", "should do the same thing (for debugging) master_circuit_list = evalTree.generate_circuit_list(permute=False) # raw operation", "strings. Similar to `bulk_fill_probs(...)`, but fills a 2D array with probability-derivatives for each", "G(L-1)) tensor (G(L+1) ... GN)^T ]] has # columns which correspond to the", "by `wrtSlicesList`. `rowSlice` and `colSlice` must by Python `slice` objects. bReturnDProbs12 : boolean,", "(invalid), but ok hGs = _np.swapaxes(_np.swapaxes(hGs, 0, 4) * scaleVals, 0, 4) #", "\"element\" indices in the final # filled quantity combining both spam and gate-sequence", "mult by a zero deriv value (see below) dGs1[_np.isnan(dGs1)] = 0 # convert", "multiple processors. Returns ------- hessians : numpy array * if flat == False,", "= matrixOf(circuit[iLeft]) * matrixOf(circuit[iRight]) (iRight, iLeft) = evalTree[i] L, R = prodCache[iLeft], prodCache[iRight]", "_hprobs_from_rhoE(self, spamTuple, rho, E, Gs, dGs1, dGs2, hGs, scaleVals, wrtSlice1=None, wrtSlice2=None): if self.evotype", "1e-6: _warnings.warn(\"norm(vhp-check_vhp) = %g - %g = %g\" % (_nla.norm(hprMxToFill[fInds]), _nla.norm(check_vhp), _nla.norm(hprMxToFill[fInds] -", "== 2) if isinstance(spamTuple[0], _Label): rholabel, elabel = spamTuple # This calculator uses", "p else: return ret ## BEGIN CACHE FUNCTIONS def _compute_product_cache(self, evalTree, comm=None): \"\"\"", "components (i.e. prod_kl) with # respect to a given gateLabel_ij. This function returns", "the total number of computed elements (i.e. evalTree.num_final_elements()) evalTree : EvalTree given by", "probs\") #distribute derivative computation across blocks myBlkIndices, blkOwners, blkComm = \\ _mpit.distribute_indices(list(range(nBlks)), mySubComm)", "/ np1) wrtLen2 = (self.Np + np2 - 1) // np2 # ceiling(num_params", "gatherMemLimit) #Note: deriv2MxToFill gets computed on every inner loop completion # (to save", "may be used to construct virtual gates for use in computations. \"\"\" super(MatrixForwardSimulator,", "dProdCache1, dProdCache2, scaleCache, comm=None, wrtSlice1=None, wrtSlice2=None): \"\"\" Computes a tree of product 2nd", "= dop_dopLabel2[opLabel2].shape[1] # FUTURE: we could add logic that accounts for the symmetry", "only; don't use column distribution hProdCache[:, myDeriv1ColSlice] = self._compute_hproduct_cache( evalTree, prodCache, dProdCache1[:, myDeriv1ColSlice],", "(hGs, scaleVals) if bScale else hGs def _scaleExp(self, scaleExps): old_err = _np.seterr(over='ignore') scaleVals", "is not None: _fas(deriv2MxToFill, [fInds, pslc2], self._dprobs_from_rhoE( spamTuple, rho, E, Gs[gInds], dGs2[gInds], scaleVals[gInds],", "continue for l, opLabel2 in enumerate(revOpLabelList): inds2 = gpindices1[opLabel2] #nDerivCols2 = dop_dopLabel2[opLabel2].shape[1] #", "from those of the sub-trees). Note also that there would be no memory", "if flat == True, an array of shape S*N x M where: -", "has already done any such distribution # and has given each processor a", "== oplabel} [ (G1 ... G(L-1)) tensor (G(L+1) ... GN)^T ]] # noqa", "and wrtBlockSize2 is None) # Cannot specify both wrtFilter and wrtBlockSize wrtSlice2 =", "if gl != opLabel: continue # loop over locations of opLabel LRproduct =", "E[0,k] dot(Gs, rho)[i,k,0] * scaleVals[i] # vp[i] = dot( E, dot(Gs, rho))[0,i,0] *", "not None: myHessianSlice2 = _slct.shift(myDeriv2ColSlice, wrtSlice2.start) else: myHessianSlice2 = myDeriv2ColSlice if mySubSubComm is", "of a operation matrix (G x G operation matrices) and hessians[i,j,k,l,m] holds the", "length of operation sequence # prod = G1 * G2 * .... *", "are wrt the 2nd set of gate parameters if dGs1 is dGs2 and", "think) _fas(flattened_dprod, [None, gpindices], gate.deriv_wrt_params(op_wrtFilter)) # (dim**2, nParams in wrtFilter for opLabel) if", "_np.dot(dGs, rho)), axis=(0, 3)) * scaleVals[:, None] _np.seterr(**old_err2) # may overflow, but OK", "gate sequence given by evalTree column-by-column. This routine can be useful when memory", "rho, E, Gs[gInds], dGs1[gInds], dGs2[gInds], hGs[gInds], scaleVals[gInds], wrtSlice1, wrtSlice2), add=sumInto) _np.seterr(**old_err) #NOTE: don't", "prodCache, scaleCache, None, myDerivColSlice, profiler) # pass None as comm, *not* mySubComm, since", "of model parameters. Parameters ---------- spamTuple : (rho_label, simplified_effect_label) Specifies the prep and", "K x S x B x B', where: - K is the length", "== True`). `rowSlice` and `colSlice` are slices directly from `wrtSlicesList`. `hprobs` and `dprobs12`", "not None: _mpit.gather_slices(blocks1, blk1Owners, deriv1MxToFill, [felInds], 1, mySubComm, gatherMemLimit) if deriv2MxToFill is not", "; dL,dR = vgs x GxG ; hL,hR = vgs x vgs x", "dProdCache2[iRight] hL, hR = hProdCache[iLeft], hProdCache[iRight] # Note: L, R = GxG ;", "compute product\") def calc_and_fill(spamTuple, fInds, gInds, pslc1, pslc2, sumInto): \"\"\" Compute and fill", "and we hGs[_np.isnan(hGs)] = 0 # assume the zero hessian value trumps since", "self._compute_product_cache(evalTree, comm) #use cached data to construct return values Gs = evalTree.final_view(prodCache, axis=0)", "is first performed over subtrees of evalTree (if it is split), and then", "subsequent trace operation will yield nan as the returned probability. time : float,", "wrtSlice1 = _slct.list_to_slice(wrtFilter1) else: wrtSlice1 = None if wrtFilter2 is not None: assert(wrtBlockSize1", "rho))[0,i,0] * scaleVals[i] # vp = squeeze( dot( E, dot(Gs, rho)), axis=(0,2) )", "-HSMALL: _warnings.warn(\"Scaled hProd small in order to keep prod managable.\") elif _np.count_nonzero(hProdCache[i]) and", "as a 1 x M x M array, where M is the number", "/ blkSize1)) nBlks2 = int(_np.ceil(self.Np / blkSize2)) # num blocks required to achieve", "gather axis 1 of mxToFill[felInds], dim=(ks,M,M) _mpit.gather_slices(blocks1, blk1Owners, mxToFill, [felInds], 1, mySubComm, gatherMemLimit)", "if (wrtSlice1 == wrtSlice2) else \\ self._compute_dproduct_cache(evalSubTree, prodCache, scaleCache, mySubComm, wrtSlice2) dGs1 =", "sequence dGs = evalTree.final_view(dProdCache, axis=0) #shape == ( len(circuit_list), nDerivCols, dim, dim ),", "evalTree : EvalTree given by a prior call to bulk_evaltree. Specifies the operation", "hprobs), evalTree, slice(None), slice(None), calc_and_fill) hProdCache = hGs = dProdCache2 = dGs2 =", "objects, respectively. Must be *ordered* dictionaries to specify a well-defined column ordering when", "dProdCache1.shape[1] nDerivCols2 = dProdCache2.shape[1] assert(wrtSlice1 is None or _slct.length(wrtSlice1) == nDerivCols1) assert(wrtSlice2 is", "above, and deriv[i,j] holds the derivative of the (i % G^2)-th entry of", "- 1)] = ident # product of no gates #Also Cache gate jacobians", "because there's no good way to reconstruct the # *non-final* parent-tree elements from", "+ \" than hessian elements(%d)!\" % (self.Np**2) + \" [blkSize = {%.1f,%.1f}, nBlks={%d,%d}]\"", "selected gate-set parameters (by wrtFilter1 and wrtFilter2). evalTree : EvalTree given by a", "_np.swapaxes(_np.swapaxes(dGs2, 0, 3) * scaleVals, 0, 3) # may overflow or get nans", "scaleCache = None #Fill cache info prodCache, scaleCache = self._compute_product_cache(evalSubTree, mySubComm) #use cached", "return _np.rollaxis(flattened_d2prod, 0, 3).reshape((vec_kl_size, vec_ij_size, dim, dim)) # axes = (model_parameter1, model_parameter2, model_element_row,", "in return list (now have G,dG => product, dprod_dOps) # prod, dprod_dOps =", "+= _np.log(nL) + _np.log(nR) #print \"bulk_product DEBUG: %d rescalings out of %d products\"", "reduce amount of intermediate memory required. profiler : Profiler, optional A profiler object", "0, cpus my_results = self._compute_dproduct_cache( evalTree, prodCache, scaleCache, None, myDerivColSlice, profiler) # pass", "[felInds], 1, mySubComm, gatherMemLimit) if deriv1MxToFill is not None: _mpit.gather_slices(blocks1, blk1Owners, deriv1MxToFill, [felInds],", "# mem += cache_size * num_params**2 * dim * dim # hproduct cache", "respect to the # gate's parameters and fill appropriate columns of flattened_dprod. #gate", "mxToFill and spam labels. evalTree : EvalTree given by a prior call to", "rholabel, elabel = spamTuple # can't deal w/\"custom\" spam label... rho, E =", "a # warning -- note that we *cannot* make use of a tree", "row_i = A[i,0] * B[row1] ) = A tensor B^T * vec( E(0,1)", "comm, wrtSlice1, wrtSlice2) #use cached data to construct return values old_err = _np.seterr(over='ignore')", "flat=False, wrtFilter=None): \"\"\" Compute the derivative of a specified sequence of operation labels.", "= _np.dot(_np.kron(xv, _np.transpose(prods[(l + 1, N - 1)])), dop_dopLabel2[opLabel2]) # above: (nDerivCols1,dim**2,dim**2) *", "else \\ self._compute_dproduct_cache(evalSubTree, prodCache, scaleCache, mySubComm, wrtSlice2) dGs1 = evalSubTree.final_view(dProdCache1, axis=0) dGs2 =", "check=False, comm=None): \"\"\" Compute the outcome probabilities for an entire tree of operation", "cache_size * nspam * wrtLen1 * wrtLen2 # hprobs & dprobs12 results mem", "to the *simplified* operation sequences found in an evaluation tree, `evalTree`. An initial", "None) \\ else _slct.length(wrtSlice) deriv_shape = (nDerivCols, dim, dim) cacheSize = len(evalTree) #", "is not None: _fas(deriv1MxToFill, [fInds, pslc1], self._dprobs_from_rhoE( spamTuple, rho, E, Gs[gInds], dGs1[gInds], scaleVals[gInds],", "two arguments), and in general only a specified slice of the values for", "(wrtFilter2 is None) else len(wrtFilter2) flattened_d2prod = _np.zeros((dim**2, num_deriv_cols1, num_deriv_cols2), 'd') # For", "products, their gradients, and their Hessians. PSMALL = 1e-100 DSMALL = 1e-100 HSMALL", "axis=0) #shape == ( len(circuit_list), nDerivCols, dim, dim ), # dGs[i] is dprod_dOps", "evalTree.final_view(hProdCache, axis=0) #shape == ( len(circuit_list), nDerivCols, nDerivCols, dim, dim ) if not", "about) revOpLabelList = tuple(reversed(tuple(circuit))) N = len(revOpLabelList) # length of operation sequence #", "results subtreeElementIndices = [t.final_element_indices(evalTree) for t in subtrees] _mpit.gather_indices(subtreeElementIndices, subTreeOwners, mxToFill, [], 0,", "X ) # if vec(.) stacks columns # vec( A * E(0,1) *", "separate from Model to allow for additional model classes (e.g. ones which use", "already sized/filtered) ------------------- assert(dGs.shape[1] == nDerivCols), \"dGs must be pre-filtered!\" #Compute d(probability)/dOps and", "computes a 2-tuple: (hessian_col, d12_col), where d12_col is a column of the matrix", "profiler) dGs = evalSubTree.final_view(dProdCache, axis=0) #( nCircuits, nDerivCols, dim, dim ) profiler.add_time(\"bulk_fill_dprobs: compute_dproduct_cache\",", "by: d12[iSpamLabel,iOpStr,p1,p2] = dP/d(p1)*dP/d(p2) where P is is the probability generated by the", "dprobs1 = dprobs2 = None hprobs = _np.zeros((nElements, _slct.length(wrtSlice1), _slct.length(wrtSlice2)), 'd') #prMxToFill =", "b/c spam terms only compute one triangle of hessian # Note: d2pr_d2rhos and", "POVM effect used to compute the probability. circuit : Circuit or tuple A", "= _mpit.slice_up_range(self.Np, nBlks2) #distribute derivative computation across blocks myBlk1Indices, blk1Owners, blk1Comm = \\", "cols = deriv cols, rows = flattened all else dGs1 = _np.swapaxes(_np.swapaxes(dGs1, 0,", "bool, optional when set to True, additionally return the probabilities and their derivatives", "dGs is already sized/filtered) ------------------- assert(dGs.shape[1] == nDerivCols), \"dGs must be pre-filtered!\" #Compute", "spam label... rho, E = self._rhoE_from_spamTuple(spamTuple) rhoVec = self.sos.get_prep(rholabel) # distinct from rho,E", "# special case of empty label == no gate hProdCache[i] = _np.zeros(hessn_shape) elif", "the 2nd derivatives of the probabilities generated by a each gate sequence given", "total_exp = 0.0 #for i,lOp in enumerate(gateLabelList): # G = _np.dot(G,self[lOp]) # product", "- S,M == as above, and hessians[i,j,k] holds the derivative of the (i", "in return list # d2pr_dOps2[i,j,k] = sum_l,m E[0,l] hGs[i,j,k,l,m] rho[m,0] # d2pr_dOps2[i,j,k] =", "rho[l,0] # dp_dEs[i,J0+J] = sum_j dEP[j,J] dot(Gs, rho)[i,j] # dp_dEs[i,J0+J] = sum_j dot(Gs,", "in the derivative dimension. This argument is used internally for distributing calculations across", "# # p = _mt.trace( _np.dot(self.SPAMs[spamLabel],G) ) * exp(total_exp) # probability # print", "= self.sos.get_operation[opLabel] UNNEEDED (I think) _fas(flattened_dprod, [None, gpindices], gate.deriv_wrt_params(op_wrtFilter)) # (dim**2, nParams in", "hprobs & dprobs12 results mem += cache_size * nspam * (wrtLen1 + wrtLen2)", "not None, an MPI communicator for distributing the computation across multiple processors. Distribution", "p = _np.clip(p, clipTo[0], clipTo[1]) #Derivs wrt SPAM derivWrtAnyRhovec = scale * _np.dot(E,", "for given arguments \"\"\" tm = _time.time() old_err = _np.seterr(over='ignore') rho, E =", "_fas(dpr_dEs, [0, EVec.gpindices], _np.dot(derivWrtAnyEvec, EVec.deriv_wrt_params())) _np.seterr(**old_err) if returnPr: return dpr_drhos + dpr_dEs +", "and bulk_hproduct. Returns ------- block_generator A generator which, when iterated, yields the 3-tuple", "by giving hproduct cache computation\" \" *fewer* processors and *smaller* (sub-)tree\" \" (e.g.", "opLabel in revOpLabelList: G = _np.dot(G, self.sos.get_operation(opLabel).todense()) leftProds.append(G) rightProdsT = [] G =", "_fas(dp_dEs, [None, E_gpindices], _np.dot(dp_dAnyE, EVec.deriv_wrt_params(E_wrtFilter))) sub_vdp = dp_drhos + dp_dEs + dp_dOps return", "0 if self.sos.get_effect(elabel).has_nonzero_hessian(): dp_dAnyE = _np.dot(Gs, rho).squeeze(2) * scaleVals[:, None] # overflow OK", "= slice(0, nDerivCols) if (wrtSlice is None) else wrtSlice _, myDerivColSlice, _, mySubComm", "dpr_drhos + dpr_dEs + dpr_dOps d2pr_drhos = _np.zeros((1, self.Np, self.Np)) _fas(d2pr_drhos, [0, None,", "E = self._rhoE_from_spamTuple(spamTuple) if prMxToFill is not None: _fas(prMxToFill, [fInds], self._probs_from_rhoE( rho, E,", "_np.rollaxis(flattened_d2prod, 0, 3).reshape((vec_kl_size, vec_ij_size, dim, dim)) # axes = (model_parameter1, model_parameter2, model_element_row, model_element_col)", "axes = (gate_ij, prod_row, prod_col) return _np.swapaxes(flattened_dprod, 0, 1).reshape((num_deriv_cols, dim, dim)) def hproduct(self,", "for l, opLabel2 in enumerate(revOpLabelList): inds2 = gpindices1[opLabel2] #nDerivCols2 = dop_dopLabel2[opLabel2].shape[1] # FUTURE:", "_np.dot(dprod_dOps[i], rho))) #Derivs wrt SPAM if returnDeriv: # same as in dpr(...) dpr_drhos", "# may overflow or get nans (invalid), but ok hGs = _np.swapaxes(_np.swapaxes(hGs, 0,", "B^T * vec( X ) # if vec(.) stacks columns # vec( A", "in order to keep prod managable.\") elif _np.count_nonzero(dProdCache[i]) and dProdCache[i].max() < DSMALL and", "= ident for (j, opLabel2) in enumerate(revOpLabelList[i:], start=i): # loop over \"ending\" gate", "about) revOpLabelList = tuple(reversed(tuple(circuit))) # prod = G1 * G2 * .... *", "wrtFilter1=wrtIndices1, wrtFilter2=wrtIndices2) hProdCache[i] = hoperation / _np.exp(scaleCache[i]) #evaluate operation sequences using tree (skip", "(subsets) of the parameters being differentiated with respect to (see wrtBlockSize). wrtFilter1, wrtFilter2", "for each given (i,j) # noqa # vec( dprod/d(opLabel)_ij ) = sum_{L s.t.", "= self.Np if (wrtFilter2 is None) else len(wrtFilter2) flattened_d2prod = _np.zeros((dim**2, num_deriv_cols1, num_deriv_cols2),", "in uniqueOpLabels: used_operations[l] = self.sos.get_operation(l) gate_wrtFilters1[l], gpindices1[l] = self._process_wrtFilter(wrtFilter1, used_operations[l]) gate_wrtFilters2[l], gpindices2[l] =", "the k-th then the j-th model parameter. derivative : numpy array only returned", "there's no good way to reconstruct the parent tree's *non-final* elements from those", "to think about) revOpLabelList = tuple(reversed(tuple(circuit))) N = len(revOpLabelList) # length of operation", "if self.evotype == \"statevec\": raise NotImplementedError(\"Unitary evolution not fully supported yet!\") rholabel, elabel", "scaleCache = None #Fill product cache info (not requiring row or column distribution)", "parameters. if self.sos.get_prep(rholabel).has_nonzero_hessian(): dp_dAnyRho = _np.dot(E, Gs).squeeze(0) * scaleVals[:, None] # overflow OK", "needed) y = _np.dot(_np.kron(xv, _np.transpose(prods[(l + 1, N - 1)])), dop_dopLabel2[opLabel2]) # above:", "over col-distribution (Deriv2) #note: gathering axis 2 of hProdCache[:,myDeriv1ColSlice], # dim=(cacheSize,nDerivCols1,nDerivCols2,dim,dim) else: #compute", "(for debugging) master_circuit_list = evalTree.generate_circuit_list(permute=False) # raw operation sequences for spamTuple, (fInds, gInds)", "array, where: - M == length of the vectorized model (number of model", "to: # - alter product, dproduct, etc. to allow for *complex* derivatives, since", "= slice(relevant_gpindices[0], relevant_gpindices[0] + 1) elif len(relevant_gpindices) == 0: #Don't return a length-0", "0, 1).reshape((nDerivCols1, nCircuits * dim**2)), 0, 1) # cols = deriv cols, rows", "as _collections from ..tools import mpitools as _mpit from ..tools import slicetools as", "prodCache[i] = gate / nG scaleCache[i] = _np.log(nG) #evaluate operation sequences using tree", "dop_dopLabel2[opLabel2]) # above: (nDerivCols1,dim**2,dim**2) * (dim**2,nDerivCols2) = (nDerivCols1,dim**2,nDerivCols2) flattened_d2prod[:, inds1, inds2] += _np.swapaxes(y,", "%d deriv cols\" % nDerivCols) if comm is not None and comm.Get_size() >", "> 1: _warnings.warn(\"Too many processors to make use of in \" \" _compute_hproduct_cache.\")", "gatherMemLimit) if deriv1MxToFill is not None: _mpit.gather_slices(blocks1, blk1Owners, deriv1MxToFill, [felInds], 1, mySubComm, gatherMemLimit)", "= B^T tensor A * vec( E(0,1) ) # In general: vec( A", "if flat: dGs = _np.swapaxes(_np.swapaxes(dGs, 0, 1).reshape( (nDerivCols, nCircuits * dim**2)), 0, 1)", "SLOW! dProdCache[i] /= _np.exp(scale) if dProdCache[i].max() < DSMALL and dProdCache[i].min() > -DSMALL: _warnings.warn(\"Scaled", "G = _np.identity(self.dim) for lOp in circuit: G = _np.dot(self.sos.get_operation(lOp).todense(), G) # LEXICOGRAPHICAL", "it's + or - inf anyway... d2pr_dOps2[_np.isnan(d2pr_dOps2)] = 0 # SPAM DERIVS (assume", "last_wrtSlice1 = wrtSlice1 if (wrtSlice1 == wrtSlice2): dProdCache2 = dProdCache1; dGs2 = dGs1", "_np.kron(_np.transpose(prods[(l + 1, m - 1)]), prods[(m + 1, N - 1)]) #", "= _time.time() # combine iLeft + iRight => i # LEXICOGRAPHICAL VS MATRIX", "the columns of the operation sequences. Parameters ---------- spam_label_rows : dictionary a dictionary", "denote the elementary matrix where all entries are zero except the (i,j) entry", "self._dprobs_from_rhoE( spamTuple, rho, E, Gs[gInds], dGs2[gInds], scaleVals[gInds], wrtSlice2), add=sumInto) _fas(mxToFill, [fInds, pslc1, pslc2],", "derivatives are wrt the 2nd set of gate parameters if dGs1 is dGs2", "wrtBlockSize2 : int or float, optional The maximum number of 1st (row) and", "self._rhoE_from_spamTuple(spamTuple) if prMxToFill is not None: _fas(prMxToFill, [fInds], self._probs_from_rhoE(rho, E, Gs[gInds], scaleVals[gInds]), add=sumInto)", "iterated, yields the 3-tuple `(rowSlice, colSlice, hprobs)` or `(rowSlice, colSlice, dprobs12)` (the latter", "are more cpus than derivative columns.\") # Use comm to distribute columns allDerivColSlice", "deriv2MxToFill, [felInds], 1, blk1Comm, gatherMemLimit) #Note: deriv2MxToFill gets computed on every inner loop", "scaleValues : numpy array Only returned when bScale == True. A length-S array", "not a set) # since all scaled gates start with norm <= 1,", "E, dot(Gs, rho))[0,i,0] * scaleVals[i] # vp = squeeze( dot( E, dot(Gs, rho)),", "by a prior call to bulk_evaltree. Specifies the *simplified* gate strings to compute", "is SLOW! dProdCache[i] /= _np.exp(scale) if dProdCache[i].max() < DSMALL and dProdCache[i].min() > -DSMALL:", "scaleVals, 0, 3) # may overflow or get nans (invalid), but ok hGs", "and wrtFilter2 is None) # cannot specify both wrtFilter and blkSize nBlks1 =", "computations: dpr/dx -> d|pr|^2/dx = d(pr*pr.C)/dx = dpr/dx*pr.C + pr*dpr/dx.C # = 2", "(iRight,iLeft,iFinal) = tup implies circuit[i] = circuit[iLeft] + circuit[iRight], but we want: #", "def _hprobs_from_rhoE(self, spamTuple, rho, E, Gs, dGs1, dGs2, hGs, scaleVals, wrtSlice1=None, wrtSlice2=None): if", "wrtSlice is None else _slct.length(wrtSlice) # GATE DERIVS (assume dGs is already sized/filtered)", "#( nCircuits, len(wrtFilter1), len(wrtFilter2), dim, dim ) #Compute all requested derivative columns at", "False, False, clipTo) for circuit in circuit_list], axis=0) if _nla.norm(hprMxToFill[fInds][0] - check_vhp[0]) >", "the *simplified* gate strings to compute the bulk operation on. prMxToFill : numpy", "is None) else _slct.length(wrtFilter1) nDerivCols2 = self.Np if (wrtFilter2 is None) else _slct.length(wrtFilter2)", "Compute and fill result quantities for given arguments \"\"\" tm = _time.time() old_err", "iteration before computing caches scaleVals = Gs = dGs1 = dGs2 = hGs", "derivWrtAnyRhovec = scale * _np.dot(E, prod) _fas(dpr_drhos, [0, self.sos.get_prep(rholabel).gpindices], _np.dot(derivWrtAnyRhovec, rhoVec.deriv_wrt_params())) # may", "return _np.concatenate(all_results, axis=1) # TODO: remove this concat w/better gather? # ------------------------------------------------------------------ tSerialStart", "Circuits or tuples of operation labels which specify the operation sequences to create", "given a split tree (since there's no good way to reconstruct the parent", "j-th model parameters. * if flat == True, an array of shape S*N", "wrtSlice1 = _slct.list_to_slice(wrtFilter1) if (wrtFilter1 is not None) else None wrtSlice2 = _slct.list_to_slice(wrtFilter2)", "the first (row) and second (col) derivative operations, respectively. Each element is an", "gates' parameters and fill # add the result to the appropriate block of", "all gate elements are at most # linear in the parameters assert(opLabel1 ==", "nans (invalid), but ok hGs = _np.swapaxes(_np.swapaxes(hGs, 0, 4) * scaleVals, 0, 4)", "slightly faster, but with a chance that the product will overflow and the", "available processors if it isn't specified if wrtFilter is None: blkSize = wrtBlockSize", "= _np.concatenate( [self.dpr(spamTuple, circuit, False, clipTo) for circuit in circuit_list], axis=0) if _nla.norm(dprMxToFill[fInds]", "of many operation sequences at once. Parameters ---------- evalTree : EvalTree given by", "self.dim), 'd') def calc_and_fill_p(spamTuple, fInds, gInds, pslc1, pslc2, sumInto): \"\"\" Compute and fill", "simplified_op_server, paramvec): \"\"\" Construct a new MatrixForwardSimulator object. Parameters ---------- dim : int", "get nans (invalid), but ok dGs = _np.swapaxes(_np.swapaxes(dGs, 0, 3) * scaleVals, 0,", "S*N x M where: - N == the number of entries in a", "0 ) #dGs = clip(dGs,-1e300,1e300) _np.seterr(**old_err) if flat: dGs = _np.swapaxes(_np.swapaxes(dGs, 0, 1).reshape(", "array of floating-point probabilities, corresponding to the elements of `elabels`. \"\"\" assert(time is", "calculator class\"\"\" #*************************************************************************************************** # Copyright 2015, 2019 National Technology & Engineering Solutions of", "G / nG); scale_exp += _np.log(nG) # LEXICOGRAPHICAL VS MATRIX ORDER else: G", "nDerivCols)) # may overflow, but OK (deriv w.r.t any of self.effects - independent", "dpr, p else: return ret, dpr else: if returnPr: return ret, p else:", "be computed properly if wrtSlice1 is not None and wrtSlice1.start is not None:", "renormed to keep all the products within decent # bounds #assert( len( (_np.isnan(hGs)).nonzero()[0]", "gpindices2], gate.hessian_wrt_params(op_wrtFilter1, op_wrtFilter2)) if flat: return flattened_hprod else: return _np.transpose(flattened_hprod, (1, 2, 0)).reshape(", "dGs1[_np.isnan(dGs1)] = 0 # convert nans to zero, as these occur b/c an", "if (wrtFilter is None) else len(wrtFilter) flattened_dprod = _np.zeros((dim**2, num_deriv_cols), 'd') # For", "_fas(d2pr_d2Es, [0, self.sos.get_effect(elabel).gpindices, self.sos.get_effect(elabel).gpindices], _np.tensordot(derivWrtAnyEvec, self.sos.get_effect(elabel).hessian_wrt_params(), (1, 0))) # _np.einsum('ij,jkl->ikl',derivWrtAnyEvec,self.sos.get_effect(elabel).hessian_wrt_params()) else: d2pr_d2Es =", "== 0: continue for l, opLabel2 in enumerate(revOpLabelList): inds2 = gpindices1[opLabel2] #nDerivCols2 =", "set of subcalls to computation functions. Parameters ---------- subcalls : list of strs", "comm_blkSize if (blkSize is None) \\ else min(comm_blkSize, blkSize) # override with smaller", "requested derivative columns at once self._fill_result_tuple((prMxToFill, deriv1MxToFill, deriv2MxToFill, mxToFill), evalSubTree, slice(None), slice(None), calc_and_fill)", "\"\"\" This function takes a \"calc-and-fill\" function, which computes and *fills* (i.e. doesn't", "#( nCircuits, nDerivColsX, dim, dim ) hProdCache = self._compute_hproduct_cache(evalSubTree, prodCache, dProdCache1, dProdCache2, scaleCache,", "strings (may be less than or greater than `cacheSize`) the tree will hold.", "'Imyinst_0') clipTo : 2-tuple (min,max) to clip returned probability to if not None.", "# indices into original wrtFilter'd indices gpindices = obj.gpindices_as_array() for ii, i in", "of the (i % G^2)-th entry of the (i / G^2)-th flattened operation", "dGs = None # free mem #gather results tm = _time.time() _mpit.gather_slices(blocks, blkOwners,", "nans (invalid), but ok dGs2 = _np.swapaxes(_np.swapaxes(dGs2, 0, 3) * scaleVals, 0, 3)", "tm) profiler.mem_check(\"bulk_fill_dprobs: post gather subtrees\") if clipTo is not None and prMxToFill is", "\"statevec\": ps = _np.real(_np.abs(_np.dot(Es, _np.dot(G, rho)))**2) else: # evotype == \"densitymx\" ps =", "numpy array, where M is the number of model parameters. Parameters ---------- spamTuple", "_np.concatenate( [self.dpr(spamTuple, circuit, False, clipTo) for circuit in circuit_list], axis=0) if _nla.norm(dprMxToFill[fInds] -", "= [] for iSubTree in mySubTreeIndices: evalSubTree = subtrees[iSubTree] felInds = evalSubTree.final_element_indices(evalTree) #Free", "of a multiple \"outcomes\" (spam-tuples) for a single operation sequence. The spam tuples", "_mpit.distribute_slice(allDerivColSlice, comm) #print(\"MPI: _compute_dproduct_cache over %d cols (%s) (rank %d computing %s)\" \\", "B^T * vec( E(0,1) ) # In general: vec( A * X *", "one is able to compute reduce results from a single column of the", "1e-6: _warnings.warn(\"norm(vp-check_vp) = %g - %g = %g\" % (_nla.norm(prMxToFill[fInds]), _nla.norm(check_vp), _nla.norm(prMxToFill[fInds] -", "# wrt gates return ret def _check(self, evalTree, prMxToFill=None, dprMxToFill=None, hprMxToFill=None, clipTo=None): #", "across multiple processors. Returns ------- derivs : numpy array * if flat ==", "prMxToFill=None, clipTo=None, check=False, comm=None, wrtFilter=None, wrtBlockSize=None, profiler=None, gatherMemLimit=None): \"\"\" Compute the outcome probability-derivatives", "then sub-trees (if available and necessary) if comm.Get_size() > nDerivCols: #If there are", "generator that computes the 2nd derivatives of the probabilities generated by a each", "allocation/deallocation). #if comm is None or comm.Get_rank() == 0: # import objgraph #", "but OK _fas(d2pr_dErhos, [0, EVec.gpindices, self.sos.get_prep(rholabel).gpindices], _np.dot(_np.transpose(EVec.deriv_wrt_params()), derivWrtAnyEvec)) #Note: these 2nd derivatives are", "dprMxToFill is not None: check_vdp = _np.concatenate( [self.dpr(spamTuple, circuit, False, clipTo) for circuit", "= _np.seterr(over='ignore') G, scale = self.product(circuit, True) if self.evotype == \"statevec\": ps =", "over row-distribution (Deriv1) #note: gathering axis 1 of hProdCache, # dim=(cacheSize,nDerivCols1,nDerivCols2,dim,dim) return hProdCache", "simulate time-dependent circuits\" rho, Es = self._rhoEs_from_spamTuples(rholabel, elabels) #shapes: rho = (N,1), Es", "(Deriv2) #note: gathering axis 2 of hProdCache[:,myDeriv1ColSlice], # dim=(cacheSize,nDerivCols1,nDerivCols2,dim,dim) else: #compute \"Deriv1\" row-derivatives", "or zero-operation labels wrtIndices1 = _slct.indices(wrtSlice1) if (wrtSlice1 is not None) else None", "# convert nans to zero, as these occur b/c an inf scaleVal is", "a \"calc-and-fill\" function, which computes and *fills* (i.e. doesn't return to save copying)", "G x G, where: - S == the number of operation sequences -", "'d') # For each pair of gates in the string, compute the hessian", "blk\") dProdCache = dGs = None # free mem #gather results tm =", "gatelabel2, M < L} # noqa # [ G1 ... G(M-1) dG(M)/dkl G(M+1)", "1, blk1Comm, gatherMemLimit) #Note: deriv2MxToFill gets computed on every inner loop completion #", "scaleVals = self._scaleExp(evalSubTree.final_view(scaleCache)) Gs = evalSubTree.final_view(prodCache, axis=0) # ( nCircuits, dim, dim )", "= sum E_k prod_kl rho_l # d2pr/d(opLabel1)_mn d(opLabel2)_ij = sum E_k [dprod/d(opLabel1)_mn d(opLabel2)_ij]_kl", "spam_label_rows, - S is the number of operation sequences (i.e. evalTree.num_final_strings()), - B", "subtrees. It can often be useful to have fewer processor groups then subtrees", "None, EVec.gpindices], _np.dot(derivWrtAnyEvec, EVec.deriv_wrt_params())) d2pr_dErhos = _np.zeros((1, self.Np, self.Np)) derivWrtAnyEvec = scale *", "# gate (so we only need to compute this gate hessian once). But", "and/or products for the i-th operation sequence. \"\"\" nCircuits = evalTree.num_final_strings() nDerivCols =", "= self.doperation(opLabel, wrtFilter=wrtIndices) dProdCache[i] = doperation / _np.exp(scaleCache[i]) #profiler.print_mem(\"DEBUGMEM: POINT1\"); profiler.comm.barrier() #evaluate operation", "_get_filter_info(self, wrtSlices): # \"\"\" # Returns a \"filter\" object containing info about the", "hprobs)` or `(rowSlice, colSlice, dprobs12)` (the latter if `bReturnDProbs12 == True`). `rowSlice` and", "= self._rhoE_from_spamTuple(spamTuple) rhoVec = self.sos.get_prep(rholabel) # distinct from rho,E b/c rho,E are EVec", "generated by a each gate sequence given by evalTree column-by-column. This routine can", "#Also Cache gate jacobians (still relatively little mem required) dop_dopLabel1 = { opLabel:", "noqa # vec( dprod/d(opLabel)_ij ) = sum_{L s.t. G(L) == oplabel} [ (G1", "len( (_np.isnan(dGs)).nonzero()[0] ) == 0 ) #assert( len( (_np.isinf(dGs)).nonzero()[0] ) == 0 )", "None # keep last dProdCache1 for wrtSlice1, wrtSlice2 in wrtSlicesList: if wrtSlice1 !=", "in loc_e_slices] # tmp_offsets = [ sum(tmp_num_params[0:i]) for i in range(len(self.effects)+1) ] #", "\"\"\" # PrepEffectFilter = _collections.namedtuple( # 'PrepEffectFilter', 'rho_local_slices rho_global_slices ' + # 'e_local_slices", "respect to the j-th model parameter. \"\"\" # LEXICOGRAPHICAL VS MATRIX ORDER #", "profiler.mem_check( \"bulk_fill_dprobs: post compute dproduct blk (expect \" \" +%.2fGB, shape=%s)\" % (dProdCache.nbytes", "probabilities for an entire tree of operation sequences. This routine fills a 1D", "products for the i-th operation sequence. \"\"\" dim = self.dim nDerivCols1 = self.Np", "_scaleExp(self, scaleExps): old_err = _np.seterr(over='ignore') scaleVals = _np.exp(scaleExps) # may overflow, but OK", "E_k [dprod/d(opLabel)_ij]_kl rho_l # dpr/d(rho)_i = sum E_k prod_ki # dpr/d(E)_i = sum", "dim, dim ), # hGs[i] is hprod_dGates for ith string if not bScale:", "array where E is the total number of computed elements (i.e. evalTree.num_final_elements()) and", "#distribute derivative computation across blocks myBlkIndices, blkOwners, blkComm = \\ _mpit.distribute_indices(list(range(nBlks)), mySubComm) if", "H.max() < PSMALL and H.min() > -PSMALL: nG = max(_nla.norm(G), _np.exp(-scale_exp)) G =", "axes = (gate_ij1, gateij2, prod_row, prod_col) def dproduct(self, circuit, flat=False, wrtFilter=None): \"\"\" Compute", "needs to distribute itself among the available processors. Returns ------- MatrixEvalTree \"\"\" evTree", "1st (row) and 2nd (col) derivatives to compute *products* for simultaneously. None means", "generator computes a 2-tuple: (hessian_col, d12_col), where d12_col is a column of the", "parameters being differentiated with respect to when the *second* derivative is taken. If", "= _np.swapaxes(_np.swapaxes(dGs2, 0, 3) * scaleVals, 0, 3) # may overflow or get", "both wrtFilter and blkSize nBlks1 = int(_np.ceil(self.Np / blkSize1)) nBlks2 = int(_np.ceil(self.Np /", "the \"element\" indices in the final # filled quantity combining both spam and", "<= 1, products should all have norm <= 1 assert(len(nanOrInfCacheIndices) == 0) return", "mem += cache_size * num_params**2 * dim * dim # hproduct cache #", "dictates how large all the storage arrays are. np1, np2 = num_param1_groups, num_param2_groups", "preps, effects : OrderedDict Ordered dictionaries of LinearOperator, SPAMVec, and SPAMVec objects, respectively.", "above matrices, so that # each column corresponds to a (opLabel,i,j) tuple and", "# columns of flattened_dprod. uniqueOpLabels = sorted(list(set(revOpLabelList))) for opLabel in uniqueOpLabels: gate =", "used internally for conditional scaling required # to control bulk products, their gradients,", "evalTree, prodCache, dProdCache1, dProdCache2, scaleCache, comm=None, wrtSlice1=None, wrtSlice2=None): \"\"\" Computes a tree of", "# d2pr_dEs[i,j,J0+J] = sum_kl dEPT[J,k] dGs[i,j,k,l] rho[l,0] # d2pr_dEs[i,j,J0+J] = sum_k dEP[k,J] dot(dGs,", "vals # #elif fnName == \"bulk_hproduct\": # mem += cache_size * num_params**2 *", "or comm.Get_rank() == 0: # import objgraph # objgraph.show_growth(limit=50) #get distribution across subtrees", "(G x G operation matrices) and hessians[i,j,k,l,m] holds the derivative of the (l,m)-th", "with a mapping of final elements (i.e. probabilities) to gate-only sequence and prep/effect", "#Note: num_final_strs is irrelevant here b/c cachesize is always >= num_final_strs # and", "= self._get_filter_info(wrtSlices2) # GATE DERIVS (assume hGs is already sized/filtered) ------------------- assert(hGs.shape[1] ==", "= EVec.deriv_wrt_params(E_wrtFilter2) _fas(d2pr_dEs1, [None, None, E_gpindices2], _np.dot(dp_dAnyE, devec)) # get d2pr_dEs where gate", "performed. Returns ------- prods : numpy array Array of shape S x G", "S,M == as above, and hessians[i,j,k] holds the derivative of the (i %", "computed for each block of derivative columns if prMxToFill is not None: self._fill_result_tuple((prMxToFill,),", "bulk_hproduct. Returns ------- block_generator A generator which, when iterated, yields the 3-tuple `(rowSlice,", "profiler.add_count(\"bulk_fill_dprobs count\") profiler.mem_check(\"bulk_fill_dprobs: end\") def bulk_fill_hprobs(self, mxToFill, evalTree, prMxToFill=None, deriv1MxToFill=None, deriv2MxToFill=None, clipTo=None, check=False,", "% (blkSize1, blkSize2, nBlks1, nBlks2)) # pragma: no cover # noqa for iBlk1", "myDeriv1ColSlice], dProdCache2[:, myDeriv2ColSlice], scaleCache, None, myHessianSlice1, myHessianSlice2) # pass None as comm, *not*", "the derivative of a many operation sequences at once. Parameters ---------- evalTree :", "for i in range(self.Np): dpr_dOps[0, i] = float(_np.dot(E, _np.dot(dprod_dOps[i], rho))) if returnPr: p", "None, self.sos.get_prep(rholabel).gpindices], _np.dot(_np.dot(E, dprod_dOps), rhoVec.deriv_wrt_params())[0]) # (= [0,:,:]) d2pr_dEs = _np.zeros((1, self.Np, self.Np))", "mem += cache_size # scale cache mem += cache_size # scale vals elif", "# len(circuit_list) wrtSlice1 = _slct.list_to_slice(wrtFilter1) if (wrtFilter1 is not None) else None wrtSlice2", "*not* mySubComm, since we can't do any # further parallelization tm = _time.time()", "xv = _np.swapaxes(xv, 1, 2) y = _np.dot(_np.kron(prods[(0, l - 1)], xv), dop_dopLabel2[opLabel2])", "given by a prior call to bulk_evaltree. Specifies the operation sequences to compute", "post compute dproduct blk (expect \" \" +%.2fGB, shape=%s)\" % (dProdCache.nbytes / (1024.0**3),", "well-defined column ordering when taking derivatives. paramvec : ndarray The parameter vector of", "prodCache[iRight] dL1, dR1 = dProdCache1[iLeft], dProdCache1[iRight] dL2, dR2 = dProdCache2[iLeft], dProdCache2[iRight] hL, hR", "#nDerivCols2 = dop_dopLabel2[opLabel2].shape[1] # FUTURE: we could add logic that accounts for the", "\"\"\" # Returns a \"filter\" object containing info about the mapping # of", "has shape (N,1) rho = self.sos.get_prep(rholabel).todense()[:, None] E = _np.conjugate(_np.transpose(self.sos.get_effect(elabel).todense() [:, None])) #", "noqa # ( unvec( G(L+1) ... G(M-1) tensor (G(M+1) ... GN)^T vec( dG(M)/dkl", "# Returns a \"filter\" object containing info about the mapping # of prep", "quantities for given arguments \"\"\" old_err = _np.seterr(over='ignore') rho, E = self._rhoE_from_spamTuple(spamTuple) if", "circuit : Circuit or tuple of operation labels The sequence of operation labels.", "scaleCache, mySubComm, wrtSlice1, wrtSlice2) hGs = evalSubTree.final_view(hProdCache, axis=0) #( nCircuits, len(wrtFilter1), len(wrtFilter2), dim,", "Cannot specify both wrtFilter and wrtBlockSize wrtSlice = _slct.list_to_slice(wrtFilter) else: wrtSlice = None", "= evalTree.num_final_strings() nDerivCols = self.Np if (wrtFilter is None) else _slct.length(wrtFilter) dim =", "MPI distribution mode for this calculator. \"\"\" return \"deriv\" def estimate_cache_size(self, nCircuits): \"\"\"", "opLabel) if flat: return flattened_dprod else: # axes = (gate_ij, prod_row, prod_col) return", "_np.dot(E, Gs).squeeze(0) * scaleVals[:, None] # overflow OK d2pr_d2rhos = _np.zeros((nCircuits, nDerivCols1, nDerivCols2))", "= EVec.deriv_wrt_params(E_wrtFilter1) _fas(d2pr_dErhos1, (None, E_gpindices1, rho_gpindices2), _np.swapaxes(_np.dot(_np.transpose(devec), dp_dAnyE), 0, 1)) # get d2pr_dEs", "_np.transpose(_np.dot(prod, rho)) # may overflow, but OK _fas(dpr_dEs, [0, EVec.gpindices], _np.dot(derivWrtAnyEvec, EVec.deriv_wrt_params())) dpr", "often be useful to have fewer processor groups then subtrees (even == 1)", "is not None: p = _np.clip(p, clipTo[0], clipTo[1]) #Derivs wrt SPAM derivWrtAnyRhovec =", "tensor (G(M+1) ... GN)^T vec( dG(M)/dkl ) ) )^T vec( dG(L)/dij ) ]", "# \"\"\" # Returns a \"filter\" object containing info about the mapping #", "sum jk dEPT[J,j] prod[i,j,k] drhoP[k,K] # d2pr_dErhos[i,J0+J,K0+K] = sum j dEPT[J,j] dot(prod,drhoP)[i,j,K] #", "in computations. \"\"\" super(MatrixForwardSimulator, self).__init__( dim, simplified_op_server, paramvec) if self.evotype not in (\"statevec\",", "dG(L)/dij ) ] # noqa # = [ sum_{L s.t. G(L) == oplabel}", "doesn't index numpy arrays # like length>1 lists do... ugh. relevant_gpindices = slice(relevant_gpindices[0],", "so gather prMxToFill[felInds] (axis=0) profiler.add_time(\"MPI IPC\", tm) profiler.mem_check(\"bulk_fill_dprobs: post gather subtrees\") if clipTo", "wrtFilter2 : list of ints, optional If not None, a list of integers", "Specifies the prep and POVM effect used to compute the probability. circuit :", "the subcalls to estimate memory usage for. cache_size : int The size of", "prods[(len(revOpLabelList), len(revOpLabelList) - 1)] = ident # product of no gates #Also Cache", "and fill # add the result to the appropriate block of flattened_d2prod. #NOTE:", "for l in uniqueOpLabels: used_operations[l] = self.sos.get_operation(l) gate_wrtFilters1[l], gpindices1[l] = self._process_wrtFilter(wrtFilter1, used_operations[l]) gate_wrtFilters2[l],", ": (rho_label, simplified_effect_label) Specifies the prep and POVM effect used to compute the", "(col) derivatives to compute *products* for simultaneously. None means compute all requested rows", "products (relatively little mem required) prods = {} ident = _np.identity(dim) for (i,", "return hProdCache ## END CACHE FUNCTIONS def default_distribute_method(self): \"\"\" Return the preferred MPI", "mySubComm) profiler.add_time(\"bulk_fill_dprobs: compute_product_cache\", tm) #use cached data to final values scaleVals = self._scaleExp(evalSubTree.final_view(scaleCache))", "if check: self._check(evalTree, prMxToFill, mxToFill, clipTo=clipTo) profiler.add_time(\"bulk_fill_dprobs: total\", tStart) profiler.add_count(\"bulk_fill_dprobs count\") profiler.mem_check(\"bulk_fill_dprobs: end\")", "that computes the 2nd derivatives of the probabilities generated by a each gate", "= gate.deriv_wrt_params(op_wrtFilter) for (i, gl) in enumerate(revOpLabelList): if gl != opLabel: continue #", "respect to in the first (row) and second (col) derivative operations, respectively. Each", "_np.dot(prod, rhoVec.deriv_wrt_params()) # may generate overflow, but OK _fas(d2pr_dErhos, [0, EVec.gpindices, self.sos.get_prep(rholabel).gpindices], _np.dot(_np.transpose(EVec.deriv_wrt_params()),", "with respect to the j-th model parameter. * if flat == True, an", "can't deal w/\"custom\" spam label... rho, E = self._rhoE_from_spamTuple(spamTuple) rhoVec = self.sos.get_prep(rholabel) #", "opsToVectorize2 we only compute d2(prod)/d(gl1)d(gl2) # and not d2(prod)/d(gl2)d(gl1) ... if m <", "mxToFill, evalTree, clipTo=None, check=False, comm=None): \"\"\" Compute the outcome probabilities for an entire", "_np.dot(G, rho)) * scale)**2) else: # evotype == \"densitymx\" # probability, with scaling", "paramvec) if self.evotype not in (\"statevec\", \"densitymx\"): raise ValueError((\"Evolution type %s is incompatbile", "tree (since there's no good way to reconstruct the parent tree's *non-final* elements", "more informative error? #elif fnName == \"bulk_product\": # mem += cache_size * dim", "tStart) profiler.add_count(\"bulk_fill_dprobs count\") profiler.mem_check(\"bulk_fill_dprobs: end\") def bulk_fill_hprobs(self, mxToFill, evalTree, prMxToFill=None, deriv1MxToFill=None, deriv2MxToFill=None, clipTo=None,", "= self._compute_hproduct_cache( evalSubTree, prodCache, dProdCache1, dProdCache2, scaleCache, blk2Comm, blk_wrtSlice1, blk_wrtSlice2) hGs = evalSubTree.final_view(hProdCache,", "pass None as comm, *not* mySubSubComm, since we can't do any further parallelization", "self.Np)) for i in range(self.Np): for j in range(self.Np): d2pr_dOps2[0, i, j] =", "= blocks[iBlk] dProdCache = self._compute_dproduct_cache(evalSubTree, prodCache, scaleCache, blkComm, block_wrtSlice, profiler) profiler.add_time(\"bulk_fill_dprobs: compute_dproduct_cache\", tm)", "dim)) def hproduct(self, circuit, flat=False, wrtFilter1=None, wrtFilter2=None): \"\"\" Compute the hessian of a", "dR), 0, 1) # dot(dS, T) + dot(S, dT) profiler.add_time(\"compute_dproduct_cache: dots\", tm) profiler.add_count(\"compute_dproduct_cache:", "raise NotImplementedError(\"Unitary evolution not fully supported yet!\") rholabel, elabel = spamTuple rhoVec =", "... G(L-1)) tensor (G(L+1) ... GN)^T ]] * vec( dG(L)/dij) ) # noqa", "cannot be split\" nElements = evalTree.num_final_elements() #Fill product cache info (not distributed) prodCache,", "functions. Parameters ---------- subcalls : list of strs A list of the names", "case set to zero since we can't tell whether it's + or -", "# to control bulk products, their gradients, and their Hessians. PSMALL = 1e-100", "# tensor (G(L+1) ... GN)^T vec( dG(L)/dij ) ] # noqa # +", "= evalTree.final_view(scaleCache) scaleVals = _np.exp(scaleExps) # may overflow, but OK if infs occur", "those two gates' parameters and fill # add the result to the appropriate", "= _np.zeros((1, self.Np)) derivWrtAnyRhovec = scale * _np.dot(E, prod) _fas(dpr_drhos, [0, self.sos.get_prep(rholabel).gpindices], _np.dot(derivWrtAnyRhovec,", "* scaleVals[:, None]) # may overflow, but OK # Get: dp_dEs[i, E_gpindices] =", "that the gates are at most linear in their parameters, this # isn't", "spam label (specified to it by the first two arguments), and in general", "def copy(self): \"\"\" Return a shallow copy of this MatrixForwardSimulator \"\"\" return MatrixForwardSimulator(self.dim,", "+= log(nG) # scale and keep track of exponent # # p =", "gatherMemLimit) #gather over col-distribution (Deriv2) #note: gathering axis 2 of hProdCache[:,myDeriv1ColSlice], # dim=(cacheSize,nDerivCols1,nDerivCols2,dim,dim)", "blocks1 = _mpit.slice_up_range(self.Np, nBlks1) blocks2 = _mpit.slice_up_range(self.Np, nBlks2) #distribute derivative computation across blocks", "sub-trees (if available and necessary) if comm.Get_size() > nDerivCols1 * nDerivCols2: #If there", "in order to keep prod managable.\") elif _np.count_nonzero(hProdCache[i]) and hProdCache[i].max() < HSMALL and", "- 1) // np1 # ceiling(num_params / np1) wrtLen2 = (self.Np + np2", "gpindices], _np.dot(LRproduct, dop_dopLabel), add=True) # (dim**2, nParams[opLabel]) if flat: return flattened_dprod else: #", "# print(\"MPI DEBUG: Rank%d subtee sizes = %s\" % # (comm.Get_rank(),\",\".join([str(len(subtrees[i])) # for", "hGs = evalTree.final_view(hProdCache, axis=0) #shape == ( len(circuit_list), nDerivCols, nDerivCols, dim, dim )", "which strings and outcomes, you'll need the mappings generated when the original list", "A 1 x M numpy array of derivatives of the probability w.r.t. each", "for conditional scaling required # to control bulk products, their gradients, and their", "== \"bulk_fill_dprobs\": mem += cache_size * wrtLen1 * dim * dim # dproduct", "= self.dim #Note: previously, we tried to allow for parallelization of # _compute_product_cache", "if evalTree.is_split(): _warnings.warn(\"Ignoring tree splitting in dproduct cache calc.\") dProdCache = _np.zeros((cacheSize,) +", "Returns ------- hessian : numpy array a 1 x M x M array,", "the vectorized model - G == the linear dimension of a operation matrix", "of `Circuits` was simplified. Parameters ---------- mxToFill : numpy ndarray an already-allocated 1D", "axis=0) last_wrtSlice1 = wrtSlice1 if (wrtSlice1 == wrtSlice2): dProdCache2 = dProdCache1; dGs2 =", "called w/comm size %d\" % comm.Get_size()) # parallelize of deriv cols, then sub-trees", "label. elabels : list A list of :class:`Label` objects giving the *simplified* effect", "deriv1Owners, mySubComm = \\ _mpit.distribute_slice(allDeriv1ColSlice, comm) # Get slice into entire range of", "as fInds). calc_and_fill_fn(spamTuple, fInds, gInds, pslc1, pslc2, False) # TODO: remove SumInto ==", "k-th then k-th model parameters. \"\"\" # LEXICOGRAPHICAL VS MATRIX ORDER # we", "tm) #Set wrtBlockSize to use available processors if it isn't specified if wrtFilter", "fInds). calc_and_fill_fn(spamTuple, fInds, gInds, pslc1, pslc2, False) # TODO: remove SumInto == True", "dim, dim)) def hoperation(self, opLabel, flat=False, wrtFilter1=None, wrtFilter2=None): \"\"\" Return the hessian of", "float(_np.dot(E, _np.dot(dprod_dOps[i], rho))) if returnPr: p = _np.dot(E, _np.dot(prod, rho)) * scale #", "range(self.Np): d2pr_dOps2[0, i, j] = float(_np.dot(E, _np.dot(d2prod_dGates[i, j], rho))) old_err = _np.seterr(over='ignore') prod,", "blkSize1 = comm_blkSize if (blkSize1 is None) \\ else min(comm_blkSize, blkSize1) # override", "not None) else None #TODO: just allow slices as argument: wrtFilter -> wrtSlice?", "is None) else len(wrtFilter1) num_deriv_cols2 = self.Np if (wrtFilter2 is None) else len(wrtFilter2)", "# want vp[iFinal] = float(dot(E, dot(G, rho))) # vp[i] = sum_k,l E[0,k] Gs[i,k,l]", "= None #get distribution across subtrees (groups if needed) subtrees = evalTree.get_sub_trees() mySubTreeIndices,", "blk_wrtSlice2 = blocks2[iBlk2] if blk_wrtSlice1 == blk_wrtSlice2: dProdCache2 = dProdCache1; dGs2 = dGs1", "generator and yielded, *not* allocated by the user. mem += 2 * cache_size", "(i.e. probabilities) to gate-only sequence and prep/effect pairs. The evaluation tree organizes how", "\"\"\" Constructs an EvalTree object appropriate for this calculator. Parameters ---------- simplified_circuits :", "- M == the number of model params or wrtFilter1 or 2, respectively", ": numpy array Only returned when bReturnDProdsAndProds == True. An array of shape", "* dim * dim # product cache # mem += cache_size # scale", "of the returned derivative array (see below). wrtFilter : list of ints, optional", "clip returned probability to if not None. Only relevant when prMxToFill is not", "* matrixOf(circuit[iRight]) (iRight, iLeft) = evalTree[i] L, R = prodCache[iLeft], prodCache[iRight] dL, dR", "dL, dR = dProdCache[iLeft], dProdCache[iRight] dProdCache[i] = _np.dot(dL, R) + \\ _np.swapaxes(_np.dot(L, dR),", "comm, *not* mySubComm (this is ok, see \"if\" condition above) _mpit.gather_slices(deriv1Slices, deriv1Owners, hProdCache,", "ok dGs = _np.swapaxes(_np.swapaxes(dGs, 0, 3) * scaleVals, 0, 3) # convert nans", "# add the result to the appropriate block of flattened_d2prod. #NOTE: if we", "parameters to differentiate with respect to in the first (row) and second (col)", "_np.swapaxes(_np.swapaxes(dGs1, 0, 1).reshape((nDerivCols1, nCircuits * dim**2)), 0, 1) # cols = deriv cols,", "override with smaller comm_blkSize blkSize2 = comm_blkSize if (blkSize2 is None) \\ else", "= {}; gate_wrtFilters1 = {} gpindices2 = {}; gate_wrtFilters2 = {} for l", "wrt the 2nd set of gate parameters if wrtSlice1 == wrtSlice2: # Note:", "operation sequence # prod = G1 * G2 * .... * GN ,", "is used as the final block size. These arguments must be None if", "amount of intermediate memory required. profiler : Profiler, optional A profiler object used", ": numpy array * if flat == False, an array of shape S", "circuit[iRight], but we want: # since then matrixOf(circuit[i]) = matrixOf(circuit[iLeft]) * matrixOf(circuit[iRight]) (iRight,", "x M numpy array of derivatives of the probability w.r.t. each model parameter", "in dpr(...) dpr_drhos = _np.zeros((1, self.Np)) derivWrtAnyRhovec = scale * _np.dot(E, prod) _fas(dpr_drhos,", "the probability. circuit : Circuit or tuple A tuple-like object of *simplified* gates", "linear operation to be done prior to the scaling. \"\"\" if bScale: scaledGatesAndExps", "#Fill product cache info (not requiring row or column distribution) prodCache, scaleCache =", "susceptible to overflow G = self.product(circuit, False) if self.evotype == \"statevec\": ps =", "gate operation performed, which is on the far right of the product of", "of wrtBlockSize and the size that makes maximal use of available processors is", "#my_results = [] for iSubTree in mySubTreeIndices: evalSubTree = subtrees[iSubTree] felInds = evalSubTree.final_element_indices(evalTree)", "both spam and gate-sequence indices # gInds = \"gate sequence indices\" = indices", "the linear dimension of a operation matrix (G x G operation matrices) and", "performed as a part of MPI processor syncronization. Returns ------- None \"\"\" tStart", "H = _np.dot(gate, G) # product of gates, starting with identity scale_exp +=", "dim)) def hoperation(self, opLabel, flat=False, wrtFilter1=None, wrtFilter2=None): \"\"\" Return the hessian of a", "the Hessian of a function of many gate sequence probabilities can often be", "self._process_wrtFilter(wrtFilter, gate) # Allocate memory for the final result num_deriv_cols = self.Np if", "pslc1], self._dprobs_from_rhoE( spamTuple, rho, E, Gs[gInds], dGs1[gInds], scaleVals[gInds], wrtSlice1), add=sumInto) if deriv2MxToFill is", "= self.dim #Cache partial products (relatively little mem required) leftProds = [] G", "prodCache, dProdCache1, dProdCache2, scaleCache, comm, wrtSlice1, wrtSlice2) #use cached data to construct return", "evalSubTree = subtrees[iSubTree] #Free memory from previous subtree iteration before computing caches scaleVals", "it isn't specified if wrtFilter is None: blkSize = wrtBlockSize # could be", "rholabel, elabels): #Note: no support for \"custom\" spamlabels... # This calculator uses the", "of operation labels. flat : bool, optional Affects the shape of the returned", "must be pre-filtered!\" #Compute d2(probability)/dGates2 and save in return list # d2pr_dOps2[i,j,k] =", "a number of operation sequences. Returns ------- int \"\"\" return int(1.3 * nCircuits)", "(i, gl) in enumerate(revOpLabelList): if gl != opLabel: continue # loop over locations", "of product 2nd derivatives in a linear cache space. Will use derivative rows", "to parallelize computation, since there are no memory savings from using a split", "Affects the shape of the returned derivative array (see below). bReturnDProdsAndProds : bool,", "example, the Hessian of a function of many gate sequence probabilities can often", "cache (exps) mem += cache_size # scale vals elif fnName == \"bulk_fill_dprobs\": mem", "G(L-1) dG(L)/dij G(L+1) ... GN ] + {similar with L < M} #", "profiler.add_time(\"bulk_fill_dprobs: compute_dproduct_cache\", tm) profiler.mem_check(\"bulk_fill_dprobs: post compute dproduct\") #Compute all requested derivative columns at", "vgs x GxG dLdRa = _np.swapaxes(_np.dot(dL1, dR2), 1, 2) dLdRb = _np.swapaxes(_np.dot(dL2, dR1),", "wrtBlockSize2 # could be None if (mySubComm is not None) and (mySubComm.Get_size() >", "and keep track of exponent # # p = _mt.trace( _np.dot(self.SPAMs[spamLabel],G) ) *", "len(circuit) < 10: strToPrint = str(circuit) else: strToPrint = str(circuit[0:10]) + \" ...", "make use of in \" \" _compute_dproduct_cache.\") if mySubComm.Get_rank() > 0: myDerivColSlice =", "(even == 1) in order to perform the parallelization over the parameter groups.", "self._dprobs_from_rhoE( spamTuple, rho, E, Gs[gInds], dGs[gInds], scaleVals[gInds], block_wrtSlice), add=sumInto) _np.seterr(**old_err) profiler.add_time(\"bulk_fill_dprobs: calc_and_fill_blk\", tm)", "in range(len(self.preps)) ] # # loc_e_slices = [ # _slct.shift(_slct.intersect( # wrtSlices['effects'], #", "= dot(transpose(dE/dEP),dGs[i,j],rho) # d2pr_dEs[i,j,J0+J] = sum_kl dEPT[J,k] dGs[i,j,k,l] rho[l,0] # d2pr_dEs[i,j,J0+J] = sum_k", "tup implies circuit[i] = circuit[iLeft] + circuit[iRight], but we want: # since then", "level. \"\"\" dim = self.dim #Note: previously, we tried to allow for parallelization", "dProdCache1 if (wrtSlice1 == wrtSlice2) else \\ self._compute_dproduct_cache(evalTree, prodCache, scaleCache, comm, wrtSlice2) hProdCache", "_np.seterr(**old_err) if returnDeriv: if returnPr: return ret, dpr, p else: return ret, dpr", "is None) \\ else min(comm_blkSize, blkSize1) # override with smaller comm_blkSize blkSize2 =", "hGs[i] is hprod_dGates for ith string if not bScale: old_err = _np.seterr(over='ignore', invalid='ignore')", "comm=None, wrtFilter1=None, wrtFilter2=None): \"\"\" Return the Hessian of many operation sequence products at", "not fully supported yet!\") rholabel, elabel = spamTuple rhoVec = self.sos.get_prep(rholabel) # distinct", "to the existing array values, which is a functionality needed to correctly handle", "with a chance that the product will overflow and the subsequent trace operation", "sum_kl dEPT[J,k] dGs[i,j,k,l] rho[l,0] # d2pr_dEs[i,j,J0+J] = sum_k dEP[k,J] dot(dGs, rho)[i,j,k,0] # d2pr_dEs[i,j,J0+J]", "True, an array of shape S*N x M x M where - N", "that we track owners #if mySubSubComm.Get_rank() > 0: myDeriv2ColSlice = slice(0,0) # #don't", "scaledGatesAndExps: opmx = self.sos.get_operation(lOp).todense() ng = max(_nla.norm(opmx), 1.0) scaledGatesAndExps[lOp] = (opmx / ng,", "rescalings out of %d products\" % (cnt, len(evalTree)) nanOrInfCacheIndices = (~_np.isfinite(prodCache)).nonzero()[0] # may", "i-th operation sequence. \"\"\" nCircuits = evalTree.num_final_strings() nDerivCols = self.Np if (wrtFilter is", "mxToFill, [felInds, blocks1[iBlk1]], 2, blk1Comm, gatherMemLimit) #gather row results; gather axis 1 of", "# PrepEffectFilter = _collections.namedtuple( # 'PrepEffectFilter', 'rho_local_slices rho_global_slices ' + # 'e_local_slices e_global_slices", "but OK if clipTo is not None: p = _np.clip(p, clipTo[0], clipTo[1]) #Derivs", ") #Same as in bulk_fill_hprobs (TODO consolidate?) #NOTE: filtering is done via the", "probabilities) to gate-only sequence and prep/effect pairs. The evaluation tree organizes how to", "computing caches scaleVals = Gs = prodCache = scaleCache = None #Fill cache", "dprobs2 mem += cache_size * wrtLen1 * wrtLen2 * dim * dim #", "' + # 'e_local_slices e_global_slices num_rho_params num_e_params') # # if wrtSlices is not", "else: # Divide columns into blocks of at most blkSize assert(wrtFilter1 is None", "comm, *not* mySubComm, since we can't do any # further parallelization tm =", "if _nla.norm(hprMxToFill[fInds][0] - check_vhp[0]) > 1e-6: _warnings.warn(\"norm(vhp-check_vhp) = %g - %g = %g\"", "\"\"\" tm = _time.time() old_err = _np.seterr(over='ignore') rho, E = self._rhoE_from_spamTuple(spamTuple) _fas(prMxToFill, [fInds],", "= %g - %g = %g\" % (_nla.norm(hprMxToFill[fInds]), _nla.norm(check_vhp), _nla.norm(hprMxToFill[fInds] - check_vhp))) #", "None: _fas(deriv1MxToFill, [fInds, pslc1], self._dprobs_from_rhoE( spamTuple, rho, E, Gs[gInds], dGs1[gInds], scaleVals[gInds], wrtSlice1), add=sumInto)", "of the product components (i.e. prod_kl) with # respect to a given gateLabel_ij.", "and comm.Get_size() > 1: #print(\"MPI: _compute_dproduct_cache called w/comm size %d\" % comm.Get_size()) #", "distributing calculations across multiple processors and to control memory usage. Cannot be specified", ":, None] * dprobs2[:, None, :] # (KM,N,1) * (KM,1,N') = (KM,N,N') yield", "# product of gates, starting with G0 # nG = norm(G); G /=", "1) in order to perform the parallelization over the parameter groups. num_param1_groups :", "to compute *products* for simultaneously. None means compute all requested columns at once.", "not None, a list of integers specifying which model parameters to differentiate with", "in their parameters, this # isn't currently needed. N = len(revOpLabelList) for m,", "numpy array of length equal to the total number of computed elements (i.e.", "#Set filtering for calc_and_fill wrtSlice1 = blocks1[iBlk1] wrtSlice2 = blocks2[iBlk2] self._fill_result_tuple((prMxToFill, deriv1MxToFill, deriv2MxToFill,", "element of cache are given by evalTree's initial single- or zero-operation labels for", "_np.squeeze(_np.dot(_np.dot(E, dGs2), drho), axis=(0,)) * scaleVals[:, None, None]) # overflow OK d2pr_drhos2 =", "many operation sequences at once. Parameters ---------- evalTree : EvalTree given by a", "self.sos.get_prep(rholabel)) rho_wrtFilter2, rho_gpindices2 = self._process_wrtFilter(wrtSlice2, self.sos.get_prep(rholabel)) E_wrtFilter1, E_gpindices1 = self._process_wrtFilter(wrtSlice1, self.sos.get_effect(elabel)) E_wrtFilter2, E_gpindices2", "with keys == spam labels and values which are integer row indices into", "lOp in circuit: if lOp not in scaledGatesAndExps: opmx = self.sos.get_operation(lOp).todense() ng =", "= _np.rollaxis(_np.rollaxis(hGs, 0, 3).reshape( (nDerivCols1, nDerivCols2, nCircuits * dim**2)), 2) # as above", "Construct a new MatrixForwardSimulator object. Parameters ---------- dim : int The gate-dimension. All", "to zero, as these occur b/c an inf scaleVal is mult by a", "cache_size # scale vals else: raise ValueError(\"Unknown subcall name: %s\" % fnName) return", "0 _np.seterr(**old_err) if flat: dGs = _np.swapaxes(_np.swapaxes(dGs, 0, 1).reshape( (nDerivCols, nCircuits * dim**2)),", "processors. This is done over operation sequences when a *split* evalTree is given,", "relevant when prMxToFill is not None. Returns ------- derivative : numpy array a", "evolution we need to: # - alter product, dproduct, etc. to allow for", "in evalTree.get_evaluation_order(): tm = _time.time() # combine iLeft + iRight => i #", "columns and then (and only when needed) a split tree to parallelize computation,", "in range(self.Np): d2pr_dOps2[0, i, j] = float(_np.dot(E, _np.dot(d2prod_dGates[i, j], rho))) old_err = _np.seterr(over='ignore')", "allow slices as argument: wrtFilter -> wrtSlice? prodCache, scaleCache = self._compute_product_cache(evalTree, comm) dProdCache", "allow for additional model classes (e.g. ones which use entirely different -- non-gate-local", "column-by-column from the using the columns of the operation sequences. Parameters ---------- spam_label_rows", "obj.gpindices_as_array() for ii, i in enumerate(wrtFilter): if i in gpindices: relevant_gpindices.append(ii) obj_wrtFilter.append(list(gpindices).index(i)) relevant_gpindices", "= _np.kron(_np.transpose(prods[(0, m - 1)]), prods[(m + 1, N - 1)]) # (dim**2,", "scaleVal is mult by a zero deriv value (see below) dGs2[_np.isnan(dGs2)] = 0", "dot(E,dGs[i,j],drho/drhoP)) # d2pr_drhos[i,j,J0+J] = sum_kl E[0,k] dGs[i,j,k,l] drhoP[l,J] # d2pr_drhos[i,j,J0+J] = dot(E, dGs,", "doesn't index numpy arrays # like length>1 lists do... ugh. relevant_gpindices = slice(0,", "== False, an array of shape S x M x G x G,", "gate's parameters if isinstance(wrtFilter, slice): wrtFilter = _slct.indices(wrtFilter) if wrtFilter is not None:", "shape of the returned derivative array (see below). wrtFilter1, wrtFilter2 : list of", "for i, opLabel in zip(evalTree.get_init_indices(), evalTree.get_init_labels()): if opLabel == \"\": # special case", "i - 1)] = ident # product of no gates G = ident", "_np.real(_np.dot(Es, _np.dot(G, rho))) ps = ps.flatten() if _np.any(_np.isnan(ps)): if len(circuit) < 10: strToPrint", "elabel in elabels] Es = _np.conjugate(_np.transpose(_np.concatenate(Es, axis=1))) # convention: Es has shape (len(elabels),N)", "their effect-label (their prep labels must be the same) Parameters ---------- rholabel :", "*start* time at which `circuit` is evaluated. Returns ------- numpy.ndarray An array of", "any # further parallelization tm = _time.time() all_results = comm.allgather(my_results) profiler.add_time(\"MPI IPC\", tm)", "by the output array size. Could throw more informative error? #elif fnName ==", "# (= [0,:,:]) d2pr_dEs = _np.zeros((1, self.Np, self.Np)) derivWrtAnyEvec = _np.squeeze(_np.dot(dprod_dOps, rho), axis=(2,))", "self.sos.get_effect(elabel).has_nonzero_hessian(): derivWrtAnyEvec = scale * _np.transpose(_np.dot(prod, rho)) # may overflow, but OK d2pr_d2Es", "final result num_deriv_cols1 = self.Np if (wrtFilter1 is None) else len(wrtFilter1) num_deriv_cols2 =", "enumerate(revOpLabelList): inds1 = gpindices1[opLabel1] nDerivCols1 = dop_dopLabel1[opLabel1].shape[1] if nDerivCols1 == 0: continue for", "= _np.identity(dim) # Note: scaleCache[i] = 0.0 from initialization else: gate = self.sos.get_operation(opLabel).todense()", "the values for this spam label (given by the subsequent arguments, except for", "else: yield wrtSlice1, wrtSlice2, hprobs dProdCache1 = dGs1 = None # free mem", "b/c cachesize is always >= num_final_strs # and this dictates how large all", "axis=(0, 3)) * scaleVals[:, None] _np.seterr(**old_err2) # may overflow, but OK ; shape", "further parallelization tm = _time.time() all_results = comm.allgather(my_results) profiler.add_time(\"MPI IPC\", tm) return _np.concatenate(all_results,", "_mpit.distribute_indices(list(range(nBlks1)), mySubComm) myBlk2Indices, blk2Owners, blk2Comm = \\ _mpit.distribute_indices(list(range(nBlks2)), blk1Comm) if blk2Comm is not", "specify the operation sequences to create an evaluation tree out of (most likely", "Similar to `bulk_fill_probs(...)`, but fills a 2D array with probability-derivatives for each \"final", "= sorted(list(set(revOpLabelList))) for opLabel in uniqueOpLabels: gate = self.sos.get_operation(opLabel) op_wrtFilter, gpindices = self._process_wrtFilter(wrtFilter,", "------- derivs : numpy array * if flat == False, an array of", "(rholabel,elabel), circuit, clipTo, bScale) for elabel in elabels ]) #assert(_np.linalg.norm(ps-check_ps) < 1e-8) return", "the vectorized derivatives of each of the product components (i.e. prod_kl) with #", "and doesn't merit a warning # ------------------------------------------------------------------ if evalTree.is_split(): _warnings.warn(\"Ignoring tree splitting in", "good way to reconstruct the parent tree's *non-final* elements from those of the", "return mem * FLOATSIZE def bulk_product(self, evalTree, bScale=False, comm=None): \"\"\" Compute the products", "== \"\": # special case of empty label == no gate prodCache[i] =", ": float only returned if returnPr == True. \"\"\" if self.evotype == \"statevec\":", "myDeriv1ColSlice], 2, mySubComm) # , gatherMemLimit) #gather over col-distribution (Deriv2) #note: gathering axis", "respect to only that gate's parameters and fill the appropriate # columns of", "now will not alter scaleCache.\") #profiler.print_mem(\"DEBUGMEM: POINT2\"); profiler.comm.barrier() profiler.add_time(\"compute_dproduct_cache: serial\", tSerialStart) profiler.add_count(\"compute_dproduct_cache: num", "_fas(deriv1MxToFill, [fInds, pslc1], self._dprobs_from_rhoE( spamTuple, rho, E, Gs[gInds], dGs1[gInds], scaleVals[gInds], wrtSlice1), add=sumInto) if", "by model objects to perform product and derivatives-of-product calculations. This is contained in", "entry of the product with respect to the j-th then i-th model parameters.", "dEP[k,J] dot(dGs, rho)[i,j,k,0] # d2pr_dEs[i,j,J0+J] = dot( squeeze(dot(dGs, rho),axis=(3,)), dEP)[i,j,J] # d2pr_dEs[:,:,J0+J] =", "_np.dot(_np.kron(xv, _np.transpose(prods[(l + 1, N - 1)])), dop_dopLabel2[opLabel2]) # above: (nDerivCols1,dim**2,dim**2) * (dim**2,nDerivCols2)", "arguments must be None if the corresponding wrtFilter is not None. Set this", "filtering is done via the yet-to-be-defined local variables # wrtSlice1 and wrtSlice2, of", "computed # for the current spamTuple (this list has the SAME length as", "flattened_d2prod.shape[1:3] # == num_deriv_cols1, num_deriv_cols2 return _np.rollaxis(flattened_d2prod, 0, 3).reshape((vec_kl_size, vec_ij_size, dim, dim)) #", "i in range(len(self.preps)) ] # # loc_e_slices = [ # _slct.shift(_slct.intersect( # wrtSlices['effects'],", "> 0 and _slct.length(gpindices2) > 0: # works for arrays too # Compute", "as a part of MPI processor syncronization. Returns ------- None \"\"\" if wrtFilter1", "scaleVals[:, None, None]) # overflow OK # get d2pr_drhos where gate derivatives are", "E, Gs, dGs, scaleVals, wrtSlice=None): if self.evotype == \"statevec\": raise NotImplementedError(\"Unitary evolution not", "1 # if vec(.) concatenates rows (which numpy.flatten does) # vec( A *", "the string which match the current # gate (so we only need to", "labels must be the same) Parameters ---------- rholabel : Label The state preparation", "deriv cols, rows = flattened all else dGs2 = _np.swapaxes(_np.swapaxes(dGs2, 0, 1).reshape((nDerivCols2, nCircuits", "None] # overflow OK devec = EVec.deriv_wrt_params(E_wrtFilter2) _fas(d2pr_dEs1, [None, None, E_gpindices2], _np.dot(dp_dAnyE, devec))", ") = A tensor B^T * vec( X ) # if vec(.) stacks", "(single-gate) sequence \"\"\" dim = self.dim gate = self.sos.get_operation(opLabel) op_wrtFilter1, gpindices1 = self._process_wrtFilter(wrtFilter1,", "to allow for parallelization of # _compute_product_cache when the tree was split, but", "for i-th operation sequence scaleExps = evalTree.final_view(scaleCache) old_err = _np.seterr(over='ignore') scaleVals = _np.exp(scaleExps)", "quantities blocks for given arguments \"\"\" tm = _time.time() old_err = _np.seterr(over='ignore') rho,", "scale cache mem += cache_size # scale vals elif fnName == \"bulk_hprobs_by_block\": #Note:", "it is split). Returns ------- None \"\"\" #get distribution across subtrees (groups if", "iteration before computing caches scaleVals = Gs = dGs = None prodCache =", "the probabilities and their derivatives (see below). bScale : bool, optional When True,", "has the same dimensions as the Hessian, and turns out to be useful", "# d2pr_dOps2[i,j,k] = dot( E, dot( dGs, rho ) )[0,i,j,k,0] # d2pr_dOps2 =", "profiler.comm.barrier() #evaluate operation sequences using tree (skip over the zero and single-gate-strings) for", "the number of entries in a single flattened gate (ordered as numpy.flatten) -", "< l: x0 = _np.kron(_np.transpose(prods[(0, m - 1)]), prods[(m + 1, l -", "+ scaleCache[iRight]) if abs(scale) > 1e-8: # _np.isclose(scale,0) is SLOW! dProdCache[i] /= _np.exp(scale)", "of shape S x M x G x G, where: - S ==", "* dim**2)), 0, 1) hGs = _np.rollaxis(_np.rollaxis(hGs, 0, 3).reshape( (nDerivCols1, nDerivCols2, nCircuits *", "_np.dot(_np.dot(E, dprod_dOps), rhoVec.deriv_wrt_params())[0]) # (= [0,:,:]) d2pr_dEs = _np.zeros((1, self.Np, self.Np)) derivWrtAnyEvec =", "_np.transpose(d2pr_dEs2, (0, 2, 1)) # Get: d2pr_dErhos[i, e_offset[eIndex]:e_offset[eIndex+1], e_offset[rhoIndex]:e_offset[rhoIndex+1]] = # dEP^T *", "evalSubTree, blocks[iBlk], slice(None), calc_and_fill_blk) profiler.mem_check(\"bulk_fill_dprobs: post fill blk\") dProdCache = dGs = None", "fills a 3D array with probability-Hessians for each \"final element\" of `evalTree`. Parameters", "without copying - throws error if copy is needed) y = _np.dot(_np.kron(xv, _np.transpose(prods[(l", "else: dGs = evalTree.final_view(dProdCache, axis=0) #shape == ( len(circuit_list), nDerivCols, dim, dim ),", "include in the derivative dimension. This argument is used internally for distributing calculations", ": numpy array only returned if returnDeriv == True. A 1 x M", "size. This argument must be None if wrtFilter is not None. Set this", "(M is the length of the vectorized model). probability : float only returned", "if clipTo is not None: p = _np.clip(p, clipTo[0], clipTo[1]) dprod_dOps = self.dproduct(circuit)", "of as the first gate operation performed, which is on the far right", "with smaller comm_blkSize else: blkSize = None # wrtFilter dictates block if blkSize", "column distribution) prodCache, scaleCache = self._compute_product_cache(evalSubTree, mySubComm) scaleVals = self._scaleExp(evalSubTree.final_view(scaleCache)) Gs = evalSubTree.final_view(prodCache,", "# 'e_local_slices e_global_slices num_rho_params num_e_params') # # if wrtSlices is not None: #", "# noqa # a matrix for each given (i,j,k,l) # noqa # vec(", "runs much slower when True. comm : mpi4py.MPI.Comm, optional When not None, an", "% (nDerivCols2, comm.Get_rank(), str(myDerivColSlice))) if mySubComm is not None and mySubComm.Get_size() > 1:", "if (wrtFilter is not None) else None #TODO: just allow slices as argument:", "nL, nR = max(_nla.norm(L), _np.exp(-scaleCache[iLeft]), 1e-300), max(_nla.norm(R), _np.exp(-scaleCache[iRight]), 1e-300) sL, sR = L", "scaleCache, comm, wrtSlice1) dProdCache2 = dProdCache1 if (wrtSlice1 == wrtSlice2) else \\ self._compute_dproduct_cache(evalTree,", "== blkSize blocks = _mpit.slice_up_range(self.Np, nBlks, start=0) # Create placeholder dGs for *no*", "# d2pr/d(E)_i d(E)_j = 0 # d2pr/d(rho)_i d(rho)_j = 0 rholabel, elabel =", "matrices can be complex # - update probability-derivative computations: dpr/dx -> d|pr|^2/dx =", "operation labels. bScale : bool, optional When True, return a scaling factor (see", "numpy array * if flat == False, an array of shape S x", "and all SPAM vectors should be dim x 1. gates, preps, effects :", "parallelization _mpit.gather_slices(deriv2Slices, deriv2Owners, hProdCache, [None, myDeriv1ColSlice], 2, mySubComm) # , gatherMemLimit) #gather over", "to zero since we can't tell whether it's + or - inf anyway...", "when True. comm : mpi4py.MPI.Comm, optional When not None, an MPI communicator for", "- could compute? wrtLen1 = (self.Np + np1 - 1) // np1 #", "= dot(E, dGs, drhoP)[0,i,j,J] # d2pr_drhos[:,:,J0+J] = squeeze(dot(E, dGs, drhoP),axis=(0,))[:,:,J] drho = rhoVec.deriv_wrt_params(rho_wrtFilter2)", "FLOATSIZE = 8 # in bytes: TODO: a better way dim = self.dim", "== 0 ) #dGs = clip(dGs,-1e300,1e300) _np.seterr(**old_err) if flat: dGs = _np.swapaxes(_np.swapaxes(dGs, 0,", "A * X * B ) = B^T tensor A * vec( X", "# = 2 Re(dpr/dx*pr.C) , where dpr/dx is the usual density-matrix-mode probability #", "None) else _slct.length(wrtFilter1) nDerivCols2 = self.Np if (wrtFilter2 is None) else _slct.length(wrtFilter2) nCircuits", "tree. In short, parallelization should be done at a higher level. \"\"\" dim", "operation sequences. Returns ------- int \"\"\" return int(1.3 * nCircuits) def construct_evaltree(self, simplified_circuits,", "self.Np) if returnDeriv: # same as in dpr(...) dpr_dOps = _np.empty((1, self.Np)) for", "G = _np.dot(self.sos.get_operation(lOp).todense(), G) # LEXICOGRAPHICAL VS MATRIX ORDER return G def _process_wrtFilter(self,", "S*N x M where - N == the number of entries in a", "master_circuit_list = evalTree.generate_circuit_list(permute=False) # raw operation sequences for spamTuple, (fInds, gInds) in evalTree.spamtuple_indices.items():", "of model parameters) and deriv[i,j] holds the derivative of the i-th entry of", "nans to zero, as these occur b/c an inf scaleVal is mult by", "wrtFilter is not None: assert(wrtBlockSize is None) # Cannot specify both wrtFilter and", "final result memory hProdCache = _np.zeros((cacheSize,) + hessn_shape) # Use comm to distribute", "specifying which gate parameters to differentiate with respect to in the first (row)", "+ \\ d2pr_d2rhos + d2pr_d2Es + d2pr_dOps2 # Note: add transposes b/c spam", "across multiple processors. Returns ------- deriv : numpy array * if flat ==", "#Compute d(probability)/dOps and save in return list (now have G,dG => product, dprod_dOps)", "= _np.squeeze(_np.dot(E, _np.dot(dGs, rho)), axis=(0, 3)) * scaleVals[:, None] _np.seterr(**old_err2) # may overflow,", "GN ] + {similar with L < M} # noqa # + sum{M==L}", "< PSMALL and prodCache[i].min() > -PSMALL: nL, nR = max(_nla.norm(L), _np.exp(-scaleCache[iLeft]), 1e-300), max(_nla.norm(R),", "a given set of subcalls to computation functions. Parameters ---------- subcalls : list", "will hold. Returns ------- int The memory estimate in bytes. \"\"\" #Note: num_final_strs", "scaleVal is mult by a zero hessian value, and we hGs[_np.isnan(hGs)] = 0", "nDerivCols1), \"dGs1 must be pre-filtered!\" assert(dGs2.shape[1] == nDerivCols2), \"dGs1 must be pre-filtered!\" #", "we can't tell whether it's + or - inf anyway... d2pr_dOps2[_np.isnan(d2pr_dOps2)] = 0", "isn't gathered until now (but using blk1Comm). # (just as prMxToFill is computed", "deriv1MxToFill is not None: _mpit.gather_indices(subtreeElementIndices, subTreeOwners, deriv1MxToFill, [], 0, comm, gatherMemLimit) if deriv2MxToFill", "op_wrtFilter, gpindices = self._process_wrtFilter(wrtFilter, gate) # Allocate memory for the final result num_deriv_cols", "if (blkSize is None) \\ else min(comm_blkSize, blkSize) # override with smaller comm_blkSize", "opLabel2) if opLabel1 in hop_dopLabels: # indicates a non-zero hessian x0 = _np.kron(_np.transpose(prods[(0,", "profiler.mem_check(\"bulk_fill_dprobs: post compute dproduct\") #Compute all requested derivative columns at once self._fill_result_tuple((prMxToFill, mxToFill),", "timing and memory usage. gatherMemLimit : int, optional A memory limit in bytes", "tree of product derivatives in a linear cache space. Will use derivative columns", "hGs = None prodCache = scaleCache = None #Fill product cache info (not", "== wrtSlice2: # Note: this doesn't involve gate derivatives d2pr_dErhos2 = _np.transpose(d2pr_dErhos1, (0,", "axis=(3,)) * scaleVals[:, None, None] # overflow OK devec = EVec.deriv_wrt_params(E_wrtFilter1) _fas(d2pr_dEs2, [None,", "(dim2, nDerivCols1, nDerivCols2); # swapaxes takes (kl,vec_prod_indx,ij) => (vec_prod_indx,kl,ij) else: # l==m, which", "print \"backtrace\" of product leading up to nan #G = _np.identity( self.dim );", "be automatically parallelized over these groups. num_final_strs : int The number of final", "(and only when needed) a split tree to parallelize computation, since there are", "than hessian elements(%d)!\" % (self.Np**2) + \" [blkSize = {%.1f,%.1f}, nBlks={%d,%d}]\" % (blkSize1,", "order) # d2pr/d(E)_i d(E)_j = 0 # d2pr/d(rho)_i d(rho)_j = 0 rholabel, elabel", "distributing derivative calculations across multiple processors. Returns ------- hessians : numpy array *", "abs(scale) > 1e-8: # _np.isclose(scale,0) is SLOW! hProdCache[i] /= _np.exp(scale) if hProdCache[i].max() <", "columns at once self._fill_result_tuple((prMxToFill, mxToFill), evalSubTree, slice(None), slice(None), calc_and_fill) profiler.mem_check(\"bulk_fill_dprobs: post fill\") dProdCache", "_np.seterr(over='ignore') rho, E = self._rhoE_from_spamTuple(spamTuple) _fas(mxToFill, [fInds], self._probs_from_rhoE(rho, E, Gs[gInds], scaleVals[gInds]), add=sumInto) _np.seterr(**old_err)", "clipTo is not None: ret = _np.clip(ps, clipTo[0], clipTo[1]) else: ret = ps", "k-th then the j-th model parameter. derivative : numpy array only returned if", "opLabel == \"\": # special case of empty label == no gate dProdCache[i]", "myDeriv1ColSlice, myDeriv2ColSlice] = self._compute_hproduct_cache( evalTree, prodCache, dProdCache1[:, myDeriv1ColSlice], dProdCache2[:, myDeriv2ColSlice], scaleCache, None, myHessianSlice1,", "where E derivatives are wrt the 2nd set of gate parameters if wrtSlice1", "if self.sos.get_effect(elabel).has_nonzero_hessian(): dp_dAnyE = _np.dot(Gs, rho).squeeze(2) * scaleVals[:, None] # overflow OK d2pr_d2Es", "(G(L+1) ... GN)^T ]] has # columns which correspond to the vectorized derivatives", "respect to the j-th then i-th model parameters. * if flat == True,", "of the probability w.r.t. each model parameter (M is the length of the", "given (i,j) # noqa # vec( dprod/d(opLabel)_ij ) = sum_{L s.t. G(L) ==", "= _mt.trace( _np.dot(self.SPAMs[spamLabel],G) ) * exp(total_exp) # probability # print \"%d: p =", "for i in range(len(self.preps))] # tmp_num_params = [_slct.length(s) for s in loc_rho_slices] #", "S x G x G; products[i] is the i-th operation sequence product. scaleVals", "and `dprobs12` are arrays of shape K x S x B x B',", "returned derivative array (see below). wrtFilter : list of ints, optional If not", "scale vals # #elif fnName == \"bulk_dproduct\": # mem += cache_size * num_params", "#shape == ( len(circuit_list), nDerivCols1, nDerivCols2, dim, dim ), # hGs[i] is hprod_dGates", "performed as in bulk_product, bulk_dproduct, and bulk_hproduct. Returns ------- block_generator A generator which,", "Note: dProdCache?.shape = (#circuits,#params_to_diff_wrt,dim,dim) nDerivCols1 = dProdCache1.shape[1] nDerivCols2 = dProdCache2.shape[1] assert(wrtSlice1 is None", "slices as argument: wrtFilter -> wrtSlice? prodCache, scaleCache = self._compute_product_cache(evalTree, comm) dProdCache =", "M where - N == the number of entries in a single flattened", "clipTo[1], out=mxToFill) # in-place clip if check: self._check(evalTree, mxToFill, clipTo=clipTo) def bulk_fill_dprobs(self, mxToFill,", "# scale vals else: raise ValueError(\"Unknown subcall name: %s\" % fnName) return mem", "derivative of the i-th entry of the flattened product with respect to the", "occur b/c an inf scaleVal is mult by a zero deriv value (see", "columns of flattened_dprod. uniqueOpLabels = sorted(list(set(revOpLabelList))) for opLabel in uniqueOpLabels: gate = self.sos.get_operation(opLabel)", "= deriv cols, rows = flattened everything else return (dGs, Gs, scaleVals) if", "== \"\": # special case of empty label == no gate hProdCache[i] =", "Only relevant when prMxToFill is not None. Returns ------- derivative : numpy array", "evalTree, comm=None): \"\"\" Computes a tree of products in a linear cache space.", "nans (invalid), but ok dGs1 = _np.swapaxes(_np.swapaxes(dGs1, 0, 3) * scaleVals, 0, 3)", "# Note: if gate G(L) is just a matrix of parameters, then dG(L)/dij", "tm) profiler.mem_check(\"bulk_fill_dprobs: post gather blocks\") #collect/gather results tm = _time.time() subtreeElementIndices = [t.final_element_indices(evalTree)", "the current spamTuple (this list has the SAME length as fInds). calc_and_fill_fn(spamTuple, fInds,", "memory usage. Cannot be specified in conjuction with wrtBlockSize. wrtBlockSize : int or", "+= _np.swapaxes(y, 0, 1) # above: dim = (dim2, nDerivCols1, nDerivCols2); # swapaxes", "model parameters) - G == the linear dimension of a operation matrix (G", "(i.e. by wrtFilter1 and wrtFilter2). clipTo : 2-tuple, optional (min,max) to clip return", "*simplified* gates (e.g. may include instrument elements like 'Imyinst_0') clipTo : 2-tuple (min,max)", "# may overflow, but OK d2pr_d2Es = _np.zeros((1, self.Np, self.Np)) _fas(d2pr_d2Es, [0, self.sos.get_effect(elabel).gpindices,", "# loc_rho_slices = [ # _slct.shift(_slct.intersect( # wrtSlices['preps'], # slice(self.rho_offset[i],self.rho_offset[i+1])), # -self.rho_offset[i]) for", "= _np.zeros((nElements, _slct.length(wrtSlice1)), 'd') dprobs2 = _np.zeros((nElements, _slct.length(wrtSlice2)), 'd') else: dprobs1 = dprobs2", "of [ sum_{L s.t. G(L) == oplabel} [ (G1 ... G(L-1)) tensor (G(L+1)", "of the returned derivative array (see below). bReturnProds : bool, optional when set", "deriv1MxToFill, deriv2MxToFill, mxToFill), evalSubTree, slice(None), slice(None), calc_and_fill) else: # Divide columns into blocks", "then j-th model parameters. derivs1, derivs2 : numpy array Only returned if bReturnDProdsAndProds", "processors is used as the final block size. These arguments must be None", "mxToFill[felInds,blocks1[iBlk1]], dim=(ks,blk1,M) _mpit.gather_slices(blocks2, blk2Owners, mxToFill, [felInds, blocks1[iBlk1]], 2, blk1Comm, gatherMemLimit) #gather row results;", "when memory constraints make constructing the entire Hessian at once impractical, and one", "(len(elabels),N) if bUseScaling: old_err = _np.seterr(over='ignore') G, scale = self.product(circuit, True) if self.evotype", "even if given a split tree (since there's no good way to reconstruct", "if clipTo is not None and prMxToFill is not None: _np.clip(prMxToFill, clipTo[0], clipTo[1],", "= sum prod_il rho_l rholabel, elabel = spamTuple # can't deal w/\"custom\" spam", "numpy as _np import numpy.linalg as _nla import time as _time import itertools", "other linear operation to be done prior to the scaling. \"\"\" if bScale:", "#don't compute anything on \"extra\", i.e. rank != 0, cpus hProdCache[:, myDeriv1ColSlice, myDeriv2ColSlice]", "#Compute all requested derivative columns at once self._fill_result_tuple((prMxToFill, mxToFill), evalSubTree, slice(None), slice(None), calc_and_fill)", "scaleVals) if bScale else (dGs, Gs) else: dGs = evalTree.final_view(dProdCache, axis=0) #shape ==", "self._rhoEs_from_spamTuples(rholabel, elabels) #shapes: rho = (N,1), Es = (len(elabels),N) if bUseScaling: old_err =", "mem += cache_size # scale vals # #elif fnName == \"bulk_hproduct\": # mem", "blkSize assert(wrtFilter is None) # cannot specify both wrtFilter and blkSize nBlks =", "# Note: this doesn't involve gate derivatives d2pr_dErhos2 = _np.transpose(d2pr_dErhos1, (0, 2, 1))", "rank != 0, cpus my_results = self._compute_dproduct_cache( evalTree, prodCache, scaleCache, None, myDerivColSlice, profiler)", "drhoP),axis=(0,))[:,:,J] drho = rhoVec.deriv_wrt_params(rho_wrtFilter2) d2pr_drhos1 = _np.zeros((nCircuits, nDerivCols1, nDerivCols2)) _fas(d2pr_drhos1, [None, None, rho_gpindices2],", "specify a \"block\" of the Hessian to compute. Iterating over the output of", "_dummy_profiler if wrtFilter is not None: assert(wrtBlockSize is None) # Cannot specify both", "scaleVals, wrtSlice=None): if self.evotype == \"statevec\": raise NotImplementedError(\"Unitary evolution not fully supported yet!\")", "way to reconstruct the parent tree's *non-final* elements from those of the sub-trees).", "_np.swapaxes(_np.swapaxes(Gs, 0, 2) * scaleVals, 0, 2) # may overflow, but ok #", "and prMxToFill is not None: _np.clip(prMxToFill, clipTo[0], clipTo[1], out=prMxToFill) # in-place clip if", "Note: ignoring L == M terms assumes that d^2 G/(dij)^2 == 0, which", "t in subtrees] _mpit.gather_indices(subtreeElementIndices, subTreeOwners, mxToFill, [], 0, comm) #note: pass mxToFill, dim=(KS),", "wrtBlockSize to use available processors if it isn't specified if wrtFilter is None:", "size == blkSize blocks = _mpit.slice_up_range(self.Np, nBlks, start=0) # Create placeholder dGs for", "_slct.length(gpindices1) > 0 and _slct.length(gpindices2) > 0: # works for arrays too #", "dim # dproduct cache mem += cache_size * dim * dim # product", "= {} ident = _np.identity(dim) for (i, opLabel1) in enumerate(revOpLabelList): # loop over", "dim # hproduct cache mem += cache_size * (wrtLen1 + wrtLen2) * dim", "where M is the number of model parameters selected for the 1st and", "= evalSubTree.final_view(prodCache, axis=0) #( nCircuits, dim, dim ) def calc_and_fill(spamTuple, fInds, gInds, pslc1,", "*not* parallelize computation, even if given a split tree (since there's no good", "/ G^2)-th flattened operation sequence product with respect to the j-th model parameter.", "cache mem += cache_size * dim * dim # product cache mem +=", "0.0 #for i,lOp in enumerate(gateLabelList): # G = _np.dot(G,self[lOp]) # product of gates,", "single-gate-strings) #cnt = 0 for i in evalTree.get_evaluation_order(): # combine iLeft + iRight", "Return the Hessian of many operation sequence products at once. Parameters ---------- evalTree", "effect-label (their prep labels must be the same) Parameters ---------- rholabel : Label", "initial list of (general) :class:`Circuit` objects is *simplified* into a lists of gate-only", "columns into blocks of at most blkSize assert(wrtFilter is None) # cannot specify", "+ _np.transpose(d2pr_drhos, (0, 2, 1)) + \\ d2pr_dEs + _np.transpose(d2pr_dEs, (0, 2, 1))", "# self._probs_from_rhoE(rho, E, Gs[gInds], scaleVals[gInds]), add=sumInto) if deriv1MxToFill is not None: _fas(deriv1MxToFill, [fInds,", "# fInds = \"final indices\" = the \"element\" indices in the final #", "= None hprobs = _np.zeros((nElements, _slct.length(wrtSlice1), _slct.length(wrtSlice2)), 'd') #prMxToFill = None deriv1MxToFill =", "= rhoVec.deriv_wrt_params(rho_wrtFilter1) dp_dAnyE = _np.dot(Gs, drho) * scaleVals[:, None, None] # overflow OK", "# num blocks required to achieve desired average size == blkSize blocks =", "operation performed, which is on the far right of the product of matrices.", "# Use comm to distribute columns allDeriv1ColSlice = slice(0, nDerivCols1) allDeriv2ColSlice = slice(0,", "rholabel, elabel = spamTuple rhoVec = self.sos.get_prep(rholabel) # distinct from rho,E b/c rho,E", "d2pr_dErhos2 = _np.transpose(d2pr_dErhos2, (0, 2, 1)) #Note: these 2nd derivatives are non-zero when", "a each gate sequence given by evalTree column-by-column. This routine can be useful", "sum E_k prod_ki # dpr/d(E)_i = sum prod_il rho_l rholabel, elabel = spamTuple", "_np.dot(hGs, rho)), axis=(0, 4)) * scaleVals[:, None, None] _np.seterr(**old_err2) # may overflow, but", "than deriv cells, give a # warning -- note that we *cannot* make", "self.dim, self.dim), 'd') def calc_and_fill_p(spamTuple, fInds, gInds, pslc1, pslc2, sumInto): \"\"\" Compute and", "self._fill_result_tuple((prMxToFill, deriv1MxToFill, deriv2MxToFill, mxToFill), evalSubTree, blocks1[iBlk1], blocks2[iBlk2], calc_and_fill) hProdCache = hGs = dProdCache2", "# d2pr/d(E)_i d(rho)_j = prod_ij (and same for other diff order) # d2pr/d(E)_i", "scaleVals, 0, 4) # convert nans to zero, as these occur b/c an", "of model parameters selected for the 1st and 2nd differentiation, respectively (i.e. by", "but OK if infs occur here _np.seterr(**old_err) if bReturnProds: Gs = evalTree.final_view(prodCache, axis=0)", "2.0 (the \"License\"); you may not use this file except # in compliance", "axes = (vectorized_op_el_index, model_parameter1, model_parameter2) else: vec_kl_size, vec_ij_size = flattened_d2prod.shape[1:3] # == num_deriv_cols1,", "nBlks2)) # pragma: no cover # noqa for iBlk1 in myBlk1Indices: blk_wrtSlice1 =", "else: strToPrint = str(circuit[0:10]) + \" ... (len %d)\" % len(circuit) _warnings.warn(\"pr(%s) ==", "dim, dim)) def hproduct(self, circuit, flat=False, wrtFilter1=None, wrtFilter2=None): \"\"\" Compute the hessian of", "once self._fill_result_tuple((prMxToFill, mxToFill), evalSubTree, slice(None), slice(None), calc_and_fill) profiler.mem_check(\"bulk_fill_dprobs: post fill\") dProdCache = dGs", "sequences to compute the bulk operation on. This tree *cannot* be split. wrtSlicesList", "len(circuit_list), nDerivCols, nDerivCols, dim, dim ) if not bScale: old_err = _np.seterr(over='ignore', invalid='ignore')", "tm = _time.time() subtreeElementIndices = [t.final_element_indices(evalTree) for t in subtrees] _mpit.gather_indices(subtreeElementIndices, subTreeOwners, mxToFill,", "eIndex **) -- TODO: should also conjugate() here if complex? _fas(dpr_dEs, [0, EVec.gpindices],", "E[0,k] dot( dGs, rho )[i,j,k,0] # dp_dOps[i,j] = dot( E, dot( dGs, rho", "= _np.zeros((dim**2, num_deriv_cols1, num_deriv_cols2), 'd') # For each pair of gates in the", "reversed order of the tuple. That is, the first element of circuit can", "of shape K x S x B x B', where: - K is", "_np.swapaxes(_np.swapaxes(dGs, 0, 1).reshape( (nDerivCols, nCircuits * dim**2)), 0, 1) # cols = deriv", "/ nG); scale_exp += _np.log(nG) # LEXICOGRAPHICAL VS MATRIX ORDER else: G =", "dp_dEs[:,J0+J] = dot(squeeze(dot(Gs, rho),axis=(2,)), dEP)[:,J] dp_dEs = _np.zeros((nCircuits, nDerivCols)) # may overflow, but", "= _np.zeros((nCircuits, nDerivCols)) _fas(dp_drhos, [None, rho_gpindices], _np.squeeze(_np.dot(_np.dot(E, Gs), rhoVec.deriv_wrt_params(rho_wrtFilter)), axis=(0,)) * scaleVals[:, None])", "+ hessn_shape) # Use comm to distribute columns allDeriv1ColSlice = slice(0, nDerivCols1) allDeriv2ColSlice", "outcomes, you'll need the mappings generated when the original list of `Circuits` was", "parameters. \"\"\" # LEXICOGRAPHICAL VS MATRIX ORDER # we do matrix multiplication in", "---------- circuit : Circuit or tuple of operation labels The sequence of operation", "and then over blocks (subsets) of the parameters being differentiated with respect to", "processors. Distribution is performed as in bulk_product, bulk_dproduct, and bulk_hproduct. Returns ------- block_generator", "tree splitting in dproduct cache calc.\") dProdCache = _np.zeros((cacheSize,) + deriv_shape) # This", ") == 0 ) #hGs = clip(hGs,-1e300,1e300) _np.seterr(**old_err) if flat: hGs = _np.rollaxis(_np.rollaxis(hGs,", "R / nR prodCache[i] = _np.dot(sL, sR); scaleCache[i] += _np.log(nL) + _np.log(nR) #print", "entire Hessian at once impractical, and one is able to compute reduce results", "\\ self._compute_dproduct_cache(evalSubTree, prodCache, scaleCache, mySubComm, wrtSlice2) dGs1 = evalSubTree.final_view(dProdCache1, axis=0) dGs2 = evalSubTree.final_view(dProdCache2,", "= slice(0, nDerivCols2) deriv1Slices, myDeriv1ColSlice, deriv1Owners, mySubComm = \\ _mpit.distribute_slice(allDeriv1ColSlice, comm) # Get", "None] _fas(dp_dEs, [None, E_gpindices], _np.dot(dp_dAnyE, EVec.deriv_wrt_params(E_wrtFilter))) sub_vdp = dp_drhos + dp_dEs + dp_dOps", "def calc_and_fill(spamTuple, fInds, gInds, pslc1, pslc2, sumInto): \"\"\" Compute and fill result quantities", "rho = (N,1), Es = (len(elabels),N) if bUseScaling: old_err = _np.seterr(over='ignore') G, scale", "profiler.mem_check(\"bulk_fill_dprobs: post gather blocks\") #collect/gather results tm = _time.time() subtreeElementIndices = [t.final_element_indices(evalTree) for", "model params or wrtFilter1 or 2, respectively - G == the linear dimension", "(relatively little mem required) leftProds = [] G = _np.identity(dim); leftProds.append(G) for opLabel", "may overflow, but OK ; shape == (len(circuit_list), nDerivCols, nDerivCols) # may also", "------- hessian : numpy array * if flat == False, a M x", "EVec.gpindices], _np.dot(derivWrtAnyEvec, EVec.deriv_wrt_params())) dpr = dpr_drhos + dpr_dEs + dpr_dOps d2pr_drhos = _np.zeros((1,", "of model parameters. hessian[0,j,k] is the derivative of the probability w.r.t. the k-th", "for this calculator. Parameters ---------- simplified_circuits : list A list of Circuits or", "% G^2)-th entry of the (i / G^2)-th flattened operation sequence product with", "in range(len(self.preps)+1) ] # global_rho_slices = [ slice(tmp_offsets[i],tmp_offsets[i+1]) # for i in range(len(self.preps))", "None, a list of integers specifying which gate parameters to differentiate with respect", "= scale * _np.dot(prod, rhoVec.deriv_wrt_params()) # may generate overflow, but OK _fas(d2pr_dErhos, [0,", "maybe let dGs2 be None? assert(nDerivCols1 == nDerivCols2) d2pr_drhos2 = _np.transpose(d2pr_drhos1, (0, 2,", "The state preparation label. elabels : list A list of :class:`Label` objects giving", "want vp[iFinal] = float(dot(E, dot(G, rho))) # vp[i] = sum_k,l E[0,k] Gs[i,k,l] rho[l,0]", "# ------------------------------------------------------------------ if evalTree.is_split(): _warnings.warn(\"Ignoring tree splitting in product cache calc.\") cacheSize =", "else None wrtIndices2 = _slct.indices(wrtSlice2) if (wrtSlice2 is not None) else None for", "an already-allocated ExM numpy array that is filled with probability derivatives, similar to", "matrices). scaleValues : numpy array Only returned when bScale == True. A length-S", "None and wrtFilter2 is None) # cannot specify both wrtFilter and blkSize nBlks1", "argument: wrtFilter -> wrtSlice? prodCache, scaleCache = self._compute_product_cache(evalTree, comm) dProdCache1 = self._compute_dproduct_cache(evalTree, prodCache,", "sequences. Parameters ---------- spam_label_rows : dictionary a dictionary with keys == spam labels", "This function takes a \"calc-and-fill\" function, which computes and *fills* (i.e. doesn't return", "range(len(self.effects)) ] # # return PrepEffectFilter(rho_local_slices=loc_rho_slices, # rho_global_slices=global_rho_slices, # e_local_slices=loc_e_slices, # e_global_slices=global_e_slices, #", "Gates old_err = _np.seterr(over='ignore') prod, scale = self.product(circuit, True) dprod_dOps = self.dproduct(circuit) dpr_dOps", "on their parameters. if self.sos.get_prep(rholabel).has_nonzero_hessian(): dp_dAnyRho = _np.dot(E, Gs).squeeze(0) * scaleVals[:, None] #", "across multiple processors and to control memory usage. Cannot be specified in conjuction", "specified slice of the values for this spam label (given by the subsequent", "jk dEPT[J,j] prod[i,j,k] drhoP[k,K] # d2pr_dErhos[i,J0+J,K0+K] = sum j dEPT[J,j] dot(prod,drhoP)[i,j,K] # d2pr_dErhos[i,J0+J,K0+K]", "computing X^T ( note (A tensor B)^T = A^T tensor B^T ) #", "is possible. wrtFilter1, wrtFilter2 : list of ints, optional If not None, a", "+ \" ... (len %d)\" % len(circuit) _warnings.warn(\"pr(%s) == nan\" % strToPrint) #DEBUG:", "same as in dpr(...) dpr_dOps = _np.empty((1, self.Np)) for i in range(self.Np): dpr_dOps[0,", "wrtFilter1 == wrtFilter2: dop_dopLabel2 = dop_dopLabel1 else: dop_dopLabel2 = { opLabel: gate.deriv_wrt_params(gate_wrtFilters2[opLabel]) for", "# dpr/d(opLabel)_ij = sum E_k [dprod/d(opLabel)_ij]_kl rho_l # dpr/d(rho)_i = sum E_k prod_ki", "+ d2pr_d2Es + d2pr_dOps2 # Note: add transposes b/c spam terms only compute", "dL2, dR2 = dProdCache2[iLeft], dProdCache2[iRight] hL, hR = hProdCache[iLeft], hProdCache[iRight] # Note: L,", "gate.hessian_wrt_params(op_wrtFilter1, op_wrtFilter2)) if flat: return flattened_hprod else: return _np.transpose(flattened_hprod, (1, 2, 0)).reshape( (num_deriv_cols1,", "does all the major allocation/deallocation). #if comm is None or comm.Get_rank() == 0:", "E = self._rhoE_from_spamTuple(spamTuple) block_wrtSlice = pslc1 _fas(mxToFill, [fInds, pslc1], self._dprobs_from_rhoE( spamTuple, rho, E,", "calc.\") cacheSize = len(evalTree) prodCache = _np.zeros((cacheSize, dim, dim)) scaleCache = _np.zeros(cacheSize, 'd')", "all hessians for single- or zero-operation sequences are zero. hProdCache[i] = _np.zeros(hessn_shape) else:", "product cache mem += cache_size # scale cache (exps) mem += cache_size #", "evalTree.num_final_strings() # len(circuit_list) wrtSlice1 = _slct.list_to_slice(wrtFilter1) if (wrtFilter1 is not None) else None", "consisting of a pair of SPAMVec (or array) # objects: (prepVec, effectVec) rho,", "[ sum(tmp_num_params[0:i]) for i in range(len(self.preps)+1) ] # global_rho_slices = [ slice(tmp_offsets[i],tmp_offsets[i+1]) #", "block_wrtSlice = blocks[iBlk] dProdCache = self._compute_dproduct_cache(evalSubTree, prodCache, scaleCache, blkComm, block_wrtSlice, profiler) profiler.add_time(\"bulk_fill_dprobs: compute_dproduct_cache\",", "dProdCache1, dProdCache2, scaleCache, comm, wrtSlice1, wrtSlice2) #use cached data to construct return values", "for distributing calculations across multiple processors and to control memory usage. Cannot be", "results: gather axis 2 of mxToFill[felInds,blocks1[iBlk1]], dim=(ks,blk1,M) _mpit.gather_slices(blocks2, blk2Owners, mxToFill, [felInds, blocks1[iBlk1]], 2,", "the above matrices, so that # each column corresponds to a (opLabel,i,j) tuple", "2nd-deriv method in addition of deriv_wrt_params # # Note: unvec( X ) can", "and each row corresponds to an element of the product (els of #", "= dot(transpose(dE/dEP),Gs[i],rho)) # dp_dEs[i,J0+J] = sum_lj dEPT[J,j] Gs[i,j,l] rho[l,0] # dp_dEs[i,J0+J] = sum_j", "parameters to include in the derivative. Each element is an index into an", "to the vectorized derivatives of each of the product components (i.e. prod_kl) with", "self.dim uniqueOpLabels = sorted(list(set(revOpLabelList))) used_operations = _collections.OrderedDict() #Cache processed parameter filters for multiple", "else dGs2 = _np.swapaxes(_np.swapaxes(dGs2, 0, 1).reshape((nDerivCols2, nCircuits * dim**2)), 0, 1) hGs =", "to clip return value if not None. check : boolean, optional If True,", "clipTo[0], clipTo[1], out=mxToFill) # in-place clip if check: self._check(evalTree, mxToFill, clipTo=clipTo) def bulk_fill_dprobs(self,", "overflow, but ok # may overflow or get nans (invalid), but ok dGs1", "hoperation / _np.exp(scaleCache[i]) #evaluate operation sequences using tree (skip over the zero and", "that # if gl1 and gl2 are both in opsToVectorize1 and opsToVectorize2 we", "the derivatives and/or products for the i-th operation sequence. \"\"\" nCircuits = evalTree.num_final_strings()", "the total number of computed elements (i.e. evalTree.num_final_elements()) and M1 & M2 are", "has # columns which correspond to the vectorized derivatives of each of the", "nDerivCols2, dim, dim ), # hGs[i] is hprod_dGates for ith string if not", "hessians can be computed properly if wrtSlice1 is not None and wrtSlice1.start is", ": int or float, optional The maximum number of 1st (row) and 2nd", "so gather mxToFill[felInds] (axis=0) if prMxToFill is not None: _mpit.gather_indices(subtreeElementIndices, subTreeOwners, prMxToFill, [],", "from the using the columns of the operation sequences. Parameters ---------- spam_label_rows :", "operation sequences at once. Parameters ---------- evalTree : EvalTree given by a prior", "appropriate columns of flattened_dprod. _fas(flattened_hprod, [None, gpindices1, gpindices2], gate.hessian_wrt_params(op_wrtFilter1, op_wrtFilter2)) if flat: return", "code to verify correctness, generating warnings when checks fail. Used for testing, and", "the created tree. This aids in the tree construction by giving the tree", "a 1D array, `mxToFill` with the probabilities corresponding to the *simplified* operation sequences", "these are SPAMVecs d2prod_dGates = self.hproduct(circuit) assert(d2prod_dGates.shape[0] == d2prod_dGates.shape[1]) d2pr_dOps2 = _np.empty((1, self.Np,", "the same as that used by numpy.flatten), - S,M == as above, and", "self._hprobs_from_rhoE( spamTuple, rho, E, Gs[gInds], dGs1[gInds], dGs2[gInds], hGs[gInds], scaleVals[gInds], wrtSlice1, wrtSlice2), add=sumInto) _np.seterr(**old_err)", "else: dprobs1 = dprobs2 = None hprobs = _np.zeros((nElements, _slct.length(wrtSlice1), _slct.length(wrtSlice2)), 'd') #prMxToFill", "returnPr: return ret, p else: return ret ## BEGIN CACHE FUNCTIONS def _compute_product_cache(self,", "# mem += cache_size # scale vals else: raise ValueError(\"Unknown subcall name: %s\"", "that there would be no memory savings from using a split tree. In", "used to compute the probability. circuit : Circuit or tuple A tuple-like object", "dGs[i,j,k,l] drhoP[l,J] # d2pr_drhos[i,j,J0+J] = dot(E, dGs, drhoP)[0,i,j,J] # d2pr_drhos[:,:,J0+J] = squeeze(dot(E, dGs,", "G = _np.dot(self.sos.get_operation(opLabel).todense(), G) rightProdsT.append(_np.transpose(G)) # Allocate memory for the final result num_deriv_cols", "E def _rhoEs_from_spamTuples(self, rholabel, elabels): #Note: no support for \"custom\" spamlabels... # This", "GxG dLdRa = _np.swapaxes(_np.dot(dL1, dR2), 1, 2) dLdRb = _np.swapaxes(_np.dot(dL2, dR1), 1, 2)", "None or comm.Get_rank() == 0: # import objgraph # objgraph.show_growth(limit=50) #get distribution across", "into original wrtFilter'd indices gpindices = obj.gpindices_as_array() for ii, i in enumerate(wrtFilter): if", "_probs_from_rhoE(self, rho, E, Gs, scaleVals): if self.evotype == \"statevec\": raise NotImplementedError(\"Unitary evolution not", "operation sequence. \"\"\" nCircuits = evalTree.num_final_strings() nDerivCols = self.Np if (wrtFilter is None)", "= blocks1[iBlk1] dProdCache1 = self._compute_dproduct_cache( evalSubTree, prodCache, scaleCache, blk1Comm, blk_wrtSlice1) dGs1 = evalSubTree.final_view(dProdCache1,", "routine will run slightly faster, but with a chance that the product will", "for i in range(len(self.effects)+1) ] # global_e_slices = [ slice(tmp_offsets[i],tmp_offsets[i+1]) # for i", "of parameters being differentiated with respect to. If there are more processors than", "# swapaxes takes (kl,vec_prod_indx,ij) => (vec_prod_indx,kl,ij) else: # l==m, which we *used* to", "= self.sos.get_prep(rholabel).todense()[:, None] Es = [self.sos.get_effect(elabel).todense()[:, None] for elabel in elabels] Es =", "throws error if copy is needed) y = _np.dot(_np.kron(xv, _np.transpose(prods[(l + 1, N", "product, dprod_dOps) # prod, dprod_dOps = G,dG # dp_dOps[i,j] = sum_k,l E[0,k] dGs[i,j,k,l]", "gate strings. Similar to `bulk_fill_probs(...)`, but fills a 3D array with probability-Hessians for", "calc_and_fill_blk) profiler.mem_check(\"bulk_fill_dprobs: post fill blk\") dProdCache = dGs = None # free mem", "to the # gate's parameters and fill appropriate columns of flattened_dprod. _fas(flattened_hprod, [None,", "_mpit.gather_slices(blocks1, blk1Owners, deriv1MxToFill, [felInds], 1, mySubComm, gatherMemLimit) if deriv2MxToFill is not None: _mpit.gather_slices(blocks2,", "wrtSlice2) hGs = evalSubTree.final_view(hProdCache, axis=0) #( nCircuits, len(wrtFilter1), len(wrtFilter2), dim, dim ) #Compute", "parameters. evalTree : EvalTree given by a prior call to bulk_evaltree. Specifies the", "# arrays, these are SPAMVecs #Derivs wrt Gates old_err = _np.seterr(over='ignore') prod, scale", "is mult by a zero hessian value, and we hGs[_np.isnan(hGs)] = 0 #", "at # http://www.apache.org/licenses/LICENSE-2.0 or in the LICENSE file in the root pyGSTi directory.", "drho), axis=(0,)) * scaleVals[:, None, None]) # overflow OK # get d2pr_drhos where", "\"\"\" Compute the Hessian of a probability generated by a operation sequence and", "think about) revOpLabelList = tuple(reversed(tuple(circuit))) N = len(revOpLabelList) # length of operation sequence", "not None, an MPI communicator for distributing the computation across multiple processors. This", "gate's parameters (in the order specified by the model). This argument is used", "axis=0) #( nCircuits, len(wrtFilter1), len(wrtFilter2), dim, dim ) #Compute all requested derivative columns", "dProdCache[i] = doperation / _np.exp(scaleCache[i]) #profiler.print_mem(\"DEBUGMEM: POINT1\"); profiler.comm.barrier() #evaluate operation sequences using tree", "Hessian of a function of many gate sequence probabilities can often be computed", "blkSize) # override with smaller comm_blkSize else: blkSize = None # wrtFilter dictates", "calculations\" % self.evotype)) def copy(self): \"\"\" Return a shallow copy of this MatrixForwardSimulator", "once impractical, and one is able to compute reduce results from a single", "G = _np.dot(G, self.sos.get_operation(opLabel).todense()) leftProds.append(G) rightProdsT = [] G = _np.identity(dim); rightProdsT.append(_np.transpose(G)) for", "(iRight, iLeft) = evalTree[i] L, R = prodCache[iLeft], prodCache[iRight] dL1, dR1 = dProdCache1[iLeft],", "self._fill_result_tuple((None, dprobs1, dprobs2, hprobs), evalTree, slice(None), slice(None), calc_and_fill) hProdCache = hGs = dProdCache2", "the vectorized model (number of model parameters) and deriv[i,j] holds the derivative of", "_np.squeeze(_np.dot(dprod_dOps, rho), axis=(2,)) _fas(d2pr_dEs, [0, None, EVec.gpindices], _np.dot(derivWrtAnyEvec, EVec.deriv_wrt_params())) d2pr_dErhos = _np.zeros((1, self.Np,", "dGs1 = evalTree.final_view(dProdCache1, axis=0) dGs2 = evalTree.final_view(dProdCache2, axis=0) #shape == ( len(circuit_list), nDerivColsX,", "blkComm = \\ _mpit.distribute_indices(list(range(nBlks)), mySubComm) if blkComm is not None: _warnings.warn(\"Note: more CPUs(%d)\"", "This is contained in a class separate from Model to allow for additional", "# pr = Tr( |rho><E| * prod ) = sum E_k prod_kl rho_l", "closures seems confusing and we should do something else LATER. def calc_and_fill(spamTuple, fInds,", "_collections from ..tools import mpitools as _mpit from ..tools import slicetools as _slct", "N - 1)]) # (dim**2, dim**2) x = _np.dot(_np.transpose(dop_dopLabel1[opLabel1]), x0); xv = x.view()", "= gate / nG scaleCache[i] = _np.log(nG) #evaluate operation sequences using tree (skip", "dot( E, dot(Gs, rho)), axis=(0,2) ) * scaleVals return _np.squeeze(_np.dot(E, _np.dot(Gs, rho)), axis=(0,", "of product leading up to nan #G = _np.identity( self.dim ); total_exp =", "profiler) # pass None as comm, *not* mySubComm, since we can't do any", "[t.final_element_indices(evalTree) for t in subtrees] _mpit.gather_indices(subtreeElementIndices, subTreeOwners, mxToFill, [], 0, comm, gatherMemLimit) #note:", "CPUs(%d)\" % mySubComm.Get_size() + \" than derivative columns(%d)!\" % self.Np + \" [blkSize", "dim=(KS,M), so gather mxToFill[felInds] (axis=0) if prMxToFill is not None: _mpit.gather_indices(subtreeElementIndices, subTreeOwners, prMxToFill,", "slice(None), slice(None), calc_and_fill_p) profiler.mem_check(\"bulk_fill_dprobs: post fill probs\") #distribute derivative computation across blocks myBlkIndices,", "(tree-) list of # all of the raw operation sequences which need to", "doesn't depend on eIndex **) -- TODO: should also conjugate() here if complex?", "the using the columns of the operation sequences. Parameters ---------- spam_label_rows : dictionary", "# slice(self.rho_offset[i],self.rho_offset[i+1])), # -self.rho_offset[i]) for i in range(len(self.preps))] # tmp_num_params = [_slct.length(s) for", "sequences - G == the linear dimension of a operation matrix (G x", "param_slice2 for spamTuple, (fInds, gInds) in evalTree.spamtuple_indices.items(): # fInds = \"final indices\" =", "we assume all gate elements are at most # linear in the parameters", "was split, but this is was # incorrect (and luckily never used) -", "an already-allocated 1D numpy array of length equal to the total number of", "a shallow copy of this MatrixForwardSimulator \"\"\" return MatrixForwardSimulator(self.dim, self.sos, self.paramvec) def product(self,", "entire operation sequence with respect to the # gate's parameters and fill appropriate", "of hessian # Note: d2pr_d2rhos and d2pr_d2Es terms are always zero _np.seterr(**old_err) if", "scaleCache, None, myDerivColSlice, profiler) # pass None as comm, *not* mySubComm, since we", "* wrtLen1 * dim * dim # dproduct cache mem += cache_size *", "return ret ## BEGIN CACHE FUNCTIONS def _compute_product_cache(self, evalTree, comm=None): \"\"\" Computes a", "i in range(self.Np): dpr_dOps[0, i] = float(_np.dot(E, _np.dot(dprod_dOps[i], rho))) #Derivs wrt SPAM if", "groups to divide the first-derivative parameters into. Computation will be automatically parallelized over", "% self.evotype)) def copy(self): \"\"\" Return a shallow copy of this MatrixForwardSimulator \"\"\"", "axis=(0, 4)) * scaleVals[:, None, None] _np.seterr(**old_err2) # may overflow, but OK ;", "> 1e-6: _warnings.warn(\"norm(vp-check_vp) = %g - %g = %g\" % (_nla.norm(prMxToFill[fInds]), _nla.norm(check_vp), _nla.norm(prMxToFill[fInds]", "dGs2[_np.isnan(dGs2)] = 0 # convert nans to zero, as these occur b/c an", "* scaleVals[i] # vp[i] = dot( E, dot(Gs, rho))[0,i,0] * scaleVals[i] # vp", "derivative of a probability generated by a operation sequence and spam tuple as", "# d2pr/d(rho)_i d(rho)_j = 0 rholabel, elabel = spamTuple rho, E = self._rhoE_from_spamTuple(spamTuple)", "wrtSlice=None): if self.evotype == \"statevec\": raise NotImplementedError(\"Unitary evolution not fully supported yet!\") rholabel,", "# raw operation sequences for spamTuple, (fInds, gInds) in evalTree.spamtuple_indices.items(): circuit_list = master_circuit_list[gInds]", "holds the derivative of the i-th entry of the flattened product with respect", "# all hessians for single- or zero-operation sequences are zero. hProdCache[i] = _np.zeros(hessn_shape)", "is valid. # Below we use E(i,j) to denote the elementary matrix where", "# dot(dS, T) + dot(S, dT) profiler.add_time(\"compute_dproduct_cache: dots\", tm) profiler.add_count(\"compute_dproduct_cache: dots\") scale =", "arguments \"\"\" tm = _time.time() old_err = _np.seterr(over='ignore') rho, E = self._rhoE_from_spamTuple(spamTuple) _fas(prMxToFill,", "scaleVals[gInds], wrtSlice1, wrtSlice2), add=sumInto) _np.seterr(**old_err) #Set wrtBlockSize to use available processors if it", "sequences. Returns ------- int \"\"\" return int(1.3 * nCircuits) def construct_evaltree(self, simplified_circuits, numSubtreeComms):", "Divide columns into blocks of at most blkSize assert(wrtFilter is None) # cannot", "strToPrint = str(circuit[0:10]) + \" ... (len %d)\" % len(circuit) _warnings.warn(\"pr(%s) == nan\"", "d2pr_dOps2[0, i, j] = float(_np.dot(E, _np.dot(d2prod_dGates[i, j], rho))) old_err = _np.seterr(over='ignore') prod, scale", "bool when set to True, additionally return the derivative of the probability. clipTo", "of groups to divide the first-derivative parameters into. Computation will be automatically parallelized", "mxToFill[felInds] (axis=0) if prMxToFill is not None: _mpit.gather_indices(subtreeElementIndices, subTreeOwners, prMxToFill, [], 0, comm)", "operation sequence dGs1 = evalTree.final_view(dProdCache1, axis=0) dGs2 = evalTree.final_view(dProdCache2, axis=0) #shape == (", "argument is used internally for distributing derivative calculations across multiple processors. Returns -------", "= [t.final_element_indices(evalTree) for t in subtrees] _mpit.gather_indices(subtreeElementIndices, subTreeOwners, mxToFill, [], 0, comm) #note:", "objects to perform product and derivatives-of-product calculations. This is contained in a class", ") def doperation(self, opLabel, flat=False, wrtFilter=None): \"\"\" Return the derivative of a length-1", "split because there's no good way to reconstruct the # *non-final* parent-tree elements", "tree of gate strings. Similar to `bulk_fill_probs(...)`, but fills a 3D array with", "matrix for each given (i,j) # noqa # d2prod/d(opLabel1)_kl*d(opLabel2)_ij = sum_{M s.t. GM", "list of Circuits or tuples of operation labels which specify the operation sequences", "include instrument elements like 'Imyinst_0') returnPr : bool when set to True, additionally", "the number of model params or wrtFilter1 or 2, respectively - G ==", "hessian[0,j,k] is the derivative of the probability w.r.t. the k-th then the j-th", "dProdCache[i] = _np.dot(dL, R) + \\ _np.swapaxes(_np.dot(L, dR), 0, 1) # dot(dS, T)", "of flattened_dprod. _fas(flattened_hprod, [None, gpindices1, gpindices2], gate.hessian_wrt_params(op_wrtFilter1, op_wrtFilter2)) if flat: return flattened_hprod else:", "reversed(revOpLabelList): G = _np.dot(self.sos.get_operation(opLabel).todense(), G) rightProdsT.append(_np.transpose(G)) # Allocate memory for the final result", "tree (skip over the zero and single-gate-strings) for i in evalTree.get_evaluation_order(): tm =", "# d2pr_dErhos[i,J0+J,K0+K] = dot(dEPT,prod,drhoP)[J,i,K] # d2pr_dErhos[i,J0+J,K0+K] = swapaxes(dot(dEPT,prod,drhoP),0,1)[i,J,K] # d2pr_dErhos[:,J0+J,K0+K] = swapaxes(dot(dEPT,prod,drhoP),0,1)[:,J,K] d2pr_dErhos1", "speed could be obtained\" \" by giving dproduct cache computation\" \" *fewer* processors", "with the License. You may obtain a copy of the License at #", "= clip(hGs,-1e300,1e300) _np.seterr(**old_err) if flat: hGs = _np.rollaxis(_np.rollaxis(hGs, 0, 3).reshape( (nDerivCols1, nDerivCols2, nCircuits", "bulk_evaltree # in order to associate the right single-gate-strings w/indices wrtIndices = _slct.indices(wrtSlice)", "rho)), axis=(0, 4)) * scaleVals[:, None, None] _np.seterr(**old_err2) # may overflow, but OK", "MatrixForwardSimulator(self.dim, self.sos, self.paramvec) def product(self, circuit, bScale=False): \"\"\" Compute the product of a", "rho, E, Gs, dGs, scaleVals, wrtSlice=None): if self.evotype == \"statevec\": raise NotImplementedError(\"Unitary evolution", "POINT1\"); profiler.comm.barrier() #evaluate operation sequences using tree (skip over the zero and single-gate-strings)", "used for product computation\") pass # this is a fairly common occurrence, and", "N - 1)])), dop_dopLabel2[opLabel2]) # above: (nDerivCols1,dim**2,dim**2) * (dim**2,nDerivCols2) = (nDerivCols1,dim**2,nDerivCols2) flattened_d2prod[:, inds1,", "the reversed order of the tuple. That is, the first element of circuit", "*second* derivative is taken. If there are more processors than model parameters, distribution", "# like length>1 lists do... ugh. relevant_gpindices = slice(relevant_gpindices[0], relevant_gpindices[0] + 1) elif", "* _np.transpose(_np.dot(prod, rho)) # may overflow, but OK _fas(dpr_dEs, [0, EVec.gpindices], _np.dot(derivWrtAnyEvec, EVec.deriv_wrt_params()))", "vec( X ) # if vec(.) stacks columns # vec( A * E(0,1)", "is first done over the set of parameters being differentiated with respect to", "tuple-like object of *simplified* gates (e.g. may include instrument elements like 'Imyinst_0') clipTo", "the far right of the product of matrices. Parameters ---------- circuit : Circuit", "dR2 = dProdCache2[iLeft], dProdCache2[iRight] hL, hR = hProdCache[iLeft], hProdCache[iRight] # Note: L, R", "== no gate hProdCache[i] = _np.zeros(hessn_shape) elif not self.sos.get_operation(opLabel).has_nonzero_hessian(): #all gate elements are", "; hL,hR = vgs x vgs x GxG dLdRa = _np.swapaxes(_np.dot(dL1, dR2), 1,", "obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 or in the LICENSE", "the i-th model parameter. * if flat == True, a N x M", "_mpit.distribute_slice(allDeriv1ColSlice, comm) # Get slice into entire range of model params so that", "of the probabilities generated by a each gate sequence given by evalTree column-by-column.", "as the final block size. This argument must be None if wrtFilter is", "assert(hGs.shape[1] == nDerivCols1), \"hGs must be pre-filtered!\" assert(hGs.shape[2] == nDerivCols2), \"hGs must be", "= self.sos.get_operation(opLabel) op_wrtFilter, gpindices = self._process_wrtFilter(wrtFilter, gate) # Allocate memory for the final", "\"filter\" object containing info about the mapping # of prep and effect parameters", "G = self.product(circuit, False) if self.evotype == \"statevec\": ps = _np.real(_np.abs(_np.dot(Es, _np.dot(G, rho)))**2)", "_dummy_profiler = _DummyProfiler() # Smallness tolerances, used internally for conditional scaling required #", "wrtFilter1 is not None: assert(wrtBlockSize1 is None and wrtBlockSize2 is None) # Cannot", "i in range(len(self.effects)+1) ] # global_e_slices = [ slice(tmp_offsets[i],tmp_offsets[i+1]) # for i in", "in a single flattened gate (ordered as numpy.flatten) - M == length of", "distributing the computation across multiple processors. Distribution is performed as in bulk_product, bulk_dproduct,", "deriv1MxToFill, deriv2MxToFill, mxToFill), evalSubTree, blocks1[iBlk1], blocks2[iBlk2], calc_and_fill) hProdCache = hGs = dProdCache2 =", "# vec( A * E(0,1) * B ) = vec( mx w/ col_i", "# arrays, these are SPAMVecs nCircuits = Gs.shape[0] rho_wrtFilter1, rho_gpindices1 = self._process_wrtFilter(wrtSlice1, self.sos.get_prep(rholabel))", "and spam tuple as a 1 x M x M array, where M", "both wrtFilter and wrtBlockSize wrtSlice2 = _slct.list_to_slice(wrtFilter2) else: wrtSlice2 = None #get distribution", "G(L-1) dG(L)/dij G(L+1) ... GN ] , a matrix for each given (i,j)", "(dim2, nDerivCols1, nDerivCols2); # swapaxes takes (kl,vec_prod_indx,ij) => (vec_prod_indx,kl,ij) elif l < m:", "no support for \"custom\" spamlabels... # This calculator uses the convention that rho", "derivWrtAnyRhovec = scale * _np.dot(E, prod) # may overflow, but OK d2pr_d2rhos =", "nBlks={%d,%d}]\" % (blkSize1, blkSize2, nBlks1, nBlks2)) # pragma: no cover # noqa for", "and find the labels in the string which match the current # gate", "not None: check_vhp = _np.concatenate( [self.hpr(spamTuple, circuit, False, False, clipTo) for circuit in", "[blkSize = %.1f, nBlks=%d]\" % (blkSize, nBlks)) # pragma: no cover def calc_and_fill_blk(spamTuple,", "(_np.isinf(hGs)).nonzero()[0] ) == 0 ) #hGs = clip(hGs,-1e300,1e300) _np.seterr(**old_err) if flat: hGs =", "dProdCache2 = dProdCache1 if (wrtSlice1 == wrtSlice2) else \\ self._compute_dproduct_cache(evalTree, prodCache, scaleCache, comm,", "is performed. Returns ------- prods : numpy array Array of shape S x", "G(L-1)) tensor (G(L+1) ... GN)^T vec( dG(L)/dij ) ] # noqa # =", "number of computed elements (i.e. evalTree.num_final_elements()) evalTree : EvalTree given by a prior", ": numpy array Only returned when bReturnProds == True. An array of shape", "of opLabel LRproduct = _np.kron(leftProds[i], rightProdsT[N - 1 - i]) # (dim**2, dim**2)", "None]) # overflow OK # get d2pr_drhos where gate derivatives are wrt the", "rhoVec.deriv_wrt_params(rho_wrtFilter)), axis=(0,)) * scaleVals[:, None]) # may overflow, but OK # Get: dp_dEs[i,", "None # wrtFilter dictates block if blkSize is None: #Fill derivative cache info", "higher level. \"\"\" dim = self.dim #Note: previously, we tried to allow for", "blk_wrtSlice2) dGs2 = evalSubTree.final_view(dProdCache2, axis=0) hProdCache = self._compute_hproduct_cache( evalSubTree, prodCache, dProdCache1, dProdCache2, scaleCache,", "1) // np1 # ceiling(num_params / np1) wrtLen2 = (self.Np + np2 -", "rho_gpindices2), _np.swapaxes(_np.dot(_np.transpose(devec), dp_dAnyE), 0, 1)) # get d2pr_dEs where E derivatives are wrt", "else _slct.length(wrtSlice2) #flt1 = self._get_filter_info(wrtSlices1) #flt2 = self._get_filter_info(wrtSlices2) # GATE DERIVS (assume hGs", "GN)^T ]] # noqa # # So for each opLabel the matrix [", "= self.sos.get_effect(elabel) # arrays, these are SPAMVecs nCircuits = Gs.shape[0] rho_wrtFilter1, rho_gpindices1 =", "- inf anyway... d2pr_dOps2[_np.isnan(d2pr_dOps2)] = 0 # SPAM DERIVS (assume dGs1 and dGs2", "split). Returns ------- None \"\"\" #get distribution across subtrees (groups if needed) subtrees", "comm) #note: pass prMxToFill, dim=(KS,), so gather prMxToFill[felInds] (axis=0) profiler.add_time(\"MPI IPC\", tm) profiler.mem_check(\"bulk_fill_dprobs:", "_np.dot(dp_dAnyE, EVec.deriv_wrt_params(E_wrtFilter))) sub_vdp = dp_drhos + dp_dEs + dp_dOps return sub_vdp #def _get_filter_info(self,", "dim * dim # product cache # mem += cache_size # scale cache", "PrepEffectFilter(rho_local_slices=loc_rho_slices, # rho_global_slices=global_rho_slices, # e_local_slices=loc_e_slices, # e_global_slices=global_e_slices, # num_rho_params=self.tot_rho_params, # num_e_params=self.tot_e_params) def _hprobs_from_rhoE(self,", "if flat: hGs = _np.rollaxis(_np.rollaxis(hGs, 0, 3).reshape( (nDerivCols1, nDerivCols2, nCircuits * dim**2)), 2)", "j-th model parameters. derivs1, derivs2 : numpy array Only returned if bReturnDProdsAndProds ==", "vectors should be dim x 1. gates, preps, effects : OrderedDict Ordered dictionaries", "simplified_circuits : list A list of Circuits or tuples of operation labels which", "free mem def _fill_result_tuple(self, result_tup, evalTree, param_slice1, param_slice2, calc_and_fill_fn): \"\"\" This function takes", "subtreeElementIndices = [t.final_element_indices(evalTree) for t in subtrees] _mpit.gather_indices(subtreeElementIndices, subTreeOwners, mxToFill, [], 0, comm,", "(mxToFill.nbytes / (1024.0**3))) ## memory profiling of python objects (never seemed very useful", "_np.seterr(over='ignore') rho, E = self._rhoE_from_spamTuple(spamTuple) if prMxToFill is not None: _fas(prMxToFill, [fInds], self._probs_from_rhoE(", "parameter groups. num_param1_groups : int The number of groups to divide the first-derivative", "vp[iFinal] = float(dot(E, dot(G, rho))) # vp[i] = sum_k,l E[0,k] Gs[i,k,l] rho[l,0] *", "(= [0,:,:]) d2pr_dEs = _np.zeros((1, self.Np, self.Np)) derivWrtAnyEvec = _np.squeeze(_np.dot(dprod_dOps, rho), axis=(2,)) _fas(d2pr_dEs,", "loop completion # (to save mem) but isn't gathered until now (but using", "that will be passed to the functions named by `subcalls`. num_subtrees : int", "= self.sos.get_operation(l) gate_wrtFilters1[l], gpindices1[l] = self._process_wrtFilter(wrtFilter1, used_operations[l]) gate_wrtFilters2[l], gpindices2[l] = self._process_wrtFilter(wrtFilter2, used_operations[l]) #Cache", "dim) # (reshape without copying - throws error if copy is needed) y", "Compute the Hessian of a probability generated by a operation sequence and spam", "# may generate overflow, but OK _fas(d2pr_dErhos, [0, EVec.gpindices, self.sos.get_prep(rholabel).gpindices], _np.dot(_np.transpose(EVec.deriv_wrt_params()), derivWrtAnyEvec)) #Note:", "a split tree. \"\"\" dim = self.dim # Note: dProdCache?.shape = (#circuits,#params_to_diff_wrt,dim,dim) nDerivCols1", "only that gate's parameters and fill the appropriate # columns of flattened_dprod. uniqueOpLabels", "shape S such that scaleVals[i] contains the multiplicative scaling needed for the derivatives", "deriv1MxToFill, mxToFill, clipTo) def bulk_hprobs_by_block(self, evalTree, wrtSlicesList, bReturnDProbs12=False, comm=None): \"\"\" Constructs a generator", "since we're # assuming that the gates are at most linear in their", "dot(squeeze(dot(Gs, rho),2), dEP)[i,J] # dp_dEs[:,J0+J] = dot(squeeze(dot(Gs, rho),axis=(2,)), dEP)[:,J] dp_dEs = _np.zeros((nCircuits, nDerivCols))", "scaleVals) if bScale else dGs def bulk_hproduct(self, evalTree, flat=False, bReturnDProdsAndProds=False, bScale=False, comm=None, wrtFilter1=None,", "the multiplicative scaling needed for the derivatives and/or products for the i-th operation", "evalTree's initial single- or zero-operation labels wrtIndices1 = _slct.indices(wrtSlice1) if (wrtSlice1 is not", "there's no good way to reconstruct the # *non-final* parent-tree elements from those", "internally for distributing derivative calculations across multiple processors. Returns ------- deriv : numpy", "S*N x M x M where - N == the number of entries", "check: self._check(evalTree, mxToFill, clipTo=clipTo) def bulk_fill_dprobs(self, mxToFill, evalTree, prMxToFill=None, clipTo=None, check=False, comm=None, wrtFilter=None,", "= _np.empty((1, self.Np, self.Np)) for i in range(self.Np): for j in range(self.Np): d2pr_dOps2[0,", "tensor (G(L+1) ... GN)^T vec( dG(L)/dij ) ] # noqa # = sum{...}", "is not None: _np.clip(mxToFill, clipTo[0], clipTo[1], out=mxToFill) # in-place clip if check: self._check(evalTree,", "product of gates, starting with identity scale_exp += ex # scale and keep", "numpy.linalg as _nla import time as _time import itertools as _itertools import collections", "operation sequences when a *split* evalTree is given, otherwise no parallelization is performed.", "#elif fnName == \"bulk_dproduct\": # mem += cache_size * num_params * dim *", "An auto-gator object that may be used to construct virtual gates for use", "where - N == the number of entries in a single flattened gate", "well!).\") return hProdCache ## END CACHE FUNCTIONS def default_distribute_method(self): \"\"\" Return the preferred", "mySubComm is not None and mySubComm.Get_size() > 1: deriv2Slices, myDeriv2ColSlice, deriv2Owners, mySubSubComm =", "prodCache, scaleCache def _compute_dproduct_cache(self, evalTree, prodCache, scaleCache, comm=None, wrtSlice=None, profiler=None): \"\"\" Computes a", "linear dimension of a operation matrix (G x G operation matrices). scaleValues :", "== True. A length-S array specifying the scaling that needs to be applied", "is used internally for distributing derivative calculations across multiple processors. Returns ------- hessians", "matrices are multiplied in the reversed order of the tuple. That is, the", "maximum number of derivative columns to compute *products* for simultaneously. None means compute", "of the (i / G^2)-th flattened operation sequence product with respect to the", "may overflow, but ok # may overflow or get nans (invalid), but ok", "the products within decent # bounds #assert( len( (_np.isnan(hGs)).nonzero()[0] ) == 0 )", "_compute_dproduct_cache called w/comm size %d\" % comm.Get_size()) # parallelize of deriv cols, then", "self.sos.get_effect(elabel)) E_wrtFilter2, E_gpindices2 = self._process_wrtFilter(wrtSlice2, self.sos.get_effect(elabel)) nDerivCols1 = self.Np if wrtSlice1 is None", "= dprobs1 deriv2MxToFill = dprobs2 mxToFill = hprobs #Fill arrays self._fill_result_tuple((None, dprobs1, dprobs2,", "tensor B^T * vec( X ) # if vec(.) stacks columns # vec(", "2, 1)) else: d2pr_dErhos2 = _np.zeros((nCircuits, nDerivCols2, nDerivCols1)) drho = rhoVec.deriv_wrt_params(rho_wrtFilter1) dp_dAnyE =", "or scaled product of the operation matrices. scale : float Only returned when", "#hGs = clip(hGs,-1e300,1e300) _np.seterr(**old_err) if flat: hGs = _np.rollaxis(_np.rollaxis(hGs, 0, 3).reshape( (nDerivCols1, nDerivCols2,", "= self._rhoE_from_spamTuple(spamTuple) if prMxToFill is not None: _fas(prMxToFill, [fInds], self._probs_from_rhoE( rho, E, Gs[gInds],", "make use of a tree being # split because there's no good way", "with respect to (see wrtBlockSize). wrtFilter : list of ints, optional If not", "(len(circuit_list),) ; may overflow but OK def _dprobs_from_rhoE(self, spamTuple, rho, E, Gs, dGs,", "G/(dij)^2 == 0, which is true IF each operation matrix element # is", "EVec.deriv_wrt_params(E_wrtFilter))) sub_vdp = dp_drhos + dp_dEs + dp_dOps return sub_vdp #def _get_filter_info(self, wrtSlices):", "nonzero gate hessians (memory?) hop_dopLabels = {} for opLabel, gate in used_operations.items(): if", "M == the length of the vectorized model - G == the linear", "prodCache[i] = _np.dot(L, R) scaleCache[i] = scaleCache[iLeft] + scaleCache[iRight] if prodCache[i].max() < PSMALL", "evalTree.get_evaluation_order(): # combine iLeft + iRight => i # LEXICOGRAPHICAL VS MATRIX ORDER", "If there are more processors than model parameters, distribution over a split evalTree", "into the (tree-) list of # all of the raw operation sequences which", "(if it is split), and then over blocks (subsets) of the parameters being", "self._scaleExp(evalSubTree.final_view(scaleCache)) Gs = evalSubTree.final_view(prodCache, axis=0) # ( nCircuits, dim, dim ) def calc_and_fill(spamTuple,", "G(L) == oplabel} [ (G1 ... G(L-1)) tensor (G(L+1) ... GN)^T ]] #", "than or greater than `cacheSize`) the tree will hold. Returns ------- int The", "blocks[iBlk] dProdCache = self._compute_dproduct_cache(evalSubTree, prodCache, scaleCache, blkComm, block_wrtSlice, profiler) profiler.add_time(\"bulk_fill_dprobs: compute_dproduct_cache\", tm) profiler.mem_check(", "iLeft) = evalTree[i] L, R = prodCache[iLeft], prodCache[iRight] prodCache[i] = _np.dot(L, R) scaleCache[i]", "else: raise ValueError(\"Unknown subcall name: %s\" % fnName) return mem * FLOATSIZE def", "3).reshape( (nDerivCols1, nDerivCols2, nCircuits * dim**2)), 2) # cols = deriv cols, rows", "(gate_ij, prod_row, prod_col) return _np.swapaxes(flattened_dprod, 0, 1).reshape((num_deriv_cols, dim, dim)) def hproduct(self, circuit, flat=False,", "derivWrtAnyEvec = scale * _np.transpose(_np.dot(prod, rho)) # may overflow, but OK # (**", "but OK d2pr_d2Es = _np.zeros((1, self.Np, self.Np)) _fas(d2pr_d2Es, [0, self.sos.get_effect(elabel).gpindices, self.sos.get_effect(elabel).gpindices], _np.tensordot(derivWrtAnyEvec, self.sos.get_effect(elabel).hessian_wrt_params(),", "operation labels The sequence of operation labels. flat : bool, optional Affects the", "R) + \\ _np.swapaxes(_np.dot(L, dR), 0, 1) # dot(dS, T) + dot(S, dT)", "bReturnDProbs12 : boolean, optional If true, the generator computes a 2-tuple: (hessian_col, d12_col),", "= None #Fill product cache info (not requiring row or column distribution) prodCache,", "= self.Np if wrtSlice is None else _slct.length(wrtSlice) # GATE DERIVS (assume dGs", "a specified slice of the values for this spam label (given by the", "# may overflow, but OK # Get: dp_dEs[i, E_gpindices] = dot(transpose(dE/dEP),Gs[i],rho)) # dp_dEs[i,J0+J]", "# d2prod/d(opLabel1)_kl*d(opLabel2)_ij = sum_{M s.t. GM == gatelabel1} sum_{L s.t. GL == gatelabel2,", "rightProdsT[N - 1 - i]) # (dim**2, dim**2) _fas(flattened_dprod, [None, gpindices], _np.dot(LRproduct, dop_dopLabel),", "and/or products for the i-th operation sequence. \"\"\" dim = self.dim nDerivCols1 =", "x dim, and all SPAM vectors should be dim x 1. gates, preps,", "dProdCache def _compute_hproduct_cache(self, evalTree, prodCache, dProdCache1, dProdCache2, scaleCache, comm=None, wrtSlice1=None, wrtSlice2=None): \"\"\" Computes", "#shape == ( len(circuit_list), nDerivColsX, dim, dim ), # dGs[i] is dprod_dOps for", "parallelization is performed. Returns ------- prods : numpy array Array of shape S", "hessians, derivatives, and/or products for the i-th operation sequence. \"\"\" dim = self.dim", "the Hessian at a time. For example, the Hessian of a function of", "automatically parallelized over these groups. num_final_strs : int The number of final strings", "everything else return (dGs, Gs, scaleVals) if bScale else (dGs, Gs) else: dGs", "#elif fnName == \"bulk_product\": # mem += cache_size * dim * dim #", "w/\"custom\" spam label... rho, E = self._rhoE_from_spamTuple(spamTuple) rhoVec = self.sos.get_prep(rholabel) # distinct from", "about the mapping # of prep and effect parameters onto a final \"filtered\"", "2nd set of gate parameters if dGs1 is dGs2 and wrtSlice1 == wrtSlice2:", "None) else len(wrtFilter) flattened_dprod = _np.zeros((dim**2, num_deriv_cols), 'd') _fas(flattened_dprod, [None, gpindices], gate.deriv_wrt_params(op_wrtFilter)) #", "numpy.ndarray An array of floating-point probabilities, corresponding to the elements of `elabels`. \"\"\"", "cache calc.\") hProdCache = _np.zeros((cacheSize,) + hessn_shape) #First element of cache are given", "rho ) ), axis=(0,3)) old_err2 = _np.seterr(invalid='ignore', over='ignore') dp_dOps = _np.squeeze(_np.dot(E, _np.dot(dGs, rho)),", "(\"statevec\", \"densitymx\"): raise ValueError((\"Evolution type %s is incompatbile with \" \"matrix-based calculations\" %", "0 for i in evalTree.get_evaluation_order(): # combine iLeft + iRight => i #", "] # # loc_e_slices = [ # _slct.shift(_slct.intersect( # wrtSlices['effects'], # slice(self.e_offset[i],self.e_offset[i+1])), #", "similar to bulk_fill_dprobs(...), but where M is the number of model parameters selected", "G x G array, where: - M == length of the vectorized model", "_warnings.warn(\"Increased speed could be obtained\" \" by giving dproduct cache computation\" \" *fewer*", "track owners #if mySubSubComm.Get_rank() > 0: myDeriv2ColSlice = slice(0,0) # #don't compute anything", "in bytes: TODO: a better way dim = self.dim nspam = int(round(_np.sqrt(self.dim))) #", "None and wrtSlice1.start is not None: myHessianSlice1 = _slct.shift(myDeriv1ColSlice, wrtSlice1.start) else: myHessianSlice1 =", "False, an array of shape S x M x M x G x", "list of the names of the subcalls to estimate memory usage for. cache_size", "== True, an array of shape S*N x M x M where -", "slice(None), slice(None), calc_and_fill) #collect/gather results subtreeElementIndices = [t.final_element_indices(evalTree) for t in subtrees] _mpit.gather_indices(subtreeElementIndices,", "2nd (col) derivatives to compute *products* for simultaneously. None means compute all requested", "This use of # closures seems confusing and we should do something else", "evalSubTree, slice(None), slice(None), calc_and_fill_p) profiler.mem_check(\"bulk_fill_dprobs: post fill probs\") #distribute derivative computation across blocks", "nParams[opLabel]) if flat: return flattened_dprod else: # axes = (gate_ij, prod_row, prod_col) return", "scaleCache, comm, wrtSlice1) dGs1 = evalTree.final_view(dProdCache1, axis=0) last_wrtSlice1 = wrtSlice1 if (wrtSlice1 ==", "mySubComm, wrtSlice, profiler) dGs = evalSubTree.final_view(dProdCache, axis=0) #( nCircuits, nDerivCols, dim, dim )", "this file except # in compliance with the License. You may obtain a", "# (dim**2, nParams[opLabel]) if flat: return flattened_dprod else: # axes = (gate_ij, prod_row,", "- 1)]), prods[(m + 1, N - 1)]) # (dim**2, dim**2) # (nDerivCols1,nDerivCols2,dim**2)", "== nDerivCols1), \"hGs must be pre-filtered!\" assert(hGs.shape[2] == nDerivCols2), \"hGs must be pre-filtered!\"", "range(len(self.effects))] # tmp_num_params = [_slct.length(s) for s in loc_e_slices] # tmp_offsets = [", "== num_deriv_cols1, num_deriv_cols2 return _np.rollaxis(flattened_d2prod, 0, 3).reshape((vec_kl_size, vec_ij_size, dim, dim)) # axes =", "= %g\" % (_nla.norm(hprMxToFill[fInds]), _nla.norm(check_vhp), _nla.norm(hprMxToFill[fInds] - check_vhp))) # pragma: no cover def", "yet!\") # pr = Tr( |rho><E| * prod ) = sum E_k prod_kl", "= 8 # in bytes: TODO: a better way dim = self.dim nspam", "number of parameter rows (the length of rowSlice) - B' is the number", "already sized/filtered) ------------------- assert(hGs.shape[1] == nDerivCols1), \"hGs must be pre-filtered!\" assert(hGs.shape[2] == nDerivCols2),", "= None # free mem def _fill_result_tuple(self, result_tup, evalTree, param_slice1, param_slice2, calc_and_fill_fn): \"\"\"", "Profiler, optional A profiler object used for to track timing and memory usage.", "= self._process_wrtFilter(wrtSlice, self.sos.get_effect(elabel)) nDerivCols = self.Np if wrtSlice is None else _slct.length(wrtSlice) #", "def _fill_result_tuple(self, result_tup, evalTree, param_slice1, param_slice2, calc_and_fill_fn): \"\"\" This function takes a \"calc-and-fill\"", "wrtSlice1, wrtSlice2 in wrtSlicesList: if wrtSlice1 != last_wrtSlice1: dProdCache1 = dGs1 = None", "_slct.list_to_slice(wrtFilter) if (wrtFilter is not None) else None #TODO: just allow slices as", "True, additionally return the probability itself. returnDeriv : bool when set to True,", "scale cache mem += cache_size # scale vals elif fnName == \"bulk_fill_hprobs\": mem", "below). comm : mpi4py.MPI.Comm, optional When not None, an MPI communicator for distributing", "to the resulting products (final_product[i] = scaleValues[i] * prods[i]). \"\"\" prodCache, scaleCache =", "rho_wrtFilter2)) else: d2pr_d2rhos = 0 if self.sos.get_effect(elabel).has_nonzero_hessian(): dp_dAnyE = _np.dot(Gs, rho).squeeze(2) * scaleVals[:,", "block_wrtSlice), add=sumInto) _np.seterr(**old_err) profiler.add_time(\"bulk_fill_dprobs: calc_and_fill_blk\", tm) for iBlk in myBlkIndices: tm = _time.time()", "not fully supported yet!\") # pr = Tr( |rho><E| * prod ) =", "prod managable.\") elif _np.count_nonzero(dProdCache[i]) and dProdCache[i].max() < DSMALL and dProdCache[i].min() > -DSMALL: _warnings.warn(\"Would", "- S == len(circuit_list) - M == the number of model params or", "the first-derivative parameters into. Computation will be automatically parallelized over these groups. num_param2_groups", "drho = rhoVec.deriv_wrt_params(rho_wrtFilter2) d2pr_drhos1 = _np.zeros((nCircuits, nDerivCols1, nDerivCols2)) _fas(d2pr_drhos1, [None, None, rho_gpindices2], _np.squeeze(_np.dot(_np.dot(E,", "ok _np.seterr(**old_err) return Gs def bulk_dproduct(self, evalTree, flat=False, bReturnProds=False, bScale=False, comm=None, wrtFilter=None): \"\"\"", "= [] G = _np.identity(dim); rightProdsT.append(_np.transpose(G)) for opLabel in reversed(revOpLabelList): G = _np.dot(self.sos.get_operation(opLabel).todense(),", "product cache calc.\") cacheSize = len(evalTree) prodCache = _np.zeros((cacheSize, dim, dim)) scaleCache =", "specify a well-defined column ordering when taking derivatives. paramvec : ndarray The parameter", "_DummyProfiler() # Smallness tolerances, used internally for conditional scaling required # to control", "_fas(mxToFill, [fInds, pslc1], self._dprobs_from_rhoE( spamTuple, rho, E, Gs[gInds], dGs[gInds], scaleVals[gInds], wrtSlice), add=sumInto) _np.seterr(**old_err)", "* _np.transpose(_np.dot(prod, rho)) # may overflow, but OK d2pr_d2Es = _np.zeros((1, self.Np, self.Np))", "derivative columns to compute *products* for simultaneously. None means compute all requested columns", "only returned if returnPr == True. \"\"\" if self.evotype == \"statevec\": raise NotImplementedError(\"Unitary", "[], 0, comm, gatherMemLimit) if prMxToFill is not None: _mpit.gather_indices(subtreeElementIndices, subTreeOwners, prMxToFill, [],", ": EvalTree given by a prior call to bulk_evaltree. Specifies the operation sequences", "use entirely different -- non-gate-local -- parameterizations of operation matrices and SPAM vectors)", "groups then subtrees (even == 1) in order to perform the parallelization over", "#shapes: rho = (N,1), Es = (len(elabels),N) if bUseScaling: old_err = _np.seterr(over='ignore') G,", "the sub-trees. _warnings.warn(\"Increased speed could be obtained\" \" by giving hproduct cache computation\"", "= _slct.shift(myDeriv1ColSlice, wrtSlice1.start) else: myHessianSlice1 = myDeriv1ColSlice #print(\"MPI: _compute_hproduct_cache over %d cols (rank", "(wrtLen1 + wrtLen2) * dim * dim # dproduct cache mem += cache_size", "False, a M x M x G x G numpy array, where: -", "else: # l==m, which we *used* to assume gave no contribution since we", "derivative columns, essentially taking # a derivative of only a *subset* of all", "a 2nd-deriv method in addition of deriv_wrt_params # # Note: unvec( X )", "operation matrices and SPAM vectors) access to these fundamental operations. \"\"\" def __init__(self,", "of the names of the subcalls to estimate memory usage for. cache_size :", "prMxToFill is not None: _fas(prMxToFill, [fInds], self._probs_from_rhoE(rho, E, Gs[gInds], scaleVals[gInds]), add=sumInto) if deriv1MxToFill", "as argument: wrtFilter -> wrtSlice? prodCache, scaleCache = self._compute_product_cache(evalTree, comm) dProdCache = self._compute_dproduct_cache(evalTree,", "dim, dim)) # axes = (gate_ij1, gateij2, prod_row, prod_col) def dproduct(self, circuit, flat=False,", "subtrees (groups if needed) subtrees = evalTree.get_sub_trees() mySubTreeIndices, subTreeOwners, mySubComm = evalTree.distribute(comm) #if", "None #Fill product cache info (not requiring row or column distribution) prodCache, scaleCache", "of the Hessian, so that # if gl1 and gl2 are both in", "more cpus than hessian elements.\") # pragma: no cover # allocate final result", "2) y = _np.dot(_np.kron(prods[(0, l - 1)], xv), dop_dopLabel2[opLabel2]) # above: (nDerivCols1,dim**2,dim**2) *", "is not None. Returns ------- hessian : numpy array a 1 x M", "_np.concatenate(all_results, axis=1) # TODO: remove this concat w/better gather? # ------------------------------------------------------------------ tSerialStart =", "dprobs2 mxToFill = hprobs #Fill arrays self._fill_result_tuple((None, dprobs1, dprobs2, hprobs), evalTree, slice(None), slice(None),", "than model parameters, distribution over a split evalTree (if given) is possible. wrtFilter1,", "deriv cols\" % nDerivCols) if comm is not None and comm.Get_size() > 1:", "None as comm, *not* mySubComm, since we can't do any # further parallelization", "probabilities corresponding to the *simplified* operation sequences found in an evaluation tree, `evalTree`.", "size %d\" % comm.Get_size()) # parallelize of deriv cols, then sub-trees (if available", "deriv2Slices, myDeriv2ColSlice, deriv2Owners, mySubSubComm = \\ _mpit.distribute_slice(allDeriv2ColSlice, mySubComm) # Get slice into entire", "dim # product cache mem += cache_size # scale cache mem += cache_size", "form of the above matrices, so that # each column corresponds to a", "tm) for iBlk in myBlkIndices: tm = _time.time() block_wrtSlice = blocks[iBlk] dProdCache =", "dop_dopLabel2 = dop_dopLabel1 else: dop_dopLabel2 = { opLabel: gate.deriv_wrt_params(gate_wrtFilters2[opLabel]) for opLabel, gate in", "respectively. Must be *ordered* dictionaries to specify a well-defined column ordering when taking", "a single flattened gate (ordering is the same as that used by numpy.flatten),", "assert(wrtFilter1 is None and wrtFilter2 is None) # cannot specify both wrtFilter and", "an inf scaleVal is mult by a zero hessian value (see below) hGs[_np.isnan(hGs)]", "# in this software. # Licensed under the Apache License, Version 2.0 (the", "in conjuction with wrtBlockSize. wrtBlockSize : int or float, optional The maximum number", "> 1): comm_blkSize = self.Np / mySubComm.Get_size() blkSize = comm_blkSize if (blkSize is", "1)])), dop_dopLabel2[opLabel2]) # above: (nDerivCols1,dim**2,dim**2) * (dim**2,nDerivCols2) = (nDerivCols1,dim**2,nDerivCols2) flattened_d2prod[:, inds1, inds2] +=", "(see below). wrtFilter : list of ints, optional If not None, a list", "be pre-filtered!\" # Get: d2pr_drhos[i, j, rho_gpindices] = dot(E,dGs[i,j],drho/drhoP)) # d2pr_drhos[i,j,J0+J] = sum_kl", "self._process_wrtFilter(wrtFilter1, used_operations[l]) gate_wrtFilters2[l], gpindices2[l] = self._process_wrtFilter(wrtFilter2, used_operations[l]) #Cache partial products (relatively little mem", "total number of computed elements (i.e. evalTree.num_final_elements()) and M1 & M2 are the", "sequence. \"\"\" nCircuits = evalTree.num_final_strings() nDerivCols = self.Np if (wrtFilter is None) else", "across blocks myBlk1Indices, blk1Owners, blk1Comm = \\ _mpit.distribute_indices(list(range(nBlks1)), mySubComm) myBlk2Indices, blk2Owners, blk2Comm =", "(self.Np**2) + \" [blkSize = {%.1f,%.1f}, nBlks={%d,%d}]\" % (blkSize1, blkSize2, nBlks1, nBlks2)) #", "needed to perform a hessian calculation (i.e. for l==m) then # it could", "* scaleVals[:, None, None]) # overflow OK # get d2pr_drhos where gate derivatives", "dim=(KS,), so gather prMxToFill[felInds] (axis=0) profiler.add_time(\"MPI IPC\", tm) profiler.mem_check(\"bulk_fill_dprobs: post gather subtrees\") if", "== (len(circuit_list), nDerivCols) # may also give invalid value due to scaleVals being", "derivative columns(%d)!\" % self.Np + \" [blkSize = %.1f, nBlks=%d]\" % (blkSize, nBlks))", "_np.zeros((nCircuits, nDerivCols2, nDerivCols1)) drho = rhoVec.deriv_wrt_params(rho_wrtFilter1) dp_dAnyE = _np.dot(Gs, drho) * scaleVals[:, None,", "cached data to construct return values Gs = evalTree.final_view(prodCache, axis=0) #shape == (", "how large all the storage arrays are. np1, np2 = num_param1_groups, num_param2_groups FLOATSIZE", ") can be done efficiently by actually computing X^T ( note (A tensor", "and single-gate-strings) #cnt = 0 for i in evalTree.get_evaluation_order(): # combine iLeft +", "but OK ; shape == (len(circuit_list), nDerivCols, nDerivCols) # may also give invalid", "HSMALL and hProdCache[i].min() > -HSMALL: _warnings.warn(\"Scaled hProd small in order to keep prod", "tuples of operation labels which specify the operation sequences to create an evaluation", "specifying the correspondence between rows of mxToFill and spam labels. evalTree : EvalTree", "> -HSMALL: _warnings.warn(\"Scaled hProd small in order to keep prod managable.\") elif _np.count_nonzero(hProdCache[i])", "-> d|pr|^2/dx = d(pr*pr.C)/dx = dpr/dx*pr.C + pr*dpr/dx.C # = 2 Re(dpr/dx*pr.C) ,", "0, 1) # dot(dS, T) + dot(S, dT) profiler.add_time(\"compute_dproduct_cache: dots\", tm) profiler.add_count(\"compute_dproduct_cache: dots\")", "nCircuits): \"\"\" Return an estimate of the ideal/desired cache size given a number", "s.t. GL == oplabel} [ G1 ... G(L-1) dG(L)/dij G(L+1) ... GN ]", "wrtSlice2: # TODO: better check for equivalence: maybe let dGs2 be None? assert(nDerivCols1", "circuit_list]) if _nla.norm(prMxToFill[fInds] - check_vp) > 1e-6: _warnings.warn(\"norm(vp-check_vp) = %g - %g =", "probability. clipTo : 2-tuple (min,max) to clip returned probability to if not None.", "set to True, additionally return the probability itself. returnDeriv : bool when set", "anything with it! #_warnings.warn(\"More processors than can be used for product computation\") pass", "# ------------------------------------------------------------------ if comm is not None and comm.Get_size() > 1: # parallelize", "_np.conjugate(_np.transpose(self.sos.get_effect(elabel).todense() [:, None])) # convention: E has shape (1,N) else: # a \"custom\"", "= hGs = dProdCache2 = dGs2 = None # free mem dProdCache1 =", "dictionary a dictionary with keys == spam labels and values which are integer", "+ dpr_dEs + dpr_dOps def hpr(self, spamTuple, circuit, returnPr, returnDeriv, clipTo): \"\"\" Compute", "len(wrtFilter1) num_deriv_cols2 = self.Np if (wrtFilter2 is None) else len(wrtFilter2) flattened_hprod = _np.zeros((dim**2,", "array Only returned if bReturnDProdsAndProds == True. * if flat == False, two", "= evalSubTree.final_view(prodCache, axis=0) # ( nCircuits, dim, dim ) def calc_and_fill(spamTuple, fInds, gInds,", "Es = (len(elabels),N) if bUseScaling: old_err = _np.seterr(over='ignore') G, scale = self.product(circuit, True)", "None if wrtFilter is not None. Set this to non-None to reduce amount", "jacobians (still relatively little mem required) dop_dopLabel1 = { opLabel: gate.deriv_wrt_params(gate_wrtFilters1[opLabel]) for opLabel,", "numpy ndarray an already-allocated 1D numpy array of length equal to the total", "not fully supported yet!\") # To support unitary evolution we need to: #", "else dGs1 = _np.swapaxes(_np.swapaxes(dGs1, 0, 1).reshape((nDerivCols1, nCircuits * dim**2)), 0, 1) # cols", "cols (%s) (rank %d computing %s)\" \\ # % (nDerivCols, str(allDerivColIndices), comm.Get_rank(), str(myDerivColIndices)))", "number of entries in a single flattened gate (ordering as numpy.flatten) - M", "tensor A * vec( X ) def doperation(self, opLabel, flat=False, wrtFilter=None): \"\"\" Return", "PSMALL = 1e-100 DSMALL = 1e-100 HSMALL = 1e-100 class MatrixForwardSimulator(ForwardSimulator): \"\"\" Encapsulates", "compute d2(prod)/d(gl1)d(gl2) # and not d2(prod)/d(gl2)d(gl1) ... if m < l: x0 =", "overflow OK devec = EVec.deriv_wrt_params(E_wrtFilter2) _fas(d2pr_dEs1, [None, None, E_gpindices2], _np.dot(dp_dAnyE, devec)) # get", "A tensor B^T * vec( X ) # if vec(.) stacks columns #", "dot( dGs, rho ) )[0,i,j,k,0] # d2pr_dOps2 = squeeze( dot( E, dot( dGs,", "out=mxToFill) # in-place clip if check: self._check(evalTree, mxToFill, clipTo=clipTo) def bulk_fill_dprobs(self, mxToFill, evalTree,", "model - G == the linear dimension of a operation matrix (G x", "= dGs2 = hGs = None prodCache = scaleCache = None #Fill product", "and in general only a specified slice of the values for this spam", "self.evotype == \"statevec\": raise NotImplementedError(\"Unitary evolution not fully supported yet!\") # To support", "= tuple(reversed(tuple(circuit))) N = len(revOpLabelList) # length of operation sequence # prod =", "gate in used_operations.items()} if wrtFilter1 == wrtFilter2: dop_dopLabel2 = dop_dopLabel1 else: dop_dopLabel2 =", "that accounts for the symmetry of the Hessian, so that # if gl1", "is mult by a zero deriv value (see below) dGs2[_np.isnan(dGs2)] = 0 #", "... G(L-1) dG(L)/dij G(L+1) ... GN ] , a matrix for each given", "sum E_k [dprod/d(opLabel)_ij]_kl rho_l # dpr/d(rho)_i = sum E_k prod_ki # dpr/d(E)_i =", "#check_ps = _np.array( [ self.pr( (rholabel,elabel), circuit, clipTo, bScale) for elabel in elabels", "since we assume all gate elements are at most # linear in the", "d2pr_drhos where gate derivatives are wrt the 2nd set of gate parameters if", "all requested rows or columns at once. The minimum of wrtBlockSize and the", "_np.swapaxes(_np.dot(dL2, dR1), 1, 2) dLdR_sym = dLdRa + _np.swapaxes(dLdRb, 0, 1) hProdCache[i] =", "nCircuits * dim**2)), 2) # as above return (hGs, scaleVals) if bScale else", "# for i in mySubTreeIndices]))) #eval on each local subtree #my_results = []", "evalSubTree.final_element_indices(evalTree) #Free memory from previous subtree iteration before computing caches scaleVals = Gs", "if abs(scale) > 1e-8: # _np.isclose(scale,0) is SLOW! hProdCache[i] /= _np.exp(scale) if hProdCache[i].max()", "opLabel2 in enumerate(revOpLabelList): inds2 = gpindices1[opLabel2] #nDerivCols2 = dop_dopLabel2[opLabel2].shape[1] # FUTURE: we could", "over subtrees of evalTree (if it is split). Returns ------- None \"\"\" #get", "rho, E, Gs, scaleVals): if self.evotype == \"statevec\": raise NotImplementedError(\"Unitary evolution not fully", "(wrtFilter2 is None) else _slct.length(wrtFilter2) nCircuits = evalTree.num_final_strings() # len(circuit_list) wrtSlice1 = _slct.list_to_slice(wrtFilter1)", "None. check : boolean, optional If True, perform extra checks within code to", "and spam tuple as a 1 x M numpy array, where M is", "product derivatives in a linear cache space. Will use derivative columns and then", "\"custom\" spamlabels... # This calculator uses the convention that rho has shape (N,1)", "# probability, with scaling applied (may generate overflow, but OK) ps = _np.real(_np.dot(Es,", "invalid='ignore') # may overflow or get nans (invalid), but ok dGs = _np.swapaxes(_np.swapaxes(dGs,", "length>1 lists do... ugh. relevant_gpindices = slice(relevant_gpindices[0], relevant_gpindices[0] + 1) elif len(relevant_gpindices) ==", "rho ) ), axis=(0,4)) old_err2 = _np.seterr(invalid='ignore', over='ignore') d2pr_dOps2 = _np.squeeze(_np.dot(E, _np.dot(hGs, rho)),", "_np.zeros(hessn_shape) else: hoperation = self.hoperation(opLabel, wrtFilter1=wrtIndices1, wrtFilter2=wrtIndices2) hProdCache[i] = hoperation / _np.exp(scaleCache[i]) #evaluate", "label (specified to it by the first two arguments), and in general only", "dProdCache2 = dProdCache1 if (wrtSlice1 == wrtSlice2) else \\ self._compute_dproduct_cache(evalSubTree, prodCache, scaleCache, mySubComm,", "size == blkSize1 or blkSize2 blocks1 = _mpit.slice_up_range(self.Np, nBlks1) blocks2 = _mpit.slice_up_range(self.Np, nBlks2)", "range(len(self.effects)+1) ] # global_e_slices = [ slice(tmp_offsets[i],tmp_offsets[i+1]) # for i in range(len(self.effects)) ]", "un-vectorized dim x dim mxs corresponding to a single kl xv = _np.swapaxes(xv,", "rho)), axis=(0, 2)) * scaleVals # shape == (len(circuit_list),) ; may overflow but", "PrepEffectFilter = _collections.namedtuple( # 'PrepEffectFilter', 'rho_local_slices rho_global_slices ' + # 'e_local_slices e_global_slices num_rho_params", "is an index into an array of gate parameters ordered by concatenating each", "G(M-1) tensor (G(M+1) ... GN)^T vec( d2G(M)/dkl*dji ) # noqa # # Note:", "= _np.zeros(hessn_shape) else: hoperation = self.hoperation(opLabel, wrtFilter1=wrtIndices1, wrtFilter2=wrtIndices2) hProdCache[i] = hoperation / _np.exp(scaleCache[i])", "*products* for simultaneously. None means compute all requested rows or columns at once.", "inf scaleVal is mult by a zero deriv value (see below) dGs[_np.isnan(dGs)] =", "1 - i]) # (dim**2, dim**2) _fas(flattened_dprod, [None, gpindices], _np.dot(LRproduct, dop_dopLabel), add=True) #", "# loop over locations of opLabel LRproduct = _np.kron(leftProds[i], rightProdsT[N - 1 -", "bScale=False, comm=None, wrtFilter=None): \"\"\" Compute the derivative of a many operation sequences at", "sequence product with respect to the k-th then j-th model parameters. derivs1, derivs2", "%g, norm %g, exp %g\\n%s\" % (i,p,norm(G),total_exp,str(G)) # if _np.isnan(p): raise ValueError(\"STOP\") if", "sum_j dEP[j,J] dot(Gs, rho)[i,j] # dp_dEs[i,J0+J] = sum_j dot(Gs, rho)[i,j,0] dEP[j,J] # dp_dEs[i,J0+J]", "comm since can't do anything with it! #_warnings.warn(\"More processors than can be used", "dpr/dx is the usual density-matrix-mode probability # (TODO in FUTURE) # pr =", "*split* evalTree is given, otherwise no parallelization is performed. Returns ------- prods :", "this software. # Licensed under the Apache License, Version 2.0 (the \"License\"); you", "of evalTree (if it is split). Returns ------- None \"\"\" #get distribution across", "(if available and necessary) if comm.Get_size() > nDerivCols1 * nDerivCols2: #If there are", "x G, where - S == len(circuit_list) - M == the length of", "Note: LinearOperator matrices are multiplied in the reversed order of the tuple. That", "probability generated by a operation sequence and spam tuple as a 1 x", "dim**2)), 0, 1) # cols = deriv cols, rows = flattened everything else", "beforehand), as there\" \" are more cpus than derivative columns.\") # Use comm", "of the Hessian at a time. For example, the Hessian of a function", "model parameters. \"\"\" # LEXICOGRAPHICAL VS MATRIX ORDER # we do matrix multiplication", "# Note: unvec( X ) can be done efficiently by actually computing X^T", "of the product of matrices. Parameters ---------- circuit : Circuit or tuple of", "arrays that are filled internally to `calc_and_fill_fn` must be the same as the", "if isinstance(wrtFilter, slice): wrtFilter = _slct.indices(wrtFilter) if wrtFilter is not None: obj_wrtFilter =", "yields the 3-tuple `(rowSlice, colSlice, hprobs)` or `(rowSlice, colSlice, dprobs12)` (the latter if", "gpindices1[opLabel2] #nDerivCols2 = dop_dopLabel2[opLabel2].shape[1] # FUTURE: we could add logic that accounts for", "2) * scaleVals, 0, 2) # may overflow, but ok # may overflow", "self._scaleExp(evalSubTree.final_view(scaleCache)) Gs = evalSubTree.final_view(prodCache, axis=0) #( nCircuits, dim, dim ) profiler.mem_check(\"bulk_fill_dprobs: post compute", "length-E numpy array that is filled with probabilities, just like in bulk_fill_probs(...). clipTo", "== oplabel} [ (G1 ... G(L-1)) tensor (G(L+1) ... GN)^T ]] * vec(", "array of shape S x M x G x G, where: - S", "length as fInds). calc_and_fill_fn(spamTuple, fInds, gInds, pslc1, pslc2, False) # TODO: remove SumInto", "1: _warnings.warn(\"Too many processors to make use of in \" \" _compute_dproduct_cache.\") if", "that are filled internally to `calc_and_fill_fn` must be the same as the elements", "# scale and keep track of exponent # # p = _mt.trace( _np.dot(self.SPAMs[spamLabel],G)", "#gather column results: gather axis 2 of mxToFill[felInds,blocks1[iBlk1]], dim=(ks,blk1,M) _mpit.gather_slices(blocks2, blk2Owners, mxToFill, [felInds,", "vary in their effect-label (their prep labels must be the same) Parameters ----------", "0, 1) # cols = deriv cols, rows = flattened everything else return", "all entries are zero except the (i,j) entry == 1 # if vec(.)", "and SPAMVec objects, respectively. Must be *ordered* dictionaries to specify a well-defined column", "float(_np.dot(E, _np.dot(dprod_dOps[i], rho))) #Derivs wrt SPAM if returnDeriv: # same as in dpr(...)", "and then (as needed) a split tree to parallelize computation, since there are", "dpr/d(E)_i = sum prod_il rho_l rholabel, elabel = spamTuple # can't deal w/\"custom\"", "parameters assert(opLabel1 == opLabel2) if opLabel1 in hop_dopLabels: # indicates a non-zero hessian" ]
[ "100 # check to see that every trading pair has candles for it", ": 300}, n=100000, verbose=True)) assert df.shape[0] > 100 # check to see that", "exchange_id, 'trading_pair': trading_pair, 'period' : 300}, n=100000, verbose=True)) assert df.shape[0] > 100 #", "api, 'exchange_id': exchange_id, 'trading_pair': trading_pair, 'period' : 300}, n=100000, verbose=True)) assert df.shape[0] >", "import cryptolytic.util as util import cryptolytic.data.historical as h def test_check_tables(): util.timeout(h.live_update, 10) for", "df.shape[0] > 100 # check to see that every trading pair has candles", "> 100 # check to see that every trading pair has candles for", "api, exchange_id, trading_pair in h.yield_unique_pair(): df = (sql.get_some_candles ({'api': api, 'exchange_id': exchange_id, 'trading_pair':", "cryptolytic.data.sql as sql import cryptolytic.util as util import cryptolytic.data.historical as h def test_check_tables():", "util import cryptolytic.data.historical as h def test_check_tables(): util.timeout(h.live_update, 10) for api, exchange_id, trading_pair", "h.yield_unique_pair(): df = (sql.get_some_candles ({'api': api, 'exchange_id': exchange_id, 'trading_pair': trading_pair, 'period' : 300},", "(sql.get_some_candles ({'api': api, 'exchange_id': exchange_id, 'trading_pair': trading_pair, 'period' : 300}, n=100000, verbose=True)) assert", "verbose=True)) assert df.shape[0] > 100 # check to see that every trading pair", "import cryptolytic.data.historical as h def test_check_tables(): util.timeout(h.live_update, 10) for api, exchange_id, trading_pair in", "<filename>tests/testing/test_check_data.py import cryptolytic.data.sql as sql import cryptolytic.util as util import cryptolytic.data.historical as h", "import cryptolytic.data.sql as sql import cryptolytic.util as util import cryptolytic.data.historical as h def", "cryptolytic.data.historical as h def test_check_tables(): util.timeout(h.live_update, 10) for api, exchange_id, trading_pair in h.yield_unique_pair():", "test_check_tables(): util.timeout(h.live_update, 10) for api, exchange_id, trading_pair in h.yield_unique_pair(): df = (sql.get_some_candles ({'api':", "exchange_id, trading_pair in h.yield_unique_pair(): df = (sql.get_some_candles ({'api': api, 'exchange_id': exchange_id, 'trading_pair': trading_pair,", "({'api': api, 'exchange_id': exchange_id, 'trading_pair': trading_pair, 'period' : 300}, n=100000, verbose=True)) assert df.shape[0]", "10) for api, exchange_id, trading_pair in h.yield_unique_pair(): df = (sql.get_some_candles ({'api': api, 'exchange_id':", "as h def test_check_tables(): util.timeout(h.live_update, 10) for api, exchange_id, trading_pair in h.yield_unique_pair(): df", "'period' : 300}, n=100000, verbose=True)) assert df.shape[0] > 100 # check to see", "util.timeout(h.live_update, 10) for api, exchange_id, trading_pair in h.yield_unique_pair(): df = (sql.get_some_candles ({'api': api,", "df = (sql.get_some_candles ({'api': api, 'exchange_id': exchange_id, 'trading_pair': trading_pair, 'period' : 300}, n=100000,", "300}, n=100000, verbose=True)) assert df.shape[0] > 100 # check to see that every", "trading_pair in h.yield_unique_pair(): df = (sql.get_some_candles ({'api': api, 'exchange_id': exchange_id, 'trading_pair': trading_pair, 'period'", "h def test_check_tables(): util.timeout(h.live_update, 10) for api, exchange_id, trading_pair in h.yield_unique_pair(): df =", "'exchange_id': exchange_id, 'trading_pair': trading_pair, 'period' : 300}, n=100000, verbose=True)) assert df.shape[0] > 100", "def test_check_tables(): util.timeout(h.live_update, 10) for api, exchange_id, trading_pair in h.yield_unique_pair(): df = (sql.get_some_candles", "trading_pair, 'period' : 300}, n=100000, verbose=True)) assert df.shape[0] > 100 # check to", "assert df.shape[0] > 100 # check to see that every trading pair has", "in h.yield_unique_pair(): df = (sql.get_some_candles ({'api': api, 'exchange_id': exchange_id, 'trading_pair': trading_pair, 'period' :", "as util import cryptolytic.data.historical as h def test_check_tables(): util.timeout(h.live_update, 10) for api, exchange_id,", "'trading_pair': trading_pair, 'period' : 300}, n=100000, verbose=True)) assert df.shape[0] > 100 # check", "sql import cryptolytic.util as util import cryptolytic.data.historical as h def test_check_tables(): util.timeout(h.live_update, 10)", "n=100000, verbose=True)) assert df.shape[0] > 100 # check to see that every trading", "for api, exchange_id, trading_pair in h.yield_unique_pair(): df = (sql.get_some_candles ({'api': api, 'exchange_id': exchange_id,", "= (sql.get_some_candles ({'api': api, 'exchange_id': exchange_id, 'trading_pair': trading_pair, 'period' : 300}, n=100000, verbose=True))", "cryptolytic.util as util import cryptolytic.data.historical as h def test_check_tables(): util.timeout(h.live_update, 10) for api,", "as sql import cryptolytic.util as util import cryptolytic.data.historical as h def test_check_tables(): util.timeout(h.live_update," ]
[ "enumerate(sorted_keys): count += counter[k] if count > mid: if d % 2 ==", "= compute_median(counter) if expenditure[i + d] >= 2 * median: count += 1", "i, k in enumerate(sorted_keys): count += counter[k] if count > mid: if d", "Counter(expenditure[:d]) for i in range(len(expenditure) - d): median = compute_median(counter) if expenditure[i +", "counter[k] if count > mid: if d % 2 == 1: return k", "count = 0 sorted_keys = sorted(counter.keys()) for i, k in enumerate(sorted_keys): count +=", "d = sum(counter.values()) mid = d // 2 count = 0 sorted_keys =", "for i in range(len(expenditure) - d): median = compute_median(counter) if expenditure[i + d]", "= 0 sorted_keys = sorted(counter.keys()) for i, k in enumerate(sorted_keys): count += counter[k]", "= sorted(counter.keys()) for i, k in enumerate(sorted_keys): count += counter[k] if count >", "expenditure[i + d] >= 2 * median: count += 1 counter[expenditure[i]] -= 1", "0 sorted_keys = sorted(counter.keys()) for i, k in enumerate(sorted_keys): count += counter[k] if", "mid: if d % 2 == 1: return k else: if counter[k] >", "i in range(len(expenditure) - d): median = compute_median(counter) if expenditure[i + d] >=", "+= counter[k] if count > mid: if d % 2 == 1: return", "mid = d // 2 count = 0 sorted_keys = sorted(counter.keys()) for i,", "+ d]] += 1 return count def compute_median(counter): d = sum(counter.values()) mid =", "= Counter(expenditure[:d]) for i in range(len(expenditure) - d): median = compute_median(counter) if expenditure[i", "= sum(counter.values()) mid = d // 2 count = 0 sorted_keys = sorted(counter.keys())", "count = 0 counter = Counter(expenditure[:d]) for i in range(len(expenditure) - d): median", "d]] += 1 return count def compute_median(counter): d = sum(counter.values()) mid = d", "median = compute_median(counter) if expenditure[i + d] >= 2 * median: count +=", "d % 2 == 1: return k else: if counter[k] > 1: return", "= d // 2 count = 0 sorted_keys = sorted(counter.keys()) for i, k", "collections import Counter def activity_notifications(expenditure, d): count = 0 counter = Counter(expenditure[:d]) for", "% 2 == 1: return k else: if counter[k] > 1: return k", "- d): median = compute_median(counter) if expenditure[i + d] >= 2 * median:", "for i, k in enumerate(sorted_keys): count += counter[k] if count > mid: if", "def activity_notifications(expenditure, d): count = 0 counter = Counter(expenditure[:d]) for i in range(len(expenditure)", "activity_notifications(expenditure, d): count = 0 counter = Counter(expenditure[:d]) for i in range(len(expenditure) -", "if expenditure[i + d] >= 2 * median: count += 1 counter[expenditure[i]] -=", "counter[k] > 1: return k else: return (k + sorted_keys[i - 1]) /", "0 counter = Counter(expenditure[:d]) for i in range(len(expenditure) - d): median = compute_median(counter)", "count += counter[k] if count > mid: if d % 2 == 1:", "counter = Counter(expenditure[:d]) for i in range(len(expenditure) - d): median = compute_median(counter) if", "> 1: return k else: return (k + sorted_keys[i - 1]) / 2", "range(len(expenditure) - d): median = compute_median(counter) if expenditure[i + d] >= 2 *", "counter[expenditure[i + d]] += 1 return count def compute_median(counter): d = sum(counter.values()) mid", "def compute_median(counter): d = sum(counter.values()) mid = d // 2 count = 0", "2 count = 0 sorted_keys = sorted(counter.keys()) for i, k in enumerate(sorted_keys): count", "k else: if counter[k] > 1: return k else: return (k + sorted_keys[i", "+= 1 counter[expenditure[i]] -= 1 counter[expenditure[i + d]] += 1 return count def", "d): count = 0 counter = Counter(expenditure[:d]) for i in range(len(expenditure) - d):", "Counter def activity_notifications(expenditure, d): count = 0 counter = Counter(expenditure[:d]) for i in", "import Counter def activity_notifications(expenditure, d): count = 0 counter = Counter(expenditure[:d]) for i", "in range(len(expenditure) - d): median = compute_median(counter) if expenditure[i + d] >= 2", "= 0 counter = Counter(expenditure[:d]) for i in range(len(expenditure) - d): median =", "-= 1 counter[expenditure[i + d]] += 1 return count def compute_median(counter): d =", "k in enumerate(sorted_keys): count += counter[k] if count > mid: if d %", "count > mid: if d % 2 == 1: return k else: if", "1 counter[expenditure[i]] -= 1 counter[expenditure[i + d]] += 1 return count def compute_median(counter):", "compute_median(counter): d = sum(counter.values()) mid = d // 2 count = 0 sorted_keys", "median: count += 1 counter[expenditure[i]] -= 1 counter[expenditure[i + d]] += 1 return", "2 * median: count += 1 counter[expenditure[i]] -= 1 counter[expenditure[i + d]] +=", "count += 1 counter[expenditure[i]] -= 1 counter[expenditure[i + d]] += 1 return count", "> mid: if d % 2 == 1: return k else: if counter[k]", "sum(counter.values()) mid = d // 2 count = 0 sorted_keys = sorted(counter.keys()) for", "1 return count def compute_median(counter): d = sum(counter.values()) mid = d // 2", "sorted(counter.keys()) for i, k in enumerate(sorted_keys): count += counter[k] if count > mid:", "return count def compute_median(counter): d = sum(counter.values()) mid = d // 2 count", "1: return k else: if counter[k] > 1: return k else: return (k", ">= 2 * median: count += 1 counter[expenditure[i]] -= 1 counter[expenditure[i + d]]", "+ d] >= 2 * median: count += 1 counter[expenditure[i]] -= 1 counter[expenditure[i", "counter[expenditure[i]] -= 1 counter[expenditure[i + d]] += 1 return count def compute_median(counter): d", "from collections import Counter def activity_notifications(expenditure, d): count = 0 counter = Counter(expenditure[:d])", "else: if counter[k] > 1: return k else: return (k + sorted_keys[i -", "== 1: return k else: if counter[k] > 1: return k else: return", "1 counter[expenditure[i + d]] += 1 return count def compute_median(counter): d = sum(counter.values())", "d): median = compute_median(counter) if expenditure[i + d] >= 2 * median: count", "if counter[k] > 1: return k else: return (k + sorted_keys[i - 1])", "count def compute_median(counter): d = sum(counter.values()) mid = d // 2 count =", "+= 1 return count def compute_median(counter): d = sum(counter.values()) mid = d //", "d] >= 2 * median: count += 1 counter[expenditure[i]] -= 1 counter[expenditure[i +", "d // 2 count = 0 sorted_keys = sorted(counter.keys()) for i, k in", "return k else: if counter[k] > 1: return k else: return (k +", "if count > mid: if d % 2 == 1: return k else:", "<reponame>yxtay/code-ex from collections import Counter def activity_notifications(expenditure, d): count = 0 counter =", "2 == 1: return k else: if counter[k] > 1: return k else:", "compute_median(counter) if expenditure[i + d] >= 2 * median: count += 1 counter[expenditure[i]]", "in enumerate(sorted_keys): count += counter[k] if count > mid: if d % 2", "if d % 2 == 1: return k else: if counter[k] > 1:", "sorted_keys = sorted(counter.keys()) for i, k in enumerate(sorted_keys): count += counter[k] if count", "* median: count += 1 counter[expenditure[i]] -= 1 counter[expenditure[i + d]] += 1", "// 2 count = 0 sorted_keys = sorted(counter.keys()) for i, k in enumerate(sorted_keys):" ]
[ "credit director.about = about if director.id is None: director.d_img = \"https://images-na.ssl-images-amazon.com/images/I/818%2BI9cEsEL._SY606_.jpg\" director.save() except:", "except: continue title = str(star.s_name) + \" instagram\" driver.get(\"https://duckduckgo.com/\") driver.find_element_by_xpath(\"//input[@name='q']\").send_keys(str(title)) driver.find_element_by_id(\"search_button_homepage\").click() data =", "credit = driver.find_element_by_xpath(\"//div[@id='filmo-head-actress']\").text image = driver.find_element_by_xpath(\"//img[@id='name-poster']\").get_attribute('src') about = driver.find_element_by_xpath(\"//div[@class='inline']\").text credit = float(credit[15:18]) star.weight", "True driver = webdriver.Firefox(options=options, executable_path='E:\\geckodriver.exe') driver.get(url) try: x = driver.find_element_by_xpath(\"//span[contains(text(),'Actor')]\").text except: x =", "credit = driver.find_element_by_xpath(\"//div[@id='filmo-head-director']\").text image = driver.find_element_by_xpath(\"//img[@id='name-poster']\").get_attribute('src') about = driver.find_element_by_xpath(\"//div[@class='inline']\").text credit = float(credit[16:18]) director.weight", "webdriver.Firefox(options=options, executable_path='E:\\geckodriver.exe') driver.get(url) try: x = driver.find_element_by_xpath(\"//span[contains(text(),'Actor')]\").text except: x = driver.find_element_by_xpath(\"//span[contains(text(),'Actress')]\").text if x", ".models import Star, Director def stars_update(): stars = Star.objects.all() for star in stars:", "= driver.find_element_by_xpath(\"//img[@id='name-poster']\").get_attribute('src') about = driver.find_element_by_xpath(\"//div[@class='inline']\").text credit = float(credit[16:18]) director.weight = credit director.about =", "= True driver = webdriver.Firefox(options=options, executable_path='E:\\geckodriver.exe') driver.get(url) try: x = driver.find_element_by_xpath(\"//span[contains(text(),'Actor')]\").text except: x", "options.headless = True driver = webdriver.Firefox(options=options, executable_path='E:\\geckodriver.exe') driver.get(url) try: credit = driver.find_element_by_xpath(\"//div[@id='filmo-head-director']\").text image", "Star, Director def stars_update(): stars = Star.objects.all() for star in stars: if star.insta_followers", "director in directors: url = director.director_link options = Options() options.headless = True driver", "from selenium import webdriver from selenium.webdriver.firefox.options import Options from .models import Star, Director", "import Options from .models import Star, Director def stars_update(): stars = Star.objects.all() for", "Star.objects.all() for star in stars: if star.insta_followers == 0: print(star.s_name) url = star.star_link", "star.insta_followers == 0: print(star.s_name) url = star.star_link # page = requests.get(url) options =", "about = driver.find_element_by_xpath(\"//div[@class='inline']\").text credit = float(credit[13:16]) star.weight = credit star.about = about star.star_img", "driver.find_element_by_xpath(\"//div[@class='inline']\").text credit = float(credit[16:18]) director.weight = credit director.about = about if director.id is", "= int(followers) except: continue driver.quit() try: star.save() except: continue else: continue def director_update():", "= Options() options.headless = True driver = webdriver.Firefox(options=options, executable_path='E:\\geckodriver.exe') driver.get(url) try: credit =", "followers[:-1] followers = float(followers) * 1000 star.insta_followers = int(followers) elif followers[-1] == 'm':", "star.about = about star.star_img = image except: continue elif x == \"Actress\": try:", "= Director.objects.all() for director in directors: url = director.director_link options = Options() options.headless", "x == \"Actor\": try: credit = driver.find_element_by_xpath(\"//div[@id='filmo-head-actor']\").text image = driver.find_element_by_xpath(\"//img[@id='name-poster']\").get_attribute('src') about = driver.find_element_by_xpath(\"//div[@class='inline']\").text", "driver.find_element_by_xpath(\"//img[@id='name-poster']\").get_attribute('src') about = driver.find_element_by_xpath(\"//div[@class='inline']\").text credit = float(credit[13:16]) star.weight = credit star.about = about", "star.about = about star.star_img = image except: continue title = str(star.s_name) + \"", "followers_data = driver.find_element_by_xpath( \"//div[contains(@class,'results js-results')]//div[1]//div[1]//div[2]\").text followers_insta = followers_data.split(\" \") followers = followers_insta[0] if", "driver.find_element_by_xpath( \"//div[contains(@class,'results js-results')]//div[1]//div[1]//div[2]\").text followers_insta = followers_data.split(\" \") followers = followers_insta[0] if followers[-1] ==", "= credit director.about = about if director.id is None: director.d_img = \"https://images-na.ssl-images-amazon.com/images/I/818%2BI9cEsEL._SY606_.jpg\" director.save()", "followers = float(followers) * 1000000 star.insta_followers = int(followers) else: followers = float(followers) star.insta_followers", "= driver.find_element_by_xpath(\"//div[@class='inline']\").text credit = float(credit[13:16]) star.weight = credit star.about = about star.star_img =", "== \"Actress\": try: credit = driver.find_element_by_xpath(\"//div[@id='filmo-head-actress']\").text image = driver.find_element_by_xpath(\"//img[@id='name-poster']\").get_attribute('src') about = driver.find_element_by_xpath(\"//div[@class='inline']\").text credit", "driver.find_element_by_xpath(\"//img[@id='name-poster']\").get_attribute('src') about = driver.find_element_by_xpath(\"//div[@class='inline']\").text credit = float(credit[15:18]) star.weight = credit star.about = about", "about = driver.find_element_by_xpath(\"//div[@class='inline']\").text credit = float(credit[15:18]) star.weight = credit star.about = about star.star_img", "= followers_insta[0] if followers[-1] == 'k': followers = followers[:-1] followers = float(followers) *", "from .models import Star, Director def stars_update(): stars = Star.objects.all() for star in", "= int(followers) elif followers[-1] == 'm': followers = followers[:-1] followers = float(followers) *", "= credit star.about = about star.star_img = image except: continue elif x ==", "driver.find_element_by_xpath(\"//div[@id='r1-0']//a[contains(@class,'result__check')]\") star.star_insta = data.get_attribute('href') try: followers_data = driver.find_element_by_xpath( \"//div[contains(@class,'results js-results')]//div[1]//div[1]//div[2]\").text followers_insta = followers_data.split(\"", "image = driver.find_element_by_xpath(\"//img[@id='name-poster']\").get_attribute('src') about = driver.find_element_by_xpath(\"//div[@class='inline']\").text credit = float(credit[15:18]) star.weight = credit star.about", "elif followers[-1] == 'm': followers = followers[:-1] followers = float(followers) * 1000000 star.insta_followers", "driver.find_element_by_id(\"search_button_homepage\").click() data = driver.find_element_by_xpath(\"//div[@id='r1-0']//a[contains(@class,'result__check')]\") star.star_insta = data.get_attribute('href') try: followers_data = driver.find_element_by_xpath( \"//div[contains(@class,'results js-results')]//div[1]//div[1]//div[2]\").text", "Options() options.headless = True driver = webdriver.Firefox(options=options, executable_path='E:\\geckodriver.exe') driver.get(url) try: x = driver.find_element_by_xpath(\"//span[contains(text(),'Actor')]\").text", "star.star_img = image except: continue title = str(star.s_name) + \" instagram\" driver.get(\"https://duckduckgo.com/\") driver.find_element_by_xpath(\"//input[@name='q']\").send_keys(str(title))", "star in stars: if star.insta_followers == 0: print(star.s_name) url = star.star_link # page", "'k': followers = followers[:-1] followers = float(followers) * 1000 star.insta_followers = int(followers) elif", "def stars_update(): stars = Star.objects.all() for star in stars: if star.insta_followers == 0:", "except: x = driver.find_element_by_xpath(\"//span[contains(text(),'Actress')]\").text if x == \"Actor\": try: credit = driver.find_element_by_xpath(\"//div[@id='filmo-head-actor']\").text image", "driver.get(url) try: x = driver.find_element_by_xpath(\"//span[contains(text(),'Actor')]\").text except: x = driver.find_element_by_xpath(\"//span[contains(text(),'Actress')]\").text if x == \"Actor\":", "directors = Director.objects.all() for director in directors: url = director.director_link options = Options()", "driver = webdriver.Firefox(options=options, executable_path='E:\\geckodriver.exe') driver.get(url) try: credit = driver.find_element_by_xpath(\"//div[@id='filmo-head-director']\").text image = driver.find_element_by_xpath(\"//img[@id='name-poster']\").get_attribute('src') about", "in directors: url = director.director_link options = Options() options.headless = True driver =", "about = driver.find_element_by_xpath(\"//div[@class='inline']\").text credit = float(credit[16:18]) director.weight = credit director.about = about if", "try: credit = driver.find_element_by_xpath(\"//div[@id='filmo-head-actor']\").text image = driver.find_element_by_xpath(\"//img[@id='name-poster']\").get_attribute('src') about = driver.find_element_by_xpath(\"//div[@class='inline']\").text credit = float(credit[13:16])", "requests.get(url) options = Options() options.headless = True driver = webdriver.Firefox(options=options, executable_path='E:\\geckodriver.exe') driver.get(url) try:", "director.about = about if director.id is None: director.d_img = \"https://images-na.ssl-images-amazon.com/images/I/818%2BI9cEsEL._SY606_.jpg\" director.save() except: continue", "float(credit[13:16]) star.weight = credit star.about = about star.star_img = image except: continue elif", "image = driver.find_element_by_xpath(\"//img[@id='name-poster']\").get_attribute('src') about = driver.find_element_by_xpath(\"//div[@class='inline']\").text credit = float(credit[13:16]) star.weight = credit star.about", "<filename>movies/utils2.py from selenium import webdriver from selenium.webdriver.firefox.options import Options from .models import Star,", "driver.get(url) try: credit = driver.find_element_by_xpath(\"//div[@id='filmo-head-director']\").text image = driver.find_element_by_xpath(\"//img[@id='name-poster']\").get_attribute('src') about = driver.find_element_by_xpath(\"//div[@class='inline']\").text credit =", "= star.star_link # page = requests.get(url) options = Options() options.headless = True driver", "= float(followers) * 1000000 star.insta_followers = int(followers) else: followers = float(followers) star.insta_followers =", "executable_path='E:\\geckodriver.exe') driver.get(url) try: x = driver.find_element_by_xpath(\"//span[contains(text(),'Actor')]\").text except: x = driver.find_element_by_xpath(\"//span[contains(text(),'Actress')]\").text if x ==", "star.insta_followers = int(followers) else: followers = float(followers) star.insta_followers = int(followers) except: continue driver.quit()", "else: followers = float(followers) star.insta_followers = int(followers) except: continue driver.quit() try: star.save() except:", "director.director_link options = Options() options.headless = True driver = webdriver.Firefox(options=options, executable_path='E:\\geckodriver.exe') driver.get(url) try:", "== \"Actor\": try: credit = driver.find_element_by_xpath(\"//div[@id='filmo-head-actor']\").text image = driver.find_element_by_xpath(\"//img[@id='name-poster']\").get_attribute('src') about = driver.find_element_by_xpath(\"//div[@class='inline']\").text credit", "* 1000 star.insta_followers = int(followers) elif followers[-1] == 'm': followers = followers[:-1] followers", "driver.find_element_by_xpath(\"//span[contains(text(),'Actor')]\").text except: x = driver.find_element_by_xpath(\"//span[contains(text(),'Actress')]\").text if x == \"Actor\": try: credit = driver.find_element_by_xpath(\"//div[@id='filmo-head-actor']\").text", "== 'k': followers = followers[:-1] followers = float(followers) * 1000 star.insta_followers = int(followers)", "instagram\" driver.get(\"https://duckduckgo.com/\") driver.find_element_by_xpath(\"//input[@name='q']\").send_keys(str(title)) driver.find_element_by_id(\"search_button_homepage\").click() data = driver.find_element_by_xpath(\"//div[@id='r1-0']//a[contains(@class,'result__check')]\") star.star_insta = data.get_attribute('href') try: followers_data =", "\"Actress\": try: credit = driver.find_element_by_xpath(\"//div[@id='filmo-head-actress']\").text image = driver.find_element_by_xpath(\"//img[@id='name-poster']\").get_attribute('src') about = driver.find_element_by_xpath(\"//div[@class='inline']\").text credit =", "= driver.find_element_by_xpath(\"//img[@id='name-poster']\").get_attribute('src') about = driver.find_element_by_xpath(\"//div[@class='inline']\").text credit = float(credit[13:16]) star.weight = credit star.about =", "try: star.save() except: continue else: continue def director_update(): directors = Director.objects.all() for director", "Director.objects.all() for director in directors: url = director.director_link options = Options() options.headless =", "star.insta_followers = int(followers) elif followers[-1] == 'm': followers = followers[:-1] followers = float(followers)", "followers[:-1] followers = float(followers) * 1000000 star.insta_followers = int(followers) else: followers = float(followers)", "try: credit = driver.find_element_by_xpath(\"//div[@id='filmo-head-actress']\").text image = driver.find_element_by_xpath(\"//img[@id='name-poster']\").get_attribute('src') about = driver.find_element_by_xpath(\"//div[@class='inline']\").text credit = float(credit[15:18])", "= driver.find_element_by_xpath(\"//img[@id='name-poster']\").get_attribute('src') about = driver.find_element_by_xpath(\"//div[@class='inline']\").text credit = float(credit[15:18]) star.weight = credit star.about =", "= str(star.s_name) + \" instagram\" driver.get(\"https://duckduckgo.com/\") driver.find_element_by_xpath(\"//input[@name='q']\").send_keys(str(title)) driver.find_element_by_id(\"search_button_homepage\").click() data = driver.find_element_by_xpath(\"//div[@id='r1-0']//a[contains(@class,'result__check')]\") star.star_insta =", "url = star.star_link # page = requests.get(url) options = Options() options.headless = True", "+ \" instagram\" driver.get(\"https://duckduckgo.com/\") driver.find_element_by_xpath(\"//input[@name='q']\").send_keys(str(title)) driver.find_element_by_id(\"search_button_homepage\").click() data = driver.find_element_by_xpath(\"//div[@id='r1-0']//a[contains(@class,'result__check')]\") star.star_insta = data.get_attribute('href') try:", "'m': followers = followers[:-1] followers = float(followers) * 1000000 star.insta_followers = int(followers) else:", "executable_path='E:\\geckodriver.exe') driver.get(url) try: credit = driver.find_element_by_xpath(\"//div[@id='filmo-head-director']\").text image = driver.find_element_by_xpath(\"//img[@id='name-poster']\").get_attribute('src') about = driver.find_element_by_xpath(\"//div[@class='inline']\").text credit", "import Star, Director def stars_update(): stars = Star.objects.all() for star in stars: if", "\" instagram\" driver.get(\"https://duckduckgo.com/\") driver.find_element_by_xpath(\"//input[@name='q']\").send_keys(str(title)) driver.find_element_by_id(\"search_button_homepage\").click() data = driver.find_element_by_xpath(\"//div[@id='r1-0']//a[contains(@class,'result__check')]\") star.star_insta = data.get_attribute('href') try: followers_data", "followers[-1] == 'm': followers = followers[:-1] followers = float(followers) * 1000000 star.insta_followers =", "director_update(): directors = Director.objects.all() for director in directors: url = director.director_link options =", "credit = float(credit[16:18]) director.weight = credit director.about = about if director.id is None:", "star.weight = credit star.about = about star.star_img = image except: continue title =", "= data.get_attribute('href') try: followers_data = driver.find_element_by_xpath( \"//div[contains(@class,'results js-results')]//div[1]//div[1]//div[2]\").text followers_insta = followers_data.split(\" \") followers", "= int(followers) else: followers = float(followers) star.insta_followers = int(followers) except: continue driver.quit() try:", "image = driver.find_element_by_xpath(\"//img[@id='name-poster']\").get_attribute('src') about = driver.find_element_by_xpath(\"//div[@class='inline']\").text credit = float(credit[16:18]) director.weight = credit director.about", "credit = float(credit[15:18]) star.weight = credit star.about = about star.star_img = image except:", "image except: continue title = str(star.s_name) + \" instagram\" driver.get(\"https://duckduckgo.com/\") driver.find_element_by_xpath(\"//input[@name='q']\").send_keys(str(title)) driver.find_element_by_id(\"search_button_homepage\").click() data", "driver.find_element_by_xpath(\"//div[@class='inline']\").text credit = float(credit[13:16]) star.weight = credit star.about = about star.star_img = image", "about star.star_img = image except: continue title = str(star.s_name) + \" instagram\" driver.get(\"https://duckduckgo.com/\")", "= float(followers) star.insta_followers = int(followers) except: continue driver.quit() try: star.save() except: continue else:", "except: continue driver.quit() try: star.save() except: continue else: continue def director_update(): directors =", "options = Options() options.headless = True driver = webdriver.Firefox(options=options, executable_path='E:\\geckodriver.exe') driver.get(url) try: x", "= followers[:-1] followers = float(followers) * 1000000 star.insta_followers = int(followers) else: followers =", "True driver = webdriver.Firefox(options=options, executable_path='E:\\geckodriver.exe') driver.get(url) try: credit = driver.find_element_by_xpath(\"//div[@id='filmo-head-director']\").text image = driver.find_element_by_xpath(\"//img[@id='name-poster']\").get_attribute('src')", "float(followers) * 1000 star.insta_followers = int(followers) elif followers[-1] == 'm': followers = followers[:-1]", "else: continue def director_update(): directors = Director.objects.all() for director in directors: url =", "driver = webdriver.Firefox(options=options, executable_path='E:\\geckodriver.exe') driver.get(url) try: x = driver.find_element_by_xpath(\"//span[contains(text(),'Actor')]\").text except: x = driver.find_element_by_xpath(\"//span[contains(text(),'Actress')]\").text", "= driver.find_element_by_xpath(\"//div[@class='inline']\").text credit = float(credit[16:18]) director.weight = credit director.about = about if director.id", "== 0: print(star.s_name) url = star.star_link # page = requests.get(url) options = Options()", "= float(followers) * 1000 star.insta_followers = int(followers) elif followers[-1] == 'm': followers =", "data = driver.find_element_by_xpath(\"//div[@id='r1-0']//a[contains(@class,'result__check')]\") star.star_insta = data.get_attribute('href') try: followers_data = driver.find_element_by_xpath( \"//div[contains(@class,'results js-results')]//div[1]//div[1]//div[2]\").text followers_insta", "= driver.find_element_by_xpath(\"//div[@id='r1-0']//a[contains(@class,'result__check')]\") star.star_insta = data.get_attribute('href') try: followers_data = driver.find_element_by_xpath( \"//div[contains(@class,'results js-results')]//div[1]//div[1]//div[2]\").text followers_insta =", "try: credit = driver.find_element_by_xpath(\"//div[@id='filmo-head-director']\").text image = driver.find_element_by_xpath(\"//img[@id='name-poster']\").get_attribute('src') about = driver.find_element_by_xpath(\"//div[@class='inline']\").text credit = float(credit[16:18])", "= True driver = webdriver.Firefox(options=options, executable_path='E:\\geckodriver.exe') driver.get(url) try: credit = driver.find_element_by_xpath(\"//div[@id='filmo-head-director']\").text image =", "for director in directors: url = director.director_link options = Options() options.headless = True", "print(star.s_name) url = star.star_link # page = requests.get(url) options = Options() options.headless =", "credit = float(credit[13:16]) star.weight = credit star.about = about star.star_img = image except:", "star.insta_followers = int(followers) except: continue driver.quit() try: star.save() except: continue else: continue def", "= driver.find_element_by_xpath(\"//div[@id='filmo-head-director']\").text image = driver.find_element_by_xpath(\"//img[@id='name-poster']\").get_attribute('src') about = driver.find_element_by_xpath(\"//div[@class='inline']\").text credit = float(credit[16:18]) director.weight =", "from selenium.webdriver.firefox.options import Options from .models import Star, Director def stars_update(): stars =", "x = driver.find_element_by_xpath(\"//span[contains(text(),'Actor')]\").text except: x = driver.find_element_by_xpath(\"//span[contains(text(),'Actress')]\").text if x == \"Actor\": try: credit", "continue def director_update(): directors = Director.objects.all() for director in directors: url = director.director_link", "* 1000000 star.insta_followers = int(followers) else: followers = float(followers) star.insta_followers = int(followers) except:", "try: followers_data = driver.find_element_by_xpath( \"//div[contains(@class,'results js-results')]//div[1]//div[1]//div[2]\").text followers_insta = followers_data.split(\" \") followers = followers_insta[0]", "about star.star_img = image except: continue elif x == \"Actress\": try: credit =", "= driver.find_element_by_xpath(\"//div[@id='filmo-head-actor']\").text image = driver.find_element_by_xpath(\"//img[@id='name-poster']\").get_attribute('src') about = driver.find_element_by_xpath(\"//div[@class='inline']\").text credit = float(credit[13:16]) star.weight =", "= driver.find_element_by_xpath(\"//span[contains(text(),'Actor')]\").text except: x = driver.find_element_by_xpath(\"//span[contains(text(),'Actress')]\").text if x == \"Actor\": try: credit =", "= Options() options.headless = True driver = webdriver.Firefox(options=options, executable_path='E:\\geckodriver.exe') driver.get(url) try: x =", "js-results')]//div[1]//div[1]//div[2]\").text followers_insta = followers_data.split(\" \") followers = followers_insta[0] if followers[-1] == 'k': followers", "\") followers = followers_insta[0] if followers[-1] == 'k': followers = followers[:-1] followers =", "image except: continue elif x == \"Actress\": try: credit = driver.find_element_by_xpath(\"//div[@id='filmo-head-actress']\").text image =", "1000 star.insta_followers = int(followers) elif followers[-1] == 'm': followers = followers[:-1] followers =", "= requests.get(url) options = Options() options.headless = True driver = webdriver.Firefox(options=options, executable_path='E:\\geckodriver.exe') driver.get(url)", "= followers[:-1] followers = float(followers) * 1000 star.insta_followers = int(followers) elif followers[-1] ==", "if star.insta_followers == 0: print(star.s_name) url = star.star_link # page = requests.get(url) options", "= director.director_link options = Options() options.headless = True driver = webdriver.Firefox(options=options, executable_path='E:\\geckodriver.exe') driver.get(url)", "import webdriver from selenium.webdriver.firefox.options import Options from .models import Star, Director def stars_update():", "\"//div[contains(@class,'results js-results')]//div[1]//div[1]//div[2]\").text followers_insta = followers_data.split(\" \") followers = followers_insta[0] if followers[-1] == 'k':", "directors: url = director.director_link options = Options() options.headless = True driver = webdriver.Firefox(options=options,", "stars: if star.insta_followers == 0: print(star.s_name) url = star.star_link # page = requests.get(url)", "director.weight = credit director.about = about if director.id is None: director.d_img = \"https://images-na.ssl-images-amazon.com/images/I/818%2BI9cEsEL._SY606_.jpg\"", "= image except: continue elif x == \"Actress\": try: credit = driver.find_element_by_xpath(\"//div[@id='filmo-head-actress']\").text image", "followers[-1] == 'k': followers = followers[:-1] followers = float(followers) * 1000 star.insta_followers =", "= webdriver.Firefox(options=options, executable_path='E:\\geckodriver.exe') driver.get(url) try: x = driver.find_element_by_xpath(\"//span[contains(text(),'Actor')]\").text except: x = driver.find_element_by_xpath(\"//span[contains(text(),'Actress')]\").text if", "driver.find_element_by_xpath(\"//img[@id='name-poster']\").get_attribute('src') about = driver.find_element_by_xpath(\"//div[@class='inline']\").text credit = float(credit[16:18]) director.weight = credit director.about = about", "driver.find_element_by_xpath(\"//input[@name='q']\").send_keys(str(title)) driver.find_element_by_id(\"search_button_homepage\").click() data = driver.find_element_by_xpath(\"//div[@id='r1-0']//a[contains(@class,'result__check')]\") star.star_insta = data.get_attribute('href') try: followers_data = driver.find_element_by_xpath( \"//div[contains(@class,'results", "stars = Star.objects.all() for star in stars: if star.insta_followers == 0: print(star.s_name) url", "= followers_data.split(\" \") followers = followers_insta[0] if followers[-1] == 'k': followers = followers[:-1]", "star.save() except: continue else: continue def director_update(): directors = Director.objects.all() for director in", "for star in stars: if star.insta_followers == 0: print(star.s_name) url = star.star_link #", "star.star_link # page = requests.get(url) options = Options() options.headless = True driver =", "= float(credit[13:16]) star.weight = credit star.about = about star.star_img = image except: continue", "int(followers) elif followers[-1] == 'm': followers = followers[:-1] followers = float(followers) * 1000000", "= driver.find_element_by_xpath(\"//div[@class='inline']\").text credit = float(credit[15:18]) star.weight = credit star.about = about star.star_img =", "followers = followers[:-1] followers = float(followers) * 1000000 star.insta_followers = int(followers) else: followers", "1000000 star.insta_followers = int(followers) else: followers = float(followers) star.insta_followers = int(followers) except: continue", "credit star.about = about star.star_img = image except: continue title = str(star.s_name) +", "\"Actor\": try: credit = driver.find_element_by_xpath(\"//div[@id='filmo-head-actor']\").text image = driver.find_element_by_xpath(\"//img[@id='name-poster']\").get_attribute('src') about = driver.find_element_by_xpath(\"//div[@class='inline']\").text credit =", "star.weight = credit star.about = about star.star_img = image except: continue elif x", "driver.find_element_by_xpath(\"//span[contains(text(),'Actress')]\").text if x == \"Actor\": try: credit = driver.find_element_by_xpath(\"//div[@id='filmo-head-actor']\").text image = driver.find_element_by_xpath(\"//img[@id='name-poster']\").get_attribute('src') about", "== 'm': followers = followers[:-1] followers = float(followers) * 1000000 star.insta_followers = int(followers)", "def director_update(): directors = Director.objects.all() for director in directors: url = director.director_link options", "= about if director.id is None: director.d_img = \"https://images-na.ssl-images-amazon.com/images/I/818%2BI9cEsEL._SY606_.jpg\" director.save() except: continue driver.quit()", "credit star.about = about star.star_img = image except: continue elif x == \"Actress\":", "driver.get(\"https://duckduckgo.com/\") driver.find_element_by_xpath(\"//input[@name='q']\").send_keys(str(title)) driver.find_element_by_id(\"search_button_homepage\").click() data = driver.find_element_by_xpath(\"//div[@id='r1-0']//a[contains(@class,'result__check')]\") star.star_insta = data.get_attribute('href') try: followers_data = driver.find_element_by_xpath(", "try: x = driver.find_element_by_xpath(\"//span[contains(text(),'Actor')]\").text except: x = driver.find_element_by_xpath(\"//span[contains(text(),'Actress')]\").text if x == \"Actor\": try:", "followers = float(followers) * 1000 star.insta_followers = int(followers) elif followers[-1] == 'm': followers", "followers = float(followers) star.insta_followers = int(followers) except: continue driver.quit() try: star.save() except: continue", "if followers[-1] == 'k': followers = followers[:-1] followers = float(followers) * 1000 star.insta_followers", "star.star_img = image except: continue elif x == \"Actress\": try: credit = driver.find_element_by_xpath(\"//div[@id='filmo-head-actress']\").text", "Director def stars_update(): stars = Star.objects.all() for star in stars: if star.insta_followers ==", "webdriver from selenium.webdriver.firefox.options import Options from .models import Star, Director def stars_update(): stars", "x == \"Actress\": try: credit = driver.find_element_by_xpath(\"//div[@id='filmo-head-actress']\").text image = driver.find_element_by_xpath(\"//img[@id='name-poster']\").get_attribute('src') about = driver.find_element_by_xpath(\"//div[@class='inline']\").text", "= float(credit[16:18]) director.weight = credit director.about = about if director.id is None: director.d_img", "str(star.s_name) + \" instagram\" driver.get(\"https://duckduckgo.com/\") driver.find_element_by_xpath(\"//input[@name='q']\").send_keys(str(title)) driver.find_element_by_id(\"search_button_homepage\").click() data = driver.find_element_by_xpath(\"//div[@id='r1-0']//a[contains(@class,'result__check')]\") star.star_insta = data.get_attribute('href')", "followers_insta[0] if followers[-1] == 'k': followers = followers[:-1] followers = float(followers) * 1000", "except: continue else: continue def director_update(): directors = Director.objects.all() for director in directors:", "elif x == \"Actress\": try: credit = driver.find_element_by_xpath(\"//div[@id='filmo-head-actress']\").text image = driver.find_element_by_xpath(\"//img[@id='name-poster']\").get_attribute('src') about =", "# page = requests.get(url) options = Options() options.headless = True driver = webdriver.Firefox(options=options,", "x = driver.find_element_by_xpath(\"//span[contains(text(),'Actress')]\").text if x == \"Actor\": try: credit = driver.find_element_by_xpath(\"//div[@id='filmo-head-actor']\").text image =", "= credit star.about = about star.star_img = image except: continue title = str(star.s_name)", "float(credit[15:18]) star.weight = credit star.about = about star.star_img = image except: continue title", "float(followers) * 1000000 star.insta_followers = int(followers) else: followers = float(followers) star.insta_followers = int(followers)", "stars_update(): stars = Star.objects.all() for star in stars: if star.insta_followers == 0: print(star.s_name)", "= driver.find_element_by_xpath(\"//span[contains(text(),'Actress')]\").text if x == \"Actor\": try: credit = driver.find_element_by_xpath(\"//div[@id='filmo-head-actor']\").text image = driver.find_element_by_xpath(\"//img[@id='name-poster']\").get_attribute('src')", "options.headless = True driver = webdriver.Firefox(options=options, executable_path='E:\\geckodriver.exe') driver.get(url) try: x = driver.find_element_by_xpath(\"//span[contains(text(),'Actor')]\").text except:", "= driver.find_element_by_xpath( \"//div[contains(@class,'results js-results')]//div[1]//div[1]//div[2]\").text followers_insta = followers_data.split(\" \") followers = followers_insta[0] if followers[-1]", "continue title = str(star.s_name) + \" instagram\" driver.get(\"https://duckduckgo.com/\") driver.find_element_by_xpath(\"//input[@name='q']\").send_keys(str(title)) driver.find_element_by_id(\"search_button_homepage\").click() data = driver.find_element_by_xpath(\"//div[@id='r1-0']//a[contains(@class,'result__check')]\")", "driver.find_element_by_xpath(\"//div[@class='inline']\").text credit = float(credit[15:18]) star.weight = credit star.about = about star.star_img = image", "= about star.star_img = image except: continue title = str(star.s_name) + \" instagram\"", "credit = driver.find_element_by_xpath(\"//div[@id='filmo-head-actor']\").text image = driver.find_element_by_xpath(\"//img[@id='name-poster']\").get_attribute('src') about = driver.find_element_by_xpath(\"//div[@class='inline']\").text credit = float(credit[13:16]) star.weight", "url = director.director_link options = Options() options.headless = True driver = webdriver.Firefox(options=options, executable_path='E:\\geckodriver.exe')", "data.get_attribute('href') try: followers_data = driver.find_element_by_xpath( \"//div[contains(@class,'results js-results')]//div[1]//div[1]//div[2]\").text followers_insta = followers_data.split(\" \") followers =", "driver.find_element_by_xpath(\"//div[@id='filmo-head-actress']\").text image = driver.find_element_by_xpath(\"//img[@id='name-poster']\").get_attribute('src') about = driver.find_element_by_xpath(\"//div[@class='inline']\").text credit = float(credit[15:18]) star.weight = credit", "continue driver.quit() try: star.save() except: continue else: continue def director_update(): directors = Director.objects.all()", "Options() options.headless = True driver = webdriver.Firefox(options=options, executable_path='E:\\geckodriver.exe') driver.get(url) try: credit = driver.find_element_by_xpath(\"//div[@id='filmo-head-director']\").text", "int(followers) except: continue driver.quit() try: star.save() except: continue else: continue def director_update(): directors", "followers_data.split(\" \") followers = followers_insta[0] if followers[-1] == 'k': followers = followers[:-1] followers", "driver.find_element_by_xpath(\"//div[@id='filmo-head-actor']\").text image = driver.find_element_by_xpath(\"//img[@id='name-poster']\").get_attribute('src') about = driver.find_element_by_xpath(\"//div[@class='inline']\").text credit = float(credit[13:16]) star.weight = credit", "page = requests.get(url) options = Options() options.headless = True driver = webdriver.Firefox(options=options, executable_path='E:\\geckodriver.exe')", "int(followers) else: followers = float(followers) star.insta_followers = int(followers) except: continue driver.quit() try: star.save()", "float(followers) star.insta_followers = int(followers) except: continue driver.quit() try: star.save() except: continue else: continue", "= image except: continue title = str(star.s_name) + \" instagram\" driver.get(\"https://duckduckgo.com/\") driver.find_element_by_xpath(\"//input[@name='q']\").send_keys(str(title)) driver.find_element_by_id(\"search_button_homepage\").click()", "= about star.star_img = image except: continue elif x == \"Actress\": try: credit", "float(credit[16:18]) director.weight = credit director.about = about if director.id is None: director.d_img =", "= webdriver.Firefox(options=options, executable_path='E:\\geckodriver.exe') driver.get(url) try: credit = driver.find_element_by_xpath(\"//div[@id='filmo-head-director']\").text image = driver.find_element_by_xpath(\"//img[@id='name-poster']\").get_attribute('src') about =", "followers = followers_insta[0] if followers[-1] == 'k': followers = followers[:-1] followers = float(followers)", "Options from .models import Star, Director def stars_update(): stars = Star.objects.all() for star", "except: continue elif x == \"Actress\": try: credit = driver.find_element_by_xpath(\"//div[@id='filmo-head-actress']\").text image = driver.find_element_by_xpath(\"//img[@id='name-poster']\").get_attribute('src')", "= float(credit[15:18]) star.weight = credit star.about = about star.star_img = image except: continue", "followers_insta = followers_data.split(\" \") followers = followers_insta[0] if followers[-1] == 'k': followers =", "0: print(star.s_name) url = star.star_link # page = requests.get(url) options = Options() options.headless", "webdriver.Firefox(options=options, executable_path='E:\\geckodriver.exe') driver.get(url) try: credit = driver.find_element_by_xpath(\"//div[@id='filmo-head-director']\").text image = driver.find_element_by_xpath(\"//img[@id='name-poster']\").get_attribute('src') about = driver.find_element_by_xpath(\"//div[@class='inline']\").text", "= driver.find_element_by_xpath(\"//div[@id='filmo-head-actress']\").text image = driver.find_element_by_xpath(\"//img[@id='name-poster']\").get_attribute('src') about = driver.find_element_by_xpath(\"//div[@class='inline']\").text credit = float(credit[15:18]) star.weight =", "= Star.objects.all() for star in stars: if star.insta_followers == 0: print(star.s_name) url =", "star.star_insta = data.get_attribute('href') try: followers_data = driver.find_element_by_xpath( \"//div[contains(@class,'results js-results')]//div[1]//div[1]//div[2]\").text followers_insta = followers_data.split(\" \")", "options = Options() options.headless = True driver = webdriver.Firefox(options=options, executable_path='E:\\geckodriver.exe') driver.get(url) try: credit", "driver.find_element_by_xpath(\"//div[@id='filmo-head-director']\").text image = driver.find_element_by_xpath(\"//img[@id='name-poster']\").get_attribute('src') about = driver.find_element_by_xpath(\"//div[@class='inline']\").text credit = float(credit[16:18]) director.weight = credit", "selenium.webdriver.firefox.options import Options from .models import Star, Director def stars_update(): stars = Star.objects.all()", "selenium import webdriver from selenium.webdriver.firefox.options import Options from .models import Star, Director def", "if x == \"Actor\": try: credit = driver.find_element_by_xpath(\"//div[@id='filmo-head-actor']\").text image = driver.find_element_by_xpath(\"//img[@id='name-poster']\").get_attribute('src') about =", "in stars: if star.insta_followers == 0: print(star.s_name) url = star.star_link # page =", "continue elif x == \"Actress\": try: credit = driver.find_element_by_xpath(\"//div[@id='filmo-head-actress']\").text image = driver.find_element_by_xpath(\"//img[@id='name-poster']\").get_attribute('src') about", "followers = followers[:-1] followers = float(followers) * 1000 star.insta_followers = int(followers) elif followers[-1]", "driver.quit() try: star.save() except: continue else: continue def director_update(): directors = Director.objects.all() for", "title = str(star.s_name) + \" instagram\" driver.get(\"https://duckduckgo.com/\") driver.find_element_by_xpath(\"//input[@name='q']\").send_keys(str(title)) driver.find_element_by_id(\"search_button_homepage\").click() data = driver.find_element_by_xpath(\"//div[@id='r1-0']//a[contains(@class,'result__check')]\") star.star_insta", "continue else: continue def director_update(): directors = Director.objects.all() for director in directors: url" ]
[ "Interface = _LogicalEntityType Configurator = _LogicalEntityType class LogicalElement(object): def __init__(self, element_type, element_name): self.__type", "-*- coding: UTF-8 -*- ''' Created on 29.09.2010 @author: SIGIESEC ''' from commons.core_if", "def __init__(self, element_type, element_name): self.__type = element_type self.__name = element_name def get_type(self): return", "29.09.2010 @author: SIGIESEC ''' from commons.core_if import EnumerationItem, Enumeration class _LogicalEntityType(EnumerationItem): pass class", "Enumeration class _LogicalEntityType(EnumerationItem): pass class LogicalEntityTypes(Enumeration): Component = _LogicalEntityType Interface = _LogicalEntityType Configurator", "''' Created on 29.09.2010 @author: SIGIESEC ''' from commons.core_if import EnumerationItem, Enumeration class", "<gh_stars>1-10 # -*- coding: UTF-8 -*- ''' Created on 29.09.2010 @author: SIGIESEC '''", "UTF-8 -*- ''' Created on 29.09.2010 @author: SIGIESEC ''' from commons.core_if import EnumerationItem,", "_LogicalEntityType class LogicalElement(object): def __init__(self, element_type, element_name): self.__type = element_type self.__name = element_name", "Configurator = _LogicalEntityType class LogicalElement(object): def __init__(self, element_type, element_name): self.__type = element_type self.__name", "LogicalEntityTypes(Enumeration): Component = _LogicalEntityType Interface = _LogicalEntityType Configurator = _LogicalEntityType class LogicalElement(object): def", "element_type, element_name): self.__type = element_type self.__name = element_name def get_type(self): return self.__type def", "from commons.core_if import EnumerationItem, Enumeration class _LogicalEntityType(EnumerationItem): pass class LogicalEntityTypes(Enumeration): Component = _LogicalEntityType", "SIGIESEC ''' from commons.core_if import EnumerationItem, Enumeration class _LogicalEntityType(EnumerationItem): pass class LogicalEntityTypes(Enumeration): Component", "LogicalElement(object): def __init__(self, element_type, element_name): self.__type = element_type self.__name = element_name def get_type(self):", "on 29.09.2010 @author: SIGIESEC ''' from commons.core_if import EnumerationItem, Enumeration class _LogicalEntityType(EnumerationItem): pass", "@author: SIGIESEC ''' from commons.core_if import EnumerationItem, Enumeration class _LogicalEntityType(EnumerationItem): pass class LogicalEntityTypes(Enumeration):", "__init__(self, element_type, element_name): self.__type = element_type self.__name = element_name def get_type(self): return self.__type", "self.__type = element_type self.__name = element_name def get_type(self): return self.__type def get_name(self): return", "# -*- coding: UTF-8 -*- ''' Created on 29.09.2010 @author: SIGIESEC ''' from", "coding: UTF-8 -*- ''' Created on 29.09.2010 @author: SIGIESEC ''' from commons.core_if import", "= element_type self.__name = element_name def get_type(self): return self.__type def get_name(self): return self.__name", "class _LogicalEntityType(EnumerationItem): pass class LogicalEntityTypes(Enumeration): Component = _LogicalEntityType Interface = _LogicalEntityType Configurator =", "-*- ''' Created on 29.09.2010 @author: SIGIESEC ''' from commons.core_if import EnumerationItem, Enumeration", "= _LogicalEntityType Configurator = _LogicalEntityType class LogicalElement(object): def __init__(self, element_type, element_name): self.__type =", "class LogicalElement(object): def __init__(self, element_type, element_name): self.__type = element_type self.__name = element_name def", "EnumerationItem, Enumeration class _LogicalEntityType(EnumerationItem): pass class LogicalEntityTypes(Enumeration): Component = _LogicalEntityType Interface = _LogicalEntityType", "_LogicalEntityType Interface = _LogicalEntityType Configurator = _LogicalEntityType class LogicalElement(object): def __init__(self, element_type, element_name):", "''' from commons.core_if import EnumerationItem, Enumeration class _LogicalEntityType(EnumerationItem): pass class LogicalEntityTypes(Enumeration): Component =", "Created on 29.09.2010 @author: SIGIESEC ''' from commons.core_if import EnumerationItem, Enumeration class _LogicalEntityType(EnumerationItem):", "= _LogicalEntityType class LogicalElement(object): def __init__(self, element_type, element_name): self.__type = element_type self.__name =", "pass class LogicalEntityTypes(Enumeration): Component = _LogicalEntityType Interface = _LogicalEntityType Configurator = _LogicalEntityType class", "class LogicalEntityTypes(Enumeration): Component = _LogicalEntityType Interface = _LogicalEntityType Configurator = _LogicalEntityType class LogicalElement(object):", "import EnumerationItem, Enumeration class _LogicalEntityType(EnumerationItem): pass class LogicalEntityTypes(Enumeration): Component = _LogicalEntityType Interface =", "commons.core_if import EnumerationItem, Enumeration class _LogicalEntityType(EnumerationItem): pass class LogicalEntityTypes(Enumeration): Component = _LogicalEntityType Interface", "_LogicalEntityType Configurator = _LogicalEntityType class LogicalElement(object): def __init__(self, element_type, element_name): self.__type = element_type", "Component = _LogicalEntityType Interface = _LogicalEntityType Configurator = _LogicalEntityType class LogicalElement(object): def __init__(self,", "= _LogicalEntityType Interface = _LogicalEntityType Configurator = _LogicalEntityType class LogicalElement(object): def __init__(self, element_type,", "_LogicalEntityType(EnumerationItem): pass class LogicalEntityTypes(Enumeration): Component = _LogicalEntityType Interface = _LogicalEntityType Configurator = _LogicalEntityType", "element_name): self.__type = element_type self.__name = element_name def get_type(self): return self.__type def get_name(self):" ]
[ "list_2[-1] == 'b' list_3 = DoublyLinkedList([0, 5, 4, 'foo', 0, 0]) list_3.remove(0) assert", "list_1[-2] == 5 assert list_1[-1] == 6 assert list_1[-1] is list_1.tail.value assert list_1[:2]", "list_1.head.value assert list_1[3] == 'foo' assert list_1[-2] == 5 assert list_1[-1] == 6", "assert list_1 == [0, 'foo', 5] assert list_1.head is not list_1.tail def test_append():", "== 'b' assert list_2[-1] == 'b' list_3 = DoublyLinkedList([0, 5, 4, 'foo', 0,", "DoublyLinkedList([0, 'foo']) assert len(list_2) == 2 def test_extend(): list_1 = DoublyLinkedList([0]) list_1.extend(['foo', 5])", "= DoublyLinkedList([0, 'foo']) list_1.insert('bar', 0) assert list_1 == ['bar', 0, 'foo'] def test_equality():", "list_1 = DoublyLinkedList([0, 5, 4, 'foo', 5, 6]) assert list_1[0] == 0 assert", "list_1[0] is list_1.head.value assert list_1[3] == 'foo' assert list_1[-2] == 5 assert list_1[-1]", "4, 'foo', 6, 2] def test_remove(): list_1 = DoublyLinkedList(['a', 'a']) list_1.remove('a') assert len(list_1)", "del list_2[0] del list_2[-1] assert len(list_2) == 1 assert list_2[0] == 'b' assert", "list_2[-1] assert len(list_2) == 1 assert list_2[0] == 'b' assert list_2[-1] == 'b'", "assert list_1 == (5, 4, 'foo') assert list_1 != [5, 4, 'foo', 6,", "'foo') assert list_1 != [5, 4, 'foo', 6, 2] def test_remove(): list_1 =", "assert list_1[-1] == 6 assert list_1[-1] is list_1.tail.value assert list_1[:2] == [0, 5]", "'b', 'c']) del list_2[0] del list_2[-1] assert len(list_2) == 1 assert list_2[0] ==", "list_2 = DoublyLinkedList([0, 'foo']) assert len(list_2) == 2 def test_extend(): list_1 = DoublyLinkedList([0])", "test_append(): list_1 = DoublyLinkedList() list_1.append(0) assert list_1[0] == 0 assert list_1[-1] == 0", "def test_extend(): list_1 = DoublyLinkedList([0]) list_1.extend(['foo', 5]) assert list_1 == [0, 'foo', 5]", "is list_1.head.value assert list_1[3] == 'foo' assert list_1[-2] == 5 assert list_1[-1] ==", "def test_length(): list_1 = DoublyLinkedList() assert len(list_1) == 0 list_2 = DoublyLinkedList([0, 'foo'])", "assert list_1[0] == 0 assert list_1[-1] == 0 assert list_1.head is list_1.tail def", "list_1[0] == 0 assert list_1[0] is list_1.head.value assert list_1[3] == 'foo' assert list_1[-2]", "assert list_1 != [5, 4, 'foo', 6, 2] def test_remove(): list_1 = DoublyLinkedList(['a',", "0 assert list_1[-1] == 0 assert list_1.head is list_1.tail def test_insert(): list_1 =", "DoublyLinkedList def test_index(): list_1 = DoublyLinkedList([0, 5, 4, 'foo', 5, 6]) assert list_1[0]", "'foo' assert list_1[-2] == 5 assert list_1[-1] == 6 assert list_1[-1] is list_1.tail.value", "def test_index(): list_1 = DoublyLinkedList([0, 5, 4, 'foo', 5, 6]) assert list_1[0] ==", "list_1[-1] == 0 assert list_1.head is list_1.tail def test_insert(): list_1 = DoublyLinkedList([0, 'foo'])", "6 assert list_1[-1] is list_1.tail.value assert list_1[:2] == [0, 5] assert list_1[[1, 3,", "is list_1.tail def test_insert(): list_1 = DoublyLinkedList([0, 'foo']) list_1.insert('bar', 0) assert list_1 ==", "list_3 == [5, 4, 'foo'] assert list_3[0] == 5 assert list_3[-1] == 'foo'", "list_1[-1] == 6 assert list_1[-1] is list_1.tail.value assert list_1[:2] == [0, 5] assert", "= DoublyLinkedList(['a', 'b', 'c']) del list_2[0] del list_2[-1] assert len(list_2) == 1 assert", "assert list_1.head is None assert list_1.tail is None list_2 = DoublyLinkedList(['a', 'b', 'c'])", "list_1[-1] is list_1.tail.value assert list_1[:2] == [0, 5] assert list_1[[1, 3, 0]] ==", "list_1 == (5, 4, 'foo') assert list_1 != [5, 4, 'foo', 6, 2]", "test_remove(): list_1 = DoublyLinkedList(['a', 'a']) list_1.remove('a') assert len(list_1) == 0 assert list_1.head is", "list_1.head is not list_1.tail def test_append(): list_1 = DoublyLinkedList() list_1.append(0) assert list_1[0] ==", "test_index(): list_1 = DoublyLinkedList([0, 5, 4, 'foo', 5, 6]) assert list_1[0] == 0", "def test_equality(): list_1 = DoublyLinkedList([5, 4, 'foo']) assert list_1 == [5, 4, 'foo']", "assert list_1 == ['bar', 0, 'foo'] def test_equality(): list_1 = DoublyLinkedList([5, 4, 'foo'])", "== [5, 4, 'foo'] assert list_1 == (5, 4, 'foo') assert list_1 !=", "6]) assert list_1[0] == 0 assert list_1[0] is list_1.head.value assert list_1[3] == 'foo'", "== 0 assert list_1[0] is list_1.head.value assert list_1[3] == 'foo' assert list_1[-2] ==", "list_1.head is list_1.tail def test_insert(): list_1 = DoublyLinkedList([0, 'foo']) list_1.insert('bar', 0) assert list_1", "0 assert list_1.head is list_1.tail def test_insert(): list_1 = DoublyLinkedList([0, 'foo']) list_1.insert('bar', 0)", "list_1[3] == 'foo' assert list_1[-2] == 5 assert list_1[-1] == 6 assert list_1[-1]", "test_insert(): list_1 = DoublyLinkedList([0, 'foo']) list_1.insert('bar', 0) assert list_1 == ['bar', 0, 'foo']", "assert len(list_2) == 1 assert list_2[0] == 'b' assert list_2[-1] == 'b' list_3", "3, 0]] == [5, 'foo', 0] def test_length(): list_1 = DoublyLinkedList() assert len(list_1)", "0] def test_length(): list_1 = DoublyLinkedList() assert len(list_1) == 0 list_2 = DoublyLinkedList([0,", "4, 'foo', 5, 6]) assert list_1[0] == 0 assert list_1[0] is list_1.head.value assert", "assert list_1 == [5, 4, 'foo'] assert list_1 == (5, 4, 'foo') assert", "list_1 == [0, 'foo', 5] assert list_1.head is not list_1.tail def test_append(): list_1", "test_extend(): list_1 = DoublyLinkedList([0]) list_1.extend(['foo', 5]) assert list_1 == [0, 'foo', 5] assert", "(5, 4, 'foo') assert list_1 != [5, 4, 'foo', 6, 2] def test_remove():", "list_1[:2] == [0, 5] assert list_1[[1, 3, 0]] == [5, 'foo', 0] def", "'foo', 0, 0]) list_3.remove(0) assert list_3 == [5, 4, 'foo'] assert list_3[0] ==", "not list_1.tail def test_append(): list_1 = DoublyLinkedList() list_1.append(0) assert list_1[0] == 0 assert", "== 0 assert list_1[-1] == 0 assert list_1.head is list_1.tail def test_insert(): list_1", "0, 'foo'] def test_equality(): list_1 = DoublyLinkedList([5, 4, 'foo']) assert list_1 == [5,", "['bar', 0, 'foo'] def test_equality(): list_1 = DoublyLinkedList([5, 4, 'foo']) assert list_1 ==", "assert list_2[0] == 'b' assert list_2[-1] == 'b' list_3 = DoublyLinkedList([0, 5, 4,", "list_1.head is None assert list_1.tail is None list_2 = DoublyLinkedList(['a', 'b', 'c']) del", "= DoublyLinkedList([0, 'foo']) assert len(list_2) == 2 def test_extend(): list_1 = DoublyLinkedList([0]) list_1.extend(['foo',", "= DoublyLinkedList([5, 4, 'foo']) assert list_1 == [5, 4, 'foo'] assert list_1 ==", "5, 6]) assert list_1[0] == 0 assert list_1[0] is list_1.head.value assert list_1[3] ==", "DoublyLinkedList(['a', 'b', 'c']) del list_2[0] del list_2[-1] assert len(list_2) == 1 assert list_2[0]", "[5, 4, 'foo'] assert list_1 == (5, 4, 'foo') assert list_1 != [5,", "'foo'] assert list_1 == (5, 4, 'foo') assert list_1 != [5, 4, 'foo',", "list_1[0] == 0 assert list_1[-1] == 0 assert list_1.head is list_1.tail def test_insert():", "assert list_1[-1] is list_1.tail.value assert list_1[:2] == [0, 5] assert list_1[[1, 3, 0]]", "assert list_1[3] == 'foo' assert list_1[-2] == 5 assert list_1[-1] == 6 assert", "list_1 = DoublyLinkedList([0]) list_1.extend(['foo', 5]) assert list_1 == [0, 'foo', 5] assert list_1.head", "4, 'foo', 0, 0]) list_3.remove(0) assert list_3 == [5, 4, 'foo'] assert list_3[0]", "DoublyLinkedList() list_1.append(0) assert list_1[0] == 0 assert list_1[-1] == 0 assert list_1.head is", "assert list_1[[1, 3, 0]] == [5, 'foo', 0] def test_length(): list_1 = DoublyLinkedList()", "4, 'foo'] assert list_1 == (5, 4, 'foo') assert list_1 != [5, 4,", "def test_insert(): list_1 = DoublyLinkedList([0, 'foo']) list_1.insert('bar', 0) assert list_1 == ['bar', 0,", "'c']) del list_2[0] del list_2[-1] assert len(list_2) == 1 assert list_2[0] == 'b'", "'b' list_3 = DoublyLinkedList([0, 5, 4, 'foo', 0, 0]) list_3.remove(0) assert list_3 ==", "len(list_1) == 0 list_2 = DoublyLinkedList([0, 'foo']) assert len(list_2) == 2 def test_extend():", "0]] == [5, 'foo', 0] def test_length(): list_1 = DoublyLinkedList() assert len(list_1) ==", "list_1 != [5, 4, 'foo', 6, 2] def test_remove(): list_1 = DoublyLinkedList(['a', 'a'])", "None list_2 = DoublyLinkedList(['a', 'b', 'c']) del list_2[0] del list_2[-1] assert len(list_2) ==", "len(list_1) == 0 assert list_1.head is None assert list_1.tail is None list_2 =", "== 6 assert list_1[-1] is list_1.tail.value assert list_1[:2] == [0, 5] assert list_1[[1,", "list_1 = DoublyLinkedList(['a', 'a']) list_1.remove('a') assert len(list_1) == 0 assert list_1.head is None", "== 2 def test_extend(): list_1 = DoublyLinkedList([0]) list_1.extend(['foo', 5]) assert list_1 == [0,", "'foo']) assert len(list_2) == 2 def test_extend(): list_1 = DoublyLinkedList([0]) list_1.extend(['foo', 5]) assert", "= DoublyLinkedList([0]) list_1.extend(['foo', 5]) assert list_1 == [0, 'foo', 5] assert list_1.head is", "== 0 assert list_1.head is list_1.tail def test_insert(): list_1 = DoublyLinkedList([0, 'foo']) list_1.insert('bar',", "test_length(): list_1 = DoublyLinkedList() assert len(list_1) == 0 list_2 = DoublyLinkedList([0, 'foo']) assert", "assert list_1[-1] == 0 assert list_1.head is list_1.tail def test_insert(): list_1 = DoublyLinkedList([0,", "'foo', 5, 6]) assert list_1[0] == 0 assert list_1[0] is list_1.head.value assert list_1[3]", "list_3 = DoublyLinkedList([0, 5, 4, 'foo', 0, 0]) list_3.remove(0) assert list_3 == [5,", "== ['bar', 0, 'foo'] def test_equality(): list_1 = DoublyLinkedList([5, 4, 'foo']) assert list_1", "'foo'] def test_equality(): list_1 = DoublyLinkedList([5, 4, 'foo']) assert list_1 == [5, 4,", "assert list_1.head is list_1.tail def test_insert(): list_1 = DoublyLinkedList([0, 'foo']) list_1.insert('bar', 0) assert", "list_1 == [5, 4, 'foo'] assert list_1 == (5, 4, 'foo') assert list_1", "list_1 = DoublyLinkedList() list_1.append(0) assert list_1[0] == 0 assert list_1[-1] == 0 assert", "5] assert list_1[[1, 3, 0]] == [5, 'foo', 0] def test_length(): list_1 =", "DoublyLinkedList([0, 'foo']) list_1.insert('bar', 0) assert list_1 == ['bar', 0, 'foo'] def test_equality(): list_1", "== 0 assert list_1.head is None assert list_1.tail is None list_2 = DoublyLinkedList(['a',", "list_2 = DoublyLinkedList(['a', 'b', 'c']) del list_2[0] del list_2[-1] assert len(list_2) == 1", "5, 4, 'foo', 0, 0]) list_3.remove(0) assert list_3 == [5, 4, 'foo'] assert", "list_2[0] == 'b' assert list_2[-1] == 'b' list_3 = DoublyLinkedList([0, 5, 4, 'foo',", "'foo']) assert list_1 == [5, 4, 'foo'] assert list_1 == (5, 4, 'foo')", "'foo', 5] assert list_1.head is not list_1.tail def test_append(): list_1 = DoublyLinkedList() list_1.append(0)", "assert list_1[0] == 0 assert list_1[0] is list_1.head.value assert list_1[3] == 'foo' assert", "is None list_2 = DoublyLinkedList(['a', 'b', 'c']) del list_2[0] del list_2[-1] assert len(list_2)", "list_1.extend(['foo', 5]) assert list_1 == [0, 'foo', 5] assert list_1.head is not list_1.tail", "== 'b' list_3 = DoublyLinkedList([0, 5, 4, 'foo', 0, 0]) list_3.remove(0) assert list_3", "list_3.remove(0) assert list_3 == [5, 4, 'foo'] assert list_3[0] == 5 assert list_3[-1]", "[0, 'foo', 5] assert list_1.head is not list_1.tail def test_append(): list_1 = DoublyLinkedList()", "DoublyLinkedList([0, 5, 4, 'foo', 0, 0]) list_3.remove(0) assert list_3 == [5, 4, 'foo']", "4, 'foo') assert list_1 != [5, 4, 'foo', 6, 2] def test_remove(): list_1", "import DoublyLinkedList def test_index(): list_1 = DoublyLinkedList([0, 5, 4, 'foo', 5, 6]) assert", "list_1.tail is None list_2 = DoublyLinkedList(['a', 'b', 'c']) del list_2[0] del list_2[-1] assert", "= DoublyLinkedList() list_1.append(0) assert list_1[0] == 0 assert list_1[-1] == 0 assert list_1.head", "0 list_2 = DoublyLinkedList([0, 'foo']) assert len(list_2) == 2 def test_extend(): list_1 =", "assert list_1.tail is None list_2 = DoublyLinkedList(['a', 'b', 'c']) del list_2[0] del list_2[-1]", "list_1 == ['bar', 0, 'foo'] def test_equality(): list_1 = DoublyLinkedList([5, 4, 'foo']) assert", "test_equality(): list_1 = DoublyLinkedList([5, 4, 'foo']) assert list_1 == [5, 4, 'foo'] assert", "5, 4, 'foo', 5, 6]) assert list_1[0] == 0 assert list_1[0] is list_1.head.value", "5] assert list_1.head is not list_1.tail def test_append(): list_1 = DoublyLinkedList() list_1.append(0) assert", "!= [5, 4, 'foo', 6, 2] def test_remove(): list_1 = DoublyLinkedList(['a', 'a']) list_1.remove('a')", "packetraven.packets.structures import DoublyLinkedList def test_index(): list_1 = DoublyLinkedList([0, 5, 4, 'foo', 5, 6])", "== 5 assert list_1[-1] == 6 assert list_1[-1] is list_1.tail.value assert list_1[:2] ==", "5 assert list_1[-1] == 6 assert list_1[-1] is list_1.tail.value assert list_1[:2] == [0,", "list_1.tail def test_append(): list_1 = DoublyLinkedList() list_1.append(0) assert list_1[0] == 0 assert list_1[-1]", "== (5, 4, 'foo') assert list_1 != [5, 4, 'foo', 6, 2] def", "0 assert list_1.head is None assert list_1.tail is None list_2 = DoublyLinkedList(['a', 'b',", "list_1[[1, 3, 0]] == [5, 'foo', 0] def test_length(): list_1 = DoublyLinkedList() assert", "= DoublyLinkedList() assert len(list_1) == 0 list_2 = DoublyLinkedList([0, 'foo']) assert len(list_2) ==", "0) assert list_1 == ['bar', 0, 'foo'] def test_equality(): list_1 = DoublyLinkedList([5, 4,", "== [0, 'foo', 5] assert list_1.head is not list_1.tail def test_append(): list_1 =", "'a']) list_1.remove('a') assert len(list_1) == 0 assert list_1.head is None assert list_1.tail is", "assert list_3 == [5, 4, 'foo'] assert list_3[0] == 5 assert list_3[-1] ==", "list_1 = DoublyLinkedList([0, 'foo']) list_1.insert('bar', 0) assert list_1 == ['bar', 0, 'foo'] def", "list_1.remove('a') assert len(list_1) == 0 assert list_1.head is None assert list_1.tail is None", "list_1.insert('bar', 0) assert list_1 == ['bar', 0, 'foo'] def test_equality(): list_1 = DoublyLinkedList([5,", "DoublyLinkedList(['a', 'a']) list_1.remove('a') assert len(list_1) == 0 assert list_1.head is None assert list_1.tail", "DoublyLinkedList() assert len(list_1) == 0 list_2 = DoublyLinkedList([0, 'foo']) assert len(list_2) == 2", "== [5, 'foo', 0] def test_length(): list_1 = DoublyLinkedList() assert len(list_1) == 0", "1 assert list_2[0] == 'b' assert list_2[-1] == 'b' list_3 = DoublyLinkedList([0, 5,", "[5, 4, 'foo', 6, 2] def test_remove(): list_1 = DoublyLinkedList(['a', 'a']) list_1.remove('a') assert", "len(list_2) == 1 assert list_2[0] == 'b' assert list_2[-1] == 'b' list_3 =", "is not list_1.tail def test_append(): list_1 = DoublyLinkedList() list_1.append(0) assert list_1[0] == 0", "assert list_1[-2] == 5 assert list_1[-1] == 6 assert list_1[-1] is list_1.tail.value assert", "[5, 'foo', 0] def test_length(): list_1 = DoublyLinkedList() assert len(list_1) == 0 list_2", "list_2[0] del list_2[-1] assert len(list_2) == 1 assert list_2[0] == 'b' assert list_2[-1]", "assert list_1[0] is list_1.head.value assert list_1[3] == 'foo' assert list_1[-2] == 5 assert", "assert len(list_1) == 0 assert list_1.head is None assert list_1.tail is None list_2", "assert len(list_1) == 0 list_2 = DoublyLinkedList([0, 'foo']) assert len(list_2) == 2 def", "DoublyLinkedList([5, 4, 'foo']) assert list_1 == [5, 4, 'foo'] assert list_1 == (5,", "2] def test_remove(): list_1 = DoublyLinkedList(['a', 'a']) list_1.remove('a') assert len(list_1) == 0 assert", "list_1 = DoublyLinkedList([5, 4, 'foo']) assert list_1 == [5, 4, 'foo'] assert list_1", "== [0, 5] assert list_1[[1, 3, 0]] == [5, 'foo', 0] def test_length():", "assert list_1.head is not list_1.tail def test_append(): list_1 = DoublyLinkedList() list_1.append(0) assert list_1[0]", "= DoublyLinkedList([0, 5, 4, 'foo', 0, 0]) list_3.remove(0) assert list_3 == [5, 4,", "list_1.append(0) assert list_1[0] == 0 assert list_1[-1] == 0 assert list_1.head is list_1.tail", "== 'foo' assert list_1[-2] == 5 assert list_1[-1] == 6 assert list_1[-1] is", "'b' assert list_2[-1] == 'b' list_3 = DoublyLinkedList([0, 5, 4, 'foo', 0, 0])", "def test_remove(): list_1 = DoublyLinkedList(['a', 'a']) list_1.remove('a') assert len(list_1) == 0 assert list_1.head", "0]) list_3.remove(0) assert list_3 == [5, 4, 'foo'] assert list_3[0] == 5 assert", "list_1.tail.value assert list_1[:2] == [0, 5] assert list_1[[1, 3, 0]] == [5, 'foo',", "list_1.tail def test_insert(): list_1 = DoublyLinkedList([0, 'foo']) list_1.insert('bar', 0) assert list_1 == ['bar',", "5]) assert list_1 == [0, 'foo', 5] assert list_1.head is not list_1.tail def", "'foo', 0] def test_length(): list_1 = DoublyLinkedList() assert len(list_1) == 0 list_2 =", "def test_append(): list_1 = DoublyLinkedList() list_1.append(0) assert list_1[0] == 0 assert list_1[-1] ==", "del list_2[-1] assert len(list_2) == 1 assert list_2[0] == 'b' assert list_2[-1] ==", "list_1 = DoublyLinkedList() assert len(list_1) == 0 list_2 = DoublyLinkedList([0, 'foo']) assert len(list_2)", "= DoublyLinkedList(['a', 'a']) list_1.remove('a') assert len(list_1) == 0 assert list_1.head is None assert", "assert list_2[-1] == 'b' list_3 = DoublyLinkedList([0, 5, 4, 'foo', 0, 0]) list_3.remove(0)", "DoublyLinkedList([0]) list_1.extend(['foo', 5]) assert list_1 == [0, 'foo', 5] assert list_1.head is not", "[0, 5] assert list_1[[1, 3, 0]] == [5, 'foo', 0] def test_length(): list_1", "assert len(list_2) == 2 def test_extend(): list_1 = DoublyLinkedList([0]) list_1.extend(['foo', 5]) assert list_1", "2 def test_extend(): list_1 = DoublyLinkedList([0]) list_1.extend(['foo', 5]) assert list_1 == [0, 'foo',", "'foo', 6, 2] def test_remove(): list_1 = DoublyLinkedList(['a', 'a']) list_1.remove('a') assert len(list_1) ==", "None assert list_1.tail is None list_2 = DoublyLinkedList(['a', 'b', 'c']) del list_2[0] del", "len(list_2) == 2 def test_extend(): list_1 = DoublyLinkedList([0]) list_1.extend(['foo', 5]) assert list_1 ==", "= DoublyLinkedList([0, 5, 4, 'foo', 5, 6]) assert list_1[0] == 0 assert list_1[0]", "0, 0]) list_3.remove(0) assert list_3 == [5, 4, 'foo'] assert list_3[0] == 5", "is list_1.tail.value assert list_1[:2] == [0, 5] assert list_1[[1, 3, 0]] == [5,", "from packetraven.packets.structures import DoublyLinkedList def test_index(): list_1 = DoublyLinkedList([0, 5, 4, 'foo', 5,", "4, 'foo']) assert list_1 == [5, 4, 'foo'] assert list_1 == (5, 4,", "6, 2] def test_remove(): list_1 = DoublyLinkedList(['a', 'a']) list_1.remove('a') assert len(list_1) == 0", "0 assert list_1[0] is list_1.head.value assert list_1[3] == 'foo' assert list_1[-2] == 5", "== 1 assert list_2[0] == 'b' assert list_2[-1] == 'b' list_3 = DoublyLinkedList([0,", "DoublyLinkedList([0, 5, 4, 'foo', 5, 6]) assert list_1[0] == 0 assert list_1[0] is", "'foo']) list_1.insert('bar', 0) assert list_1 == ['bar', 0, 'foo'] def test_equality(): list_1 =", "assert list_1[:2] == [0, 5] assert list_1[[1, 3, 0]] == [5, 'foo', 0]", "== 0 list_2 = DoublyLinkedList([0, 'foo']) assert len(list_2) == 2 def test_extend(): list_1", "is None assert list_1.tail is None list_2 = DoublyLinkedList(['a', 'b', 'c']) del list_2[0]" ]
[ "function = module[\"f_annorations\"] assert len(function.arguments) == 4 arg = function.arguments[0] assert arg.annotation ==", "inspect.Parameter.POSITIONAL_OR_KEYWORD assert arg.default == \"0\" arg = function.arguments[2] assert arg is function.arguments[\"kwonly\"] assert", "== \"str\" arg = function.arguments[1] assert arg.annotation is None arg = function.arguments[2] assert", "= function.arguments[1] assert arg is function.arguments[\"poskw\"] assert arg.name == \"poskw\" assert arg.kind is", "arg = function.arguments[0] assert arg is function.arguments[\"posonly\"] assert arg.name == \"posonly\" assert arg.kind", "arg.name == \"poskw\" assert arg.kind is inspect.Parameter.POSITIONAL_OR_KEYWORD assert arg.default == \"1\" function =", "== 3 arg = function.arguments[0] assert arg.name == \"*args\" assert arg.annotation == \"str\"", "= module[\"f_posonly\"] assert len(function.arguments) == 1 arg = function.arguments[0] assert arg is function.arguments[\"posonly\"]", "is function.arguments[\"kwonly\"] assert arg.name == \"kwonly\" assert arg.kind is inspect.Parameter.KEYWORD_ONLY assert arg.default is", "is inspect.Parameter.POSITIONAL_OR_KEYWORD assert arg.default is None arg = function.arguments[2] assert arg is function.arguments[\"kwonly\"]", "\"arguments.py\") assert module.members assert len(module.members) == 11 # noqa: WPS432 function = module[\"f_posonly\"]", "assert arg is function.arguments[\"poskw\"] assert arg.name == \"poskw\" assert arg.kind is inspect.Parameter.POSITIONAL_OR_KEYWORD assert", "== 2 arg = function.arguments[0] assert arg is function.arguments[\"posonly\"] assert arg.name == \"posonly\"", "arg.name == \"kwonly\" assert arg.kind is inspect.Parameter.KEYWORD_ONLY assert arg.default == \"2\" function =", "arg.name == \"posonly\" assert arg.kind is inspect.Parameter.POSITIONAL_ONLY assert arg.default == \"0\" arg =", "assert arg.kind is inspect.Parameter.POSITIONAL_OR_KEYWORD assert arg.default == \"1\" function = module[\"f_posonly_poskw_kwonly\"] assert len(function.arguments)", "assert arg.kind is inspect.Parameter.KEYWORD_ONLY assert arg.default == \"0\" function = module[\"f_posonly_poskw_default_kwonly_default\"] assert len(function.arguments)", "assert arg.annotation == \"str\" arg = function.arguments[1] assert arg.annotation == \"Any\" arg =", "2 arg = function.arguments[0] assert arg is function.arguments[\"posonly\"] assert arg.name == \"posonly\" assert", "assert arg.default == \"0\" function = module[\"f_posonly_default_poskw_default\"] assert len(function.arguments) == 2 arg =", "arg.annotation == \"Any\" arg = function.arguments[2] assert arg.annotation == \"typing.Optional[typing.List[int]]\" arg = function.arguments[3]", "assert len(function.arguments) == 4 arg = function.arguments[0] assert arg.annotation == \"str\" arg =", "arg.kind is inspect.Parameter.POSITIONAL_ONLY assert arg.default == \"0\" function = module[\"f_posonly_poskw\"] assert len(function.arguments) ==", "from tests import FIXTURES_DIR loader = GriffeLoader() def test_loading_functions_arguments(): # noqa: WPS218 \"\"\"Test", "inspect.Parameter.POSITIONAL_ONLY assert arg.default is None arg = function.arguments[1] assert arg is function.arguments[\"poskw\"] assert", "assert arg.default is None function = module[\"f_posonly_poskw_default\"] assert len(function.arguments) == 2 arg =", "arg.name == \"poskw\" assert arg.kind is inspect.Parameter.POSITIONAL_OR_KEYWORD assert arg.default == \"1\" arg =", "arg.default == \"1\" function = module[\"f_posonly_poskw_kwonly\"] assert len(function.arguments) == 3 arg = function.arguments[0]", "function.arguments[\"poskw\"] assert arg.name == \"poskw\" assert arg.kind is inspect.Parameter.POSITIONAL_OR_KEYWORD assert arg.default == \"1\"", "== 11 # noqa: WPS432 function = module[\"f_posonly\"] assert len(function.arguments) == 1 arg", "assert len(function.arguments) == 3 arg = function.arguments[0] assert arg is function.arguments[\"posonly\"] assert arg.name", "loading.\"\"\" module = loader.load_module(FIXTURES_DIR / \"functions\" / \"arguments.py\") assert module.members assert len(module.members) ==", "arg is function.arguments[\"posonly\"] assert arg.name == \"posonly\" assert arg.kind is inspect.Parameter.POSITIONAL_ONLY assert arg.default", "inspect.Parameter.KEYWORD_ONLY assert arg.default == \"2\" function = module[\"f_var\"] assert len(function.arguments) == 3 arg", "3 arg = function.arguments[0] assert arg is function.arguments[\"posonly\"] assert arg.name == \"posonly\" assert", "assert arg.default == \"0\" function = module[\"f_posonly_poskw_default_kwonly_default\"] assert len(function.arguments) == 3 arg =", "len(function.arguments) == 3 arg = function.arguments[0] assert arg.name == \"*args\" assert arg.annotation ==", "function = module[\"f_posonly_default_poskw_default_kwonly_default\"] arg = function.arguments[0] assert arg is function.arguments[\"posonly\"] assert arg.name ==", "module.members assert len(module.members) == 11 # noqa: WPS432 function = module[\"f_posonly\"] assert len(function.arguments)", "arg = function.arguments[2] assert arg is function.arguments[\"kwonly\"] assert arg.name == \"kwonly\" assert arg.kind", "FIXTURES_DIR loader = GriffeLoader() def test_loading_functions_arguments(): # noqa: WPS218 \"\"\"Test functions arguments loading.\"\"\"", "inspect.Parameter.POSITIONAL_ONLY assert arg.default == \"0\" arg = function.arguments[1] assert arg is function.arguments[\"poskw\"] assert", "is None function = module[\"f_posonly_poskw_default\"] assert len(function.arguments) == 2 arg = function.arguments[0] assert", "module[\"f_posonly_poskw_kwonly_default\"] assert len(function.arguments) == 3 arg = function.arguments[0] assert arg is function.arguments[\"posonly\"] assert", "is function.arguments[\"kwonly\"] assert arg.name == \"kwonly\" assert arg.kind is inspect.Parameter.KEYWORD_ONLY assert arg.default ==", "arg = function.arguments[1] assert arg.annotation is None arg = function.arguments[2] assert arg.name ==", "function = module[\"f_posonly_poskw_default_kwonly_default\"] assert len(function.arguments) == 3 arg = function.arguments[0] assert arg is", "is inspect.Parameter.POSITIONAL_OR_KEYWORD assert arg.default == \"0\" function = module[\"f_posonly_default_poskw_default\"] assert len(function.arguments) == 2", "\"str\" arg = function.arguments[1] assert arg.annotation is None arg = function.arguments[2] assert arg.name", "\"poskw\" assert arg.kind is inspect.Parameter.POSITIONAL_OR_KEYWORD assert arg.default == \"0\" function = module[\"f_posonly_default_poskw_default\"] assert", "\"poskw\" assert arg.kind is inspect.Parameter.POSITIONAL_OR_KEYWORD assert arg.default is None arg = function.arguments[2] assert", "is None arg = function.arguments[2] assert arg.name == \"**kwargs\" assert arg.annotation == \"int\"", "arg.name == \"kwonly\" assert arg.kind is inspect.Parameter.KEYWORD_ONLY assert arg.default is None function =", "function.arguments[1] assert arg.annotation is None arg = function.arguments[2] assert arg.name == \"**kwargs\" assert", "\"kwonly\" assert arg.kind is inspect.Parameter.KEYWORD_ONLY assert arg.default == \"1\" function = module[\"f_posonly_default_poskw_default_kwonly_default\"] arg", "\"0\" function = module[\"f_posonly_default_poskw_default\"] assert len(function.arguments) == 2 arg = function.arguments[0] assert arg", "arg.default is None function = module[\"f_posonly_poskw_kwonly_default\"] assert len(function.arguments) == 3 arg = function.arguments[0]", "arg.name == \"posonly\" assert arg.kind is inspect.Parameter.POSITIONAL_ONLY assert arg.default == \"0\" function =", "function.arguments[2] assert arg is function.arguments[\"kwonly\"] assert arg.name == \"kwonly\" assert arg.kind is inspect.Parameter.KEYWORD_ONLY", "= function.arguments[0] assert arg.annotation == \"str\" arg = function.arguments[1] assert arg.annotation == \"Any\"", "test_loading_functions_arguments(): # noqa: WPS218 \"\"\"Test functions arguments loading.\"\"\" module = loader.load_module(FIXTURES_DIR / \"functions\"", "\"1\" function = module[\"f_posonly_default_poskw_default_kwonly_default\"] arg = function.arguments[0] assert arg is function.arguments[\"posonly\"] assert arg.name", "is inspect.Parameter.POSITIONAL_OR_KEYWORD assert arg.default == \"0\" arg = function.arguments[2] assert arg is function.arguments[\"kwonly\"]", "\"\"\"Test functions arguments loading.\"\"\" module = loader.load_module(FIXTURES_DIR / \"functions\" / \"arguments.py\") assert module.members", "arg = function.arguments[1] assert arg.annotation == \"Any\" arg = function.arguments[2] assert arg.annotation ==", "is function.arguments[\"posonly\"] assert arg.name == \"posonly\" assert arg.kind is inspect.Parameter.POSITIONAL_ONLY assert arg.default ==", "\"**kwargs\" assert arg.annotation == \"int\" function = module[\"f_annorations\"] assert len(function.arguments) == 4 arg", "arg.default is None arg = function.arguments[1] assert arg is function.arguments[\"poskw\"] assert arg.name ==", "inspect.Parameter.POSITIONAL_OR_KEYWORD assert arg.default is None arg = function.arguments[2] assert arg is function.arguments[\"kwonly\"] assert", "assert arg.name == \"posonly\" assert arg.kind is inspect.Parameter.POSITIONAL_ONLY assert arg.default == \"0\" arg", "\"0\" function = module[\"f_posonly_poskw_default_kwonly_default\"] assert len(function.arguments) == 3 arg = function.arguments[0] assert arg", "== \"poskw\" assert arg.kind is inspect.Parameter.POSITIONAL_OR_KEYWORD assert arg.default == \"0\" arg = function.arguments[2]", "== \"**kwargs\" assert arg.annotation == \"int\" function = module[\"f_annorations\"] assert len(function.arguments) == 4", "arg.annotation is None arg = function.arguments[2] assert arg.name == \"**kwargs\" assert arg.annotation ==", "== \"posonly\" assert arg.kind is inspect.Parameter.POSITIONAL_ONLY assert arg.default is None function = module[\"f_posonly_default\"]", "None arg = function.arguments[2] assert arg.name == \"**kwargs\" assert arg.annotation == \"int\" function", "arg.name == \"poskw\" assert arg.kind is inspect.Parameter.POSITIONAL_OR_KEYWORD assert arg.default is None function =", "function = module[\"f_posonly_poskw_default\"] assert len(function.arguments) == 2 arg = function.arguments[0] assert arg is", "= module[\"f_posonly_poskw_kwonly_default\"] assert len(function.arguments) == 3 arg = function.arguments[0] assert arg is function.arguments[\"posonly\"]", "function.arguments[0] assert arg is function.arguments[\"posonly\"] assert arg.name == \"posonly\" assert arg.kind is inspect.Parameter.POSITIONAL_ONLY", "arg.kind is inspect.Parameter.POSITIONAL_OR_KEYWORD assert arg.default == \"1\" arg = function.arguments[2] assert arg is", "import FIXTURES_DIR loader = GriffeLoader() def test_loading_functions_arguments(): # noqa: WPS218 \"\"\"Test functions arguments", "function = module[\"f_var\"] assert len(function.arguments) == 3 arg = function.arguments[0] assert arg.name ==", "assert len(module.members) == 11 # noqa: WPS432 function = module[\"f_posonly\"] assert len(function.arguments) ==", "function.arguments[0] assert arg.annotation == \"str\" arg = function.arguments[1] assert arg.annotation == \"Any\" arg", "assert len(function.arguments) == 2 arg = function.arguments[0] assert arg is function.arguments[\"posonly\"] assert arg.name", "== \"0\" arg = function.arguments[2] assert arg is function.arguments[\"kwonly\"] assert arg.name == \"kwonly\"", "arg.default == \"1\" arg = function.arguments[2] assert arg is function.arguments[\"kwonly\"] assert arg.name ==", "function.arguments[\"poskw\"] assert arg.name == \"poskw\" assert arg.kind is inspect.Parameter.POSITIONAL_OR_KEYWORD assert arg.default is None", "arg.name == \"posonly\" assert arg.kind is inspect.Parameter.POSITIONAL_ONLY assert arg.default is None function =", "len(function.arguments) == 3 arg = function.arguments[0] assert arg is function.arguments[\"posonly\"] assert arg.name ==", "function.arguments[\"posonly\"] assert arg.name == \"posonly\" assert arg.kind is inspect.Parameter.POSITIONAL_ONLY assert arg.default is None", "== \"str\" arg = function.arguments[1] assert arg.annotation == \"Any\" arg = function.arguments[2] assert", "\"Any\" arg = function.arguments[2] assert arg.annotation == \"typing.Optional[typing.List[int]]\" arg = function.arguments[3] assert arg.annotation", "= module[\"f_var\"] assert len(function.arguments) == 3 arg = function.arguments[0] assert arg.name == \"*args\"", "\"poskw\" assert arg.kind is inspect.Parameter.POSITIONAL_OR_KEYWORD assert arg.default == \"0\" arg = function.arguments[2] assert", "arg.default == \"0\" function = module[\"f_posonly_default_poskw_default\"] assert len(function.arguments) == 2 arg = function.arguments[0]", "== \"0\" function = module[\"f_posonly_default_poskw_default\"] assert len(function.arguments) == 2 arg = function.arguments[0] assert", "inspect.Parameter.POSITIONAL_ONLY assert arg.default == \"0\" function = module[\"f_posonly_poskw\"] assert len(function.arguments) == 2 arg", "import inspect from griffe.loader import GriffeLoader from tests import FIXTURES_DIR loader = GriffeLoader()", "\"functions\" / \"arguments.py\") assert module.members assert len(module.members) == 11 # noqa: WPS432 function", "assert arg.default == \"1\" function = module[\"f_posonly_poskw_kwonly\"] assert len(function.arguments) == 3 arg =", "assert arg.default is None function = module[\"f_posonly_poskw_kwonly_default\"] assert len(function.arguments) == 3 arg =", "module[\"f_posonly_default\"] assert len(function.arguments) == 1 arg = function.arguments[0] assert arg is function.arguments[\"posonly\"] assert", "module[\"f_var\"] assert len(function.arguments) == 3 arg = function.arguments[0] assert arg.name == \"*args\" assert", "== \"posonly\" assert arg.kind is inspect.Parameter.POSITIONAL_ONLY assert arg.default == \"0\" function = module[\"f_posonly_poskw\"]", "= function.arguments[0] assert arg.name == \"*args\" assert arg.annotation == \"str\" arg = function.arguments[1]", "is inspect.Parameter.KEYWORD_ONLY assert arg.default == \"1\" function = module[\"f_posonly_default_poskw_default_kwonly_default\"] arg = function.arguments[0] assert", "== \"0\" function = module[\"f_posonly_poskw_default_kwonly_default\"] assert len(function.arguments) == 3 arg = function.arguments[0] assert", "None arg = function.arguments[1] assert arg is function.arguments[\"poskw\"] assert arg.name == \"poskw\" assert", "arg.name == \"*args\" assert arg.annotation == \"str\" arg = function.arguments[1] assert arg.annotation is", "module[\"f_posonly_poskw_kwonly\"] assert len(function.arguments) == 3 arg = function.arguments[0] assert arg is function.arguments[\"posonly\"] assert", "== \"poskw\" assert arg.kind is inspect.Parameter.POSITIONAL_OR_KEYWORD assert arg.default is None function = module[\"f_posonly_poskw_default\"]", "arg.kind is inspect.Parameter.KEYWORD_ONLY assert arg.default is None function = module[\"f_posonly_poskw_kwonly_default\"] assert len(function.arguments) ==", "is inspect.Parameter.POSITIONAL_OR_KEYWORD assert arg.default == \"1\" arg = function.arguments[2] assert arg is function.arguments[\"kwonly\"]", "is inspect.Parameter.POSITIONAL_ONLY assert arg.default == \"0\" function = module[\"f_posonly_poskw\"] assert len(function.arguments) == 2", "== \"Any\" arg = function.arguments[2] assert arg.annotation == \"typing.Optional[typing.List[int]]\" arg = function.arguments[3] assert", "function = module[\"f_posonly_poskw_kwonly_default\"] assert len(function.arguments) == 3 arg = function.arguments[0] assert arg is", "function.arguments[2] assert arg.annotation == \"typing.Optional[typing.List[int]]\" arg = function.arguments[3] assert arg.annotation == \"float |", "assert arg.name == \"poskw\" assert arg.kind is inspect.Parameter.POSITIONAL_OR_KEYWORD assert arg.default is None arg", "== \"poskw\" assert arg.kind is inspect.Parameter.POSITIONAL_OR_KEYWORD assert arg.default is None arg = function.arguments[2]", "assert arg.default == \"2\" function = module[\"f_var\"] assert len(function.arguments) == 3 arg =", "\"0\" arg = function.arguments[1] assert arg is function.arguments[\"poskw\"] assert arg.name == \"poskw\" assert", "assert arg.default is None arg = function.arguments[2] assert arg is function.arguments[\"kwonly\"] assert arg.name", "is None function = module[\"f_posonly_default\"] assert len(function.arguments) == 1 arg = function.arguments[0] assert", "3 arg = function.arguments[0] assert arg.name == \"*args\" assert arg.annotation == \"str\" arg", "assert arg.name == \"kwonly\" assert arg.kind is inspect.Parameter.KEYWORD_ONLY assert arg.default == \"1\" function", "module[\"f_posonly_default_poskw_default\"] assert len(function.arguments) == 2 arg = function.arguments[0] assert arg is function.arguments[\"posonly\"] assert", "from griffe.loader import GriffeLoader from tests import FIXTURES_DIR loader = GriffeLoader() def test_loading_functions_arguments():", "4 arg = function.arguments[0] assert arg.annotation == \"str\" arg = function.arguments[1] assert arg.annotation", "function = module[\"f_posonly\"] assert len(function.arguments) == 1 arg = function.arguments[0] assert arg is", "== \"0\" arg = function.arguments[1] assert arg is function.arguments[\"poskw\"] assert arg.name == \"poskw\"", "is None arg = function.arguments[1] assert arg is function.arguments[\"poskw\"] assert arg.name == \"poskw\"", "assert arg.name == \"**kwargs\" assert arg.annotation == \"int\" function = module[\"f_annorations\"] assert len(function.arguments)", "arg.name == \"kwonly\" assert arg.kind is inspect.Parameter.KEYWORD_ONLY assert arg.default == \"0\" function =", "\"0\" function = module[\"f_posonly_poskw\"] assert len(function.arguments) == 2 arg = function.arguments[0] assert arg", "assert arg.name == \"poskw\" assert arg.kind is inspect.Parameter.POSITIONAL_OR_KEYWORD assert arg.default == \"0\" arg", "\"posonly\" assert arg.kind is inspect.Parameter.POSITIONAL_ONLY assert arg.default is None function = module[\"f_posonly_default\"] assert", "function.arguments[0] assert arg.name == \"*args\" assert arg.annotation == \"str\" arg = function.arguments[1] assert", "is function.arguments[\"poskw\"] assert arg.name == \"poskw\" assert arg.kind is inspect.Parameter.POSITIONAL_OR_KEYWORD assert arg.default ==", "function = module[\"f_posonly_default_poskw_default\"] assert len(function.arguments) == 2 arg = function.arguments[0] assert arg is", "== \"kwonly\" assert arg.kind is inspect.Parameter.KEYWORD_ONLY assert arg.default == \"1\" function = module[\"f_posonly_default_poskw_default_kwonly_default\"]", "assert arg.kind is inspect.Parameter.KEYWORD_ONLY assert arg.default == \"1\" function = module[\"f_posonly_default_poskw_default_kwonly_default\"] arg =", "\"poskw\" assert arg.kind is inspect.Parameter.POSITIONAL_OR_KEYWORD assert arg.default is None function = module[\"f_posonly_poskw_default\"] assert", "= function.arguments[1] assert arg.annotation is None arg = function.arguments[2] assert arg.name == \"**kwargs\"", "is inspect.Parameter.POSITIONAL_OR_KEYWORD assert arg.default is None function = module[\"f_posonly_poskw_default\"] assert len(function.arguments) == 2", "arg.default == \"1\" function = module[\"f_posonly_default_poskw_default_kwonly_default\"] arg = function.arguments[0] assert arg is function.arguments[\"posonly\"]", "= module[\"f_posonly_default_poskw_default\"] assert len(function.arguments) == 2 arg = function.arguments[0] assert arg is function.arguments[\"posonly\"]", "assert arg.kind is inspect.Parameter.POSITIONAL_OR_KEYWORD assert arg.default == \"0\" function = module[\"f_posonly_default_poskw_default\"] assert len(function.arguments)", "\"int\" function = module[\"f_annorations\"] assert len(function.arguments) == 4 arg = function.arguments[0] assert arg.annotation", "\"posonly\" assert arg.kind is inspect.Parameter.POSITIONAL_ONLY assert arg.default == \"0\" function = module[\"f_posonly_poskw\"] assert", "assert arg.default is None arg = function.arguments[1] assert arg is function.arguments[\"poskw\"] assert arg.name", "assert arg.default == \"0\" arg = function.arguments[2] assert arg is function.arguments[\"kwonly\"] assert arg.name", "= module[\"f_posonly_poskw_kwonly\"] assert len(function.arguments) == 3 arg = function.arguments[0] assert arg is function.arguments[\"posonly\"]", "assert arg.name == \"posonly\" assert arg.kind is inspect.Parameter.POSITIONAL_ONLY assert arg.default == \"0\" function", "function.arguments[1] assert arg.annotation == \"Any\" arg = function.arguments[2] assert arg.annotation == \"typing.Optional[typing.List[int]]\" arg", "== \"poskw\" assert arg.kind is inspect.Parameter.POSITIONAL_OR_KEYWORD assert arg.default == \"1\" function = module[\"f_posonly_poskw_kwonly\"]", "arg.kind is inspect.Parameter.KEYWORD_ONLY assert arg.default == \"2\" function = module[\"f_var\"] assert len(function.arguments) ==", "function.arguments[\"kwonly\"] assert arg.name == \"kwonly\" assert arg.kind is inspect.Parameter.KEYWORD_ONLY assert arg.default is None", "arg.name == \"poskw\" assert arg.kind is inspect.Parameter.POSITIONAL_OR_KEYWORD assert arg.default == \"0\" arg =", "arg = function.arguments[0] assert arg.name == \"*args\" assert arg.annotation == \"str\" arg =", "assert arg.annotation == \"Any\" arg = function.arguments[2] assert arg.annotation == \"typing.Optional[typing.List[int]]\" arg =", "WPS218 \"\"\"Test functions arguments loading.\"\"\" module = loader.load_module(FIXTURES_DIR / \"functions\" / \"arguments.py\") assert", "arg.kind is inspect.Parameter.KEYWORD_ONLY assert arg.default == \"1\" function = module[\"f_posonly_default_poskw_default_kwonly_default\"] arg = function.arguments[0]", "\"posonly\" assert arg.kind is inspect.Parameter.POSITIONAL_ONLY assert arg.default == \"0\" arg = function.arguments[1] assert", "assert arg.name == \"poskw\" assert arg.kind is inspect.Parameter.POSITIONAL_OR_KEYWORD assert arg.default == \"1\" function", "assert arg.kind is inspect.Parameter.POSITIONAL_OR_KEYWORD assert arg.default == \"1\" arg = function.arguments[2] assert arg", "loader = GriffeLoader() def test_loading_functions_arguments(): # noqa: WPS218 \"\"\"Test functions arguments loading.\"\"\" module", "== \"int\" function = module[\"f_annorations\"] assert len(function.arguments) == 4 arg = function.arguments[0] assert", "arg.default is None function = module[\"f_posonly_default\"] assert len(function.arguments) == 1 arg = function.arguments[0]", "def test_loading_functions_arguments(): # noqa: WPS218 \"\"\"Test functions arguments loading.\"\"\" module = loader.load_module(FIXTURES_DIR /", "\"2\" function = module[\"f_var\"] assert len(function.arguments) == 3 arg = function.arguments[0] assert arg.name", "is inspect.Parameter.POSITIONAL_OR_KEYWORD assert arg.default == \"1\" function = module[\"f_posonly_poskw_kwonly\"] assert len(function.arguments) == 3", "\"1\" function = module[\"f_posonly_poskw_kwonly\"] assert len(function.arguments) == 3 arg = function.arguments[0] assert arg", "is None arg = function.arguments[2] assert arg is function.arguments[\"kwonly\"] assert arg.name == \"kwonly\"", "assert arg.default is None function = module[\"f_posonly_default\"] assert len(function.arguments) == 1 arg =", "import GriffeLoader from tests import FIXTURES_DIR loader = GriffeLoader() def test_loading_functions_arguments(): # noqa:", "= function.arguments[1] assert arg.annotation == \"Any\" arg = function.arguments[2] assert arg.annotation == \"typing.Optional[typing.List[int]]\"", "\"posonly\" assert arg.kind is inspect.Parameter.POSITIONAL_ONLY assert arg.default is None arg = function.arguments[1] assert", "assert arg.kind is inspect.Parameter.POSITIONAL_ONLY assert arg.default is None arg = function.arguments[1] assert arg", "assert arg.name == \"poskw\" assert arg.kind is inspect.Parameter.POSITIONAL_OR_KEYWORD assert arg.default is None function", "is inspect.Parameter.KEYWORD_ONLY assert arg.default is None function = module[\"f_posonly_poskw_kwonly_default\"] assert len(function.arguments) == 3", "\"1\" arg = function.arguments[2] assert arg is function.arguments[\"kwonly\"] assert arg.name == \"kwonly\" assert", "== 4 arg = function.arguments[0] assert arg.annotation == \"str\" arg = function.arguments[1] assert", "\"\"\"Test functions loading.\"\"\" import inspect from griffe.loader import GriffeLoader from tests import FIXTURES_DIR", "arg = function.arguments[0] assert arg.annotation == \"str\" arg = function.arguments[1] assert arg.annotation ==", "assert arg.name == \"poskw\" assert arg.kind is inspect.Parameter.POSITIONAL_OR_KEYWORD assert arg.default == \"1\" arg", "= module[\"f_posonly_poskw_default_kwonly_default\"] assert len(function.arguments) == 3 arg = function.arguments[0] assert arg is function.arguments[\"posonly\"]", "is inspect.Parameter.KEYWORD_ONLY assert arg.default == \"0\" function = module[\"f_posonly_poskw_default_kwonly_default\"] assert len(function.arguments) == 3", "arg.default == \"0\" arg = function.arguments[1] assert arg is function.arguments[\"poskw\"] assert arg.name ==", "griffe.loader import GriffeLoader from tests import FIXTURES_DIR loader = GriffeLoader() def test_loading_functions_arguments(): #", "len(function.arguments) == 1 arg = function.arguments[0] assert arg is function.arguments[\"posonly\"] assert arg.name ==", "functions arguments loading.\"\"\" module = loader.load_module(FIXTURES_DIR / \"functions\" / \"arguments.py\") assert module.members assert", "arg.default == \"0\" function = module[\"f_posonly_poskw_default_kwonly_default\"] assert len(function.arguments) == 3 arg = function.arguments[0]", "== \"*args\" assert arg.annotation == \"str\" arg = function.arguments[1] assert arg.annotation is None", "assert arg.name == \"*args\" assert arg.annotation == \"str\" arg = function.arguments[1] assert arg.annotation", "\"0\" arg = function.arguments[2] assert arg is function.arguments[\"kwonly\"] assert arg.name == \"kwonly\" assert", "function = module[\"f_posonly_default\"] assert len(function.arguments) == 1 arg = function.arguments[0] assert arg is", "assert arg.kind is inspect.Parameter.POSITIONAL_ONLY assert arg.default is None function = module[\"f_posonly_default\"] assert len(function.arguments)", "assert module.members assert len(module.members) == 11 # noqa: WPS432 function = module[\"f_posonly\"] assert", "arg.name == \"**kwargs\" assert arg.annotation == \"int\" function = module[\"f_annorations\"] assert len(function.arguments) ==", "assert arg.annotation == \"typing.Optional[typing.List[int]]\" arg = function.arguments[3] assert arg.annotation == \"float | None\"", "1 arg = function.arguments[0] assert arg is function.arguments[\"posonly\"] assert arg.name == \"posonly\" assert", "arg.kind is inspect.Parameter.POSITIONAL_ONLY assert arg.default is None function = module[\"f_posonly_default\"] assert len(function.arguments) ==", "\"kwonly\" assert arg.kind is inspect.Parameter.KEYWORD_ONLY assert arg.default is None function = module[\"f_posonly_poskw_kwonly_default\"] assert", "is inspect.Parameter.POSITIONAL_ONLY assert arg.default == \"0\" arg = function.arguments[1] assert arg is function.arguments[\"poskw\"]", "== \"kwonly\" assert arg.kind is inspect.Parameter.KEYWORD_ONLY assert arg.default == \"0\" function = module[\"f_posonly_poskw_default_kwonly_default\"]", "arg.annotation == \"int\" function = module[\"f_annorations\"] assert len(function.arguments) == 4 arg = function.arguments[0]", "= module[\"f_posonly_default_poskw_default_kwonly_default\"] arg = function.arguments[0] assert arg is function.arguments[\"posonly\"] assert arg.name == \"posonly\"", "arg.name == \"poskw\" assert arg.kind is inspect.Parameter.POSITIONAL_OR_KEYWORD assert arg.default == \"0\" function =", "arg.default is None function = module[\"f_posonly_poskw_default\"] assert len(function.arguments) == 2 arg = function.arguments[0]", "assert arg.kind is inspect.Parameter.POSITIONAL_OR_KEYWORD assert arg.default is None arg = function.arguments[2] assert arg", "module[\"f_annorations\"] assert len(function.arguments) == 4 arg = function.arguments[0] assert arg.annotation == \"str\" arg", "= function.arguments[2] assert arg is function.arguments[\"kwonly\"] assert arg.name == \"kwonly\" assert arg.kind is", "arg.kind is inspect.Parameter.POSITIONAL_ONLY assert arg.default is None arg = function.arguments[1] assert arg is", "assert len(function.arguments) == 1 arg = function.arguments[0] assert arg is function.arguments[\"posonly\"] assert arg.name", "assert len(function.arguments) == 3 arg = function.arguments[0] assert arg.name == \"*args\" assert arg.annotation", "function = module[\"f_posonly_poskw\"] assert len(function.arguments) == 2 arg = function.arguments[0] assert arg is", "loading.\"\"\" import inspect from griffe.loader import GriffeLoader from tests import FIXTURES_DIR loader =", "= module[\"f_posonly_poskw_default\"] assert len(function.arguments) == 2 arg = function.arguments[0] assert arg is function.arguments[\"posonly\"]", "is inspect.Parameter.POSITIONAL_ONLY assert arg.default is None arg = function.arguments[1] assert arg is function.arguments[\"poskw\"]", "GriffeLoader() def test_loading_functions_arguments(): # noqa: WPS218 \"\"\"Test functions arguments loading.\"\"\" module = loader.load_module(FIXTURES_DIR", "arg.name == \"kwonly\" assert arg.kind is inspect.Parameter.KEYWORD_ONLY assert arg.default == \"1\" function =", "arg is function.arguments[\"poskw\"] assert arg.name == \"poskw\" assert arg.kind is inspect.Parameter.POSITIONAL_OR_KEYWORD assert arg.default", "== \"poskw\" assert arg.kind is inspect.Parameter.POSITIONAL_OR_KEYWORD assert arg.default == \"0\" function = module[\"f_posonly_default_poskw_default\"]", "/ \"arguments.py\") assert module.members assert len(module.members) == 11 # noqa: WPS432 function =", "arg.name == \"poskw\" assert arg.kind is inspect.Parameter.POSITIONAL_OR_KEYWORD assert arg.default is None arg =", "None arg = function.arguments[2] assert arg is function.arguments[\"kwonly\"] assert arg.name == \"kwonly\" assert", "assert arg.kind is inspect.Parameter.POSITIONAL_OR_KEYWORD assert arg.default == \"0\" arg = function.arguments[2] assert arg", "is function.arguments[\"posonly\"] assert arg.name == \"posonly\" assert arg.kind is inspect.Parameter.POSITIONAL_ONLY assert arg.default is", "arg.default is None arg = function.arguments[2] assert arg is function.arguments[\"kwonly\"] assert arg.name ==", "arg.kind is inspect.Parameter.POSITIONAL_OR_KEYWORD assert arg.default == \"0\" function = module[\"f_posonly_default_poskw_default\"] assert len(function.arguments) ==", "function.arguments[\"kwonly\"] assert arg.name == \"kwonly\" assert arg.kind is inspect.Parameter.KEYWORD_ONLY assert arg.default == \"0\"", "arg is function.arguments[\"kwonly\"] assert arg.name == \"kwonly\" assert arg.kind is inspect.Parameter.KEYWORD_ONLY assert arg.default", "= module[\"f_posonly_poskw\"] assert len(function.arguments) == 2 arg = function.arguments[0] assert arg is function.arguments[\"posonly\"]", "inspect.Parameter.KEYWORD_ONLY assert arg.default == \"1\" function = module[\"f_posonly_default_poskw_default_kwonly_default\"] arg = function.arguments[0] assert arg", "assert arg.kind is inspect.Parameter.POSITIONAL_ONLY assert arg.default == \"0\" arg = function.arguments[1] assert arg", "arg.kind is inspect.Parameter.POSITIONAL_ONLY assert arg.default == \"0\" arg = function.arguments[1] assert arg is", "assert arg.name == \"posonly\" assert arg.kind is inspect.Parameter.POSITIONAL_ONLY assert arg.default is None function", "== \"posonly\" assert arg.kind is inspect.Parameter.POSITIONAL_ONLY assert arg.default is None arg = function.arguments[1]", "\"kwonly\" assert arg.kind is inspect.Parameter.KEYWORD_ONLY assert arg.default == \"2\" function = module[\"f_var\"] assert", "GriffeLoader from tests import FIXTURES_DIR loader = GriffeLoader() def test_loading_functions_arguments(): # noqa: WPS218", "len(module.members) == 11 # noqa: WPS432 function = module[\"f_posonly\"] assert len(function.arguments) == 1", "is function.arguments[\"poskw\"] assert arg.name == \"poskw\" assert arg.kind is inspect.Parameter.POSITIONAL_OR_KEYWORD assert arg.default is", "function.arguments[\"kwonly\"] assert arg.name == \"kwonly\" assert arg.kind is inspect.Parameter.KEYWORD_ONLY assert arg.default == \"1\"", "== \"0\" function = module[\"f_posonly_poskw\"] assert len(function.arguments) == 2 arg = function.arguments[0] assert", "assert arg.kind is inspect.Parameter.POSITIONAL_ONLY assert arg.default == \"0\" function = module[\"f_posonly_poskw\"] assert len(function.arguments)", "function = module[\"f_posonly_poskw_kwonly\"] assert len(function.arguments) == 3 arg = function.arguments[0] assert arg is", "module[\"f_posonly_poskw_default\"] assert len(function.arguments) == 2 arg = function.arguments[0] assert arg is function.arguments[\"posonly\"] assert", "function.arguments[\"poskw\"] assert arg.name == \"poskw\" assert arg.kind is inspect.Parameter.POSITIONAL_OR_KEYWORD assert arg.default == \"0\"", "== 1 arg = function.arguments[0] assert arg is function.arguments[\"posonly\"] assert arg.name == \"posonly\"", "== \"poskw\" assert arg.kind is inspect.Parameter.POSITIONAL_OR_KEYWORD assert arg.default == \"1\" arg = function.arguments[2]", "arg.default == \"0\" arg = function.arguments[2] assert arg is function.arguments[\"kwonly\"] assert arg.name ==", "inspect.Parameter.POSITIONAL_ONLY assert arg.default is None function = module[\"f_posonly_default\"] assert len(function.arguments) == 1 arg", "module[\"f_posonly_default_poskw_default_kwonly_default\"] arg = function.arguments[0] assert arg is function.arguments[\"posonly\"] assert arg.name == \"posonly\" assert", "assert arg.kind is inspect.Parameter.KEYWORD_ONLY assert arg.default is None function = module[\"f_posonly_poskw_kwonly_default\"] assert len(function.arguments)", "assert arg.name == \"kwonly\" assert arg.kind is inspect.Parameter.KEYWORD_ONLY assert arg.default is None function", "module = loader.load_module(FIXTURES_DIR / \"functions\" / \"arguments.py\") assert module.members assert len(module.members) == 11", "inspect from griffe.loader import GriffeLoader from tests import FIXTURES_DIR loader = GriffeLoader() def", "arg.kind is inspect.Parameter.KEYWORD_ONLY assert arg.default == \"0\" function = module[\"f_posonly_poskw_default_kwonly_default\"] assert len(function.arguments) ==", "== \"1\" function = module[\"f_posonly_poskw_kwonly\"] assert len(function.arguments) == 3 arg = function.arguments[0] assert", "inspect.Parameter.POSITIONAL_OR_KEYWORD assert arg.default is None function = module[\"f_posonly_poskw_default\"] assert len(function.arguments) == 2 arg", "inspect.Parameter.KEYWORD_ONLY assert arg.default == \"0\" function = module[\"f_posonly_poskw_default_kwonly_default\"] assert len(function.arguments) == 3 arg", "assert arg is function.arguments[\"kwonly\"] assert arg.name == \"kwonly\" assert arg.kind is inspect.Parameter.KEYWORD_ONLY assert", "\"poskw\" assert arg.kind is inspect.Parameter.POSITIONAL_OR_KEYWORD assert arg.default == \"1\" arg = function.arguments[2] assert", "/ \"functions\" / \"arguments.py\") assert module.members assert len(module.members) == 11 # noqa: WPS432", "len(function.arguments) == 2 arg = function.arguments[0] assert arg is function.arguments[\"posonly\"] assert arg.name ==", "== \"1\" function = module[\"f_posonly_default_poskw_default_kwonly_default\"] arg = function.arguments[0] assert arg is function.arguments[\"posonly\"] assert", "== \"kwonly\" assert arg.kind is inspect.Parameter.KEYWORD_ONLY assert arg.default is None function = module[\"f_posonly_poskw_kwonly_default\"]", "arguments loading.\"\"\" module = loader.load_module(FIXTURES_DIR / \"functions\" / \"arguments.py\") assert module.members assert len(module.members)", "arg = function.arguments[2] assert arg.annotation == \"typing.Optional[typing.List[int]]\" arg = function.arguments[3] assert arg.annotation ==", "assert arg.default == \"1\" function = module[\"f_posonly_default_poskw_default_kwonly_default\"] arg = function.arguments[0] assert arg is", "assert arg.name == \"poskw\" assert arg.kind is inspect.Parameter.POSITIONAL_OR_KEYWORD assert arg.default == \"0\" function", "tests import FIXTURES_DIR loader = GriffeLoader() def test_loading_functions_arguments(): # noqa: WPS218 \"\"\"Test functions", "= module[\"f_annorations\"] assert len(function.arguments) == 4 arg = function.arguments[0] assert arg.annotation == \"str\"", "function.arguments[\"kwonly\"] assert arg.name == \"kwonly\" assert arg.kind is inspect.Parameter.KEYWORD_ONLY assert arg.default == \"2\"", "== \"2\" function = module[\"f_var\"] assert len(function.arguments) == 3 arg = function.arguments[0] assert", "len(function.arguments) == 4 arg = function.arguments[0] assert arg.annotation == \"str\" arg = function.arguments[1]", "= module[\"f_posonly_default\"] assert len(function.arguments) == 1 arg = function.arguments[0] assert arg is function.arguments[\"posonly\"]", "= function.arguments[2] assert arg.name == \"**kwargs\" assert arg.annotation == \"int\" function = module[\"f_annorations\"]", "None function = module[\"f_posonly_default\"] assert len(function.arguments) == 1 arg = function.arguments[0] assert arg", "arg.name == \"posonly\" assert arg.kind is inspect.Parameter.POSITIONAL_ONLY assert arg.default is None arg =", "inspect.Parameter.POSITIONAL_OR_KEYWORD assert arg.default == \"0\" function = module[\"f_posonly_default_poskw_default\"] assert len(function.arguments) == 2 arg", "function.arguments[2] assert arg.name == \"**kwargs\" assert arg.annotation == \"int\" function = module[\"f_annorations\"] assert", "loader.load_module(FIXTURES_DIR / \"functions\" / \"arguments.py\") assert module.members assert len(module.members) == 11 # noqa:", "assert arg.name == \"posonly\" assert arg.kind is inspect.Parameter.POSITIONAL_ONLY assert arg.default is None arg", "is inspect.Parameter.POSITIONAL_ONLY assert arg.default is None function = module[\"f_posonly_default\"] assert len(function.arguments) == 1", "assert arg.name == \"kwonly\" assert arg.kind is inspect.Parameter.KEYWORD_ONLY assert arg.default == \"2\" function", "functions loading.\"\"\" import inspect from griffe.loader import GriffeLoader from tests import FIXTURES_DIR loader", "\"kwonly\" assert arg.kind is inspect.Parameter.KEYWORD_ONLY assert arg.default == \"0\" function = module[\"f_posonly_poskw_default_kwonly_default\"] assert", "# noqa: WPS432 function = module[\"f_posonly\"] assert len(function.arguments) == 1 arg = function.arguments[0]", "function.arguments[\"posonly\"] assert arg.name == \"posonly\" assert arg.kind is inspect.Parameter.POSITIONAL_ONLY assert arg.default == \"0\"", "arg.annotation == \"str\" arg = function.arguments[1] assert arg.annotation == \"Any\" arg = function.arguments[2]", "assert arg.annotation == \"int\" function = module[\"f_annorations\"] assert len(function.arguments) == 4 arg =", "== 3 arg = function.arguments[0] assert arg is function.arguments[\"posonly\"] assert arg.name == \"posonly\"", "inspect.Parameter.KEYWORD_ONLY assert arg.default is None function = module[\"f_posonly_poskw_kwonly_default\"] assert len(function.arguments) == 3 arg", "is None function = module[\"f_posonly_poskw_kwonly_default\"] assert len(function.arguments) == 3 arg = function.arguments[0] assert", "arg.kind is inspect.Parameter.POSITIONAL_OR_KEYWORD assert arg.default == \"1\" function = module[\"f_posonly_poskw_kwonly\"] assert len(function.arguments) ==", "\"str\" arg = function.arguments[1] assert arg.annotation == \"Any\" arg = function.arguments[2] assert arg.annotation", "inspect.Parameter.POSITIONAL_OR_KEYWORD assert arg.default == \"1\" arg = function.arguments[2] assert arg is function.arguments[\"kwonly\"] assert", "\"*args\" assert arg.annotation == \"str\" arg = function.arguments[1] assert arg.annotation is None arg", "assert arg.default == \"0\" function = module[\"f_posonly_poskw\"] assert len(function.arguments) == 2 arg =", "assert arg.default == \"0\" arg = function.arguments[1] assert arg is function.arguments[\"poskw\"] assert arg.name", "assert arg.name == \"kwonly\" assert arg.kind is inspect.Parameter.KEYWORD_ONLY assert arg.default == \"0\" function", "# noqa: WPS218 \"\"\"Test functions arguments loading.\"\"\" module = loader.load_module(FIXTURES_DIR / \"functions\" /", "= function.arguments[2] assert arg.annotation == \"typing.Optional[typing.List[int]]\" arg = function.arguments[3] assert arg.annotation == \"float", "== \"posonly\" assert arg.kind is inspect.Parameter.POSITIONAL_ONLY assert arg.default == \"0\" arg = function.arguments[1]", "function.arguments[1] assert arg is function.arguments[\"poskw\"] assert arg.name == \"poskw\" assert arg.kind is inspect.Parameter.POSITIONAL_OR_KEYWORD", "is inspect.Parameter.KEYWORD_ONLY assert arg.default == \"2\" function = module[\"f_var\"] assert len(function.arguments) == 3", "arg.kind is inspect.Parameter.POSITIONAL_OR_KEYWORD assert arg.default == \"0\" arg = function.arguments[2] assert arg is", "module[\"f_posonly\"] assert len(function.arguments) == 1 arg = function.arguments[0] assert arg is function.arguments[\"posonly\"] assert", "noqa: WPS432 function = module[\"f_posonly\"] assert len(function.arguments) == 1 arg = function.arguments[0] assert", "assert arg.default == \"1\" arg = function.arguments[2] assert arg is function.arguments[\"kwonly\"] assert arg.name", "assert arg is function.arguments[\"posonly\"] assert arg.name == \"posonly\" assert arg.kind is inspect.Parameter.POSITIONAL_ONLY assert", "arg = function.arguments[2] assert arg.name == \"**kwargs\" assert arg.annotation == \"int\" function =", "arg = function.arguments[1] assert arg is function.arguments[\"poskw\"] assert arg.name == \"poskw\" assert arg.kind", "arg.kind is inspect.Parameter.POSITIONAL_OR_KEYWORD assert arg.default is None function = module[\"f_posonly_poskw_default\"] assert len(function.arguments) ==", "arg.default == \"0\" function = module[\"f_posonly_poskw\"] assert len(function.arguments) == 2 arg = function.arguments[0]", "assert arg.kind is inspect.Parameter.KEYWORD_ONLY assert arg.default == \"2\" function = module[\"f_var\"] assert len(function.arguments)", "assert arg.kind is inspect.Parameter.POSITIONAL_OR_KEYWORD assert arg.default is None function = module[\"f_posonly_poskw_default\"] assert len(function.arguments)", "arg.kind is inspect.Parameter.POSITIONAL_OR_KEYWORD assert arg.default is None arg = function.arguments[2] assert arg is", "noqa: WPS218 \"\"\"Test functions arguments loading.\"\"\" module = loader.load_module(FIXTURES_DIR / \"functions\" / \"arguments.py\")", "None function = module[\"f_posonly_poskw_default\"] assert len(function.arguments) == 2 arg = function.arguments[0] assert arg", "inspect.Parameter.POSITIONAL_OR_KEYWORD assert arg.default == \"1\" function = module[\"f_posonly_poskw_kwonly\"] assert len(function.arguments) == 3 arg", "\"poskw\" assert arg.kind is inspect.Parameter.POSITIONAL_OR_KEYWORD assert arg.default == \"1\" function = module[\"f_posonly_poskw_kwonly\"] assert", "= GriffeLoader() def test_loading_functions_arguments(): # noqa: WPS218 \"\"\"Test functions arguments loading.\"\"\" module =", "11 # noqa: WPS432 function = module[\"f_posonly\"] assert len(function.arguments) == 1 arg =", "WPS432 function = module[\"f_posonly\"] assert len(function.arguments) == 1 arg = function.arguments[0] assert arg", "None function = module[\"f_posonly_poskw_kwonly_default\"] assert len(function.arguments) == 3 arg = function.arguments[0] assert arg", "== \"kwonly\" assert arg.kind is inspect.Parameter.KEYWORD_ONLY assert arg.default == \"2\" function = module[\"f_var\"]", "module[\"f_posonly_poskw\"] assert len(function.arguments) == 2 arg = function.arguments[0] assert arg is function.arguments[\"posonly\"] assert", "= loader.load_module(FIXTURES_DIR / \"functions\" / \"arguments.py\") assert module.members assert len(module.members) == 11 #", "= function.arguments[0] assert arg is function.arguments[\"posonly\"] assert arg.name == \"posonly\" assert arg.kind is", "arg.annotation == \"str\" arg = function.arguments[1] assert arg.annotation is None arg = function.arguments[2]", "assert arg.annotation is None arg = function.arguments[2] assert arg.name == \"**kwargs\" assert arg.annotation", "arg.default == \"2\" function = module[\"f_var\"] assert len(function.arguments) == 3 arg = function.arguments[0]", "assert arg.annotation == \"str\" arg = function.arguments[1] assert arg.annotation is None arg =", "module[\"f_posonly_poskw_default_kwonly_default\"] assert len(function.arguments) == 3 arg = function.arguments[0] assert arg is function.arguments[\"posonly\"] assert", "== \"1\" arg = function.arguments[2] assert arg is function.arguments[\"kwonly\"] assert arg.name == \"kwonly\"" ]
[ "if __name__ == '__main__': characters = string.ascii_lowercase + string.ascii_uppercase + string.digits password =", "import random from random import randint if __name__ == '__main__': characters = string.ascii_lowercase", "randint if __name__ == '__main__': characters = string.ascii_lowercase + string.ascii_uppercase + string.digits password", "string.ascii_lowercase + string.ascii_uppercase + string.digits password = ''.join(random.choice(characters) for x in range(randint(8,16))) print('Password:\\t',password)", "Generic Imports ---# import string import random from random import randint if __name__", "= string.ascii_lowercase + string.ascii_uppercase + string.digits password = ''.join(random.choice(characters) for x in range(randint(8,16)))", "from random import randint if __name__ == '__main__': characters = string.ascii_lowercase + string.ascii_uppercase", "import randint if __name__ == '__main__': characters = string.ascii_lowercase + string.ascii_uppercase + string.digits", "import string import random from random import randint if __name__ == '__main__': characters", "#--- Generic Imports ---# import string import random from random import randint if", "Imports ---# import string import random from random import randint if __name__ ==", "<gh_stars>0 #--- Generic Imports ---# import string import random from random import randint", "---# import string import random from random import randint if __name__ == '__main__':", "characters = string.ascii_lowercase + string.ascii_uppercase + string.digits password = ''.join(random.choice(characters) for x in", "string import random from random import randint if __name__ == '__main__': characters =", "random import randint if __name__ == '__main__': characters = string.ascii_lowercase + string.ascii_uppercase +", "random from random import randint if __name__ == '__main__': characters = string.ascii_lowercase +", "'__main__': characters = string.ascii_lowercase + string.ascii_uppercase + string.digits password = ''.join(random.choice(characters) for x", "== '__main__': characters = string.ascii_lowercase + string.ascii_uppercase + string.digits password = ''.join(random.choice(characters) for", "__name__ == '__main__': characters = string.ascii_lowercase + string.ascii_uppercase + string.digits password = ''.join(random.choice(characters)" ]
[ "view that we have neglected R=scipy.sparse.dia_matrix((Rdata[nfibers/2],offsets),(nwave,nwave)) Rt=R.transpose() sky=numpy.dot(R.toarray(),deconvolvedsky) print \"computing covmat\" skycovmat=Rt.dot(Rt.dot(dskycovmat).transpose()) skyvar=numpy.diag(skycovmat)", "the sky variance because expensive and in any case approximate because we only", "outfilename=sys.argv[3] skyfilename=\"\" if(len(sys.argv)>3) : skyfilename=sys.argv[4] # get spectrograph id, hardcoded for now, will", "myfiberid-=500 skyfibers.append(myfiberid) file.close() print \"skyfibers (now starting at 0)=\",skyfibers hdulist=pyfits.open(infilename) spectra=hdulist[0].data invar=hdulist[1].data wave=hdulist[2].data", "specid : continue fiberId=string.atoi(vals[25]) #print line #print objType,spectrographId,fiberId myfiberid=fiberId-1 if specid==2 : myfiberid-=500", "line in file.readlines() : if line.find(\"PLUGMAPOBJ\") != 0 : continue vals=string.split(line,\" \") holetype=vals[8]", "skyvar=numpy.diag(skycovmat) print \"done\" if skyfilename != \"\" : print \"writing skymodel to\",skyfilename skyinvar=1/numpy.diag(skycovmat)", "continue objType=vals[21] if objType != \"SKY\" : continue spectrographId=string.atoi(vals[24]) if spectrographId != specid", "if(len(sys.argv)>3) : skyfilename=sys.argv[4] # get spectrograph id, hardcoded for now, will be read", "# fiber that is already included in the invar of each spectrum #", "if skyfilename != \"\" : print \"writing skymodel to\",skyfilename skyinvar=1/numpy.diag(skycovmat) sky_array=numpy.zeros((1,sky.shape[0])) sky_array[0]=sky skyinvar_array=numpy.zeros((1,skyinvar.shape[0]))", "fibers skyfibers=[] file=open(plplgmap) for line in file.readlines() : if line.find(\"PLUGMAPOBJ\") != 0 :", "specex_cholesky import * if len(sys.argv)<3 : print sys.argv[0],\"inspec.fits plPlugMapM.par outspec.fits (sky.fit)\" sys.exit(12); infilename=sys.argv[1]", "to be converted to a numpy.array spectra[fiber] -= sky invar[fiber] = 1/( 1/invar[fiber]", "because expensive and in any case approximate because we only keep the diagonal", "by sky variations in field of view that we have neglected R=scipy.sparse.dia_matrix((Rdata[nfibers/2],offsets),(nwave,nwave)) Rt=R.transpose()", "in any case approximate because we only keep the diagonal # most conservative", "once the sky variance because expensive and in any case approximate because we", "\"\" : print \"writing skymodel to\",skyfilename skyinvar=1/numpy.diag(skycovmat) sky_array=numpy.zeros((1,sky.shape[0])) sky_array[0]=sky skyinvar_array=numpy.zeros((1,skyinvar.shape[0])) skyinvar_array[0]=skyinvar pyfits.HDUList([pyfits.PrimaryHDU(sky_array),pyfits.ImageHDU(skyinvar_array),pyfits.ImageHDU(wave)]).writeto(skyfilename,clobber=True) #pyfits.HDUList([pyfits.PrimaryHDU(skycovmat)]).writeto(\"skycovmat.fits\",clobber=True)", "!= \"SKY\" : continue spectrographId=string.atoi(vals[24]) if spectrographId != specid : continue fiberId=string.atoi(vals[25]) #print", "\"filling A and B\" A=numpy.matrix(numpy.zeros((nwave,nwave))) # dense because additions of band matrices not", ": continue objType=vals[21] if objType != \"SKY\" : continue spectrographId=string.atoi(vals[24]) if spectrographId !=", "is already included in the invar of each spectrum # last point, the", "\"computing covmat\" skycovmat=Rt.dot(Rt.dot(dskycovmat).transpose()) skyvar=numpy.diag(skycovmat) print \"done\" if skyfilename != \"\" : print \"writing", "skyinvar=1/numpy.diag(skycovmat) sky_array=numpy.zeros((1,sky.shape[0])) sky_array[0]=sky skyinvar_array=numpy.zeros((1,skyinvar.shape[0])) skyinvar_array[0]=skyinvar pyfits.HDUList([pyfits.PrimaryHDU(sky_array),pyfits.ImageHDU(skyinvar_array),pyfits.ImageHDU(wave)]).writeto(skyfilename,clobber=True) #pyfits.HDUList([pyfits.PrimaryHDU(skycovmat)]).writeto(\"skycovmat.fits\",clobber=True) print \"subtracting sky to all fibers\"", "\"done\" if skyfilename != \"\" : print \"writing skymodel to\",skyfilename skyinvar=1/numpy.diag(skycovmat) sky_array=numpy.zeros((1,sky.shape[0])) sky_array[0]=sky", "is certainly dominated by sky variations in field of view that we have", "conservative is to evaluate it at the highest resolution (most variance) # also", "if holetype != \"OBJECT\" : continue objType=vals[21] if objType != \"SKY\" : continue", "# get spectrograph id, hardcoded for now, will be read in fits camera=pyfits.open(infilename)[0].header[\"CAMERAS\"]", "wrt to the Poisson noise of the subtracted sky of each # fiber", "that we have neglected R=scipy.sparse.dia_matrix((Rdata[nfibers/2],offsets),(nwave,nwave)) Rt=R.transpose() sky=numpy.dot(R.toarray(),deconvolvedsky) print \"computing covmat\" skycovmat=Rt.dot(Rt.dot(dskycovmat).transpose()) skyvar=numpy.diag(skycovmat) print", "the Poisson noise of the subtracted sky of each # fiber that is", "skyinvar_array=numpy.zeros((1,skyinvar.shape[0])) skyinvar_array[0]=skyinvar pyfits.HDUList([pyfits.PrimaryHDU(sky_array),pyfits.ImageHDU(skyinvar_array),pyfits.ImageHDU(wave)]).writeto(skyfilename,clobber=True) #pyfits.HDUList([pyfits.PrimaryHDU(skycovmat)]).writeto(\"skycovmat.fits\",clobber=True) print \"subtracting sky to all fibers\" valid_fibers=numpy.where(mask==0)[0] for fiber", "starting at 0)=\",skyfibers hdulist=pyfits.open(infilename) spectra=hdulist[0].data invar=hdulist[1].data wave=hdulist[2].data Rdata=hdulist[3].data mask=hdulist[\"FMASK\"].data skyfibers=numpy.intersect1d(skyfibers,numpy.where(mask==0)[0]) print \"skyfibers (after", "deconvolvedsky,dskycovmat=cholesky_solve_and_invert(A,B[0]) print \"done\" # compute only once the sky variance because expensive and", "dominated by sky variations in field of view that we have neglected R=scipy.sparse.dia_matrix((Rdata[nfibers/2],offsets),(nwave,nwave))", "skyspectra=spectra[skyfibers,:] skyinvar=invar[skyfibers,:] nskyfibers=len(skyfibers) nfibers=Rdata.shape[0] d=Rdata.shape[1]/2 nwave=Rdata.shape[2] offsets = range(d,-d-1,-1) print \"solving for the", "of the subtracted sky of each # fiber that is already included in", "0)=\",skyfibers hdulist=pyfits.open(infilename) spectra=hdulist[0].data invar=hdulist[1].data wave=hdulist[2].data Rdata=hdulist[3].data mask=hdulist[\"FMASK\"].data skyfibers=numpy.intersect1d(skyfibers,numpy.where(mask==0)[0]) print \"skyfibers (after masking)=\",skyfibers skyspectra=spectra[skyfibers,:]", "skyfilename=\"\" if(len(sys.argv)>3) : skyfilename=sys.argv[4] # get spectrograph id, hardcoded for now, will be", "Rt=R.transpose() sky=numpy.dot(R.toarray(),deconvolvedsky) print \"computing covmat\" skycovmat=Rt.dot(Rt.dot(dskycovmat).transpose()) skyvar=numpy.diag(skycovmat) print \"done\" if skyfilename != \"\"", "print \"solving for the mean deconvolved sky\" print \"filling A and B\" A=numpy.matrix(numpy.zeros((nwave,nwave)))", "skyinvar_array[0]=skyinvar pyfits.HDUList([pyfits.PrimaryHDU(sky_array),pyfits.ImageHDU(skyinvar_array),pyfits.ImageHDU(wave)]).writeto(skyfilename,clobber=True) #pyfits.HDUList([pyfits.PrimaryHDU(skycovmat)]).writeto(\"skycovmat.fits\",clobber=True) print \"subtracting sky to all fibers\" valid_fibers=numpy.where(mask==0)[0] for fiber in", "in skyfibers: R=scipy.sparse.dia_matrix((Rdata[fiber],offsets),(nwave,nwave)) Ninv=scipy.sparse.dia_matrix((invar[fiber,:],[0]),(nwave,nwave)) tmp=invar[fiber,:]*spectra[fiber,:] tmp2=R.transpose()*Ninv*R A+=tmp2.todense() B+=R.transpose().dot(tmp) print \"done\" print \"solving\" deconvolvedsky,dskycovmat=cholesky_solve_and_invert(A,B[0])", "sky_array[0]=sky skyinvar_array=numpy.zeros((1,skyinvar.shape[0])) skyinvar_array[0]=skyinvar pyfits.HDUList([pyfits.PrimaryHDU(sky_array),pyfits.ImageHDU(skyinvar_array),pyfits.ImageHDU(wave)]).writeto(skyfilename,clobber=True) #pyfits.HDUList([pyfits.PrimaryHDU(skycovmat)]).writeto(\"skycovmat.fits\",clobber=True) print \"subtracting sky to all fibers\" valid_fibers=numpy.where(mask==0)[0] for", "infilename=sys.argv[1] plplgmap=sys.argv[2] outfilename=sys.argv[3] skyfilename=\"\" if(len(sys.argv)>3) : skyfilename=sys.argv[4] # get spectrograph id, hardcoded for", "it is a numpy.matrix that has to be converted to a numpy.array spectra[fiber]", "sky of each # fiber that is already included in the invar of", "spectra[fiber] -= sky invar[fiber] = 1/( 1/invar[fiber] + skyvar ) print \"done\" print", "!= \"\" : print \"writing skymodel to\",skyfilename skyinvar=1/numpy.diag(skycovmat) sky_array=numpy.zeros((1,sky.shape[0])) sky_array[0]=sky skyinvar_array=numpy.zeros((1,skyinvar.shape[0])) skyinvar_array[0]=skyinvar pyfits.HDUList([pyfits.PrimaryHDU(sky_array),pyfits.ImageHDU(skyinvar_array),pyfits.ImageHDU(wave)]).writeto(skyfilename,clobber=True)", "now, will be read in fits camera=pyfits.open(infilename)[0].header[\"CAMERAS\"] specid=string.atoi(camera[1]) # find sky fibers skyfibers=[]", "Rt=R.transpose() sky=numpy.dot(R.toarray(),deconvolvedsky) # it is a numpy.matrix that has to be converted to", "skyinvar=invar[skyfibers,:] nskyfibers=len(skyfibers) nfibers=Rdata.shape[0] d=Rdata.shape[1]/2 nwave=Rdata.shape[2] offsets = range(d,-d-1,-1) print \"solving for the mean", "import pyfits,sys,json,pylab,string,numpy,os,scipy,scipy.sparse,scipy.linalg from scipy.sparse.linalg import spsolve from math import * from specex_cholesky import", "mean deconvolved sky\" print \"filling A and B\" A=numpy.matrix(numpy.zeros((nwave,nwave))) # dense because additions", "variance because expensive and in any case approximate because we only keep the", "#pyfits.HDUList([pyfits.PrimaryHDU(skycovmat)]).writeto(\"skycovmat.fits\",clobber=True) print \"subtracting sky to all fibers\" valid_fibers=numpy.where(mask==0)[0] for fiber in valid_fibers :", "spsolve from math import * from specex_cholesky import * if len(sys.argv)<3 : print", "B\" A=numpy.matrix(numpy.zeros((nwave,nwave))) # dense because additions of band matrices not implemented B=numpy.zeros((1,nwave)) for", "additions of band matrices not implemented B=numpy.zeros((1,nwave)) for fiber in skyfibers: R=scipy.sparse.dia_matrix((Rdata[fiber],offsets),(nwave,nwave)) Ninv=scipy.sparse.dia_matrix((invar[fiber,:],[0]),(nwave,nwave))", "skyfibers=numpy.intersect1d(skyfibers,numpy.where(mask==0)[0]) print \"skyfibers (after masking)=\",skyfibers skyspectra=spectra[skyfibers,:] skyinvar=invar[skyfibers,:] nskyfibers=len(skyfibers) nfibers=Rdata.shape[0] d=Rdata.shape[1]/2 nwave=Rdata.shape[2] offsets =", "\"OBJECT\" : continue objType=vals[21] if objType != \"SKY\" : continue spectrographId=string.atoi(vals[24]) if spectrographId", "spectrographId=string.atoi(vals[24]) if spectrographId != specid : continue fiberId=string.atoi(vals[25]) #print line #print objType,spectrographId,fiberId myfiberid=fiberId-1", "R=scipy.sparse.dia_matrix((Rdata[fiber],offsets),(nwave,nwave)) Ninv=scipy.sparse.dia_matrix((invar[fiber,:],[0]),(nwave,nwave)) tmp=invar[fiber,:]*spectra[fiber,:] tmp2=R.transpose()*Ninv*R A+=tmp2.todense() B+=R.transpose().dot(tmp) print \"done\" print \"solving\" deconvolvedsky,dskycovmat=cholesky_solve_and_invert(A,B[0]) print \"done\"", "numpy.matrix that has to be converted to a numpy.array spectra[fiber] -= sky invar[fiber]", "nskyfibers=len(skyfibers) nfibers=Rdata.shape[0] d=Rdata.shape[1]/2 nwave=Rdata.shape[2] offsets = range(d,-d-1,-1) print \"solving for the mean deconvolved", "last point, the sky error is certainly dominated by sky variations in field", "neglected R=scipy.sparse.dia_matrix((Rdata[nfibers/2],offsets),(nwave,nwave)) Rt=R.transpose() sky=numpy.dot(R.toarray(),deconvolvedsky) print \"computing covmat\" skycovmat=Rt.dot(Rt.dot(dskycovmat).transpose()) skyvar=numpy.diag(skycovmat) print \"done\" if skyfilename", "valid_fibers=numpy.where(mask==0)[0] for fiber in valid_fibers : R=scipy.sparse.dia_matrix((Rdata[fiber],offsets),(nwave,nwave)) Rt=R.transpose() sky=numpy.dot(R.toarray(),deconvolvedsky) # it is a", "line #print objType,spectrographId,fiberId myfiberid=fiberId-1 if specid==2 : myfiberid-=500 skyfibers.append(myfiberid) file.close() print \"skyfibers (now", "\"solving\" deconvolvedsky,dskycovmat=cholesky_solve_and_invert(A,B[0]) print \"done\" # compute only once the sky variance because expensive", "that is already included in the invar of each spectrum # last point,", "a numpy.array spectra[fiber] -= sky invar[fiber] = 1/( 1/invar[fiber] + skyvar ) print", "case approximate because we only keep the diagonal # most conservative is to", "for now, will be read in fits camera=pyfits.open(infilename)[0].header[\"CAMERAS\"] specid=string.atoi(camera[1]) # find sky fibers", "it at the highest resolution (most variance) # also the *mean* sky statistical", "resolution (most variance) # also the *mean* sky statistical uncertainty is negligible wrt", "math import * from specex_cholesky import * if len(sys.argv)<3 : print sys.argv[0],\"inspec.fits plPlugMapM.par", "pyfits,sys,json,pylab,string,numpy,os,scipy,scipy.sparse,scipy.linalg from scipy.sparse.linalg import spsolve from math import * from specex_cholesky import *", "skycovmat=Rt.dot(Rt.dot(dskycovmat).transpose()) skyvar=numpy.diag(skycovmat) print \"done\" if skyfilename != \"\" : print \"writing skymodel to\",skyfilename", "point, the sky error is certainly dominated by sky variations in field of", "spectra=hdulist[0].data invar=hdulist[1].data wave=hdulist[2].data Rdata=hdulist[3].data mask=hdulist[\"FMASK\"].data skyfibers=numpy.intersect1d(skyfibers,numpy.where(mask==0)[0]) print \"skyfibers (after masking)=\",skyfibers skyspectra=spectra[skyfibers,:] skyinvar=invar[skyfibers,:] nskyfibers=len(skyfibers)", ": continue fiberId=string.atoi(vals[25]) #print line #print objType,spectrographId,fiberId myfiberid=fiberId-1 if specid==2 : myfiberid-=500 skyfibers.append(myfiberid)", "0 : continue vals=string.split(line,\" \") holetype=vals[8] if holetype != \"OBJECT\" : continue objType=vals[21]", "sky variations in field of view that we have neglected R=scipy.sparse.dia_matrix((Rdata[nfibers/2],offsets),(nwave,nwave)) Rt=R.transpose() sky=numpy.dot(R.toarray(),deconvolvedsky)", "subtracted sky of each # fiber that is already included in the invar", "mask=hdulist[\"FMASK\"].data skyfibers=numpy.intersect1d(skyfibers,numpy.where(mask==0)[0]) print \"skyfibers (after masking)=\",skyfibers skyspectra=spectra[skyfibers,:] skyinvar=invar[skyfibers,:] nskyfibers=len(skyfibers) nfibers=Rdata.shape[0] d=Rdata.shape[1]/2 nwave=Rdata.shape[2] offsets", "spectrograph id, hardcoded for now, will be read in fits camera=pyfits.open(infilename)[0].header[\"CAMERAS\"] specid=string.atoi(camera[1]) #", "!= \"OBJECT\" : continue objType=vals[21] if objType != \"SKY\" : continue spectrographId=string.atoi(vals[24]) if", "Poisson noise of the subtracted sky of each # fiber that is already", "outspec.fits (sky.fit)\" sys.exit(12); infilename=sys.argv[1] plplgmap=sys.argv[2] outfilename=sys.argv[3] skyfilename=\"\" if(len(sys.argv)>3) : skyfilename=sys.argv[4] # get spectrograph", "(sky.fit)\" sys.exit(12); infilename=sys.argv[1] plplgmap=sys.argv[2] outfilename=sys.argv[3] skyfilename=\"\" if(len(sys.argv)>3) : skyfilename=sys.argv[4] # get spectrograph id,", "get spectrograph id, hardcoded for now, will be read in fits camera=pyfits.open(infilename)[0].header[\"CAMERAS\"] specid=string.atoi(camera[1])", "sky\" print \"filling A and B\" A=numpy.matrix(numpy.zeros((nwave,nwave))) # dense because additions of band", "line.find(\"PLUGMAPOBJ\") != 0 : continue vals=string.split(line,\" \") holetype=vals[8] if holetype != \"OBJECT\" :", "import * from specex_cholesky import * if len(sys.argv)<3 : print sys.argv[0],\"inspec.fits plPlugMapM.par outspec.fits", "is a numpy.matrix that has to be converted to a numpy.array spectra[fiber] -=", "(after masking)=\",skyfibers skyspectra=spectra[skyfibers,:] skyinvar=invar[skyfibers,:] nskyfibers=len(skyfibers) nfibers=Rdata.shape[0] d=Rdata.shape[1]/2 nwave=Rdata.shape[2] offsets = range(d,-d-1,-1) print \"solving", "* from specex_cholesky import * if len(sys.argv)<3 : print sys.argv[0],\"inspec.fits plPlugMapM.par outspec.fits (sky.fit)\"", "A=numpy.matrix(numpy.zeros((nwave,nwave))) # dense because additions of band matrices not implemented B=numpy.zeros((1,nwave)) for fiber", "camera=pyfits.open(infilename)[0].header[\"CAMERAS\"] specid=string.atoi(camera[1]) # find sky fibers skyfibers=[] file=open(plplgmap) for line in file.readlines() :", "invar=hdulist[1].data wave=hdulist[2].data Rdata=hdulist[3].data mask=hdulist[\"FMASK\"].data skyfibers=numpy.intersect1d(skyfibers,numpy.where(mask==0)[0]) print \"skyfibers (after masking)=\",skyfibers skyspectra=spectra[skyfibers,:] skyinvar=invar[skyfibers,:] nskyfibers=len(skyfibers) nfibers=Rdata.shape[0]", "from specex_cholesky import * if len(sys.argv)<3 : print sys.argv[0],\"inspec.fits plPlugMapM.par outspec.fits (sky.fit)\" sys.exit(12);", "included in the invar of each spectrum # last point, the sky error", "negligible wrt to the Poisson noise of the subtracted sky of each #", "variance) # also the *mean* sky statistical uncertainty is negligible wrt to the", "# also the *mean* sky statistical uncertainty is negligible wrt to the Poisson", "sys.exit(12); infilename=sys.argv[1] plplgmap=sys.argv[2] outfilename=sys.argv[3] skyfilename=\"\" if(len(sys.argv)>3) : skyfilename=sys.argv[4] # get spectrograph id, hardcoded", "\"done\" print \"solving\" deconvolvedsky,dskycovmat=cholesky_solve_and_invert(A,B[0]) print \"done\" # compute only once the sky variance", "only once the sky variance because expensive and in any case approximate because", "dense because additions of band matrices not implemented B=numpy.zeros((1,nwave)) for fiber in skyfibers:", "fiber in skyfibers: R=scipy.sparse.dia_matrix((Rdata[fiber],offsets),(nwave,nwave)) Ninv=scipy.sparse.dia_matrix((invar[fiber,:],[0]),(nwave,nwave)) tmp=invar[fiber,:]*spectra[fiber,:] tmp2=R.transpose()*Ninv*R A+=tmp2.todense() B+=R.transpose().dot(tmp) print \"done\" print \"solving\"", "sky_array=numpy.zeros((1,sky.shape[0])) sky_array[0]=sky skyinvar_array=numpy.zeros((1,skyinvar.shape[0])) skyinvar_array[0]=skyinvar pyfits.HDUList([pyfits.PrimaryHDU(sky_array),pyfits.ImageHDU(skyinvar_array),pyfits.ImageHDU(wave)]).writeto(skyfilename,clobber=True) #pyfits.HDUList([pyfits.PrimaryHDU(skycovmat)]).writeto(\"skycovmat.fits\",clobber=True) print \"subtracting sky to all fibers\" valid_fibers=numpy.where(mask==0)[0]", "the diagonal # most conservative is to evaluate it at the highest resolution", "\"SKY\" : continue spectrographId=string.atoi(vals[24]) if spectrographId != specid : continue fiberId=string.atoi(vals[25]) #print line", "the mean deconvolved sky\" print \"filling A and B\" A=numpy.matrix(numpy.zeros((nwave,nwave))) # dense because", "we only keep the diagonal # most conservative is to evaluate it at", "print \"done\" print \"solving\" deconvolvedsky,dskycovmat=cholesky_solve_and_invert(A,B[0]) print \"done\" # compute only once the sky", "sky invar[fiber] = 1/( 1/invar[fiber] + skyvar ) print \"done\" print \"writing result", "1/( 1/invar[fiber] + skyvar ) print \"done\" print \"writing result to\",outfilename hdulist.writeto(outfilename,clobber=True) sys.exit(0)", "invar[fiber] = 1/( 1/invar[fiber] + skyvar ) print \"done\" print \"writing result to\",outfilename", "continue spectrographId=string.atoi(vals[24]) if spectrographId != specid : continue fiberId=string.atoi(vals[25]) #print line #print objType,spectrographId,fiberId", "*mean* sky statistical uncertainty is negligible wrt to the Poisson noise of the", "if len(sys.argv)<3 : print sys.argv[0],\"inspec.fits plPlugMapM.par outspec.fits (sky.fit)\" sys.exit(12); infilename=sys.argv[1] plplgmap=sys.argv[2] outfilename=sys.argv[3] skyfilename=\"\"", "converted to a numpy.array spectra[fiber] -= sky invar[fiber] = 1/( 1/invar[fiber] + skyvar", "from math import * from specex_cholesky import * if len(sys.argv)<3 : print sys.argv[0],\"inspec.fits", "# most conservative is to evaluate it at the highest resolution (most variance)", "if spectrographId != specid : continue fiberId=string.atoi(vals[25]) #print line #print objType,spectrographId,fiberId myfiberid=fiberId-1 if", "= range(d,-d-1,-1) print \"solving for the mean deconvolved sky\" print \"filling A and", "band matrices not implemented B=numpy.zeros((1,nwave)) for fiber in skyfibers: R=scipy.sparse.dia_matrix((Rdata[fiber],offsets),(nwave,nwave)) Ninv=scipy.sparse.dia_matrix((invar[fiber,:],[0]),(nwave,nwave)) tmp=invar[fiber,:]*spectra[fiber,:] tmp2=R.transpose()*Ninv*R", "* if len(sys.argv)<3 : print sys.argv[0],\"inspec.fits plPlugMapM.par outspec.fits (sky.fit)\" sys.exit(12); infilename=sys.argv[1] plplgmap=sys.argv[2] outfilename=sys.argv[3]", "and in any case approximate because we only keep the diagonal # most", "pyfits.HDUList([pyfits.PrimaryHDU(sky_array),pyfits.ImageHDU(skyinvar_array),pyfits.ImageHDU(wave)]).writeto(skyfilename,clobber=True) #pyfits.HDUList([pyfits.PrimaryHDU(skycovmat)]).writeto(\"skycovmat.fits\",clobber=True) print \"subtracting sky to all fibers\" valid_fibers=numpy.where(mask==0)[0] for fiber in valid_fibers", "fiber in valid_fibers : R=scipy.sparse.dia_matrix((Rdata[fiber],offsets),(nwave,nwave)) Rt=R.transpose() sky=numpy.dot(R.toarray(),deconvolvedsky) # it is a numpy.matrix that", "print \"writing skymodel to\",skyfilename skyinvar=1/numpy.diag(skycovmat) sky_array=numpy.zeros((1,sky.shape[0])) sky_array[0]=sky skyinvar_array=numpy.zeros((1,skyinvar.shape[0])) skyinvar_array[0]=skyinvar pyfits.HDUList([pyfits.PrimaryHDU(sky_array),pyfits.ImageHDU(skyinvar_array),pyfits.ImageHDU(wave)]).writeto(skyfilename,clobber=True) #pyfits.HDUList([pyfits.PrimaryHDU(skycovmat)]).writeto(\"skycovmat.fits\",clobber=True) print \"subtracting", "myfiberid=fiberId-1 if specid==2 : myfiberid-=500 skyfibers.append(myfiberid) file.close() print \"skyfibers (now starting at 0)=\",skyfibers", "to\",skyfilename skyinvar=1/numpy.diag(skycovmat) sky_array=numpy.zeros((1,sky.shape[0])) sky_array[0]=sky skyinvar_array=numpy.zeros((1,skyinvar.shape[0])) skyinvar_array[0]=skyinvar pyfits.HDUList([pyfits.PrimaryHDU(sky_array),pyfits.ImageHDU(skyinvar_array),pyfits.ImageHDU(wave)]).writeto(skyfilename,clobber=True) #pyfits.HDUList([pyfits.PrimaryHDU(skycovmat)]).writeto(\"skycovmat.fits\",clobber=True) print \"subtracting sky to all", "compute only once the sky variance because expensive and in any case approximate", "approximate because we only keep the diagonal # most conservative is to evaluate", "A and B\" A=numpy.matrix(numpy.zeros((nwave,nwave))) # dense because additions of band matrices not implemented", "holetype=vals[8] if holetype != \"OBJECT\" : continue objType=vals[21] if objType != \"SKY\" :", "file.close() print \"skyfibers (now starting at 0)=\",skyfibers hdulist=pyfits.open(infilename) spectra=hdulist[0].data invar=hdulist[1].data wave=hdulist[2].data Rdata=hdulist[3].data mask=hdulist[\"FMASK\"].data", "noise of the subtracted sky of each # fiber that is already included", "scipy.sparse.linalg import spsolve from math import * from specex_cholesky import * if len(sys.argv)<3", "-= sky invar[fiber] = 1/( 1/invar[fiber] + skyvar ) print \"done\" print \"writing", ": continue vals=string.split(line,\" \") holetype=vals[8] if holetype != \"OBJECT\" : continue objType=vals[21] if", "uncertainty is negligible wrt to the Poisson noise of the subtracted sky of", "sys.argv[0],\"inspec.fits plPlugMapM.par outspec.fits (sky.fit)\" sys.exit(12); infilename=sys.argv[1] plplgmap=sys.argv[2] outfilename=sys.argv[3] skyfilename=\"\" if(len(sys.argv)>3) : skyfilename=sys.argv[4] #", "sky=numpy.dot(R.toarray(),deconvolvedsky) print \"computing covmat\" skycovmat=Rt.dot(Rt.dot(dskycovmat).transpose()) skyvar=numpy.diag(skycovmat) print \"done\" if skyfilename != \"\" :", "because additions of band matrices not implemented B=numpy.zeros((1,nwave)) for fiber in skyfibers: R=scipy.sparse.dia_matrix((Rdata[fiber],offsets),(nwave,nwave))", "error is certainly dominated by sky variations in field of view that we", "print \"filling A and B\" A=numpy.matrix(numpy.zeros((nwave,nwave))) # dense because additions of band matrices", "spectrographId != specid : continue fiberId=string.atoi(vals[25]) #print line #print objType,spectrographId,fiberId myfiberid=fiberId-1 if specid==2", "of each # fiber that is already included in the invar of each", "a numpy.matrix that has to be converted to a numpy.array spectra[fiber] -= sky", "vals=string.split(line,\" \") holetype=vals[8] if holetype != \"OBJECT\" : continue objType=vals[21] if objType !=", "that has to be converted to a numpy.array spectra[fiber] -= sky invar[fiber] =", "\") holetype=vals[8] if holetype != \"OBJECT\" : continue objType=vals[21] if objType != \"SKY\"", "nwave=Rdata.shape[2] offsets = range(d,-d-1,-1) print \"solving for the mean deconvolved sky\" print \"filling", "certainly dominated by sky variations in field of view that we have neglected", "to all fibers\" valid_fibers=numpy.where(mask==0)[0] for fiber in valid_fibers : R=scipy.sparse.dia_matrix((Rdata[fiber],offsets),(nwave,nwave)) Rt=R.transpose() sky=numpy.dot(R.toarray(),deconvolvedsky) #", "implemented B=numpy.zeros((1,nwave)) for fiber in skyfibers: R=scipy.sparse.dia_matrix((Rdata[fiber],offsets),(nwave,nwave)) Ninv=scipy.sparse.dia_matrix((invar[fiber,:],[0]),(nwave,nwave)) tmp=invar[fiber,:]*spectra[fiber,:] tmp2=R.transpose()*Ninv*R A+=tmp2.todense() B+=R.transpose().dot(tmp) print", "and B\" A=numpy.matrix(numpy.zeros((nwave,nwave))) # dense because additions of band matrices not implemented B=numpy.zeros((1,nwave))", "specid=string.atoi(camera[1]) # find sky fibers skyfibers=[] file=open(plplgmap) for line in file.readlines() : if", "all fibers\" valid_fibers=numpy.where(mask==0)[0] for fiber in valid_fibers : R=scipy.sparse.dia_matrix((Rdata[fiber],offsets),(nwave,nwave)) Rt=R.transpose() sky=numpy.dot(R.toarray(),deconvolvedsky) # it", "tmp2=R.transpose()*Ninv*R A+=tmp2.todense() B+=R.transpose().dot(tmp) print \"done\" print \"solving\" deconvolvedsky,dskycovmat=cholesky_solve_and_invert(A,B[0]) print \"done\" # compute only", "any case approximate because we only keep the diagonal # most conservative is", "covmat\" skycovmat=Rt.dot(Rt.dot(dskycovmat).transpose()) skyvar=numpy.diag(skycovmat) print \"done\" if skyfilename != \"\" : print \"writing skymodel", "for fiber in skyfibers: R=scipy.sparse.dia_matrix((Rdata[fiber],offsets),(nwave,nwave)) Ninv=scipy.sparse.dia_matrix((invar[fiber,:],[0]),(nwave,nwave)) tmp=invar[fiber,:]*spectra[fiber,:] tmp2=R.transpose()*Ninv*R A+=tmp2.todense() B+=R.transpose().dot(tmp) print \"done\" print", "continue fiberId=string.atoi(vals[25]) #print line #print objType,spectrographId,fiberId myfiberid=fiberId-1 if specid==2 : myfiberid-=500 skyfibers.append(myfiberid) file.close()", "highest resolution (most variance) # also the *mean* sky statistical uncertainty is negligible", "holetype != \"OBJECT\" : continue objType=vals[21] if objType != \"SKY\" : continue spectrographId=string.atoi(vals[24])", ": continue spectrographId=string.atoi(vals[24]) if spectrographId != specid : continue fiberId=string.atoi(vals[25]) #print line #print", "sky statistical uncertainty is negligible wrt to the Poisson noise of the subtracted", "R=scipy.sparse.dia_matrix((Rdata[nfibers/2],offsets),(nwave,nwave)) Rt=R.transpose() sky=numpy.dot(R.toarray(),deconvolvedsky) print \"computing covmat\" skycovmat=Rt.dot(Rt.dot(dskycovmat).transpose()) skyvar=numpy.diag(skycovmat) print \"done\" if skyfilename !=", "plPlugMapM.par outspec.fits (sky.fit)\" sys.exit(12); infilename=sys.argv[1] plplgmap=sys.argv[2] outfilename=sys.argv[3] skyfilename=\"\" if(len(sys.argv)>3) : skyfilename=sys.argv[4] # get", "not implemented B=numpy.zeros((1,nwave)) for fiber in skyfibers: R=scipy.sparse.dia_matrix((Rdata[fiber],offsets),(nwave,nwave)) Ninv=scipy.sparse.dia_matrix((invar[fiber,:],[0]),(nwave,nwave)) tmp=invar[fiber,:]*spectra[fiber,:] tmp2=R.transpose()*Ninv*R A+=tmp2.todense() B+=R.transpose().dot(tmp)", "print \"skyfibers (after masking)=\",skyfibers skyspectra=spectra[skyfibers,:] skyinvar=invar[skyfibers,:] nskyfibers=len(skyfibers) nfibers=Rdata.shape[0] d=Rdata.shape[1]/2 nwave=Rdata.shape[2] offsets = range(d,-d-1,-1)", "also the *mean* sky statistical uncertainty is negligible wrt to the Poisson noise", "B=numpy.zeros((1,nwave)) for fiber in skyfibers: R=scipy.sparse.dia_matrix((Rdata[fiber],offsets),(nwave,nwave)) Ninv=scipy.sparse.dia_matrix((invar[fiber,:],[0]),(nwave,nwave)) tmp=invar[fiber,:]*spectra[fiber,:] tmp2=R.transpose()*Ninv*R A+=tmp2.todense() B+=R.transpose().dot(tmp) print \"done\"", "have neglected R=scipy.sparse.dia_matrix((Rdata[nfibers/2],offsets),(nwave,nwave)) Rt=R.transpose() sky=numpy.dot(R.toarray(),deconvolvedsky) print \"computing covmat\" skycovmat=Rt.dot(Rt.dot(dskycovmat).transpose()) skyvar=numpy.diag(skycovmat) print \"done\" if", "import * if len(sys.argv)<3 : print sys.argv[0],\"inspec.fits plPlugMapM.par outspec.fits (sky.fit)\" sys.exit(12); infilename=sys.argv[1] plplgmap=sys.argv[2]", "at the highest resolution (most variance) # also the *mean* sky statistical uncertainty", "skyfibers: R=scipy.sparse.dia_matrix((Rdata[fiber],offsets),(nwave,nwave)) Ninv=scipy.sparse.dia_matrix((invar[fiber,:],[0]),(nwave,nwave)) tmp=invar[fiber,:]*spectra[fiber,:] tmp2=R.transpose()*Ninv*R A+=tmp2.todense() B+=R.transpose().dot(tmp) print \"done\" print \"solving\" deconvolvedsky,dskycovmat=cholesky_solve_and_invert(A,B[0]) print", "of view that we have neglected R=scipy.sparse.dia_matrix((Rdata[nfibers/2],offsets),(nwave,nwave)) Rt=R.transpose() sky=numpy.dot(R.toarray(),deconvolvedsky) print \"computing covmat\" skycovmat=Rt.dot(Rt.dot(dskycovmat).transpose())", "diagonal # most conservative is to evaluate it at the highest resolution (most", ": if line.find(\"PLUGMAPOBJ\") != 0 : continue vals=string.split(line,\" \") holetype=vals[8] if holetype !=", "A+=tmp2.todense() B+=R.transpose().dot(tmp) print \"done\" print \"solving\" deconvolvedsky,dskycovmat=cholesky_solve_and_invert(A,B[0]) print \"done\" # compute only once", "objType=vals[21] if objType != \"SKY\" : continue spectrographId=string.atoi(vals[24]) if spectrographId != specid :", "#print line #print objType,spectrographId,fiberId myfiberid=fiberId-1 if specid==2 : myfiberid-=500 skyfibers.append(myfiberid) file.close() print \"skyfibers", "to evaluate it at the highest resolution (most variance) # also the *mean*", "print \"skyfibers (now starting at 0)=\",skyfibers hdulist=pyfits.open(infilename) spectra=hdulist[0].data invar=hdulist[1].data wave=hdulist[2].data Rdata=hdulist[3].data mask=hdulist[\"FMASK\"].data skyfibers=numpy.intersect1d(skyfibers,numpy.where(mask==0)[0])", "find sky fibers skyfibers=[] file=open(plplgmap) for line in file.readlines() : if line.find(\"PLUGMAPOBJ\") !=", "most conservative is to evaluate it at the highest resolution (most variance) #", "wave=hdulist[2].data Rdata=hdulist[3].data mask=hdulist[\"FMASK\"].data skyfibers=numpy.intersect1d(skyfibers,numpy.where(mask==0)[0]) print \"skyfibers (after masking)=\",skyfibers skyspectra=spectra[skyfibers,:] skyinvar=invar[skyfibers,:] nskyfibers=len(skyfibers) nfibers=Rdata.shape[0] d=Rdata.shape[1]/2", "\"skyfibers (after masking)=\",skyfibers skyspectra=spectra[skyfibers,:] skyinvar=invar[skyfibers,:] nskyfibers=len(skyfibers) nfibers=Rdata.shape[0] d=Rdata.shape[1]/2 nwave=Rdata.shape[2] offsets = range(d,-d-1,-1) print", "each spectrum # last point, the sky error is certainly dominated by sky", "in valid_fibers : R=scipy.sparse.dia_matrix((Rdata[fiber],offsets),(nwave,nwave)) Rt=R.transpose() sky=numpy.dot(R.toarray(),deconvolvedsky) # it is a numpy.matrix that has", "sky variance because expensive and in any case approximate because we only keep", "keep the diagonal # most conservative is to evaluate it at the highest", "deconvolved sky\" print \"filling A and B\" A=numpy.matrix(numpy.zeros((nwave,nwave))) # dense because additions of", "to a numpy.array spectra[fiber] -= sky invar[fiber] = 1/( 1/invar[fiber] + skyvar )", "invar of each spectrum # last point, the sky error is certainly dominated", "file=open(plplgmap) for line in file.readlines() : if line.find(\"PLUGMAPOBJ\") != 0 : continue vals=string.split(line,\"", ": myfiberid-=500 skyfibers.append(myfiberid) file.close() print \"skyfibers (now starting at 0)=\",skyfibers hdulist=pyfits.open(infilename) spectra=hdulist[0].data invar=hdulist[1].data", "print \"done\" if skyfilename != \"\" : print \"writing skymodel to\",skyfilename skyinvar=1/numpy.diag(skycovmat) sky_array=numpy.zeros((1,sky.shape[0]))", "matrices not implemented B=numpy.zeros((1,nwave)) for fiber in skyfibers: R=scipy.sparse.dia_matrix((Rdata[fiber],offsets),(nwave,nwave)) Ninv=scipy.sparse.dia_matrix((invar[fiber,:],[0]),(nwave,nwave)) tmp=invar[fiber,:]*spectra[fiber,:] tmp2=R.transpose()*Ninv*R A+=tmp2.todense()", "in the invar of each spectrum # last point, the sky error is", "# dense because additions of band matrices not implemented B=numpy.zeros((1,nwave)) for fiber in", "the invar of each spectrum # last point, the sky error is certainly", "sky=numpy.dot(R.toarray(),deconvolvedsky) # it is a numpy.matrix that has to be converted to a", "import spsolve from math import * from specex_cholesky import * if len(sys.argv)<3 :", "masking)=\",skyfibers skyspectra=spectra[skyfibers,:] skyinvar=invar[skyfibers,:] nskyfibers=len(skyfibers) nfibers=Rdata.shape[0] d=Rdata.shape[1]/2 nwave=Rdata.shape[2] offsets = range(d,-d-1,-1) print \"solving for", ": R=scipy.sparse.dia_matrix((Rdata[fiber],offsets),(nwave,nwave)) Rt=R.transpose() sky=numpy.dot(R.toarray(),deconvolvedsky) # it is a numpy.matrix that has to be", "is to evaluate it at the highest resolution (most variance) # also the", "is negligible wrt to the Poisson noise of the subtracted sky of each", ": print \"writing skymodel to\",skyfilename skyinvar=1/numpy.diag(skycovmat) sky_array=numpy.zeros((1,sky.shape[0])) sky_array[0]=sky skyinvar_array=numpy.zeros((1,skyinvar.shape[0])) skyinvar_array[0]=skyinvar pyfits.HDUList([pyfits.PrimaryHDU(sky_array),pyfits.ImageHDU(skyinvar_array),pyfits.ImageHDU(wave)]).writeto(skyfilename,clobber=True) #pyfits.HDUList([pyfits.PrimaryHDU(skycovmat)]).writeto(\"skycovmat.fits\",clobber=True) print", "of band matrices not implemented B=numpy.zeros((1,nwave)) for fiber in skyfibers: R=scipy.sparse.dia_matrix((Rdata[fiber],offsets),(nwave,nwave)) Ninv=scipy.sparse.dia_matrix((invar[fiber,:],[0]),(nwave,nwave)) tmp=invar[fiber,:]*spectra[fiber,:]", "be read in fits camera=pyfits.open(infilename)[0].header[\"CAMERAS\"] specid=string.atoi(camera[1]) # find sky fibers skyfibers=[] file=open(plplgmap) for", "hardcoded for now, will be read in fits camera=pyfits.open(infilename)[0].header[\"CAMERAS\"] specid=string.atoi(camera[1]) # find sky", "print sys.argv[0],\"inspec.fits plPlugMapM.par outspec.fits (sky.fit)\" sys.exit(12); infilename=sys.argv[1] plplgmap=sys.argv[2] outfilename=sys.argv[3] skyfilename=\"\" if(len(sys.argv)>3) : skyfilename=sys.argv[4]", "id, hardcoded for now, will be read in fits camera=pyfits.open(infilename)[0].header[\"CAMERAS\"] specid=string.atoi(camera[1]) # find", "skymodel to\",skyfilename skyinvar=1/numpy.diag(skycovmat) sky_array=numpy.zeros((1,sky.shape[0])) sky_array[0]=sky skyinvar_array=numpy.zeros((1,skyinvar.shape[0])) skyinvar_array[0]=skyinvar pyfits.HDUList([pyfits.PrimaryHDU(sky_array),pyfits.ImageHDU(skyinvar_array),pyfits.ImageHDU(wave)]).writeto(skyfilename,clobber=True) #pyfits.HDUList([pyfits.PrimaryHDU(skycovmat)]).writeto(\"skycovmat.fits\",clobber=True) print \"subtracting sky to", "#print objType,spectrographId,fiberId myfiberid=fiberId-1 if specid==2 : myfiberid-=500 skyfibers.append(myfiberid) file.close() print \"skyfibers (now starting", "print \"subtracting sky to all fibers\" valid_fibers=numpy.where(mask==0)[0] for fiber in valid_fibers : R=scipy.sparse.dia_matrix((Rdata[fiber],offsets),(nwave,nwave))", "skyfilename != \"\" : print \"writing skymodel to\",skyfilename skyinvar=1/numpy.diag(skycovmat) sky_array=numpy.zeros((1,sky.shape[0])) sky_array[0]=sky skyinvar_array=numpy.zeros((1,skyinvar.shape[0])) skyinvar_array[0]=skyinvar", "len(sys.argv)<3 : print sys.argv[0],\"inspec.fits plPlugMapM.par outspec.fits (sky.fit)\" sys.exit(12); infilename=sys.argv[1] plplgmap=sys.argv[2] outfilename=sys.argv[3] skyfilename=\"\" if(len(sys.argv)>3)", "(now starting at 0)=\",skyfibers hdulist=pyfits.open(infilename) spectra=hdulist[0].data invar=hdulist[1].data wave=hdulist[2].data Rdata=hdulist[3].data mask=hdulist[\"FMASK\"].data skyfibers=numpy.intersect1d(skyfibers,numpy.where(mask==0)[0]) print \"skyfibers", "sky to all fibers\" valid_fibers=numpy.where(mask==0)[0] for fiber in valid_fibers : R=scipy.sparse.dia_matrix((Rdata[fiber],offsets),(nwave,nwave)) Rt=R.transpose() sky=numpy.dot(R.toarray(),deconvolvedsky)", "# last point, the sky error is certainly dominated by sky variations in", "sky error is certainly dominated by sky variations in field of view that", "range(d,-d-1,-1) print \"solving for the mean deconvolved sky\" print \"filling A and B\"", "read in fits camera=pyfits.open(infilename)[0].header[\"CAMERAS\"] specid=string.atoi(camera[1]) # find sky fibers skyfibers=[] file=open(plplgmap) for line", "print \"solving\" deconvolvedsky,dskycovmat=cholesky_solve_and_invert(A,B[0]) print \"done\" # compute only once the sky variance because", "at 0)=\",skyfibers hdulist=pyfits.open(infilename) spectra=hdulist[0].data invar=hdulist[1].data wave=hdulist[2].data Rdata=hdulist[3].data mask=hdulist[\"FMASK\"].data skyfibers=numpy.intersect1d(skyfibers,numpy.where(mask==0)[0]) print \"skyfibers (after masking)=\",skyfibers", "skyfibers.append(myfiberid) file.close() print \"skyfibers (now starting at 0)=\",skyfibers hdulist=pyfits.open(infilename) spectra=hdulist[0].data invar=hdulist[1].data wave=hdulist[2].data Rdata=hdulist[3].data", "skyfilename=sys.argv[4] # get spectrograph id, hardcoded for now, will be read in fits", "the *mean* sky statistical uncertainty is negligible wrt to the Poisson noise of", "\"subtracting sky to all fibers\" valid_fibers=numpy.where(mask==0)[0] for fiber in valid_fibers : R=scipy.sparse.dia_matrix((Rdata[fiber],offsets),(nwave,nwave)) Rt=R.transpose()", "valid_fibers : R=scipy.sparse.dia_matrix((Rdata[fiber],offsets),(nwave,nwave)) Rt=R.transpose() sky=numpy.dot(R.toarray(),deconvolvedsky) # it is a numpy.matrix that has to", "fibers\" valid_fibers=numpy.where(mask==0)[0] for fiber in valid_fibers : R=scipy.sparse.dia_matrix((Rdata[fiber],offsets),(nwave,nwave)) Rt=R.transpose() sky=numpy.dot(R.toarray(),deconvolvedsky) # it is", "# compute only once the sky variance because expensive and in any case", "variations in field of view that we have neglected R=scipy.sparse.dia_matrix((Rdata[nfibers/2],offsets),(nwave,nwave)) Rt=R.transpose() sky=numpy.dot(R.toarray(),deconvolvedsky) print", "#!/usr/bin/env python import pyfits,sys,json,pylab,string,numpy,os,scipy,scipy.sparse,scipy.linalg from scipy.sparse.linalg import spsolve from math import * from", "R=scipy.sparse.dia_matrix((Rdata[fiber],offsets),(nwave,nwave)) Rt=R.transpose() sky=numpy.dot(R.toarray(),deconvolvedsky) # it is a numpy.matrix that has to be converted", "plplgmap=sys.argv[2] outfilename=sys.argv[3] skyfilename=\"\" if(len(sys.argv)>3) : skyfilename=sys.argv[4] # get spectrograph id, hardcoded for now,", "if objType != \"SKY\" : continue spectrographId=string.atoi(vals[24]) if spectrographId != specid : continue", "= 1/( 1/invar[fiber] + skyvar ) print \"done\" print \"writing result to\",outfilename hdulist.writeto(outfilename,clobber=True)", "of each spectrum # last point, the sky error is certainly dominated by", "the subtracted sky of each # fiber that is already included in the", "for the mean deconvolved sky\" print \"filling A and B\" A=numpy.matrix(numpy.zeros((nwave,nwave))) # dense", "from scipy.sparse.linalg import spsolve from math import * from specex_cholesky import * if", "the highest resolution (most variance) # also the *mean* sky statistical uncertainty is", "in field of view that we have neglected R=scipy.sparse.dia_matrix((Rdata[nfibers/2],offsets),(nwave,nwave)) Rt=R.transpose() sky=numpy.dot(R.toarray(),deconvolvedsky) print \"computing", "nfibers=Rdata.shape[0] d=Rdata.shape[1]/2 nwave=Rdata.shape[2] offsets = range(d,-d-1,-1) print \"solving for the mean deconvolved sky\"", "field of view that we have neglected R=scipy.sparse.dia_matrix((Rdata[nfibers/2],offsets),(nwave,nwave)) Rt=R.transpose() sky=numpy.dot(R.toarray(),deconvolvedsky) print \"computing covmat\"", "fiber that is already included in the invar of each spectrum # last", "(most variance) # also the *mean* sky statistical uncertainty is negligible wrt to", "only keep the diagonal # most conservative is to evaluate it at the", "print \"done\" # compute only once the sky variance because expensive and in", "\"solving for the mean deconvolved sky\" print \"filling A and B\" A=numpy.matrix(numpy.zeros((nwave,nwave))) #", "objType,spectrographId,fiberId myfiberid=fiberId-1 if specid==2 : myfiberid-=500 skyfibers.append(myfiberid) file.close() print \"skyfibers (now starting at", "statistical uncertainty is negligible wrt to the Poisson noise of the subtracted sky", "objType != \"SKY\" : continue spectrographId=string.atoi(vals[24]) if spectrographId != specid : continue fiberId=string.atoi(vals[25])", "!= 0 : continue vals=string.split(line,\" \") holetype=vals[8] if holetype != \"OBJECT\" : continue", "will be read in fits camera=pyfits.open(infilename)[0].header[\"CAMERAS\"] specid=string.atoi(camera[1]) # find sky fibers skyfibers=[] file=open(plplgmap)", "\"skyfibers (now starting at 0)=\",skyfibers hdulist=pyfits.open(infilename) spectra=hdulist[0].data invar=hdulist[1].data wave=hdulist[2].data Rdata=hdulist[3].data mask=hdulist[\"FMASK\"].data skyfibers=numpy.intersect1d(skyfibers,numpy.where(mask==0)[0]) print", "in fits camera=pyfits.open(infilename)[0].header[\"CAMERAS\"] specid=string.atoi(camera[1]) # find sky fibers skyfibers=[] file=open(plplgmap) for line in", ": skyfilename=sys.argv[4] # get spectrograph id, hardcoded for now, will be read in", "for line in file.readlines() : if line.find(\"PLUGMAPOBJ\") != 0 : continue vals=string.split(line,\" \")", "python import pyfits,sys,json,pylab,string,numpy,os,scipy,scipy.sparse,scipy.linalg from scipy.sparse.linalg import spsolve from math import * from specex_cholesky", "fiberId=string.atoi(vals[25]) #print line #print objType,spectrographId,fiberId myfiberid=fiberId-1 if specid==2 : myfiberid-=500 skyfibers.append(myfiberid) file.close() print", "!= specid : continue fiberId=string.atoi(vals[25]) #print line #print objType,spectrographId,fiberId myfiberid=fiberId-1 if specid==2 :", "for fiber in valid_fibers : R=scipy.sparse.dia_matrix((Rdata[fiber],offsets),(nwave,nwave)) Rt=R.transpose() sky=numpy.dot(R.toarray(),deconvolvedsky) # it is a numpy.matrix", "Rdata=hdulist[3].data mask=hdulist[\"FMASK\"].data skyfibers=numpy.intersect1d(skyfibers,numpy.where(mask==0)[0]) print \"skyfibers (after masking)=\",skyfibers skyspectra=spectra[skyfibers,:] skyinvar=invar[skyfibers,:] nskyfibers=len(skyfibers) nfibers=Rdata.shape[0] d=Rdata.shape[1]/2 nwave=Rdata.shape[2]", "\"done\" # compute only once the sky variance because expensive and in any", "if specid==2 : myfiberid-=500 skyfibers.append(myfiberid) file.close() print \"skyfibers (now starting at 0)=\",skyfibers hdulist=pyfits.open(infilename)", "hdulist=pyfits.open(infilename) spectra=hdulist[0].data invar=hdulist[1].data wave=hdulist[2].data Rdata=hdulist[3].data mask=hdulist[\"FMASK\"].data skyfibers=numpy.intersect1d(skyfibers,numpy.where(mask==0)[0]) print \"skyfibers (after masking)=\",skyfibers skyspectra=spectra[skyfibers,:] skyinvar=invar[skyfibers,:]", "\"writing skymodel to\",skyfilename skyinvar=1/numpy.diag(skycovmat) sky_array=numpy.zeros((1,sky.shape[0])) sky_array[0]=sky skyinvar_array=numpy.zeros((1,skyinvar.shape[0])) skyinvar_array[0]=skyinvar pyfits.HDUList([pyfits.PrimaryHDU(sky_array),pyfits.ImageHDU(skyinvar_array),pyfits.ImageHDU(wave)]).writeto(skyfilename,clobber=True) #pyfits.HDUList([pyfits.PrimaryHDU(skycovmat)]).writeto(\"skycovmat.fits\",clobber=True) print \"subtracting sky", "file.readlines() : if line.find(\"PLUGMAPOBJ\") != 0 : continue vals=string.split(line,\" \") holetype=vals[8] if holetype", "Ninv=scipy.sparse.dia_matrix((invar[fiber,:],[0]),(nwave,nwave)) tmp=invar[fiber,:]*spectra[fiber,:] tmp2=R.transpose()*Ninv*R A+=tmp2.todense() B+=R.transpose().dot(tmp) print \"done\" print \"solving\" deconvolvedsky,dskycovmat=cholesky_solve_and_invert(A,B[0]) print \"done\" #", "sky fibers skyfibers=[] file=open(plplgmap) for line in file.readlines() : if line.find(\"PLUGMAPOBJ\") != 0", "if line.find(\"PLUGMAPOBJ\") != 0 : continue vals=string.split(line,\" \") holetype=vals[8] if holetype != \"OBJECT\"", "we have neglected R=scipy.sparse.dia_matrix((Rdata[nfibers/2],offsets),(nwave,nwave)) Rt=R.transpose() sky=numpy.dot(R.toarray(),deconvolvedsky) print \"computing covmat\" skycovmat=Rt.dot(Rt.dot(dskycovmat).transpose()) skyvar=numpy.diag(skycovmat) print \"done\"", "be converted to a numpy.array spectra[fiber] -= sky invar[fiber] = 1/( 1/invar[fiber] +", "because we only keep the diagonal # most conservative is to evaluate it", "tmp=invar[fiber,:]*spectra[fiber,:] tmp2=R.transpose()*Ninv*R A+=tmp2.todense() B+=R.transpose().dot(tmp) print \"done\" print \"solving\" deconvolvedsky,dskycovmat=cholesky_solve_and_invert(A,B[0]) print \"done\" # compute", ": print sys.argv[0],\"inspec.fits plPlugMapM.par outspec.fits (sky.fit)\" sys.exit(12); infilename=sys.argv[1] plplgmap=sys.argv[2] outfilename=sys.argv[3] skyfilename=\"\" if(len(sys.argv)>3) :", "to the Poisson noise of the subtracted sky of each # fiber that", "the sky error is certainly dominated by sky variations in field of view", "evaluate it at the highest resolution (most variance) # also the *mean* sky", "print \"computing covmat\" skycovmat=Rt.dot(Rt.dot(dskycovmat).transpose()) skyvar=numpy.diag(skycovmat) print \"done\" if skyfilename != \"\" : print", "fits camera=pyfits.open(infilename)[0].header[\"CAMERAS\"] specid=string.atoi(camera[1]) # find sky fibers skyfibers=[] file=open(plplgmap) for line in file.readlines()", "spectrum # last point, the sky error is certainly dominated by sky variations", "B+=R.transpose().dot(tmp) print \"done\" print \"solving\" deconvolvedsky,dskycovmat=cholesky_solve_and_invert(A,B[0]) print \"done\" # compute only once the", "continue vals=string.split(line,\" \") holetype=vals[8] if holetype != \"OBJECT\" : continue objType=vals[21] if objType", "in file.readlines() : if line.find(\"PLUGMAPOBJ\") != 0 : continue vals=string.split(line,\" \") holetype=vals[8] if", "already included in the invar of each spectrum # last point, the sky", "expensive and in any case approximate because we only keep the diagonal #", "skyfibers=[] file=open(plplgmap) for line in file.readlines() : if line.find(\"PLUGMAPOBJ\") != 0 : continue", "d=Rdata.shape[1]/2 nwave=Rdata.shape[2] offsets = range(d,-d-1,-1) print \"solving for the mean deconvolved sky\" print", "has to be converted to a numpy.array spectra[fiber] -= sky invar[fiber] = 1/(", "numpy.array spectra[fiber] -= sky invar[fiber] = 1/( 1/invar[fiber] + skyvar ) print \"done\"", "offsets = range(d,-d-1,-1) print \"solving for the mean deconvolved sky\" print \"filling A", "# it is a numpy.matrix that has to be converted to a numpy.array", "specid==2 : myfiberid-=500 skyfibers.append(myfiberid) file.close() print \"skyfibers (now starting at 0)=\",skyfibers hdulist=pyfits.open(infilename) spectra=hdulist[0].data", "each # fiber that is already included in the invar of each spectrum", "# find sky fibers skyfibers=[] file=open(plplgmap) for line in file.readlines() : if line.find(\"PLUGMAPOBJ\")" ]
[ "because now when # its value is requested we will check for a", "value) def __get__(self, instance, owner): if self.allow_dynamic_override: if instance.section: try: return instance.section.get_item_attribute(instance, self.name)", "is_config_item(obj): return isinstance(obj, BaseItem) class BaseSection(object): \"\"\" A base class to allow detection", "allow detection of section classes and instances. No other functionality to be added", "should avoid this. # For example, envvar, which is consulted on every value", "instance, owner): if self.allow_dynamic_override: if instance.section: try: return instance.section.get_item_attribute(instance, self.name) except AttributeError: pass", "that are used in majority of value calculation should avoid this. # For", "dynamic value instead of set value. # Attributes that are used in majority", "= True is_config = False def is_config_section(obj): return isinstance(obj, BaseSection) class ItemAttribute(object): \"\"\"", "check for a registered # dynamic attribute with the same name and if", "\"\"\" A base class to allow detection of section classes and instances. No", "used in :class:`.Item` class to declare attributes of config items. \"\"\" def __init__(self,", "value=not_set, allow_dynamic_override=False): self.name = name self.default = default self.value = value self.attr_name =", "\"\"\" def __init__(self, name, default=not_set, value=not_set, allow_dynamic_override=False): self.name = name self.default = default", "is_section = True is_config = False def is_config_section(obj): return isinstance(obj, BaseSection) class ItemAttribute(object):", "# dynamic attribute with the same name and if available use the dynamic", "= value self.attr_name = '_{}'.format(self.name) # If set to True, this becomes an", "is designed # to be a cheap attribute. Users can, however, override envvar_name", "value. # Attributes that are used in majority of value calculation should avoid", "value calculation should avoid this. # For example, envvar, which is consulted on", "classes and instances. No other functionality to be added here. \"\"\" is_item =", "a registered # dynamic attribute with the same name and if available use", "name, default=not_set, value=not_set, allow_dynamic_override=False): self.name = name self.default = default self.value = value", "instance, value): setattr(instance, self.attr_name, value) def __get__(self, instance, owner): if self.allow_dynamic_override: if instance.section:", "instead of set value. # Attributes that are used in majority of value", "the dynamic value instead of set value. # Attributes that are used in", "designed # to be a cheap attribute. Users can, however, override envvar_name which", "if instance.section: try: return instance.section.get_item_attribute(instance, self.name) except AttributeError: pass return getattr(instance, self.attr_name, self.default)", "from .utils import not_set class BaseItem(object): is_item = True is_section = False is_config", "instances. No other functionality to be added here. \"\"\" is_item = False is_section", "= False def is_config_item(obj): return isinstance(obj, BaseItem) class BaseSection(object): \"\"\" A base class", "is requested we will check for a registered # dynamic attribute with the", "however, override envvar_name which is # used only if envvar is set to", ".utils import not_set class BaseItem(object): is_item = True is_section = False is_config =", "True is_config = False def is_config_section(obj): return isinstance(obj, BaseSection) class ItemAttribute(object): \"\"\" Class", "is_config = False def is_config_section(obj): return isinstance(obj, BaseSection) class ItemAttribute(object): \"\"\" Class used", "A base class to allow detection of section classes and instances. No other", "No other functionality to be added here. \"\"\" is_item = False is_section =", "= name self.default = default self.value = value self.attr_name = '_{}'.format(self.name) # If", "# For example, envvar, which is consulted on every value request, is designed", "self.allow_dynamic_override: if instance.section: try: return instance.section.get_item_attribute(instance, self.name) except AttributeError: pass return getattr(instance, self.attr_name,", "is set to True. self.allow_dynamic_override = allow_dynamic_override def __set__(self, instance, value): setattr(instance, self.attr_name,", "registered # dynamic attribute with the same name and if available use the", "is_config = False def is_config_item(obj): return isinstance(obj, BaseItem) class BaseSection(object): \"\"\" A base", "added here. \"\"\" is_item = False is_section = True is_config = False def", "are used in majority of value calculation should avoid this. # For example,", "ItemAttribute(object): \"\"\" Class used in :class:`.Item` class to declare attributes of config items.", "attribute. Users can, however, override envvar_name which is # used only if envvar", "False is_config = False def is_config_item(obj): return isinstance(obj, BaseItem) class BaseSection(object): \"\"\" A", "value self.attr_name = '_{}'.format(self.name) # If set to True, this becomes an expensive", "which is consulted on every value request, is designed # to be a", "here. \"\"\" is_item = False is_section = True is_config = False def is_config_section(obj):", "is consulted on every value request, is designed # to be a cheap", "to allow detection of section classes and instances. No other functionality to be", "not_set class BaseItem(object): is_item = True is_section = False is_config = False def", "to declare attributes of config items. \"\"\" def __init__(self, name, default=not_set, value=not_set, allow_dynamic_override=False):", "to be added here. \"\"\" is_item = False is_section = True is_config =", "isinstance(obj, BaseItem) class BaseSection(object): \"\"\" A base class to allow detection of section", "envvar_name which is # used only if envvar is set to True. self.allow_dynamic_override", "allow_dynamic_override=False): self.name = name self.default = default self.value = value self.attr_name = '_{}'.format(self.name)", "be added here. \"\"\" is_item = False is_section = True is_config = False", "which is # used only if envvar is set to True. self.allow_dynamic_override =", "to True. self.allow_dynamic_override = allow_dynamic_override def __set__(self, instance, value): setattr(instance, self.attr_name, value) def", "same name and if available use the dynamic value instead of set value.", "functionality to be added here. \"\"\" is_item = False is_section = True is_config", ":class:`.Item` class to declare attributes of config items. \"\"\" def __init__(self, name, default=not_set,", "is # used only if envvar is set to True. self.allow_dynamic_override = allow_dynamic_override", "default=not_set, value=not_set, allow_dynamic_override=False): self.name = name self.default = default self.value = value self.attr_name", "Attributes that are used in majority of value calculation should avoid this. #", "= False is_section = True is_config = False def is_config_section(obj): return isinstance(obj, BaseSection)", "when # its value is requested we will check for a registered #", "BaseSection(object): \"\"\" A base class to allow detection of section classes and instances.", "BaseSection) class ItemAttribute(object): \"\"\" Class used in :class:`.Item` class to declare attributes of", "can, however, override envvar_name which is # used only if envvar is set", "of set value. # Attributes that are used in majority of value calculation", "used only if envvar is set to True. self.allow_dynamic_override = allow_dynamic_override def __set__(self,", "envvar is set to True. self.allow_dynamic_override = allow_dynamic_override def __set__(self, instance, value): setattr(instance,", "use the dynamic value instead of set value. # Attributes that are used", "value is requested we will check for a registered # dynamic attribute with", "and if available use the dynamic value instead of set value. # Attributes", "= False is_config = False def is_config_item(obj): return isinstance(obj, BaseItem) class BaseSection(object): \"\"\"", "True is_section = False is_config = False def is_config_item(obj): return isinstance(obj, BaseItem) class", "return isinstance(obj, BaseSection) class ItemAttribute(object): \"\"\" Class used in :class:`.Item` class to declare", "isinstance(obj, BaseSection) class ItemAttribute(object): \"\"\" Class used in :class:`.Item` class to declare attributes", "requested we will check for a registered # dynamic attribute with the same", "this. # For example, envvar, which is consulted on every value request, is", "True, this becomes an expensive attribute because now when # its value is", "BaseItem) class BaseSection(object): \"\"\" A base class to allow detection of section classes", "cheap attribute. Users can, however, override envvar_name which is # used only if", "items. \"\"\" def __init__(self, name, default=not_set, value=not_set, allow_dynamic_override=False): self.name = name self.default =", "of value calculation should avoid this. # For example, envvar, which is consulted", "an expensive attribute because now when # its value is requested we will", "we will check for a registered # dynamic attribute with the same name", "calculation should avoid this. # For example, envvar, which is consulted on every", "its value is requested we will check for a registered # dynamic attribute", "of section classes and instances. No other functionality to be added here. \"\"\"", "If set to True, this becomes an expensive attribute because now when #", "set value. # Attributes that are used in majority of value calculation should", "\"\"\" Class used in :class:`.Item` class to declare attributes of config items. \"\"\"", "in majority of value calculation should avoid this. # For example, envvar, which", "value instead of set value. # Attributes that are used in majority of", "class BaseItem(object): is_item = True is_section = False is_config = False def is_config_item(obj):", "to be a cheap attribute. Users can, however, override envvar_name which is #", "dynamic attribute with the same name and if available use the dynamic value", "if envvar is set to True. self.allow_dynamic_override = allow_dynamic_override def __set__(self, instance, value):", "def __init__(self, name, default=not_set, value=not_set, allow_dynamic_override=False): self.name = name self.default = default self.value", "__set__(self, instance, value): setattr(instance, self.attr_name, value) def __get__(self, instance, owner): if self.allow_dynamic_override: if", "to True, this becomes an expensive attribute because now when # its value", "every value request, is designed # to be a cheap attribute. Users can,", "BaseItem(object): is_item = True is_section = False is_config = False def is_config_item(obj): return", "allow_dynamic_override def __set__(self, instance, value): setattr(instance, self.attr_name, value) def __get__(self, instance, owner): if", "avoid this. # For example, envvar, which is consulted on every value request,", "self.attr_name, value) def __get__(self, instance, owner): if self.allow_dynamic_override: if instance.section: try: return instance.section.get_item_attribute(instance,", "override envvar_name which is # used only if envvar is set to True.", "def __set__(self, instance, value): setattr(instance, self.attr_name, value) def __get__(self, instance, owner): if self.allow_dynamic_override:", "is_section = False is_config = False def is_config_item(obj): return isinstance(obj, BaseItem) class BaseSection(object):", "set to True, this becomes an expensive attribute because now when # its", "__init__(self, name, default=not_set, value=not_set, allow_dynamic_override=False): self.name = name self.default = default self.value =", "name and if available use the dynamic value instead of set value. #", "__get__(self, instance, owner): if self.allow_dynamic_override: if instance.section: try: return instance.section.get_item_attribute(instance, self.name) except AttributeError:", "owner): if self.allow_dynamic_override: if instance.section: try: return instance.section.get_item_attribute(instance, self.name) except AttributeError: pass return", "section classes and instances. No other functionality to be added here. \"\"\" is_item", "envvar, which is consulted on every value request, is designed # to be", "def is_config_item(obj): return isinstance(obj, BaseItem) class BaseSection(object): \"\"\" A base class to allow", "# If set to True, this becomes an expensive attribute because now when", "self.default = default self.value = value self.attr_name = '_{}'.format(self.name) # If set to", "default self.value = value self.attr_name = '_{}'.format(self.name) # If set to True, this", "only if envvar is set to True. self.allow_dynamic_override = allow_dynamic_override def __set__(self, instance,", "return isinstance(obj, BaseItem) class BaseSection(object): \"\"\" A base class to allow detection of", "becomes an expensive attribute because now when # its value is requested we", "<reponame>haizaar/configmanager<filename>configmanager/base.py from .utils import not_set class BaseItem(object): is_item = True is_section = False", "be a cheap attribute. Users can, however, override envvar_name which is # used", "in :class:`.Item` class to declare attributes of config items. \"\"\" def __init__(self, name,", "setattr(instance, self.attr_name, value) def __get__(self, instance, owner): if self.allow_dynamic_override: if instance.section: try: return", "is_config_section(obj): return isinstance(obj, BaseSection) class ItemAttribute(object): \"\"\" Class used in :class:`.Item` class to", "= True is_section = False is_config = False def is_config_item(obj): return isinstance(obj, BaseItem)", "= False def is_config_section(obj): return isinstance(obj, BaseSection) class ItemAttribute(object): \"\"\" Class used in", "majority of value calculation should avoid this. # For example, envvar, which is", "will check for a registered # dynamic attribute with the same name and", "True. self.allow_dynamic_override = allow_dynamic_override def __set__(self, instance, value): setattr(instance, self.attr_name, value) def __get__(self,", "# its value is requested we will check for a registered # dynamic", "other functionality to be added here. \"\"\" is_item = False is_section = True", "= '_{}'.format(self.name) # If set to True, this becomes an expensive attribute because", "self.attr_name = '_{}'.format(self.name) # If set to True, this becomes an expensive attribute", "used in majority of value calculation should avoid this. # For example, envvar,", "now when # its value is requested we will check for a registered", "example, envvar, which is consulted on every value request, is designed # to", "and instances. No other functionality to be added here. \"\"\" is_item = False", "expensive attribute because now when # its value is requested we will check", "config items. \"\"\" def __init__(self, name, default=not_set, value=not_set, allow_dynamic_override=False): self.name = name self.default", "def is_config_section(obj): return isinstance(obj, BaseSection) class ItemAttribute(object): \"\"\" Class used in :class:`.Item` class", "Users can, however, override envvar_name which is # used only if envvar is", "class to declare attributes of config items. \"\"\" def __init__(self, name, default=not_set, value=not_set,", "attributes of config items. \"\"\" def __init__(self, name, default=not_set, value=not_set, allow_dynamic_override=False): self.name =", "a cheap attribute. Users can, however, override envvar_name which is # used only", "self.name = name self.default = default self.value = value self.attr_name = '_{}'.format(self.name) #", "= allow_dynamic_override def __set__(self, instance, value): setattr(instance, self.attr_name, value) def __get__(self, instance, owner):", "for a registered # dynamic attribute with the same name and if available", "class BaseSection(object): \"\"\" A base class to allow detection of section classes and", "base class to allow detection of section classes and instances. No other functionality", "class ItemAttribute(object): \"\"\" Class used in :class:`.Item` class to declare attributes of config", "name self.default = default self.value = value self.attr_name = '_{}'.format(self.name) # If set", "with the same name and if available use the dynamic value instead of", "self.allow_dynamic_override = allow_dynamic_override def __set__(self, instance, value): setattr(instance, self.attr_name, value) def __get__(self, instance,", "\"\"\" is_item = False is_section = True is_config = False def is_config_section(obj): return", "= default self.value = value self.attr_name = '_{}'.format(self.name) # If set to True,", "is_item = True is_section = False is_config = False def is_config_item(obj): return isinstance(obj,", "'_{}'.format(self.name) # If set to True, this becomes an expensive attribute because now", "is_item = False is_section = True is_config = False def is_config_section(obj): return isinstance(obj,", "False def is_config_item(obj): return isinstance(obj, BaseItem) class BaseSection(object): \"\"\" A base class to", "if available use the dynamic value instead of set value. # Attributes that", "False is_section = True is_config = False def is_config_section(obj): return isinstance(obj, BaseSection) class", "self.value = value self.attr_name = '_{}'.format(self.name) # If set to True, this becomes", "# to be a cheap attribute. Users can, however, override envvar_name which is", "detection of section classes and instances. No other functionality to be added here.", "of config items. \"\"\" def __init__(self, name, default=not_set, value=not_set, allow_dynamic_override=False): self.name = name", "value): setattr(instance, self.attr_name, value) def __get__(self, instance, owner): if self.allow_dynamic_override: if instance.section: try:", "declare attributes of config items. \"\"\" def __init__(self, name, default=not_set, value=not_set, allow_dynamic_override=False): self.name", "# Attributes that are used in majority of value calculation should avoid this.", "Class used in :class:`.Item` class to declare attributes of config items. \"\"\" def", "set to True. self.allow_dynamic_override = allow_dynamic_override def __set__(self, instance, value): setattr(instance, self.attr_name, value)", "import not_set class BaseItem(object): is_item = True is_section = False is_config = False", "consulted on every value request, is designed # to be a cheap attribute.", "class to allow detection of section classes and instances. No other functionality to", "value request, is designed # to be a cheap attribute. Users can, however,", "request, is designed # to be a cheap attribute. Users can, however, override", "# used only if envvar is set to True. self.allow_dynamic_override = allow_dynamic_override def", "For example, envvar, which is consulted on every value request, is designed #", "the same name and if available use the dynamic value instead of set", "on every value request, is designed # to be a cheap attribute. Users", "if self.allow_dynamic_override: if instance.section: try: return instance.section.get_item_attribute(instance, self.name) except AttributeError: pass return getattr(instance,", "attribute because now when # its value is requested we will check for", "this becomes an expensive attribute because now when # its value is requested", "available use the dynamic value instead of set value. # Attributes that are", "def __get__(self, instance, owner): if self.allow_dynamic_override: if instance.section: try: return instance.section.get_item_attribute(instance, self.name) except", "attribute with the same name and if available use the dynamic value instead", "False def is_config_section(obj): return isinstance(obj, BaseSection) class ItemAttribute(object): \"\"\" Class used in :class:`.Item`" ]
[ "FlaskForm, RecaptchaField from wtforms import StringField , PasswordField, SubmitField from wtforms.validators import DataRequired,", "from wtforms import StringField , PasswordField, SubmitField from wtforms.validators import DataRequired, Email, Length", "PasswordField(\"Password\", validators=[DataRequired(\"Enter a valid password\"), Length(min=8, message=\"Password must be a minimum of 8", "firstname = StringField(\"First name\", validators=[DataRequired(\"Enter your name\")]) lastname = StringField(\"Last name\", validators=[DataRequired(\"Enter your", "last name\")]) email = StringField(\"Email\", validators=[DataRequired(\"Provide your email\"), Email(\"Please enter a valid email\")])", "validators=[DataRequired(\"Enter your last name\")]) email = StringField(\"Email\", validators=[DataRequired(\"Provide your email\"), Email(\"Please enter a", "= StringField(\"Email\", validators=[DataRequired(\"Provide your email\"), Email(\"Please enter a valid email\")]) password = PasswordField(\"Password\",", "be a minimum of 8 charaters\")]) submit = SubmitField(\"Submit\", validators=[DataRequired()]) #recaptcha = RecaptchaField({'hl':", "name\", validators=[DataRequired(\"Enter your name\")]) lastname = StringField(\"Last name\", validators=[DataRequired(\"Enter your last name\")]) email", "import StringField , PasswordField, SubmitField from wtforms.validators import DataRequired, Email, Length class SignupForm(FlaskForm):", "SignupForm(FlaskForm): firstname = StringField(\"First name\", validators=[DataRequired(\"Enter your name\")]) lastname = StringField(\"Last name\", validators=[DataRequired(\"Enter", "minimum of 8 charaters\")]) submit = SubmitField(\"Submit\", validators=[DataRequired()]) #recaptcha = RecaptchaField({'hl': 'zh', 'render':", "validators=[DataRequired(\"Enter a valid password\"), Length(min=8, message=\"Password must be a minimum of 8 charaters\")])", "StringField(\"Last name\", validators=[DataRequired(\"Enter your last name\")]) email = StringField(\"Email\", validators=[DataRequired(\"Provide your email\"), Email(\"Please", "name\")]) email = StringField(\"Email\", validators=[DataRequired(\"Provide your email\"), Email(\"Please enter a valid email\")]) password", "Email(\"Please enter a valid email\")]) password = PasswordField(\"Password\", validators=[DataRequired(\"Enter a valid password\"), Length(min=8,", "a valid password\"), Length(min=8, message=\"Password must be a minimum of 8 charaters\")]) submit", "Email, Length class SignupForm(FlaskForm): firstname = StringField(\"First name\", validators=[DataRequired(\"Enter your name\")]) lastname =", "SubmitField from wtforms.validators import DataRequired, Email, Length class SignupForm(FlaskForm): firstname = StringField(\"First name\",", "wtforms.validators import DataRequired, Email, Length class SignupForm(FlaskForm): firstname = StringField(\"First name\", validators=[DataRequired(\"Enter your", "validators=[DataRequired(\"Enter your name\")]) lastname = StringField(\"Last name\", validators=[DataRequired(\"Enter your last name\")]) email =", "valid email\")]) password = PasswordField(\"Password\", validators=[DataRequired(\"Enter a valid password\"), Length(min=8, message=\"Password must be", "email\")]) password = PasswordField(\"Password\", validators=[DataRequired(\"Enter a valid password\"), Length(min=8, message=\"Password must be a", "= StringField(\"First name\", validators=[DataRequired(\"Enter your name\")]) lastname = StringField(\"Last name\", validators=[DataRequired(\"Enter your last", "= StringField(\"Last name\", validators=[DataRequired(\"Enter your last name\")]) email = StringField(\"Email\", validators=[DataRequired(\"Provide your email\"),", "valid password\"), Length(min=8, message=\"Password must be a minimum of 8 charaters\")]) submit =", "must be a minimum of 8 charaters\")]) submit = SubmitField(\"Submit\", validators=[DataRequired()]) #recaptcha =", "a minimum of 8 charaters\")]) submit = SubmitField(\"Submit\", validators=[DataRequired()]) #recaptcha = RecaptchaField({'hl': 'zh',", "import FlaskForm, RecaptchaField from wtforms import StringField , PasswordField, SubmitField from wtforms.validators import", "your name\")]) lastname = StringField(\"Last name\", validators=[DataRequired(\"Enter your last name\")]) email = StringField(\"Email\",", "lastname = StringField(\"Last name\", validators=[DataRequired(\"Enter your last name\")]) email = StringField(\"Email\", validators=[DataRequired(\"Provide your", "email\"), Email(\"Please enter a valid email\")]) password = PasswordField(\"Password\", validators=[DataRequired(\"Enter a valid password\"),", "from flask_wtf import FlaskForm, RecaptchaField from wtforms import StringField , PasswordField, SubmitField from", "DataRequired, Email, Length class SignupForm(FlaskForm): firstname = StringField(\"First name\", validators=[DataRequired(\"Enter your name\")]) lastname", "name\", validators=[DataRequired(\"Enter your last name\")]) email = StringField(\"Email\", validators=[DataRequired(\"Provide your email\"), Email(\"Please enter", "flask_wtf import FlaskForm, RecaptchaField from wtforms import StringField , PasswordField, SubmitField from wtforms.validators", "StringField , PasswordField, SubmitField from wtforms.validators import DataRequired, Email, Length class SignupForm(FlaskForm): firstname", "message=\"Password must be a minimum of 8 charaters\")]) submit = SubmitField(\"Submit\", validators=[DataRequired()]) #recaptcha", "StringField(\"Email\", validators=[DataRequired(\"Provide your email\"), Email(\"Please enter a valid email\")]) password = PasswordField(\"Password\", validators=[DataRequired(\"Enter", "validators=[DataRequired(\"Provide your email\"), Email(\"Please enter a valid email\")]) password = PasswordField(\"Password\", validators=[DataRequired(\"Enter a", "of 8 charaters\")]) submit = SubmitField(\"Submit\", validators=[DataRequired()]) #recaptcha = RecaptchaField({'hl': 'zh', 'render': 'explicit'})", "a valid email\")]) password = PasswordField(\"Password\", validators=[DataRequired(\"Enter a valid password\"), Length(min=8, message=\"Password must", "Length(min=8, message=\"Password must be a minimum of 8 charaters\")]) submit = SubmitField(\"Submit\", validators=[DataRequired()])", "StringField(\"First name\", validators=[DataRequired(\"Enter your name\")]) lastname = StringField(\"Last name\", validators=[DataRequired(\"Enter your last name\")])", "import DataRequired, Email, Length class SignupForm(FlaskForm): firstname = StringField(\"First name\", validators=[DataRequired(\"Enter your name\")])", "email = StringField(\"Email\", validators=[DataRequired(\"Provide your email\"), Email(\"Please enter a valid email\")]) password =", "class SignupForm(FlaskForm): firstname = StringField(\"First name\", validators=[DataRequired(\"Enter your name\")]) lastname = StringField(\"Last name\",", "PasswordField, SubmitField from wtforms.validators import DataRequired, Email, Length class SignupForm(FlaskForm): firstname = StringField(\"First", ", PasswordField, SubmitField from wtforms.validators import DataRequired, Email, Length class SignupForm(FlaskForm): firstname =", "your email\"), Email(\"Please enter a valid email\")]) password = PasswordField(\"Password\", validators=[DataRequired(\"Enter a valid", "wtforms import StringField , PasswordField, SubmitField from wtforms.validators import DataRequired, Email, Length class", "password = PasswordField(\"Password\", validators=[DataRequired(\"Enter a valid password\"), Length(min=8, message=\"Password must be a minimum", "your last name\")]) email = StringField(\"Email\", validators=[DataRequired(\"Provide your email\"), Email(\"Please enter a valid", "password\"), Length(min=8, message=\"Password must be a minimum of 8 charaters\")]) submit = SubmitField(\"Submit\",", "enter a valid email\")]) password = PasswordField(\"Password\", validators=[DataRequired(\"Enter a valid password\"), Length(min=8, message=\"Password", "name\")]) lastname = StringField(\"Last name\", validators=[DataRequired(\"Enter your last name\")]) email = StringField(\"Email\", validators=[DataRequired(\"Provide", "= PasswordField(\"Password\", validators=[DataRequired(\"Enter a valid password\"), Length(min=8, message=\"Password must be a minimum of", "from wtforms.validators import DataRequired, Email, Length class SignupForm(FlaskForm): firstname = StringField(\"First name\", validators=[DataRequired(\"Enter", "Length class SignupForm(FlaskForm): firstname = StringField(\"First name\", validators=[DataRequired(\"Enter your name\")]) lastname = StringField(\"Last", "RecaptchaField from wtforms import StringField , PasswordField, SubmitField from wtforms.validators import DataRequired, Email," ]
[ "dirname(dirname(dirname(dirname(os.path.abspath(__file__))))) class SparkEnv: def __init__(self, name): os.environ['HADOOP_HOME'] = dirname(dirname(dirname(dirname(os.path.abspath(__file__))))) + r'/hadoopdir' os.environ['SPARK_HOME'] =", "from pyspark.sql import SparkSession self.ss = SparkSession.builder.appName(name).getOrCreate() def postInit(self): return (self, self.sc, self.ss)", "def __init__(self, name): os.environ['HADOOP_HOME'] = dirname(dirname(dirname(dirname(os.path.abspath(__file__))))) + r'/hadoopdir' os.environ['SPARK_HOME'] = r\"D:\\assistlibs\\hadoop\\spark-2.2.3-bin-hadoop2.6\" sys.path.append(r\"D:\\assistlibs\\hadoop\\spark-2.2.3-bin-hadoop2.6\\python\") from", "= r\"D:\\assistlibs\\hadoop\\spark-2.2.3-bin-hadoop2.6\" sys.path.append(r\"D:\\assistlibs\\hadoop\\spark-2.2.3-bin-hadoop2.6\\python\") from pyspark import SparkContext self.sc = SparkContext(\"local\", name) self.sc.setLogLevel(\"WARN\") from", "SparkContext(\"local\", name) self.sc.setLogLevel(\"WARN\") from pyspark.sql import SparkSession self.ss = SparkSession.builder.appName(name).getOrCreate() def postInit(self): return", "= dirname(dirname(dirname(dirname(os.path.abspath(__file__))))) + r'/hadoopdir' os.environ['SPARK_HOME'] = r\"D:\\assistlibs\\hadoop\\spark-2.2.3-bin-hadoop2.6\" sys.path.append(r\"D:\\assistlibs\\hadoop\\spark-2.2.3-bin-hadoop2.6\\python\") from pyspark import SparkContext self.sc", "os from os.path import * def pl(): return dirname(dirname(dirname(dirname(os.path.abspath(__file__))))) class SparkEnv: def __init__(self,", "os.environ['SPARK_HOME'] = r\"D:\\assistlibs\\hadoop\\spark-2.2.3-bin-hadoop2.6\" sys.path.append(r\"D:\\assistlibs\\hadoop\\spark-2.2.3-bin-hadoop2.6\\python\") from pyspark import SparkContext self.sc = SparkContext(\"local\", name) self.sc.setLogLevel(\"WARN\")", "SparkEnv: def __init__(self, name): os.environ['HADOOP_HOME'] = dirname(dirname(dirname(dirname(os.path.abspath(__file__))))) + r'/hadoopdir' os.environ['SPARK_HOME'] = r\"D:\\assistlibs\\hadoop\\spark-2.2.3-bin-hadoop2.6\" sys.path.append(r\"D:\\assistlibs\\hadoop\\spark-2.2.3-bin-hadoop2.6\\python\")", "SparkSession self.ss = SparkSession.builder.appName(name).getOrCreate() def postInit(self): return (self, self.sc, self.ss) def projLoc(self): return", "* def pl(): return dirname(dirname(dirname(dirname(os.path.abspath(__file__))))) class SparkEnv: def __init__(self, name): os.environ['HADOOP_HOME'] = dirname(dirname(dirname(dirname(os.path.abspath(__file__)))))", "import SparkContext self.sc = SparkContext(\"local\", name) self.sc.setLogLevel(\"WARN\") from pyspark.sql import SparkSession self.ss =", "r\"D:\\assistlibs\\hadoop\\spark-2.2.3-bin-hadoop2.6\" sys.path.append(r\"D:\\assistlibs\\hadoop\\spark-2.2.3-bin-hadoop2.6\\python\") from pyspark import SparkContext self.sc = SparkContext(\"local\", name) self.sc.setLogLevel(\"WARN\") from pyspark.sql", "pl(): return dirname(dirname(dirname(dirname(os.path.abspath(__file__))))) class SparkEnv: def __init__(self, name): os.environ['HADOOP_HOME'] = dirname(dirname(dirname(dirname(os.path.abspath(__file__))))) + r'/hadoopdir'", "name): os.environ['HADOOP_HOME'] = dirname(dirname(dirname(dirname(os.path.abspath(__file__))))) + r'/hadoopdir' os.environ['SPARK_HOME'] = r\"D:\\assistlibs\\hadoop\\spark-2.2.3-bin-hadoop2.6\" sys.path.append(r\"D:\\assistlibs\\hadoop\\spark-2.2.3-bin-hadoop2.6\\python\") from pyspark import", "r'/hadoopdir' os.environ['SPARK_HOME'] = r\"D:\\assistlibs\\hadoop\\spark-2.2.3-bin-hadoop2.6\" sys.path.append(r\"D:\\assistlibs\\hadoop\\spark-2.2.3-bin-hadoop2.6\\python\") from pyspark import SparkContext self.sc = SparkContext(\"local\", name)", "os.path import * def pl(): return dirname(dirname(dirname(dirname(os.path.abspath(__file__))))) class SparkEnv: def __init__(self, name): os.environ['HADOOP_HOME']", "sys import os from os.path import * def pl(): return dirname(dirname(dirname(dirname(os.path.abspath(__file__))))) class SparkEnv:", "import SparkSession self.ss = SparkSession.builder.appName(name).getOrCreate() def postInit(self): return (self, self.sc, self.ss) def projLoc(self):", "from pyspark import SparkContext self.sc = SparkContext(\"local\", name) self.sc.setLogLevel(\"WARN\") from pyspark.sql import SparkSession", "return dirname(dirname(dirname(dirname(os.path.abspath(__file__))))) class SparkEnv: def __init__(self, name): os.environ['HADOOP_HOME'] = dirname(dirname(dirname(dirname(os.path.abspath(__file__))))) + r'/hadoopdir' os.environ['SPARK_HOME']", "self.sc.setLogLevel(\"WARN\") from pyspark.sql import SparkSession self.ss = SparkSession.builder.appName(name).getOrCreate() def postInit(self): return (self, self.sc,", "import sys import os from os.path import * def pl(): return dirname(dirname(dirname(dirname(os.path.abspath(__file__))))) class", "self.ss = SparkSession.builder.appName(name).getOrCreate() def postInit(self): return (self, self.sc, self.ss) def projLoc(self): return dirname(dirname(dirname(dirname(os.path.abspath(__file__)))))", "sys.path.append(r\"D:\\assistlibs\\hadoop\\spark-2.2.3-bin-hadoop2.6\\python\") from pyspark import SparkContext self.sc = SparkContext(\"local\", name) self.sc.setLogLevel(\"WARN\") from pyspark.sql import", "from os.path import * def pl(): return dirname(dirname(dirname(dirname(os.path.abspath(__file__))))) class SparkEnv: def __init__(self, name):", "__init__(self, name): os.environ['HADOOP_HOME'] = dirname(dirname(dirname(dirname(os.path.abspath(__file__))))) + r'/hadoopdir' os.environ['SPARK_HOME'] = r\"D:\\assistlibs\\hadoop\\spark-2.2.3-bin-hadoop2.6\" sys.path.append(r\"D:\\assistlibs\\hadoop\\spark-2.2.3-bin-hadoop2.6\\python\") from pyspark", "os.environ['HADOOP_HOME'] = dirname(dirname(dirname(dirname(os.path.abspath(__file__))))) + r'/hadoopdir' os.environ['SPARK_HOME'] = r\"D:\\assistlibs\\hadoop\\spark-2.2.3-bin-hadoop2.6\" sys.path.append(r\"D:\\assistlibs\\hadoop\\spark-2.2.3-bin-hadoop2.6\\python\") from pyspark import SparkContext", "self.sc = SparkContext(\"local\", name) self.sc.setLogLevel(\"WARN\") from pyspark.sql import SparkSession self.ss = SparkSession.builder.appName(name).getOrCreate() def", "class SparkEnv: def __init__(self, name): os.environ['HADOOP_HOME'] = dirname(dirname(dirname(dirname(os.path.abspath(__file__))))) + r'/hadoopdir' os.environ['SPARK_HOME'] = r\"D:\\assistlibs\\hadoop\\spark-2.2.3-bin-hadoop2.6\"", "name) self.sc.setLogLevel(\"WARN\") from pyspark.sql import SparkSession self.ss = SparkSession.builder.appName(name).getOrCreate() def postInit(self): return (self,", "SparkContext self.sc = SparkContext(\"local\", name) self.sc.setLogLevel(\"WARN\") from pyspark.sql import SparkSession self.ss = SparkSession.builder.appName(name).getOrCreate()", "import * def pl(): return dirname(dirname(dirname(dirname(os.path.abspath(__file__))))) class SparkEnv: def __init__(self, name): os.environ['HADOOP_HOME'] =", "= SparkContext(\"local\", name) self.sc.setLogLevel(\"WARN\") from pyspark.sql import SparkSession self.ss = SparkSession.builder.appName(name).getOrCreate() def postInit(self):", "pyspark.sql import SparkSession self.ss = SparkSession.builder.appName(name).getOrCreate() def postInit(self): return (self, self.sc, self.ss) def", "pyspark import SparkContext self.sc = SparkContext(\"local\", name) self.sc.setLogLevel(\"WARN\") from pyspark.sql import SparkSession self.ss", "import os from os.path import * def pl(): return dirname(dirname(dirname(dirname(os.path.abspath(__file__))))) class SparkEnv: def", "+ r'/hadoopdir' os.environ['SPARK_HOME'] = r\"D:\\assistlibs\\hadoop\\spark-2.2.3-bin-hadoop2.6\" sys.path.append(r\"D:\\assistlibs\\hadoop\\spark-2.2.3-bin-hadoop2.6\\python\") from pyspark import SparkContext self.sc = SparkContext(\"local\",", "dirname(dirname(dirname(dirname(os.path.abspath(__file__))))) + r'/hadoopdir' os.environ['SPARK_HOME'] = r\"D:\\assistlibs\\hadoop\\spark-2.2.3-bin-hadoop2.6\" sys.path.append(r\"D:\\assistlibs\\hadoop\\spark-2.2.3-bin-hadoop2.6\\python\") from pyspark import SparkContext self.sc =", "def pl(): return dirname(dirname(dirname(dirname(os.path.abspath(__file__))))) class SparkEnv: def __init__(self, name): os.environ['HADOOP_HOME'] = dirname(dirname(dirname(dirname(os.path.abspath(__file__))))) +" ]
[]
[ "i1 = i2 = 0 for i in range(1,101): i1 += i i2", "<reponame>mathtimes/math-lab i1 = i2 = 0 for i in range(1,101): i1 += i", "= 0 for i in range(1,101): i1 += i i2 += i**2 print(i1**2-i2)", "= i2 = 0 for i in range(1,101): i1 += i i2 +=", "i2 = 0 for i in range(1,101): i1 += i i2 += i**2" ]
[ "helper import app.util.lang_config as lang_config import app.chat.memmode as memmode from firefly.server.globalobject import GlobalObject", "app.util.lang_config as lang_config import app.chat.memmode as memmode from firefly.server.globalobject import GlobalObject import app.core.game_module_def", "GlobalObject().remote['gate'].callRemote(\"pushObject\",cmd,buf, [dId]) return def _float_msg(self,cId,msg): c_data = {}; c_data['msg'] = msg; self.fire_event(EVENT_SEND2CLIENTBYCID,[S2C_NOTIFY_FLOAT,cId,c_data]); return;", "0; data['pid'] = cId; data['shape'] = c_info[\"figure\"]; data['vip'] = 0; data['name'] = c_info[\"nickname\"];", "as helper import app.util.lang_config as lang_config import app.chat.memmode as memmode from firefly.server.globalobject import", "log.msg('chat_main on_login fatal err %d'%(cId)); return c_info = c_data.get('data'); return def on_logout(self,ud): dId", "self.register_event(EVENT_LOGOUT,self.on_logout); self.register_event(EVENT_RELOGIN,self.on_relogin); self.register_net_event(C2S_CHAT,self.on_chat); self.register_event(EVENT_SEND2CLIENT,self._send2client); self.register_event(EVENT_SEND2CLIENTBYCID,self._send2clientbycid) return def _getdidbycid(self,cId): if self.character_map.has_key(cId): return self.character_map[cId]; return", "self.character_map.has_key(cId): del self.character_map[cId]; return def on_chat(self,ud): dId = ud[\"dId\"]; cId = ud[\"cId\"]; data", "app.protocol.ProtocolDesc import * import app.protocol.netutil as netutil from twisted.python import log import app.util.helper", "if self.character_map.has_key(cId): return self.character_map[cId]; return def _send2clientbycid(self,ud): cmd = ud[0] cId = ud[1];", "utf-8 # import app.base.game_module_mgr from app.core.game_event_def import * from app.protocol.ProtocolDesc import * import", "dId = ud[\"dId\"]; cId = ud[\"cId\"]; if self.character_map.has_key(cId): self.character_map[cId] = dId; return def", "= ud[\"dId\"]; cId = ud[\"cId\"]; if self.character_map.has_key(cId): del self.character_map[cId]; return def on_chat(self,ud): dId", "= 0; data['name'] = c_info[\"nickname\"]; data['msg'] = msg; cmd = S2C_CHAT; buf =", "c_data['msg'] = msg; self.fire_event(EVENT_SEND2CLIENTBYCID,[S2C_NOTIFY_FLOAT,cId,c_data]); return; def _is_cId_valid(self,cId):#其实就是角色是否在线的判定 return self.character_map.has_key(cId); def on_relogin(self,ud): dId =", "cId = ud[\"cId\"]; if self.character_map.has_key(cId): self.character_map[cId] = dId; return def on_login(self,ud): dId =", "ud[\"cId\"]; if self.character_map.has_key(cId): self.character_map[cId] = dId; return def on_login(self,ud): dId = ud[\"dId\"]; cId", "on_logout(self,ud): dId = ud[\"dId\"]; cId = ud[\"cId\"]; if self.character_map.has_key(cId): del self.character_map[cId]; return def", "import app.core.game_module_def as game_module_def class chat_main(app.base.game_module_mgr.game_module): def __init__(self): super(chat_main,self).__init__(); self.character_map = {}; return", "if self.character_map.has_key(cId): del self.character_map[cId]; return def on_chat(self,ud): dId = ud[\"dId\"]; cId = ud[\"cId\"];", "return self.character_map.has_key(cId); def on_relogin(self,ud): dId = ud[\"dId\"]; cId = ud[\"cId\"]; if self.character_map.has_key(cId): self.character_map[cId]", "self.register_event(EVENT_SEND2CLIENTBYCID,self._send2clientbycid) return def _getdidbycid(self,cId): if self.character_map.has_key(cId): return self.character_map[cId]; return def _send2clientbycid(self,ud): cmd =", "def on_login(self,ud): dId = ud[\"dId\"]; cId = ud[\"cId\"]; self.character_map[cId] = dId; c_data =", "data['ch'] = ch; data['srvid'] = 0; data['pid'] = cId; data['shape'] = c_info[\"figure\"]; data['vip']", "ch; data['srvid'] = 0; data['pid'] = cId; data['shape'] = c_info[\"figure\"]; data['vip'] = 0;", "= S2C_CHAT; buf = netutil.s2c_data2bufbycmd(cmd,data); exclude_list = []; GlobalObject().remote['gate'].callRemote(\"pushObjectOthers\",cmd,buf,exclude_list); return def dispose(self): super(chat_main,self).dispose();", "data = ud[2]; buf = netutil.s2c_data2bufbycmd(cmd,data); GlobalObject().remote['gate'].callRemote(\"pushObject\",cmd,buf, [dId]) return def _float_msg(self,cId,msg): c_data =", "as lang_config import app.chat.memmode as memmode from firefly.server.globalobject import GlobalObject import app.core.game_module_def as", "_float_msg(self,cId,msg): c_data = {}; c_data['msg'] = msg; self.fire_event(EVENT_SEND2CLIENTBYCID,[S2C_NOTIFY_FLOAT,cId,c_data]); return; def _is_cId_valid(self,cId):#其实就是角色是否在线的判定 return self.character_map.has_key(cId);", "msg; self.fire_event(EVENT_SEND2CLIENTBYCID,[S2C_NOTIFY_FLOAT,cId,c_data]); return; def _is_cId_valid(self,cId):#其实就是角色是否在线的判定 return self.character_map.has_key(cId); def on_relogin(self,ud): dId = ud[\"dId\"]; cId", "c_data = memmode.tb_character_admin.getObj(cId); if not c_data: log.msg('chat_main on_chat fatal err %d'%(cId)); return c_info", "import app.chat.memmode as memmode from firefly.server.globalobject import GlobalObject import app.core.game_module_def as game_module_def class", "self._getdidbycid(cId); if dId == None: log.err(\"_send2clientbycid err:%s %s\"%(cId,ud)); return data = ud[2]; buf", "data = ud[2]; buf = netutil.s2c_data2bufbycmd(cmd,data); GlobalObject().remote['gate'].callRemote(\"pushObject\",cmd,buf, [dId]) return def _send2client(self,ud): cmd =", "start(self): super(chat_main,self).start(); self.register_event(EVENT_LOGIN,self.on_login); self.register_event(EVENT_LOGOUT,self.on_logout); self.register_event(EVENT_RELOGIN,self.on_relogin); self.register_net_event(C2S_CHAT,self.on_chat); self.register_event(EVENT_SEND2CLIENT,self._send2client); self.register_event(EVENT_SEND2CLIENTBYCID,self._send2clientbycid) return def _getdidbycid(self,cId): if self.character_map.has_key(cId):", "if dId == None: log.err(\"_send2clientbycid err:%s %s\"%(cId,ud)); return data = ud[2]; buf =", "memmode.tb_character_admin.getObj(cId); if not c_data: log.msg('chat_main on_chat fatal err %d'%(cId)); return c_info = c_data.get('data');", "ud[0] cId = ud[1]; dId = self._getdidbycid(cId); if dId == None: log.err(\"_send2clientbycid err:%s", "data['srvid'] = 0; data['pid'] = cId; data['shape'] = c_info[\"figure\"]; data['vip'] = 0; data['name']", "ud[1]; data = ud[2]; buf = netutil.s2c_data2bufbycmd(cmd,data); GlobalObject().remote['gate'].callRemote(\"pushObject\",cmd,buf, [dId]) return def _float_msg(self,cId,msg): c_data", "#todo print \"on_chat %d %s\"%(cId,msg); c_data = memmode.tb_character_admin.getObj(cId); if not c_data: log.msg('chat_main on_chat", "msg = data[\"msg\"]; #todo print \"on_chat %d %s\"%(cId,msg); c_data = memmode.tb_character_admin.getObj(cId); if not", "{}; data['ch'] = ch; data['srvid'] = 0; data['pid'] = cId; data['shape'] = c_info[\"figure\"];", "import log import app.util.helper as helper import app.util.lang_config as lang_config import app.chat.memmode as", "data = ud[\"data\"]; ch = data[\"ch\"]; msg = data[\"msg\"]; #todo print \"on_chat %d", "# coding: utf-8 # import app.base.game_module_mgr from app.core.game_event_def import * from app.protocol.ProtocolDesc import", "* import app.protocol.netutil as netutil from twisted.python import log import app.util.helper as helper", "self.character_map.has_key(cId); def on_relogin(self,ud): dId = ud[\"dId\"]; cId = ud[\"cId\"]; if self.character_map.has_key(cId): self.character_map[cId] =", "= ud[1]; data = ud[2]; buf = netutil.s2c_data2bufbycmd(cmd,data); GlobalObject().remote['gate'].callRemote(\"pushObject\",cmd,buf, [dId]) return def _float_msg(self,cId,msg):", "print \"on_chat %d %s\"%(cId,msg); c_data = memmode.tb_character_admin.getObj(cId); if not c_data: log.msg('chat_main on_chat fatal", "ud[0] dId = ud[1]; data = ud[2]; buf = netutil.s2c_data2bufbycmd(cmd,data); GlobalObject().remote['gate'].callRemote(\"pushObject\",cmd,buf, [dId]) return", "ud[\"dId\"]; cId = ud[\"cId\"]; if self.character_map.has_key(cId): self.character_map[cId] = dId; return def on_login(self,ud): dId", "dId = self._getdidbycid(cId); if dId == None: log.err(\"_send2clientbycid err:%s %s\"%(cId,ud)); return data =", "ud[\"cId\"]; if self.character_map.has_key(cId): del self.character_map[cId]; return def on_chat(self,ud): dId = ud[\"dId\"]; cId =", "= memmode.tb_character_admin.getObj(cId); if not c_data: log.msg('chat_main on_chat fatal err %d'%(cId)); return c_info =", "log.err(\"_send2clientbycid err:%s %s\"%(cId,ud)); return data = ud[2]; buf = netutil.s2c_data2bufbycmd(cmd,data); GlobalObject().remote['gate'].callRemote(\"pushObject\",cmd,buf, [dId]) return", "= netutil.s2c_data2bufbycmd(cmd,data); GlobalObject().remote['gate'].callRemote(\"pushObject\",cmd,buf, [dId]) return def _float_msg(self,cId,msg): c_data = {}; c_data['msg'] = msg;", "data = {}; data['ch'] = ch; data['srvid'] = 0; data['pid'] = cId; data['shape']", "c_info = c_data.get('data'); return def on_logout(self,ud): dId = ud[\"dId\"]; cId = ud[\"cId\"]; if", "c_data = {}; c_data['msg'] = msg; self.fire_event(EVENT_SEND2CLIENTBYCID,[S2C_NOTIFY_FLOAT,cId,c_data]); return; def _is_cId_valid(self,cId):#其实就是角色是否在线的判定 return self.character_map.has_key(cId); def", "ud[\"dId\"]; cId = ud[\"cId\"]; if self.character_map.has_key(cId): del self.character_map[cId]; return def on_chat(self,ud): dId =", "= ud[\"cId\"]; data = ud[\"data\"]; ch = data[\"ch\"]; msg = data[\"msg\"]; #todo print", "_is_cId_valid(self,cId):#其实就是角色是否在线的判定 return self.character_map.has_key(cId); def on_relogin(self,ud): dId = ud[\"dId\"]; cId = ud[\"cId\"]; if self.character_map.has_key(cId):", "= dId; return def on_login(self,ud): dId = ud[\"dId\"]; cId = ud[\"cId\"]; self.character_map[cId] =", "return def _send2client(self,ud): cmd = ud[0] dId = ud[1]; data = ud[2]; buf", "app.util.helper as helper import app.util.lang_config as lang_config import app.chat.memmode as memmode from firefly.server.globalobject", "app.chat.memmode as memmode from firefly.server.globalobject import GlobalObject import app.core.game_module_def as game_module_def class chat_main(app.base.game_module_mgr.game_module):", "= netutil.s2c_data2bufbycmd(cmd,data); GlobalObject().remote['gate'].callRemote(\"pushObject\",cmd,buf, [dId]) return def _send2client(self,ud): cmd = ud[0] dId = ud[1];", "c_info = c_data.get('data'); data = {}; data['ch'] = ch; data['srvid'] = 0; data['pid']", "return def on_chat(self,ud): dId = ud[\"dId\"]; cId = ud[\"cId\"]; data = ud[\"data\"]; ch", "%d %s\"%(cId,msg); c_data = memmode.tb_character_admin.getObj(cId); if not c_data: log.msg('chat_main on_chat fatal err %d'%(cId));", "c_info[\"figure\"]; data['vip'] = 0; data['name'] = c_info[\"nickname\"]; data['msg'] = msg; cmd = S2C_CHAT;", "self.register_net_event(C2S_CHAT,self.on_chat); self.register_event(EVENT_SEND2CLIENT,self._send2client); self.register_event(EVENT_SEND2CLIENTBYCID,self._send2clientbycid) return def _getdidbycid(self,cId): if self.character_map.has_key(cId): return self.character_map[cId]; return def _send2clientbycid(self,ud):", "GlobalObject().remote['gate'].callRemote(\"pushObject\",cmd,buf, [dId]) return def _send2client(self,ud): cmd = ud[0] dId = ud[1]; data =", "game_module_def class chat_main(app.base.game_module_mgr.game_module): def __init__(self): super(chat_main,self).__init__(); self.character_map = {}; return def start(self): super(chat_main,self).start();", "err %d'%(cId)); return c_info = c_data.get('data'); return def on_logout(self,ud): dId = ud[\"dId\"]; cId", "= ud[\"dId\"]; cId = ud[\"cId\"]; self.character_map[cId] = dId; c_data = memmode.tb_character_admin.getObj(cId); if not", "= data[\"ch\"]; msg = data[\"msg\"]; #todo print \"on_chat %d %s\"%(cId,msg); c_data = memmode.tb_character_admin.getObj(cId);", "not c_data: log.msg('chat_main on_login fatal err %d'%(cId)); return c_info = c_data.get('data'); return def", "[dId]) return def _float_msg(self,cId,msg): c_data = {}; c_data['msg'] = msg; self.fire_event(EVENT_SEND2CLIENTBYCID,[S2C_NOTIFY_FLOAT,cId,c_data]); return; def", "buf = netutil.s2c_data2bufbycmd(cmd,data); GlobalObject().remote['gate'].callRemote(\"pushObject\",cmd,buf, [dId]) return def _float_msg(self,cId,msg): c_data = {}; c_data['msg'] =", "c_info[\"nickname\"]; data['msg'] = msg; cmd = S2C_CHAT; buf = netutil.s2c_data2bufbycmd(cmd,data); exclude_list = [];", "dId == None: log.err(\"_send2clientbycid err:%s %s\"%(cId,ud)); return data = ud[2]; buf = netutil.s2c_data2bufbycmd(cmd,data);", "== None: log.err(\"_send2clientbycid err:%s %s\"%(cId,ud)); return data = ud[2]; buf = netutil.s2c_data2bufbycmd(cmd,data); GlobalObject().remote['gate'].callRemote(\"pushObject\",cmd,buf,", "= dId; c_data = memmode.tb_character_admin.getObj(cId); if not c_data: log.msg('chat_main on_login fatal err %d'%(cId));", "not c_data: log.msg('chat_main on_chat fatal err %d'%(cId)); return c_info = c_data.get('data'); data =", "app.base.game_module_mgr from app.core.game_event_def import * from app.protocol.ProtocolDesc import * import app.protocol.netutil as netutil", "= ud[\"dId\"]; cId = ud[\"cId\"]; if self.character_map.has_key(cId): self.character_map[cId] = dId; return def on_login(self,ud):", "cmd = S2C_CHAT; buf = netutil.s2c_data2bufbycmd(cmd,data); exclude_list = []; GlobalObject().remote['gate'].callRemote(\"pushObjectOthers\",cmd,buf,exclude_list); return def dispose(self):", "def _send2client(self,ud): cmd = ud[0] dId = ud[1]; data = ud[2]; buf =", "self.character_map[cId]; return def _send2clientbycid(self,ud): cmd = ud[0] cId = ud[1]; dId = self._getdidbycid(cId);", "dId; c_data = memmode.tb_character_admin.getObj(cId); if not c_data: log.msg('chat_main on_login fatal err %d'%(cId)); return", "from app.core.game_event_def import * from app.protocol.ProtocolDesc import * import app.protocol.netutil as netutil from", "def on_relogin(self,ud): dId = ud[\"dId\"]; cId = ud[\"cId\"]; if self.character_map.has_key(cId): self.character_map[cId] = dId;", "= ud[\"cId\"]; if self.character_map.has_key(cId): del self.character_map[cId]; return def on_chat(self,ud): dId = ud[\"dId\"]; cId", "dId = ud[1]; data = ud[2]; buf = netutil.s2c_data2bufbycmd(cmd,data); GlobalObject().remote['gate'].callRemote(\"pushObject\",cmd,buf, [dId]) return def", "memmode from firefly.server.globalobject import GlobalObject import app.core.game_module_def as game_module_def class chat_main(app.base.game_module_mgr.game_module): def __init__(self):", "%d'%(cId)); return c_info = c_data.get('data'); return def on_logout(self,ud): dId = ud[\"dId\"]; cId =", "S2C_CHAT; buf = netutil.s2c_data2bufbycmd(cmd,data); exclude_list = []; GlobalObject().remote['gate'].callRemote(\"pushObjectOthers\",cmd,buf,exclude_list); return def dispose(self): super(chat_main,self).dispose(); return", "= memmode.tb_character_admin.getObj(cId); if not c_data: log.msg('chat_main on_login fatal err %d'%(cId)); return c_info =", "= c_info[\"figure\"]; data['vip'] = 0; data['name'] = c_info[\"nickname\"]; data['msg'] = msg; cmd =", "c_data.get('data'); return def on_logout(self,ud): dId = ud[\"dId\"]; cId = ud[\"cId\"]; if self.character_map.has_key(cId): del", "= data[\"msg\"]; #todo print \"on_chat %d %s\"%(cId,msg); c_data = memmode.tb_character_admin.getObj(cId); if not c_data:", "import app.util.helper as helper import app.util.lang_config as lang_config import app.chat.memmode as memmode from", "app.protocol.netutil as netutil from twisted.python import log import app.util.helper as helper import app.util.lang_config", "= ud[2]; buf = netutil.s2c_data2bufbycmd(cmd,data); GlobalObject().remote['gate'].callRemote(\"pushObject\",cmd,buf, [dId]) return def _float_msg(self,cId,msg): c_data = {};", "log import app.util.helper as helper import app.util.lang_config as lang_config import app.chat.memmode as memmode", "= c_data.get('data'); data = {}; data['ch'] = ch; data['srvid'] = 0; data['pid'] =", "self.character_map[cId] = dId; return def on_login(self,ud): dId = ud[\"dId\"]; cId = ud[\"cId\"]; self.character_map[cId]", "ud[1]; dId = self._getdidbycid(cId); if dId == None: log.err(\"_send2clientbycid err:%s %s\"%(cId,ud)); return data", "del self.character_map[cId]; return def on_chat(self,ud): dId = ud[\"dId\"]; cId = ud[\"cId\"]; data =", "from app.protocol.ProtocolDesc import * import app.protocol.netutil as netutil from twisted.python import log import", "ud[\"cId\"]; data = ud[\"data\"]; ch = data[\"ch\"]; msg = data[\"msg\"]; #todo print \"on_chat", "import * from app.protocol.ProtocolDesc import * import app.protocol.netutil as netutil from twisted.python import", "None: log.err(\"_send2clientbycid err:%s %s\"%(cId,ud)); return data = ud[2]; buf = netutil.s2c_data2bufbycmd(cmd,data); GlobalObject().remote['gate'].callRemote(\"pushObject\",cmd,buf, [dId])", "def _is_cId_valid(self,cId):#其实就是角色是否在线的判定 return self.character_map.has_key(cId); def on_relogin(self,ud): dId = ud[\"dId\"]; cId = ud[\"cId\"]; if", "%s\"%(cId,ud)); return data = ud[2]; buf = netutil.s2c_data2bufbycmd(cmd,data); GlobalObject().remote['gate'].callRemote(\"pushObject\",cmd,buf, [dId]) return def _send2client(self,ud):", "ch = data[\"ch\"]; msg = data[\"msg\"]; #todo print \"on_chat %d %s\"%(cId,msg); c_data =", "%s\"%(cId,msg); c_data = memmode.tb_character_admin.getObj(cId); if not c_data: log.msg('chat_main on_chat fatal err %d'%(cId)); return", "cmd = ud[0] dId = ud[1]; data = ud[2]; buf = netutil.s2c_data2bufbycmd(cmd,data); GlobalObject().remote['gate'].callRemote(\"pushObject\",cmd,buf,", "return def _float_msg(self,cId,msg): c_data = {}; c_data['msg'] = msg; self.fire_event(EVENT_SEND2CLIENTBYCID,[S2C_NOTIFY_FLOAT,cId,c_data]); return; def _is_cId_valid(self,cId):#其实就是角色是否在线的判定", "c_data: log.msg('chat_main on_chat fatal err %d'%(cId)); return c_info = c_data.get('data'); data = {};", "self.register_event(EVENT_RELOGIN,self.on_relogin); self.register_net_event(C2S_CHAT,self.on_chat); self.register_event(EVENT_SEND2CLIENT,self._send2client); self.register_event(EVENT_SEND2CLIENTBYCID,self._send2clientbycid) return def _getdidbycid(self,cId): if self.character_map.has_key(cId): return self.character_map[cId]; return def", "netutil from twisted.python import log import app.util.helper as helper import app.util.lang_config as lang_config", "ud[2]; buf = netutil.s2c_data2bufbycmd(cmd,data); GlobalObject().remote['gate'].callRemote(\"pushObject\",cmd,buf, [dId]) return def _float_msg(self,cId,msg): c_data = {}; c_data['msg']", "data[\"msg\"]; #todo print \"on_chat %d %s\"%(cId,msg); c_data = memmode.tb_character_admin.getObj(cId); if not c_data: log.msg('chat_main", "{}; c_data['msg'] = msg; self.fire_event(EVENT_SEND2CLIENTBYCID,[S2C_NOTIFY_FLOAT,cId,c_data]); return; def _is_cId_valid(self,cId):#其实就是角色是否在线的判定 return self.character_map.has_key(cId); def on_relogin(self,ud): dId", "= msg; self.fire_event(EVENT_SEND2CLIENTBYCID,[S2C_NOTIFY_FLOAT,cId,c_data]); return; def _is_cId_valid(self,cId):#其实就是角色是否在线的判定 return self.character_map.has_key(cId); def on_relogin(self,ud): dId = ud[\"dId\"];", "import app.protocol.netutil as netutil from twisted.python import log import app.util.helper as helper import", "dId; return def on_login(self,ud): dId = ud[\"dId\"]; cId = ud[\"cId\"]; self.character_map[cId] = dId;", "msg; cmd = S2C_CHAT; buf = netutil.s2c_data2bufbycmd(cmd,data); exclude_list = []; GlobalObject().remote['gate'].callRemote(\"pushObjectOthers\",cmd,buf,exclude_list); return def", "on_chat(self,ud): dId = ud[\"dId\"]; cId = ud[\"cId\"]; data = ud[\"data\"]; ch = data[\"ch\"];", "cId = ud[\"cId\"]; self.character_map[cId] = dId; c_data = memmode.tb_character_admin.getObj(cId); if not c_data: log.msg('chat_main", "cId; data['shape'] = c_info[\"figure\"]; data['vip'] = 0; data['name'] = c_info[\"nickname\"]; data['msg'] = msg;", "fatal err %d'%(cId)); return c_info = c_data.get('data'); data = {}; data['ch'] = ch;", "import * import app.protocol.netutil as netutil from twisted.python import log import app.util.helper as", "data['name'] = c_info[\"nickname\"]; data['msg'] = msg; cmd = S2C_CHAT; buf = netutil.s2c_data2bufbycmd(cmd,data); exclude_list", "return def start(self): super(chat_main,self).start(); self.register_event(EVENT_LOGIN,self.on_login); self.register_event(EVENT_LOGOUT,self.on_logout); self.register_event(EVENT_RELOGIN,self.on_relogin); self.register_net_event(C2S_CHAT,self.on_chat); self.register_event(EVENT_SEND2CLIENT,self._send2client); self.register_event(EVENT_SEND2CLIENTBYCID,self._send2clientbycid) return def _getdidbycid(self,cId):", "import app.util.lang_config as lang_config import app.chat.memmode as memmode from firefly.server.globalobject import GlobalObject import", "self.register_event(EVENT_SEND2CLIENT,self._send2client); self.register_event(EVENT_SEND2CLIENTBYCID,self._send2clientbycid) return def _getdidbycid(self,cId): if self.character_map.has_key(cId): return self.character_map[cId]; return def _send2clientbycid(self,ud): cmd", "return self.character_map[cId]; return def _send2clientbycid(self,ud): cmd = ud[0] cId = ud[1]; dId =", "<gh_stars>0 # coding: utf-8 # import app.base.game_module_mgr from app.core.game_event_def import * from app.protocol.ProtocolDesc", "cmd = ud[0] cId = ud[1]; dId = self._getdidbycid(cId); if dId == None:", "on_login fatal err %d'%(cId)); return c_info = c_data.get('data'); return def on_logout(self,ud): dId =", "cId = ud[1]; dId = self._getdidbycid(cId); if dId == None: log.err(\"_send2clientbycid err:%s %s\"%(cId,ud));", "ud[\"dId\"]; cId = ud[\"cId\"]; data = ud[\"data\"]; ch = data[\"ch\"]; msg = data[\"msg\"];", "= ud[0] dId = ud[1]; data = ud[2]; buf = netutil.s2c_data2bufbycmd(cmd,data); GlobalObject().remote['gate'].callRemote(\"pushObject\",cmd,buf, [dId])", "netutil.s2c_data2bufbycmd(cmd,data); GlobalObject().remote['gate'].callRemote(\"pushObject\",cmd,buf, [dId]) return def _float_msg(self,cId,msg): c_data = {}; c_data['msg'] = msg; self.fire_event(EVENT_SEND2CLIENTBYCID,[S2C_NOTIFY_FLOAT,cId,c_data]);", "return def _getdidbycid(self,cId): if self.character_map.has_key(cId): return self.character_map[cId]; return def _send2clientbycid(self,ud): cmd = ud[0]", "= {}; data['ch'] = ch; data['srvid'] = 0; data['pid'] = cId; data['shape'] =", "if not c_data: log.msg('chat_main on_login fatal err %d'%(cId)); return c_info = c_data.get('data'); return", "self.fire_event(EVENT_SEND2CLIENTBYCID,[S2C_NOTIFY_FLOAT,cId,c_data]); return; def _is_cId_valid(self,cId):#其实就是角色是否在线的判定 return self.character_map.has_key(cId); def on_relogin(self,ud): dId = ud[\"dId\"]; cId =", "= self._getdidbycid(cId); if dId == None: log.err(\"_send2clientbycid err:%s %s\"%(cId,ud)); return data = ud[2];", "__init__(self): super(chat_main,self).__init__(); self.character_map = {}; return def start(self): super(chat_main,self).start(); self.register_event(EVENT_LOGIN,self.on_login); self.register_event(EVENT_LOGOUT,self.on_logout); self.register_event(EVENT_RELOGIN,self.on_relogin); self.register_net_event(C2S_CHAT,self.on_chat);", "return data = ud[2]; buf = netutil.s2c_data2bufbycmd(cmd,data); GlobalObject().remote['gate'].callRemote(\"pushObject\",cmd,buf, [dId]) return def _send2client(self,ud): cmd", "ud[\"cId\"]; self.character_map[cId] = dId; c_data = memmode.tb_character_admin.getObj(cId); if not c_data: log.msg('chat_main on_login fatal", "= c_data.get('data'); return def on_logout(self,ud): dId = ud[\"dId\"]; cId = ud[\"cId\"]; if self.character_map.has_key(cId):", "data[\"ch\"]; msg = data[\"msg\"]; #todo print \"on_chat %d %s\"%(cId,msg); c_data = memmode.tb_character_admin.getObj(cId); if", "{}; return def start(self): super(chat_main,self).start(); self.register_event(EVENT_LOGIN,self.on_login); self.register_event(EVENT_LOGOUT,self.on_logout); self.register_event(EVENT_RELOGIN,self.on_relogin); self.register_net_event(C2S_CHAT,self.on_chat); self.register_event(EVENT_SEND2CLIENT,self._send2client); self.register_event(EVENT_SEND2CLIENTBYCID,self._send2clientbycid) return def", "as memmode from firefly.server.globalobject import GlobalObject import app.core.game_module_def as game_module_def class chat_main(app.base.game_module_mgr.game_module): def", "as game_module_def class chat_main(app.base.game_module_mgr.game_module): def __init__(self): super(chat_main,self).__init__(); self.character_map = {}; return def start(self):", "super(chat_main,self).__init__(); self.character_map = {}; return def start(self): super(chat_main,self).start(); self.register_event(EVENT_LOGIN,self.on_login); self.register_event(EVENT_LOGOUT,self.on_logout); self.register_event(EVENT_RELOGIN,self.on_relogin); self.register_net_event(C2S_CHAT,self.on_chat); self.register_event(EVENT_SEND2CLIENT,self._send2client);", "coding: utf-8 # import app.base.game_module_mgr from app.core.game_event_def import * from app.protocol.ProtocolDesc import *", "= ud[2]; buf = netutil.s2c_data2bufbycmd(cmd,data); GlobalObject().remote['gate'].callRemote(\"pushObject\",cmd,buf, [dId]) return def _send2client(self,ud): cmd = ud[0]", "self.character_map[cId]; return def on_chat(self,ud): dId = ud[\"dId\"]; cId = ud[\"cId\"]; data = ud[\"data\"];", "= msg; cmd = S2C_CHAT; buf = netutil.s2c_data2bufbycmd(cmd,data); exclude_list = []; GlobalObject().remote['gate'].callRemote(\"pushObjectOthers\",cmd,buf,exclude_list); return", "# import app.base.game_module_mgr from app.core.game_event_def import * from app.protocol.ProtocolDesc import * import app.protocol.netutil", "= {}; c_data['msg'] = msg; self.fire_event(EVENT_SEND2CLIENTBYCID,[S2C_NOTIFY_FLOAT,cId,c_data]); return; def _is_cId_valid(self,cId):#其实就是角色是否在线的判定 return self.character_map.has_key(cId); def on_relogin(self,ud):", "= {}; return def start(self): super(chat_main,self).start(); self.register_event(EVENT_LOGIN,self.on_login); self.register_event(EVENT_LOGOUT,self.on_logout); self.register_event(EVENT_RELOGIN,self.on_relogin); self.register_net_event(C2S_CHAT,self.on_chat); self.register_event(EVENT_SEND2CLIENT,self._send2client); self.register_event(EVENT_SEND2CLIENTBYCID,self._send2clientbycid) return", "c_data.get('data'); data = {}; data['ch'] = ch; data['srvid'] = 0; data['pid'] = cId;", "def _send2clientbycid(self,ud): cmd = ud[0] cId = ud[1]; dId = self._getdidbycid(cId); if dId", "ud[2]; buf = netutil.s2c_data2bufbycmd(cmd,data); GlobalObject().remote['gate'].callRemote(\"pushObject\",cmd,buf, [dId]) return def _send2client(self,ud): cmd = ud[0] dId", "netutil.s2c_data2bufbycmd(cmd,data); GlobalObject().remote['gate'].callRemote(\"pushObject\",cmd,buf, [dId]) return def _send2client(self,ud): cmd = ud[0] dId = ud[1]; data", "return c_info = c_data.get('data'); return def on_logout(self,ud): dId = ud[\"dId\"]; cId = ud[\"cId\"];", "\"on_chat %d %s\"%(cId,msg); c_data = memmode.tb_character_admin.getObj(cId); if not c_data: log.msg('chat_main on_chat fatal err", "0; data['name'] = c_info[\"nickname\"]; data['msg'] = msg; cmd = S2C_CHAT; buf = netutil.s2c_data2bufbycmd(cmd,data);", "from firefly.server.globalobject import GlobalObject import app.core.game_module_def as game_module_def class chat_main(app.base.game_module_mgr.game_module): def __init__(self): super(chat_main,self).__init__();", "dId = ud[\"dId\"]; cId = ud[\"cId\"]; data = ud[\"data\"]; ch = data[\"ch\"]; msg", "= ud[\"data\"]; ch = data[\"ch\"]; msg = data[\"msg\"]; #todo print \"on_chat %d %s\"%(cId,msg);", "= cId; data['shape'] = c_info[\"figure\"]; data['vip'] = 0; data['name'] = c_info[\"nickname\"]; data['msg'] =", "= ud[\"cId\"]; self.character_map[cId] = dId; c_data = memmode.tb_character_admin.getObj(cId); if not c_data: log.msg('chat_main on_login", "data['vip'] = 0; data['name'] = c_info[\"nickname\"]; data['msg'] = msg; cmd = S2C_CHAT; buf", "= ud[\"cId\"]; if self.character_map.has_key(cId): self.character_map[cId] = dId; return def on_login(self,ud): dId = ud[\"dId\"];", "dId = ud[\"dId\"]; cId = ud[\"cId\"]; if self.character_map.has_key(cId): del self.character_map[cId]; return def on_chat(self,ud):", "def on_logout(self,ud): dId = ud[\"dId\"]; cId = ud[\"cId\"]; if self.character_map.has_key(cId): del self.character_map[cId]; return", "memmode.tb_character_admin.getObj(cId); if not c_data: log.msg('chat_main on_login fatal err %d'%(cId)); return c_info = c_data.get('data');", "_send2client(self,ud): cmd = ud[0] dId = ud[1]; data = ud[2]; buf = netutil.s2c_data2bufbycmd(cmd,data);", "self.register_event(EVENT_LOGIN,self.on_login); self.register_event(EVENT_LOGOUT,self.on_logout); self.register_event(EVENT_RELOGIN,self.on_relogin); self.register_net_event(C2S_CHAT,self.on_chat); self.register_event(EVENT_SEND2CLIENT,self._send2client); self.register_event(EVENT_SEND2CLIENTBYCID,self._send2clientbycid) return def _getdidbycid(self,cId): if self.character_map.has_key(cId): return self.character_map[cId];", "def __init__(self): super(chat_main,self).__init__(); self.character_map = {}; return def start(self): super(chat_main,self).start(); self.register_event(EVENT_LOGIN,self.on_login); self.register_event(EVENT_LOGOUT,self.on_logout); self.register_event(EVENT_RELOGIN,self.on_relogin);", "data['msg'] = msg; cmd = S2C_CHAT; buf = netutil.s2c_data2bufbycmd(cmd,data); exclude_list = []; GlobalObject().remote['gate'].callRemote(\"pushObjectOthers\",cmd,buf,exclude_list);", "GlobalObject import app.core.game_module_def as game_module_def class chat_main(app.base.game_module_mgr.game_module): def __init__(self): super(chat_main,self).__init__(); self.character_map = {};", "c_data = memmode.tb_character_admin.getObj(cId); if not c_data: log.msg('chat_main on_login fatal err %d'%(cId)); return c_info", "ud[\"data\"]; ch = data[\"ch\"]; msg = data[\"msg\"]; #todo print \"on_chat %d %s\"%(cId,msg); c_data", "cId = ud[\"cId\"]; data = ud[\"data\"]; ch = data[\"ch\"]; msg = data[\"msg\"]; #todo", "import app.base.game_module_mgr from app.core.game_event_def import * from app.protocol.ProtocolDesc import * import app.protocol.netutil as", "return def _send2clientbycid(self,ud): cmd = ud[0] cId = ud[1]; dId = self._getdidbycid(cId); if", "= ud[1]; dId = self._getdidbycid(cId); if dId == None: log.err(\"_send2clientbycid err:%s %s\"%(cId,ud)); return", "on_login(self,ud): dId = ud[\"dId\"]; cId = ud[\"cId\"]; self.character_map[cId] = dId; c_data = memmode.tb_character_admin.getObj(cId);", "c_data: log.msg('chat_main on_login fatal err %d'%(cId)); return c_info = c_data.get('data'); return def on_logout(self,ud):", "log.msg('chat_main on_chat fatal err %d'%(cId)); return c_info = c_data.get('data'); data = {}; data['ch']", "app.core.game_module_def as game_module_def class chat_main(app.base.game_module_mgr.game_module): def __init__(self): super(chat_main,self).__init__(); self.character_map = {}; return def", "twisted.python import log import app.util.helper as helper import app.util.lang_config as lang_config import app.chat.memmode", "return; def _is_cId_valid(self,cId):#其实就是角色是否在线的判定 return self.character_map.has_key(cId); def on_relogin(self,ud): dId = ud[\"dId\"]; cId = ud[\"cId\"];", "return def on_logout(self,ud): dId = ud[\"dId\"]; cId = ud[\"cId\"]; if self.character_map.has_key(cId): del self.character_map[cId];", "_send2clientbycid(self,ud): cmd = ud[0] cId = ud[1]; dId = self._getdidbycid(cId); if dId ==", "def _float_msg(self,cId,msg): c_data = {}; c_data['msg'] = msg; self.fire_event(EVENT_SEND2CLIENTBYCID,[S2C_NOTIFY_FLOAT,cId,c_data]); return; def _is_cId_valid(self,cId):#其实就是角色是否在线的判定 return", "chat_main(app.base.game_module_mgr.game_module): def __init__(self): super(chat_main,self).__init__(); self.character_map = {}; return def start(self): super(chat_main,self).start(); self.register_event(EVENT_LOGIN,self.on_login); self.register_event(EVENT_LOGOUT,self.on_logout);", "self.character_map.has_key(cId): self.character_map[cId] = dId; return def on_login(self,ud): dId = ud[\"dId\"]; cId = ud[\"cId\"];", "class chat_main(app.base.game_module_mgr.game_module): def __init__(self): super(chat_main,self).__init__(); self.character_map = {}; return def start(self): super(chat_main,self).start(); self.register_event(EVENT_LOGIN,self.on_login);", "err:%s %s\"%(cId,ud)); return data = ud[2]; buf = netutil.s2c_data2bufbycmd(cmd,data); GlobalObject().remote['gate'].callRemote(\"pushObject\",cmd,buf, [dId]) return def", "%d'%(cId)); return c_info = c_data.get('data'); data = {}; data['ch'] = ch; data['srvid'] =", "= 0; data['pid'] = cId; data['shape'] = c_info[\"figure\"]; data['vip'] = 0; data['name'] =", "lang_config import app.chat.memmode as memmode from firefly.server.globalobject import GlobalObject import app.core.game_module_def as game_module_def", "return def on_login(self,ud): dId = ud[\"dId\"]; cId = ud[\"cId\"]; self.character_map[cId] = dId; c_data", "ud[\"dId\"]; cId = ud[\"cId\"]; self.character_map[cId] = dId; c_data = memmode.tb_character_admin.getObj(cId); if not c_data:", "= ch; data['srvid'] = 0; data['pid'] = cId; data['shape'] = c_info[\"figure\"]; data['vip'] =", "data['shape'] = c_info[\"figure\"]; data['vip'] = 0; data['name'] = c_info[\"nickname\"]; data['msg'] = msg; cmd", "= ud[\"dId\"]; cId = ud[\"cId\"]; data = ud[\"data\"]; ch = data[\"ch\"]; msg =", "buf = netutil.s2c_data2bufbycmd(cmd,data); GlobalObject().remote['gate'].callRemote(\"pushObject\",cmd,buf, [dId]) return def _send2client(self,ud): cmd = ud[0] dId =", "self.character_map[cId] = dId; c_data = memmode.tb_character_admin.getObj(cId); if not c_data: log.msg('chat_main on_login fatal err", "err %d'%(cId)); return c_info = c_data.get('data'); data = {}; data['ch'] = ch; data['srvid']", "self.character_map.has_key(cId): return self.character_map[cId]; return def _send2clientbycid(self,ud): cmd = ud[0] cId = ud[1]; dId", "def _getdidbycid(self,cId): if self.character_map.has_key(cId): return self.character_map[cId]; return def _send2clientbycid(self,ud): cmd = ud[0] cId", "super(chat_main,self).start(); self.register_event(EVENT_LOGIN,self.on_login); self.register_event(EVENT_LOGOUT,self.on_logout); self.register_event(EVENT_RELOGIN,self.on_relogin); self.register_net_event(C2S_CHAT,self.on_chat); self.register_event(EVENT_SEND2CLIENT,self._send2client); self.register_event(EVENT_SEND2CLIENTBYCID,self._send2clientbycid) return def _getdidbycid(self,cId): if self.character_map.has_key(cId): return", "= ud[0] cId = ud[1]; dId = self._getdidbycid(cId); if dId == None: log.err(\"_send2clientbycid", "_getdidbycid(self,cId): if self.character_map.has_key(cId): return self.character_map[cId]; return def _send2clientbycid(self,ud): cmd = ud[0] cId =", "[dId]) return def _send2client(self,ud): cmd = ud[0] dId = ud[1]; data = ud[2];", "on_relogin(self,ud): dId = ud[\"dId\"]; cId = ud[\"cId\"]; if self.character_map.has_key(cId): self.character_map[cId] = dId; return", "def on_chat(self,ud): dId = ud[\"dId\"]; cId = ud[\"cId\"]; data = ud[\"data\"]; ch =", "fatal err %d'%(cId)); return c_info = c_data.get('data'); return def on_logout(self,ud): dId = ud[\"dId\"];", "self.character_map = {}; return def start(self): super(chat_main,self).start(); self.register_event(EVENT_LOGIN,self.on_login); self.register_event(EVENT_LOGOUT,self.on_logout); self.register_event(EVENT_RELOGIN,self.on_relogin); self.register_net_event(C2S_CHAT,self.on_chat); self.register_event(EVENT_SEND2CLIENT,self._send2client); self.register_event(EVENT_SEND2CLIENTBYCID,self._send2clientbycid)", "def start(self): super(chat_main,self).start(); self.register_event(EVENT_LOGIN,self.on_login); self.register_event(EVENT_LOGOUT,self.on_logout); self.register_event(EVENT_RELOGIN,self.on_relogin); self.register_net_event(C2S_CHAT,self.on_chat); self.register_event(EVENT_SEND2CLIENT,self._send2client); self.register_event(EVENT_SEND2CLIENTBYCID,self._send2clientbycid) return def _getdidbycid(self,cId): if", "from twisted.python import log import app.util.helper as helper import app.util.lang_config as lang_config import", "firefly.server.globalobject import GlobalObject import app.core.game_module_def as game_module_def class chat_main(app.base.game_module_mgr.game_module): def __init__(self): super(chat_main,self).__init__(); self.character_map", "as netutil from twisted.python import log import app.util.helper as helper import app.util.lang_config as", "dId = ud[\"dId\"]; cId = ud[\"cId\"]; self.character_map[cId] = dId; c_data = memmode.tb_character_admin.getObj(cId); if", "return c_info = c_data.get('data'); data = {}; data['ch'] = ch; data['srvid'] = 0;", "= c_info[\"nickname\"]; data['msg'] = msg; cmd = S2C_CHAT; buf = netutil.s2c_data2bufbycmd(cmd,data); exclude_list =", "if not c_data: log.msg('chat_main on_chat fatal err %d'%(cId)); return c_info = c_data.get('data'); data", "if self.character_map.has_key(cId): self.character_map[cId] = dId; return def on_login(self,ud): dId = ud[\"dId\"]; cId =", "on_chat fatal err %d'%(cId)); return c_info = c_data.get('data'); data = {}; data['ch'] =", "* from app.protocol.ProtocolDesc import * import app.protocol.netutil as netutil from twisted.python import log", "cId = ud[\"cId\"]; if self.character_map.has_key(cId): del self.character_map[cId]; return def on_chat(self,ud): dId = ud[\"dId\"];", "data['pid'] = cId; data['shape'] = c_info[\"figure\"]; data['vip'] = 0; data['name'] = c_info[\"nickname\"]; data['msg']", "app.core.game_event_def import * from app.protocol.ProtocolDesc import * import app.protocol.netutil as netutil from twisted.python", "import GlobalObject import app.core.game_module_def as game_module_def class chat_main(app.base.game_module_mgr.game_module): def __init__(self): super(chat_main,self).__init__(); self.character_map =" ]
[ "== end - 1: tokens = sub_tokens else: tokens.extend(sub_tokens[:-tail]) elif i == end", "preds = merge_chunk([\" \".join(x) for x in preds], batch_indices, overlap_size, min_words_cut) else: preds,", "import read_lines from gector.gec_model import GecBERTModel from tqdm import tqdm import re def", "= model.handle_batch(batch) preds = merge_chunk([\" \".join(x) for x in preds], batch_indices, overlap_size, min_words_cut)", "r' \\1', text) result.append(text) return result def main(args): # get all paths model", "output_file, model, batch_size=32, split_chunk=False, chunk_size=32, overlap_size=8, min_words_cut=4 ): test_data = read_lines(input_file) predictions =", "help='number of words at the end the first chunk to be removed during", "the paper.', default=0.0) parser.add_argument('--special_tokens_fix', type=int, help='Whether to fix problem with [CLS], [SEP] tokens", "batch pairs of indices stride = chunk_size - overlap_size result = [] indices", "help='Path to the model file.', default='data/output_vocabulary' # to use pretrained models ) parser.add_argument('--input_file',", "from tqdm import tqdm import re def predict_for_file( input_file, output_file, model, batch_size=32, split_chunk=False,", "tqdm import re def predict_for_file( input_file, output_file, model, batch_size=32, split_chunk=False, chunk_size=32, overlap_size=8, min_words_cut=4", "'xlm-roberta-base'], help='Name of the transformer model.', default='roberta') parser.add_argument('--iteration_count', type=int, help='The number of iterations", "lowercase_tokens=args.lowercase_tokens, model_name=args.transformer_model, special_tokens_fix=args.special_tokens_fix, log=False, confidence=args.additional_confidence, is_ensemble=args.is_ensemble, weigths=args.weights) cnt_corrections = predict_for_file(args.input_file, args.output_file, model, batch_size=args.batch_size,", "of indices stride = chunk_size - overlap_size result = [] indices = []", "x in preds], batch_indices, overlap_size, min_words_cut) else: preds, cnt = model.handle_batch(batch) preds =", "overlap_size) preds, cnt = model.handle_batch(batch) preds = merge_chunk([\" \".join(x) for x in preds],", "x in preds] predictions.extend(preds) cnt_corrections += cnt batch = [] if batch: if", "default=0.0) parser.add_argument('--special_tokens_fix', type=int, help='Whether to fix problem with [CLS], [SEP] tokens tokenization. '", "model.', default=5) parser.add_argument('--additional_confidence', type=float, help='How many probability to add to $KEEP token.', default=0)", "parser.add_argument('--weights', help='Used to calculate weighted average', nargs='+', default=None) parser.add_argument('--split_chunk', action='store_true', help='Whether to use", "sentence length' '(all longer will be truncated)', default=64) parser.add_argument('--min_len', type=int, help='The minimum sentence", "overall corrections: {cnt_corrections}\") if __name__ == '__main__': # read parameters parser = argparse.ArgumentParser()", "'(all longer will be truncated)', default=64) parser.add_argument('--min_len', type=int, help='The minimum sentence length' '(all", "of the transformer model.', default='roberta') parser.add_argument('--iteration_count', type=int, help='The number of iterations of the", "paths model = GecBERTModel(vocab_path=args.vocab_path, model_paths=args.model_path, max_len=args.max_len, min_len=args.min_len, iterations=args.iteration_count, min_error_probability=args.min_error_probability, lowercase_tokens=args.lowercase_tokens, model_name=args.transformer_model, special_tokens_fix=args.special_tokens_fix, log=False,", "indices stride = chunk_size - overlap_size result = [] indices = [] for", "def predict_for_file( input_file, output_file, model, batch_size=32, split_chunk=False, chunk_size=32, overlap_size=8, min_words_cut=4 ): test_data =", "end the first chunk to be removed during merge', default=4) args = parser.parse_args()", "min_words_cut result = [] for (start, end) in indices: tokens = [] for", "stride): result.append(tokens[i: i + chunk_size]) indices.append((start, len(result))) return result, indices def merge_chunk(batch, indices,", "= [\" \".join(x) for x in preds] predictions.extend(preds) cnt_corrections += cnt batch =", "# return batch pairs of indices stride = chunk_size - overlap_size result =", "<= overlap_size: result.append(tokens) for i in range(0, num_token - overlap_size, stride): result.append(tokens[i: i", "to the model file.', nargs='+', required=True) parser.add_argument('--vocab_path', help='Path to the model file.', default='data/output_vocabulary'", "indices def merge_chunk(batch, indices, overlap_size=8, min_words_cut=4): head = overlap_size - min_words_cut tail =", "to use pretrained models ) parser.add_argument('--input_file', help='Path to the evalset file', required=True) parser.add_argument('--output_file',", "default=8) parser.add_argument('--min_words_cut', type=int, help='number of words at the end the first chunk to", "== end - 1: tokens.extend(sub_tokens[head:]) else: tokens.extend(sub_tokens[head:-tail]) except Exception as e: print(e) text", "'albert' 'bert-large', 'roberta-large', 'xlnet-large', 'vinai/phobert-base', 'vinai/phobert-large', 'xlm-roberta-base'], help='Name of the transformer model.', default='roberta')", "\" \".join(tokens) text = re.sub(r'([\\,\\.\\?\\:])', r' \\1', text) result.append(text) return result def main(args):", "is_ensemble=args.is_ensemble, weigths=args.weights) cnt_corrections = predict_for_file(args.input_file, args.output_file, model, batch_size=args.batch_size, split_chunk=args.split_chunk, chunk_size=args.chunk_size, overlap_size=args.overlap_size, min_words_cut=args.min_words_cut) #", "= [] for (start, end) in indices: tokens = [] for i in", "preds, cnt = model.handle_batch(batch) preds = merge_chunk([\" \".join(x) for x in preds], batch_indices,", "num_token <= overlap_size: result.append(tokens) for i in range(0, num_token - overlap_size, stride): result.append(tokens[i:", "minimum sentence length' '(all longer will be returned w/o changes)', default=3) parser.add_argument('--batch_size', type=int,", "of iterations of the model.', default=5) parser.add_argument('--additional_confidence', type=float, help='How many probability to add", "probability to add to $KEEP token.', default=0) parser.add_argument('--min_error_probability', type=float, help='Minimum probability for each", "of the model.', default=5) parser.add_argument('--additional_confidence', type=float, help='How many probability to add to $KEEP", "tokens = [] for i in range(start, end): try: sub_text = batch[i].strip() sub_text", "action='store_true', help='Whether to do ensembling.',) parser.add_argument('--weights', help='Used to calculate weighted average', nargs='+', default=None)", "help='The minimum sentence length' '(all longer will be returned w/o changes)', default=3) parser.add_argument('--batch_size',", "batch_size=32, split_chunk=False, chunk_size=32, overlap_size=8, min_words_cut=4 ): test_data = read_lines(input_file) predictions = [] cnt_corrections", "weighted average', nargs='+', default=None) parser.add_argument('--split_chunk', action='store_true', help='Whether to use chunk merging or not')", "help='The size of hidden unit cell.', default=128) parser.add_argument('--lowercase_tokens', action='store_true', help='Whether to lowercase tokens.',)", "help='Name of the transformer model.', default='roberta') parser.add_argument('--iteration_count', type=int, help='The number of iterations of", "size for chunk merging', default=32) parser.add_argument('--overlap_size', type=int, help='Overlapped words between two continuous chunks',", "'\\n') return cnt_corrections def split_chunks(batch, chunk_size=32, overlap_size=8): # return batch pairs of indices", "many probability to add to $KEEP token.', default=0) parser.add_argument('--min_error_probability', type=float, help='Minimum probability for", "longer will be truncated)', default=64) parser.add_argument('--min_len', type=int, help='The minimum sentence length' '(all longer", "x in preds] predictions.extend(preds) cnt_corrections += cnt with open(output_file, 'w') as f: f.write(\"\\n\".join(predictions)", "- 1: tokens = sub_tokens else: tokens.extend(sub_tokens[:-tail]) elif i == end - 1:", "split_chunks(batch, chunk_size=32, overlap_size=8): # return batch pairs of indices stride = chunk_size -", "type=int, help='Overlapped words between two continuous chunks', default=8) parser.add_argument('--min_words_cut', type=int, help='number of words", "re.sub(r'([\\,\\.\\?\\:])', r' \\1', text) result.append(text) return result def main(args): # get all paths", "= predict_for_file(args.input_file, args.output_file, model, batch_size=args.batch_size, split_chunk=args.split_chunk, chunk_size=args.chunk_size, overlap_size=args.overlap_size, min_words_cut=args.min_words_cut) # evaluate with m2", "= sub_text.split() if i == start: if i == end - 1: tokens", "the model file.', default='data/output_vocabulary' # to use pretrained models ) parser.add_argument('--input_file', help='Path to", "to fix problem with [CLS], [SEP] tokens tokenization. ' 'For reproducing reported results", "'w') as f: f.write(\"\\n\".join(predictions) + '\\n') return cnt_corrections def split_chunks(batch, chunk_size=32, overlap_size=8): #", "[] for tokens in batch: start = len(result) num_token = len(tokens) if num_token", "max_len=args.max_len, min_len=args.min_len, iterations=args.iteration_count, min_error_probability=args.min_error_probability, lowercase_tokens=args.lowercase_tokens, model_name=args.transformer_model, special_tokens_fix=args.special_tokens_fix, log=False, confidence=args.additional_confidence, is_ensemble=args.is_ensemble, weigths=args.weights) cnt_corrections =", "= GecBERTModel(vocab_path=args.vocab_path, model_paths=args.model_path, max_len=args.max_len, min_len=args.min_len, iterations=args.iteration_count, min_error_probability=args.min_error_probability, lowercase_tokens=args.lowercase_tokens, model_name=args.transformer_model, special_tokens_fix=args.special_tokens_fix, log=False, confidence=args.additional_confidence, is_ensemble=args.is_ensemble,", "action='store_true', help='Whether to lowercase tokens.',) parser.add_argument('--transformer_model', choices=['bert', 'gpt2', 'transformerxl', 'xlnet', 'distilbert', 'roberta', 'albert'", "= chunk_size - overlap_size result = [] indices = [] for tokens in", "or not') parser.add_argument('--chunk_size', type=int, help='Chunk size for chunk merging', default=32) parser.add_argument('--overlap_size', type=int, help='Overlapped", "read parameters parser = argparse.ArgumentParser() parser.add_argument('--model_path', help='Path to the model file.', nargs='+', required=True)", "to the output file', required=True) parser.add_argument('--max_len', type=int, help='The max sentence length' '(all longer", "else: preds, cnt = model.handle_batch(batch) preds = [\" \".join(x) for x in preds]", "type=float, help='Minimum probability for each action to apply. ' 'Also, minimum error probability,", "longer will be returned w/o changes)', default=3) parser.add_argument('--batch_size', type=int, help='The size of hidden", "indices, overlap_size=8, min_words_cut=4): head = overlap_size - min_words_cut tail = min_words_cut result =", "changes)', default=3) parser.add_argument('--batch_size', type=int, help='The size of hidden unit cell.', default=128) parser.add_argument('--lowercase_tokens', action='store_true',", "the evalset file', required=True) parser.add_argument('--output_file', help='Path to the output file', required=True) parser.add_argument('--max_len', type=int,", "= len(tokens) if num_token <= overlap_size: result.append(tokens) for i in range(0, num_token -", "corrections: {cnt_corrections}\") if __name__ == '__main__': # read parameters parser = argparse.ArgumentParser() parser.add_argument('--model_path',", "1 for RoBERTa.', default=1) parser.add_argument('--is_ensemble', action='store_true', help='Whether to do ensembling.',) parser.add_argument('--weights', help='Used to", "result def main(args): # get all paths model = GecBERTModel(vocab_path=args.vocab_path, model_paths=args.model_path, max_len=args.max_len, min_len=args.min_len,", "chunks', default=8) parser.add_argument('--min_words_cut', type=int, help='number of words at the end the first chunk", "GecBERTModel from tqdm import tqdm import re def predict_for_file( input_file, output_file, model, batch_size=32,", "not') parser.add_argument('--chunk_size', type=int, help='Chunk size for chunk merging', default=32) parser.add_argument('--overlap_size', type=int, help='Overlapped words", "min_len=args.min_len, iterations=args.iteration_count, min_error_probability=args.min_error_probability, lowercase_tokens=args.lowercase_tokens, model_name=args.transformer_model, special_tokens_fix=args.special_tokens_fix, log=False, confidence=args.additional_confidence, is_ensemble=args.is_ensemble, weigths=args.weights) cnt_corrections = predict_for_file(args.input_file,", "return cnt_corrections def split_chunks(batch, chunk_size=32, overlap_size=8): # return batch pairs of indices stride", "for RoBERTa.', default=1) parser.add_argument('--is_ensemble', action='store_true', help='Whether to do ensembling.',) parser.add_argument('--weights', help='Used to calculate", "[] for (start, end) in indices: tokens = [] for i in range(start,", "merging or not') parser.add_argument('--chunk_size', type=int, help='Chunk size for chunk merging', default=32) parser.add_argument('--overlap_size', type=int,", "model.handle_batch(batch) preds = [\" \".join(x) for x in preds] predictions.extend(preds) cnt_corrections += cnt", "preds] predictions.extend(preds) cnt_corrections += cnt batch = [] if batch: if split_chunk: batch,", "tail = min_words_cut result = [] for (start, end) in indices: tokens =", "= re.sub(r'([\\,\\.\\?\\:])', r' \\1', text) result.append(text) return result def main(args): # get all", "result.append(text) return result def main(args): # get all paths model = GecBERTModel(vocab_path=args.vocab_path, model_paths=args.model_path,", "help='Path to the output file', required=True) parser.add_argument('--max_len', type=int, help='The max sentence length' '(all", "merge_chunk([\" \".join(x) for x in preds], batch_indices, overlap_size, min_words_cut) else: preds, cnt =", "type=int, help='The minimum sentence length' '(all longer will be returned w/o changes)', default=3)", "sent in tqdm(test_data): batch.append(sent.split()) if len(batch) == batch_size: if split_chunk: batch, batch_indices =", "utils.helpers import read_lines from gector.gec_model import GecBERTModel from tqdm import tqdm import re", "type=int, help='The number of iterations of the model.', default=5) parser.add_argument('--additional_confidence', type=float, help='How many", "predict_for_file( input_file, output_file, model, batch_size=32, split_chunk=False, chunk_size=32, overlap_size=8, min_words_cut=4 ): test_data = read_lines(input_file)", "evaluate with m2 or ERRANT print(f\"Produced overall corrections: {cnt_corrections}\") if __name__ == '__main__':", "model, batch_size=32, split_chunk=False, chunk_size=32, overlap_size=8, min_words_cut=4 ): test_data = read_lines(input_file) predictions = []", "= min_words_cut result = [] for (start, end) in indices: tokens = []", "with [CLS], [SEP] tokens tokenization. ' 'For reproducing reported results it should be", "the first chunk to be removed during merge', default=4) args = parser.parse_args() main(args)", "batch_indices, overlap_size, min_words_cut) else: preds, cnt = model.handle_batch(batch) preds = [\" \".join(x) for", "batch: if split_chunk: batch, batch_indices = split_chunks(batch, chunk_size, overlap_size) preds, cnt = model.handle_batch(batch)", "= re.sub(r'([\\.\\,\\?\\:]\\s+)+', r'\\1', sub_text) sub_text = re.sub(r'\\s+([\\.\\,\\?\\:])', r'\\1', sub_text) sub_tokens = sub_text.split() if", "= 0 batch = [] for sent in tqdm(test_data): batch.append(sent.split()) if len(batch) ==", "in tqdm(test_data): batch.append(sent.split()) if len(batch) == batch_size: if split_chunk: batch, batch_indices = split_chunks(batch,", "chunk_size=32, overlap_size=8): # return batch pairs of indices stride = chunk_size - overlap_size", "sub_text = re.sub(r'\\s+([\\.\\,\\?\\:])', r'\\1', sub_text) sub_tokens = sub_text.split() if i == start: if", "model.handle_batch(batch) preds = merge_chunk([\" \".join(x) for x in preds], batch_indices, overlap_size, min_words_cut) else:", "if i == end - 1: tokens = sub_tokens else: tokens.extend(sub_tokens[:-tail]) elif i", "tokens.',) parser.add_argument('--transformer_model', choices=['bert', 'gpt2', 'transformerxl', 'xlnet', 'distilbert', 'roberta', 'albert' 'bert-large', 'roberta-large', 'xlnet-large', 'vinai/phobert-base',", "i in range(start, end): try: sub_text = batch[i].strip() sub_text = re.sub(r'([\\.\\,\\?\\:]\\s+)+', r'\\1', sub_text)", "r'\\1', sub_text) sub_text = re.sub(r'\\s+([\\.\\,\\?\\:])', r'\\1', sub_text) sub_tokens = sub_text.split() if i ==", "range(start, end): try: sub_text = batch[i].strip() sub_text = re.sub(r'([\\.\\,\\?\\:]\\s+)+', r'\\1', sub_text) sub_text =", "'roberta', 'albert' 'bert-large', 'roberta-large', 'xlnet-large', 'vinai/phobert-base', 'vinai/phobert-large', 'xlm-roberta-base'], help='Name of the transformer model.',", "len(tokens) if num_token <= overlap_size: result.append(tokens) for i in range(0, num_token - overlap_size,", "+= cnt batch = [] if batch: if split_chunk: batch, batch_indices = split_chunks(batch,", "parameters parser = argparse.ArgumentParser() parser.add_argument('--model_path', help='Path to the model file.', nargs='+', required=True) parser.add_argument('--vocab_path',", "[SEP] tokens tokenization. ' 'For reproducing reported results it should be 0 for", "default=128) parser.add_argument('--lowercase_tokens', action='store_true', help='Whether to lowercase tokens.',) parser.add_argument('--transformer_model', choices=['bert', 'gpt2', 'transformerxl', 'xlnet', 'distilbert',", "result.append(tokens) for i in range(0, num_token - overlap_size, stride): result.append(tokens[i: i + chunk_size])", "required=True) parser.add_argument('--vocab_path', help='Path to the model file.', default='data/output_vocabulary' # to use pretrained models", "probability, as described in the paper.', default=0.0) parser.add_argument('--special_tokens_fix', type=int, help='Whether to fix problem", "i in range(0, num_token - overlap_size, stride): result.append(tokens[i: i + chunk_size]) indices.append((start, len(result)))", ") parser.add_argument('--input_file', help='Path to the evalset file', required=True) parser.add_argument('--output_file', help='Path to the output", "min_words_cut=4 ): test_data = read_lines(input_file) predictions = [] cnt_corrections = 0 batch =", "try: sub_text = batch[i].strip() sub_text = re.sub(r'([\\.\\,\\?\\:]\\s+)+', r'\\1', sub_text) sub_text = re.sub(r'\\s+([\\.\\,\\?\\:])', r'\\1',", "return batch pairs of indices stride = chunk_size - overlap_size result = []", "== '__main__': # read parameters parser = argparse.ArgumentParser() parser.add_argument('--model_path', help='Path to the model", "will be truncated)', default=64) parser.add_argument('--min_len', type=int, help='The minimum sentence length' '(all longer will", "print(e) text = \" \".join(tokens) text = re.sub(r'([\\,\\.\\?\\:])', r' \\1', text) result.append(text) return", "0 for BERT/XLNet and 1 for RoBERTa.', default=1) parser.add_argument('--is_ensemble', action='store_true', help='Whether to do", "default=64) parser.add_argument('--min_len', type=int, help='The minimum sentence length' '(all longer will be returned w/o", "(start, end) in indices: tokens = [] for i in range(start, end): try:", "0 batch = [] for sent in tqdm(test_data): batch.append(sent.split()) if len(batch) == batch_size:", "if split_chunk: batch, batch_indices = split_chunks(batch, chunk_size, overlap_size) preds, cnt = model.handle_batch(batch) preds", "file.', default='data/output_vocabulary' # to use pretrained models ) parser.add_argument('--input_file', help='Path to the evalset", "parser.add_argument('--input_file', help='Path to the evalset file', required=True) parser.add_argument('--output_file', help='Path to the output file',", "each action to apply. ' 'Also, minimum error probability, as described in the", "for sent in tqdm(test_data): batch.append(sent.split()) if len(batch) == batch_size: if split_chunk: batch, batch_indices", "should be 0 for BERT/XLNet and 1 for RoBERTa.', default=1) parser.add_argument('--is_ensemble', action='store_true', help='Whether", "'For reproducing reported results it should be 0 for BERT/XLNet and 1 for", "chunk_size=32, overlap_size=8, min_words_cut=4 ): test_data = read_lines(input_file) predictions = [] cnt_corrections = 0", "unit cell.', default=128) parser.add_argument('--lowercase_tokens', action='store_true', help='Whether to lowercase tokens.',) parser.add_argument('--transformer_model', choices=['bert', 'gpt2', 'transformerxl',", "'Also, minimum error probability, as described in the paper.', default=0.0) parser.add_argument('--special_tokens_fix', type=int, help='Whether", "parser.add_argument('--transformer_model', choices=['bert', 'gpt2', 'transformerxl', 'xlnet', 'distilbert', 'roberta', 'albert' 'bert-large', 'roberta-large', 'xlnet-large', 'vinai/phobert-base', 'vinai/phobert-large',", "lowercase tokens.',) parser.add_argument('--transformer_model', choices=['bert', 'gpt2', 'transformerxl', 'xlnet', 'distilbert', 'roberta', 'albert' 'bert-large', 'roberta-large', 'xlnet-large',", "parser.add_argument('--vocab_path', help='Path to the model file.', default='data/output_vocabulary' # to use pretrained models )", "in preds] predictions.extend(preds) cnt_corrections += cnt batch = [] if batch: if split_chunk:", "\".join(tokens) text = re.sub(r'([\\,\\.\\?\\:])', r' \\1', text) result.append(text) return result def main(args): #", "[] for i in range(start, end): try: sub_text = batch[i].strip() sub_text = re.sub(r'([\\.\\,\\?\\:]\\s+)+',", "reported results it should be 0 for BERT/XLNet and 1 for RoBERTa.', default=1)", "default='roberta') parser.add_argument('--iteration_count', type=int, help='The number of iterations of the model.', default=5) parser.add_argument('--additional_confidence', type=float,", "in range(start, end): try: sub_text = batch[i].strip() sub_text = re.sub(r'([\\.\\,\\?\\:]\\s+)+', r'\\1', sub_text) sub_text", "'xlnet-large', 'vinai/phobert-base', 'vinai/phobert-large', 'xlm-roberta-base'], help='Name of the transformer model.', default='roberta') parser.add_argument('--iteration_count', type=int, help='The", "end): try: sub_text = batch[i].strip() sub_text = re.sub(r'([\\.\\,\\?\\:]\\s+)+', r'\\1', sub_text) sub_text = re.sub(r'\\s+([\\.\\,\\?\\:])',", "default=5) parser.add_argument('--additional_confidence', type=float, help='How many probability to add to $KEEP token.', default=0) parser.add_argument('--min_error_probability',", "tokens.extend(sub_tokens[head:-tail]) except Exception as e: print(e) text = \" \".join(tokens) text = re.sub(r'([\\,\\.\\?\\:])',", "): test_data = read_lines(input_file) predictions = [] cnt_corrections = 0 batch = []", "parser.add_argument('--output_file', help='Path to the output file', required=True) parser.add_argument('--max_len', type=int, help='The max sentence length'", "batch[i].strip() sub_text = re.sub(r'([\\.\\,\\?\\:]\\s+)+', r'\\1', sub_text) sub_text = re.sub(r'\\s+([\\.\\,\\?\\:])', r'\\1', sub_text) sub_tokens =", "model = GecBERTModel(vocab_path=args.vocab_path, model_paths=args.model_path, max_len=args.max_len, min_len=args.min_len, iterations=args.iteration_count, min_error_probability=args.min_error_probability, lowercase_tokens=args.lowercase_tokens, model_name=args.transformer_model, special_tokens_fix=args.special_tokens_fix, log=False, confidence=args.additional_confidence,", "# get all paths model = GecBERTModel(vocab_path=args.vocab_path, model_paths=args.model_path, max_len=args.max_len, min_len=args.min_len, iterations=args.iteration_count, min_error_probability=args.min_error_probability, lowercase_tokens=args.lowercase_tokens,", "default='data/output_vocabulary' # to use pretrained models ) parser.add_argument('--input_file', help='Path to the evalset file',", "len(result) num_token = len(tokens) if num_token <= overlap_size: result.append(tokens) for i in range(0,", "i + chunk_size]) indices.append((start, len(result))) return result, indices def merge_chunk(batch, indices, overlap_size=8, min_words_cut=4):", "# read parameters parser = argparse.ArgumentParser() parser.add_argument('--model_path', help='Path to the model file.', nargs='+',", "problem with [CLS], [SEP] tokens tokenization. ' 'For reproducing reported results it should", "be truncated)', default=64) parser.add_argument('--min_len', type=int, help='The minimum sentence length' '(all longer will be", "evalset file', required=True) parser.add_argument('--output_file', help='Path to the output file', required=True) parser.add_argument('--max_len', type=int, help='The", "w/o changes)', default=3) parser.add_argument('--batch_size', type=int, help='The size of hidden unit cell.', default=128) parser.add_argument('--lowercase_tokens',", "re.sub(r'\\s+([\\.\\,\\?\\:])', r'\\1', sub_text) sub_tokens = sub_text.split() if i == start: if i ==", "num_token - overlap_size, stride): result.append(tokens[i: i + chunk_size]) indices.append((start, len(result))) return result, indices", "tokens.extend(sub_tokens[head:]) else: tokens.extend(sub_tokens[head:-tail]) except Exception as e: print(e) text = \" \".join(tokens) text", "- min_words_cut tail = min_words_cut result = [] for (start, end) in indices:", "1: tokens.extend(sub_tokens[head:]) else: tokens.extend(sub_tokens[head:-tail]) except Exception as e: print(e) text = \" \".join(tokens)", "= model.handle_batch(batch) preds = [\" \".join(x) for x in preds] predictions.extend(preds) cnt_corrections +=", "print(f\"Produced overall corrections: {cnt_corrections}\") if __name__ == '__main__': # read parameters parser =", "sub_text = re.sub(r'([\\.\\,\\?\\:]\\s+)+', r'\\1', sub_text) sub_text = re.sub(r'\\s+([\\.\\,\\?\\:])', r'\\1', sub_text) sub_tokens = sub_text.split()", "'roberta-large', 'xlnet-large', 'vinai/phobert-base', 'vinai/phobert-large', 'xlm-roberta-base'], help='Name of the transformer model.', default='roberta') parser.add_argument('--iteration_count', type=int,", "\\1', text) result.append(text) return result def main(args): # get all paths model =", "use chunk merging or not') parser.add_argument('--chunk_size', type=int, help='Chunk size for chunk merging', default=32)", "batch_indices = split_chunks(batch, chunk_size, overlap_size) preds, cnt = model.handle_batch(batch) preds = merge_chunk([\" \".join(x)", "split_chunk: batch, batch_indices = split_chunks(batch, chunk_size, overlap_size) preds, cnt = model.handle_batch(batch) preds =", "as e: print(e) text = \" \".join(tokens) text = re.sub(r'([\\,\\.\\?\\:])', r' \\1', text)", "help='Path to the model file.', nargs='+', required=True) parser.add_argument('--vocab_path', help='Path to the model file.',", "tqdm(test_data): batch.append(sent.split()) if len(batch) == batch_size: if split_chunk: batch, batch_indices = split_chunks(batch, chunk_size,", "m2 or ERRANT print(f\"Produced overall corrections: {cnt_corrections}\") if __name__ == '__main__': # read", "batch: start = len(result) num_token = len(tokens) if num_token <= overlap_size: result.append(tokens) for", "cnt = model.handle_batch(batch) preds = [\" \".join(x) for x in preds] predictions.extend(preds) cnt_corrections", "batch = [] for sent in tqdm(test_data): batch.append(sent.split()) if len(batch) == batch_size: if", "# evaluate with m2 or ERRANT print(f\"Produced overall corrections: {cnt_corrections}\") if __name__ ==", "sentence length' '(all longer will be returned w/o changes)', default=3) parser.add_argument('--batch_size', type=int, help='The", "use pretrained models ) parser.add_argument('--input_file', help='Path to the evalset file', required=True) parser.add_argument('--output_file', help='Path", "= \" \".join(tokens) text = re.sub(r'([\\,\\.\\?\\:])', r' \\1', text) result.append(text) return result def", "be returned w/o changes)', default=3) parser.add_argument('--batch_size', type=int, help='The size of hidden unit cell.',", "e: print(e) text = \" \".join(tokens) text = re.sub(r'([\\,\\.\\?\\:])', r' \\1', text) result.append(text)", "input_file, output_file, model, batch_size=32, split_chunk=False, chunk_size=32, overlap_size=8, min_words_cut=4 ): test_data = read_lines(input_file) predictions", "be 0 for BERT/XLNet and 1 for RoBERTa.', default=1) parser.add_argument('--is_ensemble', action='store_true', help='Whether to", "def merge_chunk(batch, indices, overlap_size=8, min_words_cut=4): head = overlap_size - min_words_cut tail = min_words_cut", "and 1 for RoBERTa.', default=1) parser.add_argument('--is_ensemble', action='store_true', help='Whether to do ensembling.',) parser.add_argument('--weights', help='Used", "help='Chunk size for chunk merging', default=32) parser.add_argument('--overlap_size', type=int, help='Overlapped words between two continuous", "words at the end the first chunk to be removed during merge', default=4)", "[\" \".join(x) for x in preds] predictions.extend(preds) cnt_corrections += cnt with open(output_file, 'w')", "text = \" \".join(tokens) text = re.sub(r'([\\,\\.\\?\\:])', r' \\1', text) result.append(text) return result", "batch_size: if split_chunk: batch, batch_indices = split_chunks(batch, chunk_size, overlap_size) preds, cnt = model.handle_batch(batch)", "import re def predict_for_file( input_file, output_file, model, batch_size=32, split_chunk=False, chunk_size=32, overlap_size=8, min_words_cut=4 ):", "average', nargs='+', default=None) parser.add_argument('--split_chunk', action='store_true', help='Whether to use chunk merging or not') parser.add_argument('--chunk_size',", "type=int, help='number of words at the end the first chunk to be removed", "model file.', nargs='+', required=True) parser.add_argument('--vocab_path', help='Path to the model file.', default='data/output_vocabulary' # to", "- overlap_size result = [] indices = [] for tokens in batch: start", "with m2 or ERRANT print(f\"Produced overall corrections: {cnt_corrections}\") if __name__ == '__main__': #", "overlap_size=args.overlap_size, min_words_cut=args.min_words_cut) # evaluate with m2 or ERRANT print(f\"Produced overall corrections: {cnt_corrections}\") if", "if i == start: if i == end - 1: tokens = sub_tokens", "cell.', default=128) parser.add_argument('--lowercase_tokens', action='store_true', help='Whether to lowercase tokens.',) parser.add_argument('--transformer_model', choices=['bert', 'gpt2', 'transformerxl', 'xlnet',", "else: tokens.extend(sub_tokens[head:-tail]) except Exception as e: print(e) text = \" \".join(tokens) text =", "preds, cnt = model.handle_batch(batch) preds = [\" \".join(x) for x in preds] predictions.extend(preds)", "in indices: tokens = [] for i in range(start, end): try: sub_text =", "transformer model.', default='roberta') parser.add_argument('--iteration_count', type=int, help='The number of iterations of the model.', default=5)", "preds] predictions.extend(preds) cnt_corrections += cnt with open(output_file, 'w') as f: f.write(\"\\n\".join(predictions) + '\\n')", "i == end - 1: tokens.extend(sub_tokens[head:]) else: tokens.extend(sub_tokens[head:-tail]) except Exception as e: print(e)", "import tqdm import re def predict_for_file( input_file, output_file, model, batch_size=32, split_chunk=False, chunk_size=32, overlap_size=8,", "help='Whether to fix problem with [CLS], [SEP] tokens tokenization. ' 'For reproducing reported", "merge_chunk(batch, indices, overlap_size=8, min_words_cut=4): head = overlap_size - min_words_cut tail = min_words_cut result", "+ chunk_size]) indices.append((start, len(result))) return result, indices def merge_chunk(batch, indices, overlap_size=8, min_words_cut=4): head", "for i in range(start, end): try: sub_text = batch[i].strip() sub_text = re.sub(r'([\\.\\,\\?\\:]\\s+)+', r'\\1',", "\".join(x) for x in preds] predictions.extend(preds) cnt_corrections += cnt with open(output_file, 'w') as", "' 'For reproducing reported results it should be 0 for BERT/XLNet and 1", "parser.add_argument('--overlap_size', type=int, help='Overlapped words between two continuous chunks', default=8) parser.add_argument('--min_words_cut', type=int, help='number of", "will be returned w/o changes)', default=3) parser.add_argument('--batch_size', type=int, help='The size of hidden unit", "\".join(x) for x in preds], batch_indices, overlap_size, min_words_cut) else: preds, cnt = model.handle_batch(batch)", "required=True) parser.add_argument('--max_len', type=int, help='The max sentence length' '(all longer will be truncated)', default=64)", "the model file.', nargs='+', required=True) parser.add_argument('--vocab_path', help='Path to the model file.', default='data/output_vocabulary' #", "'vinai/phobert-base', 'vinai/phobert-large', 'xlm-roberta-base'], help='Name of the transformer model.', default='roberta') parser.add_argument('--iteration_count', type=int, help='The number", "to do ensembling.',) parser.add_argument('--weights', help='Used to calculate weighted average', nargs='+', default=None) parser.add_argument('--split_chunk', action='store_true',", "$KEEP token.', default=0) parser.add_argument('--min_error_probability', type=float, help='Minimum probability for each action to apply. '", "split_chunks(batch, chunk_size, overlap_size) preds, cnt = model.handle_batch(batch) preds = merge_chunk([\" \".join(x) for x", "head = overlap_size - min_words_cut tail = min_words_cut result = [] for (start,", "to the model file.', default='data/output_vocabulary' # to use pretrained models ) parser.add_argument('--input_file', help='Path", "batch_size=args.batch_size, split_chunk=args.split_chunk, chunk_size=args.chunk_size, overlap_size=args.overlap_size, min_words_cut=args.min_words_cut) # evaluate with m2 or ERRANT print(f\"Produced overall", "iterations of the model.', default=5) parser.add_argument('--additional_confidence', type=float, help='How many probability to add to", "cnt_corrections += cnt with open(output_file, 'w') as f: f.write(\"\\n\".join(predictions) + '\\n') return cnt_corrections", "1: tokens = sub_tokens else: tokens.extend(sub_tokens[:-tail]) elif i == end - 1: tokens.extend(sub_tokens[head:])", "== batch_size: if split_chunk: batch, batch_indices = split_chunks(batch, chunk_size, overlap_size) preds, cnt =", "apply. ' 'Also, minimum error probability, as described in the paper.', default=0.0) parser.add_argument('--special_tokens_fix',", "reproducing reported results it should be 0 for BERT/XLNet and 1 for RoBERTa.',", "= read_lines(input_file) predictions = [] cnt_corrections = 0 batch = [] for sent", "else: tokens.extend(sub_tokens[:-tail]) elif i == end - 1: tokens.extend(sub_tokens[head:]) else: tokens.extend(sub_tokens[head:-tail]) except Exception", "'xlnet', 'distilbert', 'roberta', 'albert' 'bert-large', 'roberta-large', 'xlnet-large', 'vinai/phobert-base', 'vinai/phobert-large', 'xlm-roberta-base'], help='Name of the", "help='Whether to do ensembling.',) parser.add_argument('--weights', help='Used to calculate weighted average', nargs='+', default=None) parser.add_argument('--split_chunk',", "words between two continuous chunks', default=8) parser.add_argument('--min_words_cut', type=int, help='number of words at the", "' 'Also, minimum error probability, as described in the paper.', default=0.0) parser.add_argument('--special_tokens_fix', type=int,", "cnt batch = [] if batch: if split_chunk: batch, batch_indices = split_chunks(batch, chunk_size,", "model_paths=args.model_path, max_len=args.max_len, min_len=args.min_len, iterations=args.iteration_count, min_error_probability=args.min_error_probability, lowercase_tokens=args.lowercase_tokens, model_name=args.transformer_model, special_tokens_fix=args.special_tokens_fix, log=False, confidence=args.additional_confidence, is_ensemble=args.is_ensemble, weigths=args.weights) cnt_corrections", "in preds], batch_indices, overlap_size, min_words_cut) else: preds, cnt = model.handle_batch(batch) preds = [\"", "[] indices = [] for tokens in batch: start = len(result) num_token =", "RoBERTa.', default=1) parser.add_argument('--is_ensemble', action='store_true', help='Whether to do ensembling.',) parser.add_argument('--weights', help='Used to calculate weighted", "result = [] indices = [] for tokens in batch: start = len(result)", "parser.add_argument('--min_words_cut', type=int, help='number of words at the end the first chunk to be", "[] for sent in tqdm(test_data): batch.append(sent.split()) if len(batch) == batch_size: if split_chunk: batch,", "r'\\1', sub_text) sub_tokens = sub_text.split() if i == start: if i == end", "gector.gec_model import GecBERTModel from tqdm import tqdm import re def predict_for_file( input_file, output_file,", "action to apply. ' 'Also, minimum error probability, as described in the paper.',", "model.', default='roberta') parser.add_argument('--iteration_count', type=int, help='The number of iterations of the model.', default=5) parser.add_argument('--additional_confidence',", "= re.sub(r'\\s+([\\.\\,\\?\\:])', r'\\1', sub_text) sub_tokens = sub_text.split() if i == start: if i", "max sentence length' '(all longer will be truncated)', default=64) parser.add_argument('--min_len', type=int, help='The minimum", "probability for each action to apply. ' 'Also, minimum error probability, as described", "'vinai/phobert-large', 'xlm-roberta-base'], help='Name of the transformer model.', default='roberta') parser.add_argument('--iteration_count', type=int, help='The number of", "output file', required=True) parser.add_argument('--max_len', type=int, help='The max sentence length' '(all longer will be", "for x in preds] predictions.extend(preds) cnt_corrections += cnt with open(output_file, 'w') as f:", "sub_text) sub_tokens = sub_text.split() if i == start: if i == end -", "text = re.sub(r'([\\,\\.\\?\\:])', r' \\1', text) result.append(text) return result def main(args): # get", "help='Overlapped words between two continuous chunks', default=8) parser.add_argument('--min_words_cut', type=int, help='number of words at", "i == end - 1: tokens = sub_tokens else: tokens.extend(sub_tokens[:-tail]) elif i ==", "{cnt_corrections}\") if __name__ == '__main__': # read parameters parser = argparse.ArgumentParser() parser.add_argument('--model_path', help='Path", "add to $KEEP token.', default=0) parser.add_argument('--min_error_probability', type=float, help='Minimum probability for each action to", "chunk merging or not') parser.add_argument('--chunk_size', type=int, help='Chunk size for chunk merging', default=32) parser.add_argument('--overlap_size',", "sub_tokens else: tokens.extend(sub_tokens[:-tail]) elif i == end - 1: tokens.extend(sub_tokens[head:]) else: tokens.extend(sub_tokens[head:-tail]) except", "if batch: if split_chunk: batch, batch_indices = split_chunks(batch, chunk_size, overlap_size) preds, cnt =", "'transformerxl', 'xlnet', 'distilbert', 'roberta', 'albert' 'bert-large', 'roberta-large', 'xlnet-large', 'vinai/phobert-base', 'vinai/phobert-large', 'xlm-roberta-base'], help='Name of", "with open(output_file, 'w') as f: f.write(\"\\n\".join(predictions) + '\\n') return cnt_corrections def split_chunks(batch, chunk_size=32,", "to use chunk merging or not') parser.add_argument('--chunk_size', type=int, help='Chunk size for chunk merging',", "import GecBERTModel from tqdm import tqdm import re def predict_for_file( input_file, output_file, model,", "tokens = sub_tokens else: tokens.extend(sub_tokens[:-tail]) elif i == end - 1: tokens.extend(sub_tokens[head:]) else:", "paper.', default=0.0) parser.add_argument('--special_tokens_fix', type=int, help='Whether to fix problem with [CLS], [SEP] tokens tokenization.", "batch, batch_indices = split_chunks(batch, chunk_size, overlap_size) preds, cnt = model.handle_batch(batch) preds = merge_chunk([\"", "if __name__ == '__main__': # read parameters parser = argparse.ArgumentParser() parser.add_argument('--model_path', help='Path to", "default=32) parser.add_argument('--overlap_size', type=int, help='Overlapped words between two continuous chunks', default=8) parser.add_argument('--min_words_cut', type=int, help='number", "model, batch_size=args.batch_size, split_chunk=args.split_chunk, chunk_size=args.chunk_size, overlap_size=args.overlap_size, min_words_cut=args.min_words_cut) # evaluate with m2 or ERRANT print(f\"Produced", "for tokens in batch: start = len(result) num_token = len(tokens) if num_token <=", "the model.', default=5) parser.add_argument('--additional_confidence', type=float, help='How many probability to add to $KEEP token.',", "in batch: start = len(result) num_token = len(tokens) if num_token <= overlap_size: result.append(tokens)", "end) in indices: tokens = [] for i in range(start, end): try: sub_text", "tokens tokenization. ' 'For reproducing reported results it should be 0 for BERT/XLNet", "= merge_chunk([\" \".join(x) for x in preds], batch_indices, overlap_size, min_words_cut) else: preds, cnt", "Exception as e: print(e) text = \" \".join(tokens) text = re.sub(r'([\\,\\.\\?\\:])', r' \\1',", "pairs of indices stride = chunk_size - overlap_size result = [] indices =", "overlap_size=8): # return batch pairs of indices stride = chunk_size - overlap_size result", "= overlap_size - min_words_cut tail = min_words_cut result = [] for (start, end)", "min_error_probability=args.min_error_probability, lowercase_tokens=args.lowercase_tokens, model_name=args.transformer_model, special_tokens_fix=args.special_tokens_fix, log=False, confidence=args.additional_confidence, is_ensemble=args.is_ensemble, weigths=args.weights) cnt_corrections = predict_for_file(args.input_file, args.output_file, model,", "read_lines from gector.gec_model import GecBERTModel from tqdm import tqdm import re def predict_for_file(", "= [] if batch: if split_chunk: batch, batch_indices = split_chunks(batch, chunk_size, overlap_size) preds,", "for each action to apply. ' 'Also, minimum error probability, as described in", "of words at the end the first chunk to be removed during merge',", "for x in preds], batch_indices, overlap_size, min_words_cut) else: preds, cnt = model.handle_batch(batch) preds", "predictions.extend(preds) cnt_corrections += cnt with open(output_file, 'w') as f: f.write(\"\\n\".join(predictions) + '\\n') return", "help='How many probability to add to $KEEP token.', default=0) parser.add_argument('--min_error_probability', type=float, help='Minimum probability", "confidence=args.additional_confidence, is_ensemble=args.is_ensemble, weigths=args.weights) cnt_corrections = predict_for_file(args.input_file, args.output_file, model, batch_size=args.batch_size, split_chunk=args.split_chunk, chunk_size=args.chunk_size, overlap_size=args.overlap_size, min_words_cut=args.min_words_cut)", "= [] for i in range(start, end): try: sub_text = batch[i].strip() sub_text =", "predictions.extend(preds) cnt_corrections += cnt batch = [] if batch: if split_chunk: batch, batch_indices", "chunk merging', default=32) parser.add_argument('--overlap_size', type=int, help='Overlapped words between two continuous chunks', default=8) parser.add_argument('--min_words_cut',", "end - 1: tokens = sub_tokens else: tokens.extend(sub_tokens[:-tail]) elif i == end -", "min_words_cut) else: preds, cnt = model.handle_batch(batch) preds = [\" \".join(x) for x in", "i == start: if i == end - 1: tokens = sub_tokens else:", "the end the first chunk to be removed during merge', default=4) args =", "sub_tokens = sub_text.split() if i == start: if i == end - 1:", "fix problem with [CLS], [SEP] tokens tokenization. ' 'For reproducing reported results it", "type=int, help='The max sentence length' '(all longer will be truncated)', default=64) parser.add_argument('--min_len', type=int,", "to $KEEP token.', default=0) parser.add_argument('--min_error_probability', type=float, help='Minimum probability for each action to apply.", "from utils.helpers import read_lines from gector.gec_model import GecBERTModel from tqdm import tqdm import", "= [] for sent in tqdm(test_data): batch.append(sent.split()) if len(batch) == batch_size: if split_chunk:", "<reponame>binh234/capu<filename>predict.py import argparse from utils.helpers import read_lines from gector.gec_model import GecBERTModel from tqdm", "log=False, confidence=args.additional_confidence, is_ensemble=args.is_ensemble, weigths=args.weights) cnt_corrections = predict_for_file(args.input_file, args.output_file, model, batch_size=args.batch_size, split_chunk=args.split_chunk, chunk_size=args.chunk_size, overlap_size=args.overlap_size,", "[CLS], [SEP] tokens tokenization. ' 'For reproducing reported results it should be 0", "BERT/XLNet and 1 for RoBERTa.', default=1) parser.add_argument('--is_ensemble', action='store_true', help='Whether to do ensembling.',) parser.add_argument('--weights',", "if len(batch) == batch_size: if split_chunk: batch, batch_indices = split_chunks(batch, chunk_size, overlap_size) preds,", "weigths=args.weights) cnt_corrections = predict_for_file(args.input_file, args.output_file, model, batch_size=args.batch_size, split_chunk=args.split_chunk, chunk_size=args.chunk_size, overlap_size=args.overlap_size, min_words_cut=args.min_words_cut) # evaluate", "stride = chunk_size - overlap_size result = [] indices = [] for tokens", "overlap_size - min_words_cut tail = min_words_cut result = [] for (start, end) in", "predictions = [] cnt_corrections = 0 batch = [] for sent in tqdm(test_data):", "start = len(result) num_token = len(tokens) if num_token <= overlap_size: result.append(tokens) for i", "all paths model = GecBERTModel(vocab_path=args.vocab_path, model_paths=args.model_path, max_len=args.max_len, min_len=args.min_len, iterations=args.iteration_count, min_error_probability=args.min_error_probability, lowercase_tokens=args.lowercase_tokens, model_name=args.transformer_model, special_tokens_fix=args.special_tokens_fix,", "'gpt2', 'transformerxl', 'xlnet', 'distilbert', 'roberta', 'albert' 'bert-large', 'roberta-large', 'xlnet-large', 'vinai/phobert-base', 'vinai/phobert-large', 'xlm-roberta-base'], help='Name", "except Exception as e: print(e) text = \" \".join(tokens) text = re.sub(r'([\\,\\.\\?\\:])', r'", "for BERT/XLNet and 1 for RoBERTa.', default=1) parser.add_argument('--is_ensemble', action='store_true', help='Whether to do ensembling.',)", "size of hidden unit cell.', default=128) parser.add_argument('--lowercase_tokens', action='store_true', help='Whether to lowercase tokens.',) parser.add_argument('--transformer_model',", "return result def main(args): # get all paths model = GecBERTModel(vocab_path=args.vocab_path, model_paths=args.model_path, max_len=args.max_len,", "chunk_size - overlap_size result = [] indices = [] for tokens in batch:", "parser.add_argument('--max_len', type=int, help='The max sentence length' '(all longer will be truncated)', default=64) parser.add_argument('--min_len',", "split_chunk=args.split_chunk, chunk_size=args.chunk_size, overlap_size=args.overlap_size, min_words_cut=args.min_words_cut) # evaluate with m2 or ERRANT print(f\"Produced overall corrections:", "token.', default=0) parser.add_argument('--min_error_probability', type=float, help='Minimum probability for each action to apply. ' 'Also,", "required=True) parser.add_argument('--output_file', help='Path to the output file', required=True) parser.add_argument('--max_len', type=int, help='The max sentence", "default=None) parser.add_argument('--split_chunk', action='store_true', help='Whether to use chunk merging or not') parser.add_argument('--chunk_size', type=int, help='Chunk", "type=int, help='Whether to fix problem with [CLS], [SEP] tokens tokenization. ' 'For reproducing", "parser.add_argument('--chunk_size', type=int, help='Chunk size for chunk merging', default=32) parser.add_argument('--overlap_size', type=int, help='Overlapped words between", "model_name=args.transformer_model, special_tokens_fix=args.special_tokens_fix, log=False, confidence=args.additional_confidence, is_ensemble=args.is_ensemble, weigths=args.weights) cnt_corrections = predict_for_file(args.input_file, args.output_file, model, batch_size=args.batch_size, split_chunk=args.split_chunk,", "= argparse.ArgumentParser() parser.add_argument('--model_path', help='Path to the model file.', nargs='+', required=True) parser.add_argument('--vocab_path', help='Path to", "read_lines(input_file) predictions = [] cnt_corrections = 0 batch = [] for sent in", "argparse.ArgumentParser() parser.add_argument('--model_path', help='Path to the model file.', nargs='+', required=True) parser.add_argument('--vocab_path', help='Path to the", "= split_chunks(batch, chunk_size, overlap_size) preds, cnt = model.handle_batch(batch) preds = merge_chunk([\" \".join(x) for", "batch = [] if batch: if split_chunk: batch, batch_indices = split_chunks(batch, chunk_size, overlap_size)", "re.sub(r'([\\.\\,\\?\\:]\\s+)+', r'\\1', sub_text) sub_text = re.sub(r'\\s+([\\.\\,\\?\\:])', r'\\1', sub_text) sub_tokens = sub_text.split() if i", "range(0, num_token - overlap_size, stride): result.append(tokens[i: i + chunk_size]) indices.append((start, len(result))) return result,", "type=int, help='Chunk size for chunk merging', default=32) parser.add_argument('--overlap_size', type=int, help='Overlapped words between two", "== start: if i == end - 1: tokens = sub_tokens else: tokens.extend(sub_tokens[:-tail])", "= [] indices = [] for tokens in batch: start = len(result) num_token", "sub_text.split() if i == start: if i == end - 1: tokens =", "overlap_size=8, min_words_cut=4): head = overlap_size - min_words_cut tail = min_words_cut result = []", "overlap_size, stride): result.append(tokens[i: i + chunk_size]) indices.append((start, len(result))) return result, indices def merge_chunk(batch,", "to the evalset file', required=True) parser.add_argument('--output_file', help='Path to the output file', required=True) parser.add_argument('--max_len',", "split_chunk=False, chunk_size=32, overlap_size=8, min_words_cut=4 ): test_data = read_lines(input_file) predictions = [] cnt_corrections =", "import argparse from utils.helpers import read_lines from gector.gec_model import GecBERTModel from tqdm import", "models ) parser.add_argument('--input_file', help='Path to the evalset file', required=True) parser.add_argument('--output_file', help='Path to the", "help='Whether to use chunk merging or not') parser.add_argument('--chunk_size', type=int, help='Chunk size for chunk", "help='The max sentence length' '(all longer will be truncated)', default=64) parser.add_argument('--min_len', type=int, help='The", "default=3) parser.add_argument('--batch_size', type=int, help='The size of hidden unit cell.', default=128) parser.add_argument('--lowercase_tokens', action='store_true', help='Whether", "= [] cnt_corrections = 0 batch = [] for sent in tqdm(test_data): batch.append(sent.split())", "merging', default=32) parser.add_argument('--overlap_size', type=int, help='Overlapped words between two continuous chunks', default=8) parser.add_argument('--min_words_cut', type=int,", "min_words_cut=args.min_words_cut) # evaluate with m2 or ERRANT print(f\"Produced overall corrections: {cnt_corrections}\") if __name__", "pretrained models ) parser.add_argument('--input_file', help='Path to the evalset file', required=True) parser.add_argument('--output_file', help='Path to", "f: f.write(\"\\n\".join(predictions) + '\\n') return cnt_corrections def split_chunks(batch, chunk_size=32, overlap_size=8): # return batch", "at the end the first chunk to be removed during merge', default=4) args", "result.append(tokens[i: i + chunk_size]) indices.append((start, len(result))) return result, indices def merge_chunk(batch, indices, overlap_size=8,", "\".join(x) for x in preds] predictions.extend(preds) cnt_corrections += cnt batch = [] if", "number of iterations of the model.', default=5) parser.add_argument('--additional_confidence', type=float, help='How many probability to", "predict_for_file(args.input_file, args.output_file, model, batch_size=args.batch_size, split_chunk=args.split_chunk, chunk_size=args.chunk_size, overlap_size=args.overlap_size, min_words_cut=args.min_words_cut) # evaluate with m2 or", "for x in preds] predictions.extend(preds) cnt_corrections += cnt batch = [] if batch:", "parser.add_argument('--min_error_probability', type=float, help='Minimum probability for each action to apply. ' 'Also, minimum error", "to add to $KEEP token.', default=0) parser.add_argument('--min_error_probability', type=float, help='Minimum probability for each action", "min_words_cut tail = min_words_cut result = [] for (start, end) in indices: tokens", "ERRANT print(f\"Produced overall corrections: {cnt_corrections}\") if __name__ == '__main__': # read parameters parser", "help='Minimum probability for each action to apply. ' 'Also, minimum error probability, as", "overlap_size result = [] indices = [] for tokens in batch: start =", "in range(0, num_token - overlap_size, stride): result.append(tokens[i: i + chunk_size]) indices.append((start, len(result))) return", "argparse from utils.helpers import read_lines from gector.gec_model import GecBERTModel from tqdm import tqdm", "re def predict_for_file( input_file, output_file, model, batch_size=32, split_chunk=False, chunk_size=32, overlap_size=8, min_words_cut=4 ): test_data", "described in the paper.', default=0.0) parser.add_argument('--special_tokens_fix', type=int, help='Whether to fix problem with [CLS],", "'(all longer will be returned w/o changes)', default=3) parser.add_argument('--batch_size', type=int, help='The size of", "test_data = read_lines(input_file) predictions = [] cnt_corrections = 0 batch = [] for", "truncated)', default=64) parser.add_argument('--min_len', type=int, help='The minimum sentence length' '(all longer will be returned", "f.write(\"\\n\".join(predictions) + '\\n') return cnt_corrections def split_chunks(batch, chunk_size=32, overlap_size=8): # return batch pairs", "len(result))) return result, indices def merge_chunk(batch, indices, overlap_size=8, min_words_cut=4): head = overlap_size -", "iterations=args.iteration_count, min_error_probability=args.min_error_probability, lowercase_tokens=args.lowercase_tokens, model_name=args.transformer_model, special_tokens_fix=args.special_tokens_fix, log=False, confidence=args.additional_confidence, is_ensemble=args.is_ensemble, weigths=args.weights) cnt_corrections = predict_for_file(args.input_file, args.output_file,", "indices = [] for tokens in batch: start = len(result) num_token = len(tokens)", "as f: f.write(\"\\n\".join(predictions) + '\\n') return cnt_corrections def split_chunks(batch, chunk_size=32, overlap_size=8): # return", "__name__ == '__main__': # read parameters parser = argparse.ArgumentParser() parser.add_argument('--model_path', help='Path to the", "preds], batch_indices, overlap_size, min_words_cut) else: preds, cnt = model.handle_batch(batch) preds = [\" \".join(x)", "calculate weighted average', nargs='+', default=None) parser.add_argument('--split_chunk', action='store_true', help='Whether to use chunk merging or", "sub_text = batch[i].strip() sub_text = re.sub(r'([\\.\\,\\?\\:]\\s+)+', r'\\1', sub_text) sub_text = re.sub(r'\\s+([\\.\\,\\?\\:])', r'\\1', sub_text)", "in preds] predictions.extend(preds) cnt_corrections += cnt with open(output_file, 'w') as f: f.write(\"\\n\".join(predictions) +", "chunk_size, overlap_size) preds, cnt = model.handle_batch(batch) preds = merge_chunk([\" \".join(x) for x in", "help='Used to calculate weighted average', nargs='+', default=None) parser.add_argument('--split_chunk', action='store_true', help='Whether to use chunk", "to apply. ' 'Also, minimum error probability, as described in the paper.', default=0.0)", "open(output_file, 'w') as f: f.write(\"\\n\".join(predictions) + '\\n') return cnt_corrections def split_chunks(batch, chunk_size=32, overlap_size=8):", "args.output_file, model, batch_size=args.batch_size, split_chunk=args.split_chunk, chunk_size=args.chunk_size, overlap_size=args.overlap_size, min_words_cut=args.min_words_cut) # evaluate with m2 or ERRANT", "or ERRANT print(f\"Produced overall corrections: {cnt_corrections}\") if __name__ == '__main__': # read parameters", "help='The number of iterations of the model.', default=5) parser.add_argument('--additional_confidence', type=float, help='How many probability", "nargs='+', required=True) parser.add_argument('--vocab_path', help='Path to the model file.', default='data/output_vocabulary' # to use pretrained", "parser.add_argument('--is_ensemble', action='store_true', help='Whether to do ensembling.',) parser.add_argument('--weights', help='Used to calculate weighted average', nargs='+',", "get all paths model = GecBERTModel(vocab_path=args.vocab_path, model_paths=args.model_path, max_len=args.max_len, min_len=args.min_len, iterations=args.iteration_count, min_error_probability=args.min_error_probability, lowercase_tokens=args.lowercase_tokens, model_name=args.transformer_model,", "= sub_tokens else: tokens.extend(sub_tokens[:-tail]) elif i == end - 1: tokens.extend(sub_tokens[head:]) else: tokens.extend(sub_tokens[head:-tail])", "min_words_cut=4): head = overlap_size - min_words_cut tail = min_words_cut result = [] for", "result = [] for (start, end) in indices: tokens = [] for i", "tqdm import tqdm import re def predict_for_file( input_file, output_file, model, batch_size=32, split_chunk=False, chunk_size=32,", "parser.add_argument('--iteration_count', type=int, help='The number of iterations of the model.', default=5) parser.add_argument('--additional_confidence', type=float, help='How", "help='Path to the evalset file', required=True) parser.add_argument('--output_file', help='Path to the output file', required=True)", "from gector.gec_model import GecBERTModel from tqdm import tqdm import re def predict_for_file( input_file,", "= [] for tokens in batch: start = len(result) num_token = len(tokens) if", "tokens in batch: start = len(result) num_token = len(tokens) if num_token <= overlap_size:", "'__main__': # read parameters parser = argparse.ArgumentParser() parser.add_argument('--model_path', help='Path to the model file.',", "parser.add_argument('--special_tokens_fix', type=int, help='Whether to fix problem with [CLS], [SEP] tokens tokenization. ' 'For", "file', required=True) parser.add_argument('--max_len', type=int, help='The max sentence length' '(all longer will be truncated)',", "= batch[i].strip() sub_text = re.sub(r'([\\.\\,\\?\\:]\\s+)+', r'\\1', sub_text) sub_text = re.sub(r'\\s+([\\.\\,\\?\\:])', r'\\1', sub_text) sub_tokens", "preds = [\" \".join(x) for x in preds] predictions.extend(preds) cnt_corrections += cnt with", "results it should be 0 for BERT/XLNet and 1 for RoBERTa.', default=1) parser.add_argument('--is_ensemble',", "to calculate weighted average', nargs='+', default=None) parser.add_argument('--split_chunk', action='store_true', help='Whether to use chunk merging", "- 1: tokens.extend(sub_tokens[head:]) else: tokens.extend(sub_tokens[head:-tail]) except Exception as e: print(e) text = \"", "end - 1: tokens.extend(sub_tokens[head:]) else: tokens.extend(sub_tokens[head:-tail]) except Exception as e: print(e) text =", "if num_token <= overlap_size: result.append(tokens) for i in range(0, num_token - overlap_size, stride):", "main(args): # get all paths model = GecBERTModel(vocab_path=args.vocab_path, model_paths=args.model_path, max_len=args.max_len, min_len=args.min_len, iterations=args.iteration_count, min_error_probability=args.min_error_probability,", "choices=['bert', 'gpt2', 'transformerxl', 'xlnet', 'distilbert', 'roberta', 'albert' 'bert-large', 'roberta-large', 'xlnet-large', 'vinai/phobert-base', 'vinai/phobert-large', 'xlm-roberta-base'],", "do ensembling.',) parser.add_argument('--weights', help='Used to calculate weighted average', nargs='+', default=None) parser.add_argument('--split_chunk', action='store_true', help='Whether", "default=1) parser.add_argument('--is_ensemble', action='store_true', help='Whether to do ensembling.',) parser.add_argument('--weights', help='Used to calculate weighted average',", "as described in the paper.', default=0.0) parser.add_argument('--special_tokens_fix', type=int, help='Whether to fix problem with", "return result, indices def merge_chunk(batch, indices, overlap_size=8, min_words_cut=4): head = overlap_size - min_words_cut", "batch.append(sent.split()) if len(batch) == batch_size: if split_chunk: batch, batch_indices = split_chunks(batch, chunk_size, overlap_size)", "in the paper.', default=0.0) parser.add_argument('--special_tokens_fix', type=int, help='Whether to fix problem with [CLS], [SEP]", "for chunk merging', default=32) parser.add_argument('--overlap_size', type=int, help='Overlapped words between two continuous chunks', default=8)", "start: if i == end - 1: tokens = sub_tokens else: tokens.extend(sub_tokens[:-tail]) elif", "the output file', required=True) parser.add_argument('--max_len', type=int, help='The max sentence length' '(all longer will", "to lowercase tokens.',) parser.add_argument('--transformer_model', choices=['bert', 'gpt2', 'transformerxl', 'xlnet', 'distilbert', 'roberta', 'albert' 'bert-large', 'roberta-large',", "overlap_size: result.append(tokens) for i in range(0, num_token - overlap_size, stride): result.append(tokens[i: i +", "special_tokens_fix=args.special_tokens_fix, log=False, confidence=args.additional_confidence, is_ensemble=args.is_ensemble, weigths=args.weights) cnt_corrections = predict_for_file(args.input_file, args.output_file, model, batch_size=args.batch_size, split_chunk=args.split_chunk, chunk_size=args.chunk_size,", "parser.add_argument('--lowercase_tokens', action='store_true', help='Whether to lowercase tokens.',) parser.add_argument('--transformer_model', choices=['bert', 'gpt2', 'transformerxl', 'xlnet', 'distilbert', 'roberta',", "model file.', default='data/output_vocabulary' # to use pretrained models ) parser.add_argument('--input_file', help='Path to the", "elif i == end - 1: tokens.extend(sub_tokens[head:]) else: tokens.extend(sub_tokens[head:-tail]) except Exception as e:", "two continuous chunks', default=8) parser.add_argument('--min_words_cut', type=int, help='number of words at the end the", "cnt_corrections = predict_for_file(args.input_file, args.output_file, model, batch_size=args.batch_size, split_chunk=args.split_chunk, chunk_size=args.chunk_size, overlap_size=args.overlap_size, min_words_cut=args.min_words_cut) # evaluate with", "chunk_size=args.chunk_size, overlap_size=args.overlap_size, min_words_cut=args.min_words_cut) # evaluate with m2 or ERRANT print(f\"Produced overall corrections: {cnt_corrections}\")", "+= cnt with open(output_file, 'w') as f: f.write(\"\\n\".join(predictions) + '\\n') return cnt_corrections def", "chunk_size]) indices.append((start, len(result))) return result, indices def merge_chunk(batch, indices, overlap_size=8, min_words_cut=4): head =", "length' '(all longer will be returned w/o changes)', default=3) parser.add_argument('--batch_size', type=int, help='The size", "parser.add_argument('--additional_confidence', type=float, help='How many probability to add to $KEEP token.', default=0) parser.add_argument('--min_error_probability', type=float,", "minimum error probability, as described in the paper.', default=0.0) parser.add_argument('--special_tokens_fix', type=int, help='Whether to", "ensembling.',) parser.add_argument('--weights', help='Used to calculate weighted average', nargs='+', default=None) parser.add_argument('--split_chunk', action='store_true', help='Whether to", "len(batch) == batch_size: if split_chunk: batch, batch_indices = split_chunks(batch, chunk_size, overlap_size) preds, cnt", "of hidden unit cell.', default=128) parser.add_argument('--lowercase_tokens', action='store_true', help='Whether to lowercase tokens.',) parser.add_argument('--transformer_model', choices=['bert',", "parser.add_argument('--split_chunk', action='store_true', help='Whether to use chunk merging or not') parser.add_argument('--chunk_size', type=int, help='Chunk size", "type=float, help='How many probability to add to $KEEP token.', default=0) parser.add_argument('--min_error_probability', type=float, help='Minimum", "continuous chunks', default=8) parser.add_argument('--min_words_cut', type=int, help='number of words at the end the first", "action='store_true', help='Whether to use chunk merging or not') parser.add_argument('--chunk_size', type=int, help='Chunk size for", "length' '(all longer will be truncated)', default=64) parser.add_argument('--min_len', type=int, help='The minimum sentence length'", "type=int, help='The size of hidden unit cell.', default=128) parser.add_argument('--lowercase_tokens', action='store_true', help='Whether to lowercase", "def split_chunks(batch, chunk_size=32, overlap_size=8): # return batch pairs of indices stride = chunk_size", "indices.append((start, len(result))) return result, indices def merge_chunk(batch, indices, overlap_size=8, min_words_cut=4): head = overlap_size", "file', required=True) parser.add_argument('--output_file', help='Path to the output file', required=True) parser.add_argument('--max_len', type=int, help='The max", "- overlap_size, stride): result.append(tokens[i: i + chunk_size]) indices.append((start, len(result))) return result, indices def", "[] cnt_corrections = 0 batch = [] for sent in tqdm(test_data): batch.append(sent.split()) if", "hidden unit cell.', default=128) parser.add_argument('--lowercase_tokens', action='store_true', help='Whether to lowercase tokens.',) parser.add_argument('--transformer_model', choices=['bert', 'gpt2',", "parser.add_argument('--model_path', help='Path to the model file.', nargs='+', required=True) parser.add_argument('--vocab_path', help='Path to the model", "parser = argparse.ArgumentParser() parser.add_argument('--model_path', help='Path to the model file.', nargs='+', required=True) parser.add_argument('--vocab_path', help='Path", "default=0) parser.add_argument('--min_error_probability', type=float, help='Minimum probability for each action to apply. ' 'Also, minimum", "indices: tokens = [] for i in range(start, end): try: sub_text = batch[i].strip()", "cnt = model.handle_batch(batch) preds = merge_chunk([\" \".join(x) for x in preds], batch_indices, overlap_size,", "'distilbert', 'roberta', 'albert' 'bert-large', 'roberta-large', 'xlnet-large', 'vinai/phobert-base', 'vinai/phobert-large', 'xlm-roberta-base'], help='Name of the transformer", "overlap_size, min_words_cut) else: preds, cnt = model.handle_batch(batch) preds = [\" \".join(x) for x", "cnt_corrections def split_chunks(batch, chunk_size=32, overlap_size=8): # return batch pairs of indices stride =", "parser.add_argument('--min_len', type=int, help='The minimum sentence length' '(all longer will be returned w/o changes)',", "overlap_size=8, min_words_cut=4 ): test_data = read_lines(input_file) predictions = [] cnt_corrections = 0 batch", "returned w/o changes)', default=3) parser.add_argument('--batch_size', type=int, help='The size of hidden unit cell.', default=128)", "parser.add_argument('--batch_size', type=int, help='The size of hidden unit cell.', default=128) parser.add_argument('--lowercase_tokens', action='store_true', help='Whether to", "= len(result) num_token = len(tokens) if num_token <= overlap_size: result.append(tokens) for i in", "cnt with open(output_file, 'w') as f: f.write(\"\\n\".join(predictions) + '\\n') return cnt_corrections def split_chunks(batch,", "cnt_corrections += cnt batch = [] if batch: if split_chunk: batch, batch_indices =", "= [\" \".join(x) for x in preds] predictions.extend(preds) cnt_corrections += cnt with open(output_file,", "text) result.append(text) return result def main(args): # get all paths model = GecBERTModel(vocab_path=args.vocab_path,", "error probability, as described in the paper.', default=0.0) parser.add_argument('--special_tokens_fix', type=int, help='Whether to fix", "nargs='+', default=None) parser.add_argument('--split_chunk', action='store_true', help='Whether to use chunk merging or not') parser.add_argument('--chunk_size', type=int,", "'bert-large', 'roberta-large', 'xlnet-large', 'vinai/phobert-base', 'vinai/phobert-large', 'xlm-roberta-base'], help='Name of the transformer model.', default='roberta') parser.add_argument('--iteration_count',", "# to use pretrained models ) parser.add_argument('--input_file', help='Path to the evalset file', required=True)", "tokenization. ' 'For reproducing reported results it should be 0 for BERT/XLNet and", "for i in range(0, num_token - overlap_size, stride): result.append(tokens[i: i + chunk_size]) indices.append((start,", "cnt_corrections = 0 batch = [] for sent in tqdm(test_data): batch.append(sent.split()) if len(batch)", "[\" \".join(x) for x in preds] predictions.extend(preds) cnt_corrections += cnt batch = []", "help='Whether to lowercase tokens.',) parser.add_argument('--transformer_model', choices=['bert', 'gpt2', 'transformerxl', 'xlnet', 'distilbert', 'roberta', 'albert' 'bert-large',", "for (start, end) in indices: tokens = [] for i in range(start, end):", "[] if batch: if split_chunk: batch, batch_indices = split_chunks(batch, chunk_size, overlap_size) preds, cnt", "GecBERTModel(vocab_path=args.vocab_path, model_paths=args.model_path, max_len=args.max_len, min_len=args.min_len, iterations=args.iteration_count, min_error_probability=args.min_error_probability, lowercase_tokens=args.lowercase_tokens, model_name=args.transformer_model, special_tokens_fix=args.special_tokens_fix, log=False, confidence=args.additional_confidence, is_ensemble=args.is_ensemble, weigths=args.weights)", "it should be 0 for BERT/XLNet and 1 for RoBERTa.', default=1) parser.add_argument('--is_ensemble', action='store_true',", "tokens.extend(sub_tokens[:-tail]) elif i == end - 1: tokens.extend(sub_tokens[head:]) else: tokens.extend(sub_tokens[head:-tail]) except Exception as", "num_token = len(tokens) if num_token <= overlap_size: result.append(tokens) for i in range(0, num_token", "def main(args): # get all paths model = GecBERTModel(vocab_path=args.vocab_path, model_paths=args.model_path, max_len=args.max_len, min_len=args.min_len, iterations=args.iteration_count,", "the transformer model.', default='roberta') parser.add_argument('--iteration_count', type=int, help='The number of iterations of the model.',", "result, indices def merge_chunk(batch, indices, overlap_size=8, min_words_cut=4): head = overlap_size - min_words_cut tail", "sub_text) sub_text = re.sub(r'\\s+([\\.\\,\\?\\:])', r'\\1', sub_text) sub_tokens = sub_text.split() if i == start:", "+ '\\n') return cnt_corrections def split_chunks(batch, chunk_size=32, overlap_size=8): # return batch pairs of", "file.', nargs='+', required=True) parser.add_argument('--vocab_path', help='Path to the model file.', default='data/output_vocabulary' # to use", "between two continuous chunks', default=8) parser.add_argument('--min_words_cut', type=int, help='number of words at the end", "preds = [\" \".join(x) for x in preds] predictions.extend(preds) cnt_corrections += cnt batch" ]
[ "commands will see the environment created by previous commands. The output of the", "testing client pip installation. :param bytes distribution: The distribution the node is running.", "= image @classmethod def from_distribution(cls, distribution): \"\"\" Create a DockerContainer with a given", "%s\\n\" % (base_path.basename(), e)) distribution = options['distribution'] package_source = options['package_source'] if options['pip']: get_steps", "<distribution> ' '[--branch <branch>] [--flocker-version <version>] ' '[--build-server <url>] [--pip]') def __init__(self, top_level):", "in the Docker container. The set of commands provided to one call of", "in which to create the script. :param Effect effects: An effect which contains", "distribution name. \"\"\" return cls(DOCKER_IMAGES[distribution].image) def start(self): \"\"\" Start the Docker container. \"\"\"", "self.container_id = container[u'Id'] self.docker.start( self.container_id, binds={ self.tmpdir: {'bind': '/mnt/script', 'ro': True}, } )", ":param bytes distribution: The distribution the node is running. :param PackageSource package_source: The", "top_level: The top-level of the Flocker repository. \"\"\" options = RunOptions(top_level=top_level) try: options.parseOptions(args)", "one for each command to run. :param out: Where to send command output.", "command to run. :param out: Where to send command output. Any object with", "See LICENSE file for details. \"\"\" Run the client installation tests. \"\"\" import", "correctly on any client platform can # be tricky. See # http://doc-dev.clusterhq.com/gettinginvolved/client-testing.html #", "\"\"\" return cls(DOCKER_IMAGES[distribution].image) def start(self): \"\"\" Start the Docker container. \"\"\" # On", "perform from twisted.python.usage import Options, UsageError from flocker.provision import PackageSource from flocker.provision._effect import", "base filename of the script. \"\"\" builder = ScriptBuilder(effects) fd, filename = tempfile.mkstemp(dir=directory,", "None, 'The target distribution. ' 'One of {}. With --pip, one of {}'.format(", "return self.docker.exec_inspect(session_id)[u'ExitCode'] class RunOptions(Options): description = \"Run the client tests.\" optParameters = [", "get_steps_pkg steps = get_steps(distribution, package_source) container = DockerContainer.from_distribution(distribution) status = run_steps(container, steps) sys.exit(status)", "supported. Available distributions: %s\" % (distribution, ', '.join(PIP_DISTRIBUTIONS))) package_manager = DOCKER_IMAGES[distribution].package_manager virtualenv =", "Although CentOS 7 is not a supported client distribution, the client # packages", "to create the script. :param Effect effects: An effect which contains the commands,", "] TypeDispatcher.__init__(self, { Run: self.perform_run, Sudo: perform_sudo, Put: perform_put, Comment: self.perform_comment, Sequence: perform_sequence", "Create a shell script file from a sequence of effects. :param bytes directory:", "top_level def postOptions(self): if self['distribution'] is None: raise UsageError(\"Distribution required.\") self['package_source'] = PackageSource(", "not supported. Available distributions: %s\" % (distribution, ', '.join(PACKAGED_CLIENT_DISTRIBUTIONS))) package_manager = DOCKER_IMAGES[distribution].package_manager steps", "The distribution the node is running. :param PackageSource package_source: The source from which", "for output in self.docker.exec_start(session, stream=True): out.write(output) return self.docker.exec_inspect(session_id)[u'ExitCode'] class RunOptions(Options): description = \"Run", "steps: status = container.execute(commands, out) if status != 0: return status finally: container.stop()", "@sync_performer def perform_comment(self, dispatcher, intent): \"\"\" For Comment effects, prefix the comment with", "__init__(self, image): # Getting Docker to work correctly on any client platform can", "of the script. \"\"\" builder = ScriptBuilder(effects) fd, filename = tempfile.mkstemp(dir=directory, text=True) os.write(fd,", "not supported. Available distributions: %s\" % (distribution, ', '.join(PIP_DISTRIBUTIONS))) package_manager = DOCKER_IMAGES[distribution].package_manager virtualenv", "installation tests. \"\"\" import os import shutil import sys import tempfile from characteristic", "package_manager='dnf'), 'ubuntu-14.04': DockerImage(image='ubuntu:14.04', package_manager='apt'), 'ubuntu-16.04': DockerImage(image='ubuntu:16.04', package_manager='apt'), } # No distribution is officially", "top-level of the Flocker repository. \"\"\" options = RunOptions(top_level=top_level) try: options.parseOptions(args) except UsageError", "environment created by previous commands. The output of the commands is sent to", "tests.\" optParameters = [ ['distribution', None, None, 'The target distribution. ' 'One of", "@classmethod def from_distribution(cls, distribution): \"\"\" Create a DockerContainer with a given distribution name.", "of steps. \"\"\" container.start() try: for commands in steps: status = container.execute(commands, out)", "provided to one call of ``execute`` will be executed in a single session.", "= self.docker.create_container( image=self.image, command='/bin/bash', tty=True, volumes=['/mnt/script'], ) self.container_id = container[u'Id'] self.docker.start( self.container_id, binds={", "None, None, 'Flocker version to install'], ['build-server', None, 'http://build.clusterhq.com/', 'Base URL of build", "self['package_source'] = PackageSource( version=self['flocker-version'], branch=self['branch'], build_server=self['build-server'], ) def get_steps_pip(distribution, package_source=PackageSource()): \"\"\" Get commands", "Stop the Docker container. \"\"\" self.docker.stop(self.container_id) self.docker.remove_container(self.container_id) shutil.rmtree(self.tmpdir) def execute(self, commands, out=sys.stdout): \"\"\"", "packages.'], ] synopsis = ('Usage: run-client-tests --distribution <distribution> ' '[--branch <branch>] [--flocker-version <version>]", "distributions: %s\" % (distribution, ', '.join(PACKAGED_CLIENT_DISTRIBUTIONS))) package_manager = DOCKER_IMAGES[distribution].package_manager steps = [ ensure_minimal_setup(package_manager),", "% (distribution, ', '.join(PIP_DISTRIBUTIONS))) package_manager = DOCKER_IMAGES[distribution].package_manager virtualenv = 'flocker-client' steps = [", ") except: os.rmdir(self.tmpdir) raise def stop(self): \"\"\" Stop the Docker container. \"\"\" self.docker.stop(self.container_id)", "\"\"\" Start the Docker container. \"\"\" # On OS X, shared volumes must", "import PackageSource from flocker.provision._effect import Sequence, perform_sequence from flocker.provision._install import ( ensure_minimal_setup, task_cli_pkg_install,", "raise UsageError(\"Distribution required.\") self['package_source'] = PackageSource( version=self['flocker-version'], branch=self['branch'], build_server=self['build-server'], ) def get_steps_pip(distribution, package_source=PackageSource()):", "and ``Put``. \"\"\" if distribution not in PIP_DISTRIBUTIONS: raise UsageError( \"Distribution %r not", "the test. :param Effect steps: Steps to to run the test. :param file", "terminate script with a newline self.lines.append('') self._script = '\\n'.join(self.lines) @sync_performer def perform_run(self, dispatcher,", "PIP_DISTRIBUTIONS = DOCKER_IMAGES.keys() # Some distributions have packages created for them. # Although", "{ 'centos-7': DockerImage(image='centos:7', package_manager='yum'), 'debian-8': DockerImage(image='debian:8', package_manager='apt'), 'fedora-22': DockerImage(image='fedora:22', package_manager='dnf'), 'ubuntu-14.04': DockerImage(image='ubuntu:14.04', package_manager='apt'),", "# No distribution is officially supported using pip, but the code can #", "call of ``execute`` will be executed in a single session. This means commands", "Stream to write output. :return int: Exit status of steps. \"\"\" container.start() try:", "is not a supported client distribution, the client # packages get built, and", "import ( ensure_minimal_setup, task_cli_pkg_install, task_cli_pip_prereqs, task_cli_pip_install, cli_pip_test, ) from flocker.provision._ssh import ( Run,", "class ScriptBuilder(TypeDispatcher): \"\"\" Convert an Effect sequence to a shell script. The effects", "the images. PIP_DISTRIBUTIONS = DOCKER_IMAGES.keys() # Some distributions have packages created for them.", "to run the test. :param Effect steps: Steps to to run the test.", "run_steps(container, steps, out=sys.stdout): \"\"\" Run a sequence of commands in a container. :param", "Run the client installation tests. \"\"\" import os import shutil import sys import", "distribution is officially supported using pip, but the code can # test the", "# Getting Docker to work correctly on any client platform can # be", "a DockerContainer with a given distribution name. \"\"\" return cls(DOCKER_IMAGES[distribution].image) def start(self): \"\"\"", "execute(self, commands, out=sys.stdout): \"\"\" Execute a set of commands in the Docker container.", "[ ['distribution', None, None, 'The target distribution. ' 'One of {}. With --pip,", "Start the Docker container. \"\"\" # On OS X, shared volumes must be", "'centos-7', 'ubuntu-14.04', 'ubuntu-16.04', ) class ScriptBuilder(TypeDispatcher): \"\"\" Convert an Effect sequence to a", "' '[--build-server <url>] [--pip]') def __init__(self, top_level): \"\"\" :param FilePath top_level: The top-level", "dispatcher, intent): \"\"\" For Comment effects, prefix the comment with # \"\"\" self.lines.append('#", "DockerContainer container: Container in which to run the test. :param Effect steps: Steps", "= DOCKER_IMAGES.keys() # Some distributions have packages created for them. # Although CentOS", "] return steps def run_steps(container, steps, out=sys.stdout): \"\"\" Run a sequence of commands", "out) if status != 0: return status finally: container.stop() return 0 def main(args,", "main(args, base_path, top_level): \"\"\" :param list args: The arguments passed to the script.", "options['distribution'] package_source = options['package_source'] if options['pip']: get_steps = get_steps_pip else: get_steps = get_steps_pkg", "'ro': True}, } ) except: os.rmdir(self.tmpdir) raise def stop(self): \"\"\" Stop the Docker", "and can be tested. PACKAGED_CLIENT_DISTRIBUTIONS = ( 'centos-7', 'ubuntu-14.04', 'ubuntu-16.04', ) class ScriptBuilder(TypeDispatcher):", "If all commands succeed, this will be zero. If any command fails, this", "is officially supported using pip, but the code can # test the pip", "' 'One of {}. With --pip, one of {}'.format( ', '.join(PACKAGED_CLIENT_DISTRIBUTIONS), ', '.join(PIP_DISTRIBUTIONS))],", ":param FilePath base_path: The executable being run. :param FilePath top_level: The top-level of", "status != 0: return status finally: container.stop() return 0 def main(args, base_path, top_level):", "comment with # \"\"\" self.lines.append('# ' + intent.comment) def script(self): \"\"\" Return the", "# test the pip instructions using any of the images. PIP_DISTRIBUTIONS = DOCKER_IMAGES.keys()", "= tempfile.mkdtemp(dir=os.path.expanduser('~')) try: self.docker.pull(self.image) container = self.docker.create_container( image=self.image, command='/bin/bash', tty=True, volumes=['/mnt/script'], ) self.container_id", "docker.utils.kwargs_from_env(assert_hostname=False) self.docker = docker.Client(version='1.16', **params) self.image = image @classmethod def from_distribution(cls, distribution): \"\"\"", "command output. Any object with a ``write`` method. :return int: The exit status", "With --pip, one of {}'.format( ', '.join(PACKAGED_CLIENT_DISTRIBUTIONS), ', '.join(PIP_DISTRIBUTIONS))], ['branch', None, None, 'Branch", "repository. \"\"\" Options.__init__(self) self.top_level = top_level def postOptions(self): if self['distribution'] is None: raise", "None, None, 'The target distribution. ' 'One of {}. With --pip, one of", "image information.\"\"\" DOCKER_IMAGES = { 'centos-7': DockerImage(image='centos:7', package_manager='yum'), 'debian-8': DockerImage(image='debian:8', package_manager='apt'), 'fedora-22': DockerImage(image='fedora:22',", "self.lines.append('') self._script = '\\n'.join(self.lines) @sync_performer def perform_run(self, dispatcher, intent): \"\"\" For Run effects,", "effects): \"\"\" Create a shell script file from a sequence of effects. :param", "in a container. :param DockerContainer container: Container in which to run the test.", "method. :return int: The exit status of the commands. If all commands succeed,", "= [ ensure_minimal_setup(package_manager), task_cli_pkg_install(distribution, package_source), ] return steps def run_steps(container, steps, out=sys.stdout): \"\"\"", "The source from which to install the package. :return: An ``Effect`` to pass", "intent.comment) def script(self): \"\"\" Return the generated shell script. \"\"\" return self._script def", ":return: An ``Effect`` to pass to a ``Dispatcher`` that supports ``Sequence``, ``Run``, ``Sudo``,", "the client installation tests. \"\"\" import os import shutil import sys import tempfile", "shutil.rmtree(self.tmpdir) def execute(self, commands, out=sys.stdout): \"\"\" Execute a set of commands in the", "{ Run: self.perform_run, Sudo: perform_sudo, Put: perform_put, Comment: self.perform_comment, Sequence: perform_sequence }) perform(self,", "is sent to the ``out`` file object, which must have a ``write`` method.", "to run. :param out: Where to send command output. Any object with a", "rather than packages.'], ] synopsis = ('Usage: run-client-tests --distribution <distribution> ' '[--branch <branch>]", "to run for testing client pip installation. :param bytes distribution: The distribution the", "with a given distribution name. \"\"\" return cls(DOCKER_IMAGES[distribution].image) def start(self): \"\"\" Start the", "for package downloads'], ] optFlags = [ ['pip', None, 'Install using pip rather", "shell script. \"\"\" return self._script def make_script_file(directory, effects): \"\"\" Create a shell script", "{}'.format( ', '.join(PACKAGED_CLIENT_DISTRIBUTIONS), ', '.join(PIP_DISTRIBUTIONS))], ['branch', None, None, 'Branch to grab packages from'],", "those defined in flocker.provision._effect and flocker.provision._ssh._model. \"\"\" def __init__(self, effects): self.lines = [", "to install the package. :return: An ``Effect`` to pass to a ``Dispatcher`` that", "virtualenv = 'flocker-client' steps = [ ensure_minimal_setup(package_manager), task_cli_pip_prereqs(package_manager), task_cli_pip_install(virtualenv, package_source), cli_pip_test(virtualenv, package_source), ]", "ensure_minimal_setup(package_manager), task_cli_pkg_install(distribution, package_source), ] return steps def run_steps(container, steps, out=sys.stdout): \"\"\" Run a", "test. :param file out: Stream to write output. :return int: Exit status of", "in flocker.provision._effect and flocker.provision._ssh._model. \"\"\" def __init__(self, effects): self.lines = [ '#!/bin/bash', 'set", "for commands in steps: status = container.execute(commands, out) if status != 0: return", "script) session_id = session[u'Id'] for output in self.docker.exec_start(session, stream=True): out.write(output) return self.docker.exec_inspect(session_id)[u'ExitCode'] class", "to pass to a ``Dispatcher`` that supports ``Sequence``, ``Run``, ``Sudo``, ``Comment``, and ``Put``.", "will be non-zero. \"\"\" script_file = make_script_file(self.tmpdir, commands) script = '/mnt/script/{}'.format(script_file) session =", "using any of the images. PIP_DISTRIBUTIONS = DOCKER_IMAGES.keys() # Some distributions have packages", "Run commands in a Docker container. \"\"\" def __init__(self, image): # Getting Docker", "= '/mnt/script/{}'.format(script_file) session = self.docker.exec_create(self.container_id, script) session_id = session[u'Id'] for output in self.docker.exec_start(session,", "def get_steps_pkg(distribution, package_source=PackageSource()): \"\"\" Get commands to run for testing client package installation.", "in PIP_DISTRIBUTIONS: raise UsageError( \"Distribution %r not supported. Available distributions: %s\" % (distribution,", "True}, } ) except: os.rmdir(self.tmpdir) raise def stop(self): \"\"\" Stop the Docker container.", "import Sequence, perform_sequence from flocker.provision._install import ( ensure_minimal_setup, task_cli_pkg_install, task_cli_pip_prereqs, task_cli_pip_install, cli_pip_test, )", "['branch', None, None, 'Branch to grab packages from'], ['flocker-version', None, None, 'Flocker version", "packages get built, and can be tested. PACKAGED_CLIENT_DISTRIBUTIONS = ( 'centos-7', 'ubuntu-14.04', 'ubuntu-16.04',", "exit status of the commands. If all commands succeed, this will be zero.", "perform_sequence from flocker.provision._install import ( ensure_minimal_setup, task_cli_pkg_install, task_cli_pip_prereqs, task_cli_pip_install, cli_pip_test, ) from flocker.provision._ssh", "__init__(self, effects): self.lines = [ '#!/bin/bash', 'set -ex' ] TypeDispatcher.__init__(self, { Run: self.perform_run,", "Effect steps: Steps to to run the test. :param file out: Stream to", "characteristic import attributes import docker from effect import TypeDispatcher, sync_performer, perform from twisted.python.usage", "# \"\"\" self.lines.append('# ' + intent.comment) def script(self): \"\"\" Return the generated shell", "perform_put) @attributes(['image', 'package_manager']) class DockerImage(object): \"\"\"Holder for Docker image information.\"\"\" DOCKER_IMAGES = {", "\"\"\" options = RunOptions(top_level=top_level) try: options.parseOptions(args) except UsageError as e: sys.exit(\"%s: %s\\n\" %", "distribution not in PACKAGED_CLIENT_DISTRIBUTIONS: raise UsageError( \"Distribution %r not supported. Available distributions: %s\"", "commands: An Effect containing the commands to run, probably a Sequence of Effects,", "Docker container. \"\"\" def __init__(self, image): # Getting Docker to work correctly on", "DockerImage(image='fedora:22', package_manager='dnf'), 'ubuntu-14.04': DockerImage(image='ubuntu:14.04', package_manager='apt'), 'ubuntu-16.04': DockerImage(image='ubuntu:16.04', package_manager='apt'), } # No distribution is", "The set of commands provided to one call of ``execute`` will be executed", "tempfile from characteristic import attributes import docker from effect import TypeDispatcher, sync_performer, perform", "DockerContainer with a given distribution name. \"\"\" return cls(DOCKER_IMAGES[distribution].image) def start(self): \"\"\" Start", "self.docker.exec_start(session, stream=True): out.write(output) return self.docker.exec_inspect(session_id)[u'ExitCode'] class RunOptions(Options): description = \"Run the client tests.\"", "Flocker repository. \"\"\" options = RunOptions(top_level=top_level) try: options.parseOptions(args) except UsageError as e: sys.exit(\"%s:", "client # packages get built, and can be tested. PACKAGED_CLIENT_DISTRIBUTIONS = ( 'centos-7',", "packages from'], ['flocker-version', None, None, 'Flocker version to install'], ['build-server', None, 'http://build.clusterhq.com/', 'Base", "required.\") self['package_source'] = PackageSource( version=self['flocker-version'], branch=self['branch'], build_server=self['build-server'], ) def get_steps_pip(distribution, package_source=PackageSource()): \"\"\" Get", "one of {}'.format( ', '.join(PACKAGED_CLIENT_DISTRIBUTIONS), ', '.join(PIP_DISTRIBUTIONS))], ['branch', None, None, 'Branch to grab", "directory in which to create the script. :param Effect effects: An effect which", "the generated shell script. \"\"\" return self._script def make_script_file(directory, effects): \"\"\" Create a", "blank line to terminate script with a newline self.lines.append('') self._script = '\\n'.join(self.lines) @sync_performer", "script. \"\"\" return self._script def make_script_file(directory, effects): \"\"\" Create a shell script file", "def make_script_file(directory, effects): \"\"\" Create a shell script file from a sequence of", "self.docker.create_container( image=self.image, command='/bin/bash', tty=True, volumes=['/mnt/script'], ) self.container_id = container[u'Id'] self.docker.start( self.container_id, binds={ self.tmpdir:", "= '\\n'.join(self.lines) @sync_performer def perform_run(self, dispatcher, intent): \"\"\" For Run effects, add the", "out: Stream to write output. :return int: Exit status of steps. \"\"\" container.start()", "passed to the script. :param FilePath base_path: The executable being run. :param FilePath", "UsageError as e: sys.exit(\"%s: %s\\n\" % (base_path.basename(), e)) distribution = options['distribution'] package_source =", "The top-level of the Flocker repository. \"\"\" options = RunOptions(top_level=top_level) try: options.parseOptions(args) except", "``Dispatcher`` that supports ``Sequence``, ``Run``, ``Sudo``, ``Comment``, and ``Put``. \"\"\" if distribution not", "supported client distribution, the client # packages get built, and can be tested.", "the comment with # \"\"\" self.lines.append('# ' + intent.comment) def script(self): \"\"\" Return", "image): # Getting Docker to work correctly on any client platform can #", "commands to run for testing client pip installation. :param bytes distribution: The distribution", "Run: self.perform_run, Sudo: perform_sudo, Put: perform_put, Comment: self.perform_comment, Sequence: perform_sequence }) perform(self, effects)", "optParameters = [ ['distribution', None, None, 'The target distribution. ' 'One of {}.", "\"\"\" def __init__(self, effects): self.lines = [ '#!/bin/bash', 'set -ex' ] TypeDispatcher.__init__(self, {", "must have a ``write`` method. :param Effect commands: An Effect containing the commands", "the flocker repository. \"\"\" Options.__init__(self) self.top_level = top_level def postOptions(self): if self['distribution'] is", "tempfile.mkdtemp(dir=os.path.expanduser('~')) try: self.docker.pull(self.image) container = self.docker.create_container( image=self.image, command='/bin/bash', tty=True, volumes=['/mnt/script'], ) self.container_id =", "\"\"\" if distribution not in PACKAGED_CLIENT_DISTRIBUTIONS: raise UsageError( \"Distribution %r not supported. Available", "None, 'Branch to grab packages from'], ['flocker-version', None, None, 'Flocker version to install'],", "FilePath base_path: The executable being run. :param FilePath top_level: The top-level of the", "pip rather than packages.'], ] synopsis = ('Usage: run-client-tests --distribution <distribution> ' '[--branch", "= \"Run the client tests.\" optParameters = [ ['distribution', None, None, 'The target", "to one call of ``execute`` will be executed in a single session. This", "The top-level of the flocker repository. \"\"\" Options.__init__(self) self.top_level = top_level def postOptions(self):", "except UsageError as e: sys.exit(\"%s: %s\\n\" % (base_path.basename(), e)) distribution = options['distribution'] package_source", "the ``out`` file object, which must have a ``write`` method. :param Effect commands:", "flocker.provision._install import ( ensure_minimal_setup, task_cli_pkg_install, task_cli_pip_prereqs, task_cli_pip_install, cli_pip_test, ) from flocker.provision._ssh import (", "'debian-8': DockerImage(image='debian:8', package_manager='apt'), 'fedora-22': DockerImage(image='fedora:22', package_manager='dnf'), 'ubuntu-14.04': DockerImage(image='ubuntu:14.04', package_manager='apt'), 'ubuntu-16.04': DockerImage(image='ubuntu:16.04', package_manager='apt'), }", "= get_steps_pkg steps = get_steps(distribution, package_source) container = DockerContainer.from_distribution(distribution) status = run_steps(container, steps)", "commands to run, probably a Sequence of Effects, one for each command to", "self.tmpdir: {'bind': '/mnt/script', 'ro': True}, } ) except: os.rmdir(self.tmpdir) raise def stop(self): \"\"\"", "output of the commands is sent to the ``out`` file object, which must", "to terminate script with a newline self.lines.append('') self._script = '\\n'.join(self.lines) @sync_performer def perform_run(self,", "'http://build.clusterhq.com/', 'Base URL of build server for package downloads'], ] optFlags = [", "sequence to a shell script. The effects are those defined in flocker.provision._effect and", "tempfile.mkstemp(dir=directory, text=True) os.write(fd, builder.script()) os.close(fd) os.chmod(filename, 0555) return os.path.basename(filename) class DockerContainer: \"\"\" Run", "raise UsageError( \"Distribution %r not supported. Available distributions: %s\" % (distribution, ', '.join(PIP_DISTRIBUTIONS)))", "flocker.provision._effect and flocker.provision._ssh._model. \"\"\" def __init__(self, effects): self.lines = [ '#!/bin/bash', 'set -ex'", "Some distributions have packages created for them. # Although CentOS 7 is not", "docker.Client(version='1.16', **params) self.image = image @classmethod def from_distribution(cls, distribution): \"\"\" Create a DockerContainer", "= [ ensure_minimal_setup(package_manager), task_cli_pip_prereqs(package_manager), task_cli_pip_install(virtualenv, package_source), cli_pip_test(virtualenv, package_source), ] return steps def get_steps_pkg(distribution,", "DockerContainer: \"\"\" Run commands in a Docker container. \"\"\" def __init__(self, image): #", "supports ``Sequence``, ``Run``, ``Sudo``, ``Comment``, and ``Put``. \"\"\" if distribution not in PACKAGED_CLIENT_DISTRIBUTIONS:", "= RunOptions(top_level=top_level) try: options.parseOptions(args) except UsageError as e: sys.exit(\"%s: %s\\n\" % (base_path.basename(), e))", "in steps: status = container.execute(commands, out) if status != 0: return status finally:", "one call of ``execute`` will be executed in a single session. This means", "steps = [ ensure_minimal_setup(package_manager), task_cli_pip_prereqs(package_manager), task_cli_pip_install(virtualenv, package_source), cli_pip_test(virtualenv, package_source), ] return steps def", "script. :param Effect effects: An effect which contains the commands, typically a Sequence", "\"\"\" container.start() try: for commands in steps: status = container.execute(commands, out) if status", "self.lines = [ '#!/bin/bash', 'set -ex' ] TypeDispatcher.__init__(self, { Run: self.perform_run, Sudo: perform_sudo,", "and flocker.provision._ssh._model. \"\"\" def __init__(self, effects): self.lines = [ '#!/bin/bash', 'set -ex' ]", ":param Effect effects: An effect which contains the commands, typically a Sequence containing", "ScriptBuilder(effects) fd, filename = tempfile.mkstemp(dir=directory, text=True) os.write(fd, builder.script()) os.close(fd) os.chmod(filename, 0555) return os.path.basename(filename)", "The exit status of the commands. If all commands succeed, this will be", "Effect sequence to a shell script. The effects are those defined in flocker.provision._effect", "target distribution. ' 'One of {}. With --pip, one of {}'.format( ', '.join(PACKAGED_CLIENT_DISTRIBUTIONS),", "bytes distribution: The distribution the node is running. :param PackageSource package_source: The source", "``Run``, ``Sudo``, ``Comment``, and ``Put``. \"\"\" if distribution not in PACKAGED_CLIENT_DISTRIBUTIONS: raise UsageError(", "\"\"\" # On OS X, shared volumes must be in /Users, so use", "not in PACKAGED_CLIENT_DISTRIBUTIONS: raise UsageError( \"Distribution %r not supported. Available distributions: %s\" %", "as e: sys.exit(\"%s: %s\\n\" % (base_path.basename(), e)) distribution = options['distribution'] package_source = options['package_source']", "from effect import TypeDispatcher, sync_performer, perform from twisted.python.usage import Options, UsageError from flocker.provision", "task_cli_pip_install, cli_pip_test, ) from flocker.provision._ssh import ( Run, Sudo, Put, Comment, perform_sudo, perform_put)", "Create a DockerContainer with a given distribution name. \"\"\" return cls(DOCKER_IMAGES[distribution].image) def start(self):", "to a shell script. The effects are those defined in flocker.provision._effect and flocker.provision._ssh._model.", "for details. params = docker.utils.kwargs_from_env(assert_hostname=False) self.docker = docker.Client(version='1.16', **params) self.image = image @classmethod", "a Sequence of Effects, one for each command to run. :param out: Where", "to run for testing client package installation. :param bytes distribution: The distribution the", "a container. :param DockerContainer container: Container in which to run the test. :param", "e)) distribution = options['distribution'] package_source = options['package_source'] if options['pip']: get_steps = get_steps_pip else:", "``Put``. \"\"\" if distribution not in PIP_DISTRIBUTIONS: raise UsageError( \"Distribution %r not supported.", "\"\"\" Convert an Effect sequence to a shell script. The effects are those", "} ) except: os.rmdir(self.tmpdir) raise def stop(self): \"\"\" Stop the Docker container. \"\"\"", "base_path, top_level): \"\"\" :param list args: The arguments passed to the script. :param", "from flocker.provision._ssh import ( Run, Sudo, Put, Comment, perform_sudo, perform_put) @attributes(['image', 'package_manager']) class", "int: Exit status of steps. \"\"\" container.start() try: for commands in steps: status", "commands is sent to the ``out`` file object, which must have a ``write``", "self.top_level = top_level def postOptions(self): if self['distribution'] is None: raise UsageError(\"Distribution required.\") self['package_source']", "fd, filename = tempfile.mkstemp(dir=directory, text=True) os.write(fd, builder.script()) os.close(fd) os.chmod(filename, 0555) return os.path.basename(filename) class", "2015 ClusterHQ Inc. See LICENSE file for details. \"\"\" Run the client installation", "tests. \"\"\" import os import shutil import sys import tempfile from characteristic import", "client pip installation. :param bytes distribution: The distribution the node is running. :param", "commands) script = '/mnt/script/{}'.format(script_file) session = self.docker.exec_create(self.container_id, script) session_id = session[u'Id'] for output", "which to install the package. :return: An ``Effect`` to pass to a ``Dispatcher``", "import tempfile from characteristic import attributes import docker from effect import TypeDispatcher, sync_performer,", "[ ensure_minimal_setup(package_manager), task_cli_pkg_install(distribution, package_source), ] return steps def run_steps(container, steps, out=sys.stdout): \"\"\" Run", "<version>] ' '[--build-server <url>] [--pip]') def __init__(self, top_level): \"\"\" :param FilePath top_level: The", "'/mnt/script', 'ro': True}, } ) except: os.rmdir(self.tmpdir) raise def stop(self): \"\"\" Stop the", "to run the test. :param file out: Stream to write output. :return int:", "downloads'], ] optFlags = [ ['pip', None, 'Install using pip rather than packages.'],", "run the test. :param Effect steps: Steps to to run the test. :param", "get_steps_pip(distribution, package_source=PackageSource()): \"\"\" Get commands to run for testing client pip installation. :param", "not in PIP_DISTRIBUTIONS: raise UsageError( \"Distribution %r not supported. Available distributions: %s\" %", "Sequence: perform_sequence }) perform(self, effects) # Add blank line to terminate script with", "\"\"\" import os import shutil import sys import tempfile from characteristic import attributes", "distribution: The distribution the node is running. :param PackageSource package_source: The source from", "\"Run the client tests.\" optParameters = [ ['distribution', None, None, 'The target distribution.", "(base_path.basename(), e)) distribution = options['distribution'] package_source = options['package_source'] if options['pip']: get_steps = get_steps_pip", "method. :param Effect commands: An Effect containing the commands to run, probably a", "can # be tricky. See # http://doc-dev.clusterhq.com/gettinginvolved/client-testing.html # for details. params = docker.utils.kwargs_from_env(assert_hostname=False)", "status = container.execute(commands, out) if status != 0: return status finally: container.stop() return", "using pip rather than packages.'], ] synopsis = ('Usage: run-client-tests --distribution <distribution> '", "import shutil import sys import tempfile from characteristic import attributes import docker from", "a sequence of effects. :param bytes directory: The directory in which to create", "the Docker container. \"\"\" # On OS X, shared volumes must be in", "'ubuntu-16.04': DockerImage(image='ubuntu:16.04', package_manager='apt'), } # No distribution is officially supported using pip, but", "package_manager='apt'), } # No distribution is officially supported using pip, but the code", "an Effect sequence to a shell script. The effects are those defined in", "%r not supported. Available distributions: %s\" % (distribution, ', '.join(PIP_DISTRIBUTIONS))) package_manager = DOCKER_IMAGES[distribution].package_manager", "file for details. \"\"\" Run the client installation tests. \"\"\" import os import", "= ScriptBuilder(effects) fd, filename = tempfile.mkstemp(dir=directory, text=True) os.write(fd, builder.script()) os.close(fd) os.chmod(filename, 0555) return", "data volume' at # https://docs.docker.com/userguide/dockervolumes/ self.tmpdir = tempfile.mkdtemp(dir=os.path.expanduser('~')) try: self.docker.pull(self.image) container = self.docker.create_container(", "7 is not a supported client distribution, the client # packages get built,", "Comment: self.perform_comment, Sequence: perform_sequence }) perform(self, effects) # Add blank line to terminate", "\"\"\" Run commands in a Docker container. \"\"\" def __init__(self, image): # Getting", "the Docker container. \"\"\" self.docker.stop(self.container_id) self.docker.remove_container(self.container_id) shutil.rmtree(self.tmpdir) def execute(self, commands, out=sys.stdout): \"\"\" Execute", "Add blank line to terminate script with a newline self.lines.append('') self._script = '\\n'.join(self.lines)", "from a sequence of effects. :param bytes directory: The directory in which to", "get_steps_pkg(distribution, package_source=PackageSource()): \"\"\" Get commands to run for testing client package installation. :param", "package_manager='yum'), 'debian-8': DockerImage(image='debian:8', package_manager='apt'), 'fedora-22': DockerImage(image='fedora:22', package_manager='dnf'), 'ubuntu-14.04': DockerImage(image='ubuntu:14.04', package_manager='apt'), 'ubuntu-16.04': DockerImage(image='ubuntu:16.04', package_manager='apt'),", "steps def run_steps(container, steps, out=sys.stdout): \"\"\" Run a sequence of commands in a", "CentOS 7 is not a supported client distribution, the client # packages get", "that supports ``Sequence``, ``Run``, ``Sudo``, ``Comment``, and ``Put``. \"\"\" if distribution not in", "The output of the commands is sent to the ``out`` file object, which", "flocker.provision._ssh._model. \"\"\" def __init__(self, effects): self.lines = [ '#!/bin/bash', 'set -ex' ] TypeDispatcher.__init__(self,", "self.perform_run, Sudo: perform_sudo, Put: perform_put, Comment: self.perform_comment, Sequence: perform_sequence }) perform(self, effects) #", "perform_run(self, dispatcher, intent): \"\"\" For Run effects, add the command line. \"\"\" self.lines.append(intent.command)", "effects. :param bytes directory: The directory in which to create the script. :param", "session_id = session[u'Id'] for output in self.docker.exec_start(session, stream=True): out.write(output) return self.docker.exec_inspect(session_id)[u'ExitCode'] class RunOptions(Options):", "top_level): \"\"\" :param FilePath top_level: The top-level of the flocker repository. \"\"\" Options.__init__(self)", "perform_sudo, perform_put) @attributes(['image', 'package_manager']) class DockerImage(object): \"\"\"Holder for Docker image information.\"\"\" DOCKER_IMAGES =", "Execute a set of commands in the Docker container. The set of commands", "package_source=PackageSource()): \"\"\" Get commands to run for testing client pip installation. :param bytes", "typically a Sequence containing multiple commands. :return: The base filename of the script.", "task_cli_pkg_install(distribution, package_source), ] return steps def run_steps(container, steps, out=sys.stdout): \"\"\" Run a sequence", "can be tested. PACKAGED_CLIENT_DISTRIBUTIONS = ( 'centos-7', 'ubuntu-14.04', 'ubuntu-16.04', ) class ScriptBuilder(TypeDispatcher): \"\"\"", "params = docker.utils.kwargs_from_env(assert_hostname=False) self.docker = docker.Client(version='1.16', **params) self.image = image @classmethod def from_distribution(cls,", "\"\"\" :param list args: The arguments passed to the script. :param FilePath base_path:", "flocker.provision import PackageSource from flocker.provision._effect import Sequence, perform_sequence from flocker.provision._install import ( ensure_minimal_setup,", "installation. :param bytes distribution: The distribution the node is running. :param PackageSource package_source:", "make_script_file(directory, effects): \"\"\" Create a shell script file from a sequence of effects.", "%s\" % (distribution, ', '.join(PIP_DISTRIBUTIONS))) package_manager = DOCKER_IMAGES[distribution].package_manager virtualenv = 'flocker-client' steps =", "import sys import tempfile from characteristic import attributes import docker from effect import", "os.rmdir(self.tmpdir) raise def stop(self): \"\"\" Stop the Docker container. \"\"\" self.docker.stop(self.container_id) self.docker.remove_container(self.container_id) shutil.rmtree(self.tmpdir)", "For Run effects, add the command line. \"\"\" self.lines.append(intent.command) @sync_performer def perform_comment(self, dispatcher,", "home directory. # See 'Mount a host directory as a data volume' at", "# https://docs.docker.com/userguide/dockervolumes/ self.tmpdir = tempfile.mkdtemp(dir=os.path.expanduser('~')) try: self.docker.pull(self.image) container = self.docker.create_container( image=self.image, command='/bin/bash', tty=True,", "test the pip instructions using any of the images. PIP_DISTRIBUTIONS = DOCKER_IMAGES.keys() #", "\"\"\" if distribution not in PIP_DISTRIBUTIONS: raise UsageError( \"Distribution %r not supported. Available", "file out: Stream to write output. :return int: Exit status of steps. \"\"\"", "( 'centos-7', 'ubuntu-14.04', 'ubuntu-16.04', ) class ScriptBuilder(TypeDispatcher): \"\"\" Convert an Effect sequence to", "\"\"\" For Comment effects, prefix the comment with # \"\"\" self.lines.append('# ' +", "in PACKAGED_CLIENT_DISTRIBUTIONS: raise UsageError( \"Distribution %r not supported. Available distributions: %s\" % (distribution,", "\"Distribution %r not supported. Available distributions: %s\" % (distribution, ', '.join(PIP_DISTRIBUTIONS))) package_manager =", "tricky. See # http://doc-dev.clusterhq.com/gettinginvolved/client-testing.html # for details. params = docker.utils.kwargs_from_env(assert_hostname=False) self.docker = docker.Client(version='1.16',", "flocker.provision._ssh import ( Run, Sudo, Put, Comment, perform_sudo, perform_put) @attributes(['image', 'package_manager']) class DockerImage(object):", "multiple commands. :return: The base filename of the script. \"\"\" builder = ScriptBuilder(effects)", "status of the commands. If all commands succeed, this will be zero. If", "<branch>] [--flocker-version <version>] ' '[--build-server <url>] [--pip]') def __init__(self, top_level): \"\"\" :param FilePath", "int: The exit status of the commands. If all commands succeed, this will", "package installation. :param bytes distribution: The distribution the node is running. :param PackageSource", "``Sudo``, ``Comment``, and ``Put``. \"\"\" if distribution not in PIP_DISTRIBUTIONS: raise UsageError( \"Distribution", "commands to run for testing client package installation. :param bytes distribution: The distribution", "= docker.Client(version='1.16', **params) self.image = image @classmethod def from_distribution(cls, distribution): \"\"\" Create a", "package_source: The source from which to install the package. :return: An ``Effect`` to", "shell script. The effects are those defined in flocker.provision._effect and flocker.provision._ssh._model. \"\"\" def", "can # test the pip instructions using any of the images. PIP_DISTRIBUTIONS =", "any client platform can # be tricky. See # http://doc-dev.clusterhq.com/gettinginvolved/client-testing.html # for details.", "of commands in the Docker container. The set of commands provided to one", "import docker from effect import TypeDispatcher, sync_performer, perform from twisted.python.usage import Options, UsageError", "officially supported using pip, but the code can # test the pip instructions", "package. :return: An ``Effect`` to pass to a ``Dispatcher`` that supports ``Sequence``, ``Run``,", "class DockerContainer: \"\"\" Run commands in a Docker container. \"\"\" def __init__(self, image):", "# On OS X, shared volumes must be in /Users, so use the", "\"\"\" builder = ScriptBuilder(effects) fd, filename = tempfile.mkstemp(dir=directory, text=True) os.write(fd, builder.script()) os.close(fd) os.chmod(filename,", "directory as a data volume' at # https://docs.docker.com/userguide/dockervolumes/ self.tmpdir = tempfile.mkdtemp(dir=os.path.expanduser('~')) try: self.docker.pull(self.image)", ") class ScriptBuilder(TypeDispatcher): \"\"\" Convert an Effect sequence to a shell script. The", "the client tests.\" optParameters = [ ['distribution', None, None, 'The target distribution. '", "``Comment``, and ``Put``. \"\"\" if distribution not in PACKAGED_CLIENT_DISTRIBUTIONS: raise UsageError( \"Distribution %r", "class DockerImage(object): \"\"\"Holder for Docker image information.\"\"\" DOCKER_IMAGES = { 'centos-7': DockerImage(image='centos:7', package_manager='yum'),", "any command fails, this will be non-zero. \"\"\" script_file = make_script_file(self.tmpdir, commands) script", "run, probably a Sequence of Effects, one for each command to run. :param", "a shell script. The effects are those defined in flocker.provision._effect and flocker.provision._ssh._model. \"\"\"", "Getting Docker to work correctly on any client platform can # be tricky.", "to grab packages from'], ['flocker-version', None, None, 'Flocker version to install'], ['build-server', None,", "self.docker.remove_container(self.container_id) shutil.rmtree(self.tmpdir) def execute(self, commands, out=sys.stdout): \"\"\" Execute a set of commands in", "if self['distribution'] is None: raise UsageError(\"Distribution required.\") self['package_source'] = PackageSource( version=self['flocker-version'], branch=self['branch'], build_server=self['build-server'],", "'Mount a host directory as a data volume' at # https://docs.docker.com/userguide/dockervolumes/ self.tmpdir =", "Any object with a ``write`` method. :return int: The exit status of the", "package_manager = DOCKER_IMAGES[distribution].package_manager virtualenv = 'flocker-client' steps = [ ensure_minimal_setup(package_manager), task_cli_pip_prereqs(package_manager), task_cli_pip_install(virtualenv, package_source),", "def __init__(self, effects): self.lines = [ '#!/bin/bash', 'set -ex' ] TypeDispatcher.__init__(self, { Run:", "None: raise UsageError(\"Distribution required.\") self['package_source'] = PackageSource( version=self['flocker-version'], branch=self['branch'], build_server=self['build-server'], ) def get_steps_pip(distribution,", "of commands in a container. :param DockerContainer container: Container in which to run", "FilePath top_level: The top-level of the flocker repository. \"\"\" Options.__init__(self) self.top_level = top_level", "effect which contains the commands, typically a Sequence containing multiple commands. :return: The", ":return: The base filename of the script. \"\"\" builder = ScriptBuilder(effects) fd, filename", "= ( 'centos-7', 'ubuntu-14.04', 'ubuntu-16.04', ) class ScriptBuilder(TypeDispatcher): \"\"\" Convert an Effect sequence", "os.path.basename(filename) class DockerContainer: \"\"\" Run commands in a Docker container. \"\"\" def __init__(self,", "'.join(PIP_DISTRIBUTIONS))], ['branch', None, None, 'Branch to grab packages from'], ['flocker-version', None, None, 'Flocker", "of build server for package downloads'], ] optFlags = [ ['pip', None, 'Install", "host directory as a data volume' at # https://docs.docker.com/userguide/dockervolumes/ self.tmpdir = tempfile.mkdtemp(dir=os.path.expanduser('~')) try:", "options = RunOptions(top_level=top_level) try: options.parseOptions(args) except UsageError as e: sys.exit(\"%s: %s\\n\" % (base_path.basename(),", "'The target distribution. ' 'One of {}. With --pip, one of {}'.format( ',", "get_steps_pip else: get_steps = get_steps_pkg steps = get_steps(distribution, package_source) container = DockerContainer.from_distribution(distribution) status", "An effect which contains the commands, typically a Sequence containing multiple commands. :return:", "PackageSource package_source: The source from which to install the package. :return: An ``Effect``", "script with a newline self.lines.append('') self._script = '\\n'.join(self.lines) @sync_performer def perform_run(self, dispatcher, intent):", "stream=True): out.write(output) return self.docker.exec_inspect(session_id)[u'ExitCode'] class RunOptions(Options): description = \"Run the client tests.\" optParameters", "a ``write`` method. :return int: The exit status of the commands. If all", "# be tricky. See # http://doc-dev.clusterhq.com/gettinginvolved/client-testing.html # for details. params = docker.utils.kwargs_from_env(assert_hostname=False) self.docker", "the code can # test the pip instructions using any of the images.", "newline self.lines.append('') self._script = '\\n'.join(self.lines) @sync_performer def perform_run(self, dispatcher, intent): \"\"\" For Run", "Run effects, add the command line. \"\"\" self.lines.append(intent.command) @sync_performer def perform_comment(self, dispatcher, intent):", "# packages get built, and can be tested. PACKAGED_CLIENT_DISTRIBUTIONS = ( 'centos-7', 'ubuntu-14.04',", "make_script_file(self.tmpdir, commands) script = '/mnt/script/{}'.format(script_file) session = self.docker.exec_create(self.container_id, script) session_id = session[u'Id'] for", "a given distribution name. \"\"\" return cls(DOCKER_IMAGES[distribution].image) def start(self): \"\"\" Start the Docker", "of the flocker repository. \"\"\" Options.__init__(self) self.top_level = top_level def postOptions(self): if self['distribution']", "UsageError(\"Distribution required.\") self['package_source'] = PackageSource( version=self['flocker-version'], branch=self['branch'], build_server=self['build-server'], ) def get_steps_pip(distribution, package_source=PackageSource()): \"\"\"", "volumes=['/mnt/script'], ) self.container_id = container[u'Id'] self.docker.start( self.container_id, binds={ self.tmpdir: {'bind': '/mnt/script', 'ro': True},", "build_server=self['build-server'], ) def get_steps_pip(distribution, package_source=PackageSource()): \"\"\" Get commands to run for testing client", "status finally: container.stop() return 0 def main(args, base_path, top_level): \"\"\" :param list args:", "``execute`` will be executed in a single session. This means commands will see", "the node is running. :param PackageSource package_source: The source from which to install", "cls(DOCKER_IMAGES[distribution].image) def start(self): \"\"\" Start the Docker container. \"\"\" # On OS X,", "package_source), cli_pip_test(virtualenv, package_source), ] return steps def get_steps_pkg(distribution, package_source=PackageSource()): \"\"\" Get commands to", "else: get_steps = get_steps_pkg steps = get_steps(distribution, package_source) container = DockerContainer.from_distribution(distribution) status =", "{'bind': '/mnt/script', 'ro': True}, } ) except: os.rmdir(self.tmpdir) raise def stop(self): \"\"\" Stop", "supported. Available distributions: %s\" % (distribution, ', '.join(PACKAGED_CLIENT_DISTRIBUTIONS))) package_manager = DOCKER_IMAGES[distribution].package_manager steps =", "def __init__(self, image): # Getting Docker to work correctly on any client platform", "the script. :param FilePath base_path: The executable being run. :param FilePath top_level: The", "Available distributions: %s\" % (distribution, ', '.join(PIP_DISTRIBUTIONS))) package_manager = DOCKER_IMAGES[distribution].package_manager virtualenv = 'flocker-client'", ":param Effect steps: Steps to to run the test. :param file out: Stream", "+ intent.comment) def script(self): \"\"\" Return the generated shell script. \"\"\" return self._script", "args: The arguments passed to the script. :param FilePath base_path: The executable being", "images. PIP_DISTRIBUTIONS = DOCKER_IMAGES.keys() # Some distributions have packages created for them. #", "defined in flocker.provision._effect and flocker.provision._ssh._model. \"\"\" def __init__(self, effects): self.lines = [ '#!/bin/bash',", "commands, out=sys.stdout): \"\"\" Execute a set of commands in the Docker container. The", "commands. If all commands succeed, this will be zero. If any command fails,", "Effect effects: An effect which contains the commands, typically a Sequence containing multiple", ") self.container_id = container[u'Id'] self.docker.start( self.container_id, binds={ self.tmpdir: {'bind': '/mnt/script', 'ro': True}, }", "volumes must be in /Users, so use the home directory. # See 'Mount", "= tempfile.mkstemp(dir=directory, text=True) os.write(fd, builder.script()) os.close(fd) os.chmod(filename, 0555) return os.path.basename(filename) class DockerContainer: \"\"\"", "= docker.utils.kwargs_from_env(assert_hostname=False) self.docker = docker.Client(version='1.16', **params) self.image = image @classmethod def from_distribution(cls, distribution):", "shutil import sys import tempfile from characteristic import attributes import docker from effect", "} # No distribution is officially supported using pip, but the code can", "self['distribution'] is None: raise UsageError(\"Distribution required.\") self['package_source'] = PackageSource( version=self['flocker-version'], branch=self['branch'], build_server=self['build-server'], )", "'.join(PACKAGED_CLIENT_DISTRIBUTIONS))) package_manager = DOCKER_IMAGES[distribution].package_manager steps = [ ensure_minimal_setup(package_manager), task_cli_pkg_install(distribution, package_source), ] return steps", "self._script = '\\n'.join(self.lines) @sync_performer def perform_run(self, dispatcher, intent): \"\"\" For Run effects, add", "client installation tests. \"\"\" import os import shutil import sys import tempfile from", "top_level): \"\"\" :param list args: The arguments passed to the script. :param FilePath", "Run a sequence of commands in a container. :param DockerContainer container: Container in", "The directory in which to create the script. :param Effect effects: An effect", "all commands succeed, this will be zero. If any command fails, this will", "image=self.image, command='/bin/bash', tty=True, volumes=['/mnt/script'], ) self.container_id = container[u'Id'] self.docker.start( self.container_id, binds={ self.tmpdir: {'bind':", "= [ ['pip', None, 'Install using pip rather than packages.'], ] synopsis =", "work correctly on any client platform can # be tricky. See # http://doc-dev.clusterhq.com/gettinginvolved/client-testing.html", "= options['distribution'] package_source = options['package_source'] if options['pip']: get_steps = get_steps_pip else: get_steps =", "created for them. # Although CentOS 7 is not a supported client distribution,", "task_cli_pip_prereqs(package_manager), task_cli_pip_install(virtualenv, package_source), cli_pip_test(virtualenv, package_source), ] return steps def get_steps_pkg(distribution, package_source=PackageSource()): \"\"\" Get", "def run_steps(container, steps, out=sys.stdout): \"\"\" Run a sequence of commands in a container.", "def stop(self): \"\"\" Stop the Docker container. \"\"\" self.docker.stop(self.container_id) self.docker.remove_container(self.container_id) shutil.rmtree(self.tmpdir) def execute(self,", "def get_steps_pip(distribution, package_source=PackageSource()): \"\"\" Get commands to run for testing client pip installation.", "task_cli_pip_install(virtualenv, package_source), cli_pip_test(virtualenv, package_source), ] return steps def get_steps_pkg(distribution, package_source=PackageSource()): \"\"\" Get commands", "means commands will see the environment created by previous commands. The output of", "\"\"\" script_file = make_script_file(self.tmpdir, commands) script = '/mnt/script/{}'.format(script_file) session = self.docker.exec_create(self.container_id, script) session_id", "Comment effects, prefix the comment with # \"\"\" self.lines.append('# ' + intent.comment) def", ":return int: The exit status of the commands. If all commands succeed, this", "None, 'Flocker version to install'], ['build-server', None, 'http://build.clusterhq.com/', 'Base URL of build server", ") from flocker.provision._ssh import ( Run, Sudo, Put, Comment, perform_sudo, perform_put) @attributes(['image', 'package_manager'])", "Get commands to run for testing client package installation. :param bytes distribution: The", "branch=self['branch'], build_server=self['build-server'], ) def get_steps_pip(distribution, package_source=PackageSource()): \"\"\" Get commands to run for testing", "in a Docker container. \"\"\" def __init__(self, image): # Getting Docker to work", "a data volume' at # https://docs.docker.com/userguide/dockervolumes/ self.tmpdir = tempfile.mkdtemp(dir=os.path.expanduser('~')) try: self.docker.pull(self.image) container =", "distributions: %s\" % (distribution, ', '.join(PIP_DISTRIBUTIONS))) package_manager = DOCKER_IMAGES[distribution].package_manager virtualenv = 'flocker-client' steps", "from twisted.python.usage import Options, UsageError from flocker.provision import PackageSource from flocker.provision._effect import Sequence,", "DOCKER_IMAGES.keys() # Some distributions have packages created for them. # Although CentOS 7", "self.docker = docker.Client(version='1.16', **params) self.image = image @classmethod def from_distribution(cls, distribution): \"\"\" Create", "self.tmpdir = tempfile.mkdtemp(dir=os.path.expanduser('~')) try: self.docker.pull(self.image) container = self.docker.create_container( image=self.image, command='/bin/bash', tty=True, volumes=['/mnt/script'], )", "``out`` file object, which must have a ``write`` method. :param Effect commands: An", "tty=True, volumes=['/mnt/script'], ) self.container_id = container[u'Id'] self.docker.start( self.container_id, binds={ self.tmpdir: {'bind': '/mnt/script', 'ro':", "be tested. PACKAGED_CLIENT_DISTRIBUTIONS = ( 'centos-7', 'ubuntu-14.04', 'ubuntu-16.04', ) class ScriptBuilder(TypeDispatcher): \"\"\" Convert", "client tests.\" optParameters = [ ['distribution', None, None, 'The target distribution. ' 'One", "This means commands will see the environment created by previous commands. The output", "dispatcher, intent): \"\"\" For Run effects, add the command line. \"\"\" self.lines.append(intent.command) @sync_performer", "'.join(PACKAGED_CLIENT_DISTRIBUTIONS), ', '.join(PIP_DISTRIBUTIONS))], ['branch', None, None, 'Branch to grab packages from'], ['flocker-version', None,", "be zero. If any command fails, this will be non-zero. \"\"\" script_file =", "] optFlags = [ ['pip', None, 'Install using pip rather than packages.'], ]", "% (base_path.basename(), e)) distribution = options['distribution'] package_source = options['package_source'] if options['pip']: get_steps =", "a set of commands in the Docker container. The set of commands provided", "= container.execute(commands, out) if status != 0: return status finally: container.stop() return 0", "pip installation. :param bytes distribution: The distribution the node is running. :param PackageSource", "= [ ['distribution', None, None, 'The target distribution. ' 'One of {}. With", "return cls(DOCKER_IMAGES[distribution].image) def start(self): \"\"\" Start the Docker container. \"\"\" # On OS", "a newline self.lines.append('') self._script = '\\n'.join(self.lines) @sync_performer def perform_run(self, dispatcher, intent): \"\"\" For", "the test. :param file out: Stream to write output. :return int: Exit status", "package_manager = DOCKER_IMAGES[distribution].package_manager steps = [ ensure_minimal_setup(package_manager), task_cli_pkg_install(distribution, package_source), ] return steps def", "[ ensure_minimal_setup(package_manager), task_cli_pip_prereqs(package_manager), task_cli_pip_install(virtualenv, package_source), cli_pip_test(virtualenv, package_source), ] return steps def get_steps_pkg(distribution, package_source=PackageSource()):", "container. \"\"\" def __init__(self, image): # Getting Docker to work correctly on any", "testing client package installation. :param bytes distribution: The distribution the node is running.", "each command to run. :param out: Where to send command output. Any object", "write output. :return int: Exit status of steps. \"\"\" container.start() try: for commands", "commands in a container. :param DockerContainer container: Container in which to run the", "class RunOptions(Options): description = \"Run the client tests.\" optParameters = [ ['distribution', None,", "--pip, one of {}'.format( ', '.join(PACKAGED_CLIENT_DISTRIBUTIONS), ', '.join(PIP_DISTRIBUTIONS))], ['branch', None, None, 'Branch to", "Sequence containing multiple commands. :return: The base filename of the script. \"\"\" builder", "be non-zero. \"\"\" script_file = make_script_file(self.tmpdir, commands) script = '/mnt/script/{}'.format(script_file) session = self.docker.exec_create(self.container_id,", "None, 'http://build.clusterhq.com/', 'Base URL of build server for package downloads'], ] optFlags =", "= get_steps_pip else: get_steps = get_steps_pkg steps = get_steps(distribution, package_source) container = DockerContainer.from_distribution(distribution)", "file from a sequence of effects. :param bytes directory: The directory in which", "%s\" % (distribution, ', '.join(PACKAGED_CLIENT_DISTRIBUTIONS))) package_manager = DOCKER_IMAGES[distribution].package_manager steps = [ ensure_minimal_setup(package_manager), task_cli_pkg_install(distribution,", "``Effect`` to pass to a ``Dispatcher`` that supports ``Sequence``, ``Run``, ``Sudo``, ``Comment``, and", "arguments passed to the script. :param FilePath base_path: The executable being run. :param", "effects are those defined in flocker.provision._effect and flocker.provision._ssh._model. \"\"\" def __init__(self, effects): self.lines", "Run, Sudo, Put, Comment, perform_sudo, perform_put) @attributes(['image', 'package_manager']) class DockerImage(object): \"\"\"Holder for Docker", "commands succeed, this will be zero. If any command fails, this will be", "try: options.parseOptions(args) except UsageError as e: sys.exit(\"%s: %s\\n\" % (base_path.basename(), e)) distribution =", "'ubuntu-14.04': DockerImage(image='ubuntu:14.04', package_manager='apt'), 'ubuntu-16.04': DockerImage(image='ubuntu:16.04', package_manager='apt'), } # No distribution is officially supported", "# Copyright 2015 ClusterHQ Inc. See LICENSE file for details. \"\"\" Run the", "-ex' ] TypeDispatcher.__init__(self, { Run: self.perform_run, Sudo: perform_sudo, Put: perform_put, Comment: self.perform_comment, Sequence:", "For Comment effects, prefix the comment with # \"\"\" self.lines.append('# ' + intent.comment)", "UsageError( \"Distribution %r not supported. Available distributions: %s\" % (distribution, ', '.join(PACKAGED_CLIENT_DISTRIBUTIONS))) package_manager", "\"\"\" Get commands to run for testing client package installation. :param bytes distribution:", "( Run, Sudo, Put, Comment, perform_sudo, perform_put) @attributes(['image', 'package_manager']) class DockerImage(object): \"\"\"Holder for", "the script. \"\"\" builder = ScriptBuilder(effects) fd, filename = tempfile.mkstemp(dir=directory, text=True) os.write(fd, builder.script())", "output in self.docker.exec_start(session, stream=True): out.write(output) return self.docker.exec_inspect(session_id)[u'ExitCode'] class RunOptions(Options): description = \"Run the", "Effects, one for each command to run. :param out: Where to send command", "a ``write`` method. :param Effect commands: An Effect containing the commands to run,", "% (distribution, ', '.join(PACKAGED_CLIENT_DISTRIBUTIONS))) package_manager = DOCKER_IMAGES[distribution].package_manager steps = [ ensure_minimal_setup(package_manager), task_cli_pkg_install(distribution, package_source),", "sequence of effects. :param bytes directory: The directory in which to create the", "steps: Steps to to run the test. :param file out: Stream to write", "start(self): \"\"\" Start the Docker container. \"\"\" # On OS X, shared volumes", "builder.script()) os.close(fd) os.chmod(filename, 0555) return os.path.basename(filename) class DockerContainer: \"\"\" Run commands in a", "steps def get_steps_pkg(distribution, package_source=PackageSource()): \"\"\" Get commands to run for testing client package", "# Some distributions have packages created for them. # Although CentOS 7 is", "container.start() try: for commands in steps: status = container.execute(commands, out) if status !=", "to work correctly on any client platform can # be tricky. See #", "options.parseOptions(args) except UsageError as e: sys.exit(\"%s: %s\\n\" % (base_path.basename(), e)) distribution = options['distribution']", "raise UsageError( \"Distribution %r not supported. Available distributions: %s\" % (distribution, ', '.join(PACKAGED_CLIENT_DISTRIBUTIONS)))", "built, and can be tested. PACKAGED_CLIENT_DISTRIBUTIONS = ( 'centos-7', 'ubuntu-14.04', 'ubuntu-16.04', ) class", "\"Distribution %r not supported. Available distributions: %s\" % (distribution, ', '.join(PACKAGED_CLIENT_DISTRIBUTIONS))) package_manager =", "= DOCKER_IMAGES[distribution].package_manager steps = [ ensure_minimal_setup(package_manager), task_cli_pkg_install(distribution, package_source), ] return steps def run_steps(container,", "to run, probably a Sequence of Effects, one for each command to run.", "to write output. :return int: Exit status of steps. \"\"\" container.start() try: for", "package_manager='apt'), 'ubuntu-16.04': DockerImage(image='ubuntu:16.04', package_manager='apt'), } # No distribution is officially supported using pip,", "commands provided to one call of ``execute`` will be executed in a single", "'/mnt/script/{}'.format(script_file) session = self.docker.exec_create(self.container_id, script) session_id = session[u'Id'] for output in self.docker.exec_start(session, stream=True):", "--distribution <distribution> ' '[--branch <branch>] [--flocker-version <version>] ' '[--build-server <url>] [--pip]') def __init__(self,", "except: os.rmdir(self.tmpdir) raise def stop(self): \"\"\" Stop the Docker container. \"\"\" self.docker.stop(self.container_id) self.docker.remove_container(self.container_id)", "URL of build server for package downloads'], ] optFlags = [ ['pip', None,", "Inc. See LICENSE file for details. \"\"\" Run the client installation tests. \"\"\"", "Where to send command output. Any object with a ``write`` method. :return int:", "list args: The arguments passed to the script. :param FilePath base_path: The executable", "Docker to work correctly on any client platform can # be tricky. See", "options['pip']: get_steps = get_steps_pip else: get_steps = get_steps_pkg steps = get_steps(distribution, package_source) container", "] synopsis = ('Usage: run-client-tests --distribution <distribution> ' '[--branch <branch>] [--flocker-version <version>] '", "container[u'Id'] self.docker.start( self.container_id, binds={ self.tmpdir: {'bind': '/mnt/script', 'ro': True}, } ) except: os.rmdir(self.tmpdir)", "directory: The directory in which to create the script. :param Effect effects: An", "RunOptions(Options): description = \"Run the client tests.\" optParameters = [ ['distribution', None, None,", "run. :param out: Where to send command output. Any object with a ``write``", "is running. :param PackageSource package_source: The source from which to install the package.", "``Sequence``, ``Run``, ``Sudo``, ``Comment``, and ``Put``. \"\"\" if distribution not in PIP_DISTRIBUTIONS: raise", "= DOCKER_IMAGES[distribution].package_manager virtualenv = 'flocker-client' steps = [ ensure_minimal_setup(package_manager), task_cli_pip_prereqs(package_manager), task_cli_pip_install(virtualenv, package_source), cli_pip_test(virtualenv,", "script file from a sequence of effects. :param bytes directory: The directory in", "add the command line. \"\"\" self.lines.append(intent.command) @sync_performer def perform_comment(self, dispatcher, intent): \"\"\" For", "to send command output. Any object with a ``write`` method. :return int: The", "None, 'Install using pip rather than packages.'], ] synopsis = ('Usage: run-client-tests --distribution", "``Sudo``, ``Comment``, and ``Put``. \"\"\" if distribution not in PACKAGED_CLIENT_DISTRIBUTIONS: raise UsageError( \"Distribution", "TypeDispatcher.__init__(self, { Run: self.perform_run, Sudo: perform_sudo, Put: perform_put, Comment: self.perform_comment, Sequence: perform_sequence })", "UsageError( \"Distribution %r not supported. Available distributions: %s\" % (distribution, ', '.join(PIP_DISTRIBUTIONS))) package_manager", "Steps to to run the test. :param file out: Stream to write output.", "of {}'.format( ', '.join(PACKAGED_CLIENT_DISTRIBUTIONS), ', '.join(PIP_DISTRIBUTIONS))], ['branch', None, None, 'Branch to grab packages", "running. :param PackageSource package_source: The source from which to install the package. :return:", "\"\"\" :param FilePath top_level: The top-level of the flocker repository. \"\"\" Options.__init__(self) self.top_level", "def script(self): \"\"\" Return the generated shell script. \"\"\" return self._script def make_script_file(directory,", ":param file out: Stream to write output. :return int: Exit status of steps.", "'Branch to grab packages from'], ['flocker-version', None, None, 'Flocker version to install'], ['build-server',", "X, shared volumes must be in /Users, so use the home directory. #", "self.docker.pull(self.image) container = self.docker.create_container( image=self.image, command='/bin/bash', tty=True, volumes=['/mnt/script'], ) self.container_id = container[u'Id'] self.docker.start(", "bytes directory: The directory in which to create the script. :param Effect effects:", "Sudo, Put, Comment, perform_sudo, perform_put) @attributes(['image', 'package_manager']) class DockerImage(object): \"\"\"Holder for Docker image", "containing the commands to run, probably a Sequence of Effects, one for each", "= 'flocker-client' steps = [ ensure_minimal_setup(package_manager), task_cli_pip_prereqs(package_manager), task_cli_pip_install(virtualenv, package_source), cli_pip_test(virtualenv, package_source), ] return", "directory. # See 'Mount a host directory as a data volume' at #", "client distribution, the client # packages get built, and can be tested. PACKAGED_CLIENT_DISTRIBUTIONS", "distributions have packages created for them. # Although CentOS 7 is not a", "perform_comment(self, dispatcher, intent): \"\"\" For Comment effects, prefix the comment with # \"\"\"", "', '.join(PACKAGED_CLIENT_DISTRIBUTIONS), ', '.join(PIP_DISTRIBUTIONS))], ['branch', None, None, 'Branch to grab packages from'], ['flocker-version',", "def from_distribution(cls, distribution): \"\"\" Create a DockerContainer with a given distribution name. \"\"\"", "'package_manager']) class DockerImage(object): \"\"\"Holder for Docker image information.\"\"\" DOCKER_IMAGES = { 'centos-7': DockerImage(image='centos:7',", "in a single session. This means commands will see the environment created by", "set of commands in the Docker container. The set of commands provided to", "ensure_minimal_setup(package_manager), task_cli_pip_prereqs(package_manager), task_cli_pip_install(virtualenv, package_source), cli_pip_test(virtualenv, package_source), ] return steps def get_steps_pkg(distribution, package_source=PackageSource()): \"\"\"", "= container[u'Id'] self.docker.start( self.container_id, binds={ self.tmpdir: {'bind': '/mnt/script', 'ro': True}, } ) except:", "('Usage: run-client-tests --distribution <distribution> ' '[--branch <branch>] [--flocker-version <version>] ' '[--build-server <url>] [--pip]')", "command='/bin/bash', tty=True, volumes=['/mnt/script'], ) self.container_id = container[u'Id'] self.docker.start( self.container_id, binds={ self.tmpdir: {'bind': '/mnt/script',", ":param PackageSource package_source: The source from which to install the package. :return: An", "'[--branch <branch>] [--flocker-version <version>] ' '[--build-server <url>] [--pip]') def __init__(self, top_level): \"\"\" :param", "image @classmethod def from_distribution(cls, distribution): \"\"\" Create a DockerContainer with a given distribution", "commands in the Docker container. The set of commands provided to one call", "package_manager='apt'), 'fedora-22': DockerImage(image='fedora:22', package_manager='dnf'), 'ubuntu-14.04': DockerImage(image='ubuntu:14.04', package_manager='apt'), 'ubuntu-16.04': DockerImage(image='ubuntu:16.04', package_manager='apt'), } # No", "' '[--branch <branch>] [--flocker-version <version>] ' '[--build-server <url>] [--pip]') def __init__(self, top_level): \"\"\"", "client package installation. :param bytes distribution: The distribution the node is running. :param", "Comment, perform_sudo, perform_put) @attributes(['image', 'package_manager']) class DockerImage(object): \"\"\"Holder for Docker image information.\"\"\" DOCKER_IMAGES", "command line. \"\"\" self.lines.append(intent.command) @sync_performer def perform_comment(self, dispatcher, intent): \"\"\" For Comment effects,", "Put, Comment, perform_sudo, perform_put) @attributes(['image', 'package_manager']) class DockerImage(object): \"\"\"Holder for Docker image information.\"\"\"", "platform can # be tricky. See # http://doc-dev.clusterhq.com/gettinginvolved/client-testing.html # for details. params =", "= make_script_file(self.tmpdir, commands) script = '/mnt/script/{}'.format(script_file) session = self.docker.exec_create(self.container_id, script) session_id = session[u'Id']", "out.write(output) return self.docker.exec_inspect(session_id)[u'ExitCode'] class RunOptions(Options): description = \"Run the client tests.\" optParameters =", "effects, add the command line. \"\"\" self.lines.append(intent.command) @sync_performer def perform_comment(self, dispatcher, intent): \"\"\"", "package_source=PackageSource()): \"\"\" Get commands to run for testing client package installation. :param bytes", "get_steps = get_steps_pkg steps = get_steps(distribution, package_source) container = DockerContainer.from_distribution(distribution) status = run_steps(container,", "of effects. :param bytes directory: The directory in which to create the script.", "``write`` method. :return int: The exit status of the commands. If all commands", "sys import tempfile from characteristic import attributes import docker from effect import TypeDispatcher,", "['pip', None, 'Install using pip rather than packages.'], ] synopsis = ('Usage: run-client-tests", "container.execute(commands, out) if status != 0: return status finally: container.stop() return 0 def", "for each command to run. :param out: Where to send command output. Any", "= self.docker.exec_create(self.container_id, script) session_id = session[u'Id'] for output in self.docker.exec_start(session, stream=True): out.write(output) return", "which to create the script. :param Effect effects: An effect which contains the", "OS X, shared volumes must be in /Users, so use the home directory.", "the pip instructions using any of the images. PIP_DISTRIBUTIONS = DOCKER_IMAGES.keys() # Some", "prefix the comment with # \"\"\" self.lines.append('# ' + intent.comment) def script(self): \"\"\"", "instructions using any of the images. PIP_DISTRIBUTIONS = DOCKER_IMAGES.keys() # Some distributions have", "}) perform(self, effects) # Add blank line to terminate script with a newline", "import Options, UsageError from flocker.provision import PackageSource from flocker.provision._effect import Sequence, perform_sequence from", "RunOptions(top_level=top_level) try: options.parseOptions(args) except UsageError as e: sys.exit(\"%s: %s\\n\" % (base_path.basename(), e)) distribution", "distribution not in PIP_DISTRIBUTIONS: raise UsageError( \"Distribution %r not supported. Available distributions: %s\"", "run. :param FilePath top_level: The top-level of the Flocker repository. \"\"\" options =", "to install'], ['build-server', None, 'http://build.clusterhq.com/', 'Base URL of build server for package downloads'],", "Effect commands: An Effect containing the commands to run, probably a Sequence of", "session[u'Id'] for output in self.docker.exec_start(session, stream=True): out.write(output) return self.docker.exec_inspect(session_id)[u'ExitCode'] class RunOptions(Options): description =", "steps = [ ensure_minimal_setup(package_manager), task_cli_pkg_install(distribution, package_source), ] return steps def run_steps(container, steps, out=sys.stdout):", "a Sequence containing multiple commands. :return: The base filename of the script. \"\"\"", "from_distribution(cls, distribution): \"\"\" Create a DockerContainer with a given distribution name. \"\"\" return", "by previous commands. The output of the commands is sent to the ``out``", "[--pip]') def __init__(self, top_level): \"\"\" :param FilePath top_level: The top-level of the flocker", "install the package. :return: An ``Effect`` to pass to a ``Dispatcher`` that supports", "Put: perform_put, Comment: self.perform_comment, Sequence: perform_sequence }) perform(self, effects) # Add blank line", "= { 'centos-7': DockerImage(image='centos:7', package_manager='yum'), 'debian-8': DockerImage(image='debian:8', package_manager='apt'), 'fedora-22': DockerImage(image='fedora:22', package_manager='dnf'), 'ubuntu-14.04': DockerImage(image='ubuntu:14.04',", "\"\"\" return self._script def make_script_file(directory, effects): \"\"\" Create a shell script file from", "zero. If any command fails, this will be non-zero. \"\"\" script_file = make_script_file(self.tmpdir,", "DockerImage(object): \"\"\"Holder for Docker image information.\"\"\" DOCKER_IMAGES = { 'centos-7': DockerImage(image='centos:7', package_manager='yum'), 'debian-8':", "output. Any object with a ``write`` method. :return int: The exit status of", "\"\"\" Create a DockerContainer with a given distribution name. \"\"\" return cls(DOCKER_IMAGES[distribution].image) def", "/Users, so use the home directory. # See 'Mount a host directory as", "= ('Usage: run-client-tests --distribution <distribution> ' '[--branch <branch>] [--flocker-version <version>] ' '[--build-server <url>]", "'Base URL of build server for package downloads'], ] optFlags = [ ['pip',", "must be in /Users, so use the home directory. # See 'Mount a", "'\\n'.join(self.lines) @sync_performer def perform_run(self, dispatcher, intent): \"\"\" For Run effects, add the command", "which contains the commands, typically a Sequence containing multiple commands. :return: The base", "ensure_minimal_setup, task_cli_pkg_install, task_cli_pip_prereqs, task_cli_pip_install, cli_pip_test, ) from flocker.provision._ssh import ( Run, Sudo, Put,", "perform_sequence }) perform(self, effects) # Add blank line to terminate script with a", "\"\"\" self.docker.stop(self.container_id) self.docker.remove_container(self.container_id) shutil.rmtree(self.tmpdir) def execute(self, commands, out=sys.stdout): \"\"\" Execute a set of", "to to run the test. :param file out: Stream to write output. :return", "import os import shutil import sys import tempfile from characteristic import attributes import", "DOCKER_IMAGES[distribution].package_manager steps = [ ensure_minimal_setup(package_manager), task_cli_pkg_install(distribution, package_source), ] return steps def run_steps(container, steps,", "builder = ScriptBuilder(effects) fd, filename = tempfile.mkstemp(dir=directory, text=True) os.write(fd, builder.script()) os.close(fd) os.chmod(filename, 0555)", "steps, out=sys.stdout): \"\"\" Run a sequence of commands in a container. :param DockerContainer", "flocker repository. \"\"\" Options.__init__(self) self.top_level = top_level def postOptions(self): if self['distribution'] is None:", "os.write(fd, builder.script()) os.close(fd) os.chmod(filename, 0555) return os.path.basename(filename) class DockerContainer: \"\"\" Run commands in", "\"\"\"Holder for Docker image information.\"\"\" DOCKER_IMAGES = { 'centos-7': DockerImage(image='centos:7', package_manager='yum'), 'debian-8': DockerImage(image='debian:8',", "container. The set of commands provided to one call of ``execute`` will be", "server for package downloads'], ] optFlags = [ ['pip', None, 'Install using pip", "def __init__(self, top_level): \"\"\" :param FilePath top_level: The top-level of the flocker repository.", "def main(args, base_path, top_level): \"\"\" :param list args: The arguments passed to the", "distribution = options['distribution'] package_source = options['package_source'] if options['pip']: get_steps = get_steps_pip else: get_steps", "= options['package_source'] if options['pip']: get_steps = get_steps_pip else: get_steps = get_steps_pkg steps =", "self.lines.append(intent.command) @sync_performer def perform_comment(self, dispatcher, intent): \"\"\" For Comment effects, prefix the comment", "UsageError from flocker.provision import PackageSource from flocker.provision._effect import Sequence, perform_sequence from flocker.provision._install import", "filename = tempfile.mkstemp(dir=directory, text=True) os.write(fd, builder.script()) os.close(fd) os.chmod(filename, 0555) return os.path.basename(filename) class DockerContainer:", "tested. PACKAGED_CLIENT_DISTRIBUTIONS = ( 'centos-7', 'ubuntu-14.04', 'ubuntu-16.04', ) class ScriptBuilder(TypeDispatcher): \"\"\" Convert an", "Sequence, perform_sequence from flocker.provision._install import ( ensure_minimal_setup, task_cli_pkg_install, task_cli_pip_prereqs, task_cli_pip_install, cli_pip_test, ) from", "TypeDispatcher, sync_performer, perform from twisted.python.usage import Options, UsageError from flocker.provision import PackageSource from", "of {}. With --pip, one of {}'.format( ', '.join(PACKAGED_CLIENT_DISTRIBUTIONS), ', '.join(PIP_DISTRIBUTIONS))], ['branch', None,", ":param FilePath top_level: The top-level of the Flocker repository. \"\"\" options = RunOptions(top_level=top_level)", "version to install'], ['build-server', None, 'http://build.clusterhq.com/', 'Base URL of build server for package", "build server for package downloads'], ] optFlags = [ ['pip', None, 'Install using", "On OS X, shared volumes must be in /Users, so use the home", "the Flocker repository. \"\"\" options = RunOptions(top_level=top_level) try: options.parseOptions(args) except UsageError as e:", "distribution): \"\"\" Create a DockerContainer with a given distribution name. \"\"\" return cls(DOCKER_IMAGES[distribution].image)", "'#!/bin/bash', 'set -ex' ] TypeDispatcher.__init__(self, { Run: self.perform_run, Sudo: perform_sudo, Put: perform_put, Comment:", "use the home directory. # See 'Mount a host directory as a data", "be in /Users, so use the home directory. # See 'Mount a host", "effect import TypeDispatcher, sync_performer, perform from twisted.python.usage import Options, UsageError from flocker.provision import", "base_path: The executable being run. :param FilePath top_level: The top-level of the Flocker", "for them. # Although CentOS 7 is not a supported client distribution, the", "in which to run the test. :param Effect steps: Steps to to run", "single session. This means commands will see the environment created by previous commands.", "[--flocker-version <version>] ' '[--build-server <url>] [--pip]') def __init__(self, top_level): \"\"\" :param FilePath top_level:", "DockerImage(image='centos:7', package_manager='yum'), 'debian-8': DockerImage(image='debian:8', package_manager='apt'), 'fedora-22': DockerImage(image='fedora:22', package_manager='dnf'), 'ubuntu-14.04': DockerImage(image='ubuntu:14.04', package_manager='apt'), 'ubuntu-16.04': DockerImage(image='ubuntu:16.04',", "so use the home directory. # See 'Mount a host directory as a", "Available distributions: %s\" % (distribution, ', '.join(PACKAGED_CLIENT_DISTRIBUTIONS))) package_manager = DOCKER_IMAGES[distribution].package_manager steps = [", "\"\"\" Run a sequence of commands in a container. :param DockerContainer container: Container", "than packages.'], ] synopsis = ('Usage: run-client-tests --distribution <distribution> ' '[--branch <branch>] [--flocker-version", "['distribution', None, None, 'The target distribution. ' 'One of {}. With --pip, one", "@attributes(['image', 'package_manager']) class DockerImage(object): \"\"\"Holder for Docker image information.\"\"\" DOCKER_IMAGES = { 'centos-7':", "\"\"\" Execute a set of commands in the Docker container. The set of", "if status != 0: return status finally: container.stop() return 0 def main(args, base_path,", "', '.join(PIP_DISTRIBUTIONS))) package_manager = DOCKER_IMAGES[distribution].package_manager virtualenv = 'flocker-client' steps = [ ensure_minimal_setup(package_manager), task_cli_pip_prereqs(package_manager),", "] return steps def get_steps_pkg(distribution, package_source=PackageSource()): \"\"\" Get commands to run for testing", "is None: raise UsageError(\"Distribution required.\") self['package_source'] = PackageSource( version=self['flocker-version'], branch=self['branch'], build_server=self['build-server'], ) def", "volume' at # https://docs.docker.com/userguide/dockervolumes/ self.tmpdir = tempfile.mkdtemp(dir=os.path.expanduser('~')) try: self.docker.pull(self.image) container = self.docker.create_container( image=self.image,", "text=True) os.write(fd, builder.script()) os.close(fd) os.chmod(filename, 0555) return os.path.basename(filename) class DockerContainer: \"\"\" Run commands", "the home directory. # See 'Mount a host directory as a data volume'", "sent to the ``out`` file object, which must have a ``write`` method. :param", "create the script. :param Effect effects: An effect which contains the commands, typically", "get built, and can be tested. PACKAGED_CLIENT_DISTRIBUTIONS = ( 'centos-7', 'ubuntu-14.04', 'ubuntu-16.04', )", "but the code can # test the pip instructions using any of the", "a supported client distribution, the client # packages get built, and can be", "'[--build-server <url>] [--pip]') def __init__(self, top_level): \"\"\" :param FilePath top_level: The top-level of", "out=sys.stdout): \"\"\" Execute a set of commands in the Docker container. The set", "from flocker.provision._install import ( ensure_minimal_setup, task_cli_pkg_install, task_cli_pip_prereqs, task_cli_pip_install, cli_pip_test, ) from flocker.provision._ssh import", "of the commands is sent to the ``out`` file object, which must have", "Docker container. \"\"\" self.docker.stop(self.container_id) self.docker.remove_container(self.container_id) shutil.rmtree(self.tmpdir) def execute(self, commands, out=sys.stdout): \"\"\" Execute a", "in self.docker.exec_start(session, stream=True): out.write(output) return self.docker.exec_inspect(session_id)[u'ExitCode'] class RunOptions(Options): description = \"Run the client", ":param list args: The arguments passed to the script. :param FilePath base_path: The", "description = \"Run the client tests.\" optParameters = [ ['distribution', None, None, 'The", "__init__(self, top_level): \"\"\" :param FilePath top_level: The top-level of the flocker repository. \"\"\"", "Convert an Effect sequence to a shell script. The effects are those defined", "line. \"\"\" self.lines.append(intent.command) @sync_performer def perform_comment(self, dispatcher, intent): \"\"\" For Comment effects, prefix", "the Docker container. The set of commands provided to one call of ``execute``", "ClusterHQ Inc. See LICENSE file for details. \"\"\" Run the client installation tests.", "['flocker-version', None, None, 'Flocker version to install'], ['build-server', None, 'http://build.clusterhq.com/', 'Base URL of", "import attributes import docker from effect import TypeDispatcher, sync_performer, perform from twisted.python.usage import", ":param Effect commands: An Effect containing the commands to run, probably a Sequence", "self.docker.stop(self.container_id) self.docker.remove_container(self.container_id) shutil.rmtree(self.tmpdir) def execute(self, commands, out=sys.stdout): \"\"\" Execute a set of commands", "pip, but the code can # test the pip instructions using any of", "get_steps = get_steps_pip else: get_steps = get_steps_pkg steps = get_steps(distribution, package_source) container =", "the commands to run, probably a Sequence of Effects, one for each command", "self.perform_comment, Sequence: perform_sequence }) perform(self, effects) # Add blank line to terminate script", "= top_level def postOptions(self): if self['distribution'] is None: raise UsageError(\"Distribution required.\") self['package_source'] =", "script_file = make_script_file(self.tmpdir, commands) script = '/mnt/script/{}'.format(script_file) session = self.docker.exec_create(self.container_id, script) session_id =", "contains the commands, typically a Sequence containing multiple commands. :return: The base filename", "postOptions(self): if self['distribution'] is None: raise UsageError(\"Distribution required.\") self['package_source'] = PackageSource( version=self['flocker-version'], branch=self['branch'],", "'ubuntu-16.04', ) class ScriptBuilder(TypeDispatcher): \"\"\" Convert an Effect sequence to a shell script.", "e: sys.exit(\"%s: %s\\n\" % (base_path.basename(), e)) distribution = options['distribution'] package_source = options['package_source'] if", "(distribution, ', '.join(PIP_DISTRIBUTIONS))) package_manager = DOCKER_IMAGES[distribution].package_manager virtualenv = 'flocker-client' steps = [ ensure_minimal_setup(package_manager),", "attributes import docker from effect import TypeDispatcher, sync_performer, perform from twisted.python.usage import Options,", "synopsis = ('Usage: run-client-tests --distribution <distribution> ' '[--branch <branch>] [--flocker-version <version>] ' '[--build-server", "PACKAGED_CLIENT_DISTRIBUTIONS = ( 'centos-7', 'ubuntu-14.04', 'ubuntu-16.04', ) class ScriptBuilder(TypeDispatcher): \"\"\" Convert an Effect", "The effects are those defined in flocker.provision._effect and flocker.provision._ssh._model. \"\"\" def __init__(self, effects):", "command fails, this will be non-zero. \"\"\" script_file = make_script_file(self.tmpdir, commands) script =", "Get commands to run for testing client pip installation. :param bytes distribution: The", "out=sys.stdout): \"\"\" Run a sequence of commands in a container. :param DockerContainer container:", "The arguments passed to the script. :param FilePath base_path: The executable being run.", "'Install using pip rather than packages.'], ] synopsis = ('Usage: run-client-tests --distribution <distribution>", "return status finally: container.stop() return 0 def main(args, base_path, top_level): \"\"\" :param list", "\"\"\" def __init__(self, image): # Getting Docker to work correctly on any client", "from flocker.provision._effect import Sequence, perform_sequence from flocker.provision._install import ( ensure_minimal_setup, task_cli_pkg_install, task_cli_pip_prereqs, task_cli_pip_install,", "details. params = docker.utils.kwargs_from_env(assert_hostname=False) self.docker = docker.Client(version='1.16', **params) self.image = image @classmethod def", "from characteristic import attributes import docker from effect import TypeDispatcher, sync_performer, perform from", "task_cli_pip_prereqs, task_cli_pip_install, cli_pip_test, ) from flocker.provision._ssh import ( Run, Sudo, Put, Comment, perform_sudo,", "on any client platform can # be tricky. See # http://doc-dev.clusterhq.com/gettinginvolved/client-testing.html # for", "run the test. :param file out: Stream to write output. :return int: Exit", "= session[u'Id'] for output in self.docker.exec_start(session, stream=True): out.write(output) return self.docker.exec_inspect(session_id)[u'ExitCode'] class RunOptions(Options): description", "pass to a ``Dispatcher`` that supports ``Sequence``, ``Run``, ``Sudo``, ``Comment``, and ``Put``. \"\"\"", "cli_pip_test(virtualenv, package_source), ] return steps def get_steps_pkg(distribution, package_source=PackageSource()): \"\"\" Get commands to run", "ScriptBuilder(TypeDispatcher): \"\"\" Convert an Effect sequence to a shell script. The effects are", "for details. \"\"\" Run the client installation tests. \"\"\" import os import shutil", "def postOptions(self): if self['distribution'] is None: raise UsageError(\"Distribution required.\") self['package_source'] = PackageSource( version=self['flocker-version'],", "0555) return os.path.basename(filename) class DockerContainer: \"\"\" Run commands in a Docker container. \"\"\"", "node is running. :param PackageSource package_source: The source from which to install the", "will be executed in a single session. This means commands will see the", "a sequence of commands in a container. :param DockerContainer container: Container in which", "'One of {}. With --pip, one of {}'.format( ', '.join(PACKAGED_CLIENT_DISTRIBUTIONS), ', '.join(PIP_DISTRIBUTIONS))], ['branch',", "code can # test the pip instructions using any of the images. PIP_DISTRIBUTIONS", "effects, prefix the comment with # \"\"\" self.lines.append('# ' + intent.comment) def script(self):", "in /Users, so use the home directory. # See 'Mount a host directory", "created by previous commands. The output of the commands is sent to the", "Copyright 2015 ClusterHQ Inc. See LICENSE file for details. \"\"\" Run the client", "PackageSource from flocker.provision._effect import Sequence, perform_sequence from flocker.provision._install import ( ensure_minimal_setup, task_cli_pkg_install, task_cli_pip_prereqs,", "supported using pip, but the code can # test the pip instructions using", "executed in a single session. This means commands will see the environment created", "if distribution not in PIP_DISTRIBUTIONS: raise UsageError( \"Distribution %r not supported. Available distributions:", "name. \"\"\" return cls(DOCKER_IMAGES[distribution].image) def start(self): \"\"\" Start the Docker container. \"\"\" #", "package_source), ] return steps def get_steps_pkg(distribution, package_source=PackageSource()): \"\"\" Get commands to run for", "DockerImage(image='ubuntu:14.04', package_manager='apt'), 'ubuntu-16.04': DockerImage(image='ubuntu:16.04', package_manager='apt'), } # No distribution is officially supported using", "version=self['flocker-version'], branch=self['branch'], build_server=self['build-server'], ) def get_steps_pip(distribution, package_source=PackageSource()): \"\"\" Get commands to run for", "return steps def get_steps_pkg(distribution, package_source=PackageSource()): \"\"\" Get commands to run for testing client", "FilePath top_level: The top-level of the Flocker repository. \"\"\" options = RunOptions(top_level=top_level) try:", "'Flocker version to install'], ['build-server', None, 'http://build.clusterhq.com/', 'Base URL of build server for", "', '.join(PIP_DISTRIBUTIONS))], ['branch', None, None, 'Branch to grab packages from'], ['flocker-version', None, None,", "distribution the node is running. :param PackageSource package_source: The source from which to", "any of the images. PIP_DISTRIBUTIONS = DOCKER_IMAGES.keys() # Some distributions have packages created", "Docker container. \"\"\" # On OS X, shared volumes must be in /Users,", "at # https://docs.docker.com/userguide/dockervolumes/ self.tmpdir = tempfile.mkdtemp(dir=os.path.expanduser('~')) try: self.docker.pull(self.image) container = self.docker.create_container( image=self.image, command='/bin/bash',", "return os.path.basename(filename) class DockerContainer: \"\"\" Run commands in a Docker container. \"\"\" def", "options['package_source'] if options['pip']: get_steps = get_steps_pip else: get_steps = get_steps_pkg steps = get_steps(distribution,", "using pip, but the code can # test the pip instructions using any", "intent): \"\"\" For Run effects, add the command line. \"\"\" self.lines.append(intent.command) @sync_performer def", "sync_performer, perform from twisted.python.usage import Options, UsageError from flocker.provision import PackageSource from flocker.provision._effect", "\"\"\" Stop the Docker container. \"\"\" self.docker.stop(self.container_id) self.docker.remove_container(self.container_id) shutil.rmtree(self.tmpdir) def execute(self, commands, out=sys.stdout):", "commands. The output of the commands is sent to the ``out`` file object,", "for testing client package installation. :param bytes distribution: The distribution the node is", "run for testing client pip installation. :param bytes distribution: The distribution the node", "out: Where to send command output. Any object with a ``write`` method. :return", "executable being run. :param FilePath top_level: The top-level of the Flocker repository. \"\"\"", "Docker container. The set of commands provided to one call of ``execute`` will", "sys.exit(\"%s: %s\\n\" % (base_path.basename(), e)) distribution = options['distribution'] package_source = options['package_source'] if options['pip']:", "https://docs.docker.com/userguide/dockervolumes/ self.tmpdir = tempfile.mkdtemp(dir=os.path.expanduser('~')) try: self.docker.pull(self.image) container = self.docker.create_container( image=self.image, command='/bin/bash', tty=True, volumes=['/mnt/script'],", "container.stop() return 0 def main(args, base_path, top_level): \"\"\" :param list args: The arguments", "0 def main(args, base_path, top_level): \"\"\" :param list args: The arguments passed to", "'ubuntu-14.04', 'ubuntu-16.04', ) class ScriptBuilder(TypeDispatcher): \"\"\" Convert an Effect sequence to a shell", "return self._script def make_script_file(directory, effects): \"\"\" Create a shell script file from a", "distribution. ' 'One of {}. With --pip, one of {}'.format( ', '.join(PACKAGED_CLIENT_DISTRIBUTIONS), ',", "Options.__init__(self) self.top_level = top_level def postOptions(self): if self['distribution'] is None: raise UsageError(\"Distribution required.\")", "information.\"\"\" DOCKER_IMAGES = { 'centos-7': DockerImage(image='centos:7', package_manager='yum'), 'debian-8': DockerImage(image='debian:8', package_manager='apt'), 'fedora-22': DockerImage(image='fedora:22', package_manager='dnf'),", "sequence of commands in a container. :param DockerContainer container: Container in which to", "of the commands. If all commands succeed, this will be zero. If any", "status of steps. \"\"\" container.start() try: for commands in steps: status = container.execute(commands,", "source from which to install the package. :return: An ``Effect`` to pass to", "DockerImage(image='debian:8', package_manager='apt'), 'fedora-22': DockerImage(image='fedora:22', package_manager='dnf'), 'ubuntu-14.04': DockerImage(image='ubuntu:14.04', package_manager='apt'), 'ubuntu-16.04': DockerImage(image='ubuntu:16.04', package_manager='apt'), } #", "script(self): \"\"\" Return the generated shell script. \"\"\" return self._script def make_script_file(directory, effects):", "package_source = options['package_source'] if options['pip']: get_steps = get_steps_pip else: get_steps = get_steps_pkg steps", "self.container_id, binds={ self.tmpdir: {'bind': '/mnt/script', 'ro': True}, } ) except: os.rmdir(self.tmpdir) raise def", "object, which must have a ``write`` method. :param Effect commands: An Effect containing", "them. # Although CentOS 7 is not a supported client distribution, the client", "DOCKER_IMAGES = { 'centos-7': DockerImage(image='centos:7', package_manager='yum'), 'debian-8': DockerImage(image='debian:8', package_manager='apt'), 'fedora-22': DockerImage(image='fedora:22', package_manager='dnf'), 'ubuntu-14.04':", "of Effects, one for each command to run. :param out: Where to send", "flocker.provision._effect import Sequence, perform_sequence from flocker.provision._install import ( ensure_minimal_setup, task_cli_pkg_install, task_cli_pip_prereqs, task_cli_pip_install, cli_pip_test,", "\"\"\" self.lines.append(intent.command) @sync_performer def perform_comment(self, dispatcher, intent): \"\"\" For Comment effects, prefix the", "Sudo: perform_sudo, Put: perform_put, Comment: self.perform_comment, Sequence: perform_sequence }) perform(self, effects) # Add", "see the environment created by previous commands. The output of the commands is", "container = self.docker.create_container( image=self.image, command='/bin/bash', tty=True, volumes=['/mnt/script'], ) self.container_id = container[u'Id'] self.docker.start( self.container_id,", "run-client-tests --distribution <distribution> ' '[--branch <branch>] [--flocker-version <version>] ' '[--build-server <url>] [--pip]') def", "with a newline self.lines.append('') self._script = '\\n'.join(self.lines) @sync_performer def perform_run(self, dispatcher, intent): \"\"\"", "def perform_run(self, dispatcher, intent): \"\"\" For Run effects, add the command line. \"\"\"", "a Docker container. \"\"\" def __init__(self, image): # Getting Docker to work correctly", "succeed, this will be zero. If any command fails, this will be non-zero.", "perform_put, Comment: self.perform_comment, Sequence: perform_sequence }) perform(self, effects) # Add blank line to", "\"\"\" Return the generated shell script. \"\"\" return self._script def make_script_file(directory, effects): \"\"\"", "line to terminate script with a newline self.lines.append('') self._script = '\\n'.join(self.lines) @sync_performer def", "from'], ['flocker-version', None, None, 'Flocker version to install'], ['build-server', None, 'http://build.clusterhq.com/', 'Base URL", "script = '/mnt/script/{}'.format(script_file) session = self.docker.exec_create(self.container_id, script) session_id = session[u'Id'] for output in", "(distribution, ', '.join(PACKAGED_CLIENT_DISTRIBUTIONS))) package_manager = DOCKER_IMAGES[distribution].package_manager steps = [ ensure_minimal_setup(package_manager), task_cli_pkg_install(distribution, package_source), ]", "Sequence of Effects, one for each command to run. :param out: Where to", "the package. :return: An ``Effect`` to pass to a ``Dispatcher`` that supports ``Sequence``,", "commands in a Docker container. \"\"\" def __init__(self, image): # Getting Docker to", "send command output. Any object with a ``write`` method. :return int: The exit", "package downloads'], ] optFlags = [ ['pip', None, 'Install using pip rather than", "Exit status of steps. \"\"\" container.start() try: for commands in steps: status =", "twisted.python.usage import Options, UsageError from flocker.provision import PackageSource from flocker.provision._effect import Sequence, perform_sequence", "session = self.docker.exec_create(self.container_id, script) session_id = session[u'Id'] for output in self.docker.exec_start(session, stream=True): out.write(output)", "# See 'Mount a host directory as a data volume' at # https://docs.docker.com/userguide/dockervolumes/", "of commands provided to one call of ``execute`` will be executed in a", "Options, UsageError from flocker.provision import PackageSource from flocker.provision._effect import Sequence, perform_sequence from flocker.provision._install", "which must have a ``write`` method. :param Effect commands: An Effect containing the", "stop(self): \"\"\" Stop the Docker container. \"\"\" self.docker.stop(self.container_id) self.docker.remove_container(self.container_id) shutil.rmtree(self.tmpdir) def execute(self, commands,", "[ '#!/bin/bash', 'set -ex' ] TypeDispatcher.__init__(self, { Run: self.perform_run, Sudo: perform_sudo, Put: perform_put,", "this will be zero. If any command fails, this will be non-zero. \"\"\"", "\"\"\" Get commands to run for testing client pip installation. :param bytes distribution:", "have a ``write`` method. :param Effect commands: An Effect containing the commands to", "the script. :param Effect effects: An effect which contains the commands, typically a", "No distribution is officially supported using pip, but the code can # test", "DOCKER_IMAGES[distribution].package_manager virtualenv = 'flocker-client' steps = [ ensure_minimal_setup(package_manager), task_cli_pip_prereqs(package_manager), task_cli_pip_install(virtualenv, package_source), cli_pip_test(virtualenv, package_source),", "details. \"\"\" Run the client installation tests. \"\"\" import os import shutil import", "top_level: The top-level of the flocker repository. \"\"\" Options.__init__(self) self.top_level = top_level def", "test. :param Effect steps: Steps to to run the test. :param file out:", "self.image = image @classmethod def from_distribution(cls, distribution): \"\"\" Create a DockerContainer with a", "An Effect containing the commands to run, probably a Sequence of Effects, one", ":return int: Exit status of steps. \"\"\" container.start() try: for commands in steps:", "from which to install the package. :return: An ``Effect`` to pass to a", "PACKAGED_CLIENT_DISTRIBUTIONS: raise UsageError( \"Distribution %r not supported. Available distributions: %s\" % (distribution, ',", "the environment created by previous commands. The output of the commands is sent", "will see the environment created by previous commands. The output of the commands", "import TypeDispatcher, sync_performer, perform from twisted.python.usage import Options, UsageError from flocker.provision import PackageSource", "the commands, typically a Sequence containing multiple commands. :return: The base filename of", "the commands is sent to the ``out`` file object, which must have a", "given distribution name. \"\"\" return cls(DOCKER_IMAGES[distribution].image) def start(self): \"\"\" Start the Docker container.", "of the images. PIP_DISTRIBUTIONS = DOCKER_IMAGES.keys() # Some distributions have packages created for", "\"\"\" Run the client installation tests. \"\"\" import os import shutil import sys", "filename of the script. \"\"\" builder = ScriptBuilder(effects) fd, filename = tempfile.mkstemp(dir=directory, text=True)", "probably a Sequence of Effects, one for each command to run. :param out:", "with # \"\"\" self.lines.append('# ' + intent.comment) def script(self): \"\"\" Return the generated", "effects): self.lines = [ '#!/bin/bash', 'set -ex' ] TypeDispatcher.__init__(self, { Run: self.perform_run, Sudo:", "set of commands provided to one call of ``execute`` will be executed in", "output. :return int: Exit status of steps. \"\"\" container.start() try: for commands in", "0: return status finally: container.stop() return 0 def main(args, base_path, top_level): \"\"\" :param", "\"\"\" Options.__init__(self) self.top_level = top_level def postOptions(self): if self['distribution'] is None: raise UsageError(\"Distribution", "\"\"\" Create a shell script file from a sequence of effects. :param bytes", "to the script. :param FilePath base_path: The executable being run. :param FilePath top_level:", "being run. :param FilePath top_level: The top-level of the Flocker repository. \"\"\" options", "the client # packages get built, and can be tested. PACKAGED_CLIENT_DISTRIBUTIONS = (", "def perform_comment(self, dispatcher, intent): \"\"\" For Comment effects, prefix the comment with #", "# for details. params = docker.utils.kwargs_from_env(assert_hostname=False) self.docker = docker.Client(version='1.16', **params) self.image = image", "'fedora-22': DockerImage(image='fedora:22', package_manager='dnf'), 'ubuntu-14.04': DockerImage(image='ubuntu:14.04', package_manager='apt'), 'ubuntu-16.04': DockerImage(image='ubuntu:16.04', package_manager='apt'), } # No distribution", "See 'Mount a host directory as a data volume' at # https://docs.docker.com/userguide/dockervolumes/ self.tmpdir", "grab packages from'], ['flocker-version', None, None, 'Flocker version to install'], ['build-server', None, 'http://build.clusterhq.com/',", "script. The effects are those defined in flocker.provision._effect and flocker.provision._ssh._model. \"\"\" def __init__(self,", "'centos-7': DockerImage(image='centos:7', package_manager='yum'), 'debian-8': DockerImage(image='debian:8', package_manager='apt'), 'fedora-22': DockerImage(image='fedora:22', package_manager='dnf'), 'ubuntu-14.04': DockerImage(image='ubuntu:14.04', package_manager='apt'), 'ubuntu-16.04':", ":param out: Where to send command output. Any object with a ``write`` method.", "the command line. \"\"\" self.lines.append(intent.command) @sync_performer def perform_comment(self, dispatcher, intent): \"\"\" For Comment", "'flocker-client' steps = [ ensure_minimal_setup(package_manager), task_cli_pip_prereqs(package_manager), task_cli_pip_install(virtualenv, package_source), cli_pip_test(virtualenv, package_source), ] return steps", "for Docker image information.\"\"\" DOCKER_IMAGES = { 'centos-7': DockerImage(image='centos:7', package_manager='yum'), 'debian-8': DockerImage(image='debian:8', package_manager='apt'),", "try: for commands in steps: status = container.execute(commands, out) if status != 0:", "raise def stop(self): \"\"\" Stop the Docker container. \"\"\" self.docker.stop(self.container_id) self.docker.remove_container(self.container_id) shutil.rmtree(self.tmpdir) def", "%r not supported. Available distributions: %s\" % (distribution, ', '.join(PACKAGED_CLIENT_DISTRIBUTIONS))) package_manager = DOCKER_IMAGES[distribution].package_manager", "DockerImage(image='ubuntu:16.04', package_manager='apt'), } # No distribution is officially supported using pip, but the", "self.docker.start( self.container_id, binds={ self.tmpdir: {'bind': '/mnt/script', 'ro': True}, } ) except: os.rmdir(self.tmpdir) raise", "task_cli_pkg_install, task_cli_pip_prereqs, task_cli_pip_install, cli_pip_test, ) from flocker.provision._ssh import ( Run, Sudo, Put, Comment,", "self.lines.append('# ' + intent.comment) def script(self): \"\"\" Return the generated shell script. \"\"\"", ":param DockerContainer container: Container in which to run the test. :param Effect steps:", "['build-server', None, 'http://build.clusterhq.com/', 'Base URL of build server for package downloads'], ] optFlags", "containing multiple commands. :return: The base filename of the script. \"\"\" builder =", "of the Flocker repository. \"\"\" options = RunOptions(top_level=top_level) try: options.parseOptions(args) except UsageError as", "a shell script file from a sequence of effects. :param bytes directory: The", "fails, this will be non-zero. \"\"\" script_file = make_script_file(self.tmpdir, commands) script = '/mnt/script/{}'.format(script_file)", "import ( Run, Sudo, Put, Comment, perform_sudo, perform_put) @attributes(['image', 'package_manager']) class DockerImage(object): \"\"\"Holder", "commands in steps: status = container.execute(commands, out) if status != 0: return status", "to the ``out`` file object, which must have a ``write`` method. :param Effect", "have packages created for them. # Although CentOS 7 is not a supported", "intent): \"\"\" For Comment effects, prefix the comment with # \"\"\" self.lines.append('# '", "@sync_performer def perform_run(self, dispatcher, intent): \"\"\" For Run effects, add the command line.", "container. \"\"\" # On OS X, shared volumes must be in /Users, so", "if options['pip']: get_steps = get_steps_pip else: get_steps = get_steps_pkg steps = get_steps(distribution, package_source)", "= PackageSource( version=self['flocker-version'], branch=self['branch'], build_server=self['build-server'], ) def get_steps_pip(distribution, package_source=PackageSource()): \"\"\" Get commands to", "self._script def make_script_file(directory, effects): \"\"\" Create a shell script file from a sequence", "def execute(self, commands, out=sys.stdout): \"\"\" Execute a set of commands in the Docker", "supports ``Sequence``, ``Run``, ``Sudo``, ``Comment``, and ``Put``. \"\"\" if distribution not in PIP_DISTRIBUTIONS:", "distribution, the client # packages get built, and can be tested. PACKAGED_CLIENT_DISTRIBUTIONS =", "``Run``, ``Sudo``, ``Comment``, and ``Put``. \"\"\" if distribution not in PIP_DISTRIBUTIONS: raise UsageError(", "commands, typically a Sequence containing multiple commands. :return: The base filename of the", ") def get_steps_pip(distribution, package_source=PackageSource()): \"\"\" Get commands to run for testing client pip", "os.close(fd) os.chmod(filename, 0555) return os.path.basename(filename) class DockerContainer: \"\"\" Run commands in a Docker", "this will be non-zero. \"\"\" script_file = make_script_file(self.tmpdir, commands) script = '/mnt/script/{}'.format(script_file) session", "finally: container.stop() return 0 def main(args, base_path, top_level): \"\"\" :param list args: The", "try: self.docker.pull(self.image) container = self.docker.create_container( image=self.image, command='/bin/bash', tty=True, volumes=['/mnt/script'], ) self.container_id = container[u'Id']", "with a ``write`` method. :return int: The exit status of the commands. If", "script. :param FilePath base_path: The executable being run. :param FilePath top_level: The top-level", "a ``Dispatcher`` that supports ``Sequence``, ``Run``, ``Sudo``, ``Comment``, and ``Put``. \"\"\" if distribution", "shared volumes must be in /Users, so use the home directory. # See", "'set -ex' ] TypeDispatcher.__init__(self, { Run: self.perform_run, Sudo: perform_sudo, Put: perform_put, Comment: self.perform_comment,", "os import shutil import sys import tempfile from characteristic import attributes import docker", "Return the generated shell script. \"\"\" return self._script def make_script_file(directory, effects): \"\"\" Create", "See # http://doc-dev.clusterhq.com/gettinginvolved/client-testing.html # for details. params = docker.utils.kwargs_from_env(assert_hostname=False) self.docker = docker.Client(version='1.16', **params)", "{}. With --pip, one of {}'.format( ', '.join(PACKAGED_CLIENT_DISTRIBUTIONS), ', '.join(PIP_DISTRIBUTIONS))], ['branch', None, None,", "None, None, 'Branch to grab packages from'], ['flocker-version', None, None, 'Flocker version to", "be tricky. See # http://doc-dev.clusterhq.com/gettinginvolved/client-testing.html # for details. params = docker.utils.kwargs_from_env(assert_hostname=False) self.docker =", "commands. :return: The base filename of the script. \"\"\" builder = ScriptBuilder(effects) fd,", ":param bytes directory: The directory in which to create the script. :param Effect", "of ``execute`` will be executed in a single session. This means commands will", "The executable being run. :param FilePath top_level: The top-level of the Flocker repository.", "not a supported client distribution, the client # packages get built, and can", "perform_sudo, Put: perform_put, Comment: self.perform_comment, Sequence: perform_sequence }) perform(self, effects) # Add blank", "\"\"\" For Run effects, add the command line. \"\"\" self.lines.append(intent.command) @sync_performer def perform_comment(self,", "os.chmod(filename, 0555) return os.path.basename(filename) class DockerContainer: \"\"\" Run commands in a Docker container.", "previous commands. The output of the commands is sent to the ``out`` file", "``write`` method. :param Effect commands: An Effect containing the commands to run, probably", "!= 0: return status finally: container.stop() return 0 def main(args, base_path, top_level): \"\"\"", "to a ``Dispatcher`` that supports ``Sequence``, ``Run``, ``Sudo``, ``Comment``, and ``Put``. \"\"\" if", "PackageSource( version=self['flocker-version'], branch=self['branch'], build_server=self['build-server'], ) def get_steps_pip(distribution, package_source=PackageSource()): \"\"\" Get commands to run", "client platform can # be tricky. See # http://doc-dev.clusterhq.com/gettinginvolved/client-testing.html # for details. params", "LICENSE file for details. \"\"\" Run the client installation tests. \"\"\" import os", "container. \"\"\" self.docker.stop(self.container_id) self.docker.remove_container(self.container_id) shutil.rmtree(self.tmpdir) def execute(self, commands, out=sys.stdout): \"\"\" Execute a set", "generated shell script. \"\"\" return self._script def make_script_file(directory, effects): \"\"\" Create a shell", "session. This means commands will see the environment created by previous commands. The", "**params) self.image = image @classmethod def from_distribution(cls, distribution): \"\"\" Create a DockerContainer with", ":param FilePath top_level: The top-level of the flocker repository. \"\"\" Options.__init__(self) self.top_level =", "will be zero. If any command fails, this will be non-zero. \"\"\" script_file", "return 0 def main(args, base_path, top_level): \"\"\" :param list args: The arguments passed", "``Put``. \"\"\" if distribution not in PACKAGED_CLIENT_DISTRIBUTIONS: raise UsageError( \"Distribution %r not supported.", "are those defined in flocker.provision._effect and flocker.provision._ssh._model. \"\"\" def __init__(self, effects): self.lines =", "non-zero. \"\"\" script_file = make_script_file(self.tmpdir, commands) script = '/mnt/script/{}'.format(script_file) session = self.docker.exec_create(self.container_id, script)", "object with a ``write`` method. :return int: The exit status of the commands.", "'.join(PIP_DISTRIBUTIONS))) package_manager = DOCKER_IMAGES[distribution].package_manager virtualenv = 'flocker-client' steps = [ ensure_minimal_setup(package_manager), task_cli_pip_prereqs(package_manager), task_cli_pip_install(virtualenv,", "file object, which must have a ``write`` method. :param Effect commands: An Effect", "def start(self): \"\"\" Start the Docker container. \"\"\" # On OS X, shared", "# Although CentOS 7 is not a supported client distribution, the client #", "An ``Effect`` to pass to a ``Dispatcher`` that supports ``Sequence``, ``Run``, ``Sudo``, ``Comment``,", "effects) # Add blank line to terminate script with a newline self.lines.append('') self._script", "= [ '#!/bin/bash', 'set -ex' ] TypeDispatcher.__init__(self, { Run: self.perform_run, Sudo: perform_sudo, Put:", "run for testing client package installation. :param bytes distribution: The distribution the node", "from flocker.provision import PackageSource from flocker.provision._effect import Sequence, perform_sequence from flocker.provision._install import (", "' + intent.comment) def script(self): \"\"\" Return the generated shell script. \"\"\" return", "install'], ['build-server', None, 'http://build.clusterhq.com/', 'Base URL of build server for package downloads'], ]", "top-level of the flocker repository. \"\"\" Options.__init__(self) self.top_level = top_level def postOptions(self): if", "perform(self, effects) # Add blank line to terminate script with a newline self.lines.append('')", "``Comment``, and ``Put``. \"\"\" if distribution not in PIP_DISTRIBUTIONS: raise UsageError( \"Distribution %r", "steps. \"\"\" container.start() try: for commands in steps: status = container.execute(commands, out) if", "container: Container in which to run the test. :param Effect steps: Steps to", "Docker image information.\"\"\" DOCKER_IMAGES = { 'centos-7': DockerImage(image='centos:7', package_manager='yum'), 'debian-8': DockerImage(image='debian:8', package_manager='apt'), 'fedora-22':", "binds={ self.tmpdir: {'bind': '/mnt/script', 'ro': True}, } ) except: os.rmdir(self.tmpdir) raise def stop(self):", "( ensure_minimal_setup, task_cli_pkg_install, task_cli_pip_prereqs, task_cli_pip_install, cli_pip_test, ) from flocker.provision._ssh import ( Run, Sudo,", "if distribution not in PACKAGED_CLIENT_DISTRIBUTIONS: raise UsageError( \"Distribution %r not supported. Available distributions:", "container. :param DockerContainer container: Container in which to run the test. :param Effect", "http://doc-dev.clusterhq.com/gettinginvolved/client-testing.html # for details. params = docker.utils.kwargs_from_env(assert_hostname=False) self.docker = docker.Client(version='1.16', **params) self.image =", "``Sequence``, ``Run``, ``Sudo``, ``Comment``, and ``Put``. \"\"\" if distribution not in PACKAGED_CLIENT_DISTRIBUTIONS: raise", "<url>] [--pip]') def __init__(self, top_level): \"\"\" :param FilePath top_level: The top-level of the", "', '.join(PACKAGED_CLIENT_DISTRIBUTIONS))) package_manager = DOCKER_IMAGES[distribution].package_manager steps = [ ensure_minimal_setup(package_manager), task_cli_pkg_install(distribution, package_source), ] return", "self.docker.exec_inspect(session_id)[u'ExitCode'] class RunOptions(Options): description = \"Run the client tests.\" optParameters = [ ['distribution',", "effects: An effect which contains the commands, typically a Sequence containing multiple commands.", "optFlags = [ ['pip', None, 'Install using pip rather than packages.'], ] synopsis", "The base filename of the script. \"\"\" builder = ScriptBuilder(effects) fd, filename =", "and ``Put``. \"\"\" if distribution not in PACKAGED_CLIENT_DISTRIBUTIONS: raise UsageError( \"Distribution %r not", "return steps def run_steps(container, steps, out=sys.stdout): \"\"\" Run a sequence of commands in", "for testing client pip installation. :param bytes distribution: The distribution the node is", "a single session. This means commands will see the environment created by previous", "If any command fails, this will be non-zero. \"\"\" script_file = make_script_file(self.tmpdir, commands)", "a host directory as a data volume' at # https://docs.docker.com/userguide/dockervolumes/ self.tmpdir = tempfile.mkdtemp(dir=os.path.expanduser('~'))", "cli_pip_test, ) from flocker.provision._ssh import ( Run, Sudo, Put, Comment, perform_sudo, perform_put) @attributes(['image',", "# Add blank line to terminate script with a newline self.lines.append('') self._script =", "package_source), ] return steps def run_steps(container, steps, out=sys.stdout): \"\"\" Run a sequence of", "which to run the test. :param Effect steps: Steps to to run the", "be executed in a single session. This means commands will see the environment", "Container in which to run the test. :param Effect steps: Steps to to", "\"\"\" self.lines.append('# ' + intent.comment) def script(self): \"\"\" Return the generated shell script.", "as a data volume' at # https://docs.docker.com/userguide/dockervolumes/ self.tmpdir = tempfile.mkdtemp(dir=os.path.expanduser('~')) try: self.docker.pull(self.image) container", "PIP_DISTRIBUTIONS: raise UsageError( \"Distribution %r not supported. Available distributions: %s\" % (distribution, ',", "packages created for them. # Although CentOS 7 is not a supported client", "Effect containing the commands to run, probably a Sequence of Effects, one for", "# http://doc-dev.clusterhq.com/gettinginvolved/client-testing.html # for details. params = docker.utils.kwargs_from_env(assert_hostname=False) self.docker = docker.Client(version='1.16', **params) self.image", "the commands. If all commands succeed, this will be zero. If any command", "[ ['pip', None, 'Install using pip rather than packages.'], ] synopsis = ('Usage:", "repository. \"\"\" options = RunOptions(top_level=top_level) try: options.parseOptions(args) except UsageError as e: sys.exit(\"%s: %s\\n\"", "self.docker.exec_create(self.container_id, script) session_id = session[u'Id'] for output in self.docker.exec_start(session, stream=True): out.write(output) return self.docker.exec_inspect(session_id)[u'ExitCode']", "docker from effect import TypeDispatcher, sync_performer, perform from twisted.python.usage import Options, UsageError from", "pip instructions using any of the images. PIP_DISTRIBUTIONS = DOCKER_IMAGES.keys() # Some distributions", "shell script file from a sequence of effects. :param bytes directory: The directory", "script. \"\"\" builder = ScriptBuilder(effects) fd, filename = tempfile.mkstemp(dir=directory, text=True) os.write(fd, builder.script()) os.close(fd)" ]
[ "vb = -1 vt = 2 vl = 0 vr = 0 vb", "END FUNCTION #################################################### ###################################################### #FINAL FUNCTION ##################################3 out_dir='./' Nx=10 Ny=10 Ly=10 Lx=10 dx=Lx/Nx", "edge_vb_y], [edge_vt_x, edge_vt_y] ] = get_exterior_edges(FORCES_MASK) [ [edge_hl_x, edge_hl_y], [edge_hr_x, edge_hr_y], [edge_vb_x, edge_vb_y],", "velocity = to_numpy(velocity) u = velocity[0] v = velocity[1] plot_field(FORCES_MASK, plot_type=['surface'], options=[ ['limits',", "plot_type=['surface'], options=[ ['limits', [0, 1]], #['full_zoom', True], ['zoom_position', zoom_pos], ['aux_contourn', False], ['grid', True],", "True], ['zoom_position', zoom_pos], ['aux_contourn', False], ['grid', True], ['edges', [ [edge_hl_x, edge_hl_y], [edge_hr_x, edge_hr_y],", "DOMAIN = Domain(x=Nx, y=Ny, boundaries=[OPEN, STICKY], bounds=Box[0:Lx, 0:Ly]) velocity = ((DOMAIN.staggered_grid(Noise(batch=1)) * 0", "edge_hl_y], [edge_hr_x, edge_hr_y], [edge_vb_x, edge_vb_y], [edge_vt_x, edge_vt_y] ] = get_exterior_edges(FORCES_MASK) [ [edge_hl_x, edge_hl_y],", "= to_numpy(velocity) u = velocity[0] v = velocity[1] plot_field(FORCES_MASK, plot_type=['surface'], options=[ ['limits', [0,", "+ 1] = vt #Pass to phiflow velocity = to_staggered([u,v], Lx, Ly) #", "Ly) # vel= torch.zeros((1, 2, Nx+1, Ny+1)) # vel[0,0,:,:] = torch.from_numpy(u) # vel[0,1,:,:]", "# velocity = StaggeredGrid(tensor_U_unstack, geom.Box(lower, upper), extrapolation) # END FUNCTION #################################################### ###################################################### #FINAL", "D -1, Ly/2 + D +1 ] velocity = set_normal_bc(FORCES_MASK, velocity = velocity,", "= velocity[0] v = velocity[1] plot_field(FORCES_MASK, plot_type=['surface'], options=[ ['limits', [0, 1]], #['full_zoom', True],", "Nx+1, Ny+1)) # vel[0,0,:,:] = torch.from_numpy(u) # vel[0,1,:,:] = torch.from_numpy(v) # velocity_init =", "HardGeometryMask(Box[xD-D:xD+D, Ly/2-D:Ly/2+D]) >> DOMAIN.scalar_grid() FORCES_MASK = HardGeometryMask(Sphere([xD, Ly/2], radius=D/2 )) >> DOMAIN.scalar_grid() zoom_pos=[xD", "from engines.phi.torch.flow import * from numpy.core import shape_base from scipy.signal.filter_design import _vratio from", "import * from neurasim import * from util.operations.field_operate import * out_dir='./' Nx=10 Ny=10", "= get_exterior_edges(FORCES_MASK) [ [edge_hl_x, edge_hl_y], [edge_hr_x, edge_hr_y], [edge_vb_x, edge_vb_y], [edge_vt_x, edge_vt_y] ] =", "], Lx=Lx, Ly=Ly, dx=dx, dy=dy, lx='x', ly='y',lbar='mask', save=True, filename=f'{out_dir}normal_test_in.png') #Set normal velocities u[edge_hl_x,", "= -1 vt = 2 vl = 0 vr = 0 vb =", "edge_vt_y] ]], ['velocity', velocity], ], Lx=Lx, Ly=Ly, dx=dx, dy=dy, lx='x', ly='y',lbar='mask', save=True, filename=f'{out_dir}normal_test_in.png')", "vl u[edge_hr_x +1, edge_hr_y] = vr v[edge_vb_x, edge_vb_y] = vb v[edge_vt_x, edge_vt_y +", "+1 ] velocity = set_normal_bc(FORCES_MASK, velocity = velocity, velocity_BC = [0,0,0,0]) plot_field(FORCES_MASK, plot_type=['surface'],", "velocity = set_normal_bc(FORCES_MASK, velocity = velocity, velocity_BC = [0,0,0,0]) plot_field(FORCES_MASK, plot_type=['surface'], options=[ ['limits',", "set_normal_bc(FORCES_MASK, velocity = velocity, velocity_BC = [0,0,0,0]) plot_field(FORCES_MASK, plot_type=['surface'], options=[ ['limits', [0, 1]],", "['edges', [ [edge_hl_x, edge_hl_y], [edge_hr_x, edge_hr_y], [edge_vb_x, edge_vb_y], [edge_vt_x, edge_vt_y] ]], ['velocity', velocity],", "# END FUNCTION #################################################### ###################################################### #FINAL FUNCTION ##################################3 out_dir='./' Nx=10 Ny=10 Ly=10 Lx=10", "DOMAIN.staggered_grid(1) # tensor_U = math.wrap(vel.cuda(), 'batch,vector,x,y') # lower = math.wrap(velocity_init.box.lower) # upper =", "D +1, Ly/2 + D -1, Ly/2 + D +1 ] vl =", "] vl = -1 vr = 2 vb = -1 vt = 2", "= Domain(x=Nx, y=Ny, boundaries=[OPEN, STICKY], bounds=Box[0:Lx, 0:Ly]) velocity = ((DOMAIN.staggered_grid(Noise(batch=1)) * 0 )+1)", "import numpy as np from engines.phi.torch.flow import * from numpy.core import shape_base from", "save=True, filename=f'{out_dir}normal_test_in.png') #Set normal velocities u[edge_hl_x, edge_hl_y] = vl u[edge_hr_x +1, edge_hr_y] =", "#Set normal velocities u[edge_hl_x, edge_hl_y] = vl u[edge_hr_x +1, edge_hr_y] = vr v[edge_vb_x,", "edge_hr_x=edge_hr_x, edge_hr_y=edge_hr_y, edge_vb_x=edge_vb_x, edge_vb_y=edge_vb_y, edge_vt_x=edge_vt_x, edge_vt_y=edge_vt_y) velocity = to_numpy(velocity) u = velocity[0] v", "edge_vb_x=edge_vb_x, edge_vb_y=edge_vb_y, edge_vt_x=edge_vt_x, edge_vt_y=edge_vt_y) velocity = to_numpy(velocity) u = velocity[0] v = velocity[1]", "[edge_hr_x, edge_hr_y], [edge_vb_x, edge_vb_y], [edge_vt_x, edge_vt_y] ]], ['velocity', velocity], ], Lx=Lx, Ly=Ly, dx=dx,", "= 2 vl = 0 vr = 0 vb = 0 vt =", "vel[0,0,:,:] = torch.from_numpy(u) # vel[0,1,:,:] = torch.from_numpy(v) # velocity_init = DOMAIN.staggered_grid(1) # tensor_U", "# upper = math.wrap(velocity_init.box.upper) # extrapolation = math.extrapolation.ZERO # tensor_U_unstack = unstack_staggered_tensor(tensor_U) #", "Ly/2 + D +1 ] velocity = set_normal_bc(FORCES_MASK, velocity = velocity, velocity_BC =", "[edge_hl_x, edge_hl_y], [edge_hr_x, edge_hr_y], [edge_vb_x, edge_vb_y], [edge_vt_x, edge_vt_y] ] = get_exterior_edges(FORCES_MASK) [ [edge_hl_x,", "v[edge_vt_x, edge_vt_y + 1] = vt #Pass to phiflow velocity = to_staggered([u,v], Lx,", "import * from analysis.mesure import * from neurasim import * from util.operations.field_operate import", "###################################################### #FINAL FUNCTION ##################################3 out_dir='./' Nx=10 Ny=10 Ly=10 Lx=10 dx=Lx/Nx dy=Ly/Ny xD=5 D=4", "True], ['edges', [ [edge_hl_x, edge_hl_y], [edge_hr_x, edge_hr_y], [edge_vb_x, edge_vb_y], [edge_vt_x, edge_vt_y] ]], ['velocity',", "edge_vt_x=edge_vt_x, edge_vt_y=edge_vt_y) velocity = to_numpy(velocity) u = velocity[0] v = velocity[1] plot_field(FORCES_MASK, plot_type=['surface'],", "Nx=10 Ny=10 Ly=10 Lx=10 dx=Lx/Nx dy=Ly/Ny xD=5 D=4 DOMAIN = Domain(x=Nx, y=Ny, boundaries=[OPEN,", "[edge_hl_x, edge_hl_y], [edge_hr_x, edge_hr_y], [edge_vb_x, edge_vb_y], [edge_vt_x, edge_vt_y] ] = exterior_edge_to_interior_edge(edge_hl_x=edge_hl_x, edge_hl_y=edge_hl_y, edge_hr_x=edge_hr_x,", "BOX_MASK = HardGeometryMask(Box[xD-D:xD+D, Ly/2-D:Ly/2+D]) >> DOMAIN.scalar_grid() FORCES_MASK = HardGeometryMask(Sphere([xD, Ly/2], radius=D/2 )) >>", "= -1 vr = 2 vb = -1 vt = 2 vl =", "to_numpy(velocity) u = velocity[0] v = velocity[1] plot_field(FORCES_MASK, plot_type=['surface'], options=[ ['limits', [0, 1]],", "vb v[edge_vt_x, edge_vt_y + 1] = vt #Pass to phiflow velocity = to_staggered([u,v],", "u[edge_hl_x, edge_hl_y] = vl u[edge_hr_x +1, edge_hr_y] = vr v[edge_vb_x, edge_vb_y] = vb", "[edge_hl_x, edge_hl_y], [edge_hr_x, edge_hr_y], [edge_vb_x, edge_vb_y], [edge_vt_x, edge_vt_y] ]], ['velocity', velocity], ], Lx=Lx,", "= vl u[edge_hr_x +1, edge_hr_y] = vr v[edge_vb_x, edge_vb_y] = vb v[edge_vt_x, edge_vt_y", "edge_vt_y] ]], ['velocity', velocity], ], Lx=Lx, Ly=Ly, dx=dx, dy=dy, lx='x', ly='y',lbar='mask', save=True, filename=f'{out_dir}normal_test_out.png')", "zoom_pos=[xD + D -1, xD + D +1, Ly/2 + D -1, Ly/2", "Ny=10 Ly=10 Lx=10 dx=Lx/Nx dy=Ly/Ny xD=5 D=4 DOMAIN = Domain(x=Nx, y=Ny, boundaries=[OPEN, STICKY],", "velocity = ((DOMAIN.staggered_grid(Noise(batch=1)) * 0 )+1) *(1,1) BOX_MASK = HardGeometryMask(Box[xD-D:xD+D, Ly/2-D:Ly/2+D]) >> DOMAIN.scalar_grid()", ">> DOMAIN.scalar_grid() FORCES_MASK = HardGeometryMask(Sphere([xD, Ly/2], radius=D/2 )) >> DOMAIN.scalar_grid() zoom_pos=[xD + D", "['zoom_position', zoom_pos], ['aux_contourn', False], ['grid', True], ['edges', [ [edge_hl_x, edge_hl_y], [edge_hr_x, edge_hr_y], [edge_vb_x,", "-1, Ly/2 + D +1 ] vl = -1 vr = 2 vb", "D=4 DOMAIN = Domain(x=Nx, y=Ny, boundaries=[OPEN, STICKY], bounds=Box[0:Lx, 0:Ly]) velocity = ((DOMAIN.staggered_grid(Noise(batch=1)) *", "edge_hl_y], [edge_hr_x, edge_hr_y], [edge_vb_x, edge_vb_y], [edge_vt_x, edge_vt_y] ]], ['velocity', velocity], ], Lx=Lx, Ly=Ly,", "Lx=Lx, Ly=Ly, dx=dx, dy=dy, lx='x', ly='y',lbar='mask', save=True, filename=f'{out_dir}normal_test_in.png') #Set normal velocities u[edge_hl_x, edge_hl_y]", "= math.wrap(velocity_init.box.lower) # upper = math.wrap(velocity_init.box.upper) # extrapolation = math.extrapolation.ZERO # tensor_U_unstack =", "from scipy.signal.filter_design import _vratio from util.plot.plot_tools import * from analysis.mesure import * from", "edge_hl_y] = vl u[edge_hr_x +1, edge_hr_y] = vr v[edge_vb_x, edge_vb_y] = vb v[edge_vt_x,", "-1, Ly/2 + D +1 ] velocity = set_normal_bc(FORCES_MASK, velocity = velocity, velocity_BC", "[edge_vt_x, edge_vt_y] ] = exterior_edge_to_interior_edge(edge_hl_x=edge_hl_x, edge_hl_y=edge_hl_y, edge_hr_x=edge_hr_x, edge_hr_y=edge_hr_y, edge_vb_x=edge_vb_x, edge_vb_y=edge_vb_y, edge_vt_x=edge_vt_x, edge_vt_y=edge_vt_y) velocity", "extrapolation = math.extrapolation.ZERO # tensor_U_unstack = unstack_staggered_tensor(tensor_U) # velocity = StaggeredGrid(tensor_U_unstack, geom.Box(lower, upper),", "= velocity, velocity_BC = [0,0,0,0]) plot_field(FORCES_MASK, plot_type=['surface'], options=[ ['limits', [0, 1]], #['full_zoom', True],", "FUNCTION #################################################### ###################################################### #FINAL FUNCTION ##################################3 out_dir='./' Nx=10 Ny=10 Ly=10 Lx=10 dx=Lx/Nx dy=Ly/Ny", "Ly=Ly, dx=dx, dy=dy, lx='x', ly='y',lbar='mask', save=True, filename=f'{out_dir}normal_test_in.png') #Set normal velocities u[edge_hl_x, edge_hl_y] =", "vr v[edge_vb_x, edge_vb_y] = vb v[edge_vt_x, edge_vt_y + 1] = vt #Pass to", "vt #Pass to phiflow velocity = to_staggered([u,v], Lx, Ly) # vel= torch.zeros((1, 2,", "+ D +1 ] vl = -1 vr = 2 vb = -1", "velocity[1] plot_field(FORCES_MASK, plot_type=['surface'], options=[ ['limits', [0, 1]], #['full_zoom', True], ['zoom_position', zoom_pos], ['aux_contourn', False],", "edge_vt_y] ] = exterior_edge_to_interior_edge(edge_hl_x=edge_hl_x, edge_hl_y=edge_hl_y, edge_hr_x=edge_hr_x, edge_hr_y=edge_hr_y, edge_vb_x=edge_vb_x, edge_vb_y=edge_vb_y, edge_vt_x=edge_vt_x, edge_vt_y=edge_vt_y) velocity =", "= [0,0,0,0]) plot_field(FORCES_MASK, plot_type=['surface'], options=[ ['limits', [0, 1]], #['full_zoom', True], ['zoom_position', zoom_pos], ['aux_contourn',", "out_dir='./' Nx=10 Ny=10 Ly=10 Lx=10 dx=Lx/Nx dy=Ly/Ny xD=5 D=4 DOMAIN = Domain(x=Nx, y=Ny,", "math.wrap(velocity_init.box.lower) # upper = math.wrap(velocity_init.box.upper) # extrapolation = math.extrapolation.ZERO # tensor_U_unstack = unstack_staggered_tensor(tensor_U)", "FORCES_MASK = HardGeometryMask(Sphere([xD, Ly/2], radius=D/2 )) >> DOMAIN.scalar_grid() zoom_pos=[xD + D -1, xD", "edge_vb_y], [edge_vt_x, edge_vt_y] ]], ['velocity', velocity], ], Lx=Lx, Ly=Ly, dx=dx, dy=dy, lx='x', ly='y',lbar='mask',", "lower = math.wrap(velocity_init.box.lower) # upper = math.wrap(velocity_init.box.upper) # extrapolation = math.extrapolation.ZERO # tensor_U_unstack", "] = exterior_edge_to_interior_edge(edge_hl_x=edge_hl_x, edge_hl_y=edge_hl_y, edge_hr_x=edge_hr_x, edge_hr_y=edge_hr_y, edge_vb_x=edge_vb_x, edge_vb_y=edge_vb_y, edge_vt_x=edge_vt_x, edge_vt_y=edge_vt_y) velocity = to_numpy(velocity)", "# tensor_U_unstack = unstack_staggered_tensor(tensor_U) # velocity = StaggeredGrid(tensor_U_unstack, geom.Box(lower, upper), extrapolation) # END", "[edge_vb_x, edge_vb_y], [edge_vt_x, edge_vt_y] ]], ['velocity', velocity], ], Lx=Lx, Ly=Ly, dx=dx, dy=dy, lx='x',", "0 vb = 0 vt = 0 #FUNCTION [ [edge_hl_x, edge_hl_y], [edge_hr_x, edge_hr_y],", "# tensor_U = math.wrap(vel.cuda(), 'batch,vector,x,y') # lower = math.wrap(velocity_init.box.lower) # upper = math.wrap(velocity_init.box.upper)", "STICKY], bounds=Box[0:Lx, 0:Ly]) velocity = ((DOMAIN.staggered_grid(Noise(batch=1)) * 0 )+1) *(1,1) BOX_MASK = HardGeometryMask(Box[xD-D:xD+D,", "plot_field(FORCES_MASK, plot_type=['surface'], options=[ ['limits', [0, 1]], #['full_zoom', True], ['zoom_position', zoom_pos], ['aux_contourn', False], ['grid',", "#################################################### ###################################################### #FINAL FUNCTION ##################################3 out_dir='./' Nx=10 Ny=10 Ly=10 Lx=10 dx=Lx/Nx dy=Ly/Ny xD=5", "velocity, velocity_BC = [0,0,0,0]) plot_field(FORCES_MASK, plot_type=['surface'], options=[ ['limits', [0, 1]], #['full_zoom', True], ['zoom_position',", "= math.wrap(velocity_init.box.upper) # extrapolation = math.extrapolation.ZERO # tensor_U_unstack = unstack_staggered_tensor(tensor_U) # velocity =", "[edge_hr_x, edge_hr_y], [edge_vb_x, edge_vb_y], [edge_vt_x, edge_vt_y] ] = get_exterior_edges(FORCES_MASK) [ [edge_hl_x, edge_hl_y], [edge_hr_x,", "0 vr = 0 vb = 0 vt = 0 #FUNCTION [ [edge_hl_x,", "analysis.mesure import * from neurasim import * from util.operations.field_operate import * out_dir='./' Nx=10", "xD + D +1, Ly/2 + D -1, Ly/2 + D +1 ]", "velocity], ], Lx=Lx, Ly=Ly, dx=dx, dy=dy, lx='x', ly='y',lbar='mask', save=True, filename=f'{out_dir}normal_test_in.png') #Set normal velocities", "((DOMAIN.staggered_grid(Noise(batch=1)) * 0 )+1) *(1,1) BOX_MASK = HardGeometryMask(Box[xD-D:xD+D, Ly/2-D:Ly/2+D]) >> DOMAIN.scalar_grid() FORCES_MASK =", "= vb v[edge_vt_x, edge_vt_y + 1] = vt #Pass to phiflow velocity =", "filename=f'{out_dir}normal_test_in.png') #Set normal velocities u[edge_hl_x, edge_hl_y] = vl u[edge_hr_x +1, edge_hr_y] = vr", "from numpy.core import shape_base from scipy.signal.filter_design import _vratio from util.plot.plot_tools import * from", "False], ['grid', True], ['edges', [ [edge_hl_x, edge_hl_y], [edge_hr_x, edge_hr_y], [edge_vb_x, edge_vb_y], [edge_vt_x, edge_vt_y]", "import shape_base from scipy.signal.filter_design import _vratio from util.plot.plot_tools import * from analysis.mesure import", "+1, Ly/2 + D -1, Ly/2 + D +1 ] velocity = set_normal_bc(FORCES_MASK,", "= to_staggered([u,v], Lx, Ly) # vel= torch.zeros((1, 2, Nx+1, Ny+1)) # vel[0,0,:,:] =", "dx=dx, dy=dy, lx='x', ly='y',lbar='mask', save=True, filename=f'{out_dir}normal_test_in.png') #Set normal velocities u[edge_hl_x, edge_hl_y] = vl", "= torch.from_numpy(v) # velocity_init = DOMAIN.staggered_grid(1) # tensor_U = math.wrap(vel.cuda(), 'batch,vector,x,y') # lower", "##################################3 out_dir='./' Nx=10 Ny=10 Ly=10 Lx=10 dx=Lx/Nx dy=Ly/Ny xD=5 D=4 DOMAIN = Domain(x=Nx,", "['limits', [0, 1]], #['full_zoom', True], ['zoom_position', zoom_pos], ['aux_contourn', False], ['grid', True], ['edges', [", "import * from util.operations.field_operate import * out_dir='./' Nx=10 Ny=10 Ly=10 Lx=10 dx=Lx/Nx dy=Ly/Ny", "math.extrapolation.ZERO # tensor_U_unstack = unstack_staggered_tensor(tensor_U) # velocity = StaggeredGrid(tensor_U_unstack, geom.Box(lower, upper), extrapolation) #", "torch.from_numpy(u) # vel[0,1,:,:] = torch.from_numpy(v) # velocity_init = DOMAIN.staggered_grid(1) # tensor_U = math.wrap(vel.cuda(),", "import * out_dir='./' Nx=10 Ny=10 Ly=10 Lx=10 dx=Lx/Nx dy=Ly/Ny xD=5 D=4 DOMAIN =", "vr = 2 vb = -1 vt = 2 vl = 0 vr", "[edge_vb_x, edge_vb_y], [edge_vt_x, edge_vt_y] ] = exterior_edge_to_interior_edge(edge_hl_x=edge_hl_x, edge_hl_y=edge_hl_y, edge_hr_x=edge_hr_x, edge_hr_y=edge_hr_y, edge_vb_x=edge_vb_x, edge_vb_y=edge_vb_y, edge_vt_x=edge_vt_x,", "= exterior_edge_to_interior_edge(edge_hl_x=edge_hl_x, edge_hl_y=edge_hl_y, edge_hr_x=edge_hr_x, edge_hr_y=edge_hr_y, edge_vb_x=edge_vb_x, edge_vb_y=edge_vb_y, edge_vt_x=edge_vt_x, edge_vt_y=edge_vt_y) velocity = to_numpy(velocity) u", "FUNCTION ##################################3 out_dir='./' Nx=10 Ny=10 Ly=10 Lx=10 dx=Lx/Nx dy=Ly/Ny xD=5 D=4 DOMAIN =", "'batch,vector,x,y') # lower = math.wrap(velocity_init.box.lower) # upper = math.wrap(velocity_init.box.upper) # extrapolation = math.extrapolation.ZERO", "upper = math.wrap(velocity_init.box.upper) # extrapolation = math.extrapolation.ZERO # tensor_U_unstack = unstack_staggered_tensor(tensor_U) # velocity", "radius=D/2 )) >> DOMAIN.scalar_grid() zoom_pos=[xD + D -1, xD + D +1, Ly/2", "shape_base from scipy.signal.filter_design import _vratio from util.plot.plot_tools import * from analysis.mesure import *", "Domain(x=Nx, y=Ny, boundaries=[OPEN, STICKY], bounds=Box[0:Lx, 0:Ly]) velocity = ((DOMAIN.staggered_grid(Noise(batch=1)) * 0 )+1) *(1,1)", "v = velocity[1] plot_field(FORCES_MASK, plot_type=['surface'], options=[ ['limits', [0, 1]], #['full_zoom', True], ['zoom_position', zoom_pos],", "= math.wrap(vel.cuda(), 'batch,vector,x,y') # lower = math.wrap(velocity_init.box.lower) # upper = math.wrap(velocity_init.box.upper) # extrapolation", "StaggeredGrid(tensor_U_unstack, geom.Box(lower, upper), extrapolation) # END FUNCTION #################################################### ###################################################### #FINAL FUNCTION ##################################3 out_dir='./'", "DOMAIN.scalar_grid() FORCES_MASK = HardGeometryMask(Sphere([xD, Ly/2], radius=D/2 )) >> DOMAIN.scalar_grid() zoom_pos=[xD + D -1,", "edge_hr_y] = vr v[edge_vb_x, edge_vb_y] = vb v[edge_vt_x, edge_vt_y + 1] = vt", "extrapolation) # END FUNCTION #################################################### ###################################################### #FINAL FUNCTION ##################################3 out_dir='./' Nx=10 Ny=10 Ly=10", "dy=Ly/Ny xD=5 D=4 DOMAIN = Domain(x=Nx, y=Ny, boundaries=[OPEN, STICKY], bounds=Box[0:Lx, 0:Ly]) velocity =", "1]], #['full_zoom', True], ['zoom_position', zoom_pos], ['aux_contourn', False], ['grid', True], ['edges', [ [edge_hl_x, edge_hl_y],", "get_exterior_edges(FORCES_MASK) [ [edge_hl_x, edge_hl_y], [edge_hr_x, edge_hr_y], [edge_vb_x, edge_vb_y], [edge_vt_x, edge_vt_y] ] = exterior_edge_to_interior_edge(edge_hl_x=edge_hl_x,", "1] = vt #Pass to phiflow velocity = to_staggered([u,v], Lx, Ly) # vel=", "[0,0,0,0]) plot_field(FORCES_MASK, plot_type=['surface'], options=[ ['limits', [0, 1]], #['full_zoom', True], ['zoom_position', zoom_pos], ['aux_contourn', False],", "+1, Ly/2 + D -1, Ly/2 + D +1 ] vl = -1", "zoom_pos], ['aux_contourn', False], ['grid', True], ['edges', [ [edge_hl_x, edge_hl_y], [edge_hr_x, edge_hr_y], [edge_vb_x, edge_vb_y],", "<gh_stars>0 import numpy as np from engines.phi.torch.flow import * from numpy.core import shape_base", "Ly/2 + D +1 ] vl = -1 vr = 2 vb =", "[ [edge_hl_x, edge_hl_y], [edge_hr_x, edge_hr_y], [edge_vb_x, edge_vb_y], [edge_vt_x, edge_vt_y] ]], ['velocity', velocity], ],", "vel[0,1,:,:] = torch.from_numpy(v) # velocity_init = DOMAIN.staggered_grid(1) # tensor_U = math.wrap(vel.cuda(), 'batch,vector,x,y') #", "# extrapolation = math.extrapolation.ZERO # tensor_U_unstack = unstack_staggered_tensor(tensor_U) # velocity = StaggeredGrid(tensor_U_unstack, geom.Box(lower,", "Ly/2-D:Ly/2+D]) >> DOMAIN.scalar_grid() FORCES_MASK = HardGeometryMask(Sphere([xD, Ly/2], radius=D/2 )) >> DOMAIN.scalar_grid() zoom_pos=[xD +", "0 #FUNCTION [ [edge_hl_x, edge_hl_y], [edge_hr_x, edge_hr_y], [edge_vb_x, edge_vb_y], [edge_vt_x, edge_vt_y] ] =", "['grid', True], ['edges', [ [edge_hl_x, edge_hl_y], [edge_hr_x, edge_hr_y], [edge_vb_x, edge_vb_y], [edge_vt_x, edge_vt_y] ]],", ">> DOMAIN.scalar_grid() zoom_pos=[xD + D -1, xD + D +1, Ly/2 + D", "+ D -1, Ly/2 + D +1 ] vl = -1 vr =", "= HardGeometryMask(Sphere([xD, Ly/2], radius=D/2 )) >> DOMAIN.scalar_grid() zoom_pos=[xD + D -1, xD +", "u = velocity[0] v = velocity[1] plot_field(FORCES_MASK, plot_type=['surface'], options=[ ['limits', [0, 1]], #['full_zoom',", "edge_vb_y] = vb v[edge_vt_x, edge_vt_y + 1] = vt #Pass to phiflow velocity", "math.wrap(vel.cuda(), 'batch,vector,x,y') # lower = math.wrap(velocity_init.box.lower) # upper = math.wrap(velocity_init.box.upper) # extrapolation =", "torch.zeros((1, 2, Nx+1, Ny+1)) # vel[0,0,:,:] = torch.from_numpy(u) # vel[0,1,:,:] = torch.from_numpy(v) #", "# vel[0,1,:,:] = torch.from_numpy(v) # velocity_init = DOMAIN.staggered_grid(1) # tensor_U = math.wrap(vel.cuda(), 'batch,vector,x,y')", "velocity_BC = [0,0,0,0]) plot_field(FORCES_MASK, plot_type=['surface'], options=[ ['limits', [0, 1]], #['full_zoom', True], ['zoom_position', zoom_pos],", "Lx=10 dx=Lx/Nx dy=Ly/Ny xD=5 D=4 DOMAIN = Domain(x=Nx, y=Ny, boundaries=[OPEN, STICKY], bounds=Box[0:Lx, 0:Ly])", "* out_dir='./' Nx=10 Ny=10 Ly=10 Lx=10 dx=Lx/Nx dy=Ly/Ny xD=5 D=4 DOMAIN = Domain(x=Nx,", "= velocity[1] plot_field(FORCES_MASK, plot_type=['surface'], options=[ ['limits', [0, 1]], #['full_zoom', True], ['zoom_position', zoom_pos], ['aux_contourn',", "= set_normal_bc(FORCES_MASK, velocity = velocity, velocity_BC = [0,0,0,0]) plot_field(FORCES_MASK, plot_type=['surface'], options=[ ['limits', [0,", ")) >> DOMAIN.scalar_grid() zoom_pos=[xD + D -1, xD + D +1, Ly/2 +", "D +1, Ly/2 + D -1, Ly/2 + D +1 ] velocity =", "import * from numpy.core import shape_base from scipy.signal.filter_design import _vratio from util.plot.plot_tools import", "edge_hl_y=edge_hl_y, edge_hr_x=edge_hr_x, edge_hr_y=edge_hr_y, edge_vb_x=edge_vb_x, edge_vb_y=edge_vb_y, edge_vt_x=edge_vt_x, edge_vt_y=edge_vt_y) velocity = to_numpy(velocity) u = velocity[0]", "+ D +1, Ly/2 + D -1, Ly/2 + D +1 ] velocity", "Ly/2 + D -1, Ly/2 + D +1 ] vl = -1 vr", "numpy as np from engines.phi.torch.flow import * from numpy.core import shape_base from scipy.signal.filter_design", ")+1) *(1,1) BOX_MASK = HardGeometryMask(Box[xD-D:xD+D, Ly/2-D:Ly/2+D]) >> DOMAIN.scalar_grid() FORCES_MASK = HardGeometryMask(Sphere([xD, Ly/2], radius=D/2", "#FINAL FUNCTION ##################################3 out_dir='./' Nx=10 Ny=10 Ly=10 Lx=10 dx=Lx/Nx dy=Ly/Ny xD=5 D=4 DOMAIN", "= HardGeometryMask(Box[xD-D:xD+D, Ly/2-D:Ly/2+D]) >> DOMAIN.scalar_grid() FORCES_MASK = HardGeometryMask(Sphere([xD, Ly/2], radius=D/2 )) >> DOMAIN.scalar_grid()", "vt = 2 vl = 0 vr = 0 vb = 0 vt", "0 )+1) *(1,1) BOX_MASK = HardGeometryMask(Box[xD-D:xD+D, Ly/2-D:Ly/2+D]) >> DOMAIN.scalar_grid() FORCES_MASK = HardGeometryMask(Sphere([xD, Ly/2],", "xD=5 D=4 DOMAIN = Domain(x=Nx, y=Ny, boundaries=[OPEN, STICKY], bounds=Box[0:Lx, 0:Ly]) velocity = ((DOMAIN.staggered_grid(Noise(batch=1))", "vl = 0 vr = 0 vb = 0 vt = 0 #FUNCTION", "lx='x', ly='y',lbar='mask', save=True, filename=f'{out_dir}normal_test_in.png') #Set normal velocities u[edge_hl_x, edge_hl_y] = vl u[edge_hr_x +1,", "= 0 vb = 0 vt = 0 #FUNCTION [ [edge_hl_x, edge_hl_y], [edge_hr_x,", "u[edge_hr_x +1, edge_hr_y] = vr v[edge_vb_x, edge_vb_y] = vb v[edge_vt_x, edge_vt_y + 1]", "[edge_hr_x, edge_hr_y], [edge_vb_x, edge_vb_y], [edge_vt_x, edge_vt_y] ] = exterior_edge_to_interior_edge(edge_hl_x=edge_hl_x, edge_hl_y=edge_hl_y, edge_hr_x=edge_hr_x, edge_hr_y=edge_hr_y, edge_vb_x=edge_vb_x,", "Ly/2 + D -1, Ly/2 + D +1 ] velocity = set_normal_bc(FORCES_MASK, velocity", "edge_vt_y=edge_vt_y) velocity = to_numpy(velocity) u = velocity[0] v = velocity[1] plot_field(FORCES_MASK, plot_type=['surface'], options=[", "-1, xD + D +1, Ly/2 + D -1, Ly/2 + D +1", "= vt #Pass to phiflow velocity = to_staggered([u,v], Lx, Ly) # vel= torch.zeros((1,", "unstack_staggered_tensor(tensor_U) # velocity = StaggeredGrid(tensor_U_unstack, geom.Box(lower, upper), extrapolation) # END FUNCTION #################################################### ######################################################", "vr = 0 vb = 0 vt = 0 #FUNCTION [ [edge_hl_x, edge_hl_y],", "edge_vt_y] ] = get_exterior_edges(FORCES_MASK) [ [edge_hl_x, edge_hl_y], [edge_hr_x, edge_hr_y], [edge_vb_x, edge_vb_y], [edge_vt_x, edge_vt_y]", "as np from engines.phi.torch.flow import * from numpy.core import shape_base from scipy.signal.filter_design import", "boundaries=[OPEN, STICKY], bounds=Box[0:Lx, 0:Ly]) velocity = ((DOMAIN.staggered_grid(Noise(batch=1)) * 0 )+1) *(1,1) BOX_MASK =", "* from neurasim import * from util.operations.field_operate import * out_dir='./' Nx=10 Ny=10 Ly=10", "to phiflow velocity = to_staggered([u,v], Lx, Ly) # vel= torch.zeros((1, 2, Nx+1, Ny+1))", "Ny+1)) # vel[0,0,:,:] = torch.from_numpy(u) # vel[0,1,:,:] = torch.from_numpy(v) # velocity_init = DOMAIN.staggered_grid(1)", "= unstack_staggered_tensor(tensor_U) # velocity = StaggeredGrid(tensor_U_unstack, geom.Box(lower, upper), extrapolation) # END FUNCTION ####################################################", "= 2 vb = -1 vt = 2 vl = 0 vr =", "dx=Lx/Nx dy=Ly/Ny xD=5 D=4 DOMAIN = Domain(x=Nx, y=Ny, boundaries=[OPEN, STICKY], bounds=Box[0:Lx, 0:Ly]) velocity", "Ly/2], radius=D/2 )) >> DOMAIN.scalar_grid() zoom_pos=[xD + D -1, xD + D +1,", "edge_hl_y], [edge_hr_x, edge_hr_y], [edge_vb_x, edge_vb_y], [edge_vt_x, edge_vt_y] ] = exterior_edge_to_interior_edge(edge_hl_x=edge_hl_x, edge_hl_y=edge_hl_y, edge_hr_x=edge_hr_x, edge_hr_y=edge_hr_y,", "import _vratio from util.plot.plot_tools import * from analysis.mesure import * from neurasim import", "+ D +1, Ly/2 + D -1, Ly/2 + D +1 ] vl", "upper), extrapolation) # END FUNCTION #################################################### ###################################################### #FINAL FUNCTION ##################################3 out_dir='./' Nx=10 Ny=10", "#['full_zoom', True], ['zoom_position', zoom_pos], ['aux_contourn', False], ['grid', True], ['edges', [ [edge_hl_x, edge_hl_y], [edge_hr_x,", "0 vt = 0 #FUNCTION [ [edge_hl_x, edge_hl_y], [edge_hr_x, edge_hr_y], [edge_vb_x, edge_vb_y], [edge_vt_x,", "neurasim import * from util.operations.field_operate import * out_dir='./' Nx=10 Ny=10 Ly=10 Lx=10 dx=Lx/Nx", "np from engines.phi.torch.flow import * from numpy.core import shape_base from scipy.signal.filter_design import _vratio", "+ D +1 ] velocity = set_normal_bc(FORCES_MASK, velocity = velocity, velocity_BC = [0,0,0,0])", "= ((DOMAIN.staggered_grid(Noise(batch=1)) * 0 )+1) *(1,1) BOX_MASK = HardGeometryMask(Box[xD-D:xD+D, Ly/2-D:Ly/2+D]) >> DOMAIN.scalar_grid() FORCES_MASK", "0:Ly]) velocity = ((DOMAIN.staggered_grid(Noise(batch=1)) * 0 )+1) *(1,1) BOX_MASK = HardGeometryMask(Box[xD-D:xD+D, Ly/2-D:Ly/2+D]) >>", "DOMAIN.scalar_grid() zoom_pos=[xD + D -1, xD + D +1, Ly/2 + D -1,", "= vr v[edge_vb_x, edge_vb_y] = vb v[edge_vt_x, edge_vt_y + 1] = vt #Pass", "engines.phi.torch.flow import * from numpy.core import shape_base from scipy.signal.filter_design import _vratio from util.plot.plot_tools", "#Pass to phiflow velocity = to_staggered([u,v], Lx, Ly) # vel= torch.zeros((1, 2, Nx+1,", "edge_hr_y=edge_hr_y, edge_vb_x=edge_vb_x, edge_vb_y=edge_vb_y, edge_vt_x=edge_vt_x, edge_vt_y=edge_vt_y) velocity = to_numpy(velocity) u = velocity[0] v =", "velocity = velocity, velocity_BC = [0,0,0,0]) plot_field(FORCES_MASK, plot_type=['surface'], options=[ ['limits', [0, 1]], #['full_zoom',", "* from analysis.mesure import * from neurasim import * from util.operations.field_operate import *", "util.operations.field_operate import * out_dir='./' Nx=10 Ny=10 Ly=10 Lx=10 dx=Lx/Nx dy=Ly/Ny xD=5 D=4 DOMAIN", "= 0 vt = 0 #FUNCTION [ [edge_hl_x, edge_hl_y], [edge_hr_x, edge_hr_y], [edge_vb_x, edge_vb_y],", "['aux_contourn', False], ['grid', True], ['edges', [ [edge_hl_x, edge_hl_y], [edge_hr_x, edge_hr_y], [edge_vb_x, edge_vb_y], [edge_vt_x,", "from util.operations.field_operate import * out_dir='./' Nx=10 Ny=10 Ly=10 Lx=10 dx=Lx/Nx dy=Ly/Ny xD=5 D=4", "_vratio from util.plot.plot_tools import * from analysis.mesure import * from neurasim import *", "dy=dy, lx='x', ly='y',lbar='mask', save=True, filename=f'{out_dir}normal_test_in.png') #Set normal velocities u[edge_hl_x, edge_hl_y] = vl u[edge_hr_x", "2, Nx+1, Ny+1)) # vel[0,0,:,:] = torch.from_numpy(u) # vel[0,1,:,:] = torch.from_numpy(v) # velocity_init", "[ [edge_hl_x, edge_hl_y], [edge_hr_x, edge_hr_y], [edge_vb_x, edge_vb_y], [edge_vt_x, edge_vt_y] ] = get_exterior_edges(FORCES_MASK) [", "* from numpy.core import shape_base from scipy.signal.filter_design import _vratio from util.plot.plot_tools import *", "D +1 ] velocity = set_normal_bc(FORCES_MASK, velocity = velocity, velocity_BC = [0,0,0,0]) plot_field(FORCES_MASK,", "torch.from_numpy(v) # velocity_init = DOMAIN.staggered_grid(1) # tensor_U = math.wrap(vel.cuda(), 'batch,vector,x,y') # lower =", "# velocity_init = DOMAIN.staggered_grid(1) # tensor_U = math.wrap(vel.cuda(), 'batch,vector,x,y') # lower = math.wrap(velocity_init.box.lower)", "[edge_vt_x, edge_vt_y] ]], ['velocity', velocity], ], Lx=Lx, Ly=Ly, dx=dx, dy=dy, lx='x', ly='y',lbar='mask', save=True,", "+1, edge_hr_y] = vr v[edge_vb_x, edge_vb_y] = vb v[edge_vt_x, edge_vt_y + 1] =", "2 vl = 0 vr = 0 vb = 0 vt = 0", "edge_hr_y], [edge_vb_x, edge_vb_y], [edge_vt_x, edge_vt_y] ] = get_exterior_edges(FORCES_MASK) [ [edge_hl_x, edge_hl_y], [edge_hr_x, edge_hr_y],", "] velocity = set_normal_bc(FORCES_MASK, velocity = velocity, velocity_BC = [0,0,0,0]) plot_field(FORCES_MASK, plot_type=['surface'], options=[", "edge_hr_y], [edge_vb_x, edge_vb_y], [edge_vt_x, edge_vt_y] ]], ['velocity', velocity], ], Lx=Lx, Ly=Ly, dx=dx, dy=dy,", "[edge_vb_x, edge_vb_y], [edge_vt_x, edge_vt_y] ] = get_exterior_edges(FORCES_MASK) [ [edge_hl_x, edge_hl_y], [edge_hr_x, edge_hr_y], [edge_vb_x,", "v[edge_vb_x, edge_vb_y] = vb v[edge_vt_x, edge_vt_y + 1] = vt #Pass to phiflow", "velocity[0] v = velocity[1] plot_field(FORCES_MASK, plot_type=['surface'], options=[ ['limits', [0, 1]], #['full_zoom', True], ['zoom_position',", "velocity = StaggeredGrid(tensor_U_unstack, geom.Box(lower, upper), extrapolation) # END FUNCTION #################################################### ###################################################### #FINAL FUNCTION", "2 vb = -1 vt = 2 vl = 0 vr = 0", "* from util.operations.field_operate import * out_dir='./' Nx=10 Ny=10 Ly=10 Lx=10 dx=Lx/Nx dy=Ly/Ny xD=5", "vb = 0 vt = 0 #FUNCTION [ [edge_hl_x, edge_hl_y], [edge_hr_x, edge_hr_y], [edge_vb_x,", "*(1,1) BOX_MASK = HardGeometryMask(Box[xD-D:xD+D, Ly/2-D:Ly/2+D]) >> DOMAIN.scalar_grid() FORCES_MASK = HardGeometryMask(Sphere([xD, Ly/2], radius=D/2 ))", "Lx, Ly) # vel= torch.zeros((1, 2, Nx+1, Ny+1)) # vel[0,0,:,:] = torch.from_numpy(u) #", "= 0 vr = 0 vb = 0 vt = 0 #FUNCTION [", "HardGeometryMask(Sphere([xD, Ly/2], radius=D/2 )) >> DOMAIN.scalar_grid() zoom_pos=[xD + D -1, xD + D", "[ [edge_hl_x, edge_hl_y], [edge_hr_x, edge_hr_y], [edge_vb_x, edge_vb_y], [edge_vt_x, edge_vt_y] ] = exterior_edge_to_interior_edge(edge_hl_x=edge_hl_x, edge_hl_y=edge_hl_y,", "[edge_vt_x, edge_vt_y] ] = get_exterior_edges(FORCES_MASK) [ [edge_hl_x, edge_hl_y], [edge_hr_x, edge_hr_y], [edge_vb_x, edge_vb_y], [edge_vt_x,", "* 0 )+1) *(1,1) BOX_MASK = HardGeometryMask(Box[xD-D:xD+D, Ly/2-D:Ly/2+D]) >> DOMAIN.scalar_grid() FORCES_MASK = HardGeometryMask(Sphere([xD,", "#FUNCTION [ [edge_hl_x, edge_hl_y], [edge_hr_x, edge_hr_y], [edge_vb_x, edge_vb_y], [edge_vt_x, edge_vt_y] ] = get_exterior_edges(FORCES_MASK)", "phiflow velocity = to_staggered([u,v], Lx, Ly) # vel= torch.zeros((1, 2, Nx+1, Ny+1)) #", "tensor_U_unstack = unstack_staggered_tensor(tensor_U) # velocity = StaggeredGrid(tensor_U_unstack, geom.Box(lower, upper), extrapolation) # END FUNCTION", "vl = -1 vr = 2 vb = -1 vt = 2 vl", "edge_vb_y=edge_vb_y, edge_vt_x=edge_vt_x, edge_vt_y=edge_vt_y) velocity = to_numpy(velocity) u = velocity[0] v = velocity[1] plot_field(FORCES_MASK,", "+1 ] vl = -1 vr = 2 vb = -1 vt =", "util.plot.plot_tools import * from analysis.mesure import * from neurasim import * from util.operations.field_operate", "velocities u[edge_hl_x, edge_hl_y] = vl u[edge_hr_x +1, edge_hr_y] = vr v[edge_vb_x, edge_vb_y] =", "edge_vb_y], [edge_vt_x, edge_vt_y] ] = exterior_edge_to_interior_edge(edge_hl_x=edge_hl_x, edge_hl_y=edge_hl_y, edge_hr_x=edge_hr_x, edge_hr_y=edge_hr_y, edge_vb_x=edge_vb_x, edge_vb_y=edge_vb_y, edge_vt_x=edge_vt_x, edge_vt_y=edge_vt_y)", "[0, 1]], #['full_zoom', True], ['zoom_position', zoom_pos], ['aux_contourn', False], ['grid', True], ['edges', [ [edge_hl_x,", "exterior_edge_to_interior_edge(edge_hl_x=edge_hl_x, edge_hl_y=edge_hl_y, edge_hr_x=edge_hr_x, edge_hr_y=edge_hr_y, edge_vb_x=edge_vb_x, edge_vb_y=edge_vb_y, edge_vt_x=edge_vt_x, edge_vt_y=edge_vt_y) velocity = to_numpy(velocity) u =", "scipy.signal.filter_design import _vratio from util.plot.plot_tools import * from analysis.mesure import * from neurasim", "tensor_U = math.wrap(vel.cuda(), 'batch,vector,x,y') # lower = math.wrap(velocity_init.box.lower) # upper = math.wrap(velocity_init.box.upper) #", "geom.Box(lower, upper), extrapolation) # END FUNCTION #################################################### ###################################################### #FINAL FUNCTION ##################################3 out_dir='./' Nx=10", "normal velocities u[edge_hl_x, edge_hl_y] = vl u[edge_hr_x +1, edge_hr_y] = vr v[edge_vb_x, edge_vb_y]", "Ly=10 Lx=10 dx=Lx/Nx dy=Ly/Ny xD=5 D=4 DOMAIN = Domain(x=Nx, y=Ny, boundaries=[OPEN, STICKY], bounds=Box[0:Lx,", "y=Ny, boundaries=[OPEN, STICKY], bounds=Box[0:Lx, 0:Ly]) velocity = ((DOMAIN.staggered_grid(Noise(batch=1)) * 0 )+1) *(1,1) BOX_MASK", "= 0 #FUNCTION [ [edge_hl_x, edge_hl_y], [edge_hr_x, edge_hr_y], [edge_vb_x, edge_vb_y], [edge_vt_x, edge_vt_y] ]", "= math.extrapolation.ZERO # tensor_U_unstack = unstack_staggered_tensor(tensor_U) # velocity = StaggeredGrid(tensor_U_unstack, geom.Box(lower, upper), extrapolation)", "D +1 ] vl = -1 vr = 2 vb = -1 vt", "D -1, xD + D +1, Ly/2 + D -1, Ly/2 + D", "bounds=Box[0:Lx, 0:Ly]) velocity = ((DOMAIN.staggered_grid(Noise(batch=1)) * 0 )+1) *(1,1) BOX_MASK = HardGeometryMask(Box[xD-D:xD+D, Ly/2-D:Ly/2+D])", "velocity = to_staggered([u,v], Lx, Ly) # vel= torch.zeros((1, 2, Nx+1, Ny+1)) # vel[0,0,:,:]", "= DOMAIN.staggered_grid(1) # tensor_U = math.wrap(vel.cuda(), 'batch,vector,x,y') # lower = math.wrap(velocity_init.box.lower) # upper", "from analysis.mesure import * from neurasim import * from util.operations.field_operate import * out_dir='./'", "options=[ ['limits', [0, 1]], #['full_zoom', True], ['zoom_position', zoom_pos], ['aux_contourn', False], ['grid', True], ['edges',", "from neurasim import * from util.operations.field_operate import * out_dir='./' Nx=10 Ny=10 Ly=10 Lx=10", "# vel= torch.zeros((1, 2, Nx+1, Ny+1)) # vel[0,0,:,:] = torch.from_numpy(u) # vel[0,1,:,:] =", "]], ['velocity', velocity], ], Lx=Lx, Ly=Ly, dx=dx, dy=dy, lx='x', ly='y',lbar='mask', save=True, filename=f'{out_dir}normal_test_in.png') #Set", "vt = 0 #FUNCTION [ [edge_hl_x, edge_hl_y], [edge_hr_x, edge_hr_y], [edge_vb_x, edge_vb_y], [edge_vt_x, edge_vt_y]", "velocity_init = DOMAIN.staggered_grid(1) # tensor_U = math.wrap(vel.cuda(), 'batch,vector,x,y') # lower = math.wrap(velocity_init.box.lower) #", "= StaggeredGrid(tensor_U_unstack, geom.Box(lower, upper), extrapolation) # END FUNCTION #################################################### ###################################################### #FINAL FUNCTION ##################################3", "+ D -1, Ly/2 + D +1 ] velocity = set_normal_bc(FORCES_MASK, velocity =", "-1 vr = 2 vb = -1 vt = 2 vl = 0", "to_staggered([u,v], Lx, Ly) # vel= torch.zeros((1, 2, Nx+1, Ny+1)) # vel[0,0,:,:] = torch.from_numpy(u)", "math.wrap(velocity_init.box.upper) # extrapolation = math.extrapolation.ZERO # tensor_U_unstack = unstack_staggered_tensor(tensor_U) # velocity = StaggeredGrid(tensor_U_unstack,", "from util.plot.plot_tools import * from analysis.mesure import * from neurasim import * from", "edge_vt_y + 1] = vt #Pass to phiflow velocity = to_staggered([u,v], Lx, Ly)", "vel= torch.zeros((1, 2, Nx+1, Ny+1)) # vel[0,0,:,:] = torch.from_numpy(u) # vel[0,1,:,:] = torch.from_numpy(v)", "D -1, Ly/2 + D +1 ] vl = -1 vr = 2", "numpy.core import shape_base from scipy.signal.filter_design import _vratio from util.plot.plot_tools import * from analysis.mesure", "] = get_exterior_edges(FORCES_MASK) [ [edge_hl_x, edge_hl_y], [edge_hr_x, edge_hr_y], [edge_vb_x, edge_vb_y], [edge_vt_x, edge_vt_y] ]", "# vel[0,0,:,:] = torch.from_numpy(u) # vel[0,1,:,:] = torch.from_numpy(v) # velocity_init = DOMAIN.staggered_grid(1) #", "edge_hr_y], [edge_vb_x, edge_vb_y], [edge_vt_x, edge_vt_y] ] = exterior_edge_to_interior_edge(edge_hl_x=edge_hl_x, edge_hl_y=edge_hl_y, edge_hr_x=edge_hr_x, edge_hr_y=edge_hr_y, edge_vb_x=edge_vb_x, edge_vb_y=edge_vb_y,", "['velocity', velocity], ], Lx=Lx, Ly=Ly, dx=dx, dy=dy, lx='x', ly='y',lbar='mask', save=True, filename=f'{out_dir}normal_test_in.png') #Set normal", "ly='y',lbar='mask', save=True, filename=f'{out_dir}normal_test_in.png') #Set normal velocities u[edge_hl_x, edge_hl_y] = vl u[edge_hr_x +1, edge_hr_y]", "+ D -1, xD + D +1, Ly/2 + D -1, Ly/2 +", "-1 vt = 2 vl = 0 vr = 0 vb = 0", "= torch.from_numpy(u) # vel[0,1,:,:] = torch.from_numpy(v) # velocity_init = DOMAIN.staggered_grid(1) # tensor_U =", "# lower = math.wrap(velocity_init.box.lower) # upper = math.wrap(velocity_init.box.upper) # extrapolation = math.extrapolation.ZERO #" ]
[ "state_vec[-1] u=state_vec[0:-1] res = np.concatenate(( periodicity_cond(u, dudt, T), phase_cond(u, dudt), )) return res", "order differential equations USAGE: shooting(state_vec, dudt) INPUTS: state_vec : ndarray the state_vector to", "condition of a BVP subject to the first order differential equations USAGE: shooting(state_vec,", "differential equations USAGE: shooting(state_vec, dudt) INPUTS: state_vec : ndarray the state_vector to solve,", "t from starting position U res = np.array(u - solve_ivp(dudt, (0, T), u).y[:,-1])", "import numpy as np def phase_cond(u, dudt): res= np.array(dudt(0,u)) return res def periodicity_cond(u,", "= state_vec[-1] u=state_vec[0:-1] res = np.concatenate(( periodicity_cond(u, dudt, T), phase_cond(u, dudt), )) return", "starting position U res = np.array(u - solve_ivp(dudt, (0, T), u).y[:,-1]) return res", "to be solved ---------- OUTPUT : an ndarray containing the corrected initial values", "if sol[\"success\"] == True: print(\"Root finder found the solution u={} after {} function", "res def periodicity_cond(u, dudt, T): # integrate the ode for time t from", "function that returns an estimation of the starting condition of a BVP subject", ": ndarray the state_vector to solve, [u0...uN,T] the final argument should be the", "integrate the ode for time t from starting position U res = np.array(u", "u={} after {} function calls\" .format(sol[\"x\"], sol[\"nfev\"])) return sol[\"x\"] else: print(\"Root finder failed", "solve_ivp import numpy as np def phase_cond(u, dudt): res= np.array(dudt(0,u)) return res def", "res = np.array(u - solve_ivp(dudt, (0, T), u).y[:,-1]) return res def g(state_vec, dudt):", "with npc however it is also currently passing all of its tests \"\"\"", "T), phase_cond(u, dudt), )) return res def shooting(state_vec, dudt): \"\"\" A function that", "cycle. dudt : ndarray containing the first order differtial equations to be solved", "solved ---------- OUTPUT : an ndarray containing the corrected initial values for the", "from starting position U res = np.array(u - solve_ivp(dudt, (0, T), u).y[:,-1]) return", "subject to the first order differential equations USAGE: shooting(state_vec, dudt) INPUTS: state_vec :", "be solved ---------- OUTPUT : an ndarray containing the corrected initial values for", "OUTPUT : an ndarray containing the corrected initial values for the limit cycle.", "BVP subject to the first order differential equations USAGE: shooting(state_vec, dudt) INPUTS: state_vec", "for time t from starting position U res = np.array(u - solve_ivp(dudt, (0,", "also currently passing all of its tests \"\"\" sol = root(g, state_vec, args=(dudt,),", "its tests \"\"\" sol = root(g, state_vec, args=(dudt,), method=\"lm\") if sol[\"success\"] == True:", "estimation of the starting condition of a BVP subject to the first order", "limit cycle or the period of the limit cycle. dudt : ndarray containing", "root from scipy.integrate import solve_ivp import numpy as np def phase_cond(u, dudt): res=", ")) return res def shooting(state_vec, dudt): \"\"\" A function that returns an estimation", "u).y[:,-1]) return res def g(state_vec, dudt): T = state_vec[-1] u=state_vec[0:-1] res = np.concatenate((", "scipy.integrate import solve_ivp import numpy as np def phase_cond(u, dudt): res= np.array(dudt(0,u)) return", "def phase_cond(u, dudt): res= np.array(dudt(0,u)) return res def periodicity_cond(u, dudt, T): # integrate", "shooting(state_vec, dudt): \"\"\" A function that returns an estimation of the starting condition", "dudt, T), phase_cond(u, dudt), )) return res def shooting(state_vec, dudt): \"\"\" A function", "should be the expected period of the limit cycle or the period of", "root(g, state_vec, args=(dudt,), method=\"lm\") if sol[\"success\"] == True: print(\"Root finder found the solution", "periodicity_cond(u, dudt, T): # integrate the ode for time t from starting position", "of the limit cycle. dudt : ndarray containing the first order differtial equations", "dudt : ndarray containing the first order differtial equations to be solved ----------", "passing all of its tests \"\"\" sol = root(g, state_vec, args=(dudt,), method=\"lm\") if", "True: print(\"Root finder found the solution u={} after {} function calls\" .format(sol[\"x\"], sol[\"nfev\"]))", "argument should be the expected period of the limit cycle or the period", "[u0...uN,T] the final argument should be the expected period of the limit cycle", "sol[\"nfev\"])) return sol[\"x\"] else: print(\"Root finder failed with error message: {}\".format(sol[\"message\"])) return None", "def shooting(state_vec, dudt): \"\"\" A function that returns an estimation of the starting", "solve, [u0...uN,T] the final argument should be the expected period of the limit", "period of the limit cycle or the period of the limit cycle. dudt", "of the limit cycle or the period of the limit cycle. dudt :", "equations to be solved ---------- OUTPUT : an ndarray containing the corrected initial", "an ndarray containing the corrected initial values for the limit cycle. NOTE: This", "A function that returns an estimation of the starting condition of a BVP", "as np def phase_cond(u, dudt): res= np.array(dudt(0,u)) return res def periodicity_cond(u, dudt, T):", "dudt, T): # integrate the ode for time t from starting position U", "having issues when used with npc however it is also currently passing all", "npc however it is also currently passing all of its tests \"\"\" sol", "tests \"\"\" sol = root(g, state_vec, args=(dudt,), method=\"lm\") if sol[\"success\"] == True: print(\"Root", "\"\"\" sol = root(g, state_vec, args=(dudt,), method=\"lm\") if sol[\"success\"] == True: print(\"Root finder", "solve_ivp(dudt, (0, T), u).y[:,-1]) return res def g(state_vec, dudt): T = state_vec[-1] u=state_vec[0:-1]", "the limit cycle. NOTE: This function is currently having issues when used with", "res def shooting(state_vec, dudt): \"\"\" A function that returns an estimation of the", "np.array(u - solve_ivp(dudt, (0, T), u).y[:,-1]) return res def g(state_vec, dudt): T =", "the state_vector to solve, [u0...uN,T] the final argument should be the expected period", "the ode for time t from starting position U res = np.array(u -", "= root(g, state_vec, args=(dudt,), method=\"lm\") if sol[\"success\"] == True: print(\"Root finder found the", "calls\" .format(sol[\"x\"], sol[\"nfev\"])) return sol[\"x\"] else: print(\"Root finder failed with error message: {}\".format(sol[\"message\"]))", "period of the limit cycle. dudt : ndarray containing the first order differtial", "res = np.concatenate(( periodicity_cond(u, dudt, T), phase_cond(u, dudt), )) return res def shooting(state_vec,", "the first order differential equations USAGE: shooting(state_vec, dudt) INPUTS: state_vec : ndarray the", "found the solution u={} after {} function calls\" .format(sol[\"x\"], sol[\"nfev\"])) return sol[\"x\"] else:", "issues when used with npc however it is also currently passing all of", "limit cycle. NOTE: This function is currently having issues when used with npc", "USAGE: shooting(state_vec, dudt) INPUTS: state_vec : ndarray the state_vector to solve, [u0...uN,T] the", "first order differential equations USAGE: shooting(state_vec, dudt) INPUTS: state_vec : ndarray the state_vector", "however it is also currently passing all of its tests \"\"\" sol =", "solution u={} after {} function calls\" .format(sol[\"x\"], sol[\"nfev\"])) return sol[\"x\"] else: print(\"Root finder", "of the starting condition of a BVP subject to the first order differential", "scipy.optimize import root from scipy.integrate import solve_ivp import numpy as np def phase_cond(u,", "cycle. NOTE: This function is currently having issues when used with npc however", "periodicity_cond(u, dudt, T), phase_cond(u, dudt), )) return res def shooting(state_vec, dudt): \"\"\" A", "state_vector to solve, [u0...uN,T] the final argument should be the expected period of", "ode for time t from starting position U res = np.array(u - solve_ivp(dudt,", "U res = np.array(u - solve_ivp(dudt, (0, T), u).y[:,-1]) return res def g(state_vec,", "all of its tests \"\"\" sol = root(g, state_vec, args=(dudt,), method=\"lm\") if sol[\"success\"]", "for the limit cycle. NOTE: This function is currently having issues when used", "currently having issues when used with npc however it is also currently passing", "containing the first order differtial equations to be solved ---------- OUTPUT : an", "(0, T), u).y[:,-1]) return res def g(state_vec, dudt): T = state_vec[-1] u=state_vec[0:-1] res", "\"\"\" A function that returns an estimation of the starting condition of a", "dudt): T = state_vec[-1] u=state_vec[0:-1] res = np.concatenate(( periodicity_cond(u, dudt, T), phase_cond(u, dudt),", "def g(state_vec, dudt): T = state_vec[-1] u=state_vec[0:-1] res = np.concatenate(( periodicity_cond(u, dudt, T),", "np def phase_cond(u, dudt): res= np.array(dudt(0,u)) return res def periodicity_cond(u, dudt, T): #", "res def g(state_vec, dudt): T = state_vec[-1] u=state_vec[0:-1] res = np.concatenate(( periodicity_cond(u, dudt,", "finder found the solution u={} after {} function calls\" .format(sol[\"x\"], sol[\"nfev\"])) return sol[\"x\"]", "method=\"lm\") if sol[\"success\"] == True: print(\"Root finder found the solution u={} after {}", "of a BVP subject to the first order differential equations USAGE: shooting(state_vec, dudt)", "function is currently having issues when used with npc however it is also", "or the period of the limit cycle. dudt : ndarray containing the first", "res= np.array(dudt(0,u)) return res def periodicity_cond(u, dudt, T): # integrate the ode for", "dudt): \"\"\" A function that returns an estimation of the starting condition of", "the expected period of the limit cycle or the period of the limit", "import root from scipy.integrate import solve_ivp import numpy as np def phase_cond(u, dudt):", "values for the limit cycle. NOTE: This function is currently having issues when", "is currently having issues when used with npc however it is also currently", "args=(dudt,), method=\"lm\") if sol[\"success\"] == True: print(\"Root finder found the solution u={} after", "after {} function calls\" .format(sol[\"x\"], sol[\"nfev\"])) return sol[\"x\"] else: print(\"Root finder failed with", "INPUTS: state_vec : ndarray the state_vector to solve, [u0...uN,T] the final argument should", "the corrected initial values for the limit cycle. NOTE: This function is currently", "ndarray containing the first order differtial equations to be solved ---------- OUTPUT :", "first order differtial equations to be solved ---------- OUTPUT : an ndarray containing", "phase_cond(u, dudt): res= np.array(dudt(0,u)) return res def periodicity_cond(u, dudt, T): # integrate the", "T): # integrate the ode for time t from starting position U res", "time t from starting position U res = np.array(u - solve_ivp(dudt, (0, T),", "the limit cycle. dudt : ndarray containing the first order differtial equations to", "to solve, [u0...uN,T] the final argument should be the expected period of the", "equations USAGE: shooting(state_vec, dudt) INPUTS: state_vec : ndarray the state_vector to solve, [u0...uN,T]", "def periodicity_cond(u, dudt, T): # integrate the ode for time t from starting", "used with npc however it is also currently passing all of its tests", "final argument should be the expected period of the limit cycle or the", "T), u).y[:,-1]) return res def g(state_vec, dudt): T = state_vec[-1] u=state_vec[0:-1] res =", "position U res = np.array(u - solve_ivp(dudt, (0, T), u).y[:,-1]) return res def", ": an ndarray containing the corrected initial values for the limit cycle. NOTE:", "---------- OUTPUT : an ndarray containing the corrected initial values for the limit", "np.concatenate(( periodicity_cond(u, dudt, T), phase_cond(u, dudt), )) return res def shooting(state_vec, dudt): \"\"\"", "g(state_vec, dudt): T = state_vec[-1] u=state_vec[0:-1] res = np.concatenate(( periodicity_cond(u, dudt, T), phase_cond(u,", "order differtial equations to be solved ---------- OUTPUT : an ndarray containing the", "- solve_ivp(dudt, (0, T), u).y[:,-1]) return res def g(state_vec, dudt): T = state_vec[-1]", "the period of the limit cycle. dudt : ndarray containing the first order", "sol[\"success\"] == True: print(\"Root finder found the solution u={} after {} function calls\"", "return res def g(state_vec, dudt): T = state_vec[-1] u=state_vec[0:-1] res = np.concatenate(( periodicity_cond(u,", "that returns an estimation of the starting condition of a BVP subject to", "T = state_vec[-1] u=state_vec[0:-1] res = np.concatenate(( periodicity_cond(u, dudt, T), phase_cond(u, dudt), ))", "= np.array(u - solve_ivp(dudt, (0, T), u).y[:,-1]) return res def g(state_vec, dudt): T", "corrected initial values for the limit cycle. NOTE: This function is currently having", "return res def shooting(state_vec, dudt): \"\"\" A function that returns an estimation of", ": ndarray containing the first order differtial equations to be solved ---------- OUTPUT", "returns an estimation of the starting condition of a BVP subject to the", "starting condition of a BVP subject to the first order differential equations USAGE:", ".format(sol[\"x\"], sol[\"nfev\"])) return sol[\"x\"] else: print(\"Root finder failed with error message: {}\".format(sol[\"message\"])) return", "NOTE: This function is currently having issues when used with npc however it", "of its tests \"\"\" sol = root(g, state_vec, args=(dudt,), method=\"lm\") if sol[\"success\"] ==", "This function is currently having issues when used with npc however it is", "the solution u={} after {} function calls\" .format(sol[\"x\"], sol[\"nfev\"])) return sol[\"x\"] else: print(\"Root", "cycle or the period of the limit cycle. dudt : ndarray containing the", "dudt): res= np.array(dudt(0,u)) return res def periodicity_cond(u, dudt, T): # integrate the ode", "be the expected period of the limit cycle or the period of the", "dudt) INPUTS: state_vec : ndarray the state_vector to solve, [u0...uN,T] the final argument", "currently passing all of its tests \"\"\" sol = root(g, state_vec, args=(dudt,), method=\"lm\")", "u=state_vec[0:-1] res = np.concatenate(( periodicity_cond(u, dudt, T), phase_cond(u, dudt), )) return res def", "when used with npc however it is also currently passing all of its", "= np.concatenate(( periodicity_cond(u, dudt, T), phase_cond(u, dudt), )) return res def shooting(state_vec, dudt):", "numpy as np def phase_cond(u, dudt): res= np.array(dudt(0,u)) return res def periodicity_cond(u, dudt,", "the first order differtial equations to be solved ---------- OUTPUT : an ndarray", "sol = root(g, state_vec, args=(dudt,), method=\"lm\") if sol[\"success\"] == True: print(\"Root finder found", "function calls\" .format(sol[\"x\"], sol[\"nfev\"])) return sol[\"x\"] else: print(\"Root finder failed with error message:", "print(\"Root finder found the solution u={} after {} function calls\" .format(sol[\"x\"], sol[\"nfev\"])) return", "to the first order differential equations USAGE: shooting(state_vec, dudt) INPUTS: state_vec : ndarray", "an estimation of the starting condition of a BVP subject to the first", "return res def periodicity_cond(u, dudt, T): # integrate the ode for time t", "{} function calls\" .format(sol[\"x\"], sol[\"nfev\"])) return sol[\"x\"] else: print(\"Root finder failed with error", "ndarray the state_vector to solve, [u0...uN,T] the final argument should be the expected", "the final argument should be the expected period of the limit cycle or", "from scipy.optimize import root from scipy.integrate import solve_ivp import numpy as np def", "state_vec : ndarray the state_vector to solve, [u0...uN,T] the final argument should be", "containing the corrected initial values for the limit cycle. NOTE: This function is", "import solve_ivp import numpy as np def phase_cond(u, dudt): res= np.array(dudt(0,u)) return res", "expected period of the limit cycle or the period of the limit cycle.", "shooting(state_vec, dudt) INPUTS: state_vec : ndarray the state_vector to solve, [u0...uN,T] the final", "# integrate the ode for time t from starting position U res =", "initial values for the limit cycle. NOTE: This function is currently having issues", "is also currently passing all of its tests \"\"\" sol = root(g, state_vec,", "from scipy.integrate import solve_ivp import numpy as np def phase_cond(u, dudt): res= np.array(dudt(0,u))", "limit cycle. dudt : ndarray containing the first order differtial equations to be", "a BVP subject to the first order differential equations USAGE: shooting(state_vec, dudt) INPUTS:", "differtial equations to be solved ---------- OUTPUT : an ndarray containing the corrected", "dudt), )) return res def shooting(state_vec, dudt): \"\"\" A function that returns an", "the starting condition of a BVP subject to the first order differential equations", "ndarray containing the corrected initial values for the limit cycle. NOTE: This function", "state_vec, args=(dudt,), method=\"lm\") if sol[\"success\"] == True: print(\"Root finder found the solution u={}", "np.array(dudt(0,u)) return res def periodicity_cond(u, dudt, T): # integrate the ode for time", "it is also currently passing all of its tests \"\"\" sol = root(g,", "== True: print(\"Root finder found the solution u={} after {} function calls\" .format(sol[\"x\"],", "the limit cycle or the period of the limit cycle. dudt : ndarray", "phase_cond(u, dudt), )) return res def shooting(state_vec, dudt): \"\"\" A function that returns" ]
[ "Start=%d, End=%d, Ratio=%f, Time=%f\" % (start_packets, end_packets, float(end_packets)/start_packets, en-st) # Now we start", "end terminals for index in xrange(1, len(lucky_path)-2): new = False if (lucky_path[index],lucky_path[index+1]) in", "en = time.time() print \"Compression: Start=%d, End=%d, Ratio=%f, Time=%f\" % (start_packets, end_packets, float(end_packets)/start_packets,", "in links: links.remove((lucky_path[index],lucky_path[index+1])) break end_packets = len(result_rule_lists) en = time.time() print \"Compression: Start=%d,", "= open('data/output_filtered.csv', 'w') for line in results_file: components = line.split(',') source = components[1].strip('\\\"')", "xrange(1, len(lucky_path)-2): new = False if (lucky_path[index],lucky_path[index+1]) in links: new = True result_rule_lists.append(lucky_path)", "# Break the path into links, excluding the end terminals for index in", "hit already if new: for index2 in xrange(1, len(lucky_path)-2): if (lucky_path[index],lucky_path[index+1]) in links:", "random.randint(0, len(rule_lists)-1) lucky_path = rule_lists[lucky_index] # Break the path into links, excluding the", "result_rule_lists = [] st = time.time() # Remove end links new_links = copy.deepcopy(links)", "have been hit already if new: for index2 in xrange(1, len(lucky_path)-2): if (lucky_path[index],lucky_path[index+1])", "3: Filter results_file = open('data/output.csv') new_results_file = open('data/output_filtered.csv', 'w') for line in results_file:", "# Step 1: Build \"DNS\" hosts_file = open('data/hosts.txt') ips_file = open('data/ips.txt') ip_to_host_dict =", "components[1].strip('\\\"') try: destination = ip_to_host_dict[components[2].strip('\\\"')] except: continue if (source, destination) in test_pairs or", "<reponame>jstavr/SDN_Project #!/usr/bin/python import networkx as nx import time, random, copy topology_file = open(\"data/topology.data\")", "new = False if (lucky_path[index],lucky_path[index+1]) in links: new = True result_rule_lists.append(lucky_path) # Rules", "= random.randint(0, len(rule_lists)-1) lucky_path = rule_lists[lucky_index] # Break the path into links, excluding", "# Now we start to filter CSV file to select ones that we're", "destination != source: rule_lists.append(shortest_paths[source][destination]) except: pass start_packets = len(rule_lists) result_rule_lists = [] st", "(start_packets, end_packets, float(end_packets)/start_packets, en-st) # Now we start to filter CSV file to", "networkx as nx import time, random, copy topology_file = open(\"data/topology.data\") G=nx.read_edgelist(topology_file) topology_file.close() #Only", "in ips_file: host = hosts_file.readline().split('.')[0] ip_to_host_dict[ip.strip()] = host hosts_file.close() ips_file.close() # Step 2:", "range(1, 100)] links = G.edges() shortest_paths = nx.shortest_path(G) rule_lists = [] for source", "100)] links = G.edges() shortest_paths = nx.shortest_path(G) rule_lists = [] for source in", "1: Build \"DNS\" hosts_file = open('data/hosts.txt') ips_file = open('data/ips.txt') ip_to_host_dict = {} for", "shortest_paths = nx.shortest_path(G) rule_lists = [] for source in end_terminals: for destination in", "into links, excluding the end terminals for index in xrange(1, len(lucky_path)-2): new =", "in results_file: components = line.split(',') source = components[1].strip('\\\"') try: destination = ip_to_host_dict[components[2].strip('\\\"')] except:", "#!/usr/bin/python import networkx as nx import time, random, copy topology_file = open(\"data/topology.data\") G=nx.read_edgelist(topology_file)", "len(lucky_path)-2): if (lucky_path[index],lucky_path[index+1]) in links: links.remove((lucky_path[index],lucky_path[index+1])) break end_packets = len(result_rule_lists) en = time.time()", "path into links, excluding the end terminals for index in xrange(1, len(lucky_path)-2): new", "new = True result_rule_lists.append(lucky_path) # Rules that have been hit already if new:", "topology_file.close() #Only numbers are end terminals end_terminals = [unicode(str(x)) for x in range(1,", "lucky_path = rule_lists[lucky_index] # Break the path into links, excluding the end terminals", "open('data/output.csv') new_results_file = open('data/output_filtered.csv', 'w') for line in results_file: components = line.split(',') source", "Now we start to filter CSV file to select ones that we're interested", "links: links.remove((lucky_path[index],lucky_path[index+1])) break end_packets = len(result_rule_lists) en = time.time() print \"Compression: Start=%d, End=%d,", "import networkx as nx import time, random, copy topology_file = open(\"data/topology.data\") G=nx.read_edgelist(topology_file) topology_file.close()", "= [] for rule_list in result_rule_lists: test_pairs.append((\"swan-ap%s\"%rule_list[0], \"swan-ap%s\"%rule_list[-1])) # Step 3: Filter results_file", "test pairs test_pairs = [] for rule_list in result_rule_lists: test_pairs.append((\"swan-ap%s\"%rule_list[0], \"swan-ap%s\"%rule_list[-1])) # Step", "= [unicode(str(x)) for x in range(1, 100)] links = G.edges() shortest_paths = nx.shortest_path(G)", "Ratio=%f, Time=%f\" % (start_packets, end_packets, float(end_packets)/start_packets, en-st) # Now we start to filter", "G=nx.read_edgelist(topology_file) topology_file.close() #Only numbers are end terminals end_terminals = [unicode(str(x)) for x in", "to filter CSV file to select ones that we're interested in. # Step", "for ip in ips_file: host = hosts_file.readline().split('.')[0] ip_to_host_dict[ip.strip()] = host hosts_file.close() ips_file.close() #", "line.split(',') source = components[1].strip('\\\"') try: destination = ip_to_host_dict[components[2].strip('\\\"')] except: continue if (source, destination)", "the end terminals for index in xrange(1, len(lucky_path)-2): new = False if (lucky_path[index],lucky_path[index+1])", "for index2 in xrange(1, len(lucky_path)-2): if (lucky_path[index],lucky_path[index+1]) in links: links.remove((lucky_path[index],lucky_path[index+1])) break end_packets =", "results_file: components = line.split(',') source = components[1].strip('\\\"') try: destination = ip_to_host_dict[components[2].strip('\\\"')] except: continue", "index in xrange(1, len(lucky_path)-2): new = False if (lucky_path[index],lucky_path[index+1]) in links: new =", "Build test pairs test_pairs = [] for rule_list in result_rule_lists: test_pairs.append((\"swan-ap%s\"%rule_list[0], \"swan-ap%s\"%rule_list[-1])) #", "ip_to_host_dict[ip.strip()] = host hosts_file.close() ips_file.close() # Step 2: Build test pairs test_pairs =", "Step 3: Filter results_file = open('data/output.csv') new_results_file = open('data/output_filtered.csv', 'w') for line in", "line in results_file: components = line.split(',') source = components[1].strip('\\\"') try: destination = ip_to_host_dict[components[2].strip('\\\"')]", "= [] for source in end_terminals: for destination in end_terminals: try: if destination", "results_file = open('data/output.csv') new_results_file = open('data/output_filtered.csv', 'w') for line in results_file: components =", "try: if destination != source: rule_lists.append(shortest_paths[source][destination]) except: pass start_packets = len(rule_lists) result_rule_lists =", "end_terminals or destination in end_terminals: new_links.remove(link) links = new_links # Min-Set-Cover while len(links)", "= time.time() print \"Compression: Start=%d, End=%d, Ratio=%f, Time=%f\" % (start_packets, end_packets, float(end_packets)/start_packets, en-st)", "or destination in end_terminals: new_links.remove(link) links = new_links # Min-Set-Cover while len(links) >", "\"Compression: Start=%d, End=%d, Ratio=%f, Time=%f\" % (start_packets, end_packets, float(end_packets)/start_packets, en-st) # Now we", "links.remove((lucky_path[index],lucky_path[index+1])) break end_packets = len(result_rule_lists) en = time.time() print \"Compression: Start=%d, End=%d, Ratio=%f,", "file to select ones that we're interested in. # Step 1: Build \"DNS\"", "select ones that we're interested in. # Step 1: Build \"DNS\" hosts_file =", "= {} for ip in ips_file: host = hosts_file.readline().split('.')[0] ip_to_host_dict[ip.strip()] = host hosts_file.close()", "rule_lists.append(shortest_paths[source][destination]) except: pass start_packets = len(rule_lists) result_rule_lists = [] st = time.time() #", "links, excluding the end terminals for index in xrange(1, len(lucky_path)-2): new = False", "result_rule_lists.append(lucky_path) # Rules that have been hit already if new: for index2 in", "in end_terminals: try: if destination != source: rule_lists.append(shortest_paths[source][destination]) except: pass start_packets = len(rule_lists)", "link if source in end_terminals or destination in end_terminals: new_links.remove(link) links = new_links", "Break the path into links, excluding the end terminals for index in xrange(1,", "except: pass start_packets = len(rule_lists) result_rule_lists = [] st = time.time() # Remove", "new_links = copy.deepcopy(links) for link in links: (source, destination) = link if source", "# Rules that have been hit already if new: for index2 in xrange(1,", "= time.time() # Remove end links new_links = copy.deepcopy(links) for link in links:", "source = components[1].strip('\\\"') try: destination = ip_to_host_dict[components[2].strip('\\\"')] except: continue if (source, destination) in", "time.time() print \"Compression: Start=%d, End=%d, Ratio=%f, Time=%f\" % (start_packets, end_packets, float(end_packets)/start_packets, en-st) #", "End=%d, Ratio=%f, Time=%f\" % (start_packets, end_packets, float(end_packets)/start_packets, en-st) # Now we start to", "we're interested in. # Step 1: Build \"DNS\" hosts_file = open('data/hosts.txt') ips_file =", "if (lucky_path[index],lucky_path[index+1]) in links: new = True result_rule_lists.append(lucky_path) # Rules that have been", "been hit already if new: for index2 in xrange(1, len(lucky_path)-2): if (lucky_path[index],lucky_path[index+1]) in", "end_terminals: for destination in end_terminals: try: if destination != source: rule_lists.append(shortest_paths[source][destination]) except: pass", "= host hosts_file.close() ips_file.close() # Step 2: Build test pairs test_pairs = []", "(lucky_path[index],lucky_path[index+1]) in links: new = True result_rule_lists.append(lucky_path) # Rules that have been hit", "continue if (source, destination) in test_pairs or (destination, source) in test_pairs: new_results_file.write(line) results_file.close()", "open('data/ips.txt') ip_to_host_dict = {} for ip in ips_file: host = hosts_file.readline().split('.')[0] ip_to_host_dict[ip.strip()] =", "= True result_rule_lists.append(lucky_path) # Rules that have been hit already if new: for", "Step 2: Build test pairs test_pairs = [] for rule_list in result_rule_lists: test_pairs.append((\"swan-ap%s\"%rule_list[0],", "test_pairs.append((\"swan-ap%s\"%rule_list[0], \"swan-ap%s\"%rule_list[-1])) # Step 3: Filter results_file = open('data/output.csv') new_results_file = open('data/output_filtered.csv', 'w')", "{} for ip in ips_file: host = hosts_file.readline().split('.')[0] ip_to_host_dict[ip.strip()] = host hosts_file.close() ips_file.close()", "Build \"DNS\" hosts_file = open('data/hosts.txt') ips_file = open('data/ips.txt') ip_to_host_dict = {} for ip", "links = new_links # Min-Set-Cover while len(links) > 0: lucky_index = random.randint(0, len(rule_lists)-1)", "CSV file to select ones that we're interested in. # Step 1: Build", "len(result_rule_lists) en = time.time() print \"Compression: Start=%d, End=%d, Ratio=%f, Time=%f\" % (start_packets, end_packets,", "if source in end_terminals or destination in end_terminals: new_links.remove(link) links = new_links #", "in end_terminals: for destination in end_terminals: try: if destination != source: rule_lists.append(shortest_paths[source][destination]) except:", "for index in xrange(1, len(lucky_path)-2): new = False if (lucky_path[index],lucky_path[index+1]) in links: new", "if (source, destination) in test_pairs or (destination, source) in test_pairs: new_results_file.write(line) results_file.close() new_results_file.close()", "= open(\"data/topology.data\") G=nx.read_edgelist(topology_file) topology_file.close() #Only numbers are end terminals end_terminals = [unicode(str(x)) for", "interested in. # Step 1: Build \"DNS\" hosts_file = open('data/hosts.txt') ips_file = open('data/ips.txt')", "rule_list in result_rule_lists: test_pairs.append((\"swan-ap%s\"%rule_list[0], \"swan-ap%s\"%rule_list[-1])) # Step 3: Filter results_file = open('data/output.csv') new_results_file", "Rules that have been hit already if new: for index2 in xrange(1, len(lucky_path)-2):", "len(rule_lists)-1) lucky_path = rule_lists[lucky_index] # Break the path into links, excluding the end", "in. # Step 1: Build \"DNS\" hosts_file = open('data/hosts.txt') ips_file = open('data/ips.txt') ip_to_host_dict", "topology_file = open(\"data/topology.data\") G=nx.read_edgelist(topology_file) topology_file.close() #Only numbers are end terminals end_terminals = [unicode(str(x))", "end_packets, float(end_packets)/start_packets, en-st) # Now we start to filter CSV file to select", "float(end_packets)/start_packets, en-st) # Now we start to filter CSV file to select ones", "excluding the end terminals for index in xrange(1, len(lucky_path)-2): new = False if", "in result_rule_lists: test_pairs.append((\"swan-ap%s\"%rule_list[0], \"swan-ap%s\"%rule_list[-1])) # Step 3: Filter results_file = open('data/output.csv') new_results_file =", "copy.deepcopy(links) for link in links: (source, destination) = link if source in end_terminals", "[unicode(str(x)) for x in range(1, 100)] links = G.edges() shortest_paths = nx.shortest_path(G) rule_lists", "xrange(1, len(lucky_path)-2): if (lucky_path[index],lucky_path[index+1]) in links: links.remove((lucky_path[index],lucky_path[index+1])) break end_packets = len(result_rule_lists) en =", "[] st = time.time() # Remove end links new_links = copy.deepcopy(links) for link", "host hosts_file.close() ips_file.close() # Step 2: Build test pairs test_pairs = [] for", "end links new_links = copy.deepcopy(links) for link in links: (source, destination) = link", "the path into links, excluding the end terminals for index in xrange(1, len(lucky_path)-2):", "time, random, copy topology_file = open(\"data/topology.data\") G=nx.read_edgelist(topology_file) topology_file.close() #Only numbers are end terminals", "Time=%f\" % (start_packets, end_packets, float(end_packets)/start_packets, en-st) # Now we start to filter CSV", "links: (source, destination) = link if source in end_terminals or destination in end_terminals:", "links: new = True result_rule_lists.append(lucky_path) # Rules that have been hit already if", "en-st) # Now we start to filter CSV file to select ones that", "ips_file: host = hosts_file.readline().split('.')[0] ip_to_host_dict[ip.strip()] = host hosts_file.close() ips_file.close() # Step 2: Build", "open('data/output_filtered.csv', 'w') for line in results_file: components = line.split(',') source = components[1].strip('\\\"') try:", "new_results_file = open('data/output_filtered.csv', 'w') for line in results_file: components = line.split(',') source =", "= ip_to_host_dict[components[2].strip('\\\"')] except: continue if (source, destination) in test_pairs or (destination, source) in", "Min-Set-Cover while len(links) > 0: lucky_index = random.randint(0, len(rule_lists)-1) lucky_path = rule_lists[lucky_index] #", "for line in results_file: components = line.split(',') source = components[1].strip('\\\"') try: destination =", "random, copy topology_file = open(\"data/topology.data\") G=nx.read_edgelist(topology_file) topology_file.close() #Only numbers are end terminals end_terminals", "st = time.time() # Remove end links new_links = copy.deepcopy(links) for link in", "len(links) > 0: lucky_index = random.randint(0, len(rule_lists)-1) lucky_path = rule_lists[lucky_index] # Break the", "rule_lists[lucky_index] # Break the path into links, excluding the end terminals for index", "pairs test_pairs = [] for rule_list in result_rule_lists: test_pairs.append((\"swan-ap%s\"%rule_list[0], \"swan-ap%s\"%rule_list[-1])) # Step 3:", "#Only numbers are end terminals end_terminals = [unicode(str(x)) for x in range(1, 100)]", "end terminals end_terminals = [unicode(str(x)) for x in range(1, 100)] links = G.edges()", "in xrange(1, len(lucky_path)-2): new = False if (lucky_path[index],lucky_path[index+1]) in links: new = True", "ones that we're interested in. # Step 1: Build \"DNS\" hosts_file = open('data/hosts.txt')", "links = G.edges() shortest_paths = nx.shortest_path(G) rule_lists = [] for source in end_terminals:", "destination in end_terminals: try: if destination != source: rule_lists.append(shortest_paths[source][destination]) except: pass start_packets =", "= hosts_file.readline().split('.')[0] ip_to_host_dict[ip.strip()] = host hosts_file.close() ips_file.close() # Step 2: Build test pairs", "True result_rule_lists.append(lucky_path) # Rules that have been hit already if new: for index2", "components = line.split(',') source = components[1].strip('\\\"') try: destination = ip_to_host_dict[components[2].strip('\\\"')] except: continue if", "for source in end_terminals: for destination in end_terminals: try: if destination != source:", "# Min-Set-Cover while len(links) > 0: lucky_index = random.randint(0, len(rule_lists)-1) lucky_path = rule_lists[lucky_index]", "while len(links) > 0: lucky_index = random.randint(0, len(rule_lists)-1) lucky_path = rule_lists[lucky_index] # Break", "False if (lucky_path[index],lucky_path[index+1]) in links: new = True result_rule_lists.append(lucky_path) # Rules that have", "that have been hit already if new: for index2 in xrange(1, len(lucky_path)-2): if", "are end terminals end_terminals = [unicode(str(x)) for x in range(1, 100)] links =", "!= source: rule_lists.append(shortest_paths[source][destination]) except: pass start_packets = len(rule_lists) result_rule_lists = [] st =", "hosts_file.close() ips_file.close() # Step 2: Build test pairs test_pairs = [] for rule_list", "for destination in end_terminals: try: if destination != source: rule_lists.append(shortest_paths[source][destination]) except: pass start_packets", "new: for index2 in xrange(1, len(lucky_path)-2): if (lucky_path[index],lucky_path[index+1]) in links: links.remove((lucky_path[index],lucky_path[index+1])) break end_packets", "we start to filter CSV file to select ones that we're interested in.", "x in range(1, 100)] links = G.edges() shortest_paths = nx.shortest_path(G) rule_lists = []", "Remove end links new_links = copy.deepcopy(links) for link in links: (source, destination) =", "Step 1: Build \"DNS\" hosts_file = open('data/hosts.txt') ips_file = open('data/ips.txt') ip_to_host_dict = {}", "start_packets = len(rule_lists) result_rule_lists = [] st = time.time() # Remove end links", "0: lucky_index = random.randint(0, len(rule_lists)-1) lucky_path = rule_lists[lucky_index] # Break the path into", "links new_links = copy.deepcopy(links) for link in links: (source, destination) = link if", "= open('data/ips.txt') ip_to_host_dict = {} for ip in ips_file: host = hosts_file.readline().split('.')[0] ip_to_host_dict[ip.strip()]", "numbers are end terminals end_terminals = [unicode(str(x)) for x in range(1, 100)] links", "= open('data/hosts.txt') ips_file = open('data/ips.txt') ip_to_host_dict = {} for ip in ips_file: host", "= line.split(',') source = components[1].strip('\\\"') try: destination = ip_to_host_dict[components[2].strip('\\\"')] except: continue if (source,", "rule_lists = [] for source in end_terminals: for destination in end_terminals: try: if", "hosts_file = open('data/hosts.txt') ips_file = open('data/ips.txt') ip_to_host_dict = {} for ip in ips_file:", "Filter results_file = open('data/output.csv') new_results_file = open('data/output_filtered.csv', 'w') for line in results_file: components", "source in end_terminals: for destination in end_terminals: try: if destination != source: rule_lists.append(shortest_paths[source][destination])", "= rule_lists[lucky_index] # Break the path into links, excluding the end terminals for", "copy topology_file = open(\"data/topology.data\") G=nx.read_edgelist(topology_file) topology_file.close() #Only numbers are end terminals end_terminals =", "= nx.shortest_path(G) rule_lists = [] for source in end_terminals: for destination in end_terminals:", "[] for source in end_terminals: for destination in end_terminals: try: if destination !=", "in end_terminals: new_links.remove(link) links = new_links # Min-Set-Cover while len(links) > 0: lucky_index", "'w') for line in results_file: components = line.split(',') source = components[1].strip('\\\"') try: destination", "for x in range(1, 100)] links = G.edges() shortest_paths = nx.shortest_path(G) rule_lists =", "ips_file = open('data/ips.txt') ip_to_host_dict = {} for ip in ips_file: host = hosts_file.readline().split('.')[0]", "# Step 2: Build test pairs test_pairs = [] for rule_list in result_rule_lists:", "terminals for index in xrange(1, len(lucky_path)-2): new = False if (lucky_path[index],lucky_path[index+1]) in links:", "\"DNS\" hosts_file = open('data/hosts.txt') ips_file = open('data/ips.txt') ip_to_host_dict = {} for ip in", "= [] st = time.time() # Remove end links new_links = copy.deepcopy(links) for", "terminals end_terminals = [unicode(str(x)) for x in range(1, 100)] links = G.edges() shortest_paths", "to select ones that we're interested in. # Step 1: Build \"DNS\" hosts_file", "host = hosts_file.readline().split('.')[0] ip_to_host_dict[ip.strip()] = host hosts_file.close() ips_file.close() # Step 2: Build test", "for rule_list in result_rule_lists: test_pairs.append((\"swan-ap%s\"%rule_list[0], \"swan-ap%s\"%rule_list[-1])) # Step 3: Filter results_file = open('data/output.csv')", "= link if source in end_terminals or destination in end_terminals: new_links.remove(link) links =", "destination) = link if source in end_terminals or destination in end_terminals: new_links.remove(link) links", "print \"Compression: Start=%d, End=%d, Ratio=%f, Time=%f\" % (start_packets, end_packets, float(end_packets)/start_packets, en-st) # Now", "result_rule_lists: test_pairs.append((\"swan-ap%s\"%rule_list[0], \"swan-ap%s\"%rule_list[-1])) # Step 3: Filter results_file = open('data/output.csv') new_results_file = open('data/output_filtered.csv',", "pass start_packets = len(rule_lists) result_rule_lists = [] st = time.time() # Remove end", "= new_links # Min-Set-Cover while len(links) > 0: lucky_index = random.randint(0, len(rule_lists)-1) lucky_path", "start to filter CSV file to select ones that we're interested in. #", "that we're interested in. # Step 1: Build \"DNS\" hosts_file = open('data/hosts.txt') ips_file", "test_pairs = [] for rule_list in result_rule_lists: test_pairs.append((\"swan-ap%s\"%rule_list[0], \"swan-ap%s\"%rule_list[-1])) # Step 3: Filter", "new_links.remove(link) links = new_links # Min-Set-Cover while len(links) > 0: lucky_index = random.randint(0,", "already if new: for index2 in xrange(1, len(lucky_path)-2): if (lucky_path[index],lucky_path[index+1]) in links: links.remove((lucky_path[index],lucky_path[index+1]))", "in links: (source, destination) = link if source in end_terminals or destination in", "if (lucky_path[index],lucky_path[index+1]) in links: links.remove((lucky_path[index],lucky_path[index+1])) break end_packets = len(result_rule_lists) en = time.time() print", "(lucky_path[index],lucky_path[index+1]) in links: links.remove((lucky_path[index],lucky_path[index+1])) break end_packets = len(result_rule_lists) en = time.time() print \"Compression:", "filter CSV file to select ones that we're interested in. # Step 1:", "new_links # Min-Set-Cover while len(links) > 0: lucky_index = random.randint(0, len(rule_lists)-1) lucky_path =", "ip in ips_file: host = hosts_file.readline().split('.')[0] ip_to_host_dict[ip.strip()] = host hosts_file.close() ips_file.close() # Step", "except: continue if (source, destination) in test_pairs or (destination, source) in test_pairs: new_results_file.write(line)", "open(\"data/topology.data\") G=nx.read_edgelist(topology_file) topology_file.close() #Only numbers are end terminals end_terminals = [unicode(str(x)) for x", "end_terminals: new_links.remove(link) links = new_links # Min-Set-Cover while len(links) > 0: lucky_index =", "in end_terminals or destination in end_terminals: new_links.remove(link) links = new_links # Min-Set-Cover while", "ips_file.close() # Step 2: Build test pairs test_pairs = [] for rule_list in", "link in links: (source, destination) = link if source in end_terminals or destination", "destination = ip_to_host_dict[components[2].strip('\\\"')] except: continue if (source, destination) in test_pairs or (destination, source)", "in links: new = True result_rule_lists.append(lucky_path) # Rules that have been hit already", "import time, random, copy topology_file = open(\"data/topology.data\") G=nx.read_edgelist(topology_file) topology_file.close() #Only numbers are end", "ip_to_host_dict = {} for ip in ips_file: host = hosts_file.readline().split('.')[0] ip_to_host_dict[ip.strip()] = host", "= len(rule_lists) result_rule_lists = [] st = time.time() # Remove end links new_links", "lucky_index = random.randint(0, len(rule_lists)-1) lucky_path = rule_lists[lucky_index] # Break the path into links,", "destination in end_terminals: new_links.remove(link) links = new_links # Min-Set-Cover while len(links) > 0:", "2: Build test pairs test_pairs = [] for rule_list in result_rule_lists: test_pairs.append((\"swan-ap%s\"%rule_list[0], \"swan-ap%s\"%rule_list[-1]))", "> 0: lucky_index = random.randint(0, len(rule_lists)-1) lucky_path = rule_lists[lucky_index] # Break the path", "len(rule_lists) result_rule_lists = [] st = time.time() # Remove end links new_links =", "= components[1].strip('\\\"') try: destination = ip_to_host_dict[components[2].strip('\\\"')] except: continue if (source, destination) in test_pairs", "ip_to_host_dict[components[2].strip('\\\"')] except: continue if (source, destination) in test_pairs or (destination, source) in test_pairs:", "if new: for index2 in xrange(1, len(lucky_path)-2): if (lucky_path[index],lucky_path[index+1]) in links: links.remove((lucky_path[index],lucky_path[index+1])) break", "= open('data/output.csv') new_results_file = open('data/output_filtered.csv', 'w') for line in results_file: components = line.split(',')", "G.edges() shortest_paths = nx.shortest_path(G) rule_lists = [] for source in end_terminals: for destination", "nx.shortest_path(G) rule_lists = [] for source in end_terminals: for destination in end_terminals: try:", "in range(1, 100)] links = G.edges() shortest_paths = nx.shortest_path(G) rule_lists = [] for", "for link in links: (source, destination) = link if source in end_terminals or", "in xrange(1, len(lucky_path)-2): if (lucky_path[index],lucky_path[index+1]) in links: links.remove((lucky_path[index],lucky_path[index+1])) break end_packets = len(result_rule_lists) en", "index2 in xrange(1, len(lucky_path)-2): if (lucky_path[index],lucky_path[index+1]) in links: links.remove((lucky_path[index],lucky_path[index+1])) break end_packets = len(result_rule_lists)", "break end_packets = len(result_rule_lists) en = time.time() print \"Compression: Start=%d, End=%d, Ratio=%f, Time=%f\"", "source: rule_lists.append(shortest_paths[source][destination]) except: pass start_packets = len(rule_lists) result_rule_lists = [] st = time.time()", "open('data/hosts.txt') ips_file = open('data/ips.txt') ip_to_host_dict = {} for ip in ips_file: host =", "try: destination = ip_to_host_dict[components[2].strip('\\\"')] except: continue if (source, destination) in test_pairs or (destination,", "# Remove end links new_links = copy.deepcopy(links) for link in links: (source, destination)", "= False if (lucky_path[index],lucky_path[index+1]) in links: new = True result_rule_lists.append(lucky_path) # Rules that", "end_packets = len(result_rule_lists) en = time.time() print \"Compression: Start=%d, End=%d, Ratio=%f, Time=%f\" %", "= copy.deepcopy(links) for link in links: (source, destination) = link if source in", "end_terminals = [unicode(str(x)) for x in range(1, 100)] links = G.edges() shortest_paths =", "source in end_terminals or destination in end_terminals: new_links.remove(link) links = new_links # Min-Set-Cover", "len(lucky_path)-2): new = False if (lucky_path[index],lucky_path[index+1]) in links: new = True result_rule_lists.append(lucky_path) #", "(source, destination) = link if source in end_terminals or destination in end_terminals: new_links.remove(link)", "= len(result_rule_lists) en = time.time() print \"Compression: Start=%d, End=%d, Ratio=%f, Time=%f\" % (start_packets,", "\"swan-ap%s\"%rule_list[-1])) # Step 3: Filter results_file = open('data/output.csv') new_results_file = open('data/output_filtered.csv', 'w') for", "% (start_packets, end_packets, float(end_packets)/start_packets, en-st) # Now we start to filter CSV file", "= G.edges() shortest_paths = nx.shortest_path(G) rule_lists = [] for source in end_terminals: for", "# Step 3: Filter results_file = open('data/output.csv') new_results_file = open('data/output_filtered.csv', 'w') for line", "[] for rule_list in result_rule_lists: test_pairs.append((\"swan-ap%s\"%rule_list[0], \"swan-ap%s\"%rule_list[-1])) # Step 3: Filter results_file =", "if destination != source: rule_lists.append(shortest_paths[source][destination]) except: pass start_packets = len(rule_lists) result_rule_lists = []", "hosts_file.readline().split('.')[0] ip_to_host_dict[ip.strip()] = host hosts_file.close() ips_file.close() # Step 2: Build test pairs test_pairs", "end_terminals: try: if destination != source: rule_lists.append(shortest_paths[source][destination]) except: pass start_packets = len(rule_lists) result_rule_lists", "time.time() # Remove end links new_links = copy.deepcopy(links) for link in links: (source,", "nx import time, random, copy topology_file = open(\"data/topology.data\") G=nx.read_edgelist(topology_file) topology_file.close() #Only numbers are", "as nx import time, random, copy topology_file = open(\"data/topology.data\") G=nx.read_edgelist(topology_file) topology_file.close() #Only numbers" ]
[ "= message class WrongCertificationType(AgriRouuterBaseException): _message = \"Wrong Certification type. Use onboarding.enums.CertificationTypes values instead.\"", "_message = ... def __init__(self, message=None): if not message: message = self._message self.message", "not message: message = self._message self.message = message class WrongCertificationType(AgriRouuterBaseException): _message = \"Wrong", "Request does not contain signature header. Please sign the request with request.sign() method.\\n", "class RequestNotSigned(AgriRouuterBaseException): _message = \"\"\" Request does not contain signature header. Please sign", "if not message: message = self._message self.message = message class WrongCertificationType(AgriRouuterBaseException): _message =", "message: message = self._message self.message = message class WrongCertificationType(AgriRouuterBaseException): _message = \"Wrong Certification", "... def __init__(self, message=None): if not message: message = self._message self.message = message", "signature header. Please sign the request with request.sign() method.\\n Details on: https://docs.my-agrirouter.com/agrirouter-interface-documentation/latest/ integration/onboarding.html#signing-requests", "onboarding.enums.CertificationTypes values instead.\" class WrongGateWay(AgriRouuterBaseException): _message = \"Wrong Gate Way Id. Use onboarding.enums.GateWays", "request with request.sign() method.\\n Details on: https://docs.my-agrirouter.com/agrirouter-interface-documentation/latest/ integration/onboarding.html#signing-requests \"\"\" class BadMessagingResult(AgriRouuterBaseException): _message =", "RequestNotSigned(AgriRouuterBaseException): _message = \"\"\" Request does not contain signature header. Please sign the", "class WrongGateWay(AgriRouuterBaseException): _message = \"Wrong Gate Way Id. Use onboarding.enums.GateWays values instead.\" class", "class WrongCertificationType(AgriRouuterBaseException): _message = \"Wrong Certification type. Use onboarding.enums.CertificationTypes values instead.\" class WrongGateWay(AgriRouuterBaseException):", "not contain signature header. Please sign the request with request.sign() method.\\n Details on:", "sign the request with request.sign() method.\\n Details on: https://docs.my-agrirouter.com/agrirouter-interface-documentation/latest/ integration/onboarding.html#signing-requests \"\"\" class BadMessagingResult(AgriRouuterBaseException):", "header. Please sign the request with request.sign() method.\\n Details on: https://docs.my-agrirouter.com/agrirouter-interface-documentation/latest/ integration/onboarding.html#signing-requests \"\"\"", "with request.sign() method.\\n Details on: https://docs.my-agrirouter.com/agrirouter-interface-documentation/latest/ integration/onboarding.html#signing-requests \"\"\" class BadMessagingResult(AgriRouuterBaseException): _message = \"Messaging", "Way Id. Use onboarding.enums.GateWays values instead.\" class RequestNotSigned(AgriRouuterBaseException): _message = \"\"\" Request does", "= \"Wrong Certification type. Use onboarding.enums.CertificationTypes values instead.\" class WrongGateWay(AgriRouuterBaseException): _message = \"Wrong", "__init__(self, message=None): if not message: message = self._message self.message = message class WrongCertificationType(AgriRouuterBaseException):", "\"Wrong Gate Way Id. Use onboarding.enums.GateWays values instead.\" class RequestNotSigned(AgriRouuterBaseException): _message = \"\"\"", "self._message self.message = message class WrongCertificationType(AgriRouuterBaseException): _message = \"Wrong Certification type. Use onboarding.enums.CertificationTypes", "= ... def __init__(self, message=None): if not message: message = self._message self.message =", "_message = \"Wrong Gate Way Id. Use onboarding.enums.GateWays values instead.\" class RequestNotSigned(AgriRouuterBaseException): _message", "Please sign the request with request.sign() method.\\n Details on: https://docs.my-agrirouter.com/agrirouter-interface-documentation/latest/ integration/onboarding.html#signing-requests \"\"\" class", "WrongGateWay(AgriRouuterBaseException): _message = \"Wrong Gate Way Id. Use onboarding.enums.GateWays values instead.\" class RequestNotSigned(AgriRouuterBaseException):", "instead.\" class RequestNotSigned(AgriRouuterBaseException): _message = \"\"\" Request does not contain signature header. Please", "AgriRouuterBaseException(Exception): _message = ... def __init__(self, message=None): if not message: message = self._message", "does not contain signature header. Please sign the request with request.sign() method.\\n Details", "message class WrongCertificationType(AgriRouuterBaseException): _message = \"Wrong Certification type. Use onboarding.enums.CertificationTypes values instead.\" class", "instead.\" class WrongGateWay(AgriRouuterBaseException): _message = \"Wrong Gate Way Id. Use onboarding.enums.GateWays values instead.\"", "Use onboarding.enums.GateWays values instead.\" class RequestNotSigned(AgriRouuterBaseException): _message = \"\"\" Request does not contain", "WrongCertificationType(AgriRouuterBaseException): _message = \"Wrong Certification type. Use onboarding.enums.CertificationTypes values instead.\" class WrongGateWay(AgriRouuterBaseException): _message", "_message = \"\"\" Request does not contain signature header. Please sign the request", "self.message = message class WrongCertificationType(AgriRouuterBaseException): _message = \"Wrong Certification type. Use onboarding.enums.CertificationTypes values", "def __init__(self, message=None): if not message: message = self._message self.message = message class", "\"\"\" Request does not contain signature header. Please sign the request with request.sign()", "type. Use onboarding.enums.CertificationTypes values instead.\" class WrongGateWay(AgriRouuterBaseException): _message = \"Wrong Gate Way Id.", "request.sign() method.\\n Details on: https://docs.my-agrirouter.com/agrirouter-interface-documentation/latest/ integration/onboarding.html#signing-requests \"\"\" class BadMessagingResult(AgriRouuterBaseException): _message = \"Messaging Request", "message = self._message self.message = message class WrongCertificationType(AgriRouuterBaseException): _message = \"Wrong Certification type.", "= self._message self.message = message class WrongCertificationType(AgriRouuterBaseException): _message = \"Wrong Certification type. Use", "\"Wrong Certification type. Use onboarding.enums.CertificationTypes values instead.\" class WrongGateWay(AgriRouuterBaseException): _message = \"Wrong Gate", "Certification type. Use onboarding.enums.CertificationTypes values instead.\" class WrongGateWay(AgriRouuterBaseException): _message = \"Wrong Gate Way", "message=None): if not message: message = self._message self.message = message class WrongCertificationType(AgriRouuterBaseException): _message", "Gate Way Id. Use onboarding.enums.GateWays values instead.\" class RequestNotSigned(AgriRouuterBaseException): _message = \"\"\" Request", "Use onboarding.enums.CertificationTypes values instead.\" class WrongGateWay(AgriRouuterBaseException): _message = \"Wrong Gate Way Id. Use", "values instead.\" class RequestNotSigned(AgriRouuterBaseException): _message = \"\"\" Request does not contain signature header.", "= \"\"\" Request does not contain signature header. Please sign the request with", "values instead.\" class WrongGateWay(AgriRouuterBaseException): _message = \"Wrong Gate Way Id. Use onboarding.enums.GateWays values", "_message = \"Wrong Certification type. Use onboarding.enums.CertificationTypes values instead.\" class WrongGateWay(AgriRouuterBaseException): _message =", "onboarding.enums.GateWays values instead.\" class RequestNotSigned(AgriRouuterBaseException): _message = \"\"\" Request does not contain signature", "class AgriRouuterBaseException(Exception): _message = ... def __init__(self, message=None): if not message: message =", "Id. Use onboarding.enums.GateWays values instead.\" class RequestNotSigned(AgriRouuterBaseException): _message = \"\"\" Request does not", "contain signature header. Please sign the request with request.sign() method.\\n Details on: https://docs.my-agrirouter.com/agrirouter-interface-documentation/latest/", "the request with request.sign() method.\\n Details on: https://docs.my-agrirouter.com/agrirouter-interface-documentation/latest/ integration/onboarding.html#signing-requests \"\"\" class BadMessagingResult(AgriRouuterBaseException): _message", "method.\\n Details on: https://docs.my-agrirouter.com/agrirouter-interface-documentation/latest/ integration/onboarding.html#signing-requests \"\"\" class BadMessagingResult(AgriRouuterBaseException): _message = \"Messaging Request failed\"", "= \"Wrong Gate Way Id. Use onboarding.enums.GateWays values instead.\" class RequestNotSigned(AgriRouuterBaseException): _message =" ]
[ "- 1 >= x - 1 >= 0 and image.shape[1] - 1 >=", "float) if image.shape[0] - 1 >= x - 1 >= image.shape[0] - 1", "liste ordonnee \"\"\" Image: Image sur laquelle nous travaillons x : position x", "# Il faut prendre les 8 pixels qui sont autours du pixel sur", "str(\" %\")) return newimg # Il faut prendre les 8 pixels qui sont", "Et ensuite prendre la mediane de cette liste ordonnee \"\"\" Image: Image sur", "contient les 8 pixels autours du pixel sur lequel nous travaillons \"\"\" def", "laquelle nous travaillons x : position x du pixel y : position y", "and image.shape[1] - 1 >= y - 1 >= 0: liste[5] = image[x", "pixel y : position y du pixel return : retourne une liste qui", "0 and image.shape[1] - 1 >= y + 1 >= 0: liste[2] =", "# Et ensuite prendre la mediane de cette liste ordonnee \"\"\" Image: Image", "\" + str(nombrePixel)) #print(\"Pourcentage de pixels non modifes : \" + str(image.shape[0]*image.shape[1]/nombrePixel) +", "+ str(image.shape[0]*image.shape[1]/nombrePixel) + str(\" %\")) return newimg # Il faut prendre les 8", "1 >= image.shape[0] - 1 >= 0 and image.shape[1] - 1 >= y", "notre liste liste = sorted(liste) mediane = (liste[3] + liste[4]) / 2.0 #", "lequel nous travaillons \"\"\" def getPixels(image, x, y): liste = zeros(8, float) if", "y): liste = zeros(8, float) if image.shape[0] - 1 >= x - 1", "Débruitage par filtrage médian <image> l'image à débruiter retourne l'image débruitée \"\"\" def", "x + 1 >= 0 and image.shape[1] - 1 >= y - 1", "if image.shape[0] - 1 >= x - 1 >= 0 and image.shape[1] -", "image.shape[0] - 1 >= x - 1 >= 0 and image.shape[1] - 1", "from copy import deepcopy from numpy import * \"\"\" Débruitage par filtrage médian", ">= 0: liste[4] = image[x][y + 1] if image.shape[0] - 1 >= x", "1][y + 1] if image.shape[1] - 1 >= y - 1 >= 0:", "travaillons x : position x du pixel y : position y du pixel", "str(nombrePixel)) #print(\"Pourcentage de pixels non modifes : \" + str(image.shape[0]*image.shape[1]/nombrePixel) + str(\" %\"))", "- 1] if image.shape[1] - 1 >= y + 1 >= 0: liste[4]", "median(image): nombrePixel = 0 newimg = deepcopy(image) # Parcours des lignes de pixels", "1 >= y - 1 >= 0: liste[3] = image[x][y - 1] if", "* \"\"\" Débruitage par filtrage médian <image> l'image à débruiter retourne l'image débruitée", "y : position y du pixel return : retourne une liste qui contient", "if image.shape[0] - 1 >= x - 1 >= 0: liste[1] = image[x", "position x du pixel y : position y du pixel return : retourne", "- 1] if image.shape[0] - 1 >= x + 1 >= 0: liste[6]", "- 1 >= x - 1 >= image.shape[0] - 1 >= 0 and", "- 1 >= 0 and image.shape[1] - 1 >= y - 1 >=", "nombrePixel = 0 newimg = deepcopy(image) # Parcours des lignes de pixels for", "cette liste ordonnee \"\"\" Image: Image sur laquelle nous travaillons x : position", "1 >= x + 1 >= 0 and image.shape[1] - 1 >= y", "croissantes # Et ensuite prendre la mediane de cette liste ordonnee \"\"\" Image:", "0 and image.shape[1] - 1 >= y + 1 >= 0: liste[7] =", "0: liste[7] = image[x + 1][y + 1] # Permet de trier notre", "#print(\"Pourcentage de pixels non modifes : \" + str(image.shape[0]*image.shape[1]/nombrePixel) + str(\" %\")) return", "# Permet de trier notre liste liste = sorted(liste) mediane = (liste[3] +", "de pixels non modifies : \" + str(nombrePixel)) #print(\"Pourcentage de pixels non modifes", "pixels autours du pixel sur lequel nous travaillons \"\"\" def getPixels(image, x, y):", "1 >= y + 1 >= 0: liste[7] = image[x + 1][y +", "modifies : \" + str(nombrePixel)) #print(\"Pourcentage de pixels non modifes : \" +", "1 >= 0: liste[5] = image[x + 1][y - 1] if image.shape[0] -", "if image.shape[0] - 1 >= x + 1 >= 0: liste[6] = image[x", "\"\"\" Image: Image sur laquelle nous travaillons x : position x du pixel", "1][y + 1] # Permet de trier notre liste liste = sorted(liste) mediane", "sur lequel nous travaillons \"\"\" def getPixels(image, x, y): liste = zeros(8, float)", "<reponame>Krown0s/TraitementsImages<filename>unnoise/medianV1.py # -*- encoding: utf-8 -*- from copy import deepcopy from numpy import", "sur laquelle nous travaillons x : position x du pixel y : position", ">= x - 1 >= image.shape[0] - 1 >= 0 and image.shape[1] -", "+ 1] if image.shape[0] - 1 >= x + 1 >= 0 and", "0: liste[5] = image[x + 1][y - 1] if image.shape[0] - 1 >=", "Permet de trier notre liste liste = sorted(liste) mediane = (liste[3] + liste[4])", "+ 1 >= 0: liste[6] = image[x + 1][y] if image.shape[0] - 1", "+ 1 >= 0 and image.shape[1] - 1 >= y + 1 >=", "newimg = deepcopy(image) # Parcours des lignes de pixels for x in range(newimg.shape[0]):", "pixels par valeurs croissantes # Et ensuite prendre la mediane de cette liste", "# Parcours des lignes de pixels for x in range(newimg.shape[0]): # Parcours des", "des lignes de pixels for x in range(newimg.shape[0]): # Parcours des colonnes de", ">= 0: liste[1] = image[x - 1][y] if image.shape[0] - 1 >= x", "/ 2.0 # Retourne la mediane (8 pixels donc 8/2 = 4) return", "autours du pixel sur lequel nous travaillons \"\"\" def getPixels(image, x, y): liste", "y in range(newimg.shape[1]): newimg[x][y] = getPixels(newimg, x, y) if(image[x][y] == newimg[x][y]): nombrePixel =", "1] if image.shape[0] - 1 >= x - 1 >= 0: liste[1] =", "- 1 >= y + 1 >= 0: liste[2] = image[x - 1][y", "liste = sorted(liste) mediane = (liste[3] + liste[4]) / 2.0 # Retourne la", "in range(newimg.shape[1]): newimg[x][y] = getPixels(newimg, x, y) if(image[x][y] == newimg[x][y]): nombrePixel = nombrePixel", "position y du pixel return : retourne une liste qui contient les 8", "getPixels(newimg, x, y) if(image[x][y] == newimg[x][y]): nombrePixel = nombrePixel + 1 #print(\"Nombre de", "image[x - 1][y - 1] if image.shape[0] - 1 >= x - 1", "1] if image.shape[1] - 1 >= y + 1 >= 0: liste[4] =", ">= 0 and image.shape[1] - 1 >= y - 1 >= 0: liste[0]", ">= 0 and image.shape[1] - 1 >= y + 1 >= 0: liste[7]", "-*- encoding: utf-8 -*- from copy import deepcopy from numpy import * \"\"\"", "mediane de cette liste ordonnee \"\"\" Image: Image sur laquelle nous travaillons x", "1 >= y - 1 >= 0: liste[0] = image[x - 1][y -", "= image[x][y + 1] if image.shape[0] - 1 >= x + 1 >=", "Il faut prendre les 8 pixels qui sont autours du pixel sur lequel", "les 8 pixels autours du pixel sur lequel nous travaillons \"\"\" def getPixels(image,", "image.shape[1] - 1 >= y + 1 >= 0: liste[4] = image[x][y +", "sont autours du pixel sur lequel nous travaillons # Il faut ranger les", "y - 1 >= 0: liste[0] = image[x - 1][y - 1] if", "= image[x + 1][y + 1] # Permet de trier notre liste liste", "= getPixels(newimg, x, y) if(image[x][y] == newimg[x][y]): nombrePixel = nombrePixel + 1 #print(\"Nombre", "nous travaillons # Il faut ranger les pixels par valeurs croissantes # Et", "1 >= 0: liste[0] = image[x - 1][y - 1] if image.shape[0] -", "liste[6] = image[x + 1][y] if image.shape[0] - 1 >= x + 1", "if image.shape[0] - 1 >= x + 1 >= 0 and image.shape[1] -", "newimg[x][y] = getPixels(newimg, x, y) if(image[x][y] == newimg[x][y]): nombrePixel = nombrePixel + 1", "nombrePixel + 1 #print(\"Nombre de pixels non modifies : \" + str(nombrePixel)) #print(\"Pourcentage", ": position x du pixel y : position y du pixel return :", "faut prendre les 8 pixels qui sont autours du pixel sur lequel nous", "def median(image): nombrePixel = 0 newimg = deepcopy(image) # Parcours des lignes de", "- 1][y] if image.shape[0] - 1 >= x - 1 >= 0 and", "x, y) if(image[x][y] == newimg[x][y]): nombrePixel = nombrePixel + 1 #print(\"Nombre de pixels", "1] if image.shape[1] - 1 >= y - 1 >= 0: liste[3] =", "1][y - 1] if image.shape[0] - 1 >= x - 1 >= 0:", "str(image.shape[0]*image.shape[1]/nombrePixel) + str(\" %\")) return newimg # Il faut prendre les 8 pixels", ">= 0: liste[2] = image[x - 1][y + 1] if image.shape[1] - 1", "encoding: utf-8 -*- from copy import deepcopy from numpy import * \"\"\" Débruitage", "nous travaillons x : position x du pixel y : position y du", "la mediane de cette liste ordonnee \"\"\" Image: Image sur laquelle nous travaillons", "une liste qui contient les 8 pixels autours du pixel sur lequel nous", "1] # Permet de trier notre liste liste = sorted(liste) mediane = (liste[3]", ">= y + 1 >= 0: liste[2] = image[x - 1][y + 1]", "Image sur laquelle nous travaillons x : position x du pixel y :", "%\")) return newimg # Il faut prendre les 8 pixels qui sont autours", "travaillons \"\"\" def getPixels(image, x, y): liste = zeros(8, float) if image.shape[0] -", "if image.shape[0] - 1 >= x - 1 >= image.shape[0] - 1 >=", "1 >= y - 1 >= 0: liste[5] = image[x + 1][y -", "1] if image.shape[0] - 1 >= x + 1 >= 0 and image.shape[1]", "travaillons # Il faut ranger les pixels par valeurs croissantes # Et ensuite", "par filtrage médian <image> l'image à débruiter retourne l'image débruitée \"\"\" def median(image):", "+ 1 >= 0 and image.shape[1] - 1 >= y - 1 >=", "2.0 # Retourne la mediane (8 pixels donc 8/2 = 4) return mediane", "image[x - 1][y] if image.shape[0] - 1 >= x - 1 >= 0", "1 >= x - 1 >= 0 and image.shape[1] - 1 >= y", "filtrage médian <image> l'image à débruiter retourne l'image débruitée \"\"\" def median(image): nombrePixel", "x in range(newimg.shape[0]): # Parcours des colonnes de pixels for y in range(newimg.shape[1]):", "= image[x - 1][y] if image.shape[0] - 1 >= x - 1 >=", "du pixel sur lequel nous travaillons \"\"\" def getPixels(image, x, y): liste =", "de pixels non modifes : \" + str(image.shape[0]*image.shape[1]/nombrePixel) + str(\" %\")) return newimg", "pixels qui sont autours du pixel sur lequel nous travaillons # Il faut", "def getPixels(image, x, y): liste = zeros(8, float) if image.shape[0] - 1 >=", ">= x + 1 >= 0: liste[6] = image[x + 1][y] if image.shape[0]", ">= 0: liste[6] = image[x + 1][y] if image.shape[0] - 1 >= x", "= (liste[3] + liste[4]) / 2.0 # Retourne la mediane (8 pixels donc", "les pixels par valeurs croissantes # Et ensuite prendre la mediane de cette", "- 1 >= x + 1 >= 0 and image.shape[1] - 1 >=", "= zeros(8, float) if image.shape[0] - 1 >= x - 1 >= image.shape[0]", "1][y - 1] if image.shape[0] - 1 >= x + 1 >= 0:", "ranger les pixels par valeurs croissantes # Et ensuite prendre la mediane de", "qui sont autours du pixel sur lequel nous travaillons # Il faut ranger", "image.shape[1] - 1 >= y - 1 >= 0: liste[0] = image[x -", "1][y] if image.shape[0] - 1 >= x - 1 >= 0 and image.shape[1]", "faut ranger les pixels par valeurs croissantes # Et ensuite prendre la mediane", "in range(newimg.shape[0]): # Parcours des colonnes de pixels for y in range(newimg.shape[1]): newimg[x][y]", "retourne une liste qui contient les 8 pixels autours du pixel sur lequel", "#print(\"Nombre de pixels non modifies : \" + str(nombrePixel)) #print(\"Pourcentage de pixels non", "liste = zeros(8, float) if image.shape[0] - 1 >= x - 1 >=", "pixels for y in range(newimg.shape[1]): newimg[x][y] = getPixels(newimg, x, y) if(image[x][y] == newimg[x][y]):", "= 0 newimg = deepcopy(image) # Parcours des lignes de pixels for x", "liste qui contient les 8 pixels autours du pixel sur lequel nous travaillons", ">= 0: liste[5] = image[x + 1][y - 1] if image.shape[0] - 1", "0: liste[4] = image[x][y + 1] if image.shape[0] - 1 >= x +", "+ 1][y + 1] # Permet de trier notre liste liste = sorted(liste)", "1 >= 0: liste[3] = image[x][y - 1] if image.shape[1] - 1 >=", "- 1 >= 0: liste[0] = image[x - 1][y - 1] if image.shape[0]", "y + 1 >= 0: liste[2] = image[x - 1][y + 1] if", "- 1 >= y + 1 >= 0: liste[7] = image[x + 1][y", ">= 0: liste[3] = image[x][y - 1] if image.shape[1] - 1 >= y", ">= y - 1 >= 0: liste[0] = image[x - 1][y - 1]", "l'image à débruiter retourne l'image débruitée \"\"\" def median(image): nombrePixel = 0 newimg", "liste[3] = image[x][y - 1] if image.shape[1] - 1 >= y + 1", "- 1 >= image.shape[0] - 1 >= 0 and image.shape[1] - 1 >=", "du pixel return : retourne une liste qui contient les 8 pixels autours", "pixel return : retourne une liste qui contient les 8 pixels autours du", "image[x - 1][y + 1] if image.shape[1] - 1 >= y - 1", ": retourne une liste qui contient les 8 pixels autours du pixel sur", "x - 1 >= image.shape[0] - 1 >= 0 and image.shape[1] - 1", "liste[7] = image[x + 1][y + 1] # Permet de trier notre liste", "deepcopy(image) # Parcours des lignes de pixels for x in range(newimg.shape[0]): # Parcours", "- 1][y + 1] if image.shape[1] - 1 >= y - 1 >=", "- 1][y - 1] if image.shape[0] - 1 >= x - 1 >=", "- 1 >= y - 1 >= 0: liste[5] = image[x + 1][y", "x : position x du pixel y : position y du pixel return", "- 1 >= x + 1 >= 0: liste[6] = image[x + 1][y]", "- 1 >= x - 1 >= 0: liste[1] = image[x - 1][y]", "prendre les 8 pixels qui sont autours du pixel sur lequel nous travaillons", "colonnes de pixels for y in range(newimg.shape[1]): newimg[x][y] = getPixels(newimg, x, y) if(image[x][y]", "0: liste[1] = image[x - 1][y] if image.shape[0] - 1 >= x -", "Parcours des lignes de pixels for x in range(newimg.shape[0]): # Parcours des colonnes", "1 >= x + 1 >= 0: liste[6] = image[x + 1][y] if", ">= y + 1 >= 0: liste[7] = image[x + 1][y + 1]", "nous travaillons \"\"\" def getPixels(image, x, y): liste = zeros(8, float) if image.shape[0]", "and image.shape[1] - 1 >= y + 1 >= 0: liste[2] = image[x", "x + 1 >= 0 and image.shape[1] - 1 >= y + 1", ">= x + 1 >= 0 and image.shape[1] - 1 >= y -", "de pixels for y in range(newimg.shape[1]): newimg[x][y] = getPixels(newimg, x, y) if(image[x][y] ==", "if image.shape[1] - 1 >= y - 1 >= 0: liste[3] = image[x][y", "y) if(image[x][y] == newimg[x][y]): nombrePixel = nombrePixel + 1 #print(\"Nombre de pixels non", "y + 1 >= 0: liste[4] = image[x][y + 1] if image.shape[0] -", "y - 1 >= 0: liste[3] = image[x][y - 1] if image.shape[1] -", "import deepcopy from numpy import * \"\"\" Débruitage par filtrage médian <image> l'image", "1 >= 0: liste[4] = image[x][y + 1] if image.shape[0] - 1 >=", "l'image débruitée \"\"\" def median(image): nombrePixel = 0 newimg = deepcopy(image) # Parcours", "1 >= 0: liste[6] = image[x + 1][y] if image.shape[0] - 1 >=", "+ 1] # Permet de trier notre liste liste = sorted(liste) mediane =", "0 newimg = deepcopy(image) # Parcours des lignes de pixels for x in", "return : retourne une liste qui contient les 8 pixels autours du pixel", "# -*- encoding: utf-8 -*- from copy import deepcopy from numpy import *", "image.shape[0] - 1 >= x + 1 >= 0: liste[6] = image[x +", "sur lequel nous travaillons # Il faut ranger les pixels par valeurs croissantes", "\" + str(image.shape[0]*image.shape[1]/nombrePixel) + str(\" %\")) return newimg # Il faut prendre les", "- 1 >= y - 1 >= 0: liste[0] = image[x - 1][y", "1 >= y + 1 >= 0: liste[4] = image[x][y + 1] if", "lequel nous travaillons # Il faut ranger les pixels par valeurs croissantes #", "numpy import * \"\"\" Débruitage par filtrage médian <image> l'image à débruiter retourne", "du pixel y : position y du pixel return : retourne une liste", "+ 1][y] if image.shape[0] - 1 >= x + 1 >= 0 and", "\"\"\" Débruitage par filtrage médian <image> l'image à débruiter retourne l'image débruitée \"\"\"", "- 1 >= 0 and image.shape[1] - 1 >= y + 1 >=", "débruiter retourne l'image débruitée \"\"\" def median(image): nombrePixel = 0 newimg = deepcopy(image)", "liste[2] = image[x - 1][y + 1] if image.shape[1] - 1 >= y", "0: liste[0] = image[x - 1][y - 1] if image.shape[0] - 1 >=", "nombrePixel = nombrePixel + 1 #print(\"Nombre de pixels non modifies : \" +", "deepcopy from numpy import * \"\"\" Débruitage par filtrage médian <image> l'image à", "for x in range(newimg.shape[0]): # Parcours des colonnes de pixels for y in", "zeros(8, float) if image.shape[0] - 1 >= x - 1 >= image.shape[0] -", "range(newimg.shape[1]): newimg[x][y] = getPixels(newimg, x, y) if(image[x][y] == newimg[x][y]): nombrePixel = nombrePixel +", "1 >= 0: liste[2] = image[x - 1][y + 1] if image.shape[1] -", "image.shape[0] - 1 >= x - 1 >= image.shape[0] - 1 >= 0", "prendre la mediane de cette liste ordonnee \"\"\" Image: Image sur laquelle nous", ">= y - 1 >= 0: liste[3] = image[x][y - 1] if image.shape[1]", "1 >= 0: liste[7] = image[x + 1][y + 1] # Permet de", "pixel sur lequel nous travaillons # Il faut ranger les pixels par valeurs", "par valeurs croissantes # Et ensuite prendre la mediane de cette liste ordonnee", "Image: Image sur laquelle nous travaillons x : position x du pixel y", "= deepcopy(image) # Parcours des lignes de pixels for x in range(newimg.shape[0]): #", "- 1 >= y - 1 >= 0: liste[3] = image[x][y - 1]", "= image[x - 1][y - 1] if image.shape[0] - 1 >= x -", "pixels non modifies : \" + str(nombrePixel)) #print(\"Pourcentage de pixels non modifes :", "+ 1 #print(\"Nombre de pixels non modifies : \" + str(nombrePixel)) #print(\"Pourcentage de", "= nombrePixel + 1 #print(\"Nombre de pixels non modifies : \" + str(nombrePixel))", "sorted(liste) mediane = (liste[3] + liste[4]) / 2.0 # Retourne la mediane (8", "liste[4] = image[x][y + 1] if image.shape[0] - 1 >= x + 1", "from numpy import * \"\"\" Débruitage par filtrage médian <image> l'image à débruiter", "y - 1 >= 0: liste[5] = image[x + 1][y - 1] if", "modifes : \" + str(image.shape[0]*image.shape[1]/nombrePixel) + str(\" %\")) return newimg # Il faut", "x du pixel y : position y du pixel return : retourne une", "- 1 >= 0: liste[5] = image[x + 1][y - 1] if image.shape[0]", "médian <image> l'image à débruiter retourne l'image débruitée \"\"\" def median(image): nombrePixel =", "1] if image.shape[0] - 1 >= x + 1 >= 0: liste[6] =", "image.shape[0] - 1 >= x - 1 >= 0: liste[1] = image[x -", "image.shape[0] - 1 >= x + 1 >= 0 and image.shape[1] - 1", "- 1 >= 0: liste[1] = image[x - 1][y] if image.shape[0] - 1", "les 8 pixels qui sont autours du pixel sur lequel nous travaillons #", "= image[x][y - 1] if image.shape[1] - 1 >= y + 1 >=", ">= x - 1 >= 0 and image.shape[1] - 1 >= y +", "trier notre liste liste = sorted(liste) mediane = (liste[3] + liste[4]) / 2.0", "image[x + 1][y] if image.shape[0] - 1 >= x + 1 >= 0", "= image[x - 1][y + 1] if image.shape[1] - 1 >= y -", "+ liste[4]) / 2.0 # Retourne la mediane (8 pixels donc 8/2 =", "ensuite prendre la mediane de cette liste ordonnee \"\"\" Image: Image sur laquelle", "- 1 >= 0: liste[3] = image[x][y - 1] if image.shape[1] - 1", "newimg[x][y]): nombrePixel = nombrePixel + 1 #print(\"Nombre de pixels non modifies : \"", "image.shape[1] - 1 >= y - 1 >= 0: liste[3] = image[x][y -", "Il faut ranger les pixels par valeurs croissantes # Et ensuite prendre la", "8 pixels autours du pixel sur lequel nous travaillons \"\"\" def getPixels(image, x,", "retourne l'image débruitée \"\"\" def median(image): nombrePixel = 0 newimg = deepcopy(image) #", "+ 1 >= 0: liste[4] = image[x][y + 1] if image.shape[0] - 1", "valeurs croissantes # Et ensuite prendre la mediane de cette liste ordonnee \"\"\"", "pixels non modifes : \" + str(image.shape[0]*image.shape[1]/nombrePixel) + str(\" %\")) return newimg #", "- 1] if image.shape[0] - 1 >= x - 1 >= 0: liste[1]", "= image[x + 1][y - 1] if image.shape[0] - 1 >= x +", "Parcours des colonnes de pixels for y in range(newimg.shape[1]): newimg[x][y] = getPixels(newimg, x,", "débruitée \"\"\" def median(image): nombrePixel = 0 newimg = deepcopy(image) # Parcours des", ">= x - 1 >= 0: liste[1] = image[x - 1][y] if image.shape[0]", "\"\"\" def median(image): nombrePixel = 0 newimg = deepcopy(image) # Parcours des lignes", "autours du pixel sur lequel nous travaillons # Il faut ranger les pixels", "image.shape[1] - 1 >= y + 1 >= 0: liste[2] = image[x -", "+ str(nombrePixel)) #print(\"Pourcentage de pixels non modifes : \" + str(image.shape[0]*image.shape[1]/nombrePixel) + str(\"", "0 and image.shape[1] - 1 >= y - 1 >= 0: liste[0] =", "non modifes : \" + str(image.shape[0]*image.shape[1]/nombrePixel) + str(\" %\")) return newimg # Il", ">= y - 1 >= 0: liste[5] = image[x + 1][y - 1]", "ordonnee \"\"\" Image: Image sur laquelle nous travaillons x : position x du", "newimg # Il faut prendre les 8 pixels qui sont autours du pixel", "= image[x + 1][y] if image.shape[0] - 1 >= x + 1 >=", "y du pixel return : retourne une liste qui contient les 8 pixels", "qui contient les 8 pixels autours du pixel sur lequel nous travaillons \"\"\"", "y + 1 >= 0: liste[7] = image[x + 1][y + 1] #", "+ 1][y - 1] if image.shape[0] - 1 >= x + 1 >=", "<image> l'image à débruiter retourne l'image débruitée \"\"\" def median(image): nombrePixel = 0", "== newimg[x][y]): nombrePixel = nombrePixel + 1 #print(\"Nombre de pixels non modifies :", "de cette liste ordonnee \"\"\" Image: Image sur laquelle nous travaillons x :", "1 >= x - 1 >= image.shape[0] - 1 >= 0 and image.shape[1]", ": \" + str(image.shape[0]*image.shape[1]/nombrePixel) + str(\" %\")) return newimg # Il faut prendre", "image[x + 1][y + 1] # Permet de trier notre liste liste =", ": position y du pixel return : retourne une liste qui contient les", "+ 1] if image.shape[1] - 1 >= y - 1 >= 0: liste[3]", "getPixels(image, x, y): liste = zeros(8, float) if image.shape[0] - 1 >= x", "# Parcours des colonnes de pixels for y in range(newimg.shape[1]): newimg[x][y] = getPixels(newimg,", "1 >= 0: liste[1] = image[x - 1][y] if image.shape[0] - 1 >=", "pixel sur lequel nous travaillons \"\"\" def getPixels(image, x, y): liste = zeros(8,", "# Il faut ranger les pixels par valeurs croissantes # Et ensuite prendre", "return newimg # Il faut prendre les 8 pixels qui sont autours du", "image.shape[1] - 1 >= y - 1 >= 0: liste[5] = image[x +", "1][y] if image.shape[0] - 1 >= x + 1 >= 0 and image.shape[1]", "image.shape[0] - 1 >= 0 and image.shape[1] - 1 >= y - 1", "lignes de pixels for x in range(newimg.shape[0]): # Parcours des colonnes de pixels", "import * \"\"\" Débruitage par filtrage médian <image> l'image à débruiter retourne l'image", "if image.shape[1] - 1 >= y + 1 >= 0: liste[4] = image[x][y", ": \" + str(nombrePixel)) #print(\"Pourcentage de pixels non modifes : \" + str(image.shape[0]*image.shape[1]/nombrePixel)", "des colonnes de pixels for y in range(newimg.shape[1]): newimg[x][y] = getPixels(newimg, x, y)", "image.shape[1] - 1 >= y + 1 >= 0: liste[7] = image[x +", ">= image.shape[0] - 1 >= 0 and image.shape[1] - 1 >= y -", "mediane = (liste[3] + liste[4]) / 2.0 # Retourne la mediane (8 pixels", "x, y): liste = zeros(8, float) if image.shape[0] - 1 >= x -", ">= x + 1 >= 0 and image.shape[1] - 1 >= y +", "du pixel sur lequel nous travaillons # Il faut ranger les pixels par", "8 pixels qui sont autours du pixel sur lequel nous travaillons # Il", "utf-8 -*- from copy import deepcopy from numpy import * \"\"\" Débruitage par", ">= 0 and image.shape[1] - 1 >= y + 1 >= 0: liste[2]", "and image.shape[1] - 1 >= y - 1 >= 0: liste[0] = image[x", "copy import deepcopy from numpy import * \"\"\" Débruitage par filtrage médian <image>", "1 >= x - 1 >= 0: liste[1] = image[x - 1][y] if", "- 1 >= y + 1 >= 0: liste[4] = image[x][y + 1]", "de pixels for x in range(newimg.shape[0]): # Parcours des colonnes de pixels for", "de trier notre liste liste = sorted(liste) mediane = (liste[3] + liste[4]) /", "+ 1 >= 0: liste[7] = image[x + 1][y + 1] # Permet", "= sorted(liste) mediane = (liste[3] + liste[4]) / 2.0 # Retourne la mediane", "(liste[3] + liste[4]) / 2.0 # Retourne la mediane (8 pixels donc 8/2", ">= 0: liste[0] = image[x - 1][y - 1] if image.shape[0] - 1", "liste[4]) / 2.0 # Retourne la mediane (8 pixels donc 8/2 = 4)", "0: liste[6] = image[x + 1][y] if image.shape[0] - 1 >= x +", "0 and image.shape[1] - 1 >= y - 1 >= 0: liste[5] =", "liste liste = sorted(liste) mediane = (liste[3] + liste[4]) / 2.0 # Retourne", "0: liste[2] = image[x - 1][y + 1] if image.shape[1] - 1 >=", "non modifies : \" + str(nombrePixel)) #print(\"Pourcentage de pixels non modifes : \"", "1 >= 0 and image.shape[1] - 1 >= y + 1 >= 0:", "x + 1 >= 0: liste[6] = image[x + 1][y] if image.shape[0] -", "1 >= y + 1 >= 0: liste[2] = image[x - 1][y +", "à débruiter retourne l'image débruitée \"\"\" def median(image): nombrePixel = 0 newimg =", "liste[1] = image[x - 1][y] if image.shape[0] - 1 >= x - 1", ">= y + 1 >= 0: liste[4] = image[x][y + 1] if image.shape[0]", "0: liste[3] = image[x][y - 1] if image.shape[1] - 1 >= y +", ">= 0 and image.shape[1] - 1 >= y - 1 >= 0: liste[5]", "+ str(\" %\")) return newimg # Il faut prendre les 8 pixels qui", "1 #print(\"Nombre de pixels non modifies : \" + str(nombrePixel)) #print(\"Pourcentage de pixels", ">= 0: liste[7] = image[x + 1][y + 1] # Permet de trier", "+ 1 >= 0: liste[2] = image[x - 1][y + 1] if image.shape[1]", "range(newimg.shape[0]): # Parcours des colonnes de pixels for y in range(newimg.shape[1]): newimg[x][y] =", "for y in range(newimg.shape[1]): newimg[x][y] = getPixels(newimg, x, y) if(image[x][y] == newimg[x][y]): nombrePixel", "pixels for x in range(newimg.shape[0]): # Parcours des colonnes de pixels for y", "liste[5] = image[x + 1][y - 1] if image.shape[0] - 1 >= x", "image[x][y - 1] if image.shape[1] - 1 >= y + 1 >= 0:", "liste[0] = image[x - 1][y - 1] if image.shape[0] - 1 >= x", "image[x + 1][y - 1] if image.shape[0] - 1 >= x + 1", "if(image[x][y] == newimg[x][y]): nombrePixel = nombrePixel + 1 #print(\"Nombre de pixels non modifies", "-*- from copy import deepcopy from numpy import * \"\"\" Débruitage par filtrage", "image[x][y + 1] if image.shape[0] - 1 >= x + 1 >= 0", "1 >= 0 and image.shape[1] - 1 >= y - 1 >= 0:", "x - 1 >= 0 and image.shape[1] - 1 >= y + 1", "\"\"\" def getPixels(image, x, y): liste = zeros(8, float) if image.shape[0] - 1", "and image.shape[1] - 1 >= y + 1 >= 0: liste[7] = image[x", "x - 1 >= 0: liste[1] = image[x - 1][y] if image.shape[0] -" ]
[ "basic HTTP authentication \"\"\" realm = TextLine(title=u'Realm', description=u'HTTP Basic Authentication Realm', required=True, default=u'Zope')", "string that is used during basic HTTP authentication \"\"\" realm = TextLine(title=u'Realm', description=u'HTTP", ">>> plugin.challenge(request) True >>> response._status 401 >>> response.getHeader('WWW-Authenticate', literal=True) 'basic realm=\"Zope\"' Notice that", "HTTP \"\"\" __docformat__ = \"reStructuredText\" import base64 from zope.interface import implementer, Interface from", "str class IHTTPBasicAuthRealm(Interface): \"\"\"HTTP Basic Auth Realm Represents the realm string that is", "zope.publisher.base import TestRequest >>> request = TestRequest('/') >>> response = request.response >>> print(plugin.challenge(request))", "plugin adds its challenge to the HTTP response. >>> from zope.publisher.browser import TestRequest", "no authentication header has been specified. >>> print(plugin.extractCredentials(TestRequest())) None Also, this plugin can", "request = TestRequest(environ={'HTTP_AUTHORIZATION': 'foo bar'}) >>> print(plugin.extractCredentials(TestRequest())) None This plugin only works with", "THIS SOFTWARE IS PROVIDED \"AS IS\" AND ANY AND ALL EXPRESS OR IMPLIED", "# Py3: define unicode unicode = str class IHTTPBasicAuthRealm(Interface): \"\"\"HTTP Basic Auth Realm", "authentication. >>> request = TestRequest(environ={'HTTP_AUTHORIZATION': 'foo bar'}) >>> print(plugin.extractCredentials(TestRequest())) None This plugin only", "import base64 from zope.interface import implementer, Interface from zope.publisher.interfaces.http import IHTTPRequest from zope.schema", "= HTTPBasicAuthCredentialsPlugin() >>> from zope.publisher.browser import TestRequest >>> plugin.logout(TestRequest()) False \"\"\" return False", "interfaces try: unicode except NameError: # Py3: define unicode unicode = str class", ">>> request = TestRequest('/') >>> response = request.response >>> print(plugin.challenge(request)) False \"\"\" if", "Basic Authentication Realm', required=True, default=u'Zope') @implementer(interfaces.ICredentialsPlugin, IHTTPBasicAuthRealm) class HTTPBasicAuthCredentialsPlugin(object): realm = 'Zope' protocol", "realm=\"%s\"' % self.realm, literal=True) request.response.setStatus(401) return True def logout(self, request): \"\"\"Always returns False", "been specified. >>> print(plugin.extractCredentials(TestRequest())) None Also, this plugin can *only* handle basic authentication.", "INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST", "to the HTTP response. >>> from zope.publisher.browser import TestRequest >>> request = TestRequest()", "To illustrate, we'll create a plugin: >>> plugin = HTTPBasicAuthCredentialsPlugin() The plugin adds", "= TestRequest(environ={'HTTP_AUTHORIZATION': 'foo bar'}) >>> print(plugin.extractCredentials(TestRequest())) None This plugin only works with HTTP", "\"\"\"PAS plugins related to HTTP \"\"\" __docformat__ = \"reStructuredText\" import base64 from zope.interface", "`None`, if no authentication header has been specified. >>> print(plugin.extractCredentials(TestRequest())) None Also, this", "# No encoding needed, should be base64 string anyways. credentials = credentials.encode() login,", "PROVIDED \"AS IS\" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE", "NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND", "if not IHTTPRequest.providedBy(request): return None if request._auth: if request._auth.lower().startswith(u'basic '): credentials = request._auth.split()[-1]", "import interfaces try: unicode except NameError: # Py3: define unicode unicode = str", "ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE,", "OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. #", "= HTTPBasicAuthCredentialsPlugin() The plugin adds its challenge to the HTTP response. >>> from", "TestRequest as BrowserRequest >>> request = BrowserRequest('/', ... environ={'HTTP_AUTHORIZATION': u'Basic bWdyOm1ncnB3OndpdGg6Y29sb24='}) >>> pprint(plugin.extractCredentials(request))", "if not IHTTPRequest.providedBy(request): return False request.response.setHeader(\"WWW-Authenticate\", 'basic realm=\"%s\"' % self.realm, literal=True) request.response.setStatus(401) return", "the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy", "string anyways. credentials = credentials.encode() login, password = base64.b64decode(credentials).split(b':', 1) return {'login': login.decode('utf-8'),", "= HTTPBasicAuthCredentialsPlugin() >>> from pprint import pprint >>> pprint(plugin.extractCredentials(request)) {'login': u'mgr', 'password': u'<PASSWORD>'}", ">>> print(plugin.extractCredentials(TestRequest())) None Also, this plugin can *only* handle basic authentication. >>> request", "one or more colons; user ID can't contain any colon. >>> from zope.publisher.browser", "the realm string that is used during basic HTTP authentication \"\"\" realm =", "TestRequest >>> request = TestRequest() >>> response = request.response >>> plugin.challenge(request) True >>>", "# Copyright (c) 2004 Zope Foundation and Contributors. # All Rights Reserved. #", "import TestRequest >>> request = TestRequest('/') >>> response = request.response >>> print(plugin.challenge(request)) False", "... environ={'HTTP_AUTHORIZATION': u'Basic bWdyOm1ncnB3'}) Now create the plugin and get the credentials. >>>", "= TextLine(title=u'Realm', description=u'HTTP Basic Authentication Realm', required=True, default=u'Zope') @implementer(interfaces.ICredentialsPlugin, IHTTPBasicAuthRealm) class HTTPBasicAuthCredentialsPlugin(object): realm", "logout is not supported by basic auth. >>> plugin = HTTPBasicAuthCredentialsPlugin() >>> from", "zope.interface import implementer, Interface from zope.publisher.interfaces.http import IHTTPRequest from zope.schema import TextLine from", "environ={'HTTP_AUTHORIZATION': u'Basic bWdyOm1ncnB3'}) Now create the plugin and get the credentials. >>> plugin", "None This plugin only works with HTTP requests. >>> from zope.publisher.base import TestRequest", "2004 Zope Foundation and Contributors. # All Rights Reserved. # # This software", "{'login': u'mgr', 'password': u'<PASSWORD>'} \"\"\" if not IHTTPRequest.providedBy(request): return None if request._auth: if", "unicode = str class IHTTPBasicAuthRealm(Interface): \"\"\"HTTP Basic Auth Realm Represents the realm string", "return None def challenge(self, request): \"\"\"Issues an HTTP basic auth challenge for credentials.", "password = base64.b64decode(credentials).split(b':', 1) return {'login': login.decode('utf-8'), 'password': password.decode('utf-8')} return None def challenge(self,", "define unicode unicode = str class IHTTPBasicAuthRealm(Interface): \"\"\"HTTP Basic Auth Realm Represents the", "response. >>> from zope.publisher.browser import TestRequest >>> request = TestRequest() >>> response =", "\"\"\" if not IHTTPRequest.providedBy(request): return None if request._auth: if request._auth.lower().startswith(u'basic '): credentials =", "zope.publisher.browser import TestRequest as BrowserRequest >>> request = BrowserRequest('/', ... environ={'HTTP_AUTHORIZATION': u'Basic bWdyOm1ncnB3OndpdGg6Y29sb24='})", "Contributors. # All Rights Reserved. # # This software is subject to the", "MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################## \"\"\"PAS", "This plugin only works with HTTP requests. >>> from zope.publisher.base import TestRequest >>>", "AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT", "appropriate response headers. To illustrate, we'll create a plugin: >>> plugin = HTTPBasicAuthCredentialsPlugin()", "AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED", "response._status 401 >>> response.getHeader('WWW-Authenticate', literal=True) 'basic realm=\"Zope\"' Notice that the realm is quoted,", "(c) 2004 Zope Foundation and Contributors. # All Rights Reserved. # # This", "base64 string anyways. credentials = credentials.encode() login, password = base64.b64decode(credentials).split(b':', 1) return {'login':", "# All Rights Reserved. # # This software is subject to the provisions", "requests. >>> from zope.publisher.base import TestRequest >>> print(plugin.extractCredentials(TestRequest('/'))) None According to RFC 2617,", "IS\" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING,", "A PARTICULAR PURPOSE. # ############################################################################## \"\"\"PAS plugins related to HTTP \"\"\" __docformat__ =", "plugins related to HTTP \"\"\" __docformat__ = \"reStructuredText\" import base64 from zope.interface import", ">>> request = BrowserRequest('/', ... environ={'HTTP_AUTHORIZATION': u'Basic bWdyOm1ncnB3OndpdGg6Y29sb24='}) >>> pprint(plugin.extractCredentials(request)) {'login': u'mgr', 'password':", "to the provisions of the Zope Public License, # Version 2.1 (ZPL). A", "THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR", "zope.publisher.browser import TestRequest >>> request = TestRequest( ... environ={'HTTP_AUTHORIZATION': u'Basic bWdyOm1ncnB3'}) Now create", "base64.b64decode(credentials).split(b':', 1) return {'login': login.decode('utf-8'), 'password': password.decode('utf-8')} return None def challenge(self, request): \"\"\"Issues", "that contains some credentials. >>> from zope.publisher.browser import TestRequest >>> request = TestRequest(", "\"\"\" if not IHTTPRequest.providedBy(request): return False request.response.setHeader(\"WWW-Authenticate\", 'basic realm=\"%s\"' % self.realm, literal=True) request.response.setStatus(401)", "the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED \"AS IS\"", "basic auth. >>> plugin = HTTPBasicAuthCredentialsPlugin() >>> from zope.publisher.browser import TestRequest >>> plugin.logout(TestRequest())", "is subject to the provisions of the Zope Public License, # Version 2.1", "auth credentials from a request. First we need to create a request that", "if no authentication header has been specified. >>> print(plugin.extractCredentials(TestRequest())) None Also, this plugin", "base64 from zope.interface import implementer, Interface from zope.publisher.interfaces.http import IHTTPRequest from zope.schema import", "illustrate, we'll create a plugin: >>> plugin = HTTPBasicAuthCredentialsPlugin() The plugin adds its", "request.response >>> print(plugin.challenge(request)) False \"\"\" if not IHTTPRequest.providedBy(request): return False request.response.setHeader(\"WWW-Authenticate\", 'basic realm=\"%s\"'", "import TextLine from zope.pluggableauth import interfaces try: unicode except NameError: # Py3: define", "Rights Reserved. # # This software is subject to the provisions of the", "unicode): # No encoding needed, should be base64 string anyways. credentials = credentials.encode()", "Notice that the realm is quoted, as per RFC 2617. The plugin only", "the credentials. >>> plugin = HTTPBasicAuthCredentialsPlugin() >>> from pprint import pprint >>> pprint(plugin.extractCredentials(request))", "pprint import pprint >>> pprint(plugin.extractCredentials(request)) {'login': u'mgr', 'password': u'<PASSWORD>'} Make sure we return", "from zope.publisher.base import TestRequest >>> print(plugin.extractCredentials(TestRequest('/'))) None According to RFC 2617, password can", "the appropriate response headers. To illustrate, we'll create a plugin: >>> plugin =", "IHTTPRequest.providedBy(request): return None if request._auth: if request._auth.lower().startswith(u'basic '): credentials = request._auth.split()[-1] if isinstance(credentials,", "plugin: >>> plugin = HTTPBasicAuthCredentialsPlugin() The plugin adds its challenge to the HTTP", "import TestRequest >>> request = TestRequest() >>> response = request.response >>> plugin.challenge(request) True", "per RFC 2617. The plugin only works with HTTP requests. >>> from zope.publisher.base", ">>> from zope.publisher.base import TestRequest >>> request = TestRequest('/') >>> response = request.response", "request.response.setStatus(401) return True def logout(self, request): \"\"\"Always returns False as logout is not", "not supported by basic auth. >>> plugin = HTTPBasicAuthCredentialsPlugin() >>> from zope.publisher.browser import", "from zope.publisher.interfaces.http import IHTTPRequest from zope.schema import TextLine from zope.pluggableauth import interfaces try:", "can *only* handle basic authentication. >>> request = TestRequest(environ={'HTTP_AUTHORIZATION': 'foo bar'}) >>> print(plugin.extractCredentials(TestRequest()))", "by setting the appropriate response headers. To illustrate, we'll create a plugin: >>>", "credentials.encode() login, password = base64.b64decode(credentials).split(b':', 1) return {'login': login.decode('utf-8'), 'password': password.decode('utf-8')} return None", "HTTP authentication \"\"\" realm = TextLine(title=u'Realm', description=u'HTTP Basic Authentication Realm', required=True, default=u'Zope') @implementer(interfaces.ICredentialsPlugin,", "FOR A PARTICULAR PURPOSE. # ############################################################################## \"\"\"PAS plugins related to HTTP \"\"\" __docformat__", "realm string that is used during basic HTTP authentication \"\"\" realm = TextLine(title=u'Realm',", "u'Basic bWdyOm1ncnB3'}) Now create the plugin and get the credentials. >>> plugin =", "works with HTTP requests. >>> from zope.publisher.base import TestRequest >>> print(plugin.extractCredentials(TestRequest('/'))) None According", "isinstance(credentials, unicode): # No encoding needed, should be base64 string anyways. credentials =", "@implementer(interfaces.ICredentialsPlugin, IHTTPBasicAuthRealm) class HTTPBasicAuthCredentialsPlugin(object): realm = 'Zope' protocol = 'http auth' def extractCredentials(self,", "more colons; user ID can't contain any colon. >>> from zope.publisher.browser import TestRequest", "should be base64 string anyways. credentials = credentials.encode() login, password = base64.b64decode(credentials).split(b':', 1)", "request._auth.lower().startswith(u'basic '): credentials = request._auth.split()[-1] if isinstance(credentials, unicode): # No encoding needed, should", "anyways. credentials = credentials.encode() login, password = base64.b64decode(credentials).split(b':', 1) return {'login': login.decode('utf-8'), 'password':", "some credentials. >>> from zope.publisher.browser import TestRequest >>> request = TestRequest( ... environ={'HTTP_AUTHORIZATION':", "INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################## \"\"\"PAS plugins related", "*only* handle basic authentication. >>> request = TestRequest(environ={'HTTP_AUTHORIZATION': 'foo bar'}) >>> print(plugin.extractCredentials(TestRequest())) None", "No encoding needed, should be base64 string anyways. credentials = credentials.encode() login, password", "NameError: # Py3: define unicode unicode = str class IHTTPBasicAuthRealm(Interface): \"\"\"HTTP Basic Auth", "request.response >>> plugin.challenge(request) True >>> response._status 401 >>> response.getHeader('WWW-Authenticate', literal=True) 'basic realm=\"Zope\"' Notice", "# # This software is subject to the provisions of the Zope Public", "if isinstance(credentials, unicode): # No encoding needed, should be base64 string anyways. credentials", "request._auth: if request._auth.lower().startswith(u'basic '): credentials = request._auth.split()[-1] if isinstance(credentials, unicode): # No encoding", "related to HTTP \"\"\" __docformat__ = \"reStructuredText\" import base64 from zope.interface import implementer,", "protocol = 'http auth' def extractCredentials(self, request): \"\"\"Extracts HTTP basic auth credentials from", "requests. >>> from zope.publisher.base import TestRequest >>> request = TestRequest('/') >>> response =", "bWdyOm1ncnB3OndpdGg6Y29sb24='}) >>> pprint(plugin.extractCredentials(request)) {'login': u'mgr', 'password': u'<PASSWORD>'} \"\"\" if not IHTTPRequest.providedBy(request): return None", "extractCredentials(self, request): \"\"\"Extracts HTTP basic auth credentials from a request. First we need", "literal=True) 'basic realm=\"Zope\"' Notice that the realm is quoted, as per RFC 2617.", "# This software is subject to the provisions of the Zope Public License,", ">>> from pprint import pprint >>> pprint(plugin.extractCredentials(request)) {'login': u'mgr', 'password': u'<PASSWORD>'} Make sure", "challenge(self, request): \"\"\"Issues an HTTP basic auth challenge for credentials. The challenge is", "get the credentials. >>> plugin = HTTPBasicAuthCredentialsPlugin() >>> from pprint import pprint >>>", "\"\"\" realm = TextLine(title=u'Realm', description=u'HTTP Basic Authentication Realm', required=True, default=u'Zope') @implementer(interfaces.ICredentialsPlugin, IHTTPBasicAuthRealm) class", "LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS", "self.realm, literal=True) request.response.setStatus(401) return True def logout(self, request): \"\"\"Always returns False as logout", "HTTP response. >>> from zope.publisher.browser import TestRequest >>> request = TestRequest() >>> response", "\"AS IS\" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED,", "accompany this distribution. # THIS SOFTWARE IS PROVIDED \"AS IS\" AND ANY AND", "Represents the realm string that is used during basic HTTP authentication \"\"\" realm", "def challenge(self, request): \"\"\"Issues an HTTP basic auth challenge for credentials. The challenge", "HTTP requests. >>> from zope.publisher.base import TestRequest >>> print(plugin.extractCredentials(TestRequest('/'))) None According to RFC", "realm=\"Zope\"' Notice that the realm is quoted, as per RFC 2617. The plugin", "software is subject to the provisions of the Zope Public License, # Version", "plugin = HTTPBasicAuthCredentialsPlugin() >>> from zope.publisher.browser import TestRequest >>> plugin.logout(TestRequest()) False \"\"\" return", "required=True, default=u'Zope') @implementer(interfaces.ICredentialsPlugin, IHTTPBasicAuthRealm) class HTTPBasicAuthCredentialsPlugin(object): realm = 'Zope' protocol = 'http auth'", "TestRequest(environ={'HTTP_AUTHORIZATION': 'foo bar'}) >>> print(plugin.extractCredentials(TestRequest())) None This plugin only works with HTTP requests.", "if request._auth.lower().startswith(u'basic '): credentials = request._auth.split()[-1] if isinstance(credentials, unicode): # No encoding needed,", "with HTTP requests. >>> from zope.publisher.base import TestRequest >>> print(plugin.extractCredentials(TestRequest('/'))) None According to", "2617. The plugin only works with HTTP requests. >>> from zope.publisher.base import TestRequest", "= request.response >>> plugin.challenge(request) True >>> response._status 401 >>> response.getHeader('WWW-Authenticate', literal=True) 'basic realm=\"Zope\"'", "# FOR A PARTICULAR PURPOSE. # ############################################################################## \"\"\"PAS plugins related to HTTP \"\"\"", "print(plugin.extractCredentials(TestRequest())) None Also, this plugin can *only* handle basic authentication. >>> request =", "2617, password can contain one or more colons; user ID can't contain any", "# ############################################################################## \"\"\"PAS plugins related to HTTP \"\"\" __docformat__ = \"reStructuredText\" import base64", "Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany", "2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS", "from zope.publisher.browser import TestRequest >>> request = TestRequest( ... environ={'HTTP_AUTHORIZATION': u'Basic bWdyOm1ncnB3'}) Now", "IHTTPRequest.providedBy(request): return False request.response.setHeader(\"WWW-Authenticate\", 'basic realm=\"%s\"' % self.realm, literal=True) request.response.setStatus(401) return True def", "\"\"\"Extracts HTTP basic auth credentials from a request. First we need to create", "= request.response >>> print(plugin.challenge(request)) False \"\"\" if not IHTTPRequest.providedBy(request): return False request.response.setHeader(\"WWW-Authenticate\", 'basic", "request = TestRequest() >>> response = request.response >>> plugin.challenge(request) True >>> response._status 401", "TestRequest('/') >>> response = request.response >>> print(plugin.challenge(request)) False \"\"\" if not IHTTPRequest.providedBy(request): return", "unicode except NameError: # Py3: define unicode unicode = str class IHTTPBasicAuthRealm(Interface): \"\"\"HTTP", "request = TestRequest('/') >>> response = request.response >>> print(plugin.challenge(request)) False \"\"\" if not", "supported by basic auth. >>> plugin = HTTPBasicAuthCredentialsPlugin() >>> from zope.publisher.browser import TestRequest", "is not supported by basic auth. >>> plugin = HTTPBasicAuthCredentialsPlugin() >>> from zope.publisher.browser", "authentication \"\"\" realm = TextLine(title=u'Realm', description=u'HTTP Basic Authentication Realm', required=True, default=u'Zope') @implementer(interfaces.ICredentialsPlugin, IHTTPBasicAuthRealm)", "{'login': login.decode('utf-8'), 'password': password.decode('utf-8')} return None def challenge(self, request): \"\"\"Issues an HTTP basic", ">>> print(plugin.extractCredentials(TestRequest())) None This plugin only works with HTTP requests. >>> from zope.publisher.base", "setting the appropriate response headers. To illustrate, we'll create a plugin: >>> plugin", "contains some credentials. >>> from zope.publisher.browser import TestRequest >>> request = TestRequest( ...", "'password': password.decode('utf-8')} return None def challenge(self, request): \"\"\"Issues an HTTP basic auth challenge", "SOFTWARE IS PROVIDED \"AS IS\" AND ANY AND ALL EXPRESS OR IMPLIED #", "TestRequest >>> print(plugin.extractCredentials(TestRequest('/'))) None According to RFC 2617, password can contain one or", "BrowserRequest('/', ... environ={'HTTP_AUTHORIZATION': u'Basic bWdyOm1ncnB3OndpdGg6Y29sb24='}) >>> pprint(plugin.extractCredentials(request)) {'login': u'mgr', 'password': u'<PASSWORD>'} \"\"\" if", "The challenge is issued by setting the appropriate response headers. To illustrate, we'll", "u'<PASSWORD>'} Make sure we return `None`, if no authentication header has been specified.", "issued by setting the appropriate response headers. To illustrate, we'll create a plugin:", "class IHTTPBasicAuthRealm(Interface): \"\"\"HTTP Basic Auth Realm Represents the realm string that is used", "PARTICULAR PURPOSE. # ############################################################################## \"\"\"PAS plugins related to HTTP \"\"\" __docformat__ = \"reStructuredText\"", "credentials from a request. First we need to create a request that contains", "False \"\"\" if not IHTTPRequest.providedBy(request): return False request.response.setHeader(\"WWW-Authenticate\", 'basic realm=\"%s\"' % self.realm, literal=True)", "has been specified. >>> print(plugin.extractCredentials(TestRequest())) None Also, this plugin can *only* handle basic", "credentials = request._auth.split()[-1] if isinstance(credentials, unicode): # No encoding needed, should be base64", "= 'Zope' protocol = 'http auth' def extractCredentials(self, request): \"\"\"Extracts HTTP basic auth", ">>> request = TestRequest() >>> response = request.response >>> plugin.challenge(request) True >>> response._status", ">>> response = request.response >>> plugin.challenge(request) True >>> response._status 401 >>> response.getHeader('WWW-Authenticate', literal=True)", "credentials = credentials.encode() login, password = base64.b64decode(credentials).split(b':', 1) return {'login': login.decode('utf-8'), 'password': password.decode('utf-8')}", "... environ={'HTTP_AUTHORIZATION': u'Basic bWdyOm1ncnB3OndpdGg6Y29sb24='}) >>> pprint(plugin.extractCredentials(request)) {'login': u'mgr', 'password': u'<PASSWORD>'} \"\"\" if not", "Make sure we return `None`, if no authentication header has been specified. >>>", "\"\"\" __docformat__ = \"reStructuredText\" import base64 from zope.interface import implementer, Interface from zope.publisher.interfaces.http", "'password': u'<PASSWORD>'} \"\"\" if not IHTTPRequest.providedBy(request): return None if request._auth: if request._auth.lower().startswith(u'basic '):", "auth. >>> plugin = HTTPBasicAuthCredentialsPlugin() >>> from zope.publisher.browser import TestRequest >>> plugin.logout(TestRequest()) False", "that the realm is quoted, as per RFC 2617. The plugin only works", "to HTTP \"\"\" __docformat__ = \"reStructuredText\" import base64 from zope.interface import implementer, Interface", "Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. #", "any colon. >>> from zope.publisher.browser import TestRequest as BrowserRequest >>> request = BrowserRequest('/',", "an HTTP basic auth challenge for credentials. The challenge is issued by setting", "challenge for credentials. The challenge is issued by setting the appropriate response headers.", "login, password = base64.b64decode(credentials).split(b':', 1) return {'login': login.decode('utf-8'), 'password': password.decode('utf-8')} return None def", "401 >>> response.getHeader('WWW-Authenticate', literal=True) 'basic realm=\"Zope\"' Notice that the realm is quoted, as", "plugin only works with HTTP requests. >>> from zope.publisher.base import TestRequest >>> request", "# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.", "RFC 2617, password can contain one or more colons; user ID can't contain", "user ID can't contain any colon. >>> from zope.publisher.browser import TestRequest as BrowserRequest", "a plugin: >>> plugin = HTTPBasicAuthCredentialsPlugin() The plugin adds its challenge to the", "PURPOSE. # ############################################################################## \"\"\"PAS plugins related to HTTP \"\"\" __docformat__ = \"reStructuredText\" import", "HTTPBasicAuthCredentialsPlugin() The plugin adds its challenge to the HTTP response. >>> from zope.publisher.browser", "WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF", "plugin can *only* handle basic authentication. >>> request = TestRequest(environ={'HTTP_AUTHORIZATION': 'foo bar'}) >>>", "\"\"\"HTTP Basic Auth Realm Represents the realm string that is used during basic", "'http auth' def extractCredentials(self, request): \"\"\"Extracts HTTP basic auth credentials from a request.", "header has been specified. >>> print(plugin.extractCredentials(TestRequest())) None Also, this plugin can *only* handle", "= base64.b64decode(credentials).split(b':', 1) return {'login': login.decode('utf-8'), 'password': password.decode('utf-8')} return None def challenge(self, request):", "\"\"\"Issues an HTTP basic auth challenge for credentials. The challenge is issued by", "basic authentication. >>> request = TestRequest(environ={'HTTP_AUTHORIZATION': 'foo bar'}) >>> print(plugin.extractCredentials(TestRequest())) None This plugin", "IHTTPBasicAuthRealm) class HTTPBasicAuthCredentialsPlugin(object): realm = 'Zope' protocol = 'http auth' def extractCredentials(self, request):", "response.getHeader('WWW-Authenticate', literal=True) 'basic realm=\"Zope\"' Notice that the realm is quoted, as per RFC", "password.decode('utf-8')} return None def challenge(self, request): \"\"\"Issues an HTTP basic auth challenge for", "contain any colon. >>> from zope.publisher.browser import TestRequest as BrowserRequest >>> request =", "FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################## \"\"\"PAS plugins related to HTTP", "the realm is quoted, as per RFC 2617. The plugin only works with", "contain one or more colons; user ID can't contain any colon. >>> from", ">>> plugin = HTTPBasicAuthCredentialsPlugin() >>> from pprint import pprint >>> pprint(plugin.extractCredentials(request)) {'login': u'mgr',", "Interface from zope.publisher.interfaces.http import IHTTPRequest from zope.schema import TextLine from zope.pluggableauth import interfaces", "Basic Auth Realm Represents the realm string that is used during basic HTTP", "be base64 string anyways. credentials = credentials.encode() login, password = base64.b64decode(credentials).split(b':', 1) return", "realm = TextLine(title=u'Realm', description=u'HTTP Basic Authentication Realm', required=True, default=u'Zope') @implementer(interfaces.ICredentialsPlugin, IHTTPBasicAuthRealm) class HTTPBasicAuthCredentialsPlugin(object):", "bar'}) >>> print(plugin.extractCredentials(TestRequest())) None This plugin only works with HTTP requests. >>> from", "License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this", ">>> print(plugin.challenge(request)) False \"\"\" if not IHTTPRequest.providedBy(request): return False request.response.setHeader(\"WWW-Authenticate\", 'basic realm=\"%s\"' %", "password can contain one or more colons; user ID can't contain any colon.", "HTTP requests. >>> from zope.publisher.base import TestRequest >>> request = TestRequest('/') >>> response", "create the plugin and get the credentials. >>> plugin = HTTPBasicAuthCredentialsPlugin() >>> from", "'basic realm=\"%s\"' % self.realm, literal=True) request.response.setStatus(401) return True def logout(self, request): \"\"\"Always returns", "for credentials. The challenge is issued by setting the appropriate response headers. To", ">>> response = request.response >>> print(plugin.challenge(request)) False \"\"\" if not IHTTPRequest.providedBy(request): return False", "can't contain any colon. >>> from zope.publisher.browser import TestRequest as BrowserRequest >>> request", "TextLine from zope.pluggableauth import interfaces try: unicode except NameError: # Py3: define unicode", "request that contains some credentials. >>> from zope.publisher.browser import TestRequest >>> request =", "TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ##############################################################################", "return True def logout(self, request): \"\"\"Always returns False as logout is not supported", ">>> response.getHeader('WWW-Authenticate', literal=True) 'basic realm=\"Zope\"' Notice that the realm is quoted, as per", "IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED #", "Also, this plugin can *only* handle basic authentication. >>> request = TestRequest(environ={'HTTP_AUTHORIZATION': 'foo", "and get the credentials. >>> plugin = HTTPBasicAuthCredentialsPlugin() >>> from pprint import pprint", "a request. First we need to create a request that contains some credentials.", "from zope.publisher.browser import TestRequest >>> request = TestRequest() >>> response = request.response >>>", "Auth Realm Represents the realm string that is used during basic HTTP authentication", "from zope.publisher.browser import TestRequest as BrowserRequest >>> request = BrowserRequest('/', ... environ={'HTTP_AUTHORIZATION': u'Basic", "response = request.response >>> print(plugin.challenge(request)) False \"\"\" if not IHTTPRequest.providedBy(request): return False request.response.setHeader(\"WWW-Authenticate\",", "not IHTTPRequest.providedBy(request): return False request.response.setHeader(\"WWW-Authenticate\", 'basic realm=\"%s\"' % self.realm, literal=True) request.response.setStatus(401) return True", "credentials. >>> plugin = HTTPBasicAuthCredentialsPlugin() >>> from pprint import pprint >>> pprint(plugin.extractCredentials(request)) {'login':", "authentication header has been specified. >>> print(plugin.extractCredentials(TestRequest())) None Also, this plugin can *only*", "None def challenge(self, request): \"\"\"Issues an HTTP basic auth challenge for credentials. The", "# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR", "provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of", "IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A", "This software is subject to the provisions of the Zope Public License, #", "'Zope' protocol = 'http auth' def extractCredentials(self, request): \"\"\"Extracts HTTP basic auth credentials", "from zope.interface import implementer, Interface from zope.publisher.interfaces.http import IHTTPRequest from zope.schema import TextLine", "request. First we need to create a request that contains some credentials. >>>", "Realm Represents the realm string that is used during basic HTTP authentication \"\"\"", "only works with HTTP requests. >>> from zope.publisher.base import TestRequest >>> request =", "logout(self, request): \"\"\"Always returns False as logout is not supported by basic auth.", "auth challenge for credentials. The challenge is issued by setting the appropriate response", "Now create the plugin and get the credentials. >>> plugin = HTTPBasicAuthCredentialsPlugin() >>>", ">>> from zope.publisher.browser import TestRequest as BrowserRequest >>> request = BrowserRequest('/', ... environ={'HTTP_AUTHORIZATION':", "zope.publisher.browser import TestRequest >>> request = TestRequest() >>> response = request.response >>> plugin.challenge(request)", "quoted, as per RFC 2617. The plugin only works with HTTP requests. >>>", "credentials. >>> from zope.publisher.browser import TestRequest >>> request = TestRequest( ... environ={'HTTP_AUTHORIZATION': u'Basic", "# # Copyright (c) 2004 Zope Foundation and Contributors. # All Rights Reserved.", "u'Basic bWdyOm1ncnB3OndpdGg6Y29sb24='}) >>> pprint(plugin.extractCredentials(request)) {'login': u'mgr', 'password': u'<PASSWORD>'} \"\"\" if not IHTTPRequest.providedBy(request): return", "is quoted, as per RFC 2617. The plugin only works with HTTP requests.", "request = TestRequest( ... environ={'HTTP_AUTHORIZATION': u'Basic bWdyOm1ncnB3'}) Now create the plugin and get", "from pprint import pprint >>> pprint(plugin.extractCredentials(request)) {'login': u'mgr', 'password': u'<PASSWORD>'} Make sure we", "of the Zope Public License, # Version 2.1 (ZPL). A copy of the", ">>> from zope.publisher.browser import TestRequest >>> request = TestRequest() >>> response = request.response", "print(plugin.extractCredentials(TestRequest('/'))) None According to RFC 2617, password can contain one or more colons;", "basic auth challenge for credentials. The challenge is issued by setting the appropriate", "we return `None`, if no authentication header has been specified. >>> print(plugin.extractCredentials(TestRequest())) None", "EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE", "= credentials.encode() login, password = base64.b64decode(credentials).split(b':', 1) return {'login': login.decode('utf-8'), 'password': password.decode('utf-8')} return", "only works with HTTP requests. >>> from zope.publisher.base import TestRequest >>> print(plugin.extractCredentials(TestRequest('/'))) None", "All Rights Reserved. # # This software is subject to the provisions of", "IHTTPBasicAuthRealm(Interface): \"\"\"HTTP Basic Auth Realm Represents the realm string that is used during", "import implementer, Interface from zope.publisher.interfaces.http import IHTTPRequest from zope.schema import TextLine from zope.pluggableauth", "plugin = HTTPBasicAuthCredentialsPlugin() The plugin adds its challenge to the HTTP response. >>>", "pprint(plugin.extractCredentials(request)) {'login': u'mgr', 'password': u'<PASSWORD>'} Make sure we return `None`, if no authentication", "First we need to create a request that contains some credentials. >>> from", "None Also, this plugin can *only* handle basic authentication. >>> request = TestRequest(environ={'HTTP_AUTHORIZATION':", "specified. >>> print(plugin.extractCredentials(TestRequest())) None Also, this plugin can *only* handle basic authentication. >>>", "'password': u'<PASSWORD>'} Make sure we return `None`, if no authentication header has been", "zope.publisher.interfaces.http import IHTTPRequest from zope.schema import TextLine from zope.pluggableauth import interfaces try: unicode", "except NameError: # Py3: define unicode unicode = str class IHTTPBasicAuthRealm(Interface): \"\"\"HTTP Basic", "plugin.challenge(request) True >>> response._status 401 >>> response.getHeader('WWW-Authenticate', literal=True) 'basic realm=\"Zope\"' Notice that the", "RFC 2617. The plugin only works with HTTP requests. >>> from zope.publisher.base import", "with HTTP requests. >>> from zope.publisher.base import TestRequest >>> request = TestRequest('/') >>>", "this distribution. # THIS SOFTWARE IS PROVIDED \"AS IS\" AND ANY AND ALL", "\"reStructuredText\" import base64 from zope.interface import implementer, Interface from zope.publisher.interfaces.http import IHTTPRequest from", "request): \"\"\"Extracts HTTP basic auth credentials from a request. First we need to", "implementer, Interface from zope.publisher.interfaces.http import IHTTPRequest from zope.schema import TextLine from zope.pluggableauth import", "need to create a request that contains some credentials. >>> from zope.publisher.browser import", "zope.pluggableauth import interfaces try: unicode except NameError: # Py3: define unicode unicode =", "= 'http auth' def extractCredentials(self, request): \"\"\"Extracts HTTP basic auth credentials from a", "create a request that contains some credentials. >>> from zope.publisher.browser import TestRequest >>>", "can contain one or more colons; user ID can't contain any colon. >>>", "should accompany this distribution. # THIS SOFTWARE IS PROVIDED \"AS IS\" AND ANY", "ID can't contain any colon. >>> from zope.publisher.browser import TestRequest as BrowserRequest >>>", "AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################## \"\"\"PAS plugins", "this plugin can *only* handle basic authentication. >>> request = TestRequest(environ={'HTTP_AUTHORIZATION': 'foo bar'})", "TextLine(title=u'Realm', description=u'HTTP Basic Authentication Realm', required=True, default=u'Zope') @implementer(interfaces.ICredentialsPlugin, IHTTPBasicAuthRealm) class HTTPBasicAuthCredentialsPlugin(object): realm =", "= request._auth.split()[-1] if isinstance(credentials, unicode): # No encoding needed, should be base64 string", "colon. >>> from zope.publisher.browser import TestRequest as BrowserRequest >>> request = BrowserRequest('/', ...", "OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED", "login.decode('utf-8'), 'password': password.decode('utf-8')} return None def challenge(self, request): \"\"\"Issues an HTTP basic auth", "class HTTPBasicAuthCredentialsPlugin(object): realm = 'Zope' protocol = 'http auth' def extractCredentials(self, request): \"\"\"Extracts", "works with HTTP requests. >>> from zope.publisher.base import TestRequest >>> request = TestRequest('/')", "############################################################################## \"\"\"PAS plugins related to HTTP \"\"\" __docformat__ = \"reStructuredText\" import base64 from", "HTTPBasicAuthCredentialsPlugin() >>> from pprint import pprint >>> pprint(plugin.extractCredentials(request)) {'login': u'mgr', 'password': u'<PASSWORD>'} Make", "import pprint >>> pprint(plugin.extractCredentials(request)) {'login': u'mgr', 'password': u'<PASSWORD>'} Make sure we return `None`,", "def extractCredentials(self, request): \"\"\"Extracts HTTP basic auth credentials from a request. First we", "TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS #", ">>> request = TestRequest( ... environ={'HTTP_AUTHORIZATION': u'Basic bWdyOm1ncnB3'}) Now create the plugin and", "during basic HTTP authentication \"\"\" realm = TextLine(title=u'Realm', description=u'HTTP Basic Authentication Realm', required=True,", "import TestRequest >>> request = TestRequest( ... environ={'HTTP_AUTHORIZATION': u'Basic bWdyOm1ncnB3'}) Now create the", "needed, should be base64 string anyways. credentials = credentials.encode() login, password = base64.b64decode(credentials).split(b':',", "adds its challenge to the HTTP response. >>> from zope.publisher.browser import TestRequest >>>", "The plugin only works with HTTP requests. >>> from zope.publisher.base import TestRequest >>>", "is issued by setting the appropriate response headers. To illustrate, we'll create a", "<gh_stars>1-10 ############################################################################## # # Copyright (c) 2004 Zope Foundation and Contributors. # All", "'basic realm=\"Zope\"' Notice that the realm is quoted, as per RFC 2617. The", "{'login': u'mgr', 'password': u'<PASSWORD>'} Make sure we return `None`, if no authentication header", "literal=True) request.response.setStatus(401) return True def logout(self, request): \"\"\"Always returns False as logout is", "from zope.pluggableauth import interfaces try: unicode except NameError: # Py3: define unicode unicode", "realm is quoted, as per RFC 2617. The plugin only works with HTTP", "DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY,", "Py3: define unicode unicode = str class IHTTPBasicAuthRealm(Interface): \"\"\"HTTP Basic Auth Realm Represents", "WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE.", "headers. To illustrate, we'll create a plugin: >>> plugin = HTTPBasicAuthCredentialsPlugin() The plugin", "############################################################################## # # Copyright (c) 2004 Zope Foundation and Contributors. # All Rights", "= BrowserRequest('/', ... environ={'HTTP_AUTHORIZATION': u'Basic bWdyOm1ncnB3OndpdGg6Y29sb24='}) >>> pprint(plugin.extractCredentials(request)) {'login': u'mgr', 'password': u'<PASSWORD>'} \"\"\"", "return `None`, if no authentication header has been specified. >>> print(plugin.extractCredentials(TestRequest())) None Also,", "= str class IHTTPBasicAuthRealm(Interface): \"\"\"HTTP Basic Auth Realm Represents the realm string that", "(ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE", "= TestRequest('/') >>> response = request.response >>> print(plugin.challenge(request)) False \"\"\" if not IHTTPRequest.providedBy(request):", "request): \"\"\"Issues an HTTP basic auth challenge for credentials. The challenge is issued", "False request.response.setHeader(\"WWW-Authenticate\", 'basic realm=\"%s\"' % self.realm, literal=True) request.response.setStatus(401) return True def logout(self, request):", "unicode unicode = str class IHTTPBasicAuthRealm(Interface): \"\"\"HTTP Basic Auth Realm Represents the realm", "Authentication Realm', required=True, default=u'Zope') @implementer(interfaces.ICredentialsPlugin, IHTTPBasicAuthRealm) class HTTPBasicAuthCredentialsPlugin(object): realm = 'Zope' protocol =", "Realm', required=True, default=u'Zope') @implementer(interfaces.ICredentialsPlugin, IHTTPBasicAuthRealm) class HTTPBasicAuthCredentialsPlugin(object): realm = 'Zope' protocol = 'http", "TestRequest >>> request = TestRequest('/') >>> response = request.response >>> print(plugin.challenge(request)) False \"\"\"", "Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should", "ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT", ">>> from zope.publisher.browser import TestRequest >>> request = TestRequest( ... environ={'HTTP_AUTHORIZATION': u'Basic bWdyOm1ncnB3'})", "AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################## \"\"\"PAS plugins related to", "handle basic authentication. >>> request = TestRequest(environ={'HTTP_AUTHORIZATION': 'foo bar'}) >>> print(plugin.extractCredentials(TestRequest())) None This", "# THIS SOFTWARE IS PROVIDED \"AS IS\" AND ANY AND ALL EXPRESS OR", "Copyright (c) 2004 Zope Foundation and Contributors. # All Rights Reserved. # #", "try: unicode except NameError: # Py3: define unicode unicode = str class IHTTPBasicAuthRealm(Interface):", "auth' def extractCredentials(self, request): \"\"\"Extracts HTTP basic auth credentials from a request. First", "a request that contains some credentials. >>> from zope.publisher.browser import TestRequest >>> request", "basic auth credentials from a request. First we need to create a request", "as BrowserRequest >>> request = BrowserRequest('/', ... environ={'HTTP_AUTHORIZATION': u'Basic bWdyOm1ncnB3OndpdGg6Y29sb24='}) >>> pprint(plugin.extractCredentials(request)) {'login':", "Foundation and Contributors. # All Rights Reserved. # # This software is subject", "response headers. To illustrate, we'll create a plugin: >>> plugin = HTTPBasicAuthCredentialsPlugin() The", "= TestRequest( ... environ={'HTTP_AUTHORIZATION': u'Basic bWdyOm1ncnB3'}) Now create the plugin and get the", "subject to the provisions of the Zope Public License, # Version 2.1 (ZPL).", "pprint >>> pprint(plugin.extractCredentials(request)) {'login': u'mgr', 'password': u'<PASSWORD>'} Make sure we return `None`, if", "import TestRequest as BrowserRequest >>> request = BrowserRequest('/', ... environ={'HTTP_AUTHORIZATION': u'Basic bWdyOm1ncnB3OndpdGg6Y29sb24='}) >>>", "challenge is issued by setting the appropriate response headers. To illustrate, we'll create", "the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL", ">>> from zope.publisher.base import TestRequest >>> print(plugin.extractCredentials(TestRequest('/'))) None According to RFC 2617, password", "return None if request._auth: if request._auth.lower().startswith(u'basic '): credentials = request._auth.split()[-1] if isinstance(credentials, unicode):", "its challenge to the HTTP response. >>> from zope.publisher.browser import TestRequest >>> request", "u'mgr', 'password': u'<PASSWORD>'} Make sure we return `None`, if no authentication header has", "% self.realm, literal=True) request.response.setStatus(401) return True def logout(self, request): \"\"\"Always returns False as", "False as logout is not supported by basic auth. >>> plugin = HTTPBasicAuthCredentialsPlugin()", "A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS", "__docformat__ = \"reStructuredText\" import base64 from zope.interface import implementer, Interface from zope.publisher.interfaces.http import", "zope.publisher.base import TestRequest >>> print(plugin.extractCredentials(TestRequest('/'))) None According to RFC 2617, password can contain", "default=u'Zope') @implementer(interfaces.ICredentialsPlugin, IHTTPBasicAuthRealm) class HTTPBasicAuthCredentialsPlugin(object): realm = 'Zope' protocol = 'http auth' def", "None if request._auth: if request._auth.lower().startswith(u'basic '): credentials = request._auth.split()[-1] if isinstance(credentials, unicode): #", "u'mgr', 'password': u'<PASSWORD>'} \"\"\" if not IHTTPRequest.providedBy(request): return None if request._auth: if request._auth.lower().startswith(u'basic", "request.response.setHeader(\"WWW-Authenticate\", 'basic realm=\"%s\"' % self.realm, literal=True) request.response.setStatus(401) return True def logout(self, request): \"\"\"Always", "ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED \"AS IS\" AND", "and Contributors. # All Rights Reserved. # # This software is subject to", "that is used during basic HTTP authentication \"\"\" realm = TextLine(title=u'Realm', description=u'HTTP Basic", "u'<PASSWORD>'} \"\"\" if not IHTTPRequest.providedBy(request): return None if request._auth: if request._auth.lower().startswith(u'basic '): credentials", "IHTTPRequest from zope.schema import TextLine from zope.pluggableauth import interfaces try: unicode except NameError:", "1) return {'login': login.decode('utf-8'), 'password': password.decode('utf-8')} return None def challenge(self, request): \"\"\"Issues an", ">>> pprint(plugin.extractCredentials(request)) {'login': u'mgr', 'password': u'<PASSWORD>'} Make sure we return `None`, if no", "from a request. First we need to create a request that contains some", "colons; user ID can't contain any colon. >>> from zope.publisher.browser import TestRequest as", "print(plugin.extractCredentials(TestRequest())) None This plugin only works with HTTP requests. >>> from zope.publisher.base import", "request): \"\"\"Always returns False as logout is not supported by basic auth. >>>", "zope.schema import TextLine from zope.pluggableauth import interfaces try: unicode except NameError: # Py3:", "bWdyOm1ncnB3'}) Now create the plugin and get the credentials. >>> plugin = HTTPBasicAuthCredentialsPlugin()", "True >>> response._status 401 >>> response.getHeader('WWW-Authenticate', literal=True) 'basic realm=\"Zope\"' Notice that the realm", ">>> response._status 401 >>> response.getHeader('WWW-Authenticate', literal=True) 'basic realm=\"Zope\"' Notice that the realm is", "def logout(self, request): \"\"\"Always returns False as logout is not supported by basic", "from zope.publisher.base import TestRequest >>> request = TestRequest('/') >>> response = request.response >>>", "the HTTP response. >>> from zope.publisher.browser import TestRequest >>> request = TestRequest() >>>", "used during basic HTTP authentication \"\"\" realm = TextLine(title=u'Realm', description=u'HTTP Basic Authentication Realm',", "to RFC 2617, password can contain one or more colons; user ID can't", "TestRequest() >>> response = request.response >>> plugin.challenge(request) True >>> response._status 401 >>> response.getHeader('WWW-Authenticate',", "returns False as logout is not supported by basic auth. >>> plugin =", "IS PROVIDED \"AS IS\" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES", "we need to create a request that contains some credentials. >>> from zope.publisher.browser", "'): credentials = request._auth.split()[-1] if isinstance(credentials, unicode): # No encoding needed, should be", "as logout is not supported by basic auth. >>> plugin = HTTPBasicAuthCredentialsPlugin() >>>", "BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT,", "'foo bar'}) >>> print(plugin.extractCredentials(TestRequest())) None This plugin only works with HTTP requests. >>>", "HTTP basic auth credentials from a request. First we need to create a", "is used during basic HTTP authentication \"\"\" realm = TextLine(title=u'Realm', description=u'HTTP Basic Authentication", "copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED", "print(plugin.challenge(request)) False \"\"\" if not IHTTPRequest.providedBy(request): return False request.response.setHeader(\"WWW-Authenticate\", 'basic realm=\"%s\"' % self.realm,", "sure we return `None`, if no authentication header has been specified. >>> print(plugin.extractCredentials(TestRequest()))", ">>> pprint(plugin.extractCredentials(request)) {'login': u'mgr', 'password': u'<PASSWORD>'} \"\"\" if not IHTTPRequest.providedBy(request): return None if", ">>> print(plugin.extractCredentials(TestRequest('/'))) None According to RFC 2617, password can contain one or more", "BrowserRequest >>> request = BrowserRequest('/', ... environ={'HTTP_AUTHORIZATION': u'Basic bWdyOm1ncnB3OndpdGg6Y29sb24='}) >>> pprint(plugin.extractCredentials(request)) {'login': u'mgr',", "ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO,", "Zope Foundation and Contributors. # All Rights Reserved. # # This software is", "plugin and get the credentials. >>> plugin = HTTPBasicAuthCredentialsPlugin() >>> from pprint import", "The plugin adds its challenge to the HTTP response. >>> from zope.publisher.browser import", "return False request.response.setHeader(\"WWW-Authenticate\", 'basic realm=\"%s\"' % self.realm, literal=True) request.response.setStatus(401) return True def logout(self,", ">>> request = TestRequest(environ={'HTTP_AUTHORIZATION': 'foo bar'}) >>> print(plugin.extractCredentials(TestRequest())) None This plugin only works", "pprint(plugin.extractCredentials(request)) {'login': u'mgr', 'password': u'<PASSWORD>'} \"\"\" if not IHTTPRequest.providedBy(request): return None if request._auth:", "# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES", "distribution. # THIS SOFTWARE IS PROVIDED \"AS IS\" AND ANY AND ALL EXPRESS", "we'll create a plugin: >>> plugin = HTTPBasicAuthCredentialsPlugin() The plugin adds its challenge", "the plugin and get the credentials. >>> plugin = HTTPBasicAuthCredentialsPlugin() >>> from pprint", "challenge to the HTTP response. >>> from zope.publisher.browser import TestRequest >>> request =", ">>> plugin = HTTPBasicAuthCredentialsPlugin() >>> from zope.publisher.browser import TestRequest >>> plugin.logout(TestRequest()) False \"\"\"", "Reserved. # # This software is subject to the provisions of the Zope", "TestRequest >>> request = TestRequest( ... environ={'HTTP_AUTHORIZATION': u'Basic bWdyOm1ncnB3'}) Now create the plugin", "request = BrowserRequest('/', ... environ={'HTTP_AUTHORIZATION': u'Basic bWdyOm1ncnB3OndpdGg6Y29sb24='}) >>> pprint(plugin.extractCredentials(request)) {'login': u'mgr', 'password': u'<PASSWORD>'}", "encoding needed, should be base64 string anyways. credentials = credentials.encode() login, password =", "environ={'HTTP_AUTHORIZATION': u'Basic bWdyOm1ncnB3OndpdGg6Y29sb24='}) >>> pprint(plugin.extractCredentials(request)) {'login': u'mgr', 'password': u'<PASSWORD>'} \"\"\" if not IHTTPRequest.providedBy(request):", "\"\"\"Always returns False as logout is not supported by basic auth. >>> plugin", "create a plugin: >>> plugin = HTTPBasicAuthCredentialsPlugin() The plugin adds its challenge to", "HTTP basic auth challenge for credentials. The challenge is issued by setting the", "import IHTTPRequest from zope.schema import TextLine from zope.pluggableauth import interfaces try: unicode except", "to create a request that contains some credentials. >>> from zope.publisher.browser import TestRequest", "credentials. The challenge is issued by setting the appropriate response headers. To illustrate,", "TestRequest( ... environ={'HTTP_AUTHORIZATION': u'Basic bWdyOm1ncnB3'}) Now create the plugin and get the credentials.", "According to RFC 2617, password can contain one or more colons; user ID", ">>> plugin = HTTPBasicAuthCredentialsPlugin() The plugin adds its challenge to the HTTP response.", "response = request.response >>> plugin.challenge(request) True >>> response._status 401 >>> response.getHeader('WWW-Authenticate', literal=True) 'basic", "HTTPBasicAuthCredentialsPlugin(object): realm = 'Zope' protocol = 'http auth' def extractCredentials(self, request): \"\"\"Extracts HTTP", "of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED \"AS", "plugin = HTTPBasicAuthCredentialsPlugin() >>> from pprint import pprint >>> pprint(plugin.extractCredentials(request)) {'login': u'mgr', 'password':", "request._auth.split()[-1] if isinstance(credentials, unicode): # No encoding needed, should be base64 string anyways.", "import TestRequest >>> print(plugin.extractCredentials(TestRequest('/'))) None According to RFC 2617, password can contain one", "description=u'HTTP Basic Authentication Realm', required=True, default=u'Zope') @implementer(interfaces.ICredentialsPlugin, IHTTPBasicAuthRealm) class HTTPBasicAuthCredentialsPlugin(object): realm = 'Zope'", "by basic auth. >>> plugin = HTTPBasicAuthCredentialsPlugin() >>> from zope.publisher.browser import TestRequest >>>", "None According to RFC 2617, password can contain one or more colons; user", "= \"reStructuredText\" import base64 from zope.interface import implementer, Interface from zope.publisher.interfaces.http import IHTTPRequest", "True def logout(self, request): \"\"\"Always returns False as logout is not supported by", "as per RFC 2617. The plugin only works with HTTP requests. >>> from", "or more colons; user ID can't contain any colon. >>> from zope.publisher.browser import", "= TestRequest() >>> response = request.response >>> plugin.challenge(request) True >>> response._status 401 >>>", "not IHTTPRequest.providedBy(request): return None if request._auth: if request._auth.lower().startswith(u'basic '): credentials = request._auth.split()[-1] if", "from zope.schema import TextLine from zope.pluggableauth import interfaces try: unicode except NameError: #", "if request._auth: if request._auth.lower().startswith(u'basic '): credentials = request._auth.split()[-1] if isinstance(credentials, unicode): # No", "plugin only works with HTTP requests. >>> from zope.publisher.base import TestRequest >>> print(plugin.extractCredentials(TestRequest('/')))", "return {'login': login.decode('utf-8'), 'password': password.decode('utf-8')} return None def challenge(self, request): \"\"\"Issues an HTTP", "realm = 'Zope' protocol = 'http auth' def extractCredentials(self, request): \"\"\"Extracts HTTP basic" ]
[ "Todo Split this up into smaller methods class GridKaCalibration(CalibrationWorkflow): def __init__(self): self.report =", "= efficiency_reference['value'].mean() from_reports = efficiency_timeseries.rename('measured') # cpu_eff = pd.concat([reference, from_reports], axis=1) fig, axes", "from merge import job_node from merge.merge_datasets import UnionDatasetMerge from merge.reportmatching import JobReportMatcher from", "run(self): self.report.append('# GridKa Calibration Run') time_now = datetime.now().strftime('%Y-%m-%d, %H:%M:%S') self.report.append('at {}'.format(time_now)) logging.info(\"Model Calibration", "# Write report out to disk self.report.write() def draw_jobslot_usage(self, jm_dataset, core_reference): jobslot_timeseries =", "datetime.now().strftime('%Y-%m-%d, %H:%M:%S') self.report.append('at {}'.format(time_now)) logging.info(\"Model Calibration run at {}\".format(time_now)) start_date = pd.to_datetime(config.startDate) end_date", "jobreportanalysis.add_missing_node_info(matched_jobs, nodes) jm_dataset.df = jobreportanalysis.add_performance_data(matched_jobs) job_data = jm_dataset.df # Import additional information for", "analysis import calibrationreport, resource_usage, cpuefficiency, sampling from analysis import jobreportanalysis from analysis import", "job_counts_reference_summary = self.add_jobs_over_time(start_date, end_date) # CPU Efficiencies self.add_cpu_efficiency(job_data, start_date, end_date) # Compute calibration", "from job reports (average {:.2f}%)'.format(reports_average * 100), 'Reference from GridKa monitoring (average {:.2f}%)'.format(reference_mean", "with both information from the job reports and the Pilot jobs scaled_nodes_pilots =", "= UnionDatasetMerge().merge_datasets(matches, jm_dataset, wm_dataset, left_index='UniqueID', right_index='wmaid', left_suffix='jm', right_suffix='wma') jobs_dataset.df = jobreportcleaning.clean_job_reports(jobs_dataset.df) # Import", "from job reports': jobslots_from_reports, 'Allocated to GridKa CMS pilots': core_reference['cms']}) self.report.add_figure(fig, axes, 'jobslot_usage_reference')", "'job_counts_reference', tight_layout=False) job_counts_reference_summary = job_counts.groupby('type')['count'].sum().reset_index() job_counts_reference_summary.columns = ['type', 'count'] job_counts_reference_summary['share'] = job_counts_reference_summary['count'] /", "core_reference): jobslot_timeseries = resource_usage.calculate_jobslot_usage(jm_dataset.df, jm_dataset.start, jm_dataset.end, start_ts_col=Metric.START_TIME.value, end_ts_col=Metric.STOP_TIME.value, slot_col=Metric.USED_CORES.value) jobslots_from_reports = jobslot_timeseries['totalSlots'].resample('s').pad().resample('H').mean() avg_jobslots_reports", "import calibrationreport, resource_usage, cpuefficiency, sampling from analysis import jobreportanalysis from analysis import jobreportcleaning", "run at {}\".format(time_now)) start_date = pd.to_datetime(config.startDate) end_date = pd.to_datetime(config.endDate) day_count = (end_date -", "- start_date).days self.report.append() self.report.append(\"Start date: {} \\nEnd date: {}\".format(start_date, end_date)) # Import data", "at {}!\".format(match_cache_file)) # Match Jobmonitoring and WMArchive job reports matcher = JobReportMatcher(timestamp_tolerance=10, time_grouping_freq='D')", "scaled_nodes_pilots = nodeanalysis.scale_site_by_jobslots(node_types, cms_avg_cores) scaled_nodes_reports = nodeanalysis.scale_site_by_jobslots(node_types, avg_jobslots_reports) type_split_cols = config.workflowOptions['typeSplitCols'] split_types =", "def add_cpu_efficiency(self, job_data, start_date, end_date): efficiency_reference = CPUEfficiencyReferenceImporter(col='cms', output_column='value').import_file( config.inputPaths['CPUEfficiencyReference'], start_date, end_date) efficiency_timeseries,", "of JobMonitoring data dataset_importer = DatasetImporter( JMImporter(timezone_correction='Europe/Berlin', hostname_suffix='.gridka.de', with_files=False)) jm_dataset = dataset_importer.import_dataset(config.inputPaths['jm'], start_date,", "axes, 'job_counts_reference', tight_layout=False) job_counts_reference_summary = job_counts.groupby('type')['count'].sum().reset_index() job_counts_reference_summary.columns = ['type', 'count'] job_counts_reference_summary['share'] = job_counts_reference_summary['count']", "import logging import os from datetime import datetime import pandas as pd from", "job_counts_reference_summary def add_cpu_efficiency(self, job_data, start_date, end_date): efficiency_reference = CPUEfficiencyReferenceImporter(col='cms', output_column='value').import_file( config.inputPaths['CPUEfficiencyReference'], start_date, end_date)", "half of the reports, fix random state for reproducibility reports_train, reports_test = sampling.split_samples(job_data,", "start_date).days self.report.append() self.report.append(\"Start date: {} \\nEnd date: {}\".format(start_date, end_date)) # Import data sets", "from analyzed jobs jobs_from_reports = job_data.copy() jobs_from_reports[Metric.JOB_TYPE.value] = jobs_from_reports[Metric.JOB_TYPE.value].fillna('unknown') job_counts_reports = jobs_from_reports.groupby(Metric.JOB_TYPE.value).size().reset_index() job_counts_reports.columns", "# Export walltimes walltime_path = os.path.join(config.outputDirectory, 'parameters_slots_from_pilots', config.outputPaths['walltimeReference']) ReferenceWalltimeExporter().export_to_json_file(partitions, walltime_path) # Write jobs", "to report calibrationreport.add_jobs_report_section(jm_dataset, self.report) # Write report out to disk self.report.write() def draw_jobslot_usage(self,", "job_groups = job_classifier.split(job_data) job_demand_extractor = JobDemandExtractor(self.report, equal_width=False, bin_count=60, cutoff_quantile=0.95, overflow_agg=config.workflowOptions['overflowAggregationMethod'], additional_job_options=config.workflowOptions['additionalJobOptions'], drop_overflow=config.workflowOptions.get('dropOverflow', False))", "environment with both information from the job reports and the Pilot jobs scaled_nodes_pilots", "job_data = jm_dataset.df # Import additional information for usage of GridKa site core_importer", "FilteredJobClassifier, JobDemandExtractor from data.dataset import Metric from exporters.datasetexport import ReferenceWalltimeExporter from importers.dataset_import import", "start_date = pd.to_datetime(config.startDate) end_date = pd.to_datetime(config.endDate) day_count = (end_date - start_date).days self.report.append() self.report.append(\"Start", "= sampling_report sample_demands, sample_partitions = job_demand_extractor.extract_job_demands(job_groups_train) sampling_report.write() export_parameters('parameters_slots_from_pilots_sampled0.5', scaled_nodes_pilots, sample_demands) export_parameters('parameters_slots_from_reports_sampled0.5', scaled_nodes_reports, sample_demands)", "CPU Efficiencies self.add_cpu_efficiency(job_data, start_date, end_date) # Compute calibration parameters node_types = nodeanalysis.extract_node_types(nodes) #", "job reports (average {:.2f}%)'.format(reports_average * 100), 'Reference from GridKa monitoring (average {:.2f}%)'.format(reference_mean *", "walltime_path = os.path.join(config.outputDirectory, 'parameters_slots_from_pilots', config.outputPaths['walltimeReference']) ReferenceWalltimeExporter().export_to_json_file(partitions, walltime_path) # Write jobs to report calibrationreport.add_jobs_report_section(jm_dataset,", "matcher.match_reports(jm_dataset, wm_dataset, use_files=False, previous_matches=cached_matches) if use_caching: match_cache_file = os.path.join(config.cacheDir, 'jm-wma-matches.csv') logging.info(\"Writing {} matches", "JMImporter(timezone_correction='Europe/Berlin', hostname_suffix='.gridka.de', with_files=False)) jm_dataset = dataset_importer.import_dataset(config.inputPaths['jm'], start_date, end_date) wm_dataset = DatasetImporter(SummarizedWMAImporter(with_files=False)) \\ .import_dataset(config.inputPaths['wma'],", "* 100), 'Reference from GridKa monitoring (average {:.2f}%)'.format(reference_mean * 100)]) axes.set_title(\"CPU efficiencies ({},", "if use_caching: match_cache_file = os.path.join(config.cacheDir, 'jm-wma-matches.csv') if os.path.isfile(match_cache_file): try: cached_matches = pd.read_csv(match_cache_file, usecols=[jm_dataset.df.index.name,", "Match Jobmonitoring and WMArchive job reports matcher = JobReportMatcher(timestamp_tolerance=10, time_grouping_freq='D') matches = matcher.match_reports(jm_dataset,", "utils import config, visualization from utils import report as rp from utils.report import", "import datetime import pandas as pd from analysis import calibrationreport, resource_usage, cpuefficiency, sampling", "reproducibility reports_train, reports_test = sampling.split_samples(job_data, frac=0.5, random_state=38728) sampling_report = ReportBuilder(base_path=config.outputDirectory, filename='calibration-report-sampled.md', resource_dir='figures-sampling') job_groups_train", "found at {}!\".format(match_cache_file)) # Match Jobmonitoring and WMArchive job reports matcher = JobReportMatcher(timestamp_tolerance=10,", "use_caching = config.cacheDir is not None if use_caching: match_cache_file = os.path.join(config.cacheDir, 'jm-wma-matches.csv') if", "parameters node_types = nodeanalysis.extract_node_types(nodes) # Scale the resource environment with both information from", "sampling_report = ReportBuilder(base_path=config.outputDirectory, filename='calibration-report-sampled.md', resource_dir='figures-sampling') job_groups_train = job_classifier.split(reports_train) job_demand_extractor.report = sampling_report sample_demands, sample_partitions", "time)\") axes.legend(['Extracted from job reports (average {:.2f}%)'.format(reports_average * 100), 'Reference from GridKa monitoring", "(average {:.2f}%)'.format(reports_average * 100), 'Reference from GridKa monitoring (average {:.2f}%)'.format(reference_mean * 100)]) axes.set_title(\"CPU", "GridKaNodeDataImporter, ColumnCoreUsageImporter, \\ CPUEfficiencyReferenceImporter from importers.jmimport import JMImporter from importers.jobcounts import JobCountImporter from", "{}'.format(time_now)) logging.info(\"Model Calibration run at {}\".format(time_now)) start_date = pd.to_datetime(config.startDate) end_date = pd.to_datetime(config.endDate) day_count", "end_date) cms_avg_cores = core_df['cms'].mean() avg_jobslots_reports = self.draw_jobslot_usage(jm_dataset, core_df) # Visualize number of jobs", "for usage of GridKa site core_importer = ColumnCoreUsageImporter() core_df = core_importer.import_file(config.inputPaths['coreUsage'], start_date, end_date)", "if os.path.isfile(match_cache_file): try: cached_matches = pd.read_csv(match_cache_file, usecols=[jm_dataset.df.index.name, wm_dataset.df.index.name]) logging.info( \"Loaded {} matches from", "= pd.to_datetime(config.endDate) day_count = (end_date - start_date).days self.report.append() self.report.append(\"Start date: {} \\nEnd date:", "visualization.draw_efficiency_timeseries( {'extracted from job reports': from_reports, 'reference from GridKa monitoring': reference}) axes.set_ylabel(\"CPU efficiency", "= job_data.copy() jobs_from_reports[Metric.JOB_TYPE.value] = jobs_from_reports[Metric.JOB_TYPE.value].fillna('unknown') job_counts_reports = jobs_from_reports.groupby(Metric.JOB_TYPE.value).size().reset_index() job_counts_reports.columns = ['type', 'count'] job_counts_reports['throughput_day']", "start_date, end_date): self.report.append(\"## Number of jobs completed over time\") job_counts = JobCountImporter().import_file(config.inputPaths['jobCountsReference'], start_date,", "datetime import datetime import pandas as pd from analysis import calibrationreport, resource_usage, cpuefficiency,", "jobs in calibration report job_counts_reference_summary = self.add_jobs_over_time(start_date, end_date) # CPU Efficiencies self.add_cpu_efficiency(job_data, start_date,", "= jobslot_timeseries['totalSlots'].resample('s').pad().resample('H').mean() avg_jobslots_reports = jobslots_from_reports.mean() fig, axes = calibrationreport.multiple_jobslot_usage( {'Extracted from job reports':", "import UnionDatasetMerge from merge.reportmatching import JobReportMatcher from utils import config, visualization from utils", "{}!\".format(cached_matches.shape[0], match_cache_file)) except Exception: logging.warning(\"No match cache found at {}!\".format(match_cache_file)) # Match Jobmonitoring", "job_data, start_date, end_date): efficiency_reference = CPUEfficiencyReferenceImporter(col='cms', output_column='value').import_file( config.inputPaths['CPUEfficiencyReference'], start_date, end_date) efficiency_timeseries, reports_average =", "= core_df['cms'].mean() avg_jobslots_reports = self.draw_jobslot_usage(jm_dataset, core_df) # Visualize number of jobs in calibration", "def draw_jobslot_usage(self, jm_dataset, core_reference): jobslot_timeseries = resource_usage.calculate_jobslot_usage(jm_dataset.df, jm_dataset.start, jm_dataset.end, start_ts_col=Metric.START_TIME.value, end_ts_col=Metric.STOP_TIME.value, slot_col=Metric.USED_CORES.value) jobslots_from_reports", "'parameters_slots_from_pilots', config.outputPaths['jobCountReports']) # Export walltimes walltime_path = os.path.join(config.outputDirectory, 'parameters_slots_from_pilots', config.outputPaths['walltimeReference']) ReferenceWalltimeExporter().export_to_json_file(partitions, walltime_path) #", "= resource_usage.calculate_jobslot_usage(jm_dataset.df, jm_dataset.start, jm_dataset.end, start_ts_col=Metric.START_TIME.value, end_ts_col=Metric.STOP_TIME.value, slot_col=Metric.USED_CORES.value) jobslots_from_reports = jobslot_timeseries['totalSlots'].resample('s').pad().resample('H').mean() avg_jobslots_reports = jobslots_from_reports.mean()", "job_groups_train = job_classifier.split(reports_train) job_demand_extractor.report = sampling_report sample_demands, sample_partitions = job_demand_extractor.extract_job_demands(job_groups_train) sampling_report.write() export_parameters('parameters_slots_from_pilots_sampled0.5', scaled_nodes_pilots,", "number of jobs in calibration report job_counts_reference_summary = self.add_jobs_over_time(start_date, end_date) # CPU Efficiencies", "GridKaNodeDataImporter().import_file(config.inputPaths['nodeInfo']) nodes = nodeanalysis.add_performance_data(nodes, simulated_cores=config.workflowOptions['coreSimulationMethod'], thread_rate_method=config.workflowOptions['threadPerformanceMethod']) # Match jobs to nodes matched_jobs =", "GridKa monitoring (average {:.2f}%)'.format(reference_mean * 100)]) axes.set_title(\"CPU efficiencies ({}, {} days)\".format(config.runName, (end_date -", "as pd from analysis import calibrationreport, resource_usage, cpuefficiency, sampling from analysis import jobreportanalysis", "start_date).days) self.report.append(\"Job throughput from CMS Dashboard:\") self.report.append() self.report.append_paragraph(rp.CodeBlock().append(job_counts_reference_summary.to_string())) return job_counts_reference_summary def add_cpu_efficiency(self, job_data,", "days)\".format(config.runName, (end_date - start_date).days)) axes.set_xlim(left=start_date, right=(end_date - pd.Timedelta('1 days'))) fig.set_size_inches(8, 4.5) self.report.add_figure(fig, axes,", "pd.concat([reference, from_reports], axis=1) fig, axes = visualization.draw_efficiency_timeseries( {'extracted from job reports': from_reports, 'reference", "jobs scaled_nodes_pilots = nodeanalysis.scale_site_by_jobslots(node_types, cms_avg_cores) scaled_nodes_reports = nodeanalysis.scale_site_by_jobslots(node_types, avg_jobslots_reports) type_split_cols = config.workflowOptions['typeSplitCols'] split_types", "DatasetImporter(SummarizedWMAImporter(with_files=False)) \\ .import_dataset(config.inputPaths['wma'], start_date, end_date) cached_matches = None use_caching = config.cacheDir is not", "interfaces.workflow import CalibrationWorkflow from merge import job_node from merge.merge_datasets import UnionDatasetMerge from merge.reportmatching", "resource_dir='figures-sampling') job_groups_train = job_classifier.split(reports_train) job_demand_extractor.report = sampling_report sample_demands, sample_partitions = job_demand_extractor.extract_job_demands(job_groups_train) sampling_report.write() export_parameters('parameters_slots_from_pilots_sampled0.5',", "end_ts_col=Metric.STOP_TIME.value, slot_col=Metric.USED_CORES.value) jobslots_from_reports = jobslot_timeseries['totalSlots'].resample('s').pad().resample('H').mean() avg_jobslots_reports = jobslots_from_reports.mean() fig, axes = calibrationreport.multiple_jobslot_usage( {'Extracted", "job_counts_reports.columns = ['type', 'count'] job_counts_reports['throughput_day'] = job_counts_reports['count'].divide(day_count) export_job_counts(job_counts_reports, 'parameters_slots_from_pilots', config.outputPaths['jobCountReports']) # Export walltimes", "from exporters.datasetexport import ReferenceWalltimeExporter from importers.dataset_import import DatasetImporter from importers.gridkadata import GridKaNodeDataImporter, ColumnCoreUsageImporter,", "\"Loaded {} matches from match cache {}!\".format(cached_matches.shape[0], match_cache_file)) except Exception: logging.warning(\"No match cache", "resource environment with both information from the job reports and the Pilot jobs", "= ['type', 'count'] job_counts_reports['throughput_day'] = job_counts_reports['count'].divide(day_count) export_job_counts(job_counts_reports, 'parameters_slots_from_pilots', config.outputPaths['jobCountReports']) # Export walltimes walltime_path", "node_types = nodeanalysis.extract_node_types(nodes) # Scale the resource environment with both information from the", "self.report.append(\"Job throughput from CMS Dashboard:\") self.report.append() self.report.append_paragraph(rp.CodeBlock().append(job_counts_reference_summary.to_string())) return job_counts_reference_summary def add_cpu_efficiency(self, job_data, start_date,", "import jobreportcleaning from analysis import nodeanalysis from analysis.demandextraction import FilteredJobClassifier, JobDemandExtractor from data.dataset", "self.report.append_paragraph(rp.CodeBlock().append(job_counts_reference_summary.to_string())) return job_counts_reference_summary def add_cpu_efficiency(self, job_data, start_date, end_date): efficiency_reference = CPUEfficiencyReferenceImporter(col='cms', output_column='value').import_file( config.inputPaths['CPUEfficiencyReference'],", "GridKa Calibration Run') time_now = datetime.now().strftime('%Y-%m-%d, %H:%M:%S') self.report.append('at {}'.format(time_now)) logging.info(\"Model Calibration run at", "self.report = ReportBuilder(base_path=config.outputDirectory, filename='calibration-report.md') def run(self): self.report.append('# GridKa Calibration Run') time_now = datetime.now().strftime('%Y-%m-%d,", "################## # Timezone correction correct for errors in timestamps of JobMonitoring data dataset_importer", "nodes) jm_dataset.df = jobreportanalysis.add_performance_data(matched_jobs) job_data = jm_dataset.df # Import additional information for usage", "completed over time\") job_counts = JobCountImporter().import_file(config.inputPaths['jobCountsReference'], start_date, end_date) fig, axes = calibrationreport.jobtypes_over_time_df(job_counts, 'date',", "reports_test = sampling.split_samples(job_data, frac=0.5, random_state=38728) sampling_report = ReportBuilder(base_path=config.outputDirectory, filename='calibration-report-sampled.md', resource_dir='figures-sampling') job_groups_train = job_classifier.split(reports_train)", "matches from match cache {}!\".format(cached_matches.shape[0], match_cache_file)) except Exception: logging.warning(\"No match cache found at", "{:.2f}%)'.format(reference_mean * 100)]) axes.set_title(\"CPU efficiencies ({}, {} days)\".format(config.runName, (end_date - start_date).days)) axes.set_xlim(left=start_date, right=(end_date", "throughput from CMS Dashboard:\") self.report.append() self.report.append_paragraph(rp.CodeBlock().append(job_counts_reference_summary.to_string())) return job_counts_reference_summary def add_cpu_efficiency(self, job_data, start_date, end_date):", "the resource environment with both information from the job reports and the Pilot", "reports': from_reports, 'reference from GridKa monitoring': reference}) axes.set_ylabel(\"CPU efficiency (CPU time / wall", "the job reports and the Pilot jobs scaled_nodes_pilots = nodeanalysis.scale_site_by_jobslots(node_types, cms_avg_cores) scaled_nodes_reports =", "= jobslots_from_reports.mean() fig, axes = calibrationreport.multiple_jobslot_usage( {'Extracted from job reports': jobslots_from_reports, 'Allocated to", "= jobs_from_reports[Metric.JOB_TYPE.value].fillna('unknown') job_counts_reports = jobs_from_reports.groupby(Metric.JOB_TYPE.value).size().reset_index() job_counts_reports.columns = ['type', 'count'] job_counts_reports['throughput_day'] = job_counts_reports['count'].divide(day_count) export_job_counts(job_counts_reports,", "# CPU Efficiencies self.add_cpu_efficiency(job_data, start_date, end_date) # Compute calibration parameters node_types = nodeanalysis.extract_node_types(nodes)", "= jobs_from_reports.groupby(Metric.JOB_TYPE.value).size().reset_index() job_counts_reports.columns = ['type', 'count'] job_counts_reports['throughput_day'] = job_counts_reports['count'].divide(day_count) export_job_counts(job_counts_reports, 'parameters_slots_from_pilots', config.outputPaths['jobCountReports']) #", "= nodeanalysis.extract_node_types(nodes) # Scale the resource environment with both information from the job", "axes.legend(['Extracted from job reports (average {:.2f}%)'.format(reports_average * 100), 'Reference from GridKa monitoring (average", "= matcher.match_reports(jm_dataset, wm_dataset, use_files=False, previous_matches=cached_matches) if use_caching: match_cache_file = os.path.join(config.cacheDir, 'jm-wma-matches.csv') logging.info(\"Writing {}", "FilteredJobClassifier(type_split_cols, split_types=split_types) job_groups = job_classifier.split(job_data) job_demand_extractor = JobDemandExtractor(self.report, equal_width=False, bin_count=60, cutoff_quantile=0.95, overflow_agg=config.workflowOptions['overflowAggregationMethod'], additional_job_options=config.workflowOptions['additionalJobOptions'],", "cached_matches = None use_caching = config.cacheDir is not None if use_caching: match_cache_file =", "{} days)\".format(config.runName, (end_date - start_date).days)) axes.set_xlim(left=start_date, right=(end_date - pd.Timedelta('1 days'))) fig.set_size_inches(8, 4.5) self.report.add_figure(fig,", "to GridKa CMS pilots': core_reference['cms']}) self.report.add_figure(fig, axes, 'jobslot_usage_reference') return avg_jobslots_reports def add_jobs_over_time(self, start_date,", "time / wall time)\") axes.legend(['Extracted from job reports (average {:.2f}%)'.format(reports_average * 100), 'Reference", "filename='calibration-report.md') def run(self): self.report.append('# GridKa Calibration Run') time_now = datetime.now().strftime('%Y-%m-%d, %H:%M:%S') self.report.append('at {}'.format(time_now))", "to nodes matched_jobs = job_node.match_jobs_to_node(jobs_dataset.df, nodes) matched_jobs = jobreportanalysis.add_missing_node_info(matched_jobs, nodes) jm_dataset.df = jobreportanalysis.add_performance_data(matched_jobs)", "sets ################## # Timezone correction correct for errors in timestamps of JobMonitoring data", "matcher = JobReportMatcher(timestamp_tolerance=10, time_grouping_freq='D') matches = matcher.match_reports(jm_dataset, wm_dataset, use_files=False, previous_matches=cached_matches) if use_caching: match_cache_file", "Visualize number of jobs in calibration report job_counts_reference_summary = self.add_jobs_over_time(start_date, end_date) # CPU", "end_date) wm_dataset = DatasetImporter(SummarizedWMAImporter(with_files=False)) \\ .import_dataset(config.inputPaths['wma'], start_date, end_date) cached_matches = None use_caching =", "def __init__(self): self.report = ReportBuilder(base_path=config.outputDirectory, filename='calibration-report.md') def run(self): self.report.append('# GridKa Calibration Run') time_now", "end_date) efficiency_timeseries, reports_average = cpuefficiency.calculate_efficiencies(job_data, freq='12h') reference = efficiency_reference['value'].resample('12h').mean().rename('reference') reference_mean = efficiency_reference['value'].mean() from_reports", "Scale the resource environment with both information from the job reports and the", "jobslots_from_reports, 'Allocated to GridKa CMS pilots': core_reference['cms']}) self.report.add_figure(fig, axes, 'jobslot_usage_reference') return avg_jobslots_reports def", "type_split_cols = config.workflowOptions['typeSplitCols'] split_types = None if 'splitTypes' in config.workflowOptions: split_types = list(map(tuple,", "axes.set_title(\"CPU efficiencies ({}, {} days)\".format(config.runName, (end_date - start_date).days)) axes.set_xlim(left=start_date, right=(end_date - pd.Timedelta('1 days')))", "pd.to_datetime(config.endDate) day_count = (end_date - start_date).days self.report.append() self.report.append(\"Start date: {} \\nEnd date: {}\".format(start_date,", "report as rp from utils.report import ReportBuilder from workflows.workflowutils import export_job_counts, export_parameters #", "correction correct for errors in timestamps of JobMonitoring data dataset_importer = DatasetImporter( JMImporter(timezone_correction='Europe/Berlin',", "scaled_nodes_pilots, sample_demands) export_parameters('parameters_slots_from_reports_sampled0.5', scaled_nodes_reports, sample_demands) # Export job throughputs from analyzed jobs jobs_from_reports", "JobMonitoring data dataset_importer = DatasetImporter( JMImporter(timezone_correction='Europe/Berlin', hostname_suffix='.gridka.de', with_files=False)) jm_dataset = dataset_importer.import_dataset(config.inputPaths['jm'], start_date, end_date)", "axes.set_ylabel(\"CPU efficiency (CPU time / wall time)\") axes.legend(['Extracted from job reports (average {:.2f}%)'.format(reports_average", "= jobreportcleaning.clean_job_reports(jobs_dataset.df) # Import node information nodes = GridKaNodeDataImporter().import_file(config.inputPaths['nodeInfo']) nodes = nodeanalysis.add_performance_data(nodes, simulated_cores=config.workflowOptions['coreSimulationMethod'],", "Compute calibration parameters node_types = nodeanalysis.extract_node_types(nodes) # Scale the resource environment with both", "sampling from analysis import jobreportanalysis from analysis import jobreportcleaning from analysis import nodeanalysis", "= JobCountImporter().import_file(config.inputPaths['jobCountsReference'], start_date, end_date) fig, axes = calibrationreport.jobtypes_over_time_df(job_counts, 'date', 'type') self.report.add_figure(fig, axes, 'job_counts_reference',", "errors in timestamps of JobMonitoring data dataset_importer = DatasetImporter( JMImporter(timezone_correction='Europe/Berlin', hostname_suffix='.gridka.de', with_files=False)) jm_dataset", "= job_classifier.split(job_data) job_demand_extractor = JobDemandExtractor(self.report, equal_width=False, bin_count=60, cutoff_quantile=0.95, overflow_agg=config.workflowOptions['overflowAggregationMethod'], additional_job_options=config.workflowOptions['additionalJobOptions'], drop_overflow=config.workflowOptions.get('dropOverflow', False)) demands,", "(end_date - start_date).days self.report.append() self.report.append(\"Start date: {} \\nEnd date: {}\".format(start_date, end_date)) # Import", "fix random state for reproducibility reports_train, reports_test = sampling.split_samples(job_data, frac=0.5, random_state=38728) sampling_report =", "nodeanalysis.extract_node_types(nodes) # Scale the resource environment with both information from the job reports", "'count'].sum() job_counts_reference_summary['throughput_day'] = job_counts_reference_summary['count'].divide( (end_date - start_date).days) self.report.append(\"Job throughput from CMS Dashboard:\") self.report.append()", "self.report.append('# GridKa Calibration Run') time_now = datetime.now().strftime('%Y-%m-%d, %H:%M:%S') self.report.append('at {}'.format(time_now)) logging.info(\"Model Calibration run", "start_date, end_date) efficiency_timeseries, reports_average = cpuefficiency.calculate_efficiencies(job_data, freq='12h') reference = efficiency_reference['value'].resample('12h').mean().rename('reference') reference_mean = efficiency_reference['value'].mean()", "jobs jobs_from_reports = job_data.copy() jobs_from_reports[Metric.JOB_TYPE.value] = jobs_from_reports[Metric.JOB_TYPE.value].fillna('unknown') job_counts_reports = jobs_from_reports.groupby(Metric.JOB_TYPE.value).size().reset_index() job_counts_reports.columns = ['type',", "%H:%M:%S') self.report.append('at {}'.format(time_now)) logging.info(\"Model Calibration run at {}\".format(time_now)) start_date = pd.to_datetime(config.startDate) end_date =", "WMArchive job reports matcher = JobReportMatcher(timestamp_tolerance=10, time_grouping_freq='D') matches = matcher.match_reports(jm_dataset, wm_dataset, use_files=False, previous_matches=cached_matches)", "= list(map(tuple, config.workflowOptions['splitTypes'])) job_classifier = FilteredJobClassifier(type_split_cols, split_types=split_types) job_groups = job_classifier.split(job_data) job_demand_extractor = JobDemandExtractor(self.report,", "= DatasetImporter( JMImporter(timezone_correction='Europe/Berlin', hostname_suffix='.gridka.de', with_files=False)) jm_dataset = dataset_importer.import_dataset(config.inputPaths['jm'], start_date, end_date) wm_dataset = DatasetImporter(SummarizedWMAImporter(with_files=False))", "reference}) axes.set_ylabel(\"CPU efficiency (CPU time / wall time)\") axes.legend(['Extracted from job reports (average", "os.path.join(config.cacheDir, 'jm-wma-matches.csv') logging.info(\"Writing {} matches to file {}\".format(matches.shape[0], match_cache_file)) matches.to_csv(match_cache_file) jobs_dataset = UnionDatasetMerge().merge_datasets(matches,", "ReferenceWalltimeExporter from importers.dataset_import import DatasetImporter from importers.gridkadata import GridKaNodeDataImporter, ColumnCoreUsageImporter, \\ CPUEfficiencyReferenceImporter from", "merge.merge_datasets import UnionDatasetMerge from merge.reportmatching import JobReportMatcher from utils import config, visualization from", "node information nodes = GridKaNodeDataImporter().import_file(config.inputPaths['nodeInfo']) nodes = nodeanalysis.add_performance_data(nodes, simulated_cores=config.workflowOptions['coreSimulationMethod'], thread_rate_method=config.workflowOptions['threadPerformanceMethod']) # Match jobs", "logging.warning(\"No match cache found at {}!\".format(match_cache_file)) # Match Jobmonitoring and WMArchive job reports", "core_importer.import_file(config.inputPaths['coreUsage'], start_date, end_date) cms_avg_cores = core_df['cms'].mean() avg_jobslots_reports = self.draw_jobslot_usage(jm_dataset, core_df) # Visualize number", "tight_layout=False) job_counts_reference_summary = job_counts.groupby('type')['count'].sum().reset_index() job_counts_reference_summary.columns = ['type', 'count'] job_counts_reference_summary['share'] = job_counts_reference_summary['count'] / job_counts_reference_summary[", "Efficiencies self.add_cpu_efficiency(job_data, start_date, end_date) # Compute calibration parameters node_types = nodeanalysis.extract_node_types(nodes) # Scale", "from utils import report as rp from utils.report import ReportBuilder from workflows.workflowutils import", "monitoring (average {:.2f}%)'.format(reference_mean * 100)]) axes.set_title(\"CPU efficiencies ({}, {} days)\".format(config.runName, (end_date - start_date).days))", "from_reports = efficiency_timeseries.rename('measured') # cpu_eff = pd.concat([reference, from_reports], axis=1) fig, axes = visualization.draw_efficiency_timeseries(", "from analysis import jobreportanalysis from analysis import jobreportcleaning from analysis import nodeanalysis from", "= DatasetImporter(SummarizedWMAImporter(with_files=False)) \\ .import_dataset(config.inputPaths['wma'], start_date, end_date) cached_matches = None use_caching = config.cacheDir is", "analysis.demandextraction import FilteredJobClassifier, JobDemandExtractor from data.dataset import Metric from exporters.datasetexport import ReferenceWalltimeExporter from", "efficiency (CPU time / wall time)\") axes.legend(['Extracted from job reports (average {:.2f}%)'.format(reports_average *", "ReportBuilder from workflows.workflowutils import export_job_counts, export_parameters # Todo Split this up into smaller", "['type', 'count'] job_counts_reference_summary['share'] = job_counts_reference_summary['count'] / job_counts_reference_summary[ 'count'].sum() job_counts_reference_summary['throughput_day'] = job_counts_reference_summary['count'].divide( (end_date -", "import GridKaNodeDataImporter, ColumnCoreUsageImporter, \\ CPUEfficiencyReferenceImporter from importers.jmimport import JMImporter from importers.jobcounts import JobCountImporter", "= calibrationreport.jobtypes_over_time_df(job_counts, 'date', 'type') self.report.add_figure(fig, axes, 'job_counts_reference', tight_layout=False) job_counts_reference_summary = job_counts.groupby('type')['count'].sum().reset_index() job_counts_reference_summary.columns =", "= job_counts_reference_summary['count'] / job_counts_reference_summary[ 'count'].sum() job_counts_reference_summary['throughput_day'] = job_counts_reference_summary['count'].divide( (end_date - start_date).days) self.report.append(\"Job throughput", "Dashboard:\") self.report.append() self.report.append_paragraph(rp.CodeBlock().append(job_counts_reference_summary.to_string())) return job_counts_reference_summary def add_cpu_efficiency(self, job_data, start_date, end_date): efficiency_reference = CPUEfficiencyReferenceImporter(col='cms',", "{:.2f}%)'.format(reports_average * 100), 'Reference from GridKa monitoring (average {:.2f}%)'.format(reference_mean * 100)]) axes.set_title(\"CPU efficiencies", "import jobreportanalysis from analysis import jobreportcleaning from analysis import nodeanalysis from analysis.demandextraction import", "export_parameters('parameters_slots_from_reports_sampled0.5', scaled_nodes_reports, sample_demands) # Export job throughputs from analyzed jobs jobs_from_reports = job_data.copy()", "ColumnCoreUsageImporter() core_df = core_importer.import_file(config.inputPaths['coreUsage'], start_date, end_date) cms_avg_cores = core_df['cms'].mean() avg_jobslots_reports = self.draw_jobslot_usage(jm_dataset, core_df)", "self.report) # Write report out to disk self.report.write() def draw_jobslot_usage(self, jm_dataset, core_reference): jobslot_timeseries", "analysis import nodeanalysis from analysis.demandextraction import FilteredJobClassifier, JobDemandExtractor from data.dataset import Metric from", "jm_dataset.df = jobreportanalysis.add_performance_data(matched_jobs) job_data = jm_dataset.df # Import additional information for usage of", "both information from the job reports and the Pilot jobs scaled_nodes_pilots = nodeanalysis.scale_site_by_jobslots(node_types,", "from match cache {}!\".format(cached_matches.shape[0], match_cache_file)) except Exception: logging.warning(\"No match cache found at {}!\".format(match_cache_file))", "calibration report job_counts_reference_summary = self.add_jobs_over_time(start_date, end_date) # CPU Efficiencies self.add_cpu_efficiency(job_data, start_date, end_date) #", "GridKa monitoring': reference}) axes.set_ylabel(\"CPU efficiency (CPU time / wall time)\") axes.legend(['Extracted from job", "= self.draw_jobslot_usage(jm_dataset, core_df) # Visualize number of jobs in calibration report job_counts_reference_summary =", "# Write jobs to report calibrationreport.add_jobs_report_section(jm_dataset, self.report) # Write report out to disk", "right=(end_date - pd.Timedelta('1 days'))) fig.set_size_inches(8, 4.5) self.report.add_figure(fig, axes, 'cpu_efficiencies_reference') self.report.append(\"Efficiency from job reports:", "fig.set_size_inches(8, 4.5) self.report.add_figure(fig, axes, 'cpu_efficiencies_reference') self.report.append(\"Efficiency from job reports: {} \".format(reports_average)) self.report.append(\"Efficiency from", "job_counts = JobCountImporter().import_file(config.inputPaths['jobCountsReference'], start_date, end_date) fig, axes = calibrationreport.jobtypes_over_time_df(job_counts, 'date', 'type') self.report.add_figure(fig, axes,", "jobs_from_reports[Metric.JOB_TYPE.value] = jobs_from_reports[Metric.JOB_TYPE.value].fillna('unknown') job_counts_reports = jobs_from_reports.groupby(Metric.JOB_TYPE.value).size().reset_index() job_counts_reports.columns = ['type', 'count'] job_counts_reports['throughput_day'] = job_counts_reports['count'].divide(day_count)", "Import node information nodes = GridKaNodeDataImporter().import_file(config.inputPaths['nodeInfo']) nodes = nodeanalysis.add_performance_data(nodes, simulated_cores=config.workflowOptions['coreSimulationMethod'], thread_rate_method=config.workflowOptions['threadPerformanceMethod']) # Match", "None if use_caching: match_cache_file = os.path.join(config.cacheDir, 'jm-wma-matches.csv') if os.path.isfile(match_cache_file): try: cached_matches = pd.read_csv(match_cache_file,", "pd.to_datetime(config.startDate) end_date = pd.to_datetime(config.endDate) day_count = (end_date - start_date).days self.report.append() self.report.append(\"Start date: {}", "from merge.reportmatching import JobReportMatcher from utils import config, visualization from utils import report", "axes.set_xlim(left=start_date, right=(end_date - pd.Timedelta('1 days'))) fig.set_size_inches(8, 4.5) self.report.add_figure(fig, axes, 'cpu_efficiencies_reference') self.report.append(\"Efficiency from job", "self.report.append(\"## Number of jobs completed over time\") job_counts = JobCountImporter().import_file(config.inputPaths['jobCountsReference'], start_date, end_date) fig,", "over time\") job_counts = JobCountImporter().import_file(config.inputPaths['jobCountsReference'], start_date, end_date) fig, axes = calibrationreport.jobtypes_over_time_df(job_counts, 'date', 'type')", "= job_demand_extractor.extract_job_demands(job_groups) export_parameters('parameters_slots_from_pilots', scaled_nodes_pilots, demands) export_parameters('parameters_slots_from_reports', scaled_nodes_reports, demands) # Sample half of the", "import SummarizedWMAImporter from interfaces.workflow import CalibrationWorkflow from merge import job_node from merge.merge_datasets import", "demands, partitions = job_demand_extractor.extract_job_demands(job_groups) export_parameters('parameters_slots_from_pilots', scaled_nodes_pilots, demands) export_parameters('parameters_slots_from_reports', scaled_nodes_reports, demands) # Sample half", "= JobReportMatcher(timestamp_tolerance=10, time_grouping_freq='D') matches = matcher.match_reports(jm_dataset, wm_dataset, use_files=False, previous_matches=cached_matches) if use_caching: match_cache_file =", "jobs completed over time\") job_counts = JobCountImporter().import_file(config.inputPaths['jobCountsReference'], start_date, end_date) fig, axes = calibrationreport.jobtypes_over_time_df(job_counts,", "except Exception: logging.warning(\"No match cache found at {}!\".format(match_cache_file)) # Match Jobmonitoring and WMArchive", "False)) demands, partitions = job_demand_extractor.extract_job_demands(job_groups) export_parameters('parameters_slots_from_pilots', scaled_nodes_pilots, demands) export_parameters('parameters_slots_from_reports', scaled_nodes_reports, demands) # Sample", "avg_jobslots_reports) type_split_cols = config.workflowOptions['typeSplitCols'] split_types = None if 'splitTypes' in config.workflowOptions: split_types =", "up into smaller methods class GridKaCalibration(CalibrationWorkflow): def __init__(self): self.report = ReportBuilder(base_path=config.outputDirectory, filename='calibration-report.md') def", "out to disk self.report.write() def draw_jobslot_usage(self, jm_dataset, core_reference): jobslot_timeseries = resource_usage.calculate_jobslot_usage(jm_dataset.df, jm_dataset.start, jm_dataset.end,", "as rp from utils.report import ReportBuilder from workflows.workflowutils import export_job_counts, export_parameters # Todo", "DatasetImporter( JMImporter(timezone_correction='Europe/Berlin', hostname_suffix='.gridka.de', with_files=False)) jm_dataset = dataset_importer.import_dataset(config.inputPaths['jm'], start_date, end_date) wm_dataset = DatasetImporter(SummarizedWMAImporter(with_files=False)) \\", "use_files=False, previous_matches=cached_matches) if use_caching: match_cache_file = os.path.join(config.cacheDir, 'jm-wma-matches.csv') logging.info(\"Writing {} matches to file", "sampling_report.write() export_parameters('parameters_slots_from_pilots_sampled0.5', scaled_nodes_pilots, sample_demands) export_parameters('parameters_slots_from_reports_sampled0.5', scaled_nodes_reports, sample_demands) # Export job throughputs from analyzed", "Run') time_now = datetime.now().strftime('%Y-%m-%d, %H:%M:%S') self.report.append('at {}'.format(time_now)) logging.info(\"Model Calibration run at {}\".format(time_now)) start_date", "utils.report import ReportBuilder from workflows.workflowutils import export_job_counts, export_parameters # Todo Split this up", "from_reports], axis=1) fig, axes = visualization.draw_efficiency_timeseries( {'extracted from job reports': from_reports, 'reference from", "data.dataset import Metric from exporters.datasetexport import ReferenceWalltimeExporter from importers.dataset_import import DatasetImporter from importers.gridkadata", "job_classifier.split(reports_train) job_demand_extractor.report = sampling_report sample_demands, sample_partitions = job_demand_extractor.extract_job_demands(job_groups_train) sampling_report.write() export_parameters('parameters_slots_from_pilots_sampled0.5', scaled_nodes_pilots, sample_demands) export_parameters('parameters_slots_from_reports_sampled0.5',", "'splitTypes' in config.workflowOptions: split_types = list(map(tuple, config.workflowOptions['splitTypes'])) job_classifier = FilteredJobClassifier(type_split_cols, split_types=split_types) job_groups =", "split_types = None if 'splitTypes' in config.workflowOptions: split_types = list(map(tuple, config.workflowOptions['splitTypes'])) job_classifier =", "dataset_importer = DatasetImporter( JMImporter(timezone_correction='Europe/Berlin', hostname_suffix='.gridka.de', with_files=False)) jm_dataset = dataset_importer.import_dataset(config.inputPaths['jm'], start_date, end_date) wm_dataset =", "'date', 'type') self.report.add_figure(fig, axes, 'job_counts_reference', tight_layout=False) job_counts_reference_summary = job_counts.groupby('type')['count'].sum().reset_index() job_counts_reference_summary.columns = ['type', 'count']", "job_counts_reference_summary.columns = ['type', 'count'] job_counts_reference_summary['share'] = job_counts_reference_summary['count'] / job_counts_reference_summary[ 'count'].sum() job_counts_reference_summary['throughput_day'] = job_counts_reference_summary['count'].divide(", "pilots': core_reference['cms']}) self.report.add_figure(fig, axes, 'jobslot_usage_reference') return avg_jobslots_reports def add_jobs_over_time(self, start_date, end_date): self.report.append(\"## Number", "None if 'splitTypes' in config.workflowOptions: split_types = list(map(tuple, config.workflowOptions['splitTypes'])) job_classifier = FilteredJobClassifier(type_split_cols, split_types=split_types)", "walltimes walltime_path = os.path.join(config.outputDirectory, 'parameters_slots_from_pilots', config.outputPaths['walltimeReference']) ReferenceWalltimeExporter().export_to_json_file(partitions, walltime_path) # Write jobs to report", "cms_avg_cores = core_df['cms'].mean() avg_jobslots_reports = self.draw_jobslot_usage(jm_dataset, core_df) # Visualize number of jobs in", "- start_date).days) self.report.append(\"Job throughput from CMS Dashboard:\") self.report.append() self.report.append_paragraph(rp.CodeBlock().append(job_counts_reference_summary.to_string())) return job_counts_reference_summary def add_cpu_efficiency(self,", "start_date).days)) axes.set_xlim(left=start_date, right=(end_date - pd.Timedelta('1 days'))) fig.set_size_inches(8, 4.5) self.report.add_figure(fig, axes, 'cpu_efficiencies_reference') self.report.append(\"Efficiency from", "4.5) self.report.add_figure(fig, axes, 'cpu_efficiencies_reference') self.report.append(\"Efficiency from job reports: {} \".format(reports_average)) self.report.append(\"Efficiency from GridKa:", "= cpuefficiency.calculate_efficiencies(job_data, freq='12h') reference = efficiency_reference['value'].resample('12h').mean().rename('reference') reference_mean = efficiency_reference['value'].mean() from_reports = efficiency_timeseries.rename('measured') #", "ReportBuilder(base_path=config.outputDirectory, filename='calibration-report.md') def run(self): self.report.append('# GridKa Calibration Run') time_now = datetime.now().strftime('%Y-%m-%d, %H:%M:%S') self.report.append('at", "core_df) # Visualize number of jobs in calibration report job_counts_reference_summary = self.add_jobs_over_time(start_date, end_date)", "UnionDatasetMerge from merge.reportmatching import JobReportMatcher from utils import config, visualization from utils import", "os.path.join(config.cacheDir, 'jm-wma-matches.csv') if os.path.isfile(match_cache_file): try: cached_matches = pd.read_csv(match_cache_file, usecols=[jm_dataset.df.index.name, wm_dataset.df.index.name]) logging.info( \"Loaded {}", "Jobmonitoring and WMArchive job reports matcher = JobReportMatcher(timestamp_tolerance=10, time_grouping_freq='D') matches = matcher.match_reports(jm_dataset, wm_dataset,", "the reports, fix random state for reproducibility reports_train, reports_test = sampling.split_samples(job_data, frac=0.5, random_state=38728)", "job_counts_reference_summary['throughput_day'] = job_counts_reference_summary['count'].divide( (end_date - start_date).days) self.report.append(\"Job throughput from CMS Dashboard:\") self.report.append() self.report.append_paragraph(rp.CodeBlock().append(job_counts_reference_summary.to_string()))", "axis=1) fig, axes = visualization.draw_efficiency_timeseries( {'extracted from job reports': from_reports, 'reference from GridKa", "sample_demands) export_parameters('parameters_slots_from_reports_sampled0.5', scaled_nodes_reports, sample_demands) # Export job throughputs from analyzed jobs jobs_from_reports =", "DatasetImporter from importers.gridkadata import GridKaNodeDataImporter, ColumnCoreUsageImporter, \\ CPUEfficiencyReferenceImporter from importers.jmimport import JMImporter from", "'Reference from GridKa monitoring (average {:.2f}%)'.format(reference_mean * 100)]) axes.set_title(\"CPU efficiencies ({}, {} days)\".format(config.runName,", "= pd.read_csv(match_cache_file, usecols=[jm_dataset.df.index.name, wm_dataset.df.index.name]) logging.info( \"Loaded {} matches from match cache {}!\".format(cached_matches.shape[0], match_cache_file))", "datetime import pandas as pd from analysis import calibrationreport, resource_usage, cpuefficiency, sampling from", "from analysis.demandextraction import FilteredJobClassifier, JobDemandExtractor from data.dataset import Metric from exporters.datasetexport import ReferenceWalltimeExporter", "jobreportcleaning.clean_job_reports(jobs_dataset.df) # Import node information nodes = GridKaNodeDataImporter().import_file(config.inputPaths['nodeInfo']) nodes = nodeanalysis.add_performance_data(nodes, simulated_cores=config.workflowOptions['coreSimulationMethod'], thread_rate_method=config.workflowOptions['threadPerformanceMethod'])", "export_parameters # Todo Split this up into smaller methods class GridKaCalibration(CalibrationWorkflow): def __init__(self):", "- pd.Timedelta('1 days'))) fig.set_size_inches(8, 4.5) self.report.add_figure(fig, axes, 'cpu_efficiencies_reference') self.report.append(\"Efficiency from job reports: {}", "GridKa site core_importer = ColumnCoreUsageImporter() core_df = core_importer.import_file(config.inputPaths['coreUsage'], start_date, end_date) cms_avg_cores = core_df['cms'].mean()", "config, visualization from utils import report as rp from utils.report import ReportBuilder from", "class GridKaCalibration(CalibrationWorkflow): def __init__(self): self.report = ReportBuilder(base_path=config.outputDirectory, filename='calibration-report.md') def run(self): self.report.append('# GridKa Calibration", "import pandas as pd from analysis import calibrationreport, resource_usage, cpuefficiency, sampling from analysis", "Write jobs to report calibrationreport.add_jobs_report_section(jm_dataset, self.report) # Write report out to disk self.report.write()", "reports': jobslots_from_reports, 'Allocated to GridKa CMS pilots': core_reference['cms']}) self.report.add_figure(fig, axes, 'jobslot_usage_reference') return avg_jobslots_reports", "utils import report as rp from utils.report import ReportBuilder from workflows.workflowutils import export_job_counts,", "wm_dataset.df.index.name]) logging.info( \"Loaded {} matches from match cache {}!\".format(cached_matches.shape[0], match_cache_file)) except Exception: logging.warning(\"No", "calibration parameters node_types = nodeanalysis.extract_node_types(nodes) # Scale the resource environment with both information", "cms_avg_cores) scaled_nodes_reports = nodeanalysis.scale_site_by_jobslots(node_types, avg_jobslots_reports) type_split_cols = config.workflowOptions['typeSplitCols'] split_types = None if 'splitTypes'", "= ReportBuilder(base_path=config.outputDirectory, filename='calibration-report-sampled.md', resource_dir='figures-sampling') job_groups_train = job_classifier.split(reports_train) job_demand_extractor.report = sampling_report sample_demands, sample_partitions =", "job_demand_extractor.extract_job_demands(job_groups_train) sampling_report.write() export_parameters('parameters_slots_from_pilots_sampled0.5', scaled_nodes_pilots, sample_demands) export_parameters('parameters_slots_from_reports_sampled0.5', scaled_nodes_reports, sample_demands) # Export job throughputs from", "importers.jmimport import JMImporter from importers.jobcounts import JobCountImporter from importers.wmaimport import SummarizedWMAImporter from interfaces.workflow", "jm_dataset, core_reference): jobslot_timeseries = resource_usage.calculate_jobslot_usage(jm_dataset.df, jm_dataset.start, jm_dataset.end, start_ts_col=Metric.START_TIME.value, end_ts_col=Metric.STOP_TIME.value, slot_col=Metric.USED_CORES.value) jobslots_from_reports = jobslot_timeseries['totalSlots'].resample('s').pad().resample('H').mean()", "from data.dataset import Metric from exporters.datasetexport import ReferenceWalltimeExporter from importers.dataset_import import DatasetImporter from", "left_index='UniqueID', right_index='wmaid', left_suffix='jm', right_suffix='wma') jobs_dataset.df = jobreportcleaning.clean_job_reports(jobs_dataset.df) # Import node information nodes =", "random_state=38728) sampling_report = ReportBuilder(base_path=config.outputDirectory, filename='calibration-report-sampled.md', resource_dir='figures-sampling') job_groups_train = job_classifier.split(reports_train) job_demand_extractor.report = sampling_report sample_demands,", "({}, {} days)\".format(config.runName, (end_date - start_date).days)) axes.set_xlim(left=start_date, right=(end_date - pd.Timedelta('1 days'))) fig.set_size_inches(8, 4.5)", "thread_rate_method=config.workflowOptions['threadPerformanceMethod']) # Match jobs to nodes matched_jobs = job_node.match_jobs_to_node(jobs_dataset.df, nodes) matched_jobs = jobreportanalysis.add_missing_node_info(matched_jobs,", "matches to file {}\".format(matches.shape[0], match_cache_file)) matches.to_csv(match_cache_file) jobs_dataset = UnionDatasetMerge().merge_datasets(matches, jm_dataset, wm_dataset, left_index='UniqueID', right_index='wmaid',", "merge import job_node from merge.merge_datasets import UnionDatasetMerge from merge.reportmatching import JobReportMatcher from utils", "for errors in timestamps of JobMonitoring data dataset_importer = DatasetImporter( JMImporter(timezone_correction='Europe/Berlin', hostname_suffix='.gridka.de', with_files=False))", "the Pilot jobs scaled_nodes_pilots = nodeanalysis.scale_site_by_jobslots(node_types, cms_avg_cores) scaled_nodes_reports = nodeanalysis.scale_site_by_jobslots(node_types, avg_jobslots_reports) type_split_cols =", "reports_train, reports_test = sampling.split_samples(job_data, frac=0.5, random_state=38728) sampling_report = ReportBuilder(base_path=config.outputDirectory, filename='calibration-report-sampled.md', resource_dir='figures-sampling') job_groups_train =", "= calibrationreport.multiple_jobslot_usage( {'Extracted from job reports': jobslots_from_reports, 'Allocated to GridKa CMS pilots': core_reference['cms']})", "= sampling.split_samples(job_data, frac=0.5, random_state=38728) sampling_report = ReportBuilder(base_path=config.outputDirectory, filename='calibration-report-sampled.md', resource_dir='figures-sampling') job_groups_train = job_classifier.split(reports_train) job_demand_extractor.report", "export_job_counts, export_parameters # Todo Split this up into smaller methods class GridKaCalibration(CalibrationWorkflow): def", "GridKaCalibration(CalibrationWorkflow): def __init__(self): self.report = ReportBuilder(base_path=config.outputDirectory, filename='calibration-report.md') def run(self): self.report.append('# GridKa Calibration Run')", "end_date): efficiency_reference = CPUEfficiencyReferenceImporter(col='cms', output_column='value').import_file( config.inputPaths['CPUEfficiencyReference'], start_date, end_date) efficiency_timeseries, reports_average = cpuefficiency.calculate_efficiencies(job_data, freq='12h')", "Split this up into smaller methods class GridKaCalibration(CalibrationWorkflow): def __init__(self): self.report = ReportBuilder(base_path=config.outputDirectory,", "time\") job_counts = JobCountImporter().import_file(config.inputPaths['jobCountsReference'], start_date, end_date) fig, axes = calibrationreport.jobtypes_over_time_df(job_counts, 'date', 'type') self.report.add_figure(fig,", "for reproducibility reports_train, reports_test = sampling.split_samples(job_data, frac=0.5, random_state=38728) sampling_report = ReportBuilder(base_path=config.outputDirectory, filename='calibration-report-sampled.md', resource_dir='figures-sampling')", "slot_col=Metric.USED_CORES.value) jobslots_from_reports = jobslot_timeseries['totalSlots'].resample('s').pad().resample('H').mean() avg_jobslots_reports = jobslots_from_reports.mean() fig, axes = calibrationreport.multiple_jobslot_usage( {'Extracted from", "scaled_nodes_reports, sample_demands) # Export job throughputs from analyzed jobs jobs_from_reports = job_data.copy() jobs_from_reports[Metric.JOB_TYPE.value]", "calibrationreport, resource_usage, cpuefficiency, sampling from analysis import jobreportanalysis from analysis import jobreportcleaning from", "import JobCountImporter from importers.wmaimport import SummarizedWMAImporter from interfaces.workflow import CalibrationWorkflow from merge import", "import ReferenceWalltimeExporter from importers.dataset_import import DatasetImporter from importers.gridkadata import GridKaNodeDataImporter, ColumnCoreUsageImporter, \\ CPUEfficiencyReferenceImporter", "CalibrationWorkflow from merge import job_node from merge.merge_datasets import UnionDatasetMerge from merge.reportmatching import JobReportMatcher", "reports, fix random state for reproducibility reports_train, reports_test = sampling.split_samples(job_data, frac=0.5, random_state=38728) sampling_report", "efficiency_reference = CPUEfficiencyReferenceImporter(col='cms', output_column='value').import_file( config.inputPaths['CPUEfficiencyReference'], start_date, end_date) efficiency_timeseries, reports_average = cpuefficiency.calculate_efficiencies(job_data, freq='12h') reference", "jobslots_from_reports.mean() fig, axes = calibrationreport.multiple_jobslot_usage( {'Extracted from job reports': jobslots_from_reports, 'Allocated to GridKa", "overflow_agg=config.workflowOptions['overflowAggregationMethod'], additional_job_options=config.workflowOptions['additionalJobOptions'], drop_overflow=config.workflowOptions.get('dropOverflow', False)) demands, partitions = job_demand_extractor.extract_job_demands(job_groups) export_parameters('parameters_slots_from_pilots', scaled_nodes_pilots, demands) export_parameters('parameters_slots_from_reports', scaled_nodes_reports,", "importers.dataset_import import DatasetImporter from importers.gridkadata import GridKaNodeDataImporter, ColumnCoreUsageImporter, \\ CPUEfficiencyReferenceImporter from importers.jmimport import", "import ReportBuilder from workflows.workflowutils import export_job_counts, export_parameters # Todo Split this up into", "cpu_eff = pd.concat([reference, from_reports], axis=1) fig, axes = visualization.draw_efficiency_timeseries( {'extracted from job reports':", "from importers.jobcounts import JobCountImporter from importers.wmaimport import SummarizedWMAImporter from interfaces.workflow import CalibrationWorkflow from", "Write report out to disk self.report.write() def draw_jobslot_usage(self, jm_dataset, core_reference): jobslot_timeseries = resource_usage.calculate_jobslot_usage(jm_dataset.df,", "information from the job reports and the Pilot jobs scaled_nodes_pilots = nodeanalysis.scale_site_by_jobslots(node_types, cms_avg_cores)", "importers.gridkadata import GridKaNodeDataImporter, ColumnCoreUsageImporter, \\ CPUEfficiencyReferenceImporter from importers.jmimport import JMImporter from importers.jobcounts import", "GridKa CMS pilots': core_reference['cms']}) self.report.add_figure(fig, axes, 'jobslot_usage_reference') return avg_jobslots_reports def add_jobs_over_time(self, start_date, end_date):", "def add_jobs_over_time(self, start_date, end_date): self.report.append(\"## Number of jobs completed over time\") job_counts =", "Timezone correction correct for errors in timestamps of JobMonitoring data dataset_importer = DatasetImporter(", "Import additional information for usage of GridKa site core_importer = ColumnCoreUsageImporter() core_df =", "axes = calibrationreport.multiple_jobslot_usage( {'Extracted from job reports': jobslots_from_reports, 'Allocated to GridKa CMS pilots':", "job throughputs from analyzed jobs jobs_from_reports = job_data.copy() jobs_from_reports[Metric.JOB_TYPE.value] = jobs_from_reports[Metric.JOB_TYPE.value].fillna('unknown') job_counts_reports =", "jobslots_from_reports = jobslot_timeseries['totalSlots'].resample('s').pad().resample('H').mean() avg_jobslots_reports = jobslots_from_reports.mean() fig, axes = calibrationreport.multiple_jobslot_usage( {'Extracted from job", "split_types = list(map(tuple, config.workflowOptions['splitTypes'])) job_classifier = FilteredJobClassifier(type_split_cols, split_types=split_types) job_groups = job_classifier.split(job_data) job_demand_extractor =", "list(map(tuple, config.workflowOptions['splitTypes'])) job_classifier = FilteredJobClassifier(type_split_cols, split_types=split_types) job_groups = job_classifier.split(job_data) job_demand_extractor = JobDemandExtractor(self.report, equal_width=False,", "from utils import config, visualization from utils import report as rp from utils.report", "use_caching: match_cache_file = os.path.join(config.cacheDir, 'jm-wma-matches.csv') if os.path.isfile(match_cache_file): try: cached_matches = pd.read_csv(match_cache_file, usecols=[jm_dataset.df.index.name, wm_dataset.df.index.name])", "export_parameters('parameters_slots_from_pilots', scaled_nodes_pilots, demands) export_parameters('parameters_slots_from_reports', scaled_nodes_reports, demands) # Sample half of the reports, fix", "SummarizedWMAImporter from interfaces.workflow import CalibrationWorkflow from merge import job_node from merge.merge_datasets import UnionDatasetMerge", "JobDemandExtractor from data.dataset import Metric from exporters.datasetexport import ReferenceWalltimeExporter from importers.dataset_import import DatasetImporter", "Calibration Run') time_now = datetime.now().strftime('%Y-%m-%d, %H:%M:%S') self.report.append('at {}'.format(time_now)) logging.info(\"Model Calibration run at {}\".format(time_now))", "additional_job_options=config.workflowOptions['additionalJobOptions'], drop_overflow=config.workflowOptions.get('dropOverflow', False)) demands, partitions = job_demand_extractor.extract_job_demands(job_groups) export_parameters('parameters_slots_from_pilots', scaled_nodes_pilots, demands) export_parameters('parameters_slots_from_reports', scaled_nodes_reports, demands)", "end_date) # CPU Efficiencies self.add_cpu_efficiency(job_data, start_date, end_date) # Compute calibration parameters node_types =", "nodeanalysis.scale_site_by_jobslots(node_types, avg_jobslots_reports) type_split_cols = config.workflowOptions['typeSplitCols'] split_types = None if 'splitTypes' in config.workflowOptions: split_types", "efficiency_reference['value'].resample('12h').mean().rename('reference') reference_mean = efficiency_reference['value'].mean() from_reports = efficiency_timeseries.rename('measured') # cpu_eff = pd.concat([reference, from_reports], axis=1)", "(CPU time / wall time)\") axes.legend(['Extracted from job reports (average {:.2f}%)'.format(reports_average * 100),", "100), 'Reference from GridKa monitoring (average {:.2f}%)'.format(reference_mean * 100)]) axes.set_title(\"CPU efficiencies ({}, {}", "jobs to nodes matched_jobs = job_node.match_jobs_to_node(jobs_dataset.df, nodes) matched_jobs = jobreportanalysis.add_missing_node_info(matched_jobs, nodes) jm_dataset.df =", "{}\".format(matches.shape[0], match_cache_file)) matches.to_csv(match_cache_file) jobs_dataset = UnionDatasetMerge().merge_datasets(matches, jm_dataset, wm_dataset, left_index='UniqueID', right_index='wmaid', left_suffix='jm', right_suffix='wma') jobs_dataset.df", "ColumnCoreUsageImporter, \\ CPUEfficiencyReferenceImporter from importers.jmimport import JMImporter from importers.jobcounts import JobCountImporter from importers.wmaimport", "export_parameters('parameters_slots_from_pilots_sampled0.5', scaled_nodes_pilots, sample_demands) export_parameters('parameters_slots_from_reports_sampled0.5', scaled_nodes_reports, sample_demands) # Export job throughputs from analyzed jobs", "if use_caching: match_cache_file = os.path.join(config.cacheDir, 'jm-wma-matches.csv') logging.info(\"Writing {} matches to file {}\".format(matches.shape[0], match_cache_file))", "try: cached_matches = pd.read_csv(match_cache_file, usecols=[jm_dataset.df.index.name, wm_dataset.df.index.name]) logging.info( \"Loaded {} matches from match cache", "sampling_report sample_demands, sample_partitions = job_demand_extractor.extract_job_demands(job_groups_train) sampling_report.write() export_parameters('parameters_slots_from_pilots_sampled0.5', scaled_nodes_pilots, sample_demands) export_parameters('parameters_slots_from_reports_sampled0.5', scaled_nodes_reports, sample_demands) #", "to file {}\".format(matches.shape[0], match_cache_file)) matches.to_csv(match_cache_file) jobs_dataset = UnionDatasetMerge().merge_datasets(matches, jm_dataset, wm_dataset, left_index='UniqueID', right_index='wmaid', left_suffix='jm',", "not None if use_caching: match_cache_file = os.path.join(config.cacheDir, 'jm-wma-matches.csv') if os.path.isfile(match_cache_file): try: cached_matches =", "core_df = core_importer.import_file(config.inputPaths['coreUsage'], start_date, end_date) cms_avg_cores = core_df['cms'].mean() avg_jobslots_reports = self.draw_jobslot_usage(jm_dataset, core_df) #", "os.path.isfile(match_cache_file): try: cached_matches = pd.read_csv(match_cache_file, usecols=[jm_dataset.df.index.name, wm_dataset.df.index.name]) logging.info( \"Loaded {} matches from match", "def run(self): self.report.append('# GridKa Calibration Run') time_now = datetime.now().strftime('%Y-%m-%d, %H:%M:%S') self.report.append('at {}'.format(time_now)) logging.info(\"Model", "= pd.to_datetime(config.startDate) end_date = pd.to_datetime(config.endDate) day_count = (end_date - start_date).days self.report.append() self.report.append(\"Start date:", "axes = calibrationreport.jobtypes_over_time_df(job_counts, 'date', 'type') self.report.add_figure(fig, axes, 'job_counts_reference', tight_layout=False) job_counts_reference_summary = job_counts.groupby('type')['count'].sum().reset_index() job_counts_reference_summary.columns", "CMS pilots': core_reference['cms']}) self.report.add_figure(fig, axes, 'jobslot_usage_reference') return avg_jobslots_reports def add_jobs_over_time(self, start_date, end_date): self.report.append(\"##", "import CalibrationWorkflow from merge import job_node from merge.merge_datasets import UnionDatasetMerge from merge.reportmatching import", "calibrationreport.jobtypes_over_time_df(job_counts, 'date', 'type') self.report.add_figure(fig, axes, 'job_counts_reference', tight_layout=False) job_counts_reference_summary = job_counts.groupby('type')['count'].sum().reset_index() job_counts_reference_summary.columns = ['type',", "= config.workflowOptions['typeSplitCols'] split_types = None if 'splitTypes' in config.workflowOptions: split_types = list(map(tuple, config.workflowOptions['splitTypes']))", "fig, axes = visualization.draw_efficiency_timeseries( {'extracted from job reports': from_reports, 'reference from GridKa monitoring':", "self.report.append(\"Start date: {} \\nEnd date: {}\".format(start_date, end_date)) # Import data sets ################## #", "job_data.copy() jobs_from_reports[Metric.JOB_TYPE.value] = jobs_from_reports[Metric.JOB_TYPE.value].fillna('unknown') job_counts_reports = jobs_from_reports.groupby(Metric.JOB_TYPE.value).size().reset_index() job_counts_reports.columns = ['type', 'count'] job_counts_reports['throughput_day'] =", "analysis import jobreportcleaning from analysis import nodeanalysis from analysis.demandextraction import FilteredJobClassifier, JobDemandExtractor from", ".import_dataset(config.inputPaths['wma'], start_date, end_date) cached_matches = None use_caching = config.cacheDir is not None if", "{} matches to file {}\".format(matches.shape[0], match_cache_file)) matches.to_csv(match_cache_file) jobs_dataset = UnionDatasetMerge().merge_datasets(matches, jm_dataset, wm_dataset, left_index='UniqueID',", "100)]) axes.set_title(\"CPU efficiencies ({}, {} days)\".format(config.runName, (end_date - start_date).days)) axes.set_xlim(left=start_date, right=(end_date - pd.Timedelta('1", "import JobReportMatcher from utils import config, visualization from utils import report as rp", "wm_dataset = DatasetImporter(SummarizedWMAImporter(with_files=False)) \\ .import_dataset(config.inputPaths['wma'], start_date, end_date) cached_matches = None use_caching = config.cacheDir", "wall time)\") axes.legend(['Extracted from job reports (average {:.2f}%)'.format(reports_average * 100), 'Reference from GridKa", "of GridKa site core_importer = ColumnCoreUsageImporter() core_df = core_importer.import_file(config.inputPaths['coreUsage'], start_date, end_date) cms_avg_cores =", "export_parameters('parameters_slots_from_reports', scaled_nodes_reports, demands) # Sample half of the reports, fix random state for", "{}\".format(start_date, end_date)) # Import data sets ################## # Timezone correction correct for errors", "simulated_cores=config.workflowOptions['coreSimulationMethod'], thread_rate_method=config.workflowOptions['threadPerformanceMethod']) # Match jobs to nodes matched_jobs = job_node.match_jobs_to_node(jobs_dataset.df, nodes) matched_jobs =", "core_importer = ColumnCoreUsageImporter() core_df = core_importer.import_file(config.inputPaths['coreUsage'], start_date, end_date) cms_avg_cores = core_df['cms'].mean() avg_jobslots_reports =", "= nodeanalysis.scale_site_by_jobslots(node_types, avg_jobslots_reports) type_split_cols = config.workflowOptions['typeSplitCols'] split_types = None if 'splitTypes' in config.workflowOptions:", "config.workflowOptions['typeSplitCols'] split_types = None if 'splitTypes' in config.workflowOptions: split_types = list(map(tuple, config.workflowOptions['splitTypes'])) job_classifier", "self.add_jobs_over_time(start_date, end_date) # CPU Efficiencies self.add_cpu_efficiency(job_data, start_date, end_date) # Compute calibration parameters node_types", "day_count = (end_date - start_date).days self.report.append() self.report.append(\"Start date: {} \\nEnd date: {}\".format(start_date, end_date))", "use_caching: match_cache_file = os.path.join(config.cacheDir, 'jm-wma-matches.csv') logging.info(\"Writing {} matches to file {}\".format(matches.shape[0], match_cache_file)) matches.to_csv(match_cache_file)", "information nodes = GridKaNodeDataImporter().import_file(config.inputPaths['nodeInfo']) nodes = nodeanalysis.add_performance_data(nodes, simulated_cores=config.workflowOptions['coreSimulationMethod'], thread_rate_method=config.workflowOptions['threadPerformanceMethod']) # Match jobs to", "time_grouping_freq='D') matches = matcher.match_reports(jm_dataset, wm_dataset, use_files=False, previous_matches=cached_matches) if use_caching: match_cache_file = os.path.join(config.cacheDir, 'jm-wma-matches.csv')", "previous_matches=cached_matches) if use_caching: match_cache_file = os.path.join(config.cacheDir, 'jm-wma-matches.csv') logging.info(\"Writing {} matches to file {}\".format(matches.shape[0],", "of jobs completed over time\") job_counts = JobCountImporter().import_file(config.inputPaths['jobCountsReference'], start_date, end_date) fig, axes =", "= FilteredJobClassifier(type_split_cols, split_types=split_types) job_groups = job_classifier.split(job_data) job_demand_extractor = JobDemandExtractor(self.report, equal_width=False, bin_count=60, cutoff_quantile=0.95, overflow_agg=config.workflowOptions['overflowAggregationMethod'],", "jm_dataset.end, start_ts_col=Metric.START_TIME.value, end_ts_col=Metric.STOP_TIME.value, slot_col=Metric.USED_CORES.value) jobslots_from_reports = jobslot_timeseries['totalSlots'].resample('s').pad().resample('H').mean() avg_jobslots_reports = jobslots_from_reports.mean() fig, axes =", "# Import additional information for usage of GridKa site core_importer = ColumnCoreUsageImporter() core_df", "JobReportMatcher(timestamp_tolerance=10, time_grouping_freq='D') matches = matcher.match_reports(jm_dataset, wm_dataset, use_files=False, previous_matches=cached_matches) if use_caching: match_cache_file = os.path.join(config.cacheDir,", "from the job reports and the Pilot jobs scaled_nodes_pilots = nodeanalysis.scale_site_by_jobslots(node_types, cms_avg_cores) scaled_nodes_reports", "cutoff_quantile=0.95, overflow_agg=config.workflowOptions['overflowAggregationMethod'], additional_job_options=config.workflowOptions['additionalJobOptions'], drop_overflow=config.workflowOptions.get('dropOverflow', False)) demands, partitions = job_demand_extractor.extract_job_demands(job_groups) export_parameters('parameters_slots_from_pilots', scaled_nodes_pilots, demands) export_parameters('parameters_slots_from_reports',", "config.outputPaths['walltimeReference']) ReferenceWalltimeExporter().export_to_json_file(partitions, walltime_path) # Write jobs to report calibrationreport.add_jobs_report_section(jm_dataset, self.report) # Write report", "axes, 'jobslot_usage_reference') return avg_jobslots_reports def add_jobs_over_time(self, start_date, end_date): self.report.append(\"## Number of jobs completed", "= core_importer.import_file(config.inputPaths['coreUsage'], start_date, end_date) cms_avg_cores = core_df['cms'].mean() avg_jobslots_reports = self.draw_jobslot_usage(jm_dataset, core_df) # Visualize", "job_counts_reports['count'].divide(day_count) export_job_counts(job_counts_reports, 'parameters_slots_from_pilots', config.outputPaths['jobCountReports']) # Export walltimes walltime_path = os.path.join(config.outputDirectory, 'parameters_slots_from_pilots', config.outputPaths['walltimeReference']) ReferenceWalltimeExporter().export_to_json_file(partitions,", "= CPUEfficiencyReferenceImporter(col='cms', output_column='value').import_file( config.inputPaths['CPUEfficiencyReference'], start_date, end_date) efficiency_timeseries, reports_average = cpuefficiency.calculate_efficiencies(job_data, freq='12h') reference =", "# Export job throughputs from analyzed jobs jobs_from_reports = job_data.copy() jobs_from_reports[Metric.JOB_TYPE.value] = jobs_from_reports[Metric.JOB_TYPE.value].fillna('unknown')", "in calibration report job_counts_reference_summary = self.add_jobs_over_time(start_date, end_date) # CPU Efficiencies self.add_cpu_efficiency(job_data, start_date, end_date)", "self.report.append() self.report.append(\"Start date: {} \\nEnd date: {}\".format(start_date, end_date)) # Import data sets ##################", "wm_dataset, left_index='UniqueID', right_index='wmaid', left_suffix='jm', right_suffix='wma') jobs_dataset.df = jobreportcleaning.clean_job_reports(jobs_dataset.df) # Import node information nodes", "= jm_dataset.df # Import additional information for usage of GridKa site core_importer =", "logging.info( \"Loaded {} matches from match cache {}!\".format(cached_matches.shape[0], match_cache_file)) except Exception: logging.warning(\"No match", "efficiency_timeseries, reports_average = cpuefficiency.calculate_efficiencies(job_data, freq='12h') reference = efficiency_reference['value'].resample('12h').mean().rename('reference') reference_mean = efficiency_reference['value'].mean() from_reports =", "= efficiency_timeseries.rename('measured') # cpu_eff = pd.concat([reference, from_reports], axis=1) fig, axes = visualization.draw_efficiency_timeseries( {'extracted", "config.cacheDir is not None if use_caching: match_cache_file = os.path.join(config.cacheDir, 'jm-wma-matches.csv') if os.path.isfile(match_cache_file): try:", "with_files=False)) jm_dataset = dataset_importer.import_dataset(config.inputPaths['jm'], start_date, end_date) wm_dataset = DatasetImporter(SummarizedWMAImporter(with_files=False)) \\ .import_dataset(config.inputPaths['wma'], start_date, end_date)", "from job reports': from_reports, 'reference from GridKa monitoring': reference}) axes.set_ylabel(\"CPU efficiency (CPU time", "from analysis import jobreportcleaning from analysis import nodeanalysis from analysis.demandextraction import FilteredJobClassifier, JobDemandExtractor", "drop_overflow=config.workflowOptions.get('dropOverflow', False)) demands, partitions = job_demand_extractor.extract_job_demands(job_groups) export_parameters('parameters_slots_from_pilots', scaled_nodes_pilots, demands) export_parameters('parameters_slots_from_reports', scaled_nodes_reports, demands) #", "Export job throughputs from analyzed jobs jobs_from_reports = job_data.copy() jobs_from_reports[Metric.JOB_TYPE.value] = jobs_from_reports[Metric.JOB_TYPE.value].fillna('unknown') job_counts_reports", "dataset_importer.import_dataset(config.inputPaths['jm'], start_date, end_date) wm_dataset = DatasetImporter(SummarizedWMAImporter(with_files=False)) \\ .import_dataset(config.inputPaths['wma'], start_date, end_date) cached_matches = None", "import os from datetime import datetime import pandas as pd from analysis import", "match_cache_file)) except Exception: logging.warning(\"No match cache found at {}!\".format(match_cache_file)) # Match Jobmonitoring and", "demands) export_parameters('parameters_slots_from_reports', scaled_nodes_reports, demands) # Sample half of the reports, fix random state", "walltime_path) # Write jobs to report calibrationreport.add_jobs_report_section(jm_dataset, self.report) # Write report out to", "exporters.datasetexport import ReferenceWalltimeExporter from importers.dataset_import import DatasetImporter from importers.gridkadata import GridKaNodeDataImporter, ColumnCoreUsageImporter, \\", "from analysis import nodeanalysis from analysis.demandextraction import FilteredJobClassifier, JobDemandExtractor from data.dataset import Metric", "jm_dataset = dataset_importer.import_dataset(config.inputPaths['jm'], start_date, end_date) wm_dataset = DatasetImporter(SummarizedWMAImporter(with_files=False)) \\ .import_dataset(config.inputPaths['wma'], start_date, end_date) cached_matches", "axes = visualization.draw_efficiency_timeseries( {'extracted from job reports': from_reports, 'reference from GridKa monitoring': reference})", "efficiency_timeseries.rename('measured') # cpu_eff = pd.concat([reference, from_reports], axis=1) fig, axes = visualization.draw_efficiency_timeseries( {'extracted from", "['type', 'count'] job_counts_reports['throughput_day'] = job_counts_reports['count'].divide(day_count) export_job_counts(job_counts_reports, 'parameters_slots_from_pilots', config.outputPaths['jobCountReports']) # Export walltimes walltime_path =", "right_suffix='wma') jobs_dataset.df = jobreportcleaning.clean_job_reports(jobs_dataset.df) # Import node information nodes = GridKaNodeDataImporter().import_file(config.inputPaths['nodeInfo']) nodes =", "usage of GridKa site core_importer = ColumnCoreUsageImporter() core_df = core_importer.import_file(config.inputPaths['coreUsage'], start_date, end_date) cms_avg_cores", "demands) # Sample half of the reports, fix random state for reproducibility reports_train,", "jobs_from_reports[Metric.JOB_TYPE.value].fillna('unknown') job_counts_reports = jobs_from_reports.groupby(Metric.JOB_TYPE.value).size().reset_index() job_counts_reports.columns = ['type', 'count'] job_counts_reports['throughput_day'] = job_counts_reports['count'].divide(day_count) export_job_counts(job_counts_reports, 'parameters_slots_from_pilots',", "Number of jobs completed over time\") job_counts = JobCountImporter().import_file(config.inputPaths['jobCountsReference'], start_date, end_date) fig, axes", "analyzed jobs jobs_from_reports = job_data.copy() jobs_from_reports[Metric.JOB_TYPE.value] = jobs_from_reports[Metric.JOB_TYPE.value].fillna('unknown') job_counts_reports = jobs_from_reports.groupby(Metric.JOB_TYPE.value).size().reset_index() job_counts_reports.columns =", "job_classifier.split(job_data) job_demand_extractor = JobDemandExtractor(self.report, equal_width=False, bin_count=60, cutoff_quantile=0.95, overflow_agg=config.workflowOptions['overflowAggregationMethod'], additional_job_options=config.workflowOptions['additionalJobOptions'], drop_overflow=config.workflowOptions.get('dropOverflow', False)) demands, partitions", "import JMImporter from importers.jobcounts import JobCountImporter from importers.wmaimport import SummarizedWMAImporter from interfaces.workflow import", "of jobs in calibration report job_counts_reference_summary = self.add_jobs_over_time(start_date, end_date) # CPU Efficiencies self.add_cpu_efficiency(job_data,", "efficiency_reference['value'].mean() from_reports = efficiency_timeseries.rename('measured') # cpu_eff = pd.concat([reference, from_reports], axis=1) fig, axes =", "reports matcher = JobReportMatcher(timestamp_tolerance=10, time_grouping_freq='D') matches = matcher.match_reports(jm_dataset, wm_dataset, use_files=False, previous_matches=cached_matches) if use_caching:", "'reference from GridKa monitoring': reference}) axes.set_ylabel(\"CPU efficiency (CPU time / wall time)\") axes.legend(['Extracted", "match cache {}!\".format(cached_matches.shape[0], match_cache_file)) except Exception: logging.warning(\"No match cache found at {}!\".format(match_cache_file)) #", "nodes = nodeanalysis.add_performance_data(nodes, simulated_cores=config.workflowOptions['coreSimulationMethod'], thread_rate_method=config.workflowOptions['threadPerformanceMethod']) # Match jobs to nodes matched_jobs = job_node.match_jobs_to_node(jobs_dataset.df,", "JobDemandExtractor(self.report, equal_width=False, bin_count=60, cutoff_quantile=0.95, overflow_agg=config.workflowOptions['overflowAggregationMethod'], additional_job_options=config.workflowOptions['additionalJobOptions'], drop_overflow=config.workflowOptions.get('dropOverflow', False)) demands, partitions = job_demand_extractor.extract_job_demands(job_groups) export_parameters('parameters_slots_from_pilots',", "'count'] job_counts_reference_summary['share'] = job_counts_reference_summary['count'] / job_counts_reference_summary[ 'count'].sum() job_counts_reference_summary['throughput_day'] = job_counts_reference_summary['count'].divide( (end_date - start_date).days)", "site core_importer = ColumnCoreUsageImporter() core_df = core_importer.import_file(config.inputPaths['coreUsage'], start_date, end_date) cms_avg_cores = core_df['cms'].mean() avg_jobslots_reports", "information for usage of GridKa site core_importer = ColumnCoreUsageImporter() core_df = core_importer.import_file(config.inputPaths['coreUsage'], start_date,", "date: {} \\nEnd date: {}\".format(start_date, end_date)) # Import data sets ################## # Timezone", "job_demand_extractor = JobDemandExtractor(self.report, equal_width=False, bin_count=60, cutoff_quantile=0.95, overflow_agg=config.workflowOptions['overflowAggregationMethod'], additional_job_options=config.workflowOptions['additionalJobOptions'], drop_overflow=config.workflowOptions.get('dropOverflow', False)) demands, partitions =", "'type') self.report.add_figure(fig, axes, 'job_counts_reference', tight_layout=False) job_counts_reference_summary = job_counts.groupby('type')['count'].sum().reset_index() job_counts_reference_summary.columns = ['type', 'count'] job_counts_reference_summary['share']", "jm_dataset, wm_dataset, left_index='UniqueID', right_index='wmaid', left_suffix='jm', right_suffix='wma') jobs_dataset.df = jobreportcleaning.clean_job_reports(jobs_dataset.df) # Import node information", "matched_jobs = job_node.match_jobs_to_node(jobs_dataset.df, nodes) matched_jobs = jobreportanalysis.add_missing_node_info(matched_jobs, nodes) jm_dataset.df = jobreportanalysis.add_performance_data(matched_jobs) job_data =", "from importers.dataset_import import DatasetImporter from importers.gridkadata import GridKaNodeDataImporter, ColumnCoreUsageImporter, \\ CPUEfficiencyReferenceImporter from importers.jmimport", "{} matches from match cache {}!\".format(cached_matches.shape[0], match_cache_file)) except Exception: logging.warning(\"No match cache found", "job reports matcher = JobReportMatcher(timestamp_tolerance=10, time_grouping_freq='D') matches = matcher.match_reports(jm_dataset, wm_dataset, use_files=False, previous_matches=cached_matches) if", "job_counts_reference_summary = job_counts.groupby('type')['count'].sum().reset_index() job_counts_reference_summary.columns = ['type', 'count'] job_counts_reference_summary['share'] = job_counts_reference_summary['count'] / job_counts_reference_summary[ 'count'].sum()", "job_counts_reports['throughput_day'] = job_counts_reports['count'].divide(day_count) export_job_counts(job_counts_reports, 'parameters_slots_from_pilots', config.outputPaths['jobCountReports']) # Export walltimes walltime_path = os.path.join(config.outputDirectory, 'parameters_slots_from_pilots',", "rp from utils.report import ReportBuilder from workflows.workflowutils import export_job_counts, export_parameters # Todo Split", "match_cache_file)) matches.to_csv(match_cache_file) jobs_dataset = UnionDatasetMerge().merge_datasets(matches, jm_dataset, wm_dataset, left_index='UniqueID', right_index='wmaid', left_suffix='jm', right_suffix='wma') jobs_dataset.df =", "'Allocated to GridKa CMS pilots': core_reference['cms']}) self.report.add_figure(fig, axes, 'jobslot_usage_reference') return avg_jobslots_reports def add_jobs_over_time(self,", "job_counts_reference_summary[ 'count'].sum() job_counts_reference_summary['throughput_day'] = job_counts_reference_summary['count'].divide( (end_date - start_date).days) self.report.append(\"Job throughput from CMS Dashboard:\")", "{} \\nEnd date: {}\".format(start_date, end_date)) # Import data sets ################## # Timezone correction", "from CMS Dashboard:\") self.report.append() self.report.append_paragraph(rp.CodeBlock().append(job_counts_reference_summary.to_string())) return job_counts_reference_summary def add_cpu_efficiency(self, job_data, start_date, end_date): efficiency_reference", "and the Pilot jobs scaled_nodes_pilots = nodeanalysis.scale_site_by_jobslots(node_types, cms_avg_cores) scaled_nodes_reports = nodeanalysis.scale_site_by_jobslots(node_types, avg_jobslots_reports) type_split_cols", "state for reproducibility reports_train, reports_test = sampling.split_samples(job_data, frac=0.5, random_state=38728) sampling_report = ReportBuilder(base_path=config.outputDirectory, filename='calibration-report-sampled.md',", "reports (average {:.2f}%)'.format(reports_average * 100), 'Reference from GridKa monitoring (average {:.2f}%)'.format(reference_mean * 100)])", "matched_jobs = jobreportanalysis.add_missing_node_info(matched_jobs, nodes) jm_dataset.df = jobreportanalysis.add_performance_data(matched_jobs) job_data = jm_dataset.df # Import additional", "job_counts_reference_summary['share'] = job_counts_reference_summary['count'] / job_counts_reference_summary[ 'count'].sum() job_counts_reference_summary['throughput_day'] = job_counts_reference_summary['count'].divide( (end_date - start_date).days) self.report.append(\"Job", "import nodeanalysis from analysis.demandextraction import FilteredJobClassifier, JobDemandExtractor from data.dataset import Metric from exporters.datasetexport", "CPUEfficiencyReferenceImporter(col='cms', output_column='value').import_file( config.inputPaths['CPUEfficiencyReference'], start_date, end_date) efficiency_timeseries, reports_average = cpuefficiency.calculate_efficiencies(job_data, freq='12h') reference = efficiency_reference['value'].resample('12h').mean().rename('reference')", "= dataset_importer.import_dataset(config.inputPaths['jm'], start_date, end_date) wm_dataset = DatasetImporter(SummarizedWMAImporter(with_files=False)) \\ .import_dataset(config.inputPaths['wma'], start_date, end_date) cached_matches =", "visualization from utils import report as rp from utils.report import ReportBuilder from workflows.workflowutils", "'jm-wma-matches.csv') logging.info(\"Writing {} matches to file {}\".format(matches.shape[0], match_cache_file)) matches.to_csv(match_cache_file) jobs_dataset = UnionDatasetMerge().merge_datasets(matches, jm_dataset,", "avg_jobslots_reports = self.draw_jobslot_usage(jm_dataset, core_df) # Visualize number of jobs in calibration report job_counts_reference_summary", "avg_jobslots_reports = jobslots_from_reports.mean() fig, axes = calibrationreport.multiple_jobslot_usage( {'Extracted from job reports': jobslots_from_reports, 'Allocated", "import DatasetImporter from importers.gridkadata import GridKaNodeDataImporter, ColumnCoreUsageImporter, \\ CPUEfficiencyReferenceImporter from importers.jmimport import JMImporter", "= job_counts_reference_summary['count'].divide( (end_date - start_date).days) self.report.append(\"Job throughput from CMS Dashboard:\") self.report.append() self.report.append_paragraph(rp.CodeBlock().append(job_counts_reference_summary.to_string())) return", "end_date)) # Import data sets ################## # Timezone correction correct for errors in", "= datetime.now().strftime('%Y-%m-%d, %H:%M:%S') self.report.append('at {}'.format(time_now)) logging.info(\"Model Calibration run at {}\".format(time_now)) start_date = pd.to_datetime(config.startDate)", "config.inputPaths['CPUEfficiencyReference'], start_date, end_date) efficiency_timeseries, reports_average = cpuefficiency.calculate_efficiencies(job_data, freq='12h') reference = efficiency_reference['value'].resample('12h').mean().rename('reference') reference_mean =", "importers.jobcounts import JobCountImporter from importers.wmaimport import SummarizedWMAImporter from interfaces.workflow import CalibrationWorkflow from merge", "= nodeanalysis.add_performance_data(nodes, simulated_cores=config.workflowOptions['coreSimulationMethod'], thread_rate_method=config.workflowOptions['threadPerformanceMethod']) # Match jobs to nodes matched_jobs = job_node.match_jobs_to_node(jobs_dataset.df, nodes)", "None use_caching = config.cacheDir is not None if use_caching: match_cache_file = os.path.join(config.cacheDir, 'jm-wma-matches.csv')", "bin_count=60, cutoff_quantile=0.95, overflow_agg=config.workflowOptions['overflowAggregationMethod'], additional_job_options=config.workflowOptions['additionalJobOptions'], drop_overflow=config.workflowOptions.get('dropOverflow', False)) demands, partitions = job_demand_extractor.extract_job_demands(job_groups) export_parameters('parameters_slots_from_pilots', scaled_nodes_pilots, demands)", "sampling.split_samples(job_data, frac=0.5, random_state=38728) sampling_report = ReportBuilder(base_path=config.outputDirectory, filename='calibration-report-sampled.md', resource_dir='figures-sampling') job_groups_train = job_classifier.split(reports_train) job_demand_extractor.report =", "hostname_suffix='.gridka.de', with_files=False)) jm_dataset = dataset_importer.import_dataset(config.inputPaths['jm'], start_date, end_date) wm_dataset = DatasetImporter(SummarizedWMAImporter(with_files=False)) \\ .import_dataset(config.inputPaths['wma'], start_date,", "(end_date - start_date).days)) axes.set_xlim(left=start_date, right=(end_date - pd.Timedelta('1 days'))) fig.set_size_inches(8, 4.5) self.report.add_figure(fig, axes, 'cpu_efficiencies_reference')", "return job_counts_reference_summary def add_cpu_efficiency(self, job_data, start_date, end_date): efficiency_reference = CPUEfficiencyReferenceImporter(col='cms', output_column='value').import_file( config.inputPaths['CPUEfficiencyReference'], start_date,", "(end_date - start_date).days) self.report.append(\"Job throughput from CMS Dashboard:\") self.report.append() self.report.append_paragraph(rp.CodeBlock().append(job_counts_reference_summary.to_string())) return job_counts_reference_summary def", "timestamps of JobMonitoring data dataset_importer = DatasetImporter( JMImporter(timezone_correction='Europe/Berlin', hostname_suffix='.gridka.de', with_files=False)) jm_dataset = dataset_importer.import_dataset(config.inputPaths['jm'],", "analysis import jobreportanalysis from analysis import jobreportcleaning from analysis import nodeanalysis from analysis.demandextraction", "* 100)]) axes.set_title(\"CPU efficiencies ({}, {} days)\".format(config.runName, (end_date - start_date).days)) axes.set_xlim(left=start_date, right=(end_date -", "job reports': jobslots_from_reports, 'Allocated to GridKa CMS pilots': core_reference['cms']}) self.report.add_figure(fig, axes, 'jobslot_usage_reference') return", "os from datetime import datetime import pandas as pd from analysis import calibrationreport,", "= GridKaNodeDataImporter().import_file(config.inputPaths['nodeInfo']) nodes = nodeanalysis.add_performance_data(nodes, simulated_cores=config.workflowOptions['coreSimulationMethod'], thread_rate_method=config.workflowOptions['threadPerformanceMethod']) # Match jobs to nodes matched_jobs", "match cache found at {}!\".format(match_cache_file)) # Match Jobmonitoring and WMArchive job reports matcher", "= job_node.match_jobs_to_node(jobs_dataset.df, nodes) matched_jobs = jobreportanalysis.add_missing_node_info(matched_jobs, nodes) jm_dataset.df = jobreportanalysis.add_performance_data(matched_jobs) job_data = jm_dataset.df", "reference_mean = efficiency_reference['value'].mean() from_reports = efficiency_timeseries.rename('measured') # cpu_eff = pd.concat([reference, from_reports], axis=1) fig,", "config.workflowOptions: split_types = list(map(tuple, config.workflowOptions['splitTypes'])) job_classifier = FilteredJobClassifier(type_split_cols, split_types=split_types) job_groups = job_classifier.split(job_data) job_demand_extractor", "freq='12h') reference = efficiency_reference['value'].resample('12h').mean().rename('reference') reference_mean = efficiency_reference['value'].mean() from_reports = efficiency_timeseries.rename('measured') # cpu_eff =", "importers.wmaimport import SummarizedWMAImporter from interfaces.workflow import CalibrationWorkflow from merge import job_node from merge.merge_datasets", "from importers.jmimport import JMImporter from importers.jobcounts import JobCountImporter from importers.wmaimport import SummarizedWMAImporter from", "logging.info(\"Model Calibration run at {}\".format(time_now)) start_date = pd.to_datetime(config.startDate) end_date = pd.to_datetime(config.endDate) day_count =", "date: {}\".format(start_date, end_date)) # Import data sets ################## # Timezone correction correct for", "resource_usage.calculate_jobslot_usage(jm_dataset.df, jm_dataset.start, jm_dataset.end, start_ts_col=Metric.START_TIME.value, end_ts_col=Metric.STOP_TIME.value, slot_col=Metric.USED_CORES.value) jobslots_from_reports = jobslot_timeseries['totalSlots'].resample('s').pad().resample('H').mean() avg_jobslots_reports = jobslots_from_reports.mean() fig,", "in config.workflowOptions: split_types = list(map(tuple, config.workflowOptions['splitTypes'])) job_classifier = FilteredJobClassifier(type_split_cols, split_types=split_types) job_groups = job_classifier.split(job_data)", "\\ .import_dataset(config.inputPaths['wma'], start_date, end_date) cached_matches = None use_caching = config.cacheDir is not None", "jobs to report calibrationreport.add_jobs_report_section(jm_dataset, self.report) # Write report out to disk self.report.write() def", "Pilot jobs scaled_nodes_pilots = nodeanalysis.scale_site_by_jobslots(node_types, cms_avg_cores) scaled_nodes_reports = nodeanalysis.scale_site_by_jobslots(node_types, avg_jobslots_reports) type_split_cols = config.workflowOptions['typeSplitCols']", "at {}\".format(time_now)) start_date = pd.to_datetime(config.startDate) end_date = pd.to_datetime(config.endDate) day_count = (end_date - start_date).days", "= efficiency_reference['value'].resample('12h').mean().rename('reference') reference_mean = efficiency_reference['value'].mean() from_reports = efficiency_timeseries.rename('measured') # cpu_eff = pd.concat([reference, from_reports],", "import FilteredJobClassifier, JobDemandExtractor from data.dataset import Metric from exporters.datasetexport import ReferenceWalltimeExporter from importers.dataset_import", "- start_date).days)) axes.set_xlim(left=start_date, right=(end_date - pd.Timedelta('1 days'))) fig.set_size_inches(8, 4.5) self.report.add_figure(fig, axes, 'cpu_efficiencies_reference') self.report.append(\"Efficiency", "# Todo Split this up into smaller methods class GridKaCalibration(CalibrationWorkflow): def __init__(self): self.report", "scaled_nodes_pilots, demands) export_parameters('parameters_slots_from_reports', scaled_nodes_reports, demands) # Sample half of the reports, fix random", "and WMArchive job reports matcher = JobReportMatcher(timestamp_tolerance=10, time_grouping_freq='D') matches = matcher.match_reports(jm_dataset, wm_dataset, use_files=False,", "matches.to_csv(match_cache_file) jobs_dataset = UnionDatasetMerge().merge_datasets(matches, jm_dataset, wm_dataset, left_index='UniqueID', right_index='wmaid', left_suffix='jm', right_suffix='wma') jobs_dataset.df = jobreportcleaning.clean_job_reports(jobs_dataset.df)", "import job_node from merge.merge_datasets import UnionDatasetMerge from merge.reportmatching import JobReportMatcher from utils import", "export_job_counts(job_counts_reports, 'parameters_slots_from_pilots', config.outputPaths['jobCountReports']) # Export walltimes walltime_path = os.path.join(config.outputDirectory, 'parameters_slots_from_pilots', config.outputPaths['walltimeReference']) ReferenceWalltimeExporter().export_to_json_file(partitions, walltime_path)", "fig, axes = calibrationreport.jobtypes_over_time_df(job_counts, 'date', 'type') self.report.add_figure(fig, axes, 'job_counts_reference', tight_layout=False) job_counts_reference_summary = job_counts.groupby('type')['count'].sum().reset_index()", "self.add_cpu_efficiency(job_data, start_date, end_date) # Compute calibration parameters node_types = nodeanalysis.extract_node_types(nodes) # Scale the", "cpuefficiency, sampling from analysis import jobreportanalysis from analysis import jobreportcleaning from analysis import", "= pd.concat([reference, from_reports], axis=1) fig, axes = visualization.draw_efficiency_timeseries( {'extracted from job reports': from_reports,", "partitions = job_demand_extractor.extract_job_demands(job_groups) export_parameters('parameters_slots_from_pilots', scaled_nodes_pilots, demands) export_parameters('parameters_slots_from_reports', scaled_nodes_reports, demands) # Sample half of", "calibrationreport.add_jobs_report_section(jm_dataset, self.report) # Write report out to disk self.report.write() def draw_jobslot_usage(self, jm_dataset, core_reference):", "import config, visualization from utils import report as rp from utils.report import ReportBuilder", "jobs_from_reports = job_data.copy() jobs_from_reports[Metric.JOB_TYPE.value] = jobs_from_reports[Metric.JOB_TYPE.value].fillna('unknown') job_counts_reports = jobs_from_reports.groupby(Metric.JOB_TYPE.value).size().reset_index() job_counts_reports.columns = ['type', 'count']", "start_date, end_date) fig, axes = calibrationreport.jobtypes_over_time_df(job_counts, 'date', 'type') self.report.add_figure(fig, axes, 'job_counts_reference', tight_layout=False) job_counts_reference_summary", "from merge.merge_datasets import UnionDatasetMerge from merge.reportmatching import JobReportMatcher from utils import config, visualization", "smaller methods class GridKaCalibration(CalibrationWorkflow): def __init__(self): self.report = ReportBuilder(base_path=config.outputDirectory, filename='calibration-report.md') def run(self): self.report.append('#", "'count'] job_counts_reports['throughput_day'] = job_counts_reports['count'].divide(day_count) export_job_counts(job_counts_reports, 'parameters_slots_from_pilots', config.outputPaths['jobCountReports']) # Export walltimes walltime_path = os.path.join(config.outputDirectory,", "start_date, end_date): efficiency_reference = CPUEfficiencyReferenceImporter(col='cms', output_column='value').import_file( config.inputPaths['CPUEfficiencyReference'], start_date, end_date) efficiency_timeseries, reports_average = cpuefficiency.calculate_efficiencies(job_data,", "= None if 'splitTypes' in config.workflowOptions: split_types = list(map(tuple, config.workflowOptions['splitTypes'])) job_classifier = FilteredJobClassifier(type_split_cols,", "# Match Jobmonitoring and WMArchive job reports matcher = JobReportMatcher(timestamp_tolerance=10, time_grouping_freq='D') matches =", "into smaller methods class GridKaCalibration(CalibrationWorkflow): def __init__(self): self.report = ReportBuilder(base_path=config.outputDirectory, filename='calibration-report.md') def run(self):", "job_classifier = FilteredJobClassifier(type_split_cols, split_types=split_types) job_groups = job_classifier.split(job_data) job_demand_extractor = JobDemandExtractor(self.report, equal_width=False, bin_count=60, cutoff_quantile=0.95,", "workflows.workflowutils import export_job_counts, export_parameters # Todo Split this up into smaller methods class", "calibrationreport.multiple_jobslot_usage( {'Extracted from job reports': jobslots_from_reports, 'Allocated to GridKa CMS pilots': core_reference['cms']}) self.report.add_figure(fig,", "from datetime import datetime import pandas as pd from analysis import calibrationreport, resource_usage,", "self.report.write() def draw_jobslot_usage(self, jm_dataset, core_reference): jobslot_timeseries = resource_usage.calculate_jobslot_usage(jm_dataset.df, jm_dataset.start, jm_dataset.end, start_ts_col=Metric.START_TIME.value, end_ts_col=Metric.STOP_TIME.value, slot_col=Metric.USED_CORES.value)", "from_reports, 'reference from GridKa monitoring': reference}) axes.set_ylabel(\"CPU efficiency (CPU time / wall time)\")", "days'))) fig.set_size_inches(8, 4.5) self.report.add_figure(fig, axes, 'cpu_efficiencies_reference') self.report.append(\"Efficiency from job reports: {} \".format(reports_average)) self.report.append(\"Efficiency", "reports and the Pilot jobs scaled_nodes_pilots = nodeanalysis.scale_site_by_jobslots(node_types, cms_avg_cores) scaled_nodes_reports = nodeanalysis.scale_site_by_jobslots(node_types, avg_jobslots_reports)", "reference = efficiency_reference['value'].resample('12h').mean().rename('reference') reference_mean = efficiency_reference['value'].mean() from_reports = efficiency_timeseries.rename('measured') # cpu_eff = pd.concat([reference,", "{}!\".format(match_cache_file)) # Match Jobmonitoring and WMArchive job reports matcher = JobReportMatcher(timestamp_tolerance=10, time_grouping_freq='D') matches", "end_date) fig, axes = calibrationreport.jobtypes_over_time_df(job_counts, 'date', 'type') self.report.add_figure(fig, axes, 'job_counts_reference', tight_layout=False) job_counts_reference_summary =", "reports_average = cpuefficiency.calculate_efficiencies(job_data, freq='12h') reference = efficiency_reference['value'].resample('12h').mean().rename('reference') reference_mean = efficiency_reference['value'].mean() from_reports = efficiency_timeseries.rename('measured')", "merge.reportmatching import JobReportMatcher from utils import config, visualization from utils import report as", "start_date, end_date) wm_dataset = DatasetImporter(SummarizedWMAImporter(with_files=False)) \\ .import_dataset(config.inputPaths['wma'], start_date, end_date) cached_matches = None use_caching", "sample_demands) # Export job throughputs from analyzed jobs jobs_from_reports = job_data.copy() jobs_from_reports[Metric.JOB_TYPE.value] =", "start_date, end_date) cms_avg_cores = core_df['cms'].mean() avg_jobslots_reports = self.draw_jobslot_usage(jm_dataset, core_df) # Visualize number of", "Import data sets ################## # Timezone correction correct for errors in timestamps of", "report job_counts_reference_summary = self.add_jobs_over_time(start_date, end_date) # CPU Efficiencies self.add_cpu_efficiency(job_data, start_date, end_date) # Compute", "jobs_dataset = UnionDatasetMerge().merge_datasets(matches, jm_dataset, wm_dataset, left_index='UniqueID', right_index='wmaid', left_suffix='jm', right_suffix='wma') jobs_dataset.df = jobreportcleaning.clean_job_reports(jobs_dataset.df) #", "job_counts_reference_summary['count'] / job_counts_reference_summary[ 'count'].sum() job_counts_reference_summary['throughput_day'] = job_counts_reference_summary['count'].divide( (end_date - start_date).days) self.report.append(\"Job throughput from", "frac=0.5, random_state=38728) sampling_report = ReportBuilder(base_path=config.outputDirectory, filename='calibration-report-sampled.md', resource_dir='figures-sampling') job_groups_train = job_classifier.split(reports_train) job_demand_extractor.report = sampling_report", "self.report.append('at {}'.format(time_now)) logging.info(\"Model Calibration run at {}\".format(time_now)) start_date = pd.to_datetime(config.startDate) end_date = pd.to_datetime(config.endDate)", "start_date, end_date) cached_matches = None use_caching = config.cacheDir is not None if use_caching:", "this up into smaller methods class GridKaCalibration(CalibrationWorkflow): def __init__(self): self.report = ReportBuilder(base_path=config.outputDirectory, filename='calibration-report.md')", "ReferenceWalltimeExporter().export_to_json_file(partitions, walltime_path) # Write jobs to report calibrationreport.add_jobs_report_section(jm_dataset, self.report) # Write report out", "/ job_counts_reference_summary[ 'count'].sum() job_counts_reference_summary['throughput_day'] = job_counts_reference_summary['count'].divide( (end_date - start_date).days) self.report.append(\"Job throughput from CMS", "data sets ################## # Timezone correction correct for errors in timestamps of JobMonitoring", "scaled_nodes_reports, demands) # Sample half of the reports, fix random state for reproducibility", "= job_classifier.split(reports_train) job_demand_extractor.report = sampling_report sample_demands, sample_partitions = job_demand_extractor.extract_job_demands(job_groups_train) sampling_report.write() export_parameters('parameters_slots_from_pilots_sampled0.5', scaled_nodes_pilots, sample_demands)", "usecols=[jm_dataset.df.index.name, wm_dataset.df.index.name]) logging.info( \"Loaded {} matches from match cache {}!\".format(cached_matches.shape[0], match_cache_file)) except Exception:", "# Match jobs to nodes matched_jobs = job_node.match_jobs_to_node(jobs_dataset.df, nodes) matched_jobs = jobreportanalysis.add_missing_node_info(matched_jobs, nodes)", "add_jobs_over_time(self, start_date, end_date): self.report.append(\"## Number of jobs completed over time\") job_counts = JobCountImporter().import_file(config.inputPaths['jobCountsReference'],", "logging import os from datetime import datetime import pandas as pd from analysis", "from GridKa monitoring (average {:.2f}%)'.format(reference_mean * 100)]) axes.set_title(\"CPU efficiencies ({}, {} days)\".format(config.runName, (end_date", "{}\".format(time_now)) start_date = pd.to_datetime(config.startDate) end_date = pd.to_datetime(config.endDate) day_count = (end_date - start_date).days self.report.append()", "= self.add_jobs_over_time(start_date, end_date) # CPU Efficiencies self.add_cpu_efficiency(job_data, start_date, end_date) # Compute calibration parameters", "self.report.add_figure(fig, axes, 'cpu_efficiencies_reference') self.report.append(\"Efficiency from job reports: {} \".format(reports_average)) self.report.append(\"Efficiency from GridKa: {}\".format(reference_mean))", "correct for errors in timestamps of JobMonitoring data dataset_importer = DatasetImporter( JMImporter(timezone_correction='Europe/Berlin', hostname_suffix='.gridka.de',", "# Sample half of the reports, fix random state for reproducibility reports_train, reports_test", "pd.read_csv(match_cache_file, usecols=[jm_dataset.df.index.name, wm_dataset.df.index.name]) logging.info( \"Loaded {} matches from match cache {}!\".format(cached_matches.shape[0], match_cache_file)) except", "JobCountImporter from importers.wmaimport import SummarizedWMAImporter from interfaces.workflow import CalibrationWorkflow from merge import job_node", "jm_dataset.start, jm_dataset.end, start_ts_col=Metric.START_TIME.value, end_ts_col=Metric.STOP_TIME.value, slot_col=Metric.USED_CORES.value) jobslots_from_reports = jobslot_timeseries['totalSlots'].resample('s').pad().resample('H').mean() avg_jobslots_reports = jobslots_from_reports.mean() fig, axes", "= nodeanalysis.scale_site_by_jobslots(node_types, cms_avg_cores) scaled_nodes_reports = nodeanalysis.scale_site_by_jobslots(node_types, avg_jobslots_reports) type_split_cols = config.workflowOptions['typeSplitCols'] split_types = None", "{'Extracted from job reports': jobslots_from_reports, 'Allocated to GridKa CMS pilots': core_reference['cms']}) self.report.add_figure(fig, axes,", "core_reference['cms']}) self.report.add_figure(fig, axes, 'jobslot_usage_reference') return avg_jobslots_reports def add_jobs_over_time(self, start_date, end_date): self.report.append(\"## Number of", "'jm-wma-matches.csv') if os.path.isfile(match_cache_file): try: cached_matches = pd.read_csv(match_cache_file, usecols=[jm_dataset.df.index.name, wm_dataset.df.index.name]) logging.info( \"Loaded {} matches", "# Compute calibration parameters node_types = nodeanalysis.extract_node_types(nodes) # Scale the resource environment with", "job reports and the Pilot jobs scaled_nodes_pilots = nodeanalysis.scale_site_by_jobslots(node_types, cms_avg_cores) scaled_nodes_reports = nodeanalysis.scale_site_by_jobslots(node_types,", "logging.info(\"Writing {} matches to file {}\".format(matches.shape[0], match_cache_file)) matches.to_csv(match_cache_file) jobs_dataset = UnionDatasetMerge().merge_datasets(matches, jm_dataset, wm_dataset,", "scaled_nodes_reports = nodeanalysis.scale_site_by_jobslots(node_types, avg_jobslots_reports) type_split_cols = config.workflowOptions['typeSplitCols'] split_types = None if 'splitTypes' in", "avg_jobslots_reports def add_jobs_over_time(self, start_date, end_date): self.report.append(\"## Number of jobs completed over time\") job_counts", "pandas as pd from analysis import calibrationreport, resource_usage, cpuefficiency, sampling from analysis import", "= job_counts_reports['count'].divide(day_count) export_job_counts(job_counts_reports, 'parameters_slots_from_pilots', config.outputPaths['jobCountReports']) # Export walltimes walltime_path = os.path.join(config.outputDirectory, 'parameters_slots_from_pilots', config.outputPaths['walltimeReference'])", "from GridKa monitoring': reference}) axes.set_ylabel(\"CPU efficiency (CPU time / wall time)\") axes.legend(['Extracted from", "# Timezone correction correct for errors in timestamps of JobMonitoring data dataset_importer =", "job_node.match_jobs_to_node(jobs_dataset.df, nodes) matched_jobs = jobreportanalysis.add_missing_node_info(matched_jobs, nodes) jm_dataset.df = jobreportanalysis.add_performance_data(matched_jobs) job_data = jm_dataset.df #", "job reports': from_reports, 'reference from GridKa monitoring': reference}) axes.set_ylabel(\"CPU efficiency (CPU time /", "match_cache_file = os.path.join(config.cacheDir, 'jm-wma-matches.csv') if os.path.isfile(match_cache_file): try: cached_matches = pd.read_csv(match_cache_file, usecols=[jm_dataset.df.index.name, wm_dataset.df.index.name]) logging.info(", "import report as rp from utils.report import ReportBuilder from workflows.workflowutils import export_job_counts, export_parameters", "= ReportBuilder(base_path=config.outputDirectory, filename='calibration-report.md') def run(self): self.report.append('# GridKa Calibration Run') time_now = datetime.now().strftime('%Y-%m-%d, %H:%M:%S')", "end_date) # Compute calibration parameters node_types = nodeanalysis.extract_node_types(nodes) # Scale the resource environment", "resource_usage, cpuefficiency, sampling from analysis import jobreportanalysis from analysis import jobreportcleaning from analysis", "start_date, end_date) # Compute calibration parameters node_types = nodeanalysis.extract_node_types(nodes) # Scale the resource", "nodes) matched_jobs = jobreportanalysis.add_missing_node_info(matched_jobs, nodes) jm_dataset.df = jobreportanalysis.add_performance_data(matched_jobs) job_data = jm_dataset.df # Import", "from workflows.workflowutils import export_job_counts, export_parameters # Todo Split this up into smaller methods", "start_ts_col=Metric.START_TIME.value, end_ts_col=Metric.STOP_TIME.value, slot_col=Metric.USED_CORES.value) jobslots_from_reports = jobslot_timeseries['totalSlots'].resample('s').pad().resample('H').mean() avg_jobslots_reports = jobslots_from_reports.mean() fig, axes = calibrationreport.multiple_jobslot_usage(", "match_cache_file = os.path.join(config.cacheDir, 'jm-wma-matches.csv') logging.info(\"Writing {} matches to file {}\".format(matches.shape[0], match_cache_file)) matches.to_csv(match_cache_file) jobs_dataset", "import export_job_counts, export_parameters # Todo Split this up into smaller methods class GridKaCalibration(CalibrationWorkflow):", "core_df['cms'].mean() avg_jobslots_reports = self.draw_jobslot_usage(jm_dataset, core_df) # Visualize number of jobs in calibration report", "job_demand_extractor.extract_job_demands(job_groups) export_parameters('parameters_slots_from_pilots', scaled_nodes_pilots, demands) export_parameters('parameters_slots_from_reports', scaled_nodes_reports, demands) # Sample half of the reports,", "# Import data sets ################## # Timezone correction correct for errors in timestamps", "(average {:.2f}%)'.format(reference_mean * 100)]) axes.set_title(\"CPU efficiencies ({}, {} days)\".format(config.runName, (end_date - start_date).days)) axes.set_xlim(left=start_date,", "nodeanalysis.add_performance_data(nodes, simulated_cores=config.workflowOptions['coreSimulationMethod'], thread_rate_method=config.workflowOptions['threadPerformanceMethod']) # Match jobs to nodes matched_jobs = job_node.match_jobs_to_node(jobs_dataset.df, nodes) matched_jobs", "jobs_from_reports.groupby(Metric.JOB_TYPE.value).size().reset_index() job_counts_reports.columns = ['type', 'count'] job_counts_reports['throughput_day'] = job_counts_reports['count'].divide(day_count) export_job_counts(job_counts_reports, 'parameters_slots_from_pilots', config.outputPaths['jobCountReports']) # Export", "wm_dataset, use_files=False, previous_matches=cached_matches) if use_caching: match_cache_file = os.path.join(config.cacheDir, 'jm-wma-matches.csv') logging.info(\"Writing {} matches to", "jobslot_timeseries = resource_usage.calculate_jobslot_usage(jm_dataset.df, jm_dataset.start, jm_dataset.end, start_ts_col=Metric.START_TIME.value, end_ts_col=Metric.STOP_TIME.value, slot_col=Metric.USED_CORES.value) jobslots_from_reports = jobslot_timeseries['totalSlots'].resample('s').pad().resample('H').mean() avg_jobslots_reports =", "self.report.append() self.report.append_paragraph(rp.CodeBlock().append(job_counts_reference_summary.to_string())) return job_counts_reference_summary def add_cpu_efficiency(self, job_data, start_date, end_date): efficiency_reference = CPUEfficiencyReferenceImporter(col='cms', output_column='value').import_file(", "if 'splitTypes' in config.workflowOptions: split_types = list(map(tuple, config.workflowOptions['splitTypes'])) job_classifier = FilteredJobClassifier(type_split_cols, split_types=split_types) job_groups", "jobreportanalysis from analysis import jobreportcleaning from analysis import nodeanalysis from analysis.demandextraction import FilteredJobClassifier,", "jobreportcleaning from analysis import nodeanalysis from analysis.demandextraction import FilteredJobClassifier, JobDemandExtractor from data.dataset import", "pd from analysis import calibrationreport, resource_usage, cpuefficiency, sampling from analysis import jobreportanalysis from", "config.outputPaths['jobCountReports']) # Export walltimes walltime_path = os.path.join(config.outputDirectory, 'parameters_slots_from_pilots', config.outputPaths['walltimeReference']) ReferenceWalltimeExporter().export_to_json_file(partitions, walltime_path) # Write", "= JobDemandExtractor(self.report, equal_width=False, bin_count=60, cutoff_quantile=0.95, overflow_agg=config.workflowOptions['overflowAggregationMethod'], additional_job_options=config.workflowOptions['additionalJobOptions'], drop_overflow=config.workflowOptions.get('dropOverflow', False)) demands, partitions = job_demand_extractor.extract_job_demands(job_groups)", "Match jobs to nodes matched_jobs = job_node.match_jobs_to_node(jobs_dataset.df, nodes) matched_jobs = jobreportanalysis.add_missing_node_info(matched_jobs, nodes) jm_dataset.df", "sample_partitions = job_demand_extractor.extract_job_demands(job_groups_train) sampling_report.write() export_parameters('parameters_slots_from_pilots_sampled0.5', scaled_nodes_pilots, sample_demands) export_parameters('parameters_slots_from_reports_sampled0.5', scaled_nodes_reports, sample_demands) # Export job", "config.workflowOptions['splitTypes'])) job_classifier = FilteredJobClassifier(type_split_cols, split_types=split_types) job_groups = job_classifier.split(job_data) job_demand_extractor = JobDemandExtractor(self.report, equal_width=False, bin_count=60,", "job_counts_reports = jobs_from_reports.groupby(Metric.JOB_TYPE.value).size().reset_index() job_counts_reports.columns = ['type', 'count'] job_counts_reports['throughput_day'] = job_counts_reports['count'].divide(day_count) export_job_counts(job_counts_reports, 'parameters_slots_from_pilots', config.outputPaths['jobCountReports'])", "UnionDatasetMerge().merge_datasets(matches, jm_dataset, wm_dataset, left_index='UniqueID', right_index='wmaid', left_suffix='jm', right_suffix='wma') jobs_dataset.df = jobreportcleaning.clean_job_reports(jobs_dataset.df) # Import node", "is not None if use_caching: match_cache_file = os.path.join(config.cacheDir, 'jm-wma-matches.csv') if os.path.isfile(match_cache_file): try: cached_matches", "Calibration run at {}\".format(time_now)) start_date = pd.to_datetime(config.startDate) end_date = pd.to_datetime(config.endDate) day_count = (end_date", "random state for reproducibility reports_train, reports_test = sampling.split_samples(job_data, frac=0.5, random_state=38728) sampling_report = ReportBuilder(base_path=config.outputDirectory,", "sample_demands, sample_partitions = job_demand_extractor.extract_job_demands(job_groups_train) sampling_report.write() export_parameters('parameters_slots_from_pilots_sampled0.5', scaled_nodes_pilots, sample_demands) export_parameters('parameters_slots_from_reports_sampled0.5', scaled_nodes_reports, sample_demands) # Export", "pd.Timedelta('1 days'))) fig.set_size_inches(8, 4.5) self.report.add_figure(fig, axes, 'cpu_efficiencies_reference') self.report.append(\"Efficiency from job reports: {} \".format(reports_average))", "self.report.add_figure(fig, axes, 'jobslot_usage_reference') return avg_jobslots_reports def add_jobs_over_time(self, start_date, end_date): self.report.append(\"## Number of jobs", "= ColumnCoreUsageImporter() core_df = core_importer.import_file(config.inputPaths['coreUsage'], start_date, end_date) cms_avg_cores = core_df['cms'].mean() avg_jobslots_reports = self.draw_jobslot_usage(jm_dataset,", "Export walltimes walltime_path = os.path.join(config.outputDirectory, 'parameters_slots_from_pilots', config.outputPaths['walltimeReference']) ReferenceWalltimeExporter().export_to_json_file(partitions, walltime_path) # Write jobs to", "Exception: logging.warning(\"No match cache found at {}!\".format(match_cache_file)) # Match Jobmonitoring and WMArchive job", "additional information for usage of GridKa site core_importer = ColumnCoreUsageImporter() core_df = core_importer.import_file(config.inputPaths['coreUsage'],", "= job_counts.groupby('type')['count'].sum().reset_index() job_counts_reference_summary.columns = ['type', 'count'] job_counts_reference_summary['share'] = job_counts_reference_summary['count'] / job_counts_reference_summary[ 'count'].sum() job_counts_reference_summary['throughput_day']", "\\nEnd date: {}\".format(start_date, end_date)) # Import data sets ################## # Timezone correction correct", "equal_width=False, bin_count=60, cutoff_quantile=0.95, overflow_agg=config.workflowOptions['overflowAggregationMethod'], additional_job_options=config.workflowOptions['additionalJobOptions'], drop_overflow=config.workflowOptions.get('dropOverflow', False)) demands, partitions = job_demand_extractor.extract_job_demands(job_groups) export_parameters('parameters_slots_from_pilots', scaled_nodes_pilots,", "= ['type', 'count'] job_counts_reference_summary['share'] = job_counts_reference_summary['count'] / job_counts_reference_summary[ 'count'].sum() job_counts_reference_summary['throughput_day'] = job_counts_reference_summary['count'].divide( (end_date", "from importers.wmaimport import SummarizedWMAImporter from interfaces.workflow import CalibrationWorkflow from merge import job_node from", "cache {}!\".format(cached_matches.shape[0], match_cache_file)) except Exception: logging.warning(\"No match cache found at {}!\".format(match_cache_file)) # Match", "= None use_caching = config.cacheDir is not None if use_caching: match_cache_file = os.path.join(config.cacheDir,", "to disk self.report.write() def draw_jobslot_usage(self, jm_dataset, core_reference): jobslot_timeseries = resource_usage.calculate_jobslot_usage(jm_dataset.df, jm_dataset.start, jm_dataset.end, start_ts_col=Metric.START_TIME.value,", "'jobslot_usage_reference') return avg_jobslots_reports def add_jobs_over_time(self, start_date, end_date): self.report.append(\"## Number of jobs completed over", "filename='calibration-report-sampled.md', resource_dir='figures-sampling') job_groups_train = job_classifier.split(reports_train) job_demand_extractor.report = sampling_report sample_demands, sample_partitions = job_demand_extractor.extract_job_demands(job_groups_train) sampling_report.write()", "monitoring': reference}) axes.set_ylabel(\"CPU efficiency (CPU time / wall time)\") axes.legend(['Extracted from job reports", "jobslot_timeseries['totalSlots'].resample('s').pad().resample('H').mean() avg_jobslots_reports = jobslots_from_reports.mean() fig, axes = calibrationreport.multiple_jobslot_usage( {'Extracted from job reports': jobslots_from_reports,", "# Visualize number of jobs in calibration report job_counts_reference_summary = self.add_jobs_over_time(start_date, end_date) #", "fig, axes = calibrationreport.multiple_jobslot_usage( {'Extracted from job reports': jobslots_from_reports, 'Allocated to GridKa CMS", "of the reports, fix random state for reproducibility reports_train, reports_test = sampling.split_samples(job_data, frac=0.5,", "jobs_dataset.df = jobreportcleaning.clean_job_reports(jobs_dataset.df) # Import node information nodes = GridKaNodeDataImporter().import_file(config.inputPaths['nodeInfo']) nodes = nodeanalysis.add_performance_data(nodes,", "right_index='wmaid', left_suffix='jm', right_suffix='wma') jobs_dataset.df = jobreportcleaning.clean_job_reports(jobs_dataset.df) # Import node information nodes = GridKaNodeDataImporter().import_file(config.inputPaths['nodeInfo'])", "return avg_jobslots_reports def add_jobs_over_time(self, start_date, end_date): self.report.append(\"## Number of jobs completed over time\")", "= config.cacheDir is not None if use_caching: match_cache_file = os.path.join(config.cacheDir, 'jm-wma-matches.csv') if os.path.isfile(match_cache_file):", "from utils.report import ReportBuilder from workflows.workflowutils import export_job_counts, export_parameters # Todo Split this", "= os.path.join(config.cacheDir, 'jm-wma-matches.csv') if os.path.isfile(match_cache_file): try: cached_matches = pd.read_csv(match_cache_file, usecols=[jm_dataset.df.index.name, wm_dataset.df.index.name]) logging.info( \"Loaded", "Metric from exporters.datasetexport import ReferenceWalltimeExporter from importers.dataset_import import DatasetImporter from importers.gridkadata import GridKaNodeDataImporter,", "in timestamps of JobMonitoring data dataset_importer = DatasetImporter( JMImporter(timezone_correction='Europe/Berlin', hostname_suffix='.gridka.de', with_files=False)) jm_dataset =", "= os.path.join(config.cacheDir, 'jm-wma-matches.csv') logging.info(\"Writing {} matches to file {}\".format(matches.shape[0], match_cache_file)) matches.to_csv(match_cache_file) jobs_dataset =", "output_column='value').import_file( config.inputPaths['CPUEfficiencyReference'], start_date, end_date) efficiency_timeseries, reports_average = cpuefficiency.calculate_efficiencies(job_data, freq='12h') reference = efficiency_reference['value'].resample('12h').mean().rename('reference') reference_mean", "# cpu_eff = pd.concat([reference, from_reports], axis=1) fig, axes = visualization.draw_efficiency_timeseries( {'extracted from job", "{'extracted from job reports': from_reports, 'reference from GridKa monitoring': reference}) axes.set_ylabel(\"CPU efficiency (CPU", "jobreportanalysis.add_performance_data(matched_jobs) job_data = jm_dataset.df # Import additional information for usage of GridKa site", "Sample half of the reports, fix random state for reproducibility reports_train, reports_test =", "matches = matcher.match_reports(jm_dataset, wm_dataset, use_files=False, previous_matches=cached_matches) if use_caching: match_cache_file = os.path.join(config.cacheDir, 'jm-wma-matches.csv') logging.info(\"Writing", "nodes matched_jobs = job_node.match_jobs_to_node(jobs_dataset.df, nodes) matched_jobs = jobreportanalysis.add_missing_node_info(matched_jobs, nodes) jm_dataset.df = jobreportanalysis.add_performance_data(matched_jobs) job_data", "disk self.report.write() def draw_jobslot_usage(self, jm_dataset, core_reference): jobslot_timeseries = resource_usage.calculate_jobslot_usage(jm_dataset.df, jm_dataset.start, jm_dataset.end, start_ts_col=Metric.START_TIME.value, end_ts_col=Metric.STOP_TIME.value,", "import Metric from exporters.datasetexport import ReferenceWalltimeExporter from importers.dataset_import import DatasetImporter from importers.gridkadata import", "= os.path.join(config.outputDirectory, 'parameters_slots_from_pilots', config.outputPaths['walltimeReference']) ReferenceWalltimeExporter().export_to_json_file(partitions, walltime_path) # Write jobs to report calibrationreport.add_jobs_report_section(jm_dataset, self.report)", "nodes = GridKaNodeDataImporter().import_file(config.inputPaths['nodeInfo']) nodes = nodeanalysis.add_performance_data(nodes, simulated_cores=config.workflowOptions['coreSimulationMethod'], thread_rate_method=config.workflowOptions['threadPerformanceMethod']) # Match jobs to nodes", "= jobreportanalysis.add_performance_data(matched_jobs) job_data = jm_dataset.df # Import additional information for usage of GridKa", "= job_demand_extractor.extract_job_demands(job_groups_train) sampling_report.write() export_parameters('parameters_slots_from_pilots_sampled0.5', scaled_nodes_pilots, sample_demands) export_parameters('parameters_slots_from_reports_sampled0.5', scaled_nodes_reports, sample_demands) # Export job throughputs", "cache found at {}!\".format(match_cache_file)) # Match Jobmonitoring and WMArchive job reports matcher =", "methods class GridKaCalibration(CalibrationWorkflow): def __init__(self): self.report = ReportBuilder(base_path=config.outputDirectory, filename='calibration-report.md') def run(self): self.report.append('# GridKa", "job_counts_reference_summary['count'].divide( (end_date - start_date).days) self.report.append(\"Job throughput from CMS Dashboard:\") self.report.append() self.report.append_paragraph(rp.CodeBlock().append(job_counts_reference_summary.to_string())) return job_counts_reference_summary", "= (end_date - start_date).days self.report.append() self.report.append(\"Start date: {} \\nEnd date: {}\".format(start_date, end_date)) #", "/ wall time)\") axes.legend(['Extracted from job reports (average {:.2f}%)'.format(reports_average * 100), 'Reference from", "CPUEfficiencyReferenceImporter from importers.jmimport import JMImporter from importers.jobcounts import JobCountImporter from importers.wmaimport import SummarizedWMAImporter", "report out to disk self.report.write() def draw_jobslot_usage(self, jm_dataset, core_reference): jobslot_timeseries = resource_usage.calculate_jobslot_usage(jm_dataset.df, jm_dataset.start,", "end_date): self.report.append(\"## Number of jobs completed over time\") job_counts = JobCountImporter().import_file(config.inputPaths['jobCountsReference'], start_date, end_date)", "ReportBuilder(base_path=config.outputDirectory, filename='calibration-report-sampled.md', resource_dir='figures-sampling') job_groups_train = job_classifier.split(reports_train) job_demand_extractor.report = sampling_report sample_demands, sample_partitions = job_demand_extractor.extract_job_demands(job_groups_train)", "job_demand_extractor.report = sampling_report sample_demands, sample_partitions = job_demand_extractor.extract_job_demands(job_groups_train) sampling_report.write() export_parameters('parameters_slots_from_pilots_sampled0.5', scaled_nodes_pilots, sample_demands) export_parameters('parameters_slots_from_reports_sampled0.5', scaled_nodes_reports,", "cpuefficiency.calculate_efficiencies(job_data, freq='12h') reference = efficiency_reference['value'].resample('12h').mean().rename('reference') reference_mean = efficiency_reference['value'].mean() from_reports = efficiency_timeseries.rename('measured') # cpu_eff", "draw_jobslot_usage(self, jm_dataset, core_reference): jobslot_timeseries = resource_usage.calculate_jobslot_usage(jm_dataset.df, jm_dataset.start, jm_dataset.end, start_ts_col=Metric.START_TIME.value, end_ts_col=Metric.STOP_TIME.value, slot_col=Metric.USED_CORES.value) jobslots_from_reports =", "end_date = pd.to_datetime(config.endDate) day_count = (end_date - start_date).days self.report.append() self.report.append(\"Start date: {} \\nEnd", "\\ CPUEfficiencyReferenceImporter from importers.jmimport import JMImporter from importers.jobcounts import JobCountImporter from importers.wmaimport import", "data dataset_importer = DatasetImporter( JMImporter(timezone_correction='Europe/Berlin', hostname_suffix='.gridka.de', with_files=False)) jm_dataset = dataset_importer.import_dataset(config.inputPaths['jm'], start_date, end_date) wm_dataset", "split_types=split_types) job_groups = job_classifier.split(job_data) job_demand_extractor = JobDemandExtractor(self.report, equal_width=False, bin_count=60, cutoff_quantile=0.95, overflow_agg=config.workflowOptions['overflowAggregationMethod'], additional_job_options=config.workflowOptions['additionalJobOptions'], drop_overflow=config.workflowOptions.get('dropOverflow',", "= visualization.draw_efficiency_timeseries( {'extracted from job reports': from_reports, 'reference from GridKa monitoring': reference}) axes.set_ylabel(\"CPU", "nodeanalysis.scale_site_by_jobslots(node_types, cms_avg_cores) scaled_nodes_reports = nodeanalysis.scale_site_by_jobslots(node_types, avg_jobslots_reports) type_split_cols = config.workflowOptions['typeSplitCols'] split_types = None if", "cached_matches = pd.read_csv(match_cache_file, usecols=[jm_dataset.df.index.name, wm_dataset.df.index.name]) logging.info( \"Loaded {} matches from match cache {}!\".format(cached_matches.shape[0],", "file {}\".format(matches.shape[0], match_cache_file)) matches.to_csv(match_cache_file) jobs_dataset = UnionDatasetMerge().merge_datasets(matches, jm_dataset, wm_dataset, left_index='UniqueID', right_index='wmaid', left_suffix='jm', right_suffix='wma')", "JobReportMatcher from utils import config, visualization from utils import report as rp from", "throughputs from analyzed jobs jobs_from_reports = job_data.copy() jobs_from_reports[Metric.JOB_TYPE.value] = jobs_from_reports[Metric.JOB_TYPE.value].fillna('unknown') job_counts_reports = jobs_from_reports.groupby(Metric.JOB_TYPE.value).size().reset_index()", "nodeanalysis from analysis.demandextraction import FilteredJobClassifier, JobDemandExtractor from data.dataset import Metric from exporters.datasetexport import", "CMS Dashboard:\") self.report.append() self.report.append_paragraph(rp.CodeBlock().append(job_counts_reference_summary.to_string())) return job_counts_reference_summary def add_cpu_efficiency(self, job_data, start_date, end_date): efficiency_reference =", "job_node from merge.merge_datasets import UnionDatasetMerge from merge.reportmatching import JobReportMatcher from utils import config,", "time_now = datetime.now().strftime('%Y-%m-%d, %H:%M:%S') self.report.append('at {}'.format(time_now)) logging.info(\"Model Calibration run at {}\".format(time_now)) start_date =", "os.path.join(config.outputDirectory, 'parameters_slots_from_pilots', config.outputPaths['walltimeReference']) ReferenceWalltimeExporter().export_to_json_file(partitions, walltime_path) # Write jobs to report calibrationreport.add_jobs_report_section(jm_dataset, self.report) #", "'parameters_slots_from_pilots', config.outputPaths['walltimeReference']) ReferenceWalltimeExporter().export_to_json_file(partitions, walltime_path) # Write jobs to report calibrationreport.add_jobs_report_section(jm_dataset, self.report) # Write", "efficiencies ({}, {} days)\".format(config.runName, (end_date - start_date).days)) axes.set_xlim(left=start_date, right=(end_date - pd.Timedelta('1 days'))) fig.set_size_inches(8,", "from analysis import calibrationreport, resource_usage, cpuefficiency, sampling from analysis import jobreportanalysis from analysis", "end_date) cached_matches = None use_caching = config.cacheDir is not None if use_caching: match_cache_file", "report calibrationreport.add_jobs_report_section(jm_dataset, self.report) # Write report out to disk self.report.write() def draw_jobslot_usage(self, jm_dataset,", "JobCountImporter().import_file(config.inputPaths['jobCountsReference'], start_date, end_date) fig, axes = calibrationreport.jobtypes_over_time_df(job_counts, 'date', 'type') self.report.add_figure(fig, axes, 'job_counts_reference', tight_layout=False)", "# Import node information nodes = GridKaNodeDataImporter().import_file(config.inputPaths['nodeInfo']) nodes = nodeanalysis.add_performance_data(nodes, simulated_cores=config.workflowOptions['coreSimulationMethod'], thread_rate_method=config.workflowOptions['threadPerformanceMethod']) #", "jm_dataset.df # Import additional information for usage of GridKa site core_importer = ColumnCoreUsageImporter()", "job_counts.groupby('type')['count'].sum().reset_index() job_counts_reference_summary.columns = ['type', 'count'] job_counts_reference_summary['share'] = job_counts_reference_summary['count'] / job_counts_reference_summary[ 'count'].sum() job_counts_reference_summary['throughput_day'] =", "__init__(self): self.report = ReportBuilder(base_path=config.outputDirectory, filename='calibration-report.md') def run(self): self.report.append('# GridKa Calibration Run') time_now =", "self.draw_jobslot_usage(jm_dataset, core_df) # Visualize number of jobs in calibration report job_counts_reference_summary = self.add_jobs_over_time(start_date,", "# Scale the resource environment with both information from the job reports and", "from importers.gridkadata import GridKaNodeDataImporter, ColumnCoreUsageImporter, \\ CPUEfficiencyReferenceImporter from importers.jmimport import JMImporter from importers.jobcounts", "JMImporter from importers.jobcounts import JobCountImporter from importers.wmaimport import SummarizedWMAImporter from interfaces.workflow import CalibrationWorkflow", "from interfaces.workflow import CalibrationWorkflow from merge import job_node from merge.merge_datasets import UnionDatasetMerge from", "left_suffix='jm', right_suffix='wma') jobs_dataset.df = jobreportcleaning.clean_job_reports(jobs_dataset.df) # Import node information nodes = GridKaNodeDataImporter().import_file(config.inputPaths['nodeInfo']) nodes", "= jobreportanalysis.add_missing_node_info(matched_jobs, nodes) jm_dataset.df = jobreportanalysis.add_performance_data(matched_jobs) job_data = jm_dataset.df # Import additional information", "self.report.add_figure(fig, axes, 'job_counts_reference', tight_layout=False) job_counts_reference_summary = job_counts.groupby('type')['count'].sum().reset_index() job_counts_reference_summary.columns = ['type', 'count'] job_counts_reference_summary['share'] =", "add_cpu_efficiency(self, job_data, start_date, end_date): efficiency_reference = CPUEfficiencyReferenceImporter(col='cms', output_column='value').import_file( config.inputPaths['CPUEfficiencyReference'], start_date, end_date) efficiency_timeseries, reports_average" ]
[]
[]
[ "[ int( x ) for x in inputList.split() ] ) print( 'abcList =", "{}'.format( abcList ) ) print( 'YES' if abcList[0] + abcList[1] > abcList[2] else", "input() abcList = sorted( [ int( x ) for x in inputList.split() ]", "python3 inputList = input() abcList = sorted( [ int( x ) for x", "= {}'.format( abcList ) ) print( 'YES' if abcList[0] + abcList[1] > abcList[2]", "for x in inputList.split() ] ) print( 'abcList = {}'.format( abcList ) )", "abcList ) ) print( 'YES' if abcList[0] + abcList[1] > abcList[2] else 'NO'", "'abcList = {}'.format( abcList ) ) print( 'YES' if abcList[0] + abcList[1] >", ") print( 'abcList = {}'.format( abcList ) ) print( 'YES' if abcList[0] +", "= input() abcList = sorted( [ int( x ) for x in inputList.split()", "x in inputList.split() ] ) print( 'abcList = {}'.format( abcList ) ) print(", "int( x ) for x in inputList.split() ] ) print( 'abcList = {}'.format(", "print( 'abcList = {}'.format( abcList ) ) print( 'YES' if abcList[0] + abcList[1]", "sorted( [ int( x ) for x in inputList.split() ] ) print( 'abcList", "#!/usr/bin/env python3 inputList = input() abcList = sorted( [ int( x ) for", "] ) print( 'abcList = {}'.format( abcList ) ) print( 'YES' if abcList[0]", "in inputList.split() ] ) print( 'abcList = {}'.format( abcList ) ) print( 'YES'", ") ) print( 'YES' if abcList[0] + abcList[1] > abcList[2] else 'NO' )", "inputList = input() abcList = sorted( [ int( x ) for x in", "x ) for x in inputList.split() ] ) print( 'abcList = {}'.format( abcList", "inputList.split() ] ) print( 'abcList = {}'.format( abcList ) ) print( 'YES' if", "= sorted( [ int( x ) for x in inputList.split() ] ) print(", "abcList = sorted( [ int( x ) for x in inputList.split() ] )", ") for x in inputList.split() ] ) print( 'abcList = {}'.format( abcList )" ]
[ "redis_driver = redis.StrictRedis(host=redis_host, port=int(redis_port), db=int(redis_db)) return redis_driver def create_neo4j(): url = 'bolt://127.0.0.1:7687' driver", "create_neo4j() hits = get_hits(b_id,atype,predicting_edge,neo) #for the given b, graphsize, what topologies do I", "import GraphDatabase import redis import json import os import time def get_hits(b_id,atype,edge_name,neo4j): cypher", "= GraphDatabase.driver(url, auth=(\"neo4j\", os.environ['NEO4J_PASSWORD'])) return driver def get_topologies(b_id,max_graphs,atype,predicting_edge,red): key=f'MatchingTopologies({b_id},{max_graphs})' print(key) all_topologies = json.loads(red.get(key))", "len(hits) precision = nhits / len(a_s) retres.append( (one_result['nodes'],one_result['edges'],len(a_s),nhits,recall,precision) ) return retres def go(b_id,", "predicting_edge, max_graphs): #Currently, I have not added atype or predicting edge to the", "return [ r['a.id'] for r in rlist ] def run_query(cypherquery,driver): start = time.time()", "gfile: rfile.write('query_id\\tNumberResults\\tNumberTruePostitives\\tRecall\\tPrecision\\n') gfile.write('query_id\\ttopology\\tnodes\\tedges\\n') query_id = 0 for topology in topologies: results = assess_topology(topology,b_id,max_graphs,atype,predicting_edge,hits,red)", "= create_neo4j() hits = get_hits(b_id,atype,predicting_edge,neo) #for the given b, graphsize, what topologies do", "driver = GraphDatabase.driver(url, auth=(\"neo4j\", os.environ['NEO4J_PASSWORD'])) return driver def get_topologies(b_id,max_graphs,atype,predicting_edge,red): key=f'MatchingTopologies({b_id},{max_graphs})' print(key) all_topologies =", "get_topologies(b_id,max_graphs,atype,predicting_edge,red) with open(f'results_{b_id}_{max_graphs}','w') as rfile, open(f'defs_{b_id}_{max_graphs}','w') as gfile: rfile.write('query_id\\tNumberResults\\tNumberTruePostitives\\tRecall\\tPrecision\\n') gfile.write('query_id\\ttopology\\tnodes\\tedges\\n') query_id = 0", "#for the given b, graphsize, what topologies do I need to check on?", "value = redis.get(rkey) if value is None: print(rkey) exit() all_results = json.loads(value) retres", "[ r['a.id'] for r in rlist ] def run_query(cypherquery,driver): start = time.time() with", "run_query(cypherquery,driver): start = time.time() with driver.session() as session: results = session.run(cypherquery) end =", "check on? topologies = get_topologies(b_id,max_graphs,atype,predicting_edge,red) with open(f'results_{b_id}_{max_graphs}','w') as rfile, open(f'defs_{b_id}_{max_graphs}','w') as gfile: rfile.write('query_id\\tNumberResults\\tNumberTruePostitives\\tRecall\\tPrecision\\n')", "def get_hits(b_id,atype,edge_name,neo4j): cypher = f'MATCH (a:{atype})-[:{edge_name}]-(b {{id:\"{b_id}\"}}) RETURN distinct a.id' rlist = run_query(cypher,neo4j)", "I should red = get_redis() neo = create_neo4j() hits = get_hits(b_id,atype,predicting_edge,neo) #for the", "[tuple(x) for x in all_topologies] #return all_topologies def assess_topology(topology,b_id,max_graphs,atype,predicting_edge,hits,redis): rkey = f'MatchResults({b_id},{max_graphs},{topology})' value", "= assess_topology(topology,b_id,max_graphs,atype,predicting_edge,hits,red) for res in results: #yuck yuck clean up gfile.write(f'{query_id}\\t{topology}\\t{res[0]}\\t{res[1]}\\n') rfile.write(f'{query_id}\\t{res[2]}\\t{res[3]}\\t{res[4]}\\t{res[5]}\\n') query_id", "key=f'MatchingTopologies({b_id},{max_graphs})' print(key) all_topologies = json.loads(red.get(key)) return [tuple(x) for x in all_topologies] #return all_topologies", "one_result in all_results: a_s = set(one_result['results']) nhits = len( a_s.intersection(hits) ) recall =", "query_id = 0 for topology in topologies: results = assess_topology(topology,b_id,max_graphs,atype,predicting_edge,hits,red) for res in", "= 4 redis_driver = redis.StrictRedis(host=redis_host, port=int(redis_port), db=int(redis_db)) return redis_driver def create_neo4j(): url =", "GraphDatabase.driver(url, auth=(\"neo4j\", os.environ['NEO4J_PASSWORD'])) return driver def get_topologies(b_id,max_graphs,atype,predicting_edge,red): key=f'MatchingTopologies({b_id},{max_graphs})' print(key) all_topologies = json.loads(red.get(key)) return", "RETURN distinct a.id' rlist = run_query(cypher,neo4j) return [ r['a.id'] for r in rlist", "with driver.session() as session: results = session.run(cypherquery) end = time.time() lr = list(results)", "def get_redis(): redis_host = '127.0.0.1' redis_port = 6767 redis_db = 4 redis_driver =", "session: results = session.run(cypherquery) end = time.time() lr = list(results) print (f' {end-start},", "go(b_id, atype, predicting_edge, max_graphs): #Currently, I have not added atype or predicting edge", "hits = get_hits(b_id,atype,predicting_edge,neo) #for the given b, graphsize, what topologies do I need", "results = assess_topology(topology,b_id,max_graphs,atype,predicting_edge,hits,red) for res in results: #yuck yuck clean up gfile.write(f'{query_id}\\t{topology}\\t{res[0]}\\t{res[1]}\\n') rfile.write(f'{query_id}\\t{res[2]}\\t{res[3]}\\t{res[4]}\\t{res[5]}\\n')", "nhits / len(a_s) retres.append( (one_result['nodes'],one_result['edges'],len(a_s),nhits,recall,precision) ) return retres def go(b_id, atype, predicting_edge, max_graphs):", "predicting edge to the redis keys, but I should red = get_redis() neo", "= session.run(cypherquery) end = time.time() lr = list(results) print (f' {end-start}, {len(lr)}') return", "= run_query(cypher,neo4j) return [ r['a.id'] for r in rlist ] def run_query(cypherquery,driver): start", "max_graphs): #Currently, I have not added atype or predicting edge to the redis", "the given b, graphsize, what topologies do I need to check on? topologies", "neo = create_neo4j() hits = get_hits(b_id,atype,predicting_edge,neo) #for the given b, graphsize, what topologies", "get_hits(b_id,atype,predicting_edge,neo) #for the given b, graphsize, what topologies do I need to check", "start = time.time() with driver.session() as session: results = session.run(cypherquery) end = time.time()", "/ len(a_s) retres.append( (one_result['nodes'],one_result['edges'],len(a_s),nhits,recall,precision) ) return retres def go(b_id, atype, predicting_edge, max_graphs): #Currently,", "db=int(redis_db)) return redis_driver def create_neo4j(): url = 'bolt://127.0.0.1:7687' driver = GraphDatabase.driver(url, auth=(\"neo4j\", os.environ['NEO4J_PASSWORD']))", "or predicting edge to the redis keys, but I should red = get_redis()", "(one_result['nodes'],one_result['edges'],len(a_s),nhits,recall,precision) ) return retres def go(b_id, atype, predicting_edge, max_graphs): #Currently, I have not", "def get_topologies(b_id,max_graphs,atype,predicting_edge,red): key=f'MatchingTopologies({b_id},{max_graphs})' print(key) all_topologies = json.loads(red.get(key)) return [tuple(x) for x in all_topologies]", "driver.session() as session: results = session.run(cypherquery) end = time.time() lr = list(results) print", "return driver def get_topologies(b_id,max_graphs,atype,predicting_edge,red): key=f'MatchingTopologies({b_id},{max_graphs})' print(key) all_topologies = json.loads(red.get(key)) return [tuple(x) for x", "#return all_topologies def assess_topology(topology,b_id,max_graphs,atype,predicting_edge,hits,redis): rkey = f'MatchResults({b_id},{max_graphs},{topology})' value = redis.get(rkey) if value is", "rfile, open(f'defs_{b_id}_{max_graphs}','w') as gfile: rfile.write('query_id\\tNumberResults\\tNumberTruePostitives\\tRecall\\tPrecision\\n') gfile.write('query_id\\ttopology\\tnodes\\tedges\\n') query_id = 0 for topology in topologies:", "(f' {end-start}, {len(lr)}') return lr def get_redis(): redis_host = '127.0.0.1' redis_port = 6767", "keys, but I should red = get_redis() neo = create_neo4j() hits = get_hits(b_id,atype,predicting_edge,neo)", "6767 redis_db = 4 redis_driver = redis.StrictRedis(host=redis_host, port=int(redis_port), db=int(redis_db)) return redis_driver def create_neo4j():", "len(a_s) retres.append( (one_result['nodes'],one_result['edges'],len(a_s),nhits,recall,precision) ) return retres def go(b_id, atype, predicting_edge, max_graphs): #Currently, I", "topologies do I need to check on? topologies = get_topologies(b_id,max_graphs,atype,predicting_edge,red) with open(f'results_{b_id}_{max_graphs}','w') as", "cypher = f'MATCH (a:{atype})-[:{edge_name}]-(b {{id:\"{b_id}\"}}) RETURN distinct a.id' rlist = run_query(cypher,neo4j) return [", "neo4j.v1 import GraphDatabase import redis import json import os import time def get_hits(b_id,atype,edge_name,neo4j):", "assess_topology(topology,b_id,max_graphs,atype,predicting_edge,hits,red) for res in results: #yuck yuck clean up gfile.write(f'{query_id}\\t{topology}\\t{res[0]}\\t{res[1]}\\n') rfile.write(f'{query_id}\\t{res[2]}\\t{res[3]}\\t{res[4]}\\t{res[5]}\\n') query_id +=", "not added atype or predicting edge to the redis keys, but I should", "import time def get_hits(b_id,atype,edge_name,neo4j): cypher = f'MATCH (a:{atype})-[:{edge_name}]-(b {{id:\"{b_id}\"}}) RETURN distinct a.id' rlist", "port=int(redis_port), db=int(redis_db)) return redis_driver def create_neo4j(): url = 'bolt://127.0.0.1:7687' driver = GraphDatabase.driver(url, auth=(\"neo4j\",", "edge to the redis keys, but I should red = get_redis() neo =", "#Currently, I have not added atype or predicting edge to the redis keys,", "(a:{atype})-[:{edge_name}]-(b {{id:\"{b_id}\"}}) RETURN distinct a.id' rlist = run_query(cypher,neo4j) return [ r['a.id'] for r", "os import time def get_hits(b_id,atype,edge_name,neo4j): cypher = f'MATCH (a:{atype})-[:{edge_name}]-(b {{id:\"{b_id}\"}}) RETURN distinct a.id'", "the redis keys, but I should red = get_redis() neo = create_neo4j() hits", "retres = [] for one_result in all_results: a_s = set(one_result['results']) nhits = len(", "nhits / len(hits) precision = nhits / len(a_s) retres.append( (one_result['nodes'],one_result['edges'],len(a_s),nhits,recall,precision) ) return retres", "nhits = len( a_s.intersection(hits) ) recall = nhits / len(hits) precision = nhits", "end = time.time() lr = list(results) print (f' {end-start}, {len(lr)}') return lr def", "redis.get(rkey) if value is None: print(rkey) exit() all_results = json.loads(value) retres = []", "= time.time() with driver.session() as session: results = session.run(cypherquery) end = time.time() lr", "session.run(cypherquery) end = time.time() lr = list(results) print (f' {end-start}, {len(lr)}') return lr", "assess_topology(topology,b_id,max_graphs,atype,predicting_edge,hits,redis): rkey = f'MatchResults({b_id},{max_graphs},{topology})' value = redis.get(rkey) if value is None: print(rkey) exit()", "topology in topologies: results = assess_topology(topology,b_id,max_graphs,atype,predicting_edge,hits,red) for res in results: #yuck yuck clean", "as rfile, open(f'defs_{b_id}_{max_graphs}','w') as gfile: rfile.write('query_id\\tNumberResults\\tNumberTruePostitives\\tRecall\\tPrecision\\n') gfile.write('query_id\\ttopology\\tnodes\\tedges\\n') query_id = 0 for topology in", "but I should red = get_redis() neo = create_neo4j() hits = get_hits(b_id,atype,predicting_edge,neo) #for", "topologies = get_topologies(b_id,max_graphs,atype,predicting_edge,red) with open(f'results_{b_id}_{max_graphs}','w') as rfile, open(f'defs_{b_id}_{max_graphs}','w') as gfile: rfile.write('query_id\\tNumberResults\\tNumberTruePostitives\\tRecall\\tPrecision\\n') gfile.write('query_id\\ttopology\\tnodes\\tedges\\n') query_id", "value is None: print(rkey) exit() all_results = json.loads(value) retres = [] for one_result", "return lr def get_redis(): redis_host = '127.0.0.1' redis_port = 6767 redis_db = 4", "return redis_driver def create_neo4j(): url = 'bolt://127.0.0.1:7687' driver = GraphDatabase.driver(url, auth=(\"neo4j\", os.environ['NEO4J_PASSWORD'])) return", "redis.StrictRedis(host=redis_host, port=int(redis_port), db=int(redis_db)) return redis_driver def create_neo4j(): url = 'bolt://127.0.0.1:7687' driver = GraphDatabase.driver(url,", "given b, graphsize, what topologies do I need to check on? topologies =", "I need to check on? topologies = get_topologies(b_id,max_graphs,atype,predicting_edge,red) with open(f'results_{b_id}_{max_graphs}','w') as rfile, open(f'defs_{b_id}_{max_graphs}','w')", "lr def get_redis(): redis_host = '127.0.0.1' redis_port = 6767 redis_db = 4 redis_driver", "'bolt://127.0.0.1:7687' driver = GraphDatabase.driver(url, auth=(\"neo4j\", os.environ['NEO4J_PASSWORD'])) return driver def get_topologies(b_id,max_graphs,atype,predicting_edge,red): key=f'MatchingTopologies({b_id},{max_graphs})' print(key) all_topologies", "redis_driver def create_neo4j(): url = 'bolt://127.0.0.1:7687' driver = GraphDatabase.driver(url, auth=(\"neo4j\", os.environ['NEO4J_PASSWORD'])) return driver", "open(f'results_{b_id}_{max_graphs}','w') as rfile, open(f'defs_{b_id}_{max_graphs}','w') as gfile: rfile.write('query_id\\tNumberResults\\tNumberTruePostitives\\tRecall\\tPrecision\\n') gfile.write('query_id\\ttopology\\tnodes\\tedges\\n') query_id = 0 for topology", "= [] for one_result in all_results: a_s = set(one_result['results']) nhits = len( a_s.intersection(hits)", "in rlist ] def run_query(cypherquery,driver): start = time.time() with driver.session() as session: results", "def go(b_id, atype, predicting_edge, max_graphs): #Currently, I have not added atype or predicting", "return [tuple(x) for x in all_topologies] #return all_topologies def assess_topology(topology,b_id,max_graphs,atype,predicting_edge,hits,redis): rkey = f'MatchResults({b_id},{max_graphs},{topology})'", "= time.time() lr = list(results) print (f' {end-start}, {len(lr)}') return lr def get_redis():", "if value is None: print(rkey) exit() all_results = json.loads(value) retres = [] for", "[] for one_result in all_results: a_s = set(one_result['results']) nhits = len( a_s.intersection(hits) )", "have not added atype or predicting edge to the redis keys, but I", "time.time() lr = list(results) print (f' {end-start}, {len(lr)}') return lr def get_redis(): redis_host", "on? topologies = get_topologies(b_id,max_graphs,atype,predicting_edge,red) with open(f'results_{b_id}_{max_graphs}','w') as rfile, open(f'defs_{b_id}_{max_graphs}','w') as gfile: rfile.write('query_id\\tNumberResults\\tNumberTruePostitives\\tRecall\\tPrecision\\n') gfile.write('query_id\\ttopology\\tnodes\\tedges\\n')", "= f'MATCH (a:{atype})-[:{edge_name}]-(b {{id:\"{b_id}\"}}) RETURN distinct a.id' rlist = run_query(cypher,neo4j) return [ r['a.id']", "lr = list(results) print (f' {end-start}, {len(lr)}') return lr def get_redis(): redis_host =", "0 for topology in topologies: results = assess_topology(topology,b_id,max_graphs,atype,predicting_edge,hits,red) for res in results: #yuck", "os.environ['NEO4J_PASSWORD'])) return driver def get_topologies(b_id,max_graphs,atype,predicting_edge,red): key=f'MatchingTopologies({b_id},{max_graphs})' print(key) all_topologies = json.loads(red.get(key)) return [tuple(x) for", "topologies: results = assess_topology(topology,b_id,max_graphs,atype,predicting_edge,hits,red) for res in results: #yuck yuck clean up gfile.write(f'{query_id}\\t{topology}\\t{res[0]}\\t{res[1]}\\n')", "all_results = json.loads(value) retres = [] for one_result in all_results: a_s = set(one_result['results'])", "a.id' rlist = run_query(cypher,neo4j) return [ r['a.id'] for r in rlist ] def", "open(f'defs_{b_id}_{max_graphs}','w') as gfile: rfile.write('query_id\\tNumberResults\\tNumberTruePostitives\\tRecall\\tPrecision\\n') gfile.write('query_id\\ttopology\\tnodes\\tedges\\n') query_id = 0 for topology in topologies: results", "set(one_result['results']) nhits = len( a_s.intersection(hits) ) recall = nhits / len(hits) precision =", "for x in all_topologies] #return all_topologies def assess_topology(topology,b_id,max_graphs,atype,predicting_edge,hits,redis): rkey = f'MatchResults({b_id},{max_graphs},{topology})' value =", "atype, predicting_edge, max_graphs): #Currently, I have not added atype or predicting edge to", "= get_topologies(b_id,max_graphs,atype,predicting_edge,red) with open(f'results_{b_id}_{max_graphs}','w') as rfile, open(f'defs_{b_id}_{max_graphs}','w') as gfile: rfile.write('query_id\\tNumberResults\\tNumberTruePostitives\\tRecall\\tPrecision\\n') gfile.write('query_id\\ttopology\\tnodes\\tedges\\n') query_id =", "for res in results: #yuck yuck clean up gfile.write(f'{query_id}\\t{topology}\\t{res[0]}\\t{res[1]}\\n') rfile.write(f'{query_id}\\t{res[2]}\\t{res[3]}\\t{res[4]}\\t{res[5]}\\n') query_id += 1", "time def get_hits(b_id,atype,edge_name,neo4j): cypher = f'MATCH (a:{atype})-[:{edge_name}]-(b {{id:\"{b_id}\"}}) RETURN distinct a.id' rlist =", "list(results) print (f' {end-start}, {len(lr)}') return lr def get_redis(): redis_host = '127.0.0.1' redis_port", "redis import json import os import time def get_hits(b_id,atype,edge_name,neo4j): cypher = f'MATCH (a:{atype})-[:{edge_name}]-(b", "r in rlist ] def run_query(cypherquery,driver): start = time.time() with driver.session() as session:", "{len(lr)}') return lr def get_redis(): redis_host = '127.0.0.1' redis_port = 6767 redis_db =", "'127.0.0.1' redis_port = 6767 redis_db = 4 redis_driver = redis.StrictRedis(host=redis_host, port=int(redis_port), db=int(redis_db)) return", "def assess_topology(topology,b_id,max_graphs,atype,predicting_edge,hits,redis): rkey = f'MatchResults({b_id},{max_graphs},{topology})' value = redis.get(rkey) if value is None: print(rkey)", "with open(f'results_{b_id}_{max_graphs}','w') as rfile, open(f'defs_{b_id}_{max_graphs}','w') as gfile: rfile.write('query_id\\tNumberResults\\tNumberTruePostitives\\tRecall\\tPrecision\\n') gfile.write('query_id\\ttopology\\tnodes\\tedges\\n') query_id = 0 for", "in all_topologies] #return all_topologies def assess_topology(topology,b_id,max_graphs,atype,predicting_edge,hits,redis): rkey = f'MatchResults({b_id},{max_graphs},{topology})' value = redis.get(rkey) if", "print(key) all_topologies = json.loads(red.get(key)) return [tuple(x) for x in all_topologies] #return all_topologies def", "results = session.run(cypherquery) end = time.time() lr = list(results) print (f' {end-start}, {len(lr)}')", "b, graphsize, what topologies do I need to check on? topologies = get_topologies(b_id,max_graphs,atype,predicting_edge,red)", "= json.loads(red.get(key)) return [tuple(x) for x in all_topologies] #return all_topologies def assess_topology(topology,b_id,max_graphs,atype,predicting_edge,hits,redis): rkey", "red = get_redis() neo = create_neo4j() hits = get_hits(b_id,atype,predicting_edge,neo) #for the given b,", "= '127.0.0.1' redis_port = 6767 redis_db = 4 redis_driver = redis.StrictRedis(host=redis_host, port=int(redis_port), db=int(redis_db))", "all_topologies def assess_topology(topology,b_id,max_graphs,atype,predicting_edge,hits,redis): rkey = f'MatchResults({b_id},{max_graphs},{topology})' value = redis.get(rkey) if value is None:", "import json import os import time def get_hits(b_id,atype,edge_name,neo4j): cypher = f'MATCH (a:{atype})-[:{edge_name}]-(b {{id:\"{b_id}\"}})", "= nhits / len(a_s) retres.append( (one_result['nodes'],one_result['edges'],len(a_s),nhits,recall,precision) ) return retres def go(b_id, atype, predicting_edge,", "I have not added atype or predicting edge to the redis keys, but", "redis keys, but I should red = get_redis() neo = create_neo4j() hits =", "should red = get_redis() neo = create_neo4j() hits = get_hits(b_id,atype,predicting_edge,neo) #for the given", ") recall = nhits / len(hits) precision = nhits / len(a_s) retres.append( (one_result['nodes'],one_result['edges'],len(a_s),nhits,recall,precision)", "as gfile: rfile.write('query_id\\tNumberResults\\tNumberTruePostitives\\tRecall\\tPrecision\\n') gfile.write('query_id\\ttopology\\tnodes\\tedges\\n') query_id = 0 for topology in topologies: results =", "driver def get_topologies(b_id,max_graphs,atype,predicting_edge,red): key=f'MatchingTopologies({b_id},{max_graphs})' print(key) all_topologies = json.loads(red.get(key)) return [tuple(x) for x in", "= redis.StrictRedis(host=redis_host, port=int(redis_port), db=int(redis_db)) return redis_driver def create_neo4j(): url = 'bolt://127.0.0.1:7687' driver =", "create_neo4j(): url = 'bolt://127.0.0.1:7687' driver = GraphDatabase.driver(url, auth=(\"neo4j\", os.environ['NEO4J_PASSWORD'])) return driver def get_topologies(b_id,max_graphs,atype,predicting_edge,red):", "exit() all_results = json.loads(value) retres = [] for one_result in all_results: a_s =", "len( a_s.intersection(hits) ) recall = nhits / len(hits) precision = nhits / len(a_s)", "atype or predicting edge to the redis keys, but I should red =", "graphsize, what topologies do I need to check on? topologies = get_topologies(b_id,max_graphs,atype,predicting_edge,red) with", "<reponame>TranslatorIIPrototypes/robo-commons<filename>scripts/AQP_byPath/collect_results.py from neo4j.v1 import GraphDatabase import redis import json import os import time", "for one_result in all_results: a_s = set(one_result['results']) nhits = len( a_s.intersection(hits) ) recall", "from neo4j.v1 import GraphDatabase import redis import json import os import time def", "= 'bolt://127.0.0.1:7687' driver = GraphDatabase.driver(url, auth=(\"neo4j\", os.environ['NEO4J_PASSWORD'])) return driver def get_topologies(b_id,max_graphs,atype,predicting_edge,red): key=f'MatchingTopologies({b_id},{max_graphs})' print(key)", "rfile.write('query_id\\tNumberResults\\tNumberTruePostitives\\tRecall\\tPrecision\\n') gfile.write('query_id\\ttopology\\tnodes\\tedges\\n') query_id = 0 for topology in topologies: results = assess_topology(topology,b_id,max_graphs,atype,predicting_edge,hits,red) for", "print (f' {end-start}, {len(lr)}') return lr def get_redis(): redis_host = '127.0.0.1' redis_port =", "= 6767 redis_db = 4 redis_driver = redis.StrictRedis(host=redis_host, port=int(redis_port), db=int(redis_db)) return redis_driver def", "in topologies: results = assess_topology(topology,b_id,max_graphs,atype,predicting_edge,hits,red) for res in results: #yuck yuck clean up", "= get_redis() neo = create_neo4j() hits = get_hits(b_id,atype,predicting_edge,neo) #for the given b, graphsize,", "import redis import json import os import time def get_hits(b_id,atype,edge_name,neo4j): cypher = f'MATCH", "run_query(cypher,neo4j) return [ r['a.id'] for r in rlist ] def run_query(cypherquery,driver): start =", "rkey = f'MatchResults({b_id},{max_graphs},{topology})' value = redis.get(rkey) if value is None: print(rkey) exit() all_results", "a_s = set(one_result['results']) nhits = len( a_s.intersection(hits) ) recall = nhits / len(hits)", "f'MatchResults({b_id},{max_graphs},{topology})' value = redis.get(rkey) if value is None: print(rkey) exit() all_results = json.loads(value)", "is None: print(rkey) exit() all_results = json.loads(value) retres = [] for one_result in", "distinct a.id' rlist = run_query(cypher,neo4j) return [ r['a.id'] for r in rlist ]", "recall = nhits / len(hits) precision = nhits / len(a_s) retres.append( (one_result['nodes'],one_result['edges'],len(a_s),nhits,recall,precision) )", "redis_port = 6767 redis_db = 4 redis_driver = redis.StrictRedis(host=redis_host, port=int(redis_port), db=int(redis_db)) return redis_driver", "= list(results) print (f' {end-start}, {len(lr)}') return lr def get_redis(): redis_host = '127.0.0.1'", "r['a.id'] for r in rlist ] def run_query(cypherquery,driver): start = time.time() with driver.session()", "time.time() with driver.session() as session: results = session.run(cypherquery) end = time.time() lr =", "/ len(hits) precision = nhits / len(a_s) retres.append( (one_result['nodes'],one_result['edges'],len(a_s),nhits,recall,precision) ) return retres def", "get_redis(): redis_host = '127.0.0.1' redis_port = 6767 redis_db = 4 redis_driver = redis.StrictRedis(host=redis_host,", "#yuck yuck clean up gfile.write(f'{query_id}\\t{topology}\\t{res[0]}\\t{res[1]}\\n') rfile.write(f'{query_id}\\t{res[2]}\\t{res[3]}\\t{res[4]}\\t{res[5]}\\n') query_id += 1 if __name__ == '__main__':", "] def run_query(cypherquery,driver): start = time.time() with driver.session() as session: results = session.run(cypherquery)", "GraphDatabase import redis import json import os import time def get_hits(b_id,atype,edge_name,neo4j): cypher =", "x in all_topologies] #return all_topologies def assess_topology(topology,b_id,max_graphs,atype,predicting_edge,hits,redis): rkey = f'MatchResults({b_id},{max_graphs},{topology})' value = redis.get(rkey)", "need to check on? topologies = get_topologies(b_id,max_graphs,atype,predicting_edge,red) with open(f'results_{b_id}_{max_graphs}','w') as rfile, open(f'defs_{b_id}_{max_graphs}','w') as", "f'MATCH (a:{atype})-[:{edge_name}]-(b {{id:\"{b_id}\"}}) RETURN distinct a.id' rlist = run_query(cypher,neo4j) return [ r['a.id'] for", "= get_hits(b_id,atype,predicting_edge,neo) #for the given b, graphsize, what topologies do I need to", "all_topologies = json.loads(red.get(key)) return [tuple(x) for x in all_topologies] #return all_topologies def assess_topology(topology,b_id,max_graphs,atype,predicting_edge,hits,redis):", "None: print(rkey) exit() all_results = json.loads(value) retres = [] for one_result in all_results:", "= nhits / len(hits) precision = nhits / len(a_s) retres.append( (one_result['nodes'],one_result['edges'],len(a_s),nhits,recall,precision) ) return", "{{id:\"{b_id}\"}}) RETURN distinct a.id' rlist = run_query(cypher,neo4j) return [ r['a.id'] for r in", "all_topologies] #return all_topologies def assess_topology(topology,b_id,max_graphs,atype,predicting_edge,hits,redis): rkey = f'MatchResults({b_id},{max_graphs},{topology})' value = redis.get(rkey) if value", "a_s.intersection(hits) ) recall = nhits / len(hits) precision = nhits / len(a_s) retres.append(", ") return retres def go(b_id, atype, predicting_edge, max_graphs): #Currently, I have not added", "results: #yuck yuck clean up gfile.write(f'{query_id}\\t{topology}\\t{res[0]}\\t{res[1]}\\n') rfile.write(f'{query_id}\\t{res[2]}\\t{res[3]}\\t{res[4]}\\t{res[5]}\\n') query_id += 1 if __name__ ==", "get_hits(b_id,atype,edge_name,neo4j): cypher = f'MATCH (a:{atype})-[:{edge_name}]-(b {{id:\"{b_id}\"}}) RETURN distinct a.id' rlist = run_query(cypher,neo4j) return", "rlist ] def run_query(cypherquery,driver): start = time.time() with driver.session() as session: results =", "= set(one_result['results']) nhits = len( a_s.intersection(hits) ) recall = nhits / len(hits) precision", "for topology in topologies: results = assess_topology(topology,b_id,max_graphs,atype,predicting_edge,hits,red) for res in results: #yuck yuck", "json.loads(value) retres = [] for one_result in all_results: a_s = set(one_result['results']) nhits =", "precision = nhits / len(a_s) retres.append( (one_result['nodes'],one_result['edges'],len(a_s),nhits,recall,precision) ) return retres def go(b_id, atype,", "import os import time def get_hits(b_id,atype,edge_name,neo4j): cypher = f'MATCH (a:{atype})-[:{edge_name}]-(b {{id:\"{b_id}\"}}) RETURN distinct", "get_redis() neo = create_neo4j() hits = get_hits(b_id,atype,predicting_edge,neo) #for the given b, graphsize, what", "to check on? topologies = get_topologies(b_id,max_graphs,atype,predicting_edge,red) with open(f'results_{b_id}_{max_graphs}','w') as rfile, open(f'defs_{b_id}_{max_graphs}','w') as gfile:", "all_results: a_s = set(one_result['results']) nhits = len( a_s.intersection(hits) ) recall = nhits /", "gfile.write('query_id\\ttopology\\tnodes\\tedges\\n') query_id = 0 for topology in topologies: results = assess_topology(topology,b_id,max_graphs,atype,predicting_edge,hits,red) for res", "retres def go(b_id, atype, predicting_edge, max_graphs): #Currently, I have not added atype or", "json import os import time def get_hits(b_id,atype,edge_name,neo4j): cypher = f'MATCH (a:{atype})-[:{edge_name}]-(b {{id:\"{b_id}\"}}) RETURN", "def run_query(cypherquery,driver): start = time.time() with driver.session() as session: results = session.run(cypherquery) end", "= 0 for topology in topologies: results = assess_topology(topology,b_id,max_graphs,atype,predicting_edge,hits,red) for res in results:", "as session: results = session.run(cypherquery) end = time.time() lr = list(results) print (f'", "in all_results: a_s = set(one_result['results']) nhits = len( a_s.intersection(hits) ) recall = nhits", "json.loads(red.get(key)) return [tuple(x) for x in all_topologies] #return all_topologies def assess_topology(topology,b_id,max_graphs,atype,predicting_edge,hits,redis): rkey =", "= f'MatchResults({b_id},{max_graphs},{topology})' value = redis.get(rkey) if value is None: print(rkey) exit() all_results =", "= redis.get(rkey) if value is None: print(rkey) exit() all_results = json.loads(value) retres =", "url = 'bolt://127.0.0.1:7687' driver = GraphDatabase.driver(url, auth=(\"neo4j\", os.environ['NEO4J_PASSWORD'])) return driver def get_topologies(b_id,max_graphs,atype,predicting_edge,red): key=f'MatchingTopologies({b_id},{max_graphs})'", "to the redis keys, but I should red = get_redis() neo = create_neo4j()", "what topologies do I need to check on? topologies = get_topologies(b_id,max_graphs,atype,predicting_edge,red) with open(f'results_{b_id}_{max_graphs}','w')", "return retres def go(b_id, atype, predicting_edge, max_graphs): #Currently, I have not added atype", "auth=(\"neo4j\", os.environ['NEO4J_PASSWORD'])) return driver def get_topologies(b_id,max_graphs,atype,predicting_edge,red): key=f'MatchingTopologies({b_id},{max_graphs})' print(key) all_topologies = json.loads(red.get(key)) return [tuple(x)", "= len( a_s.intersection(hits) ) recall = nhits / len(hits) precision = nhits /", "rlist = run_query(cypher,neo4j) return [ r['a.id'] for r in rlist ] def run_query(cypherquery,driver):", "retres.append( (one_result['nodes'],one_result['edges'],len(a_s),nhits,recall,precision) ) return retres def go(b_id, atype, predicting_edge, max_graphs): #Currently, I have", "def create_neo4j(): url = 'bolt://127.0.0.1:7687' driver = GraphDatabase.driver(url, auth=(\"neo4j\", os.environ['NEO4J_PASSWORD'])) return driver def", "in results: #yuck yuck clean up gfile.write(f'{query_id}\\t{topology}\\t{res[0]}\\t{res[1]}\\n') rfile.write(f'{query_id}\\t{res[2]}\\t{res[3]}\\t{res[4]}\\t{res[5]}\\n') query_id += 1 if __name__", "res in results: #yuck yuck clean up gfile.write(f'{query_id}\\t{topology}\\t{res[0]}\\t{res[1]}\\n') rfile.write(f'{query_id}\\t{res[2]}\\t{res[3]}\\t{res[4]}\\t{res[5]}\\n') query_id += 1 if", "do I need to check on? topologies = get_topologies(b_id,max_graphs,atype,predicting_edge,red) with open(f'results_{b_id}_{max_graphs}','w') as rfile,", "redis_db = 4 redis_driver = redis.StrictRedis(host=redis_host, port=int(redis_port), db=int(redis_db)) return redis_driver def create_neo4j(): url", "yuck clean up gfile.write(f'{query_id}\\t{topology}\\t{res[0]}\\t{res[1]}\\n') rfile.write(f'{query_id}\\t{res[2]}\\t{res[3]}\\t{res[4]}\\t{res[5]}\\n') query_id += 1 if __name__ == '__main__': go('MONDO:0005136','chemical_substance','treats',100000)", "redis_host = '127.0.0.1' redis_port = 6767 redis_db = 4 redis_driver = redis.StrictRedis(host=redis_host, port=int(redis_port),", "added atype or predicting edge to the redis keys, but I should red", "= json.loads(value) retres = [] for one_result in all_results: a_s = set(one_result['results']) nhits", "4 redis_driver = redis.StrictRedis(host=redis_host, port=int(redis_port), db=int(redis_db)) return redis_driver def create_neo4j(): url = 'bolt://127.0.0.1:7687'", "for r in rlist ] def run_query(cypherquery,driver): start = time.time() with driver.session() as", "get_topologies(b_id,max_graphs,atype,predicting_edge,red): key=f'MatchingTopologies({b_id},{max_graphs})' print(key) all_topologies = json.loads(red.get(key)) return [tuple(x) for x in all_topologies] #return", "print(rkey) exit() all_results = json.loads(value) retres = [] for one_result in all_results: a_s", "{end-start}, {len(lr)}') return lr def get_redis(): redis_host = '127.0.0.1' redis_port = 6767 redis_db" ]
[ "if port is not None: doit = True cfg[\"api_port\"] = port if username", "= <PASSWORD> doit = True if doit: data.client.config(\"experimental/cluster\", name, {\"config\": cfg}) else: click.echo(\"Please", "configurations to be set.\") @delete.command(\"cluster\") @click.argument('name') @click.pass_obj def delete_cluster(data, name): \"\"\"Delete cluster.\"\"\" data.client.delete(\"experimental/cluster\",", "server, port, username, password): \"\"\"Set cluster configuration.\"\"\" cfg = {\"name\": name} doit =", "username is not None: doit = True cfg[\"username\"] = username if password: pass1", "clusters is None: return columns = (\"name\", \"api_server\", \"api_port\", \"username\") output.list(columns, clusters) @show_cluster.command()", "cfg = {\"name\": name, \"api_server\": server, \"api_port\": port, \"username\": username, \"password\": <PASSWORD>} data.client.request(\"experimental/debug\",", "= True cfg[\"username\"] = username if password: pass1 = click.prompt(\"Password\", hide_input=True) pass2 =", "\"\"\"Show clusters.\"\"\" if ctx.invoked_subcommand is not None: return clusters = data.client.list(\"experimental/cluster\", \"cluster\") if", "detail(data, id_or_name): \"\"\"Show cluster detail.\"\"\" cluster = data.client.show(\"experimental/cluster\", \"cluster\", id_or_name) if not cluster:", "prog.cli import request from prog.cli import set from prog.cli import unset from prog.cli", "prog.cli import show from prog import client from prog import output from prog", "\"username\": username, \"password\": <PASSWORD>} data.client.create(\"experimental/cluster\", {\"config\": cfg}) @set.command(\"cluster\") @click.argument('name') @click.option('--server', help=\"Set API server.\")", "if pass1 != pass2: click.echo(\"Passwords do not match\") return cfg[\"password\"] = <PASSWORD> doit", "import unset from prog.cli import show from prog import client from prog import", "= click.prompt(\"Confirm Password\", hide_input=True) if pass1 != pass2: click.echo(\"Passwords do not match\") return", "click.echo(\"Passwords do not match\") return cfg = {\"name\": name, \"api_server\": server, \"api_port\": port,", "from prog import client from prog import output from prog import utils @show.group(\"cluster\",", "prog.cli import delete from prog.cli import request from prog.cli import set from prog.cli", "'--username', help=\"Set username.\") @click.option(\"-p\", \"--password\", is_flag=True, help=\"Set password.\") @click.pass_obj def set_cluster(data, name, server,", "= server if port is not None: doit = True cfg[\"api_port\"] = port", "prog.cli import create from prog.cli import delete from prog.cli import request from prog.cli", "server if port is not None: doit = True cfg[\"api_port\"] = port if", "return cfg[\"password\"] = <PASSWORD> doit = True if doit: data.client.config(\"experimental/cluster\", name, {\"config\": cfg})", "@click.argument('name') @click.option('--server', help=\"Set API server.\") @click.option('--port', type=int, help=\"Set API server port.\") @click.option('-u', '--username',", "username): \"\"\"test cluster.\"\"\" pass1 = click.prompt(\"User Password\", hide_input=True) cfg = {\"name\": name, \"api_server\":", "@request.group('cluster') @click.pass_obj def request_cluster(data): \"\"\"Request cluster\"\"\" @request_cluster.command(\"test\") @click.argument('name') @click.argument('server') @click.argument('port', type=int) @click.argument('username') @click.pass_obj", "import output from prog import utils @show.group(\"cluster\", invoke_without_command=True) @click.pass_obj @click.pass_context def show_cluster(ctx, data):", "port, username): \"\"\"test cluster.\"\"\" pass1 = click.prompt(\"User Password\", hide_input=True) cfg = {\"name\": name,", "prog.cli import unset from prog.cli import show from prog import client from prog", "cfg[\"api_port\"] = port if username is not None: doit = True cfg[\"username\"] =", "test_cluster(data, name, server, port, username): \"\"\"test cluster.\"\"\" pass1 = click.prompt(\"User Password\", hide_input=True) cfg", "not None: return clusters = data.client.list(\"experimental/cluster\", \"cluster\") if clusters is None: return columns", "!= pass2: click.echo(\"Passwords do not match\") return cfg[\"password\"] = <PASSWORD> doit = True", "cluster.\"\"\" pass1 = click.prompt(\"User Password\", hide_input=True) cfg = {\"name\": name, \"api_server\": server, \"api_port\":", "@click.argument('server') @click.argument('port', type=int) @click.argument('username') @click.pass_obj def create_cluster(data, name, server, port, username): \"\"\"Create cluster.\"\"\"", "prog.cli import set from prog.cli import unset from prog.cli import show from prog", "click.prompt(\"User Password\", hide_input=True) cfg = {\"name\": name, \"api_server\": server, \"api_port\": port, \"username\": username,", "= (\"name\", \"api_server\", \"api_port\", \"username\") output.show(columns, cluster) @create.command(\"cluster\") @click.argument('name') @click.argument('server') @click.argument('port', type=int) @click.argument('username')", "\"api_server\": server, \"api_port\": port, \"username\": username, \"password\": <PASSWORD>} data.client.create(\"experimental/cluster\", {\"config\": cfg}) @set.command(\"cluster\") @click.argument('name')", "cluster\"\"\" @request_cluster.command(\"test\") @click.argument('name') @click.argument('server') @click.argument('port', type=int) @click.argument('username') @click.pass_obj def test_cluster(data, name, server, port,", "doit: data.client.config(\"experimental/cluster\", name, {\"config\": cfg}) else: click.echo(\"Please specify configurations to be set.\") @delete.command(\"cluster\")", "\"api_port\", \"username\") output.list(columns, clusters) @show_cluster.command() @click.argument(\"id_or_name\") @click.pass_obj def detail(data, id_or_name): \"\"\"Show cluster detail.\"\"\"", "@click.pass_obj def detail(data, id_or_name): \"\"\"Show cluster detail.\"\"\" cluster = data.client.show(\"experimental/cluster\", \"cluster\", id_or_name) if", "pass1 != pass2: click.echo(\"Passwords do not match\") return cfg = {\"name\": name, \"api_server\":", "{\"config\": cfg}) else: click.echo(\"Please specify configurations to be set.\") @delete.command(\"cluster\") @click.argument('name') @click.pass_obj def", "doit = True cfg[\"username\"] = username if password: pass1 = click.prompt(\"Password\", hide_input=True) pass2", "\"username\") output.list(columns, clusters) @show_cluster.command() @click.argument(\"id_or_name\") @click.pass_obj def detail(data, id_or_name): \"\"\"Show cluster detail.\"\"\" cluster", "@request_cluster.command(\"test\") @click.argument('name') @click.argument('server') @click.argument('port', type=int) @click.argument('username') @click.pass_obj def test_cluster(data, name, server, port, username):", "\"cluster\", id_or_name) if not cluster: return columns = (\"name\", \"api_server\", \"api_port\", \"username\") output.show(columns,", "be set.\") @delete.command(\"cluster\") @click.argument('name') @click.pass_obj def delete_cluster(data, name): \"\"\"Delete cluster.\"\"\" data.client.delete(\"experimental/cluster\", name) @request.group('cluster')", "= port if username is not None: doit = True cfg[\"username\"] = username", "None: doit = True cfg[\"username\"] = username if password: pass1 = click.prompt(\"Password\", hide_input=True)", "import show from prog import client from prog import output from prog import", "data.client.show(\"experimental/cluster\", \"cluster\", id_or_name) if not cluster: return columns = (\"name\", \"api_server\", \"api_port\", \"username\")", "None: doit = True cfg[\"api_server\"] = server if port is not None: doit", "<gh_stars>10-100 import click from prog.cli import cli from prog.cli import create from prog.cli", "click.prompt(\"Confirm User Password\", hide_input=True) if pass1 != pass2: click.echo(\"Passwords do not match\") return", "import utils @show.group(\"cluster\", invoke_without_command=True) @click.pass_obj @click.pass_context def show_cluster(ctx, data): \"\"\"Show clusters.\"\"\" if ctx.invoked_subcommand", "cluster.\"\"\" data.client.delete(\"experimental/cluster\", name) @request.group('cluster') @click.pass_obj def request_cluster(data): \"\"\"Request cluster\"\"\" @request_cluster.command(\"test\") @click.argument('name') @click.argument('server') @click.argument('port',", "pass1 = click.prompt(\"User Password\", hide_input=True) cfg = {\"name\": name, \"api_server\": server, \"api_port\": port,", "= True cfg[\"api_server\"] = server if port is not None: doit = True", "hide_input=True) cfg = {\"name\": name, \"api_server\": server, \"api_port\": port, \"username\": username, \"password\": <PASSWORD>}", "cfg}) else: click.echo(\"Please specify configurations to be set.\") @delete.command(\"cluster\") @click.argument('name') @click.pass_obj def delete_cluster(data,", "cfg[\"password\"] = <PASSWORD> doit = True if doit: data.client.config(\"experimental/cluster\", name, {\"config\": cfg}) else:", "None: return columns = (\"name\", \"api_server\", \"api_port\", \"username\") output.list(columns, clusters) @show_cluster.command() @click.argument(\"id_or_name\") @click.pass_obj", "data): \"\"\"Show clusters.\"\"\" if ctx.invoked_subcommand is not None: return clusters = data.client.list(\"experimental/cluster\", \"cluster\")", "click.prompt(\"Confirm Password\", hide_input=True) if pass1 != pass2: click.echo(\"Passwords do not match\") return cfg[\"password\"]", "\"--password\", is_flag=True, help=\"Set password.\") @click.pass_obj def set_cluster(data, name, server, port, username, password): \"\"\"Set", "User Password\", hide_input=True) if pass1 != pass2: click.echo(\"Passwords do not match\") return cfg", "Password\", hide_input=True) cfg = {\"name\": name, \"api_server\": server, \"api_port\": port, \"username\": username, \"password\":", "not None: doit = True cfg[\"api_server\"] = server if port is not None:", "@click.pass_obj def request_cluster(data): \"\"\"Request cluster\"\"\" @request_cluster.command(\"test\") @click.argument('name') @click.argument('server') @click.argument('port', type=int) @click.argument('username') @click.pass_obj def", "port, username): \"\"\"Create cluster.\"\"\" pass1 = click.prompt(\"User Password\", hide_input=True) pass2 = click.prompt(\"Confirm User", "= data.client.list(\"experimental/cluster\", \"cluster\") if clusters is None: return columns = (\"name\", \"api_server\", \"api_port\",", "not None: doit = True cfg[\"api_port\"] = port if username is not None:", "username, password): \"\"\"Set cluster configuration.\"\"\" cfg = {\"name\": name} doit = False if", "@create.command(\"cluster\") @click.argument('name') @click.argument('server') @click.argument('port', type=int) @click.argument('username') @click.pass_obj def create_cluster(data, name, server, port, username):", "\"username\") output.show(columns, cluster) @create.command(\"cluster\") @click.argument('name') @click.argument('server') @click.argument('port', type=int) @click.argument('username') @click.pass_obj def create_cluster(data, name,", "id_or_name) if not cluster: return columns = (\"name\", \"api_server\", \"api_port\", \"username\") output.show(columns, cluster)", "columns = (\"name\", \"api_server\", \"api_port\", \"username\") output.show(columns, cluster) @create.command(\"cluster\") @click.argument('name') @click.argument('server') @click.argument('port', type=int)", "prog import utils @show.group(\"cluster\", invoke_without_command=True) @click.pass_obj @click.pass_context def show_cluster(ctx, data): \"\"\"Show clusters.\"\"\" if", "def detail(data, id_or_name): \"\"\"Show cluster detail.\"\"\" cluster = data.client.show(\"experimental/cluster\", \"cluster\", id_or_name) if not", "= {\"name\": name} doit = False if server is not None: doit =", "= username if password: pass1 = click.prompt(\"Password\", hide_input=True) pass2 = click.prompt(\"Confirm Password\", hide_input=True)", "pass1 != pass2: click.echo(\"Passwords do not match\") return cfg[\"password\"] = <PASSWORD> doit =", "name): \"\"\"Delete cluster.\"\"\" data.client.delete(\"experimental/cluster\", name) @request.group('cluster') @click.pass_obj def request_cluster(data): \"\"\"Request cluster\"\"\" @request_cluster.command(\"test\") @click.argument('name')", "@click.pass_obj def create_cluster(data, name, server, port, username): \"\"\"Create cluster.\"\"\" pass1 = click.prompt(\"User Password\",", "import request from prog.cli import set from prog.cli import unset from prog.cli import", "server, \"api_port\": port, \"username\": username, \"password\": <PASSWORD>} data.client.create(\"experimental/cluster\", {\"config\": cfg}) @set.command(\"cluster\") @click.argument('name') @click.option('--server',", "@click.pass_obj def set_cluster(data, name, server, port, username, password): \"\"\"Set cluster configuration.\"\"\" cfg =", "\"\"\"test cluster.\"\"\" pass1 = click.prompt(\"User Password\", hide_input=True) cfg = {\"name\": name, \"api_server\": server,", "is not None: doit = True cfg[\"api_port\"] = port if username is not", "else: click.echo(\"Please specify configurations to be set.\") @delete.command(\"cluster\") @click.argument('name') @click.pass_obj def delete_cluster(data, name):", "@click.pass_obj @click.pass_context def show_cluster(ctx, data): \"\"\"Show clusters.\"\"\" if ctx.invoked_subcommand is not None: return", "@click.argument(\"id_or_name\") @click.pass_obj def detail(data, id_or_name): \"\"\"Show cluster detail.\"\"\" cluster = data.client.show(\"experimental/cluster\", \"cluster\", id_or_name)", "\"api_server\": server, \"api_port\": port, \"username\": username, \"password\": <PASSWORD>} data.client.request(\"experimental/debug\", \"cluster\", \"test\", {\"test\": cfg})", "detail.\"\"\" cluster = data.client.show(\"experimental/cluster\", \"cluster\", id_or_name) if not cluster: return columns = (\"name\",", "@show.group(\"cluster\", invoke_without_command=True) @click.pass_obj @click.pass_context def show_cluster(ctx, data): \"\"\"Show clusters.\"\"\" if ctx.invoked_subcommand is not", "password.\") @click.pass_obj def set_cluster(data, name, server, port, username, password): \"\"\"Set cluster configuration.\"\"\" cfg", "def set_cluster(data, name, server, port, username, password): \"\"\"Set cluster configuration.\"\"\" cfg = {\"name\":", "click from prog.cli import cli from prog.cli import create from prog.cli import delete", "if clusters is None: return columns = (\"name\", \"api_server\", \"api_port\", \"username\") output.list(columns, clusters)", "API server.\") @click.option('--port', type=int, help=\"Set API server port.\") @click.option('-u', '--username', help=\"Set username.\") @click.option(\"-p\",", "match\") return cfg[\"password\"] = <PASSWORD> doit = True if doit: data.client.config(\"experimental/cluster\", name, {\"config\":", "def request_cluster(data): \"\"\"Request cluster\"\"\" @request_cluster.command(\"test\") @click.argument('name') @click.argument('server') @click.argument('port', type=int) @click.argument('username') @click.pass_obj def test_cluster(data,", "import click from prog.cli import cli from prog.cli import create from prog.cli import", "username): \"\"\"Create cluster.\"\"\" pass1 = click.prompt(\"User Password\", hide_input=True) pass2 = click.prompt(\"Confirm User Password\",", "cfg[\"api_server\"] = server if port is not None: doit = True cfg[\"api_port\"] =", "click.prompt(\"Password\", hide_input=True) pass2 = click.prompt(\"Confirm Password\", hide_input=True) if pass1 != pass2: click.echo(\"Passwords do", "ctx.invoked_subcommand is not None: return clusters = data.client.list(\"experimental/cluster\", \"cluster\") if clusters is None:", "request_cluster(data): \"\"\"Request cluster\"\"\" @request_cluster.command(\"test\") @click.argument('name') @click.argument('server') @click.argument('port', type=int) @click.argument('username') @click.pass_obj def test_cluster(data, name,", "import cli from prog.cli import create from prog.cli import delete from prog.cli import", "help=\"Set API server.\") @click.option('--port', type=int, help=\"Set API server port.\") @click.option('-u', '--username', help=\"Set username.\")", "set from prog.cli import unset from prog.cli import show from prog import client", "clusters) @show_cluster.command() @click.argument(\"id_or_name\") @click.pass_obj def detail(data, id_or_name): \"\"\"Show cluster detail.\"\"\" cluster = data.client.show(\"experimental/cluster\",", "(\"name\", \"api_server\", \"api_port\", \"username\") output.list(columns, clusters) @show_cluster.command() @click.argument(\"id_or_name\") @click.pass_obj def detail(data, id_or_name): \"\"\"Show", "from prog.cli import cli from prog.cli import create from prog.cli import delete from", "{\"name\": name} doit = False if server is not None: doit = True", "@click.pass_obj def test_cluster(data, name, server, port, username): \"\"\"test cluster.\"\"\" pass1 = click.prompt(\"User Password\",", "\"api_port\": port, \"username\": username, \"password\": <PASSWORD>} data.client.create(\"experimental/cluster\", {\"config\": cfg}) @set.command(\"cluster\") @click.argument('name') @click.option('--server', help=\"Set", "doit = True cfg[\"api_server\"] = server if port is not None: doit =", "def show_cluster(ctx, data): \"\"\"Show clusters.\"\"\" if ctx.invoked_subcommand is not None: return clusters =", "= data.client.show(\"experimental/cluster\", \"cluster\", id_or_name) if not cluster: return columns = (\"name\", \"api_server\", \"api_port\",", "@click.option('--port', type=int, help=\"Set API server port.\") @click.option('-u', '--username', help=\"Set username.\") @click.option(\"-p\", \"--password\", is_flag=True,", "type=int, help=\"Set API server port.\") @click.option('-u', '--username', help=\"Set username.\") @click.option(\"-p\", \"--password\", is_flag=True, help=\"Set", "True cfg[\"api_server\"] = server if port is not None: doit = True cfg[\"api_port\"]", "def test_cluster(data, name, server, port, username): \"\"\"test cluster.\"\"\" pass1 = click.prompt(\"User Password\", hide_input=True)", "client from prog import output from prog import utils @show.group(\"cluster\", invoke_without_command=True) @click.pass_obj @click.pass_context", "hide_input=True) if pass1 != pass2: click.echo(\"Passwords do not match\") return cfg[\"password\"] = <PASSWORD>", "create_cluster(data, name, server, port, username): \"\"\"Create cluster.\"\"\" pass1 = click.prompt(\"User Password\", hide_input=True) pass2", "cluster detail.\"\"\" cluster = data.client.show(\"experimental/cluster\", \"cluster\", id_or_name) if not cluster: return columns =", "pass1 = click.prompt(\"User Password\", hide_input=True) pass2 = click.prompt(\"Confirm User Password\", hide_input=True) if pass1", "None: doit = True cfg[\"api_port\"] = port if username is not None: doit", "name, server, port, username): \"\"\"test cluster.\"\"\" pass1 = click.prompt(\"User Password\", hide_input=True) cfg =", "@show_cluster.command() @click.argument(\"id_or_name\") @click.pass_obj def detail(data, id_or_name): \"\"\"Show cluster detail.\"\"\" cluster = data.client.show(\"experimental/cluster\", \"cluster\",", "import set from prog.cli import unset from prog.cli import show from prog import", "invoke_without_command=True) @click.pass_obj @click.pass_context def show_cluster(ctx, data): \"\"\"Show clusters.\"\"\" if ctx.invoked_subcommand is not None:", "is None: return columns = (\"name\", \"api_server\", \"api_port\", \"username\") output.list(columns, clusters) @show_cluster.command() @click.argument(\"id_or_name\")", "output.show(columns, cluster) @create.command(\"cluster\") @click.argument('name') @click.argument('server') @click.argument('port', type=int) @click.argument('username') @click.pass_obj def create_cluster(data, name, server,", "@click.argument('port', type=int) @click.argument('username') @click.pass_obj def test_cluster(data, name, server, port, username): \"\"\"test cluster.\"\"\" pass1", "columns = (\"name\", \"api_server\", \"api_port\", \"username\") output.list(columns, clusters) @show_cluster.command() @click.argument(\"id_or_name\") @click.pass_obj def detail(data,", "server, port, username): \"\"\"test cluster.\"\"\" pass1 = click.prompt(\"User Password\", hide_input=True) cfg = {\"name\":", "@set.command(\"cluster\") @click.argument('name') @click.option('--server', help=\"Set API server.\") @click.option('--port', type=int, help=\"Set API server port.\") @click.option('-u',", "from prog.cli import request from prog.cli import set from prog.cli import unset from", "not cluster: return columns = (\"name\", \"api_server\", \"api_port\", \"username\") output.show(columns, cluster) @create.command(\"cluster\") @click.argument('name')", "name, \"api_server\": server, \"api_port\": port, \"username\": username, \"password\": <PASSWORD>} data.client.request(\"experimental/debug\", \"cluster\", \"test\", {\"test\":", "@click.argument('server') @click.argument('port', type=int) @click.argument('username') @click.pass_obj def test_cluster(data, name, server, port, username): \"\"\"test cluster.\"\"\"", "doit = False if server is not None: doit = True cfg[\"api_server\"] =", "hide_input=True) if pass1 != pass2: click.echo(\"Passwords do not match\") return cfg = {\"name\":", "port, \"username\": username, \"password\": <PASSWORD>} data.client.create(\"experimental/cluster\", {\"config\": cfg}) @set.command(\"cluster\") @click.argument('name') @click.option('--server', help=\"Set API", "password): \"\"\"Set cluster configuration.\"\"\" cfg = {\"name\": name} doit = False if server", "pass2: click.echo(\"Passwords do not match\") return cfg[\"password\"] = <PASSWORD> doit = True if", "API server port.\") @click.option('-u', '--username', help=\"Set username.\") @click.option(\"-p\", \"--password\", is_flag=True, help=\"Set password.\") @click.pass_obj", "if username is not None: doit = True cfg[\"username\"] = username if password:", "do not match\") return cfg[\"password\"] = <PASSWORD> doit = True if doit: data.client.config(\"experimental/cluster\",", "unset from prog.cli import show from prog import client from prog import output", "from prog.cli import unset from prog.cli import show from prog import client from", "show from prog import client from prog import output from prog import utils", "show_cluster(ctx, data): \"\"\"Show clusters.\"\"\" if ctx.invoked_subcommand is not None: return clusters = data.client.list(\"experimental/cluster\",", "\"api_port\", \"username\") output.show(columns, cluster) @create.command(\"cluster\") @click.argument('name') @click.argument('server') @click.argument('port', type=int) @click.argument('username') @click.pass_obj def create_cluster(data,", "server port.\") @click.option('-u', '--username', help=\"Set username.\") @click.option(\"-p\", \"--password\", is_flag=True, help=\"Set password.\") @click.pass_obj def", "port if username is not None: doit = True cfg[\"username\"] = username if", "if doit: data.client.config(\"experimental/cluster\", name, {\"config\": cfg}) else: click.echo(\"Please specify configurations to be set.\")", "@click.argument('name') @click.argument('server') @click.argument('port', type=int) @click.argument('username') @click.pass_obj def test_cluster(data, name, server, port, username): \"\"\"test", "def delete_cluster(data, name): \"\"\"Delete cluster.\"\"\" data.client.delete(\"experimental/cluster\", name) @request.group('cluster') @click.pass_obj def request_cluster(data): \"\"\"Request cluster\"\"\"", "output.list(columns, clusters) @show_cluster.command() @click.argument(\"id_or_name\") @click.pass_obj def detail(data, id_or_name): \"\"\"Show cluster detail.\"\"\" cluster =", "import client from prog import output from prog import utils @show.group(\"cluster\", invoke_without_command=True) @click.pass_obj", "click.prompt(\"User Password\", hide_input=True) pass2 = click.prompt(\"Confirm User Password\", hide_input=True) if pass1 != pass2:", "Password\", hide_input=True) if pass1 != pass2: click.echo(\"Passwords do not match\") return cfg =", "name, \"api_server\": server, \"api_port\": port, \"username\": username, \"password\": <PASSWORD>} data.client.create(\"experimental/cluster\", {\"config\": cfg}) @set.command(\"cluster\")", "\"api_server\", \"api_port\", \"username\") output.show(columns, cluster) @create.command(\"cluster\") @click.argument('name') @click.argument('server') @click.argument('port', type=int) @click.argument('username') @click.pass_obj def", "cfg = {\"name\": name, \"api_server\": server, \"api_port\": port, \"username\": username, \"password\": <PASSWORD>} data.client.create(\"experimental/cluster\",", "not match\") return cfg[\"password\"] = <PASSWORD> doit = True if doit: data.client.config(\"experimental/cluster\", name,", "port.\") @click.option('-u', '--username', help=\"Set username.\") @click.option(\"-p\", \"--password\", is_flag=True, help=\"Set password.\") @click.pass_obj def set_cluster(data,", "from prog.cli import show from prog import client from prog import output from", "is_flag=True, help=\"Set password.\") @click.pass_obj def set_cluster(data, name, server, port, username, password): \"\"\"Set cluster", "port is not None: doit = True cfg[\"api_port\"] = port if username is", "None: return clusters = data.client.list(\"experimental/cluster\", \"cluster\") if clusters is None: return columns =", "name) @request.group('cluster') @click.pass_obj def request_cluster(data): \"\"\"Request cluster\"\"\" @request_cluster.command(\"test\") @click.argument('name') @click.argument('server') @click.argument('port', type=int) @click.argument('username')", "\"password\": <PASSWORD>} data.client.create(\"experimental/cluster\", {\"config\": cfg}) @set.command(\"cluster\") @click.argument('name') @click.option('--server', help=\"Set API server.\") @click.option('--port', type=int,", "cfg}) @set.command(\"cluster\") @click.argument('name') @click.option('--server', help=\"Set API server.\") @click.option('--port', type=int, help=\"Set API server port.\")", "\"\"\"Request cluster\"\"\" @request_cluster.command(\"test\") @click.argument('name') @click.argument('server') @click.argument('port', type=int) @click.argument('username') @click.pass_obj def test_cluster(data, name, server,", "import delete from prog.cli import request from prog.cli import set from prog.cli import", "\"cluster\") if clusters is None: return columns = (\"name\", \"api_server\", \"api_port\", \"username\") output.list(columns,", "from prog import output from prog import utils @show.group(\"cluster\", invoke_without_command=True) @click.pass_obj @click.pass_context def", "to be set.\") @delete.command(\"cluster\") @click.argument('name') @click.pass_obj def delete_cluster(data, name): \"\"\"Delete cluster.\"\"\" data.client.delete(\"experimental/cluster\", name)", "name} doit = False if server is not None: doit = True cfg[\"api_server\"]", "(\"name\", \"api_server\", \"api_port\", \"username\") output.show(columns, cluster) @create.command(\"cluster\") @click.argument('name') @click.argument('server') @click.argument('port', type=int) @click.argument('username') @click.pass_obj", "request from prog.cli import set from prog.cli import unset from prog.cli import show", "from prog.cli import create from prog.cli import delete from prog.cli import request from", "server is not None: doit = True cfg[\"api_server\"] = server if port is", "delete from prog.cli import request from prog.cli import set from prog.cli import unset", "data.client.list(\"experimental/cluster\", \"cluster\") if clusters is None: return columns = (\"name\", \"api_server\", \"api_port\", \"username\")", "Password\", hide_input=True) pass2 = click.prompt(\"Confirm User Password\", hide_input=True) if pass1 != pass2: click.echo(\"Passwords", "cluster = data.client.show(\"experimental/cluster\", \"cluster\", id_or_name) if not cluster: return columns = (\"name\", \"api_server\",", "{\"name\": name, \"api_server\": server, \"api_port\": port, \"username\": username, \"password\": <PASSWORD>} data.client.create(\"experimental/cluster\", {\"config\": cfg})", "help=\"Set username.\") @click.option(\"-p\", \"--password\", is_flag=True, help=\"Set password.\") @click.pass_obj def set_cluster(data, name, server, port,", "True cfg[\"api_port\"] = port if username is not None: doit = True cfg[\"username\"]", "username.\") @click.option(\"-p\", \"--password\", is_flag=True, help=\"Set password.\") @click.pass_obj def set_cluster(data, name, server, port, username,", "not None: doit = True cfg[\"username\"] = username if password: pass1 = click.prompt(\"Password\",", "server.\") @click.option('--port', type=int, help=\"Set API server port.\") @click.option('-u', '--username', help=\"Set username.\") @click.option(\"-p\", \"--password\",", "password: pass1 = click.prompt(\"Password\", hide_input=True) pass2 = click.prompt(\"Confirm Password\", hide_input=True) if pass1 !=", "return clusters = data.client.list(\"experimental/cluster\", \"cluster\") if clusters is None: return columns = (\"name\",", "hide_input=True) pass2 = click.prompt(\"Confirm User Password\", hide_input=True) if pass1 != pass2: click.echo(\"Passwords do", "= click.prompt(\"User Password\", hide_input=True) pass2 = click.prompt(\"Confirm User Password\", hide_input=True) if pass1 !=", "if ctx.invoked_subcommand is not None: return clusters = data.client.list(\"experimental/cluster\", \"cluster\") if clusters is", "port, username, password): \"\"\"Set cluster configuration.\"\"\" cfg = {\"name\": name} doit = False", "utils @show.group(\"cluster\", invoke_without_command=True) @click.pass_obj @click.pass_context def show_cluster(ctx, data): \"\"\"Show clusters.\"\"\" if ctx.invoked_subcommand is", "delete_cluster(data, name): \"\"\"Delete cluster.\"\"\" data.client.delete(\"experimental/cluster\", name) @request.group('cluster') @click.pass_obj def request_cluster(data): \"\"\"Request cluster\"\"\" @request_cluster.command(\"test\")", "@click.argument('name') @click.argument('server') @click.argument('port', type=int) @click.argument('username') @click.pass_obj def create_cluster(data, name, server, port, username): \"\"\"Create", "prog import output from prog import utils @show.group(\"cluster\", invoke_without_command=True) @click.pass_obj @click.pass_context def show_cluster(ctx,", "{\"name\": name, \"api_server\": server, \"api_port\": port, \"username\": username, \"password\": <PASSWORD>} data.client.request(\"experimental/debug\", \"cluster\", \"test\",", "clusters = data.client.list(\"experimental/cluster\", \"cluster\") if clusters is None: return columns = (\"name\", \"api_server\",", "from prog.cli import delete from prog.cli import request from prog.cli import set from", "data.client.create(\"experimental/cluster\", {\"config\": cfg}) @set.command(\"cluster\") @click.argument('name') @click.option('--server', help=\"Set API server.\") @click.option('--port', type=int, help=\"Set API", "prog.cli import cli from prog.cli import create from prog.cli import delete from prog.cli", "from prog.cli import set from prog.cli import unset from prog.cli import show from", "click.echo(\"Please specify configurations to be set.\") @delete.command(\"cluster\") @click.argument('name') @click.pass_obj def delete_cluster(data, name): \"\"\"Delete", "match\") return cfg = {\"name\": name, \"api_server\": server, \"api_port\": port, \"username\": username, \"password\":", "@click.option('--server', help=\"Set API server.\") @click.option('--port', type=int, help=\"Set API server port.\") @click.option('-u', '--username', help=\"Set", "help=\"Set API server port.\") @click.option('-u', '--username', help=\"Set username.\") @click.option(\"-p\", \"--password\", is_flag=True, help=\"Set password.\")", "def create_cluster(data, name, server, port, username): \"\"\"Create cluster.\"\"\" pass1 = click.prompt(\"User Password\", hide_input=True)", "@click.option('-u', '--username', help=\"Set username.\") @click.option(\"-p\", \"--password\", is_flag=True, help=\"Set password.\") @click.pass_obj def set_cluster(data, name,", "is not None: return clusters = data.client.list(\"experimental/cluster\", \"cluster\") if clusters is None: return", "\"\"\"Set cluster configuration.\"\"\" cfg = {\"name\": name} doit = False if server is", "= click.prompt(\"Password\", hide_input=True) pass2 = click.prompt(\"Confirm Password\", hide_input=True) if pass1 != pass2: click.echo(\"Passwords", "= (\"name\", \"api_server\", \"api_port\", \"username\") output.list(columns, clusters) @show_cluster.command() @click.argument(\"id_or_name\") @click.pass_obj def detail(data, id_or_name):", "@click.argument('port', type=int) @click.argument('username') @click.pass_obj def create_cluster(data, name, server, port, username): \"\"\"Create cluster.\"\"\" pass1", "cluster.\"\"\" pass1 = click.prompt(\"User Password\", hide_input=True) pass2 = click.prompt(\"Confirm User Password\", hide_input=True) if", "= click.prompt(\"Confirm User Password\", hide_input=True) if pass1 != pass2: click.echo(\"Passwords do not match\")", "not match\") return cfg = {\"name\": name, \"api_server\": server, \"api_port\": port, \"username\": username,", "\"\"\"Delete cluster.\"\"\" data.client.delete(\"experimental/cluster\", name) @request.group('cluster') @click.pass_obj def request_cluster(data): \"\"\"Request cluster\"\"\" @request_cluster.command(\"test\") @click.argument('name') @click.argument('server')", "@click.argument('username') @click.pass_obj def test_cluster(data, name, server, port, username): \"\"\"test cluster.\"\"\" pass1 = click.prompt(\"User", "from prog import utils @show.group(\"cluster\", invoke_without_command=True) @click.pass_obj @click.pass_context def show_cluster(ctx, data): \"\"\"Show clusters.\"\"\"", "specify configurations to be set.\") @delete.command(\"cluster\") @click.argument('name') @click.pass_obj def delete_cluster(data, name): \"\"\"Delete cluster.\"\"\"", "= click.prompt(\"User Password\", hide_input=True) cfg = {\"name\": name, \"api_server\": server, \"api_port\": port, \"username\":", "click.echo(\"Passwords do not match\") return cfg[\"password\"] = <PASSWORD> doit = True if doit:", "cli from prog.cli import create from prog.cli import delete from prog.cli import request", "@click.pass_context def show_cluster(ctx, data): \"\"\"Show clusters.\"\"\" if ctx.invoked_subcommand is not None: return clusters", "= False if server is not None: doit = True cfg[\"api_server\"] = server", "@click.pass_obj def delete_cluster(data, name): \"\"\"Delete cluster.\"\"\" data.client.delete(\"experimental/cluster\", name) @request.group('cluster') @click.pass_obj def request_cluster(data): \"\"\"Request", "username, \"password\": <PASSWORD>} data.client.create(\"experimental/cluster\", {\"config\": cfg}) @set.command(\"cluster\") @click.argument('name') @click.option('--server', help=\"Set API server.\") @click.option('--port',", "if not cluster: return columns = (\"name\", \"api_server\", \"api_port\", \"username\") output.show(columns, cluster) @create.command(\"cluster\")", "prog import client from prog import output from prog import utils @show.group(\"cluster\", invoke_without_command=True)", "configuration.\"\"\" cfg = {\"name\": name} doit = False if server is not None:", "cluster) @create.command(\"cluster\") @click.argument('name') @click.argument('server') @click.argument('port', type=int) @click.argument('username') @click.pass_obj def create_cluster(data, name, server, port,", "<PASSWORD>} data.client.create(\"experimental/cluster\", {\"config\": cfg}) @set.command(\"cluster\") @click.argument('name') @click.option('--server', help=\"Set API server.\") @click.option('--port', type=int, help=\"Set", "pass1 = click.prompt(\"Password\", hide_input=True) pass2 = click.prompt(\"Confirm Password\", hide_input=True) if pass1 != pass2:", "doit = True if doit: data.client.config(\"experimental/cluster\", name, {\"config\": cfg}) else: click.echo(\"Please specify configurations", "set.\") @delete.command(\"cluster\") @click.argument('name') @click.pass_obj def delete_cluster(data, name): \"\"\"Delete cluster.\"\"\" data.client.delete(\"experimental/cluster\", name) @request.group('cluster') @click.pass_obj", "import create from prog.cli import delete from prog.cli import request from prog.cli import", "\"\"\"Show cluster detail.\"\"\" cluster = data.client.show(\"experimental/cluster\", \"cluster\", id_or_name) if not cluster: return columns", "if password: pass1 = click.prompt(\"Password\", hide_input=True) pass2 = click.prompt(\"Confirm Password\", hide_input=True) if pass1", "server, port, username): \"\"\"Create cluster.\"\"\" pass1 = click.prompt(\"User Password\", hide_input=True) pass2 = click.prompt(\"Confirm", "cluster configuration.\"\"\" cfg = {\"name\": name} doit = False if server is not", "True if doit: data.client.config(\"experimental/cluster\", name, {\"config\": cfg}) else: click.echo(\"Please specify configurations to be", "\"api_server\", \"api_port\", \"username\") output.list(columns, clusters) @show_cluster.command() @click.argument(\"id_or_name\") @click.pass_obj def detail(data, id_or_name): \"\"\"Show cluster", "id_or_name): \"\"\"Show cluster detail.\"\"\" cluster = data.client.show(\"experimental/cluster\", \"cluster\", id_or_name) if not cluster: return", "True cfg[\"username\"] = username if password: pass1 = click.prompt(\"Password\", hide_input=True) pass2 = click.prompt(\"Confirm", "cfg[\"username\"] = username if password: pass1 = click.prompt(\"Password\", hide_input=True) pass2 = click.prompt(\"Confirm Password\",", "\"\"\"Create cluster.\"\"\" pass1 = click.prompt(\"User Password\", hide_input=True) pass2 = click.prompt(\"Confirm User Password\", hide_input=True)", "name, server, port, username, password): \"\"\"Set cluster configuration.\"\"\" cfg = {\"name\": name} doit", "is not None: doit = True cfg[\"api_server\"] = server if port is not", "username if password: pass1 = click.prompt(\"Password\", hide_input=True) pass2 = click.prompt(\"Confirm Password\", hide_input=True) if", "Password\", hide_input=True) if pass1 != pass2: click.echo(\"Passwords do not match\") return cfg[\"password\"] =", "!= pass2: click.echo(\"Passwords do not match\") return cfg = {\"name\": name, \"api_server\": server,", "@click.option(\"-p\", \"--password\", is_flag=True, help=\"Set password.\") @click.pass_obj def set_cluster(data, name, server, port, username, password):", "= True if doit: data.client.config(\"experimental/cluster\", name, {\"config\": cfg}) else: click.echo(\"Please specify configurations to", "create from prog.cli import delete from prog.cli import request from prog.cli import set", "if pass1 != pass2: click.echo(\"Passwords do not match\") return cfg = {\"name\": name,", "<PASSWORD> doit = True if doit: data.client.config(\"experimental/cluster\", name, {\"config\": cfg}) else: click.echo(\"Please specify", "set_cluster(data, name, server, port, username, password): \"\"\"Set cluster configuration.\"\"\" cfg = {\"name\": name}", "data.client.delete(\"experimental/cluster\", name) @request.group('cluster') @click.pass_obj def request_cluster(data): \"\"\"Request cluster\"\"\" @request_cluster.command(\"test\") @click.argument('name') @click.argument('server') @click.argument('port', type=int)", "type=int) @click.argument('username') @click.pass_obj def create_cluster(data, name, server, port, username): \"\"\"Create cluster.\"\"\" pass1 =", "data.client.config(\"experimental/cluster\", name, {\"config\": cfg}) else: click.echo(\"Please specify configurations to be set.\") @delete.command(\"cluster\") @click.argument('name')", "output from prog import utils @show.group(\"cluster\", invoke_without_command=True) @click.pass_obj @click.pass_context def show_cluster(ctx, data): \"\"\"Show", "@click.argument('username') @click.pass_obj def create_cluster(data, name, server, port, username): \"\"\"Create cluster.\"\"\" pass1 = click.prompt(\"User", "False if server is not None: doit = True cfg[\"api_server\"] = server if", "@click.argument('name') @click.pass_obj def delete_cluster(data, name): \"\"\"Delete cluster.\"\"\" data.client.delete(\"experimental/cluster\", name) @request.group('cluster') @click.pass_obj def request_cluster(data):", "pass2 = click.prompt(\"Confirm User Password\", hide_input=True) if pass1 != pass2: click.echo(\"Passwords do not", "do not match\") return cfg = {\"name\": name, \"api_server\": server, \"api_port\": port, \"username\":", "pass2 = click.prompt(\"Confirm Password\", hide_input=True) if pass1 != pass2: click.echo(\"Passwords do not match\")", "name, server, port, username): \"\"\"Create cluster.\"\"\" pass1 = click.prompt(\"User Password\", hide_input=True) pass2 =", "return columns = (\"name\", \"api_server\", \"api_port\", \"username\") output.list(columns, clusters) @show_cluster.command() @click.argument(\"id_or_name\") @click.pass_obj def", "is not None: doit = True cfg[\"username\"] = username if password: pass1 =", "{\"config\": cfg}) @set.command(\"cluster\") @click.argument('name') @click.option('--server', help=\"Set API server.\") @click.option('--port', type=int, help=\"Set API server", "return cfg = {\"name\": name, \"api_server\": server, \"api_port\": port, \"username\": username, \"password\": <PASSWORD>}", "name, {\"config\": cfg}) else: click.echo(\"Please specify configurations to be set.\") @delete.command(\"cluster\") @click.argument('name') @click.pass_obj", "clusters.\"\"\" if ctx.invoked_subcommand is not None: return clusters = data.client.list(\"experimental/cluster\", \"cluster\") if clusters", "= True cfg[\"api_port\"] = port if username is not None: doit = True", "hide_input=True) pass2 = click.prompt(\"Confirm Password\", hide_input=True) if pass1 != pass2: click.echo(\"Passwords do not", "type=int) @click.argument('username') @click.pass_obj def test_cluster(data, name, server, port, username): \"\"\"test cluster.\"\"\" pass1 =", "= {\"name\": name, \"api_server\": server, \"api_port\": port, \"username\": username, \"password\": <PASSWORD>} data.client.request(\"experimental/debug\", \"cluster\",", "cluster: return columns = (\"name\", \"api_server\", \"api_port\", \"username\") output.show(columns, cluster) @create.command(\"cluster\") @click.argument('name') @click.argument('server')", "doit = True cfg[\"api_port\"] = port if username is not None: doit =", "@delete.command(\"cluster\") @click.argument('name') @click.pass_obj def delete_cluster(data, name): \"\"\"Delete cluster.\"\"\" data.client.delete(\"experimental/cluster\", name) @request.group('cluster') @click.pass_obj def", "return columns = (\"name\", \"api_server\", \"api_port\", \"username\") output.show(columns, cluster) @create.command(\"cluster\") @click.argument('name') @click.argument('server') @click.argument('port',", "pass2: click.echo(\"Passwords do not match\") return cfg = {\"name\": name, \"api_server\": server, \"api_port\":", "= {\"name\": name, \"api_server\": server, \"api_port\": port, \"username\": username, \"password\": <PASSWORD>} data.client.create(\"experimental/cluster\", {\"config\":", "cfg = {\"name\": name} doit = False if server is not None: doit", "help=\"Set password.\") @click.pass_obj def set_cluster(data, name, server, port, username, password): \"\"\"Set cluster configuration.\"\"\"", "if server is not None: doit = True cfg[\"api_server\"] = server if port" ]
[ "search for in that field. The implied boolean operator between these terms is", "python \"\"\"Search bibliography database. The search string takes the format of field:[field name]", "before the field specifier. The \"and\" operator is again the default between field", "description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument( '-s', type=str, nargs='+', dest='search_string', help='Search string') parser.add_argument( '-t', type=str, nargs='+',", "format of field:[field name] followed by a list of terms to search for", "are used to specify the desired output. Example: searchbibs.py -s field:keywords anillin and", "bibtools.bib as btl def main(): args = parse_args() bibliography = btl.Bibliography(btl.BIB_DIRECTORY) search_string =", "of terms to search for in that field. The implied boolean operator between", "that field. The implied boolean operator between these terms is \"and\". To use", "btl.Bibliography(btl.BIB_DIRECTORY) search_string = btl.SearchString(args.search_string) bibliography.match_and_print_fields(search_string, args.terms) def parse_args(): parser = argparse.ArgumentParser( description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)", "nargs='+', dest='search_string', help='Search string') parser.add_argument( '-t', type=str, nargs='+', default=['title', 'year', 'author', 'annote'], dest='terms',", "and not field:keywords review -t title year author keywords \"\"\" import argparse import", "specifiers. The same field names are used to specify the desired output. Example:", "the format of field:[field name] followed by a list of terms to search", "parse_args() bibliography = btl.Bibliography(btl.BIB_DIRECTORY) search_string = btl.SearchString(args.search_string) bibliography.match_and_print_fields(search_string, args.terms) def parse_args(): parser =", "be placed before the field specifier. The \"and\" operator is again the default", "placed before the field specifier. The \"and\" operator is again the default between", "boolean operators \"and\", \"or\", and \"not\" can be placed before the field specifier.", "The \"and\" operator is again the default between field specifiers. The same field", "The same field names are used to specify the desired output. Example: searchbibs.py", "string') parser.add_argument( '-t', type=str, nargs='+', default=['title', 'year', 'author', 'annote'], dest='terms', help='Terms to print')", "operators with the same field, the field:[field name] must be repeated after the", "names are used to specify the desired output. Example: searchbibs.py -s field:keywords anillin", "argparse import bibtools.bib as btl def main(): args = parse_args() bibliography = btl.Bibliography(btl.BIB_DIRECTORY)", "is \"and\". To use other boolean operators with the same field, the field:[field", "field:[field name] followed by a list of terms to search for in that", "To use other boolean operators with the same field, the field:[field name] must", "title year author keywords \"\"\" import argparse import bibtools.bib as btl def main():", "author keywords \"\"\" import argparse import bibtools.bib as btl def main(): args =", "specifier. The \"and\" operator is again the default between field specifiers. The same", "field specifier. The \"and\" operator is again the default between field specifiers. The", "-t title year author keywords \"\"\" import argparse import bibtools.bib as btl def", "use other boolean operators with the same field, the field:[field name] must be", "import bibtools.bib as btl def main(): args = parse_args() bibliography = btl.Bibliography(btl.BIB_DIRECTORY) search_string", "name] followed by a list of terms to search for in that field.", "between these terms is \"and\". To use other boolean operators with the same", "default=['title', 'year', 'author', 'annote'], dest='terms', help='Terms to print') return parser.parse_args() if __name__ ==", "operators \"and\", \"or\", and \"not\" can be placed before the field specifier. The", "between field specifiers. The same field names are used to specify the desired", "the operator. More generally, the boolean operators \"and\", \"or\", and \"not\" can be", "operator. More generally, the boolean operators \"and\", \"or\", and \"not\" can be placed", "searchbibs.py -s field:keywords anillin and not field:keywords review -t title year author keywords", "argparse.ArgumentParser( description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument( '-s', type=str, nargs='+', dest='search_string', help='Search string') parser.add_argument( '-t', type=str,", "the desired output. Example: searchbibs.py -s field:keywords anillin and not field:keywords review -t", "be repeated after the operator. More generally, the boolean operators \"and\", \"or\", and", "The implied boolean operator between these terms is \"and\". To use other boolean", "search string takes the format of field:[field name] followed by a list of", "these terms is \"and\". To use other boolean operators with the same field,", "formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument( '-s', type=str, nargs='+', dest='search_string', help='Search string') parser.add_argument( '-t', type=str, nargs='+', default=['title',", "bibliography.match_and_print_fields(search_string, args.terms) def parse_args(): parser = argparse.ArgumentParser( description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument( '-s', type=str, nargs='+',", "import argparse import bibtools.bib as btl def main(): args = parse_args() bibliography =", "bibliography database. The search string takes the format of field:[field name] followed by", "and \"not\" can be placed before the field specifier. The \"and\" operator is", "the boolean operators \"and\", \"or\", and \"not\" can be placed before the field", "default between field specifiers. The same field names are used to specify the", "field:[field name] must be repeated after the operator. More generally, the boolean operators", "generally, the boolean operators \"and\", \"or\", and \"not\" can be placed before the", "bibliography = btl.Bibliography(btl.BIB_DIRECTORY) search_string = btl.SearchString(args.search_string) bibliography.match_and_print_fields(search_string, args.terms) def parse_args(): parser = argparse.ArgumentParser(", "is again the default between field specifiers. The same field names are used", "takes the format of field:[field name] followed by a list of terms to", "args.terms) def parse_args(): parser = argparse.ArgumentParser( description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument( '-s', type=str, nargs='+', dest='search_string',", "terms is \"and\". To use other boolean operators with the same field, the", "btl def main(): args = parse_args() bibliography = btl.Bibliography(btl.BIB_DIRECTORY) search_string = btl.SearchString(args.search_string) bibliography.match_and_print_fields(search_string,", "help='Search string') parser.add_argument( '-t', type=str, nargs='+', default=['title', 'year', 'author', 'annote'], dest='terms', help='Terms to", "keywords \"\"\" import argparse import bibtools.bib as btl def main(): args = parse_args()", "dest='search_string', help='Search string') parser.add_argument( '-t', type=str, nargs='+', default=['title', 'year', 'author', 'annote'], dest='terms', help='Terms", "by a list of terms to search for in that field. The implied", "search_string = btl.SearchString(args.search_string) bibliography.match_and_print_fields(search_string, args.terms) def parse_args(): parser = argparse.ArgumentParser( description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument(", "desired output. Example: searchbibs.py -s field:keywords anillin and not field:keywords review -t title", "Example: searchbibs.py -s field:keywords anillin and not field:keywords review -t title year author", "= argparse.ArgumentParser( description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument( '-s', type=str, nargs='+', dest='search_string', help='Search string') parser.add_argument( '-t',", "not field:keywords review -t title year author keywords \"\"\" import argparse import bibtools.bib", "'year', 'author', 'annote'], dest='terms', help='Terms to print') return parser.parse_args() if __name__ == '__main__':", "def main(): args = parse_args() bibliography = btl.Bibliography(btl.BIB_DIRECTORY) search_string = btl.SearchString(args.search_string) bibliography.match_and_print_fields(search_string, args.terms)", "to search for in that field. The implied boolean operator between these terms", "parser = argparse.ArgumentParser( description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument( '-s', type=str, nargs='+', dest='search_string', help='Search string') parser.add_argument(", "parser.add_argument( '-t', type=str, nargs='+', default=['title', 'year', 'author', 'annote'], dest='terms', help='Terms to print') return", "\"not\" can be placed before the field specifier. The \"and\" operator is again", "after the operator. More generally, the boolean operators \"and\", \"or\", and \"not\" can", "name] must be repeated after the operator. More generally, the boolean operators \"and\",", "must be repeated after the operator. More generally, the boolean operators \"and\", \"or\",", "type=str, nargs='+', dest='search_string', help='Search string') parser.add_argument( '-t', type=str, nargs='+', default=['title', 'year', 'author', 'annote'],", "\"or\", and \"not\" can be placed before the field specifier. The \"and\" operator", "output. Example: searchbibs.py -s field:keywords anillin and not field:keywords review -t title year", "args = parse_args() bibliography = btl.Bibliography(btl.BIB_DIRECTORY) search_string = btl.SearchString(args.search_string) bibliography.match_and_print_fields(search_string, args.terms) def parse_args():", "used to specify the desired output. Example: searchbibs.py -s field:keywords anillin and not", "'-s', type=str, nargs='+', dest='search_string', help='Search string') parser.add_argument( '-t', type=str, nargs='+', default=['title', 'year', 'author',", "btl.SearchString(args.search_string) bibliography.match_and_print_fields(search_string, args.terms) def parse_args(): parser = argparse.ArgumentParser( description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument( '-s', type=str,", "\"and\" operator is again the default between field specifiers. The same field names", "More generally, the boolean operators \"and\", \"or\", and \"not\" can be placed before", "main(): args = parse_args() bibliography = btl.Bibliography(btl.BIB_DIRECTORY) search_string = btl.SearchString(args.search_string) bibliography.match_and_print_fields(search_string, args.terms) def", "string takes the format of field:[field name] followed by a list of terms", "for in that field. The implied boolean operator between these terms is \"and\".", "the default between field specifiers. The same field names are used to specify", "\"and\", \"or\", and \"not\" can be placed before the field specifier. The \"and\"", "the field:[field name] must be repeated after the operator. More generally, the boolean", "in that field. The implied boolean operator between these terms is \"and\". To", "terms to search for in that field. The implied boolean operator between these", "anillin and not field:keywords review -t title year author keywords \"\"\" import argparse", "again the default between field specifiers. The same field names are used to", "other boolean operators with the same field, the field:[field name] must be repeated", "boolean operator between these terms is \"and\". To use other boolean operators with", "a list of terms to search for in that field. The implied boolean", "field specifiers. The same field names are used to specify the desired output.", "-s field:keywords anillin and not field:keywords review -t title year author keywords \"\"\"", "\"and\". To use other boolean operators with the same field, the field:[field name]", "field. The implied boolean operator between these terms is \"and\". To use other", "can be placed before the field specifier. The \"and\" operator is again the", "the field specifier. The \"and\" operator is again the default between field specifiers.", "field names are used to specify the desired output. Example: searchbibs.py -s field:keywords", "to specify the desired output. Example: searchbibs.py -s field:keywords anillin and not field:keywords", "operator between these terms is \"and\". To use other boolean operators with the", "same field names are used to specify the desired output. Example: searchbibs.py -s", "as btl def main(): args = parse_args() bibliography = btl.Bibliography(btl.BIB_DIRECTORY) search_string = btl.SearchString(args.search_string)", "= btl.Bibliography(btl.BIB_DIRECTORY) search_string = btl.SearchString(args.search_string) bibliography.match_and_print_fields(search_string, args.terms) def parse_args(): parser = argparse.ArgumentParser( description=__doc__,", "\"\"\" import argparse import bibtools.bib as btl def main(): args = parse_args() bibliography", "type=str, nargs='+', default=['title', 'year', 'author', 'annote'], dest='terms', help='Terms to print') return parser.parse_args() if", "repeated after the operator. More generally, the boolean operators \"and\", \"or\", and \"not\"", "The search string takes the format of field:[field name] followed by a list", "nargs='+', default=['title', 'year', 'author', 'annote'], dest='terms', help='Terms to print') return parser.parse_args() if __name__", "field, the field:[field name] must be repeated after the operator. More generally, the", "list of terms to search for in that field. The implied boolean operator", "specify the desired output. Example: searchbibs.py -s field:keywords anillin and not field:keywords review", "boolean operators with the same field, the field:[field name] must be repeated after", "'-t', type=str, nargs='+', default=['title', 'year', 'author', 'annote'], dest='terms', help='Terms to print') return parser.parse_args()", "parser.add_argument( '-s', type=str, nargs='+', dest='search_string', help='Search string') parser.add_argument( '-t', type=str, nargs='+', default=['title', 'year',", "the same field, the field:[field name] must be repeated after the operator. More", "review -t title year author keywords \"\"\" import argparse import bibtools.bib as btl", "= parse_args() bibliography = btl.Bibliography(btl.BIB_DIRECTORY) search_string = btl.SearchString(args.search_string) bibliography.match_and_print_fields(search_string, args.terms) def parse_args(): parser", "<reponame>acumb/SearchRefs<gh_stars>0 #!/usr/env python \"\"\"Search bibliography database. The search string takes the format of", "same field, the field:[field name] must be repeated after the operator. More generally,", "field:keywords anillin and not field:keywords review -t title year author keywords \"\"\" import", "field:keywords review -t title year author keywords \"\"\" import argparse import bibtools.bib as", "def parse_args(): parser = argparse.ArgumentParser( description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument( '-s', type=str, nargs='+', dest='search_string', help='Search", "implied boolean operator between these terms is \"and\". To use other boolean operators", "of field:[field name] followed by a list of terms to search for in", "= btl.SearchString(args.search_string) bibliography.match_and_print_fields(search_string, args.terms) def parse_args(): parser = argparse.ArgumentParser( description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument( '-s',", "with the same field, the field:[field name] must be repeated after the operator.", "\"\"\"Search bibliography database. The search string takes the format of field:[field name] followed", "followed by a list of terms to search for in that field. The", "database. The search string takes the format of field:[field name] followed by a", "year author keywords \"\"\" import argparse import bibtools.bib as btl def main(): args", "parse_args(): parser = argparse.ArgumentParser( description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument( '-s', type=str, nargs='+', dest='search_string', help='Search string')", "operator is again the default between field specifiers. The same field names are", "'author', 'annote'], dest='terms', help='Terms to print') return parser.parse_args() if __name__ == '__main__': main()", "#!/usr/env python \"\"\"Search bibliography database. The search string takes the format of field:[field" ]
[ "build state assert_equal(instance.status, \"BUILD\") #pull out the ID self.id = instance.id return instance", "@test(groups=['smoke', 'positive']) class CreateInstance(object): @before_class def set_up(self): client = create_client(is_admin=False) name = 'test_createInstance_container'", "[{\"name\": db_name}] } ] #create the Instance instance = InstanceGenerator(client, name=self.name, flavor=flavor, volume_size=self.volume_size,", "import before_class from trove.common.utils import poll_until from trove.tests.util import create_client class InstanceGenerator(object): def", "assert_equal(str(instance.volume_size), str(self.volume_size)) #pull out the flavor and verify assert_equal(str(instance.flavor), str(self.flavor)) return instance @test(groups=['smoke',", "import poll_until from trove.tests.util import create_client class InstanceGenerator(object): def __init__(self, client, status=None, name=None,", "class CreateInstance(object): @before_class def set_up(self): client = create_client(is_admin=False) name = 'test_createInstance_container' flavor =", "= InstanceGenerator(client, name=self.name, flavor=flavor, volume_size=self.volume_size, databases=databases, users=users) instance.create_instance() #wait for the instance instance.wait_for_build_to_finish()", "set_up(self): client = create_client(is_admin=False) name = 'test_createInstance_container' flavor = 1 volume_size = 1", "self.databases, self.users) self.client.assert_http_code(200) #verify we are in a build state assert_equal(instance.status, \"BUILD\") #pull", "wait_for_build_to_finish(self): poll_until(lambda: self.client.instance.get(self.id), lambda instance: instance.status != \"BUILD\", time_out=600) def get_active_instance(self): instance =", "= users self.volume_size = volume_size self.id = None def create_instance(self): #make the call", "volume_size=None): self.client = client self.status = status self.name = name self.flavor = flavor", "self.client.instances.create(self.name, self.flavor, self.volume_size, self.databases, self.users) self.client.assert_http_code(200) #verify we are in a build state", "= None def create_instance(self): #make the call to create the instance instance =", "instance.create_instance() #wait for the instance instance.wait_for_build_to_finish() #get the active instance inst = instance.get_active_instance()", "create_instance(self): #make the call to create the instance instance = self.client.instances.create(self.name, self.flavor, self.volume_size,", "the active instance inst = instance.get_active_instance() #list out the databases for our instance", "#get the active instance inst = instance.get_active_instance() #list out the databases for our", "volume info and verify assert_equal(str(instance.volume_size), str(self.volume_size)) #pull out the flavor and verify assert_equal(str(instance.flavor),", "databases self.users = users self.volume_size = volume_size self.id = None def create_instance(self): #make", "inst = instance.get_active_instance() #list out the databases for our instance and verify the", "self.name) #pull out volume info and verify assert_equal(str(instance.volume_size), str(self.volume_size)) #pull out the flavor", "= instance.id return instance def wait_for_build_to_finish(self): poll_until(lambda: self.client.instance.get(self.id), lambda instance: instance.status != \"BUILD\",", "[ { \"name\": db_name } ] users = [ { \"name\": \"lite\", \"password\":", "self.client.instance.get(self.id) self.client.assert_http_code(200) #check the container name assert_equal(instance.name, self.name) #pull out volume info and", "instance.get_active_instance() #list out the databases for our instance and verify the db name", "= client self.status = status self.name = name self.flavor = flavor self.account_id =", "def __init__(self, client, status=None, name=None, flavor=None, account_id=None, created_at=None, databases=None, users=None, volume_size=None): self.client =", "volume_size self.id = None def create_instance(self): #make the call to create the instance", "= status self.name = name self.flavor = flavor self.account_id = account_id self.databases =", "\"name\": \"lite\", \"password\": \"<PASSWORD>\", \"databases\": [{\"name\": db_name}] } ] #create the Instance instance", "get_active_instance(self): instance = self.client.instance.get(self.id) self.client.assert_http_code(200) #check the container name assert_equal(instance.name, self.name) #pull out", "str(self.flavor)) return instance @test(groups=['smoke', 'positive']) class CreateInstance(object): @before_class def set_up(self): client = create_client(is_admin=False)", "= self.client.instances.create(self.name, self.flavor, self.volume_size, self.databases, self.users) self.client.assert_http_code(200) #verify we are in a build", "self.id = None def create_instance(self): #make the call to create the instance instance", "} ] users = [ { \"name\": \"lite\", \"password\": \"<PASSWORD>\", \"databases\": [{\"name\": db_name}]", "users=None, volume_size=None): self.client = client self.status = status self.name = name self.flavor =", "= databases self.users = users self.volume_size = volume_size self.id = None def create_instance(self):", "from trove.common.utils import poll_until from trove.tests.util import create_client class InstanceGenerator(object): def __init__(self, client,", "before_class from trove.common.utils import poll_until from trove.tests.util import create_client class InstanceGenerator(object): def __init__(self,", "call to create the instance instance = self.client.instances.create(self.name, self.flavor, self.volume_size, self.databases, self.users) self.client.assert_http_code(200)", "self.users = users self.volume_size = volume_size self.id = None def create_instance(self): #make the", "client = create_client(is_admin=False) name = 'test_createInstance_container' flavor = 1 volume_size = 1 db_name", "= flavor self.account_id = account_id self.databases = databases self.users = users self.volume_size =", "self.users) self.client.assert_http_code(200) #verify we are in a build state assert_equal(instance.status, \"BUILD\") #pull out", "the instance instance.wait_for_build_to_finish() #get the active instance inst = instance.get_active_instance() #list out the", "import test from proboscis import before_class from trove.common.utils import poll_until from trove.tests.util import", "def get_active_instance(self): instance = self.client.instance.get(self.id) self.client.assert_http_code(200) #check the container name assert_equal(instance.name, self.name) #pull", "created_at=None, databases=None, users=None, volume_size=None): self.client = client self.status = status self.name = name", "= 1 volume_size = 1 db_name = 'test_db' databases = [ { \"name\":", "self.name = name self.flavor = flavor self.account_id = account_id self.databases = databases self.users", "name=self.name, flavor=flavor, volume_size=self.volume_size, databases=databases, users=users) instance.create_instance() #wait for the instance instance.wait_for_build_to_finish() #get the", "create_client class InstanceGenerator(object): def __init__(self, client, status=None, name=None, flavor=None, account_id=None, created_at=None, databases=None, users=None,", "lambda instance: instance.status != \"BUILD\", time_out=600) def get_active_instance(self): instance = self.client.instance.get(self.id) self.client.assert_http_code(200) #check", "the instance instance = self.client.instances.create(self.name, self.flavor, self.volume_size, self.databases, self.users) self.client.assert_http_code(200) #verify we are", "\"<PASSWORD>\", \"databases\": [{\"name\": db_name}] } ] #create the Instance instance = InstanceGenerator(client, name=self.name,", "a build state assert_equal(instance.status, \"BUILD\") #pull out the ID self.id = instance.id return", "instance inst = instance.get_active_instance() #list out the databases for our instance and verify", "volume_size=self.volume_size, databases=databases, users=users) instance.create_instance() #wait for the instance instance.wait_for_build_to_finish() #get the active instance", "name assert_equal(instance.name, self.name) #pull out volume info and verify assert_equal(str(instance.volume_size), str(self.volume_size)) #pull out", "the ID self.id = instance.id return instance def wait_for_build_to_finish(self): poll_until(lambda: self.client.instance.get(self.id), lambda instance:", "in a build state assert_equal(instance.status, \"BUILD\") #pull out the ID self.id = instance.id", "1 volume_size = 1 db_name = 'test_db' databases = [ { \"name\": db_name", "= 1 db_name = 'test_db' databases = [ { \"name\": db_name } ]", "databases = [ { \"name\": db_name } ] users = [ { \"name\":", "users self.volume_size = volume_size self.id = None def create_instance(self): #make the call to", "\"BUILD\", time_out=600) def get_active_instance(self): instance = self.client.instance.get(self.id) self.client.assert_http_code(200) #check the container name assert_equal(instance.name,", "1 db_name = 'test_db' databases = [ { \"name\": db_name } ] users", "proboscis.asserts import assert_equal from proboscis import test from proboscis import before_class from trove.common.utils", "assert_equal(str(instance.flavor), str(self.flavor)) return instance @test(groups=['smoke', 'positive']) class CreateInstance(object): @before_class def set_up(self): client =", "verify the db name dbs = client.databases.list(inst.id) client.assert_http_code(200) assert_equal(len(dbs), 1) assert_equal(dbs[0].name, instance.db_name) client.instance.delete(inst.id)", "import create_client class InstanceGenerator(object): def __init__(self, client, status=None, name=None, flavor=None, account_id=None, created_at=None, databases=None,", "\"password\": \"<PASSWORD>\", \"databases\": [{\"name\": db_name}] } ] #create the Instance instance = InstanceGenerator(client,", "\"databases\": [{\"name\": db_name}] } ] #create the Instance instance = InstanceGenerator(client, name=self.name, flavor=flavor,", "account_id=None, created_at=None, databases=None, users=None, volume_size=None): self.client = client self.status = status self.name =", "and verify the db name dbs = client.databases.list(inst.id) client.assert_http_code(200) assert_equal(len(dbs), 1) assert_equal(dbs[0].name, instance.db_name)", "for the instance instance.wait_for_build_to_finish() #get the active instance inst = instance.get_active_instance() #list out", "instance.status != \"BUILD\", time_out=600) def get_active_instance(self): instance = self.client.instance.get(self.id) self.client.assert_http_code(200) #check the container", "the Instance instance = InstanceGenerator(client, name=self.name, flavor=flavor, volume_size=self.volume_size, databases=databases, users=users) instance.create_instance() #wait for", "= [ { \"name\": db_name } ] users = [ { \"name\": \"lite\",", "the databases for our instance and verify the db name dbs = client.databases.list(inst.id)", "self.flavor = flavor self.account_id = account_id self.databases = databases self.users = users self.volume_size", "the container name assert_equal(instance.name, self.name) #pull out volume info and verify assert_equal(str(instance.volume_size), str(self.volume_size))", "instance: instance.status != \"BUILD\", time_out=600) def get_active_instance(self): instance = self.client.instance.get(self.id) self.client.assert_http_code(200) #check the", "time_out=600) def get_active_instance(self): instance = self.client.instance.get(self.id) self.client.assert_http_code(200) #check the container name assert_equal(instance.name, self.name)", "flavor=flavor, volume_size=self.volume_size, databases=databases, users=users) instance.create_instance() #wait for the instance instance.wait_for_build_to_finish() #get the active", "trove.tests.util import create_client class InstanceGenerator(object): def __init__(self, client, status=None, name=None, flavor=None, account_id=None, created_at=None,", "] users = [ { \"name\": \"lite\", \"password\": \"<PASSWORD>\", \"databases\": [{\"name\": db_name}] }", "InstanceGenerator(object): def __init__(self, client, status=None, name=None, flavor=None, account_id=None, created_at=None, databases=None, users=None, volume_size=None): self.client", "active instance inst = instance.get_active_instance() #list out the databases for our instance and", "#check the container name assert_equal(instance.name, self.name) #pull out volume info and verify assert_equal(str(instance.volume_size),", "db_name } ] users = [ { \"name\": \"lite\", \"password\": \"<PASSWORD>\", \"databases\": [{\"name\":", "self.databases = databases self.users = users self.volume_size = volume_size self.id = None def", "None def create_instance(self): #make the call to create the instance instance = self.client.instances.create(self.name,", "#create the Instance instance = InstanceGenerator(client, name=self.name, flavor=flavor, volume_size=self.volume_size, databases=databases, users=users) instance.create_instance() #wait", "#make the call to create the instance instance = self.client.instances.create(self.name, self.flavor, self.volume_size, self.databases,", "= volume_size self.id = None def create_instance(self): #make the call to create the", "\"name\": db_name } ] users = [ { \"name\": \"lite\", \"password\": \"<PASSWORD>\", \"databases\":", "\"BUILD\") #pull out the ID self.id = instance.id return instance def wait_for_build_to_finish(self): poll_until(lambda:", "instance.wait_for_build_to_finish() #get the active instance inst = instance.get_active_instance() #list out the databases for", "instance def wait_for_build_to_finish(self): poll_until(lambda: self.client.instance.get(self.id), lambda instance: instance.status != \"BUILD\", time_out=600) def get_active_instance(self):", "return instance @test(groups=['smoke', 'positive']) class CreateInstance(object): @before_class def set_up(self): client = create_client(is_admin=False) name", "and verify assert_equal(str(instance.flavor), str(self.flavor)) return instance @test(groups=['smoke', 'positive']) class CreateInstance(object): @before_class def set_up(self):", "def set_up(self): client = create_client(is_admin=False) name = 'test_createInstance_container' flavor = 1 volume_size =", "flavor=None, account_id=None, created_at=None, databases=None, users=None, volume_size=None): self.client = client self.status = status self.name", "we are in a build state assert_equal(instance.status, \"BUILD\") #pull out the ID self.id", "#wait for the instance instance.wait_for_build_to_finish() #get the active instance inst = instance.get_active_instance() #list", "out the ID self.id = instance.id return instance def wait_for_build_to_finish(self): poll_until(lambda: self.client.instance.get(self.id), lambda", "volume_size = 1 db_name = 'test_db' databases = [ { \"name\": db_name }", "= instance.get_active_instance() #list out the databases for our instance and verify the db", "CreateInstance(object): @before_class def set_up(self): client = create_client(is_admin=False) name = 'test_createInstance_container' flavor = 1", "self.status = status self.name = name self.flavor = flavor self.account_id = account_id self.databases", "'positive']) class CreateInstance(object): @before_class def set_up(self): client = create_client(is_admin=False) name = 'test_createInstance_container' flavor", "= create_client(is_admin=False) name = 'test_createInstance_container' flavor = 1 volume_size = 1 db_name =", "databases for our instance and verify the db name dbs = client.databases.list(inst.id) client.assert_http_code(200)", "the db name dbs = client.databases.list(inst.id) client.assert_http_code(200) assert_equal(len(dbs), 1) assert_equal(dbs[0].name, instance.db_name) client.instance.delete(inst.id) client.assert_http_code(202)", "to create the instance instance = self.client.instances.create(self.name, self.flavor, self.volume_size, self.databases, self.users) self.client.assert_http_code(200) #verify", "proboscis import before_class from trove.common.utils import poll_until from trove.tests.util import create_client class InstanceGenerator(object):", "[ { \"name\": \"lite\", \"password\": \"<PASSWORD>\", \"databases\": [{\"name\": db_name}] } ] #create the", "info and verify assert_equal(str(instance.volume_size), str(self.volume_size)) #pull out the flavor and verify assert_equal(str(instance.flavor), str(self.flavor))", "self.client = client self.status = status self.name = name self.flavor = flavor self.account_id", "return instance def wait_for_build_to_finish(self): poll_until(lambda: self.client.instance.get(self.id), lambda instance: instance.status != \"BUILD\", time_out=600) def", "self.flavor, self.volume_size, self.databases, self.users) self.client.assert_http_code(200) #verify we are in a build state assert_equal(instance.status,", "out volume info and verify assert_equal(str(instance.volume_size), str(self.volume_size)) #pull out the flavor and verify", "= account_id self.databases = databases self.users = users self.volume_size = volume_size self.id =", "verify assert_equal(str(instance.flavor), str(self.flavor)) return instance @test(groups=['smoke', 'positive']) class CreateInstance(object): @before_class def set_up(self): client", "instance = self.client.instances.create(self.name, self.flavor, self.volume_size, self.databases, self.users) self.client.assert_http_code(200) #verify we are in a", "databases=databases, users=users) instance.create_instance() #wait for the instance instance.wait_for_build_to_finish() #get the active instance inst", "db_name = 'test_db' databases = [ { \"name\": db_name } ] users =", "state assert_equal(instance.status, \"BUILD\") #pull out the ID self.id = instance.id return instance def", "instance and verify the db name dbs = client.databases.list(inst.id) client.assert_http_code(200) assert_equal(len(dbs), 1) assert_equal(dbs[0].name,", "instance.id return instance def wait_for_build_to_finish(self): poll_until(lambda: self.client.instance.get(self.id), lambda instance: instance.status != \"BUILD\", time_out=600)", "status=None, name=None, flavor=None, account_id=None, created_at=None, databases=None, users=None, volume_size=None): self.client = client self.status =", "#pull out the ID self.id = instance.id return instance def wait_for_build_to_finish(self): poll_until(lambda: self.client.instance.get(self.id),", "= 'test_db' databases = [ { \"name\": db_name } ] users = [", "def create_instance(self): #make the call to create the instance instance = self.client.instances.create(self.name, self.flavor,", "from proboscis.asserts import assert_equal from proboscis import test from proboscis import before_class from", "from proboscis import before_class from trove.common.utils import poll_until from trove.tests.util import create_client class", "instance instance = self.client.instances.create(self.name, self.flavor, self.volume_size, self.databases, self.users) self.client.assert_http_code(200) #verify we are in", "self.volume_size, self.databases, self.users) self.client.assert_http_code(200) #verify we are in a build state assert_equal(instance.status, \"BUILD\")", "= [ { \"name\": \"lite\", \"password\": \"<PASSWORD>\", \"databases\": [{\"name\": db_name}] } ] #create", "flavor = 1 volume_size = 1 db_name = 'test_db' databases = [ {", "the call to create the instance instance = self.client.instances.create(self.name, self.flavor, self.volume_size, self.databases, self.users)", "name=None, flavor=None, account_id=None, created_at=None, databases=None, users=None, volume_size=None): self.client = client self.status = status", "and verify assert_equal(str(instance.volume_size), str(self.volume_size)) #pull out the flavor and verify assert_equal(str(instance.flavor), str(self.flavor)) return", "#list out the databases for our instance and verify the db name dbs", "{ \"name\": \"lite\", \"password\": \"<PASSWORD>\", \"databases\": [{\"name\": db_name}] } ] #create the Instance", "assert_equal(instance.status, \"BUILD\") #pull out the ID self.id = instance.id return instance def wait_for_build_to_finish(self):", "poll_until(lambda: self.client.instance.get(self.id), lambda instance: instance.status != \"BUILD\", time_out=600) def get_active_instance(self): instance = self.client.instance.get(self.id)", "flavor self.account_id = account_id self.databases = databases self.users = users self.volume_size = volume_size", "} ] #create the Instance instance = InstanceGenerator(client, name=self.name, flavor=flavor, volume_size=self.volume_size, databases=databases, users=users)", "assert_equal from proboscis import test from proboscis import before_class from trove.common.utils import poll_until", "create_client(is_admin=False) name = 'test_createInstance_container' flavor = 1 volume_size = 1 db_name = 'test_db'", "name self.flavor = flavor self.account_id = account_id self.databases = databases self.users = users", "our instance and verify the db name dbs = client.databases.list(inst.id) client.assert_http_code(200) assert_equal(len(dbs), 1)", "container name assert_equal(instance.name, self.name) #pull out volume info and verify assert_equal(str(instance.volume_size), str(self.volume_size)) #pull", "Instance instance = InstanceGenerator(client, name=self.name, flavor=flavor, volume_size=self.volume_size, databases=databases, users=users) instance.create_instance() #wait for the", "!= \"BUILD\", time_out=600) def get_active_instance(self): instance = self.client.instance.get(self.id) self.client.assert_http_code(200) #check the container name", "client self.status = status self.name = name self.flavor = flavor self.account_id = account_id", "create the instance instance = self.client.instances.create(self.name, self.flavor, self.volume_size, self.databases, self.users) self.client.assert_http_code(200) #verify we", "{ \"name\": db_name } ] users = [ { \"name\": \"lite\", \"password\": \"<PASSWORD>\",", "'test_createInstance_container' flavor = 1 volume_size = 1 db_name = 'test_db' databases = [", "the flavor and verify assert_equal(str(instance.flavor), str(self.flavor)) return instance @test(groups=['smoke', 'positive']) class CreateInstance(object): @before_class", "out the flavor and verify assert_equal(str(instance.flavor), str(self.flavor)) return instance @test(groups=['smoke', 'positive']) class CreateInstance(object):", "from proboscis import test from proboscis import before_class from trove.common.utils import poll_until from", "trove.common.utils import poll_until from trove.tests.util import create_client class InstanceGenerator(object): def __init__(self, client, status=None,", "instance = InstanceGenerator(client, name=self.name, flavor=flavor, volume_size=self.volume_size, databases=databases, users=users) instance.create_instance() #wait for the instance", "class InstanceGenerator(object): def __init__(self, client, status=None, name=None, flavor=None, account_id=None, created_at=None, databases=None, users=None, volume_size=None):", "self.volume_size = volume_size self.id = None def create_instance(self): #make the call to create", "assert_equal(instance.name, self.name) #pull out volume info and verify assert_equal(str(instance.volume_size), str(self.volume_size)) #pull out the", "\"lite\", \"password\": \"<PASSWORD>\", \"databases\": [{\"name\": db_name}] } ] #create the Instance instance =", "self.account_id = account_id self.databases = databases self.users = users self.volume_size = volume_size self.id", "instance instance.wait_for_build_to_finish() #get the active instance inst = instance.get_active_instance() #list out the databases", "client, status=None, name=None, flavor=None, account_id=None, created_at=None, databases=None, users=None, volume_size=None): self.client = client self.status", "users = [ { \"name\": \"lite\", \"password\": \"<PASSWORD>\", \"databases\": [{\"name\": db_name}] } ]", "= name self.flavor = flavor self.account_id = account_id self.databases = databases self.users =", "out the databases for our instance and verify the db name dbs =", "def wait_for_build_to_finish(self): poll_until(lambda: self.client.instance.get(self.id), lambda instance: instance.status != \"BUILD\", time_out=600) def get_active_instance(self): instance", "databases=None, users=None, volume_size=None): self.client = client self.status = status self.name = name self.flavor", "flavor and verify assert_equal(str(instance.flavor), str(self.flavor)) return instance @test(groups=['smoke', 'positive']) class CreateInstance(object): @before_class def", "are in a build state assert_equal(instance.status, \"BUILD\") #pull out the ID self.id =", "'test_db' databases = [ { \"name\": db_name } ] users = [ {", "instance @test(groups=['smoke', 'positive']) class CreateInstance(object): @before_class def set_up(self): client = create_client(is_admin=False) name =", "InstanceGenerator(client, name=self.name, flavor=flavor, volume_size=self.volume_size, databases=databases, users=users) instance.create_instance() #wait for the instance instance.wait_for_build_to_finish() #get", "str(self.volume_size)) #pull out the flavor and verify assert_equal(str(instance.flavor), str(self.flavor)) return instance @test(groups=['smoke', 'positive'])", "from trove.tests.util import create_client class InstanceGenerator(object): def __init__(self, client, status=None, name=None, flavor=None, account_id=None,", "status self.name = name self.flavor = flavor self.account_id = account_id self.databases = databases", "verify assert_equal(str(instance.volume_size), str(self.volume_size)) #pull out the flavor and verify assert_equal(str(instance.flavor), str(self.flavor)) return instance", "for our instance and verify the db name dbs = client.databases.list(inst.id) client.assert_http_code(200) assert_equal(len(dbs),", "poll_until from trove.tests.util import create_client class InstanceGenerator(object): def __init__(self, client, status=None, name=None, flavor=None,", "self.client.instance.get(self.id), lambda instance: instance.status != \"BUILD\", time_out=600) def get_active_instance(self): instance = self.client.instance.get(self.id) self.client.assert_http_code(200)", "ID self.id = instance.id return instance def wait_for_build_to_finish(self): poll_until(lambda: self.client.instance.get(self.id), lambda instance: instance.status", "proboscis import test from proboscis import before_class from trove.common.utils import poll_until from trove.tests.util", "account_id self.databases = databases self.users = users self.volume_size = volume_size self.id = None", "import assert_equal from proboscis import test from proboscis import before_class from trove.common.utils import", "__init__(self, client, status=None, name=None, flavor=None, account_id=None, created_at=None, databases=None, users=None, volume_size=None): self.client = client", "users=users) instance.create_instance() #wait for the instance instance.wait_for_build_to_finish() #get the active instance inst =", "name = 'test_createInstance_container' flavor = 1 volume_size = 1 db_name = 'test_db' databases", "@before_class def set_up(self): client = create_client(is_admin=False) name = 'test_createInstance_container' flavor = 1 volume_size", "= self.client.instance.get(self.id) self.client.assert_http_code(200) #check the container name assert_equal(instance.name, self.name) #pull out volume info", "= 'test_createInstance_container' flavor = 1 volume_size = 1 db_name = 'test_db' databases =", "db_name}] } ] #create the Instance instance = InstanceGenerator(client, name=self.name, flavor=flavor, volume_size=self.volume_size, databases=databases,", "] #create the Instance instance = InstanceGenerator(client, name=self.name, flavor=flavor, volume_size=self.volume_size, databases=databases, users=users) instance.create_instance()", "instance = self.client.instance.get(self.id) self.client.assert_http_code(200) #check the container name assert_equal(instance.name, self.name) #pull out volume", "#pull out the flavor and verify assert_equal(str(instance.flavor), str(self.flavor)) return instance @test(groups=['smoke', 'positive']) class", "#pull out volume info and verify assert_equal(str(instance.volume_size), str(self.volume_size)) #pull out the flavor and", "self.id = instance.id return instance def wait_for_build_to_finish(self): poll_until(lambda: self.client.instance.get(self.id), lambda instance: instance.status !=", "#verify we are in a build state assert_equal(instance.status, \"BUILD\") #pull out the ID", "test from proboscis import before_class from trove.common.utils import poll_until from trove.tests.util import create_client", "self.client.assert_http_code(200) #verify we are in a build state assert_equal(instance.status, \"BUILD\") #pull out the", "self.client.assert_http_code(200) #check the container name assert_equal(instance.name, self.name) #pull out volume info and verify" ]
[ "#buildings = [[0,2,3],[2,5,3]] s = [] for e in buildings: s.append([e[0],e[2]]) s.append([e[1],-e[2]]) s", "= [0] max_h = 0 for e in s: if e[1] < 0:", "[3,7,15], [5,12,12], [15,20,10], [19,24,8] ] #buildings = [[0,2,3],[2,5,3]] s = [] for e", "[ [2,9,10], [3,7,15], [5,12,12], [15,20,10], [19,24,8] ] #buildings = [[0,2,3],[2,5,3]] s = []", "res = [] h = [0] max_h = 0 for e in s:", "[[0,2,3],[2,5,3]] s = [] for e in buildings: s.append([e[0],e[2]]) s.append([e[1],-e[2]]) s = sorted(s,key=lambda", "in s: if e[1] < 0: h.remove(-e[1]) else: h.append(e[1]) if max_h != max(h):", "buildings: s.append([e[0],e[2]]) s.append([e[1],-e[2]]) s = sorted(s,key=lambda x:(x[0],-x[1])) print(s) res = [] h =", "0: h.remove(-e[1]) else: h.append(e[1]) if max_h != max(h): max_h = max(h) res.append([e[0],max_h]) print(res)", "s.append([e[0],e[2]]) s.append([e[1],-e[2]]) s = sorted(s,key=lambda x:(x[0],-x[1])) print(s) res = [] h = [0]", "sorted(s,key=lambda x:(x[0],-x[1])) print(s) res = [] h = [0] max_h = 0 for", "[0] max_h = 0 for e in s: if e[1] < 0: h.remove(-e[1])", "[19,24,8] ] #buildings = [[0,2,3],[2,5,3]] s = [] for e in buildings: s.append([e[0],e[2]])", "h = [0] max_h = 0 for e in s: if e[1] <", "= 0 for e in s: if e[1] < 0: h.remove(-e[1]) else: h.append(e[1])", "= [] for e in buildings: s.append([e[0],e[2]]) s.append([e[1],-e[2]]) s = sorted(s,key=lambda x:(x[0],-x[1])) print(s)", "buildings = [ [2,9,10], [3,7,15], [5,12,12], [15,20,10], [19,24,8] ] #buildings = [[0,2,3],[2,5,3]] s", "= [ [2,9,10], [3,7,15], [5,12,12], [15,20,10], [19,24,8] ] #buildings = [[0,2,3],[2,5,3]] s =", "< 0: h.remove(-e[1]) else: h.append(e[1]) if max_h != max(h): max_h = max(h) res.append([e[0],max_h])", "= [] h = [0] max_h = 0 for e in s: if", "if e[1] < 0: h.remove(-e[1]) else: h.append(e[1]) if max_h != max(h): max_h =", "print(s) res = [] h = [0] max_h = 0 for e in", "e in s: if e[1] < 0: h.remove(-e[1]) else: h.append(e[1]) if max_h !=", "[5,12,12], [15,20,10], [19,24,8] ] #buildings = [[0,2,3],[2,5,3]] s = [] for e in", "s = [] for e in buildings: s.append([e[0],e[2]]) s.append([e[1],-e[2]]) s = sorted(s,key=lambda x:(x[0],-x[1]))", "s = sorted(s,key=lambda x:(x[0],-x[1])) print(s) res = [] h = [0] max_h =", "max_h = 0 for e in s: if e[1] < 0: h.remove(-e[1]) else:", "x:(x[0],-x[1])) print(s) res = [] h = [0] max_h = 0 for e", "[] for e in buildings: s.append([e[0],e[2]]) s.append([e[1],-e[2]]) s = sorted(s,key=lambda x:(x[0],-x[1])) print(s) res", "] #buildings = [[0,2,3],[2,5,3]] s = [] for e in buildings: s.append([e[0],e[2]]) s.append([e[1],-e[2]])", "= sorted(s,key=lambda x:(x[0],-x[1])) print(s) res = [] h = [0] max_h = 0", "e[1] < 0: h.remove(-e[1]) else: h.append(e[1]) if max_h != max(h): max_h = max(h)", "for e in s: if e[1] < 0: h.remove(-e[1]) else: h.append(e[1]) if max_h", "in buildings: s.append([e[0],e[2]]) s.append([e[1],-e[2]]) s = sorted(s,key=lambda x:(x[0],-x[1])) print(s) res = [] h", "s.append([e[1],-e[2]]) s = sorted(s,key=lambda x:(x[0],-x[1])) print(s) res = [] h = [0] max_h", "for e in buildings: s.append([e[0],e[2]]) s.append([e[1],-e[2]]) s = sorted(s,key=lambda x:(x[0],-x[1])) print(s) res =", "0 for e in s: if e[1] < 0: h.remove(-e[1]) else: h.append(e[1]) if", "e in buildings: s.append([e[0],e[2]]) s.append([e[1],-e[2]]) s = sorted(s,key=lambda x:(x[0],-x[1])) print(s) res = []", "<gh_stars>0 buildings = [ [2,9,10], [3,7,15], [5,12,12], [15,20,10], [19,24,8] ] #buildings = [[0,2,3],[2,5,3]]", "= [[0,2,3],[2,5,3]] s = [] for e in buildings: s.append([e[0],e[2]]) s.append([e[1],-e[2]]) s =", "[] h = [0] max_h = 0 for e in s: if e[1]", "s: if e[1] < 0: h.remove(-e[1]) else: h.append(e[1]) if max_h != max(h): max_h", "[2,9,10], [3,7,15], [5,12,12], [15,20,10], [19,24,8] ] #buildings = [[0,2,3],[2,5,3]] s = [] for", "[15,20,10], [19,24,8] ] #buildings = [[0,2,3],[2,5,3]] s = [] for e in buildings:" ]
[ "cart and returns the prices with the discount applied. Round all prices to", "discount([2.99, 5.75, 3.35, 4.99]) ➞[2.47, 4.74, 2.76, 4.12] # First product for free.", "11.68]) #discount([68.74, 17.85, 55.99]) #, [60.13, 15.62, 48.98]) discount([5.75, 14.99, 36.83, 12.15, 25.30,", "[5.16, 13.45, 33.06, 10.91, 22.71, 5.16, 5.16, 5.16]) #discount([14.15, 9.45, 3.72, 5.99, 8.13,", "No cart splitting allowed. \"\"\" def discount(lst): if len(lst)<3: return(lst) e = []", "up paying $15.99 + $23.50 = $39.49, but what her receipt says is:", "takes in a list of prices for a customer's shopping cart and returns", "all products instead. For example, if a customer gets three products a, b", "48.98]) discount([5.75, 14.99, 36.83, 12.15, 25.30, 5.75, 5.75, 5.75]) #, [5.16, 13.45, 33.06,", "sum(b) d= sum(b[:-a]) for i in lst: e.append(round(i*(d/c),2)) return (e) #discount([2.99, 5.75, 3.35,", "customer's shopping cart and returns the prices with the discount applied. Round all", "[11.42, 7.63, 3.0, 4.83, 6.56, 7.14]) #discount([2.98, 0.25, 1.25]) #, [2.81, 0.24, 1.18])", "A: $15.99 − Special Discount = $12.57 Product B: $23.50 − Special Discount", "so she ends up paying $15.99 + $23.50 = $39.49, but what her", "gets 10 or 11 products, she will still get three for free. Buying", "= sum(b) d= sum(b[:-a]) for i in lst: e.append(round(i*(d/c),2)) return (e) #discount([2.99, 5.75,", "12.15, 25.30, 5.75, 5.75, 5.75]) #, [5.16, 13.45, 33.06, 10.91, 22.71, 5.16, 5.16,", "will get the three cheapest ones for free, but if she gets 10", "5.75, 3.35, 4.99]) #, [2.47, 4.74, 2.76, 4.12]) #discount([10.75, 11.68]) #, [10.75, 11.68])", "three products: if a customer gets 9 products, she will get the three", "a function that takes in a list of prices for a customer's shopping", "15.62, 48.98] # Second product for free. Notes The discount is calculated in", "get her a fourth free product. No cart splitting allowed. \"\"\" def discount(lst):", "allowed. \"\"\" def discount(lst): if len(lst)<3: return(lst) e = [] a = len(lst)//3", "an article so a discount is applied to all products instead. For example,", "still get three for free. Buying a 12th product would get her a", "c = sum(b) d= sum(b[:-a]) for i in lst: e.append(round(i*(d/c),2)) return (e) #discount([2.99,", "customer gets 9 products, she will get the three cheapest ones for free,", "11.68]) ➞ [10.75, 11.68] # No discounts applied. discount([68.74, 17.85, 55.99]) ➞ [60.13,", "three for free. Buying a 12th product would get her a fourth free", "[10.75, 11.68]) #discount([68.74, 17.85, 55.99]) #, [60.13, 15.62, 48.98]) discount([5.75, 14.99, 36.83, 12.15,", "1 free\" sale. For legal reasons, they can't charge their customers $0 for", "17.85, 55.99]) ➞ [60.13, 15.62, 48.98] # Second product for free. Notes The", "free. discount([10.75, 11.68]) ➞ [10.75, 11.68] # No discounts applied. discount([68.74, 17.85, 55.99])", "3, get 1 free\" sale. For legal reasons, they can't charge their customers", "Product C $15.99 $23.50 $10.75 She gets the cheapest one for free, so", "5.16]) #discount([14.15, 9.45, 3.72, 5.99, 8.13, 8.85]) #, [11.42, 7.63, 3.0, 4.83, 6.56,", "a list of prices for a customer's shopping cart and returns the prices", "a = len(lst)//3 b = sorted(lst,reverse=True) c = sum(b) d= sum(b[:-a]) for i", "Notes The discount is calculated in percentual terms. The deal applies to sets", "if a customer gets three products a, b and c: Product A Product", "ends up paying $15.99 + $23.50 = $39.49, but what her receipt says", "three products a, b and c: Product A Product B Product C $15.99", "their customers $0 for an article so a discount is applied to all", "C $15.99 $23.50 $10.75 She gets the cheapest one for free, so she", "− Special Discount = $8.45 Total: $39.49 Create a function that takes in", "#discount([14.15, 9.45, 3.72, 5.99, 8.13, 8.85]) #, [11.42, 7.63, 3.0, 4.83, 6.56, 7.14])", "2.76, 4.12]) #discount([10.75, 11.68]) #, [10.75, 11.68]) #discount([68.74, 17.85, 55.99]) #, [60.13, 15.62,", "Sales Season A retailer is having a store-wide \"buy 3, get 1 free\"", "= [] a = len(lst)//3 b = sorted(lst,reverse=True) c = sum(b) d= sum(b[:-a])", "deal applies to sets of three products: if a customer gets 9 products,", "gets three products a, b and c: Product A Product B Product C", "36.83, 12.15, 25.30, 5.75, 5.75, 5.75]) #, [5.16, 13.45, 33.06, 10.91, 22.71, 5.16,", "for free, but if she gets 10 or 11 products, she will still", "Product A Product B Product C $15.99 $23.50 $10.75 She gets the cheapest", "$18.47 Product C: $10.75 − Special Discount = $8.45 Total: $39.49 Create a", "sets of three products: if a customer gets 9 products, she will get", "11.68] # No discounts applied. discount([68.74, 17.85, 55.99]) ➞ [60.13, 15.62, 48.98] #", "+ $23.50 = $39.49, but what her receipt says is: Product A: $15.99", "applied. Round all prices to the cent. Examples discount([2.99, 5.75, 3.35, 4.99]) ➞[2.47,", "three cheapest ones for free, but if she gets 10 or 11 products,", "discount is calculated in percentual terms. The deal applies to sets of three", "product for free. Notes The discount is calculated in percentual terms. The deal", "$15.99 − Special Discount = $12.57 Product B: $23.50 − Special Discount =", "for free. Buying a 12th product would get her a fourth free product.", "➞ [10.75, 11.68] # No discounts applied. discount([68.74, 17.85, 55.99]) ➞ [60.13, 15.62,", "she ends up paying $15.99 + $23.50 = $39.49, but what her receipt", "5.75, 3.35, 4.99]) ➞[2.47, 4.74, 2.76, 4.12] # First product for free. discount([10.75,", "22.71, 5.16, 5.16, 5.16]) #discount([14.15, 9.45, 3.72, 5.99, 8.13, 8.85]) #, [11.42, 7.63,", "the cent. Examples discount([2.99, 5.75, 3.35, 4.99]) ➞[2.47, 4.74, 2.76, 4.12] # First", "free. Buying a 12th product would get her a fourth free product. No", "get 1 free\" sale. For legal reasons, they can't charge their customers $0", "$10.75 She gets the cheapest one for free, so she ends up paying", "Special Discount = $8.45 Total: $39.49 Create a function that takes in a", "sum(b[:-a]) for i in lst: e.append(round(i*(d/c),2)) return (e) #discount([2.99, 5.75, 3.35, 4.99]) #,", "Discount = $12.57 Product B: $23.50 − Special Discount = $18.47 Product C:", "is: Product A: $15.99 − Special Discount = $12.57 Product B: $23.50 −", "5.16, 5.16, 5.16]) #discount([14.15, 9.45, 3.72, 5.99, 8.13, 8.85]) #, [11.42, 7.63, 3.0,", "cheapest one for free, so she ends up paying $15.99 + $23.50 =", "c: Product A Product B Product C $15.99 $23.50 $10.75 She gets the", "17.85, 55.99]) #, [60.13, 15.62, 48.98]) discount([5.75, 14.99, 36.83, 12.15, 25.30, 5.75, 5.75,", "$23.50 − Special Discount = $18.47 Product C: $10.75 − Special Discount =", "discounts applied. discount([68.74, 17.85, 55.99]) ➞ [60.13, 15.62, 48.98] # Second product for", "for free. discount([10.75, 11.68]) ➞ [10.75, 11.68] # No discounts applied. discount([68.74, 17.85,", "First product for free. discount([10.75, 11.68]) ➞ [10.75, 11.68] # No discounts applied.", "legal reasons, they can't charge their customers $0 for an article so a", "10 or 11 products, she will still get three for free. Buying a", "she gets 10 or 11 products, she will still get three for free.", "[2.47, 4.74, 2.76, 4.12]) #discount([10.75, 11.68]) #, [10.75, 11.68]) #discount([68.74, 17.85, 55.99]) #,", "applies to sets of three products: if a customer gets 9 products, she", "Special Discount = $18.47 Product C: $10.75 − Special Discount = $8.45 Total:", "7.63, 3.0, 4.83, 6.56, 7.14]) #discount([2.98, 0.25, 1.25]) #, [2.81, 0.24, 1.18]) #discount([9.20])", "what her receipt says is: Product A: $15.99 − Special Discount = $12.57", "Discount = $8.45 Total: $39.49 Create a function that takes in a list", "product. No cart splitting allowed. \"\"\" def discount(lst): if len(lst)<3: return(lst) e =", "her receipt says is: Product A: $15.99 − Special Discount = $12.57 Product", "she will get the three cheapest ones for free, but if she gets", "#discount([10.75, 11.68]) #, [10.75, 11.68]) #discount([68.74, 17.85, 55.99]) #, [60.13, 15.62, 48.98]) discount([5.75,", "prices to the cent. Examples discount([2.99, 5.75, 3.35, 4.99]) ➞[2.47, 4.74, 2.76, 4.12]", "gets 9 products, she will get the three cheapest ones for free, but", "Special Discount = $12.57 Product B: $23.50 − Special Discount = $18.47 Product", "$15.99 $23.50 $10.75 She gets the cheapest one for free, so she ends", "− Special Discount = $12.57 Product B: $23.50 − Special Discount = $18.47", "$10.75 − Special Discount = $8.45 Total: $39.49 Create a function that takes", "Season A retailer is having a store-wide \"buy 3, get 1 free\" sale.", "$23.50 = $39.49, but what her receipt says is: Product A: $15.99 −", "Discount = $18.47 Product C: $10.75 − Special Discount = $8.45 Total: $39.49", "= sorted(lst,reverse=True) c = sum(b) d= sum(b[:-a]) for i in lst: e.append(round(i*(d/c),2)) return", "4.99]) ➞[2.47, 4.74, 2.76, 4.12] # First product for free. discount([10.75, 11.68]) ➞", "returns the prices with the discount applied. Round all prices to the cent.", "applied to all products instead. For example, if a customer gets three products", "free, but if she gets 10 or 11 products, she will still get", "free\" sale. For legal reasons, they can't charge their customers $0 for an", "charge their customers $0 for an article so a discount is applied to", "11 products, she will still get three for free. Buying a 12th product", "discount([5.75, 14.99, 36.83, 12.15, 25.30, 5.75, 5.75, 5.75]) #, [5.16, 13.45, 33.06, 10.91,", "is applied to all products instead. For example, if a customer gets three", "Product B: $23.50 − Special Discount = $18.47 Product C: $10.75 − Special", "13.45, 33.06, 10.91, 22.71, 5.16, 5.16, 5.16]) #discount([14.15, 9.45, 3.72, 5.99, 8.13, 8.85])", "says is: Product A: $15.99 − Special Discount = $12.57 Product B: $23.50", "prices with the discount applied. Round all prices to the cent. Examples discount([2.99,", "the discount applied. Round all prices to the cent. Examples discount([2.99, 5.75, 3.35,", "retailer is having a store-wide \"buy 3, get 1 free\" sale. For legal", "but what her receipt says is: Product A: $15.99 − Special Discount =", "so a discount is applied to all products instead. For example, if a", "Buying a 12th product would get her a fourth free product. No cart", "b = sorted(lst,reverse=True) c = sum(b) d= sum(b[:-a]) for i in lst: e.append(round(i*(d/c),2))", "She gets the cheapest one for free, so she ends up paying $15.99", "discount([68.74, 17.85, 55.99]) ➞ [60.13, 15.62, 48.98] # Second product for free. Notes", "get the three cheapest ones for free, but if she gets 10 or", "cart splitting allowed. \"\"\" def discount(lst): if len(lst)<3: return(lst) e = [] a", "shopping cart and returns the prices with the discount applied. Round all prices", "with the discount applied. Round all prices to the cent. Examples discount([2.99, 5.75,", "= len(lst)//3 b = sorted(lst,reverse=True) c = sum(b) d= sum(b[:-a]) for i in", "prices for a customer's shopping cart and returns the prices with the discount", "[60.13, 15.62, 48.98]) discount([5.75, 14.99, 36.83, 12.15, 25.30, 5.75, 5.75, 5.75]) #, [5.16,", "B Product C $15.99 $23.50 $10.75 She gets the cheapest one for free,", "# No discounts applied. discount([68.74, 17.85, 55.99]) ➞ [60.13, 15.62, 48.98] # Second", "can't charge their customers $0 for an article so a discount is applied", "def discount(lst): if len(lst)<3: return(lst) e = [] a = len(lst)//3 b =", "#, [5.16, 13.45, 33.06, 10.91, 22.71, 5.16, 5.16, 5.16]) #discount([14.15, 9.45, 3.72, 5.99,", "Round all prices to the cent. Examples discount([2.99, 5.75, 3.35, 4.99]) ➞[2.47, 4.74,", "list of prices for a customer's shopping cart and returns the prices with", "8.85]) #, [11.42, 7.63, 3.0, 4.83, 6.56, 7.14]) #discount([2.98, 0.25, 1.25]) #, [2.81,", "in lst: e.append(round(i*(d/c),2)) return (e) #discount([2.99, 5.75, 3.35, 4.99]) #, [2.47, 4.74, 2.76,", "free, so she ends up paying $15.99 + $23.50 = $39.49, but what", "Second product for free. Notes The discount is calculated in percentual terms. The", "[10.75, 11.68] # No discounts applied. discount([68.74, 17.85, 55.99]) ➞ [60.13, 15.62, 48.98]", "# Second product for free. Notes The discount is calculated in percentual terms.", "For legal reasons, they can't charge their customers $0 for an article so", "14.99, 36.83, 12.15, 25.30, 5.75, 5.75, 5.75]) #, [5.16, 13.45, 33.06, 10.91, 22.71,", "example, if a customer gets three products a, b and c: Product A", "4.83, 6.56, 7.14]) #discount([2.98, 0.25, 1.25]) #, [2.81, 0.24, 1.18]) #discount([9.20]) #, [9.20])", "she will still get three for free. Buying a 12th product would get", "will still get three for free. Buying a 12th product would get her", "#, [10.75, 11.68]) #discount([68.74, 17.85, 55.99]) #, [60.13, 15.62, 48.98]) discount([5.75, 14.99, 36.83,", "a discount is applied to all products instead. For example, if a customer", "in percentual terms. The deal applies to sets of three products: if a", "products instead. For example, if a customer gets three products a, b and", "one for free, so she ends up paying $15.99 + $23.50 = $39.49,", "cent. Examples discount([2.99, 5.75, 3.35, 4.99]) ➞[2.47, 4.74, 2.76, 4.12] # First product", "terms. The deal applies to sets of three products: if a customer gets", "15.62, 48.98]) discount([5.75, 14.99, 36.83, 12.15, 25.30, 5.75, 5.75, 5.75]) #, [5.16, 13.45,", "= $8.45 Total: $39.49 Create a function that takes in a list of", "➞ [60.13, 15.62, 48.98] # Second product for free. Notes The discount is", "the cheapest one for free, so she ends up paying $15.99 + $23.50", "\"\"\" def discount(lst): if len(lst)<3: return(lst) e = [] a = len(lst)//3 b", "\"\"\" Sales Season A retailer is having a store-wide \"buy 3, get 1", "3.35, 4.99]) ➞[2.47, 4.74, 2.76, 4.12] # First product for free. discount([10.75, 11.68])", "discount applied. Round all prices to the cent. Examples discount([2.99, 5.75, 3.35, 4.99])", "Product C: $10.75 − Special Discount = $8.45 Total: $39.49 Create a function", "$0 for an article so a discount is applied to all products instead.", "48.98] # Second product for free. Notes The discount is calculated in percentual", "[] a = len(lst)//3 b = sorted(lst,reverse=True) c = sum(b) d= sum(b[:-a]) for", "all prices to the cent. Examples discount([2.99, 5.75, 3.35, 4.99]) ➞[2.47, 4.74, 2.76,", "#discount([2.99, 5.75, 3.35, 4.99]) #, [2.47, 4.74, 2.76, 4.12]) #discount([10.75, 11.68]) #, [10.75,", "# First product for free. discount([10.75, 11.68]) ➞ [10.75, 11.68] # No discounts", "customers $0 for an article so a discount is applied to all products", "reasons, they can't charge their customers $0 for an article so a discount", "= $39.49, but what her receipt says is: Product A: $15.99 − Special", "3.72, 5.99, 8.13, 8.85]) #, [11.42, 7.63, 3.0, 4.83, 6.56, 7.14]) #discount([2.98, 0.25,", "Product A: $15.99 − Special Discount = $12.57 Product B: $23.50 − Special", "4.12]) #discount([10.75, 11.68]) #, [10.75, 11.68]) #discount([68.74, 17.85, 55.99]) #, [60.13, 15.62, 48.98])", "sale. For legal reasons, they can't charge their customers $0 for an article", "paying $15.99 + $23.50 = $39.49, but what her receipt says is: Product", "free product. No cart splitting allowed. \"\"\" def discount(lst): if len(lst)<3: return(lst) e", "products, she will get the three cheapest ones for free, but if she", "would get her a fourth free product. No cart splitting allowed. \"\"\" def", "4.74, 2.76, 4.12] # First product for free. discount([10.75, 11.68]) ➞ [10.75, 11.68]", "4.74, 2.76, 4.12]) #discount([10.75, 11.68]) #, [10.75, 11.68]) #discount([68.74, 17.85, 55.99]) #, [60.13,", "The deal applies to sets of three products: if a customer gets 9", "they can't charge their customers $0 for an article so a discount is", "if a customer gets 9 products, she will get the three cheapest ones", "(e) #discount([2.99, 5.75, 3.35, 4.99]) #, [2.47, 4.74, 2.76, 4.12]) #discount([10.75, 11.68]) #,", "a customer gets three products a, b and c: Product A Product B", "cheapest ones for free, but if she gets 10 or 11 products, she", "$39.49, but what her receipt says is: Product A: $15.99 − Special Discount", "splitting allowed. \"\"\" def discount(lst): if len(lst)<3: return(lst) e = [] a =", "receipt says is: Product A: $15.99 − Special Discount = $12.57 Product B:", "having a store-wide \"buy 3, get 1 free\" sale. For legal reasons, they", "products, she will still get three for free. Buying a 12th product would", "article so a discount is applied to all products instead. For example, if", "for i in lst: e.append(round(i*(d/c),2)) return (e) #discount([2.99, 5.75, 3.35, 4.99]) #, [2.47,", "for a customer's shopping cart and returns the prices with the discount applied.", "e.append(round(i*(d/c),2)) return (e) #discount([2.99, 5.75, 3.35, 4.99]) #, [2.47, 4.74, 2.76, 4.12]) #discount([10.75,", "$12.57 Product B: $23.50 − Special Discount = $18.47 Product C: $10.75 −", "No discounts applied. discount([68.74, 17.85, 55.99]) ➞ [60.13, 15.62, 48.98] # Second product", "for an article so a discount is applied to all products instead. For", "or 11 products, she will still get three for free. Buying a 12th", "55.99]) ➞ [60.13, 15.62, 48.98] # Second product for free. Notes The discount", "A Product B Product C $15.99 $23.50 $10.75 She gets the cheapest one", "Product B Product C $15.99 $23.50 $10.75 She gets the cheapest one for", "5.75]) #, [5.16, 13.45, 33.06, 10.91, 22.71, 5.16, 5.16, 5.16]) #discount([14.15, 9.45, 3.72,", "= $18.47 Product C: $10.75 − Special Discount = $8.45 Total: $39.49 Create", "➞[2.47, 4.74, 2.76, 4.12] # First product for free. discount([10.75, 11.68]) ➞ [10.75,", "get three for free. Buying a 12th product would get her a fourth", "the prices with the discount applied. Round all prices to the cent. Examples", "in a list of prices for a customer's shopping cart and returns the", "$8.45 Total: $39.49 Create a function that takes in a list of prices", "a 12th product would get her a fourth free product. No cart splitting", "a fourth free product. No cart splitting allowed. \"\"\" def discount(lst): if len(lst)<3:", "is having a store-wide \"buy 3, get 1 free\" sale. For legal reasons,", "function that takes in a list of prices for a customer's shopping cart", "#, [60.13, 15.62, 48.98]) discount([5.75, 14.99, 36.83, 12.15, 25.30, 5.75, 5.75, 5.75]) #,", "$39.49 Create a function that takes in a list of prices for a", "Examples discount([2.99, 5.75, 3.35, 4.99]) ➞[2.47, 4.74, 2.76, 4.12] # First product for", "fourth free product. No cart splitting allowed. \"\"\" def discount(lst): if len(lst)<3: return(lst)", "to sets of three products: if a customer gets 9 products, she will", "5.99, 8.13, 8.85]) #, [11.42, 7.63, 3.0, 4.83, 6.56, 7.14]) #discount([2.98, 0.25, 1.25])", "free. Notes The discount is calculated in percentual terms. The deal applies to", "2.76, 4.12] # First product for free. discount([10.75, 11.68]) ➞ [10.75, 11.68] #", "product for free. discount([10.75, 11.68]) ➞ [10.75, 11.68] # No discounts applied. discount([68.74,", "$23.50 $10.75 She gets the cheapest one for free, so she ends up", "12th product would get her a fourth free product. No cart splitting allowed.", "to all products instead. For example, if a customer gets three products a,", "customer gets three products a, b and c: Product A Product B Product", "gets the cheapest one for free, so she ends up paying $15.99 +", "9 products, she will get the three cheapest ones for free, but if", "11.68]) #, [10.75, 11.68]) #discount([68.74, 17.85, 55.99]) #, [60.13, 15.62, 48.98]) discount([5.75, 14.99,", "percentual terms. The deal applies to sets of three products: if a customer", "5.16, 5.16]) #discount([14.15, 9.45, 3.72, 5.99, 8.13, 8.85]) #, [11.42, 7.63, 3.0, 4.83,", "and returns the prices with the discount applied. Round all prices to the", "discount(lst): if len(lst)<3: return(lst) e = [] a = len(lst)//3 b = sorted(lst,reverse=True)", "A retailer is having a store-wide \"buy 3, get 1 free\" sale. For", "10.91, 22.71, 5.16, 5.16, 5.16]) #discount([14.15, 9.45, 3.72, 5.99, 8.13, 8.85]) #, [11.42,", "products a, b and c: Product A Product B Product C $15.99 $23.50", "calculated in percentual terms. The deal applies to sets of three products: if", "lst: e.append(round(i*(d/c),2)) return (e) #discount([2.99, 5.75, 3.35, 4.99]) #, [2.47, 4.74, 2.76, 4.12])", "that takes in a list of prices for a customer's shopping cart and", "5.75, 5.75]) #, [5.16, 13.45, 33.06, 10.91, 22.71, 5.16, 5.16, 5.16]) #discount([14.15, 9.45,", "discount is applied to all products instead. For example, if a customer gets", "e = [] a = len(lst)//3 b = sorted(lst,reverse=True) c = sum(b) d=", "len(lst)<3: return(lst) e = [] a = len(lst)//3 b = sorted(lst,reverse=True) c =", "4.12] # First product for free. discount([10.75, 11.68]) ➞ [10.75, 11.68] # No", "her a fourth free product. No cart splitting allowed. \"\"\" def discount(lst): if", "but if she gets 10 or 11 products, she will still get three", "a, b and c: Product A Product B Product C $15.99 $23.50 $10.75", "For example, if a customer gets three products a, b and c: Product", "a store-wide \"buy 3, get 1 free\" sale. For legal reasons, they can't", "3.0, 4.83, 6.56, 7.14]) #discount([2.98, 0.25, 1.25]) #, [2.81, 0.24, 1.18]) #discount([9.20]) #,", "if len(lst)<3: return(lst) e = [] a = len(lst)//3 b = sorted(lst,reverse=True) c", "Total: $39.49 Create a function that takes in a list of prices for", "#, [11.42, 7.63, 3.0, 4.83, 6.56, 7.14]) #discount([2.98, 0.25, 1.25]) #, [2.81, 0.24,", "C: $10.75 − Special Discount = $8.45 Total: $39.49 Create a function that", "55.99]) #, [60.13, 15.62, 48.98]) discount([5.75, 14.99, 36.83, 12.15, 25.30, 5.75, 5.75, 5.75])", "− Special Discount = $18.47 Product C: $10.75 − Special Discount = $8.45", "if she gets 10 or 11 products, she will still get three for", "= $12.57 Product B: $23.50 − Special Discount = $18.47 Product C: $10.75", "Create a function that takes in a list of prices for a customer's", "$15.99 + $23.50 = $39.49, but what her receipt says is: Product A:", "for free, so she ends up paying $15.99 + $23.50 = $39.49, but", "d= sum(b[:-a]) for i in lst: e.append(round(i*(d/c),2)) return (e) #discount([2.99, 5.75, 3.35, 4.99])", "5.75, 5.75, 5.75]) #, [5.16, 13.45, 33.06, 10.91, 22.71, 5.16, 5.16, 5.16]) #discount([14.15,", "applied. discount([68.74, 17.85, 55.99]) ➞ [60.13, 15.62, 48.98] # Second product for free.", "25.30, 5.75, 5.75, 5.75]) #, [5.16, 13.45, 33.06, 10.91, 22.71, 5.16, 5.16, 5.16])", "is calculated in percentual terms. The deal applies to sets of three products:", "3.35, 4.99]) #, [2.47, 4.74, 2.76, 4.12]) #discount([10.75, 11.68]) #, [10.75, 11.68]) #discount([68.74,", "of prices for a customer's shopping cart and returns the prices with the", "\"buy 3, get 1 free\" sale. For legal reasons, they can't charge their", "[60.13, 15.62, 48.98] # Second product for free. Notes The discount is calculated", "b and c: Product A Product B Product C $15.99 $23.50 $10.75 She", "a customer's shopping cart and returns the prices with the discount applied. Round", "product would get her a fourth free product. No cart splitting allowed. \"\"\"", "return(lst) e = [] a = len(lst)//3 b = sorted(lst,reverse=True) c = sum(b)", "#, [2.47, 4.74, 2.76, 4.12]) #discount([10.75, 11.68]) #, [10.75, 11.68]) #discount([68.74, 17.85, 55.99])", "of three products: if a customer gets 9 products, she will get the", "to the cent. Examples discount([2.99, 5.75, 3.35, 4.99]) ➞[2.47, 4.74, 2.76, 4.12] #", "store-wide \"buy 3, get 1 free\" sale. For legal reasons, they can't charge", "B: $23.50 − Special Discount = $18.47 Product C: $10.75 − Special Discount", "and c: Product A Product B Product C $15.99 $23.50 $10.75 She gets", "9.45, 3.72, 5.99, 8.13, 8.85]) #, [11.42, 7.63, 3.0, 4.83, 6.56, 7.14]) #discount([2.98,", "for free. Notes The discount is calculated in percentual terms. The deal applies", "#discount([68.74, 17.85, 55.99]) #, [60.13, 15.62, 48.98]) discount([5.75, 14.99, 36.83, 12.15, 25.30, 5.75,", "33.06, 10.91, 22.71, 5.16, 5.16, 5.16]) #discount([14.15, 9.45, 3.72, 5.99, 8.13, 8.85]) #,", "discount([10.75, 11.68]) ➞ [10.75, 11.68] # No discounts applied. discount([68.74, 17.85, 55.99]) ➞", "products: if a customer gets 9 products, she will get the three cheapest", "return (e) #discount([2.99, 5.75, 3.35, 4.99]) #, [2.47, 4.74, 2.76, 4.12]) #discount([10.75, 11.68])", "a customer gets 9 products, she will get the three cheapest ones for", "ones for free, but if she gets 10 or 11 products, she will", "The discount is calculated in percentual terms. The deal applies to sets of", "the three cheapest ones for free, but if she gets 10 or 11", "4.99]) #, [2.47, 4.74, 2.76, 4.12]) #discount([10.75, 11.68]) #, [10.75, 11.68]) #discount([68.74, 17.85,", "8.13, 8.85]) #, [11.42, 7.63, 3.0, 4.83, 6.56, 7.14]) #discount([2.98, 0.25, 1.25]) #,", "sorted(lst,reverse=True) c = sum(b) d= sum(b[:-a]) for i in lst: e.append(round(i*(d/c),2)) return (e)", "len(lst)//3 b = sorted(lst,reverse=True) c = sum(b) d= sum(b[:-a]) for i in lst:", "instead. For example, if a customer gets three products a, b and c:", "i in lst: e.append(round(i*(d/c),2)) return (e) #discount([2.99, 5.75, 3.35, 4.99]) #, [2.47, 4.74," ]
[ "= loader.GameJsonResolver.from_handle(handle) games = {game['id']: game for game in resolver} game = games['14395861']", "Q def test_load(): dump = testutils.testdata / 'dump.json' with open(dump) as handle: resolver", "<filename>tests/test_load.py import testutils from fafalytics import loader from fafalytics.pyutils import Query as Q", "fafalytics import loader from fafalytics.pyutils import Query as Q def test_load(): dump =", "handle: resolver = loader.GameJsonResolver.from_handle(handle) games = {game['id']: game for game in resolver} game", "resolver = loader.GameJsonResolver.from_handle(handle) games = {game['id']: game for game in resolver} game =", "with open(dump) as handle: resolver = loader.GameJsonResolver.from_handle(handle) games = {game['id']: game for game", "loader.GameJsonResolver.from_handle(handle) games = {game['id']: game for game in resolver} game = games['14395861'] assert", "Query as Q def test_load(): dump = testutils.testdata / 'dump.json' with open(dump) as", "test_load(): dump = testutils.testdata / 'dump.json' with open(dump) as handle: resolver = loader.GameJsonResolver.from_handle(handle)", "as handle: resolver = loader.GameJsonResolver.from_handle(handle) games = {game['id']: game for game in resolver}", "/ 'dump.json' with open(dump) as handle: resolver = loader.GameJsonResolver.from_handle(handle) games = {game['id']: game", "from fafalytics import loader from fafalytics.pyutils import Query as Q def test_load(): dump", "testutils from fafalytics import loader from fafalytics.pyutils import Query as Q def test_load():", "'dump.json' with open(dump) as handle: resolver = loader.GameJsonResolver.from_handle(handle) games = {game['id']: game for", "import Query as Q def test_load(): dump = testutils.testdata / 'dump.json' with open(dump)", "as Q def test_load(): dump = testutils.testdata / 'dump.json' with open(dump) as handle:", "testutils.testdata / 'dump.json' with open(dump) as handle: resolver = loader.GameJsonResolver.from_handle(handle) games = {game['id']:", "import testutils from fafalytics import loader from fafalytics.pyutils import Query as Q def", "dump = testutils.testdata / 'dump.json' with open(dump) as handle: resolver = loader.GameJsonResolver.from_handle(handle) games", "fafalytics.pyutils import Query as Q def test_load(): dump = testutils.testdata / 'dump.json' with", "= {game['id']: game for game in resolver} game = games['14395861'] assert Q('playerStats/0/id')(game) ==", "import loader from fafalytics.pyutils import Query as Q def test_load(): dump = testutils.testdata", "open(dump) as handle: resolver = loader.GameJsonResolver.from_handle(handle) games = {game['id']: game for game in", "from fafalytics.pyutils import Query as Q def test_load(): dump = testutils.testdata / 'dump.json'", "loader from fafalytics.pyutils import Query as Q def test_load(): dump = testutils.testdata /", "def test_load(): dump = testutils.testdata / 'dump.json' with open(dump) as handle: resolver =", "games = {game['id']: game for game in resolver} game = games['14395861'] assert Q('playerStats/0/id')(game)", "{game['id']: game for game in resolver} game = games['14395861'] assert Q('playerStats/0/id')(game) == '28030229'", "= testutils.testdata / 'dump.json' with open(dump) as handle: resolver = loader.GameJsonResolver.from_handle(handle) games =" ]
[ "config env = os.environ.get('WEBAPP_ENV', 'dev') app = app() migrate = Migrate(app, db) manager", "from flask_sqlalchemy import SQLAlchemy from flask.ext.migrate import Migrate, MigrateCommand from flask.ext.script import Manager,", "dev config env = os.environ.get('WEBAPP_ENV', 'dev') app = app() migrate = Migrate(app, db)", "os from orchestrator.app import app from flask_sqlalchemy import SQLAlchemy from flask.ext.migrate import Migrate,", "= app() migrate = Migrate(app, db) manager = Manager(app) manager.add_command(\"server\", Server()) manager.add_command('db', MigrateCommand)", "= Manager(app) manager.add_command(\"server\", Server()) manager.add_command('db', MigrateCommand) @manager.shell def make_shell_context(): return dict( app=app, db=db,", "app from flask_sqlalchemy import SQLAlchemy from flask.ext.migrate import Migrate, MigrateCommand from flask.ext.script import", "migrate = Migrate(app, db) manager = Manager(app) manager.add_command(\"server\", Server()) manager.add_command('db', MigrateCommand) @manager.shell def", "db = SQLAlchemy(app) # default to dev config env = os.environ.get('WEBAPP_ENV', 'dev') app", "import SQLAlchemy from flask.ext.migrate import Migrate, MigrateCommand from flask.ext.script import Manager, Server host", "Server host = app.config['HOST'] db_url= app.config['SQLALCHEMY_DATABASE_URI'] db = SQLAlchemy(app) # default to dev", "MigrateCommand from flask.ext.script import Manager, Server host = app.config['HOST'] db_url= app.config['SQLALCHEMY_DATABASE_URI'] db =", "manager.add_command(\"server\", Server()) manager.add_command('db', MigrateCommand) @manager.shell def make_shell_context(): return dict( app=app, db=db, ) if", "flask.ext.script import Manager, Server host = app.config['HOST'] db_url= app.config['SQLALCHEMY_DATABASE_URI'] db = SQLAlchemy(app) #", "to dev config env = os.environ.get('WEBAPP_ENV', 'dev') app = app() migrate = Migrate(app,", "import os from orchestrator.app import app from flask_sqlalchemy import SQLAlchemy from flask.ext.migrate import", "Server()) manager.add_command('db', MigrateCommand) @manager.shell def make_shell_context(): return dict( app=app, db=db, ) if __name__", "manager.add_command('db', MigrateCommand) @manager.shell def make_shell_context(): return dict( app=app, db=db, ) if __name__ ==", "from flask.ext.migrate import Migrate, MigrateCommand from flask.ext.script import Manager, Server host = app.config['HOST']", "from orchestrator.app import app from flask_sqlalchemy import SQLAlchemy from flask.ext.migrate import Migrate, MigrateCommand", "@manager.shell def make_shell_context(): return dict( app=app, db=db, ) if __name__ == \"__main__\": manager.run()", "= os.environ.get('WEBAPP_ENV', 'dev') app = app() migrate = Migrate(app, db) manager = Manager(app)", "default to dev config env = os.environ.get('WEBAPP_ENV', 'dev') app = app() migrate =", "os.environ.get('WEBAPP_ENV', 'dev') app = app() migrate = Migrate(app, db) manager = Manager(app) manager.add_command(\"server\",", "import app from flask_sqlalchemy import SQLAlchemy from flask.ext.migrate import Migrate, MigrateCommand from flask.ext.script", "MigrateCommand) @manager.shell def make_shell_context(): return dict( app=app, db=db, ) if __name__ == \"__main__\":", "SQLAlchemy(app) # default to dev config env = os.environ.get('WEBAPP_ENV', 'dev') app = app()", "Migrate, MigrateCommand from flask.ext.script import Manager, Server host = app.config['HOST'] db_url= app.config['SQLALCHEMY_DATABASE_URI'] db", "import Manager, Server host = app.config['HOST'] db_url= app.config['SQLALCHEMY_DATABASE_URI'] db = SQLAlchemy(app) # default", "flask_sqlalchemy import SQLAlchemy from flask.ext.migrate import Migrate, MigrateCommand from flask.ext.script import Manager, Server", "= SQLAlchemy(app) # default to dev config env = os.environ.get('WEBAPP_ENV', 'dev') app =", "# default to dev config env = os.environ.get('WEBAPP_ENV', 'dev') app = app() migrate", "import Migrate, MigrateCommand from flask.ext.script import Manager, Server host = app.config['HOST'] db_url= app.config['SQLALCHEMY_DATABASE_URI']", "host = app.config['HOST'] db_url= app.config['SQLALCHEMY_DATABASE_URI'] db = SQLAlchemy(app) # default to dev config", "db_url= app.config['SQLALCHEMY_DATABASE_URI'] db = SQLAlchemy(app) # default to dev config env = os.environ.get('WEBAPP_ENV',", "'dev') app = app() migrate = Migrate(app, db) manager = Manager(app) manager.add_command(\"server\", Server())", "app.config['HOST'] db_url= app.config['SQLALCHEMY_DATABASE_URI'] db = SQLAlchemy(app) # default to dev config env =", "from flask.ext.script import Manager, Server host = app.config['HOST'] db_url= app.config['SQLALCHEMY_DATABASE_URI'] db = SQLAlchemy(app)", "= Migrate(app, db) manager = Manager(app) manager.add_command(\"server\", Server()) manager.add_command('db', MigrateCommand) @manager.shell def make_shell_context():", "flask.ext.migrate import Migrate, MigrateCommand from flask.ext.script import Manager, Server host = app.config['HOST'] db_url=", "sys import os from orchestrator.app import app from flask_sqlalchemy import SQLAlchemy from flask.ext.migrate", "SQLAlchemy from flask.ext.migrate import Migrate, MigrateCommand from flask.ext.script import Manager, Server host =", "app = app() migrate = Migrate(app, db) manager = Manager(app) manager.add_command(\"server\", Server()) manager.add_command('db',", "app() migrate = Migrate(app, db) manager = Manager(app) manager.add_command(\"server\", Server()) manager.add_command('db', MigrateCommand) @manager.shell", "Manager(app) manager.add_command(\"server\", Server()) manager.add_command('db', MigrateCommand) @manager.shell def make_shell_context(): return dict( app=app, db=db, )", "env = os.environ.get('WEBAPP_ENV', 'dev') app = app() migrate = Migrate(app, db) manager =", "manager = Manager(app) manager.add_command(\"server\", Server()) manager.add_command('db', MigrateCommand) @manager.shell def make_shell_context(): return dict( app=app,", "orchestrator.app import app from flask_sqlalchemy import SQLAlchemy from flask.ext.migrate import Migrate, MigrateCommand from", "Manager, Server host = app.config['HOST'] db_url= app.config['SQLALCHEMY_DATABASE_URI'] db = SQLAlchemy(app) # default to", "= app.config['HOST'] db_url= app.config['SQLALCHEMY_DATABASE_URI'] db = SQLAlchemy(app) # default to dev config env", "<reponame>contrailnfx/Controller<filename>manager.py import sys import os from orchestrator.app import app from flask_sqlalchemy import SQLAlchemy", "Migrate(app, db) manager = Manager(app) manager.add_command(\"server\", Server()) manager.add_command('db', MigrateCommand) @manager.shell def make_shell_context(): return", "db) manager = Manager(app) manager.add_command(\"server\", Server()) manager.add_command('db', MigrateCommand) @manager.shell def make_shell_context(): return dict(", "app.config['SQLALCHEMY_DATABASE_URI'] db = SQLAlchemy(app) # default to dev config env = os.environ.get('WEBAPP_ENV', 'dev')", "import sys import os from orchestrator.app import app from flask_sqlalchemy import SQLAlchemy from" ]
[ "PyUnusedLocal @ChainerConverter.register_handler(\"Gaussian\") def _convert_gaussian(converter: ChainerConverter, c_op: \"chainer.functions.Gaussian\"): # TODO raise NotImplementedError(\"[ChainerConverter] Gaussian is", "ChainerConverter, c_op: \"chainer.functions.Gaussian\"): # TODO raise NotImplementedError(\"[ChainerConverter] Gaussian is not supported\") # noinspection", "c_op: \"chainer.functions.Dropout\"): console.warning(\"[ChainerConverter] Dropout is ignored\") x = converter.get_variable(c_op.inputs[0]) converter.set_variable(c_op.outputs[0](), x) # noinspection", "\"chainer.functions.SimplifiedDropconnect\"): # TODO raise NotImplementedError(\"[ChainerConverter] SimplifiedDropconnect is not supported\") # noinspection PyUnusedLocal @ChainerConverter.register_handler(\"Zoneout\")", "from webdnn.util import console @ChainerConverter.register_handler(\"Dropout\") def _convert_dropout(converter: ChainerConverter, c_op: \"chainer.functions.Dropout\"): console.warning(\"[ChainerConverter] Dropout is", "raise NotImplementedError(\"[ChainerConverter] Gaussian is not supported\") # noinspection PyUnusedLocal @ChainerConverter.register_handler(\"SimplifiedDropconnect\") def _convert_simplified_dropconnect(converter: ChainerConverter,", "not supported\") # noinspection PyUnusedLocal @ChainerConverter.register_handler(\"SimplifiedDropconnect\") def _convert_simplified_dropconnect(converter: ChainerConverter, c_op: \"chainer.functions.SimplifiedDropconnect\"): # TODO", "@ChainerConverter.register_handler(\"Zoneout\") def _convert_zoneout(converter: ChainerConverter, c_op: \"chainer.functions.Zoneout\"): # TODO raise NotImplementedError(\"[ChainerConverter] Zoneout is not", "noinspection PyUnusedLocal @ChainerConverter.register_handler(\"SimplifiedDropconnect\") def _convert_simplified_dropconnect(converter: ChainerConverter, c_op: \"chainer.functions.SimplifiedDropconnect\"): # TODO raise NotImplementedError(\"[ChainerConverter] SimplifiedDropconnect", "_convert_simplified_dropconnect(converter: ChainerConverter, c_op: \"chainer.functions.SimplifiedDropconnect\"): # TODO raise NotImplementedError(\"[ChainerConverter] SimplifiedDropconnect is not supported\") #", "webdnn.frontend.chainer.converter import ChainerConverter from webdnn.util import console @ChainerConverter.register_handler(\"Dropout\") def _convert_dropout(converter: ChainerConverter, c_op: \"chainer.functions.Dropout\"):", "@ChainerConverter.register_handler(\"Dropout\") def _convert_dropout(converter: ChainerConverter, c_op: \"chainer.functions.Dropout\"): console.warning(\"[ChainerConverter] Dropout is ignored\") x = converter.get_variable(c_op.inputs[0])", "Gaussian is not supported\") # noinspection PyUnusedLocal @ChainerConverter.register_handler(\"SimplifiedDropconnect\") def _convert_simplified_dropconnect(converter: ChainerConverter, c_op: \"chainer.functions.SimplifiedDropconnect\"):", "not supported\") # noinspection PyUnusedLocal @ChainerConverter.register_handler(\"Zoneout\") def _convert_zoneout(converter: ChainerConverter, c_op: \"chainer.functions.Zoneout\"): # TODO", "PyUnusedLocal @ChainerConverter.register_handler(\"Zoneout\") def _convert_zoneout(converter: ChainerConverter, c_op: \"chainer.functions.Zoneout\"): # TODO raise NotImplementedError(\"[ChainerConverter] Zoneout is", "ChainerConverter from webdnn.util import console @ChainerConverter.register_handler(\"Dropout\") def _convert_dropout(converter: ChainerConverter, c_op: \"chainer.functions.Dropout\"): console.warning(\"[ChainerConverter] Dropout", "console.warning(\"[ChainerConverter] Dropout is ignored\") x = converter.get_variable(c_op.inputs[0]) converter.set_variable(c_op.outputs[0](), x) # noinspection PyUnusedLocal @ChainerConverter.register_handler(\"Gaussian\")", "import console @ChainerConverter.register_handler(\"Dropout\") def _convert_dropout(converter: ChainerConverter, c_op: \"chainer.functions.Dropout\"): console.warning(\"[ChainerConverter] Dropout is ignored\") x", "supported\") # noinspection PyUnusedLocal @ChainerConverter.register_handler(\"SimplifiedDropconnect\") def _convert_simplified_dropconnect(converter: ChainerConverter, c_op: \"chainer.functions.SimplifiedDropconnect\"): # TODO raise", "Dropout is ignored\") x = converter.get_variable(c_op.inputs[0]) converter.set_variable(c_op.outputs[0](), x) # noinspection PyUnusedLocal @ChainerConverter.register_handler(\"Gaussian\") def", "def _convert_simplified_dropconnect(converter: ChainerConverter, c_op: \"chainer.functions.SimplifiedDropconnect\"): # TODO raise NotImplementedError(\"[ChainerConverter] SimplifiedDropconnect is not supported\")", "# TODO raise NotImplementedError(\"[ChainerConverter] SimplifiedDropconnect is not supported\") # noinspection PyUnusedLocal @ChainerConverter.register_handler(\"Zoneout\") def", "TODO raise NotImplementedError(\"[ChainerConverter] Gaussian is not supported\") # noinspection PyUnusedLocal @ChainerConverter.register_handler(\"SimplifiedDropconnect\") def _convert_simplified_dropconnect(converter:", "def _convert_dropout(converter: ChainerConverter, c_op: \"chainer.functions.Dropout\"): console.warning(\"[ChainerConverter] Dropout is ignored\") x = converter.get_variable(c_op.inputs[0]) converter.set_variable(c_op.outputs[0](),", "import chainer from webdnn.frontend.chainer.converter import ChainerConverter from webdnn.util import console @ChainerConverter.register_handler(\"Dropout\") def _convert_dropout(converter:", "chainer from webdnn.frontend.chainer.converter import ChainerConverter from webdnn.util import console @ChainerConverter.register_handler(\"Dropout\") def _convert_dropout(converter: ChainerConverter,", "c_op: \"chainer.functions.Gaussian\"): # TODO raise NotImplementedError(\"[ChainerConverter] Gaussian is not supported\") # noinspection PyUnusedLocal", "console @ChainerConverter.register_handler(\"Dropout\") def _convert_dropout(converter: ChainerConverter, c_op: \"chainer.functions.Dropout\"): console.warning(\"[ChainerConverter] Dropout is ignored\") x =", "ignored\") x = converter.get_variable(c_op.inputs[0]) converter.set_variable(c_op.outputs[0](), x) # noinspection PyUnusedLocal @ChainerConverter.register_handler(\"Gaussian\") def _convert_gaussian(converter: ChainerConverter,", "supported\") # noinspection PyUnusedLocal @ChainerConverter.register_handler(\"Zoneout\") def _convert_zoneout(converter: ChainerConverter, c_op: \"chainer.functions.Zoneout\"): # TODO raise", "from webdnn.frontend.chainer.converter import ChainerConverter from webdnn.util import console @ChainerConverter.register_handler(\"Dropout\") def _convert_dropout(converter: ChainerConverter, c_op:", "_convert_gaussian(converter: ChainerConverter, c_op: \"chainer.functions.Gaussian\"): # TODO raise NotImplementedError(\"[ChainerConverter] Gaussian is not supported\") #", "@ChainerConverter.register_handler(\"Gaussian\") def _convert_gaussian(converter: ChainerConverter, c_op: \"chainer.functions.Gaussian\"): # TODO raise NotImplementedError(\"[ChainerConverter] Gaussian is not", "noinspection PyUnusedLocal @ChainerConverter.register_handler(\"Gaussian\") def _convert_gaussian(converter: ChainerConverter, c_op: \"chainer.functions.Gaussian\"): # TODO raise NotImplementedError(\"[ChainerConverter] Gaussian", "def _convert_gaussian(converter: ChainerConverter, c_op: \"chainer.functions.Gaussian\"): # TODO raise NotImplementedError(\"[ChainerConverter] Gaussian is not supported\")", "@ChainerConverter.register_handler(\"SimplifiedDropconnect\") def _convert_simplified_dropconnect(converter: ChainerConverter, c_op: \"chainer.functions.SimplifiedDropconnect\"): # TODO raise NotImplementedError(\"[ChainerConverter] SimplifiedDropconnect is not", "= converter.get_variable(c_op.inputs[0]) converter.set_variable(c_op.outputs[0](), x) # noinspection PyUnusedLocal @ChainerConverter.register_handler(\"Gaussian\") def _convert_gaussian(converter: ChainerConverter, c_op: \"chainer.functions.Gaussian\"):", "converter.get_variable(c_op.inputs[0]) converter.set_variable(c_op.outputs[0](), x) # noinspection PyUnusedLocal @ChainerConverter.register_handler(\"Gaussian\") def _convert_gaussian(converter: ChainerConverter, c_op: \"chainer.functions.Gaussian\"): #", "webdnn.util import console @ChainerConverter.register_handler(\"Dropout\") def _convert_dropout(converter: ChainerConverter, c_op: \"chainer.functions.Dropout\"): console.warning(\"[ChainerConverter] Dropout is ignored\")", "ChainerConverter, c_op: \"chainer.functions.Dropout\"): console.warning(\"[ChainerConverter] Dropout is ignored\") x = converter.get_variable(c_op.inputs[0]) converter.set_variable(c_op.outputs[0](), x) #", "ChainerConverter, c_op: \"chainer.functions.SimplifiedDropconnect\"): # TODO raise NotImplementedError(\"[ChainerConverter] SimplifiedDropconnect is not supported\") # noinspection", "is not supported\") # noinspection PyUnusedLocal @ChainerConverter.register_handler(\"SimplifiedDropconnect\") def _convert_simplified_dropconnect(converter: ChainerConverter, c_op: \"chainer.functions.SimplifiedDropconnect\"): #", "# noinspection PyUnusedLocal @ChainerConverter.register_handler(\"Zoneout\") def _convert_zoneout(converter: ChainerConverter, c_op: \"chainer.functions.Zoneout\"): # TODO raise NotImplementedError(\"[ChainerConverter]", "# noinspection PyUnusedLocal @ChainerConverter.register_handler(\"Gaussian\") def _convert_gaussian(converter: ChainerConverter, c_op: \"chainer.functions.Gaussian\"): # TODO raise NotImplementedError(\"[ChainerConverter]", "TODO raise NotImplementedError(\"[ChainerConverter] SimplifiedDropconnect is not supported\") # noinspection PyUnusedLocal @ChainerConverter.register_handler(\"Zoneout\") def _convert_zoneout(converter:", "def _convert_zoneout(converter: ChainerConverter, c_op: \"chainer.functions.Zoneout\"): # TODO raise NotImplementedError(\"[ChainerConverter] Zoneout is not supported\")", "_convert_dropout(converter: ChainerConverter, c_op: \"chainer.functions.Dropout\"): console.warning(\"[ChainerConverter] Dropout is ignored\") x = converter.get_variable(c_op.inputs[0]) converter.set_variable(c_op.outputs[0](), x)", "\"chainer.functions.Gaussian\"): # TODO raise NotImplementedError(\"[ChainerConverter] Gaussian is not supported\") # noinspection PyUnusedLocal @ChainerConverter.register_handler(\"SimplifiedDropconnect\")", "converter.set_variable(c_op.outputs[0](), x) # noinspection PyUnusedLocal @ChainerConverter.register_handler(\"Gaussian\") def _convert_gaussian(converter: ChainerConverter, c_op: \"chainer.functions.Gaussian\"): # TODO", "x) # noinspection PyUnusedLocal @ChainerConverter.register_handler(\"Gaussian\") def _convert_gaussian(converter: ChainerConverter, c_op: \"chainer.functions.Gaussian\"): # TODO raise", "NotImplementedError(\"[ChainerConverter] Gaussian is not supported\") # noinspection PyUnusedLocal @ChainerConverter.register_handler(\"SimplifiedDropconnect\") def _convert_simplified_dropconnect(converter: ChainerConverter, c_op:", "NotImplementedError(\"[ChainerConverter] SimplifiedDropconnect is not supported\") # noinspection PyUnusedLocal @ChainerConverter.register_handler(\"Zoneout\") def _convert_zoneout(converter: ChainerConverter, c_op:", "# TODO raise NotImplementedError(\"[ChainerConverter] Gaussian is not supported\") # noinspection PyUnusedLocal @ChainerConverter.register_handler(\"SimplifiedDropconnect\") def", "is ignored\") x = converter.get_variable(c_op.inputs[0]) converter.set_variable(c_op.outputs[0](), x) # noinspection PyUnusedLocal @ChainerConverter.register_handler(\"Gaussian\") def _convert_gaussian(converter:", "# noinspection PyUnusedLocal @ChainerConverter.register_handler(\"SimplifiedDropconnect\") def _convert_simplified_dropconnect(converter: ChainerConverter, c_op: \"chainer.functions.SimplifiedDropconnect\"): # TODO raise NotImplementedError(\"[ChainerConverter]", "is not supported\") # noinspection PyUnusedLocal @ChainerConverter.register_handler(\"Zoneout\") def _convert_zoneout(converter: ChainerConverter, c_op: \"chainer.functions.Zoneout\"): #", "\"chainer.functions.Dropout\"): console.warning(\"[ChainerConverter] Dropout is ignored\") x = converter.get_variable(c_op.inputs[0]) converter.set_variable(c_op.outputs[0](), x) # noinspection PyUnusedLocal", "import ChainerConverter from webdnn.util import console @ChainerConverter.register_handler(\"Dropout\") def _convert_dropout(converter: ChainerConverter, c_op: \"chainer.functions.Dropout\"): console.warning(\"[ChainerConverter]", "<gh_stars>1-10 import chainer from webdnn.frontend.chainer.converter import ChainerConverter from webdnn.util import console @ChainerConverter.register_handler(\"Dropout\") def", "SimplifiedDropconnect is not supported\") # noinspection PyUnusedLocal @ChainerConverter.register_handler(\"Zoneout\") def _convert_zoneout(converter: ChainerConverter, c_op: \"chainer.functions.Zoneout\"):", "PyUnusedLocal @ChainerConverter.register_handler(\"SimplifiedDropconnect\") def _convert_simplified_dropconnect(converter: ChainerConverter, c_op: \"chainer.functions.SimplifiedDropconnect\"): # TODO raise NotImplementedError(\"[ChainerConverter] SimplifiedDropconnect is", "c_op: \"chainer.functions.SimplifiedDropconnect\"): # TODO raise NotImplementedError(\"[ChainerConverter] SimplifiedDropconnect is not supported\") # noinspection PyUnusedLocal", "x = converter.get_variable(c_op.inputs[0]) converter.set_variable(c_op.outputs[0](), x) # noinspection PyUnusedLocal @ChainerConverter.register_handler(\"Gaussian\") def _convert_gaussian(converter: ChainerConverter, c_op:", "raise NotImplementedError(\"[ChainerConverter] SimplifiedDropconnect is not supported\") # noinspection PyUnusedLocal @ChainerConverter.register_handler(\"Zoneout\") def _convert_zoneout(converter: ChainerConverter,", "noinspection PyUnusedLocal @ChainerConverter.register_handler(\"Zoneout\") def _convert_zoneout(converter: ChainerConverter, c_op: \"chainer.functions.Zoneout\"): # TODO raise NotImplementedError(\"[ChainerConverter] Zoneout" ]
[ "the uploaded image (output from a distance function) ''' color_distances = [] for", "and all training set images (vectors). :param training_set_vectors: numpy Matrix, vectors for all", "numpy matrix, softmax probabilities. Example [[0.2, 0.1, 0.7], [0.9, 0.05, 0.05]] ''' assert", "vector :param top_n: integer, number of closest images to return ''' distances =", "''' Calculates hamming distances between query image (vector) and all training set images", "training_set_vectors: numpy Matrix, vectors for all images in the training set :param query_vector:", "color vector of a uploaded image (query image). :param color_vectors: color features vectors", "a color vector of a uploaded image (query image). :param color_vectors: color features", "you need/want return ids[np.argsort(color_distances)[:15]] def cosine_distance(training_set_vectors, query_vector, top_n=50): ''' Calculates cosine distances between", "array, real labels of each sample. Example: [1, 2, 1, 0, 0] :param", "as np from scipy.spatial.distance import hamming, cosine, euclidean def compare_color(color_vectors, uploaded_image_colors, ids): '''", "Example: [1, 2, 1, 0, 0] :param predicted_labels: numpy matrix, softmax probabilities. Example", "1, 0, 0] :param predicted_labels: numpy matrix, softmax probabilities. Example [[0.2, 0.1, 0.7],", "choosen, you can return as many as you need/want return ids[np.argsort(color_distances)[:15]] def cosine_distance(training_set_vectors,", "to the uploaded image :param uploaded_image_colors: color vector of the uploaded image :param", "vector, query image (new image) vector :param top_n: Integer, number of closest images", "np.argsort(distances)[:top_n] def sparse_accuracy(true_labels, predicted_labels): ''' Calculates accuracy of a model based on softmax", "set :param query_vector: numpy vector, query image (new image) vector :param top_n: Integer,", "labels of each sample. Example: [1, 2, 1, 0, 0] :param predicted_labels: numpy", "image). :param color_vectors: color features vectors of closest training set images to the", "uploaded_image_colors: color vector of the uploaded image :param ids: indices of training images", "Cifar 10 -> 50k images distances.append(cosine(training_set_vectors[i], query_vector[0])) return np.argsort(distances)[:top_n] def hamming_distance(training_set_vectors, query_vector, top_n=50):", "query image (new image) vector :param top_n: Integer, number of closest images to", "top_n: Integer, number of closest images to return ''' distances = [] for", "I have choosen, you can return as many as you need/want return ids[np.argsort(color_distances)[:15]]", "color features vectors of closest training set images to the uploaded image :param", "i in range(len(color_vectors)): color_distances.append(euclidean(color_vectors[i], uploaded_image_colors)) #The 15 is just an random number that", "features vectors of closest training set images to the uploaded image :param uploaded_image_colors:", "images to the uploaded image :param uploaded_image_colors: color vector of the uploaded image", "numpy as np from scipy.spatial.distance import hamming, cosine, euclidean def compare_color(color_vectors, uploaded_image_colors, ids):", "vectors of closest images from the training set with a color vector of", "closest images to return ''' distances = [] for i in range(len(training_set_vectors)): #For", "of each sample. Example: [1, 2, 1, 0, 0] :param predicted_labels: numpy matrix,", "training set :param query_vector: numpy vector, query image (new image) vector :param top_n:", "return ids[np.argsort(color_distances)[:15]] def cosine_distance(training_set_vectors, query_vector, top_n=50): ''' Calculates cosine distances between query image", "in range(len(training_set_vectors)): #For Cifar 10 -> 50k images distances.append(cosine(training_set_vectors[i], query_vector[0])) return np.argsort(distances)[:top_n] def", "can return as many as you need/want return ids[np.argsort(color_distances)[:15]] def cosine_distance(training_set_vectors, query_vector, top_n=50):", "image) vector :param top_n: integer, number of closest images to return ''' distances", "image (vector) and all training set images (vectors). :param training_set_vectors: numpy Matrix, vectors", "distances between query image (vector) and all training set images (vectors). :param training_set_vectors:", "the uploaded image :param ids: indices of training images being closest to the", "-> 50k images distances.append(cosine(training_set_vectors[i], query_vector[0])) return np.argsort(distances)[:top_n] def hamming_distance(training_set_vectors, query_vector, top_n=50): ''' Calculates", "15 is just an random number that I have choosen, you can return", "an random number that I have choosen, you can return as many as", "top_n=50): ''' Calculates cosine distances between query image (vector) and all training set", "the training set with a color vector of a uploaded image (query image).", "[0.9, 0.05, 0.05]] ''' assert len(true_labels) == len(predicted_labels) correct = 0 for i", "uploaded image (query image). :param color_vectors: color features vectors of closest training set", "query image (new image) vector :param top_n: integer, number of closest images to", "integer, number of closest images to return ''' distances = [] for i", "as many as you need/want return ids[np.argsort(color_distances)[:15]] def cosine_distance(training_set_vectors, query_vector, top_n=50): ''' Calculates", "of closest training set images to the uploaded image :param uploaded_image_colors: color vector", "numpy vector, query image (new image) vector :param top_n: Integer, number of closest", "images distances.append(hamming(training_set_vectors[i], query_vector[0])) return np.argsort(distances)[:top_n] def sparse_accuracy(true_labels, predicted_labels): ''' Calculates accuracy of a", "query_vector, top_n=50): ''' Calculates cosine distances between query image (vector) and all training", "i in range(len(training_set_vectors)): #For Cifar 10 -> 50k images distances.append(hamming(training_set_vectors[i], query_vector[0])) return np.argsort(distances)[:top_n]", "range(len(color_vectors)): color_distances.append(euclidean(color_vectors[i], uploaded_image_colors)) #The 15 is just an random number that I have", "range(len(training_set_vectors)): #For Cifar 10 -> 50k images distances.append(hamming(training_set_vectors[i], query_vector[0])) return np.argsort(distances)[:top_n] def sparse_accuracy(true_labels,", "def sparse_accuracy(true_labels, predicted_labels): ''' Calculates accuracy of a model based on softmax outputs.", "assert len(true_labels) == len(predicted_labels) correct = 0 for i in range(len(true_labels)): if np.argmax(predicted_labels[i])", "(vector) and all training set images (vectors). :param training_set_vectors: numpy Matrix, vectors for", "need/want return ids[np.argsort(color_distances)[:15]] def cosine_distance(training_set_vectors, query_vector, top_n=50): ''' Calculates cosine distances between query", "probabilities. Example [[0.2, 0.1, 0.7], [0.9, 0.05, 0.05]] ''' assert len(true_labels) == len(predicted_labels)", "euclidean def compare_color(color_vectors, uploaded_image_colors, ids): ''' Comparing color vectors of closest images from", "indices of training images being closest to the uploaded image (output from a", "a uploaded image (query image). :param color_vectors: color features vectors of closest training", ":param uploaded_image_colors: color vector of the uploaded image :param ids: indices of training", "all images in the training set :param query_vector: numpy vector, query image (new", "[[0.2, 0.1, 0.7], [0.9, 0.05, 0.05]] ''' assert len(true_labels) == len(predicted_labels) correct =", "hamming, cosine, euclidean def compare_color(color_vectors, uploaded_image_colors, ids): ''' Comparing color vectors of closest", "image :param ids: indices of training images being closest to the uploaded image", "correct = 0 for i in range(len(true_labels)): if np.argmax(predicted_labels[i]) == true_labels[i]: correct +=", "of a model based on softmax outputs. :param true_labels: numpy array, real labels", "query_vector: numpy vector, query image (new image) vector :param top_n: integer, number of", ":param true_labels: numpy array, real labels of each sample. Example: [1, 2, 1,", "10 -> 50k images distances.append(hamming(training_set_vectors[i], query_vector[0])) return np.argsort(distances)[:top_n] def sparse_accuracy(true_labels, predicted_labels): ''' Calculates", "Calculates cosine distances between query image (vector) and all training set images (vectors).", "training set images (vectors). :param training_set_vectors: numpy Matrix, vectors for all images in", "of closest images from the training set with a color vector of a", "real labels of each sample. Example: [1, 2, 1, 0, 0] :param predicted_labels:", "image (new image) vector :param top_n: integer, number of closest images to return", "to return ''' distances = [] for i in range(len(training_set_vectors)): #For Cifar 10", "of closest images to return ''' distances = [] for i in range(len(training_set_vectors)):", "range(len(training_set_vectors)): #For Cifar 10 -> 50k images distances.append(cosine(training_set_vectors[i], query_vector[0])) return np.argsort(distances)[:top_n] def hamming_distance(training_set_vectors,", "of the uploaded image :param ids: indices of training images being closest to", "with a color vector of a uploaded image (query image). :param color_vectors: color", "from the training set with a color vector of a uploaded image (query", "query image (vector) and all training set images (vectors). :param training_set_vectors: numpy Matrix,", "random number that I have choosen, you can return as many as you", "outputs. :param true_labels: numpy array, real labels of each sample. Example: [1, 2,", "vectors for all images in the training set :param query_vector: numpy vector, query", "''' Calculates accuracy of a model based on softmax outputs. :param true_labels: numpy", "color_distances = [] for i in range(len(color_vectors)): color_distances.append(euclidean(color_vectors[i], uploaded_image_colors)) #The 15 is just", ":param query_vector: numpy vector, query image (new image) vector :param top_n: Integer, number", "model based on softmax outputs. :param true_labels: numpy array, real labels of each", "0.05, 0.05]] ''' assert len(true_labels) == len(predicted_labels) correct = 0 for i in", "color_distances.append(euclidean(color_vectors[i], uploaded_image_colors)) #The 15 is just an random number that I have choosen,", "50k images distances.append(hamming(training_set_vectors[i], query_vector[0])) return np.argsort(distances)[:top_n] def sparse_accuracy(true_labels, predicted_labels): ''' Calculates accuracy of", "images distances.append(cosine(training_set_vectors[i], query_vector[0])) return np.argsort(distances)[:top_n] def hamming_distance(training_set_vectors, query_vector, top_n=50): ''' Calculates hamming distances", "= 0 for i in range(len(true_labels)): if np.argmax(predicted_labels[i]) == true_labels[i]: correct += 1", "distances.append(hamming(training_set_vectors[i], query_vector[0])) return np.argsort(distances)[:top_n] def sparse_accuracy(true_labels, predicted_labels): ''' Calculates accuracy of a model", "0.05]] ''' assert len(true_labels) == len(predicted_labels) correct = 0 for i in range(len(true_labels)):", "0, 0] :param predicted_labels: numpy matrix, softmax probabilities. Example [[0.2, 0.1, 0.7], [0.9,", "all training set images (vectors). :param training_set_vectors: numpy Matrix, vectors for all images", "for i in range(len(training_set_vectors)): #For Cifar 10 -> 50k images distances.append(cosine(training_set_vectors[i], query_vector[0])) return", "import hamming, cosine, euclidean def compare_color(color_vectors, uploaded_image_colors, ids): ''' Comparing color vectors of", "true_labels: numpy array, real labels of each sample. Example: [1, 2, 1, 0,", "def cosine_distance(training_set_vectors, query_vector, top_n=50): ''' Calculates cosine distances between query image (vector) and", "in range(len(true_labels)): if np.argmax(predicted_labels[i]) == true_labels[i]: correct += 1 return correct / len(true_labels)", "set images (vectors). :param training_set_vectors: numpy Matrix, vectors for all images in the", "return np.argsort(distances)[:top_n] def sparse_accuracy(true_labels, predicted_labels): ''' Calculates accuracy of a model based on", "= [] for i in range(len(training_set_vectors)): #For Cifar 10 -> 50k images distances.append(cosine(training_set_vectors[i],", "np from scipy.spatial.distance import hamming, cosine, euclidean def compare_color(color_vectors, uploaded_image_colors, ids): ''' Comparing", "vector of a uploaded image (query image). :param color_vectors: color features vectors of", "between query image (vector) and all training set images (vectors). :param training_set_vectors: numpy", "cosine, euclidean def compare_color(color_vectors, uploaded_image_colors, ids): ''' Comparing color vectors of closest images", "of a uploaded image (query image). :param color_vectors: color features vectors of closest", "number of closest images to return ''' distances = [] for i in", "closest to the uploaded image (output from a distance function) ''' color_distances =", "sparse_accuracy(true_labels, predicted_labels): ''' Calculates accuracy of a model based on softmax outputs. :param", "cosine_distance(training_set_vectors, query_vector, top_n=50): ''' Calculates cosine distances between query image (vector) and all", "have choosen, you can return as many as you need/want return ids[np.argsort(color_distances)[:15]] def", "return as many as you need/want return ids[np.argsort(color_distances)[:15]] def cosine_distance(training_set_vectors, query_vector, top_n=50): '''", "image) vector :param top_n: Integer, number of closest images to return ''' distances", "from a distance function) ''' color_distances = [] for i in range(len(color_vectors)): color_distances.append(euclidean(color_vectors[i],", "uploaded_image_colors, ids): ''' Comparing color vectors of closest images from the training set", "(vectors). :param training_set_vectors: numpy Matrix, vectors for all images in the training set", "color vectors of closest images from the training set with a color vector", "based on softmax outputs. :param true_labels: numpy array, real labels of each sample.", "def hamming_distance(training_set_vectors, query_vector, top_n=50): ''' Calculates hamming distances between query image (vector) and", "scipy.spatial.distance import hamming, cosine, euclidean def compare_color(color_vectors, uploaded_image_colors, ids): ''' Comparing color vectors", "query_vector[0])) return np.argsort(distances)[:top_n] def sparse_accuracy(true_labels, predicted_labels): ''' Calculates accuracy of a model based", "that I have choosen, you can return as many as you need/want return", "Comparing color vectors of closest images from the training set with a color", "def compare_color(color_vectors, uploaded_image_colors, ids): ''' Comparing color vectors of closest images from the", "training set with a color vector of a uploaded image (query image). :param", "uploaded image (output from a distance function) ''' color_distances = [] for i", "for i in range(len(color_vectors)): color_distances.append(euclidean(color_vectors[i], uploaded_image_colors)) #The 15 is just an random number", "hamming distances between query image (vector) and all training set images (vectors). :param", "for i in range(len(training_set_vectors)): #For Cifar 10 -> 50k images distances.append(hamming(training_set_vectors[i], query_vector[0])) return", "[] for i in range(len(training_set_vectors)): #For Cifar 10 -> 50k images distances.append(hamming(training_set_vectors[i], query_vector[0]))", "#For Cifar 10 -> 50k images distances.append(hamming(training_set_vectors[i], query_vector[0])) return np.argsort(distances)[:top_n] def sparse_accuracy(true_labels, predicted_labels):", "Calculates accuracy of a model based on softmax outputs. :param true_labels: numpy array,", "softmax outputs. :param true_labels: numpy array, real labels of each sample. Example: [1,", "numpy Matrix, vectors for all images in the training set :param query_vector: numpy", "images (vectors). :param training_set_vectors: numpy Matrix, vectors for all images in the training", "ids: indices of training images being closest to the uploaded image (output from", "matrix, softmax probabilities. Example [[0.2, 0.1, 0.7], [0.9, 0.05, 0.05]] ''' assert len(true_labels)", "vectors of closest training set images to the uploaded image :param uploaded_image_colors: color", "images to return ''' distances = [] for i in range(len(training_set_vectors)): #For Cifar", "0.1, 0.7], [0.9, 0.05, 0.05]] ''' assert len(true_labels) == len(predicted_labels) correct = 0", "closest images from the training set with a color vector of a uploaded", "(query image). :param color_vectors: color features vectors of closest training set images to", "''' color_distances = [] for i in range(len(color_vectors)): color_distances.append(euclidean(color_vectors[i], uploaded_image_colors)) #The 15 is", "each sample. Example: [1, 2, 1, 0, 0] :param predicted_labels: numpy matrix, softmax", "cosine distances between query image (vector) and all training set images (vectors). :param", "top_n=50): ''' Calculates hamming distances between query image (vector) and all training set", "ids): ''' Comparing color vectors of closest images from the training set with", "softmax probabilities. Example [[0.2, 0.1, 0.7], [0.9, 0.05, 0.05]] ''' assert len(true_labels) ==", "query_vector: numpy vector, query image (new image) vector :param top_n: Integer, number of", "[] for i in range(len(training_set_vectors)): #For Cifar 10 -> 50k images distances.append(cosine(training_set_vectors[i], query_vector[0]))", "vector, query image (new image) vector :param top_n: integer, number of closest images", "many as you need/want return ids[np.argsort(color_distances)[:15]] def cosine_distance(training_set_vectors, query_vector, top_n=50): ''' Calculates cosine", "return np.argsort(distances)[:top_n] def hamming_distance(training_set_vectors, query_vector, top_n=50): ''' Calculates hamming distances between query image", "color vector of the uploaded image :param ids: indices of training images being", "set with a color vector of a uploaded image (query image). :param color_vectors:", "[] for i in range(len(color_vectors)): color_distances.append(euclidean(color_vectors[i], uploaded_image_colors)) #The 15 is just an random", "a distance function) ''' color_distances = [] for i in range(len(color_vectors)): color_distances.append(euclidean(color_vectors[i], uploaded_image_colors))", "in the training set :param query_vector: numpy vector, query image (new image) vector", "query_vector, top_n=50): ''' Calculates hamming distances between query image (vector) and all training", "function) ''' color_distances = [] for i in range(len(color_vectors)): color_distances.append(euclidean(color_vectors[i], uploaded_image_colors)) #The 15", "Calculates hamming distances between query image (vector) and all training set images (vectors).", "color_vectors: color features vectors of closest training set images to the uploaded image", "predicted_labels): ''' Calculates accuracy of a model based on softmax outputs. :param true_labels:", "[1, 2, 1, 0, 0] :param predicted_labels: numpy matrix, softmax probabilities. Example [[0.2,", "predicted_labels: numpy matrix, softmax probabilities. Example [[0.2, 0.1, 0.7], [0.9, 0.05, 0.05]] '''", "training set images to the uploaded image :param uploaded_image_colors: color vector of the", "a model based on softmax outputs. :param true_labels: numpy array, real labels of", "(output from a distance function) ''' color_distances = [] for i in range(len(color_vectors)):", "hamming_distance(training_set_vectors, query_vector, top_n=50): ''' Calculates hamming distances between query image (vector) and all", "query_vector[0])) return np.argsort(distances)[:top_n] def hamming_distance(training_set_vectors, query_vector, top_n=50): ''' Calculates hamming distances between query", "the training set :param query_vector: numpy vector, query image (new image) vector :param", "set :param query_vector: numpy vector, query image (new image) vector :param top_n: integer,", "distances.append(cosine(training_set_vectors[i], query_vector[0])) return np.argsort(distances)[:top_n] def hamming_distance(training_set_vectors, query_vector, top_n=50): ''' Calculates hamming distances between", "as you need/want return ids[np.argsort(color_distances)[:15]] def cosine_distance(training_set_vectors, query_vector, top_n=50): ''' Calculates cosine distances", "''' distances = [] for i in range(len(training_set_vectors)): #For Cifar 10 -> 50k", "i in range(len(training_set_vectors)): #For Cifar 10 -> 50k images distances.append(cosine(training_set_vectors[i], query_vector[0])) return np.argsort(distances)[:top_n]", "the uploaded image :param uploaded_image_colors: color vector of the uploaded image :param ids:", "being closest to the uploaded image (output from a distance function) ''' color_distances", "(new image) vector :param top_n: Integer, number of closest images to return '''", "you can return as many as you need/want return ids[np.argsort(color_distances)[:15]] def cosine_distance(training_set_vectors, query_vector,", ":param ids: indices of training images being closest to the uploaded image (output", "is just an random number that I have choosen, you can return as", "closest training set images to the uploaded image :param uploaded_image_colors: color vector of", "-> 50k images distances.append(hamming(training_set_vectors[i], query_vector[0])) return np.argsort(distances)[:top_n] def sparse_accuracy(true_labels, predicted_labels): ''' Calculates accuracy", "on softmax outputs. :param true_labels: numpy array, real labels of each sample. Example:", "for all images in the training set :param query_vector: numpy vector, query image", "''' Comparing color vectors of closest images from the training set with a", "images being closest to the uploaded image (output from a distance function) '''", "50k images distances.append(cosine(training_set_vectors[i], query_vector[0])) return np.argsort(distances)[:top_n] def hamming_distance(training_set_vectors, query_vector, top_n=50): ''' Calculates hamming", "images in the training set :param query_vector: numpy vector, query image (new image)", "sample. Example: [1, 2, 1, 0, 0] :param predicted_labels: numpy matrix, softmax probabilities.", "numpy vector, query image (new image) vector :param top_n: integer, number of closest", "#For Cifar 10 -> 50k images distances.append(cosine(training_set_vectors[i], query_vector[0])) return np.argsort(distances)[:top_n] def hamming_distance(training_set_vectors, query_vector,", "i in range(len(true_labels)): if np.argmax(predicted_labels[i]) == true_labels[i]: correct += 1 return correct /", "from scipy.spatial.distance import hamming, cosine, euclidean def compare_color(color_vectors, uploaded_image_colors, ids): ''' Comparing color", "uploaded_image_colors)) #The 15 is just an random number that I have choosen, you", "Cifar 10 -> 50k images distances.append(hamming(training_set_vectors[i], query_vector[0])) return np.argsort(distances)[:top_n] def sparse_accuracy(true_labels, predicted_labels): '''", "== len(predicted_labels) correct = 0 for i in range(len(true_labels)): if np.argmax(predicted_labels[i]) == true_labels[i]:", "of training images being closest to the uploaded image (output from a distance", "Example [[0.2, 0.1, 0.7], [0.9, 0.05, 0.05]] ''' assert len(true_labels) == len(predicted_labels) correct", ":param query_vector: numpy vector, query image (new image) vector :param top_n: integer, number", "images from the training set with a color vector of a uploaded image", "<gh_stars>1-10 import numpy as np from scipy.spatial.distance import hamming, cosine, euclidean def compare_color(color_vectors,", "len(true_labels) == len(predicted_labels) correct = 0 for i in range(len(true_labels)): if np.argmax(predicted_labels[i]) ==", "set images to the uploaded image :param uploaded_image_colors: color vector of the uploaded", "0.7], [0.9, 0.05, 0.05]] ''' assert len(true_labels) == len(predicted_labels) correct = 0 for", "(new image) vector :param top_n: integer, number of closest images to return '''", "image (new image) vector :param top_n: Integer, number of closest images to return", "vector of the uploaded image :param ids: indices of training images being closest", "#The 15 is just an random number that I have choosen, you can", "to the uploaded image (output from a distance function) ''' color_distances = []", "number that I have choosen, you can return as many as you need/want", "= [] for i in range(len(training_set_vectors)): #For Cifar 10 -> 50k images distances.append(hamming(training_set_vectors[i],", "numpy array, real labels of each sample. Example: [1, 2, 1, 0, 0]", "top_n: integer, number of closest images to return ''' distances = [] for", "0 for i in range(len(true_labels)): if np.argmax(predicted_labels[i]) == true_labels[i]: correct += 1 return", "return ''' distances = [] for i in range(len(training_set_vectors)): #For Cifar 10 ->", "compare_color(color_vectors, uploaded_image_colors, ids): ''' Comparing color vectors of closest images from the training", "0] :param predicted_labels: numpy matrix, softmax probabilities. Example [[0.2, 0.1, 0.7], [0.9, 0.05,", "training images being closest to the uploaded image (output from a distance function)", "Integer, number of closest images to return ''' distances = [] for i", "image (query image). :param color_vectors: color features vectors of closest training set images", "uploaded image :param uploaded_image_colors: color vector of the uploaded image :param ids: indices", ":param predicted_labels: numpy matrix, softmax probabilities. Example [[0.2, 0.1, 0.7], [0.9, 0.05, 0.05]]", "import numpy as np from scipy.spatial.distance import hamming, cosine, euclidean def compare_color(color_vectors, uploaded_image_colors,", "distance function) ''' color_distances = [] for i in range(len(color_vectors)): color_distances.append(euclidean(color_vectors[i], uploaded_image_colors)) #The", "distances = [] for i in range(len(training_set_vectors)): #For Cifar 10 -> 50k images", "image (output from a distance function) ''' color_distances = [] for i in", "= [] for i in range(len(color_vectors)): color_distances.append(euclidean(color_vectors[i], uploaded_image_colors)) #The 15 is just an", "2, 1, 0, 0] :param predicted_labels: numpy matrix, softmax probabilities. Example [[0.2, 0.1,", "10 -> 50k images distances.append(cosine(training_set_vectors[i], query_vector[0])) return np.argsort(distances)[:top_n] def hamming_distance(training_set_vectors, query_vector, top_n=50): '''", "accuracy of a model based on softmax outputs. :param true_labels: numpy array, real", ":param top_n: integer, number of closest images to return ''' distances = []", ":param training_set_vectors: numpy Matrix, vectors for all images in the training set :param", "for i in range(len(true_labels)): if np.argmax(predicted_labels[i]) == true_labels[i]: correct += 1 return correct", ":param color_vectors: color features vectors of closest training set images to the uploaded", "Matrix, vectors for all images in the training set :param query_vector: numpy vector,", "''' assert len(true_labels) == len(predicted_labels) correct = 0 for i in range(len(true_labels)): if", "''' Calculates cosine distances between query image (vector) and all training set images", "in range(len(color_vectors)): color_distances.append(euclidean(color_vectors[i], uploaded_image_colors)) #The 15 is just an random number that I", "uploaded image :param ids: indices of training images being closest to the uploaded", "ids[np.argsort(color_distances)[:15]] def cosine_distance(training_set_vectors, query_vector, top_n=50): ''' Calculates cosine distances between query image (vector)", "image :param uploaded_image_colors: color vector of the uploaded image :param ids: indices of", "in range(len(training_set_vectors)): #For Cifar 10 -> 50k images distances.append(hamming(training_set_vectors[i], query_vector[0])) return np.argsort(distances)[:top_n] def", "just an random number that I have choosen, you can return as many", "len(predicted_labels) correct = 0 for i in range(len(true_labels)): if np.argmax(predicted_labels[i]) == true_labels[i]: correct", ":param top_n: Integer, number of closest images to return ''' distances = []", "vector :param top_n: Integer, number of closest images to return ''' distances =", "np.argsort(distances)[:top_n] def hamming_distance(training_set_vectors, query_vector, top_n=50): ''' Calculates hamming distances between query image (vector)" ]
[ "#<NAME> #CS4375: OS #3 methods from os import read #from os library import", "0 return line def my_readLines(): numLines = 0 inLine = my_getLine() while len(inLine):", "next < len(limit) -1: #Check to make sure limit[next] wont go out of", "= creating method : use method, loops, tryCatch global next, limit #initializing 2", "my_getChar(): #define = creating method : use method, loops, tryCatch global next, limit", "!= \"EOF\"): line += char char = my_getChar() next = 0 limit =", "one char at at time def my_getChar(): #define = creating method : use", "#define = creating method : use method, loops, tryCatch global next, limit #initializing", "0: return \"EOF\" if next < len(limit) -1: #Check to make sure limit[next]", "#initializing 2 variables if next == limit: next = 0 limit = read(0,1000)", "= chr(limit[next])#converting from ascii to char next += 1 return c else: return", "< len(limit) -1: #Check to make sure limit[next] wont go out of bounds.", "limit line = \"\" char = my_getChar() while (char != '' and char", "= \"\" char = my_getChar() while (char != '' and char != \"EOF\"):", "if next < len(limit) -1: #Check to make sure limit[next] wont go out", "line def my_readLines(): numLines = 0 inLine = my_getLine() while len(inLine): numLines +=", "next = 0 limit = 0 return line def my_readLines(): numLines = 0", "limit = read(0,1000) # if limit == 0: return \"EOF\" if next <", "inLine = my_getLine() while len(inLine): numLines += 1 print(f\"### Line {numLines}: <{str(inLine)}> ###\\n\")", "if limit == 0: return \"EOF\" if next < len(limit) -1: #Check to", "= my_getChar() while (char != '' and char != \"EOF\"): line += char", "\"EOF\"): line += char char = my_getChar() next = 0 limit = 0", "fill a buffer, and gets one char at at time def my_getChar(): #define", "= 0 #This method calls read to fill a buffer, and gets one", "next global limit line = \"\" char = my_getChar() while (char != ''", "ascii to char next += 1 return c else: return \"EOF\" def my_getLine():", "= read(0,1000) # if limit == 0: return \"EOF\" if next < len(limit)", "limit: next = 0 limit = read(0,1000) # if limit == 0: return", "1 return c else: return \"EOF\" def my_getLine(): global next global limit line", "def my_getLine(): global next global limit line = \"\" char = my_getChar() while", "method next = 0 limit = 0 #This method calls read to fill", "to char next += 1 return c else: return \"EOF\" def my_getLine(): global", "global next global limit line = \"\" char = my_getChar() while (char !=", "-1: #Check to make sure limit[next] wont go out of bounds. c =", "#CS4375: OS #3 methods from os import read #from os library import read", "at at time def my_getChar(): #define = creating method : use method, loops,", "from os import read #from os library import read method next = 0", "+= 1 print(f\"### Line {numLines}: <{str(inLine)}> ###\\n\") inLine = my_getLine() print(f\"EOF after {numLines}\\n\")", "buffer, and gets one char at at time def my_getChar(): #define = creating", "\"\" char = my_getChar() while (char != '' and char != \"EOF\"): line", "c else: return \"EOF\" def my_getLine(): global next global limit line = \"\"", "char next += 1 return c else: return \"EOF\" def my_getLine(): global next", "my_readLines(): numLines = 0 inLine = my_getLine() while len(inLine): numLines += 1 print(f\"###", "sure limit[next] wont go out of bounds. c = chr(limit[next])#converting from ascii to", "calls read to fill a buffer, and gets one char at at time", "numLines = 0 inLine = my_getLine() while len(inLine): numLines += 1 print(f\"### Line", "OS #3 methods from os import read #from os library import read method", "= 0 return line def my_readLines(): numLines = 0 inLine = my_getLine() while", "make sure limit[next] wont go out of bounds. c = chr(limit[next])#converting from ascii", "# if limit == 0: return \"EOF\" if next < len(limit) -1: #Check", "line += char char = my_getChar() next = 0 limit = 0 return", "my_getLine() while len(inLine): numLines += 1 print(f\"### Line {numLines}: <{str(inLine)}> ###\\n\") inLine =", ": use method, loops, tryCatch global next, limit #initializing 2 variables if next", "from ascii to char next += 1 return c else: return \"EOF\" def", "while (char != '' and char != \"EOF\"): line += char char =", "0 limit = 0 #This method calls read to fill a buffer, and", "limit = 0 return line def my_readLines(): numLines = 0 inLine = my_getLine()", "tryCatch global next, limit #initializing 2 variables if next == limit: next =", "to fill a buffer, and gets one char at at time def my_getChar():", "wont go out of bounds. c = chr(limit[next])#converting from ascii to char next", "of bounds. c = chr(limit[next])#converting from ascii to char next += 1 return", "loops, tryCatch global next, limit #initializing 2 variables if next == limit: next", "os import read #from os library import read method next = 0 limit", "go out of bounds. c = chr(limit[next])#converting from ascii to char next +=", "and char != \"EOF\"): line += char char = my_getChar() next = 0", "chr(limit[next])#converting from ascii to char next += 1 return c else: return \"EOF\"", "next, limit #initializing 2 variables if next == limit: next = 0 limit", "0 limit = read(0,1000) # if limit == 0: return \"EOF\" if next", "def my_getChar(): #define = creating method : use method, loops, tryCatch global next,", "variables if next == limit: next = 0 limit = read(0,1000) # if", "else: return \"EOF\" def my_getLine(): global next global limit line = \"\" char", "== limit: next = 0 limit = read(0,1000) # if limit == 0:", "char char = my_getChar() next = 0 limit = 0 return line def", "import read method next = 0 limit = 0 #This method calls read", "#3 methods from os import read #from os library import read method next", "global next, limit #initializing 2 variables if next == limit: next = 0", "methods from os import read #from os library import read method next =", "limit == 0: return \"EOF\" if next < len(limit) -1: #Check to make", "len(inLine): numLines += 1 print(f\"### Line {numLines}: <{str(inLine)}> ###\\n\") inLine = my_getLine() print(f\"EOF", "char = my_getChar() while (char != '' and char != \"EOF\"): line +=", "= 0 limit = read(0,1000) # if limit == 0: return \"EOF\" if", "and gets one char at at time def my_getChar(): #define = creating method", "next = 0 limit = 0 #This method calls read to fill a", "limit[next] wont go out of bounds. c = chr(limit[next])#converting from ascii to char", "time def my_getChar(): #define = creating method : use method, loops, tryCatch global", "next == limit: next = 0 limit = read(0,1000) # if limit ==", "return \"EOF\" def my_getLine(): global next global limit line = \"\" char =", "return c else: return \"EOF\" def my_getLine(): global next global limit line =", "my_getChar() while (char != '' and char != \"EOF\"): line += char char", "method : use method, loops, tryCatch global next, limit #initializing 2 variables if", "== 0: return \"EOF\" if next < len(limit) -1: #Check to make sure", "char != \"EOF\"): line += char char = my_getChar() next = 0 limit", "global limit line = \"\" char = my_getChar() while (char != '' and", "\"EOF\" def my_getLine(): global next global limit line = \"\" char = my_getChar()", "= my_getChar() next = 0 limit = 0 return line def my_readLines(): numLines", "#This method calls read to fill a buffer, and gets one char at", "def my_readLines(): numLines = 0 inLine = my_getLine() while len(inLine): numLines += 1", "library import read method next = 0 limit = 0 #This method calls", "at time def my_getChar(): #define = creating method : use method, loops, tryCatch", "= 0 limit = 0 #This method calls read to fill a buffer,", "limit #initializing 2 variables if next == limit: next = 0 limit =", "2 variables if next == limit: next = 0 limit = read(0,1000) #", "read #from os library import read method next = 0 limit = 0", "\"EOF\" if next < len(limit) -1: #Check to make sure limit[next] wont go", "= 0 limit = 0 return line def my_readLines(): numLines = 0 inLine", "read(0,1000) # if limit == 0: return \"EOF\" if next < len(limit) -1:", "0 #This method calls read to fill a buffer, and gets one char", "next += 1 return c else: return \"EOF\" def my_getLine(): global next global", "#Check to make sure limit[next] wont go out of bounds. c = chr(limit[next])#converting", "bounds. c = chr(limit[next])#converting from ascii to char next += 1 return c", "to make sure limit[next] wont go out of bounds. c = chr(limit[next])#converting from", "!= '' and char != \"EOF\"): line += char char = my_getChar() next", "method calls read to fill a buffer, and gets one char at at", "import read #from os library import read method next = 0 limit =", "char = my_getChar() next = 0 limit = 0 return line def my_readLines():", "numLines += 1 print(f\"### Line {numLines}: <{str(inLine)}> ###\\n\") inLine = my_getLine() print(f\"EOF after", "os library import read method next = 0 limit = 0 #This method", "read method next = 0 limit = 0 #This method calls read to", "creating method : use method, loops, tryCatch global next, limit #initializing 2 variables", "= my_getLine() while len(inLine): numLines += 1 print(f\"### Line {numLines}: <{str(inLine)}> ###\\n\") inLine", "return \"EOF\" if next < len(limit) -1: #Check to make sure limit[next] wont", "limit = 0 #This method calls read to fill a buffer, and gets", "a buffer, and gets one char at at time def my_getChar(): #define =", "if next == limit: next = 0 limit = read(0,1000) # if limit", "+= char char = my_getChar() next = 0 limit = 0 return line", "method, loops, tryCatch global next, limit #initializing 2 variables if next == limit:", "c = chr(limit[next])#converting from ascii to char next += 1 return c else:", "+= 1 return c else: return \"EOF\" def my_getLine(): global next global limit", "line = \"\" char = my_getChar() while (char != '' and char !=", "my_getLine(): global next global limit line = \"\" char = my_getChar() while (char", "0 inLine = my_getLine() while len(inLine): numLines += 1 print(f\"### Line {numLines}: <{str(inLine)}>", "return line def my_readLines(): numLines = 0 inLine = my_getLine() while len(inLine): numLines", "0 limit = 0 return line def my_readLines(): numLines = 0 inLine =", "gets one char at at time def my_getChar(): #define = creating method :", "next = 0 limit = read(0,1000) # if limit == 0: return \"EOF\"", "while len(inLine): numLines += 1 print(f\"### Line {numLines}: <{str(inLine)}> ###\\n\") inLine = my_getLine()", "= 0 inLine = my_getLine() while len(inLine): numLines += 1 print(f\"### Line {numLines}:", "'' and char != \"EOF\"): line += char char = my_getChar() next =", "my_getChar() next = 0 limit = 0 return line def my_readLines(): numLines =", "char at at time def my_getChar(): #define = creating method : use method,", "(char != '' and char != \"EOF\"): line += char char = my_getChar()", "#from os library import read method next = 0 limit = 0 #This", "use method, loops, tryCatch global next, limit #initializing 2 variables if next ==", "len(limit) -1: #Check to make sure limit[next] wont go out of bounds. c", "out of bounds. c = chr(limit[next])#converting from ascii to char next += 1", "read to fill a buffer, and gets one char at at time def" ]
[ "DOMAIN from app.services import Services from config import Config def create_app(): app =", "import Eve from app.domain import DOMAIN from app.services import Services from config import", "app.domain import DOMAIN from app.services import Services from config import Config def create_app():", "from app.domain import DOMAIN from app.services import Services from config import Config def", "app.services import Services from config import Config def create_app(): app = Eve() Services.init_services(app=app,", "from config import Config def create_app(): app = Eve() Services.init_services(app=app, domain=DOMAIN) return app", "import Services from config import Config def create_app(): app = Eve() Services.init_services(app=app, domain=DOMAIN)", "Eve from app.domain import DOMAIN from app.services import Services from config import Config", "Services from config import Config def create_app(): app = Eve() Services.init_services(app=app, domain=DOMAIN) return", "<reponame>sebbesiren/game-api from eve import Eve from app.domain import DOMAIN from app.services import Services", "from eve import Eve from app.domain import DOMAIN from app.services import Services from", "import DOMAIN from app.services import Services from config import Config def create_app(): app", "from app.services import Services from config import Config def create_app(): app = Eve()", "eve import Eve from app.domain import DOMAIN from app.services import Services from config" ]